/**
 * photo_viewer.js
 * //マンション・部屋の画像ビュアー
 * @author takaaki koyama
 * @use jQuery 1.4 later
 ---------------------------------------------------------------*/
;;(function($){

	/**
	 *
	 * $([selector]).photo_viewer();
	 *
	 * @example
	 *
	 *   ・ [selector] .photo_view img
	 *   ・ [selector] .photo_thumb_list a
	 *  は必須
	 *
	 * 	以下の構造で
	 *  <div class="photo_viewer">
	 *		<div class="photo_view"> .. <img /> .. </div>
	 *		<div class="photo_thumb_list">  ..  <a /> .. <a /> .. <a /> </div>
	 *  </div>
	 */
	$.fn.photo_viewer = function(options){
		//$.extend({},options);
//alert("ok");
		$(this).each(function(index,elem){
			var $t = $(elem);
			var $target = $t.find(".photo_view img:first");
			var $comment = $t.find(".comment");
			var $thumbs = $t.find(".photo_thumb_list a");
			var is_locked = false;
			$thumbs.click(function(){
				var $t = $(this);
				if(is_locked || $t.hasClass("current")) return false;

				is_locked = true;

				var is_animating = true, is_loaded = false;
				var img = new Image();
				img.onload = function(){
					is_loaded = true;
					if(!is_animating){
						$target.attr("src",this.src).fadeIn(250);
						$thumbs.parent().find(".current").removeClass("current");
						$t.addClass("current");
//						$comment.text($t.attr('title'));
						$comment.html($t.attr('title'));
						is_locked = false;
						img = null;
					}
				}

				$target.fadeOut(250,function(){
					is_animating = false;
					if(is_loaded){
						$target.attr("src",img.src).fadeIn(250);
						$thumbs.parent().find(".current").removeClass("current");
						$t.addClass("current");
//						$comment.text($t.attr('title'));
						$comment.html($t.attr('title'));
						is_locked = false;
						img = null;
					}
				})

				img.src = $t.attr("href");


				return false;
			});

			$t.find(".btn_prev").click(function(){
				var $list = $t.find(".photo_thumb_list li");
				var index = $list.index($list.find('.current').parent());
				if(index == 0){
					index = $list.size();
				}
				index--;
				$t.find(".photo_thumb_list li:eq("+index+") a").click();
				return false;
			});

			$t.find(".btn_next").click(function(){
				var $list = $t.find(".photo_thumb_list li");
				var index = $list.index($list.find('.current').parent());
				if(index == $list.size()-1){
					index = -1;
				}
				index++;
				$t.find(".photo_thumb_list li:eq("+index+") a").click();
				return false;
			})

//			$comment.text($thumbs.eq(0).attr('title'));
			$comment.html($thumbs.eq(0).attr('title'));

		})

		return this;
	}

	//init use this !
	$(function(){
		$(".photo_viewer").photo_viewer();
	})

})(jQuery);
