/*
 * Created by: iFactor Consulting Inc.
 * Date: 2007-05-22
 * Copyright 2007, iFactor Consulting Inc.
 * All Rights Reserved.
 */

window.iFactor = new Object();
__common = function()
{
	this.configLayers = new Object();  // New Sebastian 11-25-08
	this.config = new Object();
	this.config["cookie_prefix"] = "";
	this.fullDayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
	this.fullMonthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
};
_mSvgEnabled = true;
_mSvgForced = true;

//
// Check for the console used by Firebug.  Create a fake one if it isn't here.
//
if (window.console == null)
{
	window.console = new Object();
	window.console.info = function(){}
}

/**
 * The values seem to be stored in an odd way, so this takes
 * care of that.
 *
 * @param aNode Node -- the node from which to get the value
 * @return String -- the node value
 */
__common.prototype.getXMLNodeValue = function(aNode)
{
	var nodeValue = null;
	
	if (aNode != null)
	{
		var children = aNode.childNodes;
		var i = 0;
		nodeValue = aNode.nodeValue;
		var childNode = null;
	
		if (nodeValue == null)
		{
			for (i = 0; i < children.length; i++)
			{
				childNode = children.item(i);
			
				if (childNode.nodeName == "#text")
				{
					nodeValue = childNode.nodeValue;
				}
			}
		}
	}
	
	return nodeValue;
}

/**
 * Returns the direct child node with the passed name.
 *
 * aParam aNode Node -- the node to find the child under
 * @param aName String -- the name of the node to retrieve
 * @return Node -- the found node
 */
__common.prototype.getXMLChildNamed = function(aNode, aName)
{
	var	children = aNode.childNodes;
	var i = 0;
	var childNode = null;
	var tmpNode = null;

	for (i = 0; i < children.length; i++)
	{
		tmpNode = children.item(i);
		
		if (tmpNode.nodeName == aName)
		{
			childNode = tmpNode;
			break;
		}
	}
	
	return childNode;
}

/**
 * Creates a XMLHttpRequest object.
 *
 * @return XMLHttpRequest -- the request object
 */
__common.prototype.createXMLRequest = function()
{
	var req = false;
	
	//
    // Native support.
    //
    if (window.XMLHttpRequest)
	{
    	try
		{
			req = new XMLHttpRequest();
        }
		catch(e)
		{
			req = false;
        }
    }
    
    //
    // IE ActiveX support.
    //
	else if(window.ActiveXObject)
	{
       	try
		{
        	req = new ActiveXObject("Msxml2.XMLHTTP");
      	}
		catch(e)
		{
        	try
			{
          		req = new ActiveXObject("Microsoft.XMLHTTP");
        	}
			catch(e)
			{
          		req = false;
        	}
		}
    }
    
    return req;
}

/**
 * Creates a unique tag for an asynchronous request.  Basically just a timestamp.
 *
 * @return String -- the unique tag
 */
__common.prototype.uniqueRequestTag = function(newUrl)
{
	var today = new Date();
	var unique = null;

	if (newUrl)
	{
		unique = "?timestamp=" + today.getTime();
	}
	else
	{
		unique = "&timestamp=" + today.getTime();
	}
	
	return unique;
}

/**
 * Creates a cookie for the web page.
 *
 * @param name String -- the name of the cookie
 * @param value String -- the value of the cookie (shouldn't contain a semi-colon)
 * @param days Integer -- the number of days the cookie is good for (can be null) 
 */
__common.prototype.createCookie = function(name, value, days)
{
	var expires = "";
	name = this.config["cookie_prefix"] + name;
	
	if (days != null)
	{
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		expires = "; expires=" + date.toGMTString();
	}
	
	document.cookie = name + "=" + value + expires + "; path=/";
}

/**
 * Gets the value for the cookie with the passed name.
 *
 * @param name String -- the name of the cookie to retrieve
 * @return String -- the cookie value
 */
__common.prototype.readCookie = function(name)
{
	name = this.config["cookie_prefix"] + name;
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	var i = 0;
	var c = null;
	var cookieVal = null;
	
	for(i = 0; i < ca.length; i++)
	{
		c = ca[i];
		
		while (c.charAt(0) == ' ')
		{
			c = c.substring(1, c.length);
		}
		
		if (c.indexOf(nameEQ) == 0)
		{
			cookieVal = c.substring(nameEQ.length, c.length);
			break;
		}
	}
	
	return cookieVal;
}

/**
 * Erases the named cookie.
 *
 * @param name String -- the cookie to erase
 */
__common.prototype.eraseCookie = function(name)
{
	name = this.config["cookie_prefix"] + name;
	this.createCookie(name, "", -1);
}

/**
 * Checks whether or not cookies are enabled.
 */
__common.prototype.cookiesEnabled = function()
{
	var tmpcookie = new Date();
	chkcookie = (tmpcookie.getTime() + '');
	document.cookie = "chkcookie=" + chkcookie + "; path=/";
	
	return (!(document.cookie.indexOf(chkcookie,0) < 0));
}

/**
 * Shows all of the properties for the passed object.
 *
 * @param aThing Object -- the object to debug
 */
__common.prototype.debugShow = function(aThing)
{
	var str = "";
	var i = 0;
	var aType = null;
	
	for (i in aThing)
	{
		aType = typeof aThing[i];	
		aType = aType + "";
		str = str + i + " = " + aThing[i] + "\n";
	}
	
	var win2=window.open("")
	win2.document.open()
	win2.document.write(str);
}

/**
 * Retrieves the browser type for the user.  Valid returns are...
 * Other
 * Firefox15
 * Firefox14
 * IE6
 * IE4
 * @return String -- the browser type
 */
__common.prototype.getBrowserType = function()
{
	var type = "Other";
	
	if (document.getElementById)
	{
		if (!((window.opera) && (window.print)))
		{
			if (document.all)
			{
				//
				// IE, but which one?
				//
				if((document.documentElement) && (document.documentElement.clientWidth || document.documentElement.clientHeight))
				{
					type = "IE6";
				}
				else
				{
					type = "IE4";
				}
			}
			else
			{
				//
				// Firefox, but which one?
				//
				type = "Firefox14";
				var ffn = "Firefox/"
				var ffp = navigator.userAgent.indexOf(ffn);
				ffv = parseFloat(navigator.userAgent.substring(ffp + ffn.length));	
				if (ffv >= 1.5)
				{
					type = "Firefox15";
				}
			}
		}
	}
	
	return type;
}

/**
 * Returns all arguments (if any) that have been passed to
 * the URL.
 *
 * @return Array -- the arguments (keyed on the name)
 */
__common.prototype.getArguments = function()
{
	var anObj = new Object();
	var args = window.location.search;
	var i = 0;
	var argParts = null;
	
	if ((args != null) && (args != ""))
	{
		args = args.substr(1, args.length);
		args = args.split("&");
		
		for (i = 0; i < args.length; i++)
		{
			anArg = args[i];
			argParts = anArg.split("=");
			anObj[argParts[0]] = argParts[1];
		}
	}
	
	return anObj;
}

// Helper functions for Virtual Earth's 'we are too good for hex color codes' methods
__common.prototype.convertHex2DecRGB = function(hex) {
	var colors = new Array();
	var dec = new Array();
	
	for (var i=0;i<3;i++) {
		colors[i] = hex.substr((i*2),2);
		dec[i] = this.convertHex2DecChannel(colors[i]);
	}
	//dec = dec.slice(0,-1);
	
	return dec;	
}

__common.prototype.convertHex2DecChannel = function(hex_channel) {
	var dec_channel;
	dec_channel = parseInt(hex_channel,16);
	return dec_channel.toString();
}

/**
 * Formats the date into this sort of format:
 * Mon, Oct 31 18:30
 *
 * @param aDate Date -- the date to format
 */
__common.prototype.shortDateAndTime = function(aDate)
{
	var str = this.shortDay(aDate.getDay()) + ", ";
	str = str + this.shortMonth(aDate.getMonth()) + " ";
	str = str + aDate.getDate() + ", ";
	var amPm = "AM";
	
	var tmp = aDate.getHours();
	if (tmp > 12)
	{
		amPm = "PM";
		tmp = tmp - 12;
	}
	if (tmp == 0)
	{
		tmp = 12;
	}
	str = str + tmp + ":";
	
	tmp = aDate.getMinutes() + "";
	if (tmp.length == 1)
	{
		tmp = "0" + tmp;
	}
	str = str + tmp + amPm;
	
	return str;
}

/**
 * The short day for the passed day index.
 *
 * @param idx Number -- the day index 
 */
__common.prototype.shortDay = function(idx)
{
	var aDay = this.fullDayNames[idx];
	
	return aDay.substring(0, 3);
}

/**
 * The short month for the passed month index.
 *
 * @param idx Number -- the month index
 */
__common.prototype.shortMonth = function(idx)
{
	var aMonth = this.fullMonthNames[idx];
	
	return aMonth.substring(0, 3);
}

/**
 * Returns the value for the toggle specified by the passed ID.
 *
 * @param name String -- the ID of the toggle
 */
__common.prototype.getToggleValue = function(name)
{
	return window.document.getElementById(name).checked;
}

/**
 * Figures out whether or not the named radio item has a current value
 * matching the passed value.
 *
 * @param value String -- the value to look for
 * @param name String -- the name of the radio item
 * @return Boolean -- does the radio item have the passed value?
 */
__common.prototype.isRadioButtonSelected = function(value, name)
{
	return (this.getRadioValue(name) == value);
}

/**
 * Gets the value of the named radio item.
 *
 * @param name String -- the name of the radio item
 * @return String -- the current value
 */
__common.prototype.getRadioValue = function(name)
{
	var aForm = window.document.getElementById(name);
	var radio = aForm[name];
	var value = null;
	var i = 0;
	
	for (i = 0; i < radio.length; i++)
	{
		if (radio[i].checked)
		{
			value = radio[i].value;
			break;
		}
	}
	
	return value;
}

/**
 * Sets the named radio item to the named value.
 *
 * @param newValue String -- the value of the radio item
 * @param name String -- the name of the form the radio item is in
 */
__common.prototype.setRadioValue = function(newValue, name)
{
	var aForm = window.document.getElementById(name);
	var radio = aForm[name];
	var value = null;
	var i = 0;
	
	for (i = 0; i < radio.length; i++)
	{
		value = radio[i].value;
		radio[i].checked = (value == newValue);
	}
}

/**
 * Based on the browser, returns the proper inner width and inner height
 * as an array.
 *
 * @return Array -- contains the width and height
 */
__common.prototype.getInnerWindowDimensions = function()
{
	var browserType = this.getBrowserType();
	var dims = new Array();
	
	if (browserType == "IE6")
	{
		dims[0] = document.documentElement.clientWidth;
		dims[1] = document.documentElement.clientHeight;
	}
	else if (browserType == "IE4")
	{
		dims[0] = document.body.clientWidth;
		dims[1] = document.body.clientHeight;
	}
	else
	{
		dims[0] = window.innerWidth;
		dims[1] = window.innerHeight;
	}
	
	return dims;
}

/**
 * Clears all rows out of the user table except the first one.
 *
 * @param aTable HTTPTable -- the table to clear
 */
__common.prototype.clearTable = function(aTable)
{
	while(aTable.rows.length > 0)
	{
		aTable.deleteRow(aTable.rows.length - 1);
	}
}

/**
 * Gets the host part of the URI.
 *
 * @return STRING -- the host root
 */
__common.prototype.getHostRoot = function()
{
	var loc = window.location.href;
	var cnt = 0;
	var host = "";
	var i = 0;
	var aChar = null;
	
	for (i = 0; i < loc.length; i++)
	{
		aChar = loc.charAt(i);
		
		if (aChar == '/')
		{
			cnt = cnt + 1;
		}
		
		if (cnt == 3)
		{
			break;
		}
		host = host + aChar;
	}
	return host;
}

/**
 * Tests whether or not self can be used as a float.
 *
 * @return Boolean -- can self be a float?
 */
String.prototype.validForFloat = function()
{
	var validChars = "1234567890";
	var usedPoint = false;
	var i = 0;
	var aChar = null;
	var valid = true;
	
	for (i = 0; i < this.length; i++)
	{
		aChar = this.charAt(i) + "";
		
		if (validChars.indexOf(aChar) == -1)
		{
			if (aChar == ".")
			{
				if (usedPoint)
				{
					valid = false;
					break;
				}
				else
				{
					usedPoint = true;
				}
			}
			else if ((aChar == "-") && (i != 0))
			{
				valid = false;
				break;
			}
			else if ((aChar != "-") && (aChar != "."))
			{
				valid = false;
				break;
			}
		}
	}
	
	if ((valid) && (this.length == 0))
	{
		valid = false;
	}
	
	return valid;
}

/**
 * Ensures that the correct URL separator is used for all separators
 * in the string.
 *
 * @return String -- the fixed URL string
 */
String.prototype.fixUrlSeparator = function()
{
	var bad = "\\";
	var good = "/";
	var aString = this;
	var num = 0;
	
	while(num != -1)
	{
		aString = aString.replace(bad, good);
		num = aString.indexOf(bad);
	}
	
	return encodeURI(aString);
}

/**
 * Reverses the order of things in self in-situ.
 */
Array.prototype.reverse = function()
{
	var tmp = new Array();
	var i = 0;
	var j = 0;
	
	for (i = (this.length - 1); i > -1; i--)
	{
		tmp[j] = this[i];
		j++;
	}
	
	for (i = 0; i < this.length; i++)
	{
		this[i] = tmp[i];
	}
}

/**
 * Inserts the specified thing at the specified position.  Moves everything
 * past that position up 1.
 */
Array.prototype.insertNth = function(thing, index)
{
	var i = 0;
	var tmp = new Array();
	
	for (i = 0; i < this.length; i++)
	{
		if (i < index)
		{
			tmp[i] = this[i];
		}
		else if (i == index)
		{
			tmp[i] = thing;
			tmp[i + 1] = this[i];
		}
		else if (i > index)
		{
			tmp[i + 1] = this[i];
		}
	}
	
	for (i = 0; i < tmp.length; i++)
	{
		this[i] = tmp[i];
	}
}

iFactor.common = new __common();
