/* -------------------------------------------------------------------
	=Constants
 ------------------------------------------------------------------ */
var DIRECTIONUP = "up";
var DIRECTIONDOWN = "down";


var timeoutpager = null;
/*
 * ------------------------------------------------------------------- =Standard
 * Shop-Funktionen
 * ------------------------------------------------------------------
 */
function fieldUp (id, minVal) {
	updateField(id, DIRECTIONUP, minVal);
}
function fieldDown (id, minVal) {
	updateField(id, DIRECTIONDOWN, minVal);
}
function updateField(id,direction, minVal) {
	if (minVal == null || ( typeof(minVal) != "number" ) ) minVal = 1;

	var inputObj = $(id);
	var iVal = parseString(inputObj.value);
	if ( typeof(iVal)== "number" ) {
		if (direction == DIRECTIONUP) {
			inputObj.value = iVal+1;
		}
		else {
			if (iVal>minVal) inputObj.value = iVal-1;
		}
	}
	else {
		inputObj.value = 1;
	}
}

function textFieldUp(id, maxVal){
	var inputObj = $(id);
	var iVal = parseString(inputObj.value);
	if(iVal < maxVal){
		inputObj.value = iVal+1;
	}
}

/** parses a string to an int * */
function parseString ( String ) {
	return ( !isNaN(parseInt(String)) ) ? parseInt(String) : String;
}

/** shows/hides the discount layer depending to the current style * */
function toggleDiscountLayer(id) {
	if (!id) {
		if (activeDisplayLayer) {
			activeDisplayLayer.style.display = 'none';
			activeDisplayLayer = null;
		}

		return;
	}
	if (!$(id)) return;
	if ($(id) == activeDisplayLayer ) return; // if active is the selected one

	if (activeDisplayLayer) {
		activeDisplayLayer.style.display = 'none';
		activeDisplayLayer = null;
	}

	$(id).style.display = "block";
	activeDisplayLayer = $(id);
}

/** activates the timeout within a mouseooverevent * */
function toogleProdpager ( aElementId, img250px, text, img400px ) {
	timeoutpager = window.setTimeout("toogleProdpagerDelay('"+aElementId+"', '"+img250px+"', '"+text+"', '"+img400px+"')", 500);
}

/** clears the timeout within a mouseoutevent * */
function clearProdpage() {
	if(timeoutpager) {
		window.clearTimeout(timeoutpager);
	}
}

/** toogles the prodpager after the delay to the new elements * */
function toogleProdpagerDelay(aElementId, img250px, text, img400px) {
	toggleActiveItem ($(aElementId));
	showBigElement(img250px, img400px);
	if (text && text.length > 0) {
		$('similarflag').innerHTML = text;
	}
	else {
		$('similarflag').innerHTML = '';
	}
	setBigPopupLink($('mc_imglnk_vergroessern'), img400px);
}

/** Update the Link on the BigImage to the LargerImage * */
function setBigPopupLink (elem, img) {
	if (elem && img) {
		if ($(elem).hasClassName('MagicZoomPlus')) { // new for #3785
			elem.href = img;
			MagicZoomPlus.refresh(elem.id);
		}
		else {
			elem.href = "javascript:openPopup('/ce/ProductDetailImage.html?image="+img+"', 420, 420);"
		}
	}
}


/** Sets the selected element to active in pager * */
function toggleActiveItem(elem) {
	if (!elem) return;

	var manipulateElem = (elem.parentNode && elem.parentNode.parentNode ) ? elem.parentNode.parentNode : null;
	if (manipulateElem) {

		// restyle the 'old'-Active
		if (activeElement) {
			activeElement.className = '';
		}

		// style the 'new'-Active
		manipulateElem.className = 'active';

		// save the activeElem
		saveActiveElem(elem);
	}

}

/** saves the active Element in a global var * */
function saveActiveElem ( AElem ) {
	activeElement = (AElem) ? AElem.parentNode.parentNode : null;
}

/** Shows/Hides the Image/Flash-Layer and toggles to the right image * */
function showBigElement(elem, img400px) {
	if (elem) {
		if (elem.indexOf('.swf') > -1 ) {
			// hide Image
			$('BigProductImage').style.display = 'none';

			// Append Layer to Container
			var pL = $('FlashContainerOverall');
			pL.innerHTML = '<div id="FlashContainer"></div>';

			// Append swf
			swfobject.embedSWF(elem, "FlashContainer", "250", "250", "8.0.0", false, flashvars, params, attributes);

			pL.style.display = 'inline';
			$('FlashContainer').style.display = 'inline';
		}
		else {
			// $('FlashContainer').style.display = 'none';
			var pL = $('FlashContainerOverall');
			var bI = $('BigProductImage');
			pL.innerHTML = '';
			$('FlashContainerOverall').style.display = 'none';
			bI.src = elem;
			bI.style.display = 'inline';

			setBigPopupLink(bI.parentNode, img400px);
		}

	}
}


/*
 * Die klassischen Funktionen zum öffnen von Popups und Ein-/Ausblenden von
 * Fenstern
 */
function openPopup(url, width, height, name, params) {
	if (name == null) {
		name = "ConradPopup";
	}
	var p = (params) ? params : 'width='+width+',height='+height+',left=10,top=10,resizable=no,scrollbars=no,dependent=yes,menubar=no,location=no,toolbar=no,status=yes';
	var win = window.open(url, name , p);
	win.focus();
}
function openEbulaPopup(url, width, height, name, params) {
	if (name == null) {
		name = "EbulaPopup";
	}
	var p = (params) ? params : 'width='+width+',height='+height+',left=10,top=10,resizable=yes,scrollbars=yes,dependent=yes,menubar=no,location=no,toolbar=no,status=yes';
	var win = window.open(url, name , p);
	win.focus();
}
function openPrintPopup1() {
	openPopup('', 540, 440, "Druckauswahl");
}
function openPrintPopup2(u) {
	var p = 'width=710,left=10,top=10,resizable=no,scrollbars=yes,dependent=yes,menubar=no,location=no,toolbar=no,status=yes';
	window.open(u, 'Druckansicht' , p);
	self.close();
}

function openComparePopup() {
	openPopup('',960,690, 'ConradCompare' , 'width=960,height=690,left=10,top=10,resizable=yes,scrollbars=yes,dependent=yes,menubar=no,location=no,toolbar=no,status=yes');
}

function openDeliveryCostCalculatorPopup() {
	openPopup('', 565, 425, 'DeliveryCostCalculator', 'width=565,height=425,left=10,top=10,resizable=no,scrollbars=no,dependent=yes,menubar=no,location=no,toolbar=no,status=yes');
}

function toOldWin(url, closeit) {
	if (opener == null) self.close();
	else {

		try {
			opener.focus();
			if (opener.location.href != url)
				opener.location.href = url;
		}
		catch (e) {
		}
		if (closeit)
			self.close();
	}
	return false;
}

function toLogin(loginurl) {
	if (opener.location.href != loginurl)
	opener.location.href = loginurl;
}


/* Öffnen und schließen von Layer */
function hideLayer(n) {
	$(n).hide();
}

function showLayer(n) {
	$(n).show();
}

function showhideLayer(n) {

	if ($(n).style.display) {
		$(n).show();
	}
	else {
		$(n).hide();
	} 
}
/* Ende: Öffnen und schließen von Layer */


var b2bName = null;
function changeToB2B(name) {
	$('b2b_' + name).checked = true;
	b2bName =  name;
	$('isB2CForm').value = 'false';
	showLayer('b2bTable');
	hideLayer('b2cTable');
}

function changeToB2C() {
	if (b2bName)
		$('b2c_' + b2bName).checked = false;
	$('isB2CForm').value = 'true';
	showLayer('b2cTable');
	hideLayer('b2bTable');
}

function closeB2BLayer() {
	hideLayer('businessLayer');
	hideLayer('businessLayerShadow');
}

function closeB2CLayer() {
	hideLayer('customerLayer');
	hideLayer('customerLayerShadow');
}

function closeCountryPopBLayer() {
	hideLayer('countryPopup');
	hideLayer('countryPopupLayerShadow');
}

function closeWebportalLayer() {
	hideLayer('webportalLayer');
	hideLayer('webportalLayerShadow');
}



/* IFrame zum ?berlagern in der Navigation */
function showKillIframe (mLayer, width) {
  if ( ( navigator.appName.indexOf("Explorer") != -1 || navigator.userAgent.indexOf("Gecko")) && !window.opera)  {

    var kFrame = $('killSelectElement');
    if (kFrame) {

		var ua =navigator.userAgent.toLowerCase();
		var ieVer = parseInt(ua.substring(ua.indexOf("msie")+5, ua.indexOf("msie")+8));

		if (navigator.appName.indexOf("Explorer") != -1) {
			// isIE
			mLayer.appendChild(kFrame);
			kFrame.style.display = "block";
			kFrame.style.width = "181px";
			kFrame.style.height = mLayer.offsetHeight-5+"px";
		} else {
			// is NO IE
			kFrame.style.display = "";
			kFrame.style.width = "161px";
			kFrame.style.height = mLayer.offsetHeight - 4 +"px";
			mLayer.appendChild(kFrame);
		}
	}
	if (width) { 
		kFrame.style.width = width + "px";
	}
  }
}
function hideKillIframe () {
  // hide
  var kFrame = $('killSelectElement');
  if (kFrame) {
    kFrame.style.display = "none";
  }
}

/* Funktionen zum (De-)Selektieren aller Checkboxen in einem Formular */
/* f: entweder id oder formobjekt */
function checkAll(f) {
	var e, i;
	i = 0;
	if ( typeof f == 'string') {
		while (e = document.getElementById(f).elements[i++]) {
			if (e.type == 'checkbox') e.checked = true;
		}
	}
	else if ( typeof f == 'object' ) {
		while (e = f.elements[i++]) {
			if (e.type == 'checkbox') e.checked = true;
		}
	}

}

function uncheckAll(f) {
	var e, i;
	i = 0;
	if ( typeof f == 'string') {
		while (e = document.getElementById(f).elements[i++]) {
			if (e.type == 'checkbox') e.checked = false;
		}
	}
	else if ( typeof f == 'object' ) {
		while (e = f.elements[i++]) {
			if (e.type == 'checkbox') e.checked = false;
		}
	}
}

function toggleHiddenField(inputElm, field, val) {
	field.value = val;
	inputElm.src = configuration.radioImageChecked;
	if (activeElm) {
		activeElm.src = configuration.radioImage;
	}
	activeElm = inputElm;
}

/* Funktionen zur Anzeige von Raten/Gesamtpreis bei Ratenzahlung */
function showRatesLayer() {
	$('rateSelect').selectedIndex = 'values_6';
	updateRate('values_6');
	showLayer('RatesLayer');
	// $('RatesLayer').style.display = 'block';
}

function updateRate(selectValue) {
	var values = $(selectValue).firstChild.data.split('_');

	/* $('newPrice').firstChild.data = values[0]; */
	$('rateText').firstChild.data = values[1];
	$('monthlyRate').firstChild.data = values[2];
	$('sollZins').firstChild.data = values[3];
}


/* Variations Funktionen */
function setVariationAvaiblity(code, selIndex){

	// update the hidden-value if available
	if ( $('productcode') ) {
		$('productcode').value = code;
	}

	if (variationDeliveries[code] && variationDeliveries[code][0]) {
		$('varAvaibility').innerHTML = variationDeliveries[code][0];
		/*
		 * hauptverfügbarkeit soll immer auf "beste verfügbarkeit" stehen
		 * bleiben if ( selIndex == 0 || selIndex == null) {
		 * $('product_availability').innerHTML = bestAvailability[0]; } else {
		 * $('product_availability').innerHTML = variationDeliveries[code][0]; }
		 */
	}
	if (variationDeliveries[code] && variationDeliveries[code][1]) {
		$('varAvaibility').className = "avaibility_" + variationDeliveries[code][1];
		/*
		 * if ( selIndex == 0 || selIndex == null) {
		 * $('product_availability').className = "avaibility_" +
		 * bestAvailability[1]; } else { $('product_availability').className =
		 * "avaibility_" + variationDeliveries[code][1]; }
		 */


	}
}

function checkVariation() {
	if (document.addToCartForm && document.addToCartForm.variation[document.addToCartForm.variation.selectedIndex].value == "productcode0") {
		$('ErrorVariationSize').show();
		return false;
	}
	return true;
}

function updateVariationBox() {
	setVariationAvaiblity($('ProductDetailCartForm').variation[$('ProductDetailCartForm').variation.selectedIndex].value);
}


/* Vorschau-Buttons im Schaufenster 1 */
function showVorschauButton(sku,elem) {
	// Get the Preview Layer from tzhe sku and show it
	var prevElm = $('PreviewBut_' + sku);
	prevElm.style.display = 'block';
}

function hideVorschauButton(sku) {
	// Get the Preview Layer from tzhe sku and hide it
	var prevElm = $('PreviewBut_' + sku);
	prevElm.style.display = 'none';
}


/* Kontakt - Art des Anliegens */
function kindOfContact(kind) {
	var standard = $('contact_standard');
	var techFirst = $('contact_technical_first');
	var techSecond = $('contact_technical_second');
	var other = $('contact_else');

	if (kind == 'standard') {
		standard.show();
		techFirst.hide();
		techSecond.hide();
		other.hide();
	} else if (kind == 'technical1') {
		standard.hide();
		techFirst.show();
		techSecond.hide();
		other.hide();
	} else if (kind == 'technical2') {
		standard.show();
		techFirst.hide();
		techSecond.show();
	} else if (kind == 'other') {
		standard.hide();
		techFirst.hide();
		techSecond.hide();
		other.show();
	}
}

function trim (zeichenkette) {
	return zeichenkette.replace (/^\s+/, '').replace (/\s+$/, '');
}

function showDeliverLayer() {
	// updateInfoCenter('info_delivery');
	window.top.updateInfoCenter('info_delivery_costs');
}
function hideDeliverLayer() {
	window.top.infocenter.hide();
	// $('InfoCenter').hide();;
}

function showRecyclingLayer() {
	window.top.updateInfoCenter('infocenterMenu');
}

function checkTab (id) {
	if (document.location.hash.substring(1) == id)
		$(id).show();
	else
		$(id).hide();
}

function loadURL (url, params, async, method, onSuccess, onFailure) {
	new Ajax.Request(url, {
		parameters: params,
		asynchronous: async,
		method: method,
		onSuccess: onSuccess,
		onFailure: onFailure
	});
}

var activeSearchLayer = false;
function toggleSearchLayer(id) {
	if(!id) return;

	if (activeSearchLayer != id) {
		// anderer Menupunkt
		if (activeSearchLayer)
			$(activeSearchLayer).hide();
		$(id).show();
		activeSearchLayer = id;
	}
	else {
		// weniger
		if (activeSearchLayer)
			$(activeSearchLayer).hide();
		activeSearchLayer = null;
	}
}

/* FastRegistration Bestellbestätigung */
function showFastReg() {
	$('fastReg').hide();
	$('fastRegTable').show();
}


/**
 * dlayer function set the filter number no to the value fvalue
 * 
 * @param no
 *            the filter number, integer between 1 and 6
 * @param fvalue
 *            the value, String
 */
function setFilter(no,fvalue,fid, formid, count, fieldid){
	if ($(formid)) {
		if (!fieldid) {
			$(formid).filter_selection.value = fvalue;
			$(formid).filter_selection.disabled = false;
		}
		else {
			$(fieldid).value = fvalue;
			$(fieldid).disabled = false;
		}
	}
	else {
		if (no == 'price' ) {
			$('pricerange').value = fvalue;
		} else if (no == 'feature' ) {
			$('feature').value = fvalue;
		} else if (no == 'orderby' ) {

			if( fvalue != "" ) {
				var arr = fvalue.split("&");

				$('orderBy').value = arr[0];
				$('orderSequence').value = arr[1];
			} else {
				$('orderBy').value = "";
				$('orderSequence').value = "";
			}
		}
		else if (no == 'rating' ) {
			$('bvRating').value = fvalue;
		}
		else {
			$('filter_selection_'+no).value = fvalue;
			for(i=1; i<=count; i++) {
				if ($('filter_selection_'+i).value != "") {
					$('filter_selection_'+i).disabled = false;
				}
			}
		}
	}
	if (!formid) {
		document.filter.submit();
	}
	else {
		$(formid).submit();
	}
}

function updateInfoCenter (param /* [url] */, ispop) {
	var domainName = document.domain;
	if (ispop == 'opener')
		$('iCenterIframe').innerHTML = '<iframe name="infoCenterFrame" id="infoCenterFrame" src="'+configuration.infoCenterAction + "?area=" + param+'&popup=true&domainName=' + domainName + '" height="368" width="566" scrolling="no" frameborder="0" ></iframe>';
	else
		$('iCenterIframe').innerHTML = '<iframe name="infoCenterFrame" id="infoCenterFrame" src="'+configuration.infoCenterAction + "?area=" + param+'&domainName=' + domainName + '" height="468" width="658" scrolling="no" frameborder="0" ></iframe>';
	
	var elem = $('InfoCenter');
	var xCoord = 0, yCoord = 0, width = 0;
	var arrayPageSize = getPageSize();

	width = arrayPageSize[0];
	xCoord = (width-400)/2;

	if (window && window.pageYOffset) {
		// FF, OPERA, SAFARI
		yCoord = window.pageYOffset;
	}
	else if ( document.documentElement && document.documentElement.scrollTop ) {
		// IE6, IE7
		yCoord = document.documentElement.scrollTop;
	}

	elem.style.top = (yCoord+10) + "px";
	elem.style.left = xCoord + "px";
	// $('infoCenterCloseButton').observe('click', function() { alert('hallo');
	// });
	elem.show();
}


// Produktvergleich
function updateProductComparer (code, layername, errText) {
		var params = new Hash();
		params.set("update");
		params.set("code", code);
		params.set("xml", 1);
		
		loadURL(
			configuration.actionProductsCompare, 
			params, 
			true, 
			'post', 
			function(transport) { parseResponse(transport, layername, errText);  }, 
			function(transport) { alert('failure show');  } 
		);
	}
	
	function parseResponse(transport, layername, errText) {
		var item = transport.responseXML;
		if (item && item.getElementsByTagName('status')[0]) {
			var stat = item.getElementsByTagName('status')[0].firstChild.nodeValue;
			if (stat == 1) {
				hideLayer(layername);
			}
			else {
				updateErrorLayer(item, errText,  layername);
			}
		}
		else {
			updateErrorLayer (null) 
		}
	}
	function updateErrorLayer( item, text, layerToHide ) {
		var errLayer = $$('#errors')[0];
		
		if (item) {
			errLayer.innerHTML = '<span style="color:#ff0000;">' + item.getElementsByTagName('error')[0].firstChild.nodeValue + '</span>'; 
			// errLayer.innerHTML = "No Error XML Document inner it table";
		}
		else {
			errLayer.innerHTML = text;
		}
		showLayer('productsCompareErrorLayer');
		hideLayer(layerToHide);
	}

function switchtab(num){
	if(document.getElementById("faqdiv"+num).style.display == "block"){
		document.getElementById("faqdiv"+num).style.display = "none";
		document.getElementById("faqli"+num).className = "";
		document.getElementById("faqli"+num).setAttribute("class", "");
	}
	else{
		document.getElementById("faqdiv"+num).style.display = "block";
		document.getElementById("faqli"+num).className = "open";
		document.getElementById("faqli"+num).setAttribute("class", "open");
	}
}
function closetab(i){
	document.getElementById("faqdiv"+i).style.display = "none";
	document.getElementById("faqli"+i).className = ""; 
	document.getElementById("faqli"+i).setAttribute("class", "");
}

function showTooltip(img) {
	var liObj = img.parentNode;
	var pos	= parseInt(liObj.id.substring(liObj.id.indexOf('symbol')+6))-1;
	
	var pulldown = $('symbollayer');
	var pulldownImage = pulldown.firstChild;
	pulldownImage.src = img.src.substring (0, img.src.lastIndexOf('40')) + '400.' + img.src.substring(img.src.length-3);

	var top = ((parseInt((pos / 7))+1) * 50 ) +10;
	var left = (pos % 7)  * 53 + 10;

	pulldown.setStyle ({top: '-10px', left: left+'px'});
	pulldown.onmouseover = function () { showTooltip(img); }
	pulldown.onmouseout = function () { hideTooltip(img); }
	pulldown.show();
}
function hideTooltip (img) {
	var pulldown = $('symbollayer');
	var pulldownImage = pulldown.firstChild;
	pulldownImage.src = '';
	pulldown.hide();
}

function checkShoppingListName() {  
	if ($('shoppingListInputName').value == '') {  
		$('shoppingListInputNameError').show();  
		return false;  
	}  
}  

var glblRatingTrackingStat = 0;
var then=null;
var diffSec=null;
function startReadTimer(){
    if(then == null && diffSec == null){
        then=new Date();
     }else{
        return false;
    }
}
function stopReadTimer(artnr){
    if(diffSec==null && then!=null){
        var now = new Date();
        var tmpSec = now.getSeconds()-then.getSeconds();
        diffSec = tmpSec;
        trackRatingView("viewTime", diffSec,artnr,0);
    }
}
function trackRatingView(what, secs, artnr, amount){
	if (typeof dcsMultiTrack == 'function'){
	    if(what=="viewTime" && secs != 'false'){
	        dcsMultiTrack('WT.z_rating_viewTime',secs);
	    }
	    if(what=="view" && glblRatingTrackingStat<1){
	        glblRatingTrackingStat=1;
	        dcsMultiTrack('WT.z_rating_view',artnr);
	    }
	    if(what=="trackRatingCount"){
	        dcsMultiTrack('WT.z_rating_count',amount);
	    }
	    if(what=="trackRating"){
	        dcsMultiTrack('WT.z_rating',amount);
	    }
	    if(what=="avgRating"){
	        dcsMultiTrack('WT.z_avg_rating',amount);
	    }
	}
}

// Function needed for the Inventory check
function retriveRetailStoreavailability()
{
			var xmlhttp;
			var productid = $('productID').innerHTML;
			var chainstoreId = $('chainstoreId').value;
			var productAmount = window.document.getElementById("mc_frmtxt_" + productid + "_menge").value;
			var store = $('chainstoreId');
			var storename = store.options[store.selectedIndex].text;
			var storevalue =  store.options[store.selectedIndex].value;
			//var productAmount = '1';
			// the product amount is only set if the product is not sold out
			// that is why the initial product amount in this function is set to one
			// and in case the product is not sold out the original value is used
			//if (productAmountInput != null) {
			//	productAmount = productAmountInput.value;
			//}
			
			$('chainStoreValueId').value = storevalue;
			
			// exit if no chainstore is choosen
			if(chainstoreId == 'defaultMessage'){   
				return;
			}
			
			var url = '/ce/RetailStoreInventoryCheck.html?' + 'productcode=' + productid + '&chainstoreId=' + chainstoreId ;

			// show the \images\default\default\panel\ajax-loader.gif
			$('ajaxWaitImg').setStyle({display:'block'});      			
			$('inventoryCheck').setStyle({display:'none'});
			
			new Ajax.Request(url, {
				  onSuccess: function(response){
					var responseValues = response.responseText.split(',');
					var productsAvailable = responseValues[0];
					var reservable = responseValues[1];
							
					$('productMaxValueId').value = productsAvailable;
					if(parseInt(productAmount) > parseInt(productsAvailable))
					{
						$('amountInventoryTB').value = productsAvailable;
					}
					else
					{
						$('amountInventoryTB').value = productAmount;
					}
					if (parseInt(productsAvailable) > 0) {
						$('amountInventory').innerHTML= productsAvailable;
						$('inventoryCheckProductAvailableText').setStyle({display:'inline'});
						$('inventoryCheckProductNotAvailableText').setStyle({display:'none'});
					} else {
						$('inventoryCheckProductAvailableText').setStyle({display:'none'});
						$('inventoryCheckProductNotAvailableText').setStyle({display:'inline'});
					}
					$('inventoryCheckResult').setStyle({display:'block'});
					// hide the ajax-loader image
					$('ajaxWaitImg').setStyle({display:'none'});
						
					if(reservable == 'true') {
						$('reservationNormalProductDiv').setStyle({display:'block'});
					} else {
						if (productsAvailable > 0) {
							$('reservationExtraProductDiv').setStyle({display:'block'});
						}
					}
					
				},
				onFailure:function(response){
					$('errorInventory').innerHTML=response.responseText;
					
					$('inventoryCheckError').setStyle({display:'block'});
					// hide the ajax-loader image
					$('ajaxWaitImg').setStyle({display:'none'});
        
        }
			});
}

// Function needed for the Inventory check
function resetInventoryCheck()
{
	// show the inventory check
	$('inventoryCheck').setStyle({display:'block'});
	$('inventoryCheckResult').setStyle({display:'none'});
	$('inventoryCheckError').setStyle({display:'none'});
	$('reservationNormalProductDiv').setStyle({display:'none'});
	$('reservationExtraProductDiv').setStyle({display:'none'});
}

// Update product price information
function recommendationPriceUpdate(productCode, divToUpdate) {
	var priceUpdate = new Array();
	var priceObject = new Object();
	priceObject.productId = productCode;
	priceObject.elementId = divToUpdate;
	priceUpdate.push( priceObject );
	recommendationPriceUpdateFromArray(priceUpdate);
}

function recommendationPriceUpdateFromArray(priceUpdateArray) {
	var xmlhttp;
	var productCodes = '';
	var elementIds = '';

	for (var i = 0; i < priceUpdateArray.length; i++) {
		productCodes += priceUpdateArray[i].productId + ';';
		elementIds += priceUpdateArray[i].elementId + ';';
	}

	var url = '/ce/RecommendationPriceUpdate.html?productcodes=' + productCodes + '&elementIds=' + elementIds;

	// Show waiting image on every element
	for (var i = 0; i < priceUpdateArray.length; i++) {
		$(priceUpdateArray[i].elementId).innerHTML = '<img src="/images/default/default/panel/ajax-loader.gif" />';      			
	}

	// Get the price informations
	new Ajax.Request(url, {
		onSuccess: function(response) {
			var resp = response.responseText;
			resp = trim(resp);
			var jsonObject = resp.evalJSON(true);
			for (var i = 0; i < jsonObject.length; i++) {
				$(jsonObject[i].elementId).innerHTML = jsonObject[i].priceCode;
			}
		},
		onFailure: function(response) {
			$(divToUpdate).innerHTML = '';
		}
	});
}

// increments the number of the textfield with the id productMaxValueId
function fieldUpForInventoryCheck(id)
{
	var maxValue = window.document.getElementById("productMaxValueId").value;
	textFieldUp(id, maxValue);
}


function checkPhoneNumberAvailable(phone){
        if ($("chainStore").checked) {
        
        
            if ($("lbContent2") != null) {
                $("lbContent2").remove();
            }
            
            // the service CheckAvailableProducts checks if the products for the selected chainstore are available.
            var url = '/ce/CheckAvailableProducts.html';
            var productsForChainStoreAvailable = true;
            
            //call the service in a synchronous way
            new Ajax.Request(url, {
                method: 'post',
                asynchronous: false,
                onSuccess: function(response){
                    productsForChainStoreAvailable = response.responseText;
                    //check if all products are available
                    if (productsForChainStoreAvailable.include('true')) {
                        //if not all products are available show a modal popup where the user can decide what todo with these products. Reservation process 4.1.4
                        document.getElementById("lbOnAuto2").value = '/ce/NotAvailableLayer.html';
                        document.getElementById("lbOnAuto2").style.display = "block";
                        lbox = document.getElementsByClassName('lbOn2');
                        for (i = 0; i < lbox.length; i++) {
                            //calls the initialize function of the lightbox2 js
                            valid = new lightbox(lbox[i]);
                        }
                        //returns false so that the post of the submit button is not called
                        return false;
                    }
                },
                onFailure: function(response){
                }
            });
            //returns false so that the post of the submit button is not called
            if (productsForChainStoreAvailable.include('true')) {
                return false;
            }
            
            // checks if the user has already a phone number for callbacks.
            if ((phone == null)) {
                // if not show a modal popup where the user can input his/her phonenumber. Reservation process 4.1.5
                document.getElementById("lbOnAuto2").value = '/ce/OrderprocessPhonenumber.html';
                document.getElementById("lbOnAuto2").style.display = "block";
                lbox = document.getElementsByClassName('lbOn2');
                for (i = 0; i < lbox.length; i++) {
                    //calls the initialize function of the lightbox2 js
                    valid = new lightbox(lbox[i]);
                }
                //returns false so that the post of the submit button is not called
                return false;
            }
        }
        return true;
}

// sets a chainStore to a cart
function setChainStore()
{
	var chainStoreId = $('chainstoreId').value;
	
	var url = '/ce/UpdateChainStoreForCart.html?chainStoreId=' + chainStoreId;

	new Ajax.Request(url, {
		onSuccess: function(response){
			var responseValues = response.responseText.split(',');
			$('chainStoreAddress').innerHTML = responseValues[0] + '<br />' + responseValues[1] + ' ' + responseValues[2] + '<br />' + responseValues[3] + '<br />';
		},
		onFailure: function(response) {
			$(divToUpdate).innerHTML = '';
		}
	});
}

//
function notAvailableLayer(formID, url, productCode) {
	var paramsMap = new Hash();	
	paramsMap.set('chosenProductCode', productCode);
	ajaxRequestHandler(paramsMap, url);
	return false;
}

function addQuantity(id, quantityTBId)
{
	var quantity = 0;
	var quantityId = $(quantityTBId);
	if(quantityId.id.include('mc_info_')){
		quantity = $(quantityTBId).textContent.replace('Stück','')
	}
	else{
		quantity = $(quantityTBId).value;
	}
	if($(id).href.include('quantity') == false){
		$(id).href = $(id).href + '&quantity=' + quantity;
	}
	else{
		$(id).href = $(id).href.substring(0, $(id).href.indexOf('&quantity')) + '&quantity=' + quantity;
	}
	
}

function sc_productRemoveFromCartWrapper(aObj) {
    var productNameRegExp = /(entryname=)([^&]*)/
    productNameRegExp.exec(aObj.href)
    productName = unescape(RegExp.$2);
    //alert(productName)
    sc_productRemoveFromCart(productName)
}


function addQuantityToForm (formField, quantityField) {
	if (document.getElementById(formField).value.indexOf('&quantity=') > -1)
	document.getElementById(formField).value = 
		document.getElementById(formField).value.substring(0,
				document.getElementById(formField).value.indexOf('&quantity='));
	document.getElementById(formField).value+='&quantity='+document.getElementById(quantityField).value;
}

function addValueToForm (formField, valueField, valueName) {
	if (document.getElementById(formField).value.indexOf('&'+valueName+'=') > -1)
	document.getElementById(formField).value = 
		document.getElementById(formField).value.substring(0,
				document.getElementById(formField).value.indexOf('&'+valueName+'='));
	document.getElementById(formField).value+='&'+valueName+'='+document.getElementById(valueField).value;
}

function loadRecommendations(type, code) {

	var url = '/ce/Recommendations.html?type=' + type + "&code=" + code;

	// load the recommendations
	new Ajax.Request(url, {
		onSuccess: function(response) {
			var resp = response.responseText;
			resp = trim(resp);
		},
		onFailure: function(response) {
		}
	});
}


function getAllWishLists(product,target) {
	var productAmount = window.document.getElementById("mc_frmtxt_" + product + "_menge").value;

	//Layer mit ajax-loader.gif anzeigen
	showLoadingBox();		
	var url = '/ce/WishListProductDetail.html?viewWishLists&product='+product+'&amount='+productAmount+'&target='+target;

			new Ajax.Request(url, {
				  onSuccess: function(response){
					  hideLoadingBox();
					  var resp = response.responseText;
					
				},
				onFailure:function(response){
					hideLoadingBox();
        }
			});
}

function getAllWishListsConfirmation(product,target,quantity) {
	
	
	var productAmount = quantity;
	
	

	//Layer mit ajax-loader.gif anzeigen
	showLoadingBox();		
	var url = '/ce/WishListProductDetail.html?viewWishLists&product='+product+'&amount='+productAmount+'&target='+target;

			new Ajax.Request(url, {
				  onSuccess: function(response){
					  hideLoadingBox();
					  var resp = response.responseText;
				},
				onFailure:function(response){
					hideLoadingBox();
        }
			});
}

function addProductToWishList(product,amount,counter) {
	showLoadingBox();	
	var wishlistID;
	
	for (i=0;i<counter;i++){
		if (window.document.getElementById('formular'+i).checked){
			wishlistID=window.document.getElementById('formular'+i).value;
			
		}
		
	}
	
	var url = '/ce/WishListProductDetail.html?addProduct&product='+product+'&id='+wishlistID+'&amount='+amount;
	
	new Ajax.Request(url, {
		  onSuccess: function(response){
			  hideLoadingBox();
			  var resp = response.responseText;			
		},
		onFailure:function(response){
			hideLoadingBox()
			

		}
	});
}

function createNewWishList(product,amount) {
	showLoadingBox();
	var url = '/ce/WishListProductDetail.html?createNewWishListFromDetailPage&product='+product+'&amount='+amount;
	
	new Ajax.Request(url, {
		  onSuccess: function(response){
			  hideLoadingBox();
			  var resp = response.responseText;
		},
		onFailure:function(response){
			hideLoadingBox();
		}
	});
}

function changeWishListStatus(hashcode,status) {
	showLoadingBox();	
			
			var url = '/ce/ChangeWishList.html?changeWishlistStatusFromSummary&wishlistStatus=' + status + '&hashcode=' + hashcode ;
			
			new Ajax.Request(url, {
				onSuccess: function(response){
					  hideLoadingBox();
					  var resp = response.responseText;
				},
				onFailure:function(response){
					hideLoadingBox();
				}
			});
}
function showPublic(kind) {
	if (kind == 'public'){
		 $('showPublic').show();
		 $('showNickname').show();
		 $('showCity').show();
		 $('showBirthday').show();
		 $('showDescription').show();
		 $('showMail').show();
		 
	}else{
		 $('showPublic').hide();
		 $('showNickname').hide();
		 $('showCity').hide();
		 $('showBirthday').hide();
		 $('showDescription').hide();
		 $('showMail').hide();
	}
}

function confirmationLayer() {
	showLoadingBox();	
			
			var url = '/ce/WishListProductDetail.html?confirmation';
			
			new Ajax.Request(url, {
				onSuccess: function(response){
					  hideLoadingBox();
					  var resp = response.responseText;
				},
				onFailure:function(response){
					hideLoadingBox();
				}
			});
}

function confirmationErrorLayer() {
	showLoadingBox();	
			
			var url = '/ce/WishListProductDetail.html?confirmationError';
			
			new Ajax.Request(url, {
				onSuccess: function(response){
					  hideLoadingBox();
					  var resp = response.responseText;
				},
				onFailure:function(response){
					hideLoadingBox();
				}
			});
}


function filterWishlist(optionValue){ 
	   for(var i = 1; i < jQuery("#notepad .tableborder tr").length;i++){
	      var wished    = jQuery("#wished" + i).text();
	      var recipted  = jQuery("#recipted" + i).text();
	    
	      jQuery("#row" + i).show();

	      if(optionValue == 1){
	        if(recipted >= wished){
	          jQuery("#row" + i).hide();
	        }
	      }else if(optionValue == 2){
	        if( wished > recipted ){
	          jQuery("#row" + i).hide();
	        }
	      }  
	        
	   }
	}
function changeSortCriteria(sortParms,searchParms){
	var orderBy = ' ';
	var orderSequence = '';
	var	parms = sortParms.split(',');
	orderParms = '&orderBy=nickname&orderSequence=DESC';
	orderBy = '&orderBy='+ parms[0];
	orderSequence = '&orderSequence='+ parms[1];
	var url = '/ce/SearchWishList.html?view' + searchParms + orderBy + orderSequence;
	location.href =	url;
}
 


/* 
 *  Kiala Point france
 *  get all KialaPoints for a given zip-code
 */
function checkKialaPoints(){
    hideLayer("kialaPointDetail");
	hideLayer("kialaPostCodeError");
	hideLayer("kialaTimeOut");  
	hideLayer("kialaFormManipulation");  
	hideLayer("kialaPointHasToBeSelected");
	
	//Wenn bereits Kiala Points in der Selectbox sind wird der Inhalt der Selectbox gelöscht
	document.getElementById("selectKialaStation").options.length=0;
	
	//URL für Ajaxanfrage an JavaAction um Parameter ergänzen
	var url = document.URL;
    var myArray = url.split("?");
	var zipcode = document.getElementById('postleitzahlKiala').value
    url = myArray[0] + '?wayOfDelivery=KIALA&zipcode='+zipcode;
    
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function(){
         
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			
			//ungültige Postleitzahl abfangen
			if (xmlhttp.responseXML.documentElement.getElementsByTagName("kp").length == 0) {
				showLayer('kialaPostCodeError');				
			}else{
			//Anzahl an KialaStationen im Request ermitteln
			var numberOfRequestKialaPoints = xmlhttp.responseXML.documentElement.getElementsByTagName("kp").length-1;
			var maxKialaPoints =null;
			if (numberOfRequestKialaPoints<4){
				maxKialaPoints = numberOfRequestKialaPoints;
			}else{
				maxKialaPoints = 4;
			}		
			
            //inititalise data
            var street = null;
            var zip = null;
            var town = null;
            var kialaPointImage = null;
            var locationHint = null;
            var nameArray = new Array();
            var dayArray = new Array();
            var dayStartArray = new Array();
            var dayEndArray = new Array();
			var content = null;
			var kpElement = null;
			var locationHint= null;
            
            var select = document.getElementById("selectKialaStation");
            for (i = 0; i <= maxKialaPoints; i++) {
                var name = xmlhttp.responseXML.documentElement.getElementsByTagName("name")[i];
                nameArray[i] = name.textContent;
                select.options[select.options.length] = new Option(nameArray[i],(i));
                if (i == 0) {
                    street = xmlhttp.responseXML.documentElement.getElementsByTagName("street")[i];
                    zip = xmlhttp.responseXML.documentElement.getElementsByTagName("zip")[i];
                    town = xmlhttp.responseXML.documentElement.getElementsByTagName("city")[i];
                    locationHint = xmlhttp.responseXML.documentElement.getElementsByTagName("locationHint")[i];
                    var openingHours = xmlhttp.responseXML.documentElement.getElementsByTagName("openingHours")[i];
                    kialaPointImage = xmlhttp.responseXML.documentElement.getElementsByTagName("picture")[i];
                    kpElement= xmlhttp.responseXML.documentElement.getElementsByTagName("kp")[i];
                    locationHint = xmlhttp.responseXML.documentElement.getElementsByTagName("locationHint")[i];
                    for (x = 0; x <= 6; x++) {
                        dayArray[x] = openingHours.children[x].attributes[0].nodeValue;
                        
                        //try-catch wird bnenötigt, wenn bspw. am Wochenende keine öffnungszeiten angegeben sind
                        try {
                            dayStartArray[x] = openingHours.children[x].children[0].children[0].textContent;
                        } 
                        catch (e) {
                            dayStartArray[x] = '';
                        }
                        try {
                            dayEndArray[x] = openingHours.children[x].children[0].children[1].textContent;
                        } 
                        catch (e) {
                            dayEndArray[x] = '';
                        }
                    }
                    
                } 
			}
                // Kiala Point im Div anzeigen
                 content =  street.textContent + '<br/>' + zip.textContent + ' ' + town.textContent + '<br/>' + nameArray[0] +'<br/><br/>';
         
                    for (var i = 0; i < dayArray.length; i++) {
                        content += dayArray[i] + ':' + dayStartArray[i] + '-' + dayEndArray[i] + '<br/>';
                    }
					//Setzen von nicht sichtbaren Attributen
					document.getElementById("kialaPointDetailText").innerHTML = content;
					document.getElementById("kialaPointId").value = kpElement.attributes[0].nodeValue;
					document.getElementById("kialaPointShortId").value = kpElement.attributes[1].nodeValue;
					document.getElementById("kialaPointLocationHint").value = locationHint.textContent;
					document.getElementById("kialaPointTown").value = town.textContent;
	                
                // Image vom Kiala Point einbinden 
                try {
					document.getElementById("kialaPointImage").src = kialaPointImage.attributes[0].textContent;
				}catch(e){
					document.getElementById("kialaPointImage").src ='';
				}
             showLayer('kialaPointDetail');   
        }
    }
	}
    try {
        xmlhttp.open("GET", url, true);
        // 	xmlhttp.setRequestHeader("Content-Type", "text/xml");
        xmlhttp.send();
    } 
    catch (e) {
		showLayer('kialaTimeOut');			
    }

}



/* 
 *  Kiala Point france 
 *  Refresh the KialaPoint details shown on the Page for a selectet KialaPoint (selectBox)
 */
function refreshKialaPointDetailText(kialaPointNumber){
	
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			//inititalise data
            var street = null;
            var zip = null;
            var town = null;
            var kialaPointImage = null;
            var locationHint = null;
            var nameArray = new Array();
            var dayArray = new Array();
            var dayStartArray = new Array();
            var dayEndArray = new Array();
			var content = null;
			var kpElement = null;
			var locationHint= null;
			
			var select = document.getElementById("selectKialaStation");
			name = xmlhttp.responseXML.documentElement.getElementsByTagName("name")[kialaPointNumber];
			
                    street = xmlhttp.responseXML.documentElement.getElementsByTagName("street")[kialaPointNumber];
                    zip = xmlhttp.responseXML.documentElement.getElementsByTagName("zip")[kialaPointNumber];
                    town = xmlhttp.responseXML.documentElement.getElementsByTagName("city")[kialaPointNumber];
                    locationHint = xmlhttp.responseXML.documentElement.getElementsByTagName("locationHint")[kialaPointNumber];
                    var openingHours = xmlhttp.responseXML.documentElement.getElementsByTagName("openingHours")[kialaPointNumber];
                    kialaPointImage = xmlhttp.responseXML.documentElement.getElementsByTagName("picture")[kialaPointNumber];
                    kpElement= xmlhttp.responseXML.documentElement.getElementsByTagName("kp")[kialaPointNumber];
                    locationHint = xmlhttp.responseXML.documentElement.getElementsByTagName("locationHint")[kialaPointNumber];
			for (x = 0; x <= 6; x++) {
				dayArray[x] = openingHours.children[x].attributes[0].nodeValue;
				
				//try-catch wird bnenötigt, wenn bspw. am Wochenende keine öffnungszeiten angegeben sind
				try {
					dayStartArray[x] = openingHours.children[x].children[0].children[0].textContent;
				} 
				catch (e) {
					dayStartArray[x] = '';
				}
				try {
					dayEndArray[x] = openingHours.children[x].children[0].children[1].textContent;
				} 
				catch (e) {
					dayEndArray[x] = '';
				}
			}
			// Kiala Point im Div anzeigen
			content =  street.textContent + '<br/>' + zip.textContent + ' ' + town.textContent + '<br/>' + name.textContent + '<br/><br/>';
			
			for (var i = 0; i < dayArray.length; i++) {
				content += dayArray[i] + ':' + dayStartArray[i] + '-' + dayEndArray[i] + '<br/>';
			}
			
			// Setzen von nicht sichtbaren Attributen
					document.getElementById("kialaPointDetailText").innerHTML = content;
					document.getElementById("kialaPointId").value = kpElement.attributes[0].nodeValue;
					document.getElementById("kialaPointShortId").value = kpElement.attributes[1].nodeValue;
					document.getElementById("kialaPointLocationHint").value = locationHint.textContent;
					document.getElementById("kialaPointTown").value = town.textContent;
			
			// Image vom Kiala Point einbinden 
			try {
				document.getElementById("kialaPointImage").src = kialaPointImage.attributes[0].textContent;
			} 
			catch (e) {
				document.getElementById("kialaPointImage").src = '';
			}
		}
    showLayer('kialaPointDetail');
}

/*
 * Kiala Point france
 * This function validates, if the selected Kiala Point belogs to the zipcode of the Form.
 * If the zipcode changed a error Message will appear
 */
function validateSelectKialaPoint(){
	hideLayer("kialaPostCodeError");  
  
	var status = false ;
	var numberOfSelectedKialaStations = document.getElementById("selectKialaStation").options.length; 
	if (numberOfSelectedKialaStations != 0) {
		//ID des aktuellen ausgewählten Kiala Point aus Form auslesen auslesen 
		var selectedKialaPointID = document.getElementById('kialaPointId').value;
		var selectBox = document.getElementById("selectKialaStation");
		var selectBoxPostCodeIndex =selectBox.options[selectBox.options.selectedIndex].value;
		
		//URL fär Ajaxanfrage an JavaAction um Parameter ergänzen
		var url = document.URL;
		var myArray = url.split("?");
		var zipcode = document.getElementById('postleitzahlKiala').value
		url = myArray[0] + '?wayOfDelivery=KIALA&zipcode=' + zipcode;
		
		if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		}
		else {// code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange = function(){
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				//ungültige Postleitzahl abfangen (kein KialaPoint gefunden)
				if (xmlhttp.responseXML.documentElement.getElementsByTagName("kp").length == 0) {
					showLayer('kialaPostCodeError');
				}
				else {
				
					//Vergelichen der KialaPointId der Selectbox mit ermittelten KialaPointID für aktuellen Postcode(wenn true = keine Veränderung im Formular)		
					var webServiceKialaPointID =xmlhttp.responseXML.documentElement.getElementsByTagName("kp")[selectBoxPostCodeIndex].attributes[0].nodeValue;
					if (selectedKialaPointID == webServiceKialaPointID) {
						status = true;
					}
					else {
						showLayer("kialaFormManipulation");
					}
				}
			}
		}
		try {
			xmlhttp.open("GET", url, true);
			xmlhttp.send();
		} catch (e) {
			alert(e);
			showLayer('kialaTimeOut');
		}
	}else {
		showLayer("kialaPointHasToBeSelected");
	}
	
	return status;
}

// JavaScript Action zum Öffnen eines Popups für die Druckansicht des Kontaktformulars
function showContactPrintPage(action){ 
	var p = 'width=610,height=700,left=10,top=10,resizable=yes,scrollbars=yes,dependent=yes,menubar=no,location=no,toolbar=no,status=yes';
	var win = window.open("", "Druckauswahl" , p);
	win.focus(); 
	document.getElementById('ContactForm').target = "Druckauswahl";
	document.getElementById('ContactForm').method = "GET";
	
	// Submit-Button mit neuen Parametern und neuem Target automatisch ausführen 
	document.getElementById("mc_btn_submit_print").click();	
}

// logs to the Firebug console, if available
function logToConsole(msg) {
	if (window.console) {
		window.console.log(msg);
	}
}
