/* This is the common JavaScript files for the site */

/* If we are on an HTML page and using SSL, redirect to a non-SSL page */
if ((top.location.href.indexOf("https") >= 0) && (top.location.href.indexOf(".asp") == -1))
	{ top.location.replace(top.location.href.replace("https","http")); }

var onLoadCount = (window.onload) ? 1 : 0;
function addToWindowOnLoad(codeToAdd)
	{
	if (!(window.onload))
		{ window.onload = new Function("",codeToAdd); }
	else
		{
		eval("onLoadFunction"+onLoadCount+" = window.onload;");
		window.onload = new Function("","onLoadFunction"+onLoadCount+"(); "+codeToAdd);
		onLoadCount++;
		}
	}

/* This is for the random images in the header. Preload them, then load a random image */
var numberOfImages = 10;
for (var imageIndex = 1; imageIndex<=numberOfImages; imageIndex++)
	{
	var newImage = new Image();
	newImage.src = "/images/header/random_smheader_" + imageIndex + ".gif";
	}

function loadRandomHeader()
	{
	// Make sure that the image is defined
	if (typeof(document.headerImage) != 'undefined')
		{
		// Grab a random number to determine which image to display
		var randomImageIndex = Math.ceil(Math.random()*numberOfImages);
		var imageToLoad = new Image();
		imageToLoad.src = "/images/header/random_smheader_" + randomImageIndex  + ".gif";

		var imageToChange = document.headerImage;
	//	imageToLoad.height = "88px";
		imageToChange.height = imageToLoad.height;
		imageToChange.width = imageToLoad.width;
		imageToChange.src = imageToLoad.src;
		}
	else { window.status = '-'; }
	}

function returnError(messageToAlert)
	{
	alert(messageToAlert);
	return false;
	}
	
// Get the currently selected raio option
function getSelectedRadio(RadioToGet)
	{
	if (RadioToGet.length)
		{
		for (RadioIndex=0; RadioIndex<RadioToGet.length; RadioIndex++)
			if (RadioToGet[RadioIndex].checked)
				{ return RadioToGet[RadioIndex]; }
		}
	else if (RadioToGet.checked)
		{ return RadioToGet; }
	else { return false; }
	}
	
// Displays the current length of the input along with the maxlength if it can be determined
function showMaxLengthStatus(InputName)
	{
	if ( (typeof(InputName.getAttribute) != 'undefined') && (InputName.getAttribute("maxlength") > 0) )
		{
		window.status = InputName.value.length + "/" + InputName.getAttribute("maxlength") + " characters";
		checkMaxLength(InputName);
		}
	else
		{ window.status = InputName.value.length + " characters"; }
	}

// Compares the length of a string against it&#39;s maxlength
function checkMaxLength(InputName)
	{
	if ( (typeof(InputName.getAttribute) != 'undefined') && (InputName.getAttribute("maxlength") > 0) && (InputName.value.length > InputName.getAttribute("maxlength")) )
		{
		InputName.value = InputName.value.substring(0,InputName.getAttribute("maxlength"));
		showMaxLengthStatus(InputName);
		window.status = window.status + "  Maximum field length reached";
		}
	}

// *******************************************************************
// ** Allows a user to unCheck a radio element simply by clicking
// ** the radio again...
// *******************************************************************
function checkUncheckRadio(radioObject)
	{
	var FormName = radioObject.form;
	var RadioParentObject = (typeof(radioObject.length) != 'undefined') ? eval("FormName." + radioObject.name) : radioObject;
	
	// If the item that was previously checked is the same object that we are looking at, uncheck it and set the previouslyCheck to undefined
	if (RadioParentObject.getAttribute("previouslyChecked") == radioObject)
		{
		radioObject.checked = false;
		RadioParentObject.setAttribute("previouslyChecked","undefined");
		}
	// Otherwise, set the previouslyChecked attribute to the current option
	else
		{ RadioParentObject.setAttribute("previouslyChecked",radioObject); }
	}
	
// Trims a string
function trim(s) 
	{
	// Remove leading spaces and carriage returns
	while ((s.substring(0,1) == ' ') || (s.substring(0,1) == '\n') || (s.substring(0,1) == '\r'))
		{ s = s.substring(1,s.length); }
	
	// Remove trailing spaces and carriage returns
	while ((s.substring(s.length-1,s.length) == ' ') || (s.substring(s.length-1,s.length) == '\n') || (s.substring(s.length-1,s.length) == '\r'))
		{  s = s.substring(0,s.length-1); }
		
	return s;
	}

/******************************************************************
** Functions to help format numbers as floats and dollar amounts **
******************************************************************/
var isIntegerKey = "-0123456789";
var isFloatKey = "." + isIntegerKey;
var isIntegerValue = /(^-?\d\d*$)/;
var isFloatValue = /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;
	
function is_integer(this_number)
	{
	for (var char_index=0; char_index<this_number.length; char_index++)
		{
		if (parseInt(this_number.charAt(char_index)) != this_number.charAt(char_index))
			{ return false; }
		}
	return true;
	}

function is_float(this_number)
	{
	var float_array = this_number.split(".");
	
	if (float_array.length > 2) { return false; }
	else
		{
		for (var float_index=0; float_index<float_array.length; float_index++)
			if ( !(is_integer(float_array[float_index])) )
				{ return false; }
		}
	return true;
	}

function validateKey(inputObj,keySet,e)
	{
	var key;
	var keychar;

	// Get the event
	if (window.event)
	   { key = window.event.keyCode; }
	else if (e)
	   { key = e.which; }
	else
	   { return true; }
	keychar = String.fromCharCode(key);

	// Validate the key
	if ((keychar == ".") && (keySet == isFloatKey) && (inputObj.value.indexOf(".") > 0))
		{ return false; }
	else if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
	   { return true; }
	else
		{ return (keySet.indexOf(keychar) >= 0);  }
	}
	
// Days per month, ignore leap years
var DaysPerMonth = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var DaysPerMonthLeapYear = new Array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

// *******************************************************************
// ** The following 4 functions are all helpers of the checkDate function
// ** They simply check for a valid number that is between the
// ** appropriate contraints for a year, month, and day
// *******************************************************************
function valid_year(this_year)
	{
	// Check that the year is an integer
	return (is_integer(this_year));
	}

function valid_month(this_month)
	{
	// Check that the month is an integer, and is between 1 and 12
	return ( is_integer(this_month) && check_range(this_month,1,12) );
	}

function valid_day(this_day, this_month, this_year)
	{
	// Handle leap year
	daysThisMonth = ((this_year % 4) != 0) ? DaysPerMonth[this_month-1] : DaysPerMonthLeapYear[this_month-1];
	// Check that the day is an integer, and is between 1 and the number of days in that month
	return ( is_integer(this_day) && check_range(this_day,1,daysThisMonth) );
	}
	
function check_range(this_number, this_min, this_max)
	{
	return ( (parseInt(this_number * 1) >= this_min) && (parseInt(this_number * 1) <= this_max) )
	}

function check_date(This_Date)
	{
		// Check date for minimun characters and appropriate format
		if ( (This_Date.length >= 6) && (This_Date.indexOf('/') >= 0) && (This_Date.split('/').length == 3) )
			{
			var day = This_Date.split('/')[1];
			var month = This_Date.split('/')[0];
			var year = This_Date.split('/')[2];
			
			return ( valid_year(year) && valid_month(month) && valid_day(day,month,year) );
			}
		else
			{ return false; }
	}
	
	
// *******************************************************************
// ** Takes in a date and converts it to a number that JavaScript can
// ** compare. Since dates are not a JavaScript type, we return the
// ** date in a modified float value in the format years.(days/1000)
// *******************************************************************
function convert_date(date)
	{
	// Get values from MM/DD/YY
	var date_array = date.split('/');
	var months = parseInt(date_array[0] * 1);
	var days = parseInt(date_array[1] * 1);
	var years = parseInt(date_array[2] * 1);
	
	// Convert the date to a 4 digit year
	if (years < 50)
		{ years = 2000 + years; }
	else if (years < 1000)
		{ years = 1900 + years; }
	
	// Calc num days gone by
	for (var month_count = 0; month_count < (eval(months)-1); month_count++)
		days += parseInt(DaysPerMonth[month_count]);
	
	// Return (years.days) (a comparable number)
	return years + (days/365);
	}

// Validate US and Canadian zipcodes
function isValidZip(zip,country)
	{
	var regExp_US = /^\d{5}(-\d{4})?$/
	var regExp_CA = /^[a-zA-Z]\d[a-zA-Z] \d[a-zA-Z]\d$/i
	
	return (
		( ((country == null) || (country == 'US')) && (zip.search(regExp_US) == 0))
		|| ( ((country == null) || (country == 'CN')) && (zip.search(regExp_CA) == 0))
		);
	}

// -------------------------------------------------------------------
// TabNext()
// Function to auto-tab phone field
// Arguments:
//   obj :  The input object (this)
//   event: Either 'up' or 'down' depending on the keypress event
//   len  : Max length of field - tab when input reaches this length
//   next_field: input object to get focus after this one
// -------------------------------------------------------------------
var phone_field_length=0;
function TabNext(obj,event,len,next_field) {
	if (event == "down") {
		phone_field_length=obj.value.length;
		}
	else if (event == "up") {
		if (obj.value.length != phone_field_length) {
			phone_field_length=obj.value.length;
			if (phone_field_length == len) {
				next_field.focus();
				}
			}
		}
	}