// variables used by the page focus handler routine
var mcList; 
var activateModuleId;

//Simple IE Browser Version Check.  Should still do feature sniffing though

// convert all characters to lowercase to simplify testing
var agt=navigator.userAgent.toLowerCase();

// *** BROWSER VERSION ***
var is_major = parseInt(navigator.appVersion);
var is_minor = parseFloat(navigator.appVersion);

var is_ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var is_ie3    = (is_ie && (is_major < 4));
var is_ie4    = (is_ie && (is_major == 4) && (agt.indexOf("msie 4")!=-1) );
var is_ie4up  = (is_ie && (is_major >= 4));
var is_ie5    = (is_ie && (is_major == 4) && (agt.indexOf("msie 5.0")!=-1) );
var is_ie5_5  = (is_ie && (is_major == 4) && (agt.indexOf("msie 5.5") !=-1));
var is_ie5up  = (is_ie && !is_ie3 && !is_ie4);
var is_ie5_5up =(is_ie && !is_ie3 && !is_ie4 && !is_ie5);
var is_ie6    = (is_ie && (is_major == 4) && (agt.indexOf("msie 6.")!=-1) );
var is_ie6up  = (is_ie && !is_ie3 && !is_ie4 && !is_ie5 && !is_ie5_5);
var is_ie7    = (is_ie && (is_major == 4) && (agt.indexOf("msie 7.")!=-1) );
var is_ie7up  = (is_ie && !is_ie3 && !is_ie4 && !is_ie5 && !is_ie5_5 && !is_ie6);


// Flag to stop recording scroll position when unloading
//var stop_scrolling = false;
var stop_scrolling = true;

// Perform logic to attach events (code to handle different browsers)
// This function is cross browser compatible.
function AddEventHandler(target,eventName,handlerName) {
	if ( target.addEventListener ) {
		// Firefox, Opera etc.
		target.addEventListener(eventName, handlerName, false);
	} else if ( target.attachEvent ) {
		// Internet Explorer
		target.attachEvent("on" + eventName, handlerName);
	}
	else if (typeof target[eventName] == "function")
	{
		var fOld = target[eventName];
		target[eventName] = function(e){ fOld(e); handlerName(e); };
	}
	else
	{
		target[eventName] = handlerName;
	}
}

// core interChange functions to address scrolling
function SaveScrollXY() {
	// Trap for an Internet Explorer bug that fires this function one
	// extra time when the page is unloading.
	if (stop_scrolling == true) {
		return;
	}
	// Detect the X/Y offset supported by various browsers (and DocTypes)
	if(window.pageYOffset) {
		document.Form.ScrollX.value = window.pageXOffset;
		document.Form.ScrollY.value = window.pageYOffset;
	} else if(document.body.scrollTop) {
		document.Form.ScrollX.value = document.body.scrollLeft;
		document.Form.ScrollY.value = document.body.scrollTop;
	} else {
		document.Form.ScrollX.value = document.documentElement.scrollLeft;
		document.Form.ScrollY.value = document.documentElement.scrollTop;
	}
}

function ResetScrollPosition() {
	var hidx, hidy;
	hidx = document.Form.ScrollX;
	hidy = document.Form.ScrollY;
	if (typeof hidx != 'undefined' && typeof hidy != 'undefined') {
		window.scrollTo(hidx.value, hidy.value);
	}
	stop_scrolling = false;
}

function PageUnloading() {
	// Set stop_scrolling flag so that ResetScrollPosition does not
	// fire an extra time in Internet Explorer when unloading.
	stop_scrolling = true;
}

// Perform all of the initialization functions needed by the skin
function initPage() {

    var isPageFocusIsLoaded = typeof bringModuleWithFocusIntoView != 'undefined';
    
    if (isPageFocusIsLoaded)
    {
	    // If we have PageFocusHandler "on" and we are IE7+
	    if (is_ie7up)
	        bringModuleWithFocusIntoView();
    }
    else
    {
	ResetScrollPosition();
	
	if(navigator.userAgent.indexOf("Firefox")!=-1) {
		// Firefox - Onscroll event not working under XHTML Doctype use polling instead
		window.setInterval(SaveScrollXY, 500);
	} else {
		// IE and Opera - use Onscroll event
		AddEventHandler(window,'scroll', SaveScrollXY);
	}
	AddEventHandler(window,'unload', PageUnloading);
	}
}

// Helper function to write cookies to the response HTTP string
function SetCookie (name,value) {
    
    var arrValues = window.location.pathname.split('/');
    var pathName;
    
    if (arrValues.length == 0) 
        pathName = window.location.pathname;
    else
        pathName = arrValues[0];
        
    document.cookie = name + "=" + escape (value) + "; path=" + pathName;
}

// SUMMARY: Simply discard the cookie
// param cookie_name: The cookie name
// param server_or_client: Procedure for removing cookies varies upon who generated the cookie, 
// this parameter can contain one of these two values
// "server" = the cookie we want to delete was generated on the server
// "client" = the cookie we want to delete was generated on the client
function DeleteCookie (cookie_name, server_or_client)
{
    var cookie_date = new Date ();  // current date & time
    cookie_date.setTime (cookie_date.getTime() - 1);

    if (server_or_client == "server")
    {
        document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString() + "; path=/";
    } else if (server_or_client == "client")
    {        
        var arrValues = window.location.pathname.split('/');
        var pathName;
        
        if (arrValues.length == 0) 
            pathName = window.location.pathname;
        else
            pathName = arrValues[0];
            
        document.cookie = "iCWindowID=; expires=" + cookie_date.toGMTString() + "; path=" + pathName;
    }
}

// SUMMARY: Event handler for the beforeunload used to send back a cookie
// that will enable the session manager service to keep track of
// the windows opened by the same client.
function page_beforeunload()
{
    var v = document.getElementById('iCWindowID');
    if( v == null ) return;
    SetCookie('iCWindowID', v.value);
}

// Helper function used to remove the page from the browser history
// disabling the back button functionality to prevent re post-back 
// issues.
function DisableBack()
{
	if(window.history.forward(1) != null)
		window.history.forward(1);
}

// Add an onload event handler to run the initPage script
// as soon as the page loads.
AddEventHandler(window,'load', initPage);
AddEventHandler(window,'beforeunload', page_beforeunload);
//FL5433 Enable Back button on public portal.  Individual pages that we do not want the user to 
//access via the Back button will be disabled in the ASCX so that the page is not cached by
//the browser.
//DisableBack();  

/***********************************************************
* CO #10536 Reico : Non-IE browsers do not have a click property 
* defined for some HTML Elements
*
***********************************************************/
if (window.HTMLAnchorElement && HTMLAnchorElement.prototype) 
{
HTMLElement.prototype.click = function() {
var evt = this.ownerDocument.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
this.dispatchEvent(evt);
}
}

function handleClick(targetObj)
 {
	// we should call click first, in case the link contains onclick event.
	// those events must be client-side events, such as go to bottom, minimize,etc.

	// then we see whether exists doPostBack in the href, if yes, that means it is going to postback, 
	// we need to set executingPostBack to be true in order to cancel the confirmation (which is used to prompt when the page is modified)

	// otherwise, it is a redirection. Store the url first, because the targetObj will be null when 
	// the user clicks [Cancel] in the confirmation window. 
	// This is very strange, if I don't do so, there will be a javascript exception, and everything will not work after the exception

    if (targetObj.onclick)
    {
		try
		{
			targetObj.click();
		}
		catch (e)
		{
			// bypass the exception
		}
	}
	else if (targetObj.href && targetObj.href.indexOf('PostBack')>0)
	{
		var url = targetObj.href; 
		executingPostBack = true;

		// IE will throw out a "unspecified error" working with onbeforeunload, when the user clicks [Cancel] button
		try
		{
			window.location.href = url;
		}
		catch (e)
		{
			// by pass the "unspecified error"
		}
	}
	else
	{
		var url = targetObj.href; 
		try
		{
			window.location.href = url;
		}
		catch (e)
		{
			// bypass the exception and continue
		}
	}

}

// Textbox formatting routines are attached to the 'onblur' event - ie. formatted when the user tabs off of a field.
// If the user fires a hotkey to submit the page, force the onblur to ensure formatting occurs.
function forceFormatting(srcElem)
{
    if(srcElem != null)
    {
        if(srcElem.blur != null)
        {
            // Note: forcing blur throws an error in FireFox 1.5 - "Permission denied to set property XULElement.selectedIndex".
            // This is a known bug in the firefox browser and does not prevent the blur from occurring.
            srcElem.blur();            
            
            // Reset focus to the calling element so focus handling will capture the correct cursor position
            srcElem.focus();          
        }
    }
}

// CO 9780 Hong
// this function is used to trigger hotkey for the specified targetObj
function Hotkey(event, targetObj, ctrlKey, shiftKey, altKey, keycode)
{


	if (
		targetObj
		&& event.ctrlKey == ctrlKey 
		&& event.shiftKey == shiftKey 
		&& event.altKey == altKey 
		&& event.keyCode == keycode
		&& targetObj.disabled != true
		)
	{
        var target = event.target || event.srcElement;        
        
        // apply any UI formatting before firing hotkey
        forceFormatting(target);
        
		handleClick(targetObj);
		window.event.cancelBubble = true;
	}
} // end Hotkey function


// a variable indicating this hotkey is processing
var processing = false;

/***********************************************************
* CO #10539 Vuignier : Non-IE browsers define keyCode as being read-only 
* so we need to change the value in the target instead
*
***********************************************************/
function changeKeycode(e, key)
{
	//if IE simply assign the keyCode, ignore if keycode is 8 (backspace)
	if (window.event && e.keyCode && e.keyCode != 8)
		e.keyCode = key
	
	//else if not IE, do the following
	else{
		//ignore all non char keys in Firefox - no need to convert/cancel
		if(!e.keyCode)
		{
		var newText = String.fromCharCode(key);
		// cancel the key event and insert the newKey for the current selection
		if (e.preventDefault){
			e.preventDefault();
		}
		
		if(key != 0)
		{
			//if we don't get the end and start we will be changing the key at position 0 all the time
			var oldSelectionStart = e.target.selectionStart;
			var oldSelectionEnd = e.target.selectionEnd;

			//assign the new key as the value
			e.target.value = e.target.value.substring(0, oldSelectionStart) + newText + e.target.value.substring(oldSelectionEnd);

			//set cursor to the end of the text
			e.target.setSelectionRange(oldSelectionStart + newText.length, oldSelectionStart + newText.length);
		}
	}
	}
}

// Attach this method to enable ALT +/- HotKeys to move between panels on a page.
function PageFocusHotkeys(e)
{
    var e = e || window.event;

    if (e.altKey && (e.keyCode != 18 || e.which != 18)) 
    {
        //  Alt++ (Plus) will put focus on Previous Module when Focus Handler is enabled
		if (!e.ctrlKey && (e.keyCode == 189 || e.which == 189 || e.keyCode == 109 || e.which == 109) && typeof changeFocusToPrevModule == 'function') 
		{
			changeFocusToPrevModule();
			return;
		}
        //  Alt+- (Minus) will put focus on Next Module when Focus Handler is enabled
		if (!e.ctrlKey && (e.keyCode == 187 || e.which == 187 || e.keyCode == 107 || e.which == 107) && typeof changeFocusToNextModule == 'function') 
		{
			changeFocusToNextModule();
			return;
		}
	}
}

// CustomValidator used to validate a value against a control
// containing a comma separated list of valid values (listcontrolid)
function ValidateCode(source, args) 
{
	var strValues = document.getElementById(source.listcontrolid).value;
	var arrValues = new Array();
	
	arrValues = strValues.split(',');

	for(i=0; i<=arrValues.length-1; i++)
	{
		if(arrValues[i] == args.Value)
		{
			args.IsValue = true;
			return;
		}
	}
	
	args.IsValid = false;
}

function getKeyCode(e)
{
  var key;
  //var evnt = window.event ? window.event.srcElement : e ? e.target : null;
  var evnt = e || event;

  if (!evnt)
    return 0;
  
  if (evnt && evnt.which)
    key = evnt.which;
  else if (evnt && evnt.keyCode)
    key = evnt.keyCode;
  else if (window.event && window.event.keyCode)
    key = window.event.keyCode;
  else
    return 0;
    
  return key;
}

// Flag will be set after a postback has been initiated
var blockUserInput = false;

// Codebehind will set this URL to point to the home page (application root)
var applicationRootURL = "/";

// Prevents user input by displaying a popup message
function DoBlockUserInput(e)
{
    if(blockUserInput)
    {
        var evnt = e || window.event;
        var key =  getKeyCode(evnt);        
       
        // Allow certain keys through so we don't block common browser
        // functionality - ie. ALT+TAB
        if( key == 91 || // WIN KEY
            key == 18 || // ALT
            key == 9)    // TAB
        {
            return false;
        }               
    
        // Display message
        var cont = confirm('Processing, please wait...\n\nClick "OK" to continue processing\nClick "Cancel" to return to the Home page');
        
        if(cont)
        {
            // Continue processing
            return false;
        }
        else
        {
            // Reload the page
            location.href = applicationRootURL;
        }
    }
}

// SUMMARY: NewWindowChecking is one of the many functions that work together (both on the client
// and the server) to accomplish the goal of two browsers working together maintaining their own 
// State independently. The most important server-side functions that also have this role are
// context_PreRequestHandlerExecute and context_PostRequestHandlerExecute. For more information look at
// those functions in CustomProvider.SessionPersistModule class.
function NewWindowChecking()
{

    // At this point, we know that the pre-request handling event has already run. This means that we
    // have already "used" the WindowID cookies, there is no purpose in keeping this cookies anymore, so
    // we are getting rid of them (server & client generated cookies are deleted at this point)
    if (window.document.cookie.indexOf("WindowID") >= 0)
    {
        DeleteCookie("iCWindowID", "server");
        DeleteCookie("iCWindowID", "client");
    }
        
    // window.opener not equal to this means that the page just opened was not created in this browser
    // this happens when we are just starting with the application (opening the root interChange), creating 
    // a new window from scratch (for example by pressing ALT+N), or navigating from another browser window
    // (like when we use an "information link" - the green rounded button - to open a new window).
    if(window.opener != this)
    {
        try
        {        
            window.opener = this;
            
            // If the condition below is met, we have a clear indication that we have to increment the WindowID (iCWindowID)
            // this is because our opener is requesting a new window (through the Popup parameter) and also there is no flag 
            // turned on indicating that we already incremented that session (DoNotIncrement cookie is not there)
            if(window.location.href.indexOf("PopUp=") < 0  && window.document.cookie.indexOf("DoNotIncrement") < 0)
            {
                var url = window.location.href;
                
                // last char is / so this must be the portal root
                // unfortunately, there are lots of ways that this might have gotten there
                // so we will take no chances, and redirect using ?PopUp=N
                if( url.charAt(url.length - 1) == '/' )
                {
                    window.navigate(url + "?PopUp=N");
                    return;
                }
                // Modify the url to cause a postback that initiates a new Session
                else if( url.indexOf("?") < 0)
                {
                    url = url + "?PopUp=N";   
                }
                else
                {
                    url = url + "&PopUp=N";   
                }
                
                //Tries to do the postback through the form if it exists, otherwise navigate.
                try
                {
                    theForm.action = url;
                    theForm.submit();
                }
                catch(e)
                {
                    window.navigate(url);
                }

            }
            
            // if this cookie was "used alread" (by saying used, we mean that this flag prevented the additional round-trip we would have 
            // incurred otherwise) we are clearing the flag (the cookie). The fact that the cookie is there is enough prove that it was 
            // already used, so we can safely discard it (knowing that DoNotIncrement was "used" above already).
            if (window.document.cookie.indexOf("DoNotIncrement") >= 0)
                DeleteCookie("DoNotIncrement", "server");
        }
        catch(e){}
    }
}

function IEWindowBlocker()
{
    if(is_ie && window.opener != this)
    {
        try
        {
            // Same check we do in the NewWindowChecking. In plain English this would be something lik "are we going to postback?"
            // "if that is true... then enable the popup blocker"...
            if(window.location.href.indexOf("PopUp=") < 0 && window.document.cookie.indexOf("DoNotIncrement") < 0)
            {
                var page = getPageSize();
                var blocker = document.getElementById('blocker1');  
                blocker.style.display = 'block';
                blocker.style.width = page[0];
                blocker.style.height = page[1];  
                blocker = document.getElementById('blocker');
                blocker.style.display = 'block';
                blocker.style.width = page[0];
                blocker.style.height = page[1];  
             }
        }
        catch(e){}
    }
}

function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}
