/*
FUNCTION: showHide														
																		
PARAMETERS:																
	elem																
		- string: the ID of the object to show or hide					
	bt																	
		- string: the ID of the button element that called this function
	swap																
		- array: the show/hide values									
	displayType															
		- array: the display style for show/hide						
*/
function showHide(elem, bt, swap, displayType) {
	var btCalledFrom							= document.getElementById(bt).tagName;
	var arrayNum;
	
	if (document.getElementById(elem).style.display == 'none') {
		arrayNum								= 0;
	} else {
		arrayNum								= 1;
	}
	
	if (btCalledFrom.toLowerCase() == 'a') {
		document.getElementById(bt).innerHTML	= swap[arrayNum];
	} else if (btCalledFrom.toLowerCase() == 'img') {
		document.getElementById(bt).src			= swap[arrayNum];
	}
		
	document.getElementById(elem).style.display = displayType[arrayNum];
}
/*
FUNCTION: generatePassword										
																
PARAMETERS:														
	formName													
		- string: the name of the form							
	formField													
		- string: the name of the field which gets the password	
	len															
		- numeric: the size of the password						
*/
function generatePassword(formName, formField, len) {
	if (len == null || len == '') {
		var length		= 8;
	} else {
		var length		= len;
	}
	
	var sPassword		= '';
	
	var noPunction		= true;
	var randomLength	= false;
	
	if (parseInt(navigator.appVersion) <= 3) {
		alert('Sorry this only works in 4.0+ browsers');
		return true;
	}
	
	if (randomLength) {
		length = Math.random();
	
		length = parseInt(length * 100);
		length = (length % 7) + 6;
	}

	for (i = 0; i < length; i++) {
		numI			= getRandomNum();
		if (noPunction) { 
			while (checkPunc(numI)) { 
				numI	= getRandomNum();
			}
		}
		sPassword		= sPassword + String.fromCharCode(numI);
	}
	
	document.forms[formName].elements[formField].value = sPassword;
	return true;
}
/*
FUNCTION: getRandomNum	
						
PARAMETERS: none		
*/
function getRandomNum() {
	var rndNum = Math.random();
	
	rndNum = parseInt(rndNum * 1000);
	
	rndNum = (rndNum % 94) + 33;
	return rndNum;
}
/*
FUNCTION: checkPunc							
											
PARAMETERS:									
	num										
		- number: the ascii number to check	
*/
function checkPunc(num) {
	if ((num >= 33) && (num <= 47)) {
		return true;
	}
	if ((num >= 58) && (num <= 64)) {
		return true;
	}
	if ((num >= 91) && (num <= 96)) {
		return true;
	}
	if ((num >= 123) && (num <= 126)) {
		return true;
	}
	return false;
}
/*
FUNCTION: newWindow									
													
PARAMETERS:											
	page											
		- string: the page (url) to load			
	name											
		- string: the name of the new window		
	w												
		- number: the width of the new window		
	h												
		- number: the height of the new window		
	props											
		- string: the properties of the new window	
*/
function newWindow(page, name, w, h, props) {
	var winL	= (screen.width - w) / 2;
	var winT	= (screen.height - h) / 2;
	winProps	= 'height=' + h + ',width=' + w + ',top=' + winT + ',left=' + winL + props;
	win			= window.open(page, name, winProps);
	
	if (parseInt(navigator.appVersion) >= 4) {
		win.window.focus();
	}
}
/*
FUNCTION: hasSpecChar				
									
PARAMETERS:							
	sourceString					
		- string: the text to check	
*/
function hasSpecChar(sourceString) {
	specChars = '<>%*#';
	for (i = 0; i < sourceString.length; i++) {
		for (j = 0; j < specChars.length; j++) {
			if (sourceString.indexOf(specChars.charAt(j)) != -1) {
				return true;
				break;
			}
		}
	}
	return false;
}
/*
FUNCTION: stripNonNumeric								
														
PARAMETERS:												
	sourceString										
		- string: text to strip all non numeric chars	
*/
function stripNonNumeric(sourceString) {
	var i;
	var returnString	= '';
	var numeric			= '0123456789';
	for (i = 0; i < sourceString.length; i++) {
		var c			= sourceString.charAt(i);
		if (numeric.indexOf(c) != -1) {
			returnString += c;
		}
	}
	
	return returnString;
}
/*
FUNCTION: applyMask											
															
PARAMETERS:													
	theField												
		- string: the name of the text field to apply mask	
	mask													
		- string: how to mask the text field				
	domestic (not used)										
		- yes:												
		- no:												
	type													
		- alphamsk: strips all non numeric chars from text	
*/
function applyMask(theField, mask, domestic, type) {
	var mi;
	var si				= 0;
	var returnString	= '';
	
	if (type != 'alphamask') {
		var string		= stripNonNumeric(theField.value);
	} else {
		var string		= theField.value;
	}
	
	for (mi = 0; mi < mask.length && si < string.length; mi++) {
		var mc			= mask.charAt(mi);
		var sc			= string.charAt(si);
		
		if (mc != "#") {
			returnString += mc;
		} else {
			returnString += sc;
			si += 1 
		}
	}
	
	theField.value = returnString;
}
/*
FUNCTION: isEmail							
											
PARAMETERS:									
	sourceString							
		- string: the email address to check
*/
function isEmail(sourceString) {
	// make sure search function is available
	if(sourceString.search) {
		if (sourceString.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1) {
			return true;
		} else {
			return false;
		}
	} else {
		return true;
	}
}
/*
FUNCTION: isNumeric						
										
PARAMETERS:								
	sourceString						
		- string: the string to check	
*/
function isNumeric(sourceString) {
	var validChars		= '0123456789.';
	var isNumber		= true;
	var char;
	
	for (i = 0; i < sourceString.length && isNumber == true; i++) {
		char = sourceString.charAt(i); 
		if (validChars.indexOf(char) == -1) {
			isNumber	= false;
		}
	}
	
	return isNumber;
}
/*
FUNCTION: isURL						
									
PARAMETERS:							
	sourceString					
		- string: the URL to check	
*/
function isURL(sourceString) {
	if (sourceString.search) {
		if (sourceString.search(/^((http|https)\:\/\/)[a-zA-Z0-9\/-\/.]+\.[a-zA-Z]{2,3}(\S*)?$/) != -1) {
			return true;
		} else {
			return false;
		}
	} else {
		return true;
	}
}
/*
FUNCTION: checkdate										
														
PARAMETERS:												
	date												
		- string: the date to check in mm/dd/yyyy format
*/
function checkdate(date) {
	var validformat		= /^\d{1,2}\/\d{1,2}\/\d{2,4}$/; //Basic check for format validity
	
	if (!validformat.test(date)) {
		return false;
	} else {
		var monthField	= date.split('/')[0];
		var dayField	= date.split('/')[1];
		var yearField	= date.split('/')[2];
		var dayObj		= new Date(yearField, monthField - 1, dayField);
		
		if ((dayObj.getMonth() + 1 != monthField) || (dayObj.getDate() != dayField) || (dayObj.getFullYear() != yearField)) {
			return false;
		} else {
			return true;
		}
	}
}
/*
FUNCTION: changeWindowLocation						
													
PARAMETERS:											
	location										
		- string: the page to go to					
	newWin											
		- true: opens location a new browser window	
		- false: opens location in the same window	
*/
function changeWindowLocation(location, newWin) {
	if (newWin == null || newWin == '') {
		newWin	= false;
	}
	
	if (!newWin) {
		window.location					= location;
		
		if (window.event) {
			window.event.returnValue	= false;
		}
	} else {
		window.open(location);
	}
}
/*
FUNCTION: trimTextForDisplay							
														
PARAMETERS:												
	sourceString										
		- string: the string to trim					
	length												
		- numeric: the length trim by					
	ellipsisPlacement									
		- middle: put "..." in the middle of the string	
		- end: put "..." at the end of the string		
*/
function trimTextForDisplay(sourceString, length, ellipsisPlacement) {
	if (ellipsisPlacement == '' || ellipsisPlacement == null) {
		ellipsisPlacement	= 'end';
	}
	
	var leftOfEllipsis		= '';
	var rightOfEllipsis		= '';
	var trimCount			= Math.round(length/2)-3;
	var stringLength		= String(sourceString).length;
	
	if (stringLength > length) {
		if (ellipsisPlacement == 'middle') {
			leftOfEllipsis	= String(sourceString).substring(0, trimCount);
			rightOfEllipsis	= String(sourceString).substring(stringLength, stringLength - trimCount);
			
			return leftOfEllipsis + ' ... ' + rightOfEllipsis;
		} else if (ellipsisPlacement == 'end') {
			return String(sourceString).substring(0, length) + ' ...';
		}
	} else {
		return sourceString;
	}
}
/*
FUNCTION: showHideCFWindow															
																					
PARAMETERS: 																		
	action																			
		- show: Shows the window													
		- hide: Hides the window													
	windowName																		
		- string: The name of the window											
	additionalArgs																	
		- object: an object that contains multiple properties						
			- confirmClose: displays warning msg before close (if true)				
			- destroyWindow: completely destroys the window, doesn't just hide it	
*/
function showHideCFWindow(action, windowName, additionalArgs) {
	var confirmClose		= false;
	var destroyWindow		= false;
		
	if (typeof(additionalArgs) != 'undefined') {
		if (typeof(additionalArgs.confirmClose) != 'undefined') {
			confirmClose	= additionalArgs.confirmClose;
		}
	
		if (typeof(additionalArgs.destroyWindow) != 'undefined') {
			destroyWindow	= additionalArgs.destroyWindow;
		}
	}
	
	if (action == 'show') {
		ColdFusion.Window.show(windowName);
	} else if (action == 'hide') {
		if (confirmClose) {
			if (confirm('Are you sure you want to close this window?')) {
				ColdFusion.Window.hide(windowName);
			}
		} else {
			ColdFusion.Window.hide(windowName);
		}
		
		if (destroyWindow) {
			ColdFusion.Window.destroy(windowName, true);
		}
	}
}
/*
FUNCTION: createCFWindow						
												
PARAMETERS:										
	wName										
		- string: name of the window			
	wTitle										
		- string: title of the window			
	wURL										
		- string: location of the page to load	
	wResize										
		- true: window is resizable				
		- false: window is not resizable		
	wClose										
		- true: window is closable				
		- false: window is not closable			
	wHeight										
		- number: height of the window			
	wMinHeight									
		- number: min height of the window		
	wWidth										
		- number: width of the window			
	wMinWidth									
		- number: min width of the window		
	wModal										
		- true: window is modal					
		- false: window is not modal			
*/
function createCFWindow(wName, wTitle, wURL, wResize, wClose, wHeight, wMinHeight, wWidth, wMinWidth, wModal) {
	if (wResize) {
		ColdFusion.Window.create(wName, wTitle, wURL, {center:true,draggable:true,resizable:true,closable:wClose,height:wHeight,minheight:wMinHeight,width:wWidth,minwidth:wMinWidth,modal:wModal});
	} else {
		ColdFusion.Window.create(wName, wTitle, wURL, {center:true,draggable:true,resizable:false,closable:wClose,height:wHeight,width:wWidth,modal:wModal});
	}
}
/*
FUNCTION: addErr								
												
PARAMETERS:										
	e2add										
		- string: the text display of the error	
*/
function addErr(e2add) {
	nextIndex				= aryErrors.length;
	aryErrors[nextIndex]	= e2add;
}
/*
FUNCTION: hasNoErrors										
															
PARAMETERS:													
	displayErrorIn											
		- string: the place where the errors are displayed	
*/
function hasNoErrors(displayErrorIn) {
	if (typeof(displayErrorIn) == 'undefined' || displayErrorIn == null || displayErrorIn == '') {
		displayErrorIn	= 'alert';
	}
	
	var errString		= '';
	
	// if error msg being didsplayed is inline use jQuery to hide it
	if (displayErrorIn != 'alert') {
		// try and use jQuery to hide the inline error message container
		try {
			jQuery('#' + displayErrorIn).hide();
		// use basic DOM to hide the element if jQuery isn't defined
		} catch (e) {
			document.getElementById(displayErrorIn).style.display	= 'none';
		}
	}
	
	if (aryErrors.length > 0) {
		for (i = 0; i < aryErrors.length; i++) {
			errString	+= aryErrors[i] + '\n';
		}
		
		if (displayErrorIn == 'alert') {
			alert('The following errors were encountered:\n\n' + errString);
		} else {
			// try and use jQuery to display the error message to the user
			try {
				jQuery('#' + displayErrorIn).html(errString.replace(/\n/g, '<br />'));
				jQuery('#' + displayErrorIn).fadeIn();
			// use basic DOM to show the message if jQuery isn't defined
			} catch (e) {
				document.getElementById(displayErrorIn).innerHTML		= errString.replace(/\n/g, '<br />');
				document.getElementById(displayErrorIn).style.display	= 'inline';
			}
		
			// try and resize modal box this prevents any errors if modalbox isn't defined
			try {
				Modalbox.resizeToContent();
			} catch(e) {
				// do nothing
			}
		}
		
		return false;
	} else {
		return true;
	}
}
/*
FUNCTION: checkFormSubmission												
																			
PARAMETERS:																	
	formName																
		- string: the name of the form										
	oArgs																	
		- object: an object that contains multiple properties				
			- displayErrorIn: the place to display any error messages		
			- includeAddress: true; checks address, false; ingores address	
			- additionalChecks: a UDF to continue checking fields			
																			
DESCRIPTION:																
	Checks any form for proper validation									
*/
function checkFormSubmission(formName, oArgs) {
	aryErrors							= new Array();
	
	var frm								= document.forms[formName];
	var cityError						= '';
	var stateError						= '';
	var zipError						= '';
	
	var displayErrorIn					= 'alert';
	var checkAddress					= true;
	var additionalChecks;
	var submitTo						= 'self';
		
	if (typeof(oArgs) != 'undefined') {
		if (typeof(oArgs.displayErrorIn) != 'undefined') {
			displayErrorIn				= oArgs.displayErrorIn;
		}
	
		if (typeof(oArgs.additionalChecks) != 'undefined') {
			additionalChecks			= oArgs.additionalChecks;
		}
	
		if (typeof(oArgs.checkAddress) != 'undefined') {
			checkAddress				= oArgs.checkAddress;
		}
		
		if (typeof(oArgs.submitTo) != 'undefined') {
			submitTo					= oArgs.submitTo;
		}
	}
	
	// check first name
	if (typeof(frm.firstname) != 'undefined') {
		if (frm.firstname.value == '') {
			addErr('First Name is missing.');
		}
	}
	
	// check last name
	if (typeof(frm.lastname) != 'undefined') {
		if (frm.lastname.value == '') {
			addErr('Last Name is missing.');
		}
	}
	
	// check email address
	if (typeof(frm.email) != 'undefined') {
		if (frm.email.value == '') {
			addErr('Email is missing.');
		} else {
			if (hasSpecChar(frm.email.value)) {
				addErr('Email contains illegal characters.');
			} else {
				if(!isEmail(frm.email.value)) {
					addErr('Email is invalid.');
				}
			}
		}
	}
	
	// check phone
	if (typeof(frm.phone) != 'undefined') {
		if (frm.phone.value == '') {
			addErr('Phone is missing.');
		}
	}
	
	// only check the address if requested to
	if (checkAddress) {
		// check address
		if (typeof(frm.address) != 'undefined') {
			if (frm.address.value == '') {
				addErr('Address is missing.');
			}
		}
		
		// check city
		if (typeof(frm.city) != 'undefined') {
			if (frm.city.value == '') {
				cityError	= 'City is missing.';
			}
		}
		
		// check state
		if (typeof(frm.state) != 'undefined') {
			if (frm.state.value == '') {
				stateError	= 'State/Province is missing.';
			}
		}
		
		// check zip
		if (typeof(frm.zip) != 'undefined') {
			if (frm.zip.value == '') {
				zipError	= 'Zip is missing.';
			}
		}
		
		// check country
		if (typeof(frm.country) != 'undefined') {
			if (frm.country.options[frm.country.selectedIndex].value == 'United States') {
				if (cityError != '') {
					addErr(cityError);
				}
				
				if (stateError != '') {
					addErr(stateError);
				}
				
				if (zipError != '') {
					addErr(zipError);
				}
			} else if (frm.country.options[frm.country.selectedIndex].value == 'Canada') {
				if (stateError != '') {
					addErr(stateError);
				}
				
				if (zipError != '') {
					addErr(zipError);
				}
			} else {
				if (cityError != '') {
					addErr(cityError);
				}
			}
		}
	}
		
	// if additional checks are needed
	// run the following code which
	// calls a user defined function
	if (typeof(additionalChecks) == 'function') {
		additionalChecks(formName);
	}
	
	// check captcha field
	if (typeof(frm.captchaplain) != 'undefined') {
		if (frm.captchaplain.value == '') {
			addErr('Security Code is missing.');
		}
	}
	
	// checks to see if there are any errors
	if (hasNoErrors(displayErrorIn)) {
		if (submitTo != 'self') {
			try {
				Modalbox.show(frm.action, {method: 'post', params: Form.serialize(formName)});
				return false;
			} catch (e) {
				return true;
			}
		}
	} else {
		return false;
	}
}
/*
FUNCTION: jQuery anonymous function 		
											
DESCRIPTION: append * to required label tags
											
PARAMETERS: none							
*/
try {
	jQuery(document).ready(function() {
		jQuery('form label.required').each(function() {
			jQuery(this).html('* ' + jQuery(this).html());
		});
	});
} catch (e) { /* do nothing */ }

/*
FUNCTION: convertURL							
												
PARAMETERS:										
	selector									
		- string: what dom element to search in	
*/
function convertURL(selector) {  
	//var regexp = /(www.[a-zA-Z0-9]*.[a-z]*)/gi;
	
	var regexp = /(www.[a-zA-Z0-9]*.[a-zA-Z]{2,3}\S*\w)/gi;
	
	jQuery(selector).not('.exclude').each(function() {
		jQuery(this).html(
			jQuery(this).html().replace(regexp, '<a href="http://$1" target="_blank">$1</a>')
		);
	});
	
	return jQuery(this);
};
/*
FUNCTION: convertEmail							
												
PARAMETERS:										
	selector									
		- string: what dom element to search in	
*/
function convertEmail(selector) {  
	var regexp = /([A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4})/gi;
		
	jQuery(selector).each(function() {
		jQuery(this).html(
			jQuery(this).html().replace(regexp, '<a href="mailto:$1">$1</a>')
		);
	});
	
	return $(this);
}
/*
FUNCTION: socialShare									
														
PARAMETERS:												
	whatNetwork											
		- string: the name of the network to share on	
*/
function socialShare(whatNetwork) {
	var netwindow,url;
	
	var currentURL	= encodeURIComponent(document.location.href);
	var title		= encodeURIComponent(document.title);
	
	switch(whatNetwork) {
		case 'twitter':
			url		= 'http://twitter.com/home?status=Looking at: ' + currentURL;
		break;
		
		case 'facebook':
			url		= 'http://www.facebook.com/sharer.php?u=' + currentURL + '&t='  + title;
		break;
		
		case 'delicious':
			url		= 'http://del.icio.us/post?url='+ currentURL + '&title=' + title;
		break;
		
		case 'diggit':
			url		= 'http://digg.com/submit?phase=2&url=' + currentURL;
		break;
		
		case 'linkedin':
			url		= 'http://www.linkedin.com/shareArticle?mini=true&url=' + currentURL + '&title=' + title + '&source=' + currentURL + '&summary=';
		break;

		case 'stumbleupon':
			url		= 'http://www.stumbleupon.com/submit?url=' + currentURL + '&title=' + title;
		break;
	}
	
	netwindow		= window.open(url, 'sharer', 'toolbar=0, status=0, scrollbars=1, width=626, height=436');
}
