/**
 *  Common scripts file
 *  @version: 1.0
 *  @require: jquery
 */

var currentPosition = 0,
    currentVolume = 80,
    currentVideo = 0,
    autoPause = true,
    player = false,
    playerReady = false,
    isJson = false,
    section = '',
    layout = '',
    ticker = false,
    hash =''
    locationId = '12846931';

$(document).ready(function()
{
    // id della sezione
    section = $(document.body).attr('id');

    // layout di pagina
    layout = ($('#news').hasClass('single-view') ? 'single' : 'list');

    // ancora interna
    hash = window.location.hash.substring(1)

    // protezione antispam per le email
    emailProtection('.email');

    // pulsanti stampa
    printButtons('a.print');

    // menu fix per IE 6
    loadNavbar('#nav ul.main li');

    // nasconde/mostra il testo 'cerca' nel form
    showSearchText('input.src_text');

    // fancybox
    addFancyBox('a.zoom, li.jpg a, li.png a, li.gif a, li.mp3 a');

    // player flash
    //createPlayer('#player');

    // latest items
    populateSnippets();

    // social
    $('div.social').find('a.btn').click(function(e){ e.preventDefault(); condividi(this.rel); });


});

// Azioni al caricamento completo della pagina
$(window).load(function()
{
    // sistemo le altezze delle colonne in homepage
    if(section == 'home') {
        equalHeights('#latest-news div.article');
    } else {
        equalHeights('#content li.document');
    }
});

// Avvia il news-ticker
function loadNewsTicker(el)
{
    if ($(el).length < 1) {
        el = "#ticker";
    }

    // metodo 1
    //ticker = $(el).show().liScroll();

    // metodo 2 (richiede meno risorse poiché evità il redraw del browser)
    var scroller = $(el).show();
    //scroller.wrap("<div class='tickercontainer'></div>");
    ticker = scroller.parent().marquee('tickercontainer').mouseover(function () {
        $(this).trigger('stop');
    }).mouseout(function () {
        $(this).trigger('start');
    });
}

// Carica i contenuti nelle snippets
function populateSnippets()
{
    var boxGsrContainer    = '#box-gsr',
        boxCogContainer    = '#box-cog',
        boxSrContainer     = '#box-sr',
        boxCfcContainer    = '#box-cfc',
        boxTickerContainer = '#box-ticker',
        boxContent         = 'div.boxContent';

    // recupera i gsr
    getItems(boxGsrContainer, boxContent, {'action': 'get_gsr'});

    // recupera i cog
    getItems(boxCogContainer, boxContent, {'action': 'get_cog'});

    // recupera le sr
    getItems(boxSrContainer, boxContent, {'action': 'get_sr'});

    // recupera le attivita cfc
    getItems(boxCfcContainer, boxContent, {'action': 'get_cfc'})

    // recupera le news dall'AIR
    getItems(boxTickerContainer, boxContent, {'action': 'get_ticker'}, loadNewsTicker)
}

// Aggiunge fancybox
function addFancyBox(els)
{

    $(els).each(function(){
        $this = $(this);
        if($this.parent().hasClass('mp3')) {
            $this.fancybox({
                'width': 360,
                'height': 22,
                'type': 'swf',
                'padding': 0,
                'href': baseUrl +'lib/mediaplayer/player.swf?autostart=true&volume='+ currentVolume +'&skin='+ baseUrl +'lib/mediaplayer/skins/five.zip&file='+ this.href,
                'transitionIn'    : 'elastic',
                'transitionOut'    : 'elastic'
            });
        } else {
            $this.fancybox({
                'titlePosition': 'over',
                'overlayShow'  : false,
                'transitionIn' : 'elastic',
                'transitionOut': 'elastic',
                'titleFormat'  : function(title, currentArray, currentIndex, currentOpts)
                    {
                        if(currentArray.length > 1) {
                        return '<p id="fancybox-title-over">'+
                               '<span class="right">Immagine ' + (currentIndex + 1) + ' / ' + currentArray.length + '</span>' +
                               '<strong>'+ title +'</strong>'+
                               '</p>';
                        }
                        return false;
                    }
            });
        }
    });

    // se il link contiene #photogallery avvio fancybox
    if(hash == 'photogallery') {
        $('a.item_thumb').trigger('click');
        return false;
    }

    // se il link contiene #video avvio fancybox
    if(hash == 'video') {
        $('a.video').trigger('click');
        return false;
    }

    // se il link contiene #audio avvio fancybox
    if(hash == 'audio') {
        $('li.mp3 a').trigger('click');
        return false;
    }

}


// Crea il sotto menu delle categorie
function subMenu()
{

    $("ul.subnav").parent().append('<span class="open"></span>'); //Only shows drop down trigger when js is enabled (Adds empty span tag after ul.subnav*)

    $("ul.topnav li span.open").click(function() { //When trigger is clicked...

        //Following events are applied to the subnav itself (moving subnav up and down)
        $(this).parent().find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click

        $(this).parent().hover(function() {
        }, function(){
            $(this).parent().find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up
        });

        //Following events are applied to the trigger (Hover events for the trigger)
        }).hover(function() {
            $(this).addClass("subhover"); //On hover over, add class "subhover"
        }, function(){    //On Hover Out
            $(this).removeClass("subhover"); //On hover out, remove class "subhover"
    });


}

// Mostra/nasconde il testo nelle searchbox
function showSearchText(els)
{
    if ($(els).length > 0) {
        $(els).each(function(i){
            var oldTxt = 'Cerca';
            this.value = oldTxt;
            $(this).focus(function(){
                if (this.value == oldTxt) {
                    this.value = '';
                }
            }).blur(function(){
                if (this.value == '') {
                    this.value = oldTxt;
                }
            });
        });
    }
}

// Carica i carousel
function loadCarousel(el, options)
{
    if ($(el).length > 0) {
        $(el).jcarousel(((options != undefined) ? options : {}));
    }
}

// Carica il menu di navigazione
function loadNavbar(els)
{
    $(els).each(function(){
        $(this)
        .mouseenter(function(e){
                e.preventDefault();
                $(this).addClass('hover')
            })
        .mouseleave(function(e){
                e.preventDefault();
                $(this).removeClass('hover');
            });
    });
}

// Antispam per le email
function emailProtection(elClass)
{
    $(elClass).each(function(){
        var el = $(this);
        var mail = el.text().replace('[AT]','@');
        var text = el.attr('title') || mail;
        var a = $("<a>", {
            "class": elClass.substring(1),
            "href": 'mailto:' + mail,
            text: text
        });
        el.replaceWith(a);
    });
}

// Aggiunge l'azione "stampa"
function printButtons(elClass)
{
    $(elClass).click(function(e){
        e.preventDefault();
        window.print();
    });
}

// Crea il player flash
function createPlayer(idPlayer)
{
    player = $(idPlayer);

    if (player.length == 0) {
        return false;
    }
    currentVideo = player.find('a.play').attr('id').substring(1);

    if(!$.flash.available || !$.flash.hasVersion(10)) {
        player.find('img').fadeIn('fast');
        player.find('a.play').show(0);
        return false;
    }

    if(player.hasClass('video')) {
        player.jwPlayer({
            'id': 'jwPlayer',
            'name': 'jwPlayer',
            'height': '100%',
            'width': '100%',
            'swf': baseUrl +'lib/mediaplayer/player.swf',
            'skin': baseUrl +'lib/mediaplayer/skins/five.zip',
            'config': baseUrl + 'lib/mediaplayer/config.xml',// 'config-local.xml',
            'image': (player.find('img').attr('src')) || 'false',
            'playlistfile': baseUrl +'inc/playlist.inc.php?id='+ currentVideo,
            'volume': currentVolume,
            'fullscreenlistener': fullscreenlistener
        });
    } else {
        player.flash({
            swf: player.attr('href'),
            width: '100%',
            height: '100%',
            align: 'middle',
            valign: 'top',
            wmode: 'transparent',
            quality:'high',
            allowscriptaccess: 'always',
            pluginspage: 'http://www.macromedia.com/go/getflashplayer'
        });
    }

}

// ferma il newsticker per risparimare un po' di risorse CPU..
function fullscreenlistener(el)
{
    el.jwPlayer('get', 'fullscreen');
}

// Carica via ajax i contenuti delle snippets
function getItems(container, content, options, callback)
{

    if(container.length < 1) { return false; }

    $.extend(options, {'section': section});
    $(content, container).fadeOut('fast', function(){
        var $this = $(this).empty(),
            msg = false;

        displayLoader($this.parent());

        $this.parent().load(
            baseUrl +"inc/ajaxcalls.inc.php? "+ content,
            object2String(options),// converto in stringa per utilizzare il GET invece del POST
            function(response, status, xhr) {
                hideLoader($this.parent());
                if (status == "success") {
                    if($(response).find(content).children().length > 0) {
                        $(content).fadeIn('slow');
                        pager(container, content, options);
                        if (typeof callback == 'function') {
                            var fn = callback;
                            fn();
                        }
                    } else {
                        msg = '<p class="log">Nessun elemento presente.</p>';
                    }
                } else {
                    msg = '<p class="log">Si è verificato un errore:<br/> '+ xhr.status +' '+ xhr.statusText +'</p>';
                }
                if(msg) {
                    $(content, container).html(msg);
                }
            }
        );
    });
}

// Converte un oggetto in string
// eg. {'key1':'value1','key2','value2'} -> key1=value1&key2=value2
function object2String(obj) {
    var val, sep1 = "=", sep2 = "&", output = "";
    if (obj) {
        for (var i in obj) {
            val = obj[i];
            switch (typeof val) {
                case ("object"):
                    if (val[0]) {
                        output += i + sep1 + array2String(val) + sep2;
                    } else {
                        output += i + sep1 + object2String(val) + sep2;
                    }
                    break;
                case ("string"):
                    output += i + sep1 + val + sep2;
                    break;
                default:
                    output += i + sep1 + val + sep2;
            }
        }
        output = output.substring(0, output.length-1);
    }
    return output;
}

// Aggiunge le azioni al paginatorore
function pager(container, content, options)
{
    $(container).find('div.boxPager div.buttons a').each(function(){
        var $this = $(this);
        $this.click(function(e){
            e.preventDefault();
            getItems(container, content, $.extend(options, {'step': this.rel}));
        });
    });
}

// Mostra il loader
function displayLoader(el)
{
    var loader = el.find("p.loader");
    if (loader.length < 1) {
        loader = $('<p class="loader">Caricamento in corso...</p>');
        $(el).append(loader);
    }
    loader.fadeIn('fast');
}

// Nasconde il loader
function hideLoader(el)
{
    var loader = el.find("p.loader");
    if (loader.length > 0) {
        //loader.fadeOut('slow');
        loader.hide();
    }
};

function condividi(via)
{
    var url = '',
        pageUrl = encodeURIComponent(document.location.toString()),
        pageTitle = encodeURIComponent(document.title.toString());

    switch(via){
        case 'facebook':
            url = 'http://www.facebook.com/sharer.php?u=' + pageUrl + '&amp;t=' + pageTitle;
        break;

        case 'twitter':
            url = 'http://twitter.com/home?status=' + pageTitle + ':+' + pageUrl;
        break

        case 'digg':
            url = 'http://digg.com/submit?url=' + pageUrl;
        break;

        case 'myspace':
            url = 'http://www.myspace.com/Modules/PostTo/Pages/?u=' + pageUrl;
        break;

        case 'buzz':
            url = 'http://www.google.com/reader/link?url='+ pageUrl +'&title='+ pageTitle;
        break;

        case 'delicious':
            url = 'http://del.icio.us/post?url='+ pageUrl +'&title='+ pageTitle;
        break;

        case 'friendfeed':
            url = 'http://friendfeed.com/share/bookmarklet/frame#title=' + pageTitle + '&url=' + pageUrl;
        break;

        case 'oknotizie':
            url = 'http://oknotizie.virgilio.it/post?url='+ pageUrl +'&title='+ pageTitle;
        break;
    }

    if (url != '') { //console.log(pageUrl, pageTitle);
        window.open(url, '_blank', 'scrollbars=yes,menubar=no,border=0,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no');
    }
}

// Imposta la stessa altezza agli elementi in una riga
function equalHeights(sel)
{
    var currentTallest = 0,
         currentRowStart = 0,
         rowDivs = new Array(),
         $el,
         topPosition = 0;

     $(sel).each(function() {

       $el = $(this);
       topPostion = $el.position().top;

       if (currentRowStart != topPostion) {

         // we just came to a new row.  Set all the heights on the completed row
         for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
           rowDivs[currentDiv].height(currentTallest);
         }

         // set the variables for the new row
         rowDivs.length = 0; // empty the array
         currentRowStart = topPostion;
         currentTallest = $el.height();
         rowDivs.push($el);

       } else {

         // another div on the current row.  Add it to the list and check if it's taller
         rowDivs.push($el);
         currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest);

      }

      // do the last row
       for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
         rowDivs[currentDiv].height(currentTallest);
       }

     });
}

// Carica la mappa
function loadMap(el)
{
    var map = $(el),
        markers = [];

    if(map.length > 0) {
        // creo i markers
        map.find('ul').each(function(){
            var $this = $(this),
                lat   = parseFloat($this.find('li.lat span').text()),
                lon   = parseFloat($this.find('li.lon span').text()),
                txt   = $this.find('li.text').html();
            markers.push({
                latitude:  lat,
                longitude: lon,
                popup:     false,
                html:      txt,
                icon:      {
                                image:            baseUrl +'img/icons/icon-marker.png',
                                iconsize:         [58,56],
                                iconanchor:       [29,56],
                                infowindowanchor: [29,28]
                            }
            });
        });
        // aggiungo la mappa
        map.gMap({
            controls: ["GSmallMapControl", "GMapTypeControl"],
            markers:  markers,
            scrollwheel: false,
            zoom: 10
        });

    }
}

// funzione per il meteo
function getWeather()
{
    $('#logo').after('<div id="weather"></div>');
    var el = $('#weather');
    displayLoader(el);
    $.yql(
        "SELECT * FROM weather.woeid WHERE w='"+ locationId +"' AND u='c'",
        function (data){
            var item = data.query.results.rss.channel.item;
            hideLoader(el);
            el.html('<img src="'+ baseUrl +'img/weather/' + item.condition.code +'.png" alt="'+ item.condition.text +'" /><p><span class="temp">'+ item.condition.temp +' °C</span><span class="date hidden">'+ item.condition.date +'</span></p>');
        }
    );
}

