﻿

//-------------------------------------------------------------  ELEMENT MANPULATION  ----------------//

function swapFade(idToHide, idToShow)
{
	$("#" + idToHide).hide();
	$("#" + idToShow).fadeIn("fast");
}


//-------------------------------------------------------------  AJAX  ----------------//

if(typeof($) == 'function')
{
	function SendRequest(sPath, oArgs, fCallback)
	{
		try
		{
			$.get
			(
				sPath
				, oArgs
				, function(result) { fCallback(result); }
			);
		} catch (e) { throwException('SendRequest()', e.lineNumber, e, e.message); }
	}

	function PostRequest(sPath, oArgs, fCallback)
	{
		try
		{
			$.post
			(
				sPath
				, oArgs
				, function(result) { fCallback(result); }
			);
		} catch (e) { throwException('SendRequest()', e.lineNumber, e, e.message); }
	}
}

function GetContent(result, id, tagname)
{
	var div = document.createElement("DIV");
	div.innerHTML = result;

	var elelist = div.getElementsByTagName(tagname.toUpperCase());
	var html = "";
	for (var i = 0; i < elelist.length; i++)
	{
		if (elelist[i].id == id)
		{
			html = elelist[i].innerHTML;
		}
	}

	return html;
}

function GetElementById(result, id, tagname)
{
	var div = document.createElement("DIV");
	div.innerHTML = result;

	var elelist = div.getElementsByTagName(tagname.toUpperCase());
	var html = "";
	for (var i = 0; i < elelist.length; i++)
	{
		if (elelist[i].id == id)
		{
			html = elelist[i];
		}
	}

	return html;
}


/* ------------------------------ Formatting Functions ------------------------ */

function toCamelCase(str, firstCharLower)
{
	str = Trim(str);
	if(Contains(str, " "))
	{
		var words = str.split(" ");

		for(var i = 0; i < words.length; i++)
		{
			str = words[i].charAt(0).toUpperCase() + words[i].substring(1);
		}
	}
	else
	{
		str = str.charAt(0).toUpperCase() + (str.length > 1 ? str.substring(1) : "");
	}

	if(firstCharLower === true)
	{
		str = str.charAt(0).toLowerCase() + (str.length > 1 ? str.substring(1) : "");
	}

	return str;
}

function FormatPath(str)
{
	str = trimSlashes(str);
	
	if(str.indexOf("/") == -1) //no segments, so don't process
	{
		str = NameToFileName(str);
	}
	else
	{
		var segments = str.split("/");
		str = "";
		for(var i = 0; i < segments.length; i++)
		{
			str += "/" + NameToFileName(segments[i]);
		}
		str = trimSlashes(str) + "/";
	}
	
	return str;
}
function trimSlashes (str) {
	if(str == null || str == ""){ return "";}
	
	var	str = str.replace(/^\/\/*/, ''),
		ws = /\//,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
}


function HtmlDecode(str)
{
	var amp = new RegExp("&amp;", "g");

	str = str.replace(amp, "&");

	return str;
}

function EncodePath(path)
{
	path = Replace(path, "%20", " ");
	path = Replace(escape(path), "\\s|%20", "+");

	return path;
}

function NameToFileName(str)
{
	str = Trim(str).toLowerCase()

	str = str.replace(/\s|&#160;|&nbsp;/g, '-');
	str = str.replace(/&|&#38;|&#038;|&amp;/g, 'and');
	str = str.replace(/%|&#37;|&#037;/g, '-per-cent');
	str = str.replace(/_/, '-');

	str = str.replace(/[^\w+]/g, '-');

	str = str.replace(/[-+]+/g, '-');
	
	str = Trim("-"+str, "-");
	if(str.charAt(0) == "-"){ str = str.substring(1); }
	
	return str;
}

function EncodeQueryString(str)
{
	var fchar = "";
	if(str.charAt(0) == "?" || str.charAt(0)== "&")
	{
		fchar = str.charAt(0);
		str = str.substring(1);
	}

	var items = str.split("&");
	var qs = "";
	var item = "";
	for (var pair in items)
	{
		item = pair.split("=");
		item[1] = escape(item[1]);
		pair = item[0] + "=" + item[1];
		qs += "&" + pair;
	}
	
	qs = fchar + qs.subtring(1);
}

function TrimLeft(str)
{
	var trim = /^\s+/;
	if(arguments[1] != null){ trim = ""+RegExp(arguments[1] + "+", ""); }
	return str.replace(trim, '');
}
function TrimRight(str)
{	
	var trim = /\s+$/;
	if (arguments[1] != null) { trim = RegExp(arguments[1] + "+$", "g"); }
	return str.replace(trim, '');
}
function Trim(str)
{
	return TrimLeft(TrimRight(str, arguments[1]), arguments[1]);
}

function RemoveNonNumbers(str)
{
	if (str == null || str == "") { return ""; }

	return Replace(str, "[^0-9]", "");
}

function Replace(source, find, replacement)
{
	if (source == "" || find == "") { return source; }

	var re = new RegExp(find, "g");
	return source.replace(re, replacement);
}

function RemoveChildObjects(oSource)
{
	while(oSource.hasChildNodes())
	{
		oSource.removeChild(oSource.firstChild);
	}
}

function AbbreviateFileSize(num)
{
	if (isNaN(num)) { return num; }

	var moniker = "kb";

	if (num >= 1073741824)
	{
		num = num / 1073741824;
		moniker = "gb";
	}
	else if (num >= 1048576)
	{
		num = num / 1048576;
		moniker = "mb";
	}
	else
	{
		num = num / 1024;
	}

	num = num + "";
	if (num.indexOf(".") > -1)
	{
		num = num.substring(0, num.indexOf(".") + 2);
		if (num.charAt(num.length - 1) == "0")
		{
			num = num.substring(0, num.indexOf("."));
		}
	}

	return num + moniker
}

/* ------------------------------ LOCATION Functions ------------------------ */

function WebAddress()
{
	var loc = window.location;

	var findKey = function(p)
	{
		return new RegExp("[?&]" + p + "=(?:([^&]*))?", "i");
	}
	var multiAmp = new RegExp("[&+]+", "g");

	pub = 
	{
		AddQueryParam: function (key, value, qs)
		{
			if(!qs){qs = loc;}

			qs = this.StripQueryParam(key, qs);
			qs = key + "=" + value + "&" + (qs ? "&" + qs : "");
			qs = qs.replace("?", "").replace(multiAmp, "&");

			return qs;
		}
		, StripQueryParam: function (parameter, qs)
		{
			if(!qs){qs = loc;}
			qs - qs.replace("?", "");

			var p = escape(unescape(parameter));
			if (qs.indexOf(parameter + "=") == 0)
			{
				qs = qs.substring(qs.indexOf("&") + 1);
				return qs
			}

			qs = qs.replace((findKey(parameter)), "").replace(multiAmp, "&");
			if(qs.charAt(0) == "&"){ qs = qs.substring(1); }

			return qs;
		}
		, GetQueryParam: function (parameter, qs)
		{
			if(!qs){qs = loc;}
			qs = "&" + qs;
			var p = escape(unescape(parameter));

			var match = (findKey(p)).exec(qs);
			var value = "";
			if (match != null)
			{
				value = Trim(unescape(match[1]));
			}
			return value;
		}
	}

	return pub;
};
var Location = new WebAddress();

/* ------------------------------ Utility Functions ------------------------ */

function ValueToInt(value)
{
	var defVal = (arguments[1] && !isNaN(arguments[1]) ? parseInt(arguments[1]) : 0);

	if(typeof(value) == 'number'){ return value;}
	else if(typeof(value) == 'string')
	{
		value = value.replace(/^[0]+/g,"");
		value = RemoveNonNumbers(value);
		return (!value || isNaN(value)) ? defVal : parseInt(value);
	}
	else
	{
		return defVal;
	}

	/*if(value && !isNaN(value)){return value;}
	else
	{
		//value = RemoveNonNumbers(value);
		value = (!value || isNaN(value)) ? 0 : parseInt(value);
		return value;
	}*/
}

function GetRadioSelectedValue(containerID)
{
	var rval = "";
	var input = document.getElementById(containerID).getElementsByTagName("INPUT");
	for (var i = input.length - 1; i >= 0; i--)
	{
		if (input[i].type == "radio" && input[i].checked)
		{
			rval = input[i].value;
			break;
		}
	}
	return rval;
}

function SetRadioSelectedValue(containerID, value)
{
	var input = document.getElementById(containerID).getElementsByTagName("INPUT");	
	for (var i = input.length - 1; i >= 0; i--)
	{
		if (input[i].type == "radio" && input[i].value == value)
		{
			input[i].checked = true;
			break;
		}
	}
}

function GetSelectValues(oSelect)
{
	var valArr = [];
	if(!oSelect){return valArr;}
	for(var i = 0; i< oSelect.length; i++)
	{
		valArr.push(oSelect[i].value);
	}
	return valArr
}

function Contains(source, value)
{
	try
	{
		if(typeof(source) == 'string')
		{	//looking up a string in a string
			return (source.indexOf(value) > -1 ? true : false);
		}
		else if(typeof(source) == 'object' && typeof(value) == 'object')
		{	//object lookup: {key:value} contains {key:value}
			var lookup = null;
			for(key in value)
			{
				lookup = key;
			}

			if(lookup)
			{
				for(key in source)
				{
					if(key = lookup && source[key] == value[lookup])
					{
						return true;
					}
				}
			}
		}
		else if(typeof(source) == 'object' && (typeof(value) == 'string' || typeof(value) == 'number'))
		{	//object key lookup: {key:value} contains {key} (value is irrelevant)
			if(lookup)
			{
				for(key in source)
				{
					if(key = value)
					{
						return true;
					}
				}
			}
		}

	}
	catch (e)
	{
		throwException('/functions.js : Contains()', e.lineNumber, e, e.message);
	}

	return false;
}

function SetAttributes(oTarget, oAttr)
{
	if(oTarget && oAttr)
	{
		for(key in oAttr)
		{
			oTarget.setAttribute(key, oAttr[key]);
		}
	}
}

function FindControl(oSource, id)
{
	if ((oSource == null || oSource == "") || (id == null || id == "")) { return null; }
	
	var oObj = null;

	var html = (typeof (oSource) == "object")
		? oSource.innerHTML
		: oSource
	;


	var re = new RegExp("id=\"?[\\w]+", "g");
	var m = html.match(re);
	
	if (m != null)
	{
		var mid = "";
		var stpos = 4;
		for (var i = 0; i < m.length; i++)
		{

			if (m[i].indexOf('"') != -1)
			{
				stpos = m[i].indexOf('"') + 1;
			}
			else if (m[i].indexOf('=') != -1)
			{
				stpos = m[i].indexOf('=') + 1;
			}
			if (Contains(m[i], id))
			{
				mid = m[i].substring(stpos, m[i].length);
				oObj = document.getElementById(mid);
				break;
			}
		}
	}

	return oObj;
}

function FindFormField(name)
{
	var useid = (arguments[1] != null)
		? arguments[1]
		: true
	;
	
	var fct = document.forms[0].length;
	if (useid)
	{
		for (var i = fct - 1; i >= 0; i--)
		{
			if (Contains(document.forms[0][i].id, name))
			{
				return document.forms[0][i];
			}
		}
	}
	else
	{
		for (var i = fct - 1; i >= 0; i--)
		{
			if (Contains(document.forms[0][i].name, name))
			{
				return document.forms[0][i];
			}
		}
	}
}

function GetQueryParam(parameter, qs)
{
	qs = "&" + qs;
	var p = escape(unescape(parameter));
	var regex = new RegExp("[?&]" + p + "=(?:([^&]*))?", "i");

	var match = regex.exec(qs);
	var value = "";
	if (match != null)
	{
		value = match[1];
	}
	return value;
}

function ListProperties(obj)
{
	var obj_props = "";
	for (var i in obj)
	{
		if (arguments[1]) { var msg = arguments[1] + "." + i + " : " + obj[i]; } else { var msg = i + " : " + obj[i]; }
		obj_props += msg + "\n";

		if (typeof obj[i] == "object")
		{
			if (arguments[1]) { ListProperties(obj[i], parent + "." + i); } else { ListProperties(obj[i], i); }
		}
	}
	return obj_props;
}

function PathAndQuery(sPath, oQuery)
{
	var qs = "";
	for (var i in oQuery)
	{
		qs += "&" + i + "=" + oQuery[i];
	}
	return sPath + "?" + qs;
}


/* ------------------------------ Validation Functions ------------------------ */

function ValidObj(arg)
{
	if(arg == ""){ return false; }
	else if(arg == null){ return false; }
	else if(typeof(arg) == 'undefined'){ return false; }
	
	return true;
}

function ValidString(str)
{
	if(str == ""){ return false; }
	else if(str == null){ return false; }
	else if(typeof(str) == 'undefined'){ return false; }
	
	str = Trim(str);
	if(str == ""){ return false; }
	else{ return true; }
}

function ValidUSZipCode(str)
{
	return /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(str);
}

function ValidEmail(str)
{
	return /^([\w]+)(\.[\w]+)*@([\w\-]+)(\.[\w]{2,7})(\.[a-z]{2})?$/i.test(str);
}

function isValidDate(date_string, format) 
{
	var days = [0,31,28,31,30,31,30,31,31,30,31,30,31];
	var year, month, day, date_parts = null;
	var rtrn = false;
	var decisionTree = {
		'm/d/y':{
			're':/(\d{1,2})[./-](\d{1,2})[./-](\d{2}|\d{4})/,
			'exact':/^(\d{1,2})[./-](\d{1,2})[./-](\d{2}|\d{4})$/,
			'month': 1,'day': 2, year: 3
		},
		'mm/dd/yy':{
			're':/(\d{1,2})[./-](\d{1,2})[./-](\d{2})/,
			'exact':/^(\d{1,2})[./-](\d{1,2})[./-](\d{2})$/,
			'month': 1,'day': 2, year: 3
		},
		'mm/dd/yyyy':{
			're':/(\d{1,2})[./-](\d{1,2})[./-](\d{4})/,
			'exact':/^(\d{1,2})[./-](\d{1,2})[./-](\d{4})$/,
			'month': 1,'day': 2, year: 3
		},
		'y/m/d':{
			're':/(\d{2}|\d{4})[./-](\d{1,2})[./-](\d{1,2})/,
			'exact':/^(\d{2}|\d{4})[./-](\d{1,2})[./-](\d{1,2})$/,
			'month': 2,'day': 3, year: 1
		},
		'yy/mm/dd':{
			're':/(\d{1,2})[./-](\d{1,2})[./-](\d{1,2})/,
			'exact':/^(\d{1,2})[./-](\d{1,2})[./-](\d{1,2})$/,
			'month': 2,'day': 3, year: 1
		},
		'yyyy/mm/dd':{
			're':/(\d{4})[./-](\d{1,2})[./-](\d{1,2})/,
			'exact':/^(\d{4})[./-](\d{1,2})[./-](\d{1,2})$/,
			'month': 2,'day': 3, year: 1
		}
	};
	var test = decisionTree[format];
	if (test) 
	{
	
		var re = new RegExp(test.re);
		var m = re.exec(date_string);
		
		if(m != null)
		{
			date_string = m[0];
			date_parts = date_string.match(test.re);
			if (date_parts) {
				year = date_parts[test.year];
				month = date_parts[test.month];
				day = date_parts[test.day];

				test = (month == 2 && 
						isLeapYear() && 
						29 || 
						days[month] || 0);

				rtrn = 1 <= day && day <= test;
			}
		}
		
	}
	
	if(arguments[2] === true)
	{	//return date parts: mm/dd/yyy, mm, dd, yyyy
		return m;
	}
	else
	{
		return rtrn;
	}
	
}//eof isValidDate

function isLeapYear() {
	return (year % 4 != 0 ? false : 
		( year % 100 != 0? true: 
		( year % 1000 != 0? false : true)));
}

function InputCount(containerID, arrTagNames)
{
	var oContainer = document.getElementById(containerID);
	var sortByType = (arguments[2] != null)? arguments[2] : false;
	
	var input = null;
	var ct = [];
	for(var i = 0; i < arrTagNames.length; i++)
	{
		input = oContainer.getElementsByTagName(arrTagNames[i].toUpperCase());
		ct.push(input.length);
	}
	
	if(!sortByType)
	{
		var total = 0;
		for(var i = 0; i < arrTagNames.length; i++)
		{
			total += ct[i];
		}
		ct = total;
	}
	
	return ct; 
}


function validateForm(messageID, feedbackID)
{
	try
	{
		if(messageContainer = document.getElementById(messageID))
		{
			messageContainer.style.display = "none";
		}

		var oForm = document.forms[0];
		var oField = GetFieldToValidate(oForm);
		var valid = true;
		var validControl = true;

		for (var i = oField.length - 1; i >= 0; i--)
		{
			switch (oField[i].Validate)
			{
				case "notnull":
					validControl = ValidString(oField[i].value);
					break;
				case "phone3":
					var number = oField[i].value;
					if (isNaN(number))
					{
						validControl = false;
					}
					else if (number.length != oField[i].maxLength)
					{
						validControl = false;
					}
					break;
				case "email": validControl = ValidEmail(oField[i].value);
					break;
				case "zipcode": validControl = ValidUSZipCode(oField[i].value);
					break;
			}

			if (!validControl)
			{
				FlagError(oField[i]);
			}
			else
			{
				ResetErrorFlag(oField[i]);
			}

			if (!validControl) { valid = false; }
		}


		if(feedbackContainer = document.getElementById(feedbackID))
		{
			if (!valid)
			{
				feedbackContainer.style.display = "block";
			}
			else
			{
				feedbackContainer.style.display = "none";
			}
		}

		return valid;
	}
	catch (e)
	{
		throwException('validateForm()', e.lineNumber, e, e.message);
		return false;
	}
}

function FlagError(oControl)
{
	if(!Contains(oControl.className, "invalid"))
	{
		oControl.className += " invalid";
		oControl.setAttribute("title", oControl.Message);
		oControl.focus();
	}
}

function ResetErrorFlag(oControl)
{
	oControl.className = Trim(oControl.className.replace("invalid", ""));
	oControl.setAttribute("title", "");
}

function GetFieldToValidate(oForm)
{
	var field = [];

	for (var i = 0; i < oForm.length; i++)
	{
		if (oForm[i].getAttribute("validate") != null)
		{
			oForm[i].Validate = oForm[i].getAttribute("validate");
			oForm[i].Message = oForm[i].getAttribute("message");
			field.push(oForm[i]);
		}
	}

	return field;
}



function ArrayFunctions($, undefined)
{
	var pub = 
	{
		Contains: function(haystack, needle)
		{
			return (pub.Position(haystack, needle) > -1 ? true : false);
		}
		, Position: function(haystack, needle)
		{
			if(!haystack || !needle){ return -1; }

			if(typeof(haystack) == 'string')
			{
				return haystack.indexOf(needle);
			}
			else if(typeof(haystack) == 'object')
			{
				var pos = 0;
				var exists = false;
				for(obj in haystack)
				{
					if(haystack[obj] == needle)
					{
						exists = true;
						break;
					}
					pos++;
				}

				return (exists ? pos : -1);
			}
		}
		, LastIndex: function(array)
		{
			if(!array || array.length == 0){return -1;}
			return array[array.length -1];
		}
	};

	return pub;
}
var Collections = new ArrayFunctions(jQuery);


/* ------------------------------ popup window functions ------------------------ */

function FileLibrary(path, options, source, onWindowOpen, onWindowClose, undefined)
{
	var defaultOptions = 
	{
		location:"no"
		, menubar:"no"
		, toolbar:"no"
		, dependent:"yes"
		, minimizable:"no"
		, modal:"no"
		, alwaysRaised:"yes"
		, resizable:"yes"
		, scrollbars:"yes"
		, width:"80%"
		, height:"70%"
		, top:"0"
		, left:"0"
	};

	var pub = 
	{
		Source: ""
		, Path: ""
		, Options: {}
		, Window:
		{
			Document: null
			, Launch : function(path, argSource, onWindowOpen, onWindowClose)
			{
				Source = argSource;
				pub.Window.Document = popup("fileLibrary", path, 680, 500);

				pub.Window.Document.onOpen = (onWindowOpen)
					? onWindowOpen
					: pub.Window.OnClose
				;

				pub.Window.Document.onClose = (onWindowClose)
					? function(selectedElement){onWindowClose(selectedElement);pub.Window.Document = null;}
					: pub.Window.OnClose
				;
			}
			, OnOpen:null
			, OnClose:null
		}
		, SetCallBackFunctions: function(onWindowOpen, onWindowClose)
		{
			pub.Window.OnClose = function(selectedElement)
			{
				onWindowClose(selectedElement);
				pub.Window.Document = null;
			};
			pub.Window.OnOpen = onWindowOpen;
		}
	};

	/*
	if(options)
	{
		if(typeof(options) == 'string' || (typeof(options) == 'object' && typeof(options.length) != 'undefined')){ alert("'options' variable must be in JSON format"); }
		else{pub.Options = options;}
	}
	else
	{
		pub.Options = defaultOptions;
	}
	*/

	var popup = function (name, url, width, height, options)
	{
		width = width || '80%';
		height = height || '70%';

		if (typeof width == 'string' && width.length > 1 && width.substr(width.length - 1, 1) == '%')
			width = parseInt(window.screen.width * parseInt(width, 10) / 100, 10);

		if (typeof height == 'string' && height.length > 1 && height.substr(height.length - 1, 1) == '%')
			height = parseInt(window.screen.height * parseInt(height, 10) / 100, 10);

		if (width < 640)
			width = 640;

		if (height < 420)
			height = 420;

		var top = parseInt((window.screen.height - height) / 2, 10),
				left = parseInt((window.screen.width - width) / 2, 10);

		options = (options || 'location=no,menubar=no,toolbar=no,dependent=yes,minimizable=no,modal=yes,alwaysRaised=yes,resizable=yes,scrollbars=yes') +
				',width=' + width +
				',height=' + height +
				',top=' + top +
				',left=' + left;

		var popupWindow = window.open(name, null, options, true);


		// Blocked by a popup blocker.
		if (!popupWindow){ return false; };


		try
		{
			popupWindow.location.href = url;
			popupWindow.moveTo(left, top);
			popupWindow.resizeTo(width, height);
			popupWindow.focus();
		}
		catch (e)
		{
			popupWindow = window.open(url, null, options, true);
		}

		return popupWindow;
	}

	return pub;
}


/* ------------------------------ Error Handling Functions ------------------------ */

function throwException(file_name, line_num, ex, msg)
{

	var msg = "Error in FILE: " + file_name + " LINE: " + line_num + "\n\nTYPE: " + ex + "\n\n" + msg + "\n\n" + ex.stack;

	if (document.getElementById('error_div'))
	{
		document.getElementById('error_div').innerHTML = "<pre class=\"error\">" + msg + "</pre>";
	} 
	else
	{
		alert(msg);
	}

}
