var MonthsArrayShort	= new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
var MonthsArray		= new Array("January", "February", "March", "April", "May", "June", "July", "August", "Septempber", "October", "November", "December");
var WeekdaysArray	= new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");


/* ****************************** ARRAY ****************************** */

//This is the normal indexOf function, but IE8 doesnt support it, so re-define it
Array.prototype.indexOf = function(str)
{
	//go thru this object (array) looking for the string passed in
	
	for (var i = 0; i < this.length; i++)
	{
		if (this[i] == str)
			return i;
	}
	
	return -1;
}

Array.prototype.sortNumeric = function(direction) {
	function asc(a, b) {
		return a - b;
	}
	function desc(a, b) {
		return b - a;
	}
	
	direction = direction || "asc";
	
	switch (direction.toLowerCase()) {
		case "desc":
			this.sort(desc);
		break;
		
		case "asc":
			this.sort(asc);
		break;
	}
}


/* ****************************** STRING ****************************** */

String.prototype.trim = function()
{
	return this.replace(/^\s+|\s+$/g,"");
}

String.prototype.replaceAll = function(OldString, NewString)
{
	var strText = this;
	var intIndexOfMatch = strText.indexOf(OldString);

	while (intIndexOfMatch != -1)
	{
		strText = strText.replace(OldString, NewString)
		intIndexOfMatch = strText.indexOf(OldString);
	}

	return(strText);
}


String.prototype.capitalize = function()
{
	return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
}


String.prototype.stripHTML = function()
{
        var matchTag = /<(?:.|\s)*?>/g;
        return this.replace(matchTag, "");
}

/* ****************************** BROWSER ****************************** */

function IsIE()
{
	return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}


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;

	return [pageWidth,pageHeight];
}


function getScrollXY()
{
	var scrOfX = 0, scrOfY = 0;
	
	if(typeof(window.pageYOffset) == 'number')
	{
		//Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	}
	else if(document.body && (document.body.scrollLeft || document.body.scrollTop))
	{
		//DOM compliant
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	}
	else if(document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop))
	{
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}

	return [scrOfX, scrOfY];
}


function getWindowSize()
{
	//Get the current size of the visible window (in case window is not full screen - also takes for account status bar, menus, firebug, etc)
	
	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 [myWidth, myHeight]
}


function getMouseXY(event)
{
	var posX,posY;
	
	if (event.pageX)
	{
		// NS 4, Mozilla
		posX = event.pageX;
		posY = event.pageY;
	}
	else
	{
		// IE, Opera
		var root = document.documentElement || document.body;
		posX = event.clientX + root.scrollLeft;
		posY = event.clientY + root.scrollTop;
	}

	return [posX, posY];
}


var FilesAddedList = "";

function AddJSFileToHead(Filename)
{
	//if the file is not already in the head, add it.
	if (FilesAddedList.indexOf(Filename) == -1)
	{
		var ScriptObj = document.createElement('script');
		ScriptObj.setAttribute("type", "text/javascript");
		ScriptObj.setAttribute("src", Filename);
		document.getElementsByTagName("head")[0].appendChild(ScriptObj);
		
		if (FilesAddedList.length > 0)
			FilesAddedList += ",";
			
		FilesAddedList += Filename
	}
}


function AddCSSFileToHead(Filename)
{
	//if the file is not already in the head, add it.

	if (FilesAddedList.indexOf(Filename) == -1)
	{
		var LinkObject = document.createElement('link');
		LinkObject.setAttribute("rel", "stylesheet");
		LinkObject.setAttribute("type", "text/css");
		LinkObject.setAttribute("href", Filename);
		document.getElementsByTagName("head")[0].appendChild(LinkObject);

		if (FilesAddedList.length > 0)
			FilesAddedList += ",";
			
		FilesAddedList += Filename
	}
}

/* ****************************** FADING, POP-UPS ****************************** */

function DisableScreen()
{
	var arrayPageSize = getPageSize();
	var PageWidth = arrayPageSize[0];
	var PageHeight = arrayPageSize[1];

	var TransparentLayer = document.createElement('div');
	TransparentLayer.id = "TransparentLayer";
	TransparentLayer.style.width = "100%";
	TransparentLayer.style.height = PageHeight + "px";
	TransparentLayer.style.backgroundColor = "black";
	TransparentLayer.style.position = "absolute";
	TransparentLayer.style.top = "0";
	TransparentLayer.style.left = "0";
	TransparentLayer.style.zIndex = "2";
	document.getElementsByTagName('body')[0].appendChild(TransparentLayer);		//append to page
	FadeInElement(id="TransparentLayer", Opacity=0, MaxOpacity=80, TransitionPause=5, StepSize=10);

	return TransparentLayer;
}

function EnableScreen()
{
	var TransparentLayer = document.getElementById('TransparentLayer');
	
	if (TransparentLayer)
	{
		FadeOutElement(id="TransparentLayer", Opacity=80, MinOpacity=0, TransitionPause=5, StepSize=10);
		setTimeout("DeleteElement('TransparentLayer')", 500);
	}
}

function DeleteElement(id)
{
	var Element = document.getElementById(id);
	
	if(Element)
		document.getElementById(id).parentNode.removeChild(Element);
	else
		ShowPopup("ERROR", "Element '"+ id +"' does not exist.");
}


function FadeInElement(id, Opacity, MaxOpacity, TransitionPause, StepSize)
{
	if (Opacity > MaxOpacity)
		Opacity = MaxOpacity;

	if (Opacity < MaxOpacity)
	{
		Opacity += StepSize;
		SetOpacity(id, Opacity);
		setTimeout("FadeInElement('"+id+"', "+Opacity+", "+MaxOpacity+", "+TransitionPause+", "+StepSize+")", TransitionPause);
	}
}


function FadeOutElement(id, Opacity, MinOpacity, TransitionPause, StepSize)
{
	if (Opacity < MinOpacity)
		Opacity = MinOpacity;

	if (Opacity > MinOpacity)
	{
		Opacity -= StepSize;
		SetOpacity(id, Opacity);
		setTimeout("FadeOutElement('"+id+"', "+Opacity+", "+MinOpacity+", "+TransitionPause+", "+StepSize+")", TransitionPause);
	}
}


function SetOpacity(id, Value)
{
	if (document.getElementById(id))
	{
		var object = document.getElementById(id).style;

		object.opacity = (Value / 100);
		object.MozOpacity = (Value / 100);
		object.KhtmlOpacity = (Value / 100);
		object.filter = "alpha(opacity=" + Value + ")";
	}
}


function ShowPopup(Title, Msg)
{
	//Create a modal pop-up window
	
	// 1. Disable window
	// 2. Create layer on top.  It should be in centre of page and have a 'close' button that re-enables screen
	
	// 1.
	DisableScreen();
	
	// 2.
	var PageDimensionsArray = getPageSize();
	var PageWidth = PageDimensionsArray[0];
	var PopupWidth = 432;

	var PageScrollArray = getScrollXY();
	var ScrollY = PageScrollArray[1];
	
	var ErrorWrapper = document.createElement("div");
	ErrorWrapper.id = "ErrorWrapper";
	ErrorWrapper.style.top = ScrollY + 200 + "px";			//get height automatically
	//ErrorWrapper.style.top = "394px";				//set at certain spot on page
	ErrorWrapper.style.left = (PageWidth-PopupWidth)/2 + "px";

	var ErrorHeader = document.createElement("div");
	ErrorHeader.id = "ErrorHeader";

	var ErrorTitle = document.createElement("div");
	ErrorTitle.id = "ErrorTitle";
	ErrorTitle.innerHTML = Title;

	var ErrorCloseLink = document.createElement("div");
	ErrorCloseLink.id = "ErrorCloseLink";

	var MyLink = document.createElement("a");
	MyLink.id = "Links";
	MyLink.innerHTML = "close";
	MyLink.href = "javascript: HidePopup();";

	var ErrorBodyWrapper = document.createElement("div");
	ErrorBodyWrapper.id = "ErrorBodyWrapper";

	var ErrorBodyText = document.createElement("div");
	ErrorBodyText.id = "ErrorBodyText";
	ErrorBodyText.innerHTML = Msg;

	var ErrorFooter = document.createElement("div");
	ErrorFooter.id = "ErrorFooter";

	ErrorWrapper.appendChild(ErrorHeader);
	ErrorHeader.appendChild(ErrorTitle);
	ErrorHeader.appendChild(ErrorCloseLink);
	ErrorCloseLink.appendChild(MyLink);
	ErrorWrapper.appendChild(ErrorBodyWrapper);
	ErrorBodyWrapper.appendChild(ErrorBodyText);
	ErrorWrapper.appendChild(ErrorFooter);

	document.getElementsByTagName('body')[0].appendChild(ErrorWrapper);		//append to page
}


function HidePopup()
{
	// 1. Destroy the help window that was created
	// 2. Re-enable screen
	
	var ErrorWrapper = document.getElementById('ErrorWrapper');
	//document.childNodes[1].removeChild(ErrorWrapper);
	//window.document.childNodes[1].childNodes[1].removeChild(ErrorWrapper);
	document.getElementsByTagName('body')[0].removeChild(ErrorWrapper);
	
	EnableScreen();
}


function DisableElement(ElementID)
{
	var ElementWidth = document.getElementById(ElementID).style.width.replace("px", "");
	var ElementHeight = document.getElementById(ElementID).style.height.replace("px", "");

	var TransparentLayer = document.createElement('div');
	TransparentLayer.id = ElementID + "TransparentLayer";
	TransparentLayer.style.width = "100%";
	TransparentLayer.style.height = "100%";	//ElementHeight + "px";
	TransparentLayer.style.backgroundColor = "black";
	TransparentLayer.style.position = "absolute";
	TransparentLayer.style.top = "0";
	TransparentLayer.style.left = "0";
	TransparentLayer.style.zIndex = "99";
	document.getElementById(ElementID).appendChild(TransparentLayer);
	
	//FadeInElement(id=ElementID + "TransparentLayer", Opacity=0, MaxOpacity=80, TransitionPause=5, StepSize=10);
	
	TransparentLayer.style.opacity = 0.8;
	TransparentLayer.style.MozOpacity = 0.8;
	TransparentLayer.style.KhtmlOpacity = 0.8;
	TransparentLayer.style.filter = "alpha(opacity=80)";
	
	return TransparentLayer;
}


function EnableElement(ElementID)
{
	//Destroy the fade layer
	//The fade layer should always have the same ID as the layer it covers, plus "TransparentLayer"
	
	//FadeOutElement(id = ElementID + 'TransparentLayer', Opacity=80, MinOpacity=0, TransitionPause=5, StepSize=10);
	//setTimeout("document.getElementById('"+ElementID+"').removeChild(document.getElementById('"+ElementID+"TransparentLayer'))", 500);
	
	try {
		document.getElementById(ElementID).removeChild(document.getElementById(ElementID + "TransparentLayer"));
	}
	catch(e) {}
}


/* ****************************** VALIDATORS ****************************** */

function IsNumeric(value)
{
	if (value == null || !value.toString().match(/^[-]?\d*\.?\d*$/) || value == "")
		return false;

	return true;
}


function IsValidEmail(str)
{
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})+$/;

	return reg.test(str);
}


function IsValidPostalCode(str)
{
	//Format is "A1B 2C3" or A1B2C3"
	
	var reg = /^[A-Za-z][0-9][A-Za-z]([ ])?[0-9][A-Za-z][0-9]$/;

	return reg.test(str);
}

function IsValidPhoneNumber(str)
{
	/*
		Valid formats are:
		1231231234
		123-123-1234
		123-123-1234 12345 (extension)
		
	*/
	var reg = /^([0-9])+$/;
	
	if (str.length == 10 && reg.test(str))
		return true;
	else if (
		(str.length >= 12) &&
		(str.length <= 18) &&
		(str.charAt(3) == "-") &&
		(str.charAt(7) == "-") &&
		reg.test(str.substr(0,3)) &&
		reg.test(str.substr(4,3)) &&
		reg.test(str.substr(8,4))
	   )
	{
		if (str.length > 12)
		{
			if ((str.charAt(12) == " ") && reg.test(str.substr(13)))
				return true;
			else
				return false;
		}
		else
			return true;
	}
	else
		return false;
}

function IsValidCreditCardNumber(ccNumb)
{
	var valid 	= "0123456789"
	var len 	= ccNumb.length;
	var bNum 	= true;
	var iCCN 	= ccNumb;
	var sCCN 	= ccNumb.toString();
	var iCCN;
	var iTotal 	= 0;
	var bResult = false;
	var digit;
	var temp;
	iCCN = sCCN.replace (/^\s+|\s+$/g,'');
	
	for (var j=0; j<len; j++)
	{
		temp = "" + iCCN.substring(j, j+1);
		if (valid.indexOf(temp) == "-1")
			return false;
	}
	
	iCCN = parseInt(iCCN);
	
	if(len == 0)
		return false;
	else
	{
		if(len >= 15)
		{
			//15 or 16 for Amex or V/MC

			for(var i=len; i>0; i--)
			{
				digit = "digit" + i;

				calc = parseInt(iCCN) % 10;	//right most digit
				calc = parseInt(calc);
				iTotal += calc;
				i--;
				digit = "digit" + i;

				iCCN = iCCN / 10; 	// subtracts right most digit from ccNum
				calc = parseInt(iCCN) % 10 ;	// step 1 double every other digit
				calc2 = calc *2;

				switch(calc2)
				{
					case 10: calc2 = 1; break;	//5*2=10 & 1+0 = 1
					case 12: calc2 = 3; break;	//6*2=12 & 1+2 = 3
					case 14: calc2 = 5; break;	//7*2=14 & 1+4 = 5
					case 16: calc2 = 7; break;	//8*2=16 & 1+6 = 7
					case 18: calc2 = 9; break;	//9*2=18 & 1+8 = 9
					default: calc2 = calc2; 	//4*2= 8 &   8 = 8  -same for all lower numbers
				}
				
				iCCN = iCCN / 10; 	// subtracts right most digit from ccNum
				iTotal += calc2;
			}

			if ((iTotal%10)==0)
				return true;
			else
				return false;
		}
	}
}


function IsValidCVS(CVS)
{
	if (IsNumeric(CVS) && (CVS.length == 3 || CVS.length == 4))
		return true;
	else
		return false;
}


function IsValidDate(DateString, Format)
{
	var Day		= "";
	var Month	= "";
	var Year	= "";

	switch(Format)
	{
		case 'DD MMM YYYY':
			//10 Nov 2010
			if (DateString.length != 11)
				return false;
			Day	= DateString.substr(0, 2);
			Month	= MonthsArrayShort.indexOf(DateString.substr(3, 3));
			Year	= DateString.substr(7, 4);
		default:
			break;
	}

	var TempDate = new Date(Year, Month-1, Day);

	if ((Year == TempDate.getFullYear()) && (Month == TempDate.getMonth()+1) && (Day == TempDate.getDate()))
		return true;
	else
		return false	
}


/* ****************************** EVENTS ****************************** */


function SetOnClick(object, action)
{
	SetEvent('onclick', object, action);
}


function SetOnDoubleClick(object, action)
{
	SetEvent('ondblclick', object, action);
}


function SetEvent(MyEvent, object, action)
{
	switch(MyEvent)
	{
		case 'onclick':
			if (IsIE())
				object.onclick = new Function(action);
			else
				object.setAttribute('onclick',action);
			break;
		case 'ondblclick':
			if (IsIE())
				object.ondblclick = new Function(action);
			else
				object.setAttribute('ondblclick',action);
			break;
		case 'onmouseover':
			if (IsIE())
				object.onmouseover = new Function(action);
			else
				object.setAttribute('onmouseover',action);
			break;
		case 'onmouseout':
			if (IsIE())
				object.onmouseout = new Function(action);
			else
				object.setAttribute('onmouseout',action);
			break;
		case 'onkeyup':
			if (IsIE())
				object.onkeyup = new Function(action);
			else
				object.setAttribute('onkeyup',action);
			break;
		default:
			alert("Library Error 512: Unknown event ["+MyEvent+"]");
			break;
	}
}


function AddLoadEvent(func)
{
	var OldOnLoad = window.onload;
	
	if (typeof window.onload == 'function')
	{
		window.onload = function()
		{
			if (OldOnLoad)
				OldOnLoad();

			func();
		}
	}
	else
	{
		window.onload = func;
	}
}


/* ****************************** FORM ****************************** */


function GetRadioSelectedValue(FormRadioGroup)
{
	for(var i = 0; i < FormRadioGroup.length; i++)
	{
		if(FormRadioGroup[i].checked == true)
			return FormRadioGroup[i].value;
	}

	return "";
}


function SetRadioSelectedValue(FormRadioGroup, Value)
{
	for(var i = 0; i < FormRadioGroup.length; i++)
	{
		if(FormRadioGroup[i].value == Value)
		{
			FormRadioGroup[i].checked = true;
			return;
		}
	}
}


function SetDropdownValue(DropDownObject, Value)
{
	Value = ("" + Value);
	
	for(var i = 0; i < DropDownObject.options.length; i++)
	{
		if (DropDownObject.options[i].value.toUpperCase() == Value.toUpperCase())
		{
			DropDownObject.options[i].selected = true;
			return true;
		}
	}
	return false;
}


function SetCheckboxValue(CheckboxObject, Value)
{
	if (Value == true || Value == 1 || (typeof (Value) == "string" && Value.toUpperCase() == "YES"))
		CheckboxObject.checked = true;
	else
		CheckboxObject.checked = false;
}


function ChangeText(MyElem, MyText)
{
	if (MyElem.value == MyText)
		MyElem.value = "";
	else if (MyElem.value == "")
		MyElem.value = MyText;
}


/* ****************************** STYLE ****************************** */


function AddClass(elem, ClassName)
{
	//if its already in there, do nothing
	if (elem.className.indexOf(ClassName) > -1)
		return elem.className;
	
	var NewClass = elem.className;

	if (NewClass.length > 0)
		NewClass += " ";

	NewClass += ClassName;
	return NewClass;
}


function RemoveClass(elem, ClassName)
{
	if (elem.className)
		return elem.className.replace(ClassName, "");
	else
		return "";
}
