﻿var globalOverlayDelay = 100;
var overlayOpacity = 0.5;

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-8794487-3']);
_gaq.push(['_trackPageview']);

var searchBandsExist = false;
var needEventRequest = false;


//Login 
var authModule = undefined;
var authModuleSettings = {

    overlayHTML: "<div class='overlay4logs'></div>",
    overlaySelector: '.overlay4logs',
    signInSelector: '.loginMenu #iLogin',
    createAccountSelector: '.loginMenu #iCreateAccount',
    mySelector: '.loginMenu #iMy',
    signOutSelector: '.loginMenu #iLogOut',

    //special
    storedKey: 'kerAuthModule',
    reloadPageAfterSignIn: false,
    logAjaxURL: '/Auth/LogIn.html',
    logOutURL: '/handlers/SecurityHandler.ashx',
    createAccountURL: '/Auth/CreateAccount.html',
    forgotPasswordURL: '/Auth/ForgotPassword.htm',

    //special events
    SignInCallback: undefined,
    SignOutCallback: undefined,
    myAccountGeneralSelector: '.myAccountLinks',
    UploadGeneralSelector: '.uploadLinks'
};
function AuthModule() {
    if ($.isFunction(authModule)) {
        return authModule;
    }
    function setUserName(data) {
        var $d = $(data);
        var username = $d.find('username').text();
        if (username) {
            $(authModuleSettings.signInSelector).parent().hide();
            $(authModuleSettings.createAccountSelector).parent().hide();
            $(authModuleSettings.mySelector).text(username);
            $(authModuleSettings.mySelector).parent().show();
            $(authModuleSettings.signOutSelector).parent().show();
        }
        var userUrl = $d.find('userURL').text();
        $(authModuleSettings.myAccountGeneralSelector).unbind('click');
        $(authModuleSettings.myAccountGeneralSelector).each(function() {
            $(this).attr('href', userUrl);
        });
        //Max
        $(authModuleSettings.UploadGeneralSelector).unbind('click');
        //            $(authModuleSettings.UploadGeneralSelector).each(function() {
        //                if ($(this).children('a').attr('href') == '')
        //                    $(this).children('a').attr('href', '/Uplaod');
        //            });
    };

    function setLogOut() {
        $(authModuleSettings.signInSelector).parent().show();
        $(authModuleSettings.createAccountSelector).parent().show();
        $(authModuleSettings.mySelector).text('');
        $(authModuleSettings.mySelector).parent().hide();
        $(authModuleSettings.signOutSelector).parent().hide();

        $(authModuleSettings.myAccountGeneralSelector).each(function() {
            $(this).attr('href', '#');
            $(this).click(function(event) {
                event.preventDefault();
                doLogIn(function() {
                    $(authModuleSettings.myAccountGeneralSelector).unbind('click');
                    window.location.href = $(authModuleSettings.mySelector).attr('href');
                });
            })
        });
        //max
        $(authModuleSettings.UploadGeneralSelector).each(function() {
            //$(this).children('a').attr('href', '#');
            $(this).children('a').click(function(event) {
                event.preventDefault();
                doLogIn(function() {
                    $(authModuleSettings.UploadGeneralSelector).unbind('click');
                    window.location.href = '/home';
                });
            });
        });
    };

    function createOverlay() {
        var overlay = $(authModuleSettings.overlayHTML);
        overlay.css('height', Math.max(
                            $(document).height(),
                            $(window).height(),
                            document.documentElement.clientHeight,
                            $('body').height()
                            ));
        $('body').append($(overlay));
    };
    function setSignInEvent(callback) {
        if ($.isFunction(callback)) {
            authModuleSettings.SignInCallback = callback;
        }
    };
    function setSignOutEvent(callback) {
        if ($.isFunction(callback)) {
            authModuleSettings.SignOutCallback = callback;
        }
    };
    function doLogIn(successCallBack) {
        var overlay = $('body').find(authModuleSettings.overlaySelector);
        if (!overlay.length) {
            createOverlay();
        }
        overlay.load(authModuleSettings.logAjaxURL, function(data) {
            overlay.unbind();
            var l = overlay.kerLogInUser({
                SussfullCallback: function(userData) {
                    setUserName(userData);
                    if ($.isFunction(authModuleSettings.SignInCallback)) {
                        authModuleSettings.SignInCallback();
                    };
                    if ($.isFunction(successCallBack)) {
                        successCallBack();
                    }
                    else {
                        if (authModuleSettings.reloadPageAfterSignIn) {
                            window.location.reload(true);
                        }
                    }
                },
                SignUpCallBack: function() {
                    $('.loginMenu #iCreateAccount').click();
                },
                ForgotPassCallback: function() {
                    var overlay = $('html').find(authModuleSettings.overlaySelector);
                    if (!overlay.length) {
                        createOverlay();
                    }
                    overlay.load(authModuleSettings.forgotPasswordURL, function(data) {
                        overlay.unbind();
                        var l = overlay.kerForgotPassword();
                        //l.showBox();
                    });
                }
            });
            $('.overlay4logs').css('height', $("body").height());
            l.showBox();
        });
    };
    function doLogOut(successCallBack) {
        $.post(authModuleSettings.logOutURL, { action: 'logout' }, function(data) {
            setLogOut();
            if ($.isFunction(authModuleSettings.SignOutCallback)) {
                authModuleSettings.SignOutCallback();
            };
            if ($.isFunction(successCallBack)) {
                successCallBack();
            }
            if (window.location.pathname == '/Upload') {
                window.location.href = '/home';
            }
            else {
                if (authModuleSettings.reloadPageAfterSignIn) {
                    window.location.reload(true);
                }
            }
        });
    };
    function doCreateAccount() {
        var overlay = $('body').find(authModuleSettings.overlaySelector);
        if (!overlay.length) {
            createOverlay();
        }
        overlay.load(authModuleSettings.createAccountURL, function(data) {
            overlay.unbind();
            var l = overlay.kerCreateAccount();
            l.showBox();
        });
    };
    function getIsLogged() {
        return $(authModuleSettings.mySelector).is(':visible');
    };
    //public 
    this.DoLogInDialog = function(successCallBack) {
        doLogIn(successCallBack);
    };
    this.doLogOut = function() {
        doLogOut(successCallBack);
    };
    this.createAccountDialog = function() {
        doCreateAccount();
    };
    this.SetReloadPage = function(valToSet) {
        authModuleSettings.reloadPageAfterSignIn = valToSet;
    };
    this.IsUserLogged = function() {
        return getIsLogged();
    };
    this.SetSignInEvent = function(callBack) {
        setSignInEvent(callBack);
    };
    this.SetSignOutEvent = function(callBack) {
        setSignOutEvent(callBack);
    }
    this.InitCustom = function(myitem) {
        var isLogged = getIsLogged();
        if (!isLogged) {
            $(myitem).click(function(event) {
                event.preventDefault();
                var $item = $(this);
                doLogIn(function() {
                    $(authModuleSettings.UploadGeneralSelector).unbind('click');
                    if ($item.find('a').length > 0) {
                        var URL = $item.children('a:first').attr('href');
                        if (URL != '#') {
                            window.location.href = $item.children('a:first').attr('href');
                        }
                        else {
                            window.location.reload();
                        }
                    }
                    else {
                        window.location.reload();
                    }
                });
                $.scrollTo('#header', 800);
            });
        }
    }
    this.Init = function() {
        createOverlay();
        //binding defaults 
        $(authModuleSettings.signInSelector).click(function(event) {
            event.preventDefault();
            doLogIn();
        });
        $(authModuleSettings.signOutSelector).click(function(event) {
            event.preventDefault();
            doLogOut();
        });
        $(authModuleSettings.createAccountSelector).click(function(event) {
            event.preventDefault();
            doCreateAccount();
        });
        var isLogged = getIsLogged();
        if (!isLogged) {
            $(authModuleSettings.myAccountGeneralSelector).click(function(event) {
                event.preventDefault();
                doLogIn(function() {
                    $(authModuleSettings.myAccountGeneralSelector).unbind('click');
                    window.location.href = $(authModuleSettings.mySelector).attr('href');
                });
            });
            $(authModuleSettings.myAccountGeneralSelector).each(function() {
                $(this).attr('href', '#');
            });
            //max
            $(authModuleSettings.UploadGeneralSelector).click(function(event) {
                event.preventDefault();
                var $item = $(this);
                doLogIn(function() {
                    $(authModuleSettings.UploadGeneralSelector).unbind('click');
                    if ($item.find('a').length > 0) {
                        var URL = $item.children('a:first').attr('href');
                        if (URL != '#') {
                            window.location.href = $item.children('a:first').attr('href');
                        }
                        else {
                            //window.location.href = window.location.href + '?comment=true';
                            window.location.reload();
                        }
                    }
                    else {
                        window.location.reload();
                    }

                });
            });
            $(authModuleSettings.UploadGeneralSelector).children('a').each(function() {
                //$(this).attr('href', '/home');
            });
        }
        else {
            $(authModuleSettings.UploadGeneralSelector).children('a').each(function() {
                //$(this).attr('href', '/Upload');
            });
        }
    };
    return this;
};
//Main
function doBandListSearchRequest(startWith, isTop) {
    var requestURL = '/Handlers/Main.ashx';
    var params = ({
        'action': 'getbands',
        'startWith': startWith
    });
    $('#searchBandID').val('');
    $('#searchVenueID').val('');
    $(".concertDropDown").empty().append('<option>Select Concert</option>');
    needEventRequest = true;
    $.ajax({
        type: 'POST',
        async: true,
        url: requestURL,
        data: params,
        success: function(data) {
            var $d = $(data);
            if ($d.find('result').text() == 'success') {
                parceBandListSearchResponse(data, startWith.length, isTop);
            }
        }
    });
};
function parceBandListSearchResponse(data, length, isTop) {
    var html = $(data).find('html').text();
    if ($(data).find('exist').text() == "true") {
        if (isTop) {
            $('#autoSuggestionsListTop').empty().append(html);
            $('#suggestionsTop').show();
        }
        else {
            $('#autoSuggestionsListBottom').empty().append(html);
            $('#suggestionsBottom').show();
        }
    }
    else {
        $('#suggestionsTop').hide();
        $('#autoSuggestionsListTop').empty();
        $('#suggestionsBottom').hide();
        $('#autoSuggestionsListBottom').empty();
        searchBandsExist = true;
    }
}
function doVenueListSearchRequest(bandID) {
    $('.searchAjaxLoader img').fadeIn('slow');
    var requestURL = '/Handlers/Main.ashx';
    var params = ({
        'action': 'getbandvenue',
        'bandID': bandID
    });
    $('#searchVenueID').val('');
    $.ajax({
        type: 'POST',
        async: true,
        url: requestURL,
        data: params,
        success: function(data) {
            var $d = $(data);
            if ($d.find('result').text() == 'success') {
                $(".concertDropDown").empty();
                var concertCount = $(data).find('count').text();
                if (concertCount == "0") {
                    $(".concertDropDown").append('<option>No concerts found</option>');
                }
                else {
                    $(".concertDropDown").append('<option>' + concertCount + ' concerts found</option>');
                }
                $(".concertDropDown").append($(data).find('html').text());
                $('.searchAjaxLoader img').fadeOut('slow');
            }
        }
    });
};
function doSearchRequest(bandID, eventID, bandName) {
    var requestURL = '/Handlers/Main.ashx';
    var params = ({
        'action': 'getsearchurl',
        'bandID': bandID,
        'eventID': eventID,
        'bandName': bandName
    });
    $.ajax({
        type: 'POST',
        async: true,
        url: requestURL,
        data: params,
        success: function(data) {
            if ($(data).find('result').text() == 'success') {
                needEventRequest = true;
                window.location = $(data).find('url').text();
            }
        }
    });
}
//Initialization
function initSearch() {
    $('#searchBandTop').val('Enter name of band');
    $('#searchBandTop').css('color', '#444444');
    $('#suggestionsTop').hide();
    $('#autoSuggestionsListTop').empty();

    $('#searchBandBottom').val('Enter name of band');
    $('#searchBandBottom').css('color', '#444444');
    $('#suggestionsBottom').hide();
    $('#autoSuggestionsListBottom').empty();
    $(".concertDropDown").append("<option>Select Concert</option>");
}
function searchInputFocus($item) {
    if ($item.val() == 'Enter name of band') {
        $item.val('');
        $item.css('color', 'black');
    }
}
function searchInputBlur($item) {
    if ($item.val() == '') {
        $('.concertDropDown').attr('disabled', "true");
        $('#searchBandTop').css('color', '#444444');
        $('#searchBandTop').val('Enter name of band');
        $('#searchBandBottom').css('color', '#444444');
        $('#searchBandBottom').val('Enter name of band');
        $(".concertDropDown").empty().append('<option>Select Concert</option>');
    }
}
function searchInputKeyup($item, isTop) {
    if ($item.attr('value').length >= 2) {
        doBandListSearchRequest($item.attr('value'), isTop);
    }
    else {
        $('#suggestionsTop').hide();
        $('#suggestionsBottom').hide();
        $('#autoSuggestionsListTop').empty();
        $('#autoSuggestionsListBottom').empty();
    }
}
function initSuggestClick($item) {
    searchBandsExist = false;
    $('.concertDropDown').removeAttr('disabled');
    if ($item.children('div').attr('title') == '') {
        $('#searchBandTop').val($item.children('div').text());
        $('#searchBandBottom').val($item.children('div').text());
    }
    else {
        $('#searchBandTop').val($item.children('div').attr('title'));
        $('#searchBandBottom').val($item.children('div').text());
    }
    $('#searchBandID').val($item.attr('id'));
    $('#searchBandBottom').css('color', 'black');
    $('#searchBandTop').css('color', 'black');
    $('#suggestionsTop').hide();
    $('#autoSuggestionsListTop').empty();
    $('#suggestionsBottom').hide();
    $('#autoSuggestionsListBottom').empty();
}
$(function() {
    var fAuth = AuthModule();
    fAuth.Init();
    authModule = fAuth;
    initSearch();

    //Top
    $('#header .bandNameInput').bind('focus', function() {
        searchInputFocus($(this));
    });
    $('#header .bandNameInput').bind('blur', function() {
        searchInputBlur($(this));
    });
    $('#header .bandNameInput').bind('keyup', function() {
        searchInputKeyup($(this), true);
    });
    $('#autoSuggestionsListTop li').live('click', function() {
        initSuggestClick($(this));
        //$(this).find('option:first').remove();//.text('');
        if (needEventRequest) {
            doVenueListSearchRequest($('#searchBandID').val());
            needEventRequest = false;
        }
    });
    $('#header .concertDropDown').focus(function() {
        //console.log('focus');
        //        $(this).find('option:first').text('');
        //        if (needEventRequest) {
        //            doVenueListSearchRequest($('#searchBandID').val());
        //            needEventRequest = false;
        //        }
    })
    $('#header .concertDropDown').blur(function() {
        //console.log('blur');
        if ($(this).val() == '') {
            $(this).find('option:first').text('Select Concert');
        }
    })
    $('#header .concertDropDown').change(function() {
        //console.log('change');
        $('#searchVenueID').val($('#header .concertDropDown :selected').attr('id').substring(1));
    })

    //Bottom
    $('#footer .bandNameInput').bind('focus', function() {
        searchInputFocus($(this));
    });
    $('#footer .bandNameInput').bind('blur', function() {
        searchInputBlur($(this));
    });
    $('#footer .bandNameInput').bind('keyup', function() {
        searchInputKeyup($(this), false);
    });
    $('#autoSuggestionsListBottom li').live('click', function() {
        initSuggestClick($(this));
        //$(this).find('option:first').text('');
        if (needEventRequest) {
            doVenueListSearchRequest($('#searchBandID').val());
            needEventRequest = false;
        }
    });
    $('#footer .concertDropDown').focus(function() {
        //        $(this).find('option:first').text('');
        //        if (needEventRequest) {
        //            doVenueListSearchRequest($('#searchBandID').val());
        //            needEventRequest = false;
        //        }
    })
    $('#footer .concertDropDown').blur(function() {
        if ($(this).val() == '') {
            $(this).find('option:first').text('Select Concert');
        }
    })
    $('#footer .concertDropDown').change(function() {
        $('#searchVenueID').val($('#footer .concertDropDown :selected').attr('id').substring(1));
    })

    //Search button
    $('.blackButton').click(function(event) {
        event.preventDefault()
        if ($('#searchBandTop').val() != 'Enter name of band' || $('#searchBandBottom').val() != 'Enter name of band') {
            doSearchRequest($('#searchBandID').val(), $('#searchVenueID').val(), $('#searchBandTop').val());
        }
    })

    //Scroll to
    $('#footer .footerMenu .item.uploadLinks').click(function() {
        $.scrollTo('#header', 800);
    })

    //    $('#header_bottom .menuBackground .menu .myAccountLinks').click(function() {
    //        $.scrollTo('#header', 800);
    //    })

    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})
