var _debug;
function dPut(mesg, encode) {
	if (! _debug) return;
	encode = encode||false;
	if (encode) {
		mesg = mesg.replace(/</g, "&lt;");
		mesg = mesg.replace(/>/g, "&gt;");
		mesg = mesg.replace(/\n/g, "<br />");
	}
	_debug.innerHTML += mesg + "<br />";
}

/**
 * Nenga
 */
var Nenga = function(params){
	var PRELOAD_IMAGES = [
	    "nenga2012/images/bg_layer1.gif",	 	"nenga2012/images/bg_layer2.gif",		"nenga2012/images/layer_clouds.png"
	  , "nenga2012/images/tatsu_s.png",			"nenga2012/images/bitkun.png",		 	"nenga2012/images/bitkun_up.png"
	  , "nenga2012/images/motiv_msg1.png",	 	"nenga2012/images/motiv_msg2.png",		"nenga2012/images/motiv_msg3.png"
	  , "nenga2012/images/motiv_cloud1.png",	"nenga2012/images/motiv_cloud2.png",	"nenga2012/images/motiv_cloud3.png"
	  , "nenga2012/images/moon.png", "nenga2012/images/moon_flag.png", "nenga2012/images/moon_text.gif", "nenga2012/images/moon_tenugui.png"
	  , "nenga2012/images/mizuhiki.png", "nenga2012/images/year2012.png", "nenga2012/images/logo.png"
	];
	
	var MESSAGE1_TARGET_Y = 24945;
	var MESSAGE2_TARGET_Y = 22097;
	var MESSAGE3_TARGET_Y = 10150;
	
	var AISATSU_CHARS = [16, 16];
	
	var _params = {
		  autoInitialScroll: params.autoInitialScroll||false
		, debug: params.debug||false
		, initialMoveTo: 8000
	};
	
	var $_bitkun = null,
		$_tatsu = null;
	var _motiv = {};
	
	var _scrollTop = NaN,
		_lastY = NaN,
		_hSize;
	var _anim = true;

	/**
	 * scrollHandler
	 */
	var scrollHandler = function (event) {
//dPut("scroll: " + _anim);
		if (_anim) {
			event.preventDefault();
			return false;
		}
		var scrollY = $(this).scrollTop();
		if (_lastY == scrollY) return;
		_lastY = scrollY;

		event.preventDefault();

		if (isNaN(_scrollTop)) {
			_scrollTop = scrollY;
		}

//		var bodyH = $('body').height();
//		var clientH = document.documentElement.clientHeight;
		var ticks = _scrollTop - scrollY;
		var tickpct = ticks / _scrollTop;
		
		// tatsu
		_motiv.tatsu.scroll(scrollY, ticks, tickpct);

		// bitkun
		_motiv.bitkun.scroll(scrollY, ticks, tickpct);
		
		// msg1
		_motiv.msg1.scroll(scrollY, ticks, tickpct);
		_motiv.msg2.scroll(scrollY, ticks, tickpct);
		_motiv.msg3.scroll(scrollY, ticks, tickpct);

		// clouds
		_motiv.cloud1.scroll(scrollY);
		_motiv.cloud2.scroll(scrollY);
		_motiv.cloud3.scroll(scrollY);
//#		_motiv.cloud4.scroll(scrollY);
//#		_motiv.cloud5.scroll(scrollY);
//#		_motiv.cloud6.scroll(scrollY);
	};

	/**
	 * autoScroll4
	 * move to top of content
	 */
	var autoScroll4 = function () {
		_motiv.bitkun.changeUp(true);
		var count = 0;
		$('html,body').animate(
			{scrollTop: 0}, 2000, "easeInOutQuint"
			, function () {
				if (++count > 1) {
					setTimeout(function () {
						_motiv.bitkun.changeUp(false);
						_motiv.topItems.animate(true);
					}, 100);
				}
			}
		);
	};

	/**
	 * autoScroll3
	 * move to 3rd message "Hana wo sakasemasu"
	 */
	var autoScroll3 = function () {
		var count = 0;
		_motiv.bitkun.changeUp(true);
		$('html,body').animate(
			{scrollTop: (MESSAGE3_TARGET_Y)}, 4000, "easeInOutQuint"
			, function () {
				if (++count > 1) {
					_motiv.bitkun.changeUp(false);
					setTimeout(autoScroll4, 1000);
				}
			}
		);
	};

	/**
	 * autoScroll2
	 * move to 2nd message "Kaze ga fuitemo..."
	 */
	var autoScroll2 = function () {
		var count = 0;
		_motiv.bitkun.changeUp(true);
		$('html,body').animate(
			{scrollTop: (MESSAGE2_TARGET_Y)}, 2000, "easeInOutQuint"
			, function () {
				if (++count > 1) {
					_motiv.bitkun.changeUp(false);
					setTimeout(autoScroll3, 1000);
				}
			}
		);
	};

	/**
	 * autoScroll1
	 * move to 1st message "Ame ga futtemo..."
	 */
	var autoScroll1 = function () {
		var count = 0;
		_motiv.bitkun.changeUp(true);
		$('html,body').animate(
			{scrollTop: MESSAGE1_TARGET_Y}, 1500, "easeInOutQuint"
			, function () {
				if (++count > 1) {
					_motiv.bitkun.changeUp(false);
					setTimeout(autoScroll2 , 1000);
				}
			}
		);
	};
	
	/**
	 * init2
	 */
	var init2 = function () {
		var scrollTop = $(this).scrollTop();
		var bodyH = $('body').height();
		var hSize = bodyH - scrollTop;
dPut("hSize=" + hSize + ", scrollTop=" + scrollTop + " bodyH=" + bodyH);

		$_tatsu = $("#layer-tatsu");
		$_bitkun = $("#motivBitkun");

		// Calculate top margin (240, 130)
		var bitkunY, tatsuY;
		if (hSize > 480) {
			bitkunY = hSize - $_bitkun.height() - 240;
			tatsuY = hSize - $_tatsu.height() - 130;
dPut(" bitkunY=" + bitkunY + " tatsuY=" + tatsuY);
		}
		else {
			bitkunY = 2;
			tatsuY = hSize - $_tatsu.height() - 25;
dPut("*bitkunY=" + bitkunY + " tatsuY=" + tatsuY);
		}

		// tatsu: 294, 218	new:340, 264
		_motiv.tatsu = new NengaTatsu({
			  selname: "#layer-tatsu"
			, targetY: 340
			, marginTop: tatsuY
		});
		// bitkun
		_motiv.bitkun = new NengaBitkun({
			  selname: "#motivBitkun"
			, targetY: 264
			, marginTop: bitkunY
			, animation: _params.autoInitialScroll
		});

		// top items
		_motiv.topItems = new TopItems();

		// messages
		var top = hSize - $("#motiv-msg1").height();
		top = (top < 0)? 10 : (top/2);
		_motiv.msg1 = new NengaMotiv2({
			  selname:"#motiv-msg1", direction:1
			, top:top,   initialX:2000, targetY:MESSAGE1_TARGET_Y
			, range:400, holdpx:400,    range2:600
			, d: false
		});
		_motiv.msg2 = new NengaMotiv2({
			  selname:"#motiv-msg2", direction:-1, animateY:true
			, top:15,    initialX:-822, targetY:MESSAGE2_TARGET_Y
			, range:400, holdpx:400,    range2:600
			, d: true
		});
		_motiv.msg3 = new NengaMotiv2({
			  selname:"#motiv-msg3", direction:1
			, top:80,   initialX:2000, targetY:MESSAGE3_TARGET_Y
			, range:600, holdpx:800,    range2:600
			, d: false
		});

		// clouds 22957
		_motiv.cloud1 = new NengaMotiv2({
			  selname:"#motiv-cloud1", direction:1
			, top:400,    initialX:2000, targetY:23100
			, range:1600, holdpx:60,    range2:1600
			, d: false
		});
		_motiv.cloud3 = new NengaMotiv2({
			  selname:"#motiv-cloud3", direction:1
			, top:290,   initialX:1800, targetY:21000
			, range:2000, holdpx:30,    range2:2000, disabled:false
			, d: false
		});
		_motiv.cloud2 = new NengaMotiv2({
			  selname:"#motiv-cloud2", direction:-1
			, top:120,   initialX:-100, targetY:17000
			, range:3000, holdpx:30,    range2:3000, disabled:false
			, d: false
		});
/*
		_motiv.cloud4 = new NengaMotiv2({
			  selname:"#motiv-cloud4", direction:1
			, top:360,   initialX:1400, targetY:22000
			, range:2000, holdpx:30,    range2:2000, disabled:true
			, d: false
		});
		_motiv.cloud5 = new NengaMotiv2({
			  selname:"#motiv-cloud5", direction:-1
			, top:340,   initialX:140, targetY:18000
			, range:1000, holdpx:1800,    range2:1000, disabled:true
			, d: false
		});
		_motiv.cloud6 = new NengaMotiv2({
			  selname:"#motiv-cloud6", direction:1
			, top:200,   initialX:1300, targetY:12000
			, range:1200, holdpx:1200,    range2:1200, disabled:true
			, d: false
		});
*/

		// event: scroll
		jQuery(window).scroll(scrollHandler);

		if (! _params.autoInitialScroll) {
			_anim = false;
			$_bitkun.css("display", "block");
			$_tatsu.css("display", "block");
			_motiv.topItems.animate(false);
//			scrollTo(0, 0);
			return;
		}
		
		/* event listners */

		// event: bitkunAnimateionCompleted 
        jQuery(window).bind('bitkunAnimateionCompleted.Nenga', function (event) {
			_anim = false;
			_motiv.tatsu.animate();
        });

        // event: tatsuAnimateionCompleted
        jQuery(window).bind('tatsuAnimateionCompleted.Nenga', function (event) {
        	autoScroll1();
//        	autoScroll3();
        });

        // event: notifyQuake 
        jQuery(window).bind('notifyQuake.Nenga', function (event) {
        	_motiv.bitkun.quake();
        });

        // animate bitkun
		setTimeout(function () {
			if (_params.autoInitialScroll) {
				_motiv.bitkun.animate();
			}
			return;
		}, 1000);
	};
	
	/**
	 * init
	 */
	this.init = function () {
		var num2 = function (value) {
			var str = "00" + value;
			return str.substr(str.length-2);
		};

		// imagePreload
		var imagePreload = new ImagePreload(PRELOAD_IMAGES);

		// add aisatsu chars
		for (var index=0; index < AISATSU_CHARS.length; index++) {
			for (var index2=0; index2 < AISATSU_CHARS[index]; index2++) {
				var filename = "nenga2012/images/c" + (index+1) + "-" + num2(index2+1) + ".png";
				imagePreload.adddImagePath(filename);
			}
		}

dPut("body=" + $('body').height() + ", html=" + $('html').height() + ", html,body=" + $('html,body').height() );
dPut(
	"documentElement.clientHeight:" + document.documentElement.clientHeight
	+ ", body.clientHeight:" + document.body.clientHeight
);
dPut("browser isMSIE:" + __browserInfo.isMSIE + " " + __browserInfo.version);
dPut("autoInitialScroll:" + _params.autoInitialScroll);
		_hSize = document.body.clientHeight;
dPut("hSize: " + _hSize);
		if (! __browserInfo.isMSIE) {
			$(".motivLayer").css("clip", "rect(0 1200px " + (_hSize+"px") + " 0)");
		}
dPut("check rect: " + $(".motivLayer").width() + "x" + $(".motivLayer").height() + ", " + $(".motivLayer").css("clip"));

		if (_params.debug) $("#_debugWrapper_").css("display", "none");
		scrollTo(0, _hSize);
		if (_params.debug) $("#_debugWrapper_").css("display", "block");

dPut("image Waiting...");
		imagePreload.wait(function () {
dPut("Scroll to bottom");
			setTimeout(function () {
dPut("Scroll to bottom end");
				scrollTo(0, _hSize);
				init2();
			}, 1300);
		});
	};

	this.init();
};

//ready
$(document).ready(function () {
	var autoscroll = true;
	var debug = false;

/*
	var param = location.search;
	if (param && param.charAt(0) == "?") {
		var splited1 = param.substr(1).split("&");
		for (var i=0; i < splited1.length;  i++) {
			splited2 = splited1[i].split("=");
			var val = "";
			if (splited2.length > 1) {
				val = splited2[1].toLowerCase();
			}
			
			switch (splited2[0].toLowerCase()) {
			case "autoscroll":
				if (val == "false") {
					autoscroll = false;
				}
				else if (val == "true") {
					autoscroll = true;
				}
				break;
				
			case "debug":
				if (val == "false") {
					debug = false;
				}
				else if (val == "true") {
					debug = true;
				}
				break;
			}
		}
	}
*/


	if (debug) {
		_debug = document.getElementById("_debug_");
		$("#_debugWrapper_").css("display", "block");
	}


	Nenga({
		  autoInitialScroll: autoscroll
		, debug: debug
	});
});

// #
