// 
//		JSUtils.js		General-purpose Javascript utilities
//
//	-----------------------------------------------------------------------------------------------
//		function SetCookie( name, value, expires, path, domain, secure ) 
//		function GetCookie( name )		// This function gets the cookie, if it exists
//		function DeleteCookie ( cookie_name )
//		function MakeGMTDate(year, month, day)	
//			Utility function to convert (year, month, day) to GMT date format used in cookies
//		function FileExists(strURL)		// Find out if file exists in user's local file system
//		function IsNothing(myVar)		// Determine if the passed variable is undefined or null
//		function isEven(x)				// Find out if passed number is odd or even
//		function isOdd(x)
//		function findPosX(obj)			// Get the absolute X/Y position of a DOM element (pixels)
//		function findPosY(obj)
//		function ParseParams()			// Populates an array with parameters passed to page in URL
//		function popUpWindow()			// Open specified URL in a popup window
//		function extraWindow()			// Same purpose - the script-generated version that gets created in all Owl pages
//										     (modified so height & width args can be passed)
//		function nullIf()				// Sets default value in passed variable if it's null or undefined


// ------------------------ COOKIES ---------------------------------
//
// Thanks for info from http://techpatterns.com/downloads/javascript_cookies.php, and 
//   http://www.elated.com/articles/javascript-and-cookies/

/* Parameters
name, value 	This sets both the cookie's name and its value: "username=matt"
expires=date 	This optional value sets the date that the cookie will expire on. The date should be in the format 
				returned by the toGMTString() method of the Date object. If the expires value is not given, the cookie 
				will be destroyed the moment the browser is closed: "expires=13/06/2003 00:00:00".
				NOTE THE DATE FORMAT IS dd/mm/yyyy (Euro format)
path=path 		This optional value specifies a path within the site to which the cookie applies. Only documents 
				in this path will be able to retrieve the cookie. Usually this is left blank, meaning that only 
				the path that set the cookie can retrieve it: "path='/tutorials/'"
domain=domain 	This optional value specifies a domain within which the cookie applies. Only websites in this domain 
				will be able to retrieve the cookie. Usually this is left blank, meaning that only the domain that 
				set the cookie can retrieve it: "domain='yahoo.com'"
secure 			This optional flag indicates that the browser should use SSL when sending the cookie to the server.
				This flag is rarely used.
*/
function SetCookie( name, value, expires, path, domain, secure ) 
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	/*
	if the expires variable is set, make the correct 
	expires time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
		expires = expires * 1000 * 60 * 60 * 24;
		
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" + escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

// This function gets the cookie, if it exists
function GetCookie( name ) 
	{
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;

	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) )
		return null;

	if ( start == -1 ) 
		return null;
		
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) 
		end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

// This deletes the cookie when called, by setting an expiration date
//  one second before the current time. 
// GetCookie(name) should return null after this is called.
function DeleteCookie ( cookie_name )
{
	var cookie_date = new Date ( );  // current date & time
	cookie_date.setTime ( cookie_date.getTime() - 1 );
	document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}

/*** An alternate form:
function DeleteCookie( name, path, domain ) 
	{
	if ( GetCookie( name ) ) 
		document.cookie = name + "=" + ( ( path ) ? ";path=" + path : "") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
***************/

// Utility function to convert (year, month, day) to GMT date format used in cookies
//	e.g., SetCookie( "iLike", "oreo", MakeGMTDate(2008,1,22));
function MakeGMTDate(year, month, day)
{
	var gmtdate = new Date ( year, month, day );
	return gmtdate.toGMTString();
}

// Thanks for this one to: http://www.webdeveloper.com/forum/showthread.php?t=100953
function FileExists(strURL)
{
	var resp;
	dojo.debug("Seeking file " + strURL);
	
	try
		{
		var oHttp = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();    
	
		oHttp.open("GET", strURL, false);
		oHttp.send(null);	// In some platforms, this needs SOME argument, even a null
		
//		resp = oHttp.responseText;
//		dojo.debug("Seeking file " + strURL + ", response: " + resp);
		return oHttp.responseText.indexOf("404 - File not found") > 0 ? false : true;
		}
	catch(err)
		{
//		dojo.debug("Error seeking file: " + err.toString());
		return false;
		}
		
// This is a variation on the same idea, via http://jibbering.com/2002/4/httprequest.html
// (see original source - this is an adaptation of what they had there)

/*var itExists;
 
 oHttp.open("HEAD", strURL, true);
 oHttp.onreadystatechange=function() {
  if (oHttp.readyState==4) {
   if (oHttp.status==200) itExists = true;
    else if (oHttp.status==404) itExists = false;
     else alert("Status is "+ oHttp.status)
  }
 }
 xmlhttp.send(null)
*/
}

// Determine if the passed variable is undefined or null
function IsNothing(myVar)
{
	return (myVar == undefined || myVar == null);
}

function isEven(x) { return (x%2)?false:true; }
function isOdd(x) { return !isEven(x); }


// Get the absolute X/Y position of a DOM element (pixels)
function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }
 
function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
 }


// 	ParseParams
//
//	Populates an array with name/value pairs from parameters passed to page in URL
//		Pass an existing array, which may already have stuff in it; this func will push new members onto it.
//		Returns: New array members in the format of the pageParam object, below.
//
//		Example: If url = "http:// ....mypage.html?color=red&shape=round", then array will aquire:
//			pParams[n].key = 'color';
//			pParams[n].value = 'red'
//			pParams[n+1].key = 'shape';
//			pParams[n+1].value = 'round'

function pageParam(myKey, myValue)
{
	this.key = myKey;
	this.value = myValue;
}

var pParams = new Array();

function ParseParams(pParams) 
	{
	var query = window.location.search.substring(1);
	var aParms = query.split('&');
	for (var i=0; i<aParms.length; i++) 
		{
		var pos = aParms[i].indexOf('=');
		if (pos > 0) {
			var key = aParms[i].substring(0,pos);
			var val = aParms[i].substring(pos+1);
			pParams.push(new pageParam(key, val));
			}
		}
	}

// GetValueOfKey - Given an array of 'pageParams', fetch the value associated with the passed key
//	If multiple elements exist with same key, will return the first one found
//	Returns null if not found
function GetValueOfKey(pParams, mikey) {

	var valu4u = null;

	for (var i=0; i < pParams.length; i++) 
		{
		if (pParams[i].key == mikey) {
			valu4u = pParams[i].value;
			break;
			}
		}

	return valu4u;
}


function nullIf(myVar, defaultVal) {

	return ((myVar == null || myVar == undefined) ? defaultVal : myVar);
}

var popUpWin=0;

function popUpWindow(URLStr, left, top, width, height, useStatusBar, useMenuBar, useScrollBars, isResizable)
{

  var useStatusBar = nullIf(useStatusBar, "no");
  var useMenuBar = nullIf(useMenuBar, "no");
  var useScrollBars = nullIf(useScrollBars, "no");
  var isResizable = nullIf(isResizable, "no");

  if(popUpWin)
  {
    if(!popUpWin.closed) popUpWin.close();
  }

var winParams = "toolbar=no,location=no,directories=no,status=" + useStatusBar
		+ ",menubar=" + useMenuBar
		+ ",scrollbars=" + useScrollBars
		+ ",resizable=" + isResizable
		+ ",copyhistory=yes,width=" + width + ",height=" + height + ",left=" + left + ", top=" + top + ",screenX=" + left + ",screenY=" + top + "";

popUpWin = open(URLStr, 'popUpWin', winParams);
}

// This is the script-generated version that gets created in all Owl pages
function extraWindow(url, winHt, winWid)
{
     var remote;
	var winHt = nullIf(winHt, 600);		// Customization for this version: Default to the 'normal' Owl values
	var winWid = nullIf(winWid, 600);

     remote = window.open(url, 'remote', 'HEIGHT=' + winHt + ',WIDTH=' + winWid + ',resizable=yes,scrollbars=yes,location=yes');
     remote.opener = self;
     self.extra = remote;
     self.extra.focus();
}
