$(function() {
    $( "fieldset" ).addClass("ui-widget");
    $( "fieldset legend, #contenido h1" ).addClass("ui-widget-header ui-corner-all");
    $( ".botones" ).buttonset();
    $( ".boton,.boton" ).button();
    var $nombres=$("#cliente input[name$='cliente[nombres]']"),
        $rif=$("#cliente input[name$='cliente[rif]']"),
        $email=$("#cliente input[name$='cliente[email]']"),
        $telefono=$("#cliente input[name$='cliente[telefono]']"),
        $skype=$("#cliente input[name$='cliente[skype]']"),
        $direccion=$("#cliente input[name$='cliente[direccion]']"),
        $estado=$("#cliente input[name$='cliente[estado]']"),
        $municipio=$("#cliente input[name$='cliente[municipio]']"),
        allFields = $( [] ).add($nombres).add($rif).add($email).add($telefono).add($skype).add($direccion).add($estado).add($municipio),
        tips = $( ".validateTips" );
        
    var $tabs = $("#compra").tabs({
        ajaxOptions: {
            error: function( xhr, status, index, anchor ) {
                $( anchor.hash ).html("Ocurrió un error mientras se cargaba la página por favor intente de nuevo.");
            }
        }
    });
    $('.anterior').click(function() { 
        var $selected = $('#compra').tabs('option', 'selected');
        $tabs.tabs('select', $selected-1); // switch to third tab
        return false;
    });
    $('.siguiente').click(function() { 
        var $selected = $('#compra').tabs('option', 'selected');
        $tabs.tabs('select', $selected+1);
        return false;
    });
    var $tienda = $('#tienda');



    $('li',$tienda).draggable({
            cancel: 'a.ui-icon',
            helper: 'clone',
            cursor: 'move'
    });
    
    $('#compra').droppable({
            accept: '#tienda > li',
            activeClass: 'ui-state-active',
            hoverClass: 'ui-state-hover',
            drop: function(ev, ui) {
                addcarrito('agregar',$(ui.draggable).attr('id'),1);
            }
    });

    // resolve the icons behavior with event delegation
    $('ul.tienda > li').click(function(ev) {
            var $item = $(this);
            var $target = $(ev.target);

            if ($target.is('a.ui-icon-cart')) {
                addcarrito('agregar',$($item).attr('id'),1);
                return false;
            } else if ($target.is('a.ui-icon-zoomin')) {
                 alert('Aqui va funcion de maximizar imagen o mostrar un dialogo más detallado.');
            }
    });
    $('ul.tienda > li > label select').change(function(ev) {
           var $item = $('#lista_'+this.name);
           var $cant = this.value;
           addcarrito('agregar',$($item).attr('id'),$cant);
           this.value='';
    });
    
    function updateTips( t ) {
        tips.text(t).addClass( "ui-state-highlight" );
        $("#compra").tabs('select', 1);
        setTimeout(function() {
                tips.removeClass( "ui-state-highlight", 1500 );
        }, 500 );
    }
    function checkLength( o, n, min, max ) {
            if ( o.val().length > max || o.val().length < min ) {
                    o.addClass( "ui-state-error" );
                    updateTips( "El campo " + n + " debe tener entre " +
                            min + " y " + max + " carácteres." );
                    return false;
            } else {
                    return true;
            }
    }

    function checkRegexp( o, regexp, n ) {
            if ( !( regexp.test( o.val() ) ) ) {
                    o.addClass( "ui-state-error" );
                    updateTips( n );
                    return false;
            } else {
                    return true;
            }
    }

    $('#listo').click(function(ev) {
        var $cliente=$('#cliente').serialize();

        var bValid = true;
        allFields.removeClass( "ui-state-error" );
        bValid = bValid && checkLength( $nombres, "Nombres", 3, 16 );
        bValid = bValid && checkLength( $email, "email", 6, 80 );

        bValid = bValid && checkRegexp( $email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "Email no válido. sunombre@hotmail.com" );

        if ( bValid ) {
           $('#procesar').load('/tienda/procesar',$cliente);
        }
        //
        return false;
    });
});
function addcarrito($accion,$id,$cant){
    $('#compra,#'+$id).addClass('ui-state-hover');
    $('#ui-tabs-1').load('/tienda/carrito/accion/'+$accion+'/cantidad/'+$cant+'/id/'+$id,'',function(){
        $('#compra,#'+$id).removeClass('ui-state-hover');
        $("#compra").tabs('select', 0);
    });
}
