Ep = {};

Ep.urlEncodeCharacter = function(c){
    return '%' + c.charCodeAt(0).toString(16);
};

Ep.trim = function(str){
    return str.replace(/^\s+|\s+$/g,"")
}

Ep.urlDecodeCharacter = function(str, c){
    return String.fromCharCode(parseInt(c, 16));
};

Ep.urlEncode = function( s ){
    return encodeURIComponent( s ).replace( /\%20/g, '+' )
                                  .replace( /[!'()*~]/g, Ep.urlEncodeCharacter );
};

Ep.urlDecode = function( s ){
    return decodeURIComponent(s.replace( /\+/g, '%20' ))
                .replace( /\%([0-9a-f]{2})/g, Ep.urlDecodeCharacter);
};

// Trasforma la stringa € 123.456.789,00 nel float 123456789.00
Ep.euroToFloat = function(euroStr){
    euroStr = String(euroStr);
    var euroFloat = 0;
    euroStr = euroStr.slice(euroStr.indexOf("\u20ac")+1).replace(/\./g,"");
    euroStr = euroStr.replace(",",".");
    euroFloat = parseFloat(euroStr);

    return euroFloat;
}


// Trasforma il float 123456789.00 nella stringa 123.456.789,00
Ep.floatToEuro = function(euroFloat){
    euroFloat = String(Math.round(euroFloat * Math.pow(10, 2)) / Math.pow(10, 2));
    var euroStr = "";
    if(euroFloat.indexOf(".") == -1){
        var j = euroFloat.length % 3;
        if(j == 0) j = 3;
        for(var i = 0; i < euroFloat.length-1 ; i++){
            if (i == j){
                var part1 = euroFloat.slice(0,i);
                var part2 = euroFloat.slice(i);
                euroFloat = part1.concat(".",part2);
                j += 4;
            }
        }
        euroFloat += ",00";
    } else {
        var tmp = ',' + euroFloat.slice(euroFloat.indexOf(".")+1);
        if (tmp.length == 1) tmp += "00";
        if (tmp.length == 2) tmp += "0";
        euroFloat = euroFloat.slice(0,euroFloat.indexOf("."));
        j = euroFloat.length % 3;
        if(j == 0) j = 3;
        for(i = 0; i < euroFloat.length-1 ; i++){
            if (i == j){
                part1 = euroFloat.slice(0,i);
                part2 = euroFloat.slice(i);
                euroFloat = part1.concat(".",part2);
                j += 4;
            }
        }
        euroFloat += tmp;
    }
    euroStr = euroFloat;

    return euroStr;
}

Ep.formatCurrency = function(num) {
    if(isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    num = Math.floor(num/100).toString();
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+'.'+
    num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') +  num);
}

Ep.search = function() {
    // Tabella da cui è stato generato l'evento
    var $table = $(this).parents('table');
    // Visualizza tutte le righe
    $table.find('tr').css('display','');

    // Esegue un ciclo per ogni elemento di classe '.table-filter' (elementi per la ricerca)
    for(var iii = 0; iii < $table.find('.table-filter').length; iii++){
        // Elemento di ricerca
        var searcherElement = $table.find('.table-filter').get(iii);
        // Valore dell'elemento di ricerca
        var value = searcherElement.value.toUpperCase();
        var th = $table.find('.table-filter').eq(iii).parents('th').get(0);
        // Insieme delle righe visibili. Sono le uniche righe fra cui cercare le corrispondenze,
        // in questo modo si ottiene l'intersezione fra i risultati dei vari elementi di ricerca
        var visibleTr = $table.find('tr:visible');
        // Indice della colonna relativa all'elemento di ricerca
        actualIndex = false;
        for(var jjj = 0; jjj < $table.find('th').length; jjj++){
            if($table.find('th').get(jjj) == th) {
                actualIndex = jjj;
            }
        }

        // gestione wild cards
        if(value == '*' || (value == '' && searcherElement.tagName.toUpperCase() == 'INPUT')) {
            continue;
        }

        // Esegue un ciclo per ogni riga visibile
        for(var zzz = 0; zzz < visibleTr.length; zzz++){
            // Testo contenuto nella colonna relativa all'elemento di ricerca
            var text = $(visibleTr.eq(zzz).find('td').get(actualIndex)).text();
            // La colonna contiene un array stampato a video con una print_ar
            if(zzz != 0 && text.indexOf('Array') > 0 && text.indexOf(' =&gt; ') > 0) {
                var textArray = text.split(' =&gt; ');
                text = '';
                for (var j = 0; j < textArray.length; j++) {
                    if(j > 0){
                        text += textArray[j].substr(0,textArray[j].search(/\s/)) + ' ';
                    }
                }
                if(text.toUpperCase().indexOf(value) < 0 || (value.length == 0 && text.length > 0))
                    visibleTr.eq(zzz).css('display','none');
            // La colonna non contiene testo ma solo immagine guarda nel title
            } else if(zzz != 0 && text.length == 0 && $(visibleTr.eq(zzz).find('td').get(actualIndex)).html().indexOf('<img') == 0){
                if($(visibleTr.eq(zzz).find('td').get(actualIndex)).children('img').get(0).title.toUpperCase().indexOf(value) < 0)
                    visibleTr.eq(zzz).css('display','none');
            // La colonna non contiene testo ma solo input guarda nel value
            } else if(zzz != 0 && text.length == 0 && $(visibleTr.eq(zzz).find('td').get(actualIndex)).html().indexOf('<input') == 0){
                if($(visibleTr.eq(zzz).find('td').get(actualIndex)).children().val().toUpperCase().indexOf(value) < 0)
                    visibleTr.eq(zzz).css('display','none');
            // La colonna contiene testo
            } else if(zzz != 0){
                if(text.toUpperCase().indexOf(value) < 0 || (value.length == 0 && text.length > 0))
                    visibleTr.eq(zzz).css('display','none');
            }
        }
    }
}

// jsfilters
Ep.getProductPage = function(my_this, url, my_data) {
    // Disattiviamo l'area visibile dei prodotti
    var area_id;

    if ($('#ProductArea').html())  {
        area_id = '#ProductArea';
    } else {
        $('#formfilter').submit();
        return false;
    }

    $(area_id).append('<div id="overlay_child" class="overlay"></div><div class="ajaxLoader"></div>');
    $.getJSON(url,my_data,
        function(data) {
            $(area_id).html(data.resp.html);
            // filters = $.parseJSON(data.ext_data);
            filters = data.ext_data;

            // Completata disattivazione
            $('.optionSrch input[type=checkbox]').each( function () {if(this.name.indexOf('filterAll_')<0) this.disabled=true;} );
            $.each(filters, function(key, value) {
                // Resettiamo i filtri colore
                $('#filters_'+key+' input[type=checkbox]').each( function (index) {
                    if (this.name!='filterAll_'+key) {
                        that = this;

                        $.each(value, function(kk, vv) {
                            if (kk == that.value) {
                                that.disabled = false;
                                return false;
                            }

                            return true;
                        });
                    }
                });
            });

            // uncheck box "all""
            $('.filterAll').each( function () {$(this).attr('checked','');} );
        });

     return true;
}

Ep.ready = function() {

    //$('.ep_banner').epBanner('fade',{fadeDuration: 500, showDuration: 1000, height: 433, width: 651});
    // $('#limmobiliarepuntocasa-banner-genpage_home .ep_banner').epBanner('fade',{fadeDuration: 500, showDuration: 1000, height: 300, width: 990});
   // bnr = $('.ep_banner').epBanner({fadeDuration: 500, showDuration: 3000, height: 300, width: 990});

    // console.log(bnr[0]);
    // setTimeout(function() { bnr[1].stop(); },5000);
    // setTimeout(function() { bnr[1].start(); console.log('start'); },10000);
    
    //$('.ep_150_banner').epBanner('fade',{fadeDuration: 500, showDuration: 1000, height: 60, width: 763});
    //$('.ep_banner_left').epBanner('fade',{fadeDuration: 500, showDuration: 1000, height: 166, width: 208});

    //area clienti paypal cassa veloce per far scomparire/apparire i campi a seconda della scelta privato o azienda
    $('#ppfp_customerType').change(function(){
       if($('#ppfp_customerType').val() == 0){
            $('#paypalFstTaxId').css('display', 'block');
            $('#paypalFstVat').css('display', 'none');
       }else{
            $('#paypalFstTaxId').css('display', 'none');
           $('#paypalFstVat').css('display', 'block');
       }
    });

    if($('.borderArea').length>0) {
        var tab = $('<img border="0" src="/images/borderdet.png" style="position:absolute;z-index:99;height:518px;" />');
        var contentWrapper = $('#content_wrapper');
        var position =  contentWrapper.position();
        var contentPosition = $('#menuTitle').position();
        var position2 =  $('.borderArea').position();
        // DBG console.log(contentPosition);
        tab.css('left',position2.left).css('top',contentPosition.top+75);
        $('#pageTitle').append(tab);
        var menuTitle = $('#menuTitle');
        var content = $('#content');
        contentWrapper.css('left',position2.left);
        var numEls = $('#content .detProd').length;
        var width = eval($('#content .detProd').css('width').replace('px','')) * numEls;
        content.css('width',(width+20)+'px');
        if(numEls<4) $('#contentslide').hide();
        width = $(window).width() - menuTitle.outerWidth() - menuTitle.offset().left - 5;
        contentWrapper.css('width',width);
        $(window).resize(function(e) {
            width = $(window).width() - menuTitle.outerWidth() - menuTitle.offset().left - 5;
            contentWrapper.css('width',width);
            position2 =  $('.borderArea').position();
            contentWrapper.css('left',position2.left);
            tab.css('left',position2.left);
        });
        var scrollbar = $('#sliderbox').slider({
            min: 0, //$('#content').position().left,
            max: (content.width() - 775),
            step: 1,
            slide: function(event, ui) {
                content.css('left',-$( this ).slider( "option", "value"));
            },
            change: function(event,ui) {
                 content.css('left',-$( this ).slider( "option", "value"));
            }
        });
        var handleHelper = scrollbar.find('.ui-slider-handle')
            .mousedown(function(){
                    scrollbar.width( handleHelper.width() );
            }).parent();

        $('#prevbutton').live('click',function(e){
            newValue = $( '#sliderbox' ).slider( "option", "value")-20;
            $( '#sliderbox' ).slider( "option", "value", newValue);
        });
        $('#nextbutton').live('click',function(e){
            $( '#sliderbox' ).slider( "option", "value", $( '#sliderbox' ).slider( "option", "value")+20);
        });
    }

    // Editor di date
    $('.datepicker').datepicker({ dateFormat: 'dd-mm-yy'});

    $('.deleter').click(function(e) {
        if(confirm('Cancellare "' + this.title+ '"?') ) {
        } else {
            e.preventDefault();
        }
    });
    $('.confirmer').click(function(e) {
        if(confirm( this.title ) ) {
        } else {
            e.preventDefault();
        }
    });

    $('.form-submit').click(function() {});

    $('.watermarked').each(function() {
        $(this).watermark('watermark', $(this).attr('title'));
    });

    // jslang
    $('#changeCountry').click(function(e){
        e.preventDefault();
     $('#listCountry > ul').slideToggle();
    });

    $('#listCountry').mouseleave(function(){
       $('#listCountry > ul').slideToggle();
    });

    // jsimagesdes
    /* funzione per l'image hover della visualizzazione standard*/
    // 13/08/2010 -- Leonardo in collaborazione con Antonio!
    $('.detPhotoProd a').hover( function () {
        $(this).children('img').toggleClass('clsInvisible');
        $(this).parent().next().children().toggleClass('clsInvisible');
        $(this).children('div').toggleClass('borderProductDet');
    });

    $('.nodetPhotoProd a').hover( function () {
        $(this).parent().next().children().toggleClass('clsInvisible');
    });


    // jsimages
    // funzione per l'image hover della visualizzazione standard
    // 13/08/2010 -- Leonardo in collaborazione con Antonio!
    $('.photoStd a').live('hover', function () {
        $(this).children('img').toggleClass('clsInvisible');
        $(this).parent().next().children().toggleClass('clsInvisible');
        $(this).children('div').toggleClass('borderProduct');
    });
    // funzione per l'image hover della visualizzazione standard nel caso in cui ci sia una sola foto
    // 13/08/2010 -- Leonardo in collaborazione con Antonio!
    $('.nophotoStd a').live('hover', function () {
         $(this).parent().next().children().toggleClass('clsInvisible');
    });



    // Bind del click sul select dell'ordinamento
    $('#sortSelector').live('change', function(e) {
        e.preventDefault();
        Ep.getProductPage(this,$(this).attr('rel')+this.value);
    });
    // Bind del clic dei link del navigatore fra le pagine
    $('.traspLink').live('click',function(e) {
        e.preventDefault();
        Ep.getProductPage(this,this.href)
    });
    // Bind del clic checkbox dei filtri
    // DBG console.log($('.shopBy input[type=checkbox]'));
    $('.optionSrch input[type=checkbox]').click( function(e) {
        form = $(this).parents('form').get(0);

        // Se cliccato su tutti allora vengono sceccati tutti quelli di quel gruppo per disattivarli
        if (this.name.indexOf('filterAll_')>=0) {

            //console.log('ciccato all di '+my_str);
            $('#filters_'+this.name.replace('filterAll_','')+' input[type=checkbox]').each( function (index) {
                this.checked = false;
                this.enable = true;
            });
        }

        Ep.getProductPage(this,form.action,$(form).serialize());

    });
    // filtro per prezzo
    if ($("#slider-filter-price").length>0) {
        $("#slider-filter-price").slider({
            range: true,
            min: 0,
            max: $("#price_to").val(),
            values: [$("#price_from").val(),$("#price_to").val()],
            slide: function(event, ui) {
                $("#label-filter-price").html('da \u20ac ' + Ep.formatCurrency(ui.values[0]) + ' a \u20ac ' + Ep.formatCurrency(ui.values[1]));
                $("#price_from").val(ui.values[0]);
                $("#price_to").val(ui.values[1]);
            },

            stop: function(event, ui) {
                var form = $(this).parents('form').get(0);
                Ep.getProductPage(this,form.action,$(form).serialize());
            }
        });

        $("#label-filter-price").html('da \u20ac ' +  Ep.formatCurrency($("#slider-filter-price").slider('values', 0)) + ' a \u20ac ' + Ep.formatCurrency($("#slider-filter-price").slider('values',1)));
    }

    // jsaccount
    $('#lnkForPwd').click(function(e){
       e.preventDefault();
       $('#tblForPwd').toggle();
    });
    $('#invoicefrmlnk').click(function(e){
       e.preventDefault();
       $('#invoicefrm').css('display', 'block');
       //setto il campo hidden cos� so se ho specificato l'indirizzo di fatturazione
       //(per il controllo errori, altrimenti me li dà sempre
       $('#cbFrmInvoice').get(0).value = '1';
    });
    // @todo
    // Verificare
    $('#copyData').click(function(e){
        e.preventDefault();
        $('#myNameBill').val($('#myName').val());
        $('#myPhoneBill1').val($('#myPhone1').val());
        $('#mySurnameBill').val($('#mySurname').val());
        $('#myPhoneBill2').val($('#myPhone2').val());
        $('#myCOBill').val($('#myCO').val());
        $('#myPhoneBill3').val($('#myPhone3').val());
        $('#myAddressBill').val($('#myAddress').val());
        $('#myIdAddBill').val($('#myIdAdd').val());
        $('#myPostalCodeBill').val($('#myPostalCode').val());
        $('#myTaxCodeBill').val($('#myTaxCode').val());
        $('#myCityBill').val($('#myCity').val());
        $('#myProvBill').val($('#myProv').val());
        $('#myNationBill').val($('#myNation').val());
    });

    // @todo
    // verificare
    $('.service-submenu a').click(function(e){
        e.preventDefault();
        $('.service-submenu a').removeClass('active');
        $(this).addClass('active');
        // tolgo active da tutti i testi
        $('.service-text').removeClass('active');
        // imposto attivo solo il corrente
        $($(this).attr('href')).addClass('active');
    });


    //funzione recupero password
    $('#tblForPwd').submit(function(e) {
        e.preventDefault();
        var uname = $.trim($('#LostPwdUsername').val());
        if (uname=='') return false;

        $('#respPwd').html('');
        var url =  "/" + $('#LostPwdLang').val() +"/user-jsonrecoverypwd/";

        $.getJSON(url,'username='+ uname,
                    function(response){
              
                $('#respPwd').html(response.resp.html);

        });

        return true;
    });

    $('#baseFormLogin').submit(function(e) {
        if ($.trim($('#Username').val())=='' || $.trim($('#Password').val())=='')
            e.preventDefault();
    });


    //esplosione faq servizio clienti
    $('.serviceTitleToggle').click(function(){
        $(this).next().slideToggle('fast');
    });

    // Gestione minicart
    var i_nun_rows = 3;
    $('.minicart_arrows').live('click', function(e) {
        first_visible = $('.minicart_artvisible').get(0);
        // first_invisible = $(first_visible).nextUntil('.minicart_artinvisible').next();
        first_invisible = first_visible;
        for(i=0; i<i_nun_rows;i++) {
            first_invisible = $(first_invisible).next();
        }


        if (this.id=='minicart_arrow_up' && first_visible.id=='minicart_first_art') return false;
        if (this.id==first_invisible.attr('id')) return false;

        if (this.id=='minicart_arrow_down') {
            tohide = first_visible;
            toshow = first_invisible;
            $(toshow).children('.minicart_line_separator').hide();
            $(toshow).prev('div').children('.minicart_line_separator').show();
        } else if (this.id=='minicart_arrow_up') {
            toshow = $(first_visible).prev();
            tohide = $(first_invisible).prev();
            $(toshow).children('.minicart_line_separator').show();
            $(tohide).prev('div').children('.minicart_line_separator').hide();
        }
        $(tohide).slideToggle();
        $(toshow).slideToggle();
        $(tohide).removeClass('minicart_artvisible').addClass('minicart_artinvisible');
        $(toshow).removeClass('minicart_artinvisible').addClass('minicart_artvisible');

        return true;
    });


    // apre la popup con la guida taglie
    $('#lnkPopUp').click(function(e){
       e.preventDefault();
       window.open($('#lnkPopUp').attr('href'), '','width=1000,height=650,scrollbars=yes')
    });

    //@todo
    // verificare
    $('#shareProducts').click(function(e){
       e.preventDefault();
       $('#shareList').show();
    });

    //@todo
    // verificare
    $('#shareClose').click(function(e){
       e.preventDefault();
       $('#shareList').hide();
    });

    // Gestione submit del form di ricerca prodotti
    $('#frmSrch').submit(function(e){
        if ($.trim($(this).find('input[name="srch"]').get(0).value)=='') e.preventDefault();
    });

    // Gestione dei tabs (amministrazione)
    $('.tabs').tabs();
    $('.sortable').sortable({placeholder: "ui-state-highlight"});
    $('.sortable').disableSelection();

    // Laura - 2011-03-25 funzione per il refresh del captcha
    $('#cpt').click(function(e){
        e.preventDefault();
        nd = new Date();
        t = $('#imgCpt').attr('src') + "&" + nd.getTime();
        $('#imgCpt').attr('src', t);
        $('#captcha').val('');
    });

    //focus se entri nelle pagine di admin o in user-account
    $('.inputFocus').focus();


    $('.btnOnPrint').click(function(e) {window.print();});

    // ??
    $('select.table-filter').change(Ep.search);
    $('input.table-filter[type="text"]').keyup(Ep.search);

    // fancybox con informazioni sul prodotto
    if ($('.showProdInfo').length>0) {
        $('.showProdInfo').fancybox({
            width: '60%',
            height: '60%',
            autoDimensions: false,
            transitionIn: 'elastic',
            transitionOut: 'elastic',
            speedIn: 500,
            scrolling: 'auto',
            easingIn: 'swing',
            padding: 20,
            margin: 50
        });

        $('#showProdInfo').click(function(e) {e.preventDefault();});
    }

    // fancybox per richiesta contatto
    if ($('#quoteRequest').length>0) {

        $('#quoteRequest').fancybox({
            width: 750,
            height: 550,
            autoDimensions: false,
            transitionIn: 'elastic',
            transitionOut: 'elastic',
            speedIn: 500,
            scrolling: 'auto',
            easingIn: 'swing'
        });

        $('#quoteRequest').click(function(e) {e.preventDefault();});

        $('.prevBtnLink').click(function (e) {
            $('#quoteRequest').trigger('click');
            e.preventDefault();
            return false;
        });
    }

    //carosello immagini nella scheda prodotto
    $('#mycarousel').jcarousel({
        wrap: 'circular',
        vertical: false,
        scroll: 1,
        itemVisibleOutCallback: {
            onAfterAnimation: function(carousel, item, i, state, evt) {
                switch (state) {
                    case 'next':
                        delPos = carousel.last - carousel.size();
                        break;
                    case 'prev':
                        delPos = carousel.first + carousel.size();
                }
                if (carousel.get(delPos).length == 1) {
                    carousel.remove(delPos);
                    switch (state) {
                        case 'next':
                            carousel.first--;
                            carousel.last--;
                            break;
                        case 'prev':
                            carousel.first++;
                            carousel.last++;
                    }
                }
                // resequence the indexes
                var $container = carousel.container;
                var newIndex = 0;
                var currentIndex;
                $container.find('li').each(function() {
                    newIndex++;
                    $li = $(this);
                    currentIndex = $li.attr('jcarouselindex');
                    $li.removeClass('jcarousel-item-'+currentIndex);
                    $li.removeClass('jcarousel-item-'+currentIndex+'-vertical');

                    $li.attr('jcarouselindex', newIndex);
                    $li.addClass('jcarousel-item-'+newIndex);
                    $li.addClass('jcarousel-item-'+newIndex+'-vertical');
                });
            }
        }
    });

    //trasferito in immobile.js
    //$('#mycarousel li img').click(function( event ) {
    //    if($('#mycarousel > li').length > 3){
    //        $('#mycarousel').jcarousel('next');
    //    }
   //     that = this;
        //se clicco sull'immagine, sostituisco la grande con quella su cui ho cliccato.

   //      $('.imgBig img').attr('src', that.src.replace('&w=214&h=160', '&w=650&h=487').replace('&w=130&h=97', '&w=400&h=300'));


       // sostituisco anche la large image (Laura 09-09-2010)
   //     $('.largePhoto').attr('rel', Ep.urlEncode($(that).attr('rel')));
   // });

    // ************************************** CARRELLO E DETTAGLIO PRODOTTI ************************************** //

    // verifica che nel campo quantity vengano inserito soltanto valori numerici
    $('#addCartForm input[name="quantity"]').keypress(function(e) {
        if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57) ) {
            return false;
        }
        return true;
    })

    // elemento per modificare le quantità da inserire nel carrello da dettaglio prodotto (aggiunta)
    $('.cart-add-quantity-prod').click(function(e) {
        e.preventDefault();
        var $el = $(this).parents('form').find('input[name="quantity"]');
        // if(eval($(this).parent().find('input[name="purchase_max_qty"]').get(0).value)>eval($el.get(0).value)) {
            $el.attr('value',eval($el.attr('value'))+1);
        //}

    });

    // elemento per modificare le quantità da inserire nel carrello da dettaglio prodotto (sottrazione)
    $('.cart-sub-quantity-prod').click(function(e) {
        e.preventDefault();
        var $el = $(this).parents('form').find('input[name="quantity"]');
        if(eval($el.attr('value'))>1/* && eval($(this).parent().find('input[name="purchase_min_qty"]').get(0).value)<eval($el.get(0).value)*/) {
            $el.attr('value',eval($el.attr('value'))-1);
        }
    });

    // funzioni per spostare gli elementi dal carrello alla wishlist e viceversa
    $('.cartAdd').click(function(e) {
        e.preventDefault();
        $('#addCartForm').submit();
        $(this).next('.cart-add-form').submit();
    });

    // Submit form aggiungi al carello dalla pagina dei dettaglio
    $('.addCartForm').submit(function(e) {
        $('#product_error_log').html('');
        // Se presente il form per la fast registration
        if ($('#fast_registration').length>0) {
            $('#fast_registration').fancybox({
                onClosed: function(){
                    // console.log('main close');
                    $.ajax({
                        type: 'post',
                        url: '/user-disableFastRegistration' // la lingua non e' importante
                    });
                    $('#disable_fast_registration_form').attr('value',1);
                    $('#'+$('#pre_fast_registration_form').val()).submit();
                },
                //'autoDimensions': false,
                width: 660,
                height: 450

            });

            $('#pre_fast_registration_form').attr('value',this.id);
            if($('#disable_fast_registration_form').val()!='1') {
                $('#fast_registration').trigger('click');
                e.preventDefault();
                return false;
            }
        }

        // rimuovo tutti le eventuali finestre di errore
        $('.errorRequiredOption').each(function() {$(this).remove();});
        var $that = $(this);
        // e.preventDefault();
        var elsNames = [];
        var els = $(this).find('.required');

        // recupera i nome dei campi
        $(els).each(function(index) {
            found = false;
            // Va aggiunto anche il nome del form altrimenti potrei avere una stessa proprieta' con lo stesso nome e dello stesso formato
            // anche in altri form ed in quel caso prenderebbe la prima
            var filtername = '#'+$that.attr('id')+' '+this.nodeName.toLowerCase()+'[name="'+this.name+'"]';

            for(i=0;i<elsNames.length;i++) {
                if(elsNames[i]==filtername) found = true;
            }
            if(!found)
                elsNames.push(filtername);
        });

        stop = false;
        for(i=0;i<elsNames.length && !stop;i++) {

            switch($(elsNames[i]).get(0).nodeName) {
                case 'SELECT':
                    if($(elsNames[i]).get(0).value=='') {
                       position = $(elsNames[i]).prev().position();
                       $that
                            .append('<div class="errorRequiredOption" onclick="javascript:$(this).remove();" style="left:'+(position.left)+'px;top:'+(position.top)+'px;">'+$(elsNames[i]).prev().html()+' '+$('#errorMsgReqOpt').html()+'</div>');
                        stop = true;
                    }
                    break;
                case 'INPUT':
                    count = 0;
                    $(elsNames[i]).each(function(j) {
                       if(this.checked) count++;
                    });
                    if(count==0) {
                        position = $(elsNames[i]).parent().prev().position();

                        $that
                             .append('<div class="errorRequiredOption" onclick="javascript:$(this).remove();" style="left:'+(position.left)+'px;top:'+(position.top)+'px;" >'+$(elsNames[i]).parent().prev().html()+' '+$('#errorMsgReqOpt').html()+'</div>');
                        stop = true;
                    }
            }
        }

        if(!stop) {
            // Postiamo i dati via ajax
            e.preventDefault();
            $that = $(this);
            $.ajax({
                type: 'post',
                url: $that.attr('action'),
                data: $that.serialize(),
                success: function (data) {
                    var jdata = $.parseJSON(data);

                    if(jdata) {
                        if(jdata.status==0) {
                            $('#product_error_log').html(jdata.msg);
                            return false;
                        }
                    }

                    $('#resumeCartData').children().html(jdata.ext_data.cart_resume);

                    $.fancybox({
                        width: '450',
                        height: '120',
                        autoDimensions: false,
                        transitionIn: 'elastic',
                        transitionOut: 'elastic',
                        speedIn: 500,
                        scrolling: 'auto',
                        easingIn: 'swing',
                        padding: 20,
                        margin: 50,
                        content: jdata.ext_data.msg
                    });
                    return true;
                }
            });
            // this.submit();

        } else
            e.preventDefault();
    });

    $(this).find('.shopTblHead input[type=radio]').css('visibility','hidden');

    // ************************************ FINE CARRELLO E DETTAGLIO PRODOTTI ************************************ //


    
      




}

// jstip
$(document).ready(Ep.ready);


