// de
$(document).ready(function(){         
	zoomPreload=false;	
	zoomImg = $("#grossbild").attr("src");	
	if(zoomImg) {
		lupImgAlba=zoomImg.replace("albamoda_formatK","formatz");
		lupImgHeine=zoomImg.replace("albamoda_formatK","format_hv_ea_1");
		zoomPreloadAlba = new Image();
		zoomPreloadAlba.src = lupImgAlba;
		zoomPreloadHeine = new Image();
		zoomPreloadHeine.src = lupImgHeine;
	}	
	mainNavigationLayer();   
    initUebersichten(); 
    initWarenkorb(); 
    initMeinKonto();         
    initMerkliste(); 
    initCanvass(); 
    initDetailview();
    initMasstabelle();
    initSuggestSearch();
    init();

});

function init()  {
    $(".logout").unbind("click");
    $(".contact-form").unbind("click");
    $(".catalog-order-form-container").unbind("click");
    $(".sendPassword").unbind("click");
    $(".clearDate, .gutschein").unbind("focus");			
    $(".clearDate").unbind("blur");		    
    $(".gutschein").unbind("blur");			
    $(".showTermsAndConditons").unbind("click");
    $(".showImpressum").unbind("click");
    $("#showParcelShopLayer").unbind("click");
    $("#parcelShopLayer .xclose").unbind("click");
    
    
	actZoomImg = $(".jcarousel-item-1 img").attr("label");	
	
	
    $(".logout").click(			
  		function() {
  			$.ajax({
  				type: "GET",
  				url: rcContextPath + "/ajax_viewLogout.html",
  				dataType: "html",
  				success: function(html){
  					if (html.length > 0) {
  						openShadowBox(640, 485, html, false);
  					}  				
  			    }
  			});
        }		
   	);

	$(".contact-form").click(			
		function() {
			preselectedOptionParam = '';
			if ($(this).attr('rel')!="") {
				preselectedOptionParam = "?preselect="+escape($(this).attr('rel'));
			}
			openContactFormInShadowBox(preselectedOptionParam);
		}		
	);
	
	$(".catalog-order-form-container").click(			
			function() {
				$("body").attr("class", "catalog_order");
				openCatalogOrderInShadowBox();
			}
	);


	

	$(".sendPassword").click(			
		function() {
			$.ajax({
				type: "GET",
				url: rcContextPath + "/ajax_sendPassword.html",
				dataType: "html",
				success: function(html){
					if (html.length > 0) {
						openShadowBox(640, 450, html, true);
					}  				
				}
			});
		}		
	);
	
    $(".showTermsAndConditons").click(			
      		function() {
      			openTermsAndConditonsInShadowBox();
            }		
       	);

    $(".showImpressum").click(			
      		function() {
      			openImpressumInShadowBox();
            }		
       	);

    $(".clearDate, .gutschein").focus (			
    		function() {
    			if ($(this).val() == 'TT.MM.JJJJ' || $(this).val().indexOf("itte")!=-1) {
    				$(this).val("");
    				
    			}
        }		            
  	);

    $(".clearDate").blur (			
    	function() {
    		$(this).val(splitBirthday($(this).val()));
    	}		            
  	);
    $(".gutschein").blur (			
        	function() {
        		$(this).val($(this).val().toUpperCase());
        	}		            
    );    
    
    $("#content_home .suchbox").selectText(0, 0);
    $("#content_home .suchbox").click(
    	function() {
    		clearSearchBox($(this));
    	}
    );
    $("#content_home .suchbox").keydown(
		function() {
			clearSearchBox($(this));
		}
    );
    
    $(".setFocus").focus();
    
    $("#showParcelShopLayer").click(
    	function() {
    		$("#parcelShopLayer").fadeIn("middle");
    	}
    );
    
    $("#parcelShopLayer .xclose").click(
		function() {            
            $("#parcelShopLayer").fadeOut("fast");
        }		            
	); 
    
    $("#searchParcelShop").submit(function () {
    	jQuery.ajax({
    		type: "POST",
    		url: rcContextPath + "/" + $("#postalcodeCity").val() + "/ajax_getparcelshops.html",
    		timeout: 5000,
    		error: function() {
    			console.log("Failed to submit");
    		},
    		success: handleResponseOfParcelShopForm
    	});
    	
    	return false;
    });


}

function handleResponseOfParcelShopForm(response) {
	$("#parcelShopLayer div.result").replaceWith(response);
	$("#parcelShopLayer div a.result").click( function() {
		$("#parcelShopLayer div a.result").removeClass("selected");
		$(this).addClass("selected");
		var rel = $(this).attr("rel");
		$("#parcelShopLayer div.description").hide();
		$("#parcelShopLayer div.description[rel="+ rel +"]").show().addClass("selected");
		$("#parcelShopLayer div.result p.bttn").show();
		
		$("#parcelShopLayer div.result p.bttn input").live('click', function() {
			var firstName = $("div.adresse #firstName").val();
		    var lastName = $("div.adresse  #lastName").val();
		    if ($("div.adresse #firstName").val() != "Paketshop") {
		    	$("div.adresse #additionalInformation").val("z.Hd.: " +	 firstName + " " + lastName);
		    }
		    applyAddress($("#parcelShopLayer div a.selected"));
			$("#parcelShopLayer").hide();
		});
		
		return false;
	});
}

function applyAddress(dataRow) {
	var salutation = dataRow.find(".salutation").text().toLowerCase();
	var firstname = dataRow.find("span.firstname").text();
	var lastname = dataRow.find("span.lastname").text();	
	var street = dataRow.find("span.street").text();
	var postalcode = dataRow.find("span.postalcode").text();		
	var city = dataRow.find("span.city").text();				

	$(".newAddress").attr("selected", "selected");
	$("div.adresse #firstName").val(firstname);
	$("div.adresse #lastName").val(lastname);
	$("div.adresse #streetName").val(street);

	
	var regExpHouseNumber = /([0-9].*)/i;
	var houseNumber = regExpHouseNumber.exec(street)[1]
	$("div.adresse #streetName").val(street.replace(houseNumber, ""));
	$("div.adresse #houseNumber").val(houseNumber);
	$("div.adresse #postalCode").val(postalcode);
	$("div.adresse #city").val(city);
	
	return false;
}



function openOrderConfirmationInShadowBox() {
	openIframeShadowBox(643, 1500, rcContextPath + "/ajax_viewOrderConfirm.html", true);
}

function openTermsAndConditonsInShadowBox() {
	openIframeShadowBox(640, 500, rcContextPath + "/_/page/shadowbox_agb/boxedService.html", true);
}

function openImpressumInShadowBox() {
	openIframeShadowBox(740, 500, rcContextPath + "/_/page/svc_impressum/boxedService.html", true);
}

function openContactFormInShadowBox(preselectedOptionParam) {
	preselectedOption = '';
	if (typeof(preselectedOptionParam) != "undefined" && preselectedOptionParam != '') {
		preselectedOption = preselectedOptionParam;
	}
	$.ajax({
		type: "GET",
		url: rcContextPath + "/ajax_contactForm.html" + preselectedOption,
		dataType: "html",
		success: function(html){
			if (html.length > 0) {
				openShadowBox(878, 458, html, true);
			}  				
		}
	});
}

function openCatalogOrderInShadowBox() {
	$.ajax({
		type: "GET",
		url: rcContextPath + "/ajax_catalogOrder.html",
		dataType: "html",
		success: function(html){
			if (html.length > 0) {
				openShadowBox(1000, 670, html, true);
			}  				
		}
	});
}

function weitereArtikel()  {

    for (var i = 0; i < 9; i++) {
        $(".direktbestellung_vorlage").clone().prependTo("#dbende");
        $(".direktbestellung_vorlage").each(function(i){
                if(i==1)  {
                    $(this).removeClass("direktbestellung_vorlage");
                    $(this).addClass("direktbestellung");
                }
           }
        );          		
    }
    $(".direktbestellung_vorlage").html("");
    $("input.artnr").each(function(i){
            $(this).attr( "id", "orderItems[" + i + "].orderNr" );
            $(this).attr( "name", "orderItems[" + i + "].orderNr" );
       }
    );          		
    $("input.menge").each(function(j){                
            $(this).attr( "id", "orderItems[" + j + "].amount" );
            $(this).attr( "name", "orderItems[" + j + "].amount" );
       }
    );          		
    $("input.groesse").each(function(k){
            $(this).attr( "id", "orderItems[" + k + "].size" );
            $(this).attr( "name", "orderItems[" + k + "].size" );
       }
    );     
    $("label.labelartnr").each(function(l){
          $(this).attr( "for", "orderItems[" + l + "].orderNr" );
    	} 
    );     
    $("label.labelmenge").each(function(m){
          $(this).attr( "for", "orderItems[" + m + "].amount" );
    	} 
    );     
    $("label.labelgroesse").each(function(n){
          $(this).attr( "for", "orderItems[" + n + "].size" );
    	} 
    );     
    $(".mehrartikel").html("");     		
    initWarenkorb();
};

function loeschenAbbrechen(obj)  {
    obj.parent().fadeOut("fast").empty();
    return false;
}

function loescheObjekt(obj)  {
	id = obj.parent().parent().attr("id");
    obj.parent().parent().fadeOut("fast").empty();
    $("."+id).fadeOut("fast").empty();
    return false;
}


function aendernAbbrechen(obj)  {
    obj.parent().parent().parent().parent().fadeOut("fast").empty();
    return false;
}

function loescheItem()  {
    document.deleteItem.submit();
}

function aendereItem()  {	
    if($("#selSize").val() != "0" && $("#selectPromoItem").val() != "0")  {            
    		document.changeItem.submit();
     } else {
        if($("#selectPromoItem").val() == "0") {
        	if($("#selectModel").length > 0) {
        		errorMessage("Bitte wählen Sie eine Ausführung!");
            } else {		
        		errorMessage("Bitte wählen Sie eine Farbe aus!");
            }    
        } else {   
            errorMessage("Bitte wählen Sie eine Größe aus!");
        }    
     }	
}

function loescheMerklistenItem(obj) {
	$.ajax({
		type: "POST",
		url: "ajax_deleteWatchListItem.html",
		data: "variationListItemIndex="+$("#toDelete").val(),
		dataType: "html",
		success: function(html){
			if (html.length > 0) {
				setTimeout(function(){$("#ml_metanavi").replaceWith(html)}, 1000);
			}
	    }
	});
	obj.parent().fadeOut("fast").empty();
	$("#mi_"+$("#toDelete").val()).fadeOut('slow', function(){$(this).remove()});
	decreaseWatchListDeleteIndex($("#toDelete").val())
//	setTimeout("$(this).parent().parent().remove();", 4000);
}

function mainNavigationLayer()  {

    $("#topnavi li.tnav > a").unbind("mouseover");			
    $("#topnavi li.tnav > a").unbind("mouseout");			
    $("#topnavi li.tnav div > a").unbind("mouseover");			
    $("#topnavi li.tnav div > a").unbind("mouseout");			
    $(".suchbox").unbind("focus");			

    $("#topnavi li.tnav > a, #channelnavi li.tnav > a").mouseover(			
		function() {
            $(this).parent("li.tnav").each(function(i){
                $(this).addClass("subnav_show");
            }
            );          		
        }		
	);

    $("#topnavi li.tnav > a, #channelnavi li.tnav > a").mouseout(			
		function() {
            $(this).parent("li.tnav").each(function(i){
                $(this).removeClass("subnav_show");
            }
            );          		
        }		
	);

    $("#topnavi li.tnav div > a, #channelnavi li.tnav div > a").mouseover(			
		function() {
            $(this).parent("div").each(function(i){
                $(this).addClass("subnav_show");
            }
            );          		
        }		
	);

    $("#topnavi li.tnav div > a, #channelnavi li.tnav div > a").mouseout(			
		function() {
            $(this).parent("div").each(function(i){
                $(this).removeClass("subnav_show");
            }
            );          		
        }		
	);
    
    $(".suchbox").not("#content_home .suchbox").focus(
    	function() {
    		clearSearchBox($(this));
    	}
	);
    
};

function clearSearchBox(fldObj) {
	query = $(fldObj).val();	
    if(query.indexOf("uchbegr") != -1) {
    	$(fldObj).val("");
    }
}

function initUebersichten()  {    
    
    $("#content div.bundle > a").unbind("mouseover");			
    $("#content div.bundle > a").unbind("mouseout");			
    $("#content div.marke").unbind("mouseover");			
    $("#content div.marke").unbind("mouseout");			
    $("#content div.imglayer").unbind("mouseover");			
    $("#content div.imglayer").unbind("mouseout");			
    $("#content div.sbild").unbind("mouseover");			
    $("#content div.sbild").unbind("mouseout");			

	$("#content div.bundle > a").mouseover(			
		function() {
		   $("div.bundle").each(function(i){
                $(this).addClass("zidown");               
                $(this).removeClass("ziup");               
           });   
		
           $(this).parent("div").each(function(i){
               $(this).addClass("imglayer_show");
                $(this).addClass("ziup");               
                $(this).removeClass("zidown");   
                if($(this).position().left > 500 ) 
                   $(this).addClass("imglayer_left");               
           });         		
		}		
	);

    $("#content div.bundle > a").mouseout(			
		function() {
            $(this).parent("div").each(function(i){
                $(this).removeClass("imglayer_show");
            }
            );          		
        }		
	);

    $("#content div.marke").mouseover(			
		function() {
            $(this).parent("div").each(function(i){
                $(this).addClass("imglayer_show");
                 $(this).addClass("ziup");               
                 $(this).removeClass("zidown");   
                 if($(this).position().left > 500 ) 
                    $(this).addClass("imglayer_left");               
            }
            );          		
            $(this).parent("div").siblings().each(function(i){
                 $(this).addClass("zidown");               
                 $(this).removeClass("ziup");               
            }
            );          		
        }		
	);

    $("#content div.marke").mouseout(			
		function() {
            $(this).parent("div").each(function(i){
                $(this).removeClass("imglayer_show");
            }
            );          		
        }		
	);
    
    $("#content div.imglayer").mouseover(			
		function() {
            $(this).parent("div").each(function(i){
                $(this).addClass("imglayer_show");
            }
            );          		
        }		            
	);

    $("#content div.imglayer").mouseout(			
		function() {
            $(this).parent("div").each(function(i){
                $(this).removeClass("imglayer_show");
            }
            );          		
        }		            
	);
    
    $("#content div.sbild").mouseover(			
		function() {
            $(this).addClass("show");
        }		            
	);

    $("#content div.sbild").mouseout(			
		function() {
            $(this).removeClass("show");
        }		            
	);
    
};

function initWarenkorb()  {
        
    /* Warenkorb */    
    $("#leftnavi .deliveryInfo").unbind("click");        
    $(".gesamtpreis > a").unbind("click");     
    $(".deleteLinkErrBox").unbind("click");
    $(".changeLinkErrBox").unbind("click");
    $(".basketChangeLink").unbind("click");			
    $(".checkoutChangeLink").unbind("click");			
    $(".checkDOForm").unbind("click");		
    $("#bestellcontent #lieferadresse").unbind("change");
    $("#bestellcontent .ssl, #meinkonto .ssl").unbind("click");    	
    $("input[name='paymentInfo']").unbind("click");    
    $("#kreditkarte #pininfo").unbind("mouseover");
    $("#kreditkarte #pininfo").unbind("mouseout");
	$(".termine .sel_lieferdatum").unbind("change");
    $("#bestellcontent .showInfo").unbind("mouseover");
    $("#bestellcontent .showInfo").unbind("mouseout");
    $("#bestellcontent .gutschein").unbind("focus");
    
    // workaround: IE6 does not show layer although width is set in css, so we set it again with jquery 
    $("#addMissingArticleSizeWrapper").css("width", "565px");
    
    
    if ($("div.kalBasket").length > 0) {
    	// KAL request
    	if (typeof(kalResponse) == 'undefined') {
	    	$.ajax({
				type: "POST",
				url: "/KAL/AvailabilityServlet",
				contentType: "application/xml; charset=UTF-8",
				data: kalRequest,
				dataType: "xml",
				success: function(data) {
	    			kalResponse = $(data);
	    		},
	    		complete: function() {
	    			updateBasketAvailabilityInformation();
	    		}
	    		
			});
    	}

    }

	
    $("#leftnavi .deliveryInfo, #meinkonto .deliveryInfo").click (  
		function() {            
			deliveryPopup(rcContextPath + "/viewDeliveryInfo.html");
		}		            
	);

    
    
    $(".gesamtpreis > a").click (			
		function() {            
            $(".delete").empty().fadeOut("fast");    
            $(".change").empty().fadeOut("fast");    
            param=$(this).parent().parent().attr("id").split("_");
            $("#toDelete").val(param[1]);
            var obj = $(this).parent().parent().children("div.delete");
            obj.html($(".delete_container").html());
            obj.fadeIn("fast");
        }		            
	);
    
    $(".deleteLinkErrBox").click (			
    	function() {            
            $(".delete").empty().fadeOut("fast");    
            $(".change").empty().fadeOut("fast");    
            param=$(this).parent().parent().parent().attr("id").split("_");
            $("#toDelete").val(param[1]);
            var obj = $(this).parent().parent().parent().children("div.delete");
            obj.html($(".delete_container").html());
            obj.fadeIn("fast");
        }		            
    );
    
    $(".changeLinkErrBox").click (			
    		function() {            
                $(".delete").empty().fadeOut("fast");     
                $(".change").empty().fadeOut("fast");     
                $(".artikel_container").removeClass("ziup");
                $(".artikel_container").addClass("zidown");
                var container = $(this).parent().parent().parent();
                container.removeClass("zidown");
                container.addClass("ziup");
                param=container.attr("id").split("_");
                var obj = $(this).parent().parent().parent().children("div.change");
                var target = $("#flowTargetUrl").html();
               
                obj.load("ajax_changeitem.html", {
                      lineItemId: param[1]
                    , targetUrl: target
                	}
                );
                obj.fadeIn("fast"); 
            }		                    
    );
    
    $(".basketChangeLink").click (			
		function() {            
            $(".delete").empty().fadeOut("fast");     
            $(".change").empty().fadeOut("fast");     
            $(".artikel_container").removeClass("ziup");
            $(".artikel_container").addClass("zidown");
            var container = $(this).parent().parent();
            container.removeClass("zidown");
            container.addClass("ziup");
            param=container.attr("id").split("_");
            var obj = $(this).parent().parent().children("div.change");
            obj.load("ajax_changeitem.html",
                {lineItemId: param[1]}, 
            	function(){initAvailabilityInformation()}
            );
            obj.fadeIn("fast"); 
        }		                    
	);
    
    
    $(".checkoutChangeLink").click (			
    		function() {            
                $(".delete").empty().fadeOut("fast");     
                $(".change").empty().fadeOut("fast");     
                $(".artikel_container").removeClass("ziup");
                $(".artikel_container").addClass("zidown");
                var container = $(this).parent().parent();
                container.removeClass("zidown");
                container.addClass("ziup");
                param=container.attr("id").split("_");
                var obj = $(this).parent().parent().children("div.change");
                var target = $("#flowTargetUrl").html();
               
                obj.load("ajax_changeitem.html", {
                      lineItemId: param[1]
                    , targetUrl: target
                	}
                );
                obj.fadeIn("fast"); 
            }		                    
    );
    
    
        
    
    $(".checkDOForm").click (		
        function() {            
    		var error_text = "Bitte geben Sie eine gültige 7 oder  8-stellige Bestellnummer ein!";
            error = false;
            filled = false;
            clickAllowed=true;
            $('input.artnr').each(function(i, o){
                artnr= $(this).val().replace(" ","");
                $(this).val(artnr.toUpperCase()); 
               	if (artnr != "") {
			        if ( artnr.length < 7 ) {
                        $(this).css("border", "1px solid red");
	    				error = true;
    				} else {
    					if ( isNaN( artnr.substring(0,6)) == true ) {
	    					error = true;
                            $(this).css("border", "1px solid red");
                        } 
                        else   
                            $(this).css("border", "1px solid #a9a9a9");
					}
				filled = true;
    			}
            }
            );
            if(error)
                alert(error_text);
            else {
            	if (clickAllowed && filled)
				{
					clickAllowed = false;
		 			document.frmDirekt.submit();
					setTimeout("clickAllowed=true;",30000);
				}            
            }                    
        }		                    
	);

    
    
    $("#bestellcontent #lieferadresse").change (
		function() {         
            if($(this).val()!=-1)  {
                $.log($(this).val());   
				$("#insadressbuch").hide();
              	$(".adresse").load("ajax_getCustomerAddress.html", {
                    id: $($(this)).val()}
                );          
            } else {
				$("#insadressbuch").show();
            	$(".adresse").load("ajax_getCustomerAddress.html");          
			}    
        }      
	);           

    $("#bestellcontent .ssl, #meinkonto .ssl").click (
 		function() {         
            if($(this).is(":checked")) { 
     			url = $("form[name='login']").attr("action").replace(serverUrl,serverUrlSSL);
     			$("form[name='login']").attr("action",url);
 		    } else { 
     			url = $("form[name='login']").attr("action").replace(serverUrlSSL,serverUrl);
            	$("form[name='login']").attr("action",url);
            }   
        }   
   	);           
    
    $("input[name='paymentInfo']").click (
 		function() {     
            if($(this).val() == "CREDITCARD") {
                $("#kreditkarte").slideDown("slow");
                $(".kredittrenner").slideDown("slow");
            } else {
                $("#kreditkarte").slideUp("slow");
                $(".kredittrenner").slideUp("slow");
            }            
        }   
   	);            

    $("#kreditkarte #pininfo").mouseover (
 		function() {   
            $(".pininfo").fadeIn("fast");
        }   
   	);            

    $("#kreditkarte #pininfo").mouseout (
 		function() {     
            $(".pininfo").fadeOut("fast");
        }   
   	);            
  
    $(".termine .sel_lieferdatum").change (
    	function() {     
    		$("#radio_ontime").attr("checked","checked");
    		$.log($(this).val());
           	$(".termine .sel_lieferzeit").load("ajax_changedeliverytime.html", {
                date: $($(this)).val()}
            );                      
        }   
   	);            
    
    $("#bestellcontent .showInfo").mouseover (
 		function(e) {     
 			$("iframe.rateninfo").css("top", e.pageY + 20 + "px");
 			targetDiv = $(this).attr("rel");
 			$(targetDiv).css("top", e.pageY + 20 + "px");
 			$(targetDiv).fadeIn("fast");
 			$("iframe.rateninfo").fadeIn("fast");
        }   
   	);

    $("#bestellcontent .showInfo").mouseout (
 		function() {     
 			targetDiv = $(this).attr("rel");
 			$("iframe.rateninfo").fadeOut("fast");
 			$(targetDiv).fadeOut("fast");
        }   
   	);
    
};

function initMeinKonto()  {
	
	$("#kennwort a").unbind("click");
	$("#meinkonto .change").unbind("click");			
	$("#meinkonto .adresseSpeichern").unbind("click");			
	$("#meinkonto .adresseAendern").unbind("click");			
	$("#meinkonto .la_loeschen").unbind("click");			
	$("#meinkonto .loesche_adresse").unbind("click");			
	$("#meinkonto .showCancelOrder").unbind("click");			
	$("#meinkonto .cancelOrder").unbind("click");			
	$("#meinkonto .createPin").unbind("click");			
    		
	$("#kennwort a").click (			
		function() {
            $.log("Kennwort");            
            $(this).parent().hide();
            $("#kennwort_neu").show();
        }		            
	);
    
	$("#meinkonto .change").click (			
		function() {
			$("#addressForm").load("ajax_changeAddressBookAddress.html", {
                index: $(this).parent().attr("label")}			
            );
		}
	);

	$("#meinkonto .adresseSpeichern").click (			
			function() {
				$("#addressForm").submit();
			}		            
		);

	$("#meinkonto .adresseAendern").click (			
			function() {
				$("#customerForm").submit();
			}		            
		);

	$("#meinkonto .la_loeschen").click (			
			function() {
            $(".delete").empty().fadeOut("fast");    
            var obj = $(this).parent().children("div.delete");
            obj.html($(".delete_container").html());
            obj.fadeIn("fast");
            initMeinKonto();
   			}		            
		);
	
	
	$("#meinkonto .loesche_adresse").click (			
			function() {
				var obj = $(this); 
				$.ajax({
					type: "POST",
					url: "ajax_deleteAddressBookAddress.html",
					data: "index="+$(this).parent().parent().attr("label"),
					dataType: "html",
					success: function(html){
						$(".trenner_"+obj.parent().parent().attr("label")).remove();
						obj.parent().parent().fadeOut('slow');						
						setTimeout(obj.parent().parent().remove(), 2000);
						i=0;
						$(".lieferadresse").each(function(){
						    $(this).attr("label",i);
						    i+=1;
						});
						i=0;
						$(".tkurz").each(function(){
							$(this).removeClass("trenner_"+i);
						    $(this).removeClass("trenner_"+(i+1));
						    $(this).addClass("trenner_"+i);
						    i+=1;
						});
					}
				});
			}
		);	

	
    $("#meinkonto .showCancelOrder").click (	
		function() {
            $(".delete").empty().fadeOut("fast");    
            var obj = $(this).parent().parent().children("div.delete");
            $.log(obj);
            obj.html($(".delete_container").html());
            
            obj.fadeIn("fast");
            initMeinKonto();
   			}		            
		);
    		
    $("#meinkonto .cancelOrder").click (	
    		function() {
    	   		$.log("cancelOrder");
    	   		parts = $(this).parent().parent().attr("id").split("_");
    			$.ajax({
    				type: "POST",
    				url: "ajax_cancelOrder.html",
    				data: "orderId="+parts[0]+"&orderDetailId="+parts[1]+"&articelNumber="+parts[2],
    				dataType: "html",
    				success: function(html){
    					$(".delete").html(html);					
    			    }
    			});
    		}
    	);	

    $("#meinkonto .createPin").click (	
    		function() {
    	   		$.log("createPin");
    			$.ajax({
    				type: "POST",
    				url: rcContextPath + "/ajax_createPin.html",
    				dataType: "html",
    				success: function(html){
    					openShadowBox(450, 200, html, false);    			    }
    			});
    		}
    	);	
}

function showAddressChangeSb()   {
	html=$("#changedAddress").html();
	openShadowBox(440, 200, html, false); 
	setTimeout(function(){Shadowbox.close()}, 8000);
}


function initMerkliste()  {
	$("#ml_show_sendlayer").unbind("click");
	$("#kml_indenwk").unbind("click");
	$("#ml_print").unbind("click");
	$(".m_loeschen").unbind("click");			
    $(".m_basket").unbind("click");
    
    $("#ml_show_sendlayer").click(
        function(){
        	$("#send_container").load("ajax_sendWatchList.html");
        	$("#send_container").fadeIn("middle");
        }
    )
    
	$("#kml_indenwk").click(
			function() {
				$.ajax({
					type: "POST",
					url: "ajax_addCompleteWatchListToBasket.html",
					dataType: "html",
					success: function(html) {
						if (html.length > 0) {
							parts = html.split("<split/>");
							$("#indenwk").html(parts[0]);
							$("#indenwk").fadeIn("middle");                 
				            $('#indenwk').mouseleave(
			                	function() {
			                		$(this).fadeOut('slow');
			                });
							$("#ml_metanavi").replaceWith(parts[1]);
							$("#ml_items").fadeOut('slow');
							setTimeout(function(){$("#ml_items").remove();}, 2000);
						}
					}
				});            
			}
	)
	
	$("#ml_print").click(
		function() {
			printWatchListPopup("printWatchList.html");
		}
	)
	
    $(".m_loeschen").click (			
		function() {
            $(".delete").empty().fadeOut("fast");    
            $(".change").empty().fadeOut("fast");    
            parts = $(this).attr("id").split("_");
            $("#toDelete").val(parts[1]);
            var obj = $(this).parent().parent().children("div.delete");
            obj.html($(".delete_container").html());
            obj.fadeIn("fast");
        }		            
	);


    $(".m_basket").click (
		function() {
			params = $(this).attr("id").split("_");
        	$("#indenwk").load("ajax_addtobasket.html", {
                vid: params[1],
                variationListItemIndex: params[3],
                bid: $(this).attr("label").replace("indwk_","")}
            );            
            $("#indenwk").fadeIn("middle");                 
			//setTimeout("$('#indenwk').fadeOut('slow');",5000);
            $('#indenwk').mouseleave(
            	function() {
            		$(this).fadeOut('slow');
            });
			$.ajax({
				type: "POST",
				url: "ajax_deleteWatchListItem.html",
				data: "variationListItemIndex="+params[3],
				dataType: "html",
				success: function(html){
					if (html.length > 0) {
						setTimeout(function(){$("#ml_metanavi").replaceWith(html)}, 1000);
					}
			    }
			});
			$(this).parent().parent().fadeOut('middle', function(){$(this).remove()});
			decreaseWatchListDeleteIndex(params[3]);
        }		            
	);
    
}
function initCanvass()   {
    $("#fwQuickFillIn").unbind("click");
    $("#fwQuickFillIn").click(			
      		function() {
      			$.ajax({
      				type: "POST",
      				url: "ajax_viewCanvassLogin.html",      				
      					dataType: "html",
      					success: function(html){
      						openShadowBox(640, 385, html, false);	
      				    }
      				});
            }		
       	);
}    
function loginCanvass()   {
    if($('#fw_CustomerNumber').val().length > 5 && $('#fw_Birthday').val().length > 5) {
		$.ajax({
			type: "POST",
			url: "ajax_canvassLogin.html",
			data: "&customerNumber="+$('#fw_CustomerNumber').val()+"&birthday="+splitBirthday($('#fw_Birthday').val()),
				dataType: "html",
				success: function(html){
					$("#addressData").html(html);	
			    }
			});
    } else if ($('#fw_Email').val().length>5 && $('#fw_Password').val().length > 3) {
		$.ajax({
			type: "POST",
			url: "ajax_canvassLogin.html",
			data: "&email="+$('#fw_Email').val()+"&password="+$('#fw_Password').val(),
				dataType: "html",
				success: function(html){
					$("#addressData").html(html);	
			    }
			});
	} 
}
function showInvalidCanvass()   {
	html=$("#invalidCanvass").html();
	openShadowBox(440, 200, html, false);      		
}

function showCanvassLoginError()   {
	$("#shadowbox_content #canvLoginError").html($("#cError").html());	
}

function fillCanvassForm()   {
	if($("#cSalutation").html() == "Mr.")  {
		$("#herr").attr("checked","true");		
	} else {	
		$("#frau").attr("checked","true");
	}	
	$("input[name='firstName']").val($("#cName").html());
	$("input[name='lastName']").val($("#cLastName").html());
	$("input[name='streetName']").val($("#cStreetName").html());
	$("input[name='houseNumber']").val($("#cHouseNumber").html());
	$("input[name='postalCode']").val($("#cPostalCode").html());
	$("input[name='city']").val($("#cCity").html());
	$("input[name='email']").val($("#cEmail").html());
	$("input[name='additionalInformation']").val($("#cAddition").html());
	$("input[name='birthday']").val($("#cBirthday").html());
	$("input[name='phonePrefix']").val($("#cPhonePrefix").html());
	$("input[name='phoneNumber']").val($("#cPhoneNumber").html());
	
}

function decreaseWatchListDeleteIndex(deletedIndex) {
	$(".links a.m_basket").each(function(){
	    idParts = $(this).attr("id").split("_");
	    if (idParts[3] > deletedIndex) {
	    	idParts[3]--;
	    }
	    $(this).attr("id", idParts.join("_"));
	});

	$(".links a.m_loeschen").each(function(){
	    idParts = $(this).attr("id").split("_");
	    if (idParts[1] > deletedIndex) {
	    	idParts[1]--;
	    }
	    $(this).attr("id", idParts.join("_"));
	});
	
	$("#ml_items .artikel_container").each(function(){
	    idParts = $(this).attr("id").split("_");
	    if (idParts[1] > deletedIndex) {
	    	idParts[1]--;
	    }
	    $(this).attr("id", idParts.join("_"));
	});
}

function initSendWatchListFormLink() {
	$("#ml_send").unbind("click");
    $("#ml_send").click(
    	function() {
    		$("#progress_container").show();
    		$.ajax({
    			type: "POST",
    			url: "ajax_sendWatchList.html",
    			data: $("#sendWatchListForm").serialize(),
    			dataType: "html",
    			success: function(html) {
    				$("#send_container").html(html);
    				if (!$("div .error").text().length > 0) {
    					setTimeout("$('#send_container').fadeOut('middle');",3000);
    				}
    			},
    			complete: function() {
        			$("#progress_container").hide();
        		}
    		});
    	}
    )	
}

function initSendWatchListFormCancel() {
	$("#ml_send_cancel").unbind("click");
	$("#ml_send_cancel").click(
	    function() {
	    	$("#sendWatchListForm :input").val("");
	    	$("#sendWatchListForm textarea").val("");
	    	$("#send_container").fadeOut("middle");
	    	
	    }
	)
	
}

function initColorSelect()  {
    $(".change #selectPromoItem").unbind("change");   
	$(".change #selectModel").unbind("change");    

	$(".change #selectPromoItem").change (    
		function() {            
            $("#sizeSelect").load("ajax_changesizes.html", {
                pid: $(this).val(),
                size: $("#selSize :selected").text()},
                function(){initAvailabilityInformation()}
            );                              
        }	
    );	
  
	$(".change #selectModel").change (    
    		function() {  
                $.log($("#selectModel option:selected").attr("id").replace("p_",""));            
                changeImages($("#"+$("#selectModel option:selected").attr("id").replace("p_","")));     
                $(".change #selectPromoItem").load("ajax_changeBasketModels.html", {
                    pid: $(this).val(),
                    model: $("#selectPromoItem :selected").text()}
                );                              
            }	
     );
    
};

function initDetailview()  {
    $("#bilderContainer li > img").unbind("mouseover");
    $("#bilderContainer li > img").unbind("mouseout");	
    $("#bilderContainer li > img").unbind("click");	
    $("#grossbild").unbind("mouseover");
    $("#grossbild").unbind("mousemove");
    $("#grossbild").unbind("mouseleave");
    $("#grossbild").unbind("click");    
    $("#zoomicon").unbind("click");    
    $("#zoom").unbind("mouseover");
    $("#mehrtext").unbind("click");
    $("#infoLangMehr .xclose").unbind("click");
    $(".button_dv").unbind("click");
    $("#showSizeChart").unbind("click");
    $("#printArticleInformation").unbind("click");
    $("#merken").unbind("click");
    $("#recommend").unbind("click");
    $(".dictionary").unbind("click");
    $("#dictionary .xclose").unbind("click");
    $("#anzahl").unbind("blur"); 
    		
    $('#mycarousel').jcarousel({});
    $(".jcarousel-prev").html('<img src="'+rcContextPath+'/images/app/common/bttn/pfeil_links.jpg">');    
    $(".jcarousel-next").html('<img src="'+rcContextPath+'/images/app/common/bttn/pfeil_rechts.jpg">');
    $("#mycarousel").css('visibility','visible');    
    actImg = $("#grossbild").attr("src");
    actZoomImg = $("#grossbild").attr("label");
    zoomClicked = false;
    setSizeUpdateEvent();
    if ($("#detailview").length > 0) {
    	// recently viewed items list
    	addStyleToRecentlyViewedList($("#bid").val(), $("#sid").val());
    	
    	// KAL request
    	if (typeof(kalResponse) == 'undefined') {
	    	$.ajax({
				type: "POST",
				url: "/KAL/AvailabilityServlet",
				contentType: "application/xml; charset=UTF-8",
				data: kalRequest,
				dataType: "xml",
				success: function(data) {
	    			kalResponse = $(data);
	    		},
	    		complete: function() {
	    			if ($("#selSizeContainer").length > 0) {
	    				initAvailabilityInformation();
	    				showReducedPriceInfo();
	    			} else if ($("#singleSizeInput").length > 0) {
	    				initAvailabilityInformationForAccessiores();
	    			}
    				if ($("#p_"+promotItemExternalKey).length>0){	
    					if($("#selectModel option").size()>0) {
    						$("#selectModel").val($("#p_"+promotItemExternalKey).val());
    						$("#selectModel").change();	    					 
    					} else {
    						$("#selectPromoItem").val($("#p_"+promotItemExternalKey).val());
    						$("#selectPromoItem").change();
    					}
    				}	
    				$("#loadPic").fadeOut("slow");
	    		}
	    		
			});
    	}

    }
    
    $("#bilderContainer li > img").mouseover (	
		function() {            
            if($("#grossbild").height() > 402)
                $(".grossbild").css("height",$("#grossbild").height()+4+"px");
            cimg = $(this).attr("src").replace("formatP","formatK");            
            $("#grossbild").attr("src",cimg);                        
        }		            
	);    
        
    $("#bilderContainer li > img").mouseout (	
		function() {
            $("#grossbild").attr("src",actImg);
        }		            
	);    

    $("#bilderContainer li > img").click (	
		function() {
            changeImages($(this));
            if ($(this).attr("id")!="") {    
                if ($("#selectModel").length!="0")  {
                    $("#selectModel").val($("#p_"+$(this).attr("id")).val());
                    $("#selectModel").change();
                } else {
                    $("#selectPromoItem").val($("#p_"+$(this).attr("id")).val());
                    $("#selectPromoItem").change();
                }
            }    
        }		            
	);    

    $("#grossbild").click (
		function() {
			if ((zoomPreloadAlba.width != "0" || zoomPreloadHeine.width != "0" ) && !zoomClicked) {
	        	zoomImg = $("#grossbild").attr("src");	
	            if (zoomPreloadAlba.width > 0)  {
	            	lupImg=zoomImg.replace("albamoda_formatK","formatz");                
	            } else { 
	                lupImg = zoomImg.replace("albamoda_formatK","format_hv_ea_1");
	            }	
	            zoomPreload = new Image();
	            zoomPreload.src = lupImg;
	            $("#zoomPic").css("background-image","url("+lupImg+")");                
	            
				$("#zoom").fadeIn("middle");
                $("#selectModel").css("visibility","hidden");
                $("#selectPromoItem").css("visibility","hidden");
                $("#selSize").css("visibility","hidden");
                zoomClicked=true;
            } else {
                $("#zoom").hide();
                $("#selectModel").css("visibility","visible");
                $("#selectPromoItem").css("visibility","visible");
                $("#selSize").css("visibility","visible");                        	
                zoomClicked=false;
            }	
        }		            
	);    

    
    $("#grossbild").mousemove (
		function(e) {
            xpos = e.pageX - $(this).offset().left;                
            ypos = e.pageY - $(this).offset().top;
          if(zoomPreload) {
           	pic_width = zoomPreload.width;
           	pic_height = zoomPreload.height;
            orig_width = $(this).width();
            orig_height = $(this).height();
            
            xfaktor =  pic_width / orig_width;
            yfaktor =  pic_height / orig_height;
            xoff = 157/xfaktor;
            yoff = 157/yfaktor;
            if (xpos < xoff)
               xpos=0;
            else if (xpos > (orig_width - xoff)) 
               xpos = pic_width-315;
            else 
                xpos = ((xpos-xoff) * xfaktor);  

            if (ypos < yoff)
               ypos=0;
            else if (ypos > orig_height - yoff) 
               ypos = pic_height-315;
            else 
                ypos = ((ypos - yoff) * yfaktor);  
            $("#zoomPic").css("background-position", "-"+xpos+"px -"+ypos+"px");
          }  
        }		            
	);    

    $("#grossbild_cont").mouseleave (
		function() {            
            $("#zoom").hide();
            $("#selectModel").css("visibility","visible");
            $("#selectPromoItem").css("visibility","visible");
            $("#selSize").css("visibility","visible");       
            zoomClicked=false;
        }		            
	);    

    $("#zoomicon").click (
    		function() {                                   
                if(actZoomImg != "")
                	zoomPopup("zoomimage.html?zoomImg="+actZoomImg+"&bigImg="+actImg.replace("albamoda_formatK","formata"));
            }		            
    	);    
    
    $("#zoom").mouseover (
		function() {            
            $("#zoom").hide();
            $("#selectPromoItem").css("visibility","visible");
            $("#selSize").css("visibility","visible");            
        }		            
	);            
   
    $("#mehrtext").click (
		function() {         
			$(".longDescriptionContainer").html($("#infoLangText").html());
            $("#infoLangMehr").fadeIn("middle");
        }		            
	);    

    $("#infoLangMehr .xclose").click (
		function() {            
            $("#infoLangMehr").fadeOut("fast");
        }		            
	);    
    
    initButtonDv();
    
    $("#merken").click (
		function() {            
			if($("#selSize").val() != "0" && $("#selectPromoItem").val() != "0")  {            
				if($("#selectModel").val() != "0") {
					$("#aufdieml").load("ajax_addtowatchlist.html", {
						vid: $("#selSize").val(),
						bid: $("#bid").val()}
					);            
					$("#aufdieml").fadeIn("middle");                 
					// setTimeout("$('#aufdieml').fadeOut('slow');",5000);
				} else {
					errorMessage("Bitte wählen Sie eine Farbe aus!");            		
				}	
			} else {
				if($("#selectModel").val() == "0") {
					errorMessage("Bitte wählen Sie eine Farbe aus!");
				} else if($("#selectPromoItem").val() == "0") {
					if($("#selectModel").length > 0) 
						errorMessage("Bitte wählen Sie eine Ausführung!");
					else		
						errorMessage("Bitte wählen Sie eine Farbe aus!");
				} else {   
					errorMessage("Bitte wählen Sie eine Größe aus!");
				}    
			}
		}		            
    );
    
    $("#showSizeChart").click(
  		function() {
  			openIframeShadowBox(622, 700, rcContextPath + "/_/page/shadowbox_masstabelle/boxedService.html", true);
        }		
   	);
    
    $("#printArticleInformation").click(
    	function() {
    		promoItemKeyParameter = "";
    		if(typeof($('#selectPromoItem option:selected').attr('id')) != "undefined") {
    			promoItemKey = $('#selectPromoItem option:selected').attr('id').replace('p_','');
    			promoItemKeyParameter = "?promoItemKey=" + promoItemKey;
    		} else if(typeof($('#inputPromoItem').attr('title')) != "undefined") {
    			promoItemKey = $('#inputPromoItem').attr('title').substring(0, 6);
    			promoItemKeyParameter = "?promoItemKey=" + promoItemKey;
    		}
    		printArticleInformationPopup('printDetail.html' + promoItemKeyParameter); 
    	}
    );
    
    $("#recommend").click(
        function(){
        	params = $(this).attr("label").split("_");
        	$("#detailview #send_container").load("ajax_tellAFriend.html", "", function() {
    			$("#taf_bundleId").val(params[1]);
    			$("#taf_styleId").val(params[3]);
        	});
        	$("#detailview #send_container").fadeIn("middle");
        }
    );
    
    $(".dictionary").click(
    	function() {
    		params = $(this).attr("id").split("_");
    		$("#detailview #dictionary_container").load(rcContextPath + "/ajax_viewDictionaryTerm.html", 
    			{termId: params[1]},
    			function() {
    				$("#dictionary .xclose").click(
				    	function() {
				    		$("#dictionary_container").fadeOut("fast");
				    	}
    				);
    		});
    		$("#detailview #dictionary_container").fadeIn("middle");
    	}
    );
    
    
    $("#dictionary .xclose").click(
    	function() {
    		$("#dictionary_container").fadeOut("fast");
    	}
    );
    
    $("#anzahl").blur(
    	function(){
    		if (parseInt($(this).val()) > parseInt($(this).attr("rel"))) {
    			$(this).val($(this).attr("rel"));
    			errorMessage("Die Menge wurde korrigiert.");
    		}
	    }
	);
    
    initSurchargeInformation();
    
    $("#selectPromoItem").live("change", function() {
    	initSurchargeInformation();
    });
    
//    resizeRecommendationImageContainer();
}

function showReducedPriceInfo () {
	if ($("#selSize option").size() > 1 && (($("#selectPromoItem option").size() > 1 && $("#modelSelector #selectPromoItem option").size() == 0) || ($("#selectModel option").size() > 1))) {
	    $(".reducedPriceInfo").hide();  
	    $("#selSize option").each(function(){    
	    	price = $(this).text().split("EUR")[1];
	    	reducedPrice = $("#infoHead .red").text().split('EUR')[1];
	        if (reducedPrice && price && $("#infoHead .red").size() > 0 && price != reducedPrice ) {
	    		$(".reducedPriceInfo").show();    
	    	}
	    });
	}
}

function initSurchargeInformation() {
	if ($("#inputPromoItem").attr("alt") != undefined && $("#inputPromoItem").attr("alt").length > 0) {
		$("#surchargeInformationContainer #surchargeInformation").text($("#inputPromoItem").attr("alt"));
		$("#surchargeInformationContainer").show();
	} else if ($("#selectPromoItem option:selected").attr("alt") != undefined && $("#selectPromoItem option:selected").attr("alt").length > 0) {
		$("#surchargeInformationContainer #surchargeInformation").text($("#selectPromoItem option:selected").attr("alt"));
		$("#surchargeInformationContainer").show();
	} else {
		$("#surchargeInformationContainer").hide();
	}
}


function initButtonDv() {
    $(".button_dv").click (
		function() {            
            if($("#selSize").val() != "0" && $("#selectPromoItem").val() != "0")  {            
            	if($("#selectModel").val() != "0") {
	            	$("#indenwk").load("ajax_addtobasket.html", {
	                    vid: $("#selSize").val(),
	                    bid: $("#bid").val(),
	                    amount: $("#anzahl").val()}
	                );            
	                $("#indenwk").fadeIn("middle");                 
                    $(".button_dv").unbind("click");
                    setTimeout('initDetailview()',5000);
                    $('#indenwk').mouseleave(
                    	function() {
                    		$(this).fadeOut('slow');
                    });
            	} else {
                    $("#errMissing").html("Bitte wählen Sie eine Farbe aus!").fadeIn("fast");
                    //alert("Bitte wählen Sie eine Farbe aus!");            		
            	}	
            } else {
                if($("#selectModel").val() == "0") {
                	//alert("Bitte wählen Sie eine Farbe aus!");
                    errorMessage("Bitte wählen Sie eine Farbe aus!");
                } else if($("#selectPromoItem").val() == "0") {
                	if($("#selectModel").length > 0) {
                		//alert("Bitte wählen Sie eine Ausführung!");
                        errorMessage("Bitte wählen Sie eine Ausführung!");
                	} else {	
                		//alert("Bitte wählen Sie eine Farbe aus!");
                        errorMessage("Bitte wählen Sie eine Farbe aus!");                    
                    }    
                } else {   
                    //alert("Bitte wählen Sie eine Größe aus!");
                    errorMessage("Bitte wählen Sie eine Größe aus!");                    
                }    
            }
        }		            
	);

$(".button_fw").click (
		function() {            
            if($("#selSize").val() != "0" && $("#selectPromoItem").val() != "0")  {            
            	if($("#selectModel").val() != "0") {
	            	location.href="premium.html?vid="+$("#selSize").val()+"&bid="+$("#bid").val();
            	} else {
                    $("#errMissing").html("Bitte wählen Sie eine Farbe aus!").fadeIn("fast");
            	}	
            } else {
                if($("#selectModel").val() == "0") {
                    errorMessage("Bitte wählen Sie eine Farbe aus!");
                } else if($("#selectPromoItem").val() == "0") {
                	if($("#selectModel").length > 0) {
                        errorMessage("Bitte wählen Sie eine Ausführung!");
                	} else {	
                        errorMessage("Bitte wählen Sie eine Farbe aus!");                    
                    }    
                } else {   
                    errorMessage("Bitte wählen Sie eine Größe aus!");                    
                }    
            }
        }		            
	);
}


function initSuggestSearch() {
	$("#queryString").autocomplete("ajax_suggestSearch.html", {
		width: 260,
		minChars: 2,
		selectFirst: false
	});
}

function initTellAFriendFormLink() {
	$("#taf_send").unbind("click");
    $("#taf_send").click(
    	function() {
    		$("#progress_container").show();
    		$.ajax({
    			type: "POST",
    			url: "ajax_tellAFriend.html",
    			data: $("#tellAFriendForm").serialize(),
    			dataType: "html",
    			success: function(html) {
    				$("#send_container").html(html);
    			},
    			complete: function() {
        			$("#progress_container").hide();
        			if ($("#taf_success").text() != "") {
        				setTimeout("$('#detailview #send_container').fadeOut('middle');",3000);
        			}
        		}
    		});
    	}
    )	
}

function initTellAFriendFormCancel() {
	$("#taf_send_cancel").unbind("click");
	$("#taf_send_cancel").click(
	    function() {
	    	$("#tellAFriendForm :input").val("");
	    	$("#tellAFriendForm textarea").val("");
	    	$("#send_container").fadeOut("middle");
	    	
	    }
	)
}

function initMasstabelle() {
	$("a.messtechnik").click(
		function(e) {
			targetDiv = $(this).attr("rel");
			$(targetDiv).css("top", e.pageY + "px");
			$(targetDiv).show()
	});
}

function closeMesstechnik(targetDiv) {
	$("#"+targetDiv).hide();
}


function sendContactForm() {
	$("#progress_container").show();
	$.ajax({
		type: "POST",
		url: "ajax_contactForm.html",
		data: $("#contactForm").serialize(),
		dataType: "html",
		success: function(html) {
			$("#contact-form").replaceWith(html);
			if ($("#cf-success").length > 0) {
				setTimeout("Shadowbox.close();",3000);
			}
		},
		complete: function() {
			$("#progress_container").hide();
		}
	});
}

function sendCatalogOrderForm() {
	$("#progress_container").show();
	$.ajax({
		type: "POST",
		url: rcContextPath+"/ajax_catalogOrder.html",
		data: $("#catalog-order-form").serialize(),
		dataType: "html",
		success: function(html) {
		$("#catalog-order-form-container").replaceWith(html);
		if ($("#cof-success").length > 0) {
			setTimeout("Shadowbox.close();",3000);
		}
	},
	complete: function() {
		$("#progress_container").hide();
	}
	});
}

function sendPasswordRequest() {
	$("#progress_container").show();
	$.ajax({
		type: "POST",
		url: "ajax_sendPassword.html",
		data: $("#sendPasswordForm").serialize(),
		dataType: "html",
		success: function(html) {
			$("#sendPassword-form").replaceWith(html);
		},
		complete: function() {
			$("#progress_container").hide();
		}
	});
}


function addStyleToRecentlyViewedList(bid, sid) {
	if ("" != bid && "" != sid) {
		$.ajax({
			type: "POST",
			url: rcContextPath + "/ajax_addToRecentlyViewedList.html",
			data: "bid="+bid+"&sid="+sid
		});
	}
}


function errorMessage(msg)  {
    $("#errMissing").html(msg).fadeIn("fast");                    
    $("#ifr").fadeIn("fast");                    
    setTimeout("$('#errMissing').fadeOut('fast');",1000); 
    setTimeout("$('#ifr').fadeOut('fast');",1000); 
}


function setSizeUpdateEvent () {

    $("#infoSelects #selectPromoItem").unbind("change");    
    $("#infoSelects #selectModel").unbind("change");  
	$("#infoSelects .available_size").unbind("click");
	$("#infoSelects #selSize").unbind("change");
	$(".selectMissingSize").unbind("change");
	
	$("#infoSelects #selectPromoItem").change (    
		function() {  
            $.log($("#selectPromoItem option:selected").attr("id").replace("p_",""));            
            changeImages($("#"+$("#selectPromoItem option:selected").attr("id").replace("p_","")));
            $("#infoSelects #availabilityInformationContainer").hide();
            params = $("#selSize :selected").text().split(" ");
            $("#sizeSelector").load("ajax_changeDetailViewSizes.html", {
                pid: $(this).val(),
                size: params[0]},
                function() {
                	if ($("#selSizeContainer").length > 0) {
	    				initAvailabilityInformation();
	    				showReducedPriceInfo ();
	    			}
                	if ($("#singleSizeInput").length > 0) {
                		initAvailabilityInformationForAccessiores();
                	}
                }
            );
        }	
    );

	$("#infoSelects #selectModel").change (    
    		function() {  
                $.log($("#selectModel option:selected").attr("id").replace("p_",""));            
                if($("#selectModel option:selected").attr("id")!="") {
                	changeImages($("#"+$("#selectModel option:selected").attr("id").replace("p_",""))); 
                }
                params = $("#selSize :selected").text().split(" ");
                $("#modelSelector").load("ajax_changeDetailViewModels.html", {
                    pid: $(this).val(),
                    model: params[0]}
                ); 
            }	
     );
   
	
	$("#infoSelects #selSize").change(
		function() {
			$("option:disabled").css('color', '#aaa')
			
			// IE specific handling of disabled options
			if ($("#infoSelects #selSize option:selected").attr("class") == "disabled") {
				$("#infoSelects #selSize option:eq(0)").attr("selected", "selected");
			}
			
			deliveryStatement = $("#infoSelects #selSize option:selected").attr('alt');
			if (!isNaN(deliveryStatement)) {
				$("#infoSelects #availabilityInformationContainer #availabilityInformation").text(getKALAvailString(deliveryStatement));
				$("#infoSelects #availabilityInformationContainer").show();
			} else if($("#selSize").val() != 0) {
				$("#infoSelects #availabilityInformationContainer #availabilityInformation").text("lieferbar");
			} else {
				$("#infoSelects #availabilityInformationContainer").hide();
			}
		}
	);
	
	$(".selectMissingSize").change(
		function() {
			if ($(this).children("option:selected").attr("class") == "disabled") {
				$(this).children("option:eq(0)").attr("selected", "selected");
			}
		}
	);
	
	setSizeBoxClickEvent();
}

function initAvailabilityInformation() {
	var articleNumberWithPromoNumber;
	if ($("#selectPromoItem option:selected").length > 0) {
		articleNumberWithPromoNumber = $("#selectPromoItem option:selected").attr('title');
	} else if ($("#inputPromoItem").length > 0){
		articleNumberWithPromoNumber = $("#inputPromoItem").attr('title');
	}
	// disable options if article not available
	$("#selSize :options").each(function(i){
		// first entry has no value, begin with second
		if(parseInt($(this).attr('title')) > 0) {
			// reduce availability code from alt-tag by 100 to match deliveryDesignationCode
			fallbackAvailability = parseInt($(this).attr('alt') - 100);
			articleAvailability = getArticleAvailability(articleNumberWithPromoNumber, $(this).attr('title'), fallbackAvailability);
			switch(articleAvailability['deliveryDesignation']) {
				case '0':
					$(this).attr('alt', '101');
					break;
				case '1':
        			notAvailableMessage = $(this).text() + ' leider ausverkauft';
        			$(this).text(notAvailableMessage);
        			$(this).attr("disabled", "disabled");
        			$(this).attr("class", "disabled");
        			$(this).css("color", "#ccc");
        			if ($("#selSize option:selected").val() == $(this).val()) {
        				$("#selSize option:eq(0)").attr("selected", "selected");
        			}
        			break;
				case '2':
					$(this).attr('alt', articleAvailability['deliveryStatement'])
					break;
			}
		}
	});
	
	// set strike-through images for size boxes if article not available
	$("#infoSelects .available_size").each(function(i){
		// reduce availability code from alt-tag by 100 to match deliveryDesignationCode
		fallbackAvailability = $(this).attr('alt') - 100;
		articleAvailability = getArticleAvailability(articleNumberWithPromoNumber, $(this).attr('title'), fallbackAvailability);
		if(articleAvailability['deliveryDesignation'] == 1) {
			$(this).wrap('<i class="solditem"></i>');
			$(this).before('<img src="'+rcContextPath+'/images/app/common/bttn/sold.gif" width="19" height="15" alt="leider ausverkauft">');
			$(this).attr("class", "unavailable_size");
		}
	});
	
	// fit strike-through images to size box width
	$(".solditem").each(function(i){
        $(this).children("img").width($(this).children("span").width()+6);
       }
    );
	
	// set click event for size boxes
	setSizeBoxClickEvent();
	
	// display unavailability information if no variation is available
	if ($("#infoSelects .available_size").size() == 0 && $("#infoSelects .unavailable_size").size() > 0) {
		$("#selSizeContainer").replaceWith("<p>Dieser Artikel ist zur Zeit leider nicht lieferbar.</p>");
		$("#quantityContainer").hide();
		$(".button_dv").unbind("click");
		$("#infoSelects .button_dv_height").hide();
	} else {
		$("#quantityContainer").show();
		initButtonDv();
		$("#infoSelects .button_dv_height").show();
	}
}

function initAvailabilityInformationForAccessiores() {
	var articleNumberWithPromoNumber;
	if ($("#selectPromoItem option:selected").length > 0) {
		articleNumberWithPromoNumber = $("#selectPromoItem option:selected").attr('title');
	} else if ($("#inputPromoItem").length > 0){
		articleNumberWithPromoNumber = $("#inputPromoItem").attr('title');
	}
	
	fallbackAvailability = $("#selSize").attr('alt') - 100;
	articleAvailability = getArticleAvailability(articleNumberWithPromoNumber, 0, fallbackAvailability);
	
	if(typeof(articleAvailability['deliveryDesignation']) == "undefined" || articleAvailability['deliveryDesignation'] != 1) {
		// article available, maybe as subsequent delivery
		var availabilityCode;
		if (typeof(articleAvailability['deliveryStatement']) != 'undefined' && articleAvailability['deliveryStatement'] > 0) {
			availabilityCode = articleAvailability['deliveryStatement'];
		} else {
			availabilityCode = 101;
		}
		$("#infoSelects #availabilityInformationContainer #availabilityInformation").text(getKALAvailString(availabilityCode));
		$("#infoSelects #availabilityInformationContainer").show();
		$("#quantityContainer").show();
		initButtonDv();
		$("#infoSelects .button_dv_height").show();
	} else {
		// article not available
		$("#quantityContainer").hide();
		$(".button_dv").unbind("click");
		$("#infoSelects .button_dv_height").hide();
		$("#infoSelects #availabilityInformationContainer #availabilityInformation").text("Dieser Artikel ist zur Zeit leider nicht lieferbar.");
		$("#infoSelects #availabilityInformationContainer").show();
	}
	
}

function updateBasketAvailabilityInformation() {
	$("span.availabilityText").each(function() {
		parts = $(this).attr("id").split("_");
		articleNumberWithPromoNumber = parts[1];
		size = parts[2];
		articleAvailability = getArticleAvailability(articleNumberWithPromoNumber, size);

		var availabilityCode = 0;
		if(typeof(articleAvailability['deliveryDesignation']) == "undefined" || articleAvailability['deliveryDesignation'] != 1) {
			// article available, maybe as subsequent delivery
			if (typeof(articleAvailability['deliveryStatement']) != 'undefined' && articleAvailability['deliveryStatement'] > 0) {
				availabilityCode = articleAvailability['deliveryStatement'];
			} else {
				availabilityCode = 101;
			}
		} else if (articleAvailability['deliveryDesignation'] == 1) {
			availabilityCode = 100;
		}
		
		if (availabilityCode > 0) {
			$(this).text(getKALAvailString(availabilityCode));
		}
	});

	// disable options if article not available
	$(".selectMissingSize :options").each(function() {
		parts = $(this).parent().attr("rel").split("_");
		articleNumberWithPromoNumber = parts[1];
		if($(this).val()) {
			articleAvailability = getArticleAvailability(articleNumberWithPromoNumber, $(this).attr('rel'), 0);
			switch(articleAvailability['deliveryDesignation']) {
				case '1':
        			notAvailableMessage = $(this).text() + ' leider ausverkauft';
        			$(this).text(notAvailableMessage);
        			$(this).attr("disabled", "disabled");
        			$(this).attr("class", "disabled");
        			$(this).css("color", "#ccc");
        			if ($(this).parent().children("option :selected").val() == $(this).val()) {
        				$(this).parent().children("option :eq(0)").attr("selected", "selected");
        			}
        			break;
			}
		}
	});	
}

function setSizeBoxClickEvent() {
	$("#infoSelects .available_size").click (
    	function() {            
            $.log($(this).attr("label"));
            if ($(this).attr("label")!="") {    
                $("#selSize").val($(this).attr("label"));
                $("#selSize").change();
            }
        }		            
	);
}

function getArticleAvailability(articleNumberWithPromoNumber, size, fallbackAvailability) {
	var articleAvailability = new Array();
	if (typeof(kalResponse) != "undefined") {
		kalResponse.find('Article').each(function(i){
		    if ($(this).find('CompleteCatalogItemNo').text() == articleNumberWithPromoNumber &&
		        $(this).find('SizeAlphaText').text() == size) {
		    	articleAvailability['deliveryDesignation'] = $(this).find('DeliveryDesignation').text();
		    	articleAvailability['deliveryStatement'] = $(this).find('DeliveryStatement').text();
		    	articleAvailability['stock'] = $(this).find('Stock').text();
		    }
		});
	} else {
		fallbackAvailability = Math.abs(fallbackAvailability - 1);
		articleAvailability['deliveryDesignation'] = fallbackAvailability;
    	articleAvailability['deliveryStatement'] = 0;
    	articleAvailability['stock'] = (fallbackAvailability == 0) ? 1 : 0;
	}
	return articleAvailability;
}

function changeImages(obj)  {
      if(obj.attr("src")) {  
        actImg = obj.attr("src").replace("formatP","formatK");
        actZoomImg = obj.attr("label");
        $("#grossbild").attr("src",actImg);
        if (obj.attr("label")!="") 
            $("#grossbild").attr("label",obj.attr("label"));                
      }  
}

function copyInMinibasket()  {
        $("#tasche").html($("#intasche").html());        		
}  
  

function resizeRecommendationImageContainer() {
	maxImageHeight = 0;
	$("div.recommendationImageContainer img").each(function() {
		if ($(this).height() > maxImageHeight) {
			maxImageHeight = $(this).height();
		}
	});
	$("div.recommendationImageContainer").css("height", maxImageHeight + 5);
}

function showPaymentConditions()  {
	html = $("#agb").html();
	openShadowBox(500, 400, html, true);
}

function acceptPC() {
    if(!$("input[name='installmentTerms']").is(":checked")) {
    	$("input[name='installmentTerms']").attr("checked","true")	
    }
    Shadowbox.close();
}		            

function backPC() {
	$(".agb1").show();
	$(".agb2").hide();
}		            


function deniePC() {
	$(".agb1").hide();
	$(".agb2").show();
}		            

function closePC() {
    if($("input[name='installmentTerms']").is(":checked")) {
    	$("input[name='installmentTerms']").click();	
    }
    $(".invoice").click();
	$(".agb1").show();
	$(".agb2").hide();
    Shadowbox.close();
}		            

function checkPC() {
	if ($(".rates").is(":checked") && !$("input[name='installmentTerms']").is(":checked")) {
		showPaymentConditions();
	} else {
		document.services.submit();
	}	
}

function redirectToSearchEngine(redirectUrl, query) {
	redirectUrlWithQuery = redirectUrl + "&query=" + query;
	 
	if( navigator.appVersion.indexOf("MSIE")>-1 || document.location.replace) {
		document.location.replace(redirectUrlWithQuery);
	} else {
		document.location.href = redirectUrlWithQuery;
	}
}


function zoomPopup(dest)  { sizePopup(dest, 'zoom', '600', '580', '10', '400'); }
function printArticleInformationPopup(dest)  { sizePopup(dest, 'articleInformation', '650', '700', '10', '10'); }
function printWatchListPopup(dest)  { sizePopup(dest, 'watchlist', '600', '700', '10', '10'); }
function printAccountPopup(dest)  { sizePopup(dest, 'account', '610', '700', '10', '10'); }
function callbackPopup(dest) { fixedPopup(dest, 'callback', '540', '300', '370', '250'); }
function deliveryPopup(dest) { sizePopup(dest, 'delivery', '700', '450', '370', '250'); }
function companyPopup(dest) { sizePopup(dest, 'company', '1204', '768', '0', '0'); }

function sizePopup(url, name, w, h, t, l ) {
  popup(url, 'width='+w+',height='+h+',toolbar=0,menubar=0,resizable=1,scrollbars=1,status=1,left='+l+',top='+t+'', name );
}

function fixedPopup(url, name, w, h, t, l ) {
	popup(url, 'width='+w+',height='+h+',toolbar=0,menubar=0,resizable=0,scrollbars=0,status=0,left='+l+',top='+t+'', name );
}

// Popup-Basisfunktion
function popup(url, optionen, popupName){
  popupName = window.open(url,popupName,optionen);
  if (popupName){
    if (popupName.focus) popupName.focus();
  }
  return false;
}

//Shadowbox-Basisfunktion

function openShadowBox(boxWidth, boxHeight, content, modal) {
	Shadowbox.open({
      player: 'html',
      title: '',
      content: content,
      width: boxWidth,
      height: boxHeight
    }, {
    	animate:true,
    	overlayOpacity:0.3,
	    modal: modal,
	    enableKeys: false,
	    handleOversize: 'none'
    });
}

function openIframeShadowBox(boxWidth, boxHeight, content, modal) {
	Shadowbox.open({
      player: 'iframe',
      title: '',
      content: content,
      width: boxWidth,
      height: boxHeight
    }, {
    	animate:true,
    	overlayOpacity:0.3,
	    modal: modal,
	    enableKeys: false,
	    handleOversize: 'none'
    });
}

function printShadowbox()  {
    if (shadowbox_content) {
      shadowbox_content.print();
    }
}

function getKALAvailString(availno) {
    return(kal[availno]);	
}

function splitBirthday(formValue)
{
	var Satz = formValue;
	Satz = Satz.replace(/,/g,".");
	var Woerter = Satz.split(".");
	if(Woerter.length==3)
	{
		if(Woerter[0].length==1)
			Woerter[0]="0"+Woerter[0];
		if(Woerter[1].length==1)
			Woerter[1]="0"+Woerter[1];
		if(Woerter[2].length==2)
			Woerter[2]="19"+Woerter[2];
		formValue=Woerter[0]+"."+Woerter[1]+"."+Woerter[2];
	}else{
		if(Woerter.length==1 && Satz.length==8)
		{
			formValue=Satz.substr(0,2)+"."+Satz.substr(2,2)+"."+Satz.substr(4,4);
		}
		else if(Woerter.length==1 && Satz.length==6)
		{
			formValue=Satz.substr(0,2)+"."+Satz.substr(2,2)+".19"+Satz.substr(4,2);
		}
	}
return formValue;
}

function eraseCookie(name) {
	setCookie(name, "", -1);
}

function setCookie(name, value, expiresInDays) {
	var expires = "";	
	
	if (expiresInDays) {
		var date = new Date();
		date.setTime(date.getTime() + (expiresInDays * 24 * 60 * 60 * 1000));
		expires = "; expires=" + date.toGMTString();
	}	
	
	document.cookie = name + "=" + value + expires + "; path=/";
}

function getCookie(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;
}

