// ************* GLOBALS ************** //
// Browser Capability Vars
var isStnd = document.getElementById ? true : false; // Standards compliant
var isIE = document.all ? true : false; // IE 4/5
var isNN4 = (navigator.appName=="Netscape" && navigator.appVersion.charAt(0)=="4") ? true : false; // NN 4.x
var isNN6 = (document.getElementById&&!document.all) ? true : false;
var DHTML = (isStnd || isIE || isNN4); // Any of the above

var isMac = (navigator.appVersion.indexOf( "Macintosh" ) != -1) ? true : false;
var isSafari = (navigator.appVersion.indexOf( "Safari" ) != -1) ? true : false;
var ie5 = false;
var pre_w3c = false;
var lspot = 0;
var printing = false;

// Flash Vars
var reqFlashVersion = 7;
var afv = 0;
var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;

// Page and Window Vars
var adjusted = 0;
var adjID = 0;
var pageName = "";
var newWindow = null;

// Downloads
var enDownload = true;

// ************* MAIN ************** //

w3c();

function initpage(){
	if(!pre_w3c){
		//adjustLayout();
		//setActions();
	}
	if(isIE && !(isMac && ie5)) addHovers("mn");
}
function box(txt){
	/*if (txt.value == txt.defaultValue) {
         txt.value = "";
     }*/
	var m = gbi("q");
	m.style.backgroundImage="none";
	
}
function boxText(txt,val){
	if (txt.value == "") {
        var m = gbi("q");
		m.style.backgroundImage="url('images/powered_by_google_58x15.gif')";
     }
	
}

function multiMenuState(id,imgsrc,xpos,ypos){
	var m = gbi(id);
	m.style.backgroundImage="url('"+imgsrc+"')";
	var pos = xpos+"px "+ypos+"px";
	m.style.backgroundPosition=pos;
	//alert(m.style.backgroundImage);
}
function swapBGImage(id,imgsrc){
	var m = gbi(id);
	m.style.backgroundImage="url('"+imgsrc+"')";
}
function setActions(){
	/*if(isStnd && !(isMac && ie5)){
 		a = document.getElementById("lessonroll");
		if(a != null){
			a.onmouseover = function () { setFlashVar("areaOut","lesson");}
			//a.onmouseout = function () { setFlashVar("areaOut","lesson");}
		}
 		a = document.getElementById("resourcesroll");
		if(a != null){
			a.onmouseover = function () { setFlashVar("areaOver","resources");}
			//a.onmouseout = function () { setFlashVar("areaOut","resources");}
		}
		a = document.getElementById("evaluationroll");
		if(a != null){
			a.onmouseover = function () { setFlashVar("areaOver","evaluation");}
			//a.onmouseout = function () { setFlashVar("areaOut","evaluation");}
		}
	}
	*/

	MM_preloadImages('../images/lessons_btn_dwn.gif','../images/handouts_btn_dwn.gif','../images/evaluation_btn_dwn.gif','../images/lessons_btn_r.gif','../images/handouts_btn_r.gif','../images/evaluation_btn_r.gif');
	
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function adjustLayout(){
	if(adjusted<2){
		pageName = getPageFileName();		
		var maxheight = 0;
		var offset = 100;
		
		// Subtract top components from equation
		var h = xHeight("header");
		var t = xHeight("tutils");
		var f = xHeight("footer");
		var adj = h+t;
		
		var w = xHeight("wrapper");
		var l1 = xHeight("level1");
		var l2 = xHeight("level2");
		var l3 = xHeight("level3");
		var c  = xHeight("content");
		maxheight = Math.max(w,Math.max(l1,Math.max(l2,Math.max(l3,c))));

		xHeight("level3", (maxheight+offset)-t);
		xHeight("level2", maxheight-adj-f);
		if(isIE) {
			xHeight("level1", maxheight-f);
			xHeight("wrapper", maxheight-f);
		} else {
			xHeight("level1", maxheight+(f*2));
			xHeight("wrapper", maxheight+f);
		}
		//if(isIE) {
			adjID = setTimeout('adjustLayout()', 60);
			adjusted += 1;
		//}
	} else {
		//adjust the page twice
		if(adjusted > 2){
			adjusted = 0;
			if(adjID) clearTimeout(adjID);
		}
	}
} 

function toggleDownload(lang){
	display("encon", enDownload);
	display("enconb", enDownload);
	display("escon", !enDownload);
	display("esconb", !enDownload);
	if(enDownload){ // Downloads in english
		swapImage('en', "url(images/download_o.gif)");
		swapImage('es', "url(images/spanish_r.gif)");
	}else{
		swapImage('en', "url(images/download_r.gif)");
		swapImage('es', "url(images/spanish_o.gif)");
	}
	enDownload = !enDownload;
}

function printPage(){
  if (window.print)
    window.print()
  else
    alert("Sorry, your browser does not support this feature. Please choose \"Print\" from the browser menu.");
}

function emailPage(){
	title = document.title;
	loc = document.location;
	// Uncomment following to use a mail form
	//document.location.href = "email.asp?title="+title;
	document.location.href = "mailto:?Subject="+title+"&Body="+loc;
}

function w3c()  { 

  if (navigator.appName.indexOf("Netscape") != -1) {
   var version = navigator.appVersion
    var subVersion = version.substring(0,3)
    var subVersion_p = parseFloat(subVersion)
     if (subVersion_p < 5)  {
		pre_w3c = true;
		isNS = false;
    }  
  }   
 if (navigator.appName.indexOf("Explorer") != -1) {
    var version = navigator.appVersion
    var subVersion = version.substring(22,25)
    var subVersion_p = parseFloat(subVersion)
     if (subVersion_p < 5)  {
	   pre_w3c = true;
	   isNS = false;
	 }
	 if ((subVersion_p == 5) || (subVersion_p == 5.5))  {
	   ie5 = true;
	 }
  }
}  

// Date variables

var day="";
var month="";
var ampm="";
var ampmhour="";
var myweekday="";
var year="";

var mydate = new Date();
var myday = mydate.getDay();
var mymonth = mydate.getMonth();
var myweekday= mydate.getDate();
var weekday= myweekday;
var myyear= mydate.getFullYear();
year = myyear;
var myhours = mydate.getHours();
var ampmhour  =  (myhours > 12) ? myhours - 12 : myhours;
var ampm =  (myhours >= 12) ? ' PM' : ' AM';
var mytime = mydate.getMinutes();
var myminutes =  ((mytime < 10) ? ':0' : ':') + mytime;
if(myday == 0)
day = " Sunday, ";
else if(myday == 1)
day = " Monday, ";
else if(myday == 2)
day = " Tuesday, ";
else if(myday == 3)
day = " Wednesday, ";
else if(myday == 4)
day = " Thursday, ";
else if(myday == 5)
day = " Friday, ";
else if(myday == 6)
day = " Saturday, ";
if(mymonth == 0) {
month = "January ";}
else if(mymonth ==1)
month = "February ";
else if(mymonth ==2)
month = "March ";
else if(mymonth ==3)
month = "April ";
else if(mymonth ==4)
month = "May ";
else if(mymonth ==5)
month = "June ";
else if(mymonth ==6)
month = "July ";
else if(mymonth ==7)
month = "August ";
else if(mymonth ==8)
month = "September ";
else if(mymonth ==9)
month = "October ";
else if(mymonth ==10)
month = "November ";
else if(mymonth ==11)
month = "December ";

/*
	util:implCheck use to check implementation on standards compliant browsers.
	Requires: none
	Returns: boolean
	Example: implCheck("DOM","2.0");
*/
function implCheck(feature, version){
	if (document.implementation &&
		  document.implementation.hasFeature &&
		  document.implementation.hasFeature(feature, version))
	   alert(feature + " version " + version + " support available");
	else
	   alert(feature + " version " + version + " NOT available");
}

// Page / DOM and Style adjustment functions
// 'xFunctions' requires LGPL licensed X-Library from Michael Foster

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


function adjustLayoutResize(){
	if(!printing){
		if(adjID) clearTimeout(adjID);
		adjusted = false;
		adjustLayout();
	} else {
		clearTimeout(adjID);
	}
}

function adjustSets(){
	var els = document.getElementById("ridge").getElementsByTagName("div");
	for (var i=0; i<els.length; i++) {
		if(els[i].className == "set"){
			var setH = xHeightObj(els[i]);
			if(setH < 140) xHeightObj(els[i], 140);
		}
	}
}

/* Primarily required for IE6 rollover functionality */
function processNested(n,nn){
	var els = document.getElementById(n).getElementsByTagName("LI");
	for (var i=0; i<els.length; i++) {
		els[i].onmouseover=function() {
			this.className+=" "+nn;
		}
		els[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" "+nn+"\\b"), "");
		}
	}
}

/* Primarily required for IE6 rollover functionality */
function addHovers(startID){
	var navRoot = document.getElementById(startID);
	for (i=0; i<navRoot.childNodes.length; i++) {
		node = navRoot.childNodes[i];
		if (node.nodeName=="LI"){
			if(node.id=="employerstab"){
				node.onmouseover=function() {
					this.className+=" ahover";
				}
				node.onmouseout=function() {
					this.className=this.className.replace(" ahover", "");
				}
				processNested("employerstab","ahover");
				
			}else if(node.id=="coordinatorstab"){
				node.onmouseover=function() {
					this.className+=" bhover";
				}
				node.onmouseout=function() {
					this.className=this.className.replace(" bhover", "");
				}
				processNested("coordinatorstab","bhover");
				
			}else if(node.id=="captainstab"){
				node.onmouseover=function() {
					this.className+=" chover";
				}
				node.onmouseout=function() {
					this.className=this.className.replace(" chover", "");
				}
				processNested("captainstab","chover");
				
			}else if(node.id=="participantstab"){
				node.onmouseover=function() {
					this.className+=" dhover";
				}
				node.onmouseout=function() {
					this.className=this.className.replace(" dhover", "");
				}
				processNested("participantstab","dhover");
				
			}else if(node.id=="edtab"){
				node.onmouseover=function() {
					this.className+=" ehover";
				}
				node.onmouseout=function() {
					this.className=this.className.replace(" ehover", "");
				}
				processNested("edtab","ehover");
				
			}else if(node.id=="restab"){
				node.onmouseover=function() {
					this.className+=" fhover";
				}
				node.onmouseout=function() {
					this.className=this.className.replace(" fhover", "");
				}
				processNested("restab","fhover");
				
			}


		}
	}
}

function getStyle(el,styleProp){
	var x = document.getElementById(el);
	if (window.getComputedStyle)
		var y = window.getComputedStyle(x,null).getPropertyValue(styleProp);
	else if (x.currentStyle)
		var y = eval('x.currentStyle.' + styleProp);
	return y;
}

function getActiveStyleSheet() {
var i, a;
 for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
  if(a.getAttribute("rel").indexOf("style") != -1
  && a.getAttribute("title")
  && !a.disabled) return a.getAttribute("title");
  }
  return null;
}

function getIsPrintStyleSheet() {
var i, a;
 for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
  if(a.getAttribute("rel").indexOf("style") != -1
  && a.getAttribute("title").indexOf("Print") != -1
  && !a.disabled) return a.getAttribute("title");
  }
  return null;
}

// GetPageFileName returns name of current file
function getPageFileName(){
	var f = document.location.href;
	var ix  = f.lastIndexOf('/');
	if ( ix > -1 ) f = f.substring( ix + 1 );
	var ix  = f.indexOf('?');
	if ( ix > -1 ) f = f.substring(0, ix);
	if(f==""){
		return "index.php";
	}else{
		return f;
	}
	//var page  = parseInt( ( f.substring( f.indexOf('Page') + 4 ) ), 10 );
}

function getFileName(path){
	var ix  = path.lastIndexOf('\\');
	if ( ix > -1 ) path = path.substring( ix + 1 );
	//alert("Path is " + path);
	if(path==""){
		return null;
	}else{
		return path;
	}
}
// Open window functions

function openWindow(page,width,height,sbars) {
	if (newWindow != null){
		if(navigator.appName.indexOf("Netscape")>=0){
			if(newWindow.name){
		 		newWindow.close();
			}
		}else{
			newWindow.close();
		}
	}
	newWindow = window.open(page, "newWin", "width=" + width + ",height=" + height + ",screenX=0,screenY=0,top=0,left=0,status=yes,toolbar=no,menubar=no,location=no,scrollbars=" + sbars + ",resizable=yes");
	//newWindow.location.href = page;
	if (newWindow.opener == null) newWindow.opener = window;

}

/* Note: MacIE5.2.3 takes relative links from the location of this script file,
note the location of the calling file */
function zoom(page,orientation) {
	//alert("Loc: " + document.location.href + "\n" + "Page: " + page);
	if(isIE && isMac) page = getBackPaths(page);
		//alert(page);
	if (newWindow != null){
		if(navigator.appName.indexOf("Netscape")>=0){
			if(newWindow.name){
		 		newWindow.close();
			}
		}else{
			newWindow.close();
		}
	}
	if(orientation == "landscape"){
		height = 560;
		width = 730;
	} else if(orientation == "portrait"){
		height = 710;
		width = 550;
	}
	newWindow = window.open(page, "newWin", "width=" + width + ",height=" + height + ",screenX=0,screenY=0,top=0,left=0,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=yes");
	//newWindow.location.href = page;
	if (newWindow.opener == null) newWindow.opener = window;

}

function getBackPaths(url) {
	var idx = url.indexOf('?');
	
	// Fix page
	var newpage = url.substring(0,idx) + "?";
	/*var backidx = page.indexOf('../../');
	if(backidx > -1) {
		var newpage =  "../../" + newpage.substring(backidx+6, newpage.length) + "?";
	} else {
		var newpage = "../" + newpage + "?";;
	}*/
	
	// Fix parameters
	if (idx != -1){
		var pairs = url.substring(idx+1, url.length).split('&');
		for (var i=0; i<pairs.length; i++){
			nameVal = pairs[i].split('=');
			var backidx = nameVal[1].lastIndexOf('../../');
			if(backidx > -1) {
				var newval = "back2" + nameVal[1].substring(backidx+6, nameVal[1].length);
			} else {
				var newval = nameVal[1];
			}
			//params[nameVal[0]] = newval;
			newpage = newpage + nameVal[0] + "=" + newval + "&";
		}
		newpage = newpage.substring(0, newpage.length-1);
	}
	return newpage;
} 

function openWindow_nobars(page,width,height,sbars) {
	if (newWindow != null){
		if(navigator.appName.indexOf("Netscape")>=0){
			if(newWindow.name){
		 		newWindow.close();
			}
		}else{
			newWindow.close();
		}
	}
	newWindow = window.open("", "newWin", "width=" + width + ",height=" + height + ",screenX=0,screenY=0,top=0,left=0,status=yes,toolbar=no,menubar=no,location=no,scrollbars=" + sbars + ",resizable=yes");
	newWindow.location.href = page;
	if (newWindow.opener == null) newWindow.opener = window;

}
// For flash fullscreen external windows
function fsi(theURL) {
	if(isIE){
		strFeatures = "top=0,left=0,scrollbars=no,resizeable=no,menubar=no,location=no,directories=no,status=no,titlebar=no,fullscreen=yes";
	}else{
		strFeatures = "top=0,left=0,scrollbars=no,resizeable=no,menubar=no,location=no,directories=no,status=no,titlebar=no";
	}
	newWindow = window.open(theURL, '', strFeatures, '');
}
// Delay clear window (esp. for MacIE5)
// Call from "Close Window" window link on the external window
function doClearWindow(){
	if(newWindow != null){
		newWindow.close();
		setTimeout ( "clearWindow", 2000 );
	}
}
function clearWindow(){
	newWindow = null;
}

// Flash functions
/*
	checkFlash sets up page for flash embed or alternative content.
	Requires: nothing
	Returns: globals
*/
function checkFlash(){
	if ( plugin ) {
		// Netscape
		afv = parseInt(plugin.description.substring(plugin.description.indexOf(".")-1));
		plugin = afv >= reqFlashVersion;
	} else if (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 && (navigator.userAgent.indexOf("Windows 95")>=0 || navigator.userAgent.indexOf("Windows 98")>=0 || navigator.userAgent.indexOf("Windows NT")>=0)) {
		// MSIE & PC
		document.write('<SCRIPT LANGUAGE=VBScript\> \n');
		document.write('on error resume next \n');
		document.write('plugin = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.4")))\n');
		document.write('<\/SCRIPT\> \n');
	}
}

/*
	wfjs "Write Flash JavaScript" embeds flash in page.
	Requires: 	n the flash object id name
				file the swf file path
				w the width
				h the height
				bgcolor the background color to apply, defaults to white
	Returns: flash object
*/
function wfjs(n,file,w,h,bgcolor){
	//if(!isMac && !isIE){
		if(bgcolor == null) bgcolor = "#FFFFFF";
		document.write("<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0\" width=\"" + w + "\" height=\"" + h + "\" id=\"" + n + "\" align=\"middle\">");
		document.write("<param name=\"allowScriptAccess\" value=\"sameDomain\" />");
		document.write("<param name=\"movie\" value=\"" + file + "\" />");
		document.write("<param name=\"quality\" value=\"high\" />");
		document.write("<param name=\"bgcolor\" value=\"" + bgcolor + "\" />");
		document.write("<embed src=\"" + file + "\" quality=\"high\" bgcolor=\"" + bgcolor + "\" width=\"" + w + "\" height=\"" + h + "\" name=\"" + n + "\" swLiveConnect=\"true\" align=\"middle\" allowScriptAccess=\"sameDomain\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" />");
		document.write("</object>");
	//}
}

/*
	setFlashVar sets a variable in flash.
	Requires: 	flashVar the name of the Flash varible to set
				args the text we are sending
	Note:		Requires that the Flash name/id is "movie"
	Returns: nothing
*/
function setFlashVar(flashVar,args){
	if(window.document.movie != null)
   		window.document.movie.SetVariable(flashVar, args);
}

// Layer functions 

/*
	Utility:getObj creates crossbrowser layer object.
	Requires: layer name
	Returns: self with obj and style reference
	Error checking: TODO check presence of 'objName' layer
*/
function getObj(objName) { 
	if (isStnd) { 
		this.obj = document.getElementById(objName); 
		this.style = document.getElementById(objName).style; 
	} else if (isIE) { 
		this.obj = document.all[objName]; 
		this.style = document.all[objName].style; 
	} else if (isNN4) { 
		//this.obj = document.layers[objName]; 
		//this.style = document.layers[objName]; 
		this.obj = xLayer(objName);
		this.style = xLayer(objName);
	} else {
		// Other browsers
		
	}
} 

/*
	Utility:visib toggle visibility of layer.
	Requires: layer name, boolean (show | hide)
	Returns: nothing
	Error checking: TODO check presence of 'objName' layer
*/
function visib(objName, flag) { // triggers layer visibility 
	var x = gbi(objName); 
	if(x != null) x.style.visibility = (flag) ? 'visible' : 'hidden'; 
} 
function display(objName, flag) { // triggers layer display 
	var x = gbi(objName);
	if(x != null) x.style.display = (flag) ? 'block' : 'none'; 
}
function positionAbsolute(objName) { // triggers layer display 
	var x = gbi(objName); 
	if(x != null) x.style.position = 'absolute';
	return x;
}
function positionRelative(objName) { // triggers layer display 
	var x = gbi(objName); 
	if(x != null) x.style.position = 'relative';
	return x;
} 
function positionStatic(objName) { // triggers layer display 
	var x = gbi(objName); 
	if(x != null) x.style.position = 'static';
	return x;
}
function swapImage(objName, imgPath) { // triggers layer display 
	var x = gbi(objName);
	if(x != null) x.style.backgroundImage = imgPath; 
}
function gbi(e) {
  if(typeof(e)!='string') return e;
  if(document.getElementById) e=document.getElementById(e);
  else if(document.all) e=document.all[e];
  else if(document.layers) e=xLayer(e);
  else e=null;
  return e;
}

function xLayer(id,root) { // only for nn4
  var i,layer,found=null;
  if (!root) root=window;
  for(i=0; i<root.document.layers.length; i++) {
    layer=root.document.layers[i];
    if(layer.id==id) return layer;
    if(layer.document.layers.length) found=xLayer(id,layer);
    if(found) return found;
  }
  return null;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}
function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}