// News ticker
var swamp = function(){
    $('#newsticker li:first').animate({
        marginTop: '-27px'
    }, 500, function(){
        $(this).detach().appendTo('ul#newsticker').removeAttr('style');
        $('.juno', this).removeAttr('style');
        ticker();
    });
}
var ticker = function(){
    setTimeout(function(){
        var wdh = $('#newsticker li:first .juno').outerWidth();
        var spd = wdh * 15;
        if (wdh > 690) {
            $('#newsticker li:first .juno').animate({
                marginLeft: '-' + wdh + 'px'
                }, spd, 'linear', function(){
                swamp();
            });
        }
        else {
            setTimeout(function(){
                swamp();
            }, 3500);
        }
    }, 1500);
}
// Per le pagine interne: setta la voce di menu attuale
function gup(name) {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if (results == null) {
        return "";
    }
    else {
        $('#menutop li:nth-child('+results[1]+') a').addClass('active');
        return "";
    }
}
// Link mappa flash
function gotoMapFromItalyMicro(mappa){
    var pathname = location.pathname;
    var contesto;
    var slash1 = pathname.indexOf('/',1);
    var slash2 = pathname.indexOf('/',slash1 + 1);
    if (slash2 >0 && slash1 == 3){
        //lingua non default
        contesto = pathname.substring(0,slash2);
    } else {
        contesto = pathname.substring(0,slash1);
    }
    parent.location.href = "http://" + location.host + contesto + "/autostrade/traffico.do?mapLevel=micro&mappa=" + mappa;
}
function gotoMap(mappa) {
    var pathname = location.pathname;
    var contesto; //l'eventuale sottodominio /en/ per la versione inglese
    var slash1 = pathname.indexOf('/',1);
    var slash2 = pathname.indexOf('/',slash1 + 1);
    if (slash2 >0 && slash1 == 3){
        //lingua non default
        contesto = pathname.substring(0,slash2);
    } else {
        contesto = pathname.substring(0,slash1);
    }
    location.href = "http://" + location.host + contesto + "/autostrade/traffico.do?mapLevel=micro&mappa=" + mappa;
}
function isDifferent(frm){
    if (frm.dscDa.value != "" && frm.dscA.value != "" && frm.dscDa.value.toLowerCase() == frm.dscA.value.toLowerCase()) {
        alert('Specificare un Arrivo diverso dalla Partenza ');
        return false;
    } else {
        return true;
    }
}
// Setta posizione titoli news tab
function trigganuova() {
    $('.wraplinkajs a', this).each(function(){
        marle = $(this).height();
        $(this).css({
            'margin-top':'-'+marle/2+'px'
            });
    });
}
// Imposta swf object in modo rapido
function putflash(divid,movie,vwidth,vheight,bgcolor,vwmode) {
    $('#'+divid).flash({
        swf:movie,
        height:vheight,
        width:vwidth,
        bgcolor:bgcolor,
        allowfullscreen:"true",
        wmode:vwmode
    });
}
// Ruota i banner nel footer
function fadeBanner() {
    var elements= $('#banner_bot ul li').length;
    if(elements>1) {
        $('#banner_bot ul li:first').addClass('overthetop').removeClass('secondtop');
        $('#banner_bot ul li:nth-child(2)').addClass('secondtop');
        $('.overthetop').fadeOut(600,function(){
            $(this).detach().appendTo('#banner_bot ul').removeClass('overthetop').show();
        });
        setTimeout(function(){
            fadeBanner();
        },5100);
    }
}
$(document).ready(function(){
    gup('initPos');
    // associa i pannelli submenu al menu
    $('#menutop a').each(function(){
        var text = $(this).html();
        var url = $(this).attr('href');
        var name = $(this).parent().attr('class');
        $('#wrapmenu').append('<div class="selectedtab" id="tab_'+name+'"><a href="'+url+'">'+text+'</a></div>');
    });
    // prende le news da ruotare nel ticker
    $.getJSON('/autostrade/jsonBridge?srvc=jnews&nNews=4&lang=it', function(data) {
        $.each(data, function(i,item){
            $("#newsticker").append('<li><div class="feeddate">'+
                item.date+'</div><div class="feeditem"><span class="juno"><a href="'+item.link+'"><strong>'+
                item.location+'</strong> '+item.direction+' <strong>'+item.title+'</strong> '+item.description+'</a></span></li>');
        });
        ticker();
    });
    // rotazione banner spalla destra
    $('#bannerot ul').jcarousel({
        auto: 8,
        scroll: 1,
        wrap: 'last',
        easing:'easeOutSine',
        animation:600
    });

    // imposta le tab
    $("#tabs").tabs({
        idPrefix: 'ui-tabs-first',
        show: trigganuova
    });
    $("#home_news, #home_servizio, #home_iniziative, #home_consigli, #home_imprese, #home_focuson, #home_sicurezza").tabs();
    $('#home_news ul, #home_servizio ul, #home_iniziative ul, #home_consigli ul, #home_imprese ul, #home_focuson ul, #home_sicurezza ul').removeClass('ui-tabs-nav').addClass('ui-tabs-news');
    $('#home_news div, #home_servizio div, #home_iniziative div, #home_consigli div, #home_imprese div, #home_focuson div, #home_sicurezza div').removeClass('ui-tabs-panel').addClass('ui-tabs-pnl');
    $('.cercarticoli').each(function(){
        $(this).prev().addClass('ultimo');
    });
    // testo placeholder nei campi di ricerca
    $('.input').each(function() {
        var plch = $(this).attr('title');
        $(this).css('color','#ffcd9e').focus(function(){
            if($(this).val() == plch) {
                $(this).val('').removeAttr('style');
            }
        }).blur(function(){
            if(!$(this).val()) {
                $(this).css('color','#ffcd9e').val(plch);
            }
        }).val(plch);
    });
    // maschera per le webcam
    $('#elencoauto').click(function(){
        var maj = $('body').height();
        var offset = $('#elencoauto').offset();
        $('#maskview').show().animate({
            opacity: 0.3,
            height:maj
        },0);
        $('#conelenco').css({
            top: 20+offset.top,
            left: offset.left
        }).toggle();
        return false;
    });
    $('#maskview').click(function(){
        $('#conelenco').toggle();
        $(this).hide();
    });
    // cambia le webcam visualizzate in base alla strada scelta
    $('#conelenco a').click(function(){
        var nomeel = $(this).html();
        var bisban = nomeel.replace("'", "");
        var endig = bisban.replace(/\s/g, "");
        $('#webcam').empty().append('<ul id="'+endig+'"></ul>');

        $.getJSON($(this).attr('href'), function(data) {
            var token = data.token;
            $.each(data.tlcs, function(i,item){
                $("#"+endig).append('<li><a class="wc_info" href="#" onclick="window.open(\'/autostrade/popupTelecamera.do?tlc='+item.tlc+'&token='+
                    token+'\',\'webcam\',\'scrollbars=no,status=no,width=352,height=537\');return false;"><img width="110" height="70" src="'+
                    item.thumb+'" /><span>'+item.description+'</span></a></li>');
            });
            // fa ripartire jcarousel
            $("#"+endig).jcarousel({
                scroll: 1
            });
        });
        $('#currenthw').text($(this).text());
        $('#conelenco').toggle();
        $('#maskview').hide();
        return false;
    });
    // prende le top webcam
    $.getJSON('/autostrade/jsonBridge?srvc=homecams&op=tlcTmb&codArea=ALL&ntlc=30', function(data) {
        var token = data.token;
        $("#webcam").append('<ul id="Topwebcam"></ul>');
        $.each(data.tlcs, function(i,item){
            $("#Topwebcam").append('<li><a class="wc_info" href="#" onclick="window.open(\'/autostrade/popupTelecamera.do?tlc='+item.tlc+'&token='+
                token+'\',\'webcam\',\'scrollbars=yes,status=no,width=372,height=537\');return false;"><img width="110" height="70" src="'+
                item.thumb+'" /><span>'+item.description+'</span></a></li>');
        });
        $('#Topwebcam').jcarousel({
            scroll: 1
        });
    });
    // pannelli submenu
    $('#menutop a').mouseenter(function(){
        var pos = $(this).position();
        var rif = $(this).parent('li').attr('class');
        $('.selectedtab').css('display','none');
        $('.panopen').hide().removeClass('panopen');
        $('#tab_'+rif).css({
            'display': 'block',
            'left':(pos.left-7)
        });
        $('#pan_'+rif).addClass('panopen').show();
    });
    $('.panopen').live('mouseleave',function(){
        $(this).hide().removeClass('panopen');
        $('.selectedtab').css('display','none');
    });
    // Flash per WebTV
    var timetoken = Number(new Date());
    var flashvarWebcam = {
        buttonNames	: "i piu recenti,i piu visti,scelti per voi",
        buttonURLS	: "http://www.autostrade.it/videoXml/recenti-videoListSmall-it.xml?token="+timetoken+",http://www.autostrade.it/videoXml/visti-videoListSmall-it.xml?token="+timetoken+",http://www.autostrade.it/videoXml/scelti-videoListSmall-it.xml?token="+timetoken+"",
        tabNames	: "Previsioni di traffico,Grandi Opere,Sicurezza Stradale,Ambiente,Telepass,Nostre Campagne,Altri Video",
        tabURLS		: "http://www.autostrade.it/videoXml/previsioni-videoListSmall-it.xml?token="+timetoken+",http://www.autostrade.it/videoXml/grandi-opere-videoListSmall-it.xml?token="+timetoken+",http://www.autostrade.it/videoXml/sicurezza-stradale-videoListSmall-it.xml?token="+timetoken+",http://www.autostrade.it/videoXml/ambiente-videoListSmall-it.xml?token="+timetoken+",http://www.autostrade.it/videoXml/iniziative-commerciali-videoListSmall-it.xml?token="+timetoken+",http://www.autostrade.it/videoXml/nostre-campagne-videoListSmall-it.xml?token="+timetoken+",http://www.autostrade.it/videoXml/altri-video-videoListSmall-it.xml?token="+timetoken+"",
        xmlURL		: "/videoXml/sample.xml",
        skinURL		: "/videoXml/dark.swf",
		shareURL	: location.href,
		bgColor		: "0xD4E1E4",
		tabTextColor: "0x2677AA",
		tabOverColor: "0xBBC7CB",
		tabOutColor	: "0xF3F9FA",
		linkTextColor: "0x666666",
		bufferingTime: "4",
		noImageUrl	: "http://www.autostrade.it/video/warning.jpg",
		topBarStartX: "250"
    };
    $('#webcamplayer').flash({
        swf:'/videoXml/main.swf',
        height:406,
        width:485,
        bgcolor:'D5E0E4',
        flashvars:flashvarWebcam,
        allowfullscreen:"true"
    });
    // elimina parti lente
    if(!slowViaggio) {
        var flashvarsavia = {
            hostVar:''
        }
        $('#mapitaly').flash({
            swf:'flash/comuni/smallItaly_arancio-2.swf',
            height:320,
            width:221,
            bgcolor:'ff6600',
            flashvars:flashvarsavia
        });
    }
    if(slowViaggio) {
        $('.vg_perc,.vg_mete,.vg_aree').animate({
            'opacity':0.5
        }).removeAttr('href').addClass('disabled');
        $('.vg_traf').attr('href','/autostrade/realNews.do');
        $('#cercaviaggio').empty();
        $('#mapitaly').html('<a href="/autostrade/realNews.do"><img src="/images/italyslow.png" /></a>');
    }
    if(slowWebcam) {
        $('#wrapcam,#tit_topcam').remove();
    }
    trigganuova();
});

$(window).load(function () {
    if(zeroValid) {
        setTimeout(function(){
            $('#messaggioOpzione').slideDown(600);
            $('#rollOpzione').css({
                "background-image":"url('/i/opzione0/bot_apri_open.gif')"
            });
            show = true;
        },500);
        setTimeout(function(){
            $('#messaggioOpzione').slideUp(600);
            $('#rollOpzione').attr('style','');
            show = false;
        },10500);
    }
    // Fa partire la rotazione dei banner in footer
    fadeBanner();
    if(notiziari>0) { 
        $('#topradio').show();
    }
});
// Font replace per titoli
Cufon.replace('#menutop a', {
    textShadow: '1px 1px rgba(0, 0, 0, 0.5)',
    hover: true
});
Cufon.replace('.selectedtab,.eich3');


// Opzione Zero per avvisi
$(document).ready(function(){
    if(zeroValid) {
        show = false;
        var opzioneMsg = '<div id="opzioneZero"><div id="contOpzione">'
        +'<div id="closeOpzione">&nbsp;</div><div id="titoloOpzione">'+zeroTitle+'</div><div id="rollOpzione">&nbsp;</div></div>'
        +'<div id="messaggioOpzione"><div id="dataOpzione">'+zeroDate+'</div><p>'+zeroAbstract+'</p>'
        +'<div class="clr"></div></div>'
        +'</div>'
        $('#container').prepend(opzioneMsg);

        $('#rollOpzione').live('click',function(){
            //$('#messaggioOpzione').toggle(showOrHide);
            if(show){
                $('#messaggioOpzione').slideUp(600);
                $('#rollOpzione').attr('style','');
                show = false;
            } else {
                $('#messaggioOpzione').slideDown(600);
                $('#rollOpzione').css({
                    "background-image":"url('/i/opzione0/bot_apri_open.gif')"
                });
                show = true;
            }
        });
        var opzioneClose = '<div id="opzioneClose">&nbsp;</div>';
        $('#closeOpzione').live('click',function(){
            $('#opzioneZero').slideToggle(500);
            $('#container').before(opzioneClose);
        });
        $('#opzioneClose').live('click',function(){
            $('#opzioneZero').slideToggle(500);
            $(this).remove();
        });
    }
});
