/*
Permet de modifier:

	- le nombre de colonne (par défaut 2)
	- le nombre l'affichage des infos
*/

(function() {
    if ($.browser.ie){
	    var e = "abbr,article,aside,audio,bb,canvas,datagrid,datalist,details,dialog,eventsource,figure,footer,header,hgroup,mark,menu,meter,nav,output,progress,section,time,video".split(','),
	    i = e.length;
	    while (i--) {
	        document.createElement(e[i]);
	    }
	}
	
	//array remove function
	/*Array.prototype.remove = function (subject) {
		var r = new Array();
		for(var i = 0, n = this.length; i < n; i++)
		{
			if(!(this[i]==subject))
			{
				r[r.length] = this[i];
			}
		}
		return r;
	}*/
})();

(function(){
	var scroll = function(){
		this.winHeight = null;
		this.$window = $(window);
		this.$document = $(document);
		
		this.$page = null;
		this._iH = 0;//interval hide
		this._iS = 0;//interval show
		
		this._pages = {scroll:[],pageNbr:[]};//[scrollTop,pageNumber]
		
		this._page = 1;
		this._precision = 850;
		this._loading = false;
		
		this._onUpdateCallBack = [];
		// [['','',''],{lastfm:,twitter:,delicious,}]
	};
	
	scroll.prototype.setPage = function(i){
		this._page = i;
	};
	
	scroll.prototype.init = function(precision){
		this.winHeight = this.$window.height();
		
		this._precision = precision?precision:this._precision;
		
		this.$window.bind('scroll.infscr', function(){ _.scroll._scroll.call(_.scroll);});
		
		if(_.$right.find('#page').length == 0){
			this.$page = _.$right.append('<span id="page"></span>').find('#page');
		}
		console.debug(this.$page);
		
	};
	
	scroll.prototype._isNearBottom =function(){
		return (this.$window.scrollTop() >= this.$document.height() - this.winHeight - this._precision);
	};
	
	scroll.prototype.isNearElement = function(jQelement,precision){
		if(!precision)
			precision = 100;
			//this.$window.scrollTop(),
			//(jQelement.offset()).top
		console.debug(jQelement);
		//return (this.$window.scrollTop() - (jQelement.offset()).top < 0);
		return true;
	};
	
	scroll.prototype._notifHide = function(){
		//this.$page.stop().animate({opacity:0},300);
		_.$content.removeClass('scrolling');
	};
	
	scroll.prototype._scroll = function(){
		var ctx = this;
		
		
		if(this._iS === 0){
			
			var p = 1,_scroll = _.scroll.$window.scrollTop()-500, iM = this._pages.scroll.length;
			
			for(var i = 0; i < iM; i++){
				if(_scroll <= this._pages.scroll[i]){
					//console.debug(_scroll,'<=',this._pages.scroll[i]);
					p = this._pages.pageNbr[i];
					//console.debug(p);
					break;
				}
			}
			
			_.$content.addClass('scrolling');
			this.$page.text('Page '+ p);
			
			this._iS = window.setTimeout(function(){
					clearTimeout(ctx._iS);
					ctx._iS = 0;
					
			},500);
			
			if(this._iH === 0){
				this._iH = window.setTimeout(function(){
					ctx._notifHide();
					clearTimeout(ctx._iH);
					ctx._iH = 0;
				},5000);				
			}

		}
		
		
		if(this._isNearBottom() && !this._loading){
			this._loading = true;
			
			$('#more').html('Loading...');
			
			this._pages.scroll.push(this.$document.height()-10);
			this._pages.pageNbr.push(this._page);
			this._page++;
			jQuery.get('/lifestream/ajax.php',{'p':this._page},function(data){
				$('#more').remove();
				_.scroll.$window.scrollTop(_.scroll.$window.scrollTop() - 10);
				window.setTimeout(function(){_.scroll._loading = false;},1000);
				//alert(data);	
				_.$center.append(data+'<a href="/?p='+ctx._page+'" id="more">more</a>');
				$('#more').click(function(){ctx._scroll();return false;});
				
				//run callback
				ctx.onUpdate();
			});
		}
	};

	scroll.prototype.onUpdate = function(callback,context){
		if(callback){
			this._onUpdateCallBack.push([callback,context]);
		}else{
			for(var i = this._onUpdateCallBack.length-1;i>= 0;i--){
				this._onUpdateCallBack[i][0].call(this._onUpdateCallBack[i][1]);
			}
		}
	};
	
	this.scroll = new scroll();
}).call(_);

(function(){
	
	var lifestream = function(){
		this._items = [[],{}];
		
		this._$h2 = null;
		// [['','',''],{lastfm:,twitter:,delicious,}]
		
		this._$menuli = null;
	};
	
	
	
	lifestream.prototype._initItem = function(){
		this._items = [[],{}];
		
		this._$menuli = $('#header-menu ul li');
		
		var ctx = this;
		
		this._$menuli.each(function(id,el){
			$el = $(el);
			
			var $a = $el.find('a');
				rev = $el.attr('rev'),
				$span = null;
			
			if($el.find('span').length == 1)
				$span = $el.find('span').text('').addClass('notif').hide();
			else
				$span = $el.prepend('<span></span>').find('span').addClass('notif').hide();
			
			$a.unbind('click.awaitingItemsRelease');
			
			ctx._items[1][rev] = [0,$span,$a];
		});
	};
	
	
	
	//item : "<article>...</article>"
	lifestream.prototype.addItem = function(item,type){
		//If scroll
		/*
			_items[1][type] = [nbr, (span)jQueryPointer, (a)jQueryPointer];
		*/
		
		if(_.scroll.$window.scrollTop() <= 400 && this._items[0].length == 0){
			_.$center.prepend(item);
		}
		else{
			this._items[0].push(item);

			if(!this._items[1][type]){//pas dans la liste
				var $span = $('ul','#header-menu')
								.append('<li rev="' + type + '"><span></span>'+
											'<a href="/" class="sp32 sp' + type + '_32">' + type + '</a></li>')
								.find('span:last')
								.addClass('notif')
								.hide(),
					$a = $('ul li a:last','#header-menu');
				$a.bind('click.default',function(){return false;});
				
				this._items[1][type] = [1,$span,$a];
			}
			else
				this._items[1][type][0]++;
				
			this._awaitingItems();
		}
	};
	
	lifestream.prototype._awaitingItems = function(){
		var html = null, ctx = this;
		if($('#awaitingItems').length == 0){
			html = '<article id="awaitingItems" class="post"><a href="javascript:;"></a></article>';
			var tmp = 0;
			tmp = _.scroll.$window.scrollTop();
			console.debug('avt prepend',tmp);
			_.$center.prepend(html);
			
			//scroll
			var tmp2 = _.scroll.$window.scrollTop();
			//console.debug('apre prepend',tmp2,$("#awaitingItems").height(),tmp2 - $("#awaitingItems").height());
			//_.scroll.$window.scrollTop(tmp2 - $("#awaitingItems").height());
			this._$h2 = $('a','#awaitingItems');//cache
			
			this._$h2.click(function(){ctx.release();});
		}
		
		html  = '<span class="awaitingTxt">'+this._items[0].length + ' awaiting item' + (this._items[0].length!==1?'s':'')+'</span>';
		
		html += '<ul>';
		for(type in this._items[1]){
			if(this._items[1][type][0] > 0){
				html += '<li class="sp32 sp' + type + '_32"><span>'+ this._items[1][type][0] +'</span></li>';
				
				
				//menu span
				this._items[1][type][1]
					.text(this._items[1][type][0])
					.show();
				
				//menu a
				this._items[1][type][2]
					.unbind('click.awaitingItemsRelease')
					.bind('click.awaitingItemsRelease', function(){ctx.release.call(ctx);return false;});			
			}

		}
		
		var ctx2 = this;
		
		html += '</ul><div class="clear"></div>';
		
		this._$h2.html(html);
	};
	
	
	lifestream.prototype.release = function(e){
		var ctx = this;
		
		if(_.scroll.$window.scrollTop() > 400)
			$.scrollTo({top:0},
				{easing:'easeOutCirc',
				axis:'y',
				margin:true,
				duration:3000,
				onAfter:function(){
					//quick & dirty
					$('#awaitingItems').hide(500);
				
					window.setTimeout(function(){
						ctx._release.call(ctx,e);
					},1000);
				}
			});
		else{
			$('#awaitingItems').hide(500,function(){
				ctx._release.call(ctx,e);
			});
		}
		
		return false;
	};
	
	lifestream.prototype._release = function(e){
		var html = '', i = this._items[0].length-1;
		for(;i >= 0;i--){
			html += this._items[0][i];
		}

		this._initItem();

		$('#awaitingItems').remove();
		_.$center.prepend(html);
	};
	
	
	this.lifestream = new lifestream();
	this.lifestream._initItem();
}).call(_);

$(function(){
	_.scroll.init.call(_.scroll);
	/*
	_.lifestream.addItem('test','linkedin');
	_.lifestream.addItem('test','friendfeed');
	_.lifestream.addItem('test','lastfm');
	_.lifestream.addItem('test','lastfm');
	_.lifestream.addItem('test','lastfm');*/
});