// Global Namespace

var AppGlobal;
if (!AppGlobal) AppGlobal = {};

// Declare global variables
AppGlobal.BASE_URL = '/';
AppGlobal.CLASSPATH = 'js/classes/';
AppGlobal.overlay = null;

// 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.startsWith = function(str) {
	if (this.indexOf(str) == 0) return true;
	else return false;
};
String.prototype.endsWith = function(str) {
	if (this.indexOf(str) == (this.length + 1) - str.length) return true;
	else return false;
};
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, "");
}
// Validates an e-mail address
String.prototype.isEmailAddress = function() {
	var email = this;
	invalidChars = " /:,;"
	if (email == "") return false;
	for (var i = 0; i<invalidChars.length; i++) {
		badChar = invalidChars.charAt(i);
		if (email.indexOf(badChar,0) > -1) return false;
	}
	atPos = email.indexOf("@",1);
	if (atPos == -1) return false;
	if (email.indexOf("@",atPos+1) > -1) return false;
	periodPos = email.indexOf(".",atPos);
	if (periodPos == -1) return false;
	if (periodPos+3 > email.length)	return false;
	return true;
}
// Validates a date in M/D/Y format
String.prototype.isDate = function() {
	return /^\d{1,2}(\/|-)\d{1,2}(\/|-)\d{2,4}$/.test(this);
}
// Validates an integer
String.prototype.isInteger = function() { return (isNaN(this) || this.indexOf('.') != -1) ? false : true; };
// Validates currency
String.prototype.isCurrency = function() {
	return /^\d+(\.\d{2})?$/.test(this);
}
// Validates phone number
String.prototype.isPhoneNumber = function() {
	return /^\d{3}(-)?\d{3}(-)?\d{4}( .+)?/.test(this);
}

// 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>');
}

// Gets the number of days in a month
AppGlobal.getDaysInMonth = function(aDate){
	// returns the last day of a given month
	var m = new Number(aDate.getMonth());
	var y = new Number(aDate.getYear());
	var tmpDate = new Date(y, m, 28);
	var checkMonth = tmpDate.getMonth();
	var lastDay = 27;
	while(lastDay <= 31){
		temp = tmpDate.setDate(lastDay + 1);
		if(checkMonth != tmpDate.getMonth()) break;
		lastDay++
	}
	return lastDay;
}

// 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; }
	}
}

// Find product form methods
AppGlobal.onFocusFindProduct = function() {
	var form = document.getElementById("frmFindProduct");
	var field = form.t;
	if (field.value == 'Enter Keyword(s) or Blain Number') field.value = '';
}
AppGlobal.onFocusFindProductHeader = function() {
	var form = document.getElementById("frmFindProduct");
	var field = form.t;
	if (field.value == 'Find a Product') field.value = '';
}
AppGlobal.onBlurFindProduct = function() {
	var form = document.getElementById("frmFindProduct");
	var field = form.t;
	if (field.value == '') field.value = 'Enter Keyword(s) or Blain Number';
}
AppGlobal.onBlurFindProductHeader = function() {
	var form = document.getElementById("frmFindProduct");
	var field = form.t;
	if (field.value == '') field.value = 'Find a Product';
}
AppGlobal.onSubmitFindProduct = function() {
	var form = document.getElementById("frmFindProduct");
	var field = form.t;
	if (field.value == '' || field.value == 'Enter Keyword(s) or Blain Number' || field.value == 'Find a Product') {
		alert("Please enter one or more search terms.");
		return false;
	} else return true;
}

// Automatically tab to the specified field when the current field reaches a certain length
AppGlobal.autoTab = function(maxlength, field, next) {
	if (field.value.length >=  maxlength && next != null && next != undefined) next.select();
}

// Resizes the current browser window
AppGlobal.resizeWindow = function(valX, valY) {
	var maxX = Math.min(valX, screen.availWidth - 50);
	var maxY = Math.min(valY, screen.availHeight - 50);
	var moveX = 0;
	var moveY = 0;
	if (window.screenLeft) {
		if (window.screenLeft + maxX > screen.availWidth) moveX = screen.availWidth - (window.screenLeft + maxX);
		if (window.screenTop + maxY > screen.availHeight) moveY = screen.availHeight - (window.screenTop + maxY);
		window.moveBy(moveX, moveY);
	} else if (window.screenX) {
		if (window.screenX + maxX > screen.availWidth) moveX = screen.availWidth - (window.screenX + maxX);
		if (window.screenY + maxY > screen.availHeight) moveY = screen.availHeight - (window.screenY + maxY);
		window.moveBy(moveX, moveY);
	} else {
		window.moveTo(0, 0);
	}
	if (window.innerWidth) {
		iWidth = window.innerWidth;
		iHeight = window.innerHeight;
	} else if (document.documentElement.clientWidth) {
		iWidth = document.documentElement.clientWidth;
		iHeight = document.documentElement.clientHeight;
	} else {
		iWidth = document.body.clientWidth;
		iHeight = document.body.clientHeight;
	}
	iWidth = maxX - iWidth;
	iHeight = maxY - iHeight;
	window.resizeBy(iWidth, iHeight);
}

AppGlobal.preloadImages = function() {
	(new Image()).src = '/images/menu/cart_over.gif';
	(new Image()).src = '/images/menu/diy_projects_over.gif';
	(new Image()).src = '/images/menu/gift_cards_registries_over.gif';
	(new Image()).src = '/images/menu/gift_ideas_over.gif';
	(new Image()).src = '/images/menu/promotions_over.gif';
	(new Image()).src = '/images/menu/store_departments_over.gif';
	(new Image()).src = '/images/menu/store_services_over.gif';
}

// Sets up image rollovers
AppGlobal.setupRolloverImages = function() {
	// Get all of the images on this page and iterate through them to determine if any are rollovers
	var pageImages = document.getElementsByTagName("img");
	for (var x = 0; x < pageImages.length; x++) {
		// Get the base name of the current image
		var thisImage = pageImages[x].src.replace(location.protocol + '//' + location.hostname, '');
		for (var i = 0; i < arguments.length; i++) {
			if (thisImage.indexOf('/' + arguments[i] + '/') != -1 && thisImage.indexOf('_dis.') == -1) {
				// Preload rollover image
				var normalURL = thisImage;
				var rolloverURL = thisImage.replace('.', '_over.');
				// Setup rollover events
				AppGlobal.addRollover(pageImages[x], normalURL, rolloverURL);
			}
		}
	}
	// Get all of the image buttons on this page and iterate through them to determine if any are rollovers
	var inputElements = document.getElementsByTagName("input");
	for (var x = 0; x < inputElements.length; x++) {
		if (inputElements[x].getAttribute("type") == "image") {
			var thisImage = inputElements[x].src.replace(location.protocol + '//' + location.hostname, '');
			for (var i = 0; i < arguments.length; i++) {
				if (thisImage.indexOf('/' + arguments[i] + '/') != -1 && thisImage.indexOf('_dis.') == -1) {
					// Preload rollover image
					var normalURL = thisImage;
					var rolloverURL = thisImage.replace('.', '_over.');
					// Setup rollover events
					AppGlobal.addRollover(inputElements[x], normalURL, rolloverURL);
				}
			}
		}
	}
}

// Goes to the account registration page, including an e-mail address in the URL if one is filled in the form
AppGlobal.goToRegistration = function(a) {
	var txtEmail = document.getElementById("txtEmail");
	var strURL = a.href;
	var strJoin = (strURL.indexOf("?") != -1) ? "&" : "?";
	if (txtEmail) {
		if (txtEmail.value.isEmailAddress()) strURL += strJoin + "email=" + encodeURIComponent(txtEmail.value);
	}
	location.href = strURL;
	return false;
}

// Goes to the password recovery page, including an e-mail address in the URL if one is filled in the form
AppGlobal.goToPasswordRecovery = function(a) {
	var txtEmail = document.getElementById("txtEmail");
	if (!txtEmail) txtEmail = document.getElementById("txtVerifyEmail");
	var strURL = a.href;
	var strJoin = (strURL.indexOf("?") != -1) ? "&" : "?";
	if (txtEmail) {
		if (txtEmail.value.isEmailAddress()) strURL += strJoin + "email=" + encodeURIComponent(txtEmail.value);
	}
	location.href = strURL;
	return false;
}

// Opens a popup window describing what a blain number is
AppGlobal.openBlainNumberPopup = function() {
	AppGlobal.overlay = new Overlay("blainnum-popupobj");
}

// Pricing OnLoad directive
AppGlobal.onLoad = function() {
	// Load client-side form validation class if there is a form on this page
	// Preload images
	AppGlobal.preloadImages();
	// Sets up image rollovers
	AppGlobal.setupRolloverImages('navtabs', 'rollovers');
	// Initialize the find-product form
	(new Image()).src = '/images/interface/popup_bkg.png';
	if (document.getElementById("message-popupobj")) {
		AppGlobal.overlay = new Overlay("message-popupobj");
		var aClosePopupMessage = document.getElementById("aClosePopupMessage");
		if (aClosePopupMessage) aClosePopupMessage.onclick = AppGlobal.overlay.remove;
	}
	if (document.getElementById("blainnum-popupobj")) (new Image()).src = '/images/interface/blainnum_bkg.png';
}
AppGlobal.loadClass("Cookie");
AppGlobal.loadClass("Browser");
AppGlobal.loadClass("Overlay");
AppGlobal.loadClass("FormValidation");

// Assign onload parameter
if (window.addEventListener) window.addEventListener("load", AppGlobal.onLoad, false);
else if (window.attachEvent) window.attachEvent("onload", AppGlobal.onLoad);

