jQuery.noConflict();

var debugEnabled = false;

try {
	console.log();
} catch(e) {
	console = {
		log: function(str) {
			return;
		}
	}; 
};

// Formatierung für die Alert-Meldungen
String.prototype.format = function(){  
	var pattern = /\{\d+\}/g;   
	var args = arguments;  
	return this.replace(pattern, function(capture){ return args[capture.match(/\d+/)]; });   
};

CONECTO = {

	createCookie: function(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = " expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name + "=" + value + ";" + expires + "; path=/";	
	},
	
	readCookie: function(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	},
	
	eraseCookie: function(name) {
		createCookie(name,"",-1);
	},

	mixture: {
		
		totalAmount: 250,		
		minItemAmount: 50,
		tax: 20, //20% mwst	
		currentAmount: 0,
		currentPrice: 0,		
		maxBlends: 10,	
		messages: {	
			maxBlendsError: "Maximale Anzahl der Sorten erreicht! ({0})",		
			totalAmountReachedError: "Maximale Füllmenge von {0}g erreicht!",		
			totalAmountTooLowError: "{0}g Packung zu klein für aktuelle Füllmenge von {1}g!",
			currentAmountTooLowError: "Es fehlen noch {0}g in Ihrer Packung!",
			noMixtureName: "Bitte geben Sie Ihrer Mischung einen Namen!",
			addToCartError: "Beim Hinzufügen zum Warenkorb trat ein Fehler auf!"
		},
		
		setTotalAmountSelection: function(amount) {
			var spans = document.getElementById("mixture-amount").getElementsByTagName("span");
			for (var i = 0; i < spans.length; i++) 
				spans[i].style.display = 'none';
			document.getElementById("mixture-amount_"+ amount).checked = true;
			document.getElementById("checked_mixture-amount_" + amount).style.display = 'inline';
		},
		
		setTotalAmount: function(amount, justInternal) {

			if(this.getCurrentAmount() > amount) {
				this.setTotalAmountSelection(this.getTotalAmount());
				alert(this.messages.totalAmountTooLowError.format(amount, this.getCurrentAmount()));				
				return false;
			}

			justInternal = justInternal || false;

			this.totalAmount = amount;

			if (!justInternal) {
			
				jQuery.post("/Conecto_Mixture_setTotalAmount.php", {
					totalAmount: amount
				});
				
				this.setTotalAmountSelection(amount);
				
				var tabsContainer = jQuery("div#mixture-tabs");
				
				tabsContainer.tabs('option', 'disabled', [2]);
				tabsContainer.tabs('select', 1);
				
				document.getElementById("mixtureContainerWrap").style.display = 'block';
				document.getElementById("mixture-amount-heading").innerHTML = amount;				
			}
			
			this.setCurrentAmountDisplay();
			this.updateAmountSelects();
			
			if(debugEnabled)
				console.log('this.totalAmount = '+ this.getTotalAmount());
		},
		
		getTotalAmount: function() {
			return parseInt(this.totalAmount);
		},
		
		getMinItemAmount: function() {
			return parseInt(this.minItemAmount);
		},		
		
		getCurrentAmount: function() {
			return parseInt(this.currentAmount); 
		},
		
		setCurrentAmount: function(amount) {
			this.currentAmount = amount;
			
			if(this.currentAmount > 0)
				this.setCurrentAmountDisplay();
			if(debugEnabled)
				console.log('set this.currentAmount = '+ this.currentAmount);
		},
		
		updateCurrentAmount: function(amount, type) {
			amount 	= parseInt(amount);
			if (type == 'add') 
				this.currentAmount += amount;
			else 
				this.currentAmount -= amount;			
		
			this.setCurrentAmountDisplay();
								
			if(debugEnabled) {
				console.log(type + ' ' + amount + ', after: this.currentAmount = ' + this.currentAmount + ', this.currentPrice ='+ this.currentPrice);
			}
		},
		
		setCurrentAmountDisplay: function() {
			//alert(currentAmount);
			var totalAmount = this.getTotalAmount();
			var currentAmount = this.getCurrentAmount();
			
			var percent = Math.round((currentAmount/totalAmount)*100); 
			document.getElementById("myMixtureAmountCurrent").innerHTML = percent; 	
			
			//Balken			
			var maxWidth = 169; //173
			var d = maxWidth/totalAmount;
			var m = currentAmount*d;
			var barWidth = m;
			barWidth += "px";
			document.getElementById("myMixtureAmountBar").style.width = barWidth;	
			
			this.setCurrentPriceDisplay();	
		},
		
		setCurrentPriceDisplay: function() {
			var price = 0;
			var selects = document.getElementById("myMixtureForm").getElementsByTagName("select");
			for (var i = 0; i < selects.length; i++) {
				var sel = selects[i];
				var id 	= sel.name;
				var p = parseFloat(document.getElementById("myMixture-item-"+id+"-price").value);
				p = (p/100)*sel.value;
				price += p;
			}
			if(price > 0) {
				//Brutto berechnen
				price = Math.round( price*(this.tax / 100+1) * 100) / 100;
				price = price.toString();
				
				//der schönheit halber bei einer nach komma stelle noch einen 0er dranhängen
				if(
					price.indexOf(".") != -1 && 
					price.substr(price.indexOf(".")+1, price.length).length == 1 && 
					price.charAt(price.length) != "0"
				)
					price += "0";
					
				this.currentPrice = parseFloat(price);
				price = price.replace(".", ",");
			} else {
				this.currentPrice = 0;
			}

			document.getElementById("myMixturePriceCurrent").innerHTML = price; 	
		},
		
		updateAmountSelects: function() {
			
			/*if(this.getNumBlends() < 2)
				return;		
*/
			var totalAmount 		= this.getTotalAmount();
			var currentAmount 		= this.getCurrentAmount();
			var minItemAmount 		= this.getMinItemAmount();
			var numBlends 			= this.getNumBlends();
			
			var selMax = totalAmount - currentAmount;
						
			if(debugEnabled)
				console.log("selMax: "+selMax);
				
			//Select Felder anpassen
			var selects = document.getElementById("myMixtureForm").getElementsByTagName("select"); 

			for (var i = 0; i < selects.length; i++) {
				
				var sel = selects[i];				
				var currentSelVal = parseInt(sel.value);				
				var maxSelVal = selMax + currentSelVal;
				
				//Optionen hinzufügen				
				for (var m = minItemAmount; m <= maxSelVal; m += minItemAmount) {
					if (!this.optionExists(sel, m)) {
						sel.options[sel.length] = new Option(m + "g", m);
					}
				}					
				/*
				var id 	= sel.name;				
				if(product_id && id == product_id)
					continue; //Das aktuelle lassen wir in ruhe							
				*/
				//Optionen entfernen deren Auswahl die Gesamtkapazität überschreiten würde
				var j;
				for (j = sel.length - 1; j >= 0; j--) {
					var opt = sel.options[j];
					var val = parseInt(opt.value);
					if (val > maxSelVal && val > currentSelVal) {
						sel.remove(j);
					}
				}

			}									
		},
		
		updateAmount: function(amount, product_id) {

			var oldAmountField = document.getElementById("myMixture-item-"+ product_id +"-current-amount");
			var oldAmount = oldAmountField.value;
			
			this.updateCurrentAmount(oldAmount, 'remove');
			this.updateCurrentAmount(amount, 'add');

			this.updateAmountSelects();
			
			oldAmountField.value = amount;
			
			jQuery.post("/Conecto_Mixture_updateAmount.php", {
				product_id: product_id, 
				amount: amount
			}, function(ret) {
				//jQuery("#myMixture").append(ret.html);
			}, "json");
		},
		
		addToMixture: function(name, product_id, price) {			
			
			var currentAmount 	= this.getCurrentAmount();
			var totalAmount 	= this.getTotalAmount();
			var minItemAmount 	= this.getMinItemAmount();
			var numBlends 		= this.getNumBlends();
						
			if(currentAmount > (totalAmount - minItemAmount)) {
				alert(this.messages.totalAmountReachedError.format(currentAmount));
			} else if (numBlends >= this.maxBlends) {
				alert(this.messages.maxBlendsError.format(this.maxBlends));
			} else {

				jQuery.post("/Conecto_Mixture_addToMixture.php", {
					product_id: product_id, 
					totalAmount: totalAmount,
					numBlends: (numBlends + 1)
				}, function(ret) {
					jQuery("#myMixture").append(ret.html);
					CONECTO.mixture.updateAmount(minItemAmount, product_id);
				}, "json");

				jQuery("#listing-item-"+product_id).slideUp("slow", function() {

				});			

				this.updateCurrentAmount(minItemAmount, 'add');
				
				this.updateAmountSelects();
			}
			return;
		},
		
		removeFromMixture: function(product_id, price) {
			
			var amount = document.getElementById("myMixture-item-"+ product_id +"-amount").value;
			
			this.updateCurrentAmount(amount, 'remove');
			
			this.updateAmountSelects();
			
			jQuery("#myMixture-item-"+product_id).slideUp("slow", function() {
				jQuery(this).remove();
				CONECTO.mixture.setCurrentPriceDisplay();
				jQuery("#listing-item-"+product_id).slideDown("slow", function() {

				});
			});
			jQuery.post("/Conecto_Mixture_removeFromMixture.php", {
				product_id: product_id,
				amount: amount
			});
		},
		
		showOrderTab: function() {
			var currentAmount 	= this.getCurrentAmount();
			var totalAmount 	= this.getTotalAmount();
			if(currentAmount < totalAmount) {
				alert(this.messages.currentAmountTooLowError.format(totalAmount-currentAmount));
				return false; 
			}
			var tabsContainer = jQuery("div#mixture-tabs");
			//tabsContainer.tabs('option', 'disabled', null);
			tabsContainer.tabs('option', 'disabled', []);
			tabsContainer.tabs('select', 2);
			jQuery.post("/Conecto_Mixture_getOrderForm.php", {}, function(ret) {
//				document.getElementById("mixture_name").value = ret.mixture_name;
			}, "json");
		},
		
		addToCart: function() {
			var mixture_name = document.getElementById("mixture_name").value;
			if(!mixture_name) {
				alert(this.messages.noMixtureName);
				return false;
			}
			var data = jQuery("#mixture_add_to_cart_form").serialize();
			

		    // unblock when ajax activity stops 
		    //jQuery().ajaxStop(jQuery.unblockUI); 
		 
		    jQuery.blockUI({ 
				message: '<div style="padding: 10px;"><h2 style="margin: 0; height:30px; line-height:30px">Einen Moment bitte <img style="vertical-align: bottom" src="/skin/frontend/default/tridor/images/ajax-loader.gif" alt="" /></h2></div>' 
			}); 
		       				
			jQuery.post("/Conecto_Mixture_addToCart.php", data, function(ret) {
				if(ret.success_url) {
					window.location = ret.success_url;
				} else {
					jQuery.unblockUI();
					alert(this.messages.addToCartError);
				}
			}, "json");
		},
		
		checkMixtureName: function(el) {
			if(el.value.length >= 45)
				alert("Maximale Länge erreicht!");
			return;
		},
		
		getNumBlends: function() {
			return jQuery("#myMixture").children().size();
		},
		
		optionExists: function(el, m) {
			for(var i = 0; i < el.length; i++) {
				if(el.options[i].value == m)
					return true;
			}
			return false;
		}
	}
};

/*
 * Sende einen Heartbeat zum Server
 */ 
 /*
jQuery.keepAlive = {
	options: {
		url: "/common/keepalive.php",
		delay: 10	
	},	
	dummyfn:  function(){
	
	},
	
	timeoutobj:  {
		id: -1
	},
	
	set: function(options, ondummyfn) {
		if (this.timeoutobj.id > -1)
			clearTimeout(this.timeoutobj);
	
		if (options) 
			jQuery.extend(this.options, options);
	
		if (ondummyfn) 
			this.dummyfn = ondummyfn;
	
		this.timeoutobj.id = setTimeout(function() {
			jQuery.keepAlive.beat(); 
		}, this.options.delay*1000);
	},
	
	beat: function() {
		jQuery.post(this.options.url, { });
		this.timeoutobj.id = setTimeout(function(){
			jQuery.keepAlive.beat();
		}, this.options.delay*1000);
		this.dummyfn();
	}
};

jQuery.keepAlive.set({
	url: "/Conecto_Mixture_keepAlive.php",
	delay: 2*60
});
*/