function limpiadorBuscador() {
    var campoBuscador = document.getElementById('cBuscador');
    if (campoBuscador.value == 'JaponShop') campoBuscador.value = '';
}

var selecBtnDialog = 0;

if(idioma == 'pt') {
    var btnDialog = [
    {
        "Realizar Pedido": realizarPedido,
        "Atualizar": actualizarCarrito,
        "Continuar comprando": function() {
            $('#dialog').dialog("close");
        }
    },
    {
        "Continuar comprando": function() {
            $('#dialog').dialog("close");
        }
    },
    {
        "Comprar": enviarPedido
    },
    {
        "Pagar": enviarPaypal
    },
    {
        "Ok": function() {
            $('#dialog').dialog("close");
        }
    },
    {
        "Pagar": enviarRuralvia
    }
    ];

    var botonesLogin = {
        "Iniciar sessão": enviarLogin,
        "Esqueceu sua senha?": nuevoPass
    };
}
else {
    var btnDialog = [
    {
        "Finalizar Compra": realizarPedido,
        "Actualizar": actualizarCarrito,
        "Seguir Comprando": function() {
            $('#dialog').dialog("close");
        }
    },
    {
        "Seguir Comprando": function() {
            $('#dialog').dialog("close");
        }
    },
    {
        "Comprar": enviarPedido
    },
    {
        "Pagar": enviarPaypal
    },
    {
        "Ok": function() {
            $('#dialog').dialog("close");
        }
    },
    {
        "Pagar": enviarRuralvia
    }
    ];

    var botonesLogin = {
        "Iniciar": enviarLogin,
        "Olvidaste tu contraseña?": nuevoPass
    };    
}


var abiertoXcesta = false;

jQuery(document).ready(function(){

    $("#BotonConsultaEnviar").live("click", function(){
        var destino = $("#ConsultaProductoForm").attr('action');
        jQuery.ajax({
            url: destino,
            type: "POST",
            data: jQuery("#ConsultaProductoForm").serialize(),
            cache: false,
            success: function(html){
                jQuery("div#consulta-producto").html(html);
            },
            beforeSend: function(){
                jQuery("div#cargador").show();
            },
            complete: function(){
                jQuery("div#cargador").hide();
            }
        });
        return false;
    });
    
    if(idioma == 'pt') {
        $('#dialog').dialog({
            autoOpen: false,
            width: 720,
            title: 'Cesta de Ordem',
            modal: true,
            buttons: btnDialog[selecBtnDialog]
        });

        $('#alertas').dialog({
            autoOpen: false,
            title: 'Atenção',
            modal: true,
            buttons: {
                "Ok": function() {
                    $(this).dialog("close");
                }
            }
        });

        $('#login').dialog({
            autoOpen: false,
            width: 450,
            title: 'Iniciar sessão',
            modal: true,
            buttons: {
                "Enviar": enviarLogin,
                "Esqueceu sua senha?": nuevoPass
            }
        });

        $('#alta').dialog({
            autoOpen: false,
            width: 720,
            title: 'Registro de Usuário',
            modal: true,
            buttons: {
                "Enviar": enviarAlta
            }
        });
    }
    else {
        $('#dialog').dialog({
            autoOpen: false,
            width: 720,
            title: 'Cesta de pedido',
            modal: true,
            buttons: btnDialog[selecBtnDialog]
        });

        $('#alertas').dialog({
            autoOpen: false,
            title: 'Atención',
            modal: true,
            buttons: {
                "Ok": function() {
                    $(this).dialog("close");
                }
            }
        });

        $('#login').dialog({
            autoOpen: false,
            width: 450,
            title: 'Inicio de Sesión',
            modal: true,
            buttons: {
                "Enviar": enviarLogin,
                "Olvidaste tu contraseña?": nuevoPass
            }
        });

        $('#alta').dialog({
            autoOpen: false,
            width: 720,
            title: 'Registro de Usuarios',
            modal: true,
            buttons: {
                "Enviar": enviarAlta
            }
        });
    }

    $("a.agregar-producto").live('click', function(){
        var id = jQuery(this).attr('rel');
        var nro = jQuery("#ProductoCantidad"+id).attr("value");
        var stock = jQuery("#ProductoStock"+id).attr("value");
        var nroLimpio = nro.replace(/\D/g, "");
        var regex = /^[0-9]+$/;
        if (regex.test(nroLimpio) == false) {
            alert("Cantidad incorrecta. Debe entrar un número.");
            return false;
        }
        var nuevoStock = parseInt(stock) - parseInt(nroLimpio);
        if (nuevoStock < 0) {
            alert("El stock es "+stock+". Por favor, seleccione una cantidad inferior");
            return false;
        }

        jQuery.ajax({
            url: dir_raiz+'productos/agregar',
            type: "POST",
            data: {
                id: id,
                cantidad: nroLimpio
            },
            cache: false,
            success: function(html){
                jQuery("#dialog").html(html);
                $('#dialog').dialog('open');
                verificarBotones();
                actualizarNro();
            },
            beforeSend: function(){
                jQuery("div#cargador").show();
            },
            complete: function(){
                jQuery("div#cargador").hide();
            }
        });
        return false;
    });

    jQuery("select.selector-opciones").change(function() {
        var partes = jQuery(this).val().split(/:/);
        actualizarVerProd(partes[3]);
    });

    $("a.borrar-producto").live("click", function(){
        var id = $(this).attr('rel');
        jQuery.ajax({
            url: dir_raiz+'productos/quitar',
            type: "POST",
            data: {
                id: id
            },
            cache: false,
            success: function(html){
                jQuery("#dialog").html(html);
                verificarBotones();
                actualizarNro();
            },
            beforeSend: function(){
                jQuery("div#cargador").show();
            },
            complete: function(){
                jQuery("div#cargador").hide();
                $('#dialog').dialog('open');
            }
        });
        return false;
    });

    $("#menu-cesta").live("click", function(){

        jQuery.ajax({
            url: dir_raiz+'productos/lista',
            type: "GET",
            cache: false,
            success: function(html){
                jQuery("#dialog").html(html);
                $('#dialog').dialog('open');
                verificarBotones();
            },
            beforeSend: function(){
                jQuery("div#cargador").show();
            },
            complete: function(){
                jQuery("div#cargador").hide();
            }
        });
        return false;
    });

    function actualizarNro() {
        jQuery.ajax({
            url: dir_raiz+'productos/numero',
            type: "GET",
            cache: false,
            success: function(html){
                jQuery("#menu-cesta").html(html);
            }
        });
    }

    $(".producto-agregar, .esc-producto-agregar").hover(
        function () {
            $(this).find("div.aviso").show();
        },
        function () {
            $(this).find("div.aviso").hide();
        }
    );
        
    $("#menu-newsletter").hover(
        function () {
            $(this).find("#newsletter").show();
        },
        function () {
            $(this).find("#newsletter").hide();
        }
    );

    $("#BotonSuscribirse").live("click", function(){
        var urldestino = jQuery("#CorreoAgregarForm").attr('action');
		jQuery.ajax({
            url: urldestino,
            type: "POST",
            data: jQuery("#CorreoAgregarForm").serialize(),
            cache: false,
            success: function(html){
                jQuery("#boletin").html(html);
            },
            beforeSend: function(){
                jQuery("#cargador").show();
            },
            complete: function(){
                jQuery("#newsletter").show();
                jQuery("#cargador").hide();
            }
        });
        return false;
    });
    
    $("#menu-idioma").hover(
        function () {
            $("#idioma").show();
        },
        function () {
            $("#idioma").hide();
        }
    );
        
    $("#btn-presentacion").hover(
        function () {
            $("#imagen-ilustrativa").attr('src', imgs[2].src);
        },
        function () {
            $("#imagen-ilustrativa").attr('src', imgs[1].src);
        }
    );    

});

function actualizarContexto() {
    jQuery.ajax({
        url: dir_raiz+'productos/actualizar_menu',
        type: "GET",
        cache: false,
        success: function(html){
            jQuery("#menu-usuario").html(html);
        }
    });

    if(abiertoXcesta == true) {
        realizarPedido();
        $('#login').dialog("close");
    }
    else {
        $("#login").dialog( "option", "buttons", {
            "Ok": function() {
                $('#login').dialog("close");
            }
        });
    }
}

function actualizarCarrito() {
    jQuery.ajax({
        url: dir_raiz+'productos/actualizar',
        type: "POST",
        data: jQuery("#ActualizarProductoForm").serialize(),
        cache: false,
        success: function(html){
            jQuery("#dialog").html(html);
            verificarBotones();
        },
        beforeSend: function(){
            jQuery("div#cargador").show();
        },
        complete: function(){
            jQuery("div#cargador").hide();
            $("#alertas").html("Cesta Actualizada.");
            $('#alertas').dialog('open');

        }
    });
}

function realizarPedido() {
    jQuery.ajax({
        url: dir_raiz+'pedidos/agregar',
        type: "GET",
        cache: false,
        success: function(html){
            jQuery("#dialog").html(html);
            $('#dialog').dialog('open');
        },
        beforeSend: function(){
            jQuery("div#cargador").show();
        },
        complete: function(){
            jQuery("div#cargador").hide();
            verificarBotones();
        }
    });
}

function verificarBotones() {
    $("#dialog").dialog( "option", "buttons", btnDialog[selecBtnDialog])
    $('.ui-dialog-buttonpane :button')
    .each(
        function() {
            var t = $(this).text();
            if(t == 'Seguir Comprando') {
                $(this).addClass('btn-seguir');
            }
            else if(t == 'Actualizar') {
                $(this).addClass('btn-actualizar');
            }
            else if(t == 'Finalizar Compra') {
                $(this).addClass('btn-finalizar');
            }
        }
        );
}

function actualizarVerProd(indice) {
    jQuery("span#producto-precio").html(opciones[indice].precio);
    jQuery("span#producto-sku").html(opciones[indice].sku);
}

function login(cesta) {
    abiertoXcesta = cesta;

    if(cesta == true) {
        $('#dialog').dialog("close")
    }

    jQuery.ajax({
        url: dir_raiz+'usuarios/login_ajax',
        type: "GET",
        cache: false,
        success: function(html){
            jQuery("#login").html(html);
            $("#login").dialog( "option", "buttons", botonesLogin);
        },
        beforeSend: function(){
            jQuery("div#cargador").show();
        },
        complete: function(){
            jQuery("div#cargador").hide();
            $('#login').dialog('open');
        }
    });
    return false;
}

function enviarLogin() {
    var destino = $("#f-login").attr('action');
    jQuery.ajax({
        url: destino,
        type: "POST",
        data: jQuery("#f-login").serialize(),
        cache: false,
        success: function(html){
            jQuery("#login").html(html);
        },
        beforeSend: function(){
            jQuery("div#cargador").show();
        },
        complete: function(){
            jQuery("div#cargador").hide();
        }
    });
}

function nuevoPass() {
    jQuery.ajax({
        url: dir_raiz+'clientes/nuevo_pass',
        type: "GET",
        cache: false,
        success: function(html){
            jQuery("#login").html(html);
            $("#login").dialog( "option", "buttons", {
                "Enviar": enviarNuevoPass
            });
        },
        beforeSend: function(){
            jQuery("div#cargador").show();
        },
        complete: function(){
            jQuery("div#cargador").hide();
            $('#login').dialog('open');
        }
    });
    return false;
}

function enviarNuevoPass() {
    var destino = $("#f-recordar").attr('action');
    jQuery.ajax({
        url: destino,
        type: "POST",
        data: jQuery("#f-recordar").serialize(),
        cache: false,
        success: function(html){
            jQuery("#login").html(html);
        },
        beforeSend: function(){
            jQuery("div#cargador").show();
        },
        complete: function(){
            jQuery("div#cargador").hide();
        }
    });
}

function alta(cesta) {
    abiertoXcesta = cesta;

    if(cesta == true) {
        $('#dialog').dialog("close")
    }

    jQuery.ajax({
        url: dir_raiz+'clientes/alta',
        type: "GET",
        cache: false,
        success: function(html){
            jQuery("#alta").html(html);
        },
        beforeSend: function(){
            jQuery("div#cargador").show();
        },
        complete: function(){
            jQuery("div#cargador").hide();
            $('#alta').dialog('open');
        }
    });
    return false;
}

function enviarAlta() {
    var destino = $("#f-alta").attr('action');
    jQuery.ajax({
        url: destino,
        type: "POST",
        data: jQuery("#f-alta").serialize(),
        cache: false,
        success: function(html){
            jQuery("#alta").html(html);
        },
        beforeSend: function(){
            jQuery("div#cargador").show();
        },
        complete: function(){
            jQuery("div#cargador").hide();
        }
    });
}

function enviarPedido() {
    var destino = $("#PedidoAgregarForm").attr('action');
    jQuery.ajax({
        url: destino,
        type: "POST",
        data: jQuery("#PedidoAgregarForm").serialize(),
        cache: false,
        success: function(html){
            jQuery("#dialog").html(html);
            verificarBotones();
        },
        beforeSend: function(){
            jQuery("div#cargador").show();
        },
        complete: function(){
            jQuery("div#cargador").hide();
        }
    });
}

function enviarPaypal() {
    $("#f-paypal").submit();
}

function enviarRuralvia() {
    $("#tpv").submit();
}

function makeSublist(parent, child, isSubselectOptional, childVal){
    $("body").append("<select style='display:none' id='" + parent + child + "'></select>");
    $('#' + parent + child).html($("#" + child + " option"));
    var parentValue = $('#' + parent).attr('value');
    $('#' + child).html($("#" + parent + child + " .sub_" + parentValue).clone());
    childVal = (typeof childVal == "undefined") ? "" : childVal;
    $("#" + child + ' option[value="' + childVal + '"]').attr('selected', 'selected');
    
	$('#' + parent).change(function(){
        var parentValue = $('#' + parent).attr('value');
        $('#' + child).html($("#" + parent + child + " .sub_" + parentValue).clone());   
        if (isSubselectOptional) 
            $('#' + child).prepend("<option value='none'> -- Select -- </option>");
        
        $('#' + child).trigger("change");
        $('#' + child).focus();
    });
    
}

function mostrarCostos(pais) {
    if(pais != '') {
        $('#mpago-costos').show();
        $('#envio-costos').show();
        $('.lista-costos').hide();
        $('#mpago-costos-'+pais).show();
        $('#envio-costos-'+pais).show();
    }
    else {
        $('#mpago-costos').hide();
        $('#envio-costos').hide();
    }
}
