var baseClass = "_shield_klass";
var shieldClass = baseClass;
var shieldClassInc = 0;

$(function() {
	$('#floatLoc').hide();
});

function closeFloatingMenu()
{
	$('#floatLoc').hide("slow", function() {
			incClass();
    });
}

function refreshMenuWithManufacturerData(newN)
{
	var $j = jQuery;
	closeFloatingMenu();
	$j("#floatLoc").load("/fergusononline/manufacturerList?N=" + escape(newN));
	$j('#floatLoc').show("slow", onShowPop);
}

function refreshMenuWithNewData(newN)
{
	incClass();
	var $j = jQuery;	 
	closeFloatingMenu();
	$j('#floatLoc').html("<h3>Loading Please Wait</h3><br /><img src='/fergusononline/i/wait.gif' />");
	$j("#floatLoc").load("/fergusononline/dimmenu?N=" + escape(newN));
	$j('#floatLoc').show("slow", onShowPop);
}

	function refreshMenuWithData(queryString, theDimensionNameToExpose)
{
	var $j = jQuery;
	closeFloatingMenu();
	$j('#floatLoc').html("<h3>Loading Please Wait</h3><br /><img src='/fergusononline/i/wait.gif' />");
	$j("#floatLoc").load("dimensionValueList?queryString=" + escape(queryString) + "&exposeDimName=" + escape(theDimensionNameToExpose));
	$j('#floatLoc').show("slow", onShowPop);
}

	function onShowPop() {
		incClass();
		createShield('floatLoc', shieldClass);
		setTimeout("createShield('floatLoc', '" + shieldClass + "');", 2000);
	}
 
	function createShield(divId, shieldClass) {
		if (typeof document.all != 'undefined' && typeof window.opera == 'undefined' && navigator.vendor != 'KDE') {
			//alert("creates shield");
			var elm = document.getElementById(divId);
			var layer = document.createElement('iframe');
			layer.src = 'javascript:false;document.write("");';
			layer.tabIndex = '-1';
			layer.frameBorder = '0';
			elm.parentNode.appendChild(layer);
			
			layer.style.zIndex = "20";
			layer.style.position = "absolute";
			layer.className = shieldClass != null ? shieldClass : "layer_shield";
			layer.style.left = elm.offsetLeft + 'px';
			layer.style.top = elm.offsetTop + 'px';
			layer.style.width = elm.offsetWidth + 'px';
			layer.style.height = elm.offsetHeight + 'px';
		}
	}

	function removeShield(shieldClass) {
		var remClass = "." + (shieldClass != null ? shieldClass : "layer_shield");
		$(remClass).hide();
		$(remClass).remove();
	}
 
function incClass() {
	removeShield(shieldClass);
	shieldClass = baseClass + shieldClassInc++;
}

function openL1L2Menu(lowerchar, upperchar)
{
	$('#floatLoc').css({ left: 10, top: 10});
	$('#floatLoc').html("<h3>Loading Please wait</h3><br /><img src='images/wait.gif' />");
	$("#floatLoc").load("allcatmenu?lowerrange=" + lowerchar + "&upperrange=" + upperchar);
	$('#floatLoc').show("slow"); 
}

function sendSearchString(theString)
{
	$("#floatLoc").load("trap?SEARCHSTRING=" + theString); 
}

function openQuickLook(recordId, counter)
{
	$('#floatLoc').css({ left: 180, top: 130});
	var clickedLink = $("#notecard-link-" + counter);
	var toppos = clickedLink.offset().top;
	var leftpos = clickedLink.offset().left;
	$('#floatLoc').css({ left: leftpos, top: toppos});
	$('#floatLoc').html("<h3>Loading Please wait</h3><br /><img src='images/wait.gif' />");
	$("#floatLoc").load("quicklook?R=" + recordId + "&counter=" + counter );
	$('#floatLoc').show("slow"); 
}

// handles the "Compare Selected" button being clicked
function onCompareSelectedClicked() {
	// find all checked boxes, add them to the list
	$('p.product_compare input[@type=checkbox]:checked').each(function() {
		addToCompareList(this);
	});
	
	window.location = "showRecordCompare.do";
}

function removeWhenUnchecked(checkboxInput) {
	if (!checkboxInput.checked) {
		removeFromCompareList(checkboxInput.value);
	}
}

// checks if the max number of compare items has been exceeded, unchecks and alerts if so
function canAddToCompareList(checkboxInput) {
	var currentlyCheckedCount = getAllSelectedForComparison().length;

	if (currentlyCheckedCount > CustomerCompareList.getMaxSize()) {
		alert("You have exceeded the maximum number of items (4) to compare. \n Please remove other items to continue.");
		checkboxInput.checked = false;
		return false;
	} else {
		return true;
	}
}

function getAllSelectedForComparison() {
	var listItems = CustomerCompareList.getAllItems();
	var allItems = new Array();
	for (var i = 0; i < listItems.length; i++) {
		allItems.push(listItems[i].getId());
	}
	$('p.product_compare input[@type=checkbox]:checked').each(
		function() {
			if (!CustomerCompareList.getItem(this.value)) {
				allItems.push(this.value);
			}
		}
	);
	return allItems;
}

function addToCompareList(checkboxInput) {
	try {
		var o = CustomerCompareList.getItem("" + checkboxInput.value);
		if (!o) { // product already defined?
		
			if (!canAddToCompareList(checkboxInput)) {
				return false;
			}
			
			o = CustomerCompareList.createNewItem();
			o.setId("" + checkboxInput.value);
			CustomerCompareList.addItem(o);
			GlobalStorageManager.saveList("CustomerCompareList", CustomerCompareList);
		}
	} catch (e) {
		if (e.getMessage) alert(e.getMessage());
	}
}

function removeFromCompareList(rNumberValue) {
	try {
		var o = CustomerCompareList.getItem("" + rNumberValue);
		if (o) {
			CustomerCompareList.removeItem(o);
		}
		GlobalStorageManager.saveList("CustomerCompareList", CustomerCompareList);
	} catch (e) {
		if (e.getMessage) alert(e.getMessage());
	}
}

function refreshMyListCounts() {
	$("#myListCountDiv").html(CustomerProductList.getAllItems().length || "0");
	$("#list_item_count").html(CustomerProductList.getAllItems().length || "0");
}

function addToMyList(rNumber)
{
	try {
		var o = CustomerProductList.getItem("" + rNumber);
		if (!o) { // product already defined?

			if (CustomerProductList.getAllItems().length == CustomerProductList.getMaxSize()) {
				alert("You have reached the maximum number of items (100) on your list.");
				return false;
			}

			o = CustomerProductList.createNewItem();
			o.setId("" + rNumber);
			CustomerProductList.addItem(o);
			GlobalStorageManager.saveList("CustomerProductList", CustomerProductList);
		}
	} catch (e) {
		if (e.getMessage) alert(e.getMessage());
	}
	
	document.location.href = 'showMyList.do';
}

function removeFromMyList(rNumber, button)
{
	try {
		var o = CustomerProductList.getItem("" + rNumber);
		if (o) {
			CustomerProductList.removeItem(o);
		}
		GlobalStorageManager.saveList("CustomerProductList", CustomerProductList);
	} catch (e) {
		if (e.getMessage) alert(e.getMessage());
	}

	refreshMyListCounts(); 	
	$(button).parents('tr').fadeOut("slow");
  
  if (CustomerProductList.getAllItems().length == 0) {
    document.location.href = 'showMyList.do';
  }
}

function clearMyListIfVerified() {
	var response = confirm("Remove all items from your list?");
	if (response) {
		removeAllFromMyList();
	}
}

function removeAllFromMyList() {
	try {
		var allItems = CustomerProductList.getAllItems();
		for (var i = 0; i < allItems.length; i++) {
			CustomerProductList.removeItem(allItems[i]);
		}
		GlobalStorageManager.saveList("CustomerProductList", CustomerProductList);
	} catch (e) {
		if (e.getMessage) alert(e.getMessage());
	}
	
	refreshMyListCounts();
	
	document.location.href = 'showMyList.do';
}

function printerFriendly() {
	document.getElementById('css1').href = 'css/print.css'; 
}

function addParam(list, elId) {
	if ($(elId)[0] && $(elId)[0].value != "") {
		list.push($(elId)[0].value);
	}
}

function validateQuickCompareCallback(response) {
	
	if (!response) { 
		alert("A problem was encountered while validating the products, please contact the admin.");
	} else {
		var validElements = response.getElementsByTagName("valid");
		var passedAll = true;
		passedAll = updateQuickCompareElement("div.quickcompareDynamic input.qc1", validElements) && passedAll;
		passedAll = updateQuickCompareElement("div.quickcompareDynamic input.qc2", validElements) && passedAll;
		passedAll = updateQuickCompareElement("div.quickcompareDynamic input.qc3", validElements) && passedAll;
		passedAll = updateQuickCompareElement("div.quickcompareDynamic input.qc4", validElements) && passedAll;
		
		if (passedAll) {
			$("div.quickcompareDynamic input.quickcompare-button").each(function() {
				this.value = "Compare Selected"
			});
		} else {
			$("div.quickcompareDynamic input.quickcompare-button").each(function() {
				this.value = "Validate"
			});
		}
	}
	
}

function updateQuickCompareElement(selector, validItems) {
	var el = $(selector)[0];
	
	var matched = false;
	for (var i = 0; i < validItems.length; i++) {
		var productId = validItems[i].getAttribute("productId");
		var productCode = validItems[i].getAttribute("productCode");
		if (productCode == el.value || productId == el.value) {
			try {
				var o = CustomerCompareList.getItem(productId);
				if (!o) { // product already defined?
				
					if (CustomerCompareList.getAllItems().length == CustomerCompareList.getMaxSize()) {
						alert("You have reached the maximum number of items (4) to compare. \n Please remove other items to continue.");
						rNumber.checked = false;
						return false;
					}
					
					o = CustomerCompareList.createNewItem();
					o.setId(productId);
					CustomerCompareList.addItem(o);
					GlobalStorageManager.saveList("CustomerCompareList", CustomerCompareList);
				}
			} catch (e) {
				if (e.getMessage) alert(e.getMessage());
			}
			
			matched = true;
			break;
		}
	}
	
	if (!matched) {
		if (el.value != "") {
			el.value = "Invalid";
			return false;
		}
	}
	
	return true;
}

function validateQuickCompare(button) {
	if (button.value == "Validate") {
		var list = new Array();
		
		// the modal is actually a copy of the html, so access by id fails
		addParam(list, "div.quickcompareDynamic input.qc1");
		addParam(list, "div.quickcompareDynamic input.qc2");
		addParam(list, "div.quickcompareDynamic input.qc3");
		addParam(list, "div.quickcompareDynamic input.qc4");
		
		if (list.length < 1) {
			alert("Please enter the product code");
			return false;
		}
		
		button.value = "Working...";
		
		$.get("validateIds.do", { "ids" : list }, validateQuickCompareCallback);

	} else {
		button.value = "Compare Selected";
		document.location.href = "showRecordCompare.do"; 		
	}
}

// fires whenever the compare user input is changed
function itemChanged() {
	$("div.quickcompareDynamic input.quickcompare-button").each(function() {
		this.value = "Validate"
	});
}

// the modal is actually a copy of the html, so access by id fails
function synchQuickCompare() {
	// reset inputs
	$("div.quickcompareDynamic input.qc1").val('');
	$("div.quickcompareDynamic input.qc2").val('');
	$("div.quickcompareDynamic input.qc3").val('');
	$("div.quickcompareDynamic input.qc4").val('');

	var items = getAllSelectedForComparison();
	for (var i = 0; i < items.length; i ++) {
		var index = i + 1; // 1 based
		$("div.quickcompareDynamic input.qc" + index).val(items[i]);
	}
}

// fires when clear is clicked in the quick compare popup
function removeFromQuickList(index) {
	var productId = $("div.quickcompareDynamic input.qc" + (index + 1)).val();
	productId = $.trim(productId);
	
	// remove from list (if already in list)
	if (productId) {
		try {
			var entity = CustomerCompareList.getItem(productId);
			if (entity) {
				CustomerCompareList.removeItem(entity);
				GlobalStorageManager.saveList("CustomerCompareList", CustomerCompareList);
			}
		} catch (e) {
			if (e.getMessage) alert(e.getMessage());
		}
	}
	
	// uncheck checkbox
	$('p.product_compare input[@type=checkbox]:checked').each(
		function() {
			if (this.value == productId) {
				this.checked = false;
			}
		}
	);
	
	// clear from quick compare input
	$("div.quickcompareDynamic input.qc" + (index + 1)).val('');
}

function openPurchaseLocations(select) {
	if (select.value != '')
	{
		window.open(select.value);
		select.selectedIndex = 0;
	}
}
