/* change featured header */
FeaturedHeader = function(){
	this.first = false;
	this.previousId = false;
    this.ids=new Array();
    this.counter=0;
    this.timeout=false;
    this.firstDelay=5000;
    this.nextDelay=3000;
    this.delay=this.nextDelay;
	
    this.change = function(featuredId) {
        this._change(featuredId);
        if (this.timeout){
            clearTimeout(this.timeout);
        }
    }
	
    this._change = function(featuredId) {
        var currentId = false; 
        
        if (featuredId){
            currentId=featuredId;
        } else if (this.first) {
            currentId=this.first;
        }
        
        if (currentId && currentId != this.previousId){
            if (this.previousId){
                $('#'+this.previousId+'_link').toggleClass('selected');
            }
            this.previousId=currentId;
            $('#'+currentId+'_link').toggleClass('selected');
        
            var selectorPrefix='#' + currentId;
            var headline=$(selectorPrefix+ ' h1').html();
            var description=$(selectorPrefix+ ' h2').html();
            var title=$(selectorPrefix+ ' h3').html();
            var caption=$(selectorPrefix+ ' h4').html();
            var href=$(selectorPrefix+ '_link').attr('href');
            var src=$(selectorPrefix+ '_link img').attr('src');
            var wrapped=$('#featured_header');
            wrapped.css('background-image', 'url('+src+')');
            wrapped.click(function(){
                window.location=href;
            });
            $('#featured_header h2:first').html(headline);
            $('#featured_header p:first').html(caption + '<br />' +title + '<br />' + description);
            $('#featured_header a:first').attr('href', href);

            var optionalTitleImage=$(selectorPrefix+ ' h5');
            if (optionalTitleImage.length==1){
                var optionalTitleImageUrl=optionalTitleImage.html();
                if (optionalTitleImageUrl){
                    var wrappedImage=$('#featured_header img.big_title');
                    wrappedImage.attr('src', optionalTitleImageUrl);
                    wrappedImage.css('visibility','visible');
                }
            }
        }
    }
	this.put = function(featuredId) {
        if (!this.first){
            this.first=featuredId;
            this.ids=new Array();
        }
        
        this.ids.push(featuredId);
    }
    
    this.next = function() {
        this._change(this.ids[++this.counter%this.ids.length]);
    }
    
    this.carousel = function(){
        var instance=this;
        this.timeout=setTimeout(function(){
                    instance.next();
                    instance.carousel();
                   }, this.delay
                  );
        if (this.delay == this.firstDelay) this.delay=this.nextDelay;
    };
}

jQuery.fn.ellipsis = function() {
                return this.each(function()
                {
                        var el = $(this);

                        if(el.css("overflow") == "hidden")
                        {
                                var text = el.html();
                                var multiline = el.hasClass('multiline');
                                var t = $(this.cloneNode(true))
                                        .hide()
                                        .css('position', 'absolute')
                                        .css('overflow', 'visible')
                                        .width(multiline ? el.width() : 'auto')
                                        .height(multiline ? 'auto' : el.height())
                                        ;

                                el.after(t);

                                function height() { return t.height() > el.height(); };
                                function width() { return t.width() > el.width(); };

                                var func = multiline ? height : width;

                                while (text.length > 0 && func())
                                {
                                        text = text.substr(0, text.length - 1);
                                        t.html(text + "...");
                                }

                                el.html(t.html());
                                t.remove();
                        }
                });
        }
        
var changeWYSIWYGTables = function(){
    var found=$('.ce_text.block table.data_table');
    if (found.length>0){
        found.each(function(){
            var wrapped=$(this);
            
            wrapped.find('tbody tr').each(function(i){
                if (i%2==0){
                    $(this).children('td').css('background-color','#2D0E45');
                }
            });
        });
    }
}

var featuredHeader=new FeaturedHeader();
$(document).ready(
    function(){
        featuredHeader.carousel();
        $(".ellipsis").ellipsis();
        if ($.browser.msie) $(".ellipsis").css('display','inline');
        changeWYSIWYGTables();
    }
);

$(document).ready(
    function(){
        var clone=$('#header_placeholder');
        if ( clone.length>0 ){
            var replaceMe=$('div.main_area:first');
            if ($.browser.opera || $.browser.safari || $.browser.msie){//ugly workaround for firefox bug
                replaceMe.replaceWith(clone);
            } else {
                var html=clone.html();
                replaceMe.replaceWith(clone);
                replaceMe.html(html);
            }
            clone.css("visibility","visible");
        }
    }
);

/* countdown util */
function CountDown( secondsFrom1970 ) {
	// init target time
	var target			= new Date();
    target.setTime(secondsFrom1970*1000);
	this.targetTime		= target.getTime();
	/**
	 * refresh countdown
	 */
	this.refresh = function() {
		var today				 = new Date();
		var currentTime		   = today.getTime();
		// time left
		this._leftMilliseconds	= (this.targetTime - currentTime);
		this._leftSeconds		 = Math.floor( this._leftMilliseconds / 1000 );
		this._leftMinutes		 = Math.floor( this._leftSeconds / 60 );
		this._leftHours		   = Math.floor( this._leftMinutes / 60 );
		// no module
		this.leftDays			 = Math.floor( this._leftHours / 24 );
		// for print
		this.leftMilliseconds	 = this._leftMilliseconds % 1000;
		this.leftSeconds		  = this._leftSeconds % 60;
		this.leftMinutes		  = this._leftMinutes % 60;
		this.leftHours			= this._leftHours % 24;
	}
	this.refresh();
}


$(window).load(
    function(){
        if ($.browser.mozilla){
            try{
                $.each($('li > table, div > table'), function(index,element){
                    var wrapped=$(element);
                    var prev=wrapped.prev('a');
                    var next=wrapped.next('a');
                    if (next.length==1 && prev.length==1){
                        if (prev.attr('href') == next.attr('href')){
                            next.remove();
                            wrapped.remove().appendTo(prev);
                        }
                    }
                });
            } catch (exception){}
        }
    }
);

var ANIMATE_FORECAST_TIMEOUT=5000;
var currentForecast={};

var animateForecast = function(id){
    var forecasts=$('#meteo_'+id+'_info > ul > li');
    current=currentForecast[id];
    next=currentForecast[id]+1;
    if (next>2) next=0;
    
    $(forecasts[current]).fadeOut('slow', function(){
        $(forecasts[next]).fadeIn('slow', function(){
            currentForecast[id]=next;
            setTimeout(function(){animateForecast(id);}, ANIMATE_FORECAST_TIMEOUT);
        });
    });
    
}

initMeteo = function(id){
    $.get('/system/modules/meteo/feeds/data/meteo_fiorentina.json',
          {'r': Math.random()},
          function(data){
            var forecast=eval('['+data+']');
            forecast=forecast[0]['bollettino'];
            
            var title=forecast['@attributes'].name.substring(17);
            $('#meteo_'+id+'_info > span').html(title);
            
            var date=forecast.previsione['@attributes'].data.substring(0,5);
            $('#meteo_'+id+'_morning > span.heading').html(date+' - Mattina');
            $('#meteo_'+id+'_afternoon > span.heading').html(date+' - Pomeriggio');
            $('#meteo_'+id+'_night > span.heading').html(date+' - Sera');

            var icon=forecast.previsione.mattina.fenomeni.cielo;
            $('#meteo_'+id+'_morning > div > img').attr('src', '/system/modules/meteo/ico/'+escape(icon)+'.jpg');
            icon=forecast.previsione.pomeriggio.fenomeni.cielo;
            $('#meteo_'+id+'_afternoon > div > img').attr('src', '/system/modules/meteo/ico/'+escape(icon)+'.jpg');
            icon=forecast.previsione.sera.fenomeni.cielo;
            $('#meteo_'+id+'_night > div > img').attr('src', '/system/modules/meteo/ico/'+escape(icon)+'.jpg');

            var t=forecast.previsione.mattina.fenomeni.temperatura;
            var u=forecast.previsione.mattina.fenomeni.umidita;
            var v=forecast.previsione.mattina.fenomeni.vento;
            $('#meteo_'+id+'_morning > span.info').html('<br />Temp: '+t+'<br />Umidit&agrave;: '+u+'<br />Vento: '+v);
            t=forecast.previsione.pomeriggio.fenomeni.temperatura;
            u=forecast.previsione.pomeriggio.fenomeni.umidita;
            v=forecast.previsione.pomeriggio.fenomeni.vento;
            $('#meteo_'+id+'_afternoon > span.info').html('<br />Temp: '+t+'<br />Umidit&agrave;: '+u+'<br />Vento: '+v);
            t=forecast.previsione.sera.fenomeni.temperatura;
            u=forecast.previsione.sera.fenomeni.umidita;
            v=forecast.previsione.sera.fenomeni.vento;
            $('#meteo_'+id+'_night > span.info').html('<br />Temp: '+t+'<br />Umidit&agrave;: '+u+'<br />Vento: '+v);
            
            var d = new Date();

            var h = d.getHours();
            if (h < 12){//to 11:59
                currentForecast[id]=0;//morning
            } else if (h >= 18) {//from 18:00
                currentForecast[id]=2;//night
            } else {
                currentForecast[id]=1;//afternoon
            }

            var forecasts=$('#meteo_'+id+'_info > ul > li');
            $(forecasts[currentForecast[id]]).show();
            $('#meteo_'+id+' .wload').hide();
            $('#meteo_'+id+'_info').show();
            
            setTimeout(function(){animateForecast(id);}, ANIMATE_FORECAST_TIMEOUT);
            
          })
}


