// funzione per fare le colonne della stessa altezza
function equalHeight(group) { var tallest = 0; group.each(function () { var thisHeight = $(this).height(); if (thisHeight > tallest) { tallest = thisHeight; } }); group.height(tallest); }

// funzione per allineare in verticale   
(function ($) { $.fn.vAlign = function () { return this.each(function (i) { var ah = $(this).height(); var ph = $('#ring_carousel').height(); var mh = Math.ceil((ph - ah) / 2) - 30; $(this).css('margin-top', mh); }); }; })(jQuery);

// funzione per allineare in verticale   
(function ($) { $.fn.vAlign2 = function (altez) { return this.each(function (i) { var ah = $(this).height(); var ph = altez; var mh = Math.ceil((ph - ah) / 2); $(this).css('margin-top', mh); }); }; })(jQuery);


$(document).ready(function () {

    //inizializzo il banner flip
    $('#flipAdv iframe').attr('src', $('#flipAdv iframe').attr('rel'));

    //PIT MOD FOR FEED START: Se non ci sono elementi selezionati, prende il primo. Also, fix per spazio cambiato con "_" nel filterVal
    var filterVal = $('#feed_sidebar li a.selected').text().replace(/ /gi, '_');

    if (filterVal == '') {
        $('#feed_sidebar li a:first-child').addClass('selected');
        filterVal = $('#feed_sidebar li a.selected').text().replace(/ /gi, '_');
    }
    //PIT MOD FOR FEED END

    var current_feed_num = $('#feed_content li').length;  //PIT MOD FOR FEED
    var min_feed_for_more = 10; //PIT MOD FOR FEED

    if ($('#feed_content').length > 0) {
        var num_feed = 3;

        //PIT MOD FOR FEED START, se ce ne sono meno di 10 nascondo il pulsante
        if (current_feed_num <= min_feed_for_more) {
            $("#feed_more").hide();
        }
        //END PIT MOD FOR FEED

        //filtro feed
        $('#feed_sidebar li a').click(function (e) {
            e.preventDefault();
            $('#feed_sidebar li .selected').removeClass('selected');
            $(this).addClass('selected');
            filterVal = $(this).text().replace(/ /gi, '_');//PIT MOD FOR FEED, cambia lo spazio in undescore per gestire correttamente lo switch
            //alert(filterVal);
            if (filterVal == 'tutto') {
                $("#feed_content ul li").hide().addClass('hidden').each(function (index) {
                    if (index <= num_feed) { $(this).fadeIn("fast").removeClass('hidden'); }
                });
            } else {
                var ncount = -1;
                $("#feed_content ul li").each(function (index) {
                    if (!$(this).hasClass(filterVal)) {
                        $(this).hide().addClass('hidden');
                    } else {
                        ncount += 1;
                        if (ncount <= num_feed) { $(this).fadeIn("fast").removeClass('hidden'); }
                    }
                });
            }
            return false;
        });
        $('#feed_content ul li.hidden').hide();
        $("#feed_more").live('click', function () {
            num_feed += 10;
            if (filterVal == 'tutto') {
                $("#feed_content ul li.hidden").each(function (index) {
                    if (index <= 9) { $(this).fadeIn("fast").removeClass('hidden'); }
                });
            } else {
                var ncount = -1;
                $("#feed_content ul li.hidden").each(function (index) {
                    if ($(this).hasClass(filterVal)) {
                        ncount += 1;
                        if (ncount <= num_feed) { $(this).fadeIn("fast").removeClass('hidden'); }
                    }
                });
            }

            //PIT MOD FOR FEED START, se ce ne sono meno di 10 nascondo il pulsante
            if (current_feed_num <= num_feed) {
                $("#feed_more").hide();
            }
            //END PIT MOD FOR FEED
        });
    }

    if ($('#caros_mystyle').length > 0) { jQuery('#caros_mystyle').jcarousel({ wrap: 'circular', scroll: 1 }); }

    if ($('#carousel3').length > 0) { jQuery('#carousel3').jcarousel({ wrap: 'circular' }); }
    if ($('#oggi_tanti_auguri').length > 0) { $(".tooltip").tooltip({ track: true, delay: 0, opacity: 1, extraClass: "pretty fancy", showURL: false, top: -15, left: 5 }); }

    $('.blogger .info').vAlign2(88);
    //streetmemo_home caorousel
    if ($('#car_looks').length > 0) {
        $('#car_looks ul li img').vAlign2(375);
        $('#car_looks ul').carouFredSel({ width: 655, items: { visible: 3, start: -1 }, align: 'right', height: 381, scroll: { items: 1 }, auto: { play: false }, prev: { button: '#r_prev', onBefore: function () { fragmentRefreshAll('slider'); } }, next: { button: '#r_next', onBefore: function () { fragmentRefreshAll('slider'); } } });
    }

    //streetmemo_home centra le thumbs dei looks "vedi anche" 130x130 
    if ($('.looks').length > 0) { $('.looks li a img').vAlign2(130); }


    /* flipAdv */
    $('#flipAdv').prepend('<a class="close" href="#">SKIP</a>');
    //$('#flipAdv .adv').css({ 'margin-left': 50, 'margin-top': 50 });
    function pause_if_plaing() {
        if (pausa == 1) {
            $('#ring_carousel').trigger("pause"); pausa = 2; $("#ring_pause").children('span').addClass('disabled').parent().prev().children('span').removeClass('disabled');
        }
    }
    function play_if_paused() {
        if (pausa == 2) {
            pausa = 1; $('#ring_carousel').trigger("play");
            $("#ring_play").children('span').addClass('disabled').parent().next().children('span').removeClass('disabled');
        }
    }
    var flipAdvClose = function () {
        $('#flipAdv').css({ 'z-index': -10 });
        //refresh flip banner
        $('#flipAdv iframe').attr('src', $('#flipAdv iframe').attr('rel'));

        play_if_paused();
        $('#thumbs-cont').css({ 'opacity': 1 });
        advActive = false;
        $('.adFrameContainer').fadeIn(100);
        return false;
    }

    $('#flipAdv .close').click(function () {
        flipAdvClose();
        return false;
    });
    if (parseInt($.cookie('articleClick'))) {
        articleClick = parseInt($.cookie('articleClick'));
    } else {
        $.cookie('articleClick', articleClick);
    }

    function flipAdvEnabled() {
        var response = $("#flipAdv iframe").contents().find("body").html().indexOf('http://s0.2mdn.net/viewad/817-grey.gif');
        if (response != -1) {
            return false;
        } else {
            return true;
        }
    }
    function flipAdv() {
        articleClick++;
        $.cookie('articleClick', articleClick);
        if ((articleClick == rg1) || (articleClick == rg2) || (articleClick == rg3) || (articleClick > rg3 && articleClick % rgK == 0)) {
            if (flipAdvEnabled()) {
                $('#flipAdv').css({ 'z-index': 100, 'height': $('#flipAdv').parent().height() }).show();
                $('.adFrameContainer').fadeOut(450, function () { });
                pause_if_plaing();
                $('#thumbs-cont').css({ 'opacity': 0.5 });
                advActive = true;
            } else {
                //refresh flip banner
                $('#flipAdv iframe').attr('src', $('#flipAdv iframe').attr('rel'));
                cnp.ad.manager.reloadAds();
            }
        } else {
            cnp.ad.manager.reloadAds();
        }

    }
    /* fine flipAdv */

    function setSlideVoteId(newItems) {
        var idItem = newItems.attr('id');
        var itemType = newItems.attr('rel').split('_')[0];
        if (idItem.indexOf('_') != -1) {
            idItem = idItem.split('_')[1];
        }
        getVoting(idItemRef, idItem, itemType);
    }

    function thum() {
        if ($('#ring_carousel_static').length > 0) {
            $('#r_prev,#r_next').vAlign2(533);
        } else { $('#r_prev,#r_next').vAlign(); }
        var thum = $('#thumbs');
        thum.carouFredSel({
            width: 650,
            circular: true,
            height: 103,
            scroll: 2000,
            auto: false,
            prev: {
                button: "#t_prev"
            },
            next: {
                button: "#t_next"
            },
            onCreate: function () {
                if (thum.width() < 650) {
                    thum.css({ width: thum.width() + 30 });
                }
            }
        }
        );
    }


    if ($('#ring_carousel').length > 0) { //se esiste il ring carousel
        if ($('.memo_photo').length > 0) { $('.memo_photo').vAlign2(533); }

        var pausa = 0,
        articleClick = 0,
        advActive = false;

        /* adv click ranges */
        var rg1 = 3;
        var rg2 = 8;
        var rg3 = 16;
        var rgK = 8;
        /* adv click ranges */
        if ($('.embedded').length > 0) {
            var emb_first = 0; var tot = $('#ring_carousel').children('li').size(); $('#tot,.emb_tot').html(tot - 1);
        }
        else { var tot = $('#ring_carousel').children('li').size(); $('#tot').html(tot); }

        // slide verticale > setta l'altezza della didascalia come quella della foto  
        equalHeight($(".equal-height"));
        $('#ring_carousel>li').each(function (index, item) {
            if (!$(this).attr('id')) {
                $(this).attr('id', 'slide' + index);
            }
        });

        function showHideNavigation(itemType) {
            if ((itemType.toLowerCase().indexOf('test') != -1) || (itemType.toLowerCase().indexOf('quiz') != -1)) {
                $('#r_prev').hide();
                $('#r_next').hide();
            } else {
                $('#r_prev').show();
                $('#r_next').show();
            }
        }

        $('#ring_carousel').carouFredSel({
            items: 1,
            circular: true,
            auto: {},
            align: "left",
            onCreate: function (items) { showHideNavigation(items.attr('rel')); thum(); },
            scroll: {
                items: 1,
                onAfter: function (oldItems, newItems, newSizes) {
                    var item = newItems.filter(':first');
                    //var pos=item.attr('id').substr(1);

                    showHideNavigation(item.attr('rel'))
                    window.location.hash = '#--' + item.attr('id');
                    $('#ring_carousel').trigger("currentPosition", function (pos) {

                        $("#thumbs").trigger('slideTo', pos);
                        if (emb_first == 0) { emb_first = 1; $('#num,.emb_num').html(pos); } else { $('#num,.emb_num').html(pos + 1); }

                        $("#thumbs a.selected").removeClass("selected");
                        $('#thumbs a[href="#' + pos + '"]').addClass("selected");

                        try {
                            if (modVP != null) {
                                for (player in modVP) {
                                    modVP[player].pause(true);
                                }
                            }
                        } catch (er) { }
                        setSlideVoteId(newItems);
                        countUserPV("/gallery/" + newItems.attr('id') + "/");

                        flipAdv();

                        if ($('#ring_carousel_static').length > 0) {
                            $('#r_prev,#r_next').vAlign2(533);
                        } else { $('#r_prev,#r_next').vAlign(); }
                    });
                }
            },
            items: 1
        }).trigger("pause");

        $('.slideshow, #thumbs').hover(function () { pause_if_plaing(); }, function () { play_if_paused(); });
        $("#r_prev").click(function (e) { e.preventDefault(); $('#ring_carousel').trigger("prev").trigger("pause"); $("#ring_pause").children('span').addClass('disabled').parent().prev().children('span').removeClass('disabled'); return false; });
        $("#r_next").click(function (e) { e.preventDefault(); $('#ring_carousel').trigger("next").trigger("pause"); $("#ring_pause").children('span').addClass('disabled').parent().prev().children('span').removeClass('disabled'); return false; });
        $("#ring_play").click(function (e) { e.preventDefault(); pausa = 1; $('#ring_carousel').trigger("play").trigger("next"); $(this).children('span').addClass('disabled').parent().next().children('span').removeClass('disabled'); return false; });
        $("#ring_pause").click(function (e) { e.preventDefault(); pausa = 0; $('#ring_carousel').trigger("pause"); $(this).children('span').addClass('disabled').parent().prev().children('span').removeClass('disabled'); return false; }).children('span').addClass('disabled');
        $("#thumbs a").click(function (e) {
            if (!advActive) {
                pausa = 0; e.preventDefault();
                if ($(this).attr('rel') != 'noclick') {
                    $("#ring_pause").children('span').addClass('disabled').parent().prev().children('span').removeClass('disabled');
                    var link = parseInt($(this).attr("href").substr(1));
                    $('#ring_carousel').trigger("slideTo", link, 0, true).trigger("pause");
                } else {
                    alert("Stai eseguendo un test o un quiz, non puoi saltare le domande");
                }
            }
            return false;
        });


        if ($('#ring_carousel_static').length > 0) {
            $('#ring_play, #ring_pause').hide();
            var tot = $('#thumbs').children('a').size(); $('#tot').html(tot);
        }

        if (window.location.hash) {
            var slug = window.location.hash.substr(3);
            //var item=$('#thumbs a[id="'+slug+'"]');
            var item = $('#ring_carousel>li[id="' + slug + '"]');
            if (item.length) {
                //item.click();
                var index = $('#ring_carousel>li').index(item);
                $('#ring_carousel').trigger("slideTo", index, 0, true).trigger("pause");
            }
        } else {
            $('#thumbs a:first').addClass('selected');
        }
        $('#thumbs>a').each(function (index, item) {
            $(this).attr('href', '#' + index);
        });
    }
    //fine se esiste carousel
    thum();


    // Embedded
    if ($('.embedded #ring_carousel').length > 0) {
        $('#ring_carousel li').vAlign2(710);
        $('#r_next,#r_prev').hide();
        $("#click_n_play").click(function (e) {
            e.preventDefault();
            $('#r_next,#r_prev').fadeIn();
            $('.cover').animate({ "left": "-=47px" }, "fast");
            $('#ring_carousel').trigger("next").trigger("pause");
            setTimeout(function () { $('#ring_carousel').trigger("removeItem", [0, true]); }, 1000);
            $("#ring_pause").children('span').addClass('disabled').parent().prev().children('span').removeClass('disabled');
            return false;
        });
    }

    // Footer Carosello Abbonamenti
    jQuery('#roundabout').roundabout({ btnNext: '#mag_next', btnPrev: '#mag_prev', minOpacity: 1, minScale: 0.75, maxScale: 1 });
    var abbonamento = jQuery('#roundabout li.roundabout-in-focus').children('.abbonamento').html();
    jQuery('#abbonamento').html(abbonamento);
    jQuery('#roundabout li').focus(function () { var useText = jQuery(this).children('.abbonamento').html(); jQuery('#abbonamento').fadeOut(200, function () { jQuery(this).html(useText).fadeIn(400); }); });

    //Dropcap primo paragrafo foglia    
    var p1 = $(".contenuto p:first"); p1.addClass("dropcap"); var p = p1.text(); var c = p.charAt(0); p1.html('<span class="dropcap-' + c.toLowerCase() + '">' + c + '</span>' + p.substr(1));
});



