addLoadEvent(getSWFObj);
addLoadEvent(initDisplayStuff);
addLoadEvent(prepareTextOnlyLinks);

////////////////////////////////////////////

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

////////////////////////////////////////////

function navActive() {
	return (swfObj.sectionNav != null);
}

////////////////////////////////////////////

//jamie's variables:

	var currID = "";           // currently-active ID (e.g. q1_sec1_link0_media)
	var currContext = "media"; // current context of this page (media|navbar|text)
	var flashHeight = 460;     // height of flash movie in media mode
	var navbarHeight = 56;     // height of flash movie in navbar mode
	var swfObj;        // instance of SWF; used to send navigation commands from Javascript

////////////////////////////////////////////

function initDisplayStuff() {
	var myHash = document.location.hash;
		if(myHash != '') {
			var newContext = myHash.split('#');
			if(newContext[1] != '') {
				currContext = newContext[1];
			}
		} else {
			var currContext = "media";
		}
	
	if(currContext == "media") {
	//"Media" view
		toggleFlashSection();
	} else if(currContext == "navbar") {
	//"In Depth" view
		document.getElementById("flash_main").style.height = "56px";
		Element.show('in_depth_updater');
	} else {
	//text only
		Element.hide("flash_main");
		Element.show('in_depth_updater');
		Element.show('maintoggle');
		//$("id_nav").style.visibility = "visible";
	}
}
	
////////////////////////////////////////////

function getSWFObj(){
	// run getSWFObj() on load to make an instance of the SWF accessible.
	if(navigator.appName.indexOf("Microsoft") != -1){
		swfObj = window['mySWF'];
	}else{
		swfObj = document['mySWF'];
	}
}

////////////////////////////////////////////
	
function navigateFromHTML(newID){
	// use navigateFromHTML(newID) to navigate to a new section/link from within the web page.
	swfObj.sectionNav(newID);
	return false;
}
	
////////////////////////////////////////////
	
function setIDFromFlash(newID) {
// setIDFromFlash(newID) is called from the SWF.
//expecting: q1_sec1_link0_navbar

	var ID_array = newID.split('_');
	var context = ID_array[3].toLowerCase();

	var question = ID_array[0].substring(1);
	var section = ID_array[1].substring(3);
	
	var link = ID_array[2];
	var linkParts = link.split("=");
	
	if(linkParts.length > 1) {
		var linkUrl = linkParts[1];
	} else {
		linkUrl = '';
	}
	
	//need to convert section to a-z, instead of 1-9	
	if(section == '0') {
		section = '';
	} else {
		var newSection = convertNumToAlpha(section);
		section = newSection;
	}

	if (context=="navbar") {  
		setFlashHeight("swfDiv", navbarHeight);
		document.getElementById("flash_main").style.height = "56px";
		Element.show('in_depth_updater');
		
		if(linkUrl != '') {
			ajaxInDepthByUrl(linkUrl);
		} else {
			ajaxInDepth(question, section);
		}
		
	} else if(context=="text") {
		Element.show('maintoggle');
	} else {
		setFlashHeight("swfDiv", flashHeight);
		Element.hide('in_depth_updater');
		document.getElementById("flash_main").style.height = "460px";
		ajaxInDepth(question, section);
	}
	currID = newID;
}  
      
////////////////////////////////////////////
   
function getCurrID() {
	// getCurrID() is called by the SWF when it is first loaded.
	// If you change currID to something else, you can actually set the SWF 
	// to go directly to a certain section on load.
	// by default, though, currID is just an empty string on load, so the SWF ignores it.
	return currID.toString();
}

////////////////////////////////////////////

function ajaxInDepthByUrl(idURL) {
        console.info("ajaxInDepthByUrl "+idURL);
	var query = location.search;
	
	if(query != '') {
		idURL = idURL + query;
	}
	
	new Ajax.Request(
		idURL, { method: 'get', 
			onComplete: function(transport) {
				var returnMe = transport.responseText;
				var myParts = returnMe.split("<!-- indepth -->");
				if (returnMe.indexOf("Page not found") > -1) {
				   alert("Page not found "+idURL);
				}
				var inDepthChunk = myParts[1];
				//console.info("inDepthChunk",inDepthChunk);
				Element.update('in_depth_updater', inDepthChunk);
				//resizeBy(0,1);
				//resizeBy(0,-1);
				var theBody = document.getElementsByTagName("body")[0];
				theBody.style.display = "none";
				theBody.style.display = "block";
				scrollTo(0,0);
				prepareTextOnlyLinks();	
			}
		}
	);
}

////////////////////////////////////////////

function ajaxInDepth(section, subSection) {
	//this function wil only be used with the main question index.html pages and the
	//main sub-sections index.html pages

	//NEED TO ADD THE "link" var into this equations, so we can ajax all the little sub-links
	//and still sync with the flash piece...
	
	if(subSection == '') {
		var idURL = "/centennial/im/inquiry/sections/" + section + "/index.html";
	} else {
		var idURL = "/centennial/im/inquiry/sections/" + section + "/" + subSection + "/index.html";
	}
	
	var query = location.search;
	
	if(query != '') {
		idURL = idURL + query;
	}
	
	new Ajax.Request(
		idURL, { method: 'get', 
			onComplete: function(transport) {
				var returnMe = transport.responseText;
				var myParts = returnMe.split("<!-- indepth -->");
				
				var inDepthChunk = myParts[1];				
				Element.update('in_depth_updater', inDepthChunk);
				//resizeBy(0,1);
				//resizeBy(0,-1);
				var theBody = document.getElementsByTagName("body")[0];
				theBody.style.display = "none";
				theBody.style.display = "block";
				scrollTo(0,0);
				prepareTextOnlyLinks();		
			}
		}
	);
}

////////////////////////////////////////////

function toggleFlashSection() {

	if($("flash_main")) {
		Element.show('flash_main');
	}
	
	if($("in_depth_updater")) {
		Element.hide('in_depth_updater');
	}
	
	if($("maintoggle")) {
		Element.hide('maintoggle');
	}
	
	return false;
}

////////////////////////////////////////////

function toggleInDepthSection() {
		
		Element.hide('maintoggle');
		setFlashHeight("swfDiv", navbarHeight);
		document.getElementById("flash_main").style.height = "56px";
		Element.show('flash_main');
		Element.show('in_depth_updater');
		document.location.hash = "navbar";
		ajaxInDepth('1', '');

	return false;
}

////////////////////////////////////////////

function toggleTextSection() {
//this really is just for the text only section now
		Element.hide("flash_main");
		Effect.Appear('in_depth_updater');
		Element.show('maintoggle');
		
		document.location.hash = "text";
		prepareTextOnlyLinks();

	return false;
}

////////////////////////////////////////////

function prepareTextOnlyLinks() {
	//var idNav = document.getElementById("id_nav");
	var breadCrumb = document.getElementById("breadcrumb");
	var textCopy = document.getElementById("textcopy");

	if(breadCrumb && textCopy) {
		//var navLinks = idNav.getElementsByTagName("a");
		var crumbLinks = breadCrumb.getElementsByTagName("a");
		var syncLinks = textCopy.getElementsByTagName("a");
		
		var myQuery = location.search;
		var myHash = document.location.hash;
		if(myHash != '') {
			var newContext = myHash.split('#');
			if(newContext[1] != '') {
				currContext = newContext[1];
			}
		} else {
			var currContext = "navbar";
		}
		//addAjaxHandlerToTextLinks(navLinks, myQuery, currContext, 1);
		addAjaxHandlerToTextLinks(crumbLinks, myQuery, currContext, 1);
		addAjaxHandlerToTextLinks(syncLinks, myQuery, currContext, 1);
		createPodcasts(textCopy);
	} //else {alert("error: no text area");}
}


////////////////////////////////////////////

function createPodcasts(area) {
   var alla = area.getElementsByTagName("a");
   for (var x=0;x<alla.length;x++) {
      var a = alla[x];
      if (a.className.indexOf('audio') > -1) {
           var src = a.href;
           console.info("Matching MP3",src);
           var fo = new SWFObject("/centennial/im/inquiry/flash/audio-player.swf", "flashObject", "290", "24", "8", "#ffffff");
           fo.addVariable("soundFile", src);
           fo.addVariable("bg","0xEFEFEF");
           fo.addVariable("leftbg","0x265086");
           fo.addVariable("lefticon","0xF2F2F2");
           fo.addVariable("rightbg","0x265086");
           fo.addVariable("rightbghover","0x5a87c0");
           fo.addVariable("righticon","0xF2F2F2");
           fo.addVariable("righticonhover","0xFFFFFF");
           fo.addVariable("text","0x454545");
           fo.addVariable("slider","0x454545");
           fo.addVariable("track","0xF6F6E8");
           fo.addVariable("border","0xF6F6E8");
           fo.addVariable("loader","0xAAAAAA");
           if (fo.installedVer.versionIsValid(fo.getAttribute('version'))) {
              fo.write(a.parentNode);
           }
      }
   }

}


////////////////////////////////////////////

function addAjaxHandlerToTextLinks(textLinks, myQuery, currContext, syncFlash) {
//textLinks is an array of our links.
//currContext: either navbar, media, or text
//syncFlash, either 1 or 0, tells us whether or not to sync up with the flash movie

	for(var i=0; i<textLinks.length; i++) {
		var theHref = textLinks[i].getAttribute("href");
		var temp = theHref.split("#");
	
		if(myQuery != '') {
			var newHref = temp[0] + myQuery;
		} else {
			var newHref =  temp[0];
		}
	
		var myHref = newHref + "#" + currContext;
	
		textLinks[i].href = myHref; //for IE
		textLinks[i].setAttribute("href", myHref);
	
		//if its the navbar (In Depth) section, add an event handler to it
		if(currContext == "navbar") {
			textLinks[i].onclick = function() {
				var goTo = this.href.split('#');
				var myParts = goTo[0].split("sections/");
				var dissected = myParts[1].split("/");
				var q = dissected[0];
				var sec = dissected[1];
				
				if(syncFlash == 1) {
				//then use the navigateFromHTML function

					if(sec != '' && sec.length < 2) {
						sec = convertAlphaToNum(sec);
					} else {
						sec = '0';
					}
					
					var newID ='q' + q + '_sec' + sec + '_link=' + goTo[0] + '_' + currContext;
					navigateFromHTML(newID);
					
					//console.info("You just triggered the navigateFromHTML function. The parts of the newID are: \n\n q = " + q + "\n\n sec = " + sec + "\n\n link = " + goTo[0] + "\n\n context = " + currContext);
					//console.info("You just triggered the navigateFromHTML function. The newID var is: \n\n" + newID);
				}
				
				ajaxInDepthByUrl(goTo[0]);
				return false;
			}
		} 
	}
}

////////////////////////////////////////////

function convertNumToAlpha(num) {
	var alphabet = "abcdefghijklmnopqrstuvwxyz";
	var pos = alphabet.charAt(num-1);
	
	return pos;
}

////////////////////////////////////////////

function convertAlphaToNum(letter) {
	var alphabet = "abcdefghijklmnopqrstuvwxyz";
	var pos = alphabet.indexOf(letter) + 1;

	return pos;
}

////////////////////////////////////////////

function winPopUp(strURL,strType,strHeight,strWidth) {
var strOptions="";
if (strType=="slideshow") strOptions="height="+strHeight+",width="+strWidth+"top=150,left=70,scrollbars=no, status=no, resizable=yes";
if (strType=="console") strOptions="resizable,height="+strHeight+",width="+strWidth;
if (strType=="fixed") strOptions="status,scrollbars,resizable,height="+strHeight+",width="+strWidth;
if (strType=="elastic") strOptions="toolbar,menubar,scrollbars,resizable,location,height="+strHeight+",width="+strWidth;
window.open(strURL, 'popupWin', strOptions);
}

////////////////////////////////////////////

function getElementsByClassName(className, tag, elm) {
	//getElementsByClassName("info-links", "a", document);
	
	var testClass = new RegExp("(^|\\\\s)" + className + "(\\\\s|$)");
	var tag = tag || "*";
	var elm = elm || document;
	var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
	var returnElements = [];
	var current;
	var length = elements.length;
	for(var i=0; i<length; i++){
		current = elements[i];
		if(testClass.test(current.className)){
			returnElements.push(current);
		}
	}
	return returnElements;
}

//////////////////////////////////////

function goToUrl(listItem) {
//gets the href of the li's child (a) and goes there

var theLink = listItem.firstChild.href;
location.href = theLink;

}

//////////////////////

function showSub(whichElm, pointerPos, lineWidth) {
//switches the person view on mouseover from tertiary level pages

	Element.hide('defaultSubText');	
	var hideThese = getElementsByClassName('subList', 'div', document);

	for(var i=0; i<hideThese.length; i++) {
		var myID = hideThese[i].getAttribute("id");
			if(myID != whichElm) {
				Element.hide(myID);
			} else {
				var linePos = (pointerPos*1) + 1;
				document.getElementById(myID).style.display = "block";
				
				document.getElementById("pointer").style.display = "block";
				document.getElementById("pointer").style.left = pointerPos + "px";
				
				document.getElementById("line").style.display = "block";
				document.getElementById("line").style.left = linePos + "px";
				document.getElementById("line").style.width = lineWidth + "px";
			}
	}	
}


/* 
 * for browsers that don't support logging
 */
 
if(!("console" in window) || !("firebug" in console)) {
   var names = ["log", "debug", "info", "warn", "error", "assert","dir", "dirxml", "group"
                , "groupEnd", "time", "timeEnd", "count", "trace","profile", "profileEnd"];
   window.console = {};
   for (var i = 0; i <names.length; ++i) window.console[names[i]] = function() {};
}