﻿function setAnchor(value) {
   // alert(value);
    location.hash = value;
}
var sessionTimeoutID = null;
var sessionTimeout = null;
var currentAnchor = "";
//var siteType = ""; //Determines whether or not we are calling the Public or Employee versions of the site.

//On load page, init the timer which check if the there are anchor changes each 300 ms
$().ready(function() {
    $.historyInit(getAnchor);
    setInterval("checkAnchor()", 300);
});

function getAnchor(hash) {
    var data = null;
    
    //if there is not anchor, the loads the default section
    if (hash) {
        currentAnchor = "#" + hash;
        //Creates the string callback. This converts the url URL/#main&id=2 in URL/?section=main&id=2
        var splits = hash.split('/');
        if (typeof splits != 'undefined') {
            data = "{'parameters':" + JSON.stringify(splits) + "}";
            $("#hdnPage").val(splits[0]);
        }
        else {
            data = "{'parameters':['home']}";
            $("#hdnPage").val('home');
        }
    }
    else {
        data = "{'parameters':['home']}"
        $("#hdnPage").val('home');
    }

    //callAjax("Default.aspx/GetPagesWithParams", data, "main-content");
    callAjax(siteType + "/GetPagesWithParams", data, "main-content");
   
}

function setSessionExpiration(timeout) {
    
    if (sessionTimeout == null) {
        sessionTimeout = timeout;
    }
    clearTimeout(sessionTimeoutID);
    sessionTimeoutID = setTimeout("checkLogin()", (sessionTimeout * 60000));
}

function checkLogin() {
    //callAjax("Default.aspx/CheckLogin", "{}");
    callAjax(siteType + "/CheckLogin", "{}");
    
}


//Function which chek if there are anchor changes, if there are, sends the ajax petition
function checkAnchor() {
    //Check if it has changes
    if (currentAnchor != location.hash) {
        currentAnchor = location.hash;
        $.historyLoad(currentAnchor.substring(1));
    }
}

function showForgottenPassword() {
    $("#basicLoginContent").modal();
    $('#login').hide();
    $('#forgotPass').show();
    $(document).unbind("keypress");
    $("#emailForgot").keyup(function(e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            submitForgot();
        }
    }); 
    var p = jQuery("#ForgotPassForm").validate({
        rules: {
            emailForgot: {
                required: true,
                email: true
            }
        },
        messages: {
            emailForgot: {
                required: "",
                email: ""
            }
        },
        errorClass: 'err',
        highlight: function(element, errorClass) {
            $(element).addClass(errorClass);
        },
        unhighlight: function(element, errorClass) {
            $(element).removeClass(errorClass);
        },
        submitHandler: function(form) {
            getPassword();
        }
    });
}
function submitForgot() {
    jQuery("#ForgotPassForm").submit();
}

function showLogin() {
    $("#basicLoginContent").modal();
    $('#login').show();
    $('#forgotPass').hide();
    $(document).unbind("keypress");
    $("#loginemail").keyup(function(e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            submitLogin();
        }
    });
    var p = jQuery("#LoginForm").validate({
        rules: {
            loginemail: {
                required: true,
                email: true
            },
            loginpass: {
                required: true,
                minlength: 6
            }
        },
        messages: {
            loginemail: {
                required: "",
                email: ""
            },
            loginpass: {
                required: "",
                minlength: ""
            }
        },
        errorClass: 'err',
        highlight: function(element, errorClass) {
            $(element).addClass(errorClass);
        },
        unhighlight: function(element, errorClass) {
            $(element).removeClass(errorClass);
        },
        submitHandler: function(form) {
            login($("#loginemail").val(), $("#loginpass").val());
        }
    });
}
function submitLogin() {
    jQuery("#LoginForm").submit();
}



function catchEvent(page, divID) {
    if (typeof divID =="undefined") {
        divID = "main-content";
    }
    
    $("#hdnPage").val(page);
    //callAjax("Default.aspx/GetAllPages", "{'page':'" + page + "'}", divID);
    callAjax(siteType+"/GetAllPages", "{'page':'" + page + "'}", divID);
}

function loadContent(page, divID) {
    if (typeof divID =="undefined") {
        divID = "main-content";
    }
    $("#hdnPage").val(page);

    //callAjax("Default.aspx/GetThisPage", "{'page':'" + page + "'}", divID);
    callAjax(siteType + "/GetThisPage", "{'page':'" + page + "'}", divID);
}

reinitialiseScrollPane = function() {
    $('.scroll-pane').jScrollPane();
}

function markSelector() {
    var id = 'nav_' + location.hash.substring(1).split('/');
    var thisElement = $('#' + id);
    var list = thisElement.parent().parent();
    list.find('a').each(function() {
        if ($(this).hasClass('select')) {
            $(this).removeClass('select');
        }
    });
    thisElement.addClass('select');
}
function setGGTFlashNav(page) {
    if (typeof swfobject != 'undefined') {
        if (swfobject.getObjectById("headerFlash") != null) {
            if (typeof swfobject.getObjectById("headerFlash").setFlashNav != 'undefined') {
                swfobject.getObjectById("headerFlash").setFlashNav(page);
            }
        }
    }
}

function setBankCodeValidation(codeCheck) {
    for (var i = 0; i < codeCheck.length; i++) {
        if(($("#code" + (i+1) + "1").val() + $("#code" + (i+1) + "2").val()) != ""){
            var imgValidCode = document.getElementById('imgValidCode' + (i+1));
            imgValidCode.style.visibility = "visible";
            if (codeCheck[i] != "") {
                imgValidCode.src = "Theme/check-neg.png";
                $("#error" + (i + 1)).css("visibility", "visible");
                $("#errorContent" + (i + 1)).html(codeCheck[i]);
            }
            else {
                $("#code" + (i + 1) + "1").val("");
                $("#code" + (i + 1) + "2").val("");
                imgValidCode.src = "Theme/check-pos.png";
                $("#error" + (i + 1)).css("visibility", "hidden");
            }
        }
    }
}

function callAjax(url, data, divID, errorID) {
    setSessionExpiration();
    mapReset();
    if(url != ''){
        if (typeof divID == "undefined") {
            divID = "main-content";
        }
        var showModalError = true;
        if (typeof errorID == "undefined") {
            errorID = "error-content";
        }

        document.title = "Gary's Great Trips";

        $.ajax({
            type: "POST",
            url: url,
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            progress: $("#loading").modal({
                close: false,
                overlayId: 'confirmModalOverlay'
            }),
            success: function(msg) {
                $.modal.close();
                var data = msg.d;

                if (typeof data.formReset != "undefined") {
                    jQuery("#" + data.formReset).clearForm();
                }
                if (!data.error) {

                    if (typeof data.points != "undefined" && typeof data.totalPoints != "undefined") {
                        if (swfobject.getObjectById("headerFlash") != null) {
                            swfobject.getObjectById("headerFlash").ASBankPoints(data.totalPoints, data.points)
                        }
                    }
                    else {
                        if (typeof data.totalPoints != "undefined") {
                            if (swfobject.getObjectById("headerFlash") != null) {
                                swfobject.getObjectById("headerFlash").ASBankPoints(data.totalPoints, 0)
                            }
                        }
                    }

                    if (typeof data.logout != "undefined" && data.logout) {
                        setAnchor("#");
                        if (swfobject.getObjectById("headerFlash") != null) {
                            swfobject.getObjectById("headerFlash").sendToActionScript("");
                        }
                    }

                    if (typeof data.pageTitle != "undefined") {
                        document.title = data.pageTitle;
                    }

                    if (typeof data.userName != "undefined") {
                        if (swfobject.getObjectById("headerFlash") != null) {
                            if (typeof swfobject.getObjectById("headerFlash").sendToActionScript != "undefined")
                                swfobject.getObjectById("headerFlash").sendToActionScript(data.userName);
                        }
                    }
                    if (typeof data.html != "undefined") {
                        $("#" + divID).empty();
                        $("#" + divID).html(data.html);
                        jQuery(document).pngFix();
                        window.scrollTo(0, 0);
                    }

                    if (typeof data.popup != "undefined") {
                        $("#" + data.popup).modal({ onShow: reinitialiseScrollPane });
                    }
                    if (typeof data.bankCodesCheck != "undefined") {
                        setGGTFlashNav("BankPoints");
                        setBankCodeValidation(data.bankCodesCheck);
                    }

                    if (typeof data.codeError != "undefined") {
                        if (errorID == "errorFull" || $("#" + errorID).length == 0) {
                            data.codeError = "<div class='hBreak'></div><p class='error'><span id='error-content'>" + data.codeError + "</span></p><br />";
                            errorID = "errorFull";
                        }
                        $("#" + errorID).html(data.codeError);
                        $("#basicErrorPopup").modal();
                    }
                }
                else {
                    if (typeof data.errorContainer != "undefined") {
                        errorID = data.errorContainer;
                    }

                    if (data.html == "not logged in") {
                        if (swfobject.getObjectById("headerFlash") != null) {
                            if (typeof swfobject.getObjectById("headerFlash").sendToActionScript != "undefined")
                                swfobject.getObjectById("headerFlash").sendToActionScript("");
                        }
                        showLogin();
                    }
                    else {
                        if ($("#" + errorID).length==0) {
                            data.html = "<div class='hBreak'></div><p class='error'><span id='error-content'>" + data.html + "</span></p><br />";
				            errorID = "errorFull";
                        }
                        //$.modal.close();
                        $("#" + errorID).html(data.html);
                        if (errorID == 'forgotPass') {
                            showForgottenPassword();
                        }
                        else {
                            $("#basicErrorPopup").modal();
                        }

                    }
                }
             
                markSelector();
            },
            error: function(xhr, desc, exceptionobj) {
                $.modal.close();
                //$("#" + errorID).html('Sorry, there is an error or connection problem. Please press the back button and try again');
                $("#" + errorID).html(xhr.responseText);
                $("#basicErrorPopup").modal();
                markSelector();
            }
        });
     }
 }

 function setPassInput() {
     $('#loginpass').replaceWith('<input class=\'login-input\' name=\'loginpass\' id=\'loginpass\' type=\'password\' />');
     $('#loginpass').trigger('focus');
     $("#loginpass").keyup(function(e) {
         if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
             submitLogin();
         }
     });
 }
function initializer() {
    cinit();
    Custom.init();
}

function popUp(URL) {
    day = new Date();
    id = day.getTime();
    eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=615,height=600,left = 340,top = 212');");
}

function popUpFull(URL) {
    day = new Date();
    id = day.getTime();
    eval("page" + id + " = window.open(URL, '" + id + "', '');");
}

jQuery(document).ready(function() {
$.extend($.modal.defaults, {
        closeClass: "modalCloseImg simplemodal-close",
        closeHTML: "<a title='Close' onclick='javascript:closeModalCheck();'></a>",
        onShow: function(dialog) { jQuery(document).pngFix(); }
    });
    jQuery(document).pngFix();
});

function closeModalCheck() {
    if ($("#main-content").html() == "") {
        callAjax(siteType + "/GetPagesWithParams", "{'parameters':['home']}", "main-content");
    }
    document.title = "Gary's Great Trips";
    $.modal.close();
}

