/**
 * 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);
		
		$(this).each(function(index,elem){
			var $t = $(elem);
			var $target = $t.find(".photo_view img");
			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");
						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");
						is_locked = false;
						img = null;
					}
				})
				
				img.src = $t.attr("href");
				
				
				return false;
			});
			
			$t.find(".btn_prev").click(function(){
				var $list = $(".photo_thumb_list li");
				var index = $list.index($list.find('.current').parent());
				if(index == 0){
					index = $list.size();
				}
				index--;
				$(".photo_thumb_list li:eq("+index+") a").click();
				return false;
			});
			
			$t.find(".btn_next").click(function(){
				var $list = $(".photo_thumb_list li");
				var index = $list.index($list.find('.current').parent());
				if(index == $list.size()-1){
					index = -1;
				}
				index++;
				$(".photo_thumb_list li:eq("+index+") a").click();
				return false;
			})
			
		})
		
		return this;
	}
	
	//init use this !
	$(function(){
		$(".photo_box").photo_viewer();
	})
	
})(jQuery);
