$(document).ready(function(){

    slideShow();
    bindBrotativoNavBar();
    bindShoppingCartShow();
    sidebarMenuTop();
    bindUserLogout();
    
    $('ul.sf-menu').superfish();

    /*
    $('a.jqzoomimage').zoomimage({
	border: 20,
	centered: true,
        opacity:0.7
    });
    */
   
    bindDoCompra();


    
});


function bindUserLogout()
{
    $('.userDoLogout').click(function(){
        $.ajax({
            url: CONF_URL_APP + '/modulos/usuarios/actions.php',
            type:'post',
            data: {
                    'do': 'doLogout'
                  },
            cache:false,
            dataType:'json',
            success: function(data)
                     {
                         bloquearPantalla(data.msg, true);
                         setTimeout(
                            function(){
                                $.unblockUI();
                                if(data.dow)
                                    doDow(data.dow);
                            }, 3000);
                     }
        });
    });
}

function sidebarMenuTop()
{
    $('#sidebarMenuTop a[data-Nivel]').not('[data-Nivel=2]').each(function(){
        $(this).css('padding-left', ($(this).attr('data-Nivel') * 5) + 'px');
    });

}



function bindShoppingCartShow()
{
    $('#shoppingCart #scBottom').click(function(){
        
        if($('#scItems').css('display') == 'none')
        {
            $('#scItems').html('<div class="msg"><div class="loading"></div></div>');
            $('#scItems').slideDown('slow');
            $.ajax({
                url: CONF_URL_APP + '/modulos/shoppingCart/actions.php',
                type:'post',
                data: {
                        'do': 'getShoppingCart'
                      },
                cache:false,
                dataType:'json',
                success: function(data)
                         {
                            html = data.shoppingCart;
                            $(' ul, .msg' ,html).hide();
                            $('#shoppingCart #scItems').html(html);
                            $('.scInfoTotal').html(data.infoImporteTotal);
                            $('.scInfoItems').html(data.infoCantidadArticulos);
                            bindEliminarItemCesta();
                            $('#scItems ul, #scItems .msg').fadeIn('slow');
                         }
            });
        }
        else
        {
            $('#scItems .msg, #scItems ul').fadeOut('fast', function(){
                $('#scItems').slideUp('fast');
            });
        }

    });
}

function bindBrotativoNavBar()
{
    $('#brotativoNavBar div.prev').click( function(){gallery('prev');} );
    $('#brotativoNavBar div.next').click( function(){gallery('next');} );
}


function slideShow() {

    if(!$('#bannerRotativo').length)
        return;

	//Set the opacity of all images to 0
	$('#bannerRotativo a').css({opacity: 0.0});

	//Get the first image and display it (set it to full opacity)
	$('#bannerRotativo a:first').css({opacity: 1.0});

	//Set the caption background to semi-transparent
	$('#bannerRotativo .caption').css({opacity: 0.7});

	//Resize the width of the caption according to the image width
	//$('#bannerRotativo .caption').css({width: $('#bannerRotativo a').find('img').css('width')});

	//Get the caption of the first image from REL attribute and display it
	$('#bannerRotativo .content').html($('#bannerRotativo a:first').find('img').attr('rel'))
	.animate({opacity: 0.7}, 400);
	$('#bannerRotativo .content').each(function(){
		try{this.style.zoom = '0';}catch(e){;}
	});

	//Call the gallery function to run the slideshow, 6000 = change to next image after 6 seconds
	setInterval("gallery('next')",6000);

}

function gallery(prevORnext) {
    var current = ($('#bannerRotativo a.show') ?  $('#bannerRotativo a.show') : $('#bannerRotativo a:first'));

    var next = ((current.next().length) ? ((current.next().hasClass('caption'))? $('#bannerRotativo a:first') :current.next()) : $('#bannerRotativo a:first'));
    var prev = ((current.prev().length) ? ((current.prev().hasClass('caption'))? $('#bannerRotativo a:last') :current.prev()) : $('#bannerRotativo a:last'));

    var caption = prevORnext == 'prev' ? prev.find('img').attr('rel') : next.find('img').attr('rel');
    var slide = prevORnext == 'prev' ? prev : next;

    slide.css({opacity: 0.0})
    .addClass('show')
    .animate({opacity: 1.0}, 1000);

    current.animate({opacity: 0.0}, 1000)
    .removeClass('show');

    $('#bannerRotativo .caption').animate({opacity: 0.0}, {queue:false, duration:0}).css('display', 'none');
    $('#bannerRotativo .caption').animate({opacity: 0.7},100 ).slideDown();
    $('#bannerRotativo .content').html(caption);
	$('#bannerRotativo .content').each(function(){
		try{this.style.zoom = '0';}catch(e){;}
	});

}



function bindDoCompra()
{
    $('.doCompra').unbind('click').click(function(){
       $('.doCompra, .doCompraCantidad').removeClass('current');
       $(this).addClass('current');
       $(this).parent().find('.doCompraCantidad').addClass('current');
       doCompra($(this));
    });
}


function doCompra(obj)
{

    bloquearPantalla('Actualizando carrito de compras, aguarde un momento por favor...', true);

    var Cantidad;
    if($(obj).hasClass('scEliminarItem'))
    {
        Cantidad = 0;
        $('.scEliminarItem[data-IdProducto=' + $(obj).attr('data-IdProducto') + ']').fadeOut('slow');
        $('.doCompra[data-IdProducto=' + $(obj).attr('data-IdProducto') + '][class*=updateItem]').removeClass('updateItem');
    }
    else
    {
        Cantidad = isNaN(parseInt($('.doCompraCantidad[class*=current]').val())) ? 1 : parseInt($('.doCompraCantidad[class*=current]').val());
        $('.doCompra[data-IdProducto=' + $(obj).attr('data-IdProducto') + ']').not('[class*=scEliminarItem]').addClass('updateItem');
    }
    $.ajax({
        url: CONF_URL_APP + '/modulos/shoppingCart/actions.php',
        type:'post',
        data: {
                'do': 'updateItems',
                Id: $('.doCompra[class*=current]').attr('data-IdProducto'),
                Cantidad: Cantidad,
                ActualizaCompleto: $(obj).hasClass('scEliminarItem')
              },
        cache:true,
        dataType:'json',
        success: function(data, textStatus)
        {
            if(data.resultado)
            {
                //bloquearPantalla(data.msg, true);
                if(parseInt(data.itemCantidad) > 0)
                {
                    $(obj).parent().find('.scEliminarItem').fadeIn();
                }
                else
                {
                    $(obj).parent().find('.scEliminarItem').fadeOut();
                }

                $('#scItems').html(data.shoppingCart);
                $('.boxPagina .entry .checkoutSC').html(data.shoppingCartCheckout);
                $('.scInfoTotal').html(data.infoImporteTotal);
                $('.scInfoItems').html(data.infoCantidadArticulos);
                bindEliminarItemCesta();
                $.unblockUI();
            }
            else
            {
                bloquearPantalla(data.msg, true);

            }

            setTimeout(
                        function(){
                            $.unblockUI();
                            if(data.dow)
                                doDow(data.dow);
                        }, 3000);
        }

    });

}



function bindEliminarItemCesta()
{
    $('#shoppingCart li.scItem, ul.shoppingCart li.scItem').unbind('hover');
    $('#shoppingCart li.scItem, ul.shoppingCart li.scItem').hover(
        function(){$('.scEliminarItem', this).fadeIn();},
        function(){$('.scEliminarItem', this).fadeOut();}
    );

    $('.scEliminarItem').unbind('click');
    $('.scEliminarItem').click(function(){

        bloquearPantalla('Actualizando carrito de compras, aguarde un momento por favor...', true);
        var obj = $(this);
        $.ajax({
            url: CONF_URL_APP + '/modulos/shoppingCart/actions.php',
            type:'post',
            data: {
                    'do': 'updateItems',
                    Id: $(obj).attr('data-IdProducto'),
                    Cantidad: 0,
                    ActualizaCompleto: true
                  },
            cache:true,
            dataType:'json',
            success: function(data, textStatus)
            {
                if(data.resultado)
                {
                    $('.scEliminarItem[data-IdProducto=' + $(obj).attr('data-IdProducto') + ']').fadeOut('slow');
                    $('.doCompra[data-IdProducto=' + $(obj).attr('data-IdProducto') + '][class*=updateItem]').removeClass('updateItem');
                    //bloquearPantalla(data.msg, true);
                    $('#scItems').html(data.shoppingCart);
                    $('.boxPagina .entry .checkoutSC').html(data.shoppingCartCheckout);
                    $('.scInfoTotal').html(data.infoImporteTotal);
                    $('.scInfoItems').html(data.infoCantidadArticulos);
                    bindEliminarItemCesta();
                    $.unblockUI();
                }
                else
                {
                    bloquearPantalla(data.msg, true);

                }

                setTimeout(
                            function(){
                                $.unblockUI();
                                if(data.dow)
                                    doDow(data.dow);
                            }, 3000);
            }

        });

    });

}



function bindLogin(loginFormID)
{
        $('#' + loginFormID + ' input.submit').click(function(){

        bloquearPantalla('<div class="ajaxLoader">Validando datos ingresados, aguarde un momento por favor...</div>', true);
        $.ajax({
            url: CONF_URL_APP + '/modulos/usuarios/actions.php',
            type:'post',
            data: {
                    'do': 'doLoginWeb',
                    Email: $('#' + loginFormID + ' #Email').val(),
                    Password: $('#' + loginFormID + ' #Password').val()
                  },
            cache:false,
            dataType:'json',
            success: function(data, textStatus)
            {
                //bloquearPantalla(data.msg, true);
                if(data.resultado)
                {

                }
                else
                {
                    $.unblockUI();
                    $('#' + loginFormID + ' .msgError').html(data.msg).fadeIn();
                }

                setTimeout(
                            function(){
                                $.unblockUI();
                                if(data.dow)
                                    doDow(data.dow);
                            }, 3000);
            }

        });

    });
}
