$(window).load(function(){

    $('#slider').fadeIn('slow');

});

$(document).ready(function(){


    $('a.menuitem.submenuheader').dblclick(function(){
        window.location=$(this).attr('href');
    });




    $('#growl')
    .find('.close')
    .live('click', function() {
        $(this)
        .closest('.notice')
        .animate({
            border: 'none',
            height: 0,
            marginBottom: 0,
            marginTop: '-6px',
            opacity: 0,
            paddingBottom: 0,
            paddingTop: 0,
            queue: false
        }, 1000, function() {
            $(this).remove();
        });
    });


    $('a#perfilBtn').click(function(e){
        $('form#perfil').submit();
        e.preventDefault();
    })

    // Formulario de contacto
    $('a#contactarBtn').click(function(e){
        //$('form#contacto').submit();
        //alert($('form#contacto').attr('action'));
        var boton = $(this);
        boton.fadeOut('slow');
        $.ajax({
            type:"POST",
            url: $('form#contacto').attr('action'),
            data:$('form#contacto').serialize(),
            success: function(data){

                if(data.clase == 'msg-ok'){
                    addNotice($('<p class="msg-ok"></p>').append(data.msg));
                    $('form#contacto input').val('');
                }
                else{
                    var inputNombre = $('form#contacto input[name=nombre]');
                    inputNombre.removeClass('inputError');
                    var inputEmail = $('form#contacto input[name=email]');
                    inputEmail.removeClass('inputError');
                    var inputMensaje = $('form#contacto textarea[name=mensaje]');
                    inputMensaje.removeClass('inputError');
                    if(data.nombre){
                        inputNombre.addClass('inputError');
                        addNotice(data.nombre);
                    }
                    if(data.email){
                        inputEmail.addClass('inputError');
                        addNotice(data.email);
                    }
                    if(data.mensaje){
                        inputMensaje.addClass('inputError');
                        addNotice(data.mensaje);
                    }
                }
                boton.fadeIn('slow');
            },
            dataType: "json"
        });
        e.preventDefault();
    });

    // realizar Orden de Compra - Confirmar Resumen
    $('confirmarCompra').click(function(e){

        $('form#confirmarResumen').submit();
    //e.preventDefault();

    });


    // Destruir carrito
    $('a.button#destruirCarrito').click(function(e){

        if(confirm('¿Esta seguro que desea Vaciar el Carrito?')){
            $.ajax({
                type:"POST",
                url: $(this).attr('href'),
                success: function(data){

                    if(data.clase == 'msg-ok'){

                        $('ul.listing > li').fadeOut(3000, function(){
                            $(this).remove();
                        });
                        $('a#checkout').fadeOut(2000, function(){
                            $(this).remove();
                        });
                        $('li#total,#hdrPrice').html(data.total);
                        $('#hdrQty').html(data.cartqty);

                        addNotice($('<p class="msg-ok"></p>').append(data.msg));
                    }
                    else{
                        addNotice($('<p class="msg-fail"></p>').append(data.msg));
                    }
                },
                dataType: "json"
            });

        }
        e.preventDefault();

    });


    // Agregar PRODUCTOS al carrito
    $('a.button.addItem').click(function(e){

        var input = $('input[name='+ $(this).attr('rel') +'].qty');
        //        alert(input.val());
        var intRegex = /^\d+$/;
        if(!intRegex.test(input.val()) || input.val() == 0){
            alert('La cantidad debe ser un número positivo.');
        }else{

            $.ajax({
                async: false, //No deja ejecutar otro js hasta que termina el request :)
                type:"POST",
                url: $(this).attr('href'),
                data:{
                    qty: input.val()
                },
                success: function(data){

                    if(data.clase == 'msg-ok'){

                        $('#hdrPrice').html(data.total);
                        $('#hdrQty').html(data.cartqty);
                        //La multiplicacion y division por 1M es para evitar el error de multiplicacion (15,6666666666666667)
                        $('#montoComprados-'+data.id).html('$'+(1000000*parseFloat(data.price)*parseFloat(data.qty))/1000000);
                        $('#qtyComprados-'+data.id).html(data.qty+' ');
                        addNotice($('<p class="msg-ok"></p>').append(data.msg));
                    }
                    else{
                        addNotice($('<p class="msg-fail"></p>').append(data.msg));
                    }
                },
                dataType: "json"
            });

        }
        e.preventDefault();

    });

    // Agregar ARTICULO al carrito
    $('a#addArticulo').click(function(e){

        //alert($('form#verProducto').serializeArray());
        //console.log($('div.prod_info').serialize());

        var input = $('input[name='+ $(this).attr('rel') +'].qty');
        var intRegex = /^\d+$/;
        if(!intRegex.test(input.val()) || input.val() == 0){
            alert('La cantidad debe ser un número positivo.');
        }else{

            $.ajax({
                type:"POST",
                url: $(this).attr('href') + '/' + input.val(),
                data: $('form#verProducto').serializeArray(),
                success: function(data){

                    if(data.clase == 'msg-ok'){

                        $('#hdrPrice').html(data.total);
                        $('#hdrQty').html(data.cartqty);
                        addNotice($('<p class="msg-ok"></p>').append(data.msg));

                        window.location=window.location;
                    }
                    else{
                        addNotice($('<p class="msg-fail"></p>').append(data.msg));
                    }
                },
                dataType: "json"
            });

        }
        e.preventDefault();

    });



    // Actualizar cantidad de un PRODUCTO del carrito
    $('ul.cartitems li.quantity.smalltext input').change(function(){
        //alert($(this).serialize());
        var input = $(this);
        var intRegex = /^\d+$/;
        if(!intRegex.test(input.val()) || input.val() == 0){
            alert('La cantidad debe ser un número positivo.');
        }else{
            $('#totalOrdenCompra').html('Calculando...');
            $.ajax({
                async: false, //No deja ejecutar otro js hasta que termina el request :)
                type:"POST",
                url: base_url + 'carrito/updateItem',
                data: {
                    rowid : input.attr('name'),
                    qty : input.val()
                },
                success: function(data){

                    if(data.clase == 'msg-ok'){
                        $('li#' + input.attr('name') + ' ul.cartitems li.total.smalltext').html(data.subtotal);
                        $('li#total').html(data.total);
                        $('#hdrPrice').html(data.total);
                        $('#hdrQty').html(data.cartQty);
                        $('#totalOrdenCompra').html(data.total);
                    }

                },

                dataType: "json"
            });
        }
    })



    // Eliminar PRODUCTOS del carrito
    $('a.cross').click(function(e){
        
        //alert($(this).attr('href'));
        $.ajax({
            type:"POST",
            url: $(this).attr('href'),
            success: function(data){

                if(data.clase == 'msg-ok'){
                    $('#' + data.id).fadeOut(3000, function(){
                        $(this).remove();
                    });
                    $('li#total,#hdrPrice').html(data.total);
                    $('#hdrQty').html(data.cartqty);
                    addNotice($('<p class="msg-ok"></p>').append(data.msg));
                }
            },
            dataType: "json"
        });
        e.preventDefault();
    });



    
});

function addNotice(notice) {
    $('<div class="notice"></div>')
    .append('<div class="skin"></div>')
    .append('<a href="#" class="close">close</a>')
    .append($('<div class="content"></div>').html($(notice)))
    .hide()
    .appendTo('#growl')
    .fadeIn(1000)
    .fadeOut(7000, function(){
        $(this).remove();
    });
}
