var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

var _userInfoCookie;

//Mark please check below: (it needs to check the cookie)
function checkLoggedIn() {

	var myhost = location.hostname;
	var preauthurl = "";
	var author = false;
	var isNewYork = false;
	if(myhost.indexOf('pacificlifeandannuity')>-1)
		isNewYork = true;
	var ssoLoginVal = "";
	if(isNewYork)
		ssoLoginVal = getCookie("mynySLog");
	else
		ssoLoginVal = getCookie("mySLogin");
		
	if((myhost.indexOf("author")> -1) || (myhost.indexOf("vwc")> -1))
		author = true;
	if(document.location.protocol == 'http:' && !author && ssoLoginVal == 'loggedin') {
		if(myhost!=null && (myhost.toLowerCase().indexOf("my")==-1) && (myhost.toLowerCase().indexOf("ip.rsd")==-1) && (myhost.toLowerCase().indexOf("ssa.rsd")==-1)){
			if(myhost.indexOf("www")> -1) {
				if(myhost.indexOf('mutualfunds')>-1){
					preauthurl = "https://mutualfunds.myaccount.pacificlife.com";
				} else if(myhost.indexOf('pacificlifeandannuity')>-1){
					preauthurl = "https://myaccount.annuities.pacificlifeandannuity.pacificlife.com";
				} else {// Annuities
					preauthurl = "https://annuities.myaccount.pacificlife.com";
				}
				location.href = preauthurl;
			}else {
				if (myhost.toLowerCase().indexOf("modeloffice")>-1){
					if(myhost.indexOf('pacificlifeandannuity')>-1)
						preauthurl = "https://my" + myhost;
					else
						preauthurl = "https://myaccount-" + myhost;
				} else {
					preauthurl = "https://myaccount-" + myhost;
				}
			}
		}
		window.location = preauthurl;
	}
	//alert("preauthurl: " + preauthurl + " checkLoggedIn: " + ssoLoginVal);
}

// Defining object type for SSO Cookie
// N:PLEVONE:APPDEF:P:1249071068:

function getSSOCookie() {

  //var ssov3 = getCookie("PLA_SSO","N:FAKE:REGDEF:N:1249071068:");
  var ssov3 = "";
  if(location.href.indexOf("my") > -1){ 
      ssov3 = getCookie("myDYB_CUST","AUTHOR#REGDEF#N#P#IMPN#APPDEF#Y");
  } else {
      ssov3 = getCookie("DYB_CUST","AUTHOR#REGDEF#N#P#IMPN#APPDEF#Y");
  }
 // var decoded = "";
//  if(ssov3 == "N:FAKE:REGDEF:N:1249071068:"){
//    decoded = ssov3;
//  } else {
//    decoded = decode(ssov3);
//  }

 // var cookieValues =decoded.split(":");
  var cookieValues =ssov3.split("#");
  var impers = cookieValues[4].charAt(3);
  var ssoCookie = { "impers"     : impers,
                    "userid"   : cookieValues[0],
                    "agency"   : cookieValues[1],
                    "usertype" : cookieValues[3],
                    "abctype": cookieValues[2], 
                    "caalert" : cookieValues[6]
                 };
    _userInfoCookie = ssoCookie;
   return ssoCookie;

}

function getDYBCookie() {

  var dybcust = getCookie("DYB_CUST","-#APPDEF#N#P#IMPN#APPDEF#Y");
  

  var cookieValues =dybcust.split("#");
   return cookieValues;

}

function getCAAlertFlag(){
  var dybcookie = getDYBCookie();
  if(dybcookie){
    if(dybcookie.length>6)
      return dybcookie[6];
  
  }
  return 'N';

}

//Onclick event handler
//Onclick event handler
function getAgencyGroup(){

  if(_userInfoCookie == undefined )
    getSSOCookie();
  //var ssov3 = getCookie("PLA_SSO","REGDEF");
   var ssov3 = _userInfoCookie.agency;
   // set to AUTHOR if no cookie found
  if(_userInfoCookie.userid=="AUTHOR"){
    if(document.location.hostname.indexOf("author")>-1){
      if(agencyid != "")
          ssov3 = agencyid;

      return ssov3;
    }else
      return "PUBLIC";
  }
 // var decoded = decode(ssov3);
 // var agencyGroup =decoded.split(":");
    
  return _userInfoCookie.agency;
}

function getUserType(){

  if(_userInfoCookie == undefined )
    getSSOCookie();
 // var ssov3 = getCookie("PLA_SSO","REGDEF");
  
 // var decoded = decode(ssov3);
 // var agencyGroup =decoded.split(":");
 // if(agencyGroup[3] == undefined){
  //   return '';
  //}
  return _userInfoCookie.usertype;
}

//called onload from myaccount pages
function showMyHiddenElements(ssoCookie) {
    var ssoLoginVal = getCookie("mySLogin"); 
    showHiddenElements(ssoCookie, ssoLoginVal);
    return;
}
function showMyNYHiddenElements(ssoCookie) {
    var ssoLoginVal = getCookie("mynySLog"); 
    showHiddenElements(ssoCookie, ssoLoginVal);
    return;
}
function showHiddenElements(ssoCookie, ssoLoginVal) {
    var aryHiddenEle = [ "signoff", "accmngt" ]
    var displayProp = "none";
	//alert('protocol'+ document.location.protocol);
	if(document.location.protocol == 'https:') {
		if (ssoLoginVal == "loggedin") {
			// for new corp & myaccount redesign
			changeNav(1);
			
			displayProp = "inline"; 
			
			// for P,D & B usertypes no link should show for myprofile
			showHiddenMyProfileElements(ssoCookie);
			 
		} else {
				// for new corp & myaccount redesign
				changeNav(0);
				
				if (document.getElementById("myprofile")){
					document.getElementById("myprofile").style.display = "none";
				}
		}
		
		//alert(getSSOCookie.userType());
		
		for (var i=0; i<aryHiddenEle.length; i++) {
			if (document.getElementById(aryHiddenEle[i])){
				document.getElementById(aryHiddenEle[i]).style.display = displayProp;
			}
		}
		showImpersonateElements(ssoCookie);
	}
    return;
}

function showHiddenMyProfileElements(ssoCookie) {
    if(("PDB".indexOf(ssoCookie.usertype)>-1) || (ssoCookie.impers == "Y")){
        document.getElementById("myprofile").style.display = "none";
    } else {
        if (document.getElementById("myprofile")){
            document.getElementById("myprofile").style.display = "inline";
        }
    }
    showHiddenBrokElements(ssoCookie);
    showImpersonateElements(ssoCookie);
    return;
}

function showHiddenBrokElements(ssoCookie) {
    // for EJ agency id remove FAQ, Sign Off and Premium Services links 
    if("68706".indexOf(ssoCookie.agency)>-1){
        if (document.getElementById("faq"))
            document.getElementById("faq").style.display = "none";
        if (document.getElementById("signoff"))
            document.getElementById("signoff").style.display = "none";
        if (document.getElementById("ps"))
            document.getElementById("ps").innerHTML = "";
        if (document.getElementById("myprofile")) // for single sign on
            document.getElementById("myprofile").style.display = "none";
    } else {
        if (document.getElementById("faq"))
            document.getElementById("faq").style.display = "inline";
        if (document.getElementById("signoff"))
            document.getElementById("signoff").style.display = "inline";
    }
    return;
}
function showHiddenIPElements() {
    var ssoLoginVal = getCookie("ipSSOLogin"); 
    if(document.location.pathname.indexOf('ssa')>-1)
        ssoLoginVal = getCookie("ssaSSOLogin");
    var aryHiddenEle = [ "signoff", "riqsso", "myprofile" ]
    var displayProp = "none";                       
    if (ssoLoginVal == "loggedin") {
        displayProp = "inline";     
    }
    
    //alert(getSSOCookie.userType());
    
    for (var i=0; i<aryHiddenEle.length; i++) {
        if (document.getElementById(aryHiddenEle[i]))
            document.getElementById(aryHiddenEle[i]).style.display = displayProp;
    }
    return;
}

function showImpersonateElements(ssoCookie) {
    if (ssoCookie.impers == "Y") {
        document.getElementById("impMessage").style.display = "block";
    }
    return;
}

/*
function changeNav(val){
    if(document.getElementById("nav_top")){
        if(val==1){
            //alert(val);
            document.getElementById("nav_top").className="wide";        
        } else if(val==0){
            //alert(val);
            document.getElementById("nav_top").className="notwide";
        }       
    }
}
*/

function changeNav(val){
    if(document.getElementById("nav_top")){
        if(val==1){
            //alert(val);
            document.getElementById("nav_top").className="wide"; 
            if(document.getElementById("acctbtn")){
            	document.getElementById("acctbtn").style.display="none";
				document.getElementById("acctbtnout").style.display="block";
            }
  
        } else if(val==0){
            //alert(val);
            document.getElementById("nav_top").className="notwide";
            if(document.getElementById("acctbtnout")){
            	document.getElementById("acctbtnout").style.display="none";
				document.getElementById("acctbtn").style.display="block";
            }
         
        }       
    }
}



getCookie = function(name, opt_default) {
  var nameEq = name + "=";
  var cookie = String(document.cookie);
  for (var pos = -1; (pos = cookie.indexOf(nameEq, pos + 1)) >= 0;) {
    var i = pos;
    // walk back along string skipping whitespace and looking for a ; before
    // the name to make sure that we don't match cookies whose name contains
    // the given name as a suffix.
	   // alert("cookie value plus 2: " + cookie.substring(pos-2));
	var cnt = 0;
    while (--i >= 0) {
      var ch = cookie.charAt(i);
	  cnt++;
      var ch = cookie.charAt(i);
	    // if cnt is 1 or 2 then this is cookie name, if more then 2 then name is 
		// substring of another cookie name. So break out. 
      if (ch == ';' && (cnt == 1 || cnt == 2)) {
        i = -1;  // indicate success
        break;
      }
	  if(cnt == 2)
	      break;
    }
    if (i == -1) {  // first cookie in the string or we found a ;
      var end = cookie.indexOf(';', pos);
      if (end < 0) {
        end = cookie.length;
      }
      return cookie.substring(pos + nameEq.length, end);
    }
  }
  return opt_default;
}

// public method for decoding
decode = function (input) {
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;

    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

    while (i < input.length) {

        enc1 = this._keyStr.indexOf(input.charAt(i++));
        enc2 = this._keyStr.indexOf(input.charAt(i++));
        enc3 = this._keyStr.indexOf(input.charAt(i++));
        enc4 = this._keyStr.indexOf(input.charAt(i++));

        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;

        output = output + String.fromCharCode(chr1);

        if (enc3 != 64) {
            output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
            output = output + String.fromCharCode(chr3);
        }

    }

    output = utf8_decode(output);

    return output;

}

// private method for UTF-8 decoding
utf8_decode = function (utftext) {
    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;

    while ( i < utftext.length ) {

        c = utftext.charCodeAt(i);

        if (c < 128) {
            string += String.fromCharCode(c);
            i++;
        }
        else if((c > 191) && (c < 224)) {
            c2 = utftext.charCodeAt(i+1);
            string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
            i += 2;
        }
        else {
            c2 = utftext.charCodeAt(i+1);
            c3 = utftext.charCodeAt(i+2);
            string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }

    }

    return string;
}
 
function sizeWin(url, hght, wdth) {
        var features = "dependent=yes,height=" + hght + ",width=" + wdth + ",resizable=yes,scrollbars=no,toolbar=yes";
        newMedia = window.open(url, 'large', features);
        newMedia.focus();
    }
        
function mediaWin(url) {    
        var features = "dependent=yes,height=450,width=525,resizable=yes,scrollbars=yes,toolbar=yes";
        newMedia = window.open(url, 'media', features);
        newMedia.focus();
    }
    
function statementTemp(theURL,winName,features) {
    window.open(theURL,winName,features); 
} 

function PopUp(theURL,winName,features){
    group_message = window.open(theURL,winName,features);
    group_message.top.focus(); 
} 

function getSSOLoginValue(){

    var ssologin = getCookie("SSOLogin","logout");
    return ssologin;
    
}


function checkLoginValue(){
    if(getSSOLoginValue() == "logout" || getSSOLoginValue() == "timeout"){
        window.location.href="/vab/authenticate/login.html";
        
    }
    setTimeout("checkLoginValue()",10000);
}

checkLoggedIn();


// Product List 
	function agentwindow() { 
		var agentwindowprops = "location=no,menubar=no,toolbar=no,status=no,width=400,height=500,resizable=no,scrollbars=no,maximize=no";
		if ( navigator.appName == 'Netscape' ) 
			 agentwindowprops = "location=no,menubar=no,toolbar=no,status=no,width=400,height=400,resizable=no,scrollbars=no,maximize=no";
		else 
			agentwindowprops = "location=no,menubar=no,toolbar=no,status=no,width=400,height=400,resizable=no,scrollbars=no,maximize=no";

		agentlistwindow = window.open("/apps/loading_animated.html", "AgentListTop", agentwindowprops);
		agentlistwindow.focus(); 

		var today = new Date();
		var hour = today.getHours();
		var minute = today.getMinutes();
		var second = today.getSeconds();
		var locationstring = "/--/contractmanagement/agentlist.do?plaAction=producers&submittime=";	
		locationstring = locationstring + hour + minute + second;
		if (agentlistwindow != null) {
			agentlistwindow.location.href = locationstring;  
		}

	}
