// Global Namespace

var AppGlobal;
if (!AppGlobal) AppGlobal = {};

// Declare global variables
AppGlobal.BASE_URL = '/';
AppGlobal.CLASSPATH = 'js/classes/';

// Declare global variables
var win = null;

// Define prototypes
Number.prototype.NaN0 = function() { return isNaN(this)?0:this; }
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };
String.prototype.toInteger = function() { return (isNaN(this)) ? 0 : parseInt(this); };
String.prototype.toCurrency = function() { 
	num = this;
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) return "0.00";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	return num + "." + cents;
};
String.prototype.padLeft = function(len) {
	var char = "0";
	var str = this;
	if (arguments > 1) char = arguments[1];
	for (var x = str.length; x < len; x++) str = char + str + '';
	return str;
};
String.prototype.padRight = function(len) {
	var char = "0";
	var str = this;
	if (arguments > 1) char = arguments[1];
	for (var x = str.length; x < len; x++) str += char + '';
	return str;
};
String.prototype.toDate = function() {
	var val = this.replace(/[-.]/g, "/");
	var tmp = Date.parse(val);
	if (isNaN(tmp)) return this;
	else {
		var yearDigits = (val.match(/\/[0-9]{2}$/) != null) ? 2 : 4;
		d = new Date(tmp);
		if (d.getFullYear() < '1950' && yearDigits == 2) d.setFullYear(d.getFullYear() + 100);
		return parseInt(d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
	}
};
// Strips HTML from a string
String.prototype.stripHTML = function() {
	return this.replace(/<[^>]*>/g, "");
}

// Opens the customer map
function openMap(url) {
	var newwindow = window.open(url,'name','height=500,width=750');
}

// Opens a pop-up window
function openWin(url) {
	var newwindow = window.open(url,'name','height=520,width=620,scrollbars=yes,resizable=yes,menubar=yes,location=yes');
}

// Pallet popup script
function xWindow(url,name,widh) {
	popupWin = window.open(url,name, 'left=10,top=10,'+widh)
}

// Inserts the SWF logo
function swfLogo() {
	var flashContent = '<div id="flash"><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" width="97" height="63">'
		+ '<param name="movie" value="\/flash\/BarGlobe.swf" /><param name="quality" value="high" /><param name="allowFullScreen" value="false" /><param name=FlashVars value="loc=en_US&amp;required_version=5,0,0,0" /><param name="menu" value="false" /><param name="wmode" value="transparent" />'
		+ '<embed src="\/flash\/BarGlobe.swf" menu="false" width="97" height="63" quality="high" allowfullscreen="false" wmode="transparent" flashvars="loc=en_US&amp;required_version=5,0,0,0" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" menu="false">'
		+ '<\/embed>'
		+ '<\/object></div>';
	document.write(flashContent);
}

// Creates a quote request link
AppGlobal.quoteRequest = function(cat, id) {
	var mainWin = window.opener;
	mainWin.focus();
	mainWin.location.href = "/ContactUs/quoteRequest.aspx?cat=" + encodeURIComponent(cat) + "&id=" + encodeURIComponent(id);
}

// Dynamic class loader
AppGlobal.loadClass = function(source) {
	var scriptname = AppGlobal.BASE_URL + AppGlobal.CLASSPATH + source.replace('.', '/') + '.js';
	var srcid = source.replace('.', '_');
	if (self[srcid]) return;
	/* DOM does not work in Safari 2
	var head = document.getElementsByTagName("head")[0];
	script = document.createElement('script');
	script.id = srcid;
	script.type = 'text/javascript';
	script.src = scriptname;
	head.appendChild(script);
	*/
    document.write('<script id="' + srcid + '" type="text/javascript" src="'+scriptname+'"><\/script>');
}

// Opens the racking site in a new window
AppGlobal.rackingSite = function() {
	var win = window.open('http://www.rackingdeals.com', 'RackingSite', 'status=1,toolbar=1,location=1,menubar=1,directories=1,resizable=1,scrollbars=1');
}

// HTML element positioning global function
AppGlobal.getPos = function(e){
	var left = 0;
	var top  = 0;
	while (e.offsetParent){
		left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
		top  += e.offsetTop  + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);
		e     = e.offsetParent;
	}
	left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
	top  += e.offsetTop  + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);
	return { x:left, y:top };
}

// Returns a style property for an item
AppGlobal.getStyle = function(oElm, strCssRule){
	var strValue = "";
	if (document.defaultView && document.defaultView.getComputedStyle) strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
	else if (oElm.currentStyle) {
		strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){ return p1.toUpperCase(); });
		strValue = oElm.currentStyle[strCssRule];
	}
	return strValue;
}

// Sets a given element to a text value
AppGlobal.setText = function(elem, text) {
	while (elem.firstChild) elem.removeChild(elem.firstChild);
	elem.appendChild(document.createTextNode(text));
}

// Gets the value from an XML node
AppGlobal.getXMLValue = function(node) {
	return (node && node.firstChild) ? node.firstChild.nodeValue : ""
}

// Image button rollover/press handler handler
AppGlobal.addRollover = function(img, normalURL, rolloverURL) {
	(new Image()).src = rolloverURL;
	img.onmouseover = function() { img.src = rolloverURL; }
	img.onmouseout = function() { img.src = normalURL; }
	if (arguments.length > 3) {
		var hitURL = arguments[3];
		(new Image()).src = hitURL;
		img.onmousedown = function() { img.src = hitURL; }
		img.onmouseup = function() { img.src = rolloverURL; }
	}
}

// Displays a full image when a thumbnail is clicked
AppGlobal.showProductImage = function(obj) {
	// Get the image contained in the link object
	var imgThumb = obj.getElementsByTagName("img")[0];
	var imgFull = document.getElementById("imgMain");
	if (imgThumb && imgFull) {
		var divFull = imgFull.parentNode;
		while (divFull.firstChild) divFull.removeChild(divFull.firstChild);
		var imgFull = document.createElement("img");
		imgFull.src = imgThumb.src.replace("_smthumb.jpg", "_view.jpg");
		imgFull.setAttribute("alt", imgThumb.getAttribute("alt"));
		imgFull.id = "imgMain";
		if (imgFull.complete) divFull.appendChild(imgFull);
		imgFull.onload = function() { divFull.appendChild(this); }
	}
}

// Select an item in a drop-down list based on the	value or text
AppGlobal.selectDropDownItem = function(val, list, mode) {
	for (var x = 0; x < list.options.length; x++) {
		if (mode == "text" && val == list.options[x].text) { list.selectedIndex = x; return; }
		else if (mode == "value" && val == list.options[x].value) { list.selectedIndex = x; return; }
	}
}

// Cookie methods
var Cookie = {
	
	get: function(name) {
		var getValue = function(offset) {
			var endstr = document.cookie.indexOf (";", offset);
			if (endstr == -1) endstr = document.cookie.length;
			return unescape(document.cookie.substring(offset, endstr));
		}
		
		var arg = name + "=";
		var alen = arg.length;
		var clen = document.cookie.length;
		var i = 0;
		while (i < clen) {
			var j = i + alen;
			if (document.cookie.substring(i, j) == arg)
			return getValue(j);
			i = document.cookie.indexOf(" ", i) + 1;
			if (i == 0) break; 
		}
		return null;
	},
	
	set: function(name,value,expires,path,domain,secure) {
		tmppath = (path != "") ? path : basePath;
		tmpdomain = (domain != "") ? domain : baseDomain;
		document.cookie = name + "=" + escape (value) +
			((expires) ? "; expires=" + expires.toGMTString() : "") +
			((tmppath) ? "; path=" + tmppath : "") +
			((tmpdomain) ? "; domain=" + tmpdomain : "") +
			((secure) ? "; secure" : "");
	},
	
	fixDate: function(date) {
		var base = new Date(0);
		var skew = base.getTime(); // dawn of (Unix) time - should be 0
		if (skew > 0)  // Except on the Mac - ahead of its time
			date.setTime (date.getTime() - skew);
	}
}

// Browser detection methods
var Browser = {
	detect: function () {
		this.NAME = 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: [
		// Google Chrome
		{ string: navigator.userAgent, subString: "Chrome", identity: "Chrome" },
		// OmniWeb
		{ string: navigator.userAgent, subString: "OmniWeb", versionSearch: "OmniWeb/", identity: "OmniWeb" },
		// Safari
		{ string: navigator.vendor, subString: "Apple", identity: "Safari", versionSearch: "Version" },
		// Opera
		{ prop: window.opera, identity: "Opera" },
		// iCab
		{ string: navigator.vendor, subString: "iCab", identity: "iCab" },
		// Konqueror
		{ string: navigator.vendor, subString: "KDE", identity: "Konqueror" },
		// Firefox
		{ string: navigator.userAgent, subString: "Firefox", identity: "Firefox" },
		// Camino
		{ string: navigator.vendor, subString: "Camino", identity: "Camino" },
		// Newer Netscapes (6+)
		{ string: navigator.userAgent, subString: "Netscape", identity: "Netscape" },
		// Internet Explorer
		{ string: navigator.userAgent, subString: "MSIE", identity: "Internet Explorer", versionSearch: "MSIE" },
		// Generic Gecko-based Mozilla browsers
		{ string: navigator.userAgent, subString: "Gecko", identity: "Mozilla", versionSearch: "rv" },
		// Older Netscapes (4-)
		{ string: navigator.userAgent, subString: "Mozilla", identity: "Netscape", versionSearch: "Mozilla" }
	],
	dataOS : [
		// Microsoft Windows
		{ string: navigator.platform, subString: "Win", identity: "Windows" },
		// Mac OS
		{ string: navigator.platform, subString: "Mac", identity: "Mac" },
		// Linux
		{ string: navigator.platform, subString: "Linux", identity: "Linux" }
	]

};
Browser.detect();
