/**
 * JWPlayer
 */
jw_player="/common/html/js/jwplayer/player.swf";
jw_skin="/common/html/js/jwplayer/skin/glow/glow.xml";
/**
 * Dialog
 */
dialog_show = null;
dialog_hide = null;
if (!($.browser.msie)) {
    dialog_show = "drop";
    dialog_hide = "drop";
}
/**
 * General Functions
 */
Array.max = function( array ){
    return Math.max.apply( Math, array );
};
Array.min = function( array ){
    return Math.min.apply( Math, array );
};
/**
 * init Functions
 */
function init(){

    //-----> PlayIcon
    $(window).bind("load", function(){
        addPlyaIcon();
    });
    //-----> Border Radius
    $("#menu-left ul:first").children("li").children("a").prepend('<span class="tr"></span><span class="br"></span>');
    //-----> Accordion MENU SX
    // Add open Class for level 1
    $("#menu-left ul.sub-l1").each(function(){
        //add opensub class if href != #
        if( $(this).parent().find("a:first").attr("href") == "#" ){
            $(this).parent().find("a:first").addClass("opensub-l1");
        }else{
            //if header is not active -> hide menu
            if($(this).parent().find("a:first").hasClass('on')==false){
                $(this).hide();
            }else{
                $(this).parent().find("a:first").addClass('fix-on');
            }
        }
    });
    $('#menu-left ul.sub').accordion({
        active: '.on',
        header: '.opensub-l1',
        navigation: false,
        event: 'click',
        autoHeight: false,
        collapsible: true
    });
    // Add open Class for level 2
    $("#menu-left ul.sub-l2").each(function(){
        //add opensub class if href != #
        if( $(this).parent().find("a:first").attr("href") == "#" ){
            $(this).parent().find("a:first").addClass("opensub-l2");
        }else{
            //if header is not active -> hide menu
            if($(this).parent().find("a:first").hasClass('on')==false){
                $(this).hide();
            }else{
                $(this).parent().find("a:first").addClass('fix-ui-state-active');
            }
        }
    });
    $('#menu-left ul.sub-l1').accordion({
        active: '.on',
        header: '.opensub-l2',
        navigation: false,
        event: 'click',
        autoHeight: false,
        collapsible: true
    });
    // Add open Class for level 3
    $("#menu-left ul.sub-l3").each(function(){
        //add opensub class if href != #
        if( $(this).parent().find("a:first").attr("href") == "#" ){
            $(this).parent().find("a:first").addClass("opensub-l3");
        }else{
            //if header is not active -> hide menu
            if($(this).parent().find("a:first").hasClass('on')==false){
                $(this).hide();
            }else{
                $(this).parent().find("a:first").addClass('fix-ui-state-active');
            }
        }
    });
    $('#menu-left ul.sub-l2').accordion({
        active: '.on',
        header: '.opensub-l3',
        navigation: false,
        event: 'click',
        autoHeight: false,
        collapsible: true
    });
    // Add open Class for level 4
    $("#menu-left ul.sub-l4").each(function(){
        //add opensub class if href != #
        if( $(this).parent().find("a:first").attr("href") == "#" ){
            $(this).parent().find("a:first").addClass("opensub-l4");
        }else{
            //if header is not active -> hide menu
            if($(this).parent().find("a:first").hasClass('on')==false){
                $(this).hide();
            }else{
                $(this).parent().find("a:first").addClass('fix-ui-state-active');
            }
        }
    });
    $('#menu-left ul.sub-l3').accordion({
        active: '.on',
        header: '.opensub-l4',
        navigation: false,
        event: 'click',
        autoHeight: false,
        collapsible: true
    });
    //----->switch-lang
    $("select[name=switch-lang]").sSelect({
        objWidth:90
    });
    switchLanguageSite("select[name=switch-lang]");
    $('#menu-top ul li#switch-lang .containerSelectBox ul li:eq(1)').addClass('en');
    //-----> fitted
    $(".ultime-news > li, .rssfeed > li, #search-result .results > div, .box-prodotti > li:not(.not-ext), .news-list > li, .box-3-col > li, ul:not(.not-ext).box-categorie > li:not(.not-ext), ul.lista-prodotti > li:not(.not-ext), ul.lista:not(.not-ext) > li:not(.not-ext), ul.simple-list > li:not(.not-ext), .extended-anchor").fitted({
        className:{
            'hover' : 'hovering'
        }
    });
    //-----> tipsy	tooltip
    $('acronym, .photo > ul > li > a,ul#area-download > li > ul > li > a, ul.simple-list > li > a, a.info').tipsy({
        gravity: 's',
        offset: 0
    });
    $('ul.utility > li > a, ul.quick-contact > li > a,.quick-contact > a').tipsy({
        gravity: 's',
        offset: -6
    });
    //-----> fix clear ul.box-categorie li
    $("ul.box-categorie > li").each(function(){
        if($(this).index()>0 && $(this).index()%3==0){
            $(this).css("clear","both");
        }
        if($(this).index()>0 && ($(this).index()+1)%3==0 && !$(this).hasClass("box-last")){
            $(this).addClass("box-last");
        }
    });
    //-----> fix box-last
    $("ul.box-prodotti.box-2-col > li").each(function(){
        if($(this).index()%2==1 && !$(this).hasClass("box-last")){
            $(this).addClass("box-last");
        }
    });
    $("ul.box-prodotti.box-3-col > li").each(function(){
        if($(this).index()>0 && ($(this).index()+1)%3==0 && !$(this).hasClass("box-last")){
            $(this).addClass("box-last");
        }
    });

    //-----> saved_products
    //cluetip
    loadCluetip(".widget a[rel=saved_products]", false, 'href', 'title', 'click', 650, false, true, 'mee', removeSavedProducts);
    //numero di prodotti salvati
    $('.widget a[rel=saved_products]').find('span.n').load("/common/html/prodotti/save.php");

    //-----> compare_products & saved_products
    $("#compare_products").dialog({
        autoOpen: false,
        show: dialog_show,
        hide: dialog_hide,
        buttons: {
            Ok: function() {
                $( this ).dialog( "close" );
            }
        }
    });
    $("#saved_products").dialog({
        autoOpen: false,
        show: dialog_show,
        hide: dialog_show,
        buttons: {
            Ok: function() {
                $( this ).dialog( "close" );
            }
        }
    });

    $('.lista-prodotti a.compara, .utility a#compara, .widget a[rel=compare_products]').click(function(){
        $("#compare_products").dialog("open");
        return false;
    });
    //-----> input and .button focus and hover
    addHoverFocusInputClass();
    //-----> photo-gallery hover
    addHoverPhotoGalleryClass('.photo-gallery > li');
    //-----> fix footer on class
    $('#container-footer p.float-left a:last').addClass('on');
    //-----> Shadowbox
    Shadowbox.init();
    //----> focus
    $("#login form input:first").focus();
}
/**
 * loadCluetip
 */
function loadCluetip(el, local, attribute, titleAttribute, activation, width, mouseOutClose, sticky, cluetipClass, functionOnShow){
    if($(el).size()>0){
        $(el).cluetip({
            width:            width,
            cluezIndex:       1000,
            positionBy:       'auto',
            topOffset:        15,
            leftOffset:       15,
            local:            local,    // Whether to use content from the same page for the clueTip's body
            localPrefix:      null,     // string to be prepended to the tip attribute if local is true
            attribute:        attribute,   // the attribute to be used for fetching the clueTip's body content
            titleAttribute:   titleAttribute,  // the attribute to be used for fetching the clueTip's title
            splitTitle:       '',
            escapeTitle:      false,    // whether to html escape the title attribute
            showTitle:        true,
            cluetipClass:     cluetipClass,
            hoverClass:       '',
            waitImage:        true,
            cursor:           'hand',
            arrows:           true,
            dropShadow:       false,
            dropShadowSteps:  3,
            sticky:           sticky,     // keep visible until manually closed
            mouseOutClose:    mouseOutClose,    // close when clueTip is moused out
            activation:       activation,
            clickThrough:     true,     // if true, and activation is not 'click', then clicking on link will take user to the link's href, even if href and tipAttribute are equal
            tracking:         false,
            delayedClose:     0,
            closePosition:    'top',    // location of close text for sticky cluetips; can be 'top' or 'bottom' or 'title'
            closeText:        'close [x]',
            ajaxCache:        false,
            onShow:           function(ct, c){
                functionOnShow();
            }
        });
    }
}
/**
 * removeSavedProducts
 */
function removeSavedProducts(){

    $('.widget-list > li:not(.default)').fitted({
        className:{
            'hover' : 'hovering'
        }
    });

    $('.widget-list > li a.remove').tipsy({
        gravity: 's',
        offset: 0
    });

    $('.widget-list a.remove').click(function(){
        product_id=$(this).attr('rel');
        $.ajax({
            beforeSend: function(){},
            complete: function(){},
            type: "GET",
            url: "/common/html/prodotti/save.php",
            cache: false,
            data: "save_product_id="+product_id+"&remove=1",
            success: function(html){
                $('.widget a[rel=saved_products]').find('span.n_ext').animate({
                    opacity: 0.1
                }, 200, function() {
                    $('.widget a[rel=saved_products]').find('span.n').html(html);
                    $('.widget a[rel=saved_products]').find('span.n_ext').animate({
                        color: "#d60000",
                        opacity: 1
                    }, 1000, function() {
                        $('.widget a[rel=saved_products]').find('span.n_ext').animate({
                            color: "#626262"
                        }, 500);
                    });
                });
                $('.lista-prodotti a.salva-prodotto[rel='+product_id+'], .utility a#salva-prodotto[rel='+product_id+']').fadeOut().removeClass('on').fadeIn();
                $('.tipsy').fadeOut().remove();
                $('.widget-list').load(HREF_site+"/prodotti/saved_products.php .widget-list > li",function(){
                    removeSavedProducts()
                }).hide().fadeIn('slow');
            },
            error: function(){ }
        });
        return false;
    });
}
/**
 * addPlyaIcon
 */
function addPlyaIcon(){
    if($('.addPlayIcon').length>0){
        $('.addPlayIcon').each(function(){
            $(this).css({
                'position': 'relative'
            });
            $(this).append('<span class="playIcon" />');
            $(this).find('.playIcon').height($(this).height());

        });
    }
}
/**
 * switchLanguageSite
 */
function switchLanguageSite(select){
    $(select).change(function(){
        opt=$(this).find(':selected').val();
        window.location=opt;
    });
}
/**
 * addHoverFocusInputClass
 */
function addHoverFocusInputClass(){
    $('input[type=submit],input[type=reset],input[type=button],button,a.button,input.button').hover(function(){
        $(this).addClass('hover')
    },function(){
        $(this).removeClass('hover')
    });
    $('input[type=submit],input[type=reset],input[type=button],input[type=text],input[type=password],textarea,select').focus(function(){
        $(this).addClass('focus')
    });
    $('input[type=submit],input[type=reset],input[type=button],input[type=text],input[type=password],textarea,select').blur(function(){
        $(this).removeClass('focus')
    });
}
/**
 * addHoverPhotoGalleryClass
 */
function addHoverPhotoGalleryClass(el){
    $(el).hover(function(){
        $(this).addClass('hover');
        $(this).append("<span class='zoom'></span>");

    },function(){
        $(this).removeClass('hover');
        $(this).find('.zoom').remove();
    });
}
/**
 * loadKwicksMenu
 * el: selector,
 * paddingInside: padding inside 'li'
 * min: min width when 'li' are closed,
 * spacing: spacing between 'li' (1 -> border-right),
 * duration: duration of the animation
 * easing: easing effect
 */
var active=0;
var saveMaxWidth=0;
function loadKwicksMenu(el,paddingInside,min,spacing,duration,easing){
    ul=$(el).find('ul.kwicks-menu');
    if(ul.children('li').length>0){
        if(!paddingInside) {
            paddingInside=0;
        }
        if(!duration) {
            duration=500;
        }
        if(!easing) {
            easing='easeOutQuad';
        }

        if(!saveMaxWidth){
            maxWidth=0;
            var maxWidthArray = [];
            ul.children('li').each(function(i){
                maxWidthArray[i] = $(this).find("a").outerWidth();
                $(this).hover(function(){
                    $(this).addClass('hover');
                },function(){
                    $(this).removeClass('hover');
                });
                if($(this).find("a").hasClass("on")){
                    active=$(this).index();
                }
            });
            maxWidth = Array.max(maxWidthArray) + paddingInside;
            saveMaxWidth = maxWidth;
        }else{
            maxWidth = saveMaxWidth;
        }
        //fix active value depending location.hash (#)
        var hash= location.hash;
        if (hash){
            ul.children('li').each(function(i){
                if($(this).find('a').attr('href')==hash){
                    active=i;
                }
            });
        }

        ul.children('li').find('a').width(maxWidth); //fix anchor width
        ul.kwicksMenu({
            defaultKwick: active,
            event: 'mouseover',
            spacing: spacing,
            duration: duration,
            max: maxWidth,
            min: min,
            easing: easing,
            classActive: 'ui-state-active'
        });


    //active=2;
    }
}
/**
 * loadKwicksAndTabs
 */
var tabsKwicks ;
function loadKwicksAndTabs(el,paddingInside,min,spacing,duration,easing){
    loadKwicksMenu(el,paddingInside,min,spacing,duration,easing);
    if($(el).parent('div.tabs').size()==1){
        tabsKwicks=$(el).parent('div.tabs').tabs({
            selected: active,
            select: function(event, ui) {
                var url = $.data(ui.tab, 'load.tabs');
                if( url ) {
                    location.href = url;
                    return false;
                }
                return true;
            },
            show: function (event,ui){
                // se la scheda contiene una gestione a tabs
                if($(ui.panel).find("div.tabs").length>0){
                    // applico stile sub-menu-scheda
                    $("#"+ui.panel.id+" > div.tabs > div:first").addClass("sub-menu-scheda");
                    // rimuovo padding/margin top
                    $(ui.panel).css({
                        "padding-top":0,
                        "margin-top":0
                    });
                    // creo tabs
                    internal_tabs=$('div.tabs').tabs({
                        selected: 0
                    });
                }
                // se la scheda contiene una gestione a tabs

//                if($(ui.panel).find("h4").length>0 && $(ui.panel).attr("id")=='tab-scheda'){
//                    $($(ui.panel).find("h4:first:not(.subtitle)")).width(570);
//                }
                if($(ui.panel).find("a.select-tab").length>0 && $(ui.panel).attr("id")=='tab-scheda'){
                    $(ui.panel).find('a.select-tab').click(function(){
                        h=$(this).attr('href');
                        p=$(el).find("ul:first > li > a[href="+h+"]").parent('li').index();
                        tabsKwicks.tabs('select', p);
                        active=p;
                        $(el).find("ul:first > li > a").removeClass('on');
                        loadKwicksMenu('#menu-scheda',10,40,1);
                        return false;
                    });
                }
            },
            load: function (event,ui){

            }
        });
    }
}
/**
 * privacyOverlay
 */
function privacyOverlay(el){
    $(el+' a').click(function(){
        Shadowbox.open({
            content:    $(this).attr('href'),
            player:     "iframe",
            title:      $(this).attr('title'),
            height:     600,
            width:      850
        });
        return false;
    });
    $(el).next('ul').radiobutton({
        clickAll: false,
        liInline: true
    });
}
/**
 * changeTypeOfUser v1.0 vecchio sistema
 */
function isCompany(p){
    $(p).show();
    $(p+" input").removeAttr("disabled");
}
function isNotCompany(p){
    $(p).hide();
    $(p+" input").val("");
    $(p+" input").attr("disabled","disabled");
}
function changeTypeOfUser(choice,p,inline){
    $(choice).radiobutton({
        liInline:inline,
        clickAll:false
    });
    isNotCompany(p); /* default */
    if($(choice+" li:first input[type='radio']").attr("checked")){
        isNotCompany(p);
    }
    if($(choice+" li:last input[type='radio']").attr("checked")){
        isCompany(p);
    }
    $(choice+" li:first span:first").click(function(){
        isNotCompany(p);
    });
    $(choice+" li:last span:first").click(function(){
        isCompany(p);
    });
    $(choice).parents("form").bind('reset',function(){
        isNotCompany(p); /* default */
    })
}
/**
 * changeTypeOfUser v2.0
 */
function isCompany_v2(divP,divC,divPC){
    $(divP).hide();
    $(divP).find(":input:not(select)").val("");
    $(divP).find(":input").attr("disabled","disabled");

    $(divC).show();
    $(divC).find(":input:not(select,"+divPC+" input[type='checkbox']:first)").val("");
    $(divC).find(":input").removeAttr("disabled").fadeTo("fast",1);

    personHasCompany(divPC);
}

function personHasCompany(divPC){
    $(divPC).find("fieldset:first input[type='checkbox']:first").attr("checked", "checked");
    $(divPC).find("label, legend:not(:first)").fadeTo("fast",1);
    $(divPC).find("fieldset:first input[type='checkbox']:first").click(function(){
        if($(this).is(":checked")){
            $(divPC).find(":input").removeAttr("disabled").fadeTo("fast",1);
            $(divPC).find("label, legend:not(:first)").fadeTo("fast",1);
        }else{
            $(divPC).find(":input:not(input[type='checkbox']:first)").attr("disabled","disabled").fadeTo("fast",0.6);
            $(divPC).find("label, legend:not(:first)").fadeTo("fast",0.6);
        }
    });
}

function isPerson(divP,divC,divPC){
    $(divC).hide();
    $(divC).find(":input:not(select,"+divPC+" input[type='checkbox']:first)").val("");
    $(divC).find(":input").attr("disabled","disabled");


    $(divP).show();
    $(divP).find(":input:not(select)").val("");
    $(divP).find(":input").removeAttr("disabled");

}

function changeTypeOfUser_v2(choice,divP,divC,divPC){

    $(divPC).find("fieldset:first input[type='checkbox']:first").attr("checked", "checked");

    v=$(choice+" input[type='radio']:checked").val();

    if(v=="person"){
        isPerson(divP,divC,divPC);
    }else if(v=="company"){
        isCompany_v2(divP,divC,divPC);
    }else{
        $(choice+" input[type='radio'][value='person']").attr("checked", "checked");
        isPerson(divP,divC,divPC); /* default */
        v=$(choice+" input[type='radio']:checked").val();
    }

    $(choice+" input[type='radio']").click(function(){
        v=$(this).val();

        if(v=="person"){
            isPerson(divP,divC,divPC);
        }
        if(v=="company"){
            isCompany_v2(divP,divC,divPC);
        }
    });

    $(choice).parents("form").bind('reset',function(){
        isPerson(divP,divC,divPC); /* default */
    })
}
/**
 * selectCascade
 */
function selectCascade(url, loading, select, result, param, onSuccess){
    $(loading).hide();
    $(select).change(function(){
        opt=$(this).find(':selected').val();

        $.ajax({
            beforeSend: function(){
                $(result).html("");
                $(loading).show();
            },
            complete: function(){
                $(loading).hide();
            },
            type: "GET",
            url: url,
            cache: false,
            data: param+"="+opt,
            success: function(html){
                $(result).html(html);
                if(onSuccess){
                    onSuccess();
                }
            },
            error: function(){
                $(result).html('Error, please try again later..');
            }
        });
    });
}

/**
 * validateAndCaptcha
 */
function validateAndCaptcha(form, errorContainer, captchaContainer, label, title, msg){
    var firstNumber = Math.ceil(Math.random()*10);
    var secondNumber = Math.ceil(Math.random()*10);
    var theAnswer = firstNumber + secondNumber;
    $(captchaContainer).html("<label for='captcha'>"+label+"<span>*</span>: "+firstNumber+" + "+secondNumber+" =</label> <input type='text' name='captcha' id='captcha' maxlength='2' class='captcha' title='"+title+"' />");
    var validator=$(form).validate({
        errorLabelContainer: $(errorContainer)
    });
    if (validator){
        $(form+" input[type=reset]").bind("click", function(e){
            validator.resetForm();
        });
        $(captchaContainer+ " input[name=captcha]").rules("add", {
            required:true,
            digits:true,
            range:[theAnswer,theAnswer],
            messages:{
                range: msg
            }
        } );
        return validator;
    }
    return false;
}
/**
 * pre-submit callback
 */
function showRequest(formData, jqForm, options) {
    var queryString = $.param(formData);
    alert('About to submit: \n\n' + queryString);
    return true;
}
/**
 * post-submit callback
 */
function showResponse(responseText, statusText, xhr, $form)  {
    alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +
        '\n\nThe output div should have already been updated with the responseText.');
}
/**
 * Addthis
 */
function hoverAddthis(hover_me){
    $(hover_me).find("div.addthis_services").css({
        opacity: 0.9
    }).append("<span class='arrow'></span>");
    $(hover_me).each(function(){
        $(this).mouseenter(function() {
            $(this).find('.addthis_services').fadeIn('fast');
            $(this).addClass('on');
            $(this).data('in', true);
            $(this).find('.addthis_services').data('in', true);
            $(this).find('.addthis_services').data('hidden', false);
        }).mouseleave(function() {
            $obj=$(this);
            $(this).data('in', false);
            $(this).find('.addthis_services').data('in', false);
            setTimeout(function () {
                if (!$obj.data('in') && !$obj.find('.addthis_services').data('in') && !$obj.find('.addthis_services').data('hidden')) {
                    $obj.find('.addthis_services').fadeOut('fast');
                    $obj.removeClass('on');
                    $obj.find('.addthis_services').data('hidden', true);
                }
            }, 200);
        });
    });
}


function inputToUpperCase(el){
    $(el).keypress( function(){
        $(this).val($(this).val().toUpperCase());
    }).change( function(){
        $(this).val($(this).val().toUpperCase());
    });
}
