/*!
 * Copyright 2011, Root-Sea
 */

////// イメージリストのクラス //////

function RSImgeList(id, w, h, interval, fade) {
	//インターバル (分母にFPSを記入)
	//jQuery.fx.interval = Math.floor(1000 / 24);
	
	//現在のページ番号
	this.current = 1;
	
	//ID
	this.id = id;
	
	//タイプ horizontal or vertical
	this.type = "horizontal";
	
	//スライドショーを表示するdiv
	this.area = makeRectangle(this.id, 0, 0, 0, 0, "#FFFFFF", 100);
	if(this.area){
		with(this.area.style){
			width  = w + "px";
			height = h + "px";
			position = "absolute";
			visibility = "hidden";
		}
	}
	
	//setTimeout管理変数
	this.timerChange;
	
	//ロードした画像の総数
	this.loaded = 0;
	
	//// HTMLからの入力必須項目 ////
	
	//表示時間とフェード時間
	this.objTime = {interval:interval * 1000, fade:fade * 1000};
	
	//ファイル名、サムネール、リンク先、ターゲット
	this.aInfo = [];
	
	//ボタン
	this.aButton = [];
	
	//サムネイルの長さの合算
	this.totalLength = 0;
	
	//インターバルID
	this.timerID = undefined;
	
	//動作中のフラグ
	this.isMove = false;
	
	//// カスタム設定情報 ////
	
	//サムネール間のマージン
	this.margin = 1;
	
	//サムネール位置
	this.top = 0;
	this.left = 0;
	
	//サムネールの下地のカラー
	this.bgColor = "#FFFFFF";
	
	//サムネールの下地の不透明度(0～100)
	this.bgAlpha = 50;
	
	//サムネールのカバーのカラーコードおよび不透明度(0～100)
	this.coverColor;
	this.coverAlpha;
	
	//サムネールの下地の画像
	this.backgroundImage = "";
	
	//サムネイルの移動方向の反転フラグ
	this.isReverse = false;
	
	//// 親のインスタンス ////
	this.parent = undefined;
	this.setParent = function(parent) {
		this.parent = parent;
	}
	
	//静止画ファイルを追加する。
	this.addFile = function(file) {
		this.aInfo.push({ src:file });
	}
	
	//ボタンを追加する。posはボタン位置("top", "bottom", "left", "right")
	this.addButton = function(file, pos) {
		this.aButton.push({ src:file, position:pos });
	}
	
	//自分への参照
	var _this = this;
	
	//実行
	this.start = function() {
		var my = $("#" + id);
		my.empty().css({
			left	: this.left + 'px',
			top		: this.top + 'px',
			overflow: 'hidden',
			padding	: 0, 
			zIndex	: 1
		});
		
		//背景色を設定
		my.css("backgroundColor", _this.bgColor);
		my.css("z-index", 1);
		if (this.backgroundImage != "") {
			my.css("background", "url(" + this.backgroundImage + ")");
		}
		
		//サムネイルのラッパー
		var wrapper = makeRectangle(this.id + "_wrapper", 0, 0, 0, 0, this.bgColor, 100);
		with (wrapper.style) {
			position = "absolute";
			width = this.area.style.width;
			height = this.area.style.height;
			overflow = "hidden";
			if (this.backgroundImage != "") {
				background = "url(" + _this.backgroundImage + ")";
			}
		}
		this.area.appendChild(wrapper);
		
		//ラッパーにサムネイルを追加
		for(var i = 0; i < this.aInfo.length; i++) {
			//静止画
			var img = new Image();
			img.style.position = "relative";
			img.onload = loadedImage;
			img.src = this.aInfo[i]["src"] + "?nc=" + new Date().toString();
			
			//カバー
			if (this.coverColor != undefined && this.coverAlpha != undefined) {
				var cover = makeRectangle(this.id + "_cover_" + (i + 1), 0, 0, 20, 20, this.coverColor, this.coverAlpha * Number(i != 0));
				cover.style.position = "absolute";
			}
			
			var img_div = makeRectangle(this.id + "_img_" + (i + 1), 0, 0, 0, 0, this.bgColor, 100);
			img_div.style.position = "absolute";
			if (_this.backgroundImage != "") {
				img_div.style.background = "url(" + _this.backgroundImage + ")";
			}
			img_div.appendChild(img);
			
			//カバーを追加
			if (cover != undefined) {
				img_div.cover = cover; 
				img_div.appendChild(cover);
			}
			
			img_div.onmouseover = overHandler;
			img_div.onmouseout  = outHandler;
			img_div.onclick = clickHandler;
			img_div.order = (i + 1);
			
			wrapper.appendChild(img_div);
		}
		this.area.appendChild(wrapper);
	}
	
	//画像のonLoadイベントハンドラ
	loadedImage = function() {
		_this.loadCheck();
	}
	
	//ロード数のチェック
	this.loadCheck = function() {
		
		this.loaded++;
		
		// 全てロードしたら、ボタンの追加処理を開始する
		if (this.loaded == this.aInfo.length) {
			//先頭のイメージ
			var img = $("#" + _this.id + '_img_1');
			
			//表示領域の幅(または高さ)と、配置場所(センター位置)
			var l = $("#" + _this.id).width();
			//var p = 0; //オムロン仕様
			var p = Math.floor((l - img.width()) / 2);
			if (this.type == "vertical") {
				l = $("#" + _this.id).height();
				p = Math.floor((l - img.height()) / 2);
			}
			
			//他のイメージも、先頭のイメージと同じ場所に置いておく
			for(var i = 1; i <= this.aInfo.length; i++) {
				img = $("#" + this.id + '_img_' + i);
				
				if (this.type == "vertical") {
					img.css("top", p);
					this.totalLength += img.height() + this.margin;
				} else {
					img.css("left", p);
					this.totalLength += img.width() + this.margin;
				}
				
				//カバー
				cover = $("#" + this.id + '_cover_' + i);
				if (cover != undefined) {
					cover.width(img.width());
					cover.height(img.height());
				}
			}
			
			this.loaded = 0;
			
			//ボタンの追加
			for(var i = 0; i < this.aButton.length; i++) {
				img = new Image();
				img.style.position = "relative";
				img.onload = loadedButton;
				img.src = this.aButton[i]["src"];
				
				img_div = makeRectangle(this.id + "_button_" + this.aButton[i]["position"], 0, 0, 0, 0, this.bgColor, 100);
				with (img_div.style) {
					position = "absolute";
					overflow = "hidden";
					if (_this.backgroundImage != "") {
						background = "url(" + _this.backgroundImage + ")";
					}
				}
				
				img_div.appendChild(img);
				img_div.buttonType = this.aButton[i]["position"];
				img_div.onmouseover = btnOverHandler;
				img_div.onmouseout  = btnOutHandler;
				img_div.onclick = btnClickHandler;
				
				this.area.appendChild(img_div);
			}
		}
	}
	
	this.animate = function () {
		// 親のクロスフェード処理
		if (this.parent != undefined) {
			this.parent.switchSlide(this.current);
		}
		
		//タイマーIDの処理
		if (this.timerID != undefined) clearTimeout(this.timerID);
		
		//アニメーションを動かす
		this.timerID = setTimeout(_this.doScroll, _this.objTime["interval"]);
	}
	
	//スクロール処理
	this.doScroll = function(n, extra) {
		var img;
		var target, dist;
		_this.isMove = true;
		
		// 今アクティブなサムネイル
		img0 = $("#" + _this.id + '_img_' + _this.current);
		prev = _this.current;
		
		_this.adjustPosition();
		
		//処理の場合分け
		if (arguments.length == 2) {
			//サムネイルクリック時(割り込み処理)
			_this.current = n;
		} else {
			//タイマー処理
			_this.current = _this.current % _this.aInfo.length + 1;
		}
		
		// 次にアクティブなサムネイル
		img = $("#" + _this.id + '_img_' + _this.current);
		
		//次のサムネイルの目的地と、目的地までの移動距離
		//target = 0;//オムロン仕様
		target = Math.floor(($("#" + _this.id + "_wrapper").width() - img.width()) / 2);
		dist = target - parseInt(img.css("left"));
		if (_this.type == "vertical") {
			target = Math.floor(($("#" + _this.id + "_wrapper").height() - img.height()) / 2);
			dist = target - parseInt(img.css("top"));
		}
		
		var p;
		
		for(var i = 1; i <= _this.aInfo.length; i++) {
			img = $("#" + _this.id + '_img_' + i);
			
			if (_this.type == "vertical") {
				p = parseInt(img.css("top"));
				
				if (dist >= 0) {
					//下に動く時
					if (p > _this.area.offsetHeight) {
						p -= _this.totalLength;
					}
				} else {
					//上に動く時
					if ((p + img.height()) < 0) {
						p += _this.totalLength;
					}
				}
				
				img.css("top", p + "px");
				img.stop()
				   .animate({top:(p + dist) + "px"}, _this.objTime["fade"], "swing", function() { _this.isMove = false;}); 
			} else {
				p = parseInt(img.css("left"));
				
				if (dist >= 0) {
					//右に動く時
					if (p > _this.area.offsetWidth) {
						p -= _this.totalLength;
					}
				} else {
					//左に動く時
					if ((p + img.width()) < 0) {
						p += _this.totalLength;
					}
				}
				
				img.css("left", p + "px");
				img.stop()
				   .animate({left:(p + dist) + "px"}, _this.objTime["fade"], "swing", function() { _this.isMove = false;}); 
			}
			
			//黒カバーの処理
			var cover = $("#" + _this.id + "_cover_" + i);
			if (cover != undefined) {
				if (i == _this.current) {
					cover.stop().animate({opacity:0.0}, "fast");
				} else {
					cover.stop().animate({opacity:_this.coverAlpha / 100}, "fast");
				}
			}
		}
		_this.animate();
	}
	
	//サムネイルの位置をチェックする
	this.checkThumbnailPosition = function() {
		var img;
		var i;
		
		if (_this.type == "horizontal") {
			var left, right;
			var l, r;
			
			//サムネイル全体の表示範囲を調べる
			for (i = 1; i <= _this.aInfo.length; i++) {
				img = $("#" + _this.id + '_img_' + i);
				l = img.position().left;
				if (left == undefined) left = l;
				left = Math.min(left, l);
				r = l + img.width();
				if (right == undefined) right = r;
				right = Math.max(right, r);
			}
			
			//一番右のサムネイルが、表示エリアの左端より下に来ている場合
			//表示エリアの右に隠れているサムネイルを左に持ってくる
			if (left > 0) {
				for (i = 1; i <= _this.aInfo.length; i++) {
					img = $("#" + _this.id + '_img_' + i);
					l = img.position().left;
					if (l > _this.area.offsetWidth) {
						img.css("left", l - _this.totalLength);
					}
				}
				return;
			}
			
			//一番左のサムネイルが、表示エリアの右端より下に来ている場合
			//表示エリアの右に隠れているサムネイルを左に持ってくる
			if (bottom < _this.area.offsetHeight) {
				for (i = 1; i <= _this.aInfo.length; i++) {
					img = $("#" + _this.id + '_img_' + i);
					
					r = Math.floor(parseInt(img.css("left")) + img.width());
					
					if (r < 0) {
						img.css("left", r + _this.totalLength - img.width());
					}
				}
				return;
			}
		} else {
			var top, bottom;
			var t, b;
			
			//サムネイル全体の表示範囲を調べる
			for (i = 1; i <= _this.aInfo.length; i++) {
				img = $("#" + _this.id + '_img_' + i);
				t = img.position().top;
				if (top == undefined) top = t;
				top = Math.min(top, t);
				b = t + Number(img.height());
				if (bottom == undefined) bottom = b;
				bottom = Math.max(bottom, b);
			}
			
			//一番上のサムネイルの底辺が、表示エリアの上端より下に来ている場合
			//表示エリアの下に隠れているサムネイルを上に持ってくる
			if (top > 0) {
				for (i = 1; i <= _this.aInfo.length; i++) {
					img = $("#" + _this.id + '_img_' + i);
					t = img.position().top;
					if (t > _this.area.offsetHeight) {
						img.css("top", t - _this.totalLength);
					}
				}
				return;
			}
			
			//一番下のサムネイルが、表示エリアの上端より下に来ている場合
			//表示エリアの下に隠れているサムネイルを上に持ってくる
			if (bottom < _this.area.offsetHeight) {
				for (i = 1; i <= _this.aInfo.length; i++) {
					img = $("#" + _this.id + '_img_' + i);
					
					b = Math.floor(Number(img.css("top").split("px")[0]) + img.height());
					
					if (b < 0) {
						img.css("top", b + _this.totalLength - img.height());
					}
				}
				return;
			}
		}
	}
	
	// 全サムネイルの位置を直す
	this.adjustPosition = function() {
		_this.checkThumbnailPosition();
		var i, n;
		var img;
		var total = _this.aInfo.length;
		
		//var target = parseInt($("#" + _this.id + '_img_' + _this.current).css("left"));
		//if (this.type == "vertical") target = parseInt($("#" + _this.id + '_img_' + _this.current).css("top"));
		
		//var target = 0; //オムロン仕様
		var target = ($("#" + _this.id + "_wrapper").width() - $("#" + _this.id + '_img_' + _this.current).width()) / 2;
		if (this.type == "vertical") target = ($("#" + _this.id + "_wrapper").height() - $("#" + _this.id + '_img_' + _this.current).height()) / 2;
		
		var p = target;
		
		// 真ん中から右(または下)
		for (i = _this.current; i < _this.current + Math.ceil(total / 2); i++) {
			n = (i % total);
			if (n == 0) n = total;
			img = $("#" + _this.id + '_img_' + n);
			if (_this.type == "vertical") {
				img.css("top", p);			
				p += img.height() + _this.margin;
			} else {
				img.css("left", p);
				p += img.width() + _this.margin;
			}
		}
		
		p = target;
		// 真ん中から左(または上)
		for (i = _this.current - 1; i >= _this.current - Math.floor(total / 2); i--) {
			n = (i % total);
			if (n <= 0) n += total;
			img = $("#" + _this.id + '_img_' + n);
			if (_this.type == "vertical") {
				p -= img.height() + _this.margin;
				img.css("top", p);
			} else {
				p -= img.width() + _this.margin;
				img.css("left", p);
			}
		}
	}
	
	// サムネイルのロールオーバーイベントハンドラ
	var overHandler = function() {
		//カーソルを指マークに
		if (this.order == _this.current) {
			this.style.cursor = "normal";
		} else {
			this.style.cursor = "pointer";
			
			//カバー
			if (this.cover != undefined) {
				$("#" + this.cover.id).stop().animate({opacity:0.0}, "fast");
			}
		}
	}
	
	// サムネイルのロールアウトイベントハンドラ
	var outHandler = function() {
		//カーソルを矢印マークに
		this.style.cursor = "normal";
		
		//カバー
		if (this.cover != undefined) {
			if (this.order != _this.current) $("#" + this.cover.id).stop().animate({opacity:_this.coverAlpha / 100}, "fast");
		}
	}
	
	// サムネイルのクリックイベントハンドラ
	var clickHandler = function() {
		if (this.order != _this.current){
			clearInterval(_this.timerID);
			_this.timerID = undefined;
			_this.doScroll(this.order, true);
		}
	}
	
	//ボタン画像ロード完了時のイベントハンドラ
	var loadedButton = function () {
		_this.loaded++;
		
		if (_this.loaded == _this.aButton.length) {
			setTimeout( function() { settingTest(); }, 100);
		}
	}
	
	var settingTest = function() {
		var wrapper = $("#" + _this.id + "_wrapper");
		if (_this.type == "horizontal") {
			var btn_left =  $("#" + _this.id + "_button_left");
			btn_left.css("left", 0);
			var btn_right =  $("#" + _this.id + "_button_right");
			btn_right.css("left", $("#" + _this.id).width() - btn_right.width());
			wrapper.css("left", btn_left.width() + _this.margin);
			wrapper.width(parseInt(_this.area.style.width) - btn_left.width() - btn_right.width() - _this.margin - _this.margin);
		} else {
			var btn_top =  $("#" + _this.id + "_button_top");
			btn_top.css("top", 0);
			var btn_bottom =  $("#" + _this.id + "_button_bottom");
			btn_bottom.css("top", $("#" + _this.id).height() - btn_bottom.height());
			wrapper.css("top", btn_top.height());
			wrapper.height(parseInt(_this.area.style.height) - btn_top.height() - btn_bottom.height());
		}
		
		_this.area.style.visibility = "visible";
		
		_this.adjustPosition();
		_this.animate();
	}
	
	var btnOverHandler = function() {
		//カーソルを指マークにし、不透明度を0.7に
		this.style.cursor = "pointer";
		$("#" + this.id).stop().animate({opacity:0.7, alpha:0.7}, "fast");
	}
	
	var btnOutHandler  = function() {
		//カーソル、不透明度を1.0
		this.style.cursor = "normal";
		$("#" + this.id).stop().animate({opacity:1.0, alpha:1.0}, "fast");
	}
	
	var btnClickHandler = function() {
		if (_this.isMove) return;
		
		var cur;
		
		var inc = -1;
		if (!_this.isReverse) inc = 1;
		
		switch(this.buttonType) {
		case "top":
		case "left":
			cur = (_this.current % _this.aInfo.length) + inc;
			break;
		default:
			cur = (_this.current % _this.aInfo.length) - inc;
			break;
		}
		if (cur <= 0) cur += _this.aInfo.length;
		
		//alert(cur);
		
		clearTimeout(_this.timerID);
		_this.timerID = undefined;
		_this.doScroll(cur, true);
	}
	
}
