
var Timer = {
	initialized : false,
	initialize : function(){
		if(Timer.initialized) return false;
		window.currentTime = parseInt($('#serverTime').attr('title'));
		window.currentDate = new Date(window.currentTime);
		Timer.listeners = [];
		Timer.running = false;
		Timer.initialized = true;
	},
	start : function(){
		if(Timer.running) return true;
		Timer.running = true;
		window.setTimeout( Timer.incrementTime, 1000 );
	},
	stop : function(){
		Timer.running = false;
	},
	addListener : function(listener){
		Timer.listeners.push(listener);
	},
	incrementTime : function(){
		if( ! Timer.running ) return false;
		window.currentTime += 1000;
		window.currentDate.setTime(window.currentTime);
		//$('#serverTime').html(window.currentDate.toLocaleTimeString());
        if(Timer.listeners.length){
			Timer.listeners.map(function(listener){listener.setCurrentTime(window.currentTime)})
		}
		window.setTimeout( Timer.incrementTime, 1000);
	}
}


var Countdown = function (abbrElement) {
    this.abbr = $(abbrElement);
    this.endTime = parseInt(this.abbr.attr('title'));
	this.ended = false;
    Timer.addListener( this );
};

Countdown.prototype.setCurrentTime = function( currentTime ){
    var remaining = this.endTime - currentTime;
	if(remaining <= 0){
		remaining = 0;
		if(! this.ended){
			this.ended = true;
			eval(this.abbr.attr('onended'));
		}
	}
    var remainingformated = (remaining/1000);
    var temp = remainingformated%3600;
    var timeHeures = (remainingformated - temp)/3600;
    var timeSecondes = temp%60;
    var timeMinutes = (temp - timeSecondes)/60;
    if (timeHeures >=24){
        var temp2 = timeHeures%24
        var timeJours = (timeHeures - temp2)/24;
        timeHeures = temp2;
        this.abbr.html( timeJours +' jours '+ timeHeures+ ' heures '+ timeMinutes+ ' minutes');
    }
    else{
        if (timeHeures < 1){
            if (timeMinutes < 1){
                this.abbr.html(timeSecondes+ ' secondes');
            }
            else{
            this.abbr.html(timeMinutes+ ' minutes');
            }
        }
        else{
        this.abbr.html(timeHeures+ ' heures '+ timeMinutes+ ' minutes');
        }
    }
}


var Counter = {
    initialized : false,
    initialize : function(){
        if(Counter.initialized) return false;
        window.currentCount = parseInt($('#countering').attr('title'));
        Counter.listeners = [];
        Counter.running = false;
        Counter.initialized = true;
    },
    start : function(){
        if(Counter.running) return true;
        Counter.running = true;
        window.setTimeout( Counter.incrementCount, 1000 );
    },
    stop : function(){
        Timer.running = false;
    },
    addListener : function(listener){
        Counter.listeners.push(listener);
    },
    incrementCount : function(){
        if( ! Counter.running ) return false;
        if(Counter.listeners.length){
            Counter.listeners.map(function(listener){listener.setCurrentCount(window.currentCount)})
        }
        window.setTimeout( Timer.incrementTime, 10000);
    }
}


var Countering = function (abbrElement) {
    this.abbr = $(abbrElement);
    this.ended = false;
    Counter.addListener( this );
};

Countering.prototype.setCurrentCount = function(currentCounting) {

            $.ajax({
                url : "/tournaments/counter",
                success : function(data){
                    console.log("tata");
                    if (data.counting !== currentCounting) {
                        this.abbr.html(data.counting);
                        console.log(data.couting);
                    }
                },
                dataType : "json"
            });
            return true;
}

window.NotificationCenter = {
	config : {
		container: '#one_tweet_block',
		insertMethod: 'html',
		postInsert: false,
		fetchUrl: '/notifications/last'
	},
	initialize : function(options){
		this.config = jQuery.extend(this.config, options || {});
		this.container = $(this.config.container);
		this.fetchLast();
	},
	fetchLast : function(){
		$.ajax({
			url : this.config.fetchUrl,
 			success : function(data){ this.addNotification(data);}.bind(this),
			dataType : "json"
		});
	},
	addNotification: function(notification){
		if(notification.type){
			var data = this.templates[notification.type][notification.subtype](notification.data);
			this.container[this.config.insertMethod](this.fillTemplate(data));
			if(this.config.postInsert) this.container[this.config.postInsert]();
		}else return false;
	},
	fillTemplate : function(data){
		return '<div class="alert alert-' + data.type +'">'+
			'<div class="alert-image icon-'+data.icon +'">'+
			(data.image ? '<img src="'+data.image+'" alt="">':'')+
			'</div>' +
			'<div class="alert-content"><span class="v-align">'+
			(data.link ? '<a href="'+data.link+'">':'') +
			data.message +
			(data.link ? '</a>':'') +
			'</span></div>' +
			'</div>';

	},
	templates : {
		'game': {
			'defy_direct' : function(data){
				return {
					type: 'warning',
					title:'Nouveau défi !',
					image: data.user.avatar,
					icon: 'empty-avatar',
					link: '/home/personallobby',
					message: '<em>'+data.user.pseudo + '</em> vous a lancé un défi à '+ data.amount+' €'
				}
			},
			'defy_matchmaking' : function(data){
				return {
					type: 'warning',
					title:'Nouveau défi !',
					image: data.user.avatar,
					icon: 'empty-avatar',
					link: '/home/personallobby',
					message: '<em>'+data.user.pseudo + '</em> vous a lancé un défi à '+ data.amount+' €'
				}
			},
			'cancelled' : function(data){
				return {
					type: 'error',
					title:'Défi annulé!',
					image: data.user.avatar,
					icon: 'empty-avatar',
					message: '<em>'+data.user.pseudo + '</em>  a annulé son défi.'
				}
			},
			'accepted' : function(data){
				return {
					type:'success',
					title:'Défi accepté!',
					image: data.user.avatar,
					icon: 'empty-avatar',
					link: '/home/personallobby',
					message: '<em>'+data.user.pseudo + '</em>  a accepté votre défi.'
				}
			},
			'report_result' : function(data){
				return {
					type: 'info',
					title:'Report de résultat',
					image: data.user.avatar,
					icon: 'empty-avatar',
					link: '/home/personallobby',
					message: 'Reportez le résultat du défi contre <em>' + data.user.pseudo +'</em>'
				}
			},
			'result_reported' : function(data){
				return {
					type: 'info',
					title:'Report de résultat',
					image: data.user.avatar,
					icon: 'empty-avatar',
					link: '/home/personallobby',
					message: 'Confirmez le résultat reporté par <em>'+ data.user.pseudo+'</em>'
				}
			},
			'results_contested' : function(data){
				return {
					type: 'error',
					title:'Contestation de résultat',
					image: data.user.avatar,
					icon: 'empty-avatar',
					link: '/home/contradiction?idc='+data.challenge_id+'&cc=1',
					message:'<em>'+ data.user.pseudo + '</em> a contesté votre report de résultat'
				}
			},
			'account_credited' : function(data){
				return {
					type: 'success',
					title:'Compte crédité',
					icon: 'account-credited',
					message: 'Votre compte à été crédité de ' + data.amount + ' €'
				}
			}
		},
		'tournament' : {
			'announce' : function(data){
				return {
					type: 'info',
					title : 'Prochain tournoi',
					icon: 'tournament',
					link: '/tournaments',
					message: 'Le tournoi <em>'+data.tournament.name+'</em> démarre bientôt, à '+data.tournament.startTime+'. N\'acceptez pas d\'autres défis d\'ici là !'
				}
			},
			'announce_general' : function(data){
				return {
					type: 'warning',
					title : 'Prochain tournoi',
					icon: 'tournament',
					link: '/tournaments',
					message: 'Le tournoi <em>'+data.tournament.name+'</em> démarre bientôt, à '+data.tournament.startTime+'. N\'acceptez pas d\'autres défis d\'ici là !'
				}
			},
			'start' : function(data){
				return {
					type: 'warning',
					title : 'Tournoi commencé',
					icon: 'tournament',
					link: '/tournaments',
					message: 'Le tournoi <em>'+data.tournament.name+'</em> commence dans quelques instants !'
				}
			}
		}
	}
}
window.Multee = window.Multee || {};

window.Multee.HomePage = {
	config : {
		itemDisplayCount : 5,
		itemPreLoadCount : 10,
		fetchUrl : '/feed/home',
		containerId : 'feed',
		elementIdPrefix : 'feed'
	},
	lastItemId : null,
	displayedItems : [],
	stackedItems : [],
	initialize : function(options){
		this.config = jQuery.extend(this.config, options || {});
		this.fetchMore(true);
	},
	updateDisplay :function(){
		this.insertRow();
		window.setTimeout(this.updateDisplay.bind(this),3000);
	},
	insertRow : function(){
		if(this.stackedItems.length > 0){
			var toDisplay = this.stackedItems.shift();
			this.displayedItems.unshift(toDisplay);
			while(this.displayedItems.length > this.config.itemDisplayCount){
				var toRemove = this.displayedItems.pop();
				$('#'+this.config.elementIdPrefix+toRemove.id).remove();
			}
			$(toDisplay.html).hide().prependTo('#'+this.config.containerId).fadeIn('slow')
			//$('#'+this.config.containerId).prepend(toDisplay.html);
		}
	},
	fetchMore : function(initial){
		var initial = initial || false;
		$.ajax({
			url : this.config.fetchUrl,
			data : {
				'lastid' : window.Multee.HomePage.lastItemId,
				'limit' : this.config.itemPreLoadCount
			},
 			success : function(data){
				window.Multee.HomePage.stackedItems = window.Multee.HomePage.stackedItems.concat(data);
				if(data.length > 0){
					window.Multee.HomePage.lastItemId = data[data.length -1].id;
				}
				if(initial){
					while(window.Multee.HomePage.displayedItems.length < this.config.itemDisplayCount && window.Multee.HomePage.stackedItems.length > 0){
						this.insertRow();
					}
					this.updateDisplay();
				}
			}.bind(this),
			dataType : "json"
		});
		window.setTimeout(this.fetchMore.bind(this),2000);
	}
}
window.Multee.StickyHeader = {
	initialize : function(){
		this.contentBlock = $('#big_content');
		this.offset = this.contentBlock.offset().top;
		this.headerBlock = $('#notifs');
		$(document).scroll(this.sticky.bind(this));
		this.sticky();
	},
	sticky : function(){
		this.headerBlock[$(window).scrollTop() > this.offset ? 'addClass' : 'removeClass']('sticky');
	}
}


// Initialisation apres chargement du dom
$(function () {
	Timer.initialize();
	Timer.start();
	$('.countdown').map(function (index, element) {
		new Countdown(element);
	});
	window.NotificationCenter.initialize();
	if($('#feed').length){
		window.Multee.HomePage.initialize();
	}else{
		if($('#one_tweet_block').length){
			//window.Multee.HomePage.initialize({itemDisplayCount:1,itemPreLoadCount:5,containerId:'one_tweet_block'});
			window.Multee.StickyHeader.initialize();
		}
	}
});
