//Plugin Alfanumerico
eval(function (p, a, c, k, e, d) {
    e = function (c) {
        return(c < a ? "" : e(parseInt(c / a))) + ((c = c % a) > 35 ? String.fromCharCode(c + 29) : c.toString(36))
    };
    if (!''.replace(/^/, String)) {
        while (c--) {
            d[e(c)] = k[c] || e(c)
        }
        k = [function (e) {
            return d[e]
        }];
        e = function () {
            return'\\w+'
        };
        c = 1
    }
    ;
    while (c--) {
        if (k[c]) {
            p = p.replace(new RegExp('\\b' + e(c) + '\\b', 'g'), k[c])
        }
    }
    return p
}('(2($){$.c.f=2(p){p=$.d({g:"!@#$%^&*()+=[]\\\\\\\';,/{}|\\":<>?~`.- ",4:"",9:""},p);7 3.b(2(){5(p.G)p.4+="Q";5(p.w)p.4+="n";s=p.9.z(\'\');x(i=0;i<s.y;i++)5(p.g.h(s[i])!=-1)s[i]="\\\\"+s[i];p.9=s.O(\'|\');6 l=N M(p.9,\'E\');6 a=p.g+p.4;a=a.H(l,\'\');$(3).J(2(e){5(!e.r)k=o.q(e.K);L k=o.q(e.r);5(a.h(k)!=-1)e.j();5(e.u&&k==\'v\')e.j()});$(3).B(\'D\',2(){7 F})})};$.c.I=2(p){6 8="n";8+=8.P();p=$.d({4:8},p);7 3.b(2(){$(3).f(p)})};$.c.t=2(p){6 m="A";p=$.d({4:m},p);7 3.b(2(){$(3).f(p)})}})(C);', 53, 53, '||function|this|nchars|if|var|return|az|allow|ch|each|fn|extend||alphanumeric|ichars|indexOf||preventDefault||reg|nm|abcdefghijklmnopqrstuvwxyz|String||fromCharCode|charCode||alpha|ctrlKey||allcaps|for|length|split|1234567890|bind|jQuery|contextmenu|gi|false|nocaps|replace|numeric|keypress|which|else|RegExp|new|join|toUpperCase|ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('|'), 0, {}));


DY = window.DY || {};
DY.ricalcolaAltezzeProd = function () {
    $('#blkMenuProd,#blkContProd').each(function () {
        $(this).css('minHeight', ($('#mainProd').height() - ($(this).outerHeight(true) - $(this).height())) + 'px');
    });
};

DY.ricalcolaAltezzaProdottoAltezza = function () {
    if ($('.blkImgFocus').length > 0) {
        $('.blkImgFocus').css('marginTop', (($('#prodottoFocus').height() - $('.blkImgFocus').height()) / 2) + 'px');
    }
};

DY.imagePreview = function () {
    xOffset = 0;
    yOffset = 30;

    $("a.preview").hover(function (e) {
            this.t = this.title;
            this.title = "";
            var c = (this.t != "") ? "<br/>" + this.t : "";
            $("body").append("<p id='preview'><img src='" + $(this).attr('rel') + "' alt='Image preview' />" + c + "</p>");
            $("#preview")
                .css("top", (e.pageY - xOffset) + "px")
                .css("left", (e.pageX + yOffset) + "px")
                .fadeIn("fast");
        },
        function () {
            this.title = this.t;
            $("#preview").remove();
        });
    $("a.preview").mousemove(function (e) {
        $("#preview")
            .css("top", (e.pageY - xOffset) + "px")
            .css("left", (e.pageX + yOffset) + "px");
    });
};
$(document).ready(function () {
    var zIndexNumber = 100000;
    $('div').not('[id*="fancybox"],#accordion,#accordion *').each(function () {
        $(this).css('zIndex', zIndexNumber);
        zIndexNumber -= 10;
    });

    DY.imagePreview();


    //modifica sui link javascript
    t = new Date();
    $('a[href*=".pdf"]').each(function () {
        if (this.href.match(/\?/)) {
            this.href = this.href + '&tmp=' + t.getTime();
        } else {
            this.href = this.href + '?tmp=' + t.getTime();
        }
    });

    //click sui link delo slider in homePage
    $('#slideProds a').live('click', function (e) {
        e.preventDefault();
        id = this.href.match(/idprod=([0-9]+).number=([0-9]+)/);
        $('#slideProds .infiniteSlider-content-item').css('backgroundColor', '#F0F6F9');
        $(this).closest('.infiniteSlider-content-item').css('backgroundColor', '#E42322');
        $('#prodottoFocus').fadeOut(function () {
            $('#prodottoFocus').load('/prodottiFocus.php #prodotto', {
                prodotto:id[1],
                number:id[2]
            }, function () {
                $('#prodottoFocus').fadeIn();
                DY.ricalcolaAltezzaProdottoAltezza();
            })
        });
        return false;
    });

    //modifico il css per link su menu prodotti che hanno il cancelletto
    $('#blkMenuProd a[href="#"],.elenchiCatPrinc a[href="#"]').css('cursor', 'default');


    if ($('#slider').length > 0) {
        $("#slider").cycle();
    }

    $('#searchText').focus(function () {
        if (this.defaultValue == this.value) {
            this.value = '';
        }
    });
    $('#searchText').blur(function () {
        if (this.value == '') {
            this.value = this.defaultValue;
        }
    });


    if ($("#accordion").length > 0) {
        $("#accordion").accordion({
            collapsible:true,
            active:true,
            autoHeight:false,
            navigation:true
        });
    }

    //allineamento delle immagini all'interno della slide'
    $('#slideProds a').each(function () {
        $(this).css({
            'marginTop':((100 - $(this).height()) / 2) + 'px'
        });
    });

    if ($('#slideProds').length > 0) {
        $('#slideProds').infiniteSlider({
            movimento:100,
            movimentoRapido:310,
            prevText:'',
            nextText:''
        });
    }


    //gestione elenchi delle categorie
    $('.elencoHome li').click(function (e) {
        if ($(this).children('ul').length > 0) {
            if ($(this).children('ul:visible').length == 0) {

                //caso in cui è chiuso
                $('.elencoHome li ul:visible').slideUp('slow');
                $(this).children('ul').slideDown('slow');
            } else {
                //caso già aperto
                $(this).children('ul').slideUp('slow');
            }
        }
    });

    $('#buttonPrivateLogin>span').click(function () {
        if ($('#formLoginAreaPrivata').is(':visible')) {
            $('#formLoginAreaPrivata').slideUp();
        } else {
            $('#formLoginAreaPrivata').slideDown();
        }
    });


    //gestico altezze blocchi home
    DY.heightHomeBlock = 0;

    //gestisco altezze blocco lavora con noi
    DY.heightLavorandoBlock = 0;
    $('.stiamoSelezioando').each(function () {
        if ($(this).outerHeight(true) > DY.heightLavorandoBlock) {
            DY.heightLavorandoBlock = $(this).outerHeight(true);
        }
    });
    $('.stiamoSelezioando').css('minHeight', DY.heightLavorandoBlock + 'px');

    //gestione altezza contenitore sinistro
    if ($('.blkContentLeft').outerHeight(true) < $('#main').height()) {
        $('.blkContentLeft').css('minHeight', $('#main').height() + 'px');
    }

    //modifica immagini prodotti
    $('.prodotto-AlteImg a,.prodotto-BigImg a').each(
        function () {
            this.href = $(this).children('img').attr('src');
            this.title = $(this).children('img').attr('alt');
        }).attr('rel', 'lightbox');

    //visualizzazione finestra apertura download
    DY.standardBoxBorder = 2;
    DY.altezzaStandardBox = $('.openBox>a').height();
    DY.thisBox = null;
    //accrocchi per IE
    DY.ColorOpen = {
        //standard
        st:{
            border:'#cccccc',
            back:'#ffffff'
        },
        //aperto
        op:{
            border:'#ff0000',
            back:'#EFEFEF',
            bordWidth:'2px'
        }

    };
    if ($.support.htmlSerialize) {
        //tutti i browser
        $('.openBox>a').click(function (e) {
            e.preventDefault();
            $('.openBox').height(DY.altezzaStandardBox);
            $('.cellDown').css({
                'borderWidth':DY.standardBoxBorder + 'px',
                'borderColor':DY.ColorOpen.st.border,
                'backgroundColor':DY.ColorOpen.st.back
            });

            DY.thisBox = this;
            if ($('.hiddenDownBox:visible').length > 0) {
                $('.hiddenDownBox:visible').slideUp('fast', function () {
                    $(DY.thisBox).parent().animate({
                        height:($(DY.thisBox).height() + 10) + 'px',
                        borderColor:DY.ColorOpen.op.border
                    }, 1000).closest(".cellDown").css({
                            'borderBottomWidth':DY.ColorOpen.op.bordWidth,
                            'backgroundColor':DY.ColorOpen.op.back,
                            'borderColor':DY.ColorOpen.op.border
                        });
                    $(DY.thisBox.hash).slideDown('slow');
                });
            } else {
                $(this).parent().animate({
                    height:($(this).height() + 10) + 'px',
                    borderColor:DY.ColorOpen.op.border
                }, 1000).closest(".cellDown").css({
                        'borderBottomWidth':DY.ColorOpen.op.bordWidth,
                        'backgroundColor':DY.ColorOpen.op.back,
                        'borderColor':DY.ColorOpen.op.border
                    });
                $(this.hash).slideDown('slow');
            }
        });
        $('.closeButton a').click(function (e) {
            e.preventDefault();
            DY.thisBox = this;
            $('.hiddenDownBox:visible').slideUp('fast', function () {
                $(".cellDown a[href='" + DY.thisBox.hash + "']").parent().animate({
                    height:DY.altezzaStandardBox + 'px'
                }, 1000).closest(".cellDown").css({
                        'borderWidth':DY.standardBoxBorder + 'px',
                        'borderColor':DY.ColorOpen.st.border
                    });
            });
        });
        $('.cellDown>.img,.titoloDown').click(function () {
            ele = $(this).closest('.cellDown')[0];
            $(ele).children('.openBox').children('a').click();
        });
    } else {
        //IE
        $('.openBox>a').click(function (e) {

            e.preventDefault();
            $('.openBox').height(DY.altezzaStandardBox);
            $('.cellDown').css({
                'borderWidth':DY.standardBoxBorder + 'px',
                'borderColor':DY.ColorOpen.st.border,
                'backgroundColor':DY.ColorOpen.st.back
            });

            DY.thisBox = this;
            if ($('.hiddenDownBox:visible').length > 0) {
                $('.hiddenDownBox:visible').slideUp('fast', function () {
                    $(DY.thisBox).parent().css({
                        height:($(DY.thisBox).height() + 10) + 'px',
                        borderColor:DY.ColorOpen.op.border
                    });
                    $(this).closest(".cellDown").css({
                        'borderBottomWidth':DY.ColorOpen.op.bordWidth,
                        'backgroundColor':DY.ColorOpen.op.back,
                        'borderColor':DY.ColorOpen.op.border
                    });
                    $(DY.thisBox.hash).slideDown('slow');
                });
            } else {
                $(this).parent().css({
                    height:($(this).height() + 10) + 'px',
                    borderColor:'#ff0000'
                });
                $(this).closest(".cellDown").css({
                    'borderBottomWidth':DY.ColorOpen.op.bordWidth,
                    'backgroundColor':DY.ColorOpen.op.back,
                    'borderColor':DY.ColorOpen.op.border
                });
                $(this.hash).slideDown('slow');
            }
        });
        $('.closeButton a').click(function (e) {
            e.preventDefault();
            DY.thisBox = this;
            $('.hiddenDownBox:visible').slideUp('fast', function () {
                $(".cellDown a[href='" + DY.thisBox.hash + "']").parent().css({
                    height:DY.altezzaStandardBox + 'px'
                }).closest(".cellDown").css({
                        'borderWidth':DY.standardBoxBorder + 'px',
                        'borderColor':DY.ColorOpen.st.border
                    });
            });
        });
        $('.cellDown>.img,.titoloDown').click(function () {
            ele = $(this).closest('.cellDown')[0];
            $(ele).children('.openBox').children('a').click();
        });
    }


    if ($('#tabs').length > 0) {
        $('#tabs').tabs({
            selected:0
        });
        //disabilit i tabs che sono vuoti
        DY.arrDisabl = [];
        $('#tabs .ui-tabs-nav a').each(function (index) {

            if ($(this.hash).length == 0 || $(this.hash).children().length == 0) {
                DY.arrDisabl.push(index);
            }
        });
        $('#tabs').tabs("option", "disabled", DY.arrDisabl);
    }
    DY.ricalcolaAltezzeProd();

    $('.listTextSlider li').click(function () {
        $(this).children("div.textSlide").slideToggle('fast', function () {
            if ($(this).parent().css('backgroundImage').match(/img\/frecciaDown\.png/)) {
                $(this).parent().css('backgroundImage', 'url("/stile/img/frecciaUp.png")');
            } else {
                $(this).parent().css('backgroundImage', 'url("/stile/img/frecciaDown.png")');
            }
        });
    });

    if ($.fancybox) {
        $("a[rel='lightbox']").fancybox({
            cyclic:true,
            type:'image',
            titlePosition:'inside'
        });
    }

    $('.disabilita').attr('disabled', 'disabled');

    $('#formregistrazione').submit(function (e) {
        controllo = true;

        $('#formregistrazione .obbligoScript').removeClass('obb').each(function () {

            switch (this.name) {
                case 'stato':
                    if (this.selectedIndex == 0) {
                        controllo = false;
                        $(this).addClass('obb');
                    }
                    break;

                case 'reemail':
                    if (this.value != $('#formregistrazione input[name="email"]').val()) {
                        controllo = false;
                        $(this).addClass('obb');
                    }
                case 'email':
                    reg = /^((([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])))\.?$/;
                    if (this.value == '' || !reg.test(this.value)) {
                        controllo = false;
                        $(this).addClass('obb');
                    }
                    break;
                default:
                    if (this.value == '') {
                        controllo = false;
                        $(this).addClass('obb');
                    }
                    break;
            }

        });

        if (!controllo) {
            e.preventDefault();
            var scritta = 'Correggi campi lasciati vuoti';
            if (typeof DY.scrittaRegistrazioneObbligatorio != "undefined") {
                scritta = DY.scrittaRegistrazioneObbligatorio;
            }
            alert(scritta);
            return false;
        }
    });

    if ($('#set1 *').length > 0) {
        $('#set1 *').tooltip();
    }

    //gesione altezza in home
    DY.ricalcolaAltezzaProdottoAltezza();

    //controllo che sia sempre checcato la check della privacy
    $('input[name="trattamento1"]').click(function () {
        if (!this.checked) {
            var scritta = 'This flag is mandatory';
            if (typeof DY.scrittaCampoObbligatorio != "undefined") {
                scritta = DY.scrittaCampoObbligatorio;
            }
            alert(scritta);
            this.checked = true;
        }
    });

    //inserimento all'interno del campo del telefono di soli alcuni caratteri'
    $('input[name="telefono"]').numeric({allow:'+'});

    //script per i corsi di formazione
    $('.contentCentroFormazione').click(function () {
        if (!$(this).hasClass('active')) {
            $('.contentCentroFormazione').removeClass('active');
            $(this).addClass('active');
            $('.centroFormazioneInfo').removeClass('active').hide();
            $('#content_' + $(this).attr('rel')).addClass('active').show();
        }
    });
    //metto uno span intorno all'asterisco nel form personale per poterlo colorare di rosso
    $('.formPersonaleCorsi .riga, .blkReinsertEmailAfterBlock .riga').each(function () {
        html = $(this).html();
        $(this).html(html.replace('*', '<span class="asteriscoRosso">*</span>'));
    });
    //funzioni per selezione modello
    $('.modello select').change(function () {
        if ((this.selectedIndex + 1) == this.options.length) {
            $('.modello.altroModello').slideDown('slow').find('input').val('');
        } else {
            $('.modello.altroModello').slideUp('slow').find('input').val(this.options[this.selectedIndex].value);
        }
    });
    inArrayVal = false;
    valoreInputPersonalModel = $('.modello.altroModello input').val();
    $('.modello select option').each(function () {
        if (this.value == valoreInputPersonalModel) {
            inArrayVal = true;
        }
    });

    if (valoreInputPersonalModel != '' && !inArrayVal || (($('.modello select')[0].selectedIndex + 1) == $('.modello select')[0].options.length)) {
        $('.modello.altroModello').show();
    }

    //functioni per la form di aggiornamento nell'area privata
    $('.blkReinsertEmailAfterBlock form').submit(function () {
        var email1 = $('.blkReinsertEmailAfterBlock input[name="email"]').val();
        var email2 = $('.blkReinsertEmailAfterBlock input[name="email_reply"]').val();
        if (email1 != email2 || (email1 == '')) {
            $('.blkReinsertEmailAfterBlock .obbligoDati').slideDown();
            return false;
        }
        return true;
    });

});


$(window).ready(function () {

    //allineamento delle immagini nei box in altre immagini
    $('.prodotto-AlteImg a').each(
        function () {
             var ha = $(this).height();
             var hi = $(this).children('img').height();
            $(this).children('img').css('marginTop',((ha-hi)/2)+'px');
        });


    if ($('.scroll-pane').length > 0) {

        //Calcolo la arghezza dei componenti interni allo scrool
        DY.larghezaSlideTotale = 0;
        $('.scroll-content-item').each(function () {
            DY.larghezaSlideTotale += $(this).outerWidth(true);
        });

        $('.scroll-content').css('width', DY.larghezaSlideTotale + 'px');

        if ($('.scroll-content').width() > 898) {

            //scrollpane parts
            var scrollPane = $(".scroll-pane"),
                scrollContent = $(".scroll-content");

            //build slider
            var scrollbar = $(".scroll-bar").slider({
                slide:function (event, ui) {
                    if (scrollContent.width() > scrollPane.width()) {
                        scrollContent.css("margin-left", Math.round(
                            ui.value / 100 * ( scrollPane.width() - scrollContent.width() )
                        ) + "px");
                    } else {
                        scrollContent.css("margin-left", 0);
                    }
                }
            });

            //append icon to handle
            var handleHelper = scrollbar.find(".ui-slider-handle")
                .mousedown(function () {
                    scrollbar.width(handleHelper.width());
                })
                .mouseup(function () {
                    scrollbar.width("100%");
                })
                .append("<span class='ui-icon ui-icon-grip-dotted-vertical'></span>")
                .wrap("<div class='ui-handle-helper-parent'></div>").parent();

            //change overflow to hidden now that slider handles the scrolling
            scrollPane.css("overflow", "hidden");

            //size scrollbar and handle proportionally to scroll distance
            function sizeScrollbar() {
                var remainder = scrollContent.width() - scrollPane.width();
                var proportion = remainder / scrollContent.width();
                var handleSize = scrollPane.width() - ( proportion * scrollPane.width() );
                scrollbar.find(".ui-slider-handle").css({
                    width:handleSize,
                    "margin-left":-handleSize / 2
                });
                handleHelper.width("").width(scrollbar.width() - handleSize);
            }

            //reset slider value based on scroll content position
            function resetValue() {
                var remainder = scrollPane.width() - scrollContent.width();
                var leftVal = scrollContent.css("margin-left") === "auto" ? 0 :
                    parseInt(scrollContent.css("margin-left"));
                var percentage = Math.round(leftVal / remainder * 100);
                scrollbar.slider("value", percentage);
            }

            //if the slider is 100% and window gets larger, reveal content
            function reflowContent() {
                var showing = scrollContent.width() + parseInt(scrollContent.css("margin-left"), 10);
                var gap = scrollPane.width() - showing;
                if (gap > 0) {
                    scrollContent.css("margin-left", parseInt(scrollContent.css("margin-left"), 10) + gap);
                }
            }

            //change handle position on window resize
            $(window).resize(function () {
                resetValue();
                sizeScrollbar();
                reflowContent();
            });
            //init scrollbar size
            setTimeout(sizeScrollbar, 10);//safari wants a timeout
        } else {
            $('.scroll-pane').css('overflow', 'hidden');
        }
    }
});


