( function($) {
	var imgList = new Array();
	var flagList = new Array();
	var photo;
	var now = 0;
	var prev = 0;
	var bHeight = $("#imageBox").height();
	$.getJSON("./photo/photo.js", function(json) {
		photo = json["photo"];
		for( var i=0; i<photo.length; i++ ) {
			var cData = photo[i];
			flagList.push(false);
			imgList.push(
				$("<img>", { "src":"./photo/"+cData.file }).data("num", i).bind("load", loaded)
			);
		}
	} );
	
	function loaded() {
		flagList[parseInt( $(this).data("num") )] = true;
		for( var i=0; i<flagList.length; i++ ) {
			if( !flagList[i] ) return false;
		}
		var ul = $("<ul>");
		for( var j=0; j<imgList.length; j++ ) {
			var size = img_true_size( imgList[j].get(0) );
			switch( photo[j].dur ) {
				case "up":
					photo[j].from = bHeight-size.height;
					photo[j].to = 0;
				break;
				case "bottom":
					photo[j].from = 0;
					photo[j].to = bHeight-size.height;
				break;
				case "stay":
					photo[j].from = 0;
					photo[j].to = 0;
				break;
			}
			ul.append( $("<li>").css({top:photo[j].from}).append( imgList[j] ) );
		}
		$("#imageBox").append( ul ).find("li").css("opacity", 0).hide().eq(now);
		move();
	}
	
	function move() {
		var tgt = $("#imageBox li").eq(now).show();
		var index = parseInt( tgt.find("img").data("num") );
		tgt.css( { "z-index":10, "opacity":0, "top":photo[index].from } )
		tgt.animate({"opacity":1, top:photo[index].to}, {"duration":3500, "easing":"easeOutSine", "complete":endMove} );
	}
	
	function endMove() {
		if( prev != now )
			$("#imageBox li").eq(prev).hide();
		var tgt = $("#imageBox li").eq(now).css("z-index", 1);
		prev = now;
		now++;
		if( now >= imgList.length ) now = 0;
		if( now == prev ) return false;
		setTimeout( move, 2000 );
	}

	// get Image true size
	// vim http://dogmap.jp/2009/06/17/javascript-image-natural-size-2/
	var img_true_size = function(image){
		var w = image.width ,
			h = image.height ;
	 
		if ( typeof image.naturalWidth !== 'undefined' ) {  // for Firefox, Safari, Chrome
			w = image.naturalWidth;
			h = image.naturalHeight;
	 
		} else if ( typeof image.runtimeStyle !== 'undefined' ) {	// for IE
			var run = image.runtimeStyle;
			var mem = { w: run.width, h: run.height };  // keep runtimeStyle
			run.width  = "auto";
			run.height = "auto";
			w = image.width;
			h = image.height;
			run.width  = mem.w;
			run.height = mem.h;
	 
		} else {		 // for Opera
			var mem = { w: image.width, h: image.height };  // keep original style
			image.removeAttribute("width");
			image.removeAttribute("height");
			w = image.width;
			h = image.height;
			image.width  = mem.w;
			image.height = mem.h;
		}
	 
		return {width:w, height:h};
	}

} )(jQuery);
