/**
 * @author hmmh multimediahaus ag.
 */


/**
 * loader
 * Animiertes Icon für ein Ladevorgang
 * 
 * @param target {String} Selektion des Elementes, wo das Icon geladen werden soll
 * @param action {String} Steuerung der Aktion(hide o. show), die durchgeführt werden soll
 * @param yPos {int} Vertikale Ausrichtung des Icons (von unten)
 * @return
 */
var loader = $('<div class="ajaxloader"><img src="'+jswebroot+'/imagesOnline/main/ajax-loader2.gif" /></div>'); //.hide();
function ajaxLoader(target, action, yPos){
	if(action == "hide"){
		loader.hide();
	}else{		
		loader.css('bottom', yPos);		
		loader.appendTo(target);
		loader.show();
	}
}



/**
 * pSearchResults
 * Erstellung der Liste, der gefundenen Shops mit entsprechenden Informationen
 * 
 * @param allshops {Object} Gefundene Shops als Object
 * @param count {int} Anzahl
 */
var result = '';	
var allPShops =  '';
function pSearchResults(allshops, count){
	var switcher = 0;
	var result = '';
	var counter = count*2-2;
	$("#pResult").html('');
	if (allshops.errorCode != null ) {
		result += '<label class="error" style="color: #f00;">' + pshopErrorCodes[allshops.errorCode] + '</label>';
		$("#pResult").html(result);
	}else if(allshops.shopsfound == 0) {
		result += '<label class="error" style="color: #f00;">' + pshopErrorCodes['100'] + '</label>';
		$("#pResult").html(result);
	}else {
		//$("#pResult").html((allshops.shopsfound) + ' Paketshops gefunden');
		$.each(allshops.pshops, function(i, item){
			if (i == counter) {					
				result += '<li class="psid'+item.id+'">';
				result += '<input class="radio" id="paketShop'+i+'" type="radio" name="packStation" '+((i==0)? 'checked="checked"':'')+' />';
				result += '<label id="la-paketShop'+i+'" for="paketShop'+i+'">';
				result += '<span class="ps_id" style="display: none;">' + item.id + '</span>';
				result += '<span class="ps_name"><b>'+item.name+'</b></span><br />';
				result += '<span class="ps_name3">'+item.name3+'</span><br />';
				result += '<span class="ps_street">'+item.street+'</span> <span class="ps_street2"> '+item.street2+'</span><br />';
				result += '<span class="ps_zip">'+item.zip + '</span> <span class="ps_city">' + item.city + '</span><br />';
				result += 'Tel.:  <span class="ps_prefix">'+item.prefix+'</span> / <span class="ps_phone">'+ item.phone + '</span><br />';
				result += '<br />';
				result += '<b>&Ouml;ffnungszeiten</b><br />';
				$.each(item.opening, function(i, open){
					result += i + ':'+open + '<br />';
				});
				result += '</label>';
				result += '</li>';

				$(result).appendTo("#pResult");
				result = '';
				counter++;
				switcher++;
				//Anzahl der gefundenen Shops einstellen
				if (switcher == 30){
					$("#packSearchEngine .pageCounter .pc").html(pageCounter(switcher)); //pageCounter bauen
					return false;
				}
				
			}
		});
	}
}

// Fehlermeldungen für die Paketshopsuche
var pshopErrorCodes = {
	"100":"Zur angegebenen Adresse konnte leider kein PaketShop gefunden werden. Bitte prüfen Sie Ihre Angaben.",
	"101":"Bitte geben Sie mindestens eine Postleitzahl oder einen Ort an.",
	"102":"Zur angegebenen Adresse konnte leider kein PaketShop gefunden werden. Bitte prüfen Sie Ihre Angaben.",
	"103":"Der Dienst steht zur Zeit nicht zur Verfügung. "
}
		


/**
 * pageCounter
 * Erstellung von Pagination je nach Anzahl von Listenelementen
 * 
 * @param count{int} Anzahl von Listenelementen
 * @return {String} Pagination
*/ 
function pageCounter(count){
	var counterObj='';
	var rest = count%4; //rest
	var sites = (count <= 4 ? 1 : (count-rest)/4+((rest > 0) ? 1 : 0)); //seitenanzahl	
	counterObj +='Seite <span class="thisSite active">1</span> von <span class="untilSite">'+sites+'</span>';	
	if(count > 4){ //Pagination einblenden, nur wenn es mehr als 4 Listen-Elemente sind
		counterObj +='&nbsp;&nbsp;&nbsp;';
		counterObj +='<a class="previousSite" href="#">&laquo;</a>';
		for(var i=1; i<=sites; i++){
			if(i == 1)
				counterObj +='<a href="#" class="c'+ i + ' active"> 1 </a><span>|</span>';
			else if(i > 4)
				counterObj +='<a class="c'+ i + ' hideIt" href="#"> '+i+' </a><span class="hideIt">|</span>';
			else if(i == 4 || i == sites)
				counterObj +='<a href="#" class="c'+ i + '"> '+i+' </a><span  class="hideIt">|</span>';			
			else	
				counterObj +='<a href="#" class="c'+ i + '"> '+i+' </a><span>|</span>';
		}
		if(sites > 4){
			counterObj +='<a class="nextSite " href="#">&raquo;</a>';
		}
	}
	return counterObj; 
}



/**
 * nationalDaysAndSundays
 * Nationale Feiertage und Sonntage für Kalender
 * Die Feiertage werden im Array "natDays" festgehalten 
 * 
 * @param date Datum
 * @return de_day/sunday  Feiertag oder Sonntag
 */
//Diese Array serverseitig mit nicht auswählbaren Daten für den Wunschterminkalender bestücken (['monat', 'tag', "de"])
var natDays = [[1, 1, "de"], [4, 2, "de"], [4, 5, "de"], [5, 1, "de"], [5, 13, "de"], [5, 24, "de"], [6, 1, "de"],  [6, 11, "de"], [10, 3, "de"], [12, 25, "de"], [12, 26, "de"]];
function nationalDaysAndSundays(date) {  
    var day = date.getDay();
	for (i = 0; i < natDays.length; i++) {  
        if (date.getMonth() == natDays[i][0] - 1 && date.getDate() == natDays[i][1]) {  
			return [false, natDays[i][2] + "_day"];  
        }
    }
	return [(day > 0), (day==0)?'sunday':''];  
}

/**
 * leadingNull
 * Die ersten 9 Tage als zweistellige Zahl darstellen
 * 
 * @param value {int} Zahl(Tag 1-9)
 * @return {String} Zahlen 1-9 zweistellig als Sting 
 */
function leadingNull(value){
	return (parseInt(value)<10)?'0' + value:value;
}

function assumeDate(date){      
                $("#desiredTime input[name='hasDate']").val('true'); 
                $("#desiredTime input#pick_TempDesiredDeliveryDate_ID").val(date); 
                $("#desiredTime input#pick_DesiredDeliveryDate_ID").val(date);  
                $("#desiredTime input#pick_ShippingMethod_ID").val($(".pick_ShippingMethod_ID").text()); 
                $("#desiredTime input#pick_defaultDesiredDeliveryDate_ID").val(date);  
                $("#desiredTime input#pick_defaultShippingMethod_ID").val($(".pick_ShippingMethod_ID").text()); 
                $("#deliveryTime .timewrapper").ajaxSubmit({ 
                        beforeSubmit: function(){/*ajaxLoader("#", "show", "");*/}, 
                        type: 'POST', 
                        data: { TempDesiredDeliveryDate:date, LineItemID:desiredTime.LineItemID.value },
                        url: apart.getDeliveryTime, 
                        target: ".timewrapper", 
                        success: function(){ 
                                $("#econtainer").hide(); 
                                /*ajaxLoader("#", "hide", "");*/                                
                        } 
                });     
        } 


function fillHiddenFields(selector, ident){
	var id = $(selector).parent().attr('class').substring(4);
	var plic = ($("#"+ident+"_ProductLineItemsCount").val()>1)?'#inserted':'_top';


	$("#"+ident+"_ShippingAddress_ID").val($('.'+ident+'id' + id + ' .'+ident+'_id').text());		
	$("#"+ident+"_AddressShopId").val($('.'+ident+'id' + id + ' .'+ident+'_id').text());
	$("#"+ident+"_AddressID").val($('.'+ident+'id' + id + ' .'+ident+'_id').text());		
	$("#"+ident+"_defaultAddressID").val($('.'+ident+'id' + id + ' .'+ident+'_id').text());				
	
	$("#"+ident+"_AddressPage").val($('.'+ident+'id' + id + ' .'+ident+'_id').text());		
	$("#"+ident+"_LastName").val($('.'+ident+'id' + id + ' .'+ident+'_name').text());
	$("#"+ident+"_FirstName").val($('.'+ident+'id' + id + ' .'+ident+'_name3').text());
	$("#"+ident+"_Street").val($('.'+ident+'id' + id + ' .'+ident+'_street').text());
	$("#"+ident+"_Street2").val($('.'+ident+'id' + id + ' .'+ident+'_street2').text());
	$("#"+ident+"_City").val($('.'+ident+'id' + id + ' .'+ident+'_city').text());
	$("#"+ident+"_PostalCode").val($('.'+ident+'id' + id + ' .'+ident+'_zip').text());
	$("#"+ident+"_Region").val($('.'+ident+'id' + id + ' .'+ident+'_id').text());
	$("#"+ident+"_AddressName").val($('.'+ident+'id' + id + ' .'+ident+'_AddressName').text());
//	$("#"+ident+"_AddressName").val($('.'+ident+'id' + id + ' .'+ident+'_name').text()+'_'+$('.'+ident+'id' + id + ' .'+ident+'_name3').text());
	$("#"+ident+"_PhoneBusiness").val($('.'+ident+'id' + id + ' .'+ident+'_prefix').text());
	$("#"+ident+"_PhoneBusinessDirect").val($('.'+ident+'id' + id + ' .'+ident+'_phone').text());	
	$("#"+ident+"_ShopNo").val($('.'+ident+'id' + id + ' .'+ident+'_phone').text());		
	$("#"+ident+"_typecode").val($('.'+ident+'id' + id + ' .'+ident+'_typecode').text());		
// LieferServiceArt
	$("#"+ident+"_ShippingMethod_ID").val($('.'+ident+'id' + id + ' .'+ident+'_ShippingMethod_ID').text());		

}

function setFormAsActive(selector){
		if(!$(selector).hasClass("activeForm")){ 
			$(".activeForm").removeClass("activeForm");
			$(selector).addClass("activeForm");
		}
}

function fillHiddenFields24 () {

$("#24_ShippingMethod_ID").val($(".24_ShippingMethod_ID").text());
$("#24_DesiredDeliveryDate_ID").val($(".24_DesiredDeliveryDate_ID").text());
$("#24_DesiredDeliveryTime_ID").val($(".24_DesiredDeliveryTime_ID").text());
$("#24_defaultShippingMethod_ID").val($(".24_ShippingMethod_ID").text());
$("#24_defaultDesiredDeliveryDate_ID").val($(".24_DesiredDeliveryDate_ID").text());
//$("#24_defaultDesiredDeliveryTime_ID").val($(".24_DesiredDeliveryTime_ID").text());

}
function fillHiddenFieldsno () {

$("#no_ShippingMethod_ID").val($(".no_ShippingMethod_ID").text());
$("#no_DesiredDeliveryDate_ID").val($(".no_DesiredDeliveryDate_ID").text());
$("#no_DesiredDeliveryTime_ID").val($(".no_DesiredDeliveryTime_ID").text());
$("#no_defaultShippingMethod_ID").val($(".no_ShippingMethod_ID").text());
$("#no_defaultDesiredDeliveryDate_ID").val($(".no_defaultDesiredDeliveryDate_ID").text());
$("#no_defaultDesiredDeliveryTime_ID").val($(".no_defaultDesiredDeliveryTime_ID").text());

}

function fillOutfitHiddenField(activeArticle, product_ref){
	$("#ArticleRef_"+activeArticle).val(product_ref).text();		
}

function getOutfitInformation(counter, response){		
	apart.defaultSelector = ".0_"+counter;
	apart.newSelProd = "0_"+counter;
	activeProd = "0";
	apart.prodRef = counter;
	apart.activeProdCluster = counter;
	productArray[0].productCluster[counter].colorChanged = true;										
	dv.preCreateKAL(response);
}

function getOutfitInformationFallback(counter){		
	apart.defaultSelector = ".0_"+counter;
	apart.newSelProd = "0_"+counter;
	activeProd = "0";
	apart.prodRef = counter;
	apart.activeProdCluster = counter;
	productArray[0].productCluster[counter].colorChanged = true;										
	dv.saveFallbackLinkByProductRef(av.initial_article_selection.product_ref[apart.prodRef]);
}

var firstload = true;
function setOutfitMod(){
	var thisOutfit = $(".moreOutfits");
	if($(thisOutfit).hasClass("activeOutfit")){
		//Outfit Deaktivieren
			$(thisOutfit).removeClass("activeOutfit")
			apart.outfit = false;
			$(thisOutfit).text("GANZES OUTFIT KAUFEN >>");			
			$("#outfitSet").css("display", "none"); // "inline" as bugfix for IE6-bug called "double margin bug"
			$(".artikelInformation .checkBoxOutfit").css("display", "none");
			if($("#moreArtikel").length > 0)
				$("#moreArtikel").css("display", "inline");
			if($("#moreIdeas").length > 0)
				$("#moreIdeas").css("display", "inline");
			initDetailView(".0_0", "0_0");
	}else{
	//Outfit Aktivieren	
		apart.outfit = true;
		if(firstload == true){
			firstload = false;
			$.ajax({
	          type: "POST", 
	          url: window.location.protocol+"//" + window.location.host + av.initial_article_selection.KALServlet,
	          processData :false,
			  dataType :"xml",
			  timeout : 2000,
			  contentType :"application/xml; charset=UTF-8",
			  data: av.initial_article_selection.kalOutfit,
			  success: function(xml){		
				apart.OutfitCounter = 1;					
				getOutfitInformation(apart.OutfitCounter, xml);		
			  },
	          error: function() {
				  apart.OutfitCounter = 1;					
				  getOutfitInformationFallback(apart.OutfitCounter);
	          }
	        });	
			$("#outfitSet .subModulContent").css("display", "none");
			ajaxLoader("#outfitSet", "show", "-30px");
			$(".ajaxloader").append("<h1 style='left:-28px; position:relative; top:29px;'>Bitte warten ... </h1>");			
		}			
		if($("#moreArtikel").length > 0)		
			$("#moreArtikel").css("display", "none");
		if($("#moreIdeas").length > 0)
			$("#moreIdeas").css("display", "none");					
		$(thisOutfit).text("GANZES OUTFIT DEAKTIVIEREN >>");						
		$("#outfitSet").css("display", "inline"); // "inline" as bugfix for IE6-bug called "double margin bug"
		setOutfitBox(".0_0", "0_0");							
		$(thisOutfit).addClass("activeOutfit");		
	}
	setBasketButton();
}

function showOutfitAfterLoading(){
	ajaxLoader("#outfitSet", "hide", "0px");
	$("#outfitSet .subModulContent").css("display", "inline");
	$('#outfitSet .pane').jScrollPane({showArrows:true, scrollbarWidth:9, dragMaxHeight:15});
}