var FADE_CONST=10;

// Passes a variable to a flash object
// Flash object must have the swLiveConnect="true" param set
function setFlashVar(flashObjId, varName, varValue) {
	message=("Setting "+flashObjId+"'s "+varName+" to "+varValue);
	if (typeof console != "undefined") {
		console.debug(message);
	} else {
		window.status=message;
	}
	document.getElementById(flashObjId).SetVariable(varName, varValue);
}


// onload function written by Simon Willison - http://simon.incutio.com
// use this function instead of window.onload - usage addLoadEvent(functionName)
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}
// end addLoadEvent()
/*----------------------*/

// function that allows getting elements by their class name. Returns the found elements in an array
document.getElementsByClassName = function(className)
{
	var children = document.getElementsByTagName('*') || document.all;
	var elements = [];
	for(i = 0; i < children.length; i++)
	{
		if(children[i].className == className)
			elements.push(children[i]);
	}
	return elements;
}
/*----------------*/

/***** XMLHTTPRequest object section  *****/
// Create XMLHttpRequest object
function Ajax()
{
	var xmlhttp;
	xmlhttp = false;
	// native XMLHttpRequest object like firefox and safari
	if(window.XMLHttpRequest)
	{
		try
		{
			xmlhttp = new XMLHttpRequest();
		}
		catch(e)
		{
			xmlhttp = false;
		}
	// IE/Windows ActiveX version (why do people still use this browser?)
	}
	else if(window.ActiveXObject)
	{
		try
		{
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(e)
		{
			try
			{
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(e)
			{
				xmlhttp = false;
			}
		}
	}
	if(!xmlhttp)
		alert("Error loading XMLHTTP object");
	return xmlhttp;
}	
/****** End XMLHTTPRequest object creation  *****/

function setOpacity(obj, opacity)
{	
	opacity = (opacity == 100)?99.999:opacity;
	// IE/Win
	obj.style.filter = "alpha(opacity:"+opacity+")";
	// Safari < 1.2, Konqueror
	obj.style.KHTMLOpacity = opacity/100;
	// Older Mozilla and Firefox
	obj.style.MozOpacity = opacity/100;
	// Safari 1.2, newer Firefox and Mozilla, CSS3
	obj.style.opacity = opacity/100;
}
/*----------------------*/

// fade in objects. Needs to be sent the element's id, starting opacity, and the speed in milliseconds
function fadeIn(objId,opacity,speed)
{
	clearTimeout(fadeInTimer);
	if (document.getElementById)
	{
		obj = document.getElementById(objId);
		if (opacity <= 100)
		{
			setOpacity(obj, opacity);
			opacity += FADE_CONST;
			var fadeInTimer = window.setTimeout("fadeIn('"+objId+"',"+opacity+","+speed+")", speed);
		}
	}
}
/*----------------------*/

// fade out an object
// accepts the element's id, starting opacity, ending opacity, and speed in milliseconds
function fadeOut(objId,opacity,target,speed)
{
	clearTimeout(fadeOutTimer);
	if (document.getElementById)
	{
		obj = document.getElementById(objId);
		if (opacity >= target)
		{
			setOpacity(obj, opacity);
			opacity -= FADE_CONST;
			if(arguments[4])
				var fadeOutTimer = window.setTimeout("fadeOut('"+objId+"',"+opacity+","+target+","+speed+",'"+arguments[4]+"')", speed);
			else
				var fadeOutTimer = window.setTimeout("fadeOut('"+objId+"',"+opacity+","+target+","+speed+")", speed);
		}
		else
		{
			if(target == 0 && arguments[4] == "hide")
				obj.style.display = "none";
		}
	}
}
/*----------------------*/

// open a popup window
// the para argument needs to be sent as a literal object. Ex. {width:300,height:300,scrollbars:1}
function openWin(url,wName,para)
{
	alert("hello");
	// of the para argument is an object than we need to parse the array
	if(typeof(para != "object"))
		var values = _parameters(para);
	alert(values);
	//window.open(url,wName,values);
}
/*----------------------*/

// process function arguments as an literal object
function _parameters(attributes)
{
	var values = [];
	for(attribute in attributes)
	{
		values.push(attribute + "=" + attributes[attribute].toString());
	}
	return values.join(",");
}
/*----------------------*/

var timer = 200;		// delay before menu is cleared. set in milliseconds
var timerID = 0;		// variable that holds the timeout function
var reTimerID = 0;		// Secondary timer for multiple request.
var oldID = "";

function startTimer(id,opacity,target,speed)
{
	timerID  = setTimeout("hideMessage('"+id+"',"+opacity+","+target+","+speed+")", timer);
}
/*----------------------*/

function clearTimer()
{
	// if the timer is set we clear it and reset it to 0
	if(timerID)
	{
		clearTimeout(timerID);
		timerID  = 0;
	}
}
/*----------------------*/

// fade out the image and show the corresponding message and address
var count = 0;	// used to create a unique id for new elements
function showMessage(id,opacity,target,speed)
{
	// grab all the element objects for the image, the parent element, and the address bar
	var el = document.getElementById(id);
	var pEl = el.parentNode;
	var addressBar = document.getElementById("addressBar");
	var div = document.createElement("div");
	// if an image has been faded already, bring it back
	if(oldID && oldID != id)
	{
		clearTimer();
		hideMessage(oldID,50,50);	
	}
	// if the element is already faded we return
	if(el.style.opacity == .3 || el.style.filter == "alpha(opacity:"+opacity+")")
	{
		return false;
	}
	
	fadeOut(id,target,target,speed); // Had to change from fadeOut(id,opacity,target,speed); to prevent clashing timers.
	
	
	// if the element id is a number and is not greater than the number of array positions
	// then we know the image is one of the top 8 images that have an address
	if(id.length < 8)
		var imageNum = id.substr((id.length-2),1)-1;
	else
		var imageNum = id.substr((id.length-3),2)-1;
	
	// test to see if the imageNum is a number so we know it's not a bottom image on the landing page
	if(!isNaN(imageNum) || imageNum < overArray.length)
	{
		var text = document.createTextNode(overArray[imageNum]);
				
		// if the addressBar element exists then we know the image is on the landing page rather than a video/audio popup
		if(addressBar != null)
		{
			var div = document.createElement("div");
			div.className = "addressText";
			div.style.left = (pEl.parentNode.offsetLeft + 5) + "px";
			var address = document.createTextNode(addressArray[id.substr((id.length-2),1)-1]);
			div.appendChild(address);
			addressBar.appendChild(div);
		}
		
	}
	else	// it's one of the bottom 3 images on the landing page
	{
		// grab the id without the # sign
		var string = id.split("#");
		switch(string[0])
		{
			case "videoImg1":
				var text = document.createTextNode(overArray[8]);
				break;
			case "audioImg1":
				var text = document.createTextNode(overArray[9]);
				break;
			case "panaImg1":
				var text = document.createTextNode(overArray[10]);
				break;
		}
	}	
	
	// If there are any elements left behind that haven't been deleted yet
	// Hide them (don't delete them or they won't exist for their later expected cleanup) until the cleanup gets to them.
	for (var tmp=0; tmp<=count; tmp++) {
		if (document.getElementById("id"+tmp)) {
			document.getElementById("id"+tmp).style.display="none";
		}
	}
	
	// get the top/left position for where the overlay text is going
	var top = (pEl.parentNode.offsetHeight / 2) - 10;
	var left = (pEl.parentNode.offsetWidth / 2);
	// create the required elements and assign the attributes and styles
	var div = document.createElement("div");
	var a = document.createElement("a");
	div.style.position = "absolute";
	div.style.top = top + "px";
	div.className = "hotspotBlurb";
	div.setAttribute("id", "id"+(count++)); // use the count variable as a unique ID
	// take the href of the parent link and assign it to our new link
	a.setAttribute("href",el.parentNode.getAttribute("href"));
	a.onclick = function()
	{
		openResizePop(this.href,'panaWin');
		return false;
	};
	a.onmouseover = function()
	{ 
		clearTimer();
	};
	a.appendChild(text);
	div.appendChild(a);
	if (div.innerHTML.indexOf("BREAK")>-1) {
		div.innerHTML=div.innerHTML.replace("BREAK", "<br />");
	}

	//a.innerHTML=div.id;
	pEl.parentNode.appendChild(div);
	
	// Hack the alignment for thumbCont cases - this was causing a bug in IE as relative/absolute positioning wasn't inherriting correctly.
	if (pEl.parentNode.className) {
		if (pEl.parentNode.className=="thumbCont") {
			pEl.parentNode.lastChild.style.left=pEl.parentNode.offsetLeft+"px";
		}
	}
	oldID = id;
}
/*----------------------*/

// fade image back and clear address if there is one
function hideMessage(id,opacity,target,speed)
{
	var el = document.getElementById(id);
	var addressBar = document.getElementById("addressBar");
	var pEl = el.parentNode.parentNode;
	// getting and parsing the alpha filter property for IE
	if(document.all)
	{
		var ie = el.style.filter.split(":");
		var ie = ie[1].split(")");
		if(Math.round(ie[0]) <= opacity)
			fadeIn(id,target,target,speed);	// Had to change from fadeIn(id,opacity,target,speed);	to prevent clashing timers.
	}
	// if the image is still faded we bring it back
	if(el.style.opacity <= (opacity/100))
		fadeIn(id,target,target,speed); // Had to change from fadeIn(id,opacity,target,speed); to prevent clashing timers.
	var childs = pEl.getElementsByTagName("div");
	for(i in childs)
	{
		if (typeof childs[i] == "object") {
			if(childs[i].nodeName.toLowerCase() == "div" && childs[i].getAttribute("id"))
			{
				var id = childs[i].getAttribute("id");
				pEl.removeChild(childs[i]);
			}
		}
	}
	if(addressBar != null)
	{
		// while the parent has kids, remove them
		while(addressBar.firstChild)
		{
			addressBar.removeChild(addressBar.firstChild);
		}	
	}

	
}
/*----------------------*/

// execute javascript from the AJAX responset text
function launchJavascript(responseText) {
  // RegExp from prototype.sonio.net
  var ScriptFragment = '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)';
           
  var matchExp    = new RegExp(ScriptFragment, 'img');
  var scripts  = responseText.match(matchExp);
  
    if(scripts)
	{
        var js = '';
        for(var s = 0; s < scripts.length; s++)
		{
            var matchExp = new RegExp(ScriptFragment, 'im');
            js += scripts[s].match(matchExp)[1];
        }
        eval(js);
    }
}
/*-------------------------*/

// show or hide an element
function showItem(el,method)
{
	if(typeof(el) == "object")
		el.style.display = method;
	else
		document.getElementById(el).style.display = method;
}
/*-------------------------*/

// this gives the code a pause for people with slower connections.
function timeout(ms)
{
	var start = new Date();
	var stop = start.getTime() + ms;
	while(true)
	{
		var start = new Date()
		if(start.getTime() > stop)
			return true;
	}
}
/*-------------------------*/

// launches the videos for the video interviews popup
function launchVideo(video)
{
	var videoCont = document.getElementById("playerScript");
	var videoHTML = "<script type='text/javascript'>"
    videoHTML +=	"so = new FlashObject('/media/departures/flash/videoPlayer.swf', 'videoPlayer', '320', '283', '8', '#000000');"
    videoHTML +=	"so.addParam('scale', 'noscale');"
    videoHTML +=	"so.addParam('AllowScriptAccess', 'always');"
	// path to video
    videoHTML +=   	"so.addVariable('videoURL','" + video + "');"
    videoHTML +=   	"so.write('player');"
	videoHTML += "</script>";
	videoCont.innerHTML = videoHTML;
	launchJavascript(videoHTML);
}
/*-------------------------*/

// Class for the slide feature
function Slide(coverEl,id)
{
	this.coverEl = document.getElementById(coverEl);	// this is the top element
	this.el = document.getElementById(id);				// this is the element that will slide down
	this.el.style.display = "block";
	this.coverEl.style.position = "relative";
	this.coverEl.style.zIndex = 2;
	this.el.style.top = "0";
	this.el.style.zIndex = 1;
	this.startTop = (this.coverEl.offsetHeight - this.el.offsetHeight);
	this.targetTop = this.coverEl.offsetHeight;
	
	appVer = navigator.appVersion;
	if(navigator.appCodeName == "Mozilla" && appVer.indexOf("Mac") != -1)
	{
		this.firefoxMac = true;
	} else {
		this.firefoxMac = false;
	}
	//alert(this.el);
}
/*-------------------------*/

// function that activates the element to slide down
// first whe check to see if the element is already shown. If it is, we just replace the include with another
Slide.prototype.initSlide = function(incName)
{
	slideIt.incName = incName;
	slideIt.el = document.getElementById("metaOuter");
	//alert(this.el);
	var top = slideIt.el.style.top;
	slideIt.container = (document.getElementById("metaCont")) ? document.getElementById("metaCont") : document.getElementById("metaCont2");
	
	if(top.substring(0,(top.length-2)) == this.targetTop)
	{
		slideIt.container.style.visibility = "hidden";
		timeout(250);
		alert("i see you");
		slideIt.getInc();
	}
	else
	{
		slideIt.container.style.visibility = "hidden";
		slideIt.slideDown();
	}
	return false;
}
/*-------------------------*/


// Gives a convenient method to set all tags of a certain type, within metaOuter to a new display value

Slide.prototype.setAllExceptFooter = function(tagName, newDisplay) {
	parentObj=document.getElementById("metaOuter");
	childrenAry=parentObj.getElementsByTagName(tagName);
	for (i=0; i<childrenAry.length; i++) {
		thisEntry=childrenAry[i];
		if (typeof thisEntry == "object") {
			skip=false;
			if (thisEntry.id!=null) {
				if (thisEntry.id=="footer") {
					skip=true;
				}
			}
			if (skip==false) { 
				thisEntry.style.display=newDisplay; 
			}
		}
	}
}


// get the requested include file from the server
Slide.prototype.getInc = function()
{
	var ajax = Ajax();
	if(!this.incName)
		return false;
	ajax.open("GET",this.incName,true);
	ajax.onreadystatechange=function()
	{
		if (ajax.readyState==4)
		{
			if(ajax.status == 200)
			{
				//setOpacity(slideIt.container,0);
				slideIt.container.innerHTML = ajax.responseText;
				//var tempTimer = setTimeout("writeHTML("+ajax.responseText+")",1500)
				//writeHTML(ajax.responseText);
				if(!document.getElementById("metaMid"))
				{
					slideIt.container.setAttribute("id","metaCont2")
					var temp = document.getElementById("metaCont2")
				}
				else
				{
					slideIt.container.setAttribute("id","metaCont");
					var temp = document.getElementById("metaCont");
				}
				//var timer1 = setTimeout("fadeIn('"+slideIt.container.id+"',"+0+","+100+","+25+")",1500);
				//setOpacity(slideIt.container,100);
				//setTimeout("showItem('"+slideIt.container.id+"','block')",1500);
				//timeout(1500);
				//alert("timeout reached");
				slideIt.container.style.visibility = "visible";
				launchJavascript(ajax.responseText);				
			}
			else
			{
				alert("Data failed to load because the file, " + pageName + ", wasn't found on the server.");
			}
		}
	 }
	 ajax.send("");
	//ajax.close();
	return false;
}
/*-------------------------*/

// not being used at the moment
function writeHTML(responseText)
{
	slideIt.container.innerHTML = responseText;
}

// slide the element down
Slide.prototype.slideDown = function()
{
	clearTimeout(slideIt.slideDownTimer);
	slideIt.startTop += 15;
	if(slideIt.startTop < slideIt.targetTop)
	{
		slideIt.el.style.top = slideIt.startTop + "px";
		slideIt.slideDownTimer = setTimeout("slideIt.slideDown()",10);
	}
	else
	{
		slideIt.el.style.top = slideIt.targetTop + "px";
		clearTimeout(slideIt.slideDownTimer);
		slideIt.getInc();	// go get the requested file
	}
	if (this.firefoxMac) {
		this.setAllExceptFooter("table", "block");
		this.setAllExceptFooter("div", "block");
		document.getElementById("footer").style.marginTop="10px";
	}
}
/*-------------------------*/




// clear out the video/audio flash content so it doesn't play when the bottom part closes
Slide.prototype.preSlideUp = function()
{
	var audio = document.getElementsByClassName("audioStory");
	for(var i = 0; i < audio.length; i++)
	{
		audio[i].innerHTML = "";
	}
	document.getElementById("flashVid").innerHTML = "";
}

// slide the element back up
var firstSlide = 1;		// flag to tell if the increment up is the first one
Slide.prototype.slideUp = function()
{
	clearTimeout(this.slideUpTimer);
	// if this is the first increment up we clear out the flash files to stop them from playing
	if(firstSlide == 1)
		this.preSlideUp();
	this.container.style.visibility = "hidden";		// need to hide the content again so flash movies don't appear on top of each other
	this.startTop -= 15;
	if(this.startTop > (this.coverEl.offsetHeight - this.el.offsetHeight))
	{
		this.el.style.top = this.startTop + "px";
		this.slideUpTimer = setTimeout("slideIt.slideUp()",10);
	}
	else
	{
		this.el.style.top = "0";
		clearTimeout(this.slideUpTimer);
		firstSlide = 1;
	}
	if (this.firefoxMac) {
		this.setAllExceptFooter("table", "none");
		this.setAllExceptFooter("div", "none");
		document.getElementById("footer").style.display="block";
		document.getElementById("footer").style.marginTop="350px";
	}
}
/*-------------------------*/

// show/hide the editor's notes
Slide.prototype.editorNotes = function()
{
	// grab the read link and the notes themselves
	var editorLink = document.getElementById("editorLink");
	var el = document.getElementById("editorNotes");
	if(el.style.display == "none")
	{
		// set the notes opacity to 0 and display to block so we can fade it in then hide the link
		setOpacity(el,0);
		el.style.display = "block";
		editorLink.innerHTML = "Close";
		editorLink.setAttribute("title","Close editor notes")
		fadeIn(el.id,0,50);
	}
	else
	{
		editorLink.innerHTML = "Read";
		editorLink.setAttribute("title","Read the Editor's Notes")
		fadeOut(el.id,100,0,25,"hide");
	}
	//this.startTop = (this.coverEl.offsetHeight - this.el.offsetHeight);
}
/*-------------------------*/

function resizeToScreen() {
	self.moveTo(0,0);
	
	appVer = navigator.appVersion;
	if((navigator.userAgent.indexOf("Firefox") > -1) && (appVer.indexOf("Mac") != -1)) { 
		// Do nothing as Mac Firefox has issues with screen resizing.
	} else {
		self.resizeTo(screen.width,screen.height);
	}
}