/*
 * Common JavaScript functions
 */
 
// Global variables
var wizard;
var availableProducts = "";
var productCount = 0;
var displayedProductCount = 0;
var choices = "";
var products = "";
var orderedProducts = "";
var page;

// Constants
var stronghighlightparams = {startcolor:'#C8DE28', endcolor:'#E6EAC7', duration:0.6};
var lighthighlightparams = {startcolor:'#E6EAC7', endcolor:'#E6EAC7', duration:0.6};
var sliderparams = {duration:0.6};
var fadeparams = {duration:0.6};

// Servlet-related contants
var commandParameter = "cmd";
var startCommand = "start";
var orderCommand = "order";
var infoCommand = "info";
var summaryCommand = "summary";
var confirmCommand = "confirm";
var gotoStartCommand = "gotoStart";
var gotoOrderCommand = "gotoOrder";
var gotoInfoCommand = "gotoInfo";
var wizardParameter = "w";
var startChoicesParameter = "startChoices";
var orderChoicesParameter = "orderChoices";
var productParameter = "product";
var productsParameter = "products";

/*
 * Displays suitable products in the second column
 * depending on the choices made in the first column.
 */
function displayProducts(id) {

	// Make a note of the products that are already displayed
	var oldProductArray = products;
	
	// Make a list of new products to be displayed
	var newProductArray = getAvailableProducts(id);
	
	// Save the list of products that are displayed
	productIds = newProductArray;
	
	// Update list of choices
	products = newProductArray;
		
	// Update displayed product counter	
	displayedProductCount = newProductArray.length;
	updateDisplayedProductsCounter(id);

	// Remove any displayed description for all products
	removeDescriptions();

	// If products are displayed, then remove prompt to select a choice
	if (displayedProductCount > 0) {
		hideElement("info_choose_coloumn");
	}
	else {
		showElement("info_choose_coloumn");
	}
		
	// Remove all existing products
	removeProducts();
	
	// Display the new products
	displayAndHighlightProducts(oldProductArray, newProductArray, currentCategory);
	
	// Remove background color for all products
	removeBackgroundColor();

	// Show prompt to show product info
	showElement("info_about_coloumn");
}

/*
 * Removes descriptions for all products.
 */
function removeDescriptions() {
	for (var index = 0; index < productCount; index++) {
		elementId = availableProducts[index] + "-desc";
		hideElement(elementId);
	}
}

/*
 * Removes the list of products.
 */
function removeProducts() {
	for (var index = 0; index < productCount; index++) {
		elementId = availableProducts[index] + "-prod";
		hideElement(elementId);
	}
}

/*
 * Removes background color for all products.
 */
function removeBackgroundColor(productBase, numProducts) {
	for (var index = 0; index <= productCount; index++) {
		elementId = availableProducts[index] + "-prod";
		element = $(elementId);
		if (element !== null) {
			element.style.backgroundColor = "#fff";
		}
	}
}

/*
 * Displays and highlights products.
 */
function displayAndHighlightProducts(oldProductArray, newProductArray, cat) {
	var xcat = null;
	var id = "";
	if (id == "pkgcat01") {
		xcat = "cat1";
	}
	else if (id == "pkgcat02") {
		xcat = "cat2";
	}
	else if (id == "pkgcat03") {
		xcat = "cat3";
	}
	
	// The id is a product, not a category, so get the category
	else {
		max = productIds.length;
		for (var index = 0; index < max; index++) {
			if (id == productIds[index]) {
				cat = allProductCategories[index];
			}
		}
	} 
		
	var max = newProductArray.length;
	for (var index = 0; index < max; index++) {
		productId = newProductArray[index];
		prodCat = allProductCategories[index];
		
		// This is an old product which was already displayed
		if (inArray(oldProductArray, productId)) {
		
			// Display the product if the category is correct
			if (cat == "pkg" || cat == prodCat) {
				lightHighlightElement(productId + "-prod");
			}
		}
		
		// This is a new product which was not displayed before
		else {

			// Display the product if the category is correct
			if (cat == "pkg" || cat == prodCat) {
				strongHighlightElement(productId + "-prod");
			}
		}
	}
}

/*
 * Shows and highlights a hidden element
 */
function strongHighlightElement(elementId) {
	var element = $(elementId);
	if (element === null) {
		return;
	}
	if (element.style.display !== "block") {
		dummy = new Effect.Highlight(elementId, stronghighlightparams);
		element.style.display = "block";
	}
}

/*
 * Shows and highlights a hidden element
 */
function lightHighlightElement(elementId) {
	var element = $(elementId);
	if (element === null) {
		return;
	}
	if (element.style.display !== "block") {
		dummy = new Effect.Highlight(elementId, lighthighlightparams);
		element.style.display = "block";
	}
}

/*
 * Toggle the display of the shopping cart on and off
 */
function toggleCart() {
	var cart = $('carttoggle');
	if (cart !== null) {
		className = cart.className;
		
		// Hide shopping cart
		if (className == "expanded") {
			cart.className = null;
			hideElement('shoppingcart');
		}	

		// Show shopping cart
		else {
			cart.className = "expanded";
			showElement('shoppingcart');
		}	
	}
}

/*
 * Show the shopping cart
 */
function showCart() {
	var cart = $('carttoggle');
	cart.className = "expanded";
	showElement('shoppingcart');
}

/*
 * Hide the shopping cart
 */
function hideCart() {
	var cart = $('carttoggle');
	cart.className = null;
	hideElement('shoppingcart');
}

/*
 * Update the displayed (x/y) counter that shows the number of 
 * products displayed out of total possible products.
 */
function updateDisplayedProductsCounter() {

	// Set the number of products displayed
	var productString = "(" + displayedProductCount + "/" + productCount + ")";
	setText("productCount", productString);
}

/*
 * Displays popup text next to a link.
 */
function popup(elementId) {

	// Get the link element
	var linkElementId = elementId + "link";
	var linkElement = $(linkElementId);
	
	// Get the position of the link element
	var linkTop = getY(linkElement);
	var linkLeft = getX(linkElement);
	
	// Add the width of the link element and some air
	linkLeft += linkElement.clientWidth + 20;
	
	// Get the popup and position it
	var element = $(elementId);
	element.style.left = linkLeft + "px";
	element.style.top = linkTop + "px";
	showElement(elementId);
}

/*
 * Displays popup text next to a link.
 */
function popupError() {

	// Get the link element
	var linkElementId = "next-button";
	var linkElement = $(linkElementId);
	
	// Get the position of the link element
	var linkTop = getY(linkElement);
	var linkLeft = getX(linkElement);
	
	// Place the popup on the left side of the next button
	linkLeft -= 280;
	
	// Get the popup and position it
	var element = $("error-popup");
	element.style.left = linkLeft + "px";
	element.style.top = linkTop + "px";
	showElement("error-popup");
}

/*
 * Adds a single product to the static shopping cart
 */
 function addToStaticCart(id) {
 
	// Show the product in the shopping cart
 	showElement(id + "-cartitem");
 	 	
 	// Indicate that the product has been added
 	addToOrderedProducts(id);
 	
 	// Recalculate the total price
 	recalc();
}	

/*
 *  Shows or hides the billing address area
 */
function toggleBillingAddress() {
	var element = $("faktura_adresse_container");
	if (element.style.display == "none") {
		element.style.display = "block";
	}
	else {
		element.style.display = "none";
	}	
}

/*
 * Recalculates the total price.
 */
function recalc() {
	var price1 = 0;
	var price2 = 0;
	
	// Add all products
	var productArray = orderedProducts.split(",");
	var max = productArray.length;
	for (var index = 0; index < max; index++) {
		prod = productArray[index];
		if (prod.length > 0) {
			id1 = prod + "price1";
			id2 = prod + "price2";
			el1 = $(id1);
			el2 = $(id2);
			pr1 = el1.innerHTML;
			pr2 = el2.innerHTML;
			price1 += parseInt(pr1, 10);
			price2 += parseInt(pr2, 10);
		}
	}
	setText("totalprice1", price1);
	setText("totalprice2", price2);
}

/*
 * Adds a choice to the comma-separated list of selected choices.
 */
function addChoice(elementId) {
	var choiceArray = choices.split(",");
	if (!inArray(choiceArray, elementId)) {
		if (choices.length > 0) {
			choices += ",";
		}
		choices += elementId;
	}
}

/*
 * Adds a product to the comma-separated list of shopping cart items.
 */
function addToOrderedProducts(elementId) {
	var productArray = orderedProducts.split(",");
	if (!inArray(productArray, elementId)) {
		if (orderedProducts.length > 0) {
		orderedProducts += ",";
	}
	orderedProducts += elementId;
	}
}

/*
 * Remove an item from the list of ordered products
 */
function removeFromOrderedProducts(id) {
	var productArray = orderedProducts.split(",");
	var max = productArray.length;
	orderedProducts = "";
	for (var index = 0; index < max; index++) {
		prod = productArray[index];
		if (id !== prod)  {
			addToOrderedProducts(prod);
		}
	}
}

/*
 *  Finds out if a radio button or a checkbox is selected
 */
function isSelected(elementId) {
	var element = $(elementId);
	if (element === null) {
		return false;
	}
	return element.checked;
}

/*
 * Sets the text of an element using innerHTML.
 */
function setText(elementId, text) {
	var element = $(elementId);
	if (element !== null) {
		element.innerHTML = text;
	}
}

/*
 * Get the X coordinate of an element
 */
function getX(element) {
	var result = 0;
	while(element !== null ) {
		result += element.offsetLeft;
		element = element.offsetParent;
	}
	return result;
}

/*
 * Get the Y coordinate of an element
 */
function getY(element) {
	var result = 0;
	while(element !== null ) {
		result += element.offsetTop;
		element = element.offsetParent;
	}
	return result;
}
 
/*
 * Convert an array into a comma-separated list
 */
function array2list(array) {
	var max = array.length;
	var result = "";
	for (var index = 0; index < max; index++) {
		if (result.length > 0) {
			result += ",";
		}
		result += array[index];
	}
	return result;
}

/*
 * Check if an item exists in an array.
 */
function inArray(array, text) {
	var max = array.length;
	var result = false;
	for (var index = 0; index < max; index++) {
		if (text === array[index])  {
			return true;
		}
	}
	return false;
}

/*
 * Returns the position of an element in an array
 * or -1 if not found
 */
function posInArray(array, text) {
	var max = array.length;
	for (var index = 0; index < max; index++) {
		if (text === array[index])  {
			return index;
		}
	}
	return -1;
}

/*
 * Removes the visibility of an element
 */
function hideElement(elementId) {
	var element = $(elementId);
	if (element === null) {
		return;
	}
	if (element.style.display !== "none") {
		element.style.display = "none";
	}
}

/*
 * Fades away an element
 */
function fadeElement(elementId) {
	var element = $(elementId);
	if (element === null) {
		return;
	}
	dummy = new Effect.Fade(elementId, fadeparams);
}

/*
 *  Shows a hidden element
 */
function showElement(elementId) {
	var element = $(elementId);
	if (element === null) {
		return;
	}
	if (element.style.display !== "block") {
		element.style.display = "block";
	}
}

