/*-----------------------------------------------------
    NewsLister newslister.js
	
	@version    1.0.4
	@copyright Tenderfeel
	@author Tenderfeel(tenderfeel@gmail.com)
	@link http://tenderfeel.xsrv.jp/
	
	1.0.3 -> 1.0.4
	 + pagenaviのshow()とhide()をimplement
	 * ログ件数count追加に伴なう修正
	1.0.2 -> 1.0.3
	 * pagenaviのXHRでviewtypeを送信してなかった
	 * pagenaviの挿入条件修正
	1.0.1 -> 1.0.2 
	 + 日時をDateクラスに変更
	 + 出力形式分岐をPHPと同一に
	 + create_paragraphメソッド
	 * ログがdispmax以下の場合pagenaviの出力をしない 
	1.0.0 -> 1.0.1
	 - 都度リクエストする方法に戻した
------------------------------------------------------*/	

/*//////////////// O P T I O N S ///////////////////////

	logarea   :  ログ表示要素のID
	pass      :  feed.phpまでのパス
	loader    :  ローデイング画像
	method    :  ログ読み込み時のメソッド
	style     :  ログの出力形式(ul,table,dl)
	dateformat:  日時フォーマット
	diff      :  経過時間の表示
	max       :  ログの最大表示数
	
///////////////////////////////////////////////////////*/


var NewsLister = new Class({
	
	//implements
	Implements: [Options],

	//options
	options: {
		logarea:"newslister",
		pass:'newslister/feed.php',
		loader:'<img src="newslister/include/images/loader.gif" width="128" height="15" alt="Loading" />',
		method:'get',
		style:null,
		dateformat:"%Y/%m/%d",
		diff:false,
		dispmax:3
	},
	
	//initialization
	initialize: function(options) {
		//set options
		this.setOptions(options);
		
		this.logarea = $(this.options.logarea);
		this.logareaTween = new Fx.Tween(this.logarea,{'property':"opacity",'link':"cancel"});
		this.pass = this.options.pass;
		this.method = this.options.method;
		this.dispmax = this.options.dispmax;
		this.loader = this.create_loading();
		this.length = null;
		this.pageNavi = null;
		this.request = this.createRequest();
		
		this.loader.inject(this.logarea,"top");
				
		if( Browser.Engine.trident && Browser.Engine.version <= 4)
			this.logarea.set("html","ご利用中のブラウザバージョンには未対応です。<br /><a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyID=341c2ad5-8c3d-4347-8c03-08cdecd8852b&DisplayLang=ja\" target=\"_blank\" class=\"ie8update\">今すぐ最新版にアップデート！</a>");
		else
			this.request.send({data:{"viewtype":"json","page":0,"max":this.options.dispmax}});
	},
	
	//ローディングバー
	create_loading:function(){
		
		return new Element("p",{'id':"loader",'html':this.options.loader,'styles':{"margin":20,"text-align":"center"},"morph":{duration: 500,'link':"cancel"}});
	},
	
	//JSONP
	createRequest: function() {
		var logarea = this.logarea;
		var self = this;
		
		return new Request.JSONP({
			url:this.pass,
			timeout:1200,
			method:this.method,
			onRequest: function(){
				self.loader.morph({'height':15, 'opacity': 1, 'padding': 20});
			},
			onSuccess: function(txt) {
				self.loader.morph({'height':0, 'opacity': 0, 'padding': 0});//ローディングバー非表示
				if(self.logarea.getChildren()) self.logarea.getChildren().destroy();//既存段落削除
					
				if($type(txt.items)!==false){
					self.length = true;
					
					self.create_paragraph(txt.items).inject(logarea);
					
					if(!self.pageNavi && txt.count > self.options.dispmax) self.create_pagenavi(txt.pagenum);
				}
			},
			onFailure: function(el) {
				if(self.length === true) return;
				logarea.set("html","<p class=\"error\">Error:Data not found.</p>");
				self.loader.morph({'height':0, 'opacity': 0, 'padding': 0});//ローディングバー非表示
			}
		});
	},
	
	create_paragraph:function(items){
		
		switch(this.options.style){
			
			case "ul":
				var c = new Element("ul");
			
				$each(items,function(ite,i){
					var diff = (this.options.diff)? '<span class="diff">'+ this.showDiffDate(ite.date) +'</span>':'';
					new Element("li",{'html':'<em class="date">'+this.showLocalDate(ite.date)+'</em><strong>'+ite.comment+'</strong>'+diff}).inject(c);
							
				}.bind(this));
				
				return c;
			
			break;
			
			case "table":
			
				var c = new Element("table");
			
				$each(items,function(ite,i){
					
					var r = new Element("tr");		 
									 
					new Element("th",{'class':'date','scope':'row','html':this.showLocalDate(ite.date)}).inject(r);
					new Element("td",{'html':ite.comment}).inject(r);
					if(this.options.diff)
						new Element("td",{'class':'diff','html':this.showDiffDate(ite.date)}).inject(r);
						r.inject(c);
				
				}.bind(this));
				
				return c;
			
			break;
			
			default:
				var c = new Element("dl");
			
				$each(items,function(ite,i){
					new Element("dt",{'class':'date','html':this.showLocalDate(ite.date)}).inject(c);
					new Element("dd",{'html':ite.comment}).inject(c);
					if(this.options.diff)
						new Element("dd",{'class':'diff','html':this.showDiffDate(ite.date)}).inject(c);
				}.bind(this));
				
				return c;
		}
		
	},
	
	//ページナビ///////////////////////////////////
	create_pagenavi:function(pmax){
		
		var self = this;
		var current = 0;
		this.pageNavi = new Element("ul",{'class':"pagelink"});
		
		//前へ
		var prev = new Element("li",{'class':'prev'}).grab(new Element("a",{'html':"&laquo;Prev", 'href':"#",
					events:{
						"click":function(e){
							e.stop();
							current--;
							self.logareaTween.start(0)
							.chain(function(){self.request.send({'data':{"viewtype":"json","page":current,"max":self.options.dispmax}});self.logareaTween.start(1);});
							if(current >= 2 || current != 0) prev.show();
								else this.getParent().hide();
							if(current < pmax) next.show();
							
						}
					}
				})).inject(self.pageNavi,"top").hide();
		
		//次へ
		var next = new Element("li",{'class':'next'}).grab(new Element("a",{'html':"Next&raquo;", 'href':"#",
					events:{
						"click":function(e){
							e.stop();
							current++;
							self.logareaTween.start(0)
							.chain(function(){self.request.send({'data':{"viewtype":"json","page":current,"max":self.options.dispmax}});self.logareaTween.start(1);});
							if(current >= 2 || current != 0) prev.show();
							if(current < pmax) next.show();
								else this.getParent().hide();
						}
					}
				})).inject(this.pageNavi);
		this.pageNavi.inject(this.logarea,"before");
	},
	showLocalDate:function(timestamp){
		var dt = new Date(timestamp * 1000);
		return dt.format(this.options.dateformat);
	},
	showDiffDate:function(timestamp){
		var dt = new Date(timestamp * 1000);
	  	return dt.timeDiffInWords();
	}
	
});

Element.implement({
	'show':function(){
		return this.setStyle("display","block");
	},
	'hide':function(){
		return this.setStyle("display","none");
	}
});


