// determine what browser is being used
var IE5 = (document.all) ? true : false;
var N6 = (document.getElementById && !document.all) ? true : false;
function getVariable(strId)
{
	var retVal;
	if(N6)
	{
		retVal = document.getElementById(strId);
		/*
		if(retVal == null)
		{
			var items = document.getElementsByName(strId);
			if(items.length > 0)
				retVal = items[0];
		}
		*/
	}
	else if(IE5)
		retVal = document.all[strId];
	else 
		retVal = document.all[strId];
	
	return retVal;
}

function randRange(maxVal)
{
	return Math.round(maxVal * Math.random());
}

function checkLength(length)
{
	if(window.event.srcElement.value.length  >= length)
	{
		alert("You have reached the maximum length of " + length + " characters permitted here.");
		return false;
	}
}

function rand()
{
	return (new Date()).valueOf();
}

function href_stripQueryString(href)
{
	var retVal = href;
	if(href.indexOf('?') >= 0)
		retVal = href.substring(0, href.indexOf('?'));
	return retVal;
}

function href_appendQueryString(href, varName, varValue)
{
	if(href.indexOf('?') >= 0)
		href += "&" + varName + "=" + varValue;
	else
		href += "?" + varName + "=" + varValue;
	return href;
}

function href_goto(href)
{
	if(href.length > 0)
		window.open(href);
}

function radio_getValue(radioName)
{
	var radioObjs = document.getElementsByName(radioName);
		
	for(i=0;i<radioObjs.length;i++)
		if (radioObjs[i].checked == true)
			return radioObjs[i].value;
}

function checkbox_getValues(formId, checkboxName)
{
	var values = "";
	
	for(var i=0; i<getVariable(formId)[checkboxName].length; i++)
		if(getVariable(formId)[checkboxName][i].checked)
			values = listAppend(values, getVariable(formId)[checkboxName][i].value);
	
	return values;
}

function listAppend(list, value)
{
	if(list.length > 0)
		list += "," + value;
	else
		list = value;
	return list;
}




function img_scale(imgObj, width, height)
{
	var oldWidth = newWidth = imgObj.width;
	var oldHeight = newHeight = imgObj.height;
	
	if(typeof(width) == "number" && typeof(height) == "number")
	{
		newWidth = width;
		newWidth = height
	}
	else if(typeof(width) == "number")
	{
		newWidth = width;
		newHeight = (oldHeight / oldWidth) * width;
	}
	else if(typeof(height) == "number")
	{
		newWidth = (oldWidth / oldHeight) * height;
		newHeight = height;
	}
	
	/*
	resize up to native resolution
	if(typeof(imgObj.originalWidth) == "number" && typeof(imgObj.originalHeight) == "number")
	{
		if(newWidth > imgObj.originalWidth || newHeight > imgObj.originalHeight)
		{
			newWidth = imgObj.originalWidth;
			newHeight = imgObj.originalHeight;
		}
	}*/
	
	imgObj.style.width = newWidth + "px";
	imgObj.style.height = newHeight + "px";
}

function img_fit(imgObj, width, height)
{
	var scaleTo = width > height ? "width" : "height";
	var newWidth, newHeight;
	
	// scale to width
	if(width > height)
	{
		newWidth = width;
		newHeight = (imgObj.height / imgObj.width) * height;
	}
	else
	{
		newHeight = height;
		newWidth = (imgObj.width / imgObj.height) * width;
	}
	
	imgObj.style.width = newWidth + "px";
	imgObj.style.height = newHeight + "px";
}


/*
	Programatically jumps to an anchor on the page
*/
function jumpToAnchor(anchorName) 
{
	window.location = String(window.location).replace(/\#.*$/, "") + "#" + anchorName;
}

if(typeof(HTMLElement) != "undefined")
{
	HTMLElement.prototype.click = function() 
	{
		var evt = this.ownerDocument.createEvent('MouseEvents');
		evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
		this.dispatchEvent(evt);
	}
}
function jumpToAnchor_fromLink(theLink)
{
	var hyperlink = document.getElementById(theLink);
	hyperlink.click();
}

function list_append(list, item, delimiter)
{
	if(delimiter == null)
		delimiter = ",";
		
	if(list.length > 0)
		list += delimiter + item;
	else
		list += item;
	return list;
}

// BEGIN: date functions
//   - used with generateDate function to manage date fields
var daysNormal   = new Array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var daysLeapYear = new Array( 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

function isLeapYear(year)
{
   if ((year / 4)   != Math.floor(year / 4))   
		return false;
   if ((year / 100) != Math.floor(year / 100)) 
		return true;
   if ((year / 400) != Math.floor(year / 400)) 
		return false;
   return true;
}

function updateDays(dateName)
{
	var objMonth = getVariable(dateName + '_month');
	var objDay = getVariable(dateName + '_day');
	var objYear = getVariable(dateName + '_year');
	//var days = isLeapYear(objYear.value) ? daysLeapYear[parseInt(objMonth.value)-1] : daysNormal[parseInt(objMonth.value)-1];
	var days = daysInMonth(objYear.value, objMonth.value);
	var oldDay = objDay.value == "" ? 1 : objDay.value;
	
	objDay.options.length = 0;
	for(var i=1; i<=days; i++)
		objDay.options[objDay.options.length] = new Option(i, i);
	if(oldDay > days)
		oldDay = days;
	objDay.value = oldDay;
}

function daysInMonth(year, month)
{
	var days = isLeapYear(year) ? daysLeapYear[parseInt(month)-1] : daysNormal[parseInt(month)-1];
	return days;
}
// END: date functions


var iframe_counter = 1;
var debugger_showIframe = false;
function iframe_request()
{
	var iframe_loader = document.createElement("iframe");
	var iframe_id = "iframe_loader_" + iframe_counter++;
	iframe_loader.id = iframe_id;
	iframe_loader.name = iframe_id;
	//iframe_loader.style.position = "absolute";
	iframe_loader.style.left = 0;
	iframe_loader.style.top = 0;
	iframe_loader.style.border = "0px";
	iframe_loader.style.width = "500px";
	iframe_loader.style.height = "300px";
	iframe_loader.style.backgroundColor = "white";
	iframe_loader.style.display = (debugger_showIframe ? "" : "none");
	
	document.body.appendChild(iframe_loader);
	return iframe_id;
}


function table_getRowIndex(tableObj, id)
{
	var rowIndex = null;
	for(var i=0; i<tableObj.rows.length; i++)
	{
		if(tableObj.rows[i].id == id)
		{
			rowIndex = i;
			break;
		}
	}
	return rowIndex;
}

function getFrame(id)
{
	return getVariable(id).contentWindow;
}

var ani_resizeIncrement = 50;
var ani_resizeSpeed = 10;
function aniOpen(targetFrameId, href, finalHeight)
{
	var targetFrame = getVariable(targetFrameId);
			
	// keep resizing
	if(targetFrame.clientHeight < finalHeight)
	{
		targetFrame.style.height = (targetFrame.clientHeight + ani_resizeIncrement) + "px";
		window.setTimeout("aniOpen('" + targetFrameId + "', '" + href + "', " + finalHeight + ")", ani_resizeSpeed); 
	}
	// done resizing...assign href
	else
	{
		targetFrame.style.height = finalHeight + "px";
		if(href.length > 0)
			getFrame(targetFrameId).location.href = href;
	}
}

function aniClose(targetFrameId, onClose)
{
	var targetFrame = getVariable(targetFrameId);
	//alert(targetFrame);
	// keep resizing
	if(targetFrame.clientHeight > ani_resizeIncrement)
	{
		targetFrame.style.height = (targetFrame.clientHeight - ani_resizeIncrement) + "px";
		window.setTimeout("aniClose('" + targetFrameId + "', \"" + onClose + "\")", ani_resizeSpeed); 
	}
	// hide iframe and call onClose
	else
	{
		targetFrame.style.height = "0px";
		if(onClose.length > 0)
			eval(onClose);
	}
}

function aniScroll(scrollId, contentId, destHeight, increment, speed, onDone)
{
	var obj = document.getElementById(scrollId);
	var height = obj.clientHeight + increment;
	
	// expand
	if(increment > 0)
	{
		if(height >= destHeight)
		{
			obj.style.height = destHeight + "px";
			document.getElementById(contentId).style.display = "";
			setTimeout(onDone, 0);
		}
		else
		{
			obj.style.height = height + "px";
			setTimeout("aniScroll('" + scrollId + "', '" + contentId + "', " + destHeight + ", " + increment + ", " + speed + ", '" + onDone + "')", speed);
		}
	}
	
	// contract
	else
	{
		
		if(height < 0)
		{
			obj.style.height = "0px";
			setTimeout(onDone, 0);
		}
		else
		{
			document.getElementById(contentId).style.display = "none";
			obj.style.height = height + "px";
			setTimeout("aniScroll('" + scrollId + "', '" + contentId + "', " + destHeight + ", " + increment + ", " + speed + ", '" + onDone + "')", speed);
		}
	}
}


function dummy(){}









function getElementsByClass(searchClass, node, tag) 
{
	// Taken from http://www.dustindiaz.com/top-ten-javascript/
	var classElements = new Array();
	if(node == null)
		node = document;
	if(tag == null)
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\s)"+searchClass+"(\s|$)");
	for(i=0, j=0; i<elsLen; i++) 
	{
		if(pattern.test(els[i].className)) 
		{
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}


function jscss(a,o,c1,c2)
{
  switch (a){
    case 'swap':
      o.className=!jscss('check',o,c1)?o.className.replace(c2,c1): o.className.replace(c1,c2);
    break;
    case 'add':
      if(!jscss('check',o,c1)){o.className+=o.className?' '+c1:c1;}
    break;
    case 'remove':
      var rep=o.className.match(' '+c1)?' '+c1:c1;
      o.className=o.className.replace(rep,'');
    break;
    case 'check':
      return new RegExp('\\b'+c1+'\\b').test(o.className)
    break;
  }
}


function highlightImage(imgId, doHighlight)
{
	getVariable(imgId).style.opacity = doHighlight ? 1 : .7;
	getVariable(imgId).style.filter = "alpha(opacity:" + (doHighlight ? 100 : 70) + ")";
}

function init()
{
	this.getFilePart_front = function(src) { return src.substring(0, src.lastIndexOf("_")+1); };
	this.getFilePart_back = function(src) { return src.substring(src.lastIndexOf("."), src.length); };
	var imageCache = new Array();
	
	/* image thumbs
	*  Images default to being faded and are rendered at full opacity when hovered over
	*/
	var imgObjs = getElementsByClass("thumb_img", document, "img");
	for(var i=0; i<imgObjs.length; i++)
	{
		imgObjs[i].onmouseover = function() { if(typeof(highlightImage) == "function") highlightImage(this.id, true); };
		imgObjs[i].onmouseout = function() { if(typeof(highlightImage) == "function") highlightImage(this.id, false); };
		highlightImage(imgObjs[i].id, false);
	}
	
	/* button images
	*
	*/
	var imgObjs = getElementsByClass("button", document, "img");
	imgObjs = imgObjs.concat(getElementsByClass("rollover", document, "img"));
	for(var i=0; i<imgObjs.length; i++)
	{
		imgObjs[i].newSrc_front = getFilePart_front(imgObjs[i].src);
		imgObjs[i].newSrc_back =  getFilePart_back(imgObjs[i].src);
		
		// load images in cache
		imageCache[imageCache.length] = new Image();
		imageCache[imageCache.length-1].src = imgObjs[i].newSrc_front + "on" + imgObjs[i].newSrc_back;
		imageCache[imageCache.length] = new Image();
		imageCache[imageCache.length-1].src = imgObjs[i].newSrc_front + "off" + imgObjs[i].newSrc_back;
		imageCache[imageCache.length] = new Image();
		imageCache[imageCache.length-1].src = imgObjs[i].newSrc_front + "pressed" + imgObjs[i].newSrc_back;
		
		imgObjs.mouseOver = false;
		imgObjs[i].onmouseover = function() 
		{ 
			this.mouseOver = true;
			this.src = this.newSrc_front + "on" + this.newSrc_back;
		};
		imgObjs[i].onmouseout = function() 
		{ 
			this.mouseOver = false;
			this.src = this.newSrc_front + "off" + this.newSrc_back;
		};
		if(imgObjs[i].className.indexOf("button") >= 0)
		{
			imgObjs[i].onmousedown = function()
			{ 
				this.src = this.newSrc_front + "pressed" + this.newSrc_back;
			};
			imgObjs[i].onmouseup = function()
			{
				this.src = this.newSrc_front + (this.mouseOver ? "on" : "off") + this.newSrc_back;
			}
		}
	}
	var test = "hi";
}




function previewImage(destObj, show, imgSrc, imgStyle)
{
	if(show)
	{
		var img = document.createElement("img");
		img.src = imgSrc;
		img.className = "img_preview";
		if(imgStyle)
			img.style.cssText = imgStyle;
		img.style.border = "2px solid black";
		img.style.position = "absolute";
		destObj.appendChild(img);
	}
	else
	{
		var imgs = getElementsByClass("img_preview", destObj, "img") ;
		for(var i=0; i<imgs.length; i++)
			destObj.removeChild(imgs[i]);
	}
}

var previewedImages = new Array();
function previewImage_toggle(destObj, imgSrc, imgStyle)
{
	var index = -1;
	for(var i=0; i<previewedImages.length; i++)
	{
		if(previewedImages[i] == destObj.id)
		{
			index = i;
			break;
		}
	}
	
	// image being viewed, hide it
	if(index == -1)
	{
		previewImage(destObj, true, imgSrc, imgStyle);
		previewedImages[previewedImages.length] = destObj.id;
		
	}
	else
	{
		previewImage(destObj, false)
		previewedImages[index] = null;
	}
}







function stripeRows(objId)
{
	//var objId = "table_productDetails";
	var rows = document.getElementById(objId).tBodies[0].rows;
	for(var i=0; i<rows.length; i++)
		rows[i].className = "recordSet" + ((i % 2) + 1);
}


function stripeRows_ul(objId)
{
	//var objId = "table_productDetails";
	var rows = document.getElementById(objId).getElementsByTagName("li");
	for(var i=0; i<rows.length; i++)
		rows[i].className = "recordSet" + ((i % 2) + 1);
}




function addLoadEvent(func) 
{
	/*
	var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
	*/
  if(window.addEventListener)
	{
		window.addEventListener("load", func, false);
	}
	else
	{
		window.attachEvent("onload", func);
	}
}






/*
	Developed by Robert Nyman, http://www.robertnyman.com
	Code/licensing: http://code.google.com/p/getelementsbyclassname/
*/
var getElementsByClassName = function (className, tag, elm){
	if (document.getElementsByClassName) {
		getElementsByClassName = function (className, tag, elm) {
			elm = elm || document;
			var elements = elm.getElementsByClassName(className),
				nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
				returnElements = [],
				current;
			for(var i=0, il=elements.length; i<il; i+=1){
				current = elements[i];
				if(!nodeName || nodeName.test(current.nodeName)) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	else if (document.evaluate) {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = "",
				xhtmlNamespace = "http://www.w3.org/1999/xhtml",
				namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
				returnElements = [],
				elements,
				node;
			for(var j=0, jl=classes.length; j<jl; j+=1){
				classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
			}
			try	{
				elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
			}
			catch (e) {
				elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
			}
			while ((node = elements.iterateNext())) {
				returnElements.push(node);
			}
			return returnElements;
		};
	}
	else {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = [],
				elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
				current,
				returnElements = [],
				match;
			for(var k=0, kl=classes.length; k<kl; k+=1){
				classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
			}
			for(var l=0, ll=elements.length; l<ll; l+=1){
				current = elements[l];
				match = false;
				for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
					match = classesToCheck[m].test(current.className);
					if (!match) {
						break;
					}
				}
				if (match) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	return getElementsByClassName(className, tag, elm);
};



var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();