/*
$Id: general.js,v 1.3 2003/02/10 22:30:55 hpdl Exp $
osCommerce, Open Source E-Commerce Solutions
http://www.oscommerce.com
Copyright (c) 2003 osCommerce
Released under the GNU General Public License
*/

function SetFocus(TargetFormName) {
	var target = 0;
	if (TargetFormName != "") {
		for (i=0; i<document.forms.length; i++) {
			if (document.forms[i].name == TargetFormName) {
				target = i;
				break;
			}
		}
	}

	var TargetForm = document.forms[target];

	for (i=0; i<TargetForm.length; i++) {
		if ( (TargetForm.elements[i].type != "image") && (TargetForm.elements[i].type != "hidden") && (TargetForm.elements[i].type != "reset") && (TargetForm.elements[i].type != "submit") ) {
			TargetForm.elements[i].focus();

			if ( (TargetForm.elements[i].type == "text") || (TargetForm.elements[i].type == "password") ) {
				TargetForm.elements[i].select();
			}

			break;
		}
	}
}

function RemoveFormatString(TargetElement, FormatString) {
	if (TargetElement.value == FormatString) {
		TargetElement.value = "";
	}

	TargetElement.select();
}

function CheckDateRange(from, to) {
	if (Date.parse(from.value) <= Date.parse(to.value)) {
		return true;
	} else {
		return false;
	}
}

function IsValidDate(DateToCheck, FormatString) {
	var strDateToCheck;
	var strDateToCheckArray;
	var strFormatArray;
	var strFormatString;
	var strDay;
	var strMonth;
	var strYear;
	var intday;
	var intMonth;
	var intYear;
	var intDateSeparatorIdx = -1;
	var intFormatSeparatorIdx = -1;
	var strSeparatorArray = new Array("-"," ","/",".");
	var strMonthArray = new Array("jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec");
	var intDaysArray = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

	strDateToCheck = DateToCheck.toLowerCase();
	strFormatString = FormatString.toLowerCase();

	if (strDateToCheck.length != strFormatString.length) {
		return false;
	}

	for (i=0; i<strSeparatorArray.length; i++) {
		if (strFormatString.indexOf(strSeparatorArray[i]) != -1) {
			intFormatSeparatorIdx = i;
			break;
		}
	}

	for (i=0; i<strSeparatorArray.length; i++) {
		if (strDateToCheck.indexOf(strSeparatorArray[i]) != -1) {
			intDateSeparatorIdx = i;
			break;
		}
	}

	if (intDateSeparatorIdx != intFormatSeparatorIdx) {
		return false;
	}

	if (intDateSeparatorIdx != -1) {
		strFormatArray = strFormatString.split(strSeparatorArray[intFormatSeparatorIdx]);
		if (strFormatArray.length != 3) {
			return false;
		}

		strDateToCheckArray = strDateToCheck.split(strSeparatorArray[intDateSeparatorIdx]);
		if (strDateToCheckArray.length != 3) {
			return false;
		}

		for (i=0; i<strFormatArray.length; i++) {
			if (strFormatArray[i] == 'mm' || strFormatArray[i] == 'mmm') {
				strMonth = strDateToCheckArray[i];
			}

			if (strFormatArray[i] == 'dd') {
				strDay = strDateToCheckArray[i];
			}

			if (strFormatArray[i] == 'yyyy') {
				strYear = strDateToCheckArray[i];
			}
		}
	} else {
		if (FormatString.length > 7) {
			if (strFormatString.indexOf('mmm') == -1) {
				strMonth = strDateToCheck.substring(strFormatString.indexOf('mm'), 2);
			} else {
				strMonth = strDateToCheck.substring(strFormatString.indexOf('mmm'), 3);
			}

			strDay = strDateToCheck.substring(strFormatString.indexOf('dd'), 2);
			strYear = strDateToCheck.substring(strFormatString.indexOf('yyyy'), 2);
		} else {
			return false;
		}
	}

	if (strYear.length != 4) {
		return false;
	}

	intday = parseInt(strDay, 10);
	if (isNaN(intday)) {
		return false;
	}
	if (intday < 1) {
		return false;
	}

	intMonth = parseInt(strMonth, 10);
	if (isNaN(intMonth)) {
		for (i=0; i<strMonthArray.length; i++) {
			if (strMonth == strMonthArray[i]) {
				intMonth = i+1;
				break;
			}
		}
		if (isNaN(intMonth)) {
			return false;
		}
	}
	if (intMonth > 12 || intMonth < 1) {
		return false;
	}

	intYear = parseInt(strYear, 10);
	if (isNaN(intYear)) {
		return false;
	}
	if (IsLeapYear(intYear) == true) {
		intDaysArray[1] = 29;
	}

	if (intday > intDaysArray[intMonth - 1]) {
		return false;
	}

	return true;
}

function IsLeapYear(intYear) {
	if (intYear % 100 == 0) {
		if (intYear % 400 == 0) {
			return true;
		}
	} else {
		if ((intYear % 4) == 0) {
			return true;
		}
	}

	return false;
}

function popupWindow(url) {
	//window.open(url,'popupWindow','toolbar=no,location=no,directories=no status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width=450,height=450,screenX=150,screenY=150,top=150,left=150');
	popUpWin(url, 'popupWindow', '450', '450', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no');
}

function popUpWin (url, win, width, height, options) {
	try {
		var leftPos = (screen.availWidth - width) / 2;
		var topPos = (screen.availHeight - height) / 2;
		if (options.length > 0) options += ',';
		options += 'width=' + width + ',height=' + height + ',top=' + topPos + ',left=' + leftPos;
		return window.open(url, win, options);
	} catch (e) {
		if (debugMode) alert(e);
	}
}

/* DDB - 041031 - Form Field Progress Bar */
/***********************************************
* Form Field Progress Bar- By Ron Jonk- http://www.euronet.nl/~jonkr/
* Modified by Dynamic Drive for minor changes
* Script featured/ available at Dynamic Drive- http://www.dynamicdrive.com
* Please keep this notice intact
***********************************************/
function textCounter(field,counter,maxlimit,linecounter) {
	// text width//
	var fieldWidth =  parseInt(field.offsetWidth);
	var charcnt = field.value.length;        
	// trim the extra text
	if (charcnt > maxlimit) { 
		field.value = field.value.substring(0, maxlimit);
	} else { 
	// progress bar percentage
	var percentage = parseInt(100 - (( maxlimit - charcnt) * 100)/maxlimit) ;
	document.getElementById(counter).style.width =  parseInt((fieldWidth*percentage)/100)+"px";
	document.getElementById(counter).innerHTML="Limit: "+percentage+"%"
	// color correction on style from CCFFF -> CC0000
	setcolor(document.getElementById(counter),percentage,"background-color");
	}
}

function setcolor(obj,percentage,prop){
	obj.style[prop] = "rgb(80%,"+(100-percentage)+"%,"+(100-percentage)+"%)";
}

function setRadioValue(control, controlValue) {
	for (var i = 0; i < control.length; i++) {
		if (control[i].value == controlValue) {
			control[i].checked = true;
			break;
		}
	}
}

function addLoadEvent(func) {
	addEvent(window, 'load', func);
}

function isNumber(value) {
  return (parseInt(value) == value);
}

function checkZip() {
	if (this.document.forms.locator.user_zip_code.value.length != 5 || isNumber(this.document.forms.locator.user_zip_code.value) == false) {
		alert("Please enter a valid 5 digit zip code.")
		return false;
	}
}

// written by Dean Edwards, 2005
// with input from Tino Zijdel, Matthias Miller, Diego Perini
// http://dean.edwards.name/weblog/2005/10/add-event/
// 2007-07-10 TKO - Removed check for body in schedule because of problems with Firefox 2.0

function addEvent(element, type, handler) {
	// Modification by Tanny O'Haley, http://tanny.ica.com to add the
	// DOMContentLoaded for all browsers.
	if (type == "DOMContentLoaded" || type == "domload") {
		addDOMLoadEvent(handler);
		return;
	}
	
	if (element.addEventListener) {
		element.addEventListener(type, handler, false);
	} else {
		// assign each event handler a unique ID
		if (!handler.$$guid) handler.$$guid = addEvent.guid++;
		// create a hash table of event types for the element
		if (!element.events) element.events = {};
		// create a hash table of event handlers for each element/event pair
		var handlers = element.events[type];
		if (!handlers) {
			handlers = element.events[type] = {};
			// store the existing event handler (if there is one)
			if (element["on" + type]) {
				handlers[0] = element["on" + type];
			}
		}
		// store the event handler in the hash table
		handlers[handler.$$guid] = handler;
		// assign a global event handler to do all the work
		element["on" + type] = handleEvent;
	}
};
// a counter used to create unique IDs
addEvent.guid = 1;

function removeEvent(element, type, handler) {
	if (element.removeEventListener) {
		element.removeEventListener(type, handler, false);
	} else {
		// delete the event handler from the hash table
		if (element.events && element.events[type]) {
			delete element.events[type][handler.$$guid];
		}
	}
};

function handleEvent(event) {
	var returnValue = true;
	// grab the event object (IE uses a global event object)
	event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
	// get a reference to the hash table of event handlers
	var handlers = this.events[event.type];
	// execute each event handler
	for (var i in handlers) {
		this.$$handleEvent = handlers[i];
		if (this.$$handleEvent(event) === false) {
			returnValue = false;
		}
	}
	return returnValue;
};

function fixEvent(event) {
	// add W3C standard event methods
	event.preventDefault = fixEvent.preventDefault;
	event.stopPropagation = fixEvent.stopPropagation;
	return event;
};
fixEvent.preventDefault = function() {
	this.returnValue = false;
};
fixEvent.stopPropagation = function() {
	this.cancelBubble = true;
};

// End Dean Edwards addEvent.

// Tino Zijdel - crisp@xs4all.nl This little snippet fixes the problem that the onload attribute on 
// the body-element will overwrite previous attached events on the window object for the onload event.
if (!window.addEventListener) {
	document.onreadystatechange = function(){
		if (window.onload && window.onload != handleEvent) {
			addEvent(window, 'load', window.onload);
			window.onload = handleEvent;
		}
	}
}

// Here are my functions for adding the DOMContentLoaded event to browsers other
// than Mozilla.

// Array of DOMContentLoaded event handlers.
window.onDOMLoadEvents = new Array();
window.DOMContentLoadedInitDone = false;

// Function that adds DOMContentLoaded listeners to the array.
function addDOMLoadEvent(listener) {
	// If the DOMContentLoaded event has happened, run the function.
	if(window.DOMContentLoadedInitDone){
		listener();
		return;
	}

	window.onDOMLoadEvents[window.onDOMLoadEvents.length]=listener;
}

// Function to process the DOMContentLoaded events array.
function DOMContentLoadedInit() {
	// quit if this function has already been called
	if (window.DOMContentLoadedInitDone) return;

	// flag this function so we don't do the same thing twice
	window.DOMContentLoadedInitDone = true;

	// iterates through array of registered functions 
	for (var i=0; i<window.onDOMLoadEvents.length; i++) {
		var func = window.onDOMLoadEvents[i];
		func();
	}
}

function DOMContentLoadedScheduler() {
	// quit if the init function has already been called
	if (window.DOMContentLoadedInitDone) return true;
	
	// First, check for Safari or KHTML.
	// Second, check for IE.
	//if DOM methods are supported, and the body element exists
	//(using a double-check including document.body, for the benefit of older moz builds [eg ns7.1] 
	//in which getElementsByTagName('body')[0] is undefined, unless this script is in the body section)
	if(/KHTML|WebKit/i.test(navigator.userAgent)) {
		if(/loaded|complete/.test(document.readyState)) {
			DOMContentLoadedInit();
		} else {
			// Not ready yet, wait a little more.
			setTimeout("DOMContentLoadedScheduler()", 250);
		}
	} else if(document.getElementById("__ie_onload")) {
		return true;
	}

	// Check for custom developer provided function.
	if(typeof DOMContentLoadedCustom == "function") {
		if(typeof document.getElementsByTagName != 'undefined' && (document.getElementsByTagName('body')[0] != null || document.body != null)) {
			// Call custom function.
			if(DOMContentLoadedCustom()) {
				DOMContentLoadedInit();
			} else {
				// Not ready yet, wait a little more.
				setTimeout("DOMContentLoadedScheduler()", 250);
			}
		}
	}

	return true;
}

// Schedule to run the init function.
setTimeout("DOMContentLoadedScheduler()", 250);

// Just in case window.onload happens first, add it there too.
addEvent(window, "load", DOMContentLoadedInit);

// If addEventListener supports the DOMContentLoaded event.
if(document.addEventListener)
	document.addEventListener("DOMContentLoaded", DOMContentLoadedInit, false);

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
	document.write("<script id=__ie_onload defer src=\"//:\"><\/script>");
	var script = document.getElementById("__ie_onload");
	script.onreadystatechange = function() {
		if (this.readyState == "complete") {
			DOMContentLoadedInit(); // call the onload handler
		}
	};
/*@end @*/

function toggle_display(el) {
	if (document.getElementById(el).style.display == 'none') {
		document.getElementById(el).style.display = 'block';
	} else {
		document.getElementById(el).style.display = 'none';
	}
}
/* Added for Omniture Tracking of Product Add Clicks */
function OmnitureProductAdd(category, name, qty, price) {
	var s=s_gi(s_account);
	s.events="scAdd";
	//s.products is ALWAYS in the format "category, name, quantity, price" -- cannot define order of fields
	//s.products=";Product;Qty;Price[,;" + name + ";" + qty + ";" + price + "]";
	s.products=category + ";" + name + ";" + qty + ";" + price;
	s.tl(this,'o','Add to Cart');
}