/* 
================================================================================================================================ CREDITS
Copyright 	: Copyright 2011 LearntobeHealthy.org. All Rights Reserved.
Date      	: 03/11/2011
Notes     	: JavaScript file for handling various events ... onLoad, onClick, etc
================================================================================================================================ BEGIN JAVASCRIPT
*/

/* ============================================================================================================================= MULTIPLE ONLOAD HANDLER */

var onLoadFunctions = new Array();
var iloadFunction = 0;

// Pass each function that needs to load
function add_on_load(func) {
    onLoadFunctions[iloadFunction] = func;
    iloadFunction++;
}
// Loops through all of the functions that were added
function loadAllFunctions() {
    for (var i = 0; i < onLoadFunctions.length; i++) {
        eval(onLoadFunctions[i]+"()");
    }
}
// Load all of the functions that you've set
window.onload = loadAllFunctions;

/* ============================================================================================================================= CALL FUNCTIONS TO BE LOADED */

add_on_load("dropdown_menus");
add_on_load("load_modals");
add_on_load("load_flash");
add_on_load("share_callout");
add_on_load("legend_callout");
add_on_load("init_tooltips");
add_on_load("tour_videos");
add_on_load("auto_focus");

/* ============================================================================================================================= COMMON FUNCTIONS */

// ---------------------------------------------------------- WINDOW LOCATION
var url = window.location.toString();

// ---------------------------------------------------------- USER AGENT
var isie = navigator.userAgent.toLowerCase().indexOf('msie');

// ---------------------------------------------------------- GET PREVIOUS SIBLING
function prevSibling(n) {
	do n = n.previousSibling;
	while (n && n.nodeType != 1);
	return n;
}

// ---------------------------------------------------------- GET NEXT SIBLING
function nextSibling(n) {
	do n = n.nextSibling;
	while (n && n.nodeType != 1);
	return n;
}

// ---------------------------------------------------------- GET CHILD BASED ON NODENAME YOU SPECIFY
function getChild(n,char) {
	for (var i = 0; i < n.childNodes.length; i++) {
		if (n.childNodes[i].nodeName == char) {
			n = n.childNodes[i];
			break;
		}
	}
	return n;
}

// ---------------------------------------------------------- GET VALUE OF QUERYSTRING PARAMETER
function getQueryValue(key) {
	key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");

	var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
	var qs = regex.exec(window.location.href);
	if (qs == null) {
		return "";
	}
	return qs[1];
}

/* ============================================================================================================================= MAIN NAV DROPDOWN MENUS */

function dropdown_menus() {
	var nav = document.getElementById("nav");
	if (nav != null) {
		// FOR IE6: UPDATE LI CLASS NAME SO THAT THE SUB-LISTS ARE DISPLAYED
		for (var i = 0; i < nav.childNodes.length; i++) {
			node = nav.childNodes[i];
			if (node.nodeName == "LI") {
				node.onmouseover = function() { 
					this.className += " iehover";
				}
				node.onmouseout = function() { 
					this.className = this.className.replace(" iehover", "");
				}
			 }
		}
		// KEEP HOVER STATE OF THE LINK ACTIVE AS USER LOOKS AT SUB-NAVIGATION
		function showDropDown() {
			var a = getChild(this.parentNode, 'A');
			if (a != null) {
				a.className = "active";
			}
		}
		function hideDropDown() {
			var a = getChild(this.parentNode, 'A');
			if (a != null) {
				a.className = "";
			}
		}
		
		var i = 0;		
		if (document.getElementById('subnav'+i) != null) {
			while(document.getElementById('subnav' + i)) {
				document.getElementById('subnav' + i).onmouseover = showDropDown;

				var a = getChild(document.getElementById('subnav' + i).parentNode, 'A');
				if (a.className != 'active') {
					document.getElementById('subnav' + i).onmouseout = hideDropDown;
				}
				i++;
			}
		}
	}
}

/* ============================================================================================================================= LOAD MODALS */

function load_modals() {
	if(typeof init_modal == 'function') {
		init_modal();
	}
}

/* ============================================================================================================================= LOAD FLASH FILES */

function load_flash() {
	// HEALTH LOG
	if (document.getElementById('health-log') != null) {
        var alt = document.getElementById('health-log-alt');
		var flashvars = { theme: "parent" };
        var params = { wmode: "transparent" };
        var attributes = {};

		swfobject.embedSWF(
			"/teens/lib/swf/healthlog.swf", "health-log", "900", "620", "8.0.0", "/lib/swf/expressInstall.swf", 
			flashvars, params, attributes
		);
		if (alt != null) alt.style.visibility = "visible";
	}
	// TAKE A TOUR VIDEOS
	if (document.getElementById('site-tour-video') != null) {
		var alt = document.getElementById('site-tour-video-alt');
		var flashvars = { video: "100", iswide: "true" };
		var params = { wmode: "transparent", base: ".", allowFullScreen: "true" };
		var attributes = {};
        
		swfobject.embedSWF(
			"/parents-teachers/lib/swf/videoPlayer_premium.swf", "site-tour-video", "514", "376", "9.0.0", "/lib/swf/expressInstall.swf", 
			flashvars, params, attributes
		);
		if (alt != null) alt.style.visibility = "visible";
	}
}

/* ============================================================================================================================= SHARE FUNCTIONALITY */

function share_callout() {	
    var share_button = document.getElementById("share-button");
	if (share_button != null) {
		var share = document.getElementById("share");
		var share_links = document.getElementById("share-links");
		
		share_button.onclick = function() {
			if (share.className == "share-inactive") {
				share.className = "share-active";
				share_links.className = "";
			} else {
				share.className = "share-inactive";			
				share_links.className = "hid";
			}
			return false;
		}
	}

	// UPDATE SHARE LINKS TO BE THE CURRENT URL AND PAGE TITLE
	var pgTitle = document.title ? escape(document.title) : escape('LearntobeHealthy.org');
	var pgUrl =  document.location ? escape(document.location) : escape('http://www.learntobehealthy.org');

	// SOCIAL MEDIA SITES ARRAY: Twitter, Facebook, Del.icio.us
	var arrLinks = new Array();
		arrLinks[0] = 'http://www.facebook.com/share.php?u=' + pgUrl;
		arrLinks[1] = 'http://del.icio.us/post?url=' + pgUrl + '&amp;title=' + pgTitle;
		
	if (document.getElementById('share0') != null) {
	   for (var i = 0; i < arrLinks.length; i++) {
			document.getElementById('share'+i).href = arrLinks[i];
		}
	}
}

/* ============================================================================================================================= SEARCH LEGEND */

function legend_callout() {	
    var legend_button = document.getElementById("legend-button");
	if (legend_button != null) {
		var legend = document.getElementById("legend");
		
		legend_button.onclick = function() {
			if (legend.className == "legend-inactive") {
				legend.className = "legend-active";
			} else {
				legend.className = "legend-inactive";			
			}
			return false;
		}
	}
}

/* ============================================================================================================================= LOAD TOOL TIPS */

function init_tooltips() {
	function tooltip_mouseover() {
		enabletip = true;
		var span = nextSibling(this);
		if (span != null) {
			showTip(document.getElementById("tooltip"), span.innerHTML);
		}
	}
	function tooltip_mouseout() {
		enabletip = false;
		document.getElementById("tooltip").style.visibility = "hidden";
		document.getElementById("tooltip").style.left = "-9999px";
	}

	var i = 0;
	var div = document.getElementById('tooltips-container');
	if (div != null) {
		// GIVE TOOLTIP A WIDTH
		document.getElementById("tooltip").style.width = '280px';
	} else {
		// RESET TOOLTIP CONTAINER FOR KIT PAGES
		div	= document.getElementById('results-container'); 
		if (div == null) {
			div	= document.getElementById('activities'); 
		}
	}

	if (div != null) {
		var arrImgs = div.getElementsByTagName('img');
		for (var i = 0; i < arrImgs.length; i++) { 
			if (arrImgs[i].className == "tooltip") {
				arrImgs[i].onmouseover = tooltip_mouseover;
				arrImgs[i].onmouseout = tooltip_mouseout;
			}
		}
	}
	if (document.getElementById('tooltip_grpmembership') != null) {
		document.getElementById('tooltip_grpmembership').onmouseover = tooltip_mouseover;
		document.getElementById('tooltip_grpmembership').onmouseout = tooltip_mouseout;
		document.getElementById('tooltip_grpmembership').onclick = function() { return false; }
	}
}

/* ============================================================================================================================= TOUR VIDEOS */

function pass_video_to_flash() {
	var xml_id = this.href.split('video');
	if (xml_id[1] != null) {
		resetVideoPlayer(xml_id[1]);
	}
	return false;
}

function thisMovie(movieName) {
	if (window.document[movieName]) return window.document[movieName];
	if (navigator.appName.indexOf("Microsoft Internet") == -1) {
		if (document.embeds && document.embeds[movieName]) return document.embeds[movieName]; 
	} else {
		return document.getElementById(movieName);
	} 
}

function resetVideoPlayer(xml_id) {
	if (document.getElementById('site-tour-video-alt') == null) {
		if (document.getElementById('site-tour-video') != null) {
			thisMovie("site-tour-video").resetVideoPlayer(xml_id);
		}
	}
}

function tour_videos() {
	var div = document.getElementById('tour-list');
	if (div != null) {
		var arrLinks = div.getElementsByTagName('a');
		for (var i = 0; i < arrLinks.length; i++) { 
			if (arrLinks[i].rel == "tourvideo") {
				arrLinks[i].onclick = pass_video_to_flash;
			}
		}
	}
}

/* ============================================================================================================================= AUTO FOCUS ON SELECT FORM FIELDS */

function auto_focus() {
	var span = document.getElementById('userid');
	if (span != null) {
		if (span.childNodes[0] != null) {
			var field = document.getElementById(span.childNodes[0].id);
			if (field != null) {
				field.focus();
			}
		}
	}
}

/* ============================================================================================================================= KIT POPUPS */

/* USED IN EDUCATORS/TEENS/KIDS */

var ltbhWindow;

function launchCourse(folder, activity, width, height) {
	if (typeof width == "undefined" || isNaN(width)) width = 780;
	if (typeof height == "undefined" || isNaN(height)) height = 580;
	if (ltbhWindow && !ltbhWindow.closed) ltbhWindow.close();
	ltbhWindow = popup("/kits/" + folder + "/Activity" + activity + "/start.aspx", "ltbhKit", width, height, "no", "no");
}

function launchDoc(documentPath) {
	var courseW = 800;
	var courseH = 580;
	if (document.all || document.layers || document.getElementById) {
		w = screen.availWidth;
		h = screen.availHeight;
	}
	var leftPos = (w-courseW)/2;
	var topPos = (h-courseH)/2;
	var myWin = window.open('','program','scrollbars,toolbar,width='+courseW+ ',height='+courseH+',top='+topPos+',left='+leftPos);
	
	myWin.document.write("<HTML><style type=\"text/css\">body { margin:0; padding:0; }</style><BODY>");
	myWin.document.write("<OBJECT codeBase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0 height=570 width=760 classid=clsid:D27CDB6E-AE6D-11cf-96B8-444553540000 VIEWASTEXT>");
	myWin.document.write("<PARAM NAME='movie' VALUE='" + documentPath + "'>")
	myWin.document.write("<PARAM NAME='quality' VALUE='high'>")
	myWin.document.write("<PARAM NAME='SCALE' VALUE='exactfit'>")
	myWin.document.write("<EMBED src='" + documentPath + "' width='760' height='570' quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' scale='exactfit'></EMBED>");
	myWin.document.write("</OBJECT></BODY></HTML>");
}

/* ============================================================================================================================= OTHER FUNCTIONS */

/* MOVED OVER FROM common.js - NOT SURE OF USE/NEED */

function toggle(divName) {
	div = document.getElementById(divName);
	div.style.display = (div.style.display == "none" || div.style.display == "") ? "block" : "none";
	return false;
}

function popup(cPopUrl, cPopName, iPopWidth, iPopHeight, bScrollBars, resizable) {
	var iPopLeft, iPopTop;
	var oPopWindow;
	if (!oPopWindow || oPopWindow.closed){
		//Center popup window inside parent window.
		iPopLeft = (window.screen.width/2) - ((iPopWidth/2) + 10);
		iPopTop = (window.screen.height/2) - ((iPopHeight/2) + 50);
		//Open popup window
		params = "height="+ iPopHeight +",width="+ iPopWidth +",left=" + iPopLeft + ",top=" + iPopTop + ",screenX=" + iPopLeft + ",screenY=" + iPopTop + ",scrollbars=" + bScrollBars + ",resizable=" + resizable + ", status=yes";
		//alert(params);
		oPopWindow=open(cPopUrl, cPopName, params);
		oPopWindow.location.href = cPopUrl;
		oPopWindow.focus()
	} else {
		oPopWindow.focus()
	}
	return oPopWindow;
}

function showMore(id){
	document.getElementById(id+'-read').style.display = 'none';
	document.getElementById(id+'-more').style.display = 'block';
}

