var g_urlParameters = new Array();
var g_tokenIdx = "TOKENIDX";
var g_nullString = "NULL";
var g_cloneName = "CLONE";
var g_warnName = "WARN";
var g_lastToken = "LASTTOKEN";
var g_securityToken = ".SECURITYTOKEN";
var g_controlID = ".CONTROLID";
var g_guestStatus = ".GUEST";
var g_cookieCheck = "WA30_checkCookie";
var g_warning = "You are now logged out of WebAdvisor.\n\nTo insure the security of data, you should now close your browser window.  To close your browser now, click OK";
var g_displayWindowMessage = "The maximum number of cookie values has been reached.\n\nIf other windows are currently open or were not closed using the 'CLOSE WINDOW' button, then you must close all current browser windows and re-login to avoid unpredictable behavior.";
var g_setWindowMessage = g_displayWindowMessage + "\n\nThis window will now be closed.";

//Added by Rik Jones 3/21/2006
var g_cookieName = "changingPassword";

//Added by Rik Jones 5/18/2006
var g_course    =   "course";
var g_con    =   "CONSTITUENCY";
var g_type    =   "type";
var g_pid    =   "pid";
//var g_saveCourceCookie = "/eConnect/SaveCourse";
var g_saveCourceCookie = "SaveCourse";

var g_clicks = 0;
var g_busyMessage = "Your request is currently processing. Please refresh the page to regain control.";

   
//Added by Rik 10/19/2006 to ensure this is run even though it probelm wont runn here.
//This replicates code later on in displayFormHTML(focusField)

   if( document.forms != null && 
       document.forms[0] != null && 
       document.forms[0].elements != null &&
       document.forms[0].elements["JS_ENABLED"] != null) {
        document.forms[0].elements["JS_ENABLED"].value = "Y";
   }

function initWindow() { 
   var cookieValue = "cookieCheck";
   setCookie(g_cookieCheck, cookieValue);

   /* Make sure we can read the cookie back again */
   var cookie = getCookie(g_cookieCheck);

   if (cookie == cookieValue ) {
      deleteCookie(g_cookieCheck);
   } else {
      alert("Cookies are not enabled");
      window.location.replace('./html/cookies.html');
   }
   
	// WA315 - Help does not want this anymore (this function is used by help servlet)
	//var width = 350;
	//var height = screen.height - 30;
	//window.resizeTo(width, height);
	//window.moveTo(screen.width - width, 0);
	window.focus();
}

function checkClicks() {
   if( g_clicks > 0 ) {
   	initClickPrevention();
   	window.status = g_busyMessage;
   } else {
   	g_clicks+=1;
   }
}

function clickHandler (evt) {
  if (document.layers)
    return false;
  else if (evt.stopPropagation) {
    evt.stopPropagation();
    evt.preventDefault();
  }
  else if (window.event)
    return false;
}
function initClickPrevention () {
  if (document.layers) {
    window.captureEvents(Event.CLICK);
    window.onclick = clickHandler;
  }
  else if (document.all && !document.getElementById)
    document.onclick = clickHandler;
  else if (document.all)
    document.attachEvent('onclick', clickHandler);
  else if (document.addEventListener)
    document.addEventListener('click', clickHandler, true);
}

function setWindowHTML(returnURL, tokenIndex) {
   //Added by Rik 3/28/2007
   //Used to check the validity of the TOKENINDEX for URL injection
   if((tokenIndex != '') && (tokenIndex != g_nullString) && (!(isValidNumber(tokenIndex)))){
       clearCookies(tokenIndex);
       tokenIndex  = g_nullString;
   }
    //End Added By Rik 3/28/2007
   //alert("In setWindowHTML(returnURL, tokenIndex)\n" + returnURL + "\n" + tokenIndex); //debug code
   var pwdCookie = getCookie(g_cookieName);
   var cookieValue = "cookieCheck";
   setCookie(g_cookieCheck, cookieValue);

   /* Make sure we can read the cookie back again */
   var cookie = getCookie(g_cookieCheck);
   if (cookie == cookieValue ) {
      if( cookieLimitCheck(true, tokenIndex) ) {
          deleteCookie(g_cookieCheck);
  
        readURLParameters();
  
        var _currentURL = window.location.href;
        window.name = tokenIndex;
          //added By Rik 5/18/2006
        var _saveURL = window.location.href;
        //End Added By Rik

        if( returnURL != "" ) {
           window.location.replace(returnURL);
        } else {
           if( containsParameter(g_cloneName) ) {
              removeParameter(g_cloneName);
              //setURLParameter('CLONE_PROCESS','Y');
           }
           
           if( containsParameter("FORCEIDX") ) {
           	  removeParameter("FORCEIDX");
           }
  
           setURLParameter( g_tokenIdx, window.name );
           _currentURL = getBaseURI(_currentURL) + '?' + getURLParameters();
           
           if(navigator.userAgent.indexOf("Safari") != -1){
            //alert("Safari Browser has dificulty in setWindowHTML()");//debug code
            //The code below breaks misabley in Safari. So it is excluded.
           }else{
            //added By Rik Jones 5/18/2006
            //to allow trasfer of course properties to Search for Classes etc.
           if (_saveURL.indexOf(g_course) < 0){
                //Not there, need to clean up
                //alert("Rik Working\nDid Not FIND course in URL"); //debug code
                //setCookie(g_saveCourceCookie, "");
                //deleteCookie(g_saveCourceCookie); //clear the cookie
           }else{
                //Found course information
                //Save it out
                //alert("Rik Working\nFound course in URL\nBefore\n" + getURLParameters()); //debug code
                
                //clear out parameters we don't want saved
                if( containsParameter(g_con) ) {
                      removeParameter(g_con);
                  }
                if( containsParameter(g_type) ) {
                      removeParameter(g_type);
                  }  
                if( containsParameter(g_pid) ) {
                      removeParameter(g_pid);
                  }  
                if( containsParameter(g_tokenIdx) ) {
                      removeParameter(g_tokenIdx);
                  }   
                //alert("Rik Working\nFound course in URL\nAfter\n" + getURLParameters()); //debug code
                
            setCookie(g_saveCourceCookie, getURLParameters());
          
           
           }
            //End Rik Added     
            }
           
           window.location.replace(_currentURL);
        }
      }
   } else {
      alert("Cookies are not enabled");
      window.location.replace('./html/cookies.html');
   }

}


function getWindowHTML() {
   readURLParameters();

   var _currentURL = window.location.href;
   var _tokenValue = ( window.name.length < 1 ) ? g_nullString : window.name;
   //Added by Rik 3/28/2007
   //Used to check the validity of the TOKENINDEX for URL injection
   if((_tokenValue != '') && (_tokenValue != g_nullString) && (!(isValidNumber(_tokenValue)))){
       clearCookies(_tokenValue);
       _tokenValue  = g_nullString;
   }
    //added By Rik 5/18/2006
    var _saveURL = window.location.href;
    
    
   if( _currentURL.indexOf(g_tokenIdx) < 0 ) {
      setURLParameter( g_tokenIdx, _tokenValue );
      _currentURL = getBaseURI(_currentURL) + '?' + getURLParameters();
   }

     //added By Rik Jones 5/18/2006
    //to allow trasfer of course properties to Search for Classes etc.
   if (_saveURL.indexOf(g_course) < 0){
        //Not there, need to clean up
        //alert("Rik Working\nDid Not FIND course in URL"); //debug code
        //setCookie(g_saveCourceCookie, "");
        //deleteCookie(g_saveCourceCookie); //clear the cookie
   }else{
        //Found course information
        //Save it out
        //alert("Rik Working\nFound course in URL\nBefore\n" + getURLParameters()); //debug code
        
        //clear out parameters we don't want saved
        if( containsParameter(g_con) ) {
              removeParameter(g_con);
          }
        if( containsParameter(g_type) ) {
              removeParameter(g_type);
          }  
        if( containsParameter(g_pid) ) {
              removeParameter(g_pid);
          }  
        if( containsParameter(g_tokenIdx) ) {
              removeParameter(g_tokenIdx);
          }   
        //alert("Rik Working\nFound course in URL\nAfter\n" + getURLParameters()); //debug code
        
        setCookie(g_saveCourceCookie, getURLParameters());
         
           
   }
    //End Rik Added   
    
   window.location.replace(_currentURL);
}


function displayFormHTML(focusField) {
   // Begin WEB_SCR_2947
   window.focus();
   // End WEB_SCR_2947
   
   readURLParameters();

   if( document.forms != null ) {
   	   for( i = 0; i < document.forms.length; i++ ) {
   	      if( document.forms[i] != null ) {
	         if( document.forms[i].elements != null && document.forms[i].elements["JS_ENABLED"] != null ) {
       			document.forms[i].elements["JS_ENABLED"].value = "Y";
       		 }
       	  }
       }
   }
   
   var _currentURL = window.location.href;
   var _tokenValue;
   cookieLimitCheck(false,null);
   if (window.name != getURLParameter(g_tokenIdx) 
   && getURLParameter("PDF_REPORT") == null
   && getURLParameter("username") == null ) {
      if (window.name == '' ) {

         if( containsParameter(g_cloneName) ) {
            removeParameter(g_cloneName);
         } else {
            setURLParameter(g_tokenIdx,g_nullString);
         }

         _currentURL = getBaseURI(_currentURL) + '?' + getURLParameters();

         if( containsParameter(g_cloneName) )
            window.name = g_tokenIdx;
          else
            window.location.replace( _currentURL );

         return;
      } else if( _currentURL.indexOf('?') > 0 ) {
           window.open(_currentURL, getURLParameter(g_tokenIdx) );
      }
   } else {
       	if( containsParameter(g_warnName) ) {
    		//Edited By Rik Jones 2/20/2006 to take out pop-up window and clear session cookies
    		/*if( confirm(g_warning) ) {
    		    forceCloseWindow();
    		}*/
    		var theTokenvalue = getURLParameter(g_tokenIdx); //Get the value of the token from the URL parameter
    	    clearCookies(theTokenvalue); //clear all sesion cookies
    	    setCookie(g_lastToken, "00000000000");
    	    deleteCookie(g_lastToken); //clear the token cookie
    	    
    	    //setCookie(g_cookieName, "false");
    	    //setCookie(g_cookieName, "false",null, "/");
    	    //setCookie(g_cookieName, "false",null, "/eConnect/");
    	    //deleteCookie(g_cookieName); //clear the changing Password cookie
    	    //deleteCookie(g_cookieName, "/"); //clear the changing Password cookie
    	    //deleteCookie(g_cookieName, "/eConnect/"); //clear the changing Password cookie
    	    //End edit by Rik Jones 2/20/2006
    	}
    	
    	//alert("Rik Working\n" + PID );
    	
    	/*
    	    Modified by Rik on 8/22/2006
    	    Made to work only for login screen
    	
       
         if( focusField && PID && PID = "UT-LGRQ" && document.forms[0] != null && document.forms[0].elements[0] != null
                 && !document.forms[0].elements[0].disabled && document.forms[0].elements[0].type != "hidden"
                 && document.forms[0].elements[0].type != "submit" )
                 document.forms[0].elements[0].focus();
          
          */
          if (PID == "UT-LGRQ" && document.forms[0] != null && document.forms[0].elements[0] != null
                 && !document.forms[0].elements[0].disabled && document.forms[0].elements[0].type != "hidden"
                 && document.forms[0].elements[0].type != "submit" ){
                    document.forms[0].elements[0].focus();
                    document.forms[0].elements[0].select();
                 }  
                       
   }
}


function cookieLimitCheck(closeWindow,tokenIndex) {
         var bites = document.cookie.split("; "); // break cookie into array of bites
        //alert('Rik Working \nIn cookieLimitCheck\nbites.length = '+ bites.length + "\ncloseWindow = " + closeWindow);//Debug code
         if( bites.length > 36 ) { //Change by Rik on 6/16/2006 from 18 to 36              
                if( tokenIndex != null ) {
                	deleteCookie( tokenIndex );
                }

                if( closeWindow ) {
                    alert(g_setWindowMessage);
                    self.close();
                } else {
                    alert(g_displayWindowMessage);
                }
                return false;
         } else {
           return true;
         }
}

function clearCookies(tokenIndex) {
	    //Edited By Rik Jones 2/20/2006 to also null session cookie values
	    //Edited by Rik Jones 4/9/2008 to also null form cookies
         var bites = document.cookie.split("; "); // break cookie into array of bites
         var newCookie;
        for (var i=0; i < bites.length; i++) {
                var nextbite = bites[i].split("="); // break into name and value
                if( (nextbite[0].indexOf(tokenIndex) > -1 ) || 
                    (nextbite[0].indexOf(g_cookieName) > -1 ) ||
                     (nextbite[0].indexOf(g_guestStatus) > -1 ) ||
                     (nextbite[0].indexOf(g_controlID) > -1 ) ||
                     (nextbite[0].indexOf(g_securityToken) > -1 ) ||
                     (nextbite[0].indexOf(g_lastToken) > -1 ) ||
                     (nextbite[0].indexOf(g_saveCourceCookie) > -1 ) ||
                     (nextbite[0].indexOf("eConnect") > -1 ) ||
                     (nextbite[0].indexOf("SandR") > -1 ) ||
                     (nextbite[0].indexOf("course") > -1 ) ||
                     (nextbite[0].indexOf("expressReg") > -1 ) ||
                     (nextbite[0].indexOf("s4cc") > -1 )
                   )
                      {
                    setCookie(nextbite[0], "Y");
                    deleteCookie(nextbite[0]);
                }
        }
}

function forceCloseWindow() {
		 removeParameter(g_warnName);
		 _currentURL = getBaseURI(window.location.href) + '?' + getURLParameters();
         popup = window.open(_currentURL, getURLParameter(g_tokenIdx) );
         popup.close();
}

function getBaseURI(url) {
   if( url != null ) {
      if( url.indexOf("?") > -1 ) {
         var _tempArray = url.split("?");
         return _tempArray[0];
      }
   }

   return url;
}


function buildURLParameter(name,value,prefix) {
   if( prefix == null )
      prefix = '&';

   str = prefix+name+'='+value;

   return str;
}


function readURLParameters() {
   _url = window.location.href;

   if( _url.indexOf("?") > -1 ) {
      _urlArray = _url.split("?");
      if( _url.indexOf('&') > -1 ) {
         _parameterArray = _urlArray[1].split('&');

         for( i = 0; i < _parameterArray.length; i++ ) {
            var _internalArray = _parameterArray[i].split("=");
            setURLParameter(_internalArray[0], _internalArray[1]);
         }
      }
   }
}


function getURLParameter(name) {
   return g_urlParameters[name];
}


function setURLParameter(name,value) {
   g_urlParameters[name] = value;
}


function getURLParameters() {
	var _urlString = new String();
	var counter = 0;

	for ( var i in g_urlParameters) {
		var _delim = '&';

		/* Changes for AN 36081.81 */
		if (counter < 1)
			_delim = '';

		if (g_urlParameters[i] != null)
			_urlString = _urlString
					+ buildURLParameter(i, g_urlParameters[i], _delim);

		counter++;
	}

	return _urlString;
}


function containsParameter(name) {
   url = getURLParameters();

   if( url.indexOf(name+"=") > -1 )
      return true;
   else
      return false;
}


function removeParameter(name) {
   setURLParameter(name,null);
}


/*
   name - name of the cookie
   value - value of the cookie
   [expires] - expiration date of the cookie
     (defaults to end of current session)
   [path] - path for which the cookie is valid
     (defaults to path of calling document)
   [domain] - domain for which the cookie is valid
     (defaults to domain of calling document)
   [secure] - Boolean value indicating if the cookie transmission requires
     a secure transmission
   * an argument defaults when it is assigned null as a placeholder
   * a null placeholder is not required for trailing omitted arguments
*/
function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}
//clone with different name for leagacy code
function SetCookie(name, value, expires, path, domain, secure) {
    setCookie(name, value, expires, path, domain, secure);
}

/*
  name - name of the desired cookie
  return string containing value of specified cookie or null
  if cookie does not exist
*/
function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}
//clone with different name for leagacy code
function GetCookie(name) {
    return getCookie(name);
}

/*
   name - name of the cookie
   [path] - path of the cookie (must be same as path used to create cookie)
   [domain] - domain of the cookie (must be same as domain used to
     create cookie)
   path and domain default if assigned null or omitted if no explicit
     argument proceeds
*/
function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ";expires=" + ( new Date( ( new Date() ).getTime() + ( 1000 * -10 ) ) ).toGMTString();
  }
}
//clone with different name for leagacy code
function DeleteCookie(name, path, domain) {
    deleteCookie(name, path, domain);
}

function disableAndSubmit(theButton)
{
 disableButton(theButton);
 //theButton.form.submit();
}

function submitAndDisable(theButton)
{
 //document.forms[0].elements["SUBMIT_OPTIONS"].value = "CLOSE_WINDOW";
 //theButton.form.submit();
 disableButton(theButton);
}

function disableButton(theButton)
{
 var button;
     if( document.forms != null ) {
   	   for( i = 0; i < document.forms.length; i++ ) {
   	      if( document.forms[i] != null ) {
	         if( document.forms[i].elements != null && 
	         	 document.forms[i].elements[theButton] != null ) {
       			button = document.forms[i].elements[theButton];
       		 }
       	  }
       }
   }
   
 if( button != null && button != undefined ) {
	button.value="Please Wait...";
	button.disabled = true; 
	button.className = "buttonPress";
 }
}

function keyDown(event,__button) {
    var nn=(document.layers)?true:false;
    var ie=(document.all)?true:false;
	var evt=(event)?event:(window.event)?window.event:null;
	if(evt){
		if(__button) {
			var key=(evt.charCode)?evt.charCode:
				((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
		if(key=="13") {
		    if( document.forms != null ) {
		   	   for( i = 0; i < document.forms.length; i++ ) {
		   	      if( document.forms[i] != null ) {
			         if( document.forms[i].elements != null ) {
						for( j = 0; j < document.forms[i].elements.length ; j++ ) {
							if( document.forms[i].elements[j].name == __button ) {
								document.forms[i].elements[j].focus();
								return;
							}
						}
		       		 }
		       	  }
		       }
		   }
		}
		}
	}
}

//Added by Rik 3/28/2007
//Used to check the validity of the TOKENINDEX for injection
function isValidNumber(inputVal){
	//alert('In isValidNumber(inputVal)\n' + inputVal);//debug
	inputStr = inputVal.toString();
	for (var i = 0; i < inputStr.length; i++) {
		var oneChar = inputStr.charAt(i)
		if (oneChar < "0" || oneChar > "9") {
			return false
		}
	}
	return true;
}
// - support for payment processing
function navigateToPaymentProcessor(URL, RURL) {
    var finalURL = URL + '&RU=' + escape(RURL);
    window.location.href = finalURL;
}


//End Added By Rik 3/28/2007

