
(function() {

	var $body;
	
	var stepSize = -20;
	var speed = 24;

	var currentPage = null;
	var currentDialog = null;
	
	var useWebKitAnimations = (typeof WebKitTransitionEvent === "object");
	var lastAnimationTime;
	
	var animating = false;
	var defaultAnimation = "slide";

	//--------------------------------------------------------
	// First: Code to setup via 'dom:loaded' event and 
	//        manage document orientation/location changes.

	var currentWidth = 0;
	var orientationTimer;
	var orientationTimerMs = 250;

	var currentHash = location.hash;
	var hashPrefix = "#";
	var pageHistory = [];
	var portrait = "portrait";
	var landscape = "landscape";


	document.addEventListener('dom:loaded', function (event) {
		console.log("  initial setup - dom:loaded \n");

		$body = $('body')[0];

		var tmp = $('body > div.current'), startPage = !tmp.length ? $('body > div.page')[0]:
					tmp.each(function(node) { node.removeClass('current'); })[0];
		showPage(startPage);

		if (window.onorientationchange && typeof window.onorientationchange === "object")
		{
			window.onorientationchange = orientationChangeHandler;
			setTimeout(orientationChangeHandler, 0);
		} else {
			setTimeout(checkOrientationAndLocationHash, 0);
			orientationTimer = setInterval(checkOrientationAndLocationHash, orientationTimerMs);
		}

		setTimeout(scrollTo, 0, 0, 1);

		document.onscroll = function () {
			if (window.pageYOffset < 1) window.scrollTo(0, 1);
		};

		setTimeout(function () {
			var preloader = document.createElement("div");
			preloader.setAttribute('id','preloader');
			document.body.appendChild(preloader);
		}, 0);

	}, false);

	function orientationChangeHandler()
	{
		switch(window.orientation)
		{
			case 0:
				setOrientation(portrait);
				break;	
			case 90:
			case -90: 
				setOrientation(landscape);
				break;
		}
	}

	function setOrientation(orientation)
	{
		$body.removeClass( orientation===portrait?landscape:portrait ).addClass( orientation );
		adjustBodyToEl();
	}

	function adjustBodyToEl() {
		$body.style.height = $("body > div.page.current")[0].offsetHeight + "px";
	}

	function checkOrientationAndLocationHash()
	{
		if (window.innerWidth != currentWidth)
		{
			currentWidth = window.innerWidth;
			var orientation = currentWidth > 400 ? landscape : portrait;
			setOrientation(orientation);
		}
		if (location.hash != currentHash)
		{
			currentHash = location.hash;
			var page = $(currentHash)[0];
			if (page)
			{
				var index = pageHistory.indexOf(currentHash.substr(hashPrefix.length));
				var backwards = index != -1;
				if (backwards) pageHistory.splice(index, pageHistory.length);
				showPage(page, backwards);
			}
		}
	}

	//--------------------------------------------------------

	function showPage(page, backwards)
	{
		backwards = !!backwards;

		if (currentDialog)
		{
			currentDialog.removeClass("selected") = null;
		}

		if (page.className.indexOf("dialog") != -1)
		{
			currentDialog = page;
			page.addClass("selected");
			page.onsubmit = function(event)
			{
				event.stop();
				page.removeClass("selected");
				//var index = page.action.lastIndexOf(hashPrefix);
				//if (index != -1) showPage($(page.action.substr(index))[0]);
				console.log("search onSubmit");
			}
			page.onclick = function(event)
			{
				if (event.target == page) page.removeClasse("selected");
				console.log("search page clicked");
			}
		}
		else
		{
			orientationTimer = clearInterval(orientationTimer);
			var fromPage = currentPage;
			currentPage = page;
			location.href = currentHash = hashPrefix + page.id;
			pageHistory.unshift(page.id);
			page.addClass('current');
			if (fromPage) setTimeout(slidePage, 0, fromPage, page, backwards);
		}
	}

	function slidePage(fromPage, toPage, backwards)
	{
		if($(':focus').length)$(':focus')[0].blur();
		scrollTo(0, 1);
		animating = true;
		
		if(useWebKitAnimations)
		{
			//get animation type from: 1) page, 2) link, or 3) default;
			
			var animation = toPage.getAttribute('animation') || defaultAnimation;
			toPage.data = {referrer:fromPage,animation:animation};

			var callback = function animationEnd(event)
			{

//console.log("\nslidePage-callback: "+animation+"  from: "+fromPage.id+"  to: "+toPage.id+"  ["+toPage.data.referrer+"]");

				fromPage.removeClass('current');
				if (animation)
				{
					toPage.removeClass('in').removeClass(animation);
					fromPage.removeClass('out').removeClass(animation);
					if (backwards) {					
						toPage.toggleClass('reverse');
						fromPage.toggleClass('reverse');
					}
				}

				toPage.fire('pageAnimationEnd', { direction: 'in' });
				fromPage.fire('pageAnimationEnd', { direction: 'out' });

				currentPage = toPage;
				
				location.hash = hashPrefix + currentPage.id;

				var $originallink = toPage.data.referrer;
				if ($originallink) $originallink.removeClass('selected');
				lastAnimationTime = (new Date()).getTime();
				adjustBodyToEl();
				orientationTimer = setInterval(checkOrientationAndLocationHash, orientationTimerMs);
				toPage.removeEventListener('webkitAnimationEnd', callback, true);
				animating = false;
			}

			fromPage.fire('pageAnimationStart', { direction: 'out' });
			toPage.fire('pageAnimationStart', { direction: 'in' });

			toPage.addEventListener('webkitAnimationEnd', callback, true);
			if (backwards) {					
				toPage.toggleClass('reverse');
				fromPage.toggleClass('reverse');
			}
			toPage.addClass(animation).addClass('in');  // ...already current
			fromPage.addClass(animation).addClass('out');

			//console.log(" Animation started, ...no? \n   to: "+toPage.className+"\n from: "+fromPage.className);
		}
		else
		{	// js slide default...
			toPage.setStyle('left','100%').addClass('current');
			var percent=100, timer=setInterval(function()
			{
				percent += stepSize;
				if (percent <= 0)
				{
					percent = 0;
					fromPage.removeClass("current");
					clearInterval(timer);
					fromPage.setStyle('left',"0%");
					toPage.setStyle('left',"0%");
					orientationTimer = setInterval(checkOrientationAndLocationHash, orientationTimerMs);
					setTimeout(adjustBodyToEl,0);
					animating = false;
				}
				else
				{
					fromPage.setStyle('left', (backwards ? (100-percent) : (percent-100)) + "%");
					toPage.setStyle('left', (backwards ? -percent : percent) + "%");
				}
			}, speed);
		}

		return true;
	}

	//--------------------------------------------------------

	function goBack(to)  // to number OR hash
	{
		if( pageHistory.length ) {
			var numberOfPages = Math.min(parseInt(to || 1, 10), pageHistory.length-1);

			if( isNaN(numberOfPages) && typeof(to) === "string" && to != '#' )
				numberOfPages = pageHistory.indexOf(to.substr(1));

//console.log("\nNumberOfPages1: "+numberOfPages+" / "+to);

			if( isNaN(numberOfPages) || numberOfPages < 1 ) { numberOfPages = 1; }

			if (pageHistory.length > 1)
			{
				pageHistory.splice(0, numberOfPages);
				to = pageHistory.shift();
//console.log("\nNumberOfPages2: "+numberOfPages+" / "+to);
				showPage($(hashPrefix+to)[0], true);
			}
			else
			{
				location.href = currentHash = hashPrefix + (pageHistory[0]=currentPage.id);
			}
		}
	}


	function loadAndReplace(node, tmp)
	{
console.log("loadAndReplace: "+tmp.href+" / "+tmp.hash[0]);
		if(!node) node = tmp;
		if (!tmp.href || tmp.hash.charAt(0) == '#') return;
		
		requested = new io( tmp.href, {
				format: 'text',
				onFailure: function() {
					console.log("Shit! ajax failed.");
					},
				onSuccess: function(o) {
					//var p = node ? node.parent : (node=tmp).parent;
					console.log("Cool! ajax worked. "+o+" / "+p);
					}
			});
	}


	//--------------------------------------------------------

	addEventListener("click", function (event)
	{
		if (!event.target || animating) return;

		var tmp = event.target.findParentByTagName("a");
		if (tmp) {

			function unselect() { tmp.removeClass('selected'); }

console.log(" 1) ...tmp is "+tmp+" / "+tmp.id+" / "+tmp.className);
			if (tmp.hasClass("back"))
			{
				//console.log("\n\ngoing back... "+tmp.id+" / "+tmp.className+" / "+tmp.hash);
				event.stop();
				tmp.addClass("selected");
				goBack(tmp.hash);
				setTimeout(unselect, 500);
			}
			else if (tmp.hasClass("disabled"))
			{
				event.stop();
			}
			else if (tmp.hasClass("more") && tmp.href)
			{
				event.stop();
				tmp.addClass("selected");
console.log(" 2) ...tmp is "+tmp);

loadAndReplace( tmp.findParentByTagName('li'), tmp );


				loadAndReplace(tmp);
				setTimeout(unselect, 500);
			}
			else if (tmp.href && tmp.hash && tmp.hash != "#" && !tmp.target)
			{
				event.stop();
				tmp.addClass("selected");
				showPage($(tmp.hash)[0]);
				setTimeout(unselect, 500);
			}
			else if (tmp.href && tmp.target && tmp.target == "_blank")
			{
				tmp.addClass("selected");
				if (confirm('This tmp opens in a new window.'))
				{
					setTimeout(unselect, 500);
					return true;
				} else {
					event.stop();
					unselect();
					return false;
				}
			}
		}
		else if ((tmp = event.target.findParentByTagName("div")))
		{
			if( tmp.hasAttribute("toggle") )
			{
				tmp.setAttribute("toggle", (tmp.getAttribute("toggle") !== "true"));
				event.stop();
			}
		}
	}, true);

})();

