var gPriceAddOn = 0;
var gPriceTotal = 0;
if (!gOptionFields) gOptionFields = null;
if (!gOptionValid) gOptionValid = null;
gOptionSelected = "";

function checkToken(h,s,n) 
// @h - Haystack
// @s - Needles
// @n - Index
{
	// alert("checkToken() "+s);
	s = s.split("#").join("");
	//alert(s);
	var A = s.split(",");
	if (n >= A.length) return false;
	var S = "";
	for (var i=n+1; i<A.length; i++) {
		S = A[n]+"[^,]+"+A[i];
		if ( h.search(new RegExp(S))>=0 ) {
			// Token has been found
			// alert ( S +" // "+h+" -> found");
			return true;
		}
	}
	return checkToken(h,s,n+1);
}

function checkOrderId() 
{
	if (!gOptionValid) return true;
	if (!gOptionSelected) return true;
	
	if (checkToken(gOptionValid, gOptionSelected, 0)) 
	{
                 // Error einblenden
                $(".error").fadeIn();
			
	} 

        else 
        {      // Error ausblenden
               $(".error").fadeOut();
        }
	
}

function checkPrice() 
{
	var E = $('[name=we_sacf[price]]');
	gPriceBase = parseFloat(E.val());
}

function updateOrderId() 
{
	if (!gOptionFields) return;
	
	var BN = $("#orderid");					// BestellNummer
	var HV = $("[name=we_sacf[prodNum]]");    // hidden field
	var HD = $("[name=we_sacf[prodDet]]");     // hidden field
	HD.val("");
	
	var optSel 	= ""; // Options Selectes NN,NN,...
	var optBN 	= ""; // Options Selected excluding #NN
	var optTxt	= ""; // Option Detail Text
	var ov = ""; // option value
	var ot = ""; // option text
	
	for (var n=0; n<gOptionFields.length; n++) 
	{
		// 1. ORDER KÜRZEL
		ov = $("#"+gOptionFields[n]+" option:selected").attr("id");
		if (ov) optSel += ov +",";
		if (ov && ov.substr(0,1)!= "#") optBN += ov +",";
		
		// 2. ORDER DETAIL
		ov = $("#"+gOptionFields[n]+" option:selected").text();
		optTxt += ov+", ";
	}
	
	optSel = optSel.substr(0,optSel.length-1); // cur ","
	optTxt = optTxt.substr(0,optTxt.length-2); // cur ","
	HD.val( optTxt );
	// alert ( HD.val() );
	// Bestell Nummer
	HV.val(gOrderId+optBN.split(",").join(""));
	BN.text("Artikel-Nr.: "+HV.val());
	//
	gOptionSelected = optSel;
	
	checkOrderId();
		
}

function updatePrice() 
{		
	if (!gOptionFields) return;
	var C = $("[name=shop_anzahl]");
	var E = $("#preis");
	var H = $("[name=we_sacf[price]]");
	
	// calculate the new addon price
	var price = 0;
	var priceSub = 0;
	var out = "";
	for (var n=0; n<gOptionFields.length; n++) 
	{
		priceSub = parseFloat($("#"+gOptionFields[n]+" option:selected").val());
		price += priceSub;
		//out = "
	}
	
	// store for later reference
	gPriceAddOn = price;
	gPriceTotal = (price + gPriceBase);
	
	var dPrice = (gPriceTotal+0.001)+"";
	dPrice = dPrice.split(".")[0] +"."+ dPrice.split(".")[1].substr(0,2); 
	
	E.text("EUR "+dPrice+" (zzgl. MwSt.)");
	H.attr("value", gPriceTotal);

	updateOrderId();
}




$(document).ready(function(){

	// Your code here
	updatePrice();	
	
});