﻿//****************Base Functions************************************************
function addWindowOnload(func)
{
	if (typeof window.onload == 'function')
	{
		var oldFunc = window.onload;
		window.onload = function() { oldFunc(); func(); }
	}
	else
	{
		window.onload = func;
	}
}

function addTxtboxOnFocus(obj, func)
{
	if (typeof obj.onfocus == 'function')
	{
		var oldFunc = obj.onfocus;
		obj.onfocus = function() { oldFunc(); func.call(obj); }
	}
	else
	{
		obj.onfocus = func;
	}
}

function addTxtboxOnBlur(obj, func)
{
	if (typeof obj.onblur == 'function')
	{
		var oldFunc = obj.onblur;
		obj.onblur = function() { oldFunc(); func.call(obj); }
	}
	else
	{
		obj.onblur = func;
	}
}

function onTxtBoxEnterCallback(e, callback)
{
	var key;

	if (window.event)
	{
		key = window.event.keyCode;
	}
	else
	{
		key = e.which;
	}

	if (key == 13)
	{
		if (typeof (callback) == 'function')
		{
			callback();
		}
		return false;
	}
	else
	{
		return true;
	}
}

function $(id)
{
	return document.getElementById(id);
}

function setFieldValue(obj, val)
{
	if (obj)
	{
		obj.value = val;
	}
}
//******************************************************************************

//**************Array functions**************************************************
function contains(a, obj, isCaseSensitive)
{
	var i = a.length;
	while (i--)
	{
		if (isCaseSensitive)
		{
			if (a[i] === obj)
			{
				return true;
			}
		}
		else
		{
			if (a[i].toLowerCase() === obj.toLowerCase())
			{
				return true;
			}
		}
	}
	return false;
}
//******************************************************************************

//**************Node functions**************************************************
function next(elem)
{
	do
	{
		elem = elem.nextSibling;
	} while (elem && elem.nodeType != 1);
	return elem;
}

function prev(elem)
{
	do
	{
		elem = elem.previousSibling;
	} while (elem && elem.nodeType != 1);
	return elem;
}

//function parent(elem)
//{
//	do
//	{
//		elem = elem.parentNode;
//	} while (elem && elem.nodeType != 1);
//	return elem;
//}

//returns the parent node of the element
function getParentNode(elem)
{
	do
	{
		elem = elem.parentNode;
	} while (elem && elem.nodeType != 1);
	return elem;
}

function removeChildren(elem)
{
	while (elem.firstChild)
	{
		elem.removeChild(elem.firstChild);
	}
}

//******************************************************************************

//**************Validation******************************************************
function isBlank(str)
{
	var blankCheck = /^ *$/;
	return blankCheck.test(str);
}

function isNumber(str)
{
	return !isNaN(str);
}

function isEmail(str)
{
	var emailReg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	return emailReg.test(str);
}

function isZipOrPostalCode(str)
{
	var regexObj = {
		canada: /^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ]( )?\d[ABCEGHJKLMNPRSTVWXYZ]\d$/i, //i for case-insensitive
		usa: /^\d{5}(-\d{4})?$/
	}
	var regexpUSA = new RegExp(regexObj.usa);
	var regexpCAN = new RegExp(regexObj.canada);
	return regexpUSA.test(str) || regexpCAN.test(str);

}

// The specified string only contains "number characters", ex. -234.90, 0045432, 435-34543
function isNumberCharacters(str)
{
    var numberCharactersRegEx = /^(\d|\.|\-)+/;
    return numberCharactersRegEx.test(str);
}

//*******************************************************************************


//*******************Numeric String formatting functions*************************
function getNumber(str)
{
	var retVal = 0;
	var isNumber = !isNaN(str);
	if (isNumber)
	{
		retVal = str * 1;
	}
	return retVal;
}

function padZero(num, count)
{
	var zeroes = 2;
	if (count)
	{
		zeroes = count;
	}
	var str = '';
	for (var i = 0; i < zeroes; i++)
	{
		str += '0';
	}

	var retVal = str + num;
	retVal = retVal.substring(retVal.length - zeroes);
	return retVal;
}
// Remove the leading zero from a number if present
function removeLeadingZero(num)
{
	var numStr = num.toString();
	if (numStr != null && numStr.charAt(0) == '0')
	{
		var newLength = numStr.length - 1;
		return numStr.substr(1, newLength);
	}
	else
	{
		return num;
	}
}
//******************************************************************************

//********Drop Down Functions***************************************************
function getDDValue(dd)
{
	var index = dd.selectedIndex;
	if (index >= 0)
		return dd.options[index].value;
	else
		return "";
}

function setDDValue(dd, value)
{
	for (index = 0; index < dd.length; index++)
	{
		if (dd[index].value == value)
		{
			dd.selectedIndex = index;
			return;
		}
	}
}

function getDDText(dd)
{
	return dd.options[dd.selectedIndex].text;
}

function addDDOption(dd, text, value)
{
	if (!value)
	{
		value = text;
	}
	dd.options[dd.options.length] = new Option(text, value);
}

//******************************************************************************


function areObjectsEqual(obj1, obj2)
{

	for (p in obj1)
	{
		if (typeof (obj2[p]) == 'undefined')
		{
			return false;
		}
	}

	for (p in obj1)
	{
		if (obj1[p])
		{
			switch (typeof (obj1[p]))
			{
				case 'object':
					if (areObjectsEqual(!obj1[p], obj2[p]))
					{
						return false;
					};
					break;
				case 'function':
					if (typeof (obj2[p]) == 'undefined' || (p != 'equals' && obj1[p].toString() != obj2[p].toString()))
					{
						return false;
					};
					break;
				default:
					if (obj1[p] != obj2[p])
					{
						return false;
					}
			}
		}
		else
		{
			if (obj2[p])
			{
				return false;
			}
		}
	}

	for (p in obj2)
	{
		if (typeof (obj1[p]) == 'undefined')
		{
			return false;
		}
	}

	return true;
}

//*****************String Trim functions****************************************
function trim(stringToTrim)
{
	return stringToTrim.replace(/^\s+|\s+$/g, "");
}
function ltrim(stringToTrim)
{
	return stringToTrim.replace(/^\s+/, "");
}
function rtrim(stringToTrim)
{
	return stringToTrim.replace(/\s+$/, "");
}

String.format = String.prototype.format = function()
{
	for (var i = 1; i < arguments.length; i++)
	{
		var exp = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
		arguments[0] = arguments[0].replace(exp, arguments[i]);
	}
	return arguments[0];
}
//******************************************************************************
//****************Blob formatting***********************************************
function BRToCRLF(sText)
{
	var newString = sText;

	newString = newString.replace(/<br \/>/g, "\n");
	newString = newString.replace(/<br\/>/g, "\n");
	newString = newString.replace(/<br>/g, "\n");

	return newString;
}

function CRLFToBR(text)
{
	text = escape(text);

	if (text.indexOf('%0D%0A') > -1)
		var re_nlchar = new RegExp(/%0D%0A/g);
	else if (text.indexOf('%0A') > -1)
		var re_nlchar = new RegExp(/%0A/g);
	else if (text.indexOf('%0D') > -1)
		var re_nlchar = new RegExp(/%0D/g);

	return unescape(text.replace(re_nlchar, '<br />'));
}
//******************************************************************************
//********************** URL Encoder and Decoder *******************************

function URLEncode(psEncodeString)
{
	return escape(psEncodeString);
}

function URLDecode(psEncodeString)
{
	// Create a regular expression to search all +s in the string
	var lsRegExp = /\+/g;
	// Return the decoded string
	return unescape(String(psEncodeString).replace(lsRegExp, " "));
}

/*EVENT HANDLER*/
var gbEvent = {
	addListener: function(el, type, func)
	{
		if (el.addEventListener)
		{
			el.addEventListener(type, function() { func.call(el) }, true);
		}
		else if (el.attachEvent)
		{
			el.attachEvent("on" + type, function() { func.call(el) });
		}
	},
	removeListener: function(el, type, func)
	{
		if (el.removeEventListener)
		{
			el.removeEventListener(type, function() { func.call(el) }, true);
		}
		else if (el.detachEvent)
		{
			el.detachEvent("on" + type, function() { func.call(el) });
		}
	},
	addListenerWithEvent: function(el, type, func)
	{
		if (el.addEventListener)
		{
			el.addEventListener(type, function(event) { return func.call(el, event) }, true);
		}
		else if (el.attachEvent)
		{
			el.attachEvent("on" + type, function(event) { return func.call(el, event) });
		}
	}
}

function cancelEvent(e)
{
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}


/* Keyboard event processing */
var getEvent = function(event) { var oEvent; window.event ? oEvent = window.event : oEvent = event; return oEvent }
var getKeycode = function(oEvent) { var iKey; oEvent.srcElement ? iKey = oEvent.keyCode : iKey = oEvent.which; return iKey }


//********************************************************************************
//********************** Social Media Related JS *********************************


fbInit = function(d, s, id, appId)
{
	var js, fjs = d.getElementsByTagName(s)[0];
	if (d.getElementById(id)) { return; }
	js = d.createElement(s); js.id = id;
	js.src = "https://connect.facebook.net/en_US/all.js#xfbml=1";
	if (appId != '')
		js.src += "&appId=" + appId;
	fjs.parentNode.insertBefore(js, fjs);
}
//fbInit(document, 'script', 'facebook-jssdk', '');

replaceSocialMediaButtons = function(divId, contentId)
{
	var div = document.getElementById(divId);
	var content = document.getElementById(contentId);
	if ((div) && (content))
	{
		div.innerHTML = URLDecode(content.value);
		content.value = '';
	}
}

renderSocialMedia = function(containerId)
{
	var container = $(containerId);
	if (container)
	{
		if ((FB) && (FB.XFBML))
			FB.XFBML.parse(container);

		if ((gapi) && (gapi.plusone))
			gapi.plusone.go(container);
	}
}




/* GLOBAL OPENSTORE CONTROL OBJECT STORAGE */

// A global object store for all instances of the JS object associated with the user controls
var __globalOpenStoreObjects = new Array();

// Return the existing object for the specified control client id, or null if no instance has been stored yet
function __getObjectByClientId(clientId)
{
	return __globalOpenStoreObjects[clientId];
}

// Set the object associated with the control with the specified client id
function __setObjectByClientId(clientId, object)
{
	__globalOpenStoreObjects[clientId] = object;
}

// Check the global object store ... if the specified object already exists, return it, otherwise create a new instance, and save it in the global object store
function getSingleton(type, clientId, options)
{
	var existingObject = __getObjectByClientId(clientId);
	if (existingObject)
	{
		return existingObject; // Reference the existing object
	}
	else
	{
		var newInstance = new type(clientId, options);
		__setObjectByClientId(clientId, newInstance); // Save this for future use
		return newInstance;
	}
}

/*** COOKIES ***/

// Set the specified cookie
function setCookie(cookieName, value, expireDays)
{
	var expireDate = new Date();
	expireDate.setDate(expireDate.getDate() + expireDays);
	var cookieValue = escape(value) + ((expireDays == null) ? "" : "; path=/; expires=" + expireDate.toUTCString());
	document.cookie = cookieName + "=" + cookieValue;
}

// Read the specified cookie
function getCookie(cookieName)
{
	var nameEQ = cookieName + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++)
	{
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	}
	return null;
}

// Delete the specified cookie
function deleteCookie(cookieName)
{
	var cookieDate = new Date();  // current date & time
	cookieDate.setTime(cookieDate.getTime() - 1);
	document.cookie = cookieName += "=; path=/; expires=" + cookieDate.toGMTString();
}

/*** END COOKIES ***/


/*** SHOW/HIDE ELEMENT ***/
function toggleDisplay(id, isVisible)
{
	var obj = $(id);
	if (obj)
	{
		obj.className = obj.className.replace('show', '').replace('hide', '');
		obj.className += (isBlank(obj.className) ? '' : ' ') + (isVisible ? 'show' : 'hide');
	}
}

function toggleVisibility(id, isVisible)
{
	var obj = $(id);
	if (obj)
	{
		obj.className = obj.className.replace('visible', '').replace('hidden', '');
		obj.className += (isBlank(obj.className) ? '' : ' ') + (isVisible ? 'visible' : 'hidden');
	}
}
/*** END SHOW/HIDE ELEMENT ***/


//********************************************************************************
//********************** Registers Namespace  *********************************
//********************** Used for Routing     *********************************

function _registerNamespace(ns)
{
	var nsParts = ns.split(".");
	var root = window;

	for (var i = 0; i < nsParts.length; i++)
	{
		if (typeof root[nsParts[i]] == "undefined")
			root[nsParts[i]] = new Object();

		root = root[nsParts[i]];
	}
}

function GetRoutingFriendlyParameterValue(value, mode, invalidChars)
{
	var result = (trim(value + '')).replace(/\s/gi, "_");

	while (result.charAt(result.length - 1) == ".")
		result = result.substr(0, result.length - 1)

	result = result.replace(/[^A-Za-z0-9,_.-]/gi, "");
	result = URLEncode(result);

	return result;
}

// Set the opacity of the specified DOM element in a cross-browser manner
function setElementOpacity(domElement, opacityBetween0And1)
{
	var domElementStyle = domElement.style;
	var opacityBetween0And1String = opacityBetween0And1.toString();
	domElementStyle.opacity = opacityBetween0And1String;
	domElementStyle.MozOpacity = opacityBetween0And1String;
	domElementStyle.KhtmlOpacity = opacityBetween0And1String;
	if (domElementStyle.filters) { domElementStyle.filters.alpha.opacity = opacityBetween0And1String; }
	domElementStyle.opacity = opacityBetween0And1String;
	domElementStyle.filter = 'alpha(opacity=' + (Math.round(opacityBetween0And1 * 100.0)).toString() + ')';
}

//returns embedded or linked css property of an element
function getStyle(id, styleProp)
{
	var result = '';
	var obj = $(id);
	if (obj)
	{
		if (obj.currentStyle)
		{
			if (styleProp.indexOf('-') > -1)
			{
				var stylePropArr = styleProp.split('-');
				var convertedProperty = '';
				if (stylePropArr)
				{
					for (var i = 0, l = stylePropArr.length; i < l; i++)
					{
						var word = stylePropArr[i];
						if (i > 0)
						{
							convertedProperty += word.substring(0, 1).toUpperCase() + word.substring(1);
						}
						else
						{
							convertedProperty += word;
						}
					}
					styleProp = convertedProperty;
				}
			}
			result = obj.currentStyle[styleProp];
		}
		else if (window.getComputedStyle)
		{
			result = document.defaultView.getComputedStyle(obj, null).getPropertyValue(styleProp);
		}
	}
	return result;
}

// Deserialize the specified JSON string, and return the appropriate object
function deserializeJsonString(jsonString)
{
    return (new Function( 'return(' + jsonString + ');' )) ();
}
