﻿window.addEvent('domready', function() {
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
    window.addEvent('keypress', function(evt) {
        if (evt.key == 'esc') {
            hideSelectedItem(true);
        }
    });
    onlyNumbers();
    showBackImages();
    LoadClickEvents();
    LoadAnchorItem();
});

function LoadClickEvents() {
    var links = $$('a.menu_link');
    links.each(function(item, index) {
        item.addEvent('click', function() {
            var split = this.get('alt').split("|");
            if (split && split.length == 6) {
                //openSelectedItem(split[0], split[1], split[2], split[3], split[4], split[5]);
            }
            openSelectedItemNew(split[0], split[1], split[2], split[3], split[4], split[5]);
        });
    });
}

function selectAll(checkGroup, link) {
    var check = false;
    link = $(link);
    if (link.get('rel') == 'all') {
        link.set('rel', 'none');
        check = true;
        link.firstChild.nodeValue = 'Deseleccionar todos';
    } else {
        link.set('rel', 'all');
        check = false;
        link.firstChild.nodeValue = 'Seleccionar todos';
    }
    var splitted;
    $$('input[rel^=chk_' + checkGroup + '] ').each(function(item, index) {
        splitted = item.get('rel').split('|');
        item.set('checked', check);
        addRemoveCheck(splitted[2], item, splitted[1]);
    });
}

function openSelectedItemNew(itemID, itemName, itemDescription, itemPrice, itemImage, itemOptions) {
    var optionsPanel = $('ctl00_ctl00_ContentMain_ContentRestaurant_panelOptions');
    var img = $('ctl00_ctl00_ContentMain_ContentRestaurant_imgProduct');
    var name = $('ctl00_ctl00_ContentMain_ContentRestaurant_lblProductName');
    var price1 = $('ctl00_ctl00_ContentMain_ContentRestaurant_lblPrice');
    var price2 = $('ctl00_ctl00_ContentMain_ContentRestaurant_lblPrice2');
    var qty = $('ctl00_ctl00_ContentMain_ContentRestaurant_txtQuantity');
    var exp = $('ctl00_ctl00_ContentMain_ContentRestaurant_txtAditionalNotes');
    var id = $('ctl00_ctl00_ContentMain_ContentRestaurant_hidItemID');
    var op = $('ctl00_ctl00_ContentMain_ContentRestaurant_hidOptions');
    op.set('value', itemOptions);
    id.set('value', itemID);
    qty.set('value', '1');
    exp.set('value', '');
    var desc = $('prodDescription');
    if (desc) { desc.set('html', itemDescription); }
    if (name) { name.set('html', itemName); }
    if (price1) { price1.set('html', itemPrice); }
    if (img && itemImage.length > 0) {
        $('ctl00_ctl00_ContentMain_ContentRestaurant_popUpPanelRight').setStyle('display', 'block');
        img.set('src', itemImage);
        price2.set('html', '');
    } else {
        $('ctl00_ctl00_ContentMain_ContentRestaurant_popUpPanelRight').setStyle('display', 'none');
        price2.set('html', itemPrice);
    }
    new Request.HTML({
        'url': '/handlers/MenuProduct.ashx',
        'onSuccess': function(responseTree, responseElements, responseHTML, responseJavaScript) {
            if (responseHTML != '~') {
                optionsPanel.set('html', responseHTML.split('~')[0]);
                optionsPanel.setStyle('display', 'block');
                itemOptions = responseHTML.split('~')[1];
                //pongo valores por defecto
                op.set('value', itemOptions);
                var opt = itemOptions.split(';');
                opt.each(function(item, index) {
                    if (item.length > 0) {
                        var hidOpt = $('hidOpt_' + item.split(':')[0]); //obtengo el campo oculto
                        hidOpt.set('value', item.split(':')[1]);
                    }
                });
                relocatePopUp();
            } else {
                optionsPanel.setStyle('display', 'none');
            }
        },
        'onRequest': function() {
            optionsPanel.set('html', 'Cargando opciones...');
            optionsPanel.setStyle('display', 'block');
        },
        'onFailure': function(reqObj) {
            alert('Ocurrió un error al cargar el producto')
        }
    }).post({ 'productID': itemID });
    showSelectedItem();
}

function LoadAnchorItem() {
    var anchor = window.location.hash;
    if (anchor && anchor.length > 0) {
        anchor = anchor.replace('#', '');
        var links = $$('a[title=' + anchor + ']');
        if (links.length > 0) {
            links[0].fireEvent('click');
        }
    }
}

/*IE6 Bug Fix*/
function showBackImages() {
    if (navigator.userAgent.toLowerCase().indexOf('msie 6') != -1) {
        var add = $('ctl00_ctl00_ContentMain_ContentRestaurant_lnkAdd');
        var cle = $$('div.item_close')[0].getElements('a')[0];
        var i = '';
        var img = null;
        if (add && cle) {
            i = add.getParent().getStyle('background-image').replace('url(', '').replace(')', '');
            i = 'images/' + i.split('/')[i.split('/').length - 1].replace('"', '');
            img = new Element('img', {
                'src': i,
                'styles': {
                    'height': '40px',
                    'margin-left': '1px'
                }
            });
            img.inject(add);
            i = cle.getParent().getStyle('background-image').replace('url(', '').replace(')', '');
            i = 'images/' + i.split('/')[i.split('/').length - 1].replace('"', '');
            img = new Element('img', {
                'src': i,
                'styles': {
                    'margin-top': '0px'
                }
            });
            img.inject(cle);
        }
    }
}

function EndRequestHandler(sender, args) {
    //refreshCart();
    //onlyNumbers();
    //relocatePopUp();
    showAdding();
}
var adding = false;
function showAdding() {
    var loadingD = $('addingDiv');
    if (loadingD) {
        if (adding) {
            if (loadingD.getStyle('display') == 'none') {
                var viewport = window.getSize();
                var contSize = loadingD.getSize();
                loadingD.setStyle('left', (viewport.x - contSize.x) / 2);
                loadingD.setStyle('top', (viewport.y - contSize.y) / 2);
                loadingD.setStyle('display', 'block');
            }
            adding = false;
        } else {
            loadingD.setStyle('display', 'none');
        }
    }
}

function relocatePopUp() {
    var container = $('item_container');
    var overlay = $('item_overlay');
    //var loading = $('item_loading');
    if (container.getStyle('display') == 'block') {
        var viewport = window.getSize();
        var scroll = window.getScroll();
        var contSize = container.getSize();
        //
        var top = (viewport.y - contSize.y) / 2;
        if (top < 0) { top = 20; }
        container.set('tween', { duration: 'short' });
        container.tween('top', top + scroll.y);
        //var left = (viewport.x - contSize.x) / 2;
        //container.tween('left', left);

        var i = (contSize.y - 40) / 3;
        //        loading.setStyle('height', i * 2);
        //        loading.setStyle('padding-top', i + 5);
        //        loading.setStyle('width', contSize.x - 40);
    }
}

function onlyNumbers() {
    var input = $('ctl00_ctl00_ContentMain_ContentRestaurant_txtQuantity');
    if (input) {
        input.addEvent('keydown', function(evt) {
            if (evt.key == '0' || evt.key == '1' || evt.key == '2' || evt.key == '3' || evt.key == '4' || evt.key == '5' ||
            evt.key == '6' || evt.key == '7' || evt.key == '8' || evt.key == '9' || evt.key == 'backspace' ||
            (evt.code > 95 && evt.code < 106)) {
                if (this.get('value').length == 0 && (evt.key == '0' || evt.code == 96)) {
                    evt.returnValue = false; return false;
                }
                if (this.get('value').length > 2 && evt.key != 'backspace') {
                    evt.returnValue = false; return false;
                }
            } else {
                evt.returnValue = false; return false;
            }
        });
    }
}

function expandCollapse(sectionId) {
    var section = $('menu_section_' + sectionId);
    var sectionContainer = $('section_container_' + sectionId);
    //esta abierto, lo cierro
    if (section.hasClass('menu_arrow_open_new')) {
        section.removeClass('menu_arrow_open_new');
        section.addClass('menu_arrow_closed_new');
        sectionContainer.setStyle('display', 'none');
    } else {
        section.removeClass('menu_arrow_closed_new');
        section.addClass('menu_arrow_open_new');
        sectionContainer.setStyle('display', 'block');
    }
}

//function openSelectedItem(itemID) {
//    if ($('ctl00_ctl00_ContentMain_ContentRestaurant_hidItemID')) {
//        $('ctl00_ctl00_ContentMain_ContentRestaurant_UpdateProgress1').setStyle('display', 'block');
//        showSelectedItem();
//        $('ctl00_ctl00_ContentMain_ContentRestaurant_hidItemID').set('value', itemID);
//        __doPostBack('ctl00$ctl00$ContentMain$ContentRestaurant$lnkCargarItem', '');
//        return false;
//    }
//}

//nueva funcion o=optionID:defaultvalue;
//function openSelectedItem(itemID, itemName, itemDescription, itemPrice, itemImage, itemOptions) {
//    var img = $('ctl00_ctl00_ContentMain_ContentRestaurant_imgProduct');
//    var name = $('ctl00_ctl00_ContentMain_ContentRestaurant_lblProductName');
//    var price1 = $('ctl00_ctl00_ContentMain_ContentRestaurant_lblPrice');
//    var price2 = $('ctl00_ctl00_ContentMain_ContentRestaurant_lblPrice2');
//    var qty = $('ctl00_ctl00_ContentMain_ContentRestaurant_txtQuantity');
//    var exp = $('ctl00_ctl00_ContentMain_ContentRestaurant_txtAditionalNotes');
//    var id = $('ctl00_ctl00_ContentMain_ContentRestaurant_hidItemID');
//    var op = $('ctl00_ctl00_ContentMain_ContentRestaurant_hidOptions');
//    op.set('value', itemOptions);
//    id.set('value', itemID);
//    qty.set('value', '1');
//    exp.set('value', '');
//    var desc = $('prodDescription');
//    if (desc) {
//        desc.set('html', itemDescription);
//    }
//    if (name) {
//        name.set('html', itemName);
//    }
//    if (price1) {
//        price1.set('html', itemPrice);
//    }
//    if (img && itemImage.length > 0) {
//        $('ctl00_ctl00_ContentMain_ContentRestaurant_popUpPanelRight').setStyle('display', 'block');
//        img.set('src', itemImage);
//        price2.set('html', '');
//    } else {
//        $('ctl00_ctl00_ContentMain_ContentRestaurant_popUpPanelRight').setStyle('display', 'none');
//        price2.set('html', itemPrice);
//    }
//    //opciones
//    //pongo valores por defecto
//    var opt = itemOptions.split(';');
//    opt.each(function(item, index) {
//        if (item.length > 0) {
//            var hidOpt = $(hidPrefix + item.split(':')[0]); //obtengo el campo oculto
//            hidOpt.set('value', item.split(':')[1]);
//        }
//    });
//    //copio al pop up
//    $('ctl00_ctl00_ContentMain_ContentRestaurant_panelOptions').set('html', '');
//    if ($('tbl_opt_' + itemID)) {
//        var chks = $('tbl_opt_' + itemID).getElements('input:checked');
//        chks.each(function(item, index) {
//            item.set('checked', false);
//        });
//        var copy = $('tbl_opt_' + itemID).clone();
//        copy.inject($('ctl00_ctl00_ContentMain_ContentRestaurant_panelOptions'));
//        $('ctl00_ctl00_ContentMain_ContentRestaurant_panelOptions').setStyle('display', 'block');
//        copy.setStyle('display', 'block');
//    } else {
//        $('ctl00_ctl00_ContentMain_ContentRestaurant_panelOptions').setStyle('display', 'none');
//    }
//    showSelectedItem();
//}

function showSelectedItem() {
    var container = $('item_container');
    var overlay = $('item_overlay');
    //var loading = $('item_loading');
    var fullSize = window.getScrollSize();
    var viewport = window.getSize();
    var scroll = window.getScroll();
    container.setStyle('display', 'block');
    var contSize = container.getSize();
    overlay.setStyle('width', fullSize.x);
    overlay.setStyle('height', fullSize.y);
    overlay.setStyle('opacity', '0.6');
    var top = (viewport.y - contSize.y) / 2;
    var left = (viewport.x - contSize.x) / 2;
    container.setStyle('left', left);
    container.setStyle('top', top + scroll.y);
    overlay.setStyle('display', 'block');
    var i = (contSize.y - 40) / 3;
    //    loading.setStyle('height', i * 2);
    //    loading.setStyle('padding-top', i + 5);
    //    loading.setStyle('width', contSize.x - 40);
}

function hideSelectedItem(removeValue) {
    if ($('ctl00_ctl00_ContentMain_ContentRestaurant_hidItemID') && removeValue) {
        $('ctl00_ctl00_ContentMain_ContentRestaurant_hidItemID').set('value', '');
    }
    $('item_overlay').setStyle('display', 'none');
    $('item_container').setStyle('display', 'none');
}

function refreshCart() {
    var hid = $('ctl00_ctl00_ContentMain_ContentRestaurant_hidRefreshCart');
    if (hid) {
        if (hid.get('value') == 'true') {
            hideSelectedItem(true);
            hid.set('value', '');
            adding = true;
            __doPostBack('ctl00$ctl00$ContentMain$lnkRefresh', '');
        }
    }
}


/**************************/
/*  MANEJO DE OPCIONES    */
/**************************/
//var hidPrefix = 'ctl00_ctl00_ContentMain_ContentRestaurant_hidOpt_';
var hidPrefix = 'hidOpt_';
/*  MANEJO DE CHECKBOXES    */
function addRemoveCheck(hidID, check, pos) {
    var hidden = $(hidPrefix + hidID); //obtengo el campo oculto
    check = $(check);
    if (hidden) {
        var currentValues = hidden.get('value');
        //si esta marcado lo agrego a los valores anteriores
        if (check.get('checked')) {
            if (currentValues.length == 0) { currentValues += ','; }
            if (!currentValues.contains(',' + pos + ',')) { currentValues += pos + ','; }
            //si no esta marcado, lo quito de los valores anteriores
        } else {
            currentValues = currentValues.replace(pos + ',', '');
        }
        hidden.set('value', currentValues);
    }
}

function addSingleOption(hidID, combo) {
    var hidden = $(hidPrefix + hidID); //obtengo el campo oculto
    combo = $(combo);
    if (hidden) {
        hidden.set('value', combo.get('value'));
    }
}

function addMultipleOptions(hidID, pos, combo) {
    pos = pos.toInt();
    pos -= 1;
    var hidden = $(hidPrefix + hidID); //obtengo el campo oculto
    combo = $(combo);
    if (hidden) {
        var currentValuesArray = hidden.get('value').split(',');
        var newValues = '';
        for (var i = 0; i < currentValuesArray.length; i++) {
            //si hay algo
            if (currentValuesArray[i].length > 0) {
                if (i == pos) {
                    newValues += combo.get('value') + ',';
                } else {
                    newValues += currentValuesArray[i] + ',';
                }
            }
        }
        hidden.set('value', newValues);
    }
}

function validateOptions() {
    var ok = true;
    var oblig = false;
    var msg = '';
    var id = $('ctl00_ctl00_ContentMain_ContentRestaurant_hidItemID').get('value');
    //var hid = $('ctl00_ctl00_ContentMain_ContentRestaurant_hidVal_' + id);
    var hid = $('hidVal_' + id);
    if (hid && hid.get('value').length > 0) {
        var splitted = hid.get('value').split(';');
        for (var i = 0; i < splitted.length; i++) {
            if (splitted[i].length > 0) {
                var spl = splitted[i].split(':');
                var hidOpt = $(hidPrefix + spl[0]);
                if (hidOpt) {
                    switch (spl[1]) {
                        case '0':
                            if (hidOpt.get('value').length == 0 || hidOpt.get('value') == ',') {
                                //ok = confirm('No ha seleccionado ' + spl[2] + ', desea agregar el producto de todas formas?');
                                //msg = '';
                            }
                            break;
                        case '1':
                            if (hidOpt.get('value').contains('-1')) {
                                msg = 'Debe seleccionar correctamente ' + spl[2];
                                oblig = true;
                            }
                            break;
                        case 'n':
                            if (hidOpt.get('value').contains('-1')) {
                                msg = 'Debe seleccionar correctamente ' + spl[2];
                                oblig = true;
                            }
                            break;
                    }
                }
            }
        }
    }
    if (!ok || oblig) {
        if (msg.length > 0) {
            alert(msg);
        }
        //        evt = new Event();
        //        evt.preventDefault();
        // ok = true;
    } else {
        /*Si esta todo bien, oculto el pop up y muestro el agregando*/
        adding = true;
        showAdding();
        /*carrito*/
        var hidItemID = $('ctl00_ctl00_ContentMain_hidItemID');
        var hidItemQty = $('ctl00_ctl00_ContentMain_hidItemQuantity');
        var hidItemExp = $('ctl00_ctl00_ContentMain_hidItemNotes');
        var hidItemOpt = $('ctl00_ctl00_ContentMain_hidItemOptions');
        /*pop up*/
        var qty = $('ctl00_ctl00_ContentMain_ContentRestaurant_txtQuantity');
        var exp = $('ctl00_ctl00_ContentMain_ContentRestaurant_txtAditionalNotes');
        var id = $('ctl00_ctl00_ContentMain_ContentRestaurant_hidItemID');
        var op = $('ctl00_ctl00_ContentMain_ContentRestaurant_hidOptions');
        var options = '';
        var opt = op.get('value').split(';');
        opt.each(function(item, index) {
            if (item.length > 0) {
                var hidOpt = $(hidPrefix + item.split(':')[0]); //obtengo el campo oculto
                options += hidOpt.get('value') + ';';
            }
        });

        /*intercambio*/
        hidItemID.set('value', id.get('value'));
        hidItemQty.set('value', qty.get('value'));
        hidItemExp.set('value', exp.get('value'));
        hidItemOpt.set('value', options);
        __doPostBack('ctl00$ctl00$ContentMain$lnkAddToCart', '');
        hideSelectedItem(false);
        //        evt = new Event();
        //        evt.preventDefault();
    }
}