var appName='ESGI';
var Errors = new Array();

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

function GetUrlPar(param) {
    var regex = '[?&]' + param + '=([^&#]*)';
    var results = (new RegExp(regex)).exec(window.location.href);
    if (results) return results[1];
    return '';
}

function Jump(IsSecure, url)
{
    var h = document.location.href;
    if (h.indexOf('www1.esgisoftware.com')<0
	    && h.indexOf('www2.esgisoftware.com')<0
	    && h.indexOf('www.esgisoftware.com')<0
	    && h.indexOf('test1.esgisoftware.com')<0
	    && h.indexOf('test2.esgisoftware.com')<0)
            IsSecure = false;
    if (IsSecure == true)
        h = h.replace("http://", "https://");
    else
        h = h.replace("https://", "http://");
    h = h.substring(0, h.lastIndexOf('/')+1) + url;
    document.location.href = h;
}

function maximiseWindow(winRef) {
  if (window.screen) {
	try
	{
		winRef.moveTo(0,0);
		winRef.resizeTo(screen.availWidth,screen.availHeight);
	}
	catch(ex){}
  }
}

function alterWindow(winRef) {
  maximiseWindow(winRef);
  winRef.focus();
}

String.prototype.Equals = function (entry) {
	return (this == entry)
};

String.prototype.IsEmpty = function (entry) {
    return (this == null || this == "")
};

Date.prototype.addMonth = function (num) {
	var tmpdtm = this.getDate();
	this.setMonth (this.getMonth() + num);
	if (tmpdtm > this.getDate())
		this.addDays(-this.getDate());
	return this;
};

function AnimateLoginBut(ani)
{
    if (ani)
    {
        $(".LoginForm").hide();
        $(".LoginButAni").show();
    }
    else
    {
        $(".LoginButAni").hide();
        $(".LoginForm").show();        
    }
};

function LoadContent(hash){        
	hash = hash.replace(/^.*#/, '');
	$.historyLoad(hash);
    return false;
};


$(document).ready (
    function()
    {
        if (document.location.href.indexOf("?showpo")>0) ShowPO();
        if ($.historyInit) $.historyInit(pageload);
        $(".username").focus();
        $(".top_menu, .second_top_menu, .second_menu, .second_sub_menu").hover(
            function(){
                SetParams(this);
                $(Getmenu(this)).show();
            },
            function(){
                $(Getmenu(this)).hide();
            }
        );
        $(".bottom-menu-link").hover(function (){
            $(this).attr("id", "hover");
        },  function (){
            $(this).attr("id", "");
        });
        $(".LoginForm").click(function() {
            newWin = window.open("public/login2.aspx","ESGIAppWindowNormal", "toolbar=0,location=0,status=0,menubar=0,resizable=1,scrollbars=1");
            AnimateLoginBut(true);
            Login();
            return false;
        });
        $(".ForgotPasswordLink").click(function() {
            LoadDialogs("RemindPassword");
            $("div.remind_password_dialog").smart_modal(
                {show: function(){
                    $("span.DefaultText").show();
                    $("button.RemindPassword").click(function(){
                        RemindPassword();                          
                    });
                }}
            );
            $("div.remind_password_dialog").smart_modal_show();
            
            return false;
        });
        
        $("a.registration").click(function() {
            ShowRegistrationForm();
            return false;   
        });
        
        var params = $.query( document.location.href );
        if (params.Register || params.Register == "")
        {            
            ShowRegistrationForm();
        }        
    }
)


function pageload (hash) 
{    
    if (hash)
        if (hash.Equals("Registration"))        
            ShowRegistrationForm();         
        else if (hash.Equals("index.aspx"))
            GoHome();
        else        
            load_content(hash);
    else 
    {
        if (hash == "") {
        //caution! changes here may break SEO-compatibility
        //verify URL's: "/ESGI", "/ESGI?promo=1006", "/ESGI/video.aspx", "/ESGI/?promo=1006#video.aspx"..
            var s=document.location.href;
            if (s.indexOf('#') < 0 && s.indexOf('/?') > 0) GoHome();
        }
    }
}

function load_content (url)
{
    if (typeof(urchinTracker)!="undefined") urchinTracker('#'+url.toLowerCase());
    loader (true);
    $(".second_top_menu, .second_sub_menu").hide();
    $.ajax({
        type:  "GET",
        url:   "/"+ appName +"/" + url + "?NoHeaderAndFooter=1",
        cache: false,
        success: function( data )
        {
            loader (false);
            set_active_menu(url);   
            $("#home_table").hide();
            $("#inside_table").show();  
            $("#content_block").html(data);
            $("#page_name").html($("#content_block").find("input#PageName").val())
            $(".table-general").attr("id", "inside");
        },                   
        error: function(data)
        {
            loader(false); 
            alert("Page not found"); 
        }
    });
}

function set_active_menu (url)
{
    $("#table_logo a").attr("id", "");
    $("#table_logo a[href='#"+url+"']").attr("id", "active")
}

function GoHome()
{    
    $(".username").focus();
    $("#home_table").show();
    $("#inside_table").hide();
    $(".table-general").attr("id", "home");
    
    set_active_menu(null);
}
      

function RemindPassword()
{
    var username = $("input.pusername:visible").val();
    var email    = $("input.pemail:visible").val();
    
    if (username.Equals("") && email.Equals("")) {
        $("span.err:visible").html("Please enter username or email");
        return false;
    } 
    
    if (email != '' && !CheckEmail(email)) {
        $("span.err:visible").html("Please enter a valid email above");
        return false;
    }
       
    $("span.err:visible").html("");
       
    $.ajax({
        type: "POST",
        url: "Public/InfoServices/Registration.asmx/RemindPassword",
        dataType: "xml",
        data: "email=" + email + "&username=" + username,
        success: function(response) {
            var result = $(response).find("boolean").text();
            $("span.DefaultText").hide();
            if (result == 'true')
            {
                $("span.IncorrectText").hide(); 
                $("span.SeccessfulText").show(); 
                $("table.rp").hide(); 
                $("button.RemindPassword").hide();
                $("button.rp_cancel").hide();
                $("button.rp_ok").show();                
            }
            else if (result == 'false')
            {
                $("span.IncorrectText").show();         
            }
        }      
    });                    
}

     
function ResendConfirmationEmail(name, login)
{
    var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
    var username = $(".username").val();
    var password = $(".password").val();
    var email    = $("input.cemail:visible").val();
    
    if(email != '' && emailRegEx.test(email))
    {
        $.ajax({
            type: "POST",
            url: "Public/InfoServices/Registration.asmx/ResendConfirmationEmail",
            dataType: "xml",
            data: "username=" + username + "&password=" + password + "&email=" + email,
            success: function(response) {
                var resp = $(response).text();
                if (login)  {
                    doLogin();   
                } 
            }      
        }); 
        
        $(name).smart_modal_hide();    
    }
    else
    {
        var msg = "Please enter a valid email above";
        alert(msg);
        $("span.err:visible").html(msg);
    }
}


function showResponse(responseText, statusText)  { 

    alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + 
        '\n\nThe output div should have already been updated with the responseText.'); 
}
 

function UnLoadDialogs()
{
    $("#dialogs").empty();
    $("#dialogs").smart_modal_remove();
}

var ObjectBrokerUrl = "objectBroker.aspx?ClassName=[className]&XslFilename=[xslFilename]&AssemblyName=Public";
function LoadDialogsEx(className, xslFilename, objParamsStr, lpName) 
{				
    if (lpName == null || lpName == "") lpName="#dialogs";
    objUrl = ObjectBrokerUrl.replace("[className]",className).replace("[xslFilename]",xslFilename);
    if (document.location.href.toLowerCase().indexOf('/public/')<0)
        objUrl = 'public/' + objUrl;
    if (objParamsStr) {
	    if (objUrl.indexOf("?") == -1) 
	    {
		    objUrl += "?";
	    } 
	    else 
	    {
		    objUrl += "&";
	    }
	    objUrl += objParamsStr;
    }				 


    $.ajax({
        url: objUrl,
        async: false, 
        cache: false,
        dataType: "html",
        success: function(html) {
            UnLoadDialogs();
            $(html).appendTo(lpName);
        }
    });         
}
		

function LoadDialogs(name)
{
    prefix="";
    if (document.location.href.toLowerCase().indexOf('/public/')<0) prefix="public/";
    $("#dialogs ." + name).empty();
    $.ajax({
        url: prefix+"Templates/Html/"+ name +".htm",
        async: false, 
        cache: false,
        dataType: "html",
        success: function(html) {
             $(html).appendTo("#dialogs")
        }
    });        
}


var submitting=false;
function submitDialogForm(form, modal, disableButt)
{  
    if (disableButt) $(disableButt).attr("disabled", true);
    if (submitting) return;
    submitting=true;    
    $(".loaderimg").show();    
    var form = $(form);
    var s = form.formSerialize()
    $.ajax({
        async: false,
        type: "POST",
        url: form.attr("action"),
        dataType: "html",
        data: s,
        success: function(response, sta) {
            if (response.length < 300)
            {
                var i = response.indexOf("redirect=");                
                if (i>0) response = response.substring(i+9).split("\r")[0].split("\n")[0];
                document.location.href=response;
                return;
            }
            UnLoadDialogs();
            $("#dialogs").empty();
            $(response).appendTo("#dialogs");            
            $(modal).smart_modal(
                {show: function() 
                    {                        
                        submitting=false;
                    }, 
                hide_on_overlay_click: false,
                overlay: true
                }
            );
            $(modal).smart_modal_show(); 
        }      
    }); 
}

function SubmitRegFin()
{
    submitDialogForm("form[name='RegisterFin']", "div.RegFin_dialog");
}

function ShowPO()
{
    LoadDialogsEx("PurchaseOrder", "PurchaseOrder");
    $("div.PO_dialog").smart_modal(
        {show: function() 
            {}, 
            hide_on_overlay_click: false,
            overlay: true
        }
    );
    $("div.PO_dialog").smart_modal_show();
}

var newWin;

function closeNewWin()
{
    if (newWin) newWin.close();
}

function Checksum(str)
{
    var lc = str.toLowerCase();
    var i=13, sum=0;
    for(j=0; j<lc.length; ++j)
    {
        sum += i*lc.charCodeAt(j);
        i = i*17 % 100;
    }
    return sum % 40;
}
      
function Login()
{
    var username = $(".username").val();
    var password = $(".password").val();

    if (username.Equals("") || password.Equals(""))
    {
        AnimateLoginBut(false);
        alert("Please type in your login and password.");
        return false;
    }

    $.ajax({
        type: "POST",
        url: "Public/InfoServices/Registration.asmx/Login_cs",
        dataType: "xml",
        data: "username=" + username + "&pchecksum=" + Checksum(password),
        async: false,
        success: function(response)
        {
            AnimateLoginBut(false);
            var EmailIsConfirmed = $(response).find("EmailIsConfirmed").text();
            var ErrorMessage = $(response).find("ErrorMessage").text();
            var UserID = $(response).find("UserID").text();
            var EntryCount = $(response).find("EntryCount").text();
            var UserType = $(response).find("Type").text();
            var IsExpired = $(response).find("IsExpired").text();
            var ExpirationDate = $(response).find("ExpirationDate").text();
            var Email = $(response).find("Email").text();
            var HasOpenedSession = $(response).find("HasOpenedSession").text();
            var showPO = $(response).find("ShowPO").text();
            var DistrAndSchoolFilled = $(response).find("DistrictAndSchoolFilled").text();
            
            if (DistrAndSchoolFilled == 'false')
            {
                GoToStep3(0);
                return;
            }
            
            if (UserType.Equals("A"))
            {
                doLogin(HasOpenedSession);
                return true;    
            }
            
            if (ErrorMessage == '' || ErrorMessage == null)
            {                
                if (showPO == 'true')
                {
                    closeNewWin();
                    ShowPO();
                }
                else if (IsExpired == 'true') {
                    closeNewWin();
                    // Show Renewal Screen
                    ShowRenewalScreen();
                }
                else  
                {
                    if (EmailIsConfirmed == 'false')
                    {
                        closeNewWin();
                        LoadDialogs("ConfirmEmail");
                        if (EntryCount >= 3) 
                        {  
                            $("div.invalid_user_dialog").smart_modal(
                                {show: function(){                   
                                    $(".cemail").val(Email)                
                                    $("button.ResendButton").click(function(){                               
				                        ResendConfirmationEmail("div.invalid_user_dialog"); 
				                        return false;
			                        });
                                }}
                            );
                            
                            $("div.invalid_user_dialog").smart_modal_show();              
                        }
                        else 
                        {
                            $("#logintimes").text(3-EntryCount)
                            $("div.confirm_email_dialog").smart_modal(
                                {show: function(){
                                    $(".cemail").val(Email)
                                    $("button.ResendButton").click(function() {
				                            ResendConfirmationEmail("div.confirm_email_dialog", true); 
				                            return false;
			                        });
                                }}
                            );                        
                            $("div.confirm_email_dialog").smart_modal_show();  
                        }    
                    }
                    else 
                    {
                        doLogin(HasOpenedSession);
                    }                    
                }
            }                 
            else
            {
                closeNewWin();
                alert(ErrorMessage);
            }
        },
        error: function ()
        {
            closeNewWin();
            AnimateLoginBut(false);
            alert("Communication error!");
        }       
    }); 
}
   
function ShowRegistrationForm()
{
    Jump(true, 'public/Registration.aspx');
}

function ShowRenewalScreen()
{
    Jump(true, 'public/Renewal.aspx');
}
  
function ShowRegFinForm(guid)
{
        LoadDialogsEx("RegisterFin", "RegisterFin", "guid="+guid);
        $("div.RegFin_dialog").smart_modal(
            {show: function() 
                {                    
                }, 
            hide_on_overlay_click: false,
            overlay: true
            }
        );
        $("div.RegFin_dialog").smart_modal_show();     
}
      	
/* Old Code. Refactor */

var isMSIE = document.attachEvent != null;
var div_loader = null;

function SetParams ( obj )
{
	obj = $(obj);
	
	var topmenu = obj.attr("class").Equals("top_menu")
			   || obj.attr("class").Equals("second_top_menu")

	if (!obj.attr("id").Equals(""))
	    return;

	var menu = obj.parent().find(".second_top_menu, .second_sub_menu").each(function(){
        obj = topmenu ? obj.parent() : obj;
        $(this).css({
			'position' : 'absolute',
			'top'  : (obj.position().top + obj.height() - (topmenu ? (isMSIE ? 2 : 3) : 10)) + 'px',
			'left' : (obj.position().left - (topmenu ? 1 : 0)) + 'px',
			'z-index' : '1000'
		});
		
		if (topmenu)
		{
			var cnt = $(this).parent();
			if ($(this).width() < cnt.width())
			    $(this).find("table").css("width", cnt.width() + 14)
		}
	});
};

function loader (show)
{
    if (show && div_loader == null)
    {
        var div = document.createElement("div");
        var table = $("#home_table").css("display").Equals("none") ? "#inside_table" : "#home_table";
        $(div).css("width",  $(table).width());
        $(div).css("height", $(table).height());
        $(div).css("left", $(table).position().left + "px");
        $(div).attr("class", "loader");
        $(div).insertAfter("#center_container");
        div_loader = div;
    }
    else
    {
        $(div_loader).remove();
        set_loader = false;
        div_loader = null;            
    }   
};

function Getmenu( obj )
{
	return (obj.id == '') ? obj.parentNode.childNodes[1] : obj;
};

function getBounds(element)
{
    var left = element.offsetLeft;
    var top  = element.offsetTop;
    for (var parent = element.offsetParent; parent; parent = parent.offsetParent)
    {
        left += parent.offsetLeft - parent.scrollLeft;
        top  += parent.offsetTop  - parent.scrollTop;
    }

    return {
        left: left,
        top:  top,
        width:  element.offsetWidth,
        height: element.offsetHeight
    };
};

function doLogin(HasOpenedSession)
{    
    if (HasOpenedSession == 'true')
    {
        if (!confirm("Account is currently in use: This account is currently logged into on another computer. Click on 'OK' to logoff on the other computer, and login now. Click on 'Cancel' if you do not want to login."))
            return
    }

	var isGood = false;
	if (!(window.name == "ESGIAppWindowNormal" || window.name == "ESGIAppWindow")) 
	{
		if (document.forms[0]) 
		{					
			if (document.forms[0].elements["LoginForm.UserName"]) 
			{					
				try {
					//var newWin = window.open("login2.aspx","ESGIAppWindowNormal", "toolbar=0,location=0,status=0,menubar=0,resizable=1,scrollbars=1");
					newWin.opener = self;								
					isGood = true;								
					window.opener = "";
					alterWindow(newWin);
				}					
				catch (ex) 
				{
					//do nothing
				}
			}
		}
	}
	if (!isGood) 
	{					
		if (document.forms[0].elements["LoginForm.UserName"])
		{
			document.forms[0].submit();
		} 
		else 
		{
			location.href="login.aspx";
		}
	}
	return false;
}

function CheckEmail(email)
{
    var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
    return email != '' && emailRegEx.test(email)
}	

function FormatDate (date)
{
    return (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear()
};

function AddError(element, text)
{  
    if (typeof(text) == 'undefined')
        text = "This field is required";    

    var ErrorIsExist = false;
    for (var i=0; i<Errors.length; i++)
        if (Errors[i].id.Equals(element))
        {
            ErrorIsExist = true;
            break;       
        }

    if (!ErrorIsExist)
    {
        Errors.push
        ({
            id: element, 
            message: text
        });
    }                         
};
      
function HasErrors()
{
    return Errors.length > 0;
};

function ShowErrors()
{
    $(".formerror").remove();
    $(".formnotify").remove();
    
    for (var i=0; i<Errors.length;i++)
        $(Errors[i].id).after("<span class='formerror'><br /><i>"+ Errors[i].message +"</i></span>")  
    
    if (typeof(CenterDialogs) != "undefined") CenterDialogs(false);
};

function ClearErrors()
{
    Errors = new Array();
    $(".formerror").remove();
    $(".formnotify").remove();
    if (typeof(CenterDialogs) != "undefined") CenterDialogs(false);
};

function CheckForRequiredFields(selectors)
{
    for (var i=0; i<selectors.length; i++)
        if ($(selectors[i]).val().IsEmpty()) 
            AddError(selectors[i]);         
};

function IsNumbers(str)
{
    var numbers = /^([0-9]+)$/; 
    return numbers.test(str);   
};

function IsFormat (str, len)
{
    return !(str.IsEmpty() || !IsNumbers(str) || ((typeof(len) != 'undefined') && (str.length > len)))  
};

var hlEl = new Array(), hlv = new Array();
function highLightAll()
{    
    var els = $(".highlight input:visible, .highlight select:visible");
    for (i=0; i<els.length; ++i)
    {
        el = els[i];
        if (hlEl[el.name] != 1)
        {
            $(el).css("background-color", "#CCEEFF");
            $(el).focus(function(){
                if (hlEl[this.name] != 1)
                {
                    $(this).css("background-color", "#FFFFFF");
                    hlv[this.name] = $(this).val();
                }
            });            
            $(el).blur(function(){
                if (hlEl[this.name] != 1)
                {
                    if ($(this).val() == hlv[this.name])
                    {
                        $(this).css("background-color", "#CCEEFF");
                    }
                    else
                    {
                        hlEl[this.name] = 1;
                        $(this).css("background-color", "#FFFFFF");
                    }
                }
            });
        }
    }
};

function PopulateSelect(objParamsStr, strFormName, strSelectName) 
{
    var DataBrokerUrl = "dataBroker.aspx?ClassName=[className]&AssemblyName=Public";
    if (document.location.href.toLowerCase().indexOf('/public/') < 0) DataBrokerUrl = 'public/' + DataBrokerUrl;
	objUrl = DataBrokerUrl.replace("[className]","DataBrokerSelects");
	if (objParamsStr) objUrl += "&" + objParamsStr;	
    objUrl += "&FormName="+strFormName+"&ObjectName="+strSelectName+"&"+Math.random();
    $.getJSON(objUrl,
        function(data){
	        var _strFormName = data.DataBrokerSelects.FormName.Text;
	        var _strSelectName = data.DataBrokerSelects.ObjectName.Text;
	        var _objSelect = $("select[name='" + _strSelectName + "']:visible");
	        if (_objSelect!=null && _objSelect.length>0) _objSelect = _objSelect[0];
	        if (!(_objSelect)) return;//user navigated away, so cancel operation
	        _objSelect.options.length = 0;
	        var vid = 0;
	        var vname = "Please Select ...";
	        var newoption = new Option(vname, vid, true, true);
	        var sIdx = 0;
	        if (typeof(data.DataBrokerSelects.Data.pare) != "undefined") {
		        var arrData = data.DataBrokerSelects.Data.pare;
		        if (typeof(arrData.length) != "undefined") {
			        for (i=0; i<arrData.length; i++) {
				        var vid = arrData[i].key.Text;
				        var vname = arrData[i].value.Text;
				        var newoption = new Option(vname, vid, true, true);
				        if (data.DataBrokerSelects.SelectedItem.Text+"" == vid+"") 
				        {								
					        sIdx = i;
				        }
				        _objSelect[_objSelect.length] = newoption;
			        }
		        } else {
			        var vid = arrData.key.Text;
			        var vname = arrData.value.Text;
			        var newoption = new Option(vname, vid, true, true);
			        _objSelect[_objSelect.length] = newoption;
			        sIdx = 0;
		        }
		        if (_objSelect.length > 0) {
			        _objSelect.selectedIndex = sIdx;
		        }
	        }
        }
    );
}

function RenewViaCode(code)
{
    $.ajax({
        type: "POST",
        url: "Public/InfoServices/Registration.asmx/RenewViaCode",
        //dataType: "html",
        data: "acode=" + code,
        async: false,
        success: function(response)
        {
            var renewed = false;            
            var resp = $(response).find("string").text();
            if (resp.indexOf("JoinToDistrictID=") >= 0)
                renewed = true;
            else
            {
                alert(resp);
                if (resp.indexOf("Your subscription has been renewed") >= 0)
                    renewed = true;
            }

            if (renewed)
            {
                UnLoadDialogs();
            }
            
            if (resp.substring(0, 17) == "JoinToDistrictID=")
                GoToStep3(eval(resp.substring(17)));
            
        },
        error: function ()
        {
            alert("Communication error!");
        }
     });
}

function GoToStep3(districtID)//register step 3
{
    document.location.href = "public/RegistrationStep3.htm?j=" + districtID;
}

//salesforce 'contact us' page
  function cuge(x){return document.getElementById(x);}
  function CuValidateField(fld)
  {
      var el = cuge(fld[0]);
      if (el == null) return true;
      if (el.value=='') {alert(fld[1]); el.focus(); return false;}
      return true;
  }
  function pe(fn)
  {
    return 'Please enter ' + fn + '.';
  }
  function ValidateContactsForm()
  {
    if (typeof(selfClosed)!='undefined') selfClosed=true; 
    if (document.forms['contactus'].email.value.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1) 
    { 
      var s =document.location.href; 
      s=s.substr(0, s.lastIndexOf('/')); 
      if (s.toLowerCase().indexOf('/public')<0) s+= '/public'; 
      document.forms['contactus'].retURL.value = s+'/thank_you_for_your_msg.aspx';
      var flds = [['fname', pe('First Name')], ['lname', pe('Last Name')], ['phone', pe('Phone')], ['00NA0000001bkvk', pe('School')], 
	['00NA0000001blB3', pe('District')], ['00NA0000001blGN', pe('State')], ['00NA0000001blGr', pe('Position')],
	['subject', pe('Subject')], ['description', pe('Description')]];
      for(var fld in flds)      
	if (!CuValidateField(flds[fld])) return false;
      cuge('name').value = cuge('fname').value + ' ' + cuge('lname').value;
      return true;
    } 
    else 
    {
      alert('Please enter valid e-mail.');
      cuge("email").focus();
      return false;
    }
  }  
//end salesforce 'contact us' page
