// usage: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};

/*
 ____  __.____ __________  _____________________     ________________
|    |/ _|    |   \      \ \_   _____/\______   \   /  _  \__    ___/
|      < |    |   /   |   \ |    __)_  |       _/  /  /_\  \|    |   
|    |  \|    |  /    |    \|        \ |    |   \ /    |    \    |   
|____|__ \______/\____|__  /_______  / |____|_  / \____|__  /____|   
        \/               \/        \/         \/          \/         
*/

$(document).ready(function(){
	
	// *** Datenschutz/Recht
	var policyListLi = $('#policyList li');
	policyListLi.click(function() {
		policyListLi.removeClass("open");
		$(this).toggleClass("open");
	}); 
	
	// *** LAYER 
	
	var overlay = $("#overlay");
	function showOverlay() {
				overlay.height($(document).height());
		overlay.show();
	}
	
	$("#linkUnileverGroup").click(function(){
		$("#unileverLayer").show();
		if ( !($.browser.msie && $.browser.version.substr(0,1)<8) ) {	
			showOverlay();
		}
		return false;
	});
	
	$("#legalcontactlayerlink").click(function(){
		$("#EMailAnDenDatenschutz").show();
		if ( !($.browser.msie && $.browser.version.substr(0,1)<8) ) {
			showOverlay();
		}
		return false;
	});
	
	$("#codeHelp, .closeBtn").click(function(){
		$(".layer").hide();
		overlay.hide();
		return false;
	});
	
	overlay.click(function(){
		$(this).hide();
		$(".layer").hide();
		return false;
	});
	
	//*** CAPTCHA Layer
	$(".captchaHelpLayerTrigger").click(function(){
		showOverlay();
		$("#codeHelp").show();
		return false;
	});
	
	// ***
	$(".tabNavi a").click(function(){
		if(!($(this).parent().hasClass("act")))
			$(".tabNavi").toggleClass("zubereitungAct");
		$(".textContent .tabContent").hide();  
		$(".tabNavi li").removeClass("act");
		$(this).parent().addClass("act");
		$($(this).attr("href")).show();    
		return false;
	});
	
	// *** scroll pane *** 
	if ($('.scroll-pane').length) {
		$('.scroll-pane').jScrollPane({
			verticalDragMinHeight: 10,
			verticalDragMaxHeight: 10
		});
	}
	
	// KONTAKT Formular
	var productIdLevel1 = $("#ProductIdLevel1");
	var productIdLevel2 = $("#ProductIdLevel2");
	var productIdLevel3 = $("#ProductIdLevel3");
	var productIdLevel4 = $("#ProductIdLevel4");
	var complaintsForm = $('#complaintsForm');
	var callToAction = "<option>Bitte ausw&auml;hlen</option>";
	var url = "/Siteutilities/ProductsAsJSON/";
	var productId = "";

	$("#FirstPage_Theme").change(function() {
		log("FirstPage_Theme changed");
		log($(this).val());
		$("#ProductIdLevel2, #ProductIdLevel3, #ProductIdLevel4").hide();
		complaintsForm.hide();
		if ($(this).val() === "criticism" ) {
			complaintsForm.show();
			productIdLevel1.parents('div:first').show();
		} else if ($(this).val() === "other" ) {
			productIdLevel1.parents('div:first').hide();
		} else {
			productIdLevel1.find('option:first').attr('selected', 'selected').parent('select');
			productIdLevel1.parents('div:first').show();
		}
		
	});
	
	productIdLevel1.change(function() {
		// hide unused elements
		$("#ProductIdLevel2, #ProductIdLevel3, #ProductIdLevel4").hide();

		//var productId = "";
		productId = $(this)[0].value;
		if(productId !== ""){
			$.getJSON(url+ productId, null, function(data) {
				productIdLevel2.empty();
				productIdLevel2.append(callToAction);
				$.each(data, function(index, optionData) {
					productIdLevel2.append("<option value='" + optionData.Id + "'>" + optionData.Name + "</option>");
					productIdLevel2.show();
				});
			});
		}
	});

	productIdLevel2.change(function() {
		// hide unused elements
		$("#ProductIdLevel3, #ProductIdLevel4").hide();

		//var productId = "";
		productId = $(this)[0].value;
		if(productId !== ""){
			$.getJSON(url + productId, null, function(data) {
				productIdLevel3.empty();
				productIdLevel3.append(callToAction);
				//console.info(data);
				$.each(data, function(index, optionData) {
					productIdLevel3.append("<option value='" + optionData.Id + "'>" + optionData.Name + "</option>");
					productIdLevel3.show();
				});
			});
		}	
	});

	productIdLevel3.change(function() {
		productIdLevel4.hide();
		//var productId = "";
		productId = $(this)[0].value;
		if(productId !== ""){
			$.getJSON(url+ productId, null, function(data) {
				productIdLevel4.empty();
				productIdLevel4.append(callToAction);
				$.each(data, function(index, optionData) {
					productIdLevel4.append("<option value='" + optionData.Id + "'>" + optionData.Name + "</option>");
					productIdLevel4.show();
				});
			});
		}	
	});
	
	// Produktbeanstandung
	var packingExistSwitch = $("#packingExistSwitch");

	if ($("input[name='FirstPage.ExistPackaging']:checked").val() !== 'True') {
		packingExistSwitch.hide();
	}

	$("input[name='FirstPage.ExistPackaging']").change(function(){ 
		if ($("input[name='FirstPage.ExistPackaging']:checked").val() === 'True') {
			packingExistSwitch.show();
		}  
		else if ($("input[name='FirstPage.ExistPackaging']:checked").val() === 'False') {
			packingExistSwitch.hide();
		}
	});
	
	$("#showHelp").click(function(){
		$("#helpBox").toggle();
		return false;
	});
	
	//  Mindesthaltbarkeitsdatum 
	var best_before_day = $("#best_before_day");
	var date_month = $("#best_before_month");
	var date_year = $("#best_before_year");
	var firstPage_ExpireDate = $("#FirstPage_ExpireDate");
	
	 function getNewExpireDate()  {
		var FirstPage_ExpireDateNewVal = best_before_day.val() + "." + date_month.val() + "." + date_year.val() + " " + "00:00:00";
		firstPage_ExpireDate.val(FirstPage_ExpireDateNewVal);
		log("getNewExpireDate");
	}

	best_before_day.change(getNewExpireDate);
	date_month.change(getNewExpireDate);
	date_year.change(getNewExpireDate);
	
	// 	Produktionszeit
	var productionTime_hour = $("#productionTime_hour");
	var productionTime_minute = $("#productionTime_minute");

	function getNewProductionTime() {
		productionTime_hour_val = (productionTime_hour.val() !== "" ) ? productionTime_hour.val() : "00" ;
		productionTime_minute_val = (productionTime_minute.val() !== "" ) ? productionTime_minute.val() : "00" ;
		var ProductionTimeNewVal = "01.01.0001 " + productionTime_hour_val + ":" + productionTime_minute_val + ":00";
		$("#FirstPage_ProductionTime").val(ProductionTimeNewVal);
	}
	
	productionTime_hour.blur(getNewProductionTime);
	productionTime_minute.blur(getNewProductionTime);	
	
	
	// Validation
	$('.numbersOnly').keyup(function () { 
	    this.value = this.value.replace(/[^0-9\.]/g,'');
	});
	
	// E-Mail an den Datenschutz
	var AjaxForm = {
			selector: 'form.ajaxRequest',
			//userId: $('body').attr('data-userhash'),
			init: function() {
				var _this = this;
				$(this.selector).each(function(index) {
					$(this).attr('id', 'ajaxRequest_'+index);
					_this.formObserve($(this).attr('id'));
				});
			},
			formObserve: function(id) {
				var _this = this;
				var form = $('#'+id);
				form.submit(function() {
					if(form.serialize() != "") {
						$.ajax({
							//url: form.attr('action')+"?userId="+_this.userId,
							url: form.attr('action'),
							data: form.serialize(),
							type: form.attr('method'),
							cache: false,
							success: function(data) {
								form.replaceWith(data);
								_this.init();
							}
						});
					}
					return false;
				});
			}
		};
	if($('form.ajaxRequest').length) {
			AjaxForm.init();
	}

	
// Rezepte 	
	if($('.carousel').length) {
		$(".carousel ul").carouFredSel({
			items       : 6,
			auto				: false,
	    prev				:	".carouselWrapper .prev",
	    next				:	".carouselWrapper .next"
		}).trigger('slideTo','[data-id='+window.location.hash+']');
		$('[data-id='+window.location.hash+']').addClass('active');
	}
	
	if ( $.browser.msie || $("#zubereitung").length) {
		$("#zubereitung, #Von1869").hide();
	}
	
	
	// Geschichte
	if($('#player1989').length){
		var $geschichte1869 = $("#geschichte1869");
		var $tvSpots = $("#videoPlayer");
	
		var currentPlayer = player1989;
		var currentPlayerBox = $(player1989.box);
		
		$('.video-js-box').not('#player1989').hide();
		
		$("#tvSpotsTab").bind('click', function(){
			$geschichte1869.hide();
			$tvSpots.show();
		});
		
		$("#von1869Tab").bind('click', function(){
			$geschichte1869.show();
			$tvSpots.hide();
			if(currentPlayer.html5Supported()){
					currentPlayer.pause();
				} else {
					$f("*").each(function() {
						this.stop();
					});
				}
		});
		
		$("#tvControls b").bind('click', function(){
			var player = eval($(this).attr("data-video"));
			if(currentPlayer != player){
				if(currentPlayer.html5Supported()){
					currentPlayer.pause();
					currentPlayer.currentTime(0);
					currentPlayerBox.hide();
					currentPlayerBox = $(player.box).show();
					currentPlayer = player;
					currentPlayer.play();
				} else {
					$f("*").each(function() {
						this.stop();
					});
					currentPlayerBox.hide();
					currentPlayerBox = $(player.box).show();
					currentPlayer = player;
				}
				
			}
		});
		
	}

});


