var ajax_navigation = new function(){
	this.activeState = {active:"true"};
	this.shouldCatchLinks = false;
	document.body.setAttribute('data-test', 'true');
	if((document.addEventListener)&&(document.body.getAttribute('data-test')=='true')&&(document.getElementsByTagName)){
		this.shouldCatchLinks = true;
	}
	/* AJAX Request Function */
	this.request = function(path, json, node, loadingHTML){
		var http = new XMLHttpRequest();
		var url = path;
		var params = "json="+encodeURIComponent(json);
		http.open("POST", url, true);
		// Send the proper header information along with the request
		http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http.setRequestHeader("Content-length", params.length);
		http.setRequestHeader("Connection", "close");
		var resize = false;
		if(node.parentNode.offsetHeight==node.offsetHeight){
			resize = false;//true;
		}
		if(resize){
			node.parentNode.style.height = node.offsetHeight+"px";
		}
		http.onreadystatechange = function() { // Call a function when the state changes.
			if(http.readyState == 4) {
				if(http.responseText.substr(0,9)=='redirect:'){
					history.replaceState(history.state, '', http.responseText.substr(9));
					ajax_navigation.updatePage();
				} else {
					json = JSON.parse(http.responseText);
					for(type in json){
						for(needle in json[type]){
							if(type=='id'){
								value = json[type][needle];
								node = document.getElementById(needle);
								update = true;
								if(ajax_navigation.inBody(node)){
									update = false;
									tmp = document.createElement('div');
									tmp.innerHTML = value;
									if(tmp.innerHTML!=node.innerHTML){
										update = true;
									}
									tmp = '';
								}
								if(update){
									node.innerHTML = value;
									ajax_navigation.runScripts(node);
									ajax_navigation.catchLinks(node);
								}
							} else if(type=='tag'){
								tags = document.getElementsByTagName(needle);
								for(id in json[type][needle]){
									value = json[type][needle][id];
									node = tags[id];
									node.innerHTML = value;
									ajax_navigation.runScripts(node);
									ajax_navigation.catchLinks(node);
								}
							} else {
								// No clue, don't do anything
							}
						}
					}
				}
			}
		}
		http.send(params);
	}
	this.runScripts = function(node){
		scripts = node.getElementsByTagName('script');
		for(i=0;i<scripts.length;i++){
			// Catch included scripts
			if(scripts[i].getAttribute('src')){
				newScript = document.createElement('script');
				newScript.setAttribute('src', scripts[i].getAttribute('src'));
				newScript.setAttribute('type', scripts[i].getAttribute('type'));
				document.head.appendChild(newScript);
			}
			// Eval inline scripts
			eval(scripts[i].innerHTML);
		}
	}
	this.updateMainMenu = function(new_page){
		menu_item_set = false;
		var menu_items = document.getElementById('main-nav-main-menu').getElementsByTagName('li');
		for(i=1;i<menu_items.length;i++){ // Skip 'Home'
			menu_item = menu_items[i];
			path = menu_item.childNodes[0].href;
			if(location.href.indexOf(path)===0){
				if(menu_item.getAttribute('class')!='current'){
					this.resetMainMenu();
					menu_item.setAttribute('class', 'current');
				}
				menu_item_set = true;
				return true;
			}
		}
		if(!menu_item_set){
			books_path = 'http://www.forewordreviews.com/books/';
			if(location.href.indexOf(books_path)===0){
				menu_item = menu_items[1];
				if(menu_item.getAttribute('class')!='current'){
					this.resetMainMenu();
					menu_item.setAttribute('class', 'current');
					//this.updateSubMenu(new_page, menu_item.getAttribute('data-submenu'));
					menu_item_set = true;
					return true;
				}
			} else if(menu_items[0].getAttribute('class')!='current'){
				this.resetMainMenu();
				menu_items[0].setAttribute('class', 'current');
				//this.updateSubMenu(new_page, menu_items[0].getAttribute('data-submenu'));
			}
			menu_item_set = true;
			return true;
		}
	}
	
	this.updatePage = function(){
		var new_page = location.protocol+'//'+location.hostname+':'+location.port+location.pathname+location.search;
		this.updateMainMenu(new_page);
		json = {'id' : {'0':'main-nav-sub-menu', '1':'main-content', '2':'main-header-ad'}, 'tag' : {'0':'title'} };
		json = JSON.stringify(json);
		this.request(new_page, json, document.getElementById('main-content'), false);
		window.scroll(0,0);
		_gaq.push(['_trackPageview']);
	}
	this.linkClick = function(e){
		targ = e.target;
		this.blur();
		// Check if domain is the current domain
		if(this.href.indexOf(location.protocol+'//'+document.domain+'/')===0){
			location_length = location.href.length-location.hash.length;
			var full_location = location.href.substr(0, location_length)+'#';
			var search_location = location.protocol+'//'+document.domain+'/reviews/search/';
			if(this.href.indexOf(search_location)===0){
				// Disable AJAX for the search (javascript issues with google search)
			} else if(this.href.indexOf(full_location)===0){
				// Just changing the hash
				// Force pushState to avoid onpopstate call
				history.pushState(history.state, '', this.href);
				// Do nothing (default)
			} else if(this.href.substr(this.href.length-1)!='/'){
				// Not a consummo link (most likely an attachment)
				// Do nothing (default)
			} else if(this.getAttribute('target')){
				// External target that didn't get caught when adding listener
			} else if(this.getAttribute('data-ignore-ajax')=='true'){
				// Ignore AJAX request that didn't get caught when adding listener
			} else {
				// Push a history state and update sections
				history.pushState(history.state, '', this.href);
				ajax_navigation.updatePage();
				// Prevent default (cancel link)
				e.preventDefault();
			}
		} else {
			// External Link
			// Do nothing (default)
		}
	}
	this.resetMainMenu = function(){
		menu_items = document.getElementById('main-nav-main-menu').getElementsByTagName('li');
		for(i=0;i<menu_items.length;i++){
			menu_items[i].setAttribute('class', '');
		}
	}
	this.catchLinks = function(node){
		if(node){
			mainmenu_items = node.getElementsByTagName('a');
		} else {
			mainmenu_items = document.getElementsByTagName('a');
		}
		for(i=0;i<mainmenu_items.length;i++){
			if(!mainmenu_items[i].getAttribute('target')){
				if(mainmenu_items[i].getAttribute('data-ignore-ajax')!='true'){
					mainmenu_items[i].addEventListener("click", this.linkClick, true);
				}
			}
		}
	}
	if(this.shouldCatchLinks){
		history.replaceState(this.activeState, '', location.href);
		window.onpopstate = function(event){
			if(event.state===null){
				return false;
			}
			var search_location = location.protocol+'//'+document.domain+'/reviews/search/';
			if(location.href.indexOf(search_location)===0){
				document.location = location.href;
				return false;
			}
			ajax_navigation.updatePage();
		}
		this.catchLinks();
	}
	this.inBody = function(node){
		inBody = false;
		if(node){
			node = node.parentNode;
			while(node.nodeName!='#document'){
				if(node.nodeName=='BODY'){
					inBody = true;
					break;
				}
				node = node.parentNode;
			}
		}
		return inBody;
	}
}




