/**
 * Common Site Scripts
 *
 * A collection of utility functions for general site use
 *
 * @author     Melvin Waller <melvin.waller@gateway.com>
 * @since      2006
 * @version    CVS: $Id: common.js,v 1.8 2007/03/01 20:23:57 mwaller Exp $
 */

if (typeof(YAHOO) == "object") { // sets abbreviations for the YAHOO library
	var Yo=YAHOO, Yu=YAHOO.util, Yd=YAHOO.util.Dom, Ye=YAHOO.util.Event, Yc=YAHOO.widget.Calendar;
	var Ya=YAHOO.util.Anim, Ys=YAHOO.widget.Slider, Yl=YAHOO.util.Color;
}

function altTitle() // USAGE: initialize on page load using an attachEvent action
{ // Copies all image ALT values to a TITLE value to provide equivalent browser functionality
	var d=window.document;
	if (d.images.length > 0) { // test for script support
		for (var i=0; i < d.images.length; i++) { // repeat for all images
			if (d.images[i].alt.length > 0 && d.images[i].alt != " ") {
				d.images[i].title = d.images[i].alt;
			}
		}
	}
	if (d.links.length > 0) { // test for links script support
		for (var i=0; i < d.links.length; i++) { // repeat for all links
			var lnk = d.links[i];
			if (lnk != null && lnk.parentNode.tagName.toLowerCase() == "map") { // imagemap link
				d.links[i].title = d.links[i].alt + (d.links[i].title? d.links[i].title : "");
			}
		}
	}
}
if (Ye) { Ye.addListener(window, "load", altTitle, "grid1"); }


function transformLinkToSubmit(obj_form, txt_field_name)
{ // converts a link name to a hidden field and then submits the form
	var inputElement = document.createElement('input');
	inputElement.setAttribute('name', txt_field_name);
	inputElement.setAttribute('value', '1');
	inputElement.setAttribute('type', 'hidden');
	obj_form.appendChild(inputElement);
	obj_form.submit();
}

function maskPage(start_div, end_div)
{ // masks a section of a page, blocking general access links and forms
	var start=findPos(start_div), end=findPos(end_div);
	var height=end.y-start.y, elem=document.getElementById(start_div);
	if (elem) {
		var new_item = document.createElement("div");
		new_item.className = "loading_layer";
		new_item.id = "loading_layer";
		new_item.style.position = "absolute";
		new_item.style.top = start.y + "px";
		new_item.style.height = height + "px";
		new_item.style.margin = "0px 0px 0px -10px";
		new_item.style.width = "760px";
		new_item.innerHTML = "&nbsp;";
		elem.insertBefore(new_item, elem.firstChild);
	}
}

function findPos(id)
{ // get the x and y coordinates of an object within a document
	var objx, objy, x=0, y=0, t=true, d=document, coord=new Object();
	objx = objy = (d.getElementById)? d.getElementById(id) : (d.all)? d.all[id] : null;
	if (typeof(id) == "object") { objx = objy = id; }
	if (objx == null || !objx.offsetParent) return null;
	while (t) {
		x += objx.offsetLeft;
		if (!objx.offsetParent) t = false;
		objx = objx.offsetParent;
	}
	t = true;
	while (t) {
		y += objy.offsetTop;
		if (!objy.offsetParent) t = false;
		objy = objy.offsetParent;
	}
	coord.x = x;
	coord.y = y;
	return coord;
}

function offsetHeight()
{ // locate vertical window viewing position and height within the document
	var winOffset, winHeight, d=window.document;
	var nn = (navigator.appName.indexOf("Netscape") != -1);

	if (d.documentElement.scrollTop) { winOffset = d.documentElement.scrollTop; }
	else if (d.body.parentNode.scrollTop) { winOffset = d.body.parentNode.scrollTop; }
	else if (d.body.scrollTop) { winOffset = d.body.scrollTop; }
	else if (window.pageYOffset) { winOffset = window.pageYOffset; }
	else if (nn) { winOffset = pageYOffset; }
	else { winOffset = 0; }

	if (d.documentElement.clientHeight) { winHeight = d.documentElement.clientHeight; }
	else if (d.body.parentNode.clientHeight) { winHeight = d.body.parentNode.clientHeight; }
	else if (d.body.clientHeight) { winHeight = d.body.clientHeight; }
	else if (window.innerWidth) { winHeight = window.innerHeight; }
	else if (nn) { winHeight = innerHeight; }

	return new Array(winOffset, winHeight);
}

function vis(ID, state)
{ // object visibility toggle, style visibility
	var d, see;
	state = (state)? state : null;
	if (document.layers) {
		d = document.layers[ID];
		if (state && state === true) { see = "show"; }
		else if (state && state === false) { see = "hide"; }
		else see = (d.visibility == "hide")? "show" : "hide";
		if (see) { d.visibility = see; }
	}
	else {
		d = document.getElementById(ID);
		if (state && state === true) { see = "visible"; }
		else if (state && state === false) { see = "hidden"; }
		if (!state) { see = (d.style.visibility == "hidden")? "visible" : "hidden"; }
		if (see) { d.style.visibility = see; }
	}
}

function showHide(id)
{ // function that hides or shows an element, style display
	if (!document.getElementById) { document.getElementById = function() { return null; } }
	if (id == null || id == "") { return; }
	var tag = document.getElementById(id);
	var icon = id + "_toggle";
	var state = tag.style.display;
	if (tag) {
		if (document[icon].src) {
			tag.style.display = (state == "none")? "inline" : "none";
			document[icon].src = (state == "none")?
			 "/store/img/icon_contract.gif" : "/store/img/icon_expand.gif";
			document[icon].alt = (state == "none")?
			 "Hide Description" : "View Description";
		}
		else { tag.style.display = (state == "none")? "block" : "none"; }
	}
}

function oWindow(Uri, Wth, Hgt, Resize, Scroll, Name, Left, Top, Params)
{ // Fully definable pop-up windows [backwards compatible with openWin]
	Uri = Uri || "/";
	Name = Name || "buttons";
	if (!Params) {
		Wth = (Wth == parseInt(Wth))? Wth : 500;
		Hgt = (Hgt == parseInt(Hgt))? Hgt : 500;
		var Center = oCenter(Wth, Hgt);
		Resize = (Resize == parseInt(Resize))? Resize : 0;
		Scroll = (Scroll == parseInt(Scroll))? Scroll : 1;
		Left = (Left == "center")? Center[0] : (Left == parseInt(Left))? Left : 50;
		Top = (Top == "center")? Center[1] : (Top == parseInt(Top))? Top : 50;
		Params = "toolbar=0,location=0,directories=0,status=0,menubar=0" +
		 ",resizable=" + Resize + ",scrollbars=" + Scroll +
		 ",width=" + Wth + ",height=" + Hgt + ",left=" + Left + ",top=" + Top;
	}
	var Win = window.open(Uri, Name, Params);
	Win.focus();
}
function openWin(Uri, Wth, Hgt, Resize, Scroll) { oWindow(Uri, Wth, Hgt, Resize, Scroll); }
function openWin2(Uri, Wth, Hgt, Resize, Scroll) { oWindow(Uri, Wth, Hgt, Resize, Scroll); }
function popMS(Uri) 
{ // MDA Pop-Up Window
	var Wth=500, Hgt=500, pct=0.85; // 85% of parent window size
	if (parseInt(navigator.appVersion) > 3) {
		Wth = parseInt(screen.availWidth * pct);
		Hgt  = parseInt(screen.availHeight * pct);
	}
	oWindow(Uri, Wth, Hgt, 1, 1, "Genuine")
	return true;
}
function oCenter(Wth, Hgt)
{ // (left-top) screen center based on the provided object's width and height
	return new Array( (screen.width - Wth) / 2, (((screen.height - Hgt) / 2) - 20) );
}

function PopUpTrackInfo(Uri)
{ // Added for New Order Status
	oWindow(Uri, 500, 500, 1, 1, "TrackInfo", "center", "center");
}

/* makePopup: controls what links open a popup, close a popup, or open a new window
 *
 * Ex: function MYFUNCTIONNAME() { makePopup(TYPE, new Array(a,b,c), METHOD, ACTION, LABEL); }
 *  MYFUNCTIONNAME = name of the function that calls makePopup with the desired parameters
 *  TYPE = identifies the type of page link to change, ex: 'host'= host name, 'page'= page name
 *  new Array(a,b,c) = an array of host/page links to alter (based on href value)
 *  METHOD = the type of new window: 'pop' for popup, 'new' (or empty) for new window
 *  ACTION = if type='pop': 'open' to open window, 'close' (or empty) to close window
 *           if type='new': name of target new window, or '_blank' if not defined
 *  LABEL = name of the target popup window, 'popup' if not defined
 */
function makePopup(type, pages, method, action, label)
{ // USAGE: initialize on page load using an attachEvent action
	var pageref, pagetype, d=document.links;
	label = (label == "" || label == null)? "popup" : label;
	if (d.length > 0) { // links are modifiable
		for (var i=0; i < d.length; i++) { // loop through links
			href = d[i].href;
			pageref = urlSplit(href);
			pagetype = (type == "host")? pageref.host : pageref.page;
			for (var j=0; j < pages.length; j++) { // loop through array of 'pages'
				if (pages[j] == pagetype) {
					if (method == "pop") { // popup window
						if (action == "open") { // window open
							d[i].onclick = "oWindow('" + href + "',600,500,1,0," +
							 label + ",'center','center');return false;";
						}
						else { // window close
							d[i].onclick = "opener.window.location.href='" +
							 opener.window.location.href + "';window.close();return false;";
						}
					}
					else { // new window (method == "new")
						d[i].target = (action)? action : "_blank";
					}
				}
			}
		}
	}
}

function urlSplit(href)
{ // [utility] disassemble a URL (required by makePopup)
	var str, host, page, query;

	str = href.split("?"); // split query from URL
	query = (str.length > 1)? str[1] : ""; // query string

	str = href.split("//"); // split off protocol
	host = (str.length > 1)? true : false; // host specified
	str = (str.length > 1)? str[1] : str;

	str = href.split("/"); // split up path
	host = (host)? str[0] : ""; // host name
	page = (str.length > 1)? str[str.length - 1] : ""; // page name
	page = (page == "" || page == null)? b[b.length - 2] : ""; // directory/host name if no page
	page = (page == null)? "" : page; // no null values

	str.host = host;
	str.page = page;
	str.query = query;
	return str;
}


function testPassword(label,val)
{	
	var result = '';
	if(val.length < 1){
		result = "Please enter "+label+".\n";
	}
	if (val.length < 6 || val.length > 10){
		result += label + " must be 6-10 characters and contain" + 
				 " at least one number and one letter.\n" +
				 "Passwords are case-sensitive.";
	}
	else if (val.match('^[a-zA-Z]+$')){
		result = label + " must also have at least one number.";
	}
	else if (/^\d+$/.test(val)){
		result = label + " must also have at least one letter, upper or lower cased.";
	}
	
	if (result.length > 0) {
		alert(result);
		return false;
	}
	return true;
}

function matchPassword(label1,label2,val1,val2){
	if (val1 != val2) {
		alert(label1+" and "+label2+" fields must match. Please try again.");
		return false;
	}
	return true;
}

function ltrim(val)
{ // Removes leading whitespace
	var re = /\s*((\S+\s*)*)/;
	return val.replace(re, "$1");
}

function rtrim(val)
{ // Removes trailing whitespace
	var re = /((\s*\S+)*)\s*/;
	return val.replace(re, "$1");
}

function trim(val)
{ // Removes leading and trailing whitespace
	return ltrim(rtrim(val));
}


function checkKeyCode(e, type)
{
	var keycode = (window.event)? window.event.keyCode : e.which;
	var element = (window.event)? window.event.srcElement : e.target;
	var regex = '';
	switch (type) {
		case 'digit':
			regex = /\d/;
			break;
		case 'float':
			regex = (element.value && element.value!='' && element.value.search(/\./)!=-1)?/\d/:/[0-9.]/;
			break;
		default:
			return true;
	}

	// on FireFox keycode 8 = (backspace), 0 = (tab)
	return (regex.test(String.fromCharCode(keycode)) || keycode == 8 || keycode == 0);
}
