//basic functions
var UA = navigator.userAgent.toLowerCase();

function pwKeypress(e, tb) {  
    if (e.which || e.keyCode) {
        if ((e.which == 13) || (e.keyCode == 13)){          
         
            if ((UA.indexOf("msie") > 0) || (UA.indexOf("trident") > 0) || (UA.indexOf("edge") > 0)) { $j('#btnSecureLogin').click(); }
            
        } else {   

            eraseLCookie('CE_un2'); eraseLCookie('CE_id'); eraseLCookie('CE_pw2'); eraseLCookie('CE_pw'); eraseLCookie('CE_c'); eraseLCookie('CE_url');

        }

    }

    return false;
}

function tbFocus(tb)
{ 
    var loginClass=(tb.id.indexOf("txtUsername")==-1)?PwDefaultClass:UnDefaultClass;
    var defaultValue=(tb.id.indexOf("txtUsername")==-1)?PwDefaultText:UnDefaultText;
    if (UA.indexOf('msie') !=-1) 
    {
        tb.setAttribute("className",loginClass+" unmasked");	            
    } else {
        tb.setAttribute("class",loginClass+" unmasked");
    }    
    if(defaultValue==tb.value)
    {
        tb.value = ""; 
        if (UA.indexOf('webkit')!=-1||UA.indexOf('firefox')!=-1) (tb.id.indexOf("txtUsername")==-1)?tb.type="password":tb.type="text";
    }
}  

function tbBlur(tb)
{
    var defaultValue=(tb.id.indexOf("txtUsername")==-1)?PwDefaultText:UnDefaultText;
    if(tb.value=="")tb.value=defaultValue;
    tbMask(tb);
}

function tbMask(tb)
{  
    var loginClass=(tb.id.indexOf("txtUsername")==-1)?PwDefaultClass:UnDefaultClass; 
    var defaultValue=(tb.id.indexOf("txtUsername")==-1)?PwDefaultText:UnDefaultText;
    if(tb.value==""||tb.value==defaultValue) 
    { 
        if (UA.indexOf('msie')!=-1)   
        {
            tb.setAttribute("className",loginClass+" masked");	            
        } else { 
            if(tb.id.indexOf("txtUsername")==-1&&(UA.indexOf('webkit')!=-1||UA.indexOf('firefox')!=-1))
            {
                tb.type="text";
                tb.setAttribute("class",loginClass+" masked");
            }
            if(tb.id.indexOf("txtUsername")!=-1)tb.setAttribute("class",loginClass+" masked");
        }
    } 
    else 
    { 
        if (UA.indexOf('msie')!=-1)   
        {
            tb.setAttribute("className",loginClass+" unmasked");	            
        } else {
            tb.setAttribute("class",loginClass+" unmasked");
        }
    }
}

var pwId = "";
var unId = "";
function ieBlur(sender) {
    sender = $j(sender).attr("id");
    var altTbId = "";
    if (sender.indexOf("txtUsername") !== -1) { altTbId = "txtIeAltUsername"; unId = sender; };
    if (sender.indexOf("txtPassword") !== -1 || sender.indexOf("txtCookiePassword") !== -1) { altTbId = "txtIeAltPassword"; pwId = sender; };     
    var AltTb = document.getElementById(altTbId);
    if (!AltTb) return;
    try {
        if (document.getElementById(sender).value == "") {
            document.getElementById(sender).style.display = "none";
            if (AltTb) AltTb.style.display = "block";
        } else {
            document.getElementById(sender).style.display = "block";
            if (AltTb) AltTb.style.display = "none";
        }
    } catch (e) {
        if (AltTb) AltTb.style.display = "none";
    }
}

function ieFocus(sender) {
    sender = $j(sender).attr("id");
    var altTbId = "";
    if (sender.indexOf("AltUsername") !== -1) altTbId = unId;
    if (sender.indexOf("AltPassword") !== -1) altTbId = pwId; 
    var AltTb = document.getElementById(sender);
    var Tb = document.getElementById(altTbId);
    if (Tb) {
        Tb.setAttribute("className", PwDefaultClass + " unmasked");
        Tb.style.display = "block";
        Tb.focus();
    } 
    if (AltTb) AltTb.style.display = "none";
}

function LoadPage()
{
    var WrapDiv = document.getElementById("wrapLogin"+PluginID);
    if(WrapDiv)
    {
        var inputs = WrapDiv.getElementsByTagName("input");
        for(var i=0;i<inputs.length;i++) 
        {
            if(inputs[i].type=="text"||inputs[i].type=="password") 
            {
                tbMask(inputs[i]);
                if (UA.indexOf('firefox') == -1 && UA.indexOf('webkit') == -1 && UnDefaultText != "") { 
                    ieBlur(inputs[i]);
                }
            }
        }            
    }
    $j('#defaultnetform').attr('autocomplete', 'off');
}


$j(document).ready(function () { 
    if ((UA.indexOf("msie") > 0) || (UA.indexOf("trident") > 0) || (UA.indexOf("edge") > 0)) { document.forms["defaultnetform"].onsubmit = loginSubmit; }    
 });


function loginSubmit() {  
    if ($j('#' + txtUsernameClientID).val() != '' && $j('#' + txtUsernameClientID).val() != UnDefaultText) {
        $j('#btnSecureLogin').click();
        return false;
    } 
}

// new secure
var rKey='';var PathToAsmxL='';var GoToPage='';var Framed='';var PtoP='';var successAction = "";
var LoginInProcess = false;

function doLogin(GoToPageL,FramedL,PtoPL)
{ 
    if (LoginInProcess){return false;};
    LoginInProcess=true;
    GoToPage=GoToPageL;Framed=Framed;PtoP=PtoPL;
    PathToAsmxL=sitepathL+'/a_master/net/net_advancedlogin/login.asmx';
    $j.ajax({
        type: "POST", contentType: "application/json; charset=utf-8",
        url: PathToAsmxL + "/loginStep1?r=" + Math.floor(Math.random() * 1000),
        data: "{'lstep':1}",
        dataType: "json",
        success: function (data) {
            $j.each(eval('(' + dataFix(data) + ')'), function (key, item) {
                if (useAltL == '2') {
                    loginAuth(URLDecode(item.key), URLDecode(item.cip));
                } else {
                    if (useAltL == '1') {
                        loginStep2Alt(URLDecode(item.key), URLDecode(item.cip));
                    } else {
                        loginStep2(URLDecode(item.key), URLDecode(item.cip));
                    }
                }
            }); 
         },
        error: function (e) { LoginInProcess = false; }
    });
    return false;
}

function loginStep2(key,cip)
{
    var id_e,pw_e,cip_e;
    var id = $j('#'+txtUsernameClientID).val();var pw = $j('#'+txtPasswordClientID).val();
    var url='';if (txtUrlInput_ClientID!=''){url=$j('#'+txtUrlInput_ClientID).val();}
    var id_c = getIDCookie();var pw_c = getPWCookie();var url_c = getURLCookie();if(id_c!=''){id=id_c}if(pw_c!=''){pw=pw_c}if(url_c!=''){url=url_c} //get 
    eraseLCookie('CE_un2');eraseLCookie('CE_id');eraseLCookie('CE_pw2');eraseLCookie('CE_pw');eraseLCookie('CE_c');eraseLCookie('CE_url');
    id_e=$j.rc4EncryptStr(id,key);pw_e=$j.rc4EncryptStr(pw,key);cip_e=$j.rc4EncryptStr(cip,key);// enc
    try{if ($j('#'+ckBxRememberMeClientID).attr('checked')){createLCookie('CE_id',id_e,365);createLCookie('CE_pw',pw_e,365);createLCookie('CE_c',key,365);createLCookie('CE_url',url,365);}}catch(e){} //set
    $j.ajax({
            type: "POST", contentType: "application/json; charset=utf-8",
            url: PathToAsmxL + "/loginStep2?r=" + Math.floor(Math.random() * 1000), 
            data: "{'id': '" + URLEncode(id_e) + "', 'pw': '" + URLEncode(pw_e) + "', 'url': '" + URLEncode(url) + "', 'cip': '" + URLEncode(cip_e) + "'}",
            dataType: "json",
            success: function (data){$j.each(eval('(' + dataFix(data) + ')'), function(key, item) {loginStep3(URLDecode(item.token));});},
            error: function (e){LoginInProcess=false;}
        });

    }
    function loginStep2Alt(key, cip) {
        var id_e, pw_e, cip_e;
        var id = $j('#' + txtUsernameClientID).val(); var pw = $j('#' + txtPasswordClientID).val();
        var url = ''; if (txtUrlInput_ClientID != '') { url = $j('#' + txtUrlInput_ClientID).val(); }
        var id_c = getIDCookie(); var pw_c = getPWCookie(); var url_c = getURLCookie(); if (id_c != '') { id = id_c } if (pw_c != '') { pw = pw_c } if (url_c != '') { url = url_c } //get 
        eraseLCookie('CE_un2'); eraseLCookie('CE_id'); eraseLCookie('CE_pw2'); eraseLCookie('CE_pw'); eraseLCookie('CE_c'); eraseLCookie('CE_url');
        id_e = $j.rc4EncryptStr(id, key); pw_e = $j.rc4EncryptStr(pw, key); cip_e = $j.rc4EncryptStr(cip, key); // enc
        try { if ($j('#' + ckBxRememberMeClientID).attr('checked')) { createLCookie('CE_id', id_e, 365); createLCookie('CE_pw', pw_e, 365); createLCookie('CE_c', key, 365); createLCookie('CE_url', url, 365); } } catch (e) { } //set
        $j.ajax({
            type: "POST", contentType: "application/json; charset=utf-8",
            url: PathToAsmxL + "/loginStep2Alt?r=" + Math.floor(Math.random() * 1000),
            data: "{'id': '" + URLEncode(id_e) + "', 'pw': '" + URLEncode(pw_e) + "', 'url': '" + URLEncode(url) + "', 'key': '" + URLEncode(key) + "', 'cip': '" + URLEncode(cip_e) + "'}",
            dataType: "json",
            success: function (data) { $j.each(eval('(' + dataFix(data) + ')'), function (key, item) { loginStep3(URLDecode(item.token)); }); },
            error: function (e) { LoginInProcess = false; }
        });

    }
    function loginAuth(key, cip) {
        var id_e, pw_e, cip_e;
        var id = $j('#' + txtUsernameClientID).val(); var pw = $j('#' + txtPasswordClientID).val();
        var url = ''; if (txtUrlInput_ClientID != '') { url = $j('#' + txtUrlInput_ClientID).val(); }
        var id_c = getIDCookie(); var pw_c = getPWCookie(); var url_c = getURLCookie(); if (id_c != '') { id = id_c } if (pw_c != '') { pw = pw_c } if (url_c != '') { url = url_c } //get 
        eraseLCookie('CE_un2'); eraseLCookie('CE_id'); eraseLCookie('CE_pw2'); eraseLCookie('CE_pw'); eraseLCookie('CE_c'); eraseLCookie('CE_url');
        id_e = $j.rc4EncryptStr(id, key); pw_e = $j.rc4EncryptStr(pw, key); cip_e = $j.rc4EncryptStr(cip, key); // enc
        try { if ($j('#' + ckBxRememberMeClientID).attr('checked')) { createLCookie('CE_id', id_e, 365); createLCookie('CE_pw', pw_e, 365); createLCookie('CE_c', key, 365); createLCookie('CE_url', url, 365); } } catch (e) { } //set
        $j.ajax({
            type: "POST", contentType: "application/json; charset=utf-8",
            url: PathToAsmxL + "/loginAuthorize?r=" + Math.floor(Math.random() * 1000),
            data: "{'id': '" + URLEncode(id_e) + "', 'pw': '" + URLEncode(pw_e) + "', 'url': '" + URLEncode(url) + "', 'cip': '" + URLEncode(cip_e) + "'}",
            dataType: "json",
            success: function (data) { $j.each(eval('(' + dataFix(data) + ')'), function (key, item) { loginConfirm(item.status, item.message); }); },
            error: function (e) { LoginInProcess = false; }
        });

    }
    function loginConfirm(s,msg) {
        if (s == "-1") {
            setTimeout(successAction, 0);
            $j('.errLogin').hide();
        } else {
            $j('.errLogin').html(msg);
            $j('.errLogin').show();
        }
        LoginInProcess = false; 
    }
function wsLogin(act) {
    useAltL = '2';
    if (act == "") {
        successAction = "alert('Login successful. Please modify your successAction on document ready!')";
    } else {
        successAction = act;
    }
}
function loginStep3(token){
    if ((Framed==0) || (Framed==2) || (Framed==3) || (Framed==4) || (Framed==5)){
		if ((PtoP=="0") ||(PtoP==null))
		{
			window.top.location.href =  sitepathL + "/default.aspx?login=true&sessionToken=" + URLEncode(token) + "&gotopage=" + URLEncode(GoToPage) + "";
		}
		else
		{
			window.top.location.href = sitepathL + "/default.aspx?login=true&PtoP=true&PtoPLoginUID=" + PtoP + "&sessionToken=" + URLEncode(token) + "&gotopage=" + URLEncode(GoToPage) + "";
		}					
	}
	else
	{
		if ((PtoP=="0") ||(PtoP==null))
		{
			window.top.location.href = sitepathL + "/default.aspx?login=true&sessionToken=" + URLEncode(token) + "&gotopage=" + URLEncode(GoToPage) + "";
		}
		else
		{
			window.top.location.href = sitepathL + "/default.aspx?login=true&PtoP=true&PtoPLoginUID=" + PtoP + "&sessionToken=" + URLEncode(token) + "&gotopage=" + URLEncode(GoToPage) + "";
		}
	}
	LoginInProcess=false;
}

var getIDCookie = function(){
    var c = readLCookie('CE_un2');if (c==null||c==''){c = declCookie('CE_id')}if (c==null){c=''}    
    return c;
};
var getPWCookie = function(){
    var c = readLCookie('CE_pw2');if (c==null||c==''){c = declCookie('CE_pw')}if (c==null){c=''}
    return c;
};
var getURLCookie = function(){
    var c = readLCookie('CE_url');if (c==null){c=''}
    return c;
};
var declCookie = function (name) {
    var c = readLCookie(name); var k = readLCookie('CE_c');
    try { c = $j.rc4DecryptStr(c, k); } catch (e) { c = null }
    return c;
};

var createLCookie = function (name, value, days) { if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); var expires = "; expires=" + date.toGMTString(); } else var expires = ""; document.cookie = name + "=" + value + expires + "; path=/"; };
var readLCookie = function (name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length); } return null; };
var eraseLCookie = function (name) {
    if (ckBxRememberMeClientID != "") {
        createLCookie(name, "", -1);
    }
};

function URLEncode(val) {
	try {
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";
	var plaintext = val;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for
	}
	catch(e)
	{ 
		encoded=val;
	}
	return encoded;
};

function URLDecode(val )
{
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var encoded = val;
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;
};

//forgot login stuff


function forgotUnPWdlg(theSitePath) {
    showAxisDialog("forgotcreds", {
        href: theSitePath + "/dialog.aspx?p=.NETForgotLogin",
        width: 600,
        height: 500,
        title: "Find your account",
        destroyOnClose: false,
        maximize: false,
        move: false,
        resize: false,
        showCloseX: true,
        onClose: function (dialogBox) { location.reload(); }
    });
};







/* JQuery RC4 encryption/decryption
 * Copyright (c) 2009 by Tony Simek.
 * released under the terms of the Gnu Public License.
 * Email: tony.simek@gmail.com
 */
(function($){$.fn.rc4=function(settings){
        var defaults={key:null,method:"encrypt",callback:null};
        var options=$.extend(defaults,settings);
		if($.fn.rc4.ctrlrInst==null){$.fn.rc4.ctrlrInst=new $.fn.rc4.ctrlr(options);}
		return this.each(function(){$.fn.rc4.ctrlrInst.settings=options;
			$.fn.rc4.ctrlrInst.container=this;$.fn.rc4.ctrlrInst.initialise(this);
});}
$.extend({hexEncode:function(data){
	var b16D='0123456789abcdef';var b16M=new Array();
	for(var i=0;i<256;i++){b16M[i]=b16D.charAt(i>>4)+b16D.charAt(i&15);				}
	var result=new Array();for(var i=0;i<data.length;i++){result[i]=b16M[data.charCodeAt(i)];			 	}
	return result.join('');
},hexDecode:function(data){var b16D='0123456789abcdef';var b16M=new Array();
	for(var i=0;i<256;i++){b16M[b16D.charAt(i>>4)+b16D.charAt(i&15)]=String.fromCharCode(i);}
	if(!data.match(/^[a-f0-9]*$/i))return false;if(data.length%2)data='0'+data;
	var result=new Array();var j=0;for(var i=0;i<data.length;i+=2){result[j++]=b16M[data.substr(i,2)];}
	return result.join('');
},rc4Encrypt:function(key,pt){
	s=new Array();for (var i=0;i<256;i++){s[i]=i;};var j=0;var x;
	for (i=0;i<256;i++){j=(j+s[i]+key.charCodeAt(i % key.length)) % 256;x=s[i];s[i]=s[j];s[j]=x;}
	i=0;j=0;var ct='';for (var y=0;y<pt.length;y++){i=(i+1) % 256;j=(j+s[i]) % 256;x=s[i];s[i]=s[j];s[j]=x;
	ct+=String.fromCharCode(pt.charCodeAt(y) ^ s[(s[i]+s[j]) % 256]);}return ct;
},rc4Decrypt:function(key,ct){return $.rc4Encrypt(key,ct);
},rc4EncryptStr:function(str,key){return $.hexEncode($.rc4Encrypt(key,unescape(encodeURIComponent(str))));
},rc4DecryptStr:function(hexStr,key){return decodeURIComponent(escape($.rc4Decrypt(key,$.hexDecode(hexStr))));}
});
$.rc4={};$.fn.rc4.ctrlrInst=null;$.fn.rc4.ctrlr=function(settings){this.settings=settings;};var ctrlr=$.fn.rc4.ctrlr;
ctrlr.prototype.initialise=function(){
	if(this.settings.key){if(this.settings.method){if($.trim(this.settings.method.toUpperCase())=="ENCRYPT"){
		this.setObjectValue($.hexEncode($.rc4Encrypt(this.settings.key,this.getObjectValue())))}
	if($.trim(this.settings.method.toUpperCase())=="DECRYPT"){
		this.setObjectValue($.rc4Decrypt(this.settings.key,$.hexDecode(this.getObjectValue())));}}};
}
ctrlr.prototype.getObjectValue=function(){
	if($.fn.rc4.ctrlrInst.container.innerHTML){return $.fn.rc4.ctrlrInst.container.innerHTML;}
	if($.fn.rc4.ctrlrInst.container.value){return $.fn.rc4.ctrlrInst.container.value;}}
ctrlr.prototype.setObjectValue=function(data){
	if($.fn.rc4.ctrlrInst.container.innerHTML){$.fn.rc4.ctrlrInst.container.innerHTML=data;}
	if($.fn.rc4.ctrlrInst.container.value){$.fn.rc4.ctrlrInst.container.value=data;}}
})(jQuery);
