String.prototype.trim = function() { return this.replace(/(^\s*)|(\s*$)/g, ""); };
String.prototype.startsWith = function(str) { return this.substring(0, str.length) == str; };
String.prototype.endsWith = function(str) { return this.lastIndexOf(str) == this.length - str.length; };
String.prototype.pad = function(l, s, t) {
	return s || (s = " "), (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length)
		+ 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
		+ this + s.substr(0, l - t) : this;
}

//$.expr[':'].icontains = function(obj, index, meta, stack) {
//	return (obj.textContent || obj.innerText || jQuery(obj).text() || '').toLowerCase().indexOf(meta[3].toLowerCase()) >= 0;
//};
$.expr[':'].says = jQuery.browser.msie ? function(obj, index, meta, stack) {
	return jQuery(obj).text().toLowerCase() == meta[3].toLowerCase();
} : function(obj, index, meta, stack) {
	return (obj.textContent || obj.innerText || '').toLowerCase() == meta[3].toLowerCase();
};

//function pre_init_page() {
//	if (typeof PGVIEW == "object" && typeof PGVIEW.init == "function") PGVIEW.init();
//}

var _form;

function init_page() {
	_form = document.forms[0];
	if (typeof CART == "object" && typeof CART.init == "function") CART.init();
	if (typeof CATNAV == "object" && typeof CATNAV.init == "function") CATNAV.init();
	if (typeof PAGE == "object" && typeof PAGE.init == "function") PAGE.init();
	if (typeof SEARCH == "object" && typeof SEARCH.init == "function") SEARCH.init();
	if (typeof QUICKO == "object" && typeof QUICKO.init == "function") QUICKO.init();
	if (top!=self) document.body.scroll = "auto";
}


var CART = new function() {
	
	var _item_count = 0, _cart_items = null;
	
	this.init = function() {
		this.setItemCount(cart_item_count);
	};
	
	this.getProductPicks = function(){
		return _cart_items;
	};
	
	this.setItemCount = function(count){
		_item_count = count > 0 ? count : 0;
		if (_item_count == 0) _cart_items = null;
		jQuery("#header>ul.topnav>li:eq(3)").html(_item_count > 0 ? _item_count +" Items" : "Empty");
	};
	
	this.goToCheckout = function() {
		if (_item_count > 0){
			document.location = BASE_URL +"pages/checkout.aspx";
		}else{
			alert("There are currently no items in your cart.");
		}
	};
	
	this.loadCart = function(obj, callback) {
		if (typeof(callback)=="function") CART._loadCart_cb = callback;
		
		if (obj == true) {
			var fn_on_ajax_success = function(obj) {
				//console.dir(obj);
				CART.loadCart(obj);
				if (typeof(CART._loadCart_cb)=="function"){CART._loadCart_cb(); CART._loadCart_cb = null;}
			};
			$.ajax({
				url: BASE_URL + "ajax.aspx?id=cart-get-items", type: "POST", //contentType: "application/json",
				data: "JSON={}",
				dataType: "json",
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert("Error!\n" + textStatus + "\n" + errorThrown);
					//console.dir(XMLHttpRequest);
				},
				success: function(data, textStatus) {
					//alert("HTTP "+ this.type +"\n"+ textStatus +"\n"+ typeof(data));
					//console.dir(data);
					if (!("error" in data)) fn_on_ajax_success(data);
					else alert("Error!\n" + data.error);
				},
				complete: function(XMLHttpRequest, textStatus) {
					//alert("Complete.\n"+ textStatus);
				}
			});
		} else if (typeof obj == "object") {
			if ("products" in obj) {
				_cart_items = obj.products;
				this.setItemCount(_cart_items.length);
			} else {
				_cart_items = null;
				if ("message" in obj) alert(obj.message);
			}
		}
	};
	this._loadCart_cb = null;
	
	this.addToCart = function(sku, qty, callback) {
		if (typeof(callback)=="function") CART._addToCart_cb = callback;
		
		var fn_on_ajax_success = function(obj) {
			//console.dir(obj);
			CART.loadCart(obj);
			if (typeof(CART._addToCart_cb)=="function"){CART._addToCart_cb(); CART._addToCart_cb = null;}
		};
		
		var re = /"/g;

		$.ajax({
			url: BASE_URL + "ajax.aspx?id=quickorder-add-to-cart", type: "POST", //contentType: "application/json",
			data: "JSON=" + escape("{\"sku\":\"" + sku.replace(re, "\\\"") + "\",\"quantity\":" + qty + ",\"echo\":\"\"}"),
			dataType: "json",
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				alert("Error!\n" + textStatus + "\n" + errorThrown);
				//console.dir(XMLHttpRequest);
			},
			success: function(data, textStatus) {
				//alert("HTTP "+ this.type +"\n"+ textStatus +"\n"+ typeof(data));
				//console.dir(data);
				if (!("error" in data)) fn_on_ajax_success(data);
				else alert("Error!\n" + data.error);
			},
			complete: function(XMLHttpRequest, textStatus) {
				//alert("Complete.\n"+ textStatus);
			}
		});
	};
	this._addToCart_cb = null;
	
};


var CATNAV = new function() {
	this.init = function() {
		//jQuery("#leftnav>ul.categories ul.sub").css("display","none");
		jQuery("#leftnav>ul.categories ul.sub li.active>div").html("-");
		jQuery("#leftnav>ul.categories ul.sub li.active>ul.sub").css("display","inherit");
	};
	
	this.sc = function(c){
		var $n = jQuery("#leftnav>ul.categories #s"+ c);
		if ($n.css("display") == "none"){
			//$n.show();
			$n.css("display","inherit");
			
			$n = jQuery("#leftnav>ul.categories #"+ c +">div");
			$n.html("-");
		}else{
			//$n.hide();
			$n.css("display","none");
			
			$n = jQuery("#leftnav>ul.categories #"+ c +">div");
			$n.html("+");
		}
	};
	
	this.expand = function(c){
		var $n = jQuery("#leftnav>ul.categories #s"+ c);
		$n.css("display","inherit");
		
		$n = jQuery("#leftnav>ul.categories #"+ c +">div");
		$n.html("-");
	};
	
	this.collapse = function(c){
		var $n = jQuery("#leftnav>ul.categories #s"+ c);
		$n.css("display","none");
		
		$n = jQuery("#leftnav>ul.categories #"+ c +">div");
		$n.html("+");
	};

};


var SEARCH = new function() {
	this.init = function() {
		jQuery(_form.find).keydown(search_entry_kd);
	};

	var search_entry_kd = function(e) {
		//console.dir(e);
		var charCode = e.charCode ? e.charCode : e.keyCode;
		if (charCode == 13) {
			e.preventDefault();
			window.setTimeout("SEARCH.execute()", 100);
			return false;
		}
	}

	this.execute = function() {
		var s = alltrim(_form.find.value);
		if (s.length < 3) {
			alert("Please search a word or part number at least 3 characters long.");
		} else {
			document.location = BASE_URL +"pages/search.aspx?find=" + escape(s);
			//_form.action = BASE_URL + "pages/search.aspx";
			//_form.method = "get";
			//_form.__VIEWSTATE.disabled = true;
			//_form.submit();
		}
	};

};


function getNumber(str) {
	var re = /\d+/; //re.compile;
	str = re.exec(str);
	return str ? parseInt(str[0]) : null;
}

function showDropDown(){
	return true;	//do nothing
}

function alltrim(str) {
	return str.replace(/^\s+|\s+$/g, '');
}
function isEmail(mailvalue) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(mailvalue))
	{
		return (true);
	}
	return (false);
}
function IsNumeric(sText)
{
	var i = 0;
	var ValidChars = "0123456789";
	var IsNumber=true;
	var Char;
	for (i = 0; i < sText.length && IsNumber == true; i++) 
	{ 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) 
		{
			IsNumber = false;
        }
	}
	return IsNumber;
}
function isEmpty(str)
{	var strTrim
	if (alltrim(str) == "")	{
		return true;
	}	
	else {
		return false;
	}
}
function GetXmlHttpObject()
{
	var xmlHttp=null;
	try
	{
		xmlHttp=new XMLHttpRequest();
	}
	catch (e)
	{
		try
	    {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
	    }
		catch (e)
	    {
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
	    }
	}
	return xmlHttp;
}
var xmlHttp = GetXmlHttpObject();


/*
{
	"record_count": 685,
	"record_index": 0,
	"records_per_page": 5,
	"sort_expression": "",
	"sort_direction": "Ascending"
}
*/


var PGVIEW = new function() {
	
	this.init = function(config){
		
		this.prepare(false);
	};
	
	this.prepare = function(complete) {
		var $pgblocks = jQuery("#content_main>span.list_page_block");
		var pg_count = $pgblocks.length;
		//if (pg_count == 0) return;
		if (pg_count > 0) {
			$pgblocks.last().css("display", "none");
		}// else if (pg_count == 1) {
		//	$pgblocks.eq(0).css("visibility", "hidden");
		//}
		
	};
	
	this.finalize = function(){
		var $pgblocks = jQuery("#content_main>span.list_page_block");
		var pg_count = $pgblocks.length;
		if (!pg_count) return;
		
		$pgblocks.each(function(idx) {
			$(this).attr("id", "list_page_" + idx);
		});
		
		var $pgs = jQuery("#content_main>div.pagenum");
		var html = ["PAGE"];
		jQuery.each($pgblocks, function(idx, val) {
			html.push((idx > 0 ? "," : " ") + "<a href=\"javascript:\" onclick=\"PGVIEW.page(" + idx + ");\">" + (idx + 1) + "</a>" + (idx>0&&(idx+1)%30==0? "<br />": ""));
		});
		html.push(" <a class=\"next\" href=\"javascript:\" onclick=\"PGVIEW.page('next');\">Next</a> | <a class=\"prev\" href=\"javascript:\" onclick=\"PGVIEW.page('prev');\">Previous</a>");
		$pgs.html(html.join(''));
		
		PGVIEW.page(true); //resume last view
	};
	
	this.page = function(pg) {
		var $pg = jQuery("#content_main>span.list_page_block:visible");
		var current = $pg.length ? getNumber($pg.attr("id")) : null;
		if (typeof pg == "string") {
			var pg_count = jQuery("#content_main>span.list_page_block").length;
			//alert(current + "\n" + pg_count);
			if (pg == "next") {
				if (current < pg_count-1) PGVIEW.page(++current);
			} else if (pg == "prev") {
				if (current > 0) PGVIEW.page(--current);
			}
		} else if (typeof pg == "number") {
			$pg.css("display", "none");
			jQuery("#content_main>span.list_page_block:eq(" + pg + ")").css("display", "block");
			jQuery("#content_main>div.pagenum>a[class~=active]").removeClass("active");
			jQuery("#content_main>div.pagenum>a:says(" + (pg+1) + ")").addClass("active");
		} else if (pg==true) {
			//jQuery("#content_main>span.list_page_block:first").css("visibility", "");
			PGVIEW.page(0);
		}
	};
	
};