/*
 * glpgs screen maker
 * version 0.2.0 (2011/04/07)
 * Author: Kota Naito (kota.naito@glpgs.com)
 * Requires jQuery v1.5.1 or later
 * 
 * WATASI HA HOMU HOMU HA DESU!!
*/

var GlpgsScreen = function(_options){

/*
 * private members
*/
	var options = {
		// スクリーンを設置するHTML要素のID
		baseID: "",
		// ナビ部分として使用するh1タグのクラス名
		pageName: "page_name",
		// 作成するナビ部分(ulタグ)のクラス名
		navName: "nav_list",
		// 最初に表示するページの番号
		firstPage: 1,
		// 画面遷移アニメーションにかける時間(ミリ秒)
		animation: 1000,
		// 自動ページ送り(ミリ秒・0なら停止)
		autoPagerize: 0
	};
	var self = this;
	var base;
	var pageTimer;
	var numPages;
	var numShow;

/*
 * public methods
*/
	// 指定された画面を表示
	this.showPageAt = function(index, animation){
		// サニタイズ
		if(typeof(index)!=="number"){
			return;
		}
		if(typeof(animation)!=="number"){
			animation = options.animation;
		}
		if(typeof(numShow)!=="number"){
			numShow = 0;
		}
		// ナビ部分の背景変更
		$("ul."+options.navName+" li", base).each(function(i,e){
			$(e).css({backgroundPosition:(i==index)
				?-$(e).width()+"px "+($(e).height()*-i)+"px"
				:"0 "+($(e).height()*-i)+"px"
			});
		});
		// 画面変更
		for(var i=0; i<numPages; i++){
			if($("article:eq("+i+")", base).queue().length != 0){
				$("article:eq("+i+")", base).stop(true, true);
				$("article:eq("+i+")", base).show().hide();
			}
		}
		$("article:eq("+numShow+")" ,base).fadeOut(animation/2, function(){
			$("article:eq("+index+")" ,base).fadeIn(animation/2);
		});
		// numShow更新
		numShow = index;
		// 自動ページ送り設定
		this.setPagerize();
	};
	// 表示している画面番号の取得
	this.getNumShow = function(){
		return numShow;
	};
	// 次の画面の表示
	this.showNextPage = function(){
		self.showPageAt((numShow+1)%numPages);
	};
	// 前の画面の表示
	this.showPrevPage = function(){
		self.showPageAt((numShow+numPages-1)%numPages);
	};
	// ページ送りを設定
	this.setPagerize = function(speed){
		clearTimeout(pageTimer);
		if(typeof(speed) === "number"){
			option.autoPagerize = speed;
		}else if(typeof(speed) !== "undefined"){
			return;
		}
		if(options.autoPagerize != 0){
			pageTimer = setTimeout(self.showNextPage, options.autoPagerize);
		}
	};

/*
 * constructor
*/
	(function(){
		// オプション設定反映
		if(typeof(_options)==="object"){
			for(var key in _options){
				if(typeof(options[key])===typeof(_options[key])){
					options[key] = _options[key];
				}
			}
		}
		if(options.baseID === ""){
			// baseIDが指定されていなければ動作しない
			return;
		}else{
			base = $("#"+options.baseID);
		}
		// 画面名取得
		var pageNames = [];
		$("article", base).each(function(i,e){
			pageNames.push($("."+options.pageName, e).text());
			$("."+options.pageName, e).remove();
		});
		// 画面作成
		var nav_ul = $("<ul class='clearfix "+options.navName+"'>")
			.insertBefore($("*:first", base));
		$.each(pageNames, function(i,e){
			$("<li>")
				.text(e)
				.click(function(){self.showPageAt(i)})
				.appendTo($(nav_ul));
		});
		numPages = pageNames.length;
		self.showPageAt(options.firstPage, 0);
	})();
};

