/** Initialize the Main Nav's drop-down menus **/
new Event.observe(window,'load',function() { initializeSubMenus(); });

function initializeSubMenus() {
	var images = new Array('images/bg_menu_sel_left.gif','images/bg_menu_sel_right.gif','images/bg_menu_hov_left.gif','images/bg_menu_hov_right.gif','images/subnav_bl.png','images/subnav_br.png','images/subnav_tr.png');
	var menuimg = new Array();
	for(var x=0;x<images.length;x++) {
		menuimg[x] = new Image();
		menuimg[x].src = images[x];
	}
}

/* Load error variables */
var error1 = 'We encountered an error while trying to communicate with the server. Please refresh the page.';

var hidden = false;
var shown = false;
function hideSelects(selects) {
	shown = true;
	if(!hidden) {
		for(var i = 0; i<selects.length; i++) {
			$(selects[i]).setStyle({'position':'relative','display':'none'});
		}
	}
	hidden = true;
}
function showSelects(selects) {
	shown = false;
	setTimeout(function() {
		if(!shown) {
			for(var i = 0; i<selects.length; i++) {
				$(selects[i]).show();
			}
			hidden = false;
		}
	},500);
}
function openSubMenu(element) {
	var id = $(element).identify();
	$(id).up().removeClassName('selected');
}
function closeSubMenu(element) {
	var id = $(element).identify();
	$(id).up().addClassName('selected');
}

function printWindow() {
	window.print();
}
function doNav(url) {
	document.location.href = url;
}
function doNavNewWindow(url) {
	window.open(url,'_blank');
}
function doNavLightView(url) {
	Lightview.show({
		href: url,
		rel: 'ajax',
		options: {
			autosize: true,
			topclose: true
		}
	});
}
function closeLightView() {
	Lightview.hide();
}
function pleaseWait(id) {
	$('pleaseWait'+id).show();
}
function showLoader() {
	$('loaderProcessing').style.display = 'block';
}
function deleteThis(id,type) {
	if(confirm('Are you sure you want to completely remove this '+type+'?')) {
		var url = $(id).href;
		doNav(url);
	}
	return false;
}
function deleteThisLightView(id,type) {
	if(confirm('Are you sure you want to completely remove this '+type+'?')) {
		var url = $(id).href;
		doNavLightView(url);
	}
	return false;
}
function submitAjaxForm(id,div) {
	$(id).request({
		onSuccess:function(transport) {
			$(div).update(transport.responseText);
		}
	});
	return false;
}
function submitAjaxFormLightView(id,url) {
	$(id).request({
		onComplete:function(transport) {
			if(transport.responseText != '') {
				alert(transport.responseText);
				doNavLightView(transport.responseText);
			} else {
				doNavLightView(url);
			}
		}
	});
	return false;
}
/* Pricing Tier Ajax Functions */
function submitPricingForm() {
	var vars = $('pricingForm').serialize();
	var url = $('pricingForm').action;
	new Ajax.Request(url+'&'+vars,{
		method:'get',
		onSuccess:function(transport) {
			var r = transport.responseText;
			doNavLightView(r);
		},
		onFailure:function() { alert('There was a problem communicating with the server. Please try again.'); }
	});
	return false;
}
function addPricingTier(i,el) {
	var el = $(el).identify();
	var newi = i;
	new Ajax.Request('ajax_pricing.php?action=addtier&i='+i,{
		method:'get',
		onSuccess:function(transport) {
			var response = transport.responseText;
			$('customTiers').insert(response);
		},
		onFailure:function() { alert('There was a problem communicating with the server. Please try again.'); }
	});
	newi++;
	$(el).onclick = function() { return addPricingTier(newi,el); };
	return false;
}
function refreshPricingTiers() {
	var value = $F('pricing');
	var parent = $('pricing').up();
	parent = $(parent).identify();
	new Ajax.Updater(parent,'ajax_pricing.php?action=refreshpricingtiers&chosen='+value);
}
function removeElement(id,text) {
	if(confirm('Are you sure you want to remove this '+text+'?')) {
		$(id).remove();
	}
	return false;
}

/* Customer Buyer Ajax Functions */
function toggleUsernameInfo() {
	var ac = $F('activeSelect');
	if(ac == 'yes') {
		$('usernameInfo').show();
	} else {
		$('usernameInfo').hide();
	}
	return false;
}
function submitBuyerForm() {
	var vars = $('buyerForm').serialize();
	var url = $('buyerForm').action;
	new Ajax.Request(url+'&'+vars,{
		method:'get',
		onSuccess:function(transport) {
			var r = transport.responseText;
			if(r == 'close') {
				closeLightView();
			} else {
				doNavLightView(r);
			}
		},
		onFailure:function() { alert('There was a problem communicating with the server. Please try again.'); }
	});
	return false;
}
function loadCustomerBuyers(cid) {
	new Ajax.Updater('buyerList','ajax_buyers.php?cid='+cid);
}

/* Customer Ship-To Ajax Functions */
function submitShipToForm() {
	var vars = $('shipToForm').serialize();
	var url = $('shipToForm').action;
	new Ajax.Request(url+'&'+vars,{
		method:'get',
		onSuccess:function(transport) {
			var r = transport.responseText;
			if(r == 'close') {
				closeLightView();
			} else {
				doNavLightView(r);
			}
		},
		onFailure:function() { alert('There was a problem communicating with the server. Please try again.'); }
	});
	return false;
}
function loadShipTos(cid) {
	new Ajax.Updater('shipToList','ajax_shiptos.php?cid='+cid);
}
/* Customer Payment Methods Ajax Functions */
function submitPaymentMethodForm() {
	var vars = $('paymentMethodForm').serialize();
	var url = $('paymentMethodForm').action;
	new Ajax.Request(url+'&'+vars,{
		method:'get',
		onSuccess:function(transport) {
			var r = transport.responseText;
			if(r == 'close') {
				closeLightView();
			} else {
				Lightview.show({
					href: r,
					rel: 'ajax',
					options: {
						autosize: true,
						topclose: true,
						ajax: { onComplete:function() { new Event.observe('method','change',function() { switchPaymentMethod(); }) } }
					}
				});
			}
		},
		onFailure:function() { alert('There was a problem communicating with the server. Please try again.'); }
	});
	return false;
}
function switchPaymentMethod() {
	var chosen = $F('method');
	new Ajax.Updater('methodInfoContainer','ajax_paymentmethods.php?action=method&type='+chosen);
}
function loadPaymentMethods(cid) {
	new Ajax.Updater('paymentMethodsList','ajax_paymentmethods.php?cid='+cid);
}

/* Customers */
var loadingCustomers = false;
function loadCustomers(newSearch) {
	if(loadingCustomers) {
		loadingCustomers.transport.abort();
	}
	$('customerDisplay').update('<div align="center"><br /><br /><br /><br /><img src="images/loader_gray_lg.gif" border="0" /><br /><br /><span class="dkgray t16">Loading Customers...Please Wait</span><br /><br /><br /><br /></div>');
	var search = $F('ajaxSearch');
	if($('ajaxInactive').checked) {
		var inactive = '';
	} else {
		var inactive = 'no';
	}
	new Ajax.Request('ajax_customers.php?action=customers&search='+search+'&inactive='+inactive+'&new='+newSearch,{
		method:'get',
		onCreate:function(request) { var loadingCustomers = request; },
		onSuccess:function(transport) {
			var response = transport.responseText;
			$('customerDisplay').update(response);
			loadingCustomers = false;
		},
		onFailure:function() { alert('We encountered an error while trying to communicate with the database. Please refresh the page.'); }
	});
	return false;
}
function changeCustomerPage(page) {
	if(loadingCustomers) {
		loadingCustomers.transport.abort();
	}
	var search = $F('ajaxSearch');
	if($('ajaxInactive').checked) {
		var inactive = '';
	} else {
		var inactive = 'no';
	}
	new Ajax.Request('ajax_customers.php?action=customers&search='+search+'&inactive='+inactive+'&page='+page,{
		method:'get',
		onCreate:function(request) { var loadingCustomers = request; },
		onSuccess:function(transport) {
			var response = transport.responseText;
			$('customerDisplay').update(response);
			loadingCustomers = false;
		},
		onFailure:function() { alert('We encountered an error while trying to communicate with the database. Please refresh the page.'); }
	});
	return false;
}

/* Product Conditions Ajax Functions */
function submitProductConditionForm() {
	var vars = $('productConditionForm').serialize();
	var url = $('productConditionForm').action;
	new Ajax.Request(url+'&'+vars,{
		method:'get',
		onSuccess:function(transport) {
			var r = transport.responseText;
			if(r == 'close') {
				closeLightView();
			} else {
				doNavLightView(r);
			}
		},
		onFailure:function() { alert('There was a problem communicating with the server. Please try again.'); }
	});
	return false;
}
function refreshProductConditions() {
	var parent = $('condition').up();
	parent = $(parent).identify();
	new Ajax.Updater(parent,'ajax_product_conditions.php?action=refreshproductconditions');
}

/* Lead Times Ajax Functions */
function submitLeadtimeForm() {
	var vars = $('leadtimeForm').serialize();
	var url = $('leadtimeForm').action;
	new Ajax.Request(url+'&'+vars,{
		method:'get',
		onSuccess:function(transport) {
			var r = transport.responseText;
			if(r == 'close') {
				closeLightView();
			} else {
				doNavLightView(r);
			}
		},
		onFailure:function() { alert('There was a problem communicating with the server. Please try again.'); }
	});
	return false;
}
/* Products */
var loadingProducts = false;
function loadProducts(newSearch) {
	if(!newSearch) {
		newSearch = 'no';
	}
	if(loadingProducts) {
		loadingProducts.transport.abort();
	}
	$('productDisplay').update('<div align="center"><br /><br /><br /><br /><img src="images/loader_gray_lg.gif" border="0" /><br /><br /><span class="dkgray t16">Loading Products...Please Wait</span><br /><br /><br /><br /></div>');
	var search = $F('ajaxSearch');
	if($('ajaxInactive').checked) {
		var inactive = '';
	} else {
		var inactive = 'no';
	}
	new Ajax.Request('ajax_products.php?action=products&search='+search+'&inactive='+inactive+'&new='+newSearch,{
		method:'get',
		onCreate:function(request) { var loadingProducts = request; },
		onSuccess:function(transport) {
			var response = transport.responseText;
			$('productDisplay').update(response);
			loadingProducts = false;
		},
		onFailure:function() { alert('We encountered an error while trying to communicate with the database. Please refresh the page.'); }
	});
	return false;
}
function changeProductPage(page) {
	if(loadingProducts) {
		loadingProducts.transport.abort();
	}
	var search = $F('ajaxSearch');
	if($('ajaxInactive').checked) {
		var inactive = '';
	} else {
		var inactive = 'no';
	}
	new Ajax.Request('ajax_products.php?action=products&search='+search+'&inactive='+inactive+'&page='+page,{
		method:'get',
		onCreate:function(request) { var loadingProducts = request; },
		onSuccess:function(transport) {
			var response = transport.responseText;
			$('productDisplay').update(response);
			loadingProducts = false;
		},
		onFailure:function() { alert('We encountered an error while trying to communicate with the database. Please refresh the page.'); }
	});
	return false;
}
function addQtyDiscount(i,el) {
	el = $(el).identify();
	var newi = i;
	new Ajax.Request('ajax_products.php?action=addQtyDiscount&i='+i,{
		method:'get',
		onSuccess:function(transport) {
			var r = transport.responseText;
			$('qtyDiscountsContainer').insert(r);
		},
		onFailure:function() { alert('We encountered an error while trying to communicate with the database. Please refresh the page.'); }
	});
	newi++;
	$(el).onclick = function() { return addQtyDiscount(newi,el); }
	return false;
}
function removeQtyDiscount(i) {
	$('qtyDiscount'+i).remove();
	return false;
}
function removeCurrentImage(id,img) {
	if(confirm('Are you sure you want to remove this image? This action is unrecoverable.')) {
		new Ajax.Updater(id,'ajax_products.php?action=removeimage&img='+img);
	}
	return false;
}

var loadingSearchResults = false;
function submitSearchResults() {
	//$('advancedSearchContainer').hide();
	if(loadingSearchResults) {
		loadingSearchResults.transport.abort();
	}
	var query = $('searchForm').serialize();
	$('productContainer').update('<div align="center"><br /><br /><img src="images/loader_gray_lg.gif" border="0" /><br /><br /><span class="gray t16">Loading Search Results...Please Wait</span><br /><br /><br /><br /></div>');
	new Ajax.Request('ajax_products.php?action=productSearch&page=1&'+query,{
		method:'get',
		onCreate:function(request) { var loadingSearchResults = request; },
		onSuccess:function(transport) {
			var response = transport.responseText;
			$('productContainer').update(response);
			loadingSearchResults = false;
			//initializeStoreNav();
		},
		onFailure:function() { alert('We encountered an error while trying to communicate with the database. Please refresh the page.'); }
	});
	return false;
}
function loadSearchResults() {
	if(loadingSearchResults) {
		loadingSearchResults.transport.abort();
	}
	var query = $('searchForm').serialize();
	$('productContainer').update('<div align="center"><br /><br /><img src="images/loader_gray_lg.gif" border="0" /><br /><br /><span class="gray t16">Loading Search Results...Please Wait</span><br /><br /><br /><br /></div>');
	new Ajax.Request('ajax_products.php?action=productSearch&'+query,{
		method:'get',
		onCreate:function(request) { var loadingSearchResults = request; },
		onSuccess:function(transport) {
			var response = transport.responseText;
			$('productContainer').update(response);
			loadingSearchResults = false;
			//initializeStoreNav();
		},
		onFailure:function() { alert('We encountered an error while trying to communicate with the database. Please refresh the page.'); }
	});
	return false;
}
function changeSearchResultsPage(page) {
	//$('advancedSearchContainer').hide();
	if(loadingSearchResults) {
		loadingSearchResults.transport.abort();
	}
	var query = $('searchForm').serialize();
	new Ajax.Request('ajax_products.php?action=productSearch&page='+page+'&'+query,{
		method:'get',
		onCreate:function(request) { var loadingSearchResults = request; },
		onSuccess:function(transport) {
			var response = transport.responseText;
			$('productContainer').update(response);
			loadingSearchResults = false;
		},
		onFailure:function() { alert('We encountered an error while trying to communicate with the database. Please refresh the page.'); }
	});
	return false;
}
function toggleQty(key) {
	if($('product'+key).checked) {
		$('qtyContainer'+key).show();
	} else {
		$('qtyContainer'+key).hide();
	}
}
function toggleAllStoreCheckboxes() {
	var checkboxes = $('storeForm').getInputs('checkbox');
	if($('toggleall').checked) {
		checkboxes.each(function(element,index) {
			element.checked = true;
			if(element.id != 'toggleall') {
				element.next().show();
			}
		});
	} else {
		checkboxes.each(function(element,index) {
			element.checked = false;
			if(element.id != 'toggleall') {
				element.next().hide();
			}
		});
	}
}
var timeCheck;
var pt = false;
function checkMinMaxQty(min_qty,key) {
	clearTimeout(pt);
	pt = setTimeout(function() {
		var qty = $F('productQty'+key)*1;
		if(Object.isElement($('productMaxQty'+key))) {
			var max = $F('productMaxQty'+key)*1;
			if(qty > max) {
				alert('This product is limited to stock on hand.  We will automatically adjust the quantity to the maximum available.');
				$('productQty'+key).value = max;
				qty = max;
			}
		}
		var rem = (qty*1)/(min_qty*1);
		if(rem.toString().search(/\./) != '-1') {
			alert('This product is sold in packages of '+min_qty+'. Please enter a quantity in multiples of '+min_qty+'.');
		}
	},400);
}
function updateQuoteQty(key,id,min_qty) {
	clearTimeout(t);
	t = setTimeout(function() {
		var qty = $F('quoteQty'+key)*1;
		if(Object.isElement($('absoluteMaxQty'+key))) {
			var max = $F('absoluteMaxQty'+key)*1;
			if(qty > max) {
				alert('This product is limited to stock on hand.  We will automatically adjust the quantity to the maximum available.');
				$('quoteQty'+key).value = max;
				qty = max;
			}
		}
		var rem = (qty*1)/(min_qty*1);
		if(rem.toString().search(/\./) != '-1') {
			alert('This product is sold in packages of '+min_qty+'. Please enter a quantity in multiples of '+min_qty+'.');
		} else {
			updateQuote(id);
		}
	},400);
	return false;
}
/* quote functions */
var submitquote = true;
function checkForSelectedProducts(quoteid) {
	var vars = $('storeForm').serialize();
	new Ajax.Request('ajax_quotes.php?action=checkForSelectedProducts&'+vars,{
		onSuccess:function(transport) {
			var response = transport.responseText;
			if(response) {
				alert(response);
			} else {
				if(quoteid != '') {
					addItemsToQuote(quoteid);
				} else {
					doNavLightView('ajax_quotes.php?action=choose');
				}
			}
		},
		onFailure:function() { alert(error1); }
	});
	return false;
}
function addItemsToQuote(id) {
		var vars = $('storeForm').serialize();
		doNavLightView('ajax_quotes.php?action=addItems&quoteid='+id+'&'+vars);
		var checkboxes = $('storeForm').getInputs('checkbox');
		checkboxes.each(function(element,index) {
			element.checked = false;
			if(element.id != 'toggleall') {
				element.next().hide();
			}
		});
	return false;
}
function checkQuoteName() {
	if($F('quoteName') == '') {
		alert('Please enter a RFQ # to save these items to a quote.');
	} else {
		submitAjaxForm('newQuoteForm','quotesList');
	}	
	return false;
}
function loadQuote(id) {
	new Ajax.Updater('quoteItems','ajax_quotes.php?action=loadQuote&id='+id);
	return false;
}
function updateQuote(id) {
	$('quoteForm').request({
		onSuccess:function(transport) {
			var response = transport.responseText;
			if(response != '') {
				alert(response);
			}
			loadQuote(id);
		},
		onFailue:function() { alert(error1); }
	});
}
var t = false;
function updateQuoteQty(key,id,min_qty) {
	clearTimeout(t);
	t = setTimeout(function() {
		var qty = $F('quoteQty'+key)*1;
		if(Object.isElement($('absoluteMaxQty'+key))) {
			var max = $F('absoluteMaxQty'+key)*1;
			if(qty > max) {
				alert('This product is limited to stock on hand.  We will automatically adjust the quantity to the maximum available.');
				$('quoteQty'+key).value = max;
				qty = max;
			}
		}
		var rem = (qty*1)/(min_qty*1);
		if(rem.toString().search(/\./) != '-1') {
			alert('This product is sold in packages of '+min_qty+'. Please enter a quantity in multiples of '+min_qty+'.');
		} else {
			updateQuote(id);
		}
	},400);
	return false;
}
function removeQuoteItem(item, id) {
	if(confirm('Are you sure you want to remove this product from the quote?')) {
		new Ajax.Updater('quoteItems','ajax_quotes.php?action=removeQuoteItem&id='+id+'&item='+item);
	}
	return false;
}
function makeOffer(key,el) {
	var price = $('priceContainer'+key).innerHTML;
	var el = $(el).identify();
	$('productPrice'+key).remove();
	$('productRFQ'+key).value = 'no';
	$(el).insert({before:'<span id="makeOfferBox'+key+'">Make an Offer: <input type="text" name="product['+key+'][price]" id="productPrice'+key+'" value="'+price+'" style="width:60px;" /><input type="hidden" name="product['+key+'][offermade]" id="productOffer'+key+'" value="yes" /> <a href="#" onclick="return cancelMakeOffer(\''+key+'\',\''+el+'\');" class="t10">cancel</a></span>'});
	$(el).hide();
	$('product'+key).checked = true;
	$('qtyContainer'+key).show();
	/*$('priceContainer'+key).update('Make an Offer: <input type="text" name="product['+key+'][price]" id="productPrice'+key+'" value="'+price+'" style="width:60px;" /><input type="hidden" name="product['+key+'][offermade]" id="productOffer'+key+'" value="yes" />');*/
	$('productPrice'+key).select();
	return false;
}
function cancelMakeOffer(key,el) {
	$('productRFQ'+key).value = 'yes';
	$(el).show();
	var price = $('priceContainer'+key).value;
	$('makeOfferBox'+key).insert({before:'<input type="hidden" name="product['+key+'][price]" id="productPrice'+key+'" value="'+price+'" style="width:60px;" />'});
	$('makeOfferBox'+key).remove();
	$('productPrice'+key).hide();
	return false;
}
function toggleQuoteItems(el) {
	var checkboxes = $('quoteForm').getInputs('checkbox');
	if($(el).checked) {
		checkboxes.each(function(element,index) {
			element.checked = true;
		});
	} else {
		checkboxes.each(function(element,index) {
			element.checked = false;
		});
	}
}
function addItemsToOrder() {
	$('quoteForm').action = 'checkout.php?action=process&section=addItems';
	$('quoteForm').submit();
	return false;
}

function getShipToInfo() {
	var shipTo = $F('shipto');
	new Ajax.Updater('shipToContainer','ajax_shiptos.php?action=getShipTo&id='+shipTo);
	return false;
}
function getPaymentMethodInfo() {
	var paymentmethod = $F('paymentmethod');
	new Ajax.Updater('paymentMethodContainer','ajax_paymentmethods.php?action=getPaymentMethod&id='+paymentmethod,{
		onComplete:function() {
			if(Object.isElement($('cc_select'))) {
				new Event.observe('cc_select','change',loadCreditCardInfo);
				loadCreditCardInfo();
			}
		}
	});
	return false;
}
function loadCreditCardInfo() {
	var cc_select = $F('cc_select');
	new Ajax.Updater('creditCardContainer','ajax_paymentmethods.php?action=getCreditCard&id='+cc_select);
	return false;
}

/* Admin Quote Functions */
function loadAdminQuote(id) {
	new Ajax.Updater('quoteItems','ajax_quotes.php?action=loadAdminQuote&id='+id,{
		onComplete:function() {
			Sortable.create('quoteTable',{
				tag:'tr',
				handle:'move',
				onUpdate: function() {
					var ids = Sortable.sequence('quoteTable').join('+');
					new Ajax.Request('ajax_reorder.php?ids='+ids+'&table=quote_items',{
						method:'get',
						onFailure:function() {
							alert('There was a problem updating the order of these items.');
						}
					});
				}
			});
		}
	});
	return false;
}
function updateAdminQuote(id) {
	$('quoteForm').request({
		onSuccess:function(transport) {
			var response = transport.responseText;
			if(response) {
				alert(response);
			}
			loadAdminQuote(id);
		},
		onFailue:function() { alert(error1); }
	});
}
var t = false;
function updateAdminQuoteQty(key,id,min_qty) {
	clearTimeout(t);
	t = setTimeout(function() {
		var qty = $F('quoteQty'+key)*1;
		if(Object.isElement($('absoluteMaxQty'+key))) {
			var max = $F('absoluteMaxQty'+key)*1;
			if(qty > max) {
				alert('This product is limited to stock on hand.  We will automatically adjust the quantity to the maximum available.');
				$('quoteQty'+key).value = max;
				qty = max;
			}
		}
		var rem = (qty*1)/(min_qty*1);
		if(rem.toString().search(/\./) != '-1') {
			alert('This product is sold in packages of '+min_qty+'. Please enter a quantity in multiples of '+min_qty+'.');
		} else {
			updateAdminQuote(id);
		}
	},400);
	return false;
}
function removeAdminQuoteItem(item, id) {
	if(confirm('Are you sure you want to remove this product from the quote?')) {
		new Ajax.Updater('quoteItems','ajax_quotes.php?action=removeAdminQuoteItem&id='+id+'&item='+item);
	}
	return false;
}
function runAdminQuoteAction(id,key,item) {
	var action = $F('action'+key);
	if(action == 'noquote' || action == '' || action == 'accept' || action == 'defaultprice') {
		new Ajax.Updater('quoteItems','ajax_quotes.php?action=itemaction_'+action+'&id='+id+'&item='+item);
	} else if(action == 'quote') {
		doNavLightView('ajax_quotes.php?action=itemaction_quote&id='+id+'&item='+item);
	} else if(action == 'new') {
		doNav('ajax_quotes.php?action=itemaction_new&id='+id+'&item='+item);
	} else if(action == 'counter') {
		doNavLightView('ajax_quotes.php?action=itemaction_counter&id='+id+'&item='+item);
	}
	return false;
}
function submitLeadPriceForm(id,quote) {
	$(id).request({
		onComplete:function(transport) {
			if(transport.responseText != '') {
				doNavLightView(transport.responseText);
			} else {
				closeLightView();
				loadAdminQuote(quote);
			}
		}
	});
	return false;
}
function submitCounterOfferForm(id,quote) {
	$(id).request({
		onComplete:function(transport) {
			if(transport.responseText != '') {
				doNavLightView(transport.responseText);
			} else {
				closeLightView();
				loadAdminQuote(quote);
			}
		}
	});
	return false;
}

/* new quote functions */
function newQuoteSelectCustomer() {
	var chosen = $F('customer_quote');
	new Ajax.Updater('customerData','ajax_quotes.php?action=newquote&section=selectcustomer&id='+chosen,{
		onComplete:function(transport) {
			if(transport.responseText != '') {
				if(Object.isElement($('buyer'))) {
					new Event.observe('buyer','change',function() { newQuoteSelectBuyer() });
					newQuoteSelectBuyer();
				} else {
					setTimeout(function() { new Event.observe('buyer','change',function() { newQuoteSelectBuyer() }); },200);
					newQuoteSelectBuyer();
				}
			}
		}
	});
	return false;
}
function newQuoteSelectBuyer() {
	var customer = $F('customer_quote');
	var chosen = $F('buyer');
	new Ajax.Updater('buyerData','ajax_quotes.php?action=newquote&section=selectbuyer&id='+chosen+'&customer='+customer);
	return false;
}

var loadingSearchResults = false;
function loadSearchResultsAdminStore() {
	if(loadingSearchResults) {
		loadingSearchResults.transport.abort();
	}
	var customer = $F('customer');
	var query = $('searchForm').serialize();
	$('productContainer').update('<div align="center"><br /><br /><img src="images/loader_gray_lg.gif" border="0" /><br /><br /><span class="gray t16">Loading Search Results...Please Wait</span><br /><br /><br /><br /></div>');
	new Ajax.Request('ajax_adminstore.php?action=productSearch&customerid='+customer+'&'+query,{
		method:'get',
		onCreate:function(request) { var loadingSearchResults = request; },
		onSuccess:function(transport) {
			var response = transport.responseText;
			$('productContainer').update(response);
			loadingSearchResults = false;
		},
		onFailure:function() { alert('We encountered an error while trying to communicate with the database. Please refresh the page.'); }
	});
	return false;
}
function submitSearchResultsAdminStore() {
	if(loadingSearchResults) {
		loadingSearchResults.transport.abort();
	}
	var query = $('searchForm').serialize();
	$('productContainer').update('<div align="center"><br /><br /><img src="images/loader_gray_lg.gif" border="0" /><br /><br /><span class="gray t16">Loading Search Results...Please Wait</span><br /><br /><br /><br /></div>');
	new Ajax.Request('ajax_adminstore.php?action=productSearch&page=1&'+query,{
		method:'get',
		onCreate:function(request) { var loadingSearchResults = request; },
		onSuccess:function(transport) {
			var response = transport.responseText;
			$('productContainer').update(response);
			loadingSearchResults = false;
		},
		onFailure:function() { alert('We encountered an error while trying to communicate with the database. Please refresh the page.'); }
	});
	return false;
}
function changeSearchResultsPageAdminStore(page) {
	//$('advancedSearchContainer').hide();
	if(loadingSearchResults) {
		loadingSearchResults.transport.abort();
	}
	var query = $('searchForm').serialize();
	new Ajax.Request('ajax_adminstore.php?action=productSearch&page='+page+'&'+query,{
		method:'get',
		onCreate:function(request) { var loadingSearchResults = request; },
		onSuccess:function(transport) {
			var response = transport.responseText;
			$('productContainer').update(response);
			loadingSearchResults = false;
		},
		onFailure:function() { alert('We encountered an error while trying to communicate with the database. Please refresh the page.'); }
	});
	return false;
}
function checkForSelectedProductsStoreAdmin(quoteid) {
	var vars = $('storeForm').serialize();
	new Ajax.Request('ajax_quotes.php?action=checkForSelectedProducts&'+vars,{
		onSuccess:function(transport) {
			var response = transport.responseText;
			if(response) {
				alert(response);
			} else {
				addItemsToQuoteAdminStore(quoteid);
			}
		},
		onFailure:function() { alert(error1); }
	});
	return false;
}
function addItemsToQuoteAdminStore(quoteid) {
	var vars = $('storeForm').serialize();
	new Ajax.Request('ajax_adminstore.php?action=additems&quoteid='+quoteid+'&'+vars,{
		onSuccess:function(transport) {
			if(transport.responseText != '') {
				alert(transport.responseText);
			} else {
				closeLightView();
				loadAdminQuote(quoteid);
			}
		}
	});
	return false;
}
function loadQuoteAdminStore() {
	new Ajax.Updater('quoteItems','ajax_adminstore.php?action=loadquoteitems');
}
function saveQuoteDraft() {
	var vars = $('newQuoteForm').serialize();
	new Ajax.Request('ajax_adminstore.php?action=savechanges&'+vars,{
		method:'get',
		onSuccess:function() {
			loadQuoteAdminStore();
		}
	});
	return false;
}
function validateAdminQuote() {
	var vars = $('newQuoteForm').serialize();
	new Ajax.Request('ajax_adminstore.php?action=validatequote&'+vars,{
		method:'get',
		onSuccess:function(transport) {
			var r = transport.responseText;
			if(r != '') {
				alert(r);
			} else {
				$('newQuoteForm').submit();
			}
		}
	});
	return false;
}
function removeItemAdminQuote(id) {
	if(confirm('Are you sure you want to remove this product from the quote?')) {
		var vars = $('newQuoteForm').serialize();
		new Ajax.Request('ajax_adminstore.php?action=savechanges&remove='+id+'&'+vars,{
			method:'get',
			onSuccess:function() {
				loadQuoteAdminStore();
			}
		});
	}
	return false;
}
function viewLargeImage(img) {
	doNavLightView(img);
	return false;
}
function showMinimumOrderNotice(amount,total,event) {
	if(!confirm('Your order does not meet our minimum purchase amount of $'+total+'.  Please click Cancel to add more parts to your order or click Okay to have a Minimum PO Fee of $'+amount+' added to your order.')) {
		Event.stop(event);
	}
}
function showMinimumOrderNoticeIntl(amount,total,event) {
	if(!confirm('Your order does not meet our minimum purchase amount of $'+total+'.  Please click Cancel to add more parts to your order or click Okay to have a Minimum PO Fee of $'+amount+' added to your order.')) {
		Event.stop(event);
	}
}
function submitUserAgreement() {
	if($('agree').checked) {
		$('createAccountForm').submit()
	} else {
		alert('Please check that you agree with the statements made in the user agreement.');
	}
	return false;
}


/* Reports */
function runReport(page) {
	$('resultsContainer').update('<div align="center" class="t16 gray"><br /><br /><img src="images/loader_gray_lg.gif" border="0" /><br /><br />Loading Report Results...A lot of processing is going on so this can take a few minutes. Please be patent.</div>');
	new Ajax.Request($('reportFilterForm').action+'&page='+page,{
		method:'post',
		postBody:$('reportFilterForm').serialize(),
		onComplete:function(transport) {
			var r = transport.responseText;
			$('resultsContainer').update(r);
		}
	});
	return false;
}
function runPartNumReport(page) {
	$('resultsContainer').update('<div align="center" class="t16 gray"><br /><br /><img src="images/loader_gray_lg.gif" border="0" /><br /><br />Loading Report Results...A lot of processing is going on so this can take a few minutes. Please be patent.</div>');
	new Ajax.Request($('reportFilterForm').action+'&page='+page,{
		method:'post',
		postBody:$('reportFilterForm').serialize(),
		onComplete:function(transport) {
			var r = transport.responseText;
			$('resultsContainer').update(r);
		}
	});
	return false;
}
function seePartDetails(id,tier,rfq) {
	$('banner').insert('<div style="top:50%;left:50%;margin:-66px 0 0 -66px;padding:50px;background:#fff;border:1px solid #ccc;position:fixed;" id="loaderLightBox"><img src="images/loader_gray_lg.gif" border="0" alt="Loading" /></div>');
	var vars = $('reportFilterForm').serialize();
	new Ajax.Updater('resultsContainer',$('reportFilterForm').action+'&part_details='+id+'&price_tier='+tier+'&rfq='+rfq,{
		method:'post',
		postVars:vars,
		onComplete:function() {
			new Effect.ScrollTo('partDetailsContainer');
			$('loaderLightBox').remove();
		}
	});
	return false;
}
function acknowledgeOldProduct(el,id) {
	if($(el).checked) {
		new Ajax.Request('ajax_products.php?action=acknowledgeoldproduct&id='+id,{
			method:'get',
			onComplete:function() {
				$(el).up().remove();
			}
		});
	}
}
function submitAddProductToOrderForm() {
	if($F('qty') == '') {
		alert('Please enter a quantity to add to this order.');
	} else if($F('product') == '') {
		alert('Please enter a product to add to this order.');
	} else if($F('chosenProduct') == '') {
		alert('We could not find the product you selected. Please try selecting it again.');
	} else {
		$('addToOrderForm').submit();
	}
	return false;
}
function saveAsPDF(element) {
	doNavLightView('ajax_popups.php?action=preparePDF');
	setTimeout(function() { doNavNewWindow($(element).href); },1500);
	return false;
}
function editQuoteNote() {
	$('quoteNote').request({
		onSuccess:function(transport) {
			var id = transport.responseText;
			loadAdminQuote(id);
			closeLightView();
		},
		onFailure:function() { alert('error'); }
	});
	return false;
}
function editOrderNote() {
	$('orderNote').request({
		onSuccess:function(transport) {
			var id = transport.responseText;
			doNav('admin-orders.php?action=view&id='+id);
			closeLightView();
		},
		onFailure:function() { alert('error'); }
	});
	return false;
}
function checkMultipleConditions() {
	var cond = $F('condition');
	if(cond == 9) {
		$('multipleConditions').show();
		$('nonMultipleCondition').hide();
	} else {
		$('multipleConditions').hide();
		$('nonMultipleCondition').show();
	}
}
function addMultipleCondition(i,el) {
	el = $(el).identify();
	var newi = i;
	new Ajax.Request('ajax_products.php?action=addMultipleCondition&i='+i,{
		method:'get',
		onSuccess:function(transport) {
			var r = transport.responseText;
			$('multipleConditionsContainer').insert(r);
		},
		onFailure:function() { alert('We encountered an error while trying to communicate with the database. Please refresh the page.'); }
	});
	newi++;
	$(el).onclick = function() { return addMultipleCondition(newi,el); }
	return false;
}
function removeMultipleCondition(i) {
	$('multipleCondition'+i).remove();
	return false;
}
function loadCustomerData(n) {
	var customer = $('customer'+n).value;
	new Ajax.Request('ajax_customers.php?action=loadCustomerData&n='+n+'&customer='+customer,{
		method:'get',
		onSuccess:function(transport) {
			var response = transport.responseText;
			if(response) {
				$('customer'+n+'Container').update(response);
			}
		},
		onFailure:function() { alert(error1); }
	});
	return false;
}
function shipWhenAvailable() {
	if($('ship_when_available').checked) {
		$('requiredDateContainer').hide();
	} else {
		$('requiredDateContainer').show();
	}
}
function cot_tl_bigPopup(url) {
    newwindow = window.open(url, 'name', 'WIDTH=450,HEIGHT=500,FRAMEBORDER=0,MARGINWIDTH=0,MARGINHEIGHT=0,SCROLLBARS=1,allowtransparency=true');
    if (window.focus) {
        newwindow.focus();
    }
    return false;
}
new Event.observe(window, 'load', function() {
	host = location.host;
    if (window.location.protocol.toLowerCase() == "https:") {
        cot_tl_dummyMini = 'https://secure.comodo.com/trustlogo/images/cot_bgf0.gif';
        cot_tl_miniBaseURL = 'https://secure.comodo.com/ttb_searcher/trustlogo?v_querytype=C&v_shortname=SC2&v_search=' + host + '&x=6&y=5';
        cot_tl_bigBaseURL = 'https://secure.comodo.com/ttb_searcher/trustlogo?v_querytype=W&v_shortname=SC2&v_search=' + host + '&x=6&y=5';
		$('footer').insert({after:'<div id="cot_tl_pop" style="display:none;"><iframe id="frame_pop" name="frame_pop" src="' + cot_tl_miniBaseURL + '" width="244" height="194" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" allowtransparency="true"></iframe></div>'});
		new Event.observe('comodoTL', 'click', function(e) {
			cot_tl_bigPopup(cot_tl_bigBaseURL);
			Event.stop(e);
		});
		new Event.observe('comodoTL', 'mouseover', function() {
			$('cot_tl_pop').show();
		});
		new Event.observe('comodoTL', 'mouseout', function() {
			$('cot_tl_pop').hide();
		});
    } else {
        cot_tl_dummyMini = 'http://www.trustlogo.com/images/cot_bgf0.gif';
        cot_tl_miniBaseURL = 'http://www.trustlogo.com/ttb_searcher/trustlogo?v_querytype=C&v_shortname=SC2&v_search=' + host + '&x=6&y=5';
        cot_tl_bigBaseURL = 'http://www.trustlogo.com/ttb_searcher/trustlogo?v_querytype=W&v_shortname=SC2&v_search=' + host + '&x=6&y=5';
    }  
});

function selectWholesale() {
	if($('wholesaler').checked) {
		$('wholesalePricing').show();
		$('standardPricing').hide();
	} else {
		$('wholesalePricing').hide();
		$('standardPricing').show();
	}
}