
(function() {

	var $body;
	
	var stepSize = -20;
	var speed = 24;
	
	///var topZ = 10;

	var currentPage = null;
	var currentTab = null;
	var currentDialog = null;
	
	var useWebKitAnimations = (typeof WebKitTransitionEvent === "object");

	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 portrait = "portrait";
	var landscape = "landscape";

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


	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,'fade');  ///initial page animation...

		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, (navigator.standalone?0:1));

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

//if (navigator.standalonee) {
	($('info')[0]).setCSS( {display:'none'} );
//}

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

	}, false);


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

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

	function adjustBodyToPageHeight() {
		$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, backwardsORanimation)
	{
		var fromPage = currentPage;
		if( fromPage ) page.setCSS({visibility:'hidden'});
		currentPage = page;
		var animation, backwards = (backwardsORanimation === true);
		if( backwards ) {
			animation = fromPage.getAttribute('animation');
		} else {
			animation = (backwardsORanimation || defaultAnimation).trim();
			page.setAttribute('animation',animation);
		}
		location.href = currentHash = hashPrefix + page.id;
		pageHistory.unshift(page.id);
		page.addClass('current');
		///page.setCSS( {zIndex:(++topZ)} );
		if (fromPage) setTimeout(slidePage, 0, fromPage, page, animation, backwards);
	}

	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));
			}
			if( isNaN(numberOfPages) || numberOfPages < 1 ) {
				numberOfPages = 1;
			}
			if (pageHistory.length > 1)
			{
				pageHistory.splice(0, numberOfPages);
				to = pageHistory.shift();
				///console.log(" goBACKto: "+to+"  "+$(hashPrefix+to)[0].id+"  "+$(hashPrefix+to)[0].getAttribute('animation'));
				showPage($(hashPrefix+to)[0], true);
			}
			else
			{
				location.href = currentHash = hashPrefix + (pageHistory[0]=currentPage.id);
			}
		}
	}

	function slidePage(fromPage, toPage, animation, backwards)
	{
		if($(':focus').length)$(':focus')[0].blur();
		scrollTo(0, (navigator.standalone?0:1));
		animating = true;
		if(useWebKitAnimations)
		{
			var callback = function animationEnd(event)
			{
				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;
				adjustBodyToPageHeight();
				orientationTimer = setInterval(checkOrientationAndLocationHash, orientationTimerMs);
				toPage.removeEventListener('webkitAnimationEnd', callback, true);
				animating = false;
			}
			//fromPage.fire('pageAnimationStart', { direction: 'out' });
			//toPage.fire('pageAnimationStart', { direction: 'in' });
			setTimeout(function(to){to.setCSS({visibility:'visible'});},1,toPage);
			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');
		}
		else
		{	// js slide default...
			toPage.setStyle('left','100%').addClass('current').setCSS({visibility:'visible'});
			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(adjustBodyToPageHeight,0);
					animating = false;
				}
				else
				{
					fromPage.setStyle('left', (backwards ? (100-percent) : (percent-100)) + "%");
					toPage.setStyle('left', (backwards ? -percent : percent) + "%");
				}
			}, speed);
		}

		return true;
	}

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

	function loadAndReplace(tmp)
	{
		///if (!tmp.href || tmp.hash.charAt(0) == '#') return;
		if (!tmp.href) return;
		(tmp.hasClass('liLoadMore')?tmp.findParentByTagName('li'):tmp).addClass('loading');
		///console.log(" classes: "+tmp.className);
		requested = new io( tmp.href, {
				format: 'text',
				onFailure: function() {
						console.log("Shit! ajax failed.");
					},
				onSuccess: function(o) {
						///console.log(" RETURNED:  \n"+o.text);
						if (tmp.hasClass('liLoadMore')) {
							var p = tmp.findParentByTagName('ul');
							tmp = p.removeChild(tmp.findParentByTagName('li'));
						} else {
							var p = tmp.parentNode;
							tmp = p.removeChild(tmp);
						}
						p.innerHTML += o.text;
						tmp = null; 
					}
			});
	}


	//--------------------------------------------------------
	/*
	$body.ontouchstart = function(event) // should check timing w/ touchend, but...
	{
		if(event.touches.length !== 1 || animating) return;
		processClicks((event.touches[0]).target);
		event.preventDefault();
	}
	*/

	addEventListener("click", function (event)
	{
		if (!event.target || animating) return;
		var tmp = event.target.findParentByTagName("a");
		if (tmp.hasClass("disabled"))
		{
			event.stop();
			return;
		}

		if (tmp)
		{
			function unselect() { tmp.removeClass('selected'); }
			
			if (tmp.hasAttribute('glowable'))
			{
				if(tmp.glow == null) tmp.glow  = new GlowOnTouch( tmp );
				setTimeout(function(){
						if (tmp.glow) {tmp.glow = tmp.glow.removeGlow();}
					}, 350);
			}
			
			if (tmp.hasClass("back"))
			{
				event.stop();
				tmp.addClass("selected");
				goBack(tmp.hash);
				setTimeout(unselect, 500);
			}
			else if (tmp.hasClass("more") && tmp.href)
			{
				event.stop();
				tmp.addClass("selected");
				if (navigator.onLine)
				{
					loadAndReplace(tmp);
				}
				else
				{
					alert("You must be connected to the\ninternet for additional content.");
					unselect();
				}
			}
			else if (tmp.hasClass("confirm") && tmp.href)
			{
				if (navigator.onLine)
				{
					tmp.addClass("selected");
					if (confirm('This tmp opens in a new window.'))
					{
						setTimeout(unselect, 500);
						return true;
					} else {
						event.stop();
						unselect();
						return false;
					}
				}
				else
				{
					event.stop();
					unselect();
					if (tmp.glow) {tmp.glow = tmp.glow.removeGlow();}
					alert("You must be connected to the\ninternet to access external links .");
					return false;
				}

			}
			else if (tmp.href && tmp.hash && tmp.hash != "#" && !tmp.target)
			{
				console.log(" type1 "+tmp.id);
				event.stop();
				tmp.addClass("selected");
				showPage($(tmp.hash)[0],tmp.getAttribute('animation'));
				setTimeout(unselect, 500);
			}
		}
		else if ((tmp = event.target.findParentByTagName("div")))
		{
			if( tmp.hasAttribute("toggle") )
			{
				tmp.setAttribute("toggle", (tmp.getAttribute("toggle") !== "true"));
				event.stop();
			}
		}
	}, true);


	//--------------------------------------------------------
	//
	function GlowOnTouch(el)
	{
		this.radius = 100;
		this.element = el;
		this.topElement = el.findParentByClassName('page dialog');
		var xy = el.getXY(this.topElement);
		var x = parseInt(xy.x + (el.offsetWidth / 2), 10);
		var y = parseInt(xy.y + (el.offsetHeight / 2), 10);
		var half = Math.round(this.radius/2);
		this.canvas = document.createElement('canvas');
		this.canvas.width = this.radius;
		this.canvas.height = this.radius;
		this.canvas.setCSS( {
				left: (x - half) + 'px',
				top: (y - half) + 'px',
				position: 'absolute',
				webkitTransitionProperty: 'opacity',
				webkitTransitionDuration: '250ms',
				pointerEvents: 'none'
			} );
		this.topElement.appendChild(this.canvas);
		var context = this.canvas.getContext("2d");
		var gradient = context.createRadialGradient(half,half,0,half,half,half);
		gradient.addColorStop(0, 'rgba(255,255,255,1)');
		gradient.addColorStop(0.6, 'rgba(255,255,255,0.05)');//8
		gradient.addColorStop(0.8, 'rgba(255,255,255,0)');//9
		context.fillStyle = gradient;
		context.fillRect(0,0,this.radius,this.radius);	
		this.visible = true;
	}

	base.extend(GlowOnTouch.prototype, {

		removeGlow: function() {
			this.canvas.remove();
			this.canvas.setCSS({opacity:0});
			this.visible = false;
			this.canvas = null;
			this.element.glow = null;
			return null;
		}
	});

})();
