/////////////////////////////////////////
/////////////////////////////////////////
// --------------------------------------
//	Author: Nick Licata
//	2011.01.10	-	initial version
// --------------------------------------
/////////////////////////////////////////
/////////////////////////////////////////

var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

var isW3C = (document.getElementById != null);
var isNN4 = (document.layers != null);
var isIE4 = (document.all != null);
var isNS6 = (!isIE4 && isW3C);

var whitespace = " \t\n\r";
var iKey;

$(document).ready(function(){	
	//childOnload();	
	getObj("template_footer").style.display = "";
	setTemplateFooter();
	
	// fix footer on resize	
	$(window).resize(function() {
		//alert("resize");
		setTemplateFooter();
	});

	// fix footer on scroll
	$(window).scroll(function () { 
		//alert("scroll");	
		setTemplateFooter();
	});	
	
	try{
		page_onLoad();
	}
	catch(e){
		// do nothing	
	}

});

function setTemplateFooter(){
	getObj("template_footer").style.position = "fixed";
	getObj("template_footer").style.width = "100%";
	getObj("template_footer").style.bottom = "0px"; 	
}

function menuToggleItems(id){
	for(i=0; i<items.length; i++){
		if(items[i] != id){
			tmpobj = getObj(items[i]);
			$(tmpobj).slideUp("slow");
		}
	}
	if(getObj(id).style.display == "none"){
		tmpobj = getObj(id);
		$(tmpobj).slideDown("slow");
	}
	else{
		tmpobj = getObj(id);
		$(tmpobj).slideUp("slow");
	}
}
	
/*
	STRING & FORMATTING FUNCTIONS
*/
function charInString(c, s) {
	for (i = 0; i < s.length; i++) {
		if (s.charAt(i) == c) return true;
	}
	return false	
}

function parseStringToAssocArray(string, iseparator, sseparator){
	var _data = Array();
	var data = Array();
	var tmparr = Array();
	try{
		_data = string.split(iseparator);
		for(i=0; i<_data.length; i++){
			tmparr = _data[i].split(sseparator);
			if(tmparr.length>0){
				//alert(tmparr[0] + "=" + tmparr[1]);
				data[tmparr[0]] = ((tmparr.length==2) ? tmparr[1] : "blank");
				//alert(data[tmparr[0]] + "=" + ((tmparr.length>1) ? tmparr[1] : "blank"));
			}
		}
	}
	catch(e){
		alert(e);
	}
	//for(x in data){
	//	alert(x + "  =  " + data[x]);
	//}
	return data;
}

function charFromCharCode(charCode){
	return unescape('%' + charCode.toString(16));
}

function ensureCharacterInPropertybag(sCharacter, sPropertybag) {
	if (sPropertybag.indexOf(sCharacter) == -1) {
		return false;
	}
	else{ 
		return true;
	}		
}

function isStringNumeric(string){
	var haserr = false;
	try{
		for(i=0; i<=string.length; i++){
			if(!charInBag(string.substr(i, 1), "0123456789")){
				haserr = true;	
			}
		}
	}
	catch(e){
		that.errors.push("[" + e + "]");
	}
	return !haserr;
}

function DupChar(srcCtl, dstCtl) {
    getObj(dstCtl).value = getObj(srcCtl).value;
    return true;
}

function charInBag(char, bag){
	try{
		if (bag.indexOf(char) == -1){
			return false;
		}
		else {
			return true;
		}
	}
	catch(e){
		return false;	
	}
}

function convertSeconds(SourceId, DisplayId){	
	try{
		var secs = new Number(getObj(SourceId).value);
		var hours = (secs/60/60);		
		var result = Math.round(hours*100)/100;		
		getObj(DisplayId).innerHTML = result;		
	}
	catch(e){
		getObj(DisplayId).innerHTML = e;
	}
}

function formatMoneyToNumber(strAmount) {
	// Remove all extra characters
	strAmount = replaceChars(strAmount,'$',''); // Remove '$'
	strAmount = replaceChars(strAmount,',',''); // Remove ','
	strAmount = replaceChars(strAmount,' ',''); // Remove ' '

	if ( strAmount.indexOf('.') != strAmount.lastIndexOf('.') ) // Make sure there aren't two decimals in number
	{ strAmount = strAmount.substring(0,strAmount.lastIndexOf('.')); }
	return strAmount;
}

function formatMoney(strAmount) {
	// Formats to $X,XXX.XX
	strAmount = '' + formatMoneyToNumber(strAmount);

	// Split up amount
	strDollar = '' + Math.floor(strAmount);
	nCents = 100 * (strAmount - strDollar) + 0.5;
	strTenth = '' + Math.floor(nCents/10);
	strHundreth = '' + Math.floor(nCents%10);

	// Add commas
	nCommas = Math.ceil((strDollar.length/3)-1); // Numbers of commas needed
	for (var nPlace = 1; nPlace < nCommas+1; nPlace++) {
		nLength = strDollar.length - nPlace + 1;
		nCommaPos = nLength - (3 * nPlace);
		strDollar = strDollar.substring(0,nCommaPos)+','+strDollar.substring(nCommaPos,strDollar.length);
	}

	// Put it all together
	strAmount = '$' + strDollar + '.' + strTenth + strHundreth;

	return strAmount;
}

function replaceChars(strOrig, strOut, strAdd) {
	strTemp = "" + strOrig;
	while (strTemp.indexOf(strOut)>-1) {
		nCharPos = strTemp.indexOf(strOut);
		strTemp = "" + (strTemp.substring(0, nCharPos) + strAdd + strTemp.substring((nCharPos+ strOut.length), trTemp.length));
	}
	return strTemp;
}

function stripInitialWhitespace (Name, v) {
   	var i = 0;

    while ((i < v.length) && charInString (v.charAt(i), whitespace))
       i++;
    
    Name.value = v.substring (i, v.length);
}

function LTrim(str) {
    var s = new String(str);

    if (whitespace.indexOf(s.charAt(0)) != -1) {
        // We have a string with leading blank(s)...

        var j=0, i = s.length;

        // Iterate from the far left of string until we
        // don't have any more whitespace...
        while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
            j++;

        // Get the substring from the first non-whitespace
        // character to the end of the string...
        s = s.substring(j, i);
    }

    return s;
}

function RTrim(str) {
    var s = new String(str);

    if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
		// We have a string with trailing blank(s)...

        var i = s.length - 1;       // Get length of string

        // Iterate from the far right of string until we
        // don't have any more whitespace...
        while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
            i--;

        // Get the substring from the front of the string to
        // where the last non-whitespace character is...
        s = s.substring(0, i+1);
    }

    return s;
}

function Trim(str) {
	return RTrim(LTrim(str));
}



/*
	DOM / FORMS / HTML
*/
function PrintDivContent(div, autoClose){
	var DocumentContainer = document.getElementById(div);
	var WindowObject = window.open("", "PrintWindow", "width=750,height=650,top=50,left=50,toolbars=no,scrollbars=yes,status=no,resizable=yes");
	WindowObject.document.writeln(DocumentContainer.innerHTML);
	WindowObject.document.close();
	WindowObject.focus();
	WindowObject.print();
	if(autoClose != 'undefined' && autoClose != null){
		WindowObject.close();
	}
}
			
function openWindow(lnk, titl, opts){	
	var url = lnk;	
	var wintitle = titl;
	var str = new String;
	str = "toolbar=" + opts['toolbar'] + ", ";
	str = str + "location=" + opts['location'] + ", ";	
	str = str + "directories=" + opts['directories'] + ", ";		
	str = str + "status=" + opts['status'] + ", ";
	str = str + "menubar=" + opts['menubar'] + ", ";
	str = str + "scrollbars=" + opts['scrollbars'] + ", ";
	str = str + "resizable=" + opts['resizable'] + ", ";
	str = str + "copyhistory=" + opts['copyhistory'] + ", ";
	str = str + "width=" + opts['width'] + ", ";
	str = str + "height=" + opts['height'];	
	var winopts = str;	
	/*
	var opts = new Array(9);
	opts['toolbar'] = 'no';
	opts['location'] = 'no';
	opts['directories'] = 'no';
	opts['status'] = 'yes';
	opts['menubar'] = 'no';
	opts['scrollbars'] = 'yes';
	opts['resizable'] = 'no';
	opts['copyhistory'] = 'no';
	opts['width'] = '600';
	opts['height'] = '400';
	*/
	window.open(url, wintitle, winopts);
}

function winClose(){
	window.close();
}

function printPage(){
	window.print();
}

function isMac() {
	// function determines if we're using a Mac..
	var agentString = navigator.userAgent.toLowerCase();
	if (agentString.indexOf('mac') != -1) {
		return true;
	} else {
		return false;
	}
}

//<input... onkeypress="return ensureCharInBag(event);">ensureInteger
function ensureCharInBag(e, sPropertybag) {
	if (isIE4) { iKey = window.event.keyCode; } else { iKey = e.which; }
	if ((iKey == 8) || (iKey == 0) || (iKey == 13)) { return true; }
	
	var sChar = charFromCharCode(iKey);
	return ensureCharacterInPropertybag(sChar, sPropertybag);
}

function ensureAlphaNumeric(e) {
	if (isIE4) { iKey = window.event.keyCode; } else { iKey = e.which; }
	if ((iKey == 8) || (iKey == 0) || (iKey == 13)) { return true; }
	
	var sChar = charFromCharCode(iKey);
	var sPropertybag = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	return ensureCharacterInPropertybag(sChar, sPropertybag);
}

function ensureAlpha(e){
	if (isIE4) { iKey = window.event.keyCode; } else { iKey = e.which; }
	if ((iKey == 8) || (iKey == 0) || (iKey == 13)) { return true; }
	
	var sChar = charFromCharCode(iKey);
	var sPropertybag = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	return ensureCharacterInPropertybag(sChar, sPropertybag);	
}

function ensureInteger(e) {
	if (isIE4) { iKey = window.event.keyCode; } else { iKey = e.which; }
	if ((iKey == 8) || (iKey == 0) || (iKey == 13)) { return true; }
	
	var sChar = charFromCharCode(iKey);
	var sPropertybag = "0123456789";
	return ensureCharacterInPropertybag(sChar, sPropertybag);
}

function ensureFloat(e) {
	if (isIE4) { iKey = window.event.keyCode; } else { iKey = e.which; }
	if ((iKey == 8) || (iKey == 0) || (iKey == 13)) { return true; }
	
	var sChar = charFromCharCode(iKey);
	var sPropertybag = ".0123456789";
	return ensureCharacterInPropertybag(sChar, sPropertybag);
}

function ensureEmailChar(e) {
	if (isIE4) { iKey = window.event.keyCode; } else { iKey = e.which; }
	if ((iKey == 8) || (iKey == 0) || (iKey == 13)) { return true; }
	
	var sChar = charFromCharCode(iKey);
	var sPropertybag = "-_@0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.";
	return ensureCharacterInPropertybag(sChar, sPropertybag);
}

function ensureNoKeypress(e) {
	return false;
}

function toggleObjectDisplay(obj1, obj2){
	try{
		if (getObj(obj1).style.display == 'none'){
			getObj(obj1).style.display = '';
			if(obj2 != null){
				getObj(obj2).style.display = 'none';
			}
		}
		else{
			getObj(obj1).style.display = 'none';
			if(obj2 != null){
				getObj(obj2).style.display = '';
			}
		}
	}
	catch(ex){
		
	}
}

function toggleLayer(name) {
	if (isW3C) {
		if (document.getElementById(name).style.display == 'none')
			document.getElementById(name).style.display = 'inline';
		else
			document.getElementById(name).style.display = 'none';
	} else if (isNN4) {
		// alert('NN4 toggle '+name+'('+document.layers[name].visibility +')');
		if (document.layers[name].visibility == 'hide')
			document.layers[name].visibility = 'visible';
		else
			document.layers[name].visibility = 'hidden';
	} else if (isIE4) {
		if (document.all.name.style.visibility == 'hidden')
			document.all.name.style.visibility = 'visible';
		else
			document.all.name.style.visibility = 'hidden';
	}
}

function showLayer(name) {
	if (isW3C) {
		document.getElementById(name).style.display = 'inline';
	} else if (isNN4) {
		document.layers[name].visibility = 'visible';
	} else if (isIE4) {
		document.all.name.style.visibility = 'visible';
	}
}
	
function hideLayer(name) {
	if (isW3C) {
		document.getElementById(name).style.display = 'none';
	} else if (isNN4) {
		document.layers[name].visibility = 'hidden';
	} else if (isIE4) {
		document.all.name.style.visibility = 'hidden';
	}
}
	
function getObj(id) {
	if (isW3C) {
		return document.getElementById(id);
	} else if (isIE4) {
		return document.all[id];
	} else if (isNN4) {
		return document.layers[id];
	}
}

function getStyle(id) {
	if (isW3C) {
		return document.getElementById(id).style;
	} else if (isIE4) {
		return document.all[id].style;
	} else if (isNN4) {
		return document.layers[id];
	}
}

function selectOption(element, value) {
	var i;
	for (i=0;i<element.options.length;i++) {
		if (element.options[i].value.toLowerCase() == value.toLowerCase()) {
			element.selectedIndex = i;
		}
	}
}

function setAllOptionsByControlType(id, value, type) {
	var i=0;
	var e;
	while ((e = getObj(type+id+'_'+i++)) != null ) {
		e.checked = ( value ? true : false );
	}
}

function setAllOptions(id, value) {
	var i=0;
	var e;
	while ( (e = getObj(id+'_'+i++)) != null ) {
		e.checked = ( value ? true : false );
	}
}

function selectedValue(element) {
	return element.options[element.selectedIndex].value
}

function getSelectedOption(id) {
	var a=null;
	var i=0;
	var e;
	while ( (e = getObj(id+'_'+i++)) != null ) {
		if ( e.checked ) {
			a = e.value;
			break;
		}
	}
	
	return a;
}

function toUpperCase(e) {
	// when called from a keypress event attached to an input tag, this function makes
	// the value of the input tag upper case, ensuring the data is entered that way.
	if (isIE4) {
		if (window.event.keyCode >= 97 && window.event.keyCode <=122)
			window.event.keyCode = window.event.keyCode - 32;			
	} else {
		e.target.value = e.target.value.toUpperCase();
	}
}
		
function toLowerCase(e) {
	// when called from a keypress event attached to an input tag, this function makes
	// the value of the input tag lower case, ensuring the data is entered that way.
	if (isIE4) {
		if (window.event.keyCode >= 65 && window.event.keyCode <=90)
			window.event.keyCode = window.event.keyCode + 32;				
	} else {
		e.target.value = e.target.value.toLowerCase();
	}
}

function capitilizeFormObjects(e) {
	// function iterates through all input tags and ensures values are entered
	// in the proper case.  This function is called onSubmit() for each form.
	var oCollection = document.getElementsByTagName("INPUT");
	var i;
	for (i=0;i<oCollection.length;i++) {
		// if our current element in our iteration is a text field that doesn't
		// have the word "email" in the id, we want to make it upper case.
		if ((oCollection[i].type.toLowerCase() == "text") && (oCollection[i].id.toLowerCase().indexOf("email") == -1)) {
			oCollection[i].value = oCollection[i].value.toUpperCase();
		} else if ((oCollection[i].type.toLowerCase() == "text") && (oCollection[i].id.toLowerCase().indexOf("email") != -1)) {
			oCollection[i].value = oCollection[i].value.toLowerCase();
		}
	}
}

function getParam(arg) {
	var q = new String(window.location.href);
	if(q.indexOf(arg) >= 0){
		var pntr = q.indexOf(arg) + arg.length + 1;
		if (q.indexOf("&", pntr) >= 0) {
			return q.substring(pntr, q.indexOf("&", pntr));
		} 
		else{
			return q.substring(pntr, q.length);
		}
	} 
	else{
		return null;
	}
}



/*
	COOKIES
*/
function createCookie(name, value, days) {
	if(days){
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name + "=" + value+expires + "; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	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;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}



/*
	GENERAL HELPER / WORKER FUNCTIONS
*/
function addToOutlookContacts(nam, comp, eml, ph){
	var err = 'false';		
	var lname = document.getElementById(nam).innerHTML;
	var fname = document.getElementById(nam).innerHTML;
	var midName = '';
	var company = document.getElementById(comp).innerHTML;
	var eml = document.getElementById(eml).innerHTML;
	var phone = document.getElementById(ph).innerHTML;	
	makeContact(lname, fname, midName, company, eml, phone);
}

function makeContact(lastName, firstName, midName, companyName, emailAddress, phoneNumber) {
	try{
		outlookApp = new ActiveXObject("Outlook.Application");
	}
	catch(E){
		var msg;
		msg = "This site can not add contacts to Outlook unless it is 'trusted' by your browser.\n" + 
			  "To mark this site as trusted go to TOOLS > INTERNET OPTIONS > SECURITY tab >\n" + 
			  "Highlight 'Trusted' sites at top > Click 'Sites' button > Uncheck checkbox at bottom >\n" + 
			  "Type qa.hamiltontampa.com in the text box > click the 'Add' button > Click the 'Close' button >\n" + 
			  "Lower security level slide bar to 'Low' > Click OK > Refresh this web page or restart the browser.\n" + 
			  "These steps are only required once.\n\n" + 
			  "You must answer YES to requests for ActiveX Controls.\n\n" + 
			  "You will not be able to add contacts until these steps are completed.\n" + 
			  "Never add a non-hamilton website to your trusted sites list.\n\n" + 
			  "If there are any questions please see your network administrator.";
		alert(msg);
		return;
	}
	nameSpace = outlookApp.getNameSpace("MAPI"); 
	contactFolder = nameSpace.getDefaultFolder(10); 
	contactItem = contactFolder.Items.add("IPM.Contact"); 
	contactItem.LastName = lastName; 
	contactItem.FirstName = firstName; 
	contactItem.MiddleName = midName; 
	contactItem.CompanyName = companyName; 
	contactItem.Email1Address = emailAddress; 
	contactItem.BusinessTelephoneNumber = phoneNumber;
	contactItem.Categories = 'GAL'; 
	contactItem.Display(false);  // true = modal
}

function xmod(subpg, addparams){  
	var res = new String();
	var xmlHttp;
  	try{
		xmlHttp=new XMLHttpRequest();
	}  
  	catch (e){
	  	try{  
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e){      
			try{
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
		  	catch (e){
				alert("Your browser does not support AJAX!");
				return false;
			}
		}
	}
	xmlHttp.onreadystatechange=function(){
		if(xmlHttp.readyState==4){
			// RETURN IS TEXT - CHANGE BELOW FOR XML
			res = xmlHttp.responseText;
			// UNCOMMENT BELOW FOR REG EXP FILTERING
			/*
			res = res.replace(/\r/g, "");
			res = res.replace(/[^ A-Za-z0-9`~!@#\$%\^&\*\(\)-_=\+\\\|\]\[\}\{'";:\?\/\.>,<]/g, "");
			res = res.replace(/'/g, "");
			res = res.replace(/ +/g, " ");
			res = res.replace(/^\s/g, "");
			res = res.replace(/\s$/g, ""); 
			*/
			// CHANGE XMODRESP TO YOUR CALL BACK FUNCTION OR MAKE 
			// SURE YOU HAVE SAME SIGNATURE FUNCTION NAMED XMODRESP
			eval("xmodresp(res, addparams)");
		}
	}	
	xmlHttp.open("GET", subpg, true);
	xmlHttp.send(null);	
}

function daysInMonth(month, year) {
	var lDate = new Date(year, month, 0);
	return lDate.getDate();
}

function isMod10(ccnum){		
	try{
		var total = new Number();
		var tmpcc_ = new String(ccnum);
		tmpcc_ = tmpcc_.replace("-", "");
		tmpcc_ = tmpcc_.replace(" ", "");
		var tmpcc = new String(tmpcc_);		
		if(tmpcc.length < 16){
			tmpcc = "0" + tmpcc;
		}
		if(tmpcc.length < 16){
			return false;
		}		
		atmp = tmpcc.split("");		
		for(i=0;i<atmp.length;i++){
			if((i%2) == 0){
				atmp[i] = (parseInt(atmp[i]) * 2);
			}
		}
		for(i=0;i<atmp.length;i++){
			tmp = new String(atmp[i]);			
			if(tmp.length > 1){
				atmp[i] = eval(tmp.substr(0,1)) + eval(tmp.substr(1,1));
			}			
		}		
		for(i=0;i<atmp.length;i++){
			total += eval(atmp[i]);
		}		
		if(total%10 == 0){
			return true;					
		}
		else{
			return false;	
		}
	}
	catch(e){
		return false;
	}
}

function maskCC(evt, obj){
	try{
		thiskey = evt.which;
		if ((thiskey != 8) && (thiskey != 0) && (thiskey != 13)) {
			var tmp = new String();
			tmp = getObj(obj).value;
			tmp = tmp.replace(/-/gi, "")
			switch(tmp.length){
				case 4:		
					getObj(obj).value = tmp + "-";
					break;
				case 8:
					getObj(obj).value = tmp.substr(0,4) + "-" + tmp.substr(4,4) + "-";
					break;
				case 12:
					getObj(obj).value = tmp.substr(0,4) + "-" + tmp.substr(4,4) + "-" + tmp.substr(8,4) + "-";
					break;
				default:
					// nothing
					break;
			}
		}			
	}
	catch(e){
		//alert(e);
	}		
}

function maskPhoneNumber(evt, obj){
	try{
		thiskey = evt.which;
		if ((thiskey != 8) && (thiskey != 0) && (thiskey != 13)) {
			var tmp = new String();
			tmp = getObj(obj).value;
			tmp = tmp.replace(/-/gi, "")
			switch(tmp.length){
				case 3:		
					getObj(obj).value = tmp + "-";
					break;
				case 6:
					getObj(obj).value = tmp.substr(0,3) + "-" + tmp.substr(3,3) + "-";
					break;
				case 7:
					getObj(obj).value = tmp.substr(0,3) + "-" + tmp.substr(3,4);
					break;
				case 10:
					getObj(obj).value = tmp.substr(0,3) + "-" + tmp.substr(3,3) + "-" + tmp.substr(6,4);
					break;
				default:
					// nothing
					break;
			}
		}			
	}
	catch(e){
		//alert(e);
	}		
}
