var storefilter = $H();

document.observe('dom:loaded', function() {
	storeObservers();
	
	// cache initial page
	webkit.cacheset('store','showall-page_1',$('inventorydisplay'));
});

function storeObservers() {
	if ($('storepagenavwrapper')) {
		$$('#nmstore .storepagenav a').each(function(o) {
			o.stopObserving('click');
			o.observe('click', function(e) {
				e.stop();
				var thisID = o.id.replace(/^page_/,'');				
				if ($('page_' + thisID + 'wrapper').hasClassName('thispage')) { return; }
				gotopage(thisID);
			})
		});
	}
	
	$$('.addtocartbutton').each(function(o) {
		o.stopObserving('click');
		o.observe('click', function(e) {
			e.stop();
			var thisID = o.id.replace(/^addtocart_/,'');
			add_tocart('store_cartdisplay',thisID,$('quantity_' + thisID).getValue());
		})
	});
	
	if ($('complete_order')) {
		$$('#nmstore #complete_order a').each(function(o) {
			o.stopObserving('click');
			o.observe('click', function(e) {
				e.stop();
				$('customer_options').submit();
			})
		});
	}
}


// these two variables need to be global
var cartwaitHTML;
var nocartwaitHTML;

/*
var loading = new Image();
loading.src = "/nm_webkit/libs" + devpath + "/images/loading.gif";

var waitHTML = '<div class="waitHTML"><img src = "' + loading.src + '"></div>';
*/

if (nocartwaitHTML) {
	cartwaitHTML = "<div id = \"store_cartframe\"></div>";
}
else {
	cartwaitHTML = '<div id = \"store_cartframe\">' + waitHTML + '</div><div id = \"store_bottombg\"></div>';
}

// icon preloaders
us_iconoff = new Image();
us_iconoff.src = "/nm_webkit/iconsets/wkdemo/usflag.jpg";
can_iconoff = new Image();
can_iconoff.src = "/nm_webkit/iconsets/store_default/canflag.jpg";
fgn_iconoff = new Image();
fgn_iconoff.src = "/nm_webkit/iconsets/store_default/worldmap.jpg";

us_iconon = new Image();
us_iconon.src = "/nm_webkit/iconsets/wkdemo/usflagp.jpg";
can_iconon = new Image();
can_iconon.src = "/nm_webkit/iconsets/store_default/canflagp.jpg";
fgn_iconon = new Image();
fgn_iconon.src = "/nm_webkit/iconsets/store_default/worldmapp.jpg";

// mouseovers
function storeimg_act(imgName, icon_num) {
	imgOn = eval(imgName + "on.src");
	document.images[imgName + icon_num].src = imgOn;
}

function storeimg_inact(imgName, icon_num) {
	imgOff = eval(imgName + "off.src");
	document.images[imgName + icon_num].src = imgOff;
}

var feedbacktimer;  // used to ensure that text feedback is not modified when div block does not exist

function add_tocart(ID,prodID,quantity) {
	$('store_cartdisplay').style.display = "block";
	var ajaxParameters = 'act=add&prodID=' + prodID + '&quantity=' + quantity;
	new Ajax.Updater(ID, '/nm_webkit/libs/store_header.php', {
		method: 'get',
		parameters: ajaxParameters,
		onComplete: function(transport) {
			new Effect.ScrollTo('top', { duration: 0.75 });
			if ($('revieworder')) {
				new Effect.Appear('revieworder', { duration: 0.75});
			}
		}
	});
}

function cart_display(ID,act) {
	if (act == "show") {	
		new Effect.Fade('store_cartlink_hide', { duration: 0.45 });
		new Effect.SlideDown('store_cartlink_show', { duration: 0.5 });
	}
	else if (act == "hide") {
		//document.getElementById('store_cartlink_hide').style.display = 'block';
		new Effect.SlideUp('store_cartlink_show', { duration: 0.5, afterFinish: function() {
			new Effect.Appear('store_cartlink_hide', { duration: 0.5 });
			}});
		}
	}

function update_quantity(ID,act,prodID,quantity,orig_quantity) {
	if (feedbacktimer) {
		// cancel previous feedback timers
		clearTimeout(feedbacktimer);
	}

	if (quantity == 0 && act == "update") {
		$('prodquantity_' + prodID).value = orig_quantity;
		/*
		Modalbox.show('/nm_webkit/libs' + devpath + '/dialog_missingquantity.php', { title:"ERROR: missing quantity", overlayClose:false });
		return false;
		*/
	}
	
	var ajaxParameters = 'prodID=' + prodID + '&quantity=' + quantity + '&act=' + act;
	
	new Ajax.Updater(ID, '/nm_webkit/libs/store_header.php', {
		method: 'get',
		parameters: ajaxParameters,
		onComplete: function(transport) {
			new Effect.Highlight('cartquantity_' + prodID, { startcolor: store_highlightstart, endcolor: store_highlightend, duration: 1.0 });
		}
	});
}

function update_checkout(ID,act,prodID,quantity,orig_quantity,tax_state) {
	if (feedbacktimer) {
		// cancel previous feedback timers
		clearTimeout(feedbacktimer);
	}
	
	if (quantity == 0 && act == "update") {
		document.getElementById('coprodquantity_' + prodID).value = orig_quantity;
		/*
		Modalbox.show('/nm_webkit/libs' + devpath + '/dialog_missingquantity.php', { title:"ERROR: missing quantity", overlayClose:false });
		return false;
		*/
	}
	
	if (tax_state == "undefined") {
		tax_state = "";
	}
	
	if (act == "delete") {
		new Effect.Shrink('cocartprod_' + prodID, { direction: "top-left", duration: 0.5, afterFinish: function() {
			var ajaxParameters = 'act=' + act + '&prodID=' + prodID + '&tax_state=' + tax_state;
			
			new Ajax.Updater(ID, '/nm_webkit/templates/store_template_xhtml.php', {
				method: 'get',
				parameters: ajaxParameters,
				onComplete: function(transport) {
					if ($('emptycart')) {
						$('nmstore').innerHTML = waitHTML;
						$('store_cartdisplay').style.display = "none";
						
						var ajaxParameters = 'act=returntoinventory';
						new Ajax.Updater('nmstore', '/nm_webkit/templates/store_template_xhtml.php', {
							method: 'get',
							parameters: ajaxParameters
						})					
					}
				}
			});
		}});
	}
	else if (act == "add") {
		new Effect.Shrink('imcartprod_' + prodID, { direction: "top-left", duration: 0.5, afterFinish: function() {
			var ajaxParameters = 'act=' + act + '&prodID=' + prodID + '&tax_state=' + tax_state;
			
			new Ajax.Updater(ID, '/nm_webkit/templates/store_template_xhtml.php', {
				method: 'get',
				parameters: ajaxParameters,
				onComplete: function(transport) {
					new Effect.Highlight('cocartquantity_' + prodID, { startcolor: store_highlightstart, endcolor: store_highlightend, duration: 1.0 });
				}
			});
			
		}});
	}
	else if (act == "update") {
		var ajaxParameters = 'act=' + act + '&quantity=' + quantity + '&prodID=' + prodID + '&tax_state=' + tax_state;
		
		new Ajax.Updater(ID, '/nm_webkit/templates/store_template_xhtml.php', {
			method: 'get',
			parameters: ajaxParameters,
			onComplete: function(transport) {
				new Effect.Highlight('cocartquantity_' + prodID, { startcolor: store_highlightstart, endcolor: store_highlightend, duration: 1.0 });
			}
		});
	}
}

function remove_fromcart(ID,act,prodID,num_incart) {
	if (feedbacktimer) {
		// cancel previous feedback timers
		clearTimeout(feedbacktimer);
	}
	
	new Effect.Shrink('cartprod_' + prodID, { direction: "top-left", duration: 0.5, afterFinish: function() {
		var ajaxParameters = 'act=' + act + '&prodID=' + prodID;
		
		new Ajax.Updater(ID, '/nm_webkit/libs/store_header.php', {
			method: 'get',
			parameters: ajaxParameters
		})			
	}});
}

function apply_taxship (ID,act,tax_state,ship_method) {
	var ajaxParameters = 'act=' + act + '&tax_state=' + tax_state + '&ship_method=' + ship_method;
	
	new Ajax.Updater(ID, '/nm_webkit/templates/store_template_xhtml.php', {
		method: 'get',
		parameters: ajaxParameters
	})
}

function apply_taxmenu (home_state, ship_method) {
	if (!ship_method) {
		// customer has selected state/province
		if (document.getElementById('customer_options').ship_method.value=='standard') {
			// user has selected standard shipping
			var ship_method = "standard";
		}
		else if (document.getElementById('customer_options').ship_method.value=='expedited') {
			var ship_method = "expedited";
		}
	}
	document.getElementById('tax_applied').innerHTML = '<b>Appropriate taxes are being determined for your order...</b>';
	apply_taxship('store_revieworder','apply_tax',home_state,ship_method);
	new Effect.Fade('tax_applied', { delay:3.0, duration: 0.5 })
}

function set_sameship () {
	if (!document.getElementById('customer_options').same_ship.checked) {
		document.getElementById('customer_options').ship_fname.value = document.getElementById('customer_options').bill_fname.value;
		document.getElementById('customer_options').ship_lname.value = document.getElementById('customer_options').bill_lname.value;
		document.getElementById('customer_options').ship_address.value = document.getElementById('customer_options').bill_address.value;		
		document.getElementById('customer_options').ship_address2.value = document.getElementById('customer_options').bill_address2.value;				
		document.getElementById('customer_options').ship_city.value = document.getElementById('customer_options').bill_city.value;	
		document.getElementById('customer_options').ship_zip.value = document.getElementById('customer_options').bill_zip.value;

		if (document.getElementById('customer_options').bill_country.value !== "Outside of the US and Canada") {			
			document.getElementById('customer_options').ship_state.value = document.getElementById('customer_options').bill_state.value;
			if (!document.getElementById('customer_options').bill_state.options[document.getElementById('customer_options').bill_state.selectedIndex].value) {
				var home_state = document.getElementById('customer_options').ship_state.options[document.getElementById('customer_options').ship_state.selectedIndex].value;
			}
			else {
				var home_state = document.getElementById('customer_options').bill_state.options[document.getElementById('customer_options').bill_state.selectedIndex].value;
			}

			if (home_state && document.getElementById('customer_options').charge_tax.value == 1) {
				document.getElementById('tax_applied').innerHTML = '<b>Appropriate taxes are being determined for your order...</b>';
				apply_taxship('store_revieworder','apply_tax','" + home_state + "','" + ship_method + "');
				setTimeout("document.getElementById('tax_applied').innerHTML = ''", 3000);
			}	
		}
	}
}

function sync_custoptions (field) {
	if (!document.getElementById('customer_options').same_ship.checked) {
		if (field == "fname") {
			document.getElementById('customer_options').ship_fname.value = document.getElementById('customer_options').bill_fname.value;
		}
		else if (field == "lname") {
			document.getElementById('customer_options').ship_lname.value = document.getElementById('customer_options').bill_lname.value;
		}
		else if (field == "address") {
			document.getElementById('customer_options').ship_address.value = document.getElementById('customer_options').bill_address.value;
		}
		else if (field == "address2") {
			document.getElementById('customer_options').ship_address2.value = document.getElementById('customer_options').bill_address2.value;
		}
		else if (field == "city") {
			document.getElementById('customer_options').ship_city.value = document.getElementById('customer_options').bill_city.value;
		}
		else if (field == "state") {
			document.getElementById('customer_options').ship_state.value = document.getElementById('customer_options').bill_state.value;
		}
		else if (field == "zip") {
			document.getElementById('customer_options').ship_zip.value = document.getElementById('customer_options').bill_zip.value;
		}
		
		if (document.getElementById('customer_options').bill_country.value == "Outside of the US and Canada") {
			document.getElementById('customer_options').ship_country.value = document.getElementById('customer_options').bill_countryinput.value;
		}
	}
}

function shipping_info() {
	var revealicon = document.getElementById('store_shippinginfo').innerHTML;
	if (document.getElementById('store_shippinginfotext').style.display == "none") {
		// change info to conceal
		document.getElementById('store_shippinginfo').innerHTML = revealicon.replace('ajax_reveal.jpg','ajax_conceal.jpg');
		// reveal shipping options
		new Effect.BlindDown('store_shippinginfotext', { duration: 0.5 });
	}
	else {
		// change info to reveal
		document.getElementById('store_shippinginfo').innerHTML = revealicon.replace('ajax_conceal.jpg','ajax_reveal.jpg');
		// conceal shipping options
		new Effect.BlindUp('store_shippinginfotext', { duration: 0.5 });		
	}
}

function payment_info(ID,act) {
	var revealicon = document.getElementById('store_paymentinfo').innerHTML;
	if (document.getElementById('store_paymentinfotext').style.display == "none") {
		// change info to conceal
		document.getElementById('store_paymentinfo').innerHTML = revealicon.replace('ajax_reveal.jpg','ajax_conceal.jpg');
		// reveal payment options
		new Effect.BlindDown('store_paymentinfotext', { duration: 0.5 });
	}
	else {
		// change info to reveal
		document.getElementById('store_paymentinfo').innerHTML = revealicon.replace('ajax_conceal.jpg','ajax_reveal.jpg');
		// conceal payment options
		new Effect.BlindUp('store_paymentinfotext', { duration: 0.5 });		
	}
}

function checkout() {
	$('nmstore').innerHTML = waitHTML;
	var ajaxParameters = 'act=showcheckout';
	new Effect.SlideUp('store_cartdisplay', { duration:0.25, afterFinish: function() {
		new Ajax.Updater('nmstore', '/nm_webkit/templates/store_template_xhtml.php', {
			method: 'get',
			parameters: ajaxParameters,
			onComplete:function() {
				storeObservers();
				
				if (typeof customStoreObservers !== "undefined") {
					customStoreObservers();
				}
			}
		});
	}});
}

function returntoinventory() {
	$('nmstore').innerHTML = waitHTML;
	$('store_cartdisplay').innerHTML = cartwaitHTML;	
	new Effect.SlideDown('store_cartdisplay', { duration:0.25, afterFinish: function() {
		// redraw cart
		var cartParameters = 'act=show';
		new Ajax.Updater('store_cartdisplay', '/nm_webkit/libs/store_header.php', {
			method: 'get',
			parameters: cartParameters
		});
		
		var invParameters = 'act=returntoinventory';
		new Ajax.Updater('nmstore', '/nm_webkit/templates/store_template_xhtml.php', {
			method: 'get',
			parameters: invParameters
		});
	}});
}

function complete_order() {
	document.getElementById('customer_options').submit();
	return true;
}

function clear_notesfield(text) {
	if (document.getElementById('customer_options').other.value == text) { 
		document.getElementById('customer_options').other.value=''; 
	}
}

function categoryswitch(category) {
	if (category) {
		$('store_displaymodeall').checked=false;
		$('store_displaymodecategory').checked=true;
	}
	else {
		$('show_categorylist').value='';
		$('store_displaymodeall').checked=true;
		$('store_displaymodecategory').checked=false;
	}
	$('inventorydisplay').innerHTML = waitHTML;
	var ajaxParameters = 'act=returntoinventory&show_category=' + category + '&categoryswitch=1';
	new Ajax.Updater('inventorydisplay', '/nm_webkit/templates/store_template_xhtml.php', {
		method: 'get',
		parameters: ajaxParameters,
		onComplete: function(transport) {
			$('storesearch').value = '';			
		//	new Effect.ScrollTo('store_displaymode', { duration: 0.75 });
		}
		
	});
}

function gotopage(pagenum) {
	var searchterm = $('storesearch').value;
	if ($('jsondata')) {
		var jsondata = $('jsondata').innerHTML.evalJSON();	
		if (typeof jsondata.store.defaultsearchterm !== "undefined" && jsondata.store.defaultsearchterm == $('storesearch').value) {
			var searchterm = '';
		}
	}
	
	var filterquerystring = '';
	var cacheToken;
	storefilter.each(function(pair) {
		filterquerystring += '&' + pair.key + '=' + pair.value;
		if (pair.value !== '') {
			cacheToken = pair.key + '-' + pair.value;
		}
	});
	
	if (typeof cacheToken == "undefined") {
		// default to show all
		var cacheToken = "showall";
	}
	
	// check cache
	if (webkit.cacheget('store', cacheToken + '-page_' + pagenum)) {
		// output cache
		webkit.cacheoutput('store', cacheToken + '-page_' + pagenum, $('inventorydisplay'));
		
		// re-establish observers
		storeObservers();
		if (typeof customStoreObservers !== "undefined") {
			customStoreObservers();
		}
	}
	else {		
		$('inventorydisplay').setOpacity(0.5);
		var ajaxParameters = "act=returntoinventory&limit=" + pagenum + '&searchfor=' + searchterm + filterquerystring;
		new Ajax.Updater('inventorydisplay', '/nm_webkit/templates/store_template_xhtml.php', {
			method: 'get',
			parameters: ajaxParameters,
			onComplete: function() {
				$('inventorydisplay').setOpacity(1);			
				storeObservers();

				if (typeof customStoreObservers !== "undefined") {
					customStoreObservers();
				}

				webkit.cacheset('store', cacheToken + '-page_' + pagenum, $('inventorydisplay'));
			}
		});
	}	
}

function searchinventory() {
	$('inventorydisplay').innerHTML = waitHTML;
	var ajaxParameters = 'act=returntoinventory&searchfor=' + $('storesearch').value;
	new Ajax.Updater('inventorydisplay', '/nm_webkit/templates/store_template_xhtml.php', {
		method: 'get',
		parameters: ajaxParameters,
		onComplete: function(transport) {
		//	new Effect.ScrollTo('store_displaymode', { duration: 0.75 });
		}
	});
}

function showurl(ID) {
	var URLhtml = "<p>URL for this product: <a href = \"?showprod=" + ID + "\">" + window.location + "?showprod=" + ID + "</a>&nbsp;&nbsp;&nbsp;(<a href = \"javascript:hideurl(" + ID + ")\">hide</a>)</p>";
	$('productURL_' + ID).innerHTML = URLhtml;
	new Effect.Appear("productURL_" + ID, { duration:0.5});
}

function hideurl(ID) {
	new Effect.Fade("productURL_" + ID, { duration: 0.25});
}

function gotocountry(country) {
        $('nmstore').innerHTML = waitHTML;

        var ajaxParameters = 'set_country=' + country;

        new Ajax.Updater('nmstore', '/nm_webkit/templates/store_template_xhtml.php', {
                method: 'get',
                parameters: ajaxParameters
        });
}