var cartEmptyText = new Array();
cartEmptyText["ca"] = "El carret&#243; est&#224; vuit.";
cartEmptyText["es"] = "El carro esta vacio.";

var popupTitleText = new Array();
popupTitleText["ca"] = "Instruccions especials";
popupTitleText["es"] = "Instrucciones especiales";

var popupDescText = new Array();
popupDescText["ca"] = "Si vols, pots escriure una nota per dir-nos com vols aquest producte.";
popupDescText["es"] = "Si quieres, puedes escribir una nota para decirnos como quieres este producto.";

var popupCloseText = new Array();
popupCloseText["ca"] = "Tancar";
popupCloseText["es"] = "Cerrar";

var popupNoShowText = new Array();
popupNoShowText["ca"] = "No mostrar més";
popupNoShowText["es"] = "No mostrar más";

var cartPickupText = new Array();
cartPickupText["ca"] = "Recollida a la nostra botiga";
cartPickupText["es"] = "Recogida en nuestra tienda";

var cartDeliveryText = new Array();
cartDeliveryText["ca"] = "Lliurament a domicili";
cartDeliveryText["es"] = "Entrega a domicilio";

var cartChangeDeliveryOption = new Array();
cartChangeDeliveryOption["ca"] = "Canviar l'opció de lliurament";
cartChangeDeliveryOption["es"] = "Cambiar la opción de entrega";

var cartChangeDeliveryHint = new Array();
cartChangeDeliveryHint["ca"] = "Indiqui l'opció de lliurament";
cartChangeDeliveryHint["es"] = "Indique la opción de entrega";

var ieVers;

if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
	ieVers = new Number(RegExp.$1);
}

//alert (ieVers);

function addEvent(elm, evType, fn, useCapture)
// cross-browser event handling for IE5+, NS6+ and Mozilla 
// By Scott Andrew 
{
  if (elm.addEventListener) { 
    elm.addEventListener(evType, fn, useCapture); 
    return true; 
  } else if (elm.attachEvent) { 
    var r = elm.attachEvent('on' + evType, fn); 
    return r; 
  } else {
    elm['on' + evType] = fn;
  }
}

function dropEvent(elm, evType, fn, useCapture)
// cross-browser event handling for IE5+, NS6+ and Mozilla 
// By Greg Robbins :P 
{
  if (elm.removeEventListener) { 
    elm.removeEventListener(evType, fn, useCapture); 
    return true; 
  } else if (elm.detachEvent) { 
    var r = elm.detachEvent('on' + evType, fn); 
    return r; 
  } else {
    elm['on' + evType] = null;
  }
}

// climb up the tree to the supplied tag.
function ascendDOM(e, target) {
  while (e.nodeName.toLowerCase() != target && e.nodeName.toLowerCase() != 'html')
  {
  	e = e.parentNode;
  	alert(e);
  }
  return (e.nodeName.toLowerCase() == 'html') ? null : e;
}

function fetchTarget(e)
{
	if(window.event && window.event.srcElement)
	{
		return window.event.srcElement;
	}
	else if(e && e.target)
	{
		return e.target;
	}
	else
	{
		return;
	}
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		//alert(curleft);
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			//alert(obj.tagName);
			curleft += obj.offsetLeft
			//alert(obj.tagName + "(" + obj.id + "): " + obj.offsetLeft)
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function cancelClick(e)
{
	if (window.event) {
      window.event.cancelBubble = true;
      window.event.returnValue = false;
    }
    if (e && e.stopPropagation && e.preventDefault) {
      e.stopPropagation();
      e.preventDefault();
    }
	return false;
}


function addAllEvents()
{
	fetchCartButtons();
	fetchCartSelects();
	fetchDropButtons();
	fetchCitySelector();
	fetchLoginButton();
	fetchCreateButton();
	fetchLoginActivate();
	fetchCityLinks();
	loadDeliveryChkbx();
	loadClientArea();
	loadCartChangeDeliveryOption();
}

var allowPopups = true;

function detectEvents(str)
{
	data = str.split("_");
	return data;
}

function fetchCartButtons()
{
	allButtons = document.getElementsByTagName("INPUT");
	for(i = 0; i < allButtons.length; i++)
	{
		if(allButtons[i].id.match(/addCart(S?)_([0-9]+)/))
		{
			addEvent(allButtons[i], "click", addCart, false);
			addEvent(allButtons[i], "mouseover", cartButtonRollOn, false);
			addEvent(allButtons[i], "mouseout", cartButtonRollOff, false);
			allButtons[i].onclick = cancelClick;
		}
	}
}

function cartButtonRollOn(e)
{
	target = fetchTarget(e);
	target.src = isPro ? "img_std/pro_button_on.gif" : "img_std/cart_button_on.gif";
	return;
}

function cartButtonRollOff(e)
{
	target = fetchTarget(e);
	target.src = isPro ? "img_std/pro_button_off.gif" : "img_std/cart_button_off.gif";
	return;
}

function fetchCartSelects()
{
	cartItemsObj = document.getElementById("cartItems");
	if(cartItemsObj)
	{
		cartSelects = cartItemsObj.getElementsByTagName("SELECT");
		for(i = 0; i < cartSelects.length; i++)
		{
			addEvent(cartSelects[i], "change", changeCart, false);
		}
	}
}

function fetchCitySelector()
{
	cityIdSelectorObj = document.getElementById("cityIdSelector");
	if(cityIdSelectorObj) addEvent(cityIdSelectorObj, "change", selectCity, false);
}

function addCart(e)
{
	target = fetchTarget(e);
	match = target.id.match(/addCart(S?)_([0-9]+)/);
	idItem = match[2];
	isSaleItem = match[1] == "" ? false : true;
	
	//alert(idItem + ", " + isSaleItem);
	
	usePricePrefix = isSaleItem ? "usePriceS_" : "usePrice_";
	itemQtyPrefix = isSaleItem ? "itemQtyS_" : "itemQty_";
	
	usePriceObj = document.getElementById(usePricePrefix + idItem);
	usePriceVal = usePriceObj.value;
	
	itemQtyObj = document.getElementById(itemQtyPrefix + idItem);
	itemQtyVal = itemQtyObj.selectedIndex;
	
	//alert(idItem + ", " + usePriceVal + ", " + itemQtyVal);
	ajaxObj.call("action=ajaxCart&myAction=addCart&idItem=" + idItem + "&usePriceVal=" + usePriceVal + "&itemQtyVal=" + itemQtyVal, addCartResp);
	
	if(window.event)
	{
		window.event.cancelBubble = true;
		window.event.returnValue = false;
	}
	if(e && e.stopPropagation && e.preventDefault)
	{
		e.stopPropagation();
		e.preventDefault();
	}
}

function changeCart(e)
{
	target = fetchTarget(e);
	
	//itemQty_201_public
	parts = target.id.split("_");
	
	isDrop = parts[0] == "drop" ? true : false;
	idItem = parts[1];
	usePriceVal = parts[2];
	
	if(!isDrop)
	{
		itemQtyVal = target.options[target.selectedIndex].value;
		useAction = itemQtyVal == "x" ? "dropCart" : "updateCart";
	}
	else
	{
		itemQtyVal = "x";
		useAction = "dropCart";
	}
	ajaxObj.call("action=ajaxCart&myAction=" + useAction + "&idItem=" + idItem + "&usePriceVal=" + usePriceVal + "&itemQtyVal=" + itemQtyVal, addCartResp);
	
	if(window.event)
	{
		window.event.cancelBubble = true;
		window.event.returnValue = false;
	}
	if(e && e.stopPropagation && e.preventDefault)
	{
		e.stopPropagation();
		e.preventDefault();
	}
}


function addCartResp(resp)
{
	//return;
	idItem = resp.idItem;
	usePriceGroup = resp.usePriceGroup;
	qty = resp.qty;
	
	myAction = resp["queryVars"]["myAction"];
	//alert(resp);
	//alert(idItem + ", " + usePriceGroup + ", " + qty);
	
	itemContainerObjId = "cartItem_" + idItem + "_" + usePriceGroup;
	
	//find item in cart
	itemContainerObj = document.getElementById(itemContainerObjId);
	
	//if found
	if(itemContainerObj)
	{
		if(qty == "x")
		{
			cartListObj = document.getElementById("cartItems");
			cartListObj.removeChild(itemContainerObj);
			
			cartListItems = cartListObj.getElementsByTagName("LI");
			//alert(cartListItems.length);
			if(cartListItems.length == 0)
			{
				cartEmpty = document.createElement("LI");
				cartEmpty.id = "emptyCart";
				cartEmpty.innerHTML = cartEmptyText[pageLang];
				cartListObj.appendChild(cartEmpty);
			}
		}
		else
		{
			//alert("Found itemContainerObj: " + itemContainerObjId);
			selectObj = document.getElementById("itemQty_" + idItem + "_" + usePriceGroup);
			selectObj.selectedIndex = parseInt(qty) + 1;
			cartPriceObj = document.getElementById("itemPrice_" + idItem + "_" + usePriceGroup);
			newItemAmount = resp.item.amount.replace(/\./g, ",") + " &euro;";
			if(resp.item.isAproxPrice == true) newItemAmount += "*";
			cartPriceObj.innerHTML = newItemAmount;
		}
	}
	else
	{
		//alert("Not found: " + itemContainerObjId);
		cartItemObj = createCartItem(resp.item);
		cartListObj = document.getElementById("cartItems");
		cartListObj.insertBefore(cartItemObj, cartListObj.firstChild);
		
		emptyCartObj = document.getElementById("emptyCart");
		if(emptyCartObj)
		{
			cartListObj.removeChild(emptyCartObj);
		}
	}
	
	cartTotalAmountObj = document.getElementById("cartTotalAmount");
	cartTotalAmountCheckoutObj = document.getElementById("cartTotalAmountCheckout");
	isMinOrderAlertObj = document.getElementById("isMinOrderAlert");
	
	//alert(resp.cartTotal);
	cartTotalVal = resp.cartTotal.toFixed(2) + "";
	cartTotalAmountObj.innerHTML = cartTotalVal.replace(/\./g, ",");
	
	//if(cartTotalAmountObj && isMinOrderAlertObj)
	if(isMinOrderAlertObj)
	{
		//cartTotalAmountObj.innerHTML = cartTotalVal.replace(/\./g, ",");
		if(resp.isMinOrder == true)
		{
			//cartTotalAmountCheckoutObj.className = "";
			isMinOrderAlertObj.style.display = "none";
		}
		else
		{
			//cartTotalAmountCheckoutObj.className = "error";
			isMinOrderAlertObj.style.display = "block";
		}
	}
	
	orderButtonObj = document.getElementById("orderButton");
	//have to use this in the checkout cart
	if(!orderButtonObj) orderButtonObj = document.getElementById("orderButtonX");
	minOrderObj = document.getElementById("minOrder");
	
	if(orderButtonObj)
	{
		if(resp.isMinOrder == true)
		{
			orderButtonObj.style.display = "block";
			if(minOrderObj) minOrderObj.style.display = "none";
		}
		else
		{
			orderButtonObj.style.display = "none";
			if(minOrderObj) minOrderObj.style.display = "block";
		}
	}
	
	orderButtonHintObj = document.getElementById("orderButtonHint");
	orderButtonWarnObj = document.getElementById("orderButtonWarn");
	
	if(orderButtonHintObj && orderButtonWarnObj)
	{		
		if(resp.isMinOrder == true)
		{
			orderButtonObj.style.display = "block";
			orderButtonHintObj.style.display = "block";
			orderButtonWarnObj.style.display = "none";
		}
		else
		{
			orderButtonObj.style.display = "none";
			orderButtonHintObj.style.display = "none";
			orderButtonWarnObj.style.display = "block";
		}
	}
	
	if (myAction == "addCart") {
		cartButtonObj = document.getElementById("addCart_" + idItem);
		if(cartButtonObj)
		{
			createCartCommentPopup(cartButtonObj);
		}
	}
}

function createCartItem(itemObj)
{
	cartItemObj = document.createElement('LI');
	cartItemObj.className = 'cartItem';
	cartItemObj.id = "cartItem_" + itemObj.id + "_" + itemObj.priceGroup;
	//title of item
	escTitle = unescape(itemObj.title);
	itemTitle = document.createTextNode(escTitle);
	cartItemObj.appendChild(itemTitle);
	cartItemObj.appendChild(document.createElement('BR'));
	//price
	cartPriceObj = document.createElement("DIV");
	cartPriceObj.className = "price";
	cartPriceObj.id = "itemPrice_" + itemObj.id + "_" + itemObj.priceGroup;
	cartPriceObj.innerHTML = itemObj.amount.replace(/\./g, ",");
	cartPriceObj.innerHTML += " &euro;";
	if(itemObj.isAproxPrice == true)
	{
		cartPriceObj.innerHTML += "*";
	}
	cartItemObj.appendChild(cartPriceObj);
	//delete button
	dropObj = document.createElement("IMG");
	dropObj.setAttribute('id', "drop_" + itemObj.id + "_" + itemObj.priceGroup);
	dropObj.setAttribute('name', "drop_" + itemObj.id + "_" + itemObj.priceGroup);
	dropObj.setAttribute('class', "drop");
	dropObj.setAttribute('style', "float:left;");
	dropObj.setAttribute('src', "img_std/drop_off.gif");
	addEvent(dropObj, "click", changeCart, false);
	addEvent(dropObj, "mouseover", cartDropOn, false);
	addEvent(dropObj, "mouseout", cartDropOff, false);
	cartItemObj.appendChild(dropObj);

	//select menu
	selectObj = document.createElement('SELECT');
	selectObj.setAttribute('id', "itemQty_" + itemObj.id + "_" + itemObj.priceGroup);
	selectObj.setAttribute('name', "itemQty_" + itemObj.id + "_" + itemObj.priceGroup);
	for(sProp in itemObj.cartMenu)
	{
		newOption = createCartItemOption(itemObj.qty, sProp, itemObj.cartMenu[sProp]);
		selectObj.appendChild(newOption);
	}
	
	addEvent(selectObj, "change", changeCart, false);
	cartItemObj.appendChild(selectObj);
	
	return cartItemObj;
}











function createCartItemOption(qty, key, val)
{
	optionObj = document.createElement('OPTION');
	optionObj.setAttribute('label', val);
	optionObj.setAttribute('value', key);
	optionObj.innerHTML = val;
	if(qty == key)
	{
		optionObj.selected = true;
	}
	
	return optionObj;
}

function assignDeliveryCheckboxes()
{
	inputs = document.getElementsByTagName("INPUT");
	if(!inputs) return false;
	if(!initSelTimes) return false;
	
	for(i in inputs)
	{
		if (inputs[i].type != "checkbox") continue;
		//alert(inputs[i].id);
		for(j in initSelTimes)
		{
			if(initSelTimes[j] == inputs[i].id)
			{
				inputs[i].checked = true;
			}
		}
		addEvent(inputs[i], "change", changeDeliveryChkBx, false);
	}
}

function changeDeliveryChkBx(e)
{
	target = fetchTarget(e);
	match = target.id.match(/dayId_([0-9]+)_timeId_([0-9]+)/);
	dayId = match[1];
	timeId = match[2];
	isChecked = target.checked;
	
	//alert("dayId = " + dayId + ", timeId = " + timeId + ", cityId = " + cityId + ", value = " + isChecked);
	ajaxObj.call("action=ajaxSetDelivery&dayId=" + dayId + "&timeId=" + timeId + "&cityId=" + cityId + "&value=" + isChecked, changeDeliveryChkBxResp);
}

function selectCity(e)
{
	target = fetchTarget(e);
	ajaxObj.call("action=ajaxSelectCity&cityId=" + target.value + "&pageLang=" + pageLang, selectCityResp);
}

function selectCityResp(resp)
{
	//alert(resp);
	min_orderObj = document.getElementById("min_order");
	if(min_orderObj) min_orderObj.innerHTML = resp["min_order"];
	
	isMinOrderAlertObj = document.getElementById("isMinOrderAlert");
	
	if(isMinOrderAlertObj)
	{
		isMinOrderAlertObj.style.display = resp["isMinOrder"] ? "none" : "block";
	}
	
	minOrderValObj = document.getElementById("minOrderVal");
	minOrderVal2Obj = document.getElementById("minOrderVal2");
	if(minOrderValObj && minOrderVal2Obj)
	{
		minOrderValObj.innerHTML = resp.min_order + " &euro;";
		minOrderVal2Obj.innerHTML = resp.min_order + " &euro;";
	}
	
	orderButtonObj = document.getElementById("orderButtonX");
	orderButtonHintObj = document.getElementById("orderButtonHint");
	orderButtonWarnObj = document.getElementById("orderButtonWarn");
	
	if(orderButtonObj && orderButtonHintObj && orderButtonWarnObj)
	{		
		if(resp.isMinOrder == true)
		{
			orderButtonObj.style.display = "block";
			orderButtonHintObj.style.display = "block";
			orderButtonWarnObj.style.display = "none";
		}
		else
		{
			orderButtonObj.style.display = "none";
			orderButtonHintObj.style.display = "none";
			orderButtonWarnObj.style.display = "block";
		}
	}
	
	deliveryTableObj = document.getElementById("deliveryTable");
	if(deliveryTableObj)
	{
		//Remove rows
		tBodyObj = deliveryTableObj.getElementsByTagName("TBODY")[0];
		dropRows = tBodyObj.childNodes;
		while(tBodyObj.childNodes[0])
		{
			tBodyObj.removeChild(tBodyObj.childNodes[0]);
		}
		
		days = resp["matrix"]["days"];
		
		for(i = 0; i < days.length; i++)
		{
			timeStamp = days[i]["date"];
			d = new Date();
			d.setTime(timeStamp * 1000);
			
			//fix month display
			monthString = d.getMonth() + 1;
			monthString = monthString.toString();
			monthString = monthString.length == 1 ? "0" + monthString : monthString;
			
			//make formatted date
			formattedDate = d.getDate() + "." + monthString + "." + d.getFullYear();
			
			//create row
			trObj = document.createElement("TR");
			
			//create TH with day name
			thObj = document.createElement("TH");
			thObj.innerHTML = days[i]["weekday"] + ", " + formattedDate;
			//last generated row needs noBorder class
			if(i == (days.length - 1))
			{
				thObj.className = "noBorder";
			}
			
			trObj.appendChild(thObj);
			
			//create new TD
			tdObj = document.createElement("TD");
			//last generated row needs noBorder class
			if(i == (days.length - 1))
			{
				tdObj.className = "noBorder";
			}
			
			//loop thru times
			times = days[i]["times"];
			for(j = 0; j < times.length; j++)
			{
				startTime = times[j]["start_time"].substring(0,5);
				endTime = times[j]["end_time"].substring(0,5);
				idTime = times[j]["id_time"];
				
				//create radio
				if(!document.all)
				{
					radioObj = document.createElement("INPUT");
					radioObj.type = "radio";
					radioObj.name = "delivery_date";
					radioObj.value = "idTime_" + idTime + "_date_" + timeStamp;
					radioObj.id = "idTime_" + idTime;
				}
				else
				{
					radioObj = document.createElement('<input type="radio" name="delivery_date" value="idTime_' + idTime + '_date_' + timeStamp + '" id="idTime_' + idTime + '" />');
				}
				
				//addEvent(radioObj, "click", alertClick, false);
				
				//append radio
				tdObj.appendChild(radioObj);
				
				//create label
				labelObj = document.createElement("LABEL");
				//labelObj.htmlFor = radioObj.id;
				labelObj.innerHTML = "de " + startTime + " a " + endTime;
				
				//append label
				tdObj.appendChild(labelObj);
				
				//line br
				breakObj = document.createElement("BR");
				tdObj.appendChild(breakObj);
			}
			
			trObj.appendChild(tdObj);
			
			//append new row
			tBodyObj.appendChild(trObj);
		}
		
		//make last rounded row
		lastCellObj = document.createElement("TD");
		lastCellObj.className = "bottomRow";
		lastCellObj.colSpan = 2;
		lastCellObj.innerHTML = "&nbsp;";
		lastRowObj = document.createElement("TR");
		lastRowObj.appendChild(lastCellObj);
		tBodyObj.appendChild(lastRowObj);
	}
}


function alertClick(e)
{
	target = fetchTarget(e);
	alert(target.id);
}

/*
  5 => Array (4)
    weekday => viernes
    iso_day => 5
    times => Array (3)
      0 => Array (3)
        start_time => 08:30:00
        end_time => 13:00:00
        id_time => 27
      1 => Array (3)
        start_time => 15:00:00
        end_time => 18:00:00
        id_time => 28
      2 => Array (3)
        start_time => 18:00:00
        end_time => 21:00:00
        id_time => 29
    date => 1182463200
    
    
<tr>
	<th>viernes, 22.06.2007</th>
	<td>
		<input type="radio" name="delivery_date" title="" value="idTime_27_date_1182463200" id="idTime_27" />
		<label for="idTime_27">de 08:30 a 13:00</label>
		<br />
		<input type="radio" name="delivery_date" title="" value="idTime_28_date_1182463200" id="idTime_28" />
		<label for="idTime_28">de 15:00 a 18:00</label>
		<br />
		<input type="radio" name="delivery_date" title="" value="idTime_29_date_1182463200" id="idTime_29" />
		<label for="idTime_29">de 18:00 a 21:00</label>
		<br />
	</td>
</tr>

 */

function changeDeliveryChkBxResp(resp)
{
	//alert(resp);
	return;
}

function clientLogin()
{
	usernameObj = document.getElementById("usernameInput");
	passwordObj = document.getElementById("passwordInput");
	
	if(usernameObj && passwordObj)
	{
		usernameVal = usernameObj.value;
		passwordVal = passwordObj.value;
		ajaxObj.call("action=ajaxCustomerLogin&myAction=login&username=" + usernameVal + "&password=" + passwordVal + "&lang=" + pageLang, clientLoginResp);
	}
}

function clientLogout()
{
	ajaxObj.call("action=ajaxCustomerLogin&myAction=logout&lang=" + pageLang, clientLoginResp);
}

function clientLoginResp(resp)
{
	//passed values
	loginStatus = resp["loginStatus"];
	nameVal = resp["name"];
	displayVal = resp["display"];
	//get these values from document
	loginContainerObj = document.getElementById("loginContainer");
	loginErrorObj = document.getElementById("loginError");
	
	//fetch ncessary objects
	firstNameObj = document.getElementById("first_name");
	lastNameObj = document.getElementById("last_name");
	address1Obj = document.getElementById("address_1");
	address2Obj = document.getElementById("address_2");
	address3Obj = document.getElementById("address_3");
	phoneObj = document.getElementById("phone");
	cellObj = document.getElementById("cell");
	companyNameObj = document.getElementById("company_name");
	nifObj = document.getElementById("nif");
	emailObj = document.getElementById("email");
	
	switch(loginStatus)
	{
		//logged in correctly
		case 1 :
			loginContainerObj.innerHTML = displayVal;
			fetchLoginActivate();
			fetchLoginButton();
			selectCityResp(resp);
			setCityMenu(resp["id_city"]);
			firstNameObj.value = resp["first_name"];
			lastNameObj.value = resp["last_name"];
			address1Obj.value = resp["address_1"];
			address2Obj.value = resp["address_2"];
			address3Obj.value = resp["address_3"];
			phoneObj.value = resp["phone"];
			cellObj.value = resp["cell"];
			companyNameObj.value = resp["company_name"];
			nifObj.value = resp["nif"];
			emailObj.value = resp["email"];
			break;
		//logged off correctly
		case 0 : 
			loginContainerObj.innerHTML = displayVal;
			loginActivateSwitch();
			fetchLoginButton();
			selectCityResp(resp);
			setCityMenu(resp["id_city"]);
			firstNameObj.value = "";
			lastNameObj.value = "";
			address1Obj.value = "";
			address2Obj.value = "";
			address3Obj.value = "";
			phoneObj.value = "";
			cellObj.value = "";
			companyNameObj.value = "";
			nifObj.value = "";
			emailObj.value = "";
			break;
		//login failed
		case -1 :
			if(loginErrorObj)
			{
				loginErrorObj.style.display = "block";
			}
		
	}
}

function setCityMenu(id_city)
{
	cityIdSelectorObj = document.getElementById("cityIdSelector");
	
	if(cityIdSelectorObj)
	{
		for(i = 0; i < cityIdSelectorObj.options.length; i++)
		{
			if (cityIdSelectorObj.options[i].value == id_city)
			{
				cityIdSelectorObj.options[i].selected = true;
			}
		}
	}
}

function fetchLoginButton()
{
	loginButtonObj = document.getElementById("loginButton");
	logoutLinkObj = document.getElementById("logoutLink");
	if(loginButtonObj)
	{
		addEvent(loginButtonObj, "click", clientLogin, false);
	}
	if(logoutLinkObj)
	{
		addEvent(logoutLinkObj, "click", clientLogout, false);
	}
}


function fetchCreateButton()
{
	createButtonObj = document.getElementById("createButton");
	
	if(createButtonObj)
	{
		addEvent(createButtonObj, "click", createUser, false);
	}
}

function createUser()
{
	passwordInputObj = document.getElementById("passwordInput");
	password2InputObj = document.getElementById("password2Input");
	createErrorObj = document.getElementById("createError");
	
	if(passwordInputObj.value != password2InputObj.value)
	{
		createErrorObj.style.display = "block";
		return;
	}
	
	ajaxObj.call("action=ajaxCreateUser&password=" + passwordInputObj.value + "&lang=" + pageLang, createUserResp);
}

function createUserResp(resp)
{
	displayVal = resp["display"];
	loginContainerObj = document.getElementById("loginContainer");
	
	if(loginContainerObj)
	{
		loginContainerObj.innerHTML = displayVal;
	}
}


function loadConstantDivs()
{
	allTds = document.getElementsByTagName("TD");
	for(i = 0; i < allTds.length; i++)
	{
		myTd = allTds[i];
		match = myTd.id.match(/const_(ca|es)_([0-9]+)/)
		if(match)
		{
			myTd.lang = match[1];
			myTd.constId = match[2];
		}
	}
}

function loadConstantControls()
{
	allButtons = document.getElementsByTagName("A");
	for(i = 0; i < allButtons.length; i++)
	{
		myButton = allButtons[i];
		match = myButton.id.match(/control_([0-9]+)/)
		if(match)
		{
			myButton.constId = match[1];
			addEvent(myButton, "click", editConst, false);
		}
	}
}

function editConst(e)
{
	target = fetchTarget(e);
	
	caConstId = "const_ca_" + target.constId;
	constObj = document.getElementById(caConstId);
	
	dropEvent(constObj, "click", editConst, false);
	constVal = constObj.innerHTML;
	textAreaObj = document.createElement("Textarea");
	textAreaObj.innerHTML = unescape(constVal);
	textAreaObj.className = "constEditTextArea";
	textAreaObj.id = "editConst_ca_" + constObj.constId;
	constObj.innerHTML = null;
	constObj.appendChild(textAreaObj);
	
	esConstId = "const_es_" + target.constId;
	constObj = document.getElementById(esConstId);
	
	dropEvent(constObj, "click", editConst, false);
	constVal = constObj.innerHTML;
	textAreaObj = document.createElement("Textarea");
	textAreaObj.innerHTML = unescape(constVal);
	textAreaObj.className = "constEditTextArea";
	textAreaObj.id = "editConst_es_" + constObj.constId;
	constObj.innerHTML = null;
	constObj.appendChild(textAreaObj);
	
	target.innerHTML = "Guardar";
	dropEvent(target, "click", editConst, false);
	addEvent(target, "click", saveConst, false);
}

function saveConst(e)
{
	target = fetchTarget(e);
	
	caEditConstObj = document.getElementById("editConst_ca_" + target.constId);
	caConstVal = caEditConstObj.value;
	esEditConstObj = document.getElementById("editConst_es_" + target.constId);
	esConstVal = esEditConstObj.value;
	
	ajaxObj.call("action=ajaxUpdateConst&id=" + target.constId + "&es=" + escape(esConstVal) + "&ca=" + escape(caConstVal), updateConstResp);
}

function updateConstResp(resp)
{
	if(resp["result"] != true) return;
	id = resp["id"];
	
	caTd = document.getElementById("const_ca_" + id);
	caEditConstObj = document.getElementById("editConst_ca_" + id);
	caConstVal = caEditConstObj.value;
	caTd.removeChild(caEditConstObj);
	caTd.innerHTML = caConstVal;
	
	esTd = document.getElementById("const_es_" + id);
	esEditConstObj = document.getElementById("editConst_es_" + id);
	esConstVal = esEditConstObj.value;
	esTd.removeChild(esEditConstObj);
	esTd.innerHTML = esConstVal;
	
	controlObj = document.getElementById("control_" + id);
	controlObj.innerHTML = "Editar";
	dropEvent(controlObj, "click", saveConst, false);
	addEvent(controlObj, "click", editConst, false);
}


function fetchLoginActivate()
{
	loginActivateObj = document.getElementById("loginActivate");
	loginDeactivateObj = document.getElementById("loginDeactivate");
	
	if(!loginActivateObj) return;
	addEvent(loginActivateObj, "click", loginActivateSwitch, false);
	if(!loginDeactivateObj) return;
	addEvent(loginDeactivateObj, "click", loginActivateSwitch, false);
}

function loginActivateSwitch()
{
	loginOnObj = document.getElementById("loginOn");
	loginOffObj = document.getElementById("loginOff");
	
	//alert(loginOffObj.style.display);
	
	if(loginOffObj.style.display == "block")
	{
		loginOffObj.style.display = "none";
		loginOnObj.style.display = "block";
	}
	else
	{
		loginOffObj.style.display = "block";
		loginOnObj.style.display = "none";
	}
}

function fetchCityLinks()
{
	allAnchors = document.getElementsByTagName("A");
	//cityView_11
	for(i = 0; i < allAnchors.length; i++)
	{
		if(allAnchors[i].id.match(/cityView_([0-9]+)/))
		{
			addEvent(allAnchors[i], "click", cityView, false);
		}
	}
}

function cityView(e)
{
	target = fetchTarget(e);
	
	myMatch = target.id.match(/[0-9]+/);
	cityId = myMatch[0];
	
	ajaxObj.call("action=ajaxViewCity&cityId=" + cityId + "&lang=" + pageLang, cityViewResp);
}

function cityViewResp(resp)
{
	cityInfoDispObj = document.getElementById("cityInfoDisp");
	cityInfoDispObj.innerHTML = resp;
}

function fetchDropButtons()
{
	cartItemsObj = document.getElementById("cartItems");
	if(cartItemsObj)
	{
		cartDrops = cartItemsObj.getElementsByTagName("IMG");
		for(i = 0; i < cartDrops.length; i++)
		{
			if(!cartDrops[i].id.match(/^drop_/)) continue;
			addEvent(cartDrops[i], "mouseover", cartDropOn, false);
			addEvent(cartDrops[i], "mouseout", cartDropOff, false);
			addEvent(cartDrops[i], "click", changeCart, false);
		}
	}
}

function cartDropOn(e)
{
	target = fetchTarget(e);
	target.src = "img_std/drop_on.gif";
}

function cartDropOff(e)
{
	target = fetchTarget(e);
	target.src = "img_std/drop_off.gif";
}


function loadDeliveryChkbx()
{
	isPickupObj = document.getElementById("isPickup");
	isDeliveryObj = document.getElementById("isDelivery");
	isXmasObj = document.getElementById("isXmas");
	if(!isPickupObj || !isDeliveryObj) return;
	addEvent(isPickupObj, "click", isDeliveryChange, false);
	addEvent(isDeliveryObj, "click", isDeliveryChange, false);
	if(isXmasObj) addEvent(isXmasObj, "click", isDeliveryChange, false);
}

function isDeliveryChange(e)
{
	radioObj = document.forms.clientForm.deliverySelect;
	deliveryValue = false;
	for(i = 0; i < radioObj.length; i++)
	{
		if(radioObj[i].checked) deliveryValue = radioObj[i].value;
	}
	
	//alert(deliveryValue);
	
	addressTRObj = document.getElementById("addressTR");
	cityTRObj = document.getElementById("cityTR");
	
	switch(deliveryValue)
	{
		case false:
			
			break;
		case "isPickup" :
			addressTRObj.style.display = "none";
			cityTRObj.style.display = "none";
			break;
		case "isDelivery" :
			addressTRObj.style.display = "";
			cityTRObj.style.display = "";
			break;
		case "isXmas" :
			addressTRObj.style.display = "none";
			cityTRObj.style.display = "none";
	}
	
	ajaxObj.call("action=ajaxOrderDeliveryOption&deliveryType=" + deliveryValue, ajaxOrderDeliveryOptionResp);
}

function ajaxOrderDeliveryOptionResp(resp)
{
	//alert(resp);
	if(resp["isDelivery"] == true)
	{
		//alert("isDelivery");
		cityIdSelectorObj = document.getElementById("cityIdSelector");
		//alert(cityIdSelectorObj.value);
		idCity = cityIdSelectorObj.value;
		ajaxObj.call("action=ajaxSelectCity&cityId=" + idCity + "&pageLang=" + pageLang, selectCityResp);
	} 
	else if (resp["isXmas"] == true)
	{
		//alert("isXmas");
		ajaxObj.call("action=ajaxSelectCity&cityId=xmas&pageLang=" + pageLang, selectCityResp);
	}
	else if (resp["isInStorePickup"] == true)
	{
		//alert("isInStorePickup");
		ajaxObj.call("action=ajaxSelectCity&cityId=store&pageLang=" + pageLang, selectCityResp);
	}
}




function isDeliveryChangeX(e)
{
	target = fetchTarget(e);
	checkedOption = target.id;
	//alert(checkedOption);
	
	isPickupObj = document.getElementById("isPickup");
	isDeliveryObj = document.getElementById("isDelivery");
	
	addressTRObj = document.getElementById("addressTR");
	cityTRObj = document.getElementById("cityTR");
	
	deliveryState = "";
	
	if(isPickupObj.checked == false && isDeliveryObj.checked == false)
	{
		//alert("no checked items");
		deliveryState = "none";
	}
	
	if(isPickupObj.checked == true && isDeliveryObj.checked == true)
	{
		//alert("both checked items");
		if(isPickupObj.id == checkedOption) isDeliveryObj.checked = false;
		if(isDeliveryObj.id == checkedOption) isPickupObj.checked = false;
	}
	
	if(isPickupObj.checked == false && isDeliveryObj.checked == true)
	{
		alert(addressTRObj.style.display);
		//alert("delivery checked");
		//addressTRObj.style.display = "table-row";
		//cityTRObj.style.display = "table-row";
	}
	
	if(isPickupObj.checked == true && isDeliveryObj.checked == false)
	{
		alert(addressTRObj.style.display);
		//alert("pickup checked");
		//addressTRObj.style.display = "none";
		//cityTRObj.style.display = "none";
	}
	
	
	return;
	if (target.checked == true)
	{
		//alert("checked delivery");
		isPickupObj = document.getElementById("isPickup");
		isPickupObj.checked = false;
		

	}
	else
	{
		//alert("unchecked delivery");
	}
}

function setDeliveryState()
{
	
}

function setPickupState()
{
	
}




function noShowPopups()
{
	allowPopups = false;
}

function createCartCommentPopup(buttonObj)
{
	if (allowPopups == false) return;
	
	popupObj = document.createElement("div");
	popupObj.className = "cartCommentPopup";
	buttonPos = findPos(buttonObj);
	idItem = buttonObj.id.match(/addCart_([0-9]+)/)[1];
	popupObj.id = "cartCommentPopup_" + idItem;
	
	popupObjContainer = document.createElement("div");
	popupObjContainer.className = "cartCommentPopupContainer";
	popupObj.appendChild(popupObjContainer);
	
	closeButton = document.createElement("img");
	closeButton.src = "img_std/drop_off.gif";
	closeButton.id = "cartCommentPopupClose_" + idItem;
	closeButton.className = "closeButton";
	addEvent(closeButton, "click", closeCartCommentPopup, false);
	addEvent(closeButton, "mouseover", cartDropOn, false);
	addEvent(closeButton, "mouseout", cartDropOff, false);
	popupObjContainer.appendChild(closeButton);
	
	popupTitleObj = document.createElement("h3");
	popupTitleObj.innerHTML = popupTitleText[pageLang];
	popupObjContainer.appendChild(popupTitleObj);
	
	popupDescObj = document.createElement("p");
	popupDescObj.innerHTML = popupDescText[pageLang];
	popupObjContainer.appendChild(popupDescObj);
	
	popupCommentBox = document.createElement("textarea");
	popupCommentBox.id = "comment_" + idItem;
	popupObjContainer.appendChild(popupCommentBox);
	
	popupSaveButton = document.createElement("a");
	popupSaveButton.href = "#";
	addEvent(popupSaveButton, "click", cancelClick, false);
	popupSaveButton.className = "saveButton";
	popupSaveButton.innerHTML = "OK";
	popupSaveButton.id = "commentSave_" + idItem;
	addEvent(popupSaveButton, "click", savePopupComment, false);
	popupObjContainer.appendChild(popupSaveButton);
	
	popupFooterObj = document.createElement("p");
	popupFooterObj.className = "footer";
	
	popupCloseObj = document.createElement("a");
	popupCloseObj.href = "#";
	addEvent(popupCloseObj, "click", cancelClick, false);
	popupCloseObj.innerHTML = popupCloseText[pageLang];
	popupCloseObj.id = "link_cartCommentPopupClose_" + idItem;
	addEvent(popupCloseObj, "click", closeCartCommentPopup, false);
	
	popupFooterObj.appendChild(popupCloseObj);
	
	brObj = document.createElement("br");
	popupFooterObj.appendChild(brObj);
	
	popupNoShowObj = document.createElement("a");
	popupNoShowObj.href = "#";
	addEvent(popupNoShowObj, "click", cancelClick, false);
	popupNoShowObj.innerHTML = popupNoShowText[pageLang];
	popupNoShowObj.id = "noshow_cartCommentPopupClose_" + idItem;
	addEvent(popupNoShowObj, "click", closeCartCommentPopup, false);
	addEvent(popupNoShowObj, "click", noShowPopups, false);
	popupFooterObj.appendChild(popupNoShowObj);
	
	popupObjContainer.appendChild(popupFooterObj);
	
	
	if(ieVers >= 7)
	{
		popupObj.style.left = (buttonPos[0]- 218) + "px";
	}
	else
	{
		popupObj.style.left = buttonPos[0] + "px";
	}
	
	//popupObj.style.left = buttonPos[0] + "px";
	
	popupObj.style.top = (buttonPos[1] + 20) + "px";
	document.body.appendChild(popupObj);
	popupObj.style.zIndex = 10;
	
	popupCommentBox.focus();
}


function savePopupComment(e)
{
	target = fetchTarget(e);
	//alert(target.id);
	idItem = target.id.match(/commentSave_([0-9]+)/)[1];
	commentObj = document.getElementById("comment_" + idItem);
	commentText = escape(commentObj.value);
	//commentText = commentObj.value;
	//alert(commentText);
	ajaxObj.call("action=ajaxCartComment&idItem=" + idItem + "&comment=" + commentText, savePopupCommentResp);
	
	popupObj = document.getElementById("cartCommentPopup_" + idItem);
	document.body.removeChild(popupObj);
}

function savePopupCommentResp(resp)
{
	
}

function closeCartCommentPopup(e)
{
	target = fetchTarget(e);
	idItem = target.id.match(/cartCommentPopupClose_([0-9]+)/)[1];
	popupObj = document.getElementById("cartCommentPopup_" + idItem);
	document.body.removeChild(popupObj);
}

function setupCheckoutComments()
{
	taArr = document.getElementsByTagName("textarea");
	for(i = 0; i < taArr.length; i++)
	{
		if(taArr[i].id.match(/cartComment_([0-9]+)/))
		{
			addEvent(taArr[i], "change", updateCartComment, false);
		}
	}
}

function updateCartComment(e)
{
	target = fetchTarget(e);
	idItem = target.id.match(/cartComment_([0-9]+)/)[1];
	commentText = escape(target.value);
	ajaxObj.call("action=ajaxCartComment&idItem=" + idItem + "&comment=" + commentText, savePopupCommentResp);
}


function loadClientArea()
{
	loadForgotPwd();
	loadClientLoginButton();
	loadOrderDetailsButtons();
}

function loadForgotPwd()
{
	forgotPwdLinkObj = document.getElementById("forgotPasswordLink");
	if(!forgotPwdLinkObj) return;
	addEvent(forgotPwdLinkObj, "click", openForgotPwd, false);
}

function openForgotPwd(e)
{
	ajaxObj.call("action=ajaxOpenForgotPwd&lang=" + pageLang, openForgotPwdResp);
}

function openForgotPwdResp(resp)
{
	forgotPwdObj = document.getElementById("forgot_pwd");
	forgotPwdObj.innerHTML = resp;
	recover_pwd_buttonObj = document.getElementById("recover_pwd_button");
	addEvent(recover_pwd_buttonObj, "click", recoverPwd, false);
	
	forgotPwdLinkObj = document.getElementById("forgotPasswordLink");
	dropEvent(forgotPwdLinkObj, "click", openForgotPwd, false);
}

function recoverPwd(e)
{
	recover_emailObj = document.getElementById("recover_email");
	emailVal = recover_emailObj.value;
	ajaxObj.call("action=ajaxRecoverPwd&email=" + escape(emailVal) + "&lang=" + pageLang, recoverPwdResp);
}

function recoverPwdResp(resp)
{
	if(resp["success"] == 0)
	{
		recoverPwdErrObj = document.getElementById("recoverPwdErr");
		recoverPwdErrObj.innerHTML = resp["errMsg"];
	}
	else
	{
		forgotPwdObj = document.getElementById("forgot_pwd");
		forgotPwdObj.innerHTML = resp["successMsg"];
		forgotPwdLinkObj = document.getElementById("forgotPasswordLink");
		if(!forgotPwdLinkObj) return;
		addEvent(forgotPwdLinkObj, "click", openForgotPwd, false);
	}
}


function loadClientLoginButton()
{
	clientLoginButtonObj = document.getElementById("clientLoginButton");
	if(!clientLoginButtonObj) return;
	addEvent(clientLoginButtonObj, "click", clientAreaLogin, false);
}

function clientAreaLogin()
{
	emailObj = document.getElementById("email");
	passwdObj = document.getElementById("passwd");
	email = emailObj.value;
	passwd = passwdObj.value;
	ajaxObj.call("action=ajaxClientAreaLogin&email=" + email + "&passwd=" + passwd + "&lang=" + pageLang, clientAreaLoginResp);
}

function clientAreaLoginResp(resp)
{
	if(resp["success"] == 0)
	{
		loginErrorObj = document.getElementById("loginError");
		loginErrorObj.innerHTML = resp["loginErr"];
	}
	else
	{
		client_area_containerObj = document.getElementById("client_area_container");
		client_area_containerObj.innerHTML = resp["pageContent"];
		loadOrderDetailsButtons();
	}
}

function loadOrderDetailsButtons()
{
	anchorsArr = document.getElementsByTagName("a");
	for(i = 0; i < anchorsArr.length; i++)
	{
		if(anchorsArr[i].id.match(/orderDetail_([0-9]+)/))
		{
			addEvent(anchorsArr[i], "click", loadOrderDetails, false);
		}
		if(anchorsArr[i].id.match(/recoverOrder_([0-9]+)/))
		{
			addEvent(anchorsArr[i], "click", recoverOrder, false);
		}
	}
}

function loadOrderDetails(e)
{
	target = fetchTarget(e);
	idOrder = target.id.match(/orderDetail_([0-9]+)/)[1];
	//alert(idOrder);
	ajaxObj.call("action=ajaxLoadOrderDetails&idOrder=" + idOrder + "&lang=" + pageLang, loadOrderDetailsResp);
}

function loadOrderDetailsResp(resp)
{
	orderDivObj = document.getElementById("orderDiv_" + resp["idOrder"]);
	orderItemListObj = document.createElement("ul");
	orderItemListObj.id = "orderItemList_" + resp["idOrder"];
	items = resp["items"];
	for(i = 0; i < items.length; i++)
	{
		itemsLiObj = document.createElement("li");
		itemsLiObj.innerHTML = items[i]["title"] + ": " + items[i]["quantity"];
		orderItemListObj.appendChild(itemsLiObj);
	}
	orderDivObj.appendChild(orderItemListObj);
	
	orderControlText = document.getElementById("orderDetail_" + resp["idOrder"]);
	orderControlText.revertText = orderControlText.innerHTML;
	orderControlText.innerHTML = resp["closeText"];
	
	dropEvent(orderControlText, "click", loadOrderDetails, false);
	addEvent(orderControlText, "click", closeOrderDetails, false);
}

function closeOrderDetails(e)
{
	target = fetchTarget(e);
	idOrder = target.id.match(/orderDetail_([0-9]+)/)[1];
	dropEvent(orderControlText, "click", closeOrderDetails, false);
	addEvent(orderControlText, "click", loadOrderDetails, false);
	orderItemListObj = document.getElementById("orderItemList_" + idOrder);
	orderItemListObj.parentNode.removeChild(orderItemListObj);
	target.innerHTML = target.revertText;
}

function recoverOrder(e)
{
	target = fetchTarget(e);
	idOrder = target.id.match(/recoverOrder_([0-9]+)/)[1];
	ajaxObj.call("action=ajaxRecoverOrder&idOrder=" + idOrder + "&lang=" + pageLang, recoverOrderResp);
}

function recoverOrderResp(resp)
{
	cartContentObj = document.getElementById("cartContent");
	cartContentObj.innerHTML = resp["cartContent"];
	
	cartTotalObj = document.getElementById("cartTotalAmount");
	cartTotalObj.innerHTML = resp["cartTotal"];
	
	minOrderObj = document.getElementById("minOrder");
	orderButtonObj = document.getElementById("orderButton");
	
	if(resp["isMinOrder"] == 0)
	{
		minOrderObj.style.display = "block";
		orderButtonObj.style.display = "none";
	}
	else
	{
		minOrderObj.style.display = "none";
		orderButtonObj.style.display = "block";
	}
	
	fetchCartSelects();
	fetchDropButtons();
}


function loadCartChangeDeliveryOption()
{
	cartChangeDeliveryOptionObj = document.getElementById("cartChangeDeliveryOptionLink");
	if(!cartChangeDeliveryOptionObj) return;
	addEvent(cartChangeDeliveryOptionObj, "click", getCartDeliveryOptions, false);
	addEvent(cartChangeDeliveryOptionObj, "click", cancelClick, false);
}

function getCartDeliveryOptions(e)
{
	//alert("getCartDeliveryOptions()");
	ajaxObj.call("action=ajaxGetCartDeliveryOptions&lang=" + pageLang, ajaxGetCartDeliveryOptionsResp);
}

function ajaxGetCartDeliveryOptionsResp(resp)
{
	cartContainerObj = document.getElementById("cartContainer");
	selectorLayerObj = document.createElement("DIV");
	selectorLayerObj.id = "selectorLayer";
	selectorLayerObj.innerHTML = resp["html"];
	cartContainerObj.appendChild(selectorLayerObj);
	
	selectorLinks = selectorLayerObj.getElementsByTagName("A");
	for(i = 0; i < selectorLinks.length; i++)
	{
		addEvent(selectorLinks[i], "click", ajaxCartSetDelivery, false);
		addEvent(selectorLinks[i], "click", cancelClick, false);
	}
	
	cartChangeDeliveryOptionLinkObj = document.getElementById("cartChangeDeliveryOptionLink");
	cartChangeDeliveryOptionLinkObj.style.visibility = "hidden";
}

function ajaxCartSetDelivery(e)
{
	target = fetchTarget(e);
	id_delivery_city = target.id.match(/cartSelectButton_([0-9]+)/)[1];
	//alert(id_delivery_city);
	ajaxObj.call("action=ajaxCartSetDelivery&id_delivery_city=" + id_delivery_city + "&lang=" + pageLang, ajaxCartSetDeliveryResp);
}

function ajaxCartSetDeliveryResp(resp)
{
	
	
	minOrderObj = document.getElementById("minOrder");
	minOrderValObj = document.getElementById("minOrderVal");
	minOrderTextObj = document.getElementById("minOrderText");
	orderButtonObj = document.getElementById("orderButton");
	selectorLayerObj = document.getElementById("selectorLayer");
	
	minOrderValObj.innerHTML = resp["minOrder"];
	
	
	if(resp["isStore"])
	{
		minOrderTextObj.innerHTML = resp["cityName"];
	}
	else
	{
		minOrderTextObj.innerHTML = cartDeliveryText[pageLang] + ":<br />" + resp["cityName"];
	}
	if(resp["isMinOrder"])
	{
		orderButtonObj.style.display = "block";
		minOrderObj.style.display = "none";
	}
	else
	{
		orderButtonObj.style.display = "none";
		minOrderObj.style.display = "block";
	}
	
	selectorLayerObj.parentNode.removeChild(selectorLayerObj);
	cartChangeDeliveryOptionLinkObj = document.getElementById("cartChangeDeliveryOptionLink");
	cartChangeDeliveryOptionLinkObj.style.visibility = "visible";
	
}

addEvent(window, "load", addAllEvents, false);








