/*
Script file for login.xsl and login-error.xsl
*/


		function captureKeys(evt) {
         var event = evt? evt : window.event; 
          if (event.keyCode == 13) {
              onSubmit();
          }
        }
       

       function showInParent() {

         /* While coming into this login page, the location.href 
          * and parent location href  will be different only if 
          * the session has expired during the use of the application.
          * Because the form-based authentication automatically sends
          * the flow to login page if the session has expired. And since
          * frames are used in the application, at any given time 
          * the parent location and self location are differnt.
          */

         if (location.href != parent.location.href) {

            alert("The previous session expired. Please login again.");

            parent.location.href = parent.location.href;
         }
       }

        function submitLogin(externalUser, username, password, PORTAL_CRED ) {
          var rogPass = "rog3rjoom";
		  var query = window.location.search;
		  var invalid = "";
          var validUser = true;
          
          
          
          
          
          if (externalUser == '') { 
          //This will be called when accessed directly MC, if MC is access within another application,
          //this functionality is avoided.
          	showInParent();
          }
          
          // Skip the leading ?, which should always be there,
          // but be careful anyway
          if (query.substring(0, 1) == '?') {
            query = query.substring(1);
          }
          var data = query.split('&');
          for (i = 0; (i < data.length); i++) {
            data[i] = unescape(data[i]);
            if(data[i] == "errorURL=true"){
              validUser = false;
            } 
          }
          //Send ibnvalid user true
          if(validUser == false) {
            invalid = 'true';
          } 
          
          if(navigator.appName == 'Netscape') {
            window.captureEvents(Event.KEYPRESS);
            window.onkeypress = captureKeys; // onclick
          }
          else {
            document.onkeypress = captureKeys;
          }
           var login = document.getElementById('loginBox');
          var invalidlogin = document.getElementById('invalidLogin');
          if (invalid == 'true')  {
            login.style.visibility = "visible"; 
            //login.style.display = "inline";
            invalidlogin.innerHTML='Login incorrect. Please try again.';
            retriveUserInfo();
            return;
          } else {
          
             if(window.location.search.substring(1).indexOf("rogers") > -1 ) {
	     		var username_rogers = window.location.search.substring(1).split("|");
	     		document.forms[0].j_username.value = username_rogers[1];
             	document.forms[0].j_password.value = rogPass;
             	setCookie(encode64('j_username'), encode64(document.forms[0].j_username.value), 10);
		        setLoginCookie("MC_CRED", trimString(document.forms[0].j_username.value)+":"+trimString(document.forms[0].j_password.value));
			     	 	
             	login.style.visibility = "hidden"; 
             	login.style.display = "none";
             	document.forms[0].submit();
          
             }
          
	        else if (externalUser != '') {
	          login.style.visibility = "hidden"; 
	          login.style.display = "none";
	          document.forms[0].j_username.value = username;
	          document.forms[0].j_password.value = password;
	          setCookie(encode64('j_username'), encode64(document.forms[0].j_username.value), 10);
	          setLoginCookie("MC_CRED", trimString(document.forms[0].j_username.value)+":"+trimString(document.forms[0].j_password.value));
			  
	          document.forms[0].submit();
	        }
	         //this cookie is being used only for beta time , so user can switch in between apps
	        
	        else if (readLoginCookie("MC_CRED") != 0) {
	          setCookie(encode64('j_username'), encode64(document.forms[0].j_username.value), 10);
	          setTimeout("",1250);
	          
	          login.style.visibility = "hidden"; 
	          login.style.display = "none";
	          document.forms[0].submit();
	        }
	        else if (readCookie(PORTAL_CRED) != 0) {
	          login.style.visibility = "hidden"; 
	          login.style.display = "none";
	          document.forms[0].submit();
	        }
	        else {
	          login.style.visibility = "visible"; 
	          //login.style.display = "inline";
	          retriveUserInfo();
	        }
	      }  
        }
        function retriveUserInfo() {
          var userName = Get_Cookie(encode64('j_username'));
          if (userName != null) 
            if (userName != 'null') 
              if (userName != 'undefined')
                document.forms[0].j_username.value = decode64(userName);

          document.forms[0].j_username.focus();
        }

        function onSubmit() {
			if (validate(document.forms[0].j_username) && validatePassword(document.forms[0].j_password))
			{
			  setLoginCookie("MC_CRED", trimString(document.forms[0].j_username.value)+":"+trimString(document.forms[0].j_password.value));
			  
			  document.forms[0].j_username.value = trimString(document.forms[0].j_username.value); 
			  document.forms[0].j_password.value = trimString(document.forms[0].j_password.value);
			  setCookie(encode64('j_username'), encode64(document.forms[0].j_username.value), 10);
			  document.getElementById('tblLogin').style.visibility = "hidden";
			  document.getElementById('tblLogin').style.display = "none";

			  document.forms[0].submit();
			}
		  return false;
        }

       function trimString(str) {
         // Checking for spaces at the beginning of the string
         var chr = str.substring(0, 1);
         while (chr == " ") {
            str = str.substring(1, str.length);
            chr = str.substring(0, 1);
         }

         // Checking for spaces at the end of the string
         chr = str.substring(str.length - 1, str.length);
         while (chr == " ") {
            str = str.substring(0, str.length - 1);
            chr = str.substring(str.length - 1, str.length);
         }
         return str;
       }

        function setCookie(cookieName,cookieValue,nDays) {
          var today = new Date();
          var expire = new Date();
          if (nDays==null || nDays==0) nDays=1;
          expire.setTime(today.getTime() + 3600000*24*nDays);
          document.cookie = cookieName + "=" + escape(cookieValue) + ";expires="+expire.toGMTString();
        }

         function setLoginCookie(cookieName,cookieValue) {
            var expires = false;
            var path = false;
            var domain = false;
            var secure = false;
          	var curCookie = cookieName + "=" + encode64(cookieValue) + 
				((expires) ? "; expires=" + expires.toGMTString() : "") + 
				";path=/" +
				((domain) ? "; domain=" + domain : "") + 
				((secure) ? "; secure" : ""); 
				
          document.cookie = curCookie;
        }


        // this function gets the cookie, if it exists
        function Get_Cookie( name ) {
          var start = document.cookie.indexOf( name + "=" );
          var len = start + name.length + 1;
          if (!start) {
            if(name != document.cookie.substring( 0, name.length ) )
            {
              return null;
            }
          }  
          if ( start == -1 ) return null;
          var end = document.cookie.indexOf( ";", len );
          if ( end == -1 ) end = document.cookie.length;
          return unescape( document.cookie.substring( len, end ) );
        }

        function readCookie(PORTAL_CRED)  {
          if(PORTAL_CRED != '') {
            var Portal_Cred_Cookie = PORTAL_CRED;
            var firstDecode = decode64(Portal_Cred_Cookie);
            var secondSplit = firstDecode.split(" ");
            var decodedCookie = decode64(secondSplit[1]);
            var splitusernamepassword = decodedCookie.split(":");
            var portal_userName = splitusernamepassword[0];
            var portal_password =  splitusernamepassword[1];
            document.forms[0].j_password.value = portal_password;
            document.forms[0].j_username.value = portal_userName;
            setCookie(encode64('j_username'), encode64(document.forms[0].j_username.value), 10);
            return portal_userName + ":" + portal_password;
          }
          return 0;
        }

        function readLoginCookie(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) {
					var cookieVal = c.substring(nameEQ.length,c.length);
					 var firstDecode = decode64(cookieVal);
				            var splitusernamepassword = firstDecode.split(":");
		            var portal_userName = splitusernamepassword[0];
		            var portal_password =  splitusernamepassword[1];
		           document.forms[0].j_password.value = portal_password;
		           document.forms[0].j_username.value = portal_userName;
				 return c.substring(nameEQ.length,c.length);
				}
			}
			return 0;
		}
        
       
        var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        function encode64(input) {
          var output = "";
          var chr1, chr2, chr3;
          var enc1, enc2, enc3, enc4;
          var i = 0;
          do {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            if (isNaN(chr2)) {
               enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
               enc4 = 64;
            }
            output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + 
            keyStr.charAt(enc3) + keyStr.charAt(enc4);
         } while (i < input.length);
         return output;
      }

      function decode64(input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
      //remove all characters that are not A-Z, a-z, 0-9, +, /, or =
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        do {
          enc1 = keyStr.indexOf(input.charAt(i++));
          enc2 = keyStr.indexOf(input.charAt(i++));
          enc3 = keyStr.indexOf(input.charAt(i++));
          enc4 = 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);
          }
        } while (i < input.length);
        return output;
      } 
      
      function forgotPassword() {
        if (document.forms[0].j_username.value == null || trimString(document.forms[0].j_username.value).length == 0) {
          alert("Please enter a valid Username.");
        }
        else if (validate(document.forms[0].j_username)){
          var userName = encode64(document.forms[0].j_username.value);
          var urlRedirect = location.protocol + "//" + location.hostname +
          ":" + location.port + "/NATApp/servlet/UserRedirectionServlet?action=forgotpassword&id=" +
	       userName;
	      document.forms[0].returnURL.value = location.href.replace('j_security_check', '');
          document.forms[0].action = urlRedirect;
          document.forms[0].submit();
        }
        return false;
      }

      function changePassword() {
        if (document.forms[0].j_username.value == null || trimString(document.forms[0].j_username.value).length == 0) {
          alert("Please enter a valid Username.");
        }
        else if (validate(document.forms[0].j_username)){
          var userName = encode64(document.forms[0].j_username.value);
          var urlRedirect = location.protocol + "//" + location.hostname +
          ":" + location.port + "/NATApp/servlet/UserRedirectionServlet?action=changepassword&id=" +
          userName;
		  document.forms[0].returnURL.value = location.href.replace('j_security_check', '');	
          document.forms[0].action = urlRedirect;
          document.forms[0].submit();
        }
        
        return false;
      }
      
      function validatePassword(object) {
  	  	var success = true;
  	  	if (object.value == null || trimString(object.value).length == 0) {
  	  	  success = false; 	
          alert("Please enter a valid password.");
          object.focus();
        }
        return success;
  	  }	
  
	  function validate(object) {
        var success     = true;
        var invalidChar = new RegExp('[!#{<>}\/%]','g');
        if (object.value != '' && object.value.match(invalidChar)) {
          success = false;  
          alert("Only Alphanumeric characters allowed");
          object.focus();
        }
    
        return success;
      }