/* ================================================================================
	prettyMobile v1.0
	Copyright 2009, Stéphane Caron
	Released under http://creativecommons.org/licenses/by/2.5/
	More information: http://www.no-margin-for-errors.com/projects/prettyMobile/
=================================================================================== */


/* ------------------------------------------------------------------------
	Bind the nav functions, init variables
------------------------------------------------------------------------- */
	var pageWidth = 0; // Used for the Portrait/Landscpae mode
		animationDuration = 1000, // Animation duration, used for the callback (please see the CSS for animation speed)
		animationDurationFast = 500,
		hashHistory = new Array(),
		urlHistory = new Array(),
		titleHistory = new Array(),
		hashPrefix = '#_', // To prevent page scroll
		bottomMargin = 20, // So the content is not flush with the bottom of the page
		isLoading = false,
		startingX = 0,
		startingSliderX = 0,
		totalSliderX = 0,
		currentSliderPos = 0;

	// Document readyness
	if(/Safari/i.test(navigator.userAgent)){
		var _timer=setInterval(function(){
			if(/loaded|complete/.test(document.readyState)){
				clearInterval(_timer)
				documentReady();
			}
		}, 10);
	}

	// Use $ as Sizzle selector
	window.$ = function(selector){
		return Sizzle(selector);
	};

	function documentReady() {
		updateOrientation();
		bindFunctions();
		
		var stateObj = { url:window.location.href, title:'' };
		history.pushState(stateObj,'','#home');
	};
	
	window.onpopstate = function(event){
		if(event.state)
			changePage('previous',event.state.url,event.state.title);
	}
	
	function bindFunctions(){
		$news_gallery = $('.pm_in-viewport ul#news li');
		
		for (var i = $news_gallery.length - 1; i >= 0; i--){
			$news_gallery[i].style.left = i * parseFloat(pageWidth) + 'px';
			
			$news_gallery[i].ontouchstart = function(evt){
				touch = evt.touches[0];
				if(!this.parentNode.style.left) this.parentNode.style.left = 0;
				startingSliderX = parseFloat(this.parentNode.style.left);
				startingX = touch.pageX;
				totalSliderX = $news_gallery.length * 320;
			}

			$news_gallery[i].ontouchmove = function(evt){
				evt.preventDefault(); // prevent window scrolling!
				touch = evt.touches[0];
				dx = startingX - touch.pageX;
				
				$('.pm_in-viewport ul#news')[0].style.left = (startingSliderX - dx) + 'px';
			}
			
			$news_gallery[i].ontouchend = function(evt){
				if(startingSliderX - (startingSliderX - dx) > 75){
					currentSliderPos++;
				}else if (startingSliderX - (startingSliderX - dx) < -75){
					currentSliderPos--;
				}
				
				target_pos_x = -(currentSliderPos * 320);
				if(target_pos_x > 0) target_pos_x = 0;
				if(target_pos_x < -(totalSliderX-320)) target_pos_x = -(totalSliderX-320);
			
			
				$('.pm_in-viewport ul#news')[0].className = 'animate-left-fast';
				$('.pm_in-viewport ul#news')[0].style.left =  target_pos_x + 'px';
				setTimeout(function(){
					$('.pm_in-viewport ul#news')[0].className = '';
				},animationDurationFast);
			}
		}
		
		for (var i = $('a[rel*=next]').length - 1; i >= 0; i--){
			$('a[rel*=next]')[i].onclick = function() {
				var _self = this;
				changePage('next',_self.href,_self.title,function(){
					var stateObj = { url:_self.href, title:_self.title };
					history.pushState(stateObj,_self.title,'#'+_self.id);
				});
				return false;
			}
		};
		
		for (var i = $('a[rel*=previous]').length - 1; i >= 0; i--){
			$('a[rel*=previous]')[i].onclick = function() {
				var _self = this;
				changePage('previous',_self.href,_self.title,function(){
					var stateObj = { url:_self.href, title:_self.title };
					history.pushState(stateObj,_self.title,'#'+_self.id);
				});

				return false;
			}
		};
		
		for (var i = $('a[rel*=back]').length - 1; i >= 0; i--){
			$('a[rel*=back]')[i].onclick = function() {
				history.back();
				return false;
			}
		};
		
		for (var i = $('a[rel*=tabs]').length - 1; i >= 0; i--){
			$('a[rel*=tabs]')[i].onclick = function() {
				changePage('tabs',this.href,this.title);
				return false;
			}
		};
		
		// Make sure a user can't click on "swiping" item
		for (var i = $('a[rel*=swipe]').length - 1; i >= 0; i--){
			$('a[rel*=swipe]')[i].onclick = function() {
				return false;
			}
		};
		
		for (var i = $('a[rel*=home]').length - 1; i >= 0; i--){
			$('a[rel*=home]')[i].onclick = function() {
				var _self = this;
				changePage('previous',_self.href,_self.title,function(){
					var stateObj = { url:_self.href, title:_self.title };
					history.pushState(stateObj,_self.title,'#'+_self.id);
				});
				return false;
			}
		};
		
		for (var i = $('a[rel*=footer]:first').length - 1; i >= 0; i--){
			$('a[rel*=footer]:first')[i].onclick = function() {
				var _self = this;
				changePage('previous',_self.href,_self.title,function(){
					var stateObj = { url:_self.href, title:_self.title };
					history.pushState(stateObj,_self.title,'#'+_self.id);
				});
				return false;
			}
		};
		
		for (var i = $('a[rel*=footer]:last').length - 1; i >= 0; i--){
			$('a[rel*=footer]:last')[i].onclick = function() {
				var _self = this;
				changePage('previous',_self.href,_self.title,function(){
					var stateObj = { url:_self.href, title:_self.title };
					history.pushState(stateObj,_self.title,'#'+_self.id);
				});
				return false;
			}
		};
		
		for (var i = $('a[rel*=expand]').length - 1; i >= 0; i--){
			$('a[rel*=expand]')[i].onclick = function(){
				link = this;
				if(link.className == 'selected'){
					link.className = '';
				}else{
					link.className = 'selected';
				}

				if(parseFloat(link.parentNode.style.height) < 50 || link.parentNode.style.height == '') {
					// Select the last node, has to loop to make sure we do not select whitespace
					for (var i = link.parentNode.childNodes.length - 1; i >= 0; i--){
						if (link.parentNode.childNodes[i].nodeType == 1 && link.parentNode.childNodes[i].nodeName == 'UL') {
							target_height = link.parentNode.childNodes[i].clientHeight + 65;
							break;
						}	
					}
				}else{
					target_height = 46;
				}
				
				link.parentNode.className = link.parentNode.className + ' animate-height';
				link.parentNode.style.height = target_height + 'px';

				setTimeout(function(){
					link.parentNode.className = '';
					fixHeight();
				},(animationDuration));
				
				return false;
			}
		};

		// // Bind the swipe gestures
		swipe();
	}


/* ------------------------------------------------------------------------
	Change page functions
------------------------------------------------------------------------- */

	changePage = function(direction,page,title,callback){
		$('.loader')[0].style.display = "block";
		
		// Load the content
		isLoading = true;
		var ajax = new ajaxRequest(page,function(responseHTML){
			$('.loader')[0].style.display = "none";
			
			isLoading = false;
			
			// Cache the selectors
			$pm_outofviewport = $('.pm_out-of-viewport')[0];
			$pm_inviewport = $('.pm_in-viewport')[0];
			
			$pm_outofviewport.innerHTML = responseHTML;
			
			if(direction == 'next'){
				$pm_outofviewport.style.left = pageWidth;
			}else if(direction == 'previous'){
				$pm_outofviewport.style.left = '-' + pageWidth;
			}
			
			fixHeight(direction);
			
			window.scrollTo(0, 1);

			if(title != undefined && title != "" && title != $('.pm_page-title')[0].innerHTML){
				setTimeout(function(){
					$('.pm_page-title')[0].innerHTML = title;
				},(animationDuration/2));
			}
			
			//Slide depending on the direction
			if(direction == 'next'){
				$pm_inviewport.className = $pm_inviewport.className + ' animate-left';
				$pm_inviewport.style.left = '-' + pageWidth;

				$pm_outofviewport.className = $pm_outofviewport.className + ' animate-left';
				$pm_outofviewport.style.left = 0;
			}else if(direction == 'previous'){
				$pm_inviewport.className = $pm_inviewport.className + ' animate-left';
				$pm_inviewport.style.left = pageWidth;

				$pm_outofviewport.className = $pm_outofviewport.className + ' animate-left';
				$pm_outofviewport.style.left = 0;
			}else{
				$('.pm_in-viewport')[0].style.left = pageWidth;
				$('.pm_in-viewport')[0].className = 'pm_out-of-viewport';
				$pm_outofviewport.className = 'pm_in-viewport';
				$pm_outofviewport.style.left = 0;

				// Rebind the function
				bindFunctions();
			}

			// Once it's done, reclass the divs properly
			setTimeout(function(){
				$pm_inviewport.className = 'pm_out-of-viewport';
				$pm_outofviewport.className = 'pm_in-viewport';

				// Rebind the function
				bindFunctions();

				if(callback) callback();
			},animationDuration);
		});
		ajax.loadPage();
	}


/* ------------------------------------------------------------------------
	Swipe Nav
------------------------------------------------------------------------- */

	swipe = function(toSwipe){
		if($('.pm_in-viewport a[rel*=swipe]').length == 0) return; // Make sure we can swipe
		
		// Fadeout the gallery caption
		setTimeout(function(){ fade($('.pm_in-viewport .pm_gallery_count')[0]); },2000);

		var startingX = 0; // The swipe init pos
		var dx = 0; // The swipe differente (back/next)

		$('.pm_in-viewport a[rel*=swipe] img')[0].ontouchstart = function(evt){
			evt.preventDefault(); // prevent window scrolling!
			touch = evt.touches[0];
			startingX = touch.pageX;
		}
		
		$('.pm_in-viewport a[rel*=swipe] img')[0].ontouchmove = function(evt){
			evt.preventDefault(); // prevent window scrolling!
			touch = evt.touches[0];
			dx = startingX - touch.pageX;
		}
		$('.pm_in-viewport a[rel*=swipe] img')[0].ontouchend = function(evt){
			if(dx > -10 && dx < 10){
				// When the user clicks, show the current picture, then fade it out.
				$('.pm_in-viewport #pm_gallery_count')[0].style.opacity = 1;
				$('.pm_in-viewport #pm_gallery_count')[0].FadeState = 2;

				// Fadeout the gallery caption
				setTimeout(function(){ fade($('.pm_in-viewport .pm_gallery_count')[0]); },2000);
			}
			
			if(dx > 50) { // Next motion
				if($('.pm_in-viewport a[rel*=last]').length != 0) return; // Make sure we can swipe next
				changePage('next',this.parentNode.href)
			}else if(dx < 50){ // Previous motion
				if($('.pm_in-viewport a[rel*=first]').length != 0) return; // Make sure we can swipe next
				history.back();
			}
		}
	}


/* ------------------------------------------------------------------------------------------------------------------------
	fade function taken from: http://www.switchonthecode.com/tutorials/javascript-tutorial-simple-fade-animation
------------------------------------------------------------------------------------------------------------------------- */

	function fade(element) {
		if(element == null)
			return;

		if(element.FadeState == null) {
			if(element.style.opacity == null || element.style.opacity == '' || element.style.opacity == '1') {
				element.FadeState = 2;
			} else {
				element.FadeState = -2;
			}
		}

		if(element.FadeState == 1 || element.FadeState == -1) {
			element.FadeState = element.FadeState == 1 ? -1 : 1;
			element.FadeTimeLeft = (animationDuration/2) - element.FadeTimeLeft;
		} else {
			element.FadeState = element.FadeState == 2 ? -1 : 1;
			element.FadeTimeLeft = (animationDuration/2);
			setTimeout(function(){
				animateFade(new Date().getTime(),element);
			},33);
		}  
	}
	
	function animateFade(lastTick, element){  
		var curTick = new Date().getTime();
		var elapsedTicks = curTick - lastTick;

		if(element.FadeTimeLeft <= elapsedTicks) {
			element.style.opacity = element.FadeState == 1 ? '1' : '0';
			element.FadeState = element.FadeState == 1 ? 2 : -2;
			return;
		}

		element.FadeTimeLeft -= elapsedTicks;
		var newOpVal = element.FadeTimeLeft/(animationDuration/2);
		if(element.FadeState == 1)
		newOpVal = 1 - newOpVal;

		element.style.opacity = newOpVal;
		element.style.filter = 'alpha(opacity = ' + (newOpVal*100) + ')';

		setTimeout(function(){
			animateFade(curTick,element);
		},33);
	}


/* ------------------------------------------------------------------------
	fix the page height
------------------------------------------------------------------------- */

	function fixHeight(direction){
		for (var i = $('#pm_container,.pm_content-container').length - 1; i >= 0; i--){
			$('#pm_container,.pm_content-container')[i].style.height = '';
		};

		if(direction == 'next' || direction == 'previous' || direction == 'tabs'){
			($('.pm_out-of-viewport')[0].offsetHeight + $('#pm_header')[0].offsetHeight > window.innerHeight) ? pageHeight = $('.pm_out-of-viewport')[0].offsetHeight + $('#pm_header')[0].offsetHeight + bottomMargin : pageHeight = window.innerHeight;
		}else{
			($('.pm_in-viewport')[0].offsetHeight + $('#pm_header')[0].offsetHeight > window.innerHeight) ? pageHeight = $('.pm_in-viewport')[0].offsetHeight + $('#pm_header')[0].offsetHeight + bottomMargin : pageHeight = window.innerHeight;
		}
		
		for (var i = $('#pm_container,.pm_content-container').length - 1; i >= 0; i--){
			$('#pm_container,.pm_content-container')[i].style.height = pageHeight + 'px';
		};
	}

/* ------------------------------------------------------------------------
	Ajax function
------------------------------------------------------------------------- */

	function ajaxRequest(url, callback) {
		self = this; // To fix scoping issue
		
		self.loadPage = function(){
			self.http_request = new XMLHttpRequest();
			self.http_request.onreadystatechange = this.loadDone;
			self.http_request.open('GET', url, true);
			self.http_request.setRequestHeader("X-Requested-With", "XMLHttpRequest")
			self.http_request.send();
		}
		
		self.loadDone = function(){
			if (self.http_request.readyState == 4) {
				if (self.http_request.status == 200) {
					callback(self.http_request.responseText);
				} else {
					alert('There was a problem with the request.');
				}
			}
		}
	}



/* ------------------------------------------------------------------------
	Orientation functions
------------------------------------------------------------------------- */

	updateOrientation = function() {
		var orientation = window.orientation;
		switch(orientation) {
			case 0:
				pageWidth = 320;
				$('body')[0].className = "pm_portrait";
	        break; 
			case 90:
				pageWidth = 480;
				$('body')[0].className = "pm_landscape";
			break;
			case -90: 
				pageWidth = 480;
				$('body')[0].className = "pm_landscape";
	        break;
			default:
				pageWidth = 320;
				$('body')[0].className = "pm_portrait";
			break;
		}
		pageWidth += 'px';

		$('.pm_out-of-viewport')[0].style.left = pageWidth;
		fixHeight();
	};
