$(function(){

       $('table.mostrar td input').focus(function(){
            valor_original = this.value;
            this.value="";
            $(this).css({border:"1px solid #E73D3A",backgroundColor:"#fff" });
        })
        .blur(function(){
            if((this.value == "")||(this.value == 0))
                this.value = valor_original;      
            $(this).css({border:"1px solid #999" });
        }
        );

     $('#dialog-comprar').dialog({
            autoOpen: false,
            modal: true,
            buttons: {
                'realizar pedido': function() {
                    location.href = WEB + "tienda"
                    $(this).dialog('close');
                },
                'continuar compra': function() {
                    $(this).dialog('close');
                }
            },
            close: function() {
				$comentario = $(this).find('#comentario');
                var comentario = $comentario.val();
                if(comentario){
                    $.ajax ({ url: $(this).find('form').attr('action')+'/nota/'+comentario,
                    success:function(msg){
                                $('#compras').html(msg);
                                mapear_carrito();
                            }
                    });
                    $comentario.val('');
                }
			}

        });


     //star
     $('a[rel="toggle"]').click( function(){
         
            $link = $(this);
            $.ajax ({ url: $link.attr('href') });
            $link.toggleClass('ui-state-disabled');
            return false;
            });
     $('a[rel="icon-toggle"]').click( function(){
         
            $link = $(this);
            $.ajax ({ url: $link.attr('href') });
            $link.toggleClass('icon-disabled');
            return false;
            });

     //FUNCIÓN QUE AVISA CUANDO SE HA AGREGADO UN PRODUCTO
	 $('a[rel="comprar"]').click(function() {


            $elementopadre = $(this).parent().parent();
            var id = $elementopadre.attr('id');
            id = id.replace(/id_/, "");
            /*-------------------*/
            $elementoinput = $elementopadre.find("td input[type = text]");

            $('#dialog-comprar').dialog('open');

            /*----------------------*/
            var unidades = $elementoinput.val();
            var tipo_unidad = $elementoinput.parent().text();
            if(tipo_unidad == ' grs.'){
            if( unidades < 100){
                    if(LOCALE == 'ca') alert('la cantitat seleccionada deu de ser superior a 100 grs');
                    else alert('la cantidad seleccionada debe ser superior a 100 grs');
                    $elementoinput.val('100');
                    return false;
				}
			}else{
                if(unidades == 0) unidades = 1;
            }


            $link = $(this);          
            $.ajax ({ url: $link.attr('href')+'/cantidad/'+unidades,
                    success:function(msg){
                                $('#compras').html(msg);
                                mapear_carrito();
                            }
            });
            $elementoinput.val('');
            return false;
	 });

     function comprartodos(){
        var productos = "";
        var cantidades = "";
        var numeros_correctos = true;
        var num = 0;
      
        $(":checkbox").each(function(i){
            if(this.checked){
                num++;
                unidades = $(this).parent().parent().find("td input[type = text]").val();
                tipo_unidad = $(this).parent().parent().find("td input[type = text]").parent().text();
                if(tipo_unidad == ' grs.'){
                    if( unidades < 100){
                        numeros_correctos = false;
                        $(this).parent().parent().find("td input[type = text]").css({ backgroundColor:"#ED7375"});
                    }
                }else{
                    if(unidades == 0){
                        numeros_correctos = false;
                        $(this).parent().parent().find("td input[type = text]").css({ backgroundColor:"#ED7375"});
                    }
                }
            }
        })
        if(num){
            if(numeros_correctos){
                $(":checkbox").each(function(i){//es comno si la i fuera un contador
                    if(this.checked){
                        var punteroch = $(this);
                        cantidades += punteroch.parent().parent().find("td input[type = text]").val() + "-";
                        productos += punteroch.attr("id").replace(/ch_/g, "") + "-";
                    }
                });

                cantidades = cantidades.substring(0,cantidades.length-1);
                productos = productos.substring(0,productos.length-1);

                $link = $(this);
                $.ajax ({ url: $link.attr('href') + "/productos/" + productos + "/cantidades/" +cantidades,
                        success:function(msg){
                                    $('#compras').html(msg);
                                    mapear_carrito();
                                }
                });
                mapear_carrito();
            }else{
                alert('alguna de las cantidades especificadas no son correctas');
            }
        }else{
            alert('Ningún producto ha sido seleccionado');
        }
        return false;
    }

         mapear_carrito();
    });



//Mapeado de las funciones del carrito
function mapear_carrito(){

    //FUNCIÓN PARA BORRAR ARTICULOS DE LA COMPRA
	$('#compras a[rel="carro-delete"]').click( function(){
        var producto = $(this).attr('title').replace('Eliminar producto ','');
        if (confirm('¿Desea borrar el producto '+ producto +' de su compra?')){
            $link = $(this);
            $.ajax ({ url: $link.attr('href'),
                    success:function(msg){
                                $('#compras').html(msg);
                                mapear_carrito();
                            }
            });
        }
        return false;
    });
    $('#compras a[rel="carro-empty"] button').click(function(){

        if (confirm('¿Desea vaciar el carrito de la compra?')){
            $link = $(this);
            $.ajax ({ url: $link.parent().attr('href'),
                    success:function(msg){
                                $('#compras').html(msg);
                                mapear_carrito();
                            }
            });
        }
        return false;
    });

    //FUNCION PARA AGREGAR NOTAS AL CARRITO DE LA COMPRA
    $('a[rel="carro-comentario"]').click(function(){

        $link = $(this);
        var title = $link.attr('title');
        if(title == 'añade un comentario') title = '';

        var comentario = '';
        comentario = prompt('Introduzca el comentario que desee acerca del producto.',title);
        if(comentario){
            comentario = '/nota/'+comentario;

            $.ajax ({ url: $link.attr('href')+comentario,
                    success:function(msg){
                                $('#compras').html(msg);
                                mapear_carrito();
                            }
            });
        }
        return false;
    });

    //FUNCION PARA RECALCULAR EL CONTENIDO DEL CARRITO
    var valor_anterior= null;
    $('.num input').focus(function(){
         valor_anterior = this.value;
    }),
    $(".num input").blur(function () {
           
         var mensaje = 'La cantidad de este producto se ha actualizado a ';
         var unidades = $(this).val();
         var tipo_unidad = $(this).parent().text();
             tipo_unidad = tipo_unidad.substr(5, 4);


         var id = $(this).attr('id');
         	 id = id.replace(/cantidad/, "");
             mensaje += unidades + ' ' + tipo_unidad;
         if($(this).val() != ""){             
             if($(this).val() != valor_anterior){
                 if($(this).val() != 0){
                     if(tipo_unidad == 'grs.'){
                         if(unidades >= 100){
                         alert(mensaje);
                             $.ajax ({ url: COMPRA + '/set/id/' + id + '/cantidad/' + unidades,
                                 success:function(msg){
                                 $('#compras').html(msg);
                                 mapear_carrito();
                                 }
                            });
                         }else{
                            alert('la cantidad introducia debe ser superior a 100 grs.');
                            $(this).val(valor_anterior);
                         }
                     }else{
                        alert(mensaje);
                        $.ajax ({ url: COMPRA + '/set/id/' + id + '/cantidad/' + unidades,
                            success:function(msg){
                            $('#compras').html(msg);
                            mapear_carrito();
                            }
                        });
                    }
                }else{
                    alert('Seleccione un valor mayor que 0. Si lo que desea es borrar el producto haga click en eliminar.');
                    $(this).val(valor_anterior);
                }
            }else{
                $(this).val(valor_anterior);
            }
        }
        return false;
    });

    //FUNCIÓN VACIAR CARRITO
    $('a[rel="carro-empty"]').click(function(){

        if(confirm('¿Está seguro de que desea vaciar su carrito de la compra?')){
            $link = $(this);
            $.ajax ({ url: $link.attr('href'),
                    success:function(msg){
                                $('#compras').html(msg);
                                mapear_carrito();
                            }
            });
        }
        return false;
    });

}

