

/* indicates, if the user clicked the rating stars */
var persisted = false;
/* indicates, that an input field was initialized or reset */
var reset = false;
/* holds average product rating. Will be updated when page opens and user rates the product on the page */
var gv_rating = 0;
/* Will be set to true if new payment option was added */
var paymentOptionAdded = false;

/* default max quantity */ 
var defaultMaxQuantity = 99;

/* default Min Quantity */
var defaultMinQuantity = 1;

/* default max quantity weighed goods */
var defaultWeighedMaxQuantity = 9000;

/* default min quantity weighed goods */
var defaultWeighedMinQuantity = 100;

var oldTextValue = "";

var saveButtonPressed = false;

var products = [];

function getUrlParam(name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.href);
  if(results == null)
    return "";
  else
    return decodeURIComponent(unescape(results[1].replace(/\+/g, " ")));
}

function displayErrorMessageIfNecessary(errorCode) {
    if (errorCode == '') {
    	return;
    }

    switch (errorCode) {
    case 'NUMBER_REQUIRED':
    	displayActiveBarMessage("Ein ID oder Preisfeld ist nicht gef&uuml;llt oder enth&auml;lt ung&uuml;ltige Werte. Bitte &uuml;berpr&uuml;fe alle Felder mit *.");
    	break;
    case 'EAN_ALREADY_EXISTS':
    	displayActiveBarMessage("Die EAN ist bereits einem Artikel zugeordnet. Der entsprechende Artikel kann mit der regularen Suche identifiziert werden.");
    	break;
    default:
    	activeBar("Error: " + errorCode);
    }
}

function displayActiveBarMessage(message) {
	var bar = new ActiveBar(message);
	bar.show();
}

function imgError(source){
    source.src = "/FroodiesImages/images/products/keinBild.gif";
    source.onerror = "";
    return true;
}

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
 	} 
	else {
    window.onload = function() {
      if (oldonload) {
    	  oldonload();
      }
      func();
    };
  }
}

function Product(id, name, longDescription, producer, imagePath, weighedGood, averageRating, ratingCount, producerLink, producerLogo, ingredients, isBio, country) {
	this.id = id;
	this.name = name;
	this.longDescription = longDescription;
	this.producer = producer;
	this.imagePath = imagePath;
	this.weighedGood = weighedGood;
	this.averageRating = averageRating;
	this.ratingCount = ratingCount;
	this.articles = [];
	this.productAttributes = "";
	this.selectedArticle = 0;
	this.index = 0;
	this.producerLink = producerLink;
	this.producerLogo = producerLogo;
	this.ingredients = ingredients;
	this.isBio = isBio;
	this.productattributes = [];
	this.country = country;
}
function ShoppingList(id, name) {
	this.id = id;
	this.name = name;
}
function ProductAttribute(id, name) {
	this.id = id;
	this.name = name;
	this.productattributevalues = [];
}

function ProductAttributeValue(id, name, defaultValue) {
	this.id = id;
	this.name = name;
	this.defaultValue = defaultValue;
}

function Article(id, shortDescription, imagePath, multiplicator, quantity, unit, minQuantity, maxQuantity, addQuantity, addUnit, refQuantity, refUnit, deposit, price, weightPerUnit, nmbOfItems, isSpecialOffer, previousPrice, articleNumber, deliveredAmount, currentReferencePrice) {
	var privatePrice = 0;
	var factor = 0;
	this.id = id;
	this.shortDescription = shortDescription;
	this.imagePath = imagePath;
	this.multiplicator = multiplicator;
	this.quantity = quantity;
	this.minQuantity = minQuantity;
	this.maxQuantity = maxQuantity;
	this.unit = unit;
	this.addQuantity = addQuantity;
	this.addUnit = addUnit;
	this.refQuantity = refQuantity;
	this.refUnit = refUnit;
	this.deposit = deposit;
	this.price = price;
	this.previousPrice = previousPrice;
	this.weighedGood = false;
	this.weightPerUnit = weightPerUnit;
	this.availabilities = [];
	this.isSpecialOffer = isSpecialOffer;
	this.articleNumber = articleNumber;
	this.deliveredAmount = deliveredAmount;
    this.currentReferencePrice = currentReferencePrice;
	if (isNaN(nmbOfItems) || nmbOfItems == "")
		this.nmbOfItems = 1;
	else
		this.nmbOfItems = nmbOfItems;

	var netUnit = this.unit; 

	if (this.addQuantity) {
		netUnit = this.addUnit;
	}
		
	if (netUnit == this.refUnit)
		factor = 1;		
	else if (netUnit == "g" && this.refUnit == "kg" || netUnit == "ml" && this.refUnit == "l")
		factor = 1000;
	else if (netUnit == "kg" && this.refUnit == "g" || netUnit == "l" && this.refUnit == "ml")
		 factor = 0.001;
	
	this.getRefPrice = function() {		
		if (this.weighedGood == "true") 
			this.privatePrice = this.price; 
		else {
			if (this.addQuantity) {
				this.privatePrice = this.price / (this.addQuantity * this.multiplicator) * this.refQuantity * factor;
			} else {
				this.privatePrice = this.price / (this.quantity * this.multiplicator) * this.refQuantity * factor;
			}
		}
		return this.getFormattedCurrency();
	};
	
	this.getFormattedPrice = function() {
		this.privatePrice = this.price;
		return this.getFormattedCurrency();
	};
	
	this.getFormattedUnitPrice = function() {
		this.privatePrice = this.price * this.nmbOfItems;
		return this.getFormattedCurrency();
	};
	
	this.getFormattedDeposit = function() {
		this.privatePrice = this.deposit * this.nmbOfItems;
		return this.getFormattedCurrency();
	};
	
	this.getFormattedSum = function() {
		// alert("Weighed Good: " + this.weighedGood + " Price: " + this.price + " Items: " + this.nmbOfItems + " Quantity " + this.quantity + " Deposit: " + this.deposit);
	    if (this.weighedGood == "true") 
	    	this.privatePrice = parseInt(this.price) * parseInt(this.nmbOfItems) / parseInt(this.refQuantity) * 1 / factor;
	    else 
	    	if (this.weightPerUnit != 0) 
	    		this.privatePrice = parseFloat(this.price) * parseFloat(this.weightPerUnit) / parseFloat(this.quantity) * parseFloat(this.nmbOfItems);
	    	else {
	    		// alert(this.price + " " + this.deposit + " " + this.nmbOfItems);
				this.privatePrice = (parseInt(this.price) + parseInt(this.deposit)) * parseInt(this.nmbOfItems);
			}
	
		return this.getFormattedCurrency();
	};
	
	this.getFormattedCurrency = function() {
		var formattedPrice = this.privatePrice / 100;	
		return formatZahl(formattedPrice,2,2);
		/* var i = parseFloat(this.privatePrice);
		if(isNaN(i)) { i = 0,00; }
		var minus = '';
		if(i < 0) { minus = '-'; }
		i = Math.abs(i);
		// i = parseInt(i + .005);
		i = Math.round(i);
		i = i / 100;
		s = new String(i);
		if(s.indexOf('.') < 0) { s += '.00'; }
		if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
		s = minus + s;		
		return s; */
	};
}

function Availability(id, name, available) {
	this.spotId = id;
	this.locationName = name;
	this.available = available;
}

/* Rating related functions */
function openPopupWindow(contentId, title) {
	win = new Window({className: "alphacube", width:350, height:250, destroyOnClose: true, recenterAuto: false}); 
	// win.getContent().update(content); 
	win.setTitle(title);
	win.setContent(contentId, false, false);
	// win.setHTMLContent($(contentId));
	// win.setSize(310, 250);
	win.showCenter(true);
}

/* Rating related functions */
function openRatingWindow(productId) {
	win = new Window({className: "alphacube", width:320, height:240, destroyOnClose: true, recenterAuto: false}); 
	win.getContent().update("<table border='0' cellpadding='5' cellspacing='3'><tr><td width='50' class='text'>Bewertung</td><td><img src='../images/16-star-cold.png' id='1' border='0' onmouseover='paintStars(this);' onmouseout='removeStars(this);' onclick='persistRating(this);'>" + 
	"<img src='../images/16-star-cold.png' id='2' border='0' onmouseover='paintStars(this);' onmouseout='removeStars(this);' onclick='persistRating(this);'>"+
	"<img src='../images/16-star-cold.png' id='3' border='0' onmouseover='paintStars(this);' onmouseout='removeStars(this);' onclick='persistRating(this);'>"+
	"<img src='../images/16-star-cold.png' id='4' border='0' onmouseover='paintStars(this);' onmouseout='removeStars(this);' onclick='persistRating(this);'>"+
	"<img src='../images/16-star-cold.png' id='5' border='0' onmouseover='paintStars(this);' onmouseout='removeStars(this);' onclick='persistRating(this);'>"+
	"</td></tr><tr><td colspan='2'>&nbsp;</td></tr><tr><td colspan='2' class='text'>Titel</td></tr><tr><td colspan='2'><input id='commentTitle' type='text' size='45' maxlength='45' value='<Titel>' class='text' onclick='resetField(this);' onfocus='resetField(this);'></td></tr>"+
	"<tr><td colspan='2' class='text'>Ihr Kommentar</td></tr><tr><td colspan='2'><textarea id='commentText' cols='44' rows='5' class='text' onclick='resetField(this);' onfocus='resetField(this);'><Kommentar></textarea></td>"+
	"</td></tr><tr><td colspan='2' class='alert'><span id='commentError'>&nbsp;</span><span id='ratingError'>&nbsp;</span></td></tr>"+
	"<tr><td colspan='2'><input type='button' value='Bewertung hinzuf&uuml;gen' onclick=\"setRating(" + productId + ", gv_rating, $('commentTitle'), $('commentText'));\" class='text'></td></tr></table>");
	win.showCenter();
}

function ajax(url, pars, response) {
	var ajaxRequest = new Ajax.Request (url, {
				method: 'post',
				parameters: pars,
				asynchronous: true,
				onComplete: response });
}

function ajaxSync(url, pars, response) {
	var ajaxRequest = new Ajax.Request (url, {
				method: 'post',
				parameters: pars,
				asynchronous: false,
				onComplete: response });
}

/**
 * Removes all items from shopping cart.
 */
function clearShoppingCart() {
	var shoppingCartItems = jQuery('table#myShoppingCartContentTable tr[id^="shopping_cart_item_"]');
	shoppingCartItems.each(function(index) {
		var itemId = jQuery(this).attr('id').replace(/shopping_cart_item_/g, "");
		removeItemFromShoppingCart(itemId);		
	});
}

function updateShoppingCart(aid, numOfItems) {
	var ratingResponse = function(xmlHttpRequest, json) {
		var res = xmlHttpRequest.responseText;
		var myJson = eval('(' + res + ')');
		/* for (var i = 0; i < myJson.cart.length; i++) {
			alert(myJson.cart[i].name + ", " + myJson.cart[i].id + ", " + myJson.cart[i].quantity);				
		} */
		
		var cartHTML = "<table>";		
		for (var i = 0; i < myJson.cart.length; i++) {
			cartHTML = cartHTML + "<tr><td>" + myJson.cart[i].quantity + "</td><td>" + myJson.cart[i].name + "</td></tr>";
		}
		cartHTML = cartHTML + "</table>";	
		$("cart").innerHTML = cartHTML;
	};
	Windows.closeAll();
	ajax("../updateShoppingCart.servlet.htm", "aid=" + aid + "&numOfItems=" + numOfItems, ratingResponse);
}

function setRating(productId, rating, title, text) {
    //According to FS-358: a product rating should be possible even without typing in a title or comment
    //	if (!validate(title,2,'true','commentError') || !validate(text,2,'true','commentError'))
    //		return false;

	if (rating < 1 || rating > 5) {
		message = "Bitte eine Bewertung über die Sterne vornehmen.";
		displayErrorMessage(ratingError);
		return false;
	}

	var ratingResponse = function(xmlHttpRequest, json) {
		var res = xmlHttpRequest.responseText;
		var myJson = eval('(' + res + ')');
        if (myProduct) {
            myProduct.averageRating = myJson.averageRating;
		    myProduct.ratingCount = myJson.countRating;
        }
	    updateRating(myJson.averageRating, myJson.countRating);
	};
	Windows.closeAll();
	ajax("../rating.servlet.htm", "productId=" + productId + "&rating=" + rating + "&commentTitle=" + title.value + "&commentText=" + text.value, ratingResponse);
//	gv_rating = 0;
}

/* Update rating */
function updateRating(rating, counter, idPrefix, updateConter) {
//	gv_rating = rating;
	var starElement;
    var lv_rating = parseFloat(rating);
    if (updateConter) {
        document.getElementById(idPrefix + "RatingCounter").firstChild.nodeValue = counter;
    }
    if (lv_rating >= .5) {
        starElement = $(idPrefix + "Star1");
        if (starElement != null) {
            starElement.src = "../images/new/icon_star_full.png";
        }
		if (lv_rating >= 1.5) {
            starElement = $(idPrefix + "Star2");
            if (starElement != null) {
                starElement.src = "../images/new/icon_star_full.png";
            }
			if (lv_rating >= 2.5) {
                starElement = $(idPrefix + "Star3");
                if (starElement != null) {
                    starElement.src = "../images/new/icon_star_full.png";
                }
				if (lv_rating >= 3.5) {
                    starElement = $(idPrefix + "Star4");
                    if (starElement != null) {
                        starElement.src = "../images/new/icon_star_full.png";
                    }
					if (lv_rating >= 4.5) {
                        starElement = $(idPrefix + "Star5");
                        if (starElement != null) {
                            starElement.src = "../images/new/icon_star_full.png";
                        }
                    }
					else
                        for (var i = 5; i < 6; i++) {
                            starElement = $(idPrefix + "Star" + i);
                            if (starElement != null) {
                                starElement.src = "../images/new/icon_star_empty.png";
                            }
                        }
				}
				else
                    for (var i = 4; i < 6; i++) {
                        starElement = $(idPrefix + "Star" + i);
                        if (starElement != null) {
                            starElement.src = "../images/new/icon_star_empty.png";
                        }
                    }
            }
			else
                for (var i = 3; i < 6; i++) {
                    starElement = $(idPrefix + "Star" + i);
                    if (starElement != null) {
                        starElement.src = "../images/new/icon_star_empty.png";
                    }
                }
		}
		else 
			for (var i = 2; i < 6; i++) {
                starElement = $(idPrefix + "Star" + i);
                if (starElement != null) {
                    starElement.src = "../images/new/icon_star_empty.png";
                }
            }
	}
	else 
		for (var i = 1; i < 6; i++) {
            starElement = $(idPrefix + "Star" + i);
            if (starElement != null) {
                starElement.src = "../images/new/icon_star_empty.png";
            }
        }
}

function paintStars(elem) {
	var rating = 0;
    for (var i=1; i <= 5; i++) {
		if (i <= elem.id){
			document.getElementById(i).src = "../images/new/icon_star_full.png";
            rating = i;
        }
		else
			document.getElementById(i).src = "../images/new/icon_star_empty.png";
	}
    document.getElementById("userProductRatingCounterInPopup").firstChild.nodeValue = rating;
}

function persistRating(elem) {
	gv_rating = elem.id;
	persisted = true;
	resetField($("commentTitle"));
	resetField($("commentText"));
    document.getElementById("userProductRatingCounterInPopup").firstChild.nodeValue = elem.id;
}

function resetField(obj) {
	obj.value = "";
	obj.style.color = "black";
	reset = true;
}

function removeStars(elem) {
	if (!persisted)
		for (i=1; i <= 5; i++) 
			if (i <= elem.id)
				document.getElementById(i).src = "../images/new/icon_star_empty.png";
	persisted = false;
    document.getElementById("userProductRatingCounterInPopup").firstChild.nodeValue = 0;
}

/* End rating functions */

/* Growl functions */

function addGrowlMessage(headline, description, lifetime) {
	if (lifetime == undefined) {
		lifetime = 10000;
	}
	if (headline != null && headline != undefined) {
		jQuery.jGrowl(unescape(description), { header: unescape(headline), life: lifetime });
	} else {
		jQuery.jGrowl(unescape(description), { life: lifetime });
	}
}

/* End growl functions */

/* Feedback functions */

function receivedFeedbackWindow(usr) {	
	win = new Window({className: "alphacube", title: "Feedback", width:300, height:300, destroyOnClose: true, recenterAuto: false}); 	
	
	var table = document.createElement("table");
	table.setAttribute("id", "feedback_table");
	table.setAttribute("cellspacing", "9");
	var tbody = document.createElement("tbody");
	tbody.setAttribute("id", "tbody_feedback");
	var row_1 = document.createElement("tr");
	
	var cell_1 = document.createElement("td");
	var img = document.createElement("img");
    img.src = "../images/new/Livia.png";
    img.width = 70;
    cell_1.appendChild(img);
    row_1.appendChild(cell_1);
	
	var cell_2 = document.createElement("td");
	cell_2.setAttribute("class", "text");
	var thanks_text1 = document.createTextNode("Vielen Dank für Ihre Hilfe froodies noch besser zu machen!");
	cell_2.appendChild(thanks_text1);
	var linebreak1 = document.createElement("br");
	cell_2.appendChild(linebreak1);
	var linebreak2 = document.createElement("br");
	cell_2.appendChild(linebreak2);
	var thanks_text2 = document.createTextNode("Ihr Feedback wird von unserem Kundenservice verarbeitet.");
	cell_2.appendChild(thanks_text2);	
	row_1.appendChild(cell_2);
	tbody.appendChild(row_1);
	
	var row_2 = document.createElement("tr");
	var cell_3 = document.createElement("td");
	cell_3.setAttribute("colspan", "2");
	var submit_link = document.createElement("a");
	submit_link.setAttribute("class", "linkLevel1");
	submit_link.setAttribute("id", "submit_link");
	submit_link.setAttribute("href", "javascript: Windows.closeAll()");
	var link_text = document.createTextNode("Fenster schließen");
	submit_link.appendChild(link_text);
	cell_3.appendChild(submit_link);
	row_2.appendChild(cell_3);
	tbody.appendChild(row_2);
	
	table.appendChild(tbody);
	win.getContent().appendChild(table);	
	win.showCenter(true);	
	win.setSize(310, 130);
}

function openFeedbackWindow(usr) {
	win = new Window({className: "alphacube", title: "Feedback", width:300, height:300, destroyOnClose: true, recenterAuto: false}); 	

	var table = document.createElement("table");
	table.setAttribute("id", "feedback_table");
	table.setAttribute("cellspacing", "9");
	var tbody = document.createElement("tbody");
	tbody.setAttribute("id", "tbody_feedback");
	var row_1 = document.createElement("tr");
	var cell_1 = document.createElement("td");
	cell_1.setAttribute("class", "text");
	
	var error_text = document.createTextNode("Was möchten Sie uns mitteilen?");
	cell_1.appendChild(error_text);
	row_1.appendChild(cell_1);
	tbody.appendChild(row_1);
	
	var row_2 = document.createElement("tr");
	var cell_2 = document.createElement("td"); 
	
	var select_type = document.createElement("select");
    select_type.setAttribute("id", "type");
    select_type.setAttribute("class", "text");
    select_type.setAttribute("style", "width: 290px");
	select_type.onchange = function() {updateFeedbackWindow(); };

    var blank_type_option = document.createElement("option");
    blank_type_option.setAttribute("value", "blank_type");
    var blank_type_label = document.createTextNode("");
    blank_type_option.appendChild(blank_type_label);
    
    var error_option = document.createElement("option");
    error_option.setAttribute("value", "0");
    var error_label = document.createTextNode("Ich möchte einen Fehler melden:");
    error_option.appendChild(error_label);

    var product_option = document.createElement("option");
    product_option.setAttribute("value", "1");
    var product_label = document.createTextNode("Ich vermisse folgende(s) Produkt(e):");
    product_option.appendChild(product_label);
    
    var feedback_option = document.createElement("option");
    feedback_option.setAttribute("value", "2");
    var feedback_label = document.createTextNode("Ich möchte folgendes Feedback geben:");
    feedback_option.appendChild(feedback_label);

 	select_type.appendChild(blank_type_option); 
    select_type.appendChild(error_option);
    select_type.appendChild(product_option);
    select_type.appendChild(feedback_option);
 
	cell_2.appendChild(select_type);
	row_2.appendChild(cell_2);
	tbody.appendChild(row_2);
   
	var row_5 = document.createElement("tr");
	row_5.setAttribute("id", "row_5");
	var cell_5 = document.createElement("td");
	cell_5.setAttribute("class", "text");

	var text = document.createTextNode("Ihr Text:");
	cell_5.appendChild(text);
	row_5.appendChild(cell_5);
	tbody.appendChild(row_5);
	
	var row_6 = document.createElement("tr");
	var cell_6 = document.createElement("td"); 

	var textarea = document.createElement("textarea");
    textarea.setAttribute("id", "feedbackTxt");
    textarea.setAttribute("name", "feedbackTxt");
    textarea.setAttribute("cols", "40");
    textarea.setAttribute("rows", "7");
    textarea.setAttribute("class", "text");
    textarea.setAttribute("style", "width: 290px");
    textarea.setAttribute("onfocus", "enterField($('feedbackTxt_error'))");
    
	cell_6.appendChild(textarea);
	row_6.appendChild(cell_6);
	tbody.appendChild(row_6);

	if (usr == undefined || usr == "") {
		
		var row_7 = document.createElement("tr");
		row_7.setAttribute("id", "row_7");
		var cell_7 = document.createElement("td");
		cell_7.setAttribute("class", "text");
	
		var text = document.createTextNode("Ihre E-Mailadresse:");
		cell_7.appendChild(text);
		row_7.appendChild(cell_7);
		tbody.appendChild(row_7);

		var row_8 = document.createElement("tr");
		var cell_8 = document.createElement("td"); 
	
		var input = document.createElement("input");
	    input.setAttribute("id", "email");
	    input.setAttribute("name", "email");
	    input.setAttribute("type", "text");
	    input.setAttribute("class", "text");
	    input.setAttribute("style", "width: 290px");
	    input.setAttribute("size", "40");
	    input.setAttribute("onfocus", "enterField($('email_error'))");
	   
		cell_8.appendChild(input);
		row_8.appendChild(cell_8);
		tbody.appendChild(row_8);
		
		var row_9 = document.createElement("tr");
		var cell_9 = document.createElement("td"); 
	
		var span = document.createElement("span");
	    span.setAttribute("id", "text_error");
	    span.setAttribute("class", "red8pt");
	    var error_label = document.createTextNode(" ");
	    span.appendChild(error_label);
	
		cell_9.appendChild(span);
		row_9.appendChild(cell_9);
		tbody.appendChild(row_9);
		
		win.setSize(310, 300);
	}
	else {win.setSize(310, 240);}
	
	var row_10 = document.createElement("tr");
	var cell_10 = document.createElement("td");
	var submit_link = document.createElement("a");
	submit_link.setAttribute("class", "linkLevel1");
	submit_link.setAttribute("id", "submit_link");
	// submit_link.setAttribute("href", "javascript: sendFeedback($('type').options[$('type').selectedIndex].value, $('page').options[$('page').selectedIndex].value, $('text').value)");

	if (usr != undefined && usr != "") 
		submit_link.setAttribute("href", "javascript: sendFeedback()");
	else 
	   submit_link.setAttribute("href", "javascript: sendFeedbackMail()");
   
	var link_text = document.createTextNode("Feedback abschicken");
	submit_link.appendChild(link_text);
	
	cell_10.appendChild(submit_link);
	row_10.appendChild(cell_10);
	tbody.appendChild(row_10);
	table.appendChild(tbody);
	
	win.getContent().appendChild(table);	
	// win.setLocation(95, 750);
	win.showCenter(true);	
	// win.toFront();
}

function sendFeedbackMail() {
	var queryString = "";
	var page = "";
	
	var type = $("type").options[$("type").selectedIndex].value;
	if ($("type").options[$("type").selectedIndex].value == "error")
		var page = $("page").options[$("page").selectedIndex].value;
	
	var text = $("feedbackTxt").value.replace("&","&amp;").replace("<","&lt;").replace(">","&gt;");
	var email = $("email").value;

	var ratingResponse = function(xmlHttpRequest, json) {
		var res = xmlHttpRequest.responseText;
		var myJson = eval('(' + res + ')');
		$("messageBoard").value = myJson.message;
	};

	var url = "../feedback.mail.servlet.htm";
	queryString += "type=" + encodeURIComponent(type) + "&";
    queryString += "page=" + encodeURIComponent(page) + "&";
    queryString += "email=" + encodeURIComponent(email) + "&";
    queryString += "text=" + encodeURIComponent(text);
    Windows.closeAll();
	ajax(url, queryString, ratingResponse);	
		
	receivedFeedbackWindow();
}

function updateFeedbackWindow() {
	
	/* This part is optional and depends on first dropdown */
	
	var row_3 = document.createElement("tr");
	row_3.setAttribute("id", "row_3");
	var cell_3 = document.createElement("td");
	cell_3.setAttribute("class", "text");

	var page_text = document.createTextNode("Wo ist der Fehler aufgetreten?");
	cell_3.appendChild(page_text);
	row_3.appendChild(cell_3);
	
	var row_4 = document.createElement("tr");
	row_4.setAttribute("id", "row_4");
	var cell_4 = document.createElement("td"); 
	
	var select_page = document.createElement("select");
    select_page.setAttribute("id", "page");
    select_page.setAttribute("class", "text");
    
    var product_page_option = document.createElement("option");
    product_page_option.setAttribute("value", "0");
    var product_page_label = document.createTextNode("Auf der Produktseite");
    product_page_option.appendChild(product_page_label);
    
    var product_overview_option = document.createElement("option");
    product_overview_option.setAttribute("value", "1");
    var product_overview_label = document.createTextNode("Auf der Produktübersicht");
    product_overview_option.appendChild(product_overview_label);
    
    var category_option = document.createElement("option");
    category_option.setAttribute("value", "2");
    var category_label = document.createTextNode("Auf der Kategorieübersicht");
    category_option.appendChild(category_label);
    
    var checkout_option = document.createElement("option");
    checkout_option.setAttribute("value", "3");
    var checkout_label = document.createTextNode("Beim Auschecken der Bestellung");
    checkout_option.appendChild(checkout_label);
 
    select_page.appendChild(product_page_option);
    select_page.appendChild(product_overview_option);
    select_page.appendChild(category_option);
    select_page.appendChild(checkout_option);
 
	cell_4.appendChild(select_page);
	row_4.appendChild(cell_4);
	
	/* End of optional part */
	
	if ($("type").options[$("type").selectedIndex].value == "0") {
		$("tbody_feedback").insertBefore(row_3, $("row_5"));
		$("tbody_feedback").insertBefore(row_4, $("row_5"));
		win.setSize(310, 350);
	}
	else {
		$("tbody_feedback").removeChild($("row_3"));
		$("tbody_feedback").removeChild($("row_4"));
		win.setSize(310, 300);
	}
		

}

function sendFeedback() {
	var queryString = "";
	var page = "";
	
	var type = $("type").options[$("type").selectedIndex].value;
	if ($("type").options[$("type").selectedIndex].value == "error")
		var page = $("page").options[$("page").selectedIndex].value;
	
	var text = $("feedbackTxt").value.replace("&","&amp;").replace("<","&lt;").replace(">","&gt;");

	var ratingResponse = function(xmlHttpRequest, json) {
		var res = xmlHttpRequest.responseText;
		var myJson = eval('(' + res + ')');
		$("messageBoard").value = myJson.message;
		// myProduct.averageRating = myJson.averageRating;
		// myProduct.ratingCount = myJson.countRating;	
	    // updateRating(myProduct.averageRating, myProduct.ratingCount);	
	};
	
//	if (validate($("text"),2,"true","messageBoard")) {
		var url = "../feedback.servlet.htm";
		queryString += "type=" + encodeURIComponent(type) + "&";
	    queryString += "page=" + encodeURIComponent(page) + "&";
	    queryString += "text=" + encodeURIComponent(text);
		ajax(url, queryString, ratingResponse);	
//	}
//	else {
//		Windows.closeAll();
//	}
	receivedFeedbackWindow();
}

function switchArticle (p_id, a_id, spot_id) {
	var field = "field_availability";
	var queryString = "";
	
	var ratingResponse = function(xmlHttpRequest, json) {
		var res = xmlHttpRequest.responseText;
		var myJson = eval('(' + res + ')');	
		
		if ($("messageBoard")) {
			/* if (!$("messageBoard").hasChildNodes()) {
				if (myJson.status == "nv") {
					var textNode = document.createTextNode("Der Artikel wurde auf nicht verfügbar gesetzt.");
					document.getElementById("availability_" + spot_id).firstChild.nodeValue = "Auf verfügbar setzen";	
				}	
				else {				
					var textNode = document.createTextNode("Der Artikel wurde auf verfügbar gesetzt.");
					document.getElementById("availability_" + spot_id).firstChild.nodeValue = "Auf nicht verfügbar setzen";
				}
				$("messageBoard").appendChild(textNode);
			}
			else { 
				if (myJson.status == "nv") {			
					$("messageBoard").firstChild.nodeValue = "Der Artikel wurde auf nicht verfügbar gesetzt.";
					document.getElementById("availability_" + spot_id).firstChild.nodeValue = "Auf verfügbar setzen";
				}
				else {
					$("messageBoard").firstChild.nodeValue = "Der Artikel wurde auf verfügbar gesetzt.";
					document.getElementById("availability_" + spot_id).firstChild.nodeValue = "Auf nicht verfügbar setzen";
				}
			} */
			location.reload();
		}
		else {
			if (myJson.status == "nv") {
				$("availability_" + a_id + "_" + spot_id).className = "redText";	
				$("availability_" + a_id + "_" + spot_id).firstChild.nodeValue = "nicht lieferbar";
			}
			else {
				$("availability_" + a_id + "_" + spot_id).className = "text";
				$("availability_" + a_id + "_" + spot_id).firstChild.nodeValue = "lieferbar";
			}
			if (myJson.message == "success") 
				document.images["product_status_" + a_id].src = "../images/froodies_success.gif";
			else
				document.images["product_status_" + a_id].src = "../images/froodies_loeschen.gif";
		}
	};
	var url = "../admin/productchange.servlet.htm";
	queryString += "field=" + encodeURIComponent(field) + "&";
    queryString += "a_id=" + encodeURIComponent(a_id) + "&";
    queryString += "p_id=" + encodeURIComponent(p_id) + "&";
    queryString += "spot_id=" + encodeURIComponent(spot_id);
	ajax(url, queryString, ratingResponse);	
}

/* End feedback functions */
function saveProductChange(id, p_id, a_id) {
	var obj = document.getElementById(id);
	var inputNode = obj;
	while (inputNode.tagName != "INPUT" && inputNode.tagName != "SELECT") 
		inputNode = inputNode.firstChild;

	var field = inputNode.id;
	var value = inputNode.value;
	
	/* assign p_id to a_id in order to set status correctly in ui */
	if (a_id == 0)
		a_id = p_id;
	
	var splitField = field.split("_");
	
	if (splitField[1] == "brand" || splitField[1] == "productName" || splitField[1] == "shortDescription" || splitField[1] == "unit" || splitField[1] == "addUnit" || splitField[1] == "refUnit" || 
		splitField[1] == "country" || splitField[1] == "articleimage" ) {
		if (!validate(inputNode,2,"true")) {
			document.images["product_status_" + a_id].src = "../images/froodies_loeschen.gif";
			undoEditText(id, false);
			return void(0);		
		}
	}

	if (splitField[1] == "quantity" || splitField[1] == "addQuantity" || splitField[1] == "refQuantity" || splitField[1] == "purchasePrice" || splitField[1] == "unitPrice" || splitField[1] == "weightPerUnit" || 
		splitField[1] == "artnr" || splitField[1] == "lnr" || splitField[1] == "min" || splitField[1] == "max" || splitField[1] == "crit" || splitField[1] == "multi" || splitField[1] == "attr") {
		if (!validate(inputNode,1,"true")) {
			document.images["product_status_" + a_id].src = "../images/froodies_loeschen.gif";
			undoEditText(id, false);
			return void(0);		
		}
	}
	
	if (splitField[1] == "bias" ) {
		if (!validate(inputNode,16,"true")) {
			document.images["product_status_" + a_id].src = "../images/froodies_loeschen.gif";
			undoEditText(id, false);
			return void(0);		
		}
	}
	
	
	if (splitField[1] == "ean" ) {
		if (!validate(inputNode,10,"false")) {
			document.images["product_status_" + a_id].src = "../images/froodies_loeschen.gif";
			undoEditText(id, false);
			return void(0);		
		}
	}	
	
	var queryString = "";

	var ratingResponse = function(xmlHttpRequest, json) {
		var res = xmlHttpRequest.responseText;
		var myJson = eval('(' + res + ')');
		
		if ($("messageBoard")) {
			if (!$("messageBoard").hasChildNodes()) {
				if (myJson.message == "success")
					var textNode = document.createTextNode("Die Produktdaten wurde erfolgreich geändert.");
				else
					var textNode = document.createTextNode("Beim Ändern der Produktdaten ist ein Fehler aufgetreten.");	
				$("messageBoard").appendChild(textNode);			
			}
			else {
				if (myJson.message == "success")
					$("messageBoard").firstChild.nodeValue = "Die Produktdaten wurde erfolgreich geändert.";
				else
					$("messageBoard").firstChild.nodeValue = "Beim Ändern der Produktdaten ist ein Fehler aufgetreten.";
			}
		}
		else {
			if (myJson.message == "success") 
				document.images["product_status_" + a_id].src = "../images/froodies_success.gif";	
			else							
				document.images["product_status_" + a_id].src = "../images/froodies_loeschen.gif";	
		} 	
	};
	
	var url = "../admin/productchange.servlet.htm";
	queryString += "field=" + encodeURIComponent(field) + "&";
    queryString += "value=" + encodeURIComponent(value) + "&";
    queryString += "a_id=" + encodeURIComponent(a_id) + "&";
    queryString += "p_id=" + encodeURIComponent(p_id);
    if (inputNode.tagName == "INPUT") {
    	undoEditText(obj.id, true);
    }
	ajax(url, queryString, ratingResponse);
}

function ajaxSaveWeighedGood(field, value, a_id, p_id, state) {
	var queryString = "";

	var ratingResponse = function(xmlHttpRequest, json) {
		var res = xmlHttpRequest.responseText;
		var myJson = eval('(' + res + ')');
		
		if ($("messageBoard")) {
			if (!$("messageBoard").hasChildNodes()) {
				if (myJson.message == "success")
					var textNode = document.createTextNode("Die Produktdaten wurde erfolgreich geändert.");
				else
					var textNode = document.createTextNode("Beim Ändern der Produktdaten ist ein Fehler aufgetreten.");	
				$("messageBoard").appendChild(textNode);			
			}
			else {
				if (myJson.message == "success")
					$("messageBoard").firstChild.nodeValue = "Die Produktdaten wurde erfolgreich geändert.";
				else
					$("messageBoard").firstChild.nodeValue = "Beim Ändern der Produktdaten ist ein Fehler aufgetreten.";
			}
		}
		else {
			if (myJson.message == "success") 
				document.images["product_status_" + a_id].src = "../images/froodies_success.gif";	
			else							
				document.images["product_status_" + a_id].src = "../images/froodies_loeschen.gif";	
		} 	
	};
	
	var url = "../admin/productchange.servlet.htm";
	queryString += "field=" + encodeURIComponent(field) + "&";
    queryString += "value=" + encodeURIComponent(value) + "&";
    queryString += "p_id=" + encodeURIComponent(p_id) + "&";    
    queryString += "a_id=" + encodeURIComponent(a_id) + "&";
    queryString += "state=" + encodeURIComponent(state); 
    // alert(queryString);
	ajax(url, queryString, ratingResponse);
}

function toggle(elem) {
	var obj = document.getElementById(elem);
	if (obj.style.display == "block")
		obj.style.display = "none";
	else
		obj.style.display = "block";
}

function toggleObj(obj) {
	if (obj.style.display == "block")
		obj.style.display = "none";
	else
		obj.style.display = "block";
}


/* Ajax features */
function sendData() {
	var indicator = document.getElementById("indicator");
	indicator.style.display = "block";
	setQueryString();
	var url = "../feedback.servlet.htm";
	httpRequest("POST", url, true);
}

/* Create query string */
function setQueryString() {
	queryString = "";
	var product = document.getElementById("product");
	var type = document.getElementById("typeOfFeedback");	
	var text = document.getElementById("feedbackText");
	if (product.value != "")
		queryString += product.name + "=" + encodeURIComponent(product.value) + "&";
    	queryString += type.name + "=" + encodeURIComponent(type.value) + "&";
    	queryString += text.name + "=" + encodeURIComponent(text.value);
}

/* Event handler for XMLHttpRequest */
function handleResponse() {
	var indicator = document.getElementById("indicator");
	var bubble = document.getElementById("bubble");
	try {
		if (request.readyState == 4) {
			if (request.status == 200) {
				var resp = request.responseText;
				var product = document.getElementById("product");
				indicator.style.display = "none";
				bubble.src = "../images/bubble_blue.png";
			}
			else {
				alert("A problem occured with communicating between XMLHttpRequest object and the server.");
			}
		}			
	} catch (err) {
		alert ("It does not appear that the server is available: " + err.message);
	}
}

/* Initialize a request object that is already constructed */
function initReq(reqType, url, isAsynch) {
	try {
		request.onreadystatechange = handleResponse;
		request.open(reqType, url, isAsynch);
		request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		request.send(queryString);
	} catch (errv) {
		alert("The application cannot contact the server.");
	}
}

function httpRequest(reqType, url, asynch) {
	if (window.XMLHttpRequest) {
		request = new XMLHttpRequest();
	}
	else if (window.ActiveXObject) {
		request = new ActiveXObject("Msxml2.XMLHTTP");
		if (!request) {
			request = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	if (request) {
		initReq(reqType, url, asynch);
	}
	else {
		alert("Your browser does not permit the use of all of this application's features!");
	}
}

/* Format a float */
/* zahl: the number */
/* k: */
/* fix: */
function formatZahl(zahl, k, fix) {
	if(!k) k = 0;
	var neu = '';
	    
	// Nachkommastellen
	var f = Math.pow(10, k);
	zahl = '' + parseInt( zahl * f + .5) / f;
	var idx = zahl.indexOf('.');
	if ( idx == -1) {
	    idx = zahl.length;
	    neu = ',00';
	}
	else 
		neu = ',' + zahl.substring(idx + 1);
		
	// fehlende Nullen einf?gen
	if(fix)
		for(var i = neu.length - 1; i < k; i++)
	    	neu = neu + '0';
	    while(idx > 0) {
	    	if(idx - 3 > 0)
	       		neu = '.' + zahl.substring( idx - 3, idx) + neu;
	  	    else
	        	neu = zahl.substring(0, idx) + neu;
	        
	        idx -= 3;
	    }
	return neu;
}

function IsImageOk(img) {
    // During the onload event, IE correctly identifies any images that
    // weren't downloaded as not complete. Others should too. Gecko-based
    // browsers act like NS4 in that they report this incorrectly.
    if (!img.complete) {
        return false;
    }

    // However, they do have two very useful properties: naturalWidth and
    // naturalHeight. These give the true size of the image. If it failed
    // to load, either of these should be zero.
    if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
        return false;
    }

    // No other way of checking: assume it's ok.
    return true;
}

function imageCheck() {
	for (var i = 0; i < document.images.length; i++) 
		if (!IsImageOk(document.images[i]) && !blackList(document.images[i].id)) {
			document.images[i].src = '/FroodiesImages/images/products/keinBild.gif';
		}		 
}

function imageNewCheck() {
	for (var i = 0; i < document.images.length; i++)
		if (!IsImageOk(document.images[i]) && !blackList(document.images[i].id)) {
			document.images[i].src = '../images/new/img_placeholder.png';
            document.images[i].removeAttribute('width');
            document.images[i].removeAttribute('height');
		}
}

/* this list contains images which shouldn't be replaced by the default image */
function blackList(id) {
	if (id == 'couponImage') {
		return true;
	} else if (id.startsWith('banner')) {
		/** blacklist all banners on categories view **/
		return true;
	}
	return false;
}

function showFrame(obj) { 
   if (obj.firstChild.id != "editTable") 
      obj.style.backgroundColor = "#ccff99";
	//obj.style.border = "1px solid #CCFF99";
}

function hideFrame(obj, color) {
	if (obj.firstChild.id != "editTable") 
		if (color)   
	    	obj.style.backgroundColor = color;
	    else
	    	obj.style.backgroundColor = "#ffffff";	
}

function undoEditText(id, changed) {
    var obj = document.getElementById(id);
	var inputNode = obj;
	while (inputNode.tagName != "INPUT") 
		inputNode = inputNode.firstChild;
	
	while (obj.hasChildNodes()) 
		obj.removeChild(obj.firstChild);

	if (changed)
		var textNode = document.createTextNode(inputNode.value);
	else 
		var textNode = document.createTextNode(oldTextValue);
		
	obj.appendChild(textNode);
}

/* This method will be called when a field is edited by an admin on the product page.
   It's a wrapper for the method editText() */
function editTextOnProductPage(obj, p_id) {
	editText(obj, p_id, myProduct.articles[myProduct.index].id);
}

function editText(obj, p_id, a_id) {
	obj.style.backgroundColor = "#ffffff";
	
	if (obj.firstChild.tagName != "TABLE") {
		var textNode = obj.removeChild(obj.firstChild);
	
		var table = document.createElement("table");
		table.setAttribute("id", "editTable");
		table.setAttribute("border", "0");
		var cellpadding = document.createAttribute("cellpadding");
		cellpadding.value = "5";
		table.setAttributeNode(cellpadding);
	
		var tbody = document.createElement("tbody");
		var row_1 = document.createElement("tr");
		var cell_1 = document.createElement("td");
		var colspan = document.createAttribute("colspan");
		colspan.value = "2";
		cell_1.setAttributeNode(colspan);
		
		var input = document.createElement("input");
	    input.setAttribute("type", "text");
	    input.setAttribute("id", "field_" + obj.id);
	    input.setAttribute("name", obj.id);
	    input.setAttribute("value", textNode.nodeValue);
	    input.setAttribute("onkeypress", "if (event.keyCode == 13) saveProductChange('" + obj.id + "', '" + p_id + "', '" + a_id + "')");
	    input.style.backgroundColor = "#CCFF99";
	    
	    oldTextValue = textNode.nodeValue;
	    
	    cell_1.appendChild(input);	
		row_1.appendChild(cell_1);		

		var row_2 = document.createElement("tr");
		var cell_2 = document.createElement("td");

	    var submit_link = document.createElement("a");
	    
	    /* Fix for product page */
	    // submit_link.setAttribute("href", "#");
	    submit_link.setAttribute("href", "javascript: saveProductChange('" + obj.id + "', '" + p_id + "', '" + a_id + "');");
	    // submit_link.setAttribute("onclick", "saveProductChange('" + obj.id + "', '" + p_id + "', '" + a_id + "');");
	    
		submit_link.setAttribute("class", "linkLevel1");
		submit_link.setAttribute("id", "submit_link"); 
		var link_text = document.createTextNode("Speichern");
		submit_link.appendChild(link_text);
		
	    cell_2.appendChild(submit_link);
	    
		var row_3 = document.createElement("tr");
		var cell_3 = document.createElement("td");    
	    var close_link = document.createElement("a");
	    close_link.setAttribute("href", "javascript: undoEditText('" + obj.id + "', true);");
		close_link.setAttribute("class", "linkLevel1");
		close_link.setAttribute("id", "close_link");	 
		var close_text = document.createTextNode("Schliessen");
		close_link.appendChild(close_text);					
		cell_3.appendChild(close_link);

		row_2.appendChild(cell_2);
		row_2.appendChild(cell_3);		
		
		tbody.appendChild(row_1);
		tbody.appendChild(row_2);
		
		table.appendChild(tbody);
		
		obj.appendChild(table);
		
		var inputNode = obj;
		while (inputNode.tagName != "INPUT") 
			inputNode = inputNode.firstChild;
			
		inputNode.focus();
	}
}

function editUserControl(obj,userid,changeButtonId) {
	obj.style.backgroundColor = "#ffffff";	
	$(changeButtonId).style.display = 'none';
	
	if (obj.firstChild.tagName != "TABLE") {
		var textNode = obj.removeChild(obj.firstChild);
	
		var table = document.createElement("table");
		table.setAttribute("id", "editTable");
		table.setAttribute("border", "0");
		var cellpadding = document.createAttribute("cellpadding");
		cellpadding.value = "2";
		table.setAttributeNode(cellpadding);
	
		var tbody = document.createElement("tbody");
		var row_1 = document.createElement("tr");
		var cell_1 = document.createElement("td");
		var colspan = document.createAttribute("colspan");
		colspan.value = "2";
		cell_1.setAttributeNode(colspan);

		var input = document.createElement("input");
	    input.setAttribute("type", "text");
	    input.setAttribute("id", obj.id);
	    input.setAttribute("name", obj.id);
	    input.setAttribute("value", textNode.nodeValue);
	    input.setAttribute("onkeypress", "if (event.keyCode == 13) updateUser('" + obj.id + "','" + userid + "','" + changeButtonId + "')");
	    input.style.backgroundColor = "#CCFF99";
	    
	    oldTextValue = textNode.nodeValue;
	    
	    cell_1.appendChild(input);	
		row_1.appendChild(cell_1);		

		var cell_2 = document.createElement("td");

	    var submitButton = document.createElement("input");
	    
		submitButton.setAttribute("type", "button");
		submitButton.setAttribute("id", "submitButton");
		submitButton.setAttribute("value", "speichern");
	    submitButton.setAttribute("onclick", "updateUser('" + obj.id + "','" + userid + "','" + changeButtonId + "')");
		
	    cell_2.appendChild(submitButton);
	    
		var cell_3 = document.createElement("td");    
	    var closeButton = document.createElement("input");
	    closeButton.setAttribute("value", "schliessen");
		closeButton.setAttribute("type", "button");
		closeButton.setAttribute("id", "closeButton");	
		closeButton.setAttribute("onclick", "javascript: hideEditControl('" + obj.id + "','" + changeButtonId + "');");
		cell_3.appendChild(closeButton);

		row_1.appendChild(cell_2);
		row_1.appendChild(cell_3);		
		
		tbody.appendChild(row_1);
		
		table.appendChild(tbody);
		
		obj.appendChild(table);
		
		var inputNode = obj;
		while (inputNode.tagName != "INPUT") 
			inputNode = inputNode.firstChild;
			
		inputNode.focus();
	}
}

/* Update user data */
function updateUser(id, userid, changeButtonId) {
	var fieldNode = $(id);
	while (fieldNode.tagName != "INPUT") 
		fieldNode = fieldNode.firstChild;
	
	var queryString = "";

	var ratingResponse = function(xmlHttpRequest, json) {
		var res = xmlHttpRequest.responseText;
		var myJson = eval('(' + res + ')');
		
		if ($("messageBoard")) {
			if (myJson.message != "success") {
				var textNode = document.createTextNode(myJson.message);	
				$("messageBoard").appendChild(textNode);
				$("messageBoard").style.display = 'block';
			}
			else {			
				$('editTable').remove();			
				var textNode = document.createTextNode(myJson.text);
				$('emailAddress').appendChild(textNode);
				$('emailChangeButton').style.display = 'inline';		
			}
		}
	};
	
	var url = "../admin/updateuser.servlet.htm";
	queryString += "field=" + encodeURIComponent(fieldNode.id) + "&";
    queryString += "value=" + encodeURIComponent(fieldNode.value) + "&";
    queryString += "userid=" + encodeURIComponent(userid);
    // undoEditText(obj.id, true); 
	ajax(url, queryString, ratingResponse);
}

function hideEditControl(id, changeButtonId) {
    // remove input field and replace by text node
	var inputNode = $(id);
	while (inputNode.tagName != "INPUT") 
		inputNode = inputNode.firstChild;
	
	$('editTable').remove();
	
	var textNode = document.createTextNode(inputNode.value);
	$(id).appendChild(textNode);
	$(changeButtonId).style.display = 'inline';
}

/* Shopping lists */
function createShoppingList() {
	win = new Window({className: "alphacube", width:250, height:200, destroyOnClose: true, recenterAuto: false}); 
	win.getContent().update("<table border='0' cellpadding='5' cellspacing='3'>" + 
	"<tr><td class='text'>Titel</td></tr><tr><td colspan='2'><input id='shoppingListTitle' type='text' size='30' maxlength='30' value='Titel des Merkzettels' class='grey' onclick='this.value = \"\"; this.style.color=\"black\";'></td></tr>" +
	"<tr><td class='text'>Beschreibung</td></tr><tr><td colspan='2'><textarea id='shoppingListDescription' cols='29' rows='5' class='grey' onclick='this.value = \"\"; this.style.color=\"black\";'>Beschreibung des Merkzettels</textarea></td>" +
	"</td></tr><tr><td colspan='2' class='alert'><span id=\"listTitleError\">&nbsp;</span><span id=\"listDescriptionError\">&nbsp;</span></td></tr><tr><td colspan='2'><input type='button' value='Merkzettel hinzufügen' onclick='javascript: if (!validateShoppingList()) return false; else { $(\"title\").value = $(\"shoppingListTitle\").value;$(\"description\").value = $(\"shoppingListDescription\").value; document.addCartToShoppingListForm.submit(); }'></td></tr></table>"); 
	win.showCenter();
}
function addToShoppingList(articleid, amount) {
	win = new Window({className:"alphacube",width:250,height:220,destroyOnClose:true,recenterAuto:false}); 
	var content = "<div id='newShoppingList' style='display: none;'><table border='0' cellpadding='5' cellspacing='3'><tr><td><span id='notesListLink' style='display: block;'><a href='javascript: showChooseShoppingList();' class='linkLevel1'>Merkzettel auswählen</a></span></td></tr>" + 
	"<tr><td class='alert'>&nbsp;</td></tr><tr><td class='text'>Titel</td></tr><tr><td colspan='2'><input id='shoppingListTitle' type='text' size='30' maxlength='30' value='Titel des Merkzettels' class='grey' onclick='this.value = \"\"; this.style.color=\"black\";'></td></tr>" +
	"<tr><td class='text'>Beschreibung</td></tr><tr><td colspan='2'><textarea id='shoppingListDescription' cols='29' rows='5' class='grey' onfocus='this.firstChild.nodeValue = \"\"; this.style.color=\"black\";'>Beschreibung des Merkzettels</textarea></td>" +
	"</td></tr><tr><td colspan='2' class='alert'><span id=\"listTitleError\">&nbsp;</span><span id=\"listDescriptionError\">&nbsp;</span></td></tr><tr><td colspan='2'><input type='button' value='Merkzettel anlegen' onclick='javascript: if (!validateShoppingList()) return false; else {$(\"amount\").value = " + amount + "; $(\"articleListId\").value = " + articleid + "; $(\"sl_title\").value = $(\"shoppingListTitle\").value; $(\"sl_description\").value = $(\"shoppingListDescription\").value; document.addArticleToShoppingListForm.submit(); }'></td></tr></table></div>";
	if (myShoppingLists.length > 0) {
		content = content + "<div id='selectShoppingList' style='display: block;'><table><tr><td><a href='javascript: showCreateShoppingList();' class='linkLevel1'>Neuen Merkzettel anlegen</a></td></tr>" +
		"<tr><td class='alert'>&nbsp;</td></tr><tr><td><select name='shoppingListId' id='shoppingListId'>";
		
		for (var i = 0; i < myShoppingLists.length; i++) 
			content = content + "<option value='" + myShoppingLists[i].id + "'>" + myShoppingLists[i].name + "</option>";	
		
		content = content + "</select></td></tr>" +
		"<tr><td class='alert'>&nbsp;</td></tr><tr><td><input type='button' value='Artikel hinzufügen' onclick='$(\"amount\").value = " + amount + "; $(\"articleListId\").value = " + articleid + "; document.addArticleToShoppingListForm.elements[\"listId\"].value = $(\"shoppingListId\").value; document.addArticleToShoppingListForm.submit();'></td></tr></table></div>";
		win.getContent().update(content);
		win.showCenter();		
	}	
	else {
		win.getContent().update(content);
		win.showCenter();
		$("newShoppingList").style.display = "block";
		$("notesListLink").style.display = "none";
	}	
}

function showCreateShoppingList() {
	$("newShoppingList").style.display = "block";
	$("selectShoppingList").style.display = "none";	
}

function showChooseShoppingList() {
	$("selectShoppingList").style.display = "block";	
	$("newShoppingList").style.display = "none";
}

function isAvailable(index) {
	for (var i = 0; i < myProduct.articles[index].availabilities.length; i++) 
		if (myProduct.articles[index].availabilities[i].spotId == deliverySpot) 
			if (myProduct.articles[index].availabilities[i].available == "true") 
				return true;
	return false; 
}

function submitNewsLetterForm() {
	var newsLetterForm = document.getElementById('newsLetterForm');
	var recipient = document.getElementById('newsLetterRecipient');
	if (!validate(recipient,4,"true","newsletter_email_error")) {
		return false;
	}
	newsLetterForm.submit();
}
	
function createRecommendation(recipientEmail, recipientName, promoterName, senderActionURL){
	if (!validate($("mailrecipient"),4,"true","newsletter_email_error")) {
		return false;
	}
	if (!validate($("namerecipient"),1,"true","newsletter_email_error")) {
		return false;
	}
	return createRecommendationEmail(recipientEmail, recipientName, promoterName, senderActionURL);
}

function createRecommendationEmail(recipientEmail, recipientName, promoterName, senderActionURL){
	
	if (promoterName == " ") {
		promotorName = "Ein Freund";
	}
	
	var greeting = "Guten Tag!";
	if (recipientName && recipientName != "") {
		greeting = "Guten Tag " + recipientName + "!"; 
	}
	
	var recommendationBody =
		"<form name=\"recommendationForm\" action=\""+senderActionURL+"\">\n" +
		"	<table border='0' cellpadding='5' cellspacing='3'>\n" +
		"		<tr>\n" +
		"			<td class='text'>\n" +
		"				" + greeting + "\n" +
		"				<p>" + promoterName + " möchte Sie auf froodies aufmerksam machen, den Online Frische-Supermarkt, der Ihnen ihre Lebensmitteleinkäufe direkt nach Hause liefert.\n" +
		"			</td>\n" +
		"		</tr>\n" +
		"		<tr>\n" +
		"			<td class='text'>\n" +
		"				<p>Geben Sie hier eine persönliche Meldung ein:\n" +
		"			</td>\n" +
		"		</tr>\n" +	
		"		<tr>\n" +
		"			<td>\n" +
		"				<input type=\"hidden\" name=\"myRecipientEmail\" id=\"myRecipientEmail\" value=\"" + recipientEmail + "\"/>\n" +
		"				<input type=\"hidden\" name=\"myRecipientName\" id=\"myRecipientName\" value=\"" + recipientName + "\"/>\n" +
		"				<textarea id='myPersonalText' name='myPersonalText' cols='70' rows='5' class='black'></textarea>\n" +
		"			</td>\n" +
		"		</tr>\n" +
		"		<tr>\n" +
		"			<td class='text'>&nbsp;\n" +
		"			</td>\n" +
		"		</tr>\n" +
		"		<tr>\n" +
		"			<td class='text'>\n" +
		"				<p>froodies ist der Online-Frische-Supermarkt in Deutschland. Bei uns können Sie mit wenigen\n" +
		"				Klicks schnell und bequem Ihren Lebensmitteleinkauf erledigen und sich diesen\n" +
		"				direkt nach Hause liefern lassen.\n" +
		"				</p>\n" +
		"				<ul>\n" +
		"					<li>Sie erhalten frische Lebensmittel zu Top Preisen\n" +
		"					<li>Sie sparen jede Menge Zeit\n" +
		"					<li>Sie können bequem Ihren kompletten Wocheneinkauf erledigen\n" +
		"					<li>Sie sparen sich das Schleppen schwerer Kisten und Taschen und lästige Warteschlagen an den Kassen\n" +
		"				</ul>\n" +
		"				<p>Testen Sie uns und sichern Sie sich jetzt unseren 5&#8364; Neukundengutschein für Ihre erste\n" +
		"				Bestellung auf www.froodies.de\n" +
		"				</p>\n" +
		"				<p>Viel Spaß beim Einkaufen wünscht Ihnen</p>\n" +
		"				<p>Ihr froodies Team</p>\n" +
		"			</td>\n" +
		"		</tr>\n" +
		"		<tr><td class='alert'><span id=\"email_error\">&nbsp;</span></td></tr>\n" +
		"		<tr>\n" +
		"			<td>\n" + 
		"				<input type='button' value='Mail an " + recipientEmail + " versenden' \n" +
		"					onclick='javascript: if (checkIfEmpty($(\"myPersonalText\"))) { displayErrorMessage(\"email_error\"); return false;} else {document.recommendationForm.submit(); }'>\n" + 
		"			</td>\n" +
		"		</tr>\n" +
		"	</table>" +
		"</form>";

	win = new Window({className: "alphacube", width:650, height:430, destroyOnClose: true, recenterAuto: false}); 
	win.getContent().update( recommendationBody ); 
	win.showCenter();
	return false;
}

function showConfirmEmail(){

	var message = "<strong>Vielen Dank für Ihre Empfehlung</strong><p>Ihre E-Mail wurde erfolgreich versendet. Den Status Ihrer Freundschaftswerbeaktivitäten können Sie jederzeit in Ihrem Profil unter &#8222;Meine Empfehlungen&#8220; einsehen.</p>";
	
	win = new Window({className: "alphacube", width:350, height:100, destroyOnClose: true, recenterAuto: false}); 
	win.getContent().update( message ); 
	win.showCenter();
	return false;
}

function showConfirmNewsLetter(){

	var message = "<strong>Vielen Dank für Ihre Anmeldung zum froodies-Newsletter</strong><p>Sie erhalten in Kürze Ihren ersten Newsletter von froodies mit interessanten Angeboten und Rezepten. Die Abmeldung ist jederzeit möglich.</p>";
	
	win = new Window({className: "alphacube", width:380, height:110, destroyOnClose: true, recenterAuto: false}); 
	win.getContent().update( message ); 
	win.showCenter();
	return false;
}

function showEmailError(errorMsg){
	var message = "<strong>Ihre Email konnte leider nicht versendet werden</strong><p>"+ errorMsg + "</p>";
	
	win = new Window({className: "alphacube", width:350, height:60, destroyOnClose: true, recenterAuto: false}); 
	win.getContent().update( message ); 
	win.showCenter();
	return false;
}

function showOfferDetails(){

	var message = "<strong>Neukunden erhalten 5&#8364;-Begrüßungsgutschein bei froodies<br/><br/>Gutscheincode im Bestellprozess auswählen und einlösen</strong>";
	message += "<p>Nach erfolgreicher Registrierung schicken wir Ihnen per E-Mail eine Registrierungsbestätigung mit einem Gutschein-Code, der 30 Tage gültig ist. Während des Bestellprozesses können Sie diesen Gutschein einlösen und Ihrer Bestellung zuordnen, indem Sie bei der Wahl der Zahlungsart den Link &#8222;Ihre persönlichen Gutscheine&#8220; klicken und dort den Code auswählen. Alternativ können Sie den Code auch in das vorgegebene Gutscheinfeld eingeben.</p>";
	
	win = new Window({className: "alphacube", width:550, height:160, destroyOnClose: true, recenterAuto: false}); 
	win.getContent().update( message ); 
	win.showCenter();
	return false;
}

function showFreeShippingDetails(){

	var message = "<strong>froodies Lieferkosten</strong>";
	message += "<p>In unseren Liefergebieten Dortmund, Düsseldorf, Münster und Wuppertal, bieten wir Ihnen einen persönlichen Lieferservice an, der ab einem Bestellwert von 25&euro; kostenfrei ist.</p>";
	message += "<p>Bundesweit erfolgt die  Lieferung via Standardversand ab einem Bestellwert von 75&euro; kostenfrei.</p>";
	message += "<p>Wir versuchen, die Liefer- und  Versandkosten für Sie so gering wie möglich zu halten und geben daher nur einen Teil der tatsächlich anfallenden Kosten an Sie weiter.</p>"; 
	message += "<p>Wir wünschen Ihnen viel Spaß beim Einkaufen mit froodies.</p>";
	
	win = new Window({className: "alphacube", width:550, height:165, destroyOnClose: true, recenterAuto: false}); 
	win.getContent().update( message ); 
	win.showCenter();
	return false;
}

function deleteArticle(articleid) {
	$(articleId).value = articleid;
	document.deleteArticleForm.submit();
}

/* Assign existing article to product */
function assignArticleToProduct(productId, productname, imagePath, shortDescription, multiplicator, quantity, unit, refQuantity, refUnit, deposit) {
	var ratingResponse = function(xmlHttpRequest, json) {
		var res = xmlHttpRequest.responseText;
		var articles = eval('(' + res + ')');			
		
		win = new Window({className:"alphacube",width:540,height:220,destroyOnClose:true,recenterAuto:false}); 
		var content = "<div id='assignNewArticle' style='display: none;'><table border='0' cellpadding='5' cellspacing='3'><tr><td colspan='2' align='right'><span id='assignExistingArticleLink' style='display: block;'><a href='javascript: $(\"assignNewArticle\").style.display = \"none\"; $(\"assignExistingArticle\").style.display = \"block\";win.setSize(500,200);' class='linkLevel1'>Existierenden Artikel zuweisen</a></span></td></tr>" + 
		"<tr><td colspan='2' class='alert'>&nbsp;</td></tr><tr><td colspan='2' class='boldBlack8pt'>Neuen Artikel hinzufügen</td></tr><tr><td colspan='2' class='alert'>&nbsp;</td></tr><tr><td class='text'>Lieferantennummer*</td><td><input type='text' size='7' name='new_lnr' id='new_lnr' class='text'></td></tr><tr><td class='text'>Artikelnummer*</td><td><input type='text' size='7' name='new_artnr' id='new_artnr' class='text'></td></tr>" +
		"<tr><td class='text'>Ean*</td><td><input type='text' name='new_ean' id='new_ean' class='text'></td></tr>" +
		"<tr><td class='text'>Bildname*</td><td><input type='text' name='new_articleImage' id='new_articleImage' value='" + imagePath + "' class='text'></td></tr>" +		
		"<tr><td class='text'>Kurzbeschreibung*</td><td><input type='text' name='new_shortDescription' id='new_shortDescription' value='" + shortDescription + "' class='text'></td></tr>" +
		"<tr><td class='text'>Multiplikator</td><td><input type='text' size='5' name='new_multiplicator' id='new_multiplicator'  value='" + multiplicator + "' class='text'></td></tr>" +		
		"<tr><td class='text'>Menge*</td><td><input type='text' size='5' name='new_quantity' id='new_quantity' value='" + quantity + "' class='text'></td></tr>" +
		"<tr><td class='text'>Einheit*</td><td><select name='new_unit' id='new_unit' class='text'>";
		
		for (var i = 0; i < myUnits.unit.length; i++) {
			if (myUnits.unit[i] == unit) 
				content = content + "<option value='" + myUnits.unit[i] + "' selected='selected'>" + myUnits.unit[i] + "</option>";
			else
				content = content + "<option value='" + myUnits.unit[i] + "'>" + myUnits.unit[i] + "</option>";
		}
		
		content = content + "</select></td></tr>" +	
		"<tr><td class='text'>Mindestmenge*</td><td><input type='text' size='5' name='new_minQuantity' id='new_minQuantity' value='1' class='text'></td></tr>" +
		"<tr><td class='text'>Maximale Menge*</td><td><input type='text' size='5' name='new_maxQuantity' id='new_maxQuantity' value='50' class='text'></td></tr>" +		
		"<tr><td class='text'>Referenzmenge*</td><td><input type='text' size='5' name='new_refQuantity' id='new_refQuantity' value='" + refQuantity + "' class='text'></td></tr>" +
		"<tr><td class='text'>Referenzeinheit*</td><td><select name='new_refUnit' id='new_refUnit' class='text'>";
	
		for (var i = 0; i < myUnits.unit.length; i++) {
			if (myUnits.unit[i] == refUnit) 
				content = content + "<option value='" + myUnits.unit[i] + "' selected='selected'>" + myUnits.unit[i] + "</option>";
			else
				content = content + "<option value='" + myUnits.unit[i] + "'>" + myUnits.unit[i] + "</option>";
		}
				
		content = content + "</select></td></tr>" +	
		"<tr><td class='text'>EK*</td><td><input type='text' size='5' name='new_purchasePrice' id='new_purchasePrice' class='text'></td></tr>" +	
		"<tr><td class='text'>VK*</td><td><input type='text' size='5' name='new_salesPrice' id='new_salesPrice' class='text'></td></tr>" +	
		"<tr><td class='text'>Pfand</td><td><input type='text' size='5' name='new_deposit' id='new_deposit' value='" + deposit + "' class='text'></td></tr>" +		
		"<tr><td class='text' colspan='2'>&nbsp;</td></tr>" +			
		"<tr><td colspan='2'><input type='button' value='Artikel zuweisen' onclick='submitNewArticleAssignment(\"" + productId + "\");' class='text'></td></tr></table></div>";
		if (articles.length > 0) {
			content = content + "<div id='assignExistingArticle' style='display: block;'><table><tr><td align='right'><a href='javascript: $(\"assignExistingArticle\").style.display = \"none\"; $(\"assignNewArticle\").style.display = \"block\"; win.setSize(280,480);' class='linkLevel1'>Neuen Artikel anlegen</a></td></tr><tr><td>&nbsp;</td></tr><tr><td class=\"boldBlack8pt\">Folgenden Artikel dem Produkt " + productname + " zuordnen:</td></tr>" +
			"<tr><td class='alert'>&nbsp;</td></tr><tr><td><select name='newArticleId' id='newArticleId'>";
		
			for (var i = 0; i < articles.length; i++) 
				content = content + "<option value='" + articles[i].id + "'>" + articles[i].id + " - " + articles[i].description + "</option>";	
			
			content = content + "</select></td></tr>" +
			"<tr><td class='alert'>&nbsp;</td></tr><tr><td align='left'><input type='button' value='Artikel zuweisen' onclick='$(\"articleid\").value = $(\"newArticleId\").value; $(\"productid\").value = \"" + productId + "\"; document.assignArticleToProductForm.submit();'></td></tr></table></div>"; 
			win.getContent().update(content);
			win.showCenter();		
		}	
		else {
			win.getContent().update(content);
			win.showCenter();
			$("newShoppingList").style.display = "block";
			$("notesListLink").style.display = "none";
		}	
	};
	
	/* call backend via ajax to load articles */
	ajax("../admin/retrieveArticles.servlet.htm","",ratingResponse);
}

function submitNewArticleAssignment(productId) {
	$("productid").value = productId;
	$("articleNumber").value = $("new_artnr").value;
	$("distributorNumber").value = $("new_lnr").value;
	$("ean").value = $("new_ean").value;
	$("articleImage").value = $("new_articleImage").value;
	$("shortDescription").value = $("new_shortDescription").value;
	$("multiplicator").value = $("new_multiplicator").value;
	$("quantity").value = $("new_quantity").value;
	$("unit").value = $("new_unit").value;
	$("minQuantity").value = $("new_minQuantity").value;
	$("maxQuantity").value = $("new_maxQuantity").value;
	$("refQuantity").value = $("new_refQuantity").value;
	$("refUnit").value = $("new_refUnit").value;
	$("purchasePrice").value = $("new_purchasePrice").value;
	$("salesPrice").value = $("new_salesPrice").value;
	$("deposit").value = $("new_deposit").value;
	document.assignArticleToProductForm.submit();
}

/* functions for delivery address checkout */
function showFrame(obj) { 
   if (obj.firstChild.id != "editTable") {
      obj.style.backgroundColor = "#ccff99";
   }

	//obj.style.border = "1px solid #CCFF99";
}

function hideFrame(obj) {
	if (obj.firstChild.id != "editTable") {
		obj.style.backgroundColor = "#ffffff";
	}
}

Array.prototype.contains = function(obj) {
	var i, listed = false;
    for (i=0; i<this.length; i++) {
		if (this[i] === obj) {
			listed = true;
         	break;
       	}
	}
    return listed;
};

/**
function undoEditText(id) {
    var obj = document.getElementById(id);
	var inputNode = obj;
	while (inputNode.tagName != "INPUT") 
		inputNode = inputNode.firstChild;
	
	while (obj.hasChildNodes()) 
		obj.removeChild(obj.firstChild);
		
	var textNode = document.createTextNode(inputNode.value);
	obj.appendChild(textNode);
}
**/

function createAddress() {
	document.getElementById("deliveryAddress").style.display = "block";
	document.getElementById("createAddress").style.display = "none";
	document.getElementById("addressImg").style.display = "none";
	var obj = document.getElementById("deliveryInstruction");
	if(obj) obj.value = "";
	document.getElementById("newAddress").checked = true;
	document.getElementById("street").focus();
}

function Address(deliveryType,deliveryInstruction,zipcode) {
	this.deliveryType = deliveryType;
	this.deliveryInstruction = deliveryInstruction;
	this.zipcode = zipcode;
}
 
function showDeliveryInstruction(deliveryType,index) {	
	if( deliveryType == "Bürolieferung") {
		document.getElementById("Bürolieferung").checked = true;
		radioGrp = document.deliveryAddressForm.address;
		radioGrp[selectedIndex(radioGrp)].checked = false;
		shippingElements = document.getElementsByName("shippingType");
		shippingElements[selectedIndex(shippingElements)].checked = false;		
	}
	else if (deliveryType == "Drive Through") {
			document.getElementById("Drive Through").checked = true;
			radioGrp = document.deliveryAddressForm.address;
			radioGrp[selectedIndex(radioGrp)].checked = false;	
			radioGrpShipping = document.deliveryAddressForm.shippingType;
			radioGrpShipping[selectedIndex(radioGrpShipping)].checked = false;	
	}	
	else if (deliveryType == "Versand") {
			document.getElementById("Versand").checked = true;
			deliveryInstruction.disabled = false;
			deliveryInstruction.style.fontWeight = 'normal';
			if( index != -1) {
				radioGrp = document.deliveryAddressForm.address;
				radioGrp[index].checked = true;
				shippingElements = document.getElementsByName("shippingType");
				shippingElements[selectedIndex(shippingElements)].checked = true;	
			}	
	}	
	else {
		if ($("Heimlieferung"))
			$("Heimlieferung").checked = true;
		else
			$("Versand").checked = true;

		if( index != -1) {
			radioGrp = document.deliveryAddressForm.address;
			radioGrp[index].checked = true;	
		}	
	}
}

function selectedIndex(radiogroup){
	for(i=0;i<radiogroup.length;i++){
		if(radiogroup[i].checked) return i;
	}
	// If no index is selected, return 0
	return 0;
}

function cancelDialog() {
	/* default delivery address auswählen */
	radiogroup = document.deliveryAddressForm.address;
	for (var i = 0; i < radiogroup.length; i++) 
		if (radiogroup[i].value == deliveryAddressId) {
			radiogroup[i].checked = true;
			return true;
		}
}

function okDialog() {
	document.deliveryAddressForm.locationChanged.value = true;
	submitAddressData('false');
	return true;
}

function hasDeliveryLocationChangedNewAddress() {
    var zip = document.getElementById("zip").value;
	var oldIsHomeDelivery = allDeliveryZipCodes.contains(zip);
	var newIsHomeDelivery = allDeliveryZipCodes.contains(deliveryAddress.zipcode);

	/* Currently only tested on zip code level
	   to be implemented: ajax call which checks if same spot */	
	if (zip != deliveryAddress.zipcode)
		if (oldIsHomeDelivery != newIsHomeDelivery) {
			Dialog.confirm("Bei einer Änderung der Postleitzahl sind möglicherweise nicht mehr alle Produkte lieferbar. Bitte Ok klicken, um zur Prüfung der Lieferung zu gelangen. Cancel macht die Auswahl rückgängig.", 
			{className: "alphacube", width:300, okLabel: "Ok", id: "myDialogId", cancel: cancelDialog, ok: okDialog });
		}	
}

function hasDeliveryLocationChanged(index) {
	var oldIsHomeDelivery = allDeliveryZipCodes.contains(homeAddresses[index].zipcode);
	var newIsHomeDelivery = allDeliveryZipCodes.contains(deliveryAddress.zipcode);

	/* Currently only tested on zip code level
	   to be implemented: ajax call which checks if same spot */	
	if (homeAddresses[index].zipcode != deliveryAddress.zipcode)
		if (oldIsHomeDelivery != newIsHomeDelivery) {
			Dialog.confirm("Bei einer Änderung der Postleitzahl sind möglicherweise nicht mehr alle Produkte lieferbar. Bitte Ok klicken, um zur Prüfung der Lieferung zu gelangen. Cancel macht die Auswahl rückgängig.", 
			{className: "alphacube", width:300, okLabel: "Ok", id: "myDialogId", cancel: cancelDialog, ok: okDialog });
		}	
}

function submitAddressData(fieldval) {
	if( document.getElementById("newAddress").checked && fieldval) {
		// var dataOk = false;
		if (!validate($("street"),1,true,street_error))
			return false;		
		if (!validate($("zip"),8,true,zip_error))
			return false;	
		if (!validate($("city"),1,true,city_error))
			return false;
		if (!validate($("deliveryDescription"),2,true,deliveryDescription_error))
			return false;
		if (!validate($("deliveryNote"),2,false,deliveryNote_error))
			return false;		
		return true;	
	}
	else {
		if (!validate($("deliveryNote"),2,false,deliveryNote_error))
			return false;
		return true;
	}
}
/* end: functions for delivery address checkout */

function checkBrowserName(name){  
   var agent = navigator.userAgent.toLowerCase();  
   
   if (agent.indexOf(name.toLowerCase())>-1)  
     return true;  
    
   return false;  
} 

function couponPopup() {
	couponPopup = new Window({className:"alphacube",width:400,height:260,destroyOnClose:true,recenterAuto:false});
	couponContent = "<img src='../images/froodieUndLivia_fuerStartseite.jpg' border='0' id='couponImage' class='centerImage'>";
	couponPopup.setHTMLContent(couponContent);
	couponPopup.showCenter();
}

function persistAvailability(articleId, spotId, availability) {
	$("availabilityloader" + articleId + "_" + spotId).innerHTML = "<img src='../images/ajax-loader.gif'>";
	var ratingResponse = function(xmlHttpRequest, json) {
		var res = xmlHttpRequest.responseText;
		var myJson = eval('(' + res + ')');
		message = myJson.message;
		$("availabilityloader" + articleId + "_" + spotId).innerHTML = "";
	};
	ajax("../admin/changeAvailability.servlet.htm", "articleId=" + articleId + "&spotId=" + spotId + "&availability=" + availability, ratingResponse);
}

function persistStorageArea(articleId,storageAreaId) {
	// $("saloader" + articleId + "_" + siteId).innerHTML = "<img src='../images/ajax-loader.gif'>";
		var ratingResponse = function(xmlHttpRequest, json) {
			var res = xmlHttpRequest.responseText;
			var myJson = eval('(' + res + ')');
			message = myJson.message;
			// $("saloader" + articleId + "_" + siteId).innerHTML = "";
		};
		ajax("../../admin/changeStorageArea.servlet.htm", "articleId=" + articleId + "&storageAreaId=" + storageAreaId, ratingResponse);
	}

function persistArticleInformation(articleId, spotId, supplier, storageArea, purchasePrice, salesPrice, isOffer) {
	$("progress_" + articleId + "_" + spotId).innerHTML = "<img src='../images/ajax-loader.gif'>";
	var ratingResponse = function(xmlHttpRequest, json) {
		var res = xmlHttpRequest.responseText;
		var myJson = eval('(' + res + ')');
		message = myJson.message;
		$("progress_" + articleId + "_" + spotId).innerHTML = "";
	};
	// alert(articleId + ", " + spotId + ", " + supplier + ", " + purchasePrice + ", " + salesPrice);
	ajax("../admin/changeArticleInformation.servlet.htm", "articleId=" + articleId + "&spotId=" + spotId + "&supplier=" +
		supplier + "&storageArea=" + storageArea + "&purchasePrice=" + purchasePrice + "&salesPrice=" + salesPrice + "&isOffer=" + isOffer, ratingResponse);
}

/* takes site id an returns list of delivery spots */
function getDeliverySpotsForSite(site) {
	var ratingResponse = function(xmlHttpRequest, json) {
		var res = xmlHttpRequest.responseText;
		var myJson = eval('(' + res + ')');
		message = myJson.message;		
		var deliverySpotHTML = "&nbsp;Spot&nbsp;<select name='deliverySpot' id='deliverySpot' class='text' onchange='getSuppliersForSite(" + myJson.siteId + ")'>";
		deliverySpotHTML = deliverySpotHTML + "<option value='' selected='selected'></option>";
		for (var i = 0; i < myJson.deliverySpot.length; i++) {
			deliverySpotHTML = deliverySpotHTML + "<option value='" + myJson.deliverySpot[i].id + "'>" + myJson.deliverySpot[i].name + "</option>";		
		}
		deliverySpotHTML = deliverySpotHTML + "</select>";
		$("deliverySpotSelectionPane").innerHTML = deliverySpotHTML;
	};
	ajax("../admin/getDeliverySpotsForSite.servlet.htm", "siteId=" + site.value, ratingResponse);
}

/* takes site id an returns list of delivery spots */
function getSuppliersForSite(siteId) {
	var ratingResponse = function(xmlHttpRequest, json) {
		var res = xmlHttpRequest.responseText;
		var myJson = eval('(' + res + ')');
		message = myJson.message;		
		var supplierHTML = "&nbsp;Lieferant&nbsp;<select name='supplier' id='supplier' class='text'>";
		for (var i = 0; i < myJson.supplier.length; i++) {
			if (i == 0)
				supplierHTML = supplierHTML + "<option value='" + myJson.supplier[i].id + "' selected='selected'>" + myJson.supplier[i].name + "</option>";
			else
				supplierHTML = supplierHTML + "<option value='" + myJson.supplier[i].id + "'>" + myJson.supplier[i].name + "</option>";		
		}
		supplierHTML = supplierHTML + "</select>";
		$("supplierSelectionPane").innerHTML = supplierHTML;
	};
	ajax("../admin/getSuppliersForSite.servlet.htm", "siteId=" + site.value, ratingResponse);
}


function persistCountry(object, productID) {
	$("countryloader" + productID).innerHTML = "<img src='../images/ajax-loader.gif'>";
	var ratingResponse = function(xmlHttpRequest, json) {
		var res = xmlHttpRequest.responseText;
		var myJson = eval('(' + res + ')');
		message = myJson.message;
		$("countryloader" + productID).innerHTML = "";
	};
	ajax("../admin/switchCountry.servlet.htm", "productID=" + productID + "&origin=" + object.value, ratingResponse);
}

function switchAvailability(articleID) {
	$("availabilityImage" + articleID).src = "../images/ajax-loader.gif";
	var ratingResponse = function(xmlHttpRequest, json) {
		var res = xmlHttpRequest.responseText;
		var myJson = eval('(' + res + ')');
		var available = myJson.available;
		if (available == "false")
			$("availabilityImage" + articleID).src = "../images/froodies_loeschen.gif";
		else
			$("availabilityImage" + articleID).src = "../images/froodies_success.gif";
	};
	ajax("../admin/switchAvailability.servlet.htm", "articleID=" + articleID, ratingResponse);
}

function switchAddressType(selection) {
	$("companyContainer").style.display = "none";
	$("postalNumberContainer").style.display = "none";
	$("packstationContainer").style.display = "none";
	$("streetContainer").style.display = "none";
	if (selection == 'private') {
		$("streetContainer").style.display = "block";
		$("deliveryAddressCompanyName").value = "";
		$("deliveryAddressCompanyNameMore").value = "";
		$("deliveryAddressPostalNumber").value = "";
		$("deliveryAddressPackstationNumber").value = "";
	}
	else if (selection == 'company') {
		$("companyContainer").style.display = "block";
		$("streetContainer").style.display = "block";
		$("deliveryAddressPostalNumber").value = "";
		$("deliveryAddressPackstationNumber").value = "";
	}
	else if (selection == 'packstation') {
		$("postalNumberContainer").style.display = "block";
		$("packstationContainer").style.display = "block";
		$("deliveryAddressCompanyName").value = "";
		$("deliveryAddressCompanyNameMore").value = "";		
	}
}

function addNewCouponField(max) {
	var max = max - 1;
	var row_1 = document.createElement("tr");
	var cell_1 = document.createElement("td");
	cell_1.setAttribute("class", "text");
    
	var label_text = document.createTextNode("Gutscheincode:");
    cell_1.appendChild(label_text);	
	row_1.appendChild(cell_1);
	
	var cell_2 = document.createElement("td");
	cell_2.setAttribute("class", "text");
	var inputField = document.createElement("input");
    inputField.setAttribute("name", "coupon");
    inputField.setAttribute("type", "text");
    inputField.setAttribute("maxlength", "29");
    inputField.setAttribute("size", "40");
    
    cell_2.appendChild(inputField);
    row_1.appendChild(cell_2);
    
	var validateButton = document.createElement("input");
	validateButton.setAttribute("name", "validateButton");
    validateButton.setAttribute("type", "button");
    validateButton.setAttribute("value", "einlösen");
    validateButton.setAttribute("onclick", "validateCoupon(" + max + ")");	

	/* cell_1.appendChild(validateButton); */
	Element.insert($('row_coupon_message_' + max), {'after': row_1});
}
function addNewCouponSelection(obj,currentCoupon,maxCoupons) {
	newCoupon = currentCoupon + 1;
	obj.show();
	if (currentCoupon < maxCoupons - 1)
		$('coupon_selection_link').href = "javascript:addNewCouponSelection($('row_coupon_message_" + newCoupon + "')," + newCoupon + "," + maxCoupons + ");";
	else
		$$('tr.new_coupon_link').each(Element.hide);
}
/* approvePurchasePrices.jsp */
/* validate if relevant field are filled and submit request */
function submitPricesQuery() {
	if ($("searchTerm").value != "" || $("category").value != "")
		if ($("deliverySpot").value != "")
			document.priceCalculationForm.submit();
		else
			alert("Bitte einen Standort auswählen!");
	else {
		alert("Bitte entweder eine Kategorie wählen oder einen Suchebegriff eingeben!");
		return false;
	}
}

/**
 * This function fires when user changed type of margin on the supplier's details page.
 *
 * @param marginSelector <select> control.
 */
function changeMarginType(marginSelector) {
    var optionValue = marginSelector.options[marginSelector.selectedIndex].value;
    switch (optionValue) {
        case "1":
          $("highInput").style.display = "none";
          $("zeroInput").style.display = "none";
          $("lowInput").style.display = "block";
          break;
        case "2":
          $("highInput").style.display = "block";
          $("zeroInput").style.display = "none";
          $("lowInput").style.display = "none";	
          break;
        case "3":
          $("highInput").style.display = "none";
          $("zeroInput").style.display = "block";
          $("lowInput").style.display = "none";
          break;
    }
}

/**
 * This function fires when user changed business model type on the supplier's details page.
 *
 * @param modelOrdinal Ordinal number of the currently selected business model.
 */
function changeBusinessModel(modelOrdinal) {
    switch (modelOrdinal) {
        case "0":
          $("partnerSurcharge").disabled = true;
          $("partnerShare").disabled = true;
          break;
        case "2":
          $("partnerSurcharge").disabled = true;
          $("partnerShare").disabled = false;
          break;
        case "1":
          $("partnerSurcharge").disabled = false;
          $("partnerShare").disabled = true;
          break;
    }
}

function runFader( idPrefix, fadeTime, cycleTime, currItemNum ) {
	var nextItemNum = currItemNum + 1;
	
	var currItem = idPrefix + currItemNum;
	var nextItem = idPrefix + nextItemNum;

	if (jQuery(nextItem).length == 0) {
		nextItem = idPrefix + "1";
		nextItemNum = 1;
	}

	jQuery( currItem ).fadeOut( fadeTime );

	var fadeInArgs = "'" + currItem + "','" + nextItem + "'," + fadeTime;
	setTimeout( "fadeIn(" + fadeInArgs + ")", fadeTime - 10 );
	
	var runFaderArgs = "'" + idPrefix + "'," + fadeTime + "," + cycleTime + "," + nextItemNum;
	setTimeout( "runFader(" + runFaderArgs + ")", cycleTime );
}

function fadeIn( currItemId, nextItemId, fadeTime ) {
	jQuery(currItemId).hide();
	jQuery(nextItemId).fadeIn(fadeTime);
}

var menuSlideTimer = null;
/**
 * Registers onhover function for menu items in header on every page.
 */
jQuery(document).ready(function() {
	if (!jQuery.browser.msie) {
		jQuery('div.nav div.navcon ul li').hover(
			function() {
				headerMenuSlideDown(jQuery(this));
			},
			function() {
				headerMenuSlideUp(jQuery(this));
			}
		);
		menuSlideTimer = null;
	}
});

/**
 * Slide up header menu.
 */
function headerMenuSlideUp(menuItem) {
	if (menuSlideTimer) {
		clearTimeout(menuSlideTimer);
		menuSlideTimer = null;
	}
	menuItem.find('div#subMenuItem').slideUp('fast');
	//jQuery(this).removeClass('bold');
}

/**
 * Slide down header menu.
 */
function headerMenuSlideDown(menuItem) {
	if (jQuery.browser.msie) {
		var zIndexNumber = 99;
		jQuery('div').each(function(idx,el) {
			if (el.className != 'ac_box') {
				el.style.zIndex = zIndexNumber;
				zIndexNumber -= 1;
			}
		});
	}
	var subMenu = menuItem.find('div#subMenuItem');
	var link = menuItem.find('a');
	// menuItem.addClass('bold');
	if (subMenu.length == 0 && link.length > 0) {
		var blockIdValues = link.attr('id').split('_');
		var catId = blockIdValues[1];
		var menuLocation = blockIdValues[0];
		jQuery.ajax({
			type: "POST",
			url: "../shop/displayCategorySubMenu.htm",
			data: "categoryId=" + catId,
			async: false,
			success: function(data){
				menuItem.append(data);
				subMenu = menuItem.find('div#subMenuItem');
				var menuColumns = menuItem.find('table#tableCatColumn td[id^=tdChildCat]');
				if (menuColumns.length > 0) {
					if (menuLocation == 'top') {
						menuItem.find('table#tableCatMenu').attr("class", "submenuTopTable");
						menuColumns.attr("class", "tdTopChildCatCell");
					} else {
						menuItem.find('table#tableCatMenu').attr("class", "submenuBottomTable");
						menuColumns.attr("class", "tdBottomChildCatCell");
					}
					menuSlideTimer = setTimeout(function() {
						menuSlideTimer = null;
						subMenu.stop(true, true);
						subMenu.slideDown();
					}, 400);
				}
			}
		});
	} else {
		var menuColumns = menuItem.find('table#tableCatColumn td[id^=tdChildCat]');
		if (menuColumns.length > 0) {
			menuSlideTimer = setTimeout(function() {
				menuSlideTimer = null;
				subMenu.stop(true, true);
				subMenu.slideDown();
			}, 400);
		}
	}
}

/**
 * Initializes slider for the topsellers control.
 */
jQuery(document).ready(function() {
    jQuery('#topSellersSlider').jcarousel();
});

/**
 * Checks and updates quantity.
 *
 * @param amountObj Element with amount value.
 * @param count Count delta value.
 * @param minQuantity Minimum quantity for the aticle.
 * @param maxQuantity Maximum quantity for the aticle.
 */
function checkAndUpdateQuantity(amountObj, count, minQuantity, maxQuantity) {
	var newCnt = parseInt(amountObj.value) + count;
	if (parseInt(newCnt) < parseInt(minQuantity)) {
    	alert("Die Mindestbestellmenge beträgt " + minQuantity);
    	newCnt = parseInt(minQuantity);
    } else if (parseInt(newCnt) > parseInt(maxQuantity)) {
    	alert("Die maximale Bestellmenge beträgt " + maxQuantity);
    	newCnt = parseInt(maxQuantity);
    }
    amountObj.value = newCnt;
}

/**
 * Checks quantity and/or updates price for the selected article.
 *
 * @param id Article ID.
 * @param amountObj Element with amount value.
 * @param targetObj Element for calculated value.
 * @param checkerObj Element for check is calculation of price needed or not.
 * @param count Count delta value.
 * @param minQuantity Minimum quantity for the aticle.
 * @param maxQuantity Maximum quantity for the aticle.
 * @param isDepositInclude Include or not deposit during calcualtions.
  */
function checkQuantityOrUpdatePrice(id, amountObj, targetObj, checkerObj, count, minQuantity, maxQuantity, isDepositInclude) {
    if (checkerObj.value == 'true') {
        checkAndUpdateQuantity(amountObj, count, minQuantity, maxQuantity);
    } else {
        checkAndUpdateQuantity(amountObj, count, minQuantity, maxQuantity);
    }
}

/**
 * Updates quantity for the selected article.
 *
 * @param id Article ID.
 * @param amountObj Element with amount value.
 * @param targetObj Element for calculated value.
 * @param count Count delta value.
 * @param minQuantity Minimum quantity for the aticle.
 * @param maxQuantity Maximum quantity for the aticle.
 * @param isDepositInclude Include or not deposit during calcualtions.
  */
function updateQuantityAndPrice(id, amountObj, targetObj, count, minQuantity, maxQuantity, isDepositInclude) {
    checkAndUpdateQuantity(amountObj, count, minQuantity, maxQuantity);
	updatePrice(id, minQuantity, maxQuantity, amountObj, targetObj, isDepositInclude);
}

/**
 * Updates quantity for the selected article.
 *
 * @param id Article ID.
 * @param amountObj Element with amount value.
 * @param targetObj Element for calculated value.
 * @param count Count delta value.
 * @param minQuantity Minimum quantity for the aticle.
 * @param maxQuantity Maximum quantity for the aticle.
 */
function updateQuantityWithDeposit(id, amountObj, targetObj, count, minQuantity, maxQuantity) {
	updateQuantityAndPrice(id, amountObj, targetObj, count, minQuantity, maxQuantity, true);
}

/**
 * Updates quantity for the selected article.
 *
 * @param id Article ID.
 * @param amountObj Element with amount value.
 * @param targetObj Element for calculated value.
 * @param count Count delta value.
 * @param minQuantity Minimum quantity for the aticle.
 * @param maxQuantity Maximum quantity for the aticle.
 */
function updateQuantity(id, amountObj, targetObj, count, minQuantity, maxQuantity) {
	updateQuantityAndPrice(id, amountObj, targetObj, count, minQuantity, maxQuantity, false);
}

/**
 * Calculates new price for the selected article.
 *
 * @param id Article ID.
 * @param minQuantity Minimum quantity for the aticle.
 * @param maxQuantity Maximum quantity for the aticle.
 * @param obj Input control with value of amount.
 * @param targetObj Target element for the sum value.
 * @param isDepositInclude Include or not deposit during calcualtions.
 */
function updatePrice(id, minQuantity, maxQuantity, obj, targetObj, isDepositInclude) {
    var queryString = "";
	var amount = obj.value;
	if (isNaN(amount) || !amount || parseInt(amount) < parseInt(minQuantity)) {
    	alert("Die Mindestbestellmenge beträgt " + minQuantity);
    	amount = parseInt(minQuantity);
    	obj.value = parseInt(minQuantity);
    } else if (parseInt(amount) > parseInt(maxQuantity)) {
    	alert("Die maximale Bestellmenge beträgt " + maxQuantity);
    	amount = parseInt(maxQuantity);
    	obj.value = parseInt(maxQuantity);
    }
	var ratingResponse = function(xmlHttpRequest, json) {
		var res = xmlHttpRequest.responseText;
		var myJson = eval('(' + res + ')');
		var price = myJson.priceInEuro;
		var error = Boolean(myJson.error);
		if (!error) {
		    targetObj.childNodes[0].nodeValue = price;
        }
	};
	var url = "../pricecalculation.servlet.htm";
	queryString += "articleid=" + encodeURIComponent(id) + "&";
	queryString += "amount=" + encodeURIComponent(amount) + "&";
    queryString += "isDepositInclude=" + encodeURIComponent(isDepositInclude);
	ajax(url, queryString, ratingResponse);
}

/**
 * Calculates new price for the selected article.
 * Deposit is not take part into calculation.
 *
 * @param id Article ID.
 * @param minQuantity Minimum quantity for the aticle.
 * @param maxQuantity Maximum quantity for the aticle.
 * @param obj Input control with value of amount.
 * @param targetObj Target element for the sum value.
 */
function calculatePrice(id, minQuantity, maxQuantity, obj, targetObj) {
    updatePrice(id, minQuantity, maxQuantity, obj, targetObj, false);
}

/**
 * Calculates new price for the selected article.
 * Deposit is take into account during calculation.
 *
 * @param id Article ID.
 * @param minQuantity Minimum quantity for the aticle.
 * @param maxQuantity Maximum quantity for the aticle.
 * @param obj Input control with value of amount.
 * @param targetObj Target element for the sum value.
 */
function calculatePriceWithDeposit(id, minQuantity, maxQuantity, obj, targetObj) {
    updatePrice(id, minQuantity, maxQuantity, obj, targetObj, true);
}

/**
 * Calculates new price for the selected article.
 * Deposit is not taken into account during calculation.
 *
 * @param id Article ID.
 * @param minQuantity Minimum quantity for the aticle.
 * @param maxQuantity Maximum quantity for the aticle.
 * @param obj Input control with value of amount.
 * @param targetObj Target element for the sum value.
 */
function calculatePriceWithoutDeposit(id, minQuantity, maxQuantity, obj, targetObj) {
    updatePrice(id, minQuantity, maxQuantity, obj, targetObj, false);
}

/**
 * Adds selected article to the shopping cart.
 *
 * @param id Article ID.
 * @param amountObj Element with amount to add.
 */
function addArticleToShoppingBag(id, amountObj) {
	$("articleId").value = id;
	$("amount").value = amountObj.value;
	document.forms['AddArticleToShoppingCartForm'].submit();
}

/**
 * Adds all recipe's ingredients to the shopping cart.
 */
function addAllRecipeIngredientsToShoppingCart() {
    var s = "";
    var selectors = document.getElementsByName("selector");
    for (var i = 0; i < selectors.length; i++) {
        if (selectors[i].options.length > 0) {
            var index = selectors[i].id.replace(/selector_/, "");
            var itemRow = document.getElementById("item1_" + index);
            if (itemRow && itemRow.style.display == '') {
                var coefficient = 1;
                if (selectors[i].value.split("|")[4] && selectors[i].value.split("|")[5] == 'true') {
                    coefficient = selectors[i].value.split("|")[4];
                }
                s += selectors[i].value.split("|")[0];
                s += "|";
                s += coefficient * document.getElementById("quantity_" + index).value;
                if (i < selectors.length - 1) s += ",";
            }
        }
    }
     var ratingResponse = function(xmlHttpRequest, json) {
        var res = xmlHttpRequest.responseText;
        var myJson = eval('(' + res + ')');
        updateShoppingCart(myJson);
    };
    ajax("../shop/addToShoppingCart.servlet.htm", "shoppingString=" + s, ratingResponse);
}

/**
 * Adds selected recipe's ingredient to the shopping cart.
 *
 * @param id Index of the ingredient on the page.
 */
function addRecipeIngredientToShoppingCart(id) {
    // add the item identified by the index of row to the shopping basket
    var selector = document.getElementById("selector_" + id);
    if (selector.options.length > 0) {
        var quantity = document.getElementById("quantity_" + id).value;
        if (quantity > 0) {
            var selection = selector.value.split("|");
            var articleId = selection[0];
     
            addToShoppingCart(articleId, quantity);
        }
    }
}

/**
 * Adds item to shopping cart using ajax and updates shopping cart
 * content table
 *
 * @param articleId Article id
 * @param itemCount article amount
 */
function addToShoppingCart(articleId, itemCount) { 
	var ratingResponse = function(xmlHttpRequest, json) {
        var res = xmlHttpRequest.responseText;
        var myJson = eval('(' + res + ')');
        updateCartAfterAddingItem(myJson);
    };
    var parametersString = "articleId=" + articleId + "&itemCount=" + itemCount;
    var productAttributes = document.getElementsByName("productAttributes[]");
    for(var i = 0; productAttributes != null && i < productAttributes.length; i++){
        var selectedOption = productAttributes[i].options[productAttributes[i].selectedIndex];
        parametersString += "&productAttribute=" + selectedOption.value;
    }
    ajax("../shop/addToShoppingCart.servlet.htm", parametersString, ratingResponse);
}

/**
 * Updates shopping cart on UI after adding item/items
 *
 * @param shoppingCartItemsInfo JSON object with information about changes in shopping cart
 */
function updateCartAfterAddingItem(shoppingCartItemsInfo) {
    if ($("totalSum") == null) {
        $("myShoppingCartHeaderButtons").style.visibility = "visible";
        $("myShoppingCartContentTable").children[0].removeChild($("myShoppingCartContentTable").children[0].children[0]);
        $("callCheckOut").style.display = "";
        $("myShoppingCartContentTable").children[0].insertBefore(createShoppingCartSumElement(shoppingCartItemsInfo), $("callCheckOut"));
    }
    $("totalSum").children[1].children[0].innerHTML = shoppingCartItemsInfo.totalPrice + "&euro;";

    for (var i = 0; i < shoppingCartItemsInfo.items.length; i++) {
        var item = shoppingCartItemsInfo.items[i];
        var itemElement = $("shopping_cart_item_" + item.articleId);
        if (itemElement != null) {
            var tdWithAmountAndName = itemElement.children[0];
            tdWithAmountAndName.children[0].innerHTML = item.amount + defineUnit(item) + " ";
            var tdWithPrice = itemElement.children[1];
            tdWithPrice.children[0].innerHTML = item.priceInEuro + "&euro;";
        } else {
            $("myShoppingCartContentTable").children[0].insertBefore(
            		createShoppingCartItemElement(item, shoppingCartItemsInfo.context), 
            		$("totalSum"));
        }
        var shoppingCartItem = jQuery("#shopping_cart_item_" + item.articleId);
        for (var k = 0; k < 4; k++) {
            shoppingCartItem.fadeOut(150).fadeIn(150);
        }
    }
}

/**
 * Defines shopping cart item unit
 *
 * @param item
 */
function defineUnit(item){
    var unit;
    if(item.isWeighedGood){
        unit = item.unitShortTxt;
    } else if(item.weightPerUnit != 0 || item.unitShortTxt == "St") {
        unit = " St.";
    } else {
        unit = "";
    }
    return unit;
}

/**
 * Creates <tr> with information about added shopping cart item
 *
 * @param item
 */
function createShoppingCartItemElement(item, context) {
    var tr = document.createElement("tr");
    tr.setAttribute("id", "shopping_cart_item_" + item.articleId);

    var tdWithAmountAndName = document.createElement("td");
    tdWithAmountAndName.className = "text";
    tdWithAmountAndName.setAttribute("width", "100%");

    var span = document.createElement("span");
    span.innerHTML = item.amount + defineUnit(item) + " ";
    tdWithAmountAndName.appendChild(span);

    var a = document.createElement("a");
    a.setAttribute("title", item.displayName);
    a.className = "linkLevel1";
    a.setAttribute("href", context + "/?prodId=" + item.productId);

    a.innerHTML = item.displayNameShort;
    tdWithAmountAndName.appendChild(a);

    tr.appendChild(tdWithAmountAndName);

    tdWithPrice = document.createElement("td");
    tdWithPrice.setAttribute("align", "right");
    tdWithPrice.className = "text";

    var small = document.createElement("small");
    small.innerHTML = item.priceInEuro + "&euro;";
    tdWithPrice.appendChild(small);

    tr.appendChild(tdWithPrice);

    var tdWithDeleteButton = document.createElement("td");
    tdWithDeleteButton.style.paddingTop = "5px";
    tdWithDeleteButton.style.paddingRight = "5px";
    a = document.createElement("a");
    a.setAttribute("href", "javascript:removeItemFromShoppingCart(" + item.articleId + ");");
    var img = document.createElement("img");
    img.setAttribute("src", context + "/images/new/btn_x_small.png");
    a.appendChild(img);
    tdWithDeleteButton.appendChild(a);

    tr.appendChild(tdWithDeleteButton);

    return tr;
}

/**
 * Creates <tr> with information about shopping cart total sum
 *
 * @param shoppingCartItemsInfo
 */
function createShoppingCartSumElement(shoppingCartItemsInfo) {
    var tr = document.createElement("tr");
    tr.setAttribute("id", "totalSum");

    var tdWithSumTitle = document.createElement("td");
    tdWithSumTitle.className = 'text';
    var strong = document.createElement("strong");
    strong.appendChild(document.createTextNode("Summe:"));
    tdWithSumTitle.appendChild(strong);
    tr.appendChild(tdWithSumTitle);

    var tdWithSumValue = document.createElement("td");
    tdWithSumValue.className = "text";
    tdWithSumValue.setAttribute("align", "right");
    strong = document.createElement("strong");
    strong.innerHTML = shoppingCartItemsInfo.totalPrice + "&euro;";
    tdWithSumValue.appendChild(strong);
    tr.appendChild(tdWithSumValue);

    var tdEmpty = document.createElement("td");
    tr.appendChild(tdEmpty);
    
    return tr;
}

/*
 * Removes item from shopping cart using ajax and updates shopping cart
 * content table
 *
 * @param articleId Article id
 */
function removeItemFromShoppingCart(articleId) {
    var ratingResponse = function(xmlHttpRequest, json) {
        var res = xmlHttpRequest.responseText;
        var shoppingCartInfo = eval('(' + res + ')');
        updateShoppingCartAfterRemovingItem(shoppingCartInfo, articleId);
    };
    var parametersString = "articleId=" + articleId;
    ajax("../shop/removeFromShoppingCart.servlet.htm", parametersString, ratingResponse);
}

/**
 * Updates shopping cart on UI after removing item
 *
 * @param shoppingCartInfo JSON object with information about changes in shopping cart
 * @param articleId article id being deleted
 */
function updateShoppingCartAfterRemovingItem(shoppingCartInfo, articleId) {
    var form = document.forms['ShoppingCartForm'];

    if (form) {
        form.submit();
    } else {
        var itemElement = $("shopping_cart_item_" + articleId);
        itemElement.parentNode.removeChild(itemElement);

        if ($("myShoppingCartContentTable").children[0].children.length > 2) {
            $("totalSum").children[1].children[0].innerHTML = shoppingCartInfo.totalPrice + "&euro;";
        } else {
            $("myShoppingCartContentTable").children[0].removeChild($("totalSum"));
            $("callCheckOut").style.display = "none";

            var tr = document.createElement("tr");
            var td = document.createElement("td");
            td.setAttribute("align", "center");
            td.className = "text";
            td.innerHTML = "lst noch leer";
            tr.appendChild(td);

            $("myShoppingCartContentTable").children[0].insertBefore(tr, $("callCheckOut"));

            $("myShoppingCartHeaderButtons").style.visibility = "hidden";
        }
    }
}


/**
 * Currently selected tab for recipe.
 */
var	tabSelect = 1;

/**
 * Change tab of recipe.
 * @param id ID of new tab.
 */
function setTab(id, tabsCount){
    if (id != tabSelect) {
        for (var i = 1; i <= tabsCount; i++) {
            if (i != id) {
                if (i == 1) {
                    document.getElementById("tab_" + i + "_img").src = "../images/new/left_off_2.png";
                } else if (i == tabsCount) {
                    document.getElementById("tab_" + i + "_img").src = "../images/new/right_off.png";
                }
                document.getElementById("tab_" + i + "_cell").className = "tdBkgOff";
                document.getElementById("tabData_" + i).style.display = "none";
            } else {
                 if (i == 1) {
                    document.getElementById("tab_" + i + "_img").src = "../images/new/left_on.png";
                } else if (i == tabsCount) {
                    document.getElementById("tab_" + i + "_img").src = "../images/new/right_on_2.png";
                }
                document.getElementById("tab_" + i + "_cell").className = "tdBkgOn";
                document.getElementById("tabData_" + i).style.display = "block";
            }
        }
        tabSelect = id;
    }
}

/**
 * Fires on change-article action on the product detail page.
 *
 * @param oldArticleId Old article ID.
 * @param newArticleId New article ID.
 */
function setCurrentArticle(oldArticleId, newArticleId) {
    $('articleId').value = $('articleId_' + newArticleId).value;
    $('articleNumber').value = $('articleNumber_' + newArticleId).value;
    $('articleAmount').value = $('articleAmount_' + newArticleId).value;
    $('articleMinQuantity').value = $('articleMinQuantity_' + newArticleId).value;
    $('articleMaxQuantity').value = $('articleMaxQuantity_' + newArticleId).value;
    $('articlePricedByWeight').value = $('articlePricedByWeight_' + newArticleId).value;
    $('articleImage').src = $('articleImage_' + newArticleId).src;
    $('articleImage').writeAttribute('rel', $('articleZoomedImage_' + newArticleId).src);
    $('articlePrice').value = $('articlePriceInCent_' + newArticleId).value;
    $('articleDeposit').value = $('articleDepositInCent_' + newArticleId).value;
    $('articleDesc').childNodes[0].nodeValue = $('articleDesc_' + newArticleId).value;
    $('articlePriceDetail').childNodes[0].nodeValue = $('articlePriceDetail_' + newArticleId).childNodes[0].nodeValue;
    $('articleUnitDesc').childNodes[0].nodeValue = $('articleUnitDesc_' + newArticleId).childNodes[0].nodeValue;
    var isArticleOffer = $('articleIsOffer_' + newArticleId).value;
    if (isArticleOffer == 'true') {
        $('articlePreviousPrice').childNodes[0].nodeValue = $('articlePreviousPrice_' + newArticleId).childNodes[0].nodeValue;
        $('articleSinglePrice').removeClassName('articleNormalPrice').addClassName('articleOfferPrice');
        $('articleOfferStamp').childNodes[0].nodeValue = $('articleOfferStamp_' + newArticleId).childNodes[0].nodeValue;
        $('productOfferMiddleStamp').style.visibility = 'visible';
    } else {
        $('articleSinglePrice').removeClassName('articleOfferPrice').addClassName('articleNormalPrice');
        $('articlePreviousPrice').childNodes[0].nodeValue = '';
        $('productOfferMiddleStamp').style.visibility = 'hidden';
    }
    $$('#productArticlesTable td[id^=article' + newArticleId + ']').each(function(cell) {
        cell.addClassName('invisibleBlock');
    });
    $$('#productArticlesTable td[id^=article' + oldArticleId + ']').each(function(cell) {
        cell.removeClassName('invisibleBlock');
    });
    // recalculate sum
    calculatePriceWithoutDeposit($('articleId').value, $('articleMinQuantity').value,
            $('articleMaxQuantity').value, $('articleAmount'), $('sumAll'));
}

function price2float(t) {
    return parseFloat(t.replace(/,/, '.'));
}
function toInt(t) {
    return parseInt(t);
}
function swap(a, b) {
    var c = a.cloneNode(true);
    var d = b.cloneNode(true);
    var p = a.parentNode;
    if (p) {
        p.replaceChild(c, b);
        p.replaceChild(d, a);
    }
}
function cmpv(a, b, c, d, o) {
    return((o == 0 && (a < b || (a == b && c < d))) || (o == 1 && (b < a || (b == a && c < d))));
}
;
function qsort(t, v, i, s, e, z) {
    if (e - s < 1)return;
    var x = Math.floor((s + e) / 2);
    var p = v[x];
    var p2 = i[x];
    var l = s;
    var r = e;
    while (l <= r) {
        while (cmpv(v[l], p, i[l], p2, z))l++;
        while (cmpv(p, v[r], p2, i[r], z))r--;
        if (l <= r) {
            if (l < r) {
                swap(t[l], t[r]);
                var m = v[l];
                v[l] = v[r];
                v[r] = m;
                m = i[l];
                i[l] = i[r];
                i[r] = m;
            }
            l++;
            r--;
        }
    }
    qsort(t, v, i, s, r, z);
    qsort(t, v, i, l, e, z);
}
function sort(tablename, col, order, func) {
    var obj = document.getElementById(tablename);
    if (obj) {
        sortRows(obj.rows, col, order, func, 1);
    }
}

function sortRows(rows, col, order, func, startIndex) {
    var rowcount = rows.length - 1;
    var values = new Array();
    var indexes = new Array();
    for (var i = startIndex; i <= rowcount; i++) {
        var columns = rows[i].cells;
        indexes[i] = i;
        for (var j = 0; j < columns.length; j++) {
            if (columns[j].id.replace(/\..*/, '') == col) {
                var value = columns[j].getAttribute("value");
                if (value == null) value = columns[j].firstChild.nodeValue;
                if (func == null)
                    values[i] = value;
                else {
                    var expression = func + "('" + value + "')";
                    values[i] = eval(expression);
                }
                break;
            }
        }
    }
    qsort(rows, values, indexes, startIndex, rowcount, order);

}

function validateVisibility() {
	if ($("attention").options[$("attention").selectedIndex].value == "Geworben durch froodies Kunden")
		$("promoter").style.display = "block";
	else {
		$("promoter").value = null;
		$("promoter").style.display = "none";
	}
}

