// This file is copied from the Employee Desktop application
// It's principal use in DCMS is to track opening of popup windows, so that the
// logout function can close them.

// common.js
// Please add comments for all new methods
//these three functions are not used, but are here in case we need them...
function trapEnterKey(theKey) {
   var whichCode;
   whichCode = (window.Event) ? theKey.which : theKey.keyCode;
   if ( whichCode == "13" ) {
     submitSearchForm(document.agentSearchForm);
   } else whichCode = null;
}

function focusSearchField() {
   if (document.agentSearchForm) {
        document.agentSearchForm.queryString.focus();
   }
}

// submit form
function submitSearchForm(theForm)
{
  if (theForm) {
  	if (theForm.queryString) {
//      if (theForm.queryString.value == "") {
  //       alert('Empty search field. Please re-enter.');
//	 theForm.action=window.location;
  //     } else {
  		theForm.action=theForm.action+theForm.queryString.value;
  //     }
  	}
//document.getElementsByTagName('goButton')[0].href
  	theForm.submit();
  } else {
	alert('Invalid search entry. Please try again.');
        return false;
  }
}
/*
function MM_findObj(n, d) { //v4.01 
	var p,i,x;  
  	if(!d) d=document; 
  	if((p=n.indexOf("?")) > 0 && parent.frames.length) { 
	    d=parent.frames[n.substring(p+1)].document; 
	    n=n.substring(0,p);
	} 
	if(!(x=d[n])&&d.all) x=d.all[n]; 
	for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n]; 
	for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); 
  	if(!x && d.getElementById) x=d.getElementById(n); 
	return x; 
} 

function MM_showHideLayers() { //v6.0 
  var i,p,v,obj,args=MM_showHideLayers.arguments; 
  for (i=0; i<(args.length-2); i+=3) {
  	if ((obj=MM_findObj(args[i]))!=null) { 
  		v=args[i+2]; 
    	if (obj.style) { 
    		obj=obj.style; 
    		v=(v=='show')?'visible':(v=='hide')?'hidden':v; 
    	} 
    	obj.visibility=v; 
    } 
  }  
} 

// this function calls MM_showHideLayers() so that it can be neatly called by a timeOut function in the pagebar 
function hoverOver() { 
MM_showHideLayers('desktopDirectory','','show'); 
} 
*/
// these are added here, in the desktop it is in
// the html for the page
	var cookieName = "EUDDesktopCookie"  
	var childWindowOptions = 'resizable=yes,scrollbars=yes,menubar=yes,toolbar=yes,directories=yes,titlebar=yes,alwaysRaised=yes,location=yes,status=yes,height=480,width=640';
	var openedWins = new Array();
	var openedWinsTitle = new Array();
	var cookieName = 'EUDDesktopCookie';
	var delimiter = '#~#';
	var timerID;
	var fficGlobalLogoutURL = '/wps/myportal/!ut/p/kcxml/04_Sj9SPykssy0xPLMnMz0vM0Y_QjzKLN4j3NQHJgFjGpvqRqCKOcAFfj_zcVP0gfW_9AP2C3NCIckdHRQBDU1Uq/delta/base64xml/L0lKSklKSWchL0lCakFBQ3lBQkVRaUlBISEvNElENnhCX1dFTkRDLzEzLzEyL2xv';
//dy added this
	var logoutURL = fficGlobalLogoutURL
	var startTimer = false;  //the boolean variable 
	var countDown = null;     //the name of the timer itself 

function startCountDown() { 
        startTimer = true; 
        countDown = setTimeout('showDesktopDirectory()', 500); 
} 
function stopCountDown() {    //To turn the timeout off 
    if (startTimer) { 
        clearTimeout(countDown); 
        startTimer = false; 
        } 
}     
//reset the javascript timer on the parent window, we do not use this now
function OnClickHandler(evt) {
        // because IE and Netspace/FireFox browser have different DOM Event object
        // this line below will ensure the correct event object is used
    //        evt = (evt) ? evt : ((window.event) ? window.event : "");    
        
        // if(evt.srcElement.tagName=='SPAN') {        
                // resetTimer();
        // }
         // if(evt.srcElement.tagName=='A'){
        //        var url= evt.srcElement.href;
        //        //alert(url.indexOf('#Logout'));
        //        if(url!=null && url.indexOf('#Logout')==-1){
        //                resetTimer();
        //        }
//        }
}


// Call this on the body onLoad tag if session timeout is needed.
function setTimer(){ 
  //this will call the method update_timer method passed 25 mins of user loading the page.
  // The time is in milliseconds
    if(flag==true){
      fficEUDTimerID = setTimeout('update_timer()',1500000);
    }
    flag=false;
}


// Called by setTimer to open a window. If we ever implement session timeout, and we want the
// popup window to close on logout, change the window.open to use addWindow instead.
function update_timer(){ 
        window.open(sessionTimeoutURL,'NewWindow','resizable=no,scrollbars=no,menubar=no,toolbar=no,status=no,width=400,height=400,screenX=200,screenY=200,top=200,left=200');
}

// This gets placed on the logout call in ToolBarInclude.jsp.  
// It is responsible for closing the child windows 
function eudLogout(logoutURL){
        var name=confirm("Are you certain you want to close **ALL** web pages\nopened by the Employee Desktop?")
        if (name==true) {
                closeDependentWindows(); 
                window.location.href=logoutURL;
        }
}
function eudAgentLogout(){
        var name=confirm("Are you certain you want to close **ALL** web pages\nopened by the Fireman's Fund Agent Desktop?")
        if (name==true) {
            closeDependentWindows(); 
          	var env=getEnvironment()
			var wpsURL = ""
			if (env=="dev") {
				wpsURL = "/wps/myportal/agent/kcxml/04_Sj9SPykssy0xPLMnMz0vM0Y_QjzKLN4038vMCSUGYnvqRGGIeGGLOSEJB-t76vh75uan6AfoFuaGhEeWOigCvKd2q/delta/base64xml/L0lKSklKSWchL0lCakFBQ3lBQkVRaUlBISEvNElENnhCX1dFTkRDLzEvMi9sbw!!"
			} else if (env=="test") {
				wpsURL = "/wps/myportal/agent/kcxml/04_Sj9SPykssy0xPLMnMz0vM0Y_QjzKLt4w3dnQCSUGYjvqRGGKWGGLOHgihIH1vfV-P_NxU_QD9gtzQ0IhyR0UAl9JX7w!!/delta/base64xml/L0lKSklKSWchL0lCakFBQ3lBQkVRaUlBISEvNElENnhCX1dFTkRDLzEvMjgwL2xv"
			} else if (env == "uat") {
				wpsURL = "/wps/myportal/agent/kcxml/04_Sj9SPykssy0xPLMnMz0vM0Y_QjzKLd4w3MXYCSUGYjvqRGGKWGGJGHkjqgvS99X098nNT9QP0C3JDQyPKHRUBMr0RRQ!!/delta/base64xml/L0lKSklKSWchL0lCakFBQ3lBQkVRaUlBISEvNElENnhCX1dFTkRDLzEvMTAwNy9sbw!!"
			} else if (env == "cert") {
				wpsURL = "/wps/myportal/agent/kcxml/04_Sj9SPykssy0xPLMnMz0vM0Y_QjzKLd443CTAHSUGYZvqRGGKmmGJmLgixIH1vfV-P_NxU_QD9gtzQ0IhyR0UAEF-h3g!!/delta/base64xml/L0lKSklKSWchL0lCakFBQ3lBQkVRaUlBISEvNElENnhCX1dFTkRDLzEvNzk2L2xv"
			} else {
				wpsURL = "/wps/myportal/agent/kcxml/04_Sj9SPykssy0xPLMnMz0vM0Y_QjzKLd4o3DbMESUGYFvqRGGLmmGLO_gixIH1vfV-P_NxU_QD9gtzQ0IhyR0UAj--FOQ!!/delta/base64xml/L0lKSklKSWchL0lCakFBQ3lBQkVRaUlBISEvNElENnhCX1dFTkRDLzEvMjk4MjM3L2xv"
			}

	        window.location.href=wpsURL;
       }
}

// This is called from within sessionTimeout.jsp, but it is currently using window.opener, we should change
// this if we ever need to use that JSP
function eudTimerLogout(){
        closeDependentWindows();         
        window.location.href=fficGlobalLogoutURL;
}

// Called by onClickHandler
function resetTimer(){
        clearTimeout(fficEUDTimerID); 
        flag=true;
        setTimer();
        var tamWindow = window.open(sessionMaintainURL, 'TAMPortalHome','resizable=no,scrollbars=no,menubar=no,toolbar=no,status=no,width=5,height=5,screenX=-100,screenY=-100,top=2000,left=2000');
 
}

// This is called by the continue button from within sessionTimeout.jsp.  It in turn calls setTimer
function childResetTimer(){
        clearTimeout(fficEUDTimerID); 
        flag=true;
        setTimer();        
}


// Shortcut function to addWindow method below.  Used by TopTools/Notes
function jump(url){
        addWindow(url,'', null);
}
/* These two functions moved to DCMSLib.js
// This method is used when we need to have a handle on closing child windows on logout. It
// takes in the same parameters as window.open. We need to use this for opening all popup windows
// that need window management
function addWindow(url, title, windowParams) {
//alert("in addWindow")
        var aWindow = null;
        var invalids = "!@#$%^&*()-~,'<.>/?;:\|";         
 
        for(i=0; i < title.length; i++) {
                var tempVal = title.charAt(i);                 
 
                for(k=0; k < invalids.length; k++) {
                        var tempInvalidVal = invalids.charAt(k);                         
                        if(tempVal == tempInvalidVal || tempVal == " ") {                                 
 
 
                                title = title.replace(title.charAt(i),"_");                        
                        }                         
                }                         
        } 
 

        if(windowParams == null) {
 //       alert("in addWindow 3")
                aWindow = window.open(url, title,'width=640,height=480,directories=no,location=yes,menubar=yes,toolbar=yes,titlebar=yes,resizable=yes,scrollbars=yes,alwaysRaised=yes,status=yes');
                aWindow.focus();
                openedWinsTitle[openedWinsTitle.length] = title; 
                openedWins[openedWins.length] = aWindow; 
        }
        else {
                aWindow = window.open(url, title, windowParams);
                aWindow.focus();
                openedWinsTitle[openedWinsTitle.length] = title;                 
                openedWins[openedWins.length] = aWindow;                                 
        }    
        // different from EUD version
        persistWindows()
        return aWindow     
} 
 
// Called on the body onUnload tag in order to keep track of the windows opened with addWindow
// dy 20070130 This is invoked always from addWindow. The onUnLoad event is not predictable enough.
function persistWindows() {
//alert("start persistWindows")
        if (openedWinsTitle.length > 0) {                     
                    // get existing cookie value 
                    var cookieGoodies = getCookie(cookieName);     
                    // create additional cookie values 
                    var moreCookieText = ''; 
                    if (openedWinsTitle) { 
                        for(i=0; i<openedWinsTitle.length; i++){ 
                                var winName = openedWinsTitle[i]; 
                                var winHnd = openedWins[i]; 
                                if (winHnd && winHnd.open && !winHnd.closed) {         
                                        moreCookieText += openedWinsTitle[i] + delimiter; 
                                    } 
                        } 
                    } 
                    // create the new cookie 
                createCookie(cookieName, cookieGoodies + moreCookieText); 
        } 
//alert("end persistWindows")        
} 
 */

function getCookie(label) {
        var labelLen = label.length;
        var cLen = document.cookie.length;
        var i = 0;
        var cEnd;
        while(i < cLen) {
                var j = i + labelLen
                if(document.cookie.substring(i,j) == label) {
                        cEnd = document.cookie.indexOf(";",j);
                        cEnd = ((cEnd==-1) ? document.cookie.length : cEnd);
                        cVal = unescape(document.cookie.substring(j+1,cEnd));
                        cVal = ((cVal==';') ? '' : cVal);
                        return cVal;
                }
                i++;
        }
        return "";
}
 
// Global Variables for the InitializeTimer, StartTheTimer and StopTheClock methods
var fficEUDTimerID = null;
var fficEUDTimerRunning = false;
var fficEUDsecs = 0;

// Initialize time timer, put this in the onload method
function InitializeTimer()
{
    // Get the URL
    var URL = location.pathname;
    var strURL = URL.toString();
    var strURLUpper = strURL.toUpperCase();

    // alert(strURLUpper);        
    // alert('Logout URL' + fficGlobalLogoutURL);

    // Set the length of the timer, in seconds    
    // If the user is a contractor, set the timer to be 30 mins
    if (strURLUpper.indexOf('CONTRACTOR') != -1) {
            fficEUDsecs = 1800;  // 30 mins = 1800
                // alert(fficEUDsecs);  
    }
    else {
            // otherwise, set the timer to be 6 hrs
            fficEUDsecs = 21600; // 6 hours = 21600
                // alert(fficEUDsecs);  
    }

          // Reset the timer
    StopTheClock();
    StartTheTimer();
}

// Stop the Clock
function StopTheClock()
{
    if(fficEUDTimerRunning) {
        clearTimeout(fficEUDTimerID);
    }
    fficEUDTimerRunning = false;
}

// Start the Timer based on the secs in the Init method
function StartTheTimer()
{  
         var delay = 1000;  // in milliseconds
         
         // alert(fficEUDsecs);
         
    if (fficEUDsecs==0)
    {
        StopTheClock()
        // Here's where you put something useful that's
        // supposed to happen after the allotted time.
        // In our example, we want to redirect (right now it's yahoo.com)
        window.location.href=fficGlobalLogoutURL;
    }
    else
    {
        // Uncomment this if you want to see the value in the status bar
                  //self.status = secs
        fficEUDsecs = fficEUDsecs - 1;
        fficEUDTimerRunning = true;
        fficEUDTimerID = self.setTimeout("StartTheTimer()", delay);
    }
} 
 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
// FUNCTION: closeDependentWindows 
// 
// Close all child/dependent windows 
//  
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
function closeDependentWindows() { 
        // Close all windows in the current array. 
//        for(i=0;i < openedWinsTitle.length;i++){ 
//                closeWindow(openedWinsTitle[i]); 
//        } 
        openedWinsTitle = null; 
        openedWins = null;     
        // Close all windows in the cookie. 
         var cookieGoodies = getCookie(cookieName); 
            if (cookieGoodies.length > 0) { 
                var windowNames = cookieGoodies.split(delimiter); 
                var windowHnd; 
                for(i=0;i < windowNames.length;i++) {                 
                        if (windowNames[i].length > 0) { 
                                closeWindow(windowNames[i]); 
                        } 
                } 
            }     
        eraseCookie(cookieName); 
} 
 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
// FUNCTION: closeWindow 
// 
// Close the specified window 
//  
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
function closeWindow(windowTitle) { 
        var windowHnd  = window.open("#", windowTitle, ""); 
        if (windowHnd && windowHnd.open && !windowHnd.closed) { 
                windowHnd.close(); 
        } 
} 
 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
// FUNCTION: createCookie 
// 
// Create the specified cookie. 
//  
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
function createCookie(name,value,days) { 
        var expires = ""; 
        if (days) { 
                var date = new Date(); 
                date.setTime(date.getTime()+(days*24*60*60*1000)); 
                expires = "; expires="+date.toGMTString(); 
                document.cookie = name + "=" + value + '; path=/' + '; expires=' + date.toGMTString(); 
        } else { 
                document.cookie = name + "=" + value + '; path=/';; 
        } 
} 
 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
// FUNCTION: eraseCookie 
// 
// Delete the specified cookie.   
// Deleting the cookie is done by 
// setting the expiry date to a past 
// date. 
//  
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
function eraseCookie(name) { 
        createCookie(name,"",-1); 
}
