function setOnLoadFunction( aFunction )
{
    window.onload = aFunction;            //firefox
    document.body.onload = aFunction;     //windows
}

function changeto( bgColor ){

    if ( typeof event == "undefined" )  //firefox doesn't have window.event
        return;

    var source=event.srcElement

    if ( source.tagName=="TR" || source.tagName=="TABLE" )
    {
        return;
    }

    while ( source.tagName != "TR" )
    {
        source=source.parentElement
    }
    source.style.backgroundColor = bgColor;
}

function setPointer( pointerStyle ) {
  if ( document.all )
    for (var i=0;i < document.all.length; i++)
       document.all(i).style.cursor = pointerStyle;
}

function confirmDelete(formNameObj, promptVal) {
  if (confirm(promptVal)) {
    formNameObj.submit();
  } 
}

function launchPopup( popupUrl , targetName, width , height , showScrollBars )
{
    popupUrl = popupUrl;
    popUpWindow = window.open( popupUrl , targetName , "menubar=no,status=no,toolbar=no,location=no,scrollbars=" +
                      showScrollBars + ",width=" + width + ",height=" + height );
    popUpWindow.focus();
}

this.getTime = function()
{
    var now = new Date();
    var minutes = now.getMinutes();
    if (minutes < 10)
        minutes = "0" + minutes;
    var seconds = now.getSeconds();
    if (seconds < 10)
        seconds = "0" + seconds;

    return now.getHours() + ":" + minutes + ":" + seconds;
}

/*
       Persists a cookie in the browser

       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;
    //alert(document.cookie + " | " + curCookie);
}

// Retrieves a cookie from the browser with the specified name
function getCookie( name )
{
    // cookies are separated by semicolons
    var aCookie = document.cookie.split("; ");
    for ( var i = 0; i < aCookie.length; i++ )
    {
        // a name/value pair (a crumb) is separated by an equal sign
        var aCrumb = aCookie[i].split("=");

        if ( name == aCrumb[0] && aCrumb.length > 1 )
        {
            return unescape(aCrumb[1]);
        }
    }
    return null;
}

function loadShowHideColumnsFromCookie(controller)
{
	var cookie = getCookie( "COLUMN_STATE_" + window.name );

	if ( cookie != null && cookie != "" )
	{
		controller.applySettings( getColumnVisibility( cookie ), getAggregationRowVisibility( cookie ) );
		return true;
	}
	return false;
}

function getColumnVisibility( cookie )
{
   var result = new Object();
   var states = cookie.split( "|" );

   for ( var i = 0; i < states.length - 1; i++ )
   {
	   var column = states[ i ].split( "=" );
	   result[ column[0] ] = ( column[1] == "true" );
   }

   return result;
}

function getAggregationRowVisibility( cookie )
{
   var states = cookie.split( "|" );
   return states[ states.length - 1 ] == "true";
}


function persistDropDown( elementId )
{
    var selectElement = document.getElementById( elementId );

    if ( selectElement != null )
    {
        selectElement.onchange = onChangePersistSelectionUsingValue;
    }
}

function loadStateFromCookie( cookieNameAndElementId )
{
    var value = getCookie( cookieNameAndElementId );
    var selectElement = document.getElementById( cookieNameAndElementId );

    if ( selectElement != null && value != null )
    {
          selectElement.selectedIndex = value;
    }
}

function persistDropDownUsingCookie( cookieNameAndElementId )
{
    var value = getCookie( cookieNameAndElementId );
    var selectElement = document.getElementById( cookieNameAndElementId );

    if ( selectElement != null && value != null )
    {
          selectElement.selectedIndex = value;
    }

    if ( selectElement != null )
    {
        selectElement.onchange = onChangePersistSelection;
    }
}

// Used for creating an event object.
function Event( _source ){
    this.srcElement = _source;
}

// Retrieves the source of an event.
function getEventSourceElement( event )
{
     if ( !event )                   // IE doesn't pass events as parameters into onchange functions - but can get
                                    // event from the window.
        return window.event.srcElement;   // IE 5 and earlier

    if ( event.target)              // double check we have an event object - i.e. that someone isn't doing something stupid.
        return event.target;        // firefox

    return event.srcElement;    // IE 5.5 and later
}

// This will only work cross-browser from an inline attribute if it is called in following way:
// <select ... onchange="javascript: onChangePersistSelection( event );" ... >
function onChangePersistSelection( event )
{
    // Find the source of the change event
    var changedElement = getEventSourceElement(event);
    // Find the index of the selected option
    var index = changedElement.selectedIndex;
    // Set an expiry date for the cookie one year in the future.
    var expires = new Date();
    expires.setFullYear( expires.getFullYear() + 1 );
    // Save a cookie using the id of the element as the name.
    setCookie(changedElement.id, index, expires);
}

// Call this from html SELECT elements to persist their selection.
// Requires a matching setSelectedIndex method specific to the element.
function onChangePersistSelectionUsingValue( event )
{
    // Find the source of the change event
    var changedElement = getEventSourceElement(event);
    // Find the index of the selected option
    var value = changedElement.value;
    // Set an expiry date for the cookie one year in the future.
    var expires = new Date();
    expires.setFullYear( expires.getFullYear() + 1 );
    // Save a cookie using the id of the element as the name.
    setCookie(changedElement.id, value, expires);
}

// Allows two action to be chained together. This allows any number of actions to
// be performed in response to an event (by chaining EventChain objects together.
// param event : The event to run the actions in response to.
// param func : The new function to add to the event chain.
// Useage: Create new instance then register the eventAction method with the chosen event.
function EventChain(event, func)
{
    var actionPair = new Array();
    // Method which will be called in response to the event.w
    this.eventAction = function()
    {
        if (actionPair[0] != null) actionPair[0]();
        if (actionPair[1] != null) actionPair[1]();
    }

    // Push the original function onto the stack.
    actionPair.push(eval(event));
    actionPair.push(func);


}

function addEventHandler( eventName, handler )
{
    // Handle the case where this is the only handler for the event.
    var currentHandler = eval(eventName);
    if (typeof(currentHandler) == "undefined")
    {
        eval(eventName + " = " + handler);
    }
    else
    {
        // If there is already a handler assigned to this event then create an EventChain.
        var chain = new EventChain(eventName, handler);
        // Wire up the event to the action in the EventChain
        eval(eventName + " = chain.eventAction");
    }
}

// Describes a dimension with height and width.
// Provides method to compare against another dimension.
function Dimension( height, width )
{
    this.height = height;
    this.width = width;

    this.greaterThan = function( otherDimension, range )
    {
        if (this.width > otherDimension.width+range || this.height+range > otherDimension.height )
        {
            return true;
        }
        return false;
    }
}

// Resize the scroll pane specified to be slightly smaller than
// the browser window.
function resizeScrollPane( elementId ) {
    var scrollspan = $( elementId );

    scrollspan.style.width = calculateScrollSpanWidth( elementId ) + "px";
    scrollspan.style.height = calculateScrollSpanHeight( elementId ) + "px";

    // Returns the dimensions of the browser window
    // in a non-browser specific way.
    function getBrowserDimension()
    {
         var myWidth = 0, myHeight = 0;
        if( typeof( window.innerWidth ) == 'number' ) {
            //Non-IE
            myWidth = window.innerWidth;
            myHeight = window.innerHeight;
        } else if( document.documentElement &&
          ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
            //IE 6+ in 'standards compliant mode'
            myWidth = document.documentElement.clientWidth;
            myHeight = document.documentElement.clientHeight;
        } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
            //IE 4 compatible
            myWidth = document.body.clientWidth;
            myHeight = document.body.clientHeight;
        }
        return new Dimension(myHeight, myWidth);
    }

    function calculateScrollSpanHeight( elementId )
    {
        var result = getBrowserDimension().height - getOffsetFromTopOfPage( $( elementId ) );
        return result > 0 ? result : 0;
    }

    function calculateScrollSpanWidth( elementId )
    {
        // hard-code the scroll span width to be the browser width minus a padding found by experimenting.
        var result = getBrowserDimension().width - 35;
        return result > 0 ? result : 0;
    }

    // Returns the scroll dimensions of the specified element.
    function getScrollSpanDimension(elementId)
    {
        var scrollspan = document.getElementById(elementId);
        var spanDimension = new Dimension(scrollspan.scrollHeight, scrollspan.scrollWidth);
        return spanDimension;
    }

    // Returns the offset dimensions of the specified element
    function getScrollSpanOffsetDimension(elementId)
    {
        var scrollspan = document.getElementById(elementId);
        var spanDimension = new Dimension(scrollspan.offsetHeight, scrollspan.offsetWidth);
        return spanDimension;
    }

    function getOffsetFromTopOfPageById(elementId)
    {
        var element = document.getElementById(elementId);
        return getOffsetFromTopOfPage(element);
    }

    function getOffsetFromTopOfPage(element)
    {
        var offset=0;
        if (element.offsetParent != null )
        {
            offset += getOffsetFromTopOfPage(element.offsetParent);
        }
        offset += typeof(element.offsetTop) == 'number' ? element.offsetTop :0;
        return offset;
    }
}



var logContents = new Array();
function log(message)
{
    logContents.push(message);    
}

// Toggle the visibility of two components.
// Param1: the element to hide
// Param2: the element to make visible
function toggleVisibility(visibleElementId, hiddenElementId)
{
    var visibleElement = document.getElementById(visibleElementId);
    var hiddenElement = document.getElementById(hiddenElementId);
    visibleElement.style.display = "none";
    hiddenElement.style.display = "inline";
    setCookie("visibleElementId", hiddenElementId);
    setCookie("hiddenElementId", visibleElementId);
}

//Global LoadManager object to handle chains of onLoad functions in Tiles
function LoadManager()
{
	var loadFunctions = new Array();

	this.addFunction = function(functionName)
	{
		loadFunctions.push(functionName);
	}

	this.runFunctions = function()
	{
		for (var j=0; j<loadFunctions.length; j++)
		{
			alert(loadFunctions[j]);
			eval(loadFunctions[j]);
		}
	}
}
var loadManager = new LoadManager();
