/***
Very, very, very important tidbits...
  None of this code works with out the <!-- mark --> and <!-- unmark --> comment tags inside all the template files.  Those comments
  are used to help the javascript find the content of the page that it should be sucking into the current page.  Without, it can't find
  crap.
 
TODO
- retitle page
- get body class
***/

// Instantiate the location checker...
var checker;
// Instantiate our pageHistory holder...
var pageHistory = "";

document.observe('dom:loaded', function(){
	$('ajaxnavLoading').setStyle({ position: "absolute", display: "none", top: "280px", textAlign: "center", width: "100%" });
	$('ajaxnavLoading').setOpacity(0);
	
	// Arm main nav
	var mainnavitems = $$('#main-nav ul li a');
	if (mainnavitems!="") { addAjaxBehaviour(mainnavitems); }
	var footernavitems = $$('#footer-nav ul li a');
	if (footernavitems!="") { addAjaxBehaviour(footernavitems); }
	
	
	// Support bookmarks and shares
	// Check if a hash is available...
	if (document.location.hash != "") {

		// We've got something in the hash...try and get the page...

		clearInterval(checker); // Kill the interval, don't want it checking while we're ajax-i-fying...
		// Hide the content...
		$('ajaxnavLoading').setStyle({display: "block"});
		$('ajaxnavLoading').setOpacity(1);
		$('content').setOpacity(0);

		// Request the page...
		new Ajax.Request("http://www.cadence-unplugged.com" + document.location.hash.replace("#",""), {
			method:'get',
			onSuccess: function(transport){
				var response = transport.responseText || "no response text";
				// Get our demarked content
				var regex2 = new RegExp('<!-- mark -->((.|\n|\f|\r)*?)<!-- unmark -->','i');
				contents = regex2.exec(response);
				// Check and see regex returned something we can use...
				if (contents != null) {
					// Get the title
					var regex = new RegExp('<title>((.|\n|\f|\r)*?)</title>','i');
					title = regex.exec(response);
					if (title != null) {
						document.title = title[1];
					}
					// Get the body class...
					regex = new RegExp('<body class="([^"]*?)">','i');
					bodyClass = regex.exec(response);
					// Apply body class (some of the sIFR replacement targets need it)...
					var body = $$('body'); body = body[0]; // This is why I hate Prototype
					body.className = bodyClass[1];
					// Write out the content and store the page history...
					pageHistory = document.location.hash.replace("#","");
					$('content').update(contents[1]);
				} else {
					// Eventually won't need this, but oughtta keep it just in case
					window.history.back(); // Push back so the hash updates
					alert("Couldn't load the requested page...");
				}
				// Fade it all in, arm the newly created sub navs, and fire up the URL checker...
				new Effect.Opacity('ajaxnavLoading', { from: 1, to: 0, duration: 0.2, afterFinish: function() { $('ajaxnavLoading').setStyle({display: "none"}); } });
				new Effect.Opacity('content', { from: 0, to: 1.0, duration: 1 });
				armNavSubs();
				checker = setInterval("checkForChange();", 200);
			},
			onFailure: function(){
				alert("Couldn't load the requested page...");
				new Effect.Opacity('ajaxnavLoading', { from: 1, to: 0, duration: 0.2, afterFinish: function() { $('ajaxnavLoading').setStyle({display: "none"}); } });
				new Effect.Opacity('content', { from: 0, to: 1.0, duration: 1 });
				// Clear the hash, it wasn't valid...
				document.location.hash = "";
				checker = setInterval("checkForChange();", 200);
			}
		});
		
	} else {
		// No hash, therefore arm the sub navs, if they exist, and fire up the checker...
		var subnavtopitems = $$('#sub-nav-top ul li a');
		var subnavitems = $$('#sub-nav ul li a');
		if (subnavitems!="") { addAjaxBehaviour(subnavitems); }
		if (subnavtopitems!="") { addAjaxBehaviour(subnavtopitems); }
		
		// Also arm other special content links, if they exist...
		var calReturnLinks = $$('.calendar-returnlink a');
		var calLinks = $$('#cal-calendar a');
		if (calReturnLinks !="") { addAjaxBehaviour(calReturnLinks); }
		if (calLinks !="") { addAjaxBehaviour(calLinks); }
		
		// Check for changes in the URL vs. the history...
		checker = setInterval("checkForChange();", 200);
	}
	//Arm the home logo, no matter what...
	var logo = $$('#logo-link a');
	addAjaxBehaviour(logo);


});

function checkForChange() {
	/* var historyCheck = $('history') ? $('history').innerHTML : "";
	historyCheck = historyCheck == document.location.href.replace(document.location.protocol + "//" + document.location.host,"") ? "" : historyCheck;
	alert("History: " + historyCheck);
	var hashCheck = document.location.hash.replace("#","") != "" ? document.location.hash.replace("#","") : document.location.href.replace(document.location.protocol + "//" + document.location.host,"");
	alert("Hash Check: " + hashCheck);
	clearInterval(checker);
	checker = setInterval("checkForChange();", 8000); */
	
	// Set up a var, in case the history var doesn't have a value...
	var historyCheck = pageHistory;
	// Check to make sure the history path doesn't exist the current page; if it does, empty it...
	historyCheck = historyCheck == document.location.href.replace(document.location.protocol + "//" + document.location.host,"") ? "" : historyCheck;
	
	// HASH is URL escaping the "&" in the news page argument, need to sanitize hash or history...probably history
	historyCheck = historyCheck.replace(/&amp;/g, "&");


	// Check it against the hash, and if they don't match, load the correct page...
	if (historyCheck != document.location.hash.replace("#","")) {
		// Need a hash check to see if the person used the back button all the way to their original page, and there's no hash...
		var hashCheck = document.location.hash.replace("#","") != "" ? document.location.hash.replace("#","") : document.location.href.replace(document.location.protocol + "//" + document.location.host,"");
		// Kill the checker, and bring in loading graphics...
		clearInterval(checker);
		$('ajaxnavLoading').setStyle({display: "block"});
		$('ajaxnavLoading').setOpacity(1);
		$('content').setOpacity(0);
		// Get the page...
		new Ajax.Request("http://www.cadence-unplugged.com" + hashCheck, {
			method:'get',
			onSuccess: function(transport){
				var response = transport.responseText || "no response text";
				var regex2 = new RegExp('<!-- mark -->((.|\n|\f|\r)*?)<!-- unmark -->','i');
				contents = regex2.exec(response);
				// Check and see regex returned something we can use...
				if (contents != null) {
					var regex = new RegExp('<title>((.|\n|\f|\r)*?)</title>','i');
					title = regex.exec(response);
					if (title != null) {
						document.title = title[1];
					}
					regex = new RegExp('<body class="([^"]*?)">','i');
					bodyClass = regex.exec(response);
					var body = $$('body'); body = body[0];
					body.className = bodyClass[1];
					// Write out the content and redefine the history var
					pageHistory = hashCheck;
					$('content').update(contents[1]);
				} else {
					window.history.back();
					alert("Couldn't load the requested page...");
				}
				new Effect.Opacity('ajaxnavLoading', { from: 1, to: 0, duration: 0.2, afterFinish: function() { $('ajaxnavLoading').setStyle({display: "none"}); } });
				new Effect.Opacity('content', { from: 0, to: 1.0, duration: 1 });
				armNavSubs();
				checker = setInterval("checkForChange();", 200);
			},
			onFailure: function(){
				alert("Couldn't load the requested page...");
				new Effect.Opacity('ajaxnavLoading', { from: 1, to: 0, duration: 0.2, afterFinish: function() { $('ajaxnavLoading').setStyle({display: "none"}); } });
				new Effect.Opacity('content', { from: 0, to: 1.0, duration: 1 });
				document.location.hash = "";
				checker = setInterval("checkForChange();", 200);
			}
		});
	}
}

// Function for adding the ajax loading behaviour to the sub nav items after they get sucked in...
function armNavSubs() {
	var subnavtopitems = $$('#sub-nav-top ul li a');
	var subnavitems = $$('#sub-nav ul li a');
	if (subnavitems!="") { addAjaxBehaviour(subnavitems); }
	if (subnavtopitems!="") { addAjaxBehaviour(subnavtopitems); }
	
	// Also arm other special content links, if they exist...
	var calReturnLinks = $$('.calendar-returnlink a');
	var calLinks = $$('#cal-calendar a');
	if (calReturnLinks !="") { addAjaxBehaviour(calReturnLinks); }
	if (calLinks !="") { addAjaxBehaviour(calLinks); }

	reloadSifr();
}

// This removes the sifr-config.js file and reincludes it, so that flash replacement happens
function reloadSifr() {
	// Reload sifr-config.js...
	var scripts = $$('script');
	for (var i=0;i<scripts.length;i++) {
		if (scripts[i].src.indexOf('sifr-config') > -1) {
			Element.remove(scripts[i]);
		}
	}
	include_dom('js/sifr-config.js');
}

// Add ajax loading to nav items...
function addAjaxBehaviour(navitems) {
	for (var i=0;i<navitems.length;i++) {
		// Exception for main nav items
		
		navitems[i].onclick = function() {
			// If we clicked a main nav anchor, then reset it's class
			if (this.parentNode.parentNode.parentNode.readAttribute('id') == 'main-nav') {
				resetMainNav(this);
			}
			clearInterval(checker);
			$('ajaxnavLoading').setStyle({display: "block"});
			$('ajaxnavLoading').setOpacity(1);
			$('content').setOpacity(0);
			
			var cleanedHref = this.href.replace(document.location.protocol + "//" + document.location.host,"");
			document.location.hash = cleanedHref;
			new Ajax.Request(this.href, {
				method:'get',
				onSuccess: function(transport){
					var response = transport.responseText || "no response text";
					var regex2 = new RegExp('<!-- mark -->((.|\n|\f|\r)*?)<!-- unmark -->','i');
					contents = regex2.exec(response);
					if (contents != null) {
						var regex = new RegExp('<title>((.|\n|\f|\r)*?)</title>','i');
						title = regex.exec(response);
						if (title != null) {
							document.title = title[1];
						}
						// Get the body class...
						regex = new RegExp('<body class="([^"]*?)">','i');
						bodyClass = regex.exec(response);
						var body = $$('body'); body = body[0];
						body.className = bodyClass[1];
						pageHistory = cleanedHref;
						$('content').update(contents[1]);
					} else {
						//document.location.hash = $('history').innerHTML;
						window.history.back();
						alert("Couldn't load the requested page...");
					}
					new Effect.Opacity('ajaxnavLoading', { from: 1, to: 0, duration: 0.2, afterFinish: function() { $('ajaxnavLoading').setStyle({display: "none"}); } });
					new Effect.Opacity('content', { from: 0, to: 1.0, duration: 1 });
					armNavSubs();
					checker = setInterval("checkForChange();", 200);

				},
				onFailure: function(){
					alert("Couldn't load the requested page...");
					new Effect.Opacity('ajaxnavLoading', { from: 1, to: 0, duration: 0.2, afterFinish: function() { $('ajaxnavLoading').setStyle({display: "none"}); } });
					new Effect.Opacity('content', { from: 0, to: 1.0, duration: 1 });
					checker = setInterval("checkForChange();", 200);
				}
			});

			return false;
		}

	}
}

function resetMainNav(anchor) {
	var mainnavitems = $$('#main-nav ul li a');
	if (mainnavitems!="") {
		for (var i=0;i<mainnavitems.length;i++) {
			mainnavitems[i].removeClassName('activeparent');
			mainnavitems[i].removeClassName('currentpage');
		}
		anchor.addClassName('activeparent');
	}
}

function include_dom(script_filename) {
    var html_doc = document.getElementsByTagName('head').item(0);
    var js = document.createElement('script');
    js.setAttribute('language', 'javascript');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', script_filename);
    html_doc.appendChild(js);
    return false;
}