App = new Object();

App.UI = (function(){
	var FLAGS = {
		ajax_complete: false
	};

	var ajaxQueue = $({});
	var currentRequest = false;

	var historyPushing = false;
	var historyRegex = new RegExp('^#!/.');
	var locationRegex = new RegExp('^#!/');
	
	var hoover;
	var slided = false;
	var pointer = null;
	var map = null;
	

	function onContentLinkClick(e) {
		pointer = $(this);
		pointer.css("cursor", "progress"); 
		loadPage(this.href);
		e.preventDefault();
	}

	function onPageLoad(e, url, fromHistory) {
		if (pointer != null)
			pointer.css("cursor", "pointer"); 
		pushHistory(url);
	}

	/*function onLanguageLinkClick(e) {
		var language = $(this).closest('li').attr('class');
		var id;

		if (window.location.hash && /^#!/.test(window.location.hash)) {
			id = window.location.hash.match(nodeIdRegex)[1];
		} else if (nodeIdRegex.test(window.location)) {
			id = window.location.match(nodeIdRegex)[1];
		} else if (window.location.path = '/') {
			return true;
		}

		if (language in slugs) {
			this.href = window.baseUrl + language + '/view/' + id + '/' + slugs[language];
		}
	}

	function highlightMenuItem() {
		$('#nav .current').removeClass('current');

		$(this).parents('ul:not(:visible)').slideDown(100);
		$(this).parents('li').each(function(){
			$(this).addClass('current');
		});
		$(this).next('ul.child').slideDown(100, function() {
			$("#nav li:not(.current) ul").slideUp(100);
		});
		$(this).addClass('current');
	}

	function getMenuItem(url) {
		if (nodeIdRegex.test(url)) {
			var nodeLink = $('#node-' + url.match()[1]);
			if (nodeLink.length) {
				return nodeLink.get(0);
			}
		}
		return null;
	}*/

	function storePage(url, data) {
		if (!hasLocalStorage()) {
			return false;
		}
		localStorage.setItem(url, data);
	}

	function hasLocalStorage() {
		return 'localStorage' in window;
	}

	function loadPage(href) {
		var cacheKey = href.replace(window.baseUrl, '');
		//if (!hasLocalStorage() || !localStorage.getItem(cacheKey)) {
			$.ajax({
				url: href,
				data: null,
				type: 'GET',
				success: function(data) {
					$slidingcontainer.show();
					$slidingcontainer.html(data);
					$slidingcontainer.hide();
					//storePage(cacheKey, data);
					$(window).trigger('ui.pageload', [href, false]);
					slidingContainerToggle();
				}
			});
		/*} else {
			$slidingcontainer.show();
			$('#layout').show().html(localStorage.getItem(cacheKey));
			$slidingcontainer.hide();
			$(window).trigger('ui.pageload', [href, true]);
			slidingContainerToggle();
		}*/
		try {
			_gaq.push(['_trackPageview', cacheKey]);
		} catch(err) {}
	}

	function pushHistory(url) {
		historyPushing = true;
		var loc = url.replace(window.langUrl, '/');
		if(location.hash != '#!' + loc)
			window.location.hash = '!' + loc;
		else
			popHistory();
	}

	function popHistory(e) {
		if (!historyPushing && historyRegex.test(location.hash))
			loadPage(window.langUrl + location.hash.replace(locationRegex, ''));
		historyPushing = false;
	}

	function loadImages(path) {
		$.ajax({
			url: window.baseUrl + path,
			data: null,
			type: 'GET',
			success: function(data) {
				setSlideshow(data);
			}
		});
	}
	
	function setSlideshow(data) {
		$.supersized({
			// Functionality
			slide_interval          :   6000,		// Length between transitions
			transition              :   1, 			// 0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
			performance             :   1,          // Quality

			// Components							
			slide_links				:	'blank',	// Individual links for each slide (Options: false, 'num', 'name', 'blank')
			slides 					:  	data
		});
	}

	function loadNews(href) {
		var cacheKey = href.replace(window.baseUrl, '');
		//if (!hasLocalStorage() || !localStorage.getItem(cacheKey)) {
			$.ajax({
				url: href,
				data: null,
				type: 'GET',
				success: function(data) {
					$('header').prepend(data);
					//storePage(cacheKey, data);
				}
			});
		//}
		//else {
			//$('header').prepend(localStorage.getItem(cacheKey));
		//}
	}

	function loadMap() {
		var myLatlng = new google.maps.LatLng(-33, -65);
		var myOptions = {zoom: 4, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP};
		map = new google.maps.Map(document.getElementById("gmap"), myOptions);
	}
	
	function getMap() {
		return map;
	}

	function slidingContainerToggle() {
		if(!admin && $slidingcontainer.is(':hidden')){
			$slidingcontainer.animate({
				height: 'toggle'
				}, {
					duration: 500,
					specialEasing: {
						height: 'linear'
					}
				}
			);
		}
	}

	function init() {
		if(!admin)
			$('#container').delegate('a[target!="_blank"][name!="home"]', 'click', onContentLinkClick);

		$(window).bind('ui.pageload', onPageLoad);
		$(window).hashchange(popHistory);
		
		/*
		// AJAX spinner
		$(document).ajaxSend(function() {
			//$('#loader').fadeIn(100);
		});
		$(document).ajaxStop(function() {
			//$('#loader').fadeOut(50);
		});

		$.ajaxQueue = function(ajaxOpts) {
			// hold the original complete function
			var oldComplete = ajaxOpts.complete;

			// queue our ajax request
			ajaxQueue.queue(function(next) {

			  // create a complete callback to fire the next event in the queue
			  ajaxOpts.complete = function() {
				  
				// fire the original complete if it was there
				if (oldComplete) oldComplete.apply(this, arguments);

				next(); // run the next query in the queue
			  };

			  // run the query
			  currentRequest = $.ajax(ajaxOpts);
			});
		};
		
		$("#language-switcher li a span").each(function() {
			var html = $(this).html();
			html = html.replace(/\(.*$/, '');
			html = $.trim(html);
			$(this).html(html);
		});
		var $selected = $("#language-switcher li.selected").remove().html();
		$("#language-switcher").before('<div id="selectedLanguage">' + $selected + '</div>');
		$("#language-switcher").hide();

		$("#selectedLanguage").click(function() {
			$("#language-switcher").slideToggle();
			return false;
		});

		$("#language-switcher").delegate('#language-switcher li a', 'click', onLanguageLinkClick);
		*/

		$slidingcontainer = $('.slidingcontainer');
		if(!admin) {
			$slidingcontainer.hide().hover(function() {
				hover = slided = true;
			}, function(e) {
				if(hover && e.pageY - this.offsetTop < 0){
					$('#footer').fadeTo('slow', 1);
					$(this).animate({
					height: 'toggle'
					}, {
						duration: 500,
						specialEasing: {
							height: 'linear'
						}
					});
					hover = false;
				}
			});

			popHistory();
		}

		$('footer').hover(function() {
			if(slided)
				slidingContainerToggle();
		});
	}

	function setTitle(title) {
		document.title = title;
	}

	return {
		init: init,
		setTitle: setTitle,
		setSlideshow: setSlideshow,
		loadImages: loadImages,
		loadNews: loadNews,
		loadMap: loadMap,
		getMap: getMap
	};
})();

$(App.UI.init);	

