/* Front end tools used to control front end rendering of widgets and
   minor unobtrusive components 
   
   Created by DG 01/05/2008
*/
/* Basic DHTML ID CALLER FUNCTIONS */
var blnLoadedFrontEndTools = true;
var onLoadEvents = new Array();

function AddOnLoadEvent( _evt )
{
  onLoadEvents.push(_evt);  
}

/* Performs a foreach on the array in question */
Array.prototype.foreach = function(predicate)
{
    for(var idx=0;idx<this.length;idx++)
        predicate(this[idx]);
};

Array.prototype.foreach_reverse = function(predicate)
{
    for(var idx=(this.length-1);idx>-1;idx--)
        predicate(this[idx]);
};

window.onload = function() { onLoadEvents.foreach(function(e){ e(); }); };

/* wrapper for document.getElementByID() and document.all and document.GetelementsByTagName*/
function $()
{
    var arrObjectsReturned = new Array();
    switch(arguments.length)
    {
        case 1: {arrObjectsReturned.push(document.getElementById(arguments[0]));}; break;
        case 2: {
                    var objs = arguments[0].getElementsByTagName(arguments[1]);
                        for(var i=0;i<objs.length;i++)
                        {
                            arrObjectsReturned.push(objs[i]);
                        }
                }; break;
        case 3: {   //look through all elements and search for particular attribute
                    //if it matches, add to collection
                    //DG 09/05/2008
                    var JSON_Parsed =  eval("("+arguments[0]+")");
                    var findElements=document.getElementsByTagName(JSON_Parsed.tag);
                        if(findElements.length>0)
                        {
                            for(var iCtrl=0;iCtrl<findElements.length;iCtrl++)
                            {     
                                var foundVal = findElements[iCtrl].getAttribute( JSON_Parsed.key );
                                if( foundVal!=null&&foundVal!=undefined )
                                if( foundVal.toString().indexOf(JSON_Parsed.value)>-1 )//match particular value
                                    arrObjectsReturned.push( findElements[iCtrl] ); //add to collection
                            }
                        }
                    
                }; break;
    }
    return  arrObjectsReturned;
}

//safely removes all children from specified container
function DOM_RemoveAllChildren( DOMObject )
{
    for(var iObj=(DOMObject.childNodes.length-1);iObj>-1 ; iObj--)
        DOMObject.removeChild(DOMObject.childNodes[iObj]);
        
}

/* AJAX Callbacks to Pages */
var _Obj = new Array();
var _IsHTML = true;
var xmlHttp;
var functionToExec;
var returnData;
var intGlobalObjectIdentifier=0;
function AJAX_SetTarget(callback_function, URL, GET_POST, params)
{
		functionToExec=callback_function;
		xmlHttp=AJAX_CreateRequestObject(AJAX_StateChanged);
		xmlHttp.open(GET_POST, URL , true);  
		if(GET_POST=="POST")
		{
            xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		}
		
		xmlHttp.send(params);
}

function AJAX_StateChanged() 
{ 
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
	{ 
		try{
			functionToExec(xmlHttp); 
		}catch(e){	
		        //alert(e.message);
		        //throw(e);
		}	
	} 
}  

function AJAX_CreateRequestObject(handler) 
{
	var ro;
	var browser = navigator.appName;
	
	if(browser == "Microsoft Internet Explorer"){
		ro = new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		ro = new XMLHttpRequest();
	}

	ro.onreadystatechange = handler;
	return ro;
}

//this is a base widget class


var obj_fade_collection = new Array();
var _faderInt;

function setOpacity( object, level)
{
    if(object.style.filter!=null)
	    object.style.filter = "alpha(style=0, opacity="+level+")";
	if(object.filters!=null)
		object.filters.alpha.opacity = level;
	if(object.style.MozOpacity!=null)
		object.style.MozOpacity = parseInt(level)/100;
    object.opacity = level;
}

function getOpacity(object)
{
    return object.opacity;
}

function fadeout(_obj, _time, _interval)
{
    obj_fade_collection.push(_obj);
    setOpacity(_obj, 100);
    setTimeout("startFade("+_interval+")", _time);  
}

function startFade(_interval)
{
    _faderInt = setInterval("fadeoutTrans()", _interval);
}

function fadeoutTrans()
{
   var blnContinue = false;
   obj_fade_collection.foreach( function(evt){
        var itemOpacity = getOpacity(evt);
        if(itemOpacity>0)
           {
                blnContinue = true;
                setOpacity(evt,itemOpacity-(itemOpacity>10)?10:1);
           } 
   }); 
}
var msgbox;
var msgcontainer;
var _rolloverInt;
//shows a message JS style
function showGDSMessage( _msg )
{
  clearInterval(_rolloverInt);
  
  msgcontainer = $("gds_statusModule")[0];
  DOM_RemoveAllChildren(msgcontainer);
  
  msgbox = document.createElement("DIV");
  msgbox.id = "msgbox";
  msgbox.appendChild(document.createTextNode(_msg));
      
  msgcontainer.appendChild(msgbox);
  msgcontainer.style.position = "relative";
  msgcontainer.style.overflow = "hidden";
  msgcontainer.style.height = "30px";
  
  msgbox.className = "status";
  msgbox.style.position = "relative";
  msgbox.style.top = "-50px";
  msgbox.top = -50;
  
  //show roll out effect
  _rolloverInt = setInterval("rollEffect('down')",30);
}

function rollEffect(_dir)
{
   if(_dir=="down")
   {
     if(msgbox.top<0)
     {
        msgbox.top = msgbox.top + ((msgbox.top<-15)?15:1);
        msgbox.style.top = msgbox.top + "px";
     }
     else {
        clearInterval(_rolloverInt);
        setTimeout("rollUp()", 5000);
     }
   }
   else {
        //up
       if(msgbox.top>-50)
         {
            msgbox.top = msgbox.top - ((msgbox.top>15)?15:1);
            msgbox.style.top = msgbox.top + "px";
         }
         else {
            clearInterval(_rolloverInt);
         } 
   }
}

function rollUp()
{
 _rolloverInt = setInterval("rollEffect('up')",30);
}

function trimFast(str) 
{
	var whitespace = ' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000';
	for (var i = 0; i < str.length; i++) {
		if (whitespace.indexOf(str.charAt(i)) === -1) {
			str = str.substring(i);
			break;
		}
	}
	for (i = str.length - 1; i >= 0; i--) {
		if (whitespace.indexOf(str.charAt(i)) === -1) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

function toSentenceCase(sentence) 
{
  return sentence.toString().toLowerCase().replace(/(^\s*\w|[\.\!\?]\s*\w)/g,function(c){return c.toUpperCase()});
}

var _intCurrentResolution_Width, _intCurrentResolution_Height;

function getBrowser_ScreenDimensions()
{
	_intCurrentBrowserWidth = document.documentElement.clientWidth;
	_intCurrentBrowserHeight = document.documentElement.clientHeight;
	if(navigator.appVersion.indexOf("MSIE") > -1 ) _blnIsIE = true;
	
	//Get screen resolution
	_intCurrentResolution_Width = screen.width;
	_intCurrentResolution_Height = screen.height;
}

/////////////////
///This function loads a page in a new window
///Daniel GRant 20/10/2006
/////////////////
function loadNewWindow(obj_srcElement, _width,  _height, _blnUseScrollBars)
{/*
	if(_currentKey != "ctrl")
		alert("Please hold down on ctrl key while clicking to open in new browser window");
	else
	{
	*/
	    getBrowser_ScreenDimensions();
		//Resolution buffer vars
		var _x=0, _y=0;
		
		_y = ((_intCurrentResolution_Height - _height) / 2) - 20;
		_x = (_intCurrentResolution_Width - _width) / 2;
		
		_currentKey = "";
		
		var _newWindow;
		try{
			_newWindow = window.open(obj_srcElement.attributes['href'].value, '_blank', "height="+_height+",width="+_width+",status=yes,toolbar=no,menubar=no,location=0,scrollbars="+_blnUseScrollBars.toString()+",top="+_y+"px, left="+_x+"px");
		}
		catch(e)
		{
			_newWindow = window.open(obj_srcElement.href, '_blank', "height="+_height+",width="+_width+",status=yes,toolbar=no,menubar=no,location=0,scrollbars="+_blnUseScrollBars.toString()+",top="+_y+"px, left="+_x+"px");
		}	
		
		if(!_newWindow)
			alert("Our system has detected you have popup blocker enabled, please enable popups from this site to continue.");
	/*}*/
	return false;
}

/// <summary>
/// Checks to see if an object exists in the document
/// </summary>
/// George Cooke
/// <param name="element">The ID of the element to be checked for</param>
function chkObject(element) 
{
    if (document.getElementById(element) != null) 
        return true;
        
    return false;
}

/// <summary>
/// Finds the footer and moves it to the bottom of the page
/// </summary>
/// George Cooke
/// <param name="extraHeight">Additional Height to be added for any elements that won't be picked up automatically</param>
function setFooterHeight(extraHeight)
{
    difHeight = 0;
    stdFooter = 'pinnedFooter';
    stdContainer = 'container'
    multiColumn = 0;
    spacerHeight = 10; 
    
    var isIE = /*@cc_on!@*/false;

    // Check which footer is being used, and exit if one cannot be found
    if (!chkObject(stdFooter))
    {
        stdFooter = 'stdPinnedFooter';
        if (!chkObject(stdFooter))
            return;
    }
            
    // Get the standard items
    headerHeight = document.getElementById('header').offsetHeight * 1;    
    footerHeight = document.getElementById(stdFooter).offsetHeight * 1; 
    
    // If there is no footer (no footer height) then don't do anything
    if (footerHeight == 0)
        return;
    
    // Get the overall window height - this is different in IE to other browsers
    if (isIE)
    { windowHeight = document.documentElement.clientHeight; }
    else
    { windowHeight = window.innerHeight; }
    
    // See if this is a multi column page as it affects the spacing requirements and what container is modified
    if (chkObject('maincol'))
    {
        // Reset the height to default
        ResetHeight('maincol');
    
        multiColumn = 1;
        containerHeight = document.getElementById('maincol').offsetHeight * 1;
        
        if (chkObject('container'))
        {
            difHeight = (containerHeight - footerHeight) - document.getElementById('container').offsetHeight * 1;
        }
        else
        {
            stdContainer = 'maincol';
        }
    }
    else
    {
        if (chkObject('container'))
        {
            ResetHeight('container');
            containerHeight = document.getElementById('container').offsetHeight * 1; 
        }
        else
        {
            return;
        }    
    }
    
    // If the container is empty (no height), then this must be an index page, in which case we need to expand the
    // whole content, instead of just one column, as this causes the footer to wrap
    if (containerHeight == 0)
    {
        stdContainer = 'ContentDiv'
        containerHeight = document.getElementById(stdContainer).offsetHeight * 1; 
    }

    // Get the total height required above the footer
    contentHeight = headerHeight + containerHeight;

    if (contentHeight < windowHeight)
    {
        // Work out how high the content needs to be to put the footer at the bottom
        newContainerHeight = windowHeight - (headerHeight + footerHeight + spacerHeight);
        
        // In some cases, the content heights can be very close, so make sure the current content doesn't get shrunk
        if (newContainerHeight < containerHeight)
            return;
        
        if (difHeight > 0)
        { newContainerHeight = newContainerHeight - difHeight; }
        
        ResetHeight(stdContainer, newContainerHeight);
        
        // If extra height has been requested, add it here
        // NOTE - Currently not implemented
//        if (extraHeight != null)
//        {
//            if (containerHeight < extraHeight)
//                newContainerHeight = newContainerHeight + extraHeight;
//        }
    } 
}

/// <summary>
/// Resets the height of a container item
/// </summary>
/// George Cooke
/// <param name="container">The ID of the container to be reset</param>
/// <param name="height">The height in px that it should be reset to, if left as NULL the height will be set back to auto</param>
function ResetHeight(container, height)
{
    var isIE = /*@cc_on!@*/false;

    // Set the container height - this is different in IE to other browsers
    if (height != null)
    {
        if (isIE)
        { document.getElementById(container).style.height = newContainerHeight; } 
        else 
        { document.getElementById(container).style.height = newContainerHeight + 'px'; }
    }
    else
    {   
        if (isIE)
        { document.getElementById(container).style.height = 'auto'; } 
        else 
        { document.getElementById(container).style.height = 'auto'; }
    }
}