var enablePrefetching = false;
var enableCaching = true;
var prefetchDelay = 250; //ms
var enableFirebugTracing = false;

//valid values for tracingType are:
// firebuglite  - firebug.d.console.cmd.log()
// firebug  - console.log()
// alert  - basic javascript alert()
// none  - no tracing/logging
var tracingType = 'none';

var currentUrl = '';
var currentLoadingUrl = '';
var defaultUrl = 'home';
var targetUrl = '';
var toHash = '';

var loadedInitialPage = false;

var xmlhttp = {};

var ajaxContentCache = {};


function loadContent(contentUrl, noRender) {
  trace('loadContent("' + contentUrl + '", ' + noRender + ')');
  
  // {{{ Determine contentUrl
  if (contentUrl.substr(0, 1) == '/') {
    contentUrl = contentUrl.substr(1);
  }
  
  if (contentUrl == '') {
    contentUrl = defaultUrl;
  }
  
  if (contentUrl.substr(0, 7) == 'comment') {
    //this is a REAL hash, lets artificially scroll to it
    moveToId(contentUrl);
    toHash = contentUrl;
    contentUrl = defaultUrl;
  }
  
  trace('contentUrl: ' + contentUrl + ', currentUrl: ' + currentUrl);
  
  if (contentUrl == currentUrl) {
    //no need to reload same content
    return;
  }
  // }}} Determine contentUrl
  
  if (!noRender) {
    currentUrl = contentUrl;
  }
  
  var content = getUrlCache(contentUrl);
  if (content != null) {
    trace("it's cached! calling setContent");
    setContent(content);
    return;
  }
  
  currentLoadingUrl = contentUrl;
  url = '/ajax.php?page=' + contentUrl;
  
  xmlhttp[contentUrl]=false;
  /*@cc_on @*/
  /*@if (@_jscript_version >= 5)
  // JScript gives us Conditional compilation, we can cope with old IE versions.
  // and security blocked creation of the objects.
   try {
    xmlhttp[contentUrl] = new ActiveXObject("Msxml2.XMLHTTP");
   } catch (e) {
    try {
     xmlhttp[contentUrl] = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (E) {
     xmlhttp[contentUrl] = false;
    }
   }
  @end @*/
  if (!xmlhttp[contentUrl] && typeof XMLHttpRequest!='undefined') {
    try {
      xmlhttp[contentUrl] = new XMLHttpRequest();
    } catch (e) {
      xmlhttp[contentUrl]=false;
    }
  }
  if (!xmlhttp[contentUrl] && window.createRequest) {
    try {
      xmlhttp[contentUrl] = window.createRequest();
    } catch (e) {
      xmlhttp[contentUrl]=false;
    }
  }
  
  if (xmlhttp[contentUrl] != null) {
    if (noRender) {
      trace('using stage_change_norender');
      xmlhttp[contentUrl].onreadystatechange = state_change_norender;
    } else {
      trace('using stage_change');
      xmlhttp[contentUrl].onreadystatechange = state_change;
    }
    xmlhttp[contentUrl].open("GET", url, true);
    xmlhttp[contentUrl].send(null);
  } else {
    alert("Your browser does not support XMLHTTP requests");
  }
  
}

function setContent(contentText) {
  var targ=document.getElementById('maincontent');
  targ.innerHTML = contentText;
  targ.className = "span-24 last " + getCssClass(currentUrl);
  parseScripts(targ);
  
  if (toHash) {
    moveToId(toHash);
    toHash = '';
  } else {
    moveToElement(document.body);
  }
  
  hijackUrls(targ);
  
  if (!loadedInitialPage) {
    //well, we just loaded it now!
    loadedInitialPage = true;
    trace('  starting prefetcher');
    startPrefetcher();
  }
}

function state_change() {
  
  if (xmlhttp[currentUrl].readyState == 4) {
    //loaded
    if (xmlhttp[currentUrl].status == 200) {
      trace('state_change: ' + currentUrl);
      //ok
      //cache it for later
      setUrlCache(currentUrl, xmlhttp[currentUrl].responseText);
      
      trace('state_change: calling setContent');
      //render the content
      setContent(xmlhttp[currentUrl].responseText);
      
    } else {
      alert("Problem retrieving data");
    }
  }
}

function state_change_norender() {
  
  if (xmlhttp[currentLoadingUrl].readyState == 4) {
    //loaded
    if (xmlhttp[currentLoadingUrl].status == 200) {
      trace('state_change_norender: storing in cache, ' + currentLoadingUrl);
      //ok
      //cache it for later
      setUrlCache(currentLoadingUrl, xmlhttp[currentLoadingUrl].responseText);
      
      trace('state_change_norender: starting prefetcher');
      //DO NOT render the content.
      //instead, start the prefetcher timer again
      startPrefetcher();
    }
  }
}

function hijackUrls(element) {
  aTags = element.getElementsByTagName('a');
  for (var i = 0; i < aTags.length; i++) {
  	if(aTags[i].rel.length > 1 && aTags[i].rel != 'nofollow'){
    	aTags[i].onclick = hijackedOnClick;
    }
  }
}

function hijackedOnClick() {
  toHash = '';
  var toRel = '';
  if (this.rel.search(/\#/) == -1) {
    //normal
    toRel = this.rel;
  } else {
    toRel = this.rel.split('#')[0];
    toHash = this.rel.split('#')[1];
  }
  SWFAddress.setValue(toRel);
  hilightNav(document.getElementById('nav'), toRel);
  return false;
}

function hilightNav(element, rel) {
  var lastClass = '';
  liTags = element.getElementsByTagName('li');
  for (var i = 0; i < liTags.length; i++) {
  	aTags = liTags[i].getElementsByTagName('a');
    
    var lastClass = '';
    if ($(liTags[i]).hasClass('last')) {
      lastClass = ' last';
    }
    
   	if(aTags[0].rel == rel){
   		liTags[i].className = rel.substr(1) + " active" + lastClass;
   	}else{
   		if(aTags[0].rel.length<1){
   			liTags[i].className = "schedule" + lastClass;//temp fix
   		}else{
   			liTags[i].className = aTags[0].rel.substr(1).replace(/\//, '_') + lastClass;
   		}
   	}
  }
}

function moveToId(id) {
  moveToElement(document.getElementById(id));
}

function moveToElement(el) {
  var selectedPosX = 0;
  var selectedPosY = 0;
  
  while(el != null) {
    selectedPosX += el.offsetLeft;
    selectedPosY += el.offsetTop;
    el = el.offsetParent;
  }
  
  window.scrollTo(selectedPosX, selectedPosY);
}

//PAGE LOAD
function pageLoaded(sDefaultUrl) {
  trace('pageLoaded("' + sDefaultUrl + '")');
  
  defaultUrl = sDefaultUrl;
  
  /**
   * This block of code was supposed to speed up page rendering
   * by grabbing the content within the <noscript> tag
   * as a starting point.
   *
   * Unfortunately, it doesn't work to well and ends up causing
   * WebKit-based browsers to fail to load the initial page.
   *
   * Solution?  Don't run this code!  Instead, force the initial
   * page to be loaded using ajax.
   *
   * Don't worry, if javascript isn't enabled, the user will
   * still get the <noscript> content by default.
   *
   *
  var el = document.getElementById('maincontentNoscript');
  if (el == null) {
    trace('el is null!');
  } else {
    if (el.innerText == null) {
      trace('el.innerText is null!');
    } else {
      var content = el.innerText;
      currentUrl = defaultUrl;
      setUrlCache(currentUrl, content);
      setContent(content);
    }
  }
  */
  
  sfHover();
  hijackUrls(document.getElementById('nav'));
  
  
  trace('  setting SWFAddress.onChange()');
  trace('  getPath(): ' + SWFAddress.getPath());
  
  SWFAddress.onChange = function() {
    loadContent(SWFAddress.getPath(), false);
  }
  
  trace('  calling loadContent()');
  loadContent(SWFAddress.getPath(), false);
  
  //trace('  starting prefetcher');
  //startPrefetcher();
}



//getCssClass -  returns appropriate css class based on currentURL, most cases simply strips slash and returns top level page name
function getCssClass(str) {
	var r;
	if(str.indexOf("/") > 0){
		r = str.split("/")[0];
	}else if(str.indexOf("_") > 0){
		r = str.split("_")[0];
	}else{
		r = str;
	}
	return r;
}

//parse and eval javscripts...
function parseScripts(t) {
	var scriptTags = t.getElementsByTagName("script");
	for (var i = 0; i < scriptTags.length; i++) {
		eval(scriptTags[i].text);
	}
	setSIFR();
}

var aUrlsToPrefetch = [
  'gallery',
  'gallery/4',
  'gallery/5'/*,
  'lineup',
  'lineup/saturday',
  'gallery/1',
  'gallery/2',
  'gallery/3',
  'tickets',
  'tickets/super',
  'lineup/sunday',
  'lineup/monday',
  'gorge',
  'gorge/camping',
  'gorge/map',
  'gorge/seating',
  'sponsors',
  'contact',
  'home', */
];

var prefetchTimer = null;

function startPrefetcher() {
  if (enablePrefetching) {
    prefetchTimer = window.setTimeout(prefetchOneUrl, prefetchDelay);
  }
}

function isUrlCached(url) {
  if (ajaxContentCache[url] != null && ajaxContentCache[url]) {
    return true;
  }
}

function getUrlCache(url) {
  if (enableCaching && isUrlCached(url)) {
    return ajaxContentCache[url];
  }
  return null;
}

function setUrlCache(url, content) {
  if (enableCaching) {
    ajaxContentCache[url] = content;
  }
}

function prefetchOneUrl() {
  for (var i = 0; i < aUrlsToPrefetch.length; ++i) {
    if (!isUrlCached(aUrlsToPrefetch[i])) {
      cacheUrl(aUrlsToPrefetch[i]);
      return;
    }
  }
}

function cacheUrl(url) {
  loadContent(url, true);
}

//valid values for tracingType are:
// firebuglite  - firebug.d.console.cmd.log()
// firebug  - console.log()
// alert  - basic javascript alert()
// none  - no tracing/logging

function trace(s) {
  switch (tracingType) {
    case "firebuglite":
      firebug.d.console.cmd.log(s);
      break;
    case "firebug":
      console.log(s);
      break;
    case "alert":
      alert(s);
      break;
    case "none":
    default:
      //no tracing/logging
  }
}
