if (window.jQuery && window.ExpressoStore) { jQuery(function($) {
    if (ExpressoStore.stock) {
		var match_sku = function(formdata) {
			if (typeof formdata["entry_id"] == "undefined") return false;
			var entry_id = formdata["entry_id"].value;
			if (typeof ExpressoStore.stock[entry_id] == "undefined") return false;
			var stockdata = ExpressoStore.stock[entry_id];
			if (stockdata.length === 1) return stockdata[0];
			for (var i=0; i<stockdata.length; i++) {
				var match = true;
				for (var mod_id in stockdata[i]["opt_values"]) {
					var mod_name = "modifiers["+mod_id+"]";
					if (typeof formdata[mod_name] == "undefined" || formdata[mod_name].value != stockdata[i]["opt_values"][mod_id]) {
						match = false; break;
					}
				}
				if (match) return stockdata[i];
			}
			return false;
		}
		var update_sku = function() {
			var sku = ""; var stock_level = ""; var in_stock = true;
			var skudata = match_sku(this.form.elements);
			if (skudata !== false) {
				sku = skudata.sku;
				if (skudata.track_stock === "y") {
					stock_level = skudata.stock_level;
					if (stock_level <= 0) in_stock = false;
				}
			}
			var form = $(this.form);
			$(".store_product_sku", form).val(sku).text(sku).trigger("change");
			$(".store_product_stock", form).val(stock_level).text(stock_level).trigger("change");
			$(".store_product_in_stock", form).toggle(in_stock);
			$(".store_product_out_of_stock", form).toggle(in_stock == false);
		}
		$('form.store_product_form [name^="modifiers"]').live("change", update_sku);
		$("form.store_product_form").find("input:first").each(update_sku);
	}

	if (ExpressoStore.countries) {
		var change_region_select = function(country_code, region_elem) {
			var country_regions = ExpressoStore.countries[country_code]["regions"];
			region_elem.empty();
			for (var key in country_regions)
			{
				region_elem.append('<option value="'+key+'">'+country_regions[key]+'</option>');
			}

			if (region_elem.children().size() == 0)
			{
				region_elem.append('<option></option>');
			}
		}
		$("select[name=billing_country]").change(function(){
			change_region_select($(this).val(), $("select[name=billing_region]"));
		});
		$("select[name=shipping_country]").change(function(){
			change_region_select($(this).val(), $("select[name=shipping_region]"));
		});
    }
});}
