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 popupOptionsText = new Array();
popupOptionsText["ca"] = "Com ho vol?";
popupOptionsText["es"] = "¿Cómo lo quiere?";

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();
    loadItemOptions();
    loadItemHilites();
}

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++)
        {
            if (cartSelects[i].className.match(/item_opt/)) {
                addEvent(cartSelects[i], "change", writeItemOpt, false);
            }
            else {
                addEvent(cartSelects[i], "change", changeCart, false);
            }
        }
    }
}

function writeItemOpt(e) {
    target = fetchTarget(e);
    id_item = 0;
    matches = target.id.match(/options_([0-9]+)/);
    if(!matches) return;
    id_item = matches[1];
    item_ta = document.getElementById("comment_" + id_item);
    selectedOption = target[target.selectedIndex];
    if(window.console) console.log(selectedOption);
    //alert(selectedOption.label);
    item_ta.value += selectedOption.label + " ";
    item_ta.focus();
    target.selectedIndex = 0;
    
}

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, resp);
        }
    }
}

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, resp)
{
    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);
    
    if(resp.item.options_menu.length > 0) {
        popupOptionsMenu = document.createElement("select");
        popupOptionsMenu.id = 'options_' + idItem;
        opt = document.createElement("option");
        opt.value = -1;
        opt.label = popupOptionsText[pageLang];
        opt.innerHTML = popupOptionsText[pageLang];
        popupOptionsMenu.appendChild(opt)
        for(i in resp.item.options_menu) {
            opt = document.createElement("option");
            opt.value = resp.item.options_menu[i];
            opt.label = resp.item.options_menu[i];
            opt.innerHTML = resp.item.options_menu[i];
            popupOptionsMenu.appendChild(opt)
        }
        addEvent(popupOptionsMenu, "change", writeItemOpt, false);
        popupObjContainer.appendChild(popupOptionsMenu);
    }


    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(/comment_([0-9]+)/))
        {
            addEvent(taArr[i], "blur", updateCartComment, false);
        }
    }
}

function updateCartComment(e)
{
    target = fetchTarget(e);
    idItem = target.id.match(/comment_([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";
}

function loadItemOptions() {
    optionsTable = document.getElementById("itemOptionsTable");
    if(!optionsTable) return;
    optionsTableAnchors = optionsTable.getElementsByTagName("A");
    for(i = 0; i < optionsTableAnchors.length; i++) {
        if(optionsTableAnchors[i].id.match(/edit_option_([0-9]+)/)) {
            addEvent(optionsTableAnchors[i], "click", editOption, false);
        }
        if(optionsTableAnchors[i].id.match(/drop_option_([0-9]+)/)) {
            addEvent(optionsTableAnchors[i], "click", dropOption, false);
        }
        if(optionsTableAnchors[i].id.match(/save_option_([0-9]+)/)) {
            addEvent(optionsTableAnchors[i], "click", ajaxSaveOption, false);
        }
    }
    addOptionButton = document.getElementById("addOption");
    addEvent(addOptionButton, "click", addOption, false);
}

function addOption() {
    existsNewRow = document.getElementById("option_new");
    if(existsNewRow) return;
    optionsTable = document.getElementById("itemOptionsTable");
    newRow = optionsTable.insertRow(1);
    newRow.id = "option_new";
    createNewOptionRow(newRow);
}

function createNewOptionRow(newRow) {
    //newOptionRow = document.createElement("TR");
    //newOptionRow.id = "newRow";
    
    /* CA cell */
    newTd_ca = document.createElement("TD");
    newInput_ca = document.createElement("INPUT");
    newInput_ca.id = "input_option_ca_new";
    newSpan_ca = document.createElement("SPAN");
    newSpan_ca.style.display = "none";
    newSpan_ca.id = "option_ca_new";
    newTd_ca.appendChild(newInput_ca);
    newTd_ca.appendChild(newSpan_ca);
    newRow.appendChild(newTd_ca);
    
    /* ES cell */
    newTd_es = document.createElement("TD");
    newInput_es = document.createElement("INPUT");
    newInput_es.id = "input_option_es_new";
    newSpan_es = document.createElement("SPAN");
    newSpan_es.style.display = "none";
    newSpan_es.id = "option_es_new";
    newTd_es.appendChild(newInput_es);
    newTd_es.appendChild(newSpan_es);
    newRow.appendChild(newTd_es);
    
    /* Action cell */
    newTd_a = document.createElement("TD");
    newRow.appendChild(newTd_a);
    
    /* Save button */
    newSave = document.createElement("A");
    newSave.innerHTML = "Guardar";
    newSave.className = "button";
    newSave.href = "javascript: void(0)";
    newSave.id = "save_option_new";
    newSave.style.display = "block";
    addEvent(newSave, "click", ajaxSaveOption, false);
    newTd_a.appendChild(newSave);
    
    /* Edit button */
    newEdit = document.createElement("A");
    newEdit.innerHTML = "Editar";
    newEdit.className = "button";
    newEdit.href = "javascript: void(0)";
    newEdit.id = "edit_option_new";
    newEdit.style.display = "none";
    addEvent(newEdit, "click", editOption, false);
    newTd_a.appendChild(newEdit);
    
    /* Drop button */
    newDrop = document.createElement("A");
    newDrop.innerHTML = "Eliminar";
    newDrop.className = "button";
    newDrop.href = "javascript: void(0)";
    newDrop.id = "drop_option_new";
    newDrop.style.display = "block";
    addEvent(newDrop, "click", dropOption, false);
    newTd_a.appendChild(newDrop);

}

function ajaxSaveOption(e) {
    target = fetchTarget(e);
    optionId = target.id.match(/save_option_([a-zA-Z0-9]+)/)[1];
    performVal = optionId == "new" ? "insert" : "update" ;
    option_value_es = "";
    option_value_ca = "";
    Obj_input_option_es = document.getElementById("input_option_es_" + optionId);
    if(Obj_input_option_es) {
        option_value_es = Obj_input_option_es.value;
    }
    Obj_input_option_ca = document.getElementById("input_option_ca_" + optionId);
    if(Obj_input_option_ca) {
        option_value_ca = Obj_input_option_ca.value;
    }
    //alert(optionId);
    //alert(option_value_ca);
    //alert(option_value_es);
    ajaxObj.call("action=ajaxHandleOption&id=" + optionId + "&perform=" + performVal + "&title_es=" + escape(option_value_es) + "&title_ca=" + escape(option_value_ca), ajaxSaveOptionResp);
}

function ajaxSaveOptionResp(resp) {
    //{"perform":"insert","msg":null,"title_es":"this","title_ca":"try","id":"12"}
    if(resp["perform"] == "insert_ok") {
        lookup_id = "new";
    } else {
        lookup_id = resp["id"];
    }
    //get row
    tr_obj = document.getElementById("option_" + lookup_id);
    //if drop, remove row and leave
    if(resp["perform"] == "drop_ok") {
        tr_obj.parentNode.removeChild(tr_obj);
        return;
    }
    //get all elements
    input_ca = document.getElementById("input_option_ca_" + lookup_id);
    input_es = document.getElementById("input_option_es_" + lookup_id);
    span_ca = document.getElementById("option_ca_" + lookup_id);
    span_es = document.getElementById("option_es_" + lookup_id);
    save_button = document.getElementById("save_option_" + lookup_id);
    edit_button = document.getElementById("edit_option_" + lookup_id);
    drop_button = document.getElementById("drop_option_" + lookup_id);

    //replace values in spans
    span_ca.innerHTML = resp["title_ca"];
    span_es.innerHTML = resp["title_es"];
    
    //if new option, replace all IDs
    if(resp["perform"] == "insert_ok") {
        span_ca.id = span_ca.id.replace(/new/, resp["id"]);
        span_es.id = span_es.id.replace(/new/, resp["id"]);
        input_ca.id = input_ca.id.replace(/new/, resp["id"]);
        input_es.id = input_es.id.replace(/new/, resp["id"]);
        save_button.id = save_button.id.replace(/new/, resp["id"]);
        edit_button.id = edit_button.id.replace(/new/, resp["id"]);
        drop_button.id = drop_button.id.replace(/new/, resp["id"]);
        tr_obj.id = tr_obj.id.replace(/new/, resp["id"]);   
    }
    
    //hide inputs, show spans
    input_ca.style.display = "none"; span_ca.style.display = "inline";
    input_es.style.display = "none"; span_es.style.display = "inline";
    save_button.style.display = "none";
    edit_button.style.display = "inline";

}

function editOption(e) {
    target = fetchTarget(e);
    optionId = target.id.match(/edit_option_([a-zA-Z0-9]+)/)[1];
    //alert(optionId);
    //get all elements
    input_ca = document.getElementById("input_option_ca_" + optionId);
    input_es = document.getElementById("input_option_es_" + optionId);
    span_ca = document.getElementById("option_ca_" + optionId);
    span_es = document.getElementById("option_es_" + optionId);
    save_button = document.getElementById("save_option_" + optionId);
    edit_button = document.getElementById("edit_option_" + optionId);
    drop_button = document.getElementById("drop_option_" + optionId);
    //show inputs and hide spans
    input_ca.style.display = "inline"; span_ca.style.display = "none";
    input_es.style.display = "inline"; span_es.style.display = "none";
    save_button.style.display = "inline";
    edit_button.style.display = "none";

}

function dropOption(e) {
    target = fetchTarget(e);
    optionId = target.id.match(/drop_option_([a-zA-Z0-9]+)/)[1];
    if(confirm('Està segur que vol eliminar aquesta opció?\n\nNo es pot desfer.')) {
        ajaxObj.call("action=ajaxHandleOption&id=" + optionId + "&perform=drop", ajaxSaveOptionResp);
    }
    
}









function loadItemHilites() {
    hilitesTable = document.getElementById("itemHilitesTable");
    if(!hilitesTable) return;
    hilitesTableAnchors = hilitesTable.getElementsByTagName("A");
    for(i = 0; i < hilitesTableAnchors.length; i++) {
        if(hilitesTableAnchors[i].id.match(/edit_hilite_([0-9]+)/)) {
            addEvent(hilitesTableAnchors[i], "click", editHilite, false);
        }
        if(hilitesTableAnchors[i].id.match(/drop_hilite_([0-9]+)/)) {
            addEvent(hilitesTableAnchors[i], "click", dropHilite, false);
        }
        if(hilitesTableAnchors[i].id.match(/save_hilite_([0-9]+)/)) {
            addEvent(hilitesTableAnchors[i], "click", ajaxSaveHilite, false);
        }
    }
    addHiliteButton = document.getElementById("addHilite");
    addEvent(addHiliteButton, "click", addHilite, false);
}

function addHilite() {
    existsNewRow = document.getElementById("hilite_new");
    if(existsNewRow) return;
    hilitesTable = document.getElementById("itemHilitesTable");
    newRow = hilitesTable.insertRow(1);
    newRow.id = "hilite_new";
    createNewHiliteRow(newRow);
}

function createNewHiliteRow(newRow) {
    //newHiliteRow = document.createElement("TR");
    //newHiliteRow.id = "newRow";
    
    /* CA cell */
    newTd_ca = document.createElement("TD");
    newInput_ca = document.createElement("INPUT");
    newInput_ca.id = "input_hilite_ca_new";
    newSpan_ca = document.createElement("SPAN");
    newSpan_ca.style.display = "none";
    newSpan_ca.id = "hilite_ca_new";
    newTd_ca.appendChild(newInput_ca);
    newTd_ca.appendChild(newSpan_ca);
    newRow.appendChild(newTd_ca);
    
    /* ES cell */
    newTd_es = document.createElement("TD");
    newInput_es = document.createElement("INPUT");
    newInput_es.id = "input_hilite_es_new";
    newSpan_es = document.createElement("SPAN");
    newSpan_es.style.display = "none";
    newSpan_es.id = "hilite_es_new";
    newTd_es.appendChild(newInput_es);
    newTd_es.appendChild(newSpan_es);
    newRow.appendChild(newTd_es);
    
    /* Action cell */
    newTd_a = document.createElement("TD");
    newRow.appendChild(newTd_a);
    
    /* Save button */
    newSave = document.createElement("A");
    newSave.innerHTML = "Guardar";
    newSave.className = "button";
    newSave.href = "javascript: void(0)";
    newSave.id = "save_hilite_new";
    newSave.style.display = "block";
    addEvent(newSave, "click", ajaxSaveHilite, false);
    newTd_a.appendChild(newSave);
    
    /* Edit button */
    newEdit = document.createElement("A");
    newEdit.innerHTML = "Editar";
    newEdit.className = "button";
    newEdit.href = "javascript: void(0)";
    newEdit.id = "edit_hilite_new";
    newEdit.style.display = "none";
    addEvent(newEdit, "click", editHilite, false);
    newTd_a.appendChild(newEdit);
    
    /* Drop button */
    newDrop = document.createElement("A");
    newDrop.innerHTML = "Eliminar";
    newDrop.className = "button";
    newDrop.href = "javascript: void(0)";
    newDrop.id = "drop_hilite_new";
    newDrop.style.display = "block";
    addEvent(newDrop, "click", dropHilite, false);
    newTd_a.appendChild(newDrop);

}

function ajaxSaveHilite(e) {
    target = fetchTarget(e);
    hiliteId = target.id.match(/save_hilite_([a-zA-Z0-9]+)/)[1];
    performVal = hiliteId == "new" ? "insert" : "update" ;
    hilite_value_es = "";
    hilite_value_ca = "";
    Obj_input_hilite_es = document.getElementById("input_hilite_es_" + hiliteId);
    if(Obj_input_hilite_es) {
        hilite_value_es = Obj_input_hilite_es.value;
    }
    Obj_input_hilite_ca = document.getElementById("input_hilite_ca_" + hiliteId);
    if(Obj_input_hilite_ca) {
        hilite_value_ca = Obj_input_hilite_ca.value;
    }
    //alert(hiliteId);
    //alert(hilite_value_ca);
    //alert(hilite_value_es);
    ajaxObj.call("action=ajaxHandleHilite&id=" + hiliteId + "&perform=" + performVal + "&title_es=" + escape(hilite_value_es) + "&title_ca=" + escape(hilite_value_ca), ajaxSaveHiliteResp);
}

function ajaxSaveHiliteResp(resp) {
    //{"perform":"insert","msg":null,"title_es":"this","title_ca":"try","id":"12"}
    if(resp["perform"] == "insert_ok") {
        lookup_id = "new";
    } else {
        lookup_id = resp["id"];
    }
    //get row
    tr_obj = document.getElementById("hilite_" + lookup_id);
    //if drop, remove row and leave
    if(resp["perform"] == "drop_ok") {
        tr_obj.parentNode.removeChild(tr_obj);
        return;
    }
    //get all elements
    input_ca = document.getElementById("input_hilite_ca_" + lookup_id);
    input_es = document.getElementById("input_hilite_es_" + lookup_id);
    span_ca = document.getElementById("hilite_ca_" + lookup_id);
    span_es = document.getElementById("hilite_es_" + lookup_id);
    save_button = document.getElementById("save_hilite_" + lookup_id);
    edit_button = document.getElementById("edit_hilite_" + lookup_id);
    drop_button = document.getElementById("drop_hilite_" + lookup_id);

    //replace values in spans
    span_ca.innerHTML = resp["title_ca"];
    span_es.innerHTML = resp["title_es"];
    
    //if new hilite, replace all IDs
    if(resp["perform"] == "insert_ok") {
        span_ca.id = span_ca.id.replace(/new/, resp["id"]);
        span_es.id = span_es.id.replace(/new/, resp["id"]);
        input_ca.id = input_ca.id.replace(/new/, resp["id"]);
        input_es.id = input_es.id.replace(/new/, resp["id"]);
        save_button.id = save_button.id.replace(/new/, resp["id"]);
        edit_button.id = edit_button.id.replace(/new/, resp["id"]);
        drop_button.id = drop_button.id.replace(/new/, resp["id"]);
        tr_obj.id = tr_obj.id.replace(/new/, resp["id"]);   
    }
    
    //hide inputs, show spans
    input_ca.style.display = "none"; span_ca.style.display = "inline";
    input_es.style.display = "none"; span_es.style.display = "inline";
    save_button.style.display = "none";
    edit_button.style.display = "inline";

}

function editHilite(e) {
    target = fetchTarget(e);
    hiliteId = target.id.match(/edit_hilite_([a-zA-Z0-9]+)/)[1];
    //alert(hiliteId);
    //get all elements
    input_ca = document.getElementById("input_hilite_ca_" + hiliteId);
    input_es = document.getElementById("input_hilite_es_" + hiliteId);
    span_ca = document.getElementById("hilite_ca_" + hiliteId);
    span_es = document.getElementById("hilite_es_" + hiliteId);
    save_button = document.getElementById("save_hilite_" + hiliteId);
    edit_button = document.getElementById("edit_hilite_" + hiliteId);
    drop_button = document.getElementById("drop_hilite_" + hiliteId);
    //show inputs and hide spans
    input_ca.style.display = "inline"; span_ca.style.display = "none";
    input_es.style.display = "inline"; span_es.style.display = "none";
    save_button.style.display = "inline";
    edit_button.style.display = "none";

}

function dropHilite(e) {
    target = fetchTarget(e);
    hiliteId = target.id.match(/drop_hilite_([a-zA-Z0-9]+)/)[1];
    if(confirm('Està segur que vol eliminar aquesta opció?\n\nNo es pot desfer.')) {
        ajaxObj.call("action=ajaxHandleHilite&id=" + hiliteId + "&perform=drop", ajaxSaveHiliteResp);
    }
    
}

addEvent(window, "load", addAllEvents, false);

