var cartEmptyText = new Array();
cartEmptyText["ca"] = "El carret&#243; est&#224; vuit.";
cartEmptyText["es"] = "El carro esta vacio.";

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 cancelClick()
{
	return false;
}


function addAllEvents()
{
	fetchCartButtons();
	fetchCartSelects();
	fetchDropButtons();
	fetchCitySelector();
	fetchLoginButton();
	fetchCreateButton();
	fetchLoginActivate();
	fetchCityLinks();
}



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_([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(/[0-9]+/);
	idItem = match[0];
	
	usePriceObj = document.getElementById("usePrice_" + idItem);
	usePriceVal = usePriceObj.value;
	
	itemQtyObj = document.getElementById("itemQty_" + 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" : "addCart";
	}
	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)
{
	idItem = resp.idItem;
	usePriceGroup = resp.usePriceGroup;
	qty = resp.qty;
	
	//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, ",");
			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(cartTotalAmountCheckoutObj && isMinOrderAlertObj)
	{
		cartTotalAmountCheckoutObj.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");
	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 = "inline";
		}
	}
}

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, ",");
	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, 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";
	}
	orderButtonObj = document.getElementById("orderButton");
	if(orderButtonObj)
	{
		if(resp.isMinOrder == true)
		{
			orderButtonObj.style.display = "block";
		}
		else
		{
			orderButtonObj.style.display = "none";
		}
	}
}

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");
	
	switch(loginStatus)
	{
		//logged in correctly
		case 1 :
		loginContainerObj.innerHTML = displayVal;
		fetchLoginActivate();
		fetchLoginButton();
		selectCityResp(resp);
		setCityMenu(resp["id_city"]);
		break;
		//logged off correctly
		case 0 : 
		loginContainerObj.innerHTML = displayVal;
		loginActivateSwitch();
		fetchLoginButton();
		selectCityResp(resp);
		setCityMenu(resp["id_city"]);
		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";
}




addEvent(window, "load", addAllEvents, false);








