/* Main Javascript File */

var curpage;

/* compare functions */
function toggleCompare (prod_id) {
	var numchecked = 0;
	$("input[id^='compare_']").each (function () {
		if ($(this).attr ("checked") == true) {
			numchecked++;
		}
	});
	if (numchecked > 4) {
		$("#compare_" + prod_id).attr ("checked", false);
		alert ("You can only select up to 4 items to compare");
	}
}

function doCompare () {
	var numchecked = 0;
	var compareProds = "";
	$("input[id^='compare_']").each (function () {
		if ($(this).attr ("checked") == true) {
			numchecked++;
			compareProds += "&compare[]=" + $(this).val ();
		}
	});
	if (numchecked == 1) {
		alert ("Please select more than 1 item to compare");
	}
	else if (numchecked > 1) {
		url = "/php/categories_rev3.php?cmd=compare" + compareProds + "&prevpage=" + escape (document.location.href);

		$.fn.colorbox ({href: url, open: true, width: "850px", height: "600px", title: "Compare Items"});
	}
	else {
		alert ("Please select up to 4 items to compare");
	}
}

/* functions for quick search */
function focusQuickSearch (textbox) {
	if (textbox.value == "Search") {
		textbox.value = "";
	}
	else {
	}
}

function blurQuickSearch (textbox) {
	if (/^\s*$/.test (textbox.value)) {
		textbox.value = "Search";
	}
	else {
	}
}

// show/hide the UL object directly after the DIV object passed
function toggleMore (div_id) {
	if ($("#" + div_id).text () == "+ more") {
		$("#" + div_id + " + UL").show ();
		$("#" + div_id).text ("- less");
	}
	else {
		$("#" + div_id + " + UL").hide ();
		$("#" + div_id).text ("+ more");
	}
}

// toggle the hidden attributes (grayed out ones)
function toggleMoreSet (head_id) {
	var header_text = $("#" + head_id).text ();
	if (header_text.charAt (0) == "+") {
		$("#" + head_id + " + DIV").show ();
		$("#" + head_id).text (header_text.replace (/^\+/, "-"));
		$("#" + head_id).addClass ("hidden_active");
	}
	else {
		$("#" + head_id + " + DIV").hide ();
		$("#" + head_id).text (header_text.replace (/^\-/, "+"));
		$("#" + head_id).removeClass ("hidden_active");
	}
}

function sb_loadContact () {
	$.fn.colorbox ({href: "/php/contact_popup.php", open: true, width: "665px", height: "550px", title: "Contact Us", speed: 150, iframe: true});
}

function loadGoogleRatings () {
	$.fn.colorbox ({href: "http://www.google.com/products/reviews?cid=e898c34268ab73d8&sort=1", open: true, width: "800px", height: "550px", title: "Ratings for OnTimeSupplies.com", speed: 150, iframe: true});
}

function setupTonerFinderWidget (formclass) {
	$.getJSON ("/php/tonerfinder.php",
		{cmd: "getBrands"},
		function (j) {
			// setup top brands
			$(formclass + " select[name=brand]").append ("<option value=\"\"></option><option value=\"\" style=\"font-weight: bold;\">&gt;&gt; Popular Brands &lt;&lt;</option>\n");
			$(formclass + " select[name=brand]").append ("<option value=\"5\">CANON</option>\n");
			$(formclass + " select[name=brand]").append ("<option value=\"4\">EPSON</option>\n");
			$(formclass + " select[name=brand]").append ("<option value=\"9\">HP</option>\n");
			$(formclass + " select[name=brand]").append ("<option value=\"112\">KONICA MINOLTA</option>\n");
			$(formclass + " select[name=brand]").append ("<option value=\"2\">LEXMARK</option>\n");
			$(formclass + " select[name=brand]").append ("<option value=\"1\">OKIDATA</option>\n");
			$(formclass + " select[name=brand]").append ("<option value=\"3\">PANASONIC</option>\n");
			$(formclass + " select[name=brand]").append ("<option value=\"86\">RICOH</option>\n");
			$(formclass + " select[name=brand]").append ("<option value=\"13\">SHARP</option>\n");
			$(formclass + " select[name=brand]").append ("<option value=\"89\">TOSHIBA</option>\n");
			$(formclass + " select[name=brand]").append ("<option value=\"10\">XEROX</option>\n");

			$(formclass + " select[name=brand]").append ("<option value=\"\"></option><option value=\"\" style=\"font-weight: bold;\">&gt;&gt; All Brands &lt;&lt;</option>\n");

			for (i in j) {
				$(formclass + " select[name=brand]").append ("<option value=\"" + i + "\">" + j[i] + "</option>\n");
			}
			$(formclass + " select[name=brand]").change (function () {
				tonerFinderWidget_loadModels (formclass, $(this).val ());
			});
		}
	);
}

function tonerFinderWidget_loadModels (formclass, brand_id) {
	// clear models
	$(formclass + " select[name=model]").children ().remove ().end ().append ("<option value=\"\">-- select --</option>");

	if (brand_id.length > 0) {
		$.getJSON ("/php/tonerfinder.php",
			{cmd: "getModels", brand: brand_id},
			function (j) {
				for (i in j) {
					$(formclass + " select[name=model]").append ("<option value=\"" + i + "\">" + j[i] + "</option>\n");
				}
			}
		);
	}
}

function checkTonerFinderWidget (formclass) {
	if ($(formclass + " select[name=model]").val () > 0) {
		return true;
	}
	else {
		alert ("Please select a machine model");
	}
	return false;
}

function switchQuickFind (type) {
	switch (type) {
	case "categories":
		$("div#az_categories").show ();
		$("span#az_categoryazs").show ();
		$("div#az_tab_categories").addClass ("tab_on");
		$("div#az_tab_categories").removeClass ("tab_off");
		$("div#az_brands").hide ();
		$("span#az_brandazs").hide ();
		$("div#az_tab_brands").addClass ("tab_off");
		$("div#az_tab_brands").removeClass ("tab_on");
		curQuickFind = "categories";
		break;
	case "brands":
		$("div#az_categories").hide ();
		$("span#az_categoryazs").hide ();
		$("div#az_tab_categories").addClass ("tab_off");
		$("div#az_tab_categories").removeClass ("tab_on");
		$("div#az_brands").show ();
		$("span#az_brandazs").show ();
		$("div#az_tab_brands").addClass ("tab_on");
		$("div#az_tab_brands").removeClass ("tab_off");
		curQuickFind = "brands";
		break;
	}
}

var quickfind_highlight_type = "cat";
var quickfind_highlight_id = "";
var curQuickFind = "categories";

function setupQuickFind () {
	// load quick find links
	$("#az_quickfind_links").load ("/content/quickfind_links_rev3.html", function () {
		$('div.az a[href*=#]').click (function () {
			//alert ("Click");
			var target = $("div#az_" + curQuickFind + " a[name='" + this.hash.slice (1) + "']");
			if (target.length > 0) {
				var targetOffset = target.position ().top - $("div#az_" + curQuickFind + " a[name='az_top']").position ().top;
				$("div#az_" + curQuickFind).animate ({scrollTop: targetOffset}, 300);
			}
			return false;
		});

		switchQuickFind ("categories");

		quickfind_highlight ();
	});

	if ($("div.quickfind_container_180").length > 0) {
		$("div.quickfind_container_180").show ();
	}
	else {
		$("div.index_quickfind_container").show ();
	}
}

function quickfind_highlight () {
	var type = quickfind_highlight_type;
	var id = quickfind_highlight_id;

	if (type == "cat") {
		switchQuickFind ("categories");
		var target = $("#quickfind_cat_" + id);
		if (target.length > 0) {
			var targetOffset = target.position ().top - $("div#az_categories a[name='az_top']").position ().top - 100;
			$("div#az_categories").animate ({scrollTop: targetOffset}, 300);
			target.prepend ("&raquo; ");
			target.css ("font-weight", "bold").css ("font-size", "9pt");
		}
	}
	else if (type == "brand") {
		switchQuickFind ("brands");
		var target = $("#quickfind_brand_" + id);
		if (target.length > 0) {
			var targetOffset = target.position ().top - $("div#az_brands a[name='az_top']").position ().top - 100;
			$("div#az_brands").animate ({scrollTop: targetOffset}, 300);
			target.prepend ("&raquo; ");
			target.css ("font-weight", "bold").css ("font-size", "9pt");
		}
	}
}

function currency_format (num) {
	num = num.toString ().replace (/\$|\,/g, '');
	if (isNaN (num)) {
		num = "0";
	}
	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;
	}
	for (var i = 0; i < Math.floor ((num.length - (1 + i)) / 3); i++) {
		num = num.substring (0, num.length - (4 * i + 3)) + ',' + num.substring (num.length - (4 * i + 3));
	}
	return (((sign) ? '' : '-') + num + '.' + cents);
}

/* top navigation hover menus */
function setupTopnav (docobj) {
	$("li#topnav_os").append ($("div#topnav_os_rev3", docobj).html ());
	$("li#topnav_os div.subnav_rev3").css ("margin-left", "-" + ($("li#topnav_os").offset ().left - $("div.header_rev3 div.header_bot").offset ().left) + "px");

	$("li#topnav_of").append ($("div#topnav_of_rev3", docobj).html ());
	$("li#topnav_of div.subnav_rev3").css ("margin-left", "-" + ($("li#topnav_of").offset ().left - $("div.header_rev3 div.header_bot").offset ().left) + "px");

	$("li#topnav_tech").append ($("div#topnav_tech_rev3", docobj).html ());
	$("li#topnav_tech div.subnav_rev3").css ("margin-left", "-" + ($("li#topnav_tech").offset ().left - $("div.header_rev3 div.header_bot").offset ().left) + "px");

	$("li#topnav_jan").append ($("div#topnav_jan_rev3", docobj).html ());
	$("li#topnav_jan div.subnav_rev3").css ("margin-left", "-" + ($("li#topnav_jan").offset ().left - $("div.header_rev3 div.header_bot").offset ().left) + "px");

	$("div.header_rev3 div.topnav_qf").append ($("div#topnav_quickfind", docobj).html ());
	setupQuickFind ();
	$("div.header_rev3 div.topnav_qf span").click (function () {
		$("div.header_rev3 div.topnav_qf div.topnav_quickfind_container").toggle ();
	});

	// hover intent
	$("ul.topnav li.topnav").each (function () {
		$(this).hoverIntent ({
			sensitivity: 3,
			interval: 150,
			timeout: 150,
			over: function () {
				$(this).addClass ("hover");
				$("span.topnav", this).addClass ("hover");
				$("a.topnav", this).addClass ("hover");
				$("div.subnav_rev3", this).show ();
			},
			out: function () {
				$(this).removeClass ("hover");
				$("span.topnav", this).removeClass ("hover");
				$("a.topnav", this).removeClass ("hover");
				$("div.subnav_rev3", this).hide ();
			}
		});
	});
}

function setupTopnavQuickfind () {
	// load quick find links
	$("ul.topnav div.subnav_az div.links").load ("/php/quickfind.php?cmd=az_table", function () {
		$('ul.topnav div.subnav_az div.letters a[href*=#]').click (function () {
			//alert ("Click");
			var target = $("ul.topnav div.subnav_az div.links a[name='" + this.hash.slice (1) + "']");
			if (target.length > 0) {
				var targetOffset = target.position ().left - $("ul.topnav div.subnav_az div.links a[name='az_top']").position ().left;
				$("ul.topnav div.subnav_az div.links").animate ({scrollLeft: targetOffset}, 300);
			}
			return false;
		});
	});
}

function categoryLoadFeatured () {
	// hide products
	$("div#category_products").hide ();
	// show default template
	$("div#category_template").show ();

	// deselect all attributes
	$("DIV.default_left_column DIV.block_attributes DIV.atb_list INPUT[type=checkbox]").attr ("checked", false);

	// remove atbs cookie
	$.cookie ("cat_atbs_" + ca_id, null);
	// remove URL cookie
	$.cookie ("cat_url_" + ca_id, null);
}

function categoryToggleMoreAtbs (idx) {
	if ($("a#atb_more_" + idx).html () == "+ more") {
		$("ul#atb_" + idx + " li").addClass ("show");
		$("a#atb_more_" + idx).html ("- less");
	}
	else {
		$("ul#atb_" + idx + " li").removeClass ("show");
		$("a#atb_more_" + idx).html ("+ more");
	}
}

// save the state of attribute checkboxes
function categorySaveState () {
	var checkbox_state = "";
	$("DIV.default_left_column DIV.block_attributes DIV.atb_list INPUT[type=checkbox]:checked").each (function () {
		if (checkbox_state != "") {
			checkbox_state += ";";
		}
		checkbox_state += $(this).attr ("id");
	});
	$.cookie ("cat_atbs_" + ca_id, checkbox_state, {expires: 5, path: '/'});
	//alert ("set cookie");
}

// load the state of attribute checkboxes
function categoryLoadState () {
	// check to see if url params were passed through cookie
	var selected_atbnames = $.cookie ("cat_atbnames_" + ca_id);
	if (selected_atbnames && selected_atbnames.length > 0) {
		selected_atbnames = selected_atbnames.split (";");
		for (i = 0; i < selected_atbnames.length; i++) {
			atb_parts = selected_atbnames[i].split (":");
			$("DIV.default_left_column DIV.block_attributes DIV.atb_list INPUT[name='atbs[" + atb_parts[0] + "][]'][value='" + atb_parts[1] + "']").attr ("checked", true).parent ().parent ().addClass ("shown");
		}
		$.cookie ("cat_url_" + ca_id, "", {expires: 0});
		$.cookie ("cat_atbnames_" + ca_id, null, {expires: 0, path: '/'});

		categorySaveState ();
		categoryLoadProducts ();
	}
	else {
		var selected_atbs = $.cookie ("cat_atbs_" + ca_id)
		if (selected_atbs) {
			selected_atbs = selected_atbs.split (";");
			//alert (selected_atbs.length);
			if (selected_atbs.length > 0) {
				for (i = 0; i < selected_atbs.length; i++) {
					if (selected_atbs[i] != "") {
						$("#" + selected_atbs[i]).attr ("checked", true).parent ().parent ().addClass ("shown");
					}
				}
			}
		}
		var selected_url = $.cookie ("cat_url_" + ca_id);
		if (selected_url) {
			categoryUpdateProducts (selected_url);
		}
		else {
			categoryLoadProducts ();
		}
	}
}


function loadResellerRatings (ratings_container) {
	var rr_url = "/php/getResellerRatings.php";
	var max_comment_length = 300;

	$.get (rr_url, function (xml) {
		var overall_rating = $("overall_rating", xml).text ();
		var overall_reviews = $("overall_reviews", xml).text ();
		var seolink = $("seolink", xml).text ();

		$(ratings_container + " div.overall").html ("<b>" + overall_rating + "/10</b> rating, <b>" + overall_reviews + "</b> reviews\n");
		var count = 0;
		$("ROW", xml).each (function (id) {
			var rating = $("rating", $("ROW", xml).get (id)).text ();
			var answer = $("answer", $("ROW", xml).get (id)).text ();
			var comment = $("comment", $("ROW", xml).get (id)).text ();
			comment = comment.substr (0, max_comment_length) + (comment.length > max_comment_length ? "..." : "");
			var username = $("username", $("ROW", xml).get (id)).text ();
			var date = $("date", $("ROW", xml).get (id)).text ();
			date = date.substr (0, date.indexOf (" "));
			/*var active = (count == 0) ? " review_row_active" : "";*/
			if (count < 5) {
				$(ratings_container + " div.rows").append ("<div class=\"review_row\"><div class=\"comment\">" + comment + "</div><div class=\"author\">by " + username + ", " + date + "</div></div>");
			}
			count++;
		});

		$(ratings_container + " div.rows").cycle ({
			fx: 'fade',
			speed: 1000,
			timeout: 9000,
			cleartype: 1,
			cleartypeNoBg: true
		});

		$(ratings_container).click (function () {
			$.fn.colorbox ({href: seolink + "#reviews", open: true, width: "870px", height: "550px", title: "Our reviews at ResellerRatings.com", speed: 150, iframe: true});
		});
	});
}

/* Side Buttons */
function sb_loadContact () {
	$.fn.colorbox ({href: "/php/contact_popup.php", open: true, width: "665px", height: "550px", title: "Contact Us", speed: 150, iframe: true});
}

function sb_feedbackForm () {
	var myurl = document.location.href;
	myurl = myurl.replace ("http://www.ontimesupplies.com", "").replace ("https://www.ontimesupplies.com", "");

	$.fn.colorbox ({href: "http://www.ontimesupplies.com/feedback.php?url=" + escape (myurl), open: true, width: "665px", height: "550px", title: "Send Feedback", speed: 150, iframe: true});
}

// setup the enlarge button in list and grid views
function setupEnlargeButtons () {
	// When there is a list of items, enable the "enlarge" button on mouse over
	$("table.grid_container td, table.list_container tr").mouseover (function () {
		$("img.enlarge", $(this)).css ("display", "block");
	}).mouseout (function () {
		$("img.enlarge", $(this)).hide ();
	});

	// Individual colorbox
	/*$("a[class=colorbox]").each (function () {
		$(this).colorbox ({width: "80%", height: "80%", iframe: true});
	});*/
	$("a[class=colorbox]").each (function () {
	//$("a[class=colorbox]").click (function () {
		$(this).click (function () {
			$.fn.colorbox ({
				width: "80%",
				height: "80%",
				html: '<object width="100%" height="100%">\
	<param name="wmode" value="opaque">\
	<param name="movie" value="/js/zoom.swf">\
	<param name="zoomMax" value="100">\
	<param name="image" value="' + $(this).attr ("href") + '">\
	<embed src="/js/zoom.swf" flashvars="image=' + $(this).attr ("href") + '&amp;zoomMax=100" type="application/x-shockwave-flash" wmode="opaque" width="100%" height="100%"></embed>\
	</object>',
				open: true,
				scrolling: false
			});
			return false;
		});
	});
}

/* Item quickview */
function quickview_item (item_id) {
	// use colorbox to show item quickview
	$.fn.colorbox ({href: "/php/items_rev3.php?mode=quickview&id=" + item_id, open: true, width: "850px", height: "600px", title: "Item Quick View", speed: 150, iframe: true});
}
function quickview_close () {
	$.fn.colorbox.close ();
}

// currency format
function formatCurrency (num) {
	num = num.toString ().replace (/\$|\,/g, '');
	if (isNaN (num)) {
		num = "0";
	}
	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;
	}
	for (var i = 0; i < Math.floor ((num.length - (1 + i)) / 3); i++) {
		num = num.substring (0, num.length - (4 * i + 3)) + ',' + num.substring (num.length - (4 * i + 3));
	}
	return (((sign) ? '' : '-') + '$' + num + '.' + cents);
}

// trim
function trim (str) {
	str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}

/* add to list login and create account functions */
function addToList_login_warning (message) {
	$("div#add_to_list_login div.warning").text (message);
	$("div#add_to_list_login div.warning").show ();

	$("iframe.add_to_list_iframe").attr ("src", "/myaccount.php?cmd=blank");
}

function addToList_create_warning (message) {
	$("div#add_to_list_create div.warning").text (message);
	$("div#add_to_list_create div.warning").show ();

	$("iframe.add_to_list_iframe").attr ("src", "/myaccount.php?cmd=blank");
}

function addToList_login_success () {
	$("div.add_to_list_dialog div.logindiv").hide ();
	$("div.add_to_list_dialog form[name=add_to_list_form]").show ();

	$("iframe.add_to_list_iframe").attr ("src", "/myaccount.php?cmd=blank");

	load_addtolist_options ();
}

function addToList_add_warning (message) {
	$("div.add_to_list_confirmation").dialog ('option', 'title', 'Error');
	$("div.add_to_list_confirmation").html (message);

	$("iframe.add_to_list_iframe").attr ("src", "/myaccount.php?cmd=blank");
}

function addToList_add_success () {
	$("div.add_to_list_confirmation").dialog ('option', 'title', 'Success');
	$("div.add_to_list_confirmation").html ("Item added to your shopping list<br><a href=\"/lists.php\" class=\"viewlists\">View your Shopping Lists</a>");

	$("iframe.add_to_list_iframe").attr ("src", "/myaccount.php?cmd=blank");
}

function gsa_pricing_dialog () {
	$("div.gsa_pricing_dialog").dialog ({modal: true, buttons: {"Ok": function () { $(this).dialog("close"); }}});
}

function load_addtolist_options () {
	$.getJSON ("/lists.php", {method: "json"}, function (j) {
		var options = "";
		if (j.length > 0) {
			for (var i = 0; i < j.length; i++) {
				options += "<option value=\"" + j[i].id + "\">" + j[i].name + "</option>\n";
			}

			$("form[name=add_to_list_form] select[name=cu_li_id]").html (options);
			$("form[name=add_to_list_form] div.existing").show ();
			$("form[name=add_to_list_form] div.noexisting").hide ();
			$("form[name=add_to_list_form] input.list_radio").show ();
			$("form[name=add_to_list_form] input[name=newlist][value=no]").attr ("checked", true);
			$("form[name=add_to_list_form] input[name=newlist][value=yes]").attr ("checked", false);
		}
		else {
			$("form[name=add_to_list_form] select[name=cu_li_id]").html ("");
			$("form[name=add_to_list_form] div.existing").hide ();
			$("form[name=add_to_list_form] div.noexisting").show ();
			$("form[name=add_to_list_form] input.list_radio").hide ();
		}
	});
}

function setupAddToListDialog () {
	// add to list login
	$("div.add_to_list_dialog div.logintabs").tabs ();

	$("div.add_to_list_confirmation").dialog ({
		bgiframe: true,
		autoOpen: false,
		height: 100,
		width: 400,
		modal: true,
		buttons: {
			'OK': function () {
				$(this).html ('<div class="loading"><img src="/images/loading.gif"> Loading...</div>');
				$(this).dialog ('close');
			}
		}
	});

	// add to list dialog

	$("div.add_to_list_dialog").dialog ({
		bgiframe: true,
		autoOpen: false,
		height: 400,
		width: 420,
		modal: true,
		buttons: {
			'Add to List': function () {
				var newlist = $("form[name=add_to_list_form] input[name=newlist]:checked").val ();
				if (newlist == "no") {
					var list_id = $("form[name=add_to_list_form] select[name=cu_li_id]").val ();
					var prod_type = $("form[name=add_to_list_form] input[name=prod_type]").val ();
					var prod_productnum = $("form[name=add_to_list_form] input[name=prod_productnum]").val ();
					var prod_qty = $("form[name=add_to_list_form] input[name=prod_qty]").val ();
					var prod_uom = $("form[name=add_to_list_form] input[name=prod_uom]").val ();
					var prod_option = $("form[name=add_to_list_form] input[name=prod_option]").val ();
					var prod_params = $("form[name=add_to_list_form] input[name=prod_params]").val ();

					// enable new dialog
					$(this).dialog ('close');
					$("div.add_to_list_confirmation").dialog ('open');

					// send request
					$("iframe.add_to_list_iframe").attr ("src", "/lists.php?cmd=add_item&method=ajax&warningfunction=addToList_add_warning&successfunction=addToList_add_success&list_id=" + list_id + "&type=" + prod_type + "&productnum=" + prod_productnum + "&qty=" + prod_qty + "&uom=" + prod_uom + "&option=" + prod_option + "&params=" + prod_params);
				}
				else if (newlist == "yes") {
					// add new list
					var list_name = $("form[name=add_to_list_form] input[name=cu_li_name]").val ();
					if (/^\s*$/.test (list_name)) {
						alert ("Please enter a list name");
					}
					else {
						$.getJSON ("/lists.php", {cmd: "add_list", method: "json", cu_li_name: list_name}, function (j) {
							if (j.length > 0) {
								if (j[0].error == 1) {
									alert (j[0].message);
								}
								else {
									var list_id = j[0].list_id;
									var prod_type = $("form[name=add_to_list_form] input[name=prod_type]").val ();
									var prod_productnum = $("form[name=add_to_list_form] input[name=prod_productnum]").val ();
									var prod_qty = $("form[name=add_to_list_form] input[name=prod_qty]").val ();
									var prod_uom = $("form[name=add_to_list_form] input[name=prod_uom]").val ();
									var prod_option = $("form[name=add_to_list_form] input[name=prod_option]").val ();
									var prod_params = $("form[name=add_to_list_form] input[name=prod_params]").val ();

									// enable new dialog
									$("div.add_to_list_dialog").dialog ('close');
									$("div.add_to_list_confirmation").dialog ('open');

									// send request
									$("iframe.add_to_list_iframe").attr ("src", "/lists.php?cmd=add_item&method=ajax&warningfunction=addToList_add_warning&successfunction=addToList_add_success&list_id=" + list_id + "&type=" + prod_type + "&productnum=" + prod_productnum + "&qty=" + prod_qty + "&uom=" + prod_uom + "&option=" + prod_option + "&params=" + prod_params);
								}
							}
							else {
								alert ("Cannot create new list. Please try again");
							}
						});
					}
				}
				else {
					alert ("Please select a list or enter a name for a new list");
				}
			},
			'Cancel': function () {
				$(this).dialog ('close');
			}
		}
	});

}

function stockCheckScreen (sku) {
	$.fn.colorbox ({href: "/php/livestockcheck.php?item=" + sku, open: true, width: "90%", height: "90%", title: "Stock Check", speed: 150, iframe: true});
}

function digicertPopup () {
	var width = 480;
	var height = 525;
	var ww = screen.width;
	var hh = screen.height;
	var left = (ww - width) / 2;
	var top = (hh - height) / 2;
	window.open ('https://www.digicert.com/custsupport/sspopup.php?order_id=00166645&hostname=','oo',"dependent=1,height="+height+",width="+width+",left="+left+",top="+top+",location=0,menubar=0,resizable=0,scrollbars=0,status=0,toolbar=0");
}

/* In-page Logins */
function in_page_login_warning (message) {
	$("div#in_page_login div.warning").text (message);
	$("div#in_page_login div.warning").show ();

	$("iframe.in_page_login_frame").attr ("src", "/blank.html");
}

function in_page_login_success () {
	$("iframe.in_page_login_frame").attr ("src", "/blank.html");
	$("iframe.in_page_login_frame").load (function () {
		window.location.reload ();
	});
}

/* In page GSA Create Account */
function gsa_create_account_warning (message) {
	$("div#gsa_create_account div.warning").text (message);
	$("div#gsa_create_account div.warning").show ();

	$("iframe.gsa_create_account_frame").attr ("src", "/blank.html");
}

function gsa_create_account_success () {
	$("iframe.gsa_create_account_frame").attr ("src", "/blank.html");
	$("iframe.gsa_create_account_frame").load (function () {
		window.location.reload ();
	});
}

function setupItemSnippets () {
	$("div.item_snippet_container").hover (function () {
		$("div.add_to_cart img", this).attr ("src", "/images/add_to_cart2.small.on.gif");
		//$(this).parent ().fadeTo ("fast", 1.00);
		$(this).addClass ("item_snippet_container_hover");
	}, function () {
		$("div.add_to_cart img", this).attr ("src", "/images/add_to_cart2.small.gif");
		//$(this).parent ().fadeTo ("fast", 0.70);
		$(this).removeClass ("item_snippet_container_hover");
	});
}

/* Run these functions when document is ready */
$(document).ready (function () {

	setupEnlargeButtons ();

	// add to list
	setupAddToListDialog ();

	// Quick Find
	if ($("div.quickfind_outer").length > 0) {
		//setupQuickFind ();
	}

	// in page login
	$("a[rel=in_page_login]").colorbox ({
		width: "400px",
		height: "300px",
		rel: 'nofollow'
	});
	// GSA create account
	$("a[rel=gsa_create_account]").colorbox ({
		width: "500px",
		height: "420px"
	});
	// What is GSA
	$("a[rel=what_is_gsa]").colorbox ({
		width: "500px",
		height: "280px"
	});

	$("form.quicksearch input[name=query]").autocomplete ({
		minLength: 2,
		delay: 50,
		max: 15,
		source: search_keywords,
		focus: function (event, ui) {
			$("form.quicksearch input[name=query]").val (ui.item.value);
			return false;
		},
		select: function (event, ui) {
			$("form.quicksearch input[name=query]").val (ui.item.value);
			location.href = "http://www.ontimesupplies.com" + ui.item.url;
		}
	});

	// item snippets
	setupItemSnippets ();

	if (curpage == "category_main") {
		// functions specific to category page

		// featured prods
		$("DIV.category_container DIV.featured_items_container UL.featured_prods").cycle ({
			fx: 'scrollLeft',
			pager: 'DIV.category_container DIV.featured_items_container SPAN.nav',
			speed: 800,
			timeout: 5000,
			cleartypeNoBg: true,
			pause: true
		});

		// folded attributes
		$("DIV.default_left_column DIV.block_attributes H4.folded").click (function () {
			if ($(this).hasClass ("folded_active")) {
				$(this).removeClass ("folded_active");
				$("img", this).attr ("src", "/images/expand_icon.gif");
				$(this).next ().hide ();
			}
			else {
				$(this).addClass ("folded_active");
				$("img", this).attr ("src", "/images/collapse_icon.gif");
				$(this).next ().show ();
			}
		});
	}
	else if (curpage == "category_toplevel") {
		/*$("DIV.category_container DIV.sub_categories UL.catlist LI TABLE").each (function () {
			$(this).click (function (event) {
				$(this).next ().slideToggle ('fast');
			});
		});

		$("DIV.category_container DIV.sub_categories UL.catlist LI H3 A").each (function () {
			// disable links to 2nd level category
			$(this).click (function (event) {
				$(this).parent ().parent ().click ();
				return false;
			});
		});*/

		if (ca_id == "1") {
			// cycle the collections
			$("DIV.category_container DIV.office_furniture_top UL.colls").cycle ({
				fx: 'scrollLeft',
				pager: 'DIV.category_container DIV.office_furniture_top DIV.colls_nav',
				speed: 800,
				timeout: 5000,
				cleartypeNoBg: true,
				pause: true
			});
		}
	}
	else if (curpage == "category_midlevel") {
		// links
		$("DIV.category_container DIV.sub_categories UL.catlist LI").each (function () {
			$(this).click (function (event) {
				document.location.href = $("H3 A", this).attr ("href");
			});
		});
	}
	else if (curpage == "brand_main") {
		$("DIV.brand_container DIV.brand_categories UL.catlist LI TABLE").each (function () {
			$(this).click (function (event) {
				$(this).next ().slideToggle ('fast');
			});
		});

		// links
		$("DIV.brand_container DIV.brand_categories UL.catlist LI.thirdlevel").each (function () {
			$(this).click (function (event) {
				document.location.href = $("H3 A", this).attr ("href");
			});
		});
	}
	else if (curpage == "brands_list") {
		// links
		$("DIV.brand_container DIV.brandslist UL.brandslist LI").each (function () {
			$(this).click (function (event) {
				document.location.href = $("H3 A", this).attr ("href");
			});
		});
	}
	else if (curpage == "qs_main") {
	}
	else if (curpage == "index") {
		// featured products
		//$("#featured_prods").jcarousel ({scroll: 1});

		// deals of the day
		$("div.dotd div.main_container").cycle ({
			fx: 'scrollLeft',
			/*pager: 'DIV.category_container DIV.featured_items_container DIV.nav',*/
			speed: 800,
			timeout: 6000,
			cleartypeNoBg: true,
			cleartype: 1,
			pause: true,
			pager: 'div.dotd div.list_container',
			pagerAnchorBuilder: function (idx, slide) {
				return 'div.dotd div.list_container a:eq(' + idx + ')';
			}
		});

		if ($("div.dotd2").length > 0) {
			$("div.dotd2 div.main_container").cycle ({
				fx: 'scrollLeft',
				/*pager: 'DIV.category_container DIV.featured_items_container DIV.nav',*/
				speed: 800,
				timeout: 10000,
				cleartypeNoBg: true,
				cleartype: 1,
				pause: true,
				pager: 'div.dotd2 div.list_container',
				pagerAnchorBuilder: function (idx, slide) {
					return 'div.dotd2 div.list_container a:eq(' + idx + ')';
				}
			});
		}

		// toner finder
		//setupTonerFinderWidget ("form[name=tonerfinder_widget]");

		// reviews
		loadResellerRatings ("div.index_widget_ratings div.content");

		// my OTS
		if ($("div.myots_outer").length > 0) {
			$("div.myots_outer div.title").click (function () {
				$("div.myots_outer div.contents").hide ();
				$(this).next ().slideDown ("fast");
				return false;
			});
			$("div.myots_outer div.contents").hide ();
			$("div.myots_outer div.contents:first").slideDown ("fast");
		}
	}
	else if (curpage == "coll_list") {
	}
	else if (curpage == "kb_article") {
	}
});




/* Cart Functions */


function addToCart_item (productnum, qty, bulkmin, bulkmultiple, unitprice_avail) {
	qty = qty.replace (",", "");
	if (!/^[1-9][0-9]*$/.test (qty)) {
		alert ("Please enter a valid quantity, greater than 0");
		return;
	}
	qty = parseInt (qty);

	if (unitprice_avail == "n" && qty < bulkmin) {
		alert ("You must purchase at least " + bulkmin + " of this item.");
		return;
	}

	if (qty > bulkmin && qty % bulkmultiple != 0) {
		alert ("You must purchase this item in multiples of " + bulkmultiple + " if you order more than " + bulkmin + ".\nPlease purchase " + (Math.ceil (qty / bulkmultiple) * bulkmultiple));
		return;
	}

	//alert ("add to cart: " + qty);
	document.location.href = "/cart.php?cmd=add&type=item&id=" + productnum + "&quantity=" + qty + "&option=default&params=";
}

function addMultipleItems_to_cart (formname) {
	// see if any items are checked
	if ($("form[name=" + formname + "] input[type=checkbox][name^=addtocart_sku]:checked").length < 1) {
		alert ("Please select some items to add to your cart");
	}
	else {
		// check quantities
		var allclear = true;
		var url_params = "";

		$("form[name=" + formname + "] input[type=checkbox][name^=addtocart_sku]:checked").each (function () {
			if (allclear) {
				var cursku = $(this).val ();
				var qty = $("form[name=" + formname + "] input[type=text][name=qty_" + cursku + "]").val ();
				var skunum = $("form[name=" + formname + "] input[type=hidden][name=sku_" + cursku + "]").val ();
				var bulkqty = $("form[name=" + formname + "] input[type=hidden][name=bulkqty_" + cursku + "]").val ();
				var bulkmultiple = $("form[name=" + formname + "] input[type=hidden][name=bulkmultiple_" + cursku + "]").val ();
				bulkqty = parseInt (bulkqty);
				bulkmultiple = parseInt (bulkmultiple);

				qty = qty.replace (",", "");
				if (!/^[1-9][0-9]*$/.test (qty)) {
					alert ("Please enter a valid quantity for " + skunum + ", greater than 0");
					allclear = false;
				}
				qty = parseInt (qty);

				if (qty > bulkqty && qty % bulkmultiple != 0) {
					alert ("You must purchase item " + skunum + " in multiples of " + bulkmultiple + " if you order more than " + bulkqty + ".\nPlease purchase " + (Math.ceil (qty / bulkmultiple) * bulkmultiple));
					allclear = false;
				}

				url_params += "&id[" + cursku + "]=1&quantity[" + cursku + "]=" + qty;
			}
		});

		if (allclear) {
			document.location.href = "/cart.php?cmd=multiadd" + url_params;
		}
	}
}

function addToList_item (productnum, qty, bulkmin, bulkmultiple, prod_image, prod_title, prod_uom, unitprice_avail) {
	qty = qty.replace (",", "");
	if (!/^[1-9][0-9]*$/.test (qty)) {
		alert ("Please enter a valid quantity, greater than 0");
		return;
	}
	qty = parseInt (qty);

	if (unitprice_avail == "n" && qty < bulkmin) {
		alert ("You must purchase (or add to list) at least " + bulkmin + " of this item.");
		return;
	}

	if (qty > bulkmin && qty % bulkmultiple != 0) {
		alert ("You must purchase (or add to list) this item in multiples of " + bulkmultiple + " if you order more than " + bulkmin + ".\nPlease purchase (add to list) " + (Math.ceil (qty / bulkmultiple) * bulkmultiple));
		return;
	}

	//alert ("add to cart: " + qty);
	//document.location.href = "/cart.php?cmd=add&type=item&id=" + productnum + "&quantity=" + qty + "&option=default&params=";

	load_addtolist_options ();
	$("div.add_to_list_dialog").dialog ('open');
	$("DIV.add_to_list_dialog DIV.thumbnail IMG").attr ("src", prod_image);
	$("DIV.add_to_list_dialog DIV.details DIV.title").text (prod_title);
	//$("DIV.add_to_list_dialog DIV.details DIV.price").text ("$" + prod_price);
	$("DIV.add_to_list_dialog DIV.details DIV.qty").text ("Qty: " + qty);
	$("form[name=add_to_list_form] input[name=prod_type]").val ("item");
	$("form[name=add_to_list_form] input[name=prod_productnum]").val (productnum);
	$("form[name=add_to_list_form] input[name=prod_qty]").val (qty);
	$("form[name=add_to_list_form] input[name=prod_uom]").val (prod_uom);
	$("form[name=add_to_list_form] input[name=prod_option]").val ("default");
	$("form[name=add_to_list_form] input[name=prod_params]").val ("");
}

function changeQty (producttype, productnum, qty, uom, option, params, bulkmin, bulkmultiple, unitprice_avail) {
	qty = qty.replace (",", "");
	if (!/^[1-9][0-9]*$/.test (qty)) {
		alert ("Please enter a valid quantity, greater than 0");
		return;
	}
	qty = parseInt (qty);

	if (unitprice_avail == "n" && qty < bulkmin) {
		alert ("You must purchase at least " + bulkmin + " of this item.");
		return;
	}

	if (qty > bulkmin && qty % bulkmultiple != 0) {
		alert ("You must purchase this item in multiples of " + bulkmultiple + " if you order more than " + bulkmin + ".\nPlease purchase " + (Math.ceil (qty / bulkmultiple) * bulkmultiple));
		return;
	}

	document.location.href = "/cart.php?cmd=change&type=" + producttype + "&id=" + productnum + "&quantity=" + qty + "&uom=" + uom + "&option=" + option + "&params=" + escape (params);
}

function list_changeQty (list_id, producttype, productnum, qty, uom, option, params, bulkmin, bulkmultiple, unitprice_avail) {
	qty = qty.replace (",", "");
	if (!/^[1-9][0-9]*$/.test (qty)) {
		alert ("Please enter a valid quantity, greater than 0");
		return;
	}
	qty = parseInt (qty);

	if (unitprice_avail == "n" && qty < bulkmin) {
		alert ("You must add-to-list / purchase at least " + bulkmin + " of this item.");
		return;
	}

	if (qty > bulkmin && qty % bulkmultiple != 0) {
		alert ("You must add-to-list / purchase this item in multiples of " + bulkmultiple + " if you order more than " + bulkmin + ".\nPlease add-to-list / purchase " + (Math.ceil (qty / bulkmultiple) * bulkmultiple));
		return;
	}

	document.location.href = "/lists.php?cmd=change_item&list_id=" + list_id + "&type=" + producttype + "&id=" + productnum + "&quantity=" + qty + "&uom=" + uom + "&option=" + option + "&params=" + escape (params);
}

function list_removeItem (list_id, producttype, productnum, uom, option, params) {
	document.location.href = "/lists.php?cmd=change_item&list_id=" + list_id + "&type=" + producttype + "&id=" + productnum + "&quantity=0&uom=" + uom + "&option=" + option + "&params=" + escape (params);
}

function removeItem (producttype, productnum, uom, option, params) {
	document.location.href = "/cart.php?cmd=change&type=" + producttype + "&id=" + productnum + "&quantity=0&uom=" + uom + "&option=" + option + "&params=" + escape (params);
}


function list_checkall (checkstate) {
	$("div.shoppinglist_container form[name=listform] input[type=checkbox][name^=itemhash]").attr ("checked", checkstate);
}
function move_list_to_cart (list_id) {
	// check to see any items are selected
	if ($("div.shoppinglist_container form[name=listform] input[type=checkbox][name^=itemhash]:checked").length < 1) {
		alert ("Please select some items to add to your cart");
	}
	else {
		var itemhash_url = "";
		$("div.shoppinglist_container form[name=listform] input[type=checkbox][name^=itemhash]:checked").each (function () {
			itemhash_url += "&itemhash[]=" + $(this).val ();
		});
		list_url = "/lists.php?cmd=add_to_cart&list_id=" + list_id + itemhash_url;
		//alert (list_url);
		document.location.href = list_url;
	}
}
function move_to_list (list_id) {
	// check to see any items are selected
	if ($("div.shoppinglist_container form[name=listform] input[type=checkbox][name^=itemhash]:checked").length < 1) {
		alert ("Please select some items to move to another list");
	}
	else {
		var new_list_id = $("div.shoppinglist_container form[name=listform] select[name=new_list_id]").val ();

		var itemhash_url = "";
		$("div.shoppinglist_container form[name=listform] input[type=checkbox][name^=itemhash]:checked").each (function () {
			itemhash_url += "&itemhash[]=" + $(this).val ();
		});
		list_url = "/lists.php?cmd=move_to_list&list_id=" + list_id + "&new_list_id=" + new_list_id + itemhash_url;
		//alert (list_url);
		document.location.href = list_url;
	}
}


// collections
function addToCart_col (col_id, params) {
	//alert ("Collection ID: " + col_id + "\n\nParameters: " + params);
	document.location.href = "/cart.php?cmd=add&type=collection&id=" + col_id + "&quantity=1&option=default&params=" + escape (params);
}