/* 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);
            
			var pW=wrapped.parent().width();
			
			if (pW<wrapped.width()){
				wrapped.width(pW);
			}
			
            wrapped.find('tbody tr').each(function(i){
                if (i%2==0){
                    $(this).children('td').addClass('even');
                }
            });
        });
    }
}

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){}
        }
		
		//refine containers
		var container=$('div.details_big');
		if (container.length>0){
			var containerBottom=container.position().top+container.height();
			var maxB=containerBottom;
			container.find('*').each(function(i, e){
				var wrapped=$(e);
				var eBottom=wrapped.position().top+wrapped.height();
				if (maxB<eBottom) maxB=eBottom;
			});

			if (containerBottom<maxB){
				container.height(container.height()+(maxB-containerBottom));
			}   
		}
	}
);

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, dictionary){
    $.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+' - '+dictionary['Mattina']);
            $('#meteo_'+id+'_afternoon > span.heading').html(date+' - '+dictionary['Pomeriggio']);
            $('#meteo_'+id+'_night > span.heading').html(date+' - '+dictionary['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 />'+dictionary['Temp']+': '+t+'<br />'+dictionary['Umidita']+': '+u+'<br />'+dictionary['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 />'+dictionary['Temp']+': '+t+'<br />'+dictionary['Umidita']+': '+u+'<br />'+dictionary['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 />'+dictionary['Temp']+': '+t+'<br />'+dictionary['Umidita']+': '+u+'<br />'+dictionary['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);
            
          })
}

$(document).ready(
    function(){
    
        var test=$('#news_ticker');
        if (test.size()==0) return;
        
        var BLOCK_SIZE=6;
        var total_blocks=0;
        var current_block=0;
        var total=0;
        var current=0;
        var ANIMATE_DURATION=300;
        var FADE_DURATION=300;
        var ANIMATION_TIMEOUT=3000;
        var timeout=false;
        
        var TITLE_IDS_PREFIX='news_ticker_title_';
        var TEXTS_IDS_PREFIX='news_ticker_texts_';
        
    
        var body=$('#news_ticker div.ticker_body');
        var container=$('#news_ticker div.ticker_titles ul');
        var prevButton=$('#news_ticker div.ticker_prev');
        var nextButton=$('#news_ticker div.ticker_next');
        var lis=container.children('li');
        var newWidth=parseInt(body.width()*lis.size()/BLOCK_SIZE);
        container.width(newWidth);   
        total_blocks=lis.size()/BLOCK_SIZE;
        total=lis.size();
        
        var textDivs=$('#news_ticker div.ticker_texts div');
        textDivs.hide();
        $(textDivs[0]).fadeIn();
        
        var setButtonsStatus=function(){
            if (current_block==0){
                prevButton.addClass('disabled');
                nextButton.removeClass('disabled');
            } else if (current_block==total_blocks-1){
                nextButton.addClass('disabled');
                prevButton.removeClass('disabled');
            } else {
                prevButton.removeClass('disabled');
                nextButton.removeClass('disabled');
            }
        }
        
        var activateFirstInBlock=function(){
            click($('#'+TITLE_IDS_PREFIX+(current_block*BLOCK_SIZE)));
        }
        
        var animateBlock=function(direction){
            current_block+=direction;
            var currentLeft=parseInt(container.css('left'));
            var newLeft=currentLeft-body.width()*direction;
            container.animate({'left': newLeft+'px'}, ANIMATE_DURATION, activateFirstInBlock);
            setButtonsStatus();
        }
        
        var next=function(){           
            if (current_block<total_blocks-1) {
                animateBlock(1);
            }
        };
        nextButton.click(function(){
            if (!nextButton.hasClass('disabled')){
                if (timeout) clearTimeout(timeout);
                next();
            }
        });
        var prev=function(){           
            if (current_block>0) {
                animateBlock(-1);
            }
        };
        prevButton.click(function(){
            if (!prevButton.hasClass('disabled')){
                if (timeout) clearTimeout(timeout);
                prev();
            }
        });

        var click=function(source){
            var wrapped=$(source);
            
            var findMeSelector='#'+wrapped.attr('id').replace(TITLE_IDS_PREFIX, TEXTS_IDS_PREFIX);
            
            if (findMeSelector!='#news_ticker_texts_'+current){
                current=findMeSelector.substring(TEXTS_IDS_PREFIX.length+1);
                lis.removeClass('active');
                wrapped.addClass('active');
                var wrappedTexts=$(findMeSelector);
                $('#news_ticker div.ticker_texts div:visible').fadeOut(FADE_DURATION, function(){
                    wrappedTexts.fadeIn(FADE_DURATION);
                });
                setButtonsStatus();
             }
        }
        $('#news_ticker div.ticker_titles li').click(function(){
            if (timeout) clearTimeout(timeout);
            click(this);
        });
        
        $(lis[0]).addClass('active');
        setButtonsStatus();
        
        var animate=function(){
            var nextIndex=parseInt(current)+1;
            if (nextIndex==total){
                current_block=0;
                container.animate({'left': '0px'}, ANIMATE_DURATION, activateFirstInBlock);
                timeout=setTimeout(animate, ANIMATION_TIMEOUT);
                setButtonsStatus();
            } else if (nextIndex>0 && nextIndex%BLOCK_SIZE!=0){
                click($('#'+TITLE_IDS_PREFIX+nextIndex));
                timeout=setTimeout(animate, ANIMATION_TIMEOUT);
            } else {
                next();
                timeout=setTimeout(animate, ANIMATION_TIMEOUT+ANIMATE_DURATION);
            }
        }
        
        timeout=setTimeout(animate, ANIMATION_TIMEOUT);
        $('#news_ticker div.loader').hide();
    }
);

$(window).load(function(){

    var fbILikeWrapped=$('#fb_i_like');
    if (fbILikeWrapped.size()==1){
        fbILikeWrapped.append('<div><iframe src="http://www.facebook.com/plugins/like.php?href='+escape(window.location)+'&amp;layout=button_count&amp;show_faces=false&amp;width=190&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=54" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:190px; height:54px;" allowTransparency="false"></iframe></div>');
    }

    var fbILikeWrapped=$('#fb_i_like_noface');
    if (fbILikeWrapped.size()==1){
        fbILikeWrapped.append('<div><iframe src="http://www.facebook.com/plugins/like.php?href='+escape(window.location)+'&amp;layout=button_count&amp;show_faces=false&amp;width=120&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=90" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:120px; height:20px;" allowTransparency="false"></iframe></div>');
    }

    var fbShareWrapped=$('#fb_share');
    if (fbShareWrapped.size()==1){
        if (!$.browser.msie) fbShareWrapped.append('<a name="fb_share" type="button_count" href="http://www.facebook.com/sharer.php">Condividi</a>');
        fbShareWrapped.append('<script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script>');
    }

    var tShareWrapped=$('#t_share');
    if (tShareWrapped.size()==1){
        tShareWrapped.append('<a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>');
    }
});

$(document).ready(
    function(){
		$('li.match tr.mbuttons div').click(function(event){
		
			//event.preventDefault();
			var div=$(this);
			var link=$(div.parents('a'));
			var what=false;
			if (div.hasClass('highlights')){
				what="hl";
			} else if (div.hasClass('moviola')){
				what="mv";
			} else if (div.hasClass('realtime')){
				what="st";
			} else if (div.hasClass('results')){
				what="st&results=true";
			} else if (div.hasClass('biglietteria')){
				link.attr('href', '/biglietteria.html');
			}
			
			if (what) link.attr('href', link.attr('href')+'?what='+what);
			link.click();
			
		});
    }
);

