/* 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 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) {	
	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;
	if (isNaN(nmbOfItems) || nmbOfItems == "")
		this.nmbOfItems = 1;
	else
		this.nmbOfItems = nmbOfItems;

	// what other combinations of unit / refUnit are possible?
	if (this.unit == this.refUnit)
		factor = 1;		
	else if (this.unit == "g" && this.refUnit == "kg" || this.unit == "ml" && this.refUnit == "l")
		factor = 1000;
	else if (this.unit == "kg" && this.refUnit == "g" || this.unit == "l" && this.refUnit == "ml")
		 factor = 0.001;
	
	this.getRefPrice = function() {		
		if (this.weighedGood == "true") 
			this.privatePrice = this.price; 
		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() {
	win = new Window({className: "alphacube", width:300, height:220, 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(" + myProduct.id + ", 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 setRating(productId, rating, title, text) {
	if (!validate(title,2,'true','commentError') || !validate(text,2,'true','commentError') || !reset)
		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 + ')');
		myProduct.averageRating = myJson.averageRating;
		myProduct.ratingCount = myJson.countRating;
	    updateRating(myProduct.averageRating, myProduct.ratingCount);	
	}
	Windows.closeAll();
	ajax("../rating.servlet.htm", "productId=" + productId + "&rating=" + rating + "&commentTitle=" + title.value + "&commentText=" + text.value, ratingResponse);	
}

/* Update rating */
function updateRating(rating, counter) {
	gv_rating = rating;
	var lv_rating = parseFloat(rating);
	// alert("Aktueller Wert: " + document.getElementById("ratingCounter").firstChild.nodeValue + " Neuer Wert: " + counter);
	document.getElementById("ratingCounter").firstChild.nodeValue = counter;
	if (lv_rating >= .5) {
		$("star1").src = "../images/16-star-hot.png";
		if (lv_rating >= 1.5) {
			$("star2").src = "../images/16-star-hot.png";
			if (lv_rating >= 2.5) {
				$("star3").src = "../images/16-star-hot.png";
				if (lv_rating >= 3.5) {
					$("star4").src = "../images/16-star-hot.png";
					if (lv_rating >= 4.5) 
						$("star5").src = "../images/16-star-hot.png";
					else 
						for (var i = 5; i < 6; i++) 
							$("star" + i).src = "../images/16-star-cold.png";
				}
				else 
					for (var i = 4; i < 6; i++) 
						$("star" + i).src = "../images/16-star-cold.png";
			}
			else 
				for (var i = 3; i < 6; i++) 
					$("star" + i).src = "../images/16-star-cold.png";
		}
		else 
			for (var i = 2; i < 6; i++) 
				$("star" + i).src = "../images/16-star-cold.png";
	}
	else 
		for (var i = 1; i < 6; i++) 
			$("star" + i).src = "../images/16-star-cold.png";
}

function paintStars(elem) {
	for (i=1; i <= 5; i++) {
		if (i <= elem.id)
			document.getElementById(i).src = "../images/16-star-hot.png";
		else
			document.getElementById(i).src = "../images/16-star-cold.png";
	}	
}

function persistRating(elem) {
	gv_rating = elem.id;
	persisted = true;
	resetField($("commentTitle"));
	resetField($("commentText"));
}

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/16-star-cold.png";	
	persisted = false;	
}

/* End rating functions */

/* Feedback functions */

function openFeedbackWindow() {
	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", "10");
	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.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", "text");
    textarea.setAttribute("name", "text");
    textarea.setAttribute("cols", "40");
    textarea.setAttribute("rows", "7");
    textarea.setAttribute("class", "text");
    textarea.setAttribute("onfocus", "enterField($('text_error')");
    
	cell_6.appendChild(textarea);
	row_6.appendChild(cell_6);
	tbody.appendChild(row_6);

	var row_7 = document.createElement("tr");
	var cell_7 = 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_7.appendChild(span);
	row_7.appendChild(cell_7);
	tbody.appendChild(row_7);
	
	var row_8 = document.createElement("tr");
	var cell_8 = 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)");
	submit_link.setAttribute("href", "javascript: sendFeedback()");
   
	var link_text = document.createTextNode("Feedback abschicken");
	submit_link.appendChild(link_text);
	
	cell_8.appendChild(submit_link);
	row_8.appendChild(cell_8);
	tbody.appendChild(row_8);
	table.appendChild(tbody);
	
	win.getContent().appendChild(table);	
	// win.setLocation(95, 750);
	win.setSize(310, 270);
	win.showCenter(true);	
	// win.toFront();
}

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"));
	}
	else {
		$("tbody_feedback").removeChild($("row_3"));
		$("tbody_feedback").removeChild($("row_4"));
	}
		
	win.setSize(300, 310);
}

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 = $("text").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);
	    Windows.closeAll();
		ajax(url, queryString, ratingResponse);	
//	}
//	else {
//		Windows.closeAll();
//	}
}

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 = 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] == "min" || splitField[1] == "max" || 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] == "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);
    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';
		}		 
}

/* this list contains images which shouldn't be replaced by the default image */
function blackList(id) {
	if (id == 'couponImage')
		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) {
	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: $(\"newShoppingList\").style.display = \"none\"; $(\"selectShoppingList\").style.display = \"block\";' 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 {$(\"articleid\").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: $(\"newShoppingList\").style.display = \"block\"; $(\"selectShoppingList\").style.display = \"none\";' 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='$(\"articleid\").value = " + articleid + "; $(\"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 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; 
}

/* mail recommendation */
function createRecommendation() {
	if (!validate($("mailrecipient"),4,"true"))
		return false;
	win = new Window({className: "alphacube", width:350, height:380, destroyOnClose: true, recenterAuto: false}); 
	win.getContent().update("<table border='0' cellpadding='5' cellspacing='3'>" + 
	"<tr><td class='text'>Guten Tag!<p>Ein Freund möchte Sie auf den Lebensmittel Online Shop Froodies aufmerksam machen.</td></tr>" +
	"<tr><td class='text'>[Möchten Sie einen eigenen Text hinzufügen? Ihr Text wird an dieser Stelle in die Mail eingefügt.]</td></tr>" + 
	"<tr><td><textarea id='ptext' cols='50' rows='5' class='grey' onclick='this.value = \"\"; this.style.color=\"black\";'>&nbsp;</textarea></td></tr>" +
	"<tr><td class='text'>&nbsp;</td></tr><tr><td class='text'>Bei uns können Sie täglich 24h aus einem vollständigen Supermarktsortiment bestellen. Wir liefern in ausgewählten Gebieten zu festgelegten Zeiten bis an die Haustür." +
	"Sollten Sie außerhalb unseres Liefergebietes wohnen, haben Sie die Möglichkeit, unseren Versandservice zu nutzen.<p>Mit diesem Link gelangen Sie zu einem außergewöhnlichen Einkaufserlebnis: http://www.froodies.de<p>Ihr Froodies Team</td></tr>" +
	"<tr><td class='alert'><span id=\"email_error\">&nbsp;</span></td></tr><tr><td>" + 
	"<input type='button' value='Mail an " + $('mailrecipient').value + " versenden' onclick='javascript: if (!validate($(\"ptext\"),2,\"true\",\"email_error\")) return false; else { $(\"personaltext\").value = $(\"ptext\").value; document.recommendationForm.submit(); }'></td></tr></table>"); 
	win.showCenter();
}

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:500,height:160,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(440,140);' 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'>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;
	$("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($("houseNumber"),1,true,houseNumber_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.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() {
	var radioObj = document.forms[1].elements["addressType"];
	var obj = null;	
	
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			obj = radioObj;
		else
			return "";	
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			obj = radioObj[i];
		}
	}
	
	$("companyContainer").style.display = "none";
	$("postalNumberContainer").style.display = "none";
	$("packstationContainer").style.display = "none";
	$("streetContainer").style.display = "none";
	$("deliveryNote").style.display = "none";	
	if (obj.value == 'private') {
		$("streetContainer").style.display = "block";
		$("deliveryNote").style.display = "block";
		document.forms[1].elements["deliveryAddressCompanyName"].value = "";
		document.forms[1].elements["deliveryAddressCompanyNameMore"].value = "";
		document.forms[1].elements["deliveryAddressPostalNumber"].value = "";
		document.forms[1].elements["deliveryAddressPackstationNumber"].value = "";
	}
	else if (obj.value == 'company') {
		$("companyContainer").style.display = "block";
		$("streetContainer").style.display = "block";
		$("deliveryNote").style.display = "block";
		document.forms[1].elements["deliveryAddressPostalNumber"].value = "";
		document.forms[1].elements["deliveryAddressPackstationNumber"].value = "";
	}
	else if (obj.value == 'packstation') {
		$("postalNumberContainer").style.display = "block";
		$("packstationContainer").style.display = "block";
		document.forms[1].elements["deliveryAddressCompanyName"].value = "";
		document.forms[1].elements["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);
}

function paypalSelected() {
	/* get paypal token by ajax call */
	var ratingResponse = function(xmlHttpRequest, json) {
		var res = xmlHttpRequest.responseText;
		var myJson = eval('(' + res + ')');
		var token = myJson.token;
		/* redirect to paypal for login */
		window.location = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&TOKEN=" + escape(token);
	}
	ajax("../admin/getPaypalToken.servlet.htm", "", ratingResponse);
}

