var sPortal = "AAMI";
//360
var MOBILEBREAKPOINT = 1101;
var Check = function() {
    try {
    }
    catch (Error) {
    }
    return null;
} ();

function CheckParams() {
    try {
        var query_string = {};
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            if (typeof query_string[pair[0]] === "undefined") {
                if (pair[0] == "userlogin" && pair[1] == "Y") {
                    $("#idGuestContainer").css("display", "none");
                    $("#idLoginContainer").css("display", "block");
                    $(".cGuestAccessContainer").css("display", "none");
                }
                query_string[pair[0]] = decodeURIComponent(pair[1]);
            } else if (typeof query_string[pair[0]] === "string") {
                var arr = [query_string[pair[0]], decodeURIComponent(pair[1])];
                query_string[pair[0]] = arr;
            } else {
                query_string[pair[0]].push(decodeURIComponent(pair[1]));
            }
        }
        return query_string;
    }
    catch (Error) {
        return null;
    }
};


function CloseLoginExtendedDialog() {
    $("#idlogindropdown").css("display", "none");
}

function DisplayErrorMessage(oForm, oIDDiv, sMessage) {
    oIDDiv.css('opacity', '0');
    oIDDiv.css('background-color', 'rgb(195,0,0)');
    oIDDiv.css('color', 'white');
    oIDDiv.html(sMessage);
    oIDDiv.animate({ 'opacity': '1' }, 2200);
}

function ForgotPassword() {
    var email = prompt("Please enter your registered email address:", "");
    if (email != null && email != "") {
        SendUserIDPassword(email);
    }    
}

function DisplayMessage(oForm, oIDDiv, sMessage, sStartPage) {
    oIDDiv.fadeOut(100, function() {
        window.location.href = sStartPage;
    });
}

function UpdateCookie(sValue) {
    var datec1 = new Date();
    datec1.setTime(datec1.getTime() + (24 * 60 * 60 * 1000));
    $.cookie("guid", sValue, { expires: datec1, path: '/' });
}

function CustomizeExperience() {
    var sDetails = "";
    try {
        var d = new Date()
        var timezoneOffset = d.getTimezoneOffset();

        sDetails = timezoneOffset + "~" + screen.width + "px, " + screen.height + "px, " + $(window).width() + "px" + $(window).height() + "px.";
    }
    catch(err) {
        sDetails = "JS ERROR.";
    }
    var sData = "ACTION=CUSTOMIZEEXPERIENCE&DETAILS=" + escape(sDetails);
    $.ajax({
        type: 'POST',
        url: GetFullURL("ProcessAjax.aspx"),
        data: sData,
        success: function (xml) {
            if ($("result", xml).attr('type') == 'success') {                
            }
            else if ($("result", xml).attr('type') == 'error') {
                alert($("result", xml).text());
            }
            else {
                alert("#1:Unknown error occurred:[" + $("result", xml).text() + "]");
            }
        },
        error: function(xhr, type, exception) {
            alert("#2:Unknown error occurred.");
        },
        async: false
    });
}

function SendUserIDPassword(email) {
    var sData = "ACTION=SENDUIDPWD&CMAIL=" + escape(email);
    $.ajax({
        type: 'POST',
        url: GetFullURL("ProcessAjax.aspx"),
        data: sData,
        success: function(xml) {
            if ($("result", xml).attr('type') == 'success') {
                alert("We have emailed your User ID and Password.");
            }
            else if ($("result", xml).attr('type') == 'error') {
                alert($("result", xml).text());
            }
            else if ($("result", xml).attr('type') == 'redirect') {
                window.location.href = $("result", xml).text();
            }
            else {
                alert("#3:Unknown error occurred.");
            }
        },
        error: function(xhr, type, exception) {
            alert("#4:Unknown error occurred.");
        },
        async: false
    });
}

function IsGuidValid(sGuid) {
    //window.alert("http://"+window.location.host+window.location.pathname.replace("Login.aspx","ProcessAjax.aspx"));
    var sData = "idFIDMandatory=CHECKGUID&idFDescriptionMandatory=Check GUID&CookieGuid=" + sGuid;
    $.ajax({
        //contentType: "application/json",
        type: 'POST',
        url: GetFullURL("ProcessAjax.aspx"),
        data: sData,
        success: function(xml) {
            $("#idSubmitProgress2").css("visibility", "hidden");
            if ($("result", xml).attr('type') == 'skip')
            { }
            else if ($("result", xml).attr('type') == 'error')
                DisplayErrorMessage($("#idLoginForm"), $("#idMessage"), $("result", xml).text());
            else {
                //UpdateCookie();
                //$.cookie("guid", $("result", xml).find("guid").text(), { expires: 30, path: '/'});
                //window.alert("xml:" + $("result", xml).text());
                ////DisplayMessage($("#idLoginForm"), $("#idlogindropdown"), $("result", xml).text(), $("result", xml).find("startpage").text());
            }
        },
        error: function(xhr, type, exception) {
            $("#idSubmitProgress2").css("visibility", "hidden");
            DisplayErrorMessage($("#idLoginForm"), $("#idMessage"), "Error:: " + exception);
        }
    });
}

function SetAJAXFormEvents() {
    /*****AJAX*******/
    try {
        var sCookieGuid = $.cookie("guid");
        //window.alert(sCookieGuid);
        if (sCookieGuid != null) {
            if (IsGuidValid(sCookieGuid)) {
            }
        }
    }
    catch (excep) {
        //alert("Warning: Cookies are disbaled. Please enable Cookies in your browser. Close your browser and revisit the login page.");
    }

    $(".cGuestAccess").click(
		function(e) {
            var sEmail = $("#idEmail").val();
            //window.alert(sEmail);
            if (sEmail.length > 0) {
		        var sNewurl = GetFullURL("guest.aspx" + "?email=" + escape(sEmail));
		        window.location.href = sNewurl;
		    }
		    else {
		        var sNewurl = GetFullURL("guest.aspx");
		        window.location.href = sNewurl;
		        //window.alert("Please enter a valid e-mail address to get a free guest access.");
		    }
		    return false;
		});

		$(".cGuestAccessEx").click(
		function (e) {
		    var sEmail = $("#idEmail").val();
		    if (sEmail.length > 0) {

		        var sQtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
		        var sDtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
		        var sAtom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
		        var sQuotedPair = '\\x5c[\\x00-\\x7f]';
		        var sDomainLiteral = '\\x5b(' + sDtext + '|' + sQuotedPair + ')*\\x5d';
		        var sQuotedString = '\\x22(' + sQtext + '|' + sQuotedPair + ')*\\x22';
		        var sDomain_ref = sAtom;
		        var sSubDomain = '(' + sDomain_ref + '|' + sDomainLiteral + ')';
		        var sWord = '(' + sAtom + '|' + sQuotedString + ')';
		        var sDomain = sSubDomain + '(\\x2e' + sSubDomain + ')*';
		        var sLocalPart = sWord + '(\\x2e' + sWord + ')*';
		        var sAddrSpec = sLocalPart + '\\x40' + sDomain; // complete RFC822 email address spec
		        var sValidEmail = '^' + sAddrSpec + '$'; // as whole string
		        var oRegex = new RegExp(sValidEmail);
		        if (oRegex.test(sEmail)) {
		            var sNewurl = GetFullURL("guest.aspx" + "?email=" + escape(sEmail));
		            window.location.href = sNewurl;
		        }
                else
                    window.alert("Please enter a valid e-mail address to get free access.");
		    }
		    else {
		        window.alert("Please enter a e-mail address to get free access.");
		    }
		    return false;
		});

    $(".navlogopanel").each(
			function(e) {
			    var iRow = $(this).attr("row");
			    var iCol = $(this).attr("col");
			    var bvalue = "-" + (iCol - 1) * 150 + "px -" + (iRow - 1) * 150 + "px no-repeat url('images/backgroundAAMI.png')";
			    if (sPortal !== "DS" && sPortal !== "SDO" && sPortal !== "DEMO" && sPortal !== "CLSI") {
			        $(this).css("background", bvalue);			        
			    }
			    return true;
			});

    
    $(".navlogopanel").mouseover(
			function(e) {
			    $("#idPlatform").addClass("navlogopanel");
			    if (sPortal !== "DS" && sPortal !== "SDO" && sPortal !== "DEMO" && sPortal !== "CLSI")
	                $("#idPlatform").css("background", "-300px -150px no-repeat url('images/backgroundAAMI.png')");
                $("#idPlatform").removeClass("navlogopanel3");
			    return true;
			});
    

    $("#idPlatform, .navlogopanel").mouseover(
			function(e) {
			    $(this).children(".cBlockOutType1").css("display", "none");
			    $(this).children(".cBlockOverType2").css("display", "table-cell");
			    //$(this).children(".cPanelContent").addClass("cBlockOverType2");
			    //$(this).children(".cPanelContent").removeClass("cBlockOutType1");
			    return true;
			});
    $("#idPlatform, .navlogopanel").mouseout(
			function(e) {
			    $(this).children(".cBlockOutType1").css("display", "table-cell");
			    $(this).children(".cBlockOverType2").css("display", "none");

			    //$(this).children(".cPanelContent").html("eStandards<br>Plus");
			    //$(this).children(".cPanelContent").removeClass("cBlockOverType2");
			    //$(this).children(".cPanelContent").addClass("cBlockOutType1");
			    return true;
			});

    $(".navlogopanel").each(
			function(e) {
			    $(this).prepend("<div class=\"cFeatureTierType" + $(this).attr("tier") + "\"></div>");
			}
		);
			$("form input").focus(
			function (e) {
			    $(this).addClass("clsHighlightInput");			    
			    if ($(".login-fixed").position().top == 0)
			        $("#idlogindropdown").css("display", "block");
			    else
			        $("#idlogindropdown").css("display", "block");
			});

    $("form input").blur(
			function(e) {
			    $(this).removeClass("clsHighlightInput");
			});

    $("form textarea").focus(
			function(e) {
			    $(this).addClass("clsHighlightInput");
			});

    $("form textarea").blur(
			function(e) {
			    $(this).removeClass("clsHighlightInput");
			});

			$("#idLoginForm").submit(
			function (e) {
			    var sFID = $("#idUserID").val().toUpperCase();
			    if (sFID == "GUEST") {
			        var sNewurl = GetFullURL("guest.aspx");
			        window.location.href = sNewurl;
			    }
			    else {
			        //window.alert("http://"+window.location.host+window.location.pathname.replace("Login.aspx","ProcessAjax.aspx"));
			        $("#idSubmitProgress2").css("visibility", "visible");
			        DisplayProgress(2);
			        //var sPostURL = "http://" + window.location.host + window.location.pathname.replace("Login.aspx", "ProcessAjax.aspx").replace("login.aspx", "ProcessAjax.aspx");
			        var sPostURL = GetFullURL("ProcessAjax.aspx");
			        e.preventDefault();
			        var sData3 = $("#idLoginForm").serializeArray();
			        sData3.push({ name: 'idFIDMandatory', value: 'LOGIN' });
			        sData3.push({ name: 'idFDescriptionMandatory', value: 'Login Page' });
			        $.ajax({
			            type: 'POST',
			            url: sPostURL,
			            data: sData3,
			            success: function (xml) {
			                $("#idSubmitProgress2").css("visibility", "hidden");
			                if ($("result", xml).attr('type') == 'error')
			                    DisplayErrorMessage($("#idLoginForm"), $("#idMessage"), $("result", xml).text());
			                else if ($("result", xml).attr('type') == 'redirect')
			                    window.location.href = $("result", xml).find("newurl").text();
			                else {
			                    //window.alert($("result", xml).find("cookievalue").text());

			                    var sKeepSignedIn = $("#idKeepLoggedIn").val();
			                    if ($("#idKeepLoggedIn").is(':checked')) {
			                        UpdateCookie($("result", xml).find("cookievalue").text());
			                    }
			                    else {
			                        CustomizeExperience();
			                        window.location.href = $("result", xml).find("startpage").text();
			                    }
			                    //DisplayMessage($("#idLoginForm"), $("#idlogindropdown"), $("result", xml).text(), $("result", xml).find("startpage").text());
			                }
			            },
			            error: function (xhr, type, exception) {
			                $("#idSubmitProgress2").css("visibility", "hidden");
			                DisplayErrorMessage($("#idLoginForm"), $("#idMessage"), "Error:: " + exception);
			            },
			            complete: function (jqXHR, textStatus) {
			                HideProgress();
			            },
			            async: true
			        });
			    }
			    e.preventDefault();
			    return false;
			});
    /*****AJAX*******/    
}

function ShowClue() {
    $("#idGuestClickHere").animate({ 'font-size': '20' }, 200);
    $("#idGuestClickHere").animate({ 'font-size': '12' }, 200);
}

function DisplayProgress(iType) {
    if (iType === undefined || iType == 0 || iType == 1) {
        $("#idSubmitProgress").css("visibility", "visible");
    }
    if (iType === undefined || iType == 0 || iType == 2) {
        $("#idLargeProgress").css("left", ($(window).width() / 2) + "px");
        $("#idLargeProgress").css("display", "block");
    }
}

function HideProgress() {
    $("#idSubmitProgress").css("visibility", "hidden");
    $("#idLargeProgress").css("display", "none");
}

function HandleResize() {
    //if ($(window).width() > MOBILEBREAKPOINT) {
    if ($(".cMobileOnly").css("display") == "none") {
        $("#idBannerCenter").append($("#idLoginContainer"));
        $("#idLoginContainer").removeClass().addClass("banneritem login-section");
        ////$("#idLoginContainer").css("display", "block");
        $("#idlogindropdown").removeClass().addClass("login-dropdown");
        $("#idLoginContainerInner").removeClass().addClass("formcontainer");
    }
    else {
        if ($("#idLoginContainer").parent().attr("id")!="idLoginHolderMobile"){
            $("#idLoginHolderMobile").append($("#idLoginContainer"));
            $("#idLoginContainer").removeClass();
            ////$("#idLoginContainer").css("display", "block");
            $("#idlogindropdown").removeClass();
            $("#idLoginContainerInner").removeClass();
        }
    }

    $(".cAutoFitImage").each(function () {
        //$("#idUserID").val($(window).width());
        //$("#idPassword").val($(this).width());
        if ($(this).prop('naturalWidth') > $(window).width()) {
            $(this).width($(window).width());
            $(this).css("height", "auto");
            $(".cCatButton").width($(window).width() / 8);
        }
        else {
            $(this).css("width", "auto");
            $(this).css("height", "auto");
            $(".cCatButton").width($(window).width() / 8);
            var iFontSize = 100 * $(this).width() / 500;
            $(".cASMELandingContainer").css("font-size", iFontSize + "%");
            //alert($(this).width());
            //alert($(".cASMELandingContainer").css("font-size"));
        }
    });

}

function start() {
    $(window).resize(function () {
        HandleResize();
    });
    SetAJAXFormEvents();
    HandleResize();
    CheckPlugins();
    CheckParams();
    var oTimer2 = setTimeout("ShowClue()", 6000);
    $(".login-fixed").mousemove(function(e) { if (oTimer2 != null) clearTimeout(oTimer2); oTimer2 = null; });
    DemoInit();

    $(".cMember").css("display", "block");
    $(".cStaff").css("display", "none");
    $("#idCLSIStaffLogin").click(
			            function (e) {
			                $(".cMember").css("display", "none");
			                $(".cStaff").css("display", "block");
			            });

}
$(document).ready(start);
