$(document).ready(function() {

	/* *******************************************************************
	 * superfish menue
	 * *******************************************************************/
	$("ul.sf-menu").supersubs({ 
		minWidth:			20,							// minimum width of sub-menus in em units 
		maxWidth:			30,							// maximum width of sub-menus in em units 
		extraWidth:		1								// extra width can ensure lines don't sometimes turn over due to slight rounding differences and font-family 
	}).superfish({

		// superfish defaults
		/*
		hoverClass:		'sfHover',					// the class applied to hovered list items 
		pathClass:			'overideThisToUse',	// the class you have applied to list items that lead to the current page 
		pathLevels:		1,								// the number of levels of submenus that remain open or are restored using pathClass 
		delay:				800,							// the delay in milliseconds that the mouse can remain outside a submenu without it closing 
		animation:			{opacity:'show'},			// an object equivalent to first parameter of jQuery’s .animate() method 
		speed:				'normal',					// speed of the animation. Equivalent to second parameter of jQuery’s .animate() method 
		autoArrows:		true,							// if true, arrow mark-up generated automatically = cleaner source code at expense of initialisation performance
		dropShadows:	true,							// completely disable drop shadows by setting this to false 
		disableHI:			false,							// set to true to disable hoverIntent detection 
		onInit:				function(){},				// callback function fires once Superfish is initialised – 'this' is the containing ul
		onBeforeShow:	function(){},				// callback function fires just before reveal animation begins – 'this' is the ul about to open 
		onShow:			function(){},				// callback function fires once reveal animation completed – 'this' is the opened ul 
		onHide:				function(){}				// callback function fires after a sub-menu has closed – 'this' is the ul that just closed  
		*/
	
		delay:				400,							// 400 milliseconds delay on mouseout 
		speed:				'fast',							// faster animation speed 
		autoArrows:		false,						// disable generation of arrow mark-up 
		onBeforeShow:	function() {
			var ul = this;
			var cat = ul.attr("name");
			if (cat) {
				$.getJSON( '/karlie/index.php?forward=services/menuAjaxService.php&lang='+lang+'&cat=' + cat, function(data) {
					var html = "";
					if(data !== null) {
						$.each(data, function(key, item){
							html +="<li><a href=\"" + item.url + "\">";
							html += item.label;
							html+="</a></li>";
						});
						ul.html(html);
						$('li:last', ul).addClass('last');
						$("ul.sf-menu").supersubs({
							minWidth:		20, 
							maxWidth:		30, 
							extraWidth:	1 
						});
					}
				});
			}
		}
	
	});


	/* *******************************************************************
	 * treeview submenue
	 * *******************************************************************/

	if ($('ul#treeview').length > 0) {
		$("#treeview").treeview({
			url: '/karlie/index.php?forward=services/menuAjaxService.php&lang='+lang+'&cat='+cat,
			collapsed: true,
			unique: true
			//animated: 'fast'
		});
	}

	if ($('ul#checkoutTreeview').length > 0) {
		$("#checkoutTreeview").treeview({
			collapsed: false
			//animated: 'fast',
			//unique: true
		});
	}

	if ($('ul#noveltiesTreeview').length > 0) {
		$("#noveltiesTreeview").treeview({
			collapsed: false
			//animated: 'fast',
			//unique: true
		});
	}

	if ($('ul#hotDealsTreeview').length > 0) {
		$("#hotDealsTreeview").treeview({
			collapsed: false
			//animated: 'fast',
			//unique: true
		});
	}
	
	
	/* *******************************************************************
	 * showcase widget
	 * *******************************************************************/
	/*
	var descs = {
		'IMG-08348': 'Das Set für den perfekten Start des K&auml;tzchens ins Familienleben!',
		'IMG-61053': 'Quantum Guard - das Multifunktionsbett mit unsichtbarem Faserschutzsystem',
		'IMG-65129': 'Jetzt muss Ihre Katze nicht mehr vor verschlossener Tür auf Sie warten!',
		'IMG-84333': 'Magic Ball - das Spielzeug für aktive und neugierige Hamster',
		'IMG-88089': 'Clever spielen mit Köpfchen - Streetball für Wellensittiche'
	};
	*/
		
	$('.roundabout li').focus(function() {
		var useText = (typeof descs[$(this).attr('id')] != 'undefined') ? descs[$(this).attr('id')] : '';
		$('#description').html(useText).fadeIn(200);
	}).blur(function() {
		$('#description').fadeOut(100);
	});
		
	var interval;
		
	$('.roundabout').roundabout({
		shape: 'lazySusan',
		minOpacity: 1.0,
		maxOpacity: 1.0,
		minScale: 0.1,
		maxScale: 1.5,
		tilt: -12.0,
		clickToFocus: false,
		btnNext: '#arrow-right',
		btnPrev: '#arrow-left',
		reflect: true
	}).hover(
		function() {
			clearInterval(interval);
		},
		function() {
			interval = startAutoPlay();
		}
	);
		
	interval = startAutoPlay();

	function startAutoPlay() {
		return setInterval(function() {
			$('.roundabout').roundabout_animateToNextChild();
		}, 6000);
	}


	/* *******************************************************************
	 * text shadow for IE8 (not working at the moment)
	 * *******************************************************************/
	$("span.textShadow").textShadow();


	/* *******************************************************************
	 * JSON suggest box
	 * *******************************************************************/
	var result = "{}";
	var currequest = null;
	$('input#suggestBox').jsonSuggest(
		function(text, wildCard, caseSensitive, notCharacter) {
			var old = currequest;
			currequest = text;
			if(old!=currequest) {
				$.ajax({
					url: '/karlie/services/searchAjaxService.php?lang='+langId+'&q='+text+'&cat='+cat,
					dataType: 'json',
					success: function(data){
						if(currequest==text) {
							result=data;
							$('input#suggestBox').keyup();
						}
					}
				});
			}
	
			return result;
		},
		{ajaxResults:true}
	);
	
	$('input#suggestBox').focusout(function() {
		$(".jsonSuggestResults").fadeOut();
	});
	
	/* *******************************************************************
	 * login box
	 * *******************************************************************/
    $(".signin, .hotlineHomepage").click(function(e) {          
		e.preventDefault();
        $("fieldset#signin_menu").toggle();
		$(".signin").toggleClass("menu-open");
		$(".signin").blur();
		$("#username").focus();
    });
	
	$("fieldset#signin_menu").mouseup(function() {
		return false;
	});
	$(document).mouseup(function(e) {
		if($(e.target).parent("a.signin").length==0) {
			$(".signin").removeClass("menu-open");
			$("fieldset#signin_menu").hide();
		}
	});


	/* *******************************************************************
	 * sortable tables
	 * *******************************************************************/
	$(".tablesorter").tablesorter({
		sortList: [[0,0]],
		widgets: ['zebra']
		/*
		headers: {
			5:{sorter: false},
			6:{sorter: false},
			7:{sorter: false},
			7:{sorter: false},
			8:{sorter: false},
			9:{sorter: false},
			10:{sorter: false},
			11:{sorter: false}
		}
		*/
	});
	/*$(".tablesorter").tablesorter();*/
	

	/* *******************************************************************
	 * submit search filter form on change
	 * *******************************************************************/
	$("#productSearchForm select, #productSearchForm input[type=checkbox]").change(function() {
		document.productSearchForm.submit();
	});

	
	/* *******************************************************************
	 * submit num per page form form on change
	 * *******************************************************************/
	$(".numPerPageForm select").change(function() {
		//document.numPerPageForm.submit();
		$(this).parents("form").submit();
	});


	/* *******************************************************************
	 * tab box
	 * *******************************************************************/
	$("ul.tabs").tabs("div.panes > div", {
		effect: 'fade'
	});
	$("ul.tabs A").click(function() {
		this.blur();
	});

	
	/* *******************************************************************
	 * rating modal box
	 * *******************************************************************/
	var triggers = $(".openRatingModal").overlay({ 
		effect: 'apple',
		/*
		expose: { 
			color: '#2D7239', 
			loadSpeed: 200, 
			opacity: 0.9 
	    },
	    */
	    closeOnClick: false
	});

	$(".cancel").click(function(){
		triggers.overlay().close();
	});

	$("#submitReview").click(function(){					   				   

		var reviewToVal = $("#reviewText").val();
		
		/*
		if(reviewToVal == '') {
			return false;
		}
		*/

		$("#reviewButtons").html('<img src="/karlie/templates/html/img/ajax-loader.gif" alt="Lade" id="loading" />');

		$.post("/karlie/index.php?forward=services/rateAjaxService.php",
			$("#rating").serialize(),
				function(data) {
					if(data=="OK") {
						$("#reviewButtons").html('');
						if(reviewToVal == '') {
							$("#msg").html('<ul class="messages"><li class="success-msg"><ul><li>Bewertung erfolgreich gesendet.</li></ul></li></ul>');
						}
						else {
							$("#msg").html('<ul class="messages"><li class="success-msg"><ul><li>Rezension und Bewertung erfolgreich gesendet.</li></ul></li></ul>');
						}
						$("#msg").append('<br /><div><input type="button" class="button cancel"  style="float: right;" value="Schließen"></div>').hide().fadeIn();
						$(".cancel").click(function(){
							triggers.overlay().close();
						});
						//triggers.overlay().close();
					}
					else {
						$("#reviewButtons").html('');
						$("#msg").html('<ul class="messages"><li class="error-msg"><ul><li>Ein Fehler ist aufgetreten.</li></ul></li></ul>');
						$("#msg").append('<br /><div><input type="button" class="button cancel"  style="float: right;" value="Schließen"></div>').hide().fadeIn();
						$(".cancel").click(function(){
							triggers.overlay().close();
						});
						//triggers.overlay().close();
					}
				}
		);

		return false;
	});	
	

	/* *******************************************************************
	 * rating stars widget
	 * *******************************************************************/
	$(function(){
		$("#starify").children().not(":input").hide();
		$("#starify").stars({});
	});


	/* *******************************************************************
	 * product image zoom
	 * *******************************************************************/
	$("img[rel], span.productImageZoomTrigger[rel], span.noveltiesProductImageZoomTrigger[rel], span.hotDealsProductImageZoomTrigger[rel]").overlay({ 
		//effect: 'apple',
		expose: { 
			//color: '#2D7239', 
			color: '#666', 
			loadSpeed: 200, 
			opacity: 0.9 
	    }
	});
	

	/* *******************************************************************
	 * 360 player
	 * *******************************************************************/
	$('.productImage360Trigger').click(function(){
		var playerWindow = '';
		$('.productBoxContentLeft').append('<div class="playerWindow"></div>');
		$('.playerWindow').html('');
		playerWindow = create360Player($(this).attr("rel"));
		playerWindow.overlay().load();
	});

	function create360Player(PlayerID) {
		var pic = PlayerID + '_360_x_';
		var dir = "/images/" + PlayerID;
		var qua = 36;
		var zoom = 1/4;
		var rot = 2;
		var player = '/karlie/templates/html/flash/360Player/360Player.swf';
		var url = player + '?pc=' + pic + '&dr=' + dir + '&zo=' + zoom + '&rt=' + rot + '&qa=' + qua;
		
		$('.playerWindow').flashembed({
			src: url,
			allowfullscreen: false,
			codebase: 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
			width: '420',
			height: '420',
			quality: 'high',
			pluginspage: 'http://www.adobe.com/go/getflashplayer_de',
			align: 'middle',
			play: 'true',
			loop: 'true',
			scale: 'showall',
			wmode: 'opaque',
			devicefont: 'false',
			id: '360player_' + PlayerID,
			bgcolor: '#ffffff',
			name: '360player_' + PlayerID,
			menu: 'false',
			allowFullScreen: 'false',
			allowScriptAccess: 'sameDomain',
			movie: url,
			salign: ''
		});
		
		playerWindow = $('.playerWindow').overlay({ 
			oneInstance: false,
			expose: { 
				color: '#666', 
				loadSpeed: 200, 
				opacity: 0.9 
		    },
		    onClose: function(){
		    		$('.playerWindow').fadeOut().remove();
		    }
		});
		
		return playerWindow;
	}


	/* *******************************************************************
	 * shop-home live search
	 * *******************************************************************/
	$("#productSearchFormShopHome input").change(function(){
		$.post("/karlie/index.php?forward=services/liveSearchAjaxService.php",
				$("#productSearchFormShopHome").serialize(),
				function(data) {
					if(data!="FAILD") {
						var d = jQuery.parseJSON(data);
						$("#numArticles").html(d.numArticles);
						$("#numResults").html(d.numResults);
					}
				}
		);
	});
	

	/* *******************************************************************
	 * in den warenkorb legen bei return
	 * *******************************************************************/
	$('.productAmountField').keypress(function(event) {
		  if (event.keyCode == '13') {
			  $(this).parents("form,tr").find('.addToBasketButton,.addToBasketButton2').click();
			  return false;
		   }
	});	
	

	/* *******************************************************************
	 * add to basket buttons
	 * *******************************************************************/
	var loaderOverlay = $(".addToBasketLoader").overlay({
		left: 390,
		top: '40%',
		closeOnClick: false
	});

	$(".addToBasketButton").click(function() {

		//console.log("Adding item to the basket...");
		loaderOverlay.overlay().load();
		var productAmount = $(this).parent("form").find('.productAmountField').val();
		if (productAmount == 'Stk.' || productAmount == 0  || productAmount == '') {
			$(this).parent("form").find('.productAmountField').val(1);
		}
		$.post("/karlie/index.php?forward=services/updateCartAjaxService.php",
			$(this).parent("form").serialize(),
			function(data) {
				data = jQuery.parseJSON(data);
				if(typeof data.errors === 'undefined') {
					//console.log("Item successfully added.");
					$(".addToBasketLoader .loading").hide();
					$(".addToBasketLoader .msg").html('<ul class="messages"><li class="success-msg"><ul><li>Artikel wurde in den Warenkorb gelegt.</li></ul></li></ul>');
					loaderOverlay.delay(1200).overlay().close();
				}
				else {
					//console.log("Failure! Item was NOT added.");
					$(".addToBasketLoader .loading").hide();
					$(".addToBasketLoader .msg").html('<ul class="messages"><li class="error-msg"><ul id="em"><li>Ein Fehler ist aufgetreten.</li></ul></li></ul>');
					$.each(data.errors,function(index,value){
						$(".addToBasketLoader .msg #em").append('<li>' +value+ '</li>');
					});
					$(".addToBasketLoader .msg").append('<br /><div><input type="button" class="button cancel"  style="float: right;" value="Schließen"></div>').hide().fadeIn();
					$(".cancel").click(function(){
						loaderOverlay.overlay().close();
						$(".addToBasketLoader .msg").html('');
						$(".addToBasketLoader .loading").show();
					});
				}
			}
		);
		return false;
	});
	
	$(".addToBasketButton2").click(function(){
		//console.log("Adding item to the basket...");
		var inp = $(this).parents("tr").find("input");
		var name = inp.attr("name");
		var val = inp.val();
		if (val == 0  || val == '') {
			val = 1;
		}
		var data = {};
		data[name]=val;

		loaderOverlay.overlay().load();

		$.post("/karlie/index.php?forward=services/updateCartAjaxService.php",
				data,
				function(data) {
					data = jQuery.parseJSON(data);
					if(typeof data.errors === 'undefined') {
						//console.log("Item successfully added.");
						$(".addToBasketLoader .loading").hide();
						$(".addToBasketLoader .msg").html('<ul class="messages"><li class="success-msg"><ul><li>Artikel wurde in den Warenkorb gelegt.</li></ul></li></ul>');
						loaderOverlay.delay(1200).overlay().close();
					}
					else {
						//console.log("Failure! Item was NOT added.");
						$(".addToBasketLoader .loading").hide();
						$(".addToBasketLoader .msg").html('<ul class="messages"><li class="error-msg"><ul id="em"><li>Ein Fehler ist aufgetreten.</li>');
						$.each(data.errors,function(index,value){
							$(".addToBasketLoader .msg #em").append('<li>' +value+ '</li>');
						});
						$(".addToBasketLoader .msg").append('</ul></li></ul>');
						$(".addToBasketLoader .msg").append('<br /><div><input type="button" class="button cancel"  style="float: right;" value="Schließen"></div>').hide().fadeIn();
						$(".cancel").click(function(){
							loaderOverlay.overlay().close();
							$(".addToBasketLoader .msg").html('');
							$(".addToBasketLoader .loading").show();
						});
					}
				}
		);
		
		return false;
	});


	/* ***************************************************************** */

	var checkoutLoaderOverlay = $(".checkoutLoader").overlay({
		left: 385,
		top: '40%',
		closeOnClick: false
	});	

	/* *******************************************************************
	 * generate the cart items table
	 * cartData is set directly in mainareaLeftCheckout.csi
	 * 
	 *	$cartArray['items'][$productId]['artnr'] = $articleID;
	 *	$cartArray['items'][$productId]['amount'] = $articleAmount;
	 *	$cartArray['items'][$productId]['price'] = $articlePrice;
	 *	$cartArray['items'][$productId]['vpe'] = $vpe;
	 *	$cartArray['items'][$productId]['sum'] = $artikelSumme;
	 *	$cartArray['items'][$productId]['eshopItemId'] = $eshopItemId;
	 * $cartArray['items'][$productId]['nameCropped'] = $artNameCropped;
	 *	$cartArray['items'][$productId]['name'] = $artName;
	 *	$cartArray['items'][$productId]['mwst'] = $articleMwst;
	 * $cartArray['items'][$productId]['image'] = $image;
	 *	$cartArray['items'][$productId]['detailUrl'] = $detailUrl;
	 * *******************************************************************/
	function genearateCartTable() {
		if(typeof cartData !== 'undefined') {
			if(typeof cartData.items !== 'undefined') {
				//checkoutLoaderOverlay.overlay().load();
				$.each(cartData.items, function(index,value){
				
					$("#cartTable").find("tbody").append(
						"<tr id='item_"+index+"'><td>" + value.artnr + "</td><td>" + value.name + 
						"</td><td align=\"right\"><nobr>" + (value.price + "").replace(/\./g, ",") + " €</nobr></td><td  align=\"right\">" + value.mwst + 
						"%</td><td id=\"amount\" align=\"center\"><input size=\"4\" type=\"text\" class=\"foField\" name=\"items[" + value.eshopItemId + "]\" value=\"" +  value.amount + 
						"\" /><span class=\"berr\"></span></td><td align=\"right\"><nobr>" + (value.price * value.amount).toFixed(2).replace(/\./g, ",") + 
						" €</nobr></td><td align=\"center\" valign=\"middle\"><img src=\"/karlie/templates/html/img/icons/delete.png\" width=\"14\" height=\"14\" alt=\"Loeschen\" class=\"deleteBasketItem\" /></td></tr>"
					);//.hide().fadeIn();
					
					$("#cartTable2").find("tbody").append(
							"<tr><td>" + value.artnr + "</td><td>" + value.name + "</td><td  align=\"right\"><nobr>" + (value.price + "").replace(/\./g, ",") + " €</nobr></td><td  align=\"right\">" + value.mwst + "%</td><td align=\"right\">" +  value.amount + "</td><td align=\"right\"><nobr>" + (value.price * value.amount).toFixed(2).replace(/\./g, ",") + " €</nobr></td></tr>"
						);//.hide().fadeIn();
	
				});
				//checkoutLoaderOverlay.overlay().close();
			}
			
			$("#cartTable").find("tbody").append("<tr><td colspan='2'>Art.Nr. / EAN:</td><td colspan='2' align=\"center\"><input size='20' class='foField' id='foFieldArt' name='art' tabindex='1' /></td><td><input size=\"4\" class='foField' id=\"foFieldAm\" type=\"text\" name=\"artItem\" tabindex='2' value=\"1\" /></td><td>&nbsp;</td><td align=\"center\" valign=\"middle\">&nbsp;</td></tr>").fadeIn(null,function(){$('#foFieldArt').focus();});
			

			$("#cartTable2").find("tbody").append("<tr style='font-size:3px;'><td colspan='2'></td><td style='background-color:#cccccc;' colspan='4'></td></tr>");//.hide().fadeIn();
			$("#cartTable2").find("tbody").append("<tr><td colspan='2'></td><td colspan='3'>Summe:</td><td  align=\"right\">" + (cartData.subtotal1 + "").replace(/\./g, ",") + " €</td></tr>");//.hide().fadeIn();
			$("#cartTable2").find("tbody").append("<tr style='font-size:3px;'><td colspan='2'></td><td style='background-color:#cccccc;' colspan='4'></td></tr>");//.hide().fadeIn();
			
			$("#cartTable2").find("tbody").append("<tr><td colspan='2'></td><td colspan='3'><span class='red'>Onlinerabatt:</span></td><td  align=\"right\"><span class='red'>-" + cartData.onlinediscount + " €</span></td></tr>");//.hide().fadeIn();
			//$("#cartTable2").find("tbody").append("<tr><td colspan='5'>Zwischensumme:</td><td>" + cartData.subtotal2 + "</td></tr>").hide().fadeIn();
			$("#cartTable2").find("tbody").append("<tr><td colspan='2'></td><td colspan='3'>Rechnungsrabatt:</td><td align=\"right\">-" + (cartData.discount + "").replace(/\./g, ",") + " €</td></tr>");//.hide().fadeIn();
			
			$("#cartTable2").find("tbody").append("<tr style='font-size:3px;'><td colspan='2'></td><td style='background-color:#cccccc;' colspan='4'></td></tr>");//.hide().fadeIn();
			$("#cartTable2").find("tbody").append("<tr><td colspan='2'></td><td colspan='3'>Zwischensumme:</td><td  align=\"right\">" + (cartData.subtotal3 + "").replace(/\./g, ",") + " €</td></tr>");//.hide().fadeIn();
			$("#cartTable2").find("tbody").append("<tr style='font-size:3px;'><td colspan='2'></td><td style='background-color:#cccccc;' colspan='4'></td></tr>");//.hide().fadeIn();
			
			$("#cartTable2").find("tbody").append("<tr><td colspan='2'></td><td colspan='3'>Mindermengenzuschlag:</td><td  align=\"right\">" + (cartData.addition + "").replace(/\./g, ",") + " €</td></tr>");//.hide().fadeIn();
			//$("#cartTable2").find("tbody").append("<tr><td colspan='5'>Zwischensumme:</td><td>" + cartData.subtotal4 + "<fggfdg/td></tr>").hide().fadeIn();
			$("#cartTable2").find("tbody").append("<tr><td colspan='2'></td><td colspan='3'>Versandkosten*:</td><td align=\"right\">" + (cartData.shipping + "").replace(/\./g, ",") + " €</td></tr>");//.hide().fadeIn();
			

			$("#cartTable2").find("tbody").append("<tr style='font-size:3px;'><td colspan='2'></td><td style='background-color:#cccccc;' colspan='4'></td></tr>");//.hide().fadeIn();
			$("#cartTable2").find("tbody").append("<tr><td colspan='2'></td><td colspan='3'><strong>Endsumme:</strong></td><td align=\"right\"><strong><nobr>" + (cartData.total + "").replace(/\./g, ",") + " €</nobr></strong></td></tr>");//.hide().fadeIn();
			
			if(parseFloat(cartData.mwst7)>0 || parseFloat(cartData.mwst19)>0)
			{
				$("#cartTable2").find("tbody").append("<tr style='font-size:3px;'><td colspan='2'></td><td style='background-color:#cccccc;' colspan='4'></td></tr>");//.hide().fadeIn();
			}
			
			if(parseFloat(cartData.mwst7)>0)
			{
				$("#cartTable2").find("tbody").append("<tr><td colspan='2'></td><td colspan='3'>zzgl. MwSt. 7%:</td><td align=\"right\">" + (cartData.mwst7 + "").replace(/\./g, ",") + " €</td></tr>");//.hide().fadeIn();
			}
			if(parseFloat(cartData.mwst19)>0)
			{
				$("#cartTable2").find("tbody").append("<tr><td colspan='2'></td><td colspan='3'>zzgl. MwSt. 19%:</td><td align=\"right\">" + (cartData.mwst19 + "").replace(/\./g, ",") + " €</td></tr>");//.hide().fadeIn();
			}
			
			if(parseFloat(cartData.mwst7)>0 || parseFloat(cartData.mwst19)>0)
			{
				$("#cartTable2").find("tbody").append("<tr style='font-size:3px;'><td colspan='2'></td><td style='background-color:#cccccc;' colspan='4'></td></tr>");//.hide().fadeIn();
				$("#cartTable2").find("tbody").append("<tr><td colspan='2'></td><td colspan='3'>Endsumme inkl. MwSt.</td><td align=\"right\"><nobr>" + new String((parseFloat(cartData.total)+parseFloat(cartData.mwst7)+parseFloat(cartData.mwst19)).toFixed(2)).replace(/\./g, ",") + " €</nobr></td></tr>");//.hide().fadeIn();
			}
			
			$('.foField').keypress(function(event) {
				  if (event.keyCode == '13') {
					  $(".refreshCartButton").click();//document.forms.shoppingCartForm.submit();
					  return false;
				   }
			});
			
			/*
			}
			else {
				checkoutLoaderOverlay.overlay().close();
				$(".checkoutBoxContent:first").html("<p><strong>Sie haben momentan noch keine Artikel im Warenkorb!</strong></p>");
			}
			*/
			updateCartBoxLeft();

		}
	}
	genearateCartTable();

	
	/* *******************************************************************
	 * refresh the cart
	 * *******************************************************************/
	$(".refreshCartButton").click(function() {
		//console.log("Updating cart data...");
		checkoutLoaderOverlay.overlay().load();
		$("#updateTrigger").val(1);
		$.post("/karlie/index.php?forward=services/updateCartAjaxService.php",
			$("#shoppingCartForm").serialize(),
			function(data) {
				data = jQuery.parseJSON(data);
				if(typeof data.errors === 'undefined' && typeof data.errors2 === 'undefined') {
					//console.log("Cart successfully updated.");
					cartData = data;
					$("#cartTable").find("tbody").empty();
					genearateCartTable();
					checkoutLoaderOverlay.overlay().close();
				}
				else {
					//console.log("Failure! Cart was NOT updated.");
					$(".checkoutLoader .loading").hide();
					if(typeof data.errors2 === 'undefined')
					{
						$(".checkoutLoader .msg").html('<ul class="messages"><li class="error-msg"><ul id="em"><li>Ein Fehler ist aufgetreten.</li><li>Bitte VE prüfen.</li></ul></li></ul>');
						
						$.each(data.errors,function(index,value){
							$("#item_"+index).addClass("error");
							$("#item_"+index).children("td").addClass("error");
							$("#item_"+index).find(".berr").html('<br/>'+value);
							$("#item_"+index).find(".berr").html('<br/>'+value);
						});
					}
					else
					{
						$.each(data.errors2,function(index,value){
							$(".checkoutLoader .msg").html('<ul class="messages"><li class="error-msg"><ul id="em"><li>Ein Fehler ist aufgetreten.</li><li>'+value+'</li></ul></li></ul>');
						});
					}					
					
					$("#foFieldAm").attr("value",1);
					$("#foFieldArt").attr("value","");
					
					$(".checkoutLoader .msg").append('<br /><div><input type="button" class="button cancel"  style="float: right;" value="Schließen"></div>').hide().fadeIn();
					$(".cancel").click(function(){
						checkoutLoaderOverlay.overlay().close();
						$(".checkoutLoader .msg").html('');
						$(".checkoutLoader .loading").show();
					});
				}
			}
		);
		return false;
	});

	
	/* *******************************************************************
	 * delete single cart items
	 * *******************************************************************/
	$(".checkoutContentBox").delegate(".deleteBasketItem", "click", function() {
		//console.log("Deleting item from the basket...");
		var row = $(this).parents("tr");
		var inp = row.find("input");
		var name = inp.attr("name");
		var val = 0;
		var data = {};
		data[name]=val;
		data['update']=1;

		checkoutLoaderOverlay.overlay().load();

		$.post("/karlie/index.php?forward=services/updateCartAjaxService.php",
			data,
			function(data) {
				if(data!="FAILD") {
					//console.log("Item successfully removed");
					cartData = jQuery.parseJSON(data);
					checkoutLoaderOverlay.overlay().close();
					row.fadeOut(300, function() { 
					    row.remove();
					});
					//alert(cartData);
					if(typeof cartData !== 'undefined') {
						if(typeof cartData.items === 'undefined') {
							//alert(data);
							//$(".checkoutBoxContent").html("<p><strong>Sie haben momentan noch keine Artikel im Warenkorb!</strong></p>").hide().fadeIn();
							$("#cartTable").find("tbody").empty();
							genearateCartTable();
						}
					}
				}
				else {
					//console.log("Failure! Item was NOT removed");
					$(".checkoutLoader .loading").hide();
					$(".checkoutLoader .msg").html('<ul class="messages"><li class="error-msg"><ul><li>Ein Fehler ist aufgetreten.</li></ul></li></ul>');
					$(".checkoutLoader .msg").append('<br /><div><input type="button" class="button cancel"  style="float: right;" value="Schließen"></div>').hide().fadeIn();
					$(".cancel").click(function(){
						checkoutLoaderOverlay.overlay().close();
						$(".checkoutLoader .msg").html('');
						$(".checkoutLoader .loading").show();
					});
				}
			}
		);
		return false;
	});

	
	/* *******************************************************************
	 * delete the whole cart
	 * *******************************************************************/
	$(".emptyCartButton").click(function() {
		//console.log("Deleting cart data...");
		checkoutLoaderOverlay.overlay().load();
		$("#updateTrigger").val(-1);
		$.post("/karlie/index.php?forward=services/updateCartAjaxService.php",
			$("#shoppingCartForm").serialize(),
			function(data) {
				if(data!="FAILD") {
					//console.log("Cart successfully deleted.");
					cartData = jQuery.parseJSON(data);
					checkoutLoaderOverlay.overlay().close();
					$("#cartTable").find("tbody").empty();
					genearateCartTable();
				}
				else {
					//console.log("Failure! Cart was NOT deleted.");
					$(".checkoutLoader .loading").hide();
					$(".checkoutLoader .msg").html('<ul class="messages"><li class="error-msg"><ul><li>Ein Fehler ist aufgetreten.</li></ul></li></ul>');
					$(".checkoutLoader .msg").append('<br /><div><input type="button" class="button cancel"  style="float: right;" value="Schließen"></div>').hide().fadeIn();
					$(".cancel").click(function(){
						checkoutLoaderOverlay.overlay().close();
						$(".checkoutLoader .msg").html('');
						$(".checkoutLoader .loading").show();
					});
				}
			}
		);
		return false;
	});
	

	/* *******************************************************************
	 * check some values and go to checkout step #2 
	 * *******************************************************************/
	$(".checkoutCartButton").click(function(){
		if(typeof cartData !== 'undefined')
		{
			if(cartData.subtotal1 >= cartConfigData.minBest)
			{
				$('LI.step1').removeClass('act');
				$('LI.step2').addClass('act');
				return true;
			}
			
			checkoutLoaderOverlay.overlay().load();
			$(".checkoutLoader .loading").hide();
			$(".checkoutLoader .msg").html('<ul class="messages"><li class="error-msg"><ul><li>Ihre Bestellung hat den Mindest- bestellwert von ' + cartConfigData.minBest + ' € noch nicht erreicht.</li></ul></li></ul>');
			$(".checkoutLoader .msg").append('<br /><div><input type="button" class="button cancel"  style="float: right;" value="Schließen"></div>').hide().fadeIn();
			$(".cancel").click(function(){
				checkoutLoaderOverlay.overlay().close();
				$(".checkoutLoader .msg").html('');
				$(".checkoutLoader .loading").show();
			});
			
			return false;
		}	
	});
	
	
	/* *******************************************************************
	 * confirm the terms and conditionns and submit the order
	 * *******************************************************************/
	
	$(".finnishCartButton").click(function() {
		var agbAccepted = document.forms.shoppingCartForm.agb.checked;

		if(agbAccepted)
		{
			document.forms.shoppingCartForm.submit();
		}
		else
		{
			checkoutLoaderOverlay.overlay().load();
			$(".checkoutLoader .loading").hide();
			$(".checkoutLoader .msg").html('<ul class="messages"><li class="error-msg"><ul><li>Sie müssen unsere AGB akzeptieren</li></ul></li></ul>');
			$(".checkoutLoader .msg").append('<br /><div><input type="button" class="button cancel"  style="float: right;" value="Schließen"></div>').hide().fadeIn();
			$(".cancel").click(function(){
				checkoutLoaderOverlay.overlay().close();
				$(".checkoutLoader .msg").html('');
				$(".checkoutLoader .loading").show();
			});
		}
		
		return false;
	});

	
	/* *******************************************************************
	 * set the checkout submenue according to the current step
	 * *******************************************************************/
	if(typeof step !== 'undefined') {
		if (step != 1) {
			$('LI.step1').removeClass('act');
			$('LI.step2').addClass('act');
		}
	}

	
	/* *******************************************************************
	 * checkout accordion
	 * *******************************************************************/
	$("#checkoutAccordion").tabs("#checkoutAccordion div.pane", {
		tabs: 'h2',
		effect: 'slide',
		initialIndex: null
	});
	

	/* *******************************************************************
	 * add to whishlist
	 * *******************************************************************/
	var addToWishlistLoaderOverlay = $(".addToWishlistLoader").overlay({
		left: 390,
		top: '40%',
		closeOnClick: false
	});

	var wishlistLoaderOverlay = $(".wishlistLoader").overlay({
		left: 390,
		top: '40%',
		closeOnClick: false
	});
	
	$(".addToWishlistTrigger").click(function() {
		
		//console.log("Adding item to the wishlist...");
		var name = $(this).attr("rel");
		var val = 1;
		var data = {};
		data[name]=val;

		addToWishlistLoaderOverlay.overlay().load();
		
		$.post("/karlie/index.php?forward=services/updateCartAjaxService.php&cart=" + wishListCart,
				data,
				function(data) {
				data = jQuery.parseJSON(data);
				if(typeof data.errors === 'undefined') {
						//console.log("Item successfully added.");
						$(".addToWishlistLoader .loading").hide();
						$(".addToWishlistLoader .msg").html('<ul class="messages"><li class="success-msg"><ul><li>Artikel wurde zur Wunschliste hinzugefügt.</li></ul></li></ul>');
						addToWishlistLoaderOverlay.delay(1200).overlay().close();
					}
					else {
						//console.log("Failure! Item was NOT added.");
						$(".addToWishlistLoader .loading").hide();
						$(".addToWishlistLoader .msg").html('<ul class="messages"><li class="error-msg"><ul><li>Ein Fehler ist aufgetreten.</li></ul></li></ul>');
						$(".addToWishlistLoader .msg").append('<br /><div><input type="button" class="button cancel"  style="float: right;" value="Schließen"></div>').hide().fadeIn();
						$(".cancel").click(function(){
							addToWishlistLoaderOverlay.overlay().close();
							$(".addToWishlistLoader .msg").html('');
							$(".addToWishlistLoader .loading").show();
						});
					}
				}
		);
		
		return false;
	});

	
	/* *******************************************************************
	 * generate the wishlist items table
	 * wishlistData is set directly in mainareaLeftWishlist.csi
	 * 
	 *	$cartArray['items'][$productId]['artnr'] = $articleID;
	 *	$cartArray['items'][$productId]['amount'] = $articleAmount;
	 *	$cartArray['items'][$productId]['price'] = $articlePrice;
	 *	$cartArray['items'][$productId]['vpe'] = $vpe;
	 *	$cartArray['items'][$productId]['sum'] = $artikelSumme;
	 *	$cartArray['items'][$productId]['eshopItemId'] = $eshopItemId;
	 * $cartArray['items'][$productId]['nameCropped'] = $artNameCropped;
	 *	$cartArray['items'][$productId]['name'] = $artName;
	 *	$cartArray['items'][$productId]['mwst'] = $articleMwst;
	 * $cartArray['items'][$productId]['image'] = $image;
	 *	$cartArray['items'][$productId]['detailUrl'] = $detailUrl;
	 * *******************************************************************/
	function genearateWishlistTable() {
		if(typeof wishlistData !== 'undefined') {
			if(typeof wishlistData.items !== 'undefined') {
				$.each(wishlistData.items, function(index,value){
					$("#wishlistTable").find("tbody").append(
						"<tr><td align=\"center\" valign=\"middle\"><img src=\"" + value.image + " alt=\"\" /></td><td>" + value.artnr + "</td><td><a href=\"" + value.detailUrl + "\">" + value.name + "</a></td><td>" + value.price + "</td><td align=\"center\" valign=\"middle\"><input size=\"4\" type=\"text\" name=\"items[" + value.eshopItemId + "]\" value=\"" +  value.amount + "\" /></td><td><img src=\"/karlie/templates/html/img/icons/delete.png\" width=\"14\" height=\"14\" alt=\"Loeschen\" class=\"deleteWishlistItem\" rel=\"items[" + value.eshopItemId + "]\" /></td></tr>"
					);//.hide().fadeIn();
				});
			}
			else {
				$(".wishlistTableContent").html("<p><strong>Sie haben momentan noch keine Artikel auf Ihrer Wunschliste!</strong></p>");
			}
		}
		else {
			$(".wishlistTableContent").html("<p><strong>Sie haben momentan noch keine Artikel auf Ihrer Wunschliste!</strong></p>");
		}
	}
	genearateWishlistTable();

	
	/* *******************************************************************
	 * refresh wishlist
	 * *******************************************************************/
	$(".refreshWishlistButton").click(function() {
		//console.log("Updating wishlist data...");
		wishlistLoaderOverlay.overlay().load();
		$("#updateTrigger").val(1);
		$.post("/karlie/index.php?forward=services/updateCartAjaxService.php&cart=" + wishListCart,
			$("#wishlistForm").serialize(),
			function(data) {
				data = jQuery.parseJSON(data);
				if(typeof data.errors === 'undefined') {
					//console.log("Cart successfully updated.");
					wishlistData = data;
					$("#wishlistTable").find("tbody").empty();
					genearateWishlistTable();
					wishlistLoaderOverlay.overlay().close();
				}
				else {
					//console.log("Failure! Cart was NOT updated.");
					$(".wishlistLoader .loading").hide();
					$(".wishlistLoader .msg").html('<ul class="messages"><li class="error-msg"><ul><li>Ein Fehler ist aufgetreten.</li></ul></li></ul>');
					$(".wishlistLoader .msg").append('<br /><div><input type="button" class="button cancel"  style="float: right;" value="Schließen"></div>').hide().fadeIn();
					$(".cancel").click(function(){
						wishlistLoaderOverlay.overlay().close();
						$(".wishlistLoader .msg").html('');
						$(".wishlistLoader .loading").show();
					});
				}
			}
		);
		return false;
	});

	
	/* *******************************************************************
	 * delete single wishlist items
	 * *******************************************************************/
	$(".wishlistContentBox").delegate(".deleteWishlistItem", "click", function() {
		//console.log("Deleting item from wishlist...");
		var row = $(this).parents("tr");
		var name = $(this).attr("rel");
		var val = 0;
		var data = {};
		data[name]=val;
		data['update']=1;

		wishlistLoaderOverlay.overlay().load();

		$.post("/karlie/index.php?forward=services/updateCartAjaxService.php&cart=" + wishListCart,
			data,
			function(data) {
				data = jQuery.parseJSON(data);
				if(typeof data.errors === 'undefined') {
					//console.log("Item successfully removed");
					wishlistData = data;
					wishlistLoaderOverlay.overlay().close();
					row.fadeOut(300, function() { 
					    row.remove();
					});
					//alert(cartData);
					if(typeof wishlistData !== 'undefined') {
						if(typeof wishlistData.items === 'undefined') {
							$(".wishlistBoxContent").html("<p><strong>Sie haben momentan noch keine Artikel auf Ihrer Wunschliste!</strong></p>").hide().fadeIn();
							$("#wishlistTable").find("tbody").empty();
							genearateWishlistTable();
						}
					}
				}
				else {
					//console.log("Failure! Item was NOT removed");
					$(".wishlistLoader .loading").hide();
					$(".wishlistLoader .msg").html('<ul class="messages"><li class="error-msg"><ul><li>Ein Fehler ist aufgetreten.</li></ul></li></ul>');
					$(".wishlistLoader .msg").append('<br /><div><input type="button" class="button cancel"  style="float: right;" value="Schließen"></div>').hide().fadeIn();
					$(".cancel").click(function(){
						wishlistLoaderOverlay.overlay().close();
						$(".wishlistLoader .msg").html('');
						$(".wishlistLoader .loading").show();
					});
				}
			}
		);
		return false;
	});

	
	/* *******************************************************************
	 * delete the whole wishlist
	 * *******************************************************************/
	$(".emptyWishlistButton").click(function() {
		//console.log("Deleting wishlist...");
		wishlistLoaderOverlay.overlay().load();
		$("#updateTrigger").val(-1);
		$.post("/karlie/index.php?forward=services/updateCartAjaxService.php&cart=" + wishListCart,
			$("#wishlistForm").serialize(),
			function(data) {
				data = jQuery.parseJSON(data);
				if(typeof data.errors === 'undefined') {
					//console.log("Wishlist successfully deleted.");
					wishlistData = data;
					wishlistLoaderOverlay.overlay().close();
					$("#wishlistTable").find("tbody").empty();
					genearateWishlistTable();
				}
				else {
					//console.log("Failure! Wishlist was NOT deleted.");
					$(".wishlistLoader .loading").hide();
					$(".wishlistLoader .msg").html('<ul class="messages"><li class="error-msg"><ul><li>Ein Fehler ist aufgetreten.</li></ul></li></ul>');
					$(".wishlistLoader .msg").append('<br /><div><input type="button" class="button cancel"  style="float: right;" value="Schließen"></div>').hide().fadeIn();
					$(".cancel").click(function(){
						wishlistLoaderOverlay.overlay().close();
						$(".wishlistLoader .msg").html('');
						$(".wishlistLoader .loading").show();
					});
				}
			}
		);
		return false;
	});

	
	/* *******************************************************************
	 * add to watchlist
	 * *******************************************************************/
	var addToWatchlistLoaderOverlay = $(".addToWatchlistLoader").overlay({
		left: 390,
		top: '40%',
		closeOnClick: false
	});

	var watchlistLoaderOverlay = $(".watchlistLoader").overlay({
		left: 390,
		top: '40%',
		closeOnClick: false
	});
	
	$(".addToWatchlistTrigger").click(function() {
		
		//console.log("Adding item to the watchlist...");
		var name = $(this).attr("rel");
		var val = 1;
		var data = {};
		data[name]=val;

		addToWatchlistLoaderOverlay.overlay().load();
		
		$.post("/karlie/index.php?forward=services/updateCartAjaxService.php&cart=" + wishListCart,
				data,
				function(data) {
					data = jQuery.parseJSON(data);
					if(typeof data.errors === 'undefined') {
						//console.log("Item successfully added.");
						$(".addToWatchlistLoader .loading").hide();
						$(".addToWatchlistLoader .msg").html('<ul class="messages"><li class="success-msg"><ul><li>Artikel wurde zur Merkliste hinzugefügt.</li></ul></li></ul>');
						addToWatchlistLoaderOverlay.delay(1200).overlay().close();
					}
					else {
						//console.log("Failure! Item was NOT added.");
						$(".addToWatchlistLoader .loading").hide();
						$(".addToWatchlistLoader .msg").html('<ul class="messages"><li class="error-msg"><ul><li>Ein Fehler ist aufgetreten.</li></ul></li></ul>');
						$(".addToWatchlistLoader .msg").append('<br /><div><input type="button" class="button cancel"  style="float: right;" value="Schließen"></div>').hide().fadeIn();
						$(".cancel").click(function(){
							addToWatchlistLoaderOverlay.overlay().close();
							$(".addToWatchlistLoader .msg").html('');
							$(".addToWatchlistLoader .loading").show();
						});
					}
				}
		);
		
		return false;
	});

	
	/* *******************************************************************
	 * generate the watchlist items table
	 * watchlistData is set directly in mainareaLeftCheckout.csi
	 * 
	 *	$cartArray['items'][$productId]['artnr'] = $articleID;
	 *	$cartArray['items'][$productId]['amount'] = $articleAmount;
	 *	$cartArray['items'][$productId]['price'] = $articlePrice;
	 *	$cartArray['items'][$productId]['vpe'] = $vpe;
	 *	$cartArray['items'][$productId]['sum'] = $artikelSumme;
	 *	$cartArray['items'][$productId]['eshopItemId'] = $eshopItemId;
	 * $cartArray['items'][$productId]['nameCropped'] = $artNameCropped;
	 *	$cartArray['items'][$productId]['name'] = $artName;
	 *	$cartArray['items'][$productId]['mwst'] = $articleMwst;
	 * $cartArray['items'][$productId]['image'] = $image;
	 *	$cartArray['items'][$productId]['detailUrl'] = $detailUrl;
	 * *******************************************************************/
	function genearateWatchlistTable() {
		if(typeof watchlistData !== 'undefined') {
			if(typeof watchlistData.items !== 'undefined') {
				$.each(watchlistData.items, function(index,value){
					$("#watchlistTable").find("tbody").append(
						"<tr><td><a href=\"" + value.detailUrl + "\">" + value.nameCropped + "</a></td><td valign=\"middle\"><input type=\"checkbox\" name=\"items[" + index + "]\" value=\"" +  value.minAmount + "\" /></td><td valign=\"middle\"><img src=\"/karlie/templates/html/img/icons/delete.png\" width=\"14\" height=\"14\" alt=\"Loeschen\" class=\"deleteWatchlistItem\" rel=\"items[" + value.eshopItemId + "]\" /></td></tr>"
					);//.hide().fadeIn();
				});
			}
			else {
				$(".watchlistContent").html("<p><strong>Ihre Merkliste ist leer.</strong></p>");
			}
		}
		else {
			$(".watchlistContent").html("<p><strong>Ihre Merkliste ist leer.</strong></p>");
		}
	}
	genearateWatchlistTable();

	
	/* *******************************************************************
	 * delete single watchlist items
	 * *******************************************************************/
	$(".watchlistContent").delegate(".deleteWatchlistItem", "click", function() {
		//console.log("Deleting item from watchlist...");
		var row = $(this).parents("tr");
		var name = $(this).attr("rel");
		var val = 0;
		var data = {};
		data[name]=val;
		data['update']=1;

		watchlistLoaderOverlay.overlay().load();

		$.post("/karlie/index.php?forward=services/updateCartAjaxService.php&cart=" + wishListCart,
			data,
			function(data) {
				data = jQuery.parseJSON(data);
				if(typeof data.errors === 'undefined') {
					//console.log("Item successfully removed");
					watchlistData = data;
					watchlistLoaderOverlay.overlay().close();
					row.fadeOut(300, function() { 
					    row.remove();
					});
					//alert(cartData);
					if(typeof watchlistData !== 'undefined') {
						if(typeof watchlistData.items === 'undefined') {
							$(".watchlistContent").html("<p><strong>Ihre Merkliste ist leer.</strong></p>").hide().fadeIn();
							$("#watchlistTable").find("tbody").empty();
							genearateWatchlistTable();
						}
					}
				}
				else {
					//console.log("Failure! Item was NOT removed");
					$(".watchlistLoader .loading").hide();
					$(".watchlistLoader .msg").html('<ul class="messages"><li class="error-msg"><ul><li>Ein Fehler ist aufgetreten.</li></ul></li></ul>');
					$(".watchlistLoader .msg").append('<br /><div><input type="button" class="button cancel"  style="float: right;" value="Schließen"></div>').hide().fadeIn();
					$(".cancel").click(function(){
						watchlistLoaderOverlay.overlay().close();
						$(".watchlistLoader .msg").html('');
						$(".watchlistLoader .loading").show();
					});
				}
			}
		);
		return false;
	});

	
	/* *******************************************************************
	 * add selected watchlist items to the basket
	 * *******************************************************************/
	$(".addWatchlistToCartButton").click(function() {
		
		//console.log("Adding selected item to the basket...");
		var data = {};
		$("#watchlistForm input[type=checkbox]").each(function() {
			if ($(this).attr('checked') == true) {
				var name = $(this).attr("name");
				var val = $(this).attr("value");
				data[name]=val;
			}
		});
		data['update']=0;
		
		watchlistLoaderOverlay.overlay().load();
		
		$.post("/karlie/index.php?forward=services/updateCartAjaxService.php",
				data,
				function(data) {
					data = jQuery.parseJSON(data);
					if(typeof data.errors === 'undefined') {
						//console.log("Item successfully added.");
						$(".watchlistLoader .loading").hide();
						$(".watchlistLoader .msg").html('<ul class="messages"><li class="success-msg"><ul><li>Artikel wurden zum Warenkorb hinzugefügt.</li></ul></li></ul>');
						watchlistLoaderOverlay.delay(1200).overlay().close();
						cartData = data;
						$("#cartTable").find("tbody").empty();
						genearateCartTable();
					}
					else {
						//console.log("Failure! Item was NOT added.");
						$(".watchlistLoader .loading").hide();
						$(".watchlistLoader .msg").html('<ul class="messages"><li class="error-msg"><ul><li>Ein Fehler ist aufgetreten.</li></ul></li></ul>');
						$(".watchlistLoader .msg").append('<br /><div><input type="button" class="button cancel"  style="float: right;" value="Schließen"></div>').hide().fadeIn();
						$(".cancel").click(function(){
							watchlistLoaderOverlay.overlay().close();
							$(".watchlistLoader .msg").html('');
							$(".watchlistLoader .loading").show();
						});
					}
				}
		);
		
		return false;
	});


	/* *******************************************************************
	 * generate the lastorder items table
	 * lastOrderData is set directly in mainareaLeftCheckout.csi
	 * *******************************************************************/
	function genearateLastOrderTable() {
		if(typeof lastOrderData !== 'undefined') {
			if(typeof lastOrderData.items !== 'undefined') {
				$.each(lastOrderData.items, function(index,value){
					$("#lastOrderTable").find("tbody").append(
						"<tr><td><a href=\"" + value.detailUrl + "\">" + value.nameCropped + "</a></td><td><input type=\"checkbox\" name=\"items[" + index + "]\" value=\"" +  value.amount + "\" /></td><td></td></tr>"
					).hide().fadeIn();
				});
			}
			else {
				$(".lastOrderContent").html("<p><strong>Ihre Merkliste ist leer.</strong></p>");
			}
		}
		else {
			$(".lastOrderContent").html("<p><strong>Ihre Merkliste ist leer.</strong></p>");
		}
	}
	genearateLastOrderTable();
	
	
	/* *******************************************************************
	 * add selected last order items to the basket
	 * *******************************************************************/
	var lastOrderLoaderOverlay = $(".lastOrderLoader").overlay({
		left: 390,
		top: '40%',
		closeOnClick: false
	});
	$(".addLastOrderToCartButton").click(function() {
		
		//console.log("Adding selected item to the basket...");
		var data = {};
		$("#lastOrderForm input[type=checkbox]").each(function() {
			if ($(this).attr('checked') == true) {
				var name = $(this).attr("name");
				var val = $(this).attr("value");
				data[name]=val;
			}
		});
		data['update']=0;
		
		lastOrderLoaderOverlay.overlay().load();
		
		$.post("/karlie/index.php?forward=services/updateCartAjaxService.php",
				data,
				function(data) {
					data = jQuery.parseJSON(data);
					if(typeof data.errors === 'undefined') {
						//console.log("Item successfully added.");
						$(".lastOrderLoader .loading").hide();
						$(".lastOrderLoader .msg").html('<ul class="messages"><li class="success-msg"><ul><li>Artikel wurden zum Warenkorb hinzugefügt.</li></ul></li></ul>');
						lastOrderLoaderOverlay.delay(1200).overlay().close();
						cartData = data;
						$("#cartTable").find("tbody").empty();
						genearateCartTable();
					}
					else {
						//console.log("Failure! Item was NOT added.");
						$(".lastOrderLoader .loading").hide();
						$(".lastOrderLoader .msg").html('<ul class="messages"><li class="error-msg"><ul><li>Ein Fehler ist aufgetreten.</li></ul></li></ul>');
						$(".lastOrderLoader .msg").append('<br /><div><input type="button" class="button cancel"  style="float: right;" value="Schließen"></div>').hide().fadeIn();
						$(".cancel").click(function(){
							lastOrderLoaderOverlay.overlay().close();
							$(".lastOrderLoader .msg").html('');
							$(".lastOrderLoader .loading").show();
						});
					}
				}
		);
		
		return false;
	});	
	

	/* *******************************************************************
	 * trader register form
	 * *******************************************************************/
	
	$(".traderRegisterFormSubmit").click(function () {
		$("#traderRegisterForm").submit();
	});
	
	if ($("#hasVariantDeliveryAddress").attr("checked")) {
		$("#variantDeliveryAddress").css({'display' : 'block'});
	}

	$("#hasVariantDeliveryAddress").click(function () {
		$("#variantDeliveryAddress").slideToggle();
	});

	if ($("#isExistingCustomer").attr("checked")) {
		$("#existingCustomer").css({'display' : 'block'});
	}

	$("#isExistingCustomer").click(function () {
		$("#existingCustomer").slideToggle();
	});

	
	/* *******************************************************************
	 * forgot password form
	 * *******************************************************************/
	
	$(".forgotPasswordFormSubmit").click(function () {
		$("#forgotPasswordForm").submit();
	});


	/* *******************************************************************
	 * my account form
	 * *******************************************************************/
	
	$(".myAccountFormSubmit").click(function () {
		$("#myAccountForm").submit();
	});
	
	
	/* *******************************************************************
	 * login form (on the login page)
	 * *******************************************************************/
	
	$(".loginFormSubmit").click(function () {
		$("#loginForm").submit();
	});
	
	
	/* *******************************************************************
	 * simpleshow videoplayer overlay
	 * *******************************************************************/
	if ($('#startSimpleShow').length > 0) {
		$(function() {
			
			// install flowplayer into flowplayer container
			var player = $f("player", requestURL+"/karlie/templates/html/flash/flowplayer/flowplayer-3.2.1.swf");
	
			// action to fire the overlay 
			$("#startSimpleShow[rel]").overlay({
					
				// when overlay is opened, load the player
				onLoad: function() {
					player.load();
				},
					
				// when overlay is closed, unload the player
				onClose: function() {
					player.unload();
				}
			});
		});
	}


});



/* *******************************************************************
 * update cart savings box
 * *******************************************************************/
function updateCartBoxLeft() {
	//var saving = (cartData.subtotal2 - cartData.subtotal3).toFixed(2);
	var saving = cartData.onlinediscount;
	$("#saving").html((saving+" €").replace(/\./g, ","));

	var divToFFG = (cartConfigData.frachtFrei - cartData.subtotalVK).toFixed(2);
	$("#divFFG").html((( divToFFG > 0 ? divToFFG : "0.00") + " €").replace(/\./g, ","));
	
	$("#vk").html( cartData.shipping.replace(/\./g, ",")  + " €");
	$("#mmz").html( cartData.addition.replace(/\./g, ",")  + " €");
}


/* *******************************************************************
 * clear/recall for input field values
 * *******************************************************************/
function clickclear(thisfield, defaulttext) {
	if (thisfield.value == defaulttext) {
		thisfield.value = "";
	}
}

function clickrecall(thisfield, defaulttext) {
	if (thisfield.value == "") {
		thisfield.value = defaulttext;
	}
}