// Funzioni VARIE
// funzioni per l'urlencoding
urlEncodeCharacter = function(c)
{
    return '%' + c.charCodeAt(0).toString(16);
};
urlDecodeCharacter = function(str, c)
{
    return String.fromCharCode(parseInt(c, 16));
};
urlEncode = function( s )
{
    return encodeURIComponent( s ).replace( /\%20/g, '+' )
                                  .replace( /[!'()*~]/g, urlEncodeCharacter );
};
urlDecode = function( s )
{
    return decodeURIComponent(s.replace( /\+/g, '%20' ))
                .replace( /\%([0-9a-f]{2})/g, urlDecodeCharacter);
};

// funzione per il watermark
$.fn.watermark = function(css, text) {
    return this.each(function() {
            var i = $(this), w;
            i.focus(function() {
                    w && !(w=0) && i.removeClass(css).data('w',0).val('');
            })
            .blur(function() {
                    !i.val() && (w=1) && i.addClass(css).data('w',1).val(text);
            })
            .closest('form').submit(function() {
                    w && i.val('');
            });
            i.blur();
    });
};

function formatCurrency(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);
}

var search = function(e) {
    var searcherElement = this;
    var value = searcherElement.value.toUpperCase();
    var th = $(this).parents('th').get(0);
    var $table = $(this).parents('table');
    // cerca l'indice
    actualIndex = false;
    $(this).parents('tr').find('th').each(function(i) {
        if(this == th) {
            actualIndex = i;
            return;
        }
    });

    // gestione wild cards
    if(value=='*') { $table.find('tr').css('display',''); return false; }
    // alert($($('.document')[0]).text());
    $table.find('tr').each(function(i) {
        var text = $($(this).find('td').get(actualIndex)).html();
        if(i!=0) {
            if(text.toUpperCase().indexOf(value)<0)
                $(this).css('display','none');
            else
                $(this).css('display','');
        }
    });
    if(value=='') $table.find('tr').css('display','');
}

// @todo
// Verificare se queste servono
$(document).ready(function() {

    $('.datepicker').datepicker($.datepicker.regional['it']);

    $('.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'));
    });
});

// jstip
(function ($) {
    $(document).ready(function() {
        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);
            });
        }


        // 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');
        });

        // jsfilters
        function getProductPage(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;
        }

       // Bind del click sul select dell'ordinamento
        $('#sortSelector').live('change', function(e) {
            e.preventDefault();
            getProductPage(this,$('#sortSelectorUrl').attr('href')+this.value);
        });
        // Bind del clic dei link del navigatore fra le pagine
        $('.traspLink').live('click',function(e) {
            e.preventDefault();
            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;
                });
            }

            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 ' + formatCurrency(ui.values[0]) + ' a \u20ac ' + 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);
                    getProductPage(this,form.action,$(form).serialize());
                }
            });

            $("#label-filter-price").html('da \u20ac ' +  formatCurrency($("#slider-filter-price").slider('values', 0)) + ' a \u20ac ' + 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){
                    //var r = $.parseJSON(response.resp);
                    $('#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(search);
        $('input.table-filter[type="text"]').keyup(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.quoteRequest').click(function (e) {
                $('#quoteRequest').trigger('click');
                e.preventDefault();
                return false;            
            });
        }
        if($('#sampleRequest').length>0) {
            $('#sampleRequest').fancybox({
                width: 750,
                height: 550,
                autoDimensions: false,
                transitionIn: 'elastic',
                transitionOut: 'elastic',
                speedIn: 500,
                scrolling: 'auto',
                easingIn: 'swing'
            });
            $('.prevBtnLink.sampleRequest').click(function (e) {
                $('#sampleRequest').trigger('click');
                e.preventDefault();
                return false;            
            });
        }
    });

    var methods = {
        init: function(options) {
            // DBG console.log('methods.init()');
        },
        destroy: function() {
            // DBG console.log('methods.destroy()');
        },
        fade: function(options) {
            var settings = {
                fadeDuration: 1000,
                showDuration: 3000
            };
            if(options) $.extend(settings,options);

            this.css({'overflow':'hidden', 'position':'relative'});
            this.children().css({'overflow':'hidden', 'position':'absolute', 'top':0, 'left':0, 'display':'none'});
            this.children('.selected').css('display','block');

            if(settings.height) {
                this.css('height',settings.height)
                    .children().css('height',settings.height);
            }
            if(settings.width) {
                this.css('width',settings.width)
                    .children().css('width',settings.width);
            }

            


            return this.each(function(){
                var $this = $(this);
                var fadeInTimeout, fadeOutTimeout;

                if($this.children().length<2) return $this;

                $this.unbind('.epBanner');
                $this.bind('mouseenter.epBanner',function(mee) {
                    clearTimeout(fadeInTimeout);
                    clearTimeout(fadeOutTimeout);
                    $(this).addClass('paused');
                    $(this).children().css('display','none').css('opacity','1');
                    $(this).children('.selected').css('display','block').css('opacity','1');
                    $(this).children().stop();
                    // showBanner(this);
                    // hideBanner(this);

                });
                $this.bind('mouseleave.epBanner',function(mle) {
                    $(this).removeClass('paused');
                    $this.epBanner('fade',options);
                    // DBG hideBanner(this);
                });

                var el = $this.find('.selected').next();
                if(el.length<1) {
                    el = $this.children().eq(0);
                }
                var showDuration = settings.showDuration;
                var classes = $this.find('.selected').attr('class').split(/\s+/);
                $.each(classes,function(index,item) {
                    if(item.match(/^transtime_[0-9]+$/)) {
                        // DBG console.log(item.split(/_/)[1]);
                        showDuration = eval(item.split(/_/)[1])*1000;
                    }
                });


                fadeInTimeout = setTimeout(function() {
                    $this.find('.selected').eq(0).fadeOut(settings.fadeDuration,function() {

                        $(this).toggleClass('selected');
                        // if(!$(bnr).hasClass('paused')) showBanner(bnr);
                    });
                },showDuration);
                fadeOutTimeout = setTimeout(function() {
                    el.fadeIn(settings.fadeDuration,function() {
                        $(this).toggleClass('selected');
                        if(!$(this).hasClass('paused'))
                            $this.epBanner("fade",options);
                        // if(!$(bnr).hasClass('paused')) hideBanner(bnr);
                    });
                },showDuration);
            });
        }
    }

    jQuery.fn.epBanner = function( method ) {
        if ( methods[method] ) {
            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.epBanner' );
        }
    };

    $(document).ready(function() {
        $('.ep_banner').epBanner('fade',{fadeDuration: 500, showDuration: 1000, height: 300, width: 763});
        $('.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
    $(document).ready(function() {
       $('#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');
           }
       })
       

    });
})(jQuery);
