

$(document).ready(function(){
	//alert("Hello!");
	
	//********************************************** 
	// ILMIA MINI-SHOP   
	//**********************************************
	// init basket
	$("#ilmiaBasketRow").hide();
	
	
	// VARIABLES ----------------------------------------
	var arrProducts 		= [];
	arrProducts['blanc'] 	= {name: 'ilmia blanc', 	price: 299, priceEuro: 236, 	quantity: 0};
	arrProducts['noir'] 	= {name: 'ilmia noir', 		price: 299, priceEuro: 236, 	quantity: 0};
	arrProducts['brun'] 	= {name: 'ilmia brun', 		price: 299, priceEuro: 236, 	quantity: 0};
	price_delivery			= 9;
	price_delivery_euro		= 7;
	price_nachnahme			= 12;  // 
	
	iso_eu 					= ['Albania', 'Andorra', 'Belgium', 'Bosnia and Herzegovina', 'Bulgaria', 'Deutschland', 'Austria', 'Österreich', 'Belarus', 'Bulgaria', 'Croatia', 'Cyprus', 'Czech Republic', 'Denmark', 'Estonia', 'Finland', 'France', 'Georgia', 'Greece', 'Hungary', 'Iceland', 'Ireland', 'Italy', 'Latvia', 'Liechtenstein', 'Lithuania', 'Luxembourg', 'Macedonia, The Former Yugoslav Republic of', 'Malta', 'Moldova, Republic of', 'Monaco', 'Serbia and Montenegro', 'Netherlands', 'Norway', 'Poland', 'Portugal', 'Romania', 'San Marino', 'Serbia and Montenegro', 'Slovakia', 'Slovenia', 'Spain', 'Sweden', 'Turkey', 'United Kingdom'];
	
	addressesEqualIsChecked	= true;
	
	$("select#bill_country").change(function () {
		$("select#bill_country option:selected").each(function () {
			var sel = $(this).val();
			if(addressesEqualIsChecked){
				// ch
				if(sel == 'Schweiz'){
					price_delivery			= 9;
					price_delivery_euro		= 7;
				}
				// world
				else{
					price_delivery			= 45;
					price_delivery_euro		= 40;
					
				}
				// eu
				for(var i=0; i<iso_eu.length; i++){
					if(sel == iso_eu[i]){
						price_delivery			= 12;
						price_delivery_euro		= 10;
					}
				}
				
				// update delivery field:
				$("#deliveryTotal").html(price_delivery+".--");
				$("#deliveryTotalEuro").html(price_delivery_euro+".--");
				
				$("#vkOrder").html("CHF "+price_delivery+".-- / € "+price_delivery_euro+".--");
				$("#delInfoOrder").attr('style','display:inline');
				
				updateGrandTotal();
				//alert("selected: "+sel+", price_delivery:"+price_delivery);
			}
			
		});
	});
	
	$("select#addr_country").change(function () {
		$("select#addr_country option:selected").each(function () {
			var sel = $(this).val();
			// ch
			if(sel == 'Schweiz'){
				price_delivery			= 9;
				price_delivery_euro		= 7;
			}
			// world
			else{
				price_delivery			= 45;
				price_delivery_euro		= 40;
			}
			// eu
			for(var i=0; i<iso_eu.length; i++){
				if(sel == iso_eu[i]){
					price_delivery			= 12;
					price_delivery_euro		= 10;
				}
			}
			// update delivery field:
			$("#deliveryTotal").html(price_delivery+".--");
			$("#deliveryTotalEuro").html(price_delivery_euro+".--");
			
			$("#delInfoOrder").attr('style','display:none');
			$("#vkShipping").html("CHF "+price_delivery+".-- / € "+price_delivery_euro+".--");
			$("#delInfoShipping").attr('style','display:inline');
			
			
			updateGrandTotal();
			//alert("selected: "+sel+", price_delivery:"+price_delivery);
		});
	});
	
	
	
	
	
	
	
	
	
	// METHODS ----------------------------------------
	// calculation functions
	function updateGrandTotal(){
		
		// get all prices in table
		var total_price 		= 0;
		var total_price_euro 	= 0;
		var total_items			= 0;
		
		// chf
		$(".product_price").each( function(){
			var foundPrice 		= $(this).html();
			var foundPriceNr	= Number( foundPrice.substr(0, foundPrice.indexOf('.') ) );
			total_price 		+= foundPriceNr;
			total_items			++;
			//alert("total_price:"+total_price+"<");
			//return total_price;				
		});
		
		
		// euro
		$(".product_price_euro").each( function(){
			var foundPriceEuro	= $(this).html();
			var foundPriceEuroNr	= Number( foundPriceEuro.substr(0, foundPriceEuro.indexOf('.') ) );
			total_price_euro	+= foundPriceEuroNr;
		});
		
		
		// update delivery cost
		var found_delivery_total = $("#deliveryTotal").html();
		var found_delivery	= Number( found_delivery_total.substr(0, found_delivery_total.indexOf('.') ) );
		
		var delivery_total	= found_delivery == 0 ? price_delivery : found_delivery; //*total_items;
		$("#deliveryTotal").html(delivery_total+".--");
		
		
		
		// update delivery cost euro
		var found_delivery_euro_total 	= $("#deliveryTotalEuro").html();
		var found_delivery_euro			= Number( found_delivery_euro_total.substr(0, found_delivery_euro_total.indexOf('.') ) );
		
		var delivery_total_euro			= found_delivery_euro == 0 ? price_delivery_euro : found_delivery_euro; //*total_items;
		$("#deliveryTotalEuro").html(delivery_total_euro+".--");
		
		
		
		
		// update total in table
		var grand_total	= total_price + delivery_total;
		$("#grandTotal").html(grand_total+".--");
		
		var grand_total_euro	= total_price_euro + delivery_total_euro;
		$("#grandTotalEuro").html(grand_total_euro+".--");
		
		
		
		// set invisible if grandtotal is 10
		if(grand_total == price_delivery){
			$("#ilmiaBasketRow").hide();
			$(".orderAddressTr").addClass("dontShowTr");
			
			//$("#ilmiaBasketRow").fadeOut("slow");
			//$(".orderAddressTr").fadeOut("slow");
		}
		
		//alert("total_price:"+total_price+", found_delivery:"+found_delivery+", delivery_total:"+delivery_total+", grand_total:"+grand_total+"<");
		$("input:hidden").each(function (i) {
			//alert("input hidden : "+$(this).val()+", attr:"+$(this).attr("name"));						
		});
	}
	
	function getProductIdByProductName( prodName ){
		for(var key in arrProducts){
			var tName = arrProducts[key].name;
			if( tName == prodName ){
				return key;
			}
		}
		return false;
	}
	
	// CLICK-HANDLER ----------------------------------------
	// ADD NEW PRODUCT CLICK HANDLER
	$("#addProduct").click(
		function(){	
			
			// GET COUNT OF LISTS CURRENTLY USED:
			var listCnt				= Number( $("#basketList_id").val() );
			// update list count
			listCnt++;
			// update hidden input field 
			$("#basketList_id").val(listCnt);
			//alert("listCnt:"+listCnt);
					
			// GET SELECTED PRODUCT NAME & SIZE
			var product 			= $(".productDetail :selected");
			var product_id 			= product[0].value;
			//var product_size		= product[1].value;
			//var product_sizeshort 	= product_size.substr( 0, product_size.indexOf('-') - 1 );
			var product_size		= product[1].value;
			var product_sizeshort 	= product_size.split("_");
			var product_sizeshort_string = '';
			for(i=0; i<product_sizeshort.length; i++){ 
				if(i<product_sizeshort.length-1){ addStr = '/'; }else{ addStr = ''; }
				product_sizeshort_string += product_sizeshort[i]+addStr; 
			}
			//alert("click! >>> product:"+product_id+", product_size:"+product_size+", product_sizeshort:"+product_sizeshort+", product_sizeshort_string:"+product_sizeshort_string+", price:"+arrProducts[ product_id ].price );
						
			
			// ADD TABLE ROW FOR NEW PRODUCT			
			// 1) create html for new row
			var basketListId = 'basketList'+listCnt;
			var basketList 	= 	'<tr id="'+basketListId+'">';
						
			basketList		+= 	'<td class="tableCol1">' + arrProducts[ product_id ].name + '</td>';
			basketList		+= 	'<td class="tableCol2 product_price">' + arrProducts[ product_id ].price + '.--</td>';
			basketList		+= 	'<td class="tableCol2a">/</td>';
			basketList		+= 	'<td class="tableCol2b product_price_euro">' + arrProducts[ product_id ].priceEuro + '.--</td>';
			basketList		+= 	'<td class="tableCol3">' + product_sizeshort_string  + '</td>';
			basketList		+= 	'<td class="tableCol4">' + 1 + '</td>';
			basketList		+= 	'<td class="tableCol5">';
			basketList		+= 	'<div class="setQuantity">';
			basketList		+= 	'<a class="setQuantity_add" href="#"><img width="17" height="17" src="themes/ilmia_content/images/order_greenBtn.gif" alt="" /></a>';
			basketList		+= 	'<a class="setQuantity_subtract" href="#"><img width="17" height="17" src="themes/ilmia_content/images/order_redBtn.gif" alt="" /></a>';
			basketList		+= 	'</div>';
			basketList		+= 	'</td>';
			basketList		+= 	'</tr>';
							
			// 2) add row to table
			var table = $(".tableMiddleLines");			
			table.append( basketList );
			
			
			
			// ADD HIDDEN INPUT FIELDS FOR CURRENT ROW
			// find basketlist row : SAFARI HÄCK!!!
			var searchId 	= ".tableMiddleLines"+" #"+basketListId;
			var bskt = $( searchId );
			bskt.append( '<input type="hidden" name="basketList_product[]" id="basketList_product[]" value="' + product_id + '" />' );
			bskt.append( '<input type="hidden" name="basketList_price[]" id="basketList_price[]" value="299" />' );
			bskt.append( '<input type="hidden" name="basketList_price_euro[]" id="basketList_price_euro[]" value="236" />' );
			bskt.append( '<input type="hidden" name="basketList_size[]" id="basketList_size[]" value="' + product_sizeshort_string + '" />' );
			bskt.append( '<input type="hidden" name="basketList_quantity[]" id="basketList_quantity[]" value="1" />' );
			
			//alert("searchId:"+searchId+", bskt:"+bskt.html() );
			
					
			// CALCULATE TOTAL
			updateGrandTotal();
			
			// show basket
			$("#ilmiaBasketRow").show();
			// show form details
			$(".orderAddressTr").removeClass("dontShowTr");
			
			
			// CLICK-EVENTS FOR +/- BUTTONS ----------------------------------------
			
			// REMOVE/UNBIND ALL CLICK HANDLERS FIRST 		
			$(".setQuantity_add").unbind( "click" );
			$(".setQuantity_subtract").unbind( "click" );
				
			// ADD PRODUCT QUANTITY CLICK HANDLER
			$(".setQuantity_add").click(
				function(){	
					// get product details of current row				
					var htmlRow		= $(this).parent().parent().parent();
					var quantTd		= htmlRow.find(".tableCol4");
					var quantVal	= Number( quantTd.html() );
					var nameTd		= htmlRow.find(".tableCol1");
					var nameVal		= nameTd.html();					
					var productId	= getProductIdByProductName(nameVal);
					var priceTd		= htmlRow.find(".tableCol2");
					var priceEuroTd		= htmlRow.find(".tableCol2b"); // euro
					
					// add quantity by one
					var newQuant	= quantVal + 1;
					
					// update price
					var newPrice	= newQuant * arrProducts[ productId ].price;
					
					// update priceEuro
					var newPriceEuro	= newQuant * arrProducts[ productId ].priceEuro;
					
					// update html in row
					quantTd.html( newQuant );
					priceTd.html(newPrice+".--");
					priceEuroTd.html(newPriceEuro+".--");
										
					// find hidden input field basketList_quantity[] and remove it
					var quantInput	= htmlRow.find("input[id*=quantity]:hidden");
					quantInput.remove();
					// write hidden input field basketList_quantity anew
					var newQuantInput	= 	'<input type="hidden" name="basketList_quantity[]" id="basketList_quantity[]" value="' + newQuant + '" />';
					htmlRow.append( newQuantInput );
															
					// update grand total
					updateGrandTotal();
					
					//alert("input quantity: "+quantInput.html() );
					//alert("htmlRow:\n"+htmlRow.html());
					//alert("setQuantity_add >>> quantVal:"+quantVal+", newQuant:"+newQuant+", nameVal:"+nameVal+", productId:"+productId+", newPrice:"+newPrice);
					
					
				}
			);
			
			// SUBTRACT PRODUCT QUANTITY CLICK HANDLER
			$(".setQuantity_subtract").click(
				function(){	
					// get product details of current row				
					var htmlRow		= $(this).parent().parent().parent();
					var quantTd		= htmlRow.find(".tableCol4");
					var quantVal	= Number( quantTd.html() );
					var nameTd		= htmlRow.find(".tableCol1");
					var nameVal		= nameTd.html();					
					var productId	= getProductIdByProductName(nameVal);
					var priceTd		= htmlRow.find(".tableCol2");
					var priceEuroTd		= htmlRow.find(".tableCol2b"); // euro
					
					// subtract quantity by one
					var newQuant	= quantVal - 1;
					
					// update price
					newPrice		= newQuant * arrProducts[ productId ].price;
					
					// update priceEuro
					newPriceEuro	= newQuant * arrProducts[ productId ].priceEuro;
					
					// update html in row
					quantTd.html( newQuant );
					priceTd.html(newPrice+".--");
					priceEuroTd.html(newPriceEuro+".--");
										
					// find hidden input field basketList_quantity[] and remove it
					var quantInput	= htmlRow.find("input[id*=quantity]:hidden");
					quantInput.remove();
					// write hidden input field basketList_quantity anew
					var newQuantInput	= 	'<input type="hidden" name="basketList_quantity[]" id="basketList_quantity[]" value="' + newQuant + '" />';
					htmlRow.append( newQuantInput );
					
					
										
					//alert("setQuantity_subtract >>> quantVal:"+quantVal+", newQuant:"+newQuant+", nameVal:"+nameVal+", productId:"+productId+", newPrice:"+newPrice);
					
					// update grand total
					updateGrandTotal();
					
					// REMOVE ROW 
					if(newQuant == 0){
						htmlRow.remove();
					}
					
				}
			);
			
			
			
			
			
		}
	);
		
	
	
	// FORM VALIDATION	----------------------------------------	
	function setFormValidation() {
				
		// show a simple loading indicator
		var loader = $('<div id="loader"><img src="themes/ilmia_content/jQuery/formvalidation/loading.gif" alt="loading..." /></div>')
			.css({position: "absolute", top: "300px", left: "50%", display: "none", visibility: "hidden" })
			.appendTo("#der_inhalt");
		jQuery().ajaxStart(function() {
			//loader.show();
			loader.css({display: "inline", visibility: "visible"});
		}).ajaxStop(function() {
			//loader.hide();
			loader.css({display: "none", visibility: "hidden"});
		}).ajaxError(function(a, b, e) {
			throw e;
			//alert("ajax error!")
		});
		
				
		var container = $('#ilmiaFormError');
		// validate the form when it is submitted
		var validator = $("#ilmiaOrderForm").validate({	
			
			//*		
			submitHandler: function(form) {
				$(form).ajaxSubmit({
					target: "#formfeedback",
					success: function() { 
					//alert('Thanks for your order!'); 
						$("#ilmiaOrderForm").css({display:"none", visibility:"hidden"});
						$('#formfeedback').fadeIn('slow');						
					 }
				});
			},
			//*
			
			
			/*
			errorContainer: container,
			errorLabelContainer: $("ul", container),
			wrapper: 'li',
			ignore: '.ignoreThisField',
			/*/
			
			// dont display error messages: 
			errorPlacement: function(error, element) {
			     //error.appendTo( element.parent("td").next("td") );
				//alert("ERROR >>> element:"+element);				
			},
			
			
			rules: {			
				bill_firstname: 	{ required: true },
				bill_lastname: 		{ required: true },
				bill_street: 		{ required: true },
				bill_zipPlace: 		{ required: true },
									
				phone: 				{ required: true, minlength: 7 },
				email: 				{ required: true, email: true }
			},
			messages: {
				bill_firstname: 	"Geben Sie bitte Ihren Vornamen ein.<br />",
				bill_lastname: 		"Geben Sie bitte Ihren Nachnamen ein.",
				bill_street: 		"Geben Sie bitte Ihre Adresse ein.",
				bill_zipPlace: 		"Geben Sie bitte PLZ und Ort an.",
				addr_firstname: 	"Geben Sie bitte den Vornamen für die Versandadresse ein.<br />",
				addr_lastname: 		"Geben Sie bitte den Nachnamen für die Versandadresse ein.",
				addr_street: 		"Geben Sie bitte die Adresse für den Versand ein.",
				addr_zipPlace: 		"Geben Sie bitte PLZ und Ort für den Versand an.",
				phone: 				{
										required: "Geben Sie bitte Ihre Telefonnummer an.",
										minlength: "Geben Sie bitte mindestens 7 Zeichen ein."
									},			
				email: 				"Geben Sie bitte eine gültige E-Mail Adresse ein."
			}
		});		
	};
		
	setFormValidation();
	
	
	// SHIPPING ADDRESS OR NOT?		
	$("#addressesEqual").click( 
		function(){ 			
			var isChecked = $(this).attr("checked");
			if( isChecked ){
				$(".shippingAddressTr").addClass("dontShowTr");
				addressesEqualIsChecked = true;
				// remove rules
				$("#addr_firstname").rules("remove", "required");
				$("#addr_lastname").rules("remove", "required");
				$("#addr_street").rules("remove", "required");
				$("#addr_zipPlace").rules("remove", "required");
			}
			else {
				$(".shippingAddressTr").removeClass("dontShowTr");
				addressesEqualIsChecked = false;
				// add rules
				$("#addr_firstname").rules("add", { required:true });
				$("#addr_lastname").rules("add", { required:true });
				$("#addr_street").rules("add", { required:true });
				$("#addr_zipPlace").rules("add", { required:true });
								
			}
			//alert("addressesEqual >>> isChecked:"+isChecked); 
		}
	);
	
	
	// PAYMENTMETHOD	
	$("#paymentmethodRadio input").click( 
		function(){ 			
			var isChecked 	= $(this).attr("checked");
			var val			= $(this).val();
			if( val == 'vorauskasse' ){
				var delTot = price_delivery;
				$("#deliveryTotal").html(delTot+".--");
			}
			else if( val == 'nachnahme' ){
				var delTot = price_nachnahme + price_delivery;
				$("#deliveryTotal").html(delTot+".--");				
			}
			updateGrandTotal();
			//alert("paymentmethod >>> value:"+$(this).val()+", delTot:"+delTot+", isChecked:"+isChecked); 
		}
	);
	
	
	
	
	//********************************************** 
	// LIGHTBOX
	//**********************************************
	$(".lightbox a").lightbox();

	
	
	//********************************************** 
	// DROPDOWN PARAMS AUS DER URL
	//**********************************************
	function getURLParam(strParamName){
	  var strReturn = "";
	  var strHref = window.location.href;
	  if ( strHref.indexOf("?") > -1 ){
	    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
	    var aQueryString = strQueryString.split("&");
	    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
	      if (
	aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){
	        var aParam = aQueryString[iParam].split("=");
	        strReturn = aParam[1];
	        break;
	      }
	    }
	  }
	  return unescape(strReturn);
	}
	
	if ( getURLParam("shoe") ) {
		$("#contactFormFieldId_12 option").each(function (i) {
			//alert("-"+ getURLParam("shoe") +"=="+ $(this).val() +"-");
			if ( $(this).val().toLowerCase() == getURLParam("shoe").toLowerCase() ){ 
				$("#contactFormFieldId_12").attr("selectedIndex",i); 
				dropdownHandler({dropdownSetterId:"contactFormFieldId_12"});
			}
		});
	}
	
		
	
	//********************************************** 
	// DROPDOWN HANDLING
	//********************************************** 
	
	function dropdownHandler( eventObj ) { // shoePics
		var selectVal = $("#"+eventObj.dropdownSetterId).val();
		//alert("selectVal:"+selectVal);
		
		if( selectVal == 'brun'){
			$("#shoeImg_brun").removeClass("hideShoe");
			$("#shoeImg_noir").addClass("hideShoe");
			$("#shoeImg_blanc").addClass("hideShoe");
		}
		else if( selectVal == 'noir'){
			$("#shoeImg_brun").addClass("hideShoe");
			$("#shoeImg_noir").removeClass("hideShoe");
			$("#shoeImg_blanc").addClass("hideShoe");
		}
		else if( selectVal == 'blanc'){
			$("#shoeImg_brun").addClass("hideShoe");
			$("#shoeImg_noir").addClass("hideShoe");
			$("#shoeImg_blanc").removeClass("hideShoe");
		}	  	
    }
	
	// handler init
	$("#contactFormFieldId_12").change( function(){ dropdownHandler({dropdownSetterId:"contactFormFieldId_12"}); });
		
	
	
});

