﻿//muestra y oculta la busqueda avanzada
function showAdvOptions() {
    var divAdvSearch = document.getElementById("divAdvSearch");
    var divArrow = document.getElementById("divArrow");
    var adv_link = document.getElementById("adv_link");
    var adv_controls = document.getElementById("adv_controls");
    var hidSearch = 'ctl00_hidSearchType';
    if ($('ctl00_ctl00_hidSearchType')) { hidSearch = 'ctl00_ctl00_hidSearchType'; }
    if (divArrow) {
        if (divArrow.className == 'arrow_up') {
            divArrow.className = 'arrow_down';
            divAdvSearch.className = 'nav_down_closed';
            adv_link.style.padding = '5px 0 0 0';
            adv_controls.style.display = 'none';
            createAutocomplete(true);
            $(hidSearch).set('value', 'reg');
        }
        else if (divArrow.className == 'arrow_down') {
            divArrow.className = 'arrow_up';
            divAdvSearch.className = 'nav_down_open';
            adv_link.style.padding = '45px 0 0 0';
            adv_controls.style.display = '';
            createAutocomplete(false);
            $(hidSearch).set('value', 'adv');
        }
    }
}

function openAdvance() {
    var divAdvSearch = document.getElementById("divAdvSearch");
    var divArrow = document.getElementById("divArrow");
    var adv_link = document.getElementById("adv_link");
    var adv_controls = document.getElementById("adv_controls");
    if (divArrow) {
        divArrow.className = 'arrow_up';
        divAdvSearch.className = 'nav_down_open';
        adv_link.style.padding = '45px 0 0 0';
        adv_controls.style.display = '';
        createAutocomplete(false);
    }
}

//muestra y oculta el cambio de ciudad
function ShowHideChangeCity() {
    var cityName = 'ctl00_hylCityName';
    if ($('ctl00_ctl00_hylCityName')) { cityName = 'ctl00_ctl00_hylCityName'; }
    var container = document.getElementById('change_container');
    var linkCity = document.getElementById(cityName);
    if (container && linkCity) {
        if (container.style.display == 'none') {
            $('change_container').setStyle('display', 'block');
            //$(cityName).set('alt', $(cityName).get('html'))
            //$(cityName).set('html', 'Cancelar');
            //$(cityName).setStyle('font-size', '11px');
            //linkCity.className = '';
        } else {
            $('change_container').setStyle('display', 'none');
            //$(cityName).set('html', $(cityName).get('alt'));
            //$(cityName).setStyle('font-size', '12px');
            //linkCity.className = 'city_name';
        }
    }
}

//agrega el enter al boton de buscar
function addEventToLoginInput(inputId) {
    var input = $(inputId);
    if (input) {
        input.addEvent('keypress', function(evt) {
            if (evt.key == 'enter') {
                // __doPostBack('ctl00$ctl00$ContentMain$ContentRight$Login1$lknEnter', '');
                //   __doPostBack('ctl00$ctl00$linkLogin', '');
                __doPostBack('ctl00$ctl00$ContentMain$ContentRight$Login1$linkLogin', '');
            }
        });
    }
}

/*por cada imagen muestro el descuento*/
function showDiscount() {
    var ok = false;
    var arr = [5, 7, 10, 15, 20];
    var image = '';
    arr.each(function(item1, index1) {
        image = item1 + '_dto.png';
        $$('div[alt=discount_' + item1 + ']').each(function(item2, index2) {
            new Element('img', { 'src': '/images/' + image, 'class': 'discount_image' }).inject(item2, 'top');
            ok = true;
        });
    });
    /*oculto links para agrandar paneles*/
    if (ok) {
        if ($('lnkExpandOpenRests')) {
            $('lnkExpandOpenRests').destroy();
        }
        if ($('lnkExpandCloseRests')) {
            $('lnkExpandCloseRests').destroy();
        }
    }
    //    $$('div[alt=discount]').each(function(item, index) {
    //        new Element('img', { 'src': '/images/dto-empresa.png', 'class': 'discount_image' }).inject(item, 'top');
    //    });
    //    $$('div[alt=discount-res]').each(function(item, index) {
    //        new Element('img', { 'src': '/images/dto-empresa.png', 'class': 'discount_image_other' }).inject(item, 'top');
    //    });
}



//variables
var autocompleter; var allowEnter = true; var auxSearchText = '';
window.addEvent('domready', function() {
    showDiscount(); /*muestro restos con dto*/
    //LOGIN

    addEventToLoginInput('ctl00_ctl00_ContentMain_ContentRight_Login1_txtPassword');
    createAutocomplete(true);
    prepareHints();
    var hidMsg = 'ctl00_hidSearchDefault'
    var autoElement = 'ctl00_txtSearch';
    var ev = 'ctl00$lnkSearch';
    var linkID = 'ctl00_lnkSearch';
    if ($('ctl00_ctl00_txtSearch')) {
        autoElement = 'ctl00_ctl00_txtSearch';
        ev = 'ctl00$ctl00$lnkSearch';
        linkID = 'ctl00_ctl00_lnkSearch';
        hidMsg = 'ctl00_ctl00_hidSearchDefault';
    }
    auxSearchText = $(hidMsg).get('value');
    //if (searchText) { auxSearchText = searchText; }
    addEmptyTextToInput(autoElement, auxSearchText);
    addEventToSearchInput(autoElement, ev);
    $(linkID).addEvent('click', function(evt) {
        var hidSearch = 'ctl00_hidSearchType';
        if ($('ctl00_ctl00_hidSearchType')) { hidSearch = 'ctl00_ctl00_hidSearchType'; }
        if ($(autoElement).get('value') == auxSearchText && $(hidSearch).get('value') != 'adv') {
            evt.preventDefault();
        }
    });
    var hidSearch = 'ctl00_hidSearchType';
    if ($('ctl00_ctl00_hidSearchType')) { hidSearch = 'ctl00_ctl00_hidSearchType'; }
    if ($(hidSearch).get('value') == 'adv') { openAdvance(); }
    checkForOrders();
    /*var sound = ["sounds/alert_26.mp3"];*/
    var sound = ["sounds/ding_dong.mp3"];
    //    if (window.location.href.contains('.uy') || window.location.href.contains('.ar') || window.location.href.contains('.cl')) {
    //        sound = ["sounds/gol.mp3"];
    //    }
    Playlist.loadSounds(sound);
});

//agrega el enter al boton de buscar
function addEventToSearchInput(inputId, ev) {
    var input = $(inputId);
    if (input) {
        input.addEvent('keypress', function(evt) {
            if (evt.key == 'enter') {
                /*if (allowEnter) { __doPostBack(ev, ''); } else { allowEnter = true; }*/
                __doPostBack(ev, '');
            }
        });
    }
}

//crea el autocomplete
function createAutocomplete(create) {
    if (create) {
        var autoElement = 'ctl00_txtSearch';
        if ($('ctl00_ctl00_txtSearch')) {
            autoElement = 'ctl00_ctl00_txtSearch';
        }
        autocompleter = new Autocompleter.Local(autoElement, tokens, {
            'minLength': 1,
            'selectMode': true,
            'filterSubset': true,
            'forceSelect': false,
            'multiple': true,
            'separator': '  ',
            'onShow': function() { allowEnter = false; }
        });
    } else {
        autocompleter.destroy();
    }
}

function addEmptyTextToInput(inputId, text) {
    var t = $(inputId);
    t.addEvents({
        'focus': function() {
            if (t.value == text) { t.value = ''; t.setStyle('color', '#000000'); t.setStyle('font-style', 'normal'); }
        },
        'blur': function() {
            if (t.value == '' || t.value == text) { t.value = text; t.setStyle('color', '#878787'); t.setStyle('font-style', 'italic'); }
        }
    });
    t.fireEvent('blur');
}

/*POP UPS*/

var container;
var timeoutID;
function checkForOrders() {
    //alert('a');
    if (!container) { container = new PopUpContainer('popup_container'); }
    var hidPending = $('ctl00_hidPendingOrders');
    if (!hidPending) { hidPending = $('ctl00_ctl00_hidPendingOrders'); }
    if (hidPending && hidPending.get('value').length > 0) {
        loadPendingOrders(hidPending.get('value'));
        timeoutID = checkForOrders.delay(10000);
    } else {
        $clear(timeoutID);
    }
}

function loadPendingOrders(ordersString) {
    var orderRequest = new Request.JSON({
        'url': 'handlers/OrderClient.ashx',
        'onSuccess': function(responseJSON, responseText) {
            var orders = JSON.decode(responseText);
            orders.each(function(item, index) {
                if (item != 'error') {
                    container.addNewOrder(item);
                }
            });
        },
        'onFailure': function(reqObj) {
            timeoutID = checkForOrders.delay(10000);
            //alert('Ocurrió un error al verificar la respuesta del restaurant');
        }
    }).post({ 'a': 'req', 'os': ordersString });
}

var PopUpContainer = new Class({
    //implements 
    Implements: [Options, Events],
    //options 
    options: {

},
//initialization 
initialize: function(containerId, options) {
    //set options 
    this.setOptions(options);
    this.container = $(containerId);
    this.popUps = new Array();
},
//a method that does whatever you want 
addNewOrder: function(order) {
    if (!$('popup_order_' + order.OrderID)) {
        var pop = new PopUp(order, this.container);
        this.popUps.push(pop);
    } else {
        this.popUps.each(function(item, index) {
            if (order.OrderID == item.order.OrderID) {
                item.updateData(order);
            }
        });
    }
}
});

var PopUp = new Class({
    //implements 
    Implements: [Options, Events],
    //options 
    options: {
    //tiempos en segundos y estilos
    //        times: [5, 10, 15],
    //        classes: ['.green', '.yellow', '.red']
},

//initialization 
initialize: function(o, c, options) {
    //set options
    this.setOptions(options);
    this.order = o;
    this.container = c;
    this.waiting = false;
    this.finished = false;
    this.timerID;
    this.playedSound = false;
    this.createPopUp();
    this.updateData(o);
},
createPopUp: function() {
    //contenedor
    var divContainer = new Element('div', { id: 'popup_order_' + this.order.OrderID, 'class': 'popup' });
    //titulo
    var divTop = new Element('div', { 'class': 'popup_top' });
    var divImg = new Element('div', {
        'class': 'popup_top_left',
        'html': '<img id="popup_icon_' + this.order.OrderID + '" src="images/arrow_right.png" alt="popup_icon" />'
    });
    var divTitle = new Element('div', { id: 'popup_title_' + this.order.OrderID, 'class': 'popup_top_center' });
    var divClose = new Element('div', {
        'class': 'popup_top_close',
        'html': '<a style="display:none;" id="close_popup_' + this.order.OrderID + '" href="javascript:void(0);">X</a>'
    });
    divImg.inject(divTop);
    divTitle.inject(divTop);
    divClose.inject(divTop);
    divTop.inject(divContainer);
    var divBody = new Element('div', { 'class': 'popup_body' });
    var divMessage = new Element('div', { 'id': 'popup_message_' + this.order.OrderID });
    var divClosePopUp = new Element('div', { 'html': '<a id="close_end_' + this.order.OrderID + '" style="display:none;" href="javascript:void(0);">Cerrar</a>' });
    var divTime = new Element('div', {
        'class': 'popup_time',
        'html': '<img id="popup_loader_' + this.order.OrderID + '" src="images/ajax-loader-popup.gif" alt="loading" /><br />'
    });
    var spanTimer = new Element('span', { id: 'popup_timer_' + this.order.OrderID });
    divMessage.inject(divBody);
    spanTimer.inject(divTime);
    divTime.inject(divBody);
    divClosePopUp.inject(divBody);
    divBody.inject(divContainer);
    //al contenedor de todos
    divContainer.inject(this.container);
    if ($('close_end_' + this.order.OrderID)) {
        $('close_end_' + this.order.OrderID).addEvent('click', function() {
            var oID = this.order.OrderID;
            var orderCancel = new Request.JSON({
                'url': 'handlers/OrderClient.ashx',
                'onSuccess': function(responseJSON, responseText) {
                    var response = JSON.decode(responseText);
                    if (response.Message == 'Ok') {
                        if ($('popup_order_' + oID)) {
                            $('popup_order_' + oID).destroy();
                        }
                        var hidPending = $('ctl00_hidPendingOrders');
                        if (!hidPending) { hidPending = $('ctl00_ctl00_hidPendingOrders'); }
                        if (hidPending && hidPending.get('value').length > 0) {
                            hidPending.set('value', hidPending.get('value').replace(oID + ',', ''));
                        }
                    } else {
                        //alert('No se pudo cancelar el mensjae');
                        if ($('popup_order_' + oID)) {
                            $('popup_order_' + oID).destroy();
                        }
                        var hidPending = $('ctl00_hidPendingOrders');
                        if (!hidPending) { hidPending = $('ctl00_ctl00_hidPendingOrders'); }
                        if (hidPending && hidPending.get('value').length > 0) {
                            hidPending.set('value', hidPending.get('value').replace(oID + ',', ''));
                        }
                    }
                },
                'onFailure': function(reqObj) {
                    //alert('Ocurrió un error al cancelar el mensaje');
                    if ($('popup_order_' + oID)) {
                        $('popup_order_' + oID).destroy();
                    }
                    var hidPending = $('ctl00_hidPendingOrders');
                    if (!hidPending) { hidPending = $('ctl00_ctl00_hidPendingOrders'); }
                    if (hidPending && hidPending.get('value').length > 0) {
                        hidPending.set('value', hidPending.get('value').replace(oID + ',', ''));
                    }
                }
            }).post({ 'a': 'del', 'o': this.order.OrderID });
        } .bind(this));
    }
},

clearWait: function(isPreorder) {
    var title = '';
    var message = '';
    var image = 'images/time.png';
    this.waiting = false;
    if (isPreorder) {
        title = '¡Pedido enviado! :)';
        message = 'El pedido será confirmado a tu correo electrónico.';
        $('popup_loader_' + this.order.OrderID).setStyle('display', 'none');
        $('popup_timer_' + this.order.OrderID).setStyle('display', 'none');
    } else {
        title = '¡Pedido recibido! :)';
        message = 'En unos minutos recibirás la confirmación.';
    }

    if ($('popup_title_' + this.order.OrderID) && $('popup_message_' + this.order.OrderID) &&
            $('popup_icon_' + this.order.OrderID)) {
        $('popup_title_' + this.order.OrderID).set('html', title);
        $('popup_message_' + this.order.OrderID).set('html', message);
        $('popup_icon_' + this.order.OrderID).set('src', image);
    }
},

updateData: function(newOrderData) {
    var title = '';
    var message = '';
    var image = '';
    var show = true;
    //guardo hace cuanto esta el pedido time -> [h:m:s]
    var time = newOrderData.TimeDifference.split(':');
    this.setPopUpTimer(time);
    var random = $random(20, 30);
    //si esta dentro de los segundos que muestro
    if (time[2].toInt() < random && time[1].toInt() < 1) {
        if (!this.waiting) {
            title = 'Enviando pedido...';
            message = 'Tu pedido se está enviando a <b>' + newOrderData.RestaurantName + '</b>.';
            image = 'images/arrow_right.png';
            this.waiting = true;
            this.clearWait.delay((random - time[2].toInt()) * 1000, this, [newOrderData.IsPreorder]);
            show = true;
        } else {
            show = false;
        }
    } else {
        switch (newOrderData.OrderState) {
            case 'Pending':
                image = 'images/time.png';
                if (newOrderData.IsPreorder) {
                    title = '¡Pedido enviado! :)';
                    message = 'El pedido a <b>' + newOrderData.RestaurantName + '</b> será confirmado a tu correo electrónico.';
                    $('popup_loader_' + newOrderData.OrderID).setStyle('display', 'none');
                    $('popup_timer_' + this.order.OrderID).setStyle('display', 'none');
                    if ($('close_end_' + newOrderData.OrderID)) { $('close_end_' + newOrderData.OrderID).setStyle('display', 'block'); }
                } else {
                    title = '¡Pedido recibido! :)';
                    message = 'En unos minutos recibirás la confirmación.';
                }
                break;
            case 'Confirmed':
                if ($('close_end_' + newOrderData.OrderID)) { $('close_end_' + newOrderData.OrderID).setStyle('display', 'block'); }
                this.finished = true;
                if (!this.playedSound) { Playlist.playRandom(); this.playedSound = true; }
                $clear(this.timerID);
                image = 'images/tick.png';
                title = '¡Pedido confirmado! ;)';
                message = '<div>¡<b>' + newOrderData.RestaurantName + '</b> ha confirmado tu pedido!</div><br />';
                $('popup_loader_' + newOrderData.OrderID).setStyle('display', 'none');
                $('popup_timer_' + this.order.OrderID).setStyle('display', 'none');
                if (newOrderData.IsPreorder) {
                    if (newOrderData.DeliveryType == 'Delivery') {
                        message += '<div>Te será entregado ' + newOrderData.TimeToWait + '.</div><br />';
                    } else {
                    message += ' <div>Puedes retirarlo a las <b>' + newOrderData.TimeToWait + '</b>.</div><br />';
                    }
                } else {
                    if (newOrderData.DeliveryType == 'Delivery') {
                        message += '<div><b>' + newOrderData.TimeToWait + '</b> te será enviado.</div><br />';
                    } else {
                    message += '<div>En <b>' + newOrderData.TimeToWait + '</b> puedes retirarlo.</div><br />';
                    }
                }
                message += '<div>Por cualquier inconveniente puedes comunicarte al <b>' + newOrderData.RestaurantPhone + '</b></div>';
                break;
            case 'Rejected':
                if ($('close_end_' + newOrderData.OrderID)) { $('close_end_' + newOrderData.OrderID).setStyle('display', 'block'); }
                this.finished = true;
                if (!this.playedSound) { Playlist.playRandom(); this.playedSound = true; }
                $clear(this.timerID);
                image = 'images/cross.png';
                title = 'Pedido rechazado :(';
                message = ' <div><b>' + newOrderData.RestaurantName + '</b> ha rechazado tu pedido</div><div>Motivo: <label>' + newOrderData.RejectMessage + '</label></div><br />';
                message += '<div>Por cualquier inconveniente puedes comunicarte al ' + newOrderData.RestaurantPhone + '</div>';
                $('popup_loader_' + newOrderData.OrderID).setStyle('display', 'none');
                $('popup_timer_' + this.order.OrderID).setStyle('display', 'none');
                break;
        }
    }
    if (show) {
        //seteo de valores
        if ($('popup_title_' + newOrderData.OrderID) && $('popup_message_' + newOrderData.OrderID) &&
            $('popup_icon_' + newOrderData.OrderID)) {
            $('popup_title_' + newOrderData.OrderID).set('html', title);
            $('popup_message_' + newOrderData.OrderID).set('html', message);
            $('popup_icon_' + newOrderData.OrderID).set('src', image);
        }
    }
},
setPopUpTimer: function(time) {
    if ($('popup_timer_' + this.order.OrderID) && $('popup_timer_' + this.order.OrderID).get('html').length == 0 && !this.finished) {
        var h = time[0].toInt();
        var m = time[1].toInt();
        var s = time[2].toInt();
        var timer = '';
        if (h > 0) { if (h < 10) { timer += '0'; } timer += '' + h + ':'; }
        if (m < 10) { timer += '0'; } timer += '' + m + ':';
        if (s < 10) { timer += '0'; } timer += '' + s;
        $('popup_timer_' + this.order.OrderID).set('html', timer);
        this.timerID = this.refreshTime.periodical(1000, this);
    }
},
refreshTime: function() {
    if ($('popup_timer_' + this.order.OrderID) && $('popup_timer_' + this.order.OrderID).get('html').length > 0) {
        var current = $('popup_timer_' + this.order.OrderID).get('html');
        var time = current.split(':');
        var h = 0;
        var m = 0;
        var s = 0;
        if (time.length == 3) {
            h = time[0].toInt();
            m = time[1].toInt();
            s = time[2].toInt();
        } else {
            m = time[0].toInt();
            s = time[1].toInt();
        }
        s += 1; if (s == 60) { s = 0; m += 1; }
        if (m == 60) { m = 0; h += 1; }
        var timer = '';
        if (h > 0) { if (h < 10) { timer += '0'; } timer += '' + h + ':'; }
        if (m < 10) { timer += '0'; } timer += '' + m + ':';
        if (s < 10) { timer += '0'; } timer += '' + s;
        $('popup_timer_' + this.order.OrderID).set('html', timer);
    }
}
});

function prepareHints() {
    $$('span.hint').each(function(item, index) {
        var x = item.getParent().getElements('input');
        if (x.length == 0) {
            x = item.getParent().getElements('textarea');
        }
        if (x.length > 0) {
            var txt = x[0];
            item.setStyle('width', txt.getStyle('width'));
            txt.addEvents({
                'focus': function() {
                    item.fade('in');
                },
                'blur': function() {
                    item.fade('out');
                }
            });
        }
    });
}