//æøå
var PageController = new function(){
	this.activePage = null;
	this.mouseX = 0;
	this.mouseY = 0;
	var _this = this;
	var originalTitle;
	
	this.initialize = function(){
	
		originalTitle = "iSkjåk";
	
		ViewController.activateStartupLoader();
	
		MapController.initializeMap("googleMap", 61.945, 7.949, 11);
		MapController.map.setMap('ga-physical');
		MapController.map.setMap('sk-topo2');
		
		this.setPositionFromAddress();
		var minimizeMain = ViewController.mainIsMinimized;
		this.catchAsyncGmapRedirect(function(){
			if(minimizeMain)
				ViewController.minimizeMain();
		});
			
		MapController.map.onNewPosition(function(){
			PageController.updateCoordsInAddress();
		});
		
		// mouse pos
		if (window.captureEvents){
			window.captureEvents(Event.MOUSEMOVE);
			window.onmousemove=_this.getCursorXY;
		}
		else
			document.onmousemove=_this.getCursorXY;
			
		ViewController.moveHeader();
	}
	
	this.getCursorXY = function(e) {
		_this.mouseX = (typeof event=='undefined') ? e.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
		_this.mouseY = (typeof event=='undefined') ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
		//console.log(_this.mouseX + " - " + _this.mouseY);
	}

	// Shows the position on the map at zoom level X and shakes markers near the point
	this.showOnMap = function(lat, lon, zoom, showRestoreButton){
		try {
			if(zoom == null)
				zoom = 15;
			var marker = MapController.map.addMarker(new GLatLng(parseFloat(lat), parseFloat(lon)), zoom, null, 'showOnMap', null, GoogleMapIcon.getLoaderIcon(), null);
			if(showRestoreButton)
				ViewController.showRestoreBtn();
			ViewController.minimizeMain();
			ViewController.minimizeHeader(); 
			MapController.map.moveTo(lat, lon, zoom);
			setTimeout(function(){
				marker.hide();
			}, 6000);
		} catch(e) { alert(e); }
		return false;
	}

	// Checks if the URL contains a redirect in the anchor, and perfoms this redirect
	this.catchAsyncGmapRedirect = function(callback){
		var anchor = this.getAnchor();
		if(anchor == null)
			return;
			
		if(anchor.substr(0, 2)=="!/"){
			if(anchor.indexOf('(x:')>-1){
				this.showPage(anchor.substring(1, anchor.indexOf('(x:')), callback);
			} else {
				this.showPage(anchor.substring(1), callback);
			}
		}
	}
	
	// Gets the map position from the URL and updates the map
	this.setPositionFromAddress = function(){
		var fullurl = document.location.href;
		
		if(fullurl.indexOf('(x:')==-1)
			return;

		Util.log("Catch map position from URL");

		var q = fullurl.substring(fullurl.indexOf('#')+1, fullurl.length);
		var x = q.substring(q.indexOf('(x:')+3, q.indexOf('y:'));
		var y = q.substring(q.indexOf('y:')+2, q.indexOf('z:'));
		var z = q.substring(q.indexOf('z:')+2, q.indexOf('h:'));
		var h = q.substring(q.indexOf('h:')+2, q.indexOf('m:'));
		var m = q.substring(q.indexOf('m:')+2, q.indexOf(')'));
		
		if(h=="1")
			ViewController.minimizeHeader();
		if(m=="1")
			ViewController.minimizeMain();
		//else
		//	ViewController.restoreMain();
		
		MapController.map.moveTo(x, y, z);
	}
	
	// Sets the current map coords and zoom level as anchor tag in the URL
	this.updateCoordsInAddress = function(){
		var headerMinimized = ViewController.headerIsMinimized;
		var mainMinimized = ViewController.mainIsMinimized;
		
		var anchor = this.getAnchor();
		var temp = "";

		// check if it is something else than coords in the anchor. perserve these
		if(anchor!=null && anchor.substr(0,3)!="(x:"){
			if(anchor.indexOf("(x:")<0)
				temp = anchor;
			else
				temp = anchor.substring(0, anchor.indexOf("(x:"));
			temp = temp.replace("http://" + window.location.hostname, ""); // IE remove domain
		}
		
		window.location.href = this.stripAnchor(window.location.href) + '#' + temp + '(x:' + roundNumber(MapController.map.getCenterPos().lat(), 3) + 'y:' + roundNumber(MapController.map.getCenterPos().lng(),3) + 'z:' + MapController.map.getZoomLevel() + 'h:' + (ViewController.headerIsMinimized ? 1 : 0) + 'm:' + (ViewController.mainIsMinimized ? 1 : 0) + ')';
	}

	this.addBeforeCoordsInAddress = function(url){
		if(url!=null && url!="" && url.charAt(0)!="/")
			url = "/" + url;
		window.location.href = this.stripAnchor(window.location.href) + "#" + (url.length>0 ? "!" + url : "");
		this.updateCoordsInAddress();
	}
	
	// Return the anchor of the URL
	this.getAnchor = function(){
		var url = document.location.href;
		if(url.indexOf('#')<0)
			return null;
		return UrlDecode(url.substring(url.indexOf('#')+1));
	}
	
	// Returns the current URL with possible anchor removed
	this.stripAnchor = function(url){
		return url.substring(0, url.indexOf('#'));
	}
	
	this.setTitle = function(title){
		document.title = originalTitle + " - " + title;
	}
	
	this.showPage = function(href, callback){
		$("#main .content").scrollTop(0);
		ViewController.restoreMain();
		if(href != this.activePage){
			$("#main").slideUp(300, function(){
				ViewController.showLoader();
				
				$.get(href, { async: "true" },
					  function(data){
							_this.activePage = href;
							$("#mainContent").html(data);
							ViewController.moveHeader();
							ViewController.hideLoader();
							$("#main").slideDown(300);
							// add url to anchor
							PageController.addBeforeCoordsInAddress(href);
							ViewController.updateStyles();
							
							onDocumentLoaded();
							
							PageController.addToHistory(href);
							
							if(callback != undefined && callback != null)
								callback();
								
							PageController.setTitle($("#main h1").text());	// update title
								
							if(PageController.historyCanGoBack()){
								$("#lnkBack").attr('title', 'Tilbake til "' + PageController.historyBackTitle() + '"');
								$("#lnkBack").show();
							} else
								$("#lnkBack").hide();
							if(PageController.historyCanGoForward()){
								$("#lnkForward").attr('title', 'Frem til "' + PageController.historyForwardTitle() + '"');
								$("#lnkForward").show();
							} else
								$("#lnkForward").hide();
								
								
							_gaq.push(['_trackPageview', href]);
					  });
			});
		}
	}
	
	this.history = [];
	this.historyLnk = 0;
	
	this.addToHistory = function(href){
							
		if(this.historyLnk<(this.history.length-1)){
			this.history.splice(this.historyLnk+1, this.history.length);
		}
		this.history.push({ href: href, title: $("#main h1").text() });	
		this.historyLnk = this.history.length-1;
		
	}
	
	this.historyCanGoBack = function(){
		return this.historyLnk>0;
	}
	
	this.historyGoBack = function(){
		if(!this.historyCanGoBack())
			return;
			
		var href = this.history[this.historyLnk-1].href;
		var lnk = this.historyLnk-1;
		if(href != null){
			this.showPage(href, function(){
				PageController.historyLnk = lnk;
				PageController.history.splice(PageController.history.length-1, 1);
			});
		}
	}
	
	this.historyBackTitle = function(){
		return this.history[this.historyLnk-1].title;
	}
	
	this.historyCanGoForward = function(){
		return this.historyLnk<this.history.length-1;
	}
	
	this.historyGoForward = function(){
		if(!this.historyCanGoForward())
			return;
			
		var href = this.history[this.historyLnk+1].href;
		var lnk = this.historyLnk+1;
		if(href !=null){
			this.showPage(href, function(){
				PageController.history.splice(PageController.history.length-1, 1);
				PageController.historyLnk = lnk;
			});
		}
	}
	
	this.historyForwardTitle = function(){
		return this.history[this.historyLnk+1].title;
	}
	
	this.historyShow = function(){
		var r = "";
		for(var i = 0; i<this.history.length; i++){
			r += " " + this.history[i].href;
		}
		console.log(r);
	}
}

