// turn overlay off or on
var useOverlay = false;

//check browser
/* 
var browserApp;
jQuery.each(jQuery.browser, function(i) {
   if($.browser.msie){ browserApp = "IE";}
   else if ($.browser.safari) {browserApp = "Safari"}
   else if ($.browser.opera) {browserApp = "Opera"}
   else if ($.browser.mozilla) {browserApp = "Mozilla"}

 });
*/

//function to load additonal JavaScript documents or style sheets


function loadFile(filename, filetype){
 if (filetype=="js"){ //if filename is an external JavaScript file
  var fileref = document.createElement("script");
  fileref.setAttribute("type","text/javascript");
  fileref.setAttribute("src", filename);
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref = document.createElement("link");
  fileref.setAttribute("rel", "stylesheet");
  fileref.setAttribute("type", "text/css");
  fileref.setAttribute("href", filename);
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref);
}

/********* Usage: ***************

loadFile("myscript.js", "js"); //dynamically load and add this .js file
loadFile("mystyle.css", "css"); //dynamically load and add this .css file  

********************************/

// initialize some variables

var URL = "null";
var xcoord, ycoord;

// Function to create a cookie and set its value

function setCookie(name, value, expires) {
    document.cookie = escape(name) + "=" + escape(value) + "; path=/" + 
        ((expires == null) ? "" : "; expires=" + expires.toGMTString(  ));
}

// Function to retrieve a cookie's value
function getCookie(name) {
    var cookiename = name + "=";
    var dc = document.cookie;
    var begin, end;

    if (dc.length > 0) {
        begin = dc.indexOf(cookiename);
        if (begin != -1) {
            begin += cookiename.length;
            end = dc.indexOf(";", begin);
            if (end == -1) {
                end = dc.length;
            }
            return unescape(dc.substring(begin, end));
        } 
    }
    return null;
}

// Function to delete a cookie
function deleteCookie(name) {
    document.cookie = name + "=; expires=Thu, 01-Jan-70 00:00:01 GMT" +  
        "; path=/";
}

// Function to set the Help cookie
function rememberHelp(setting) {
	
	var exp = new Date();               
exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * 31));  

	if (setting == 1){ setCookie("liveHelp", "on", exp);}
else if (setting == 0){ setCookie("liveHelp", "off", exp);}
}
	// set text for helpSelector
	
   var helpOn = '<span id="instructions">Click on the question marks for explanations</span> <span id="selectLink">Hide help</span>';
   var helpOff = '<span id="selectLink">Show help</span>';
   
function checkHelp() {
	if (getCookie('liveHelp') == "off"){
		$(".helpIcon").hide();
		$("#helpSelector").html(helpOff);
	}
}

////////////////// START execute when document is loaded ////////////////
   
$(document).ready(function(){
						   					   
	// load css file if missing							   
	if($(".help").length > 0 && $("link[href*='help.css']").length == 0) { loadFile("assets/css/help.css", "css"); }

	//add help icons where needed
	$(".help").after('<img src="assets/images/help/q-mark.png" alt="?" class="helpIcon" />');
						   
 	//add help HTML elements to document if necessary

	 var liveHelpDiv ='<div style="display: none;" id="liveHelp"><span class="tooltip"><span class="top"></span><span class="middle"><a href="javascript:remove();" class="closer">[Close]</a></span><span class="bottom"></span></span></div>';
	 var pointerDiv = '	<div class="" style="display: none;" id="pointer"></div>';
	 var helpSelectorDiv = '<div id="helpSelector"><span id="instructions">Click on the question marks for explanations</span> <span id="selectLink">Hide help</span></div>';
	 var overlayDiv = '<div id="overlay"></div>';

 
 	if($("div[id='liveHelp']").length == 0) { $("body").prepend(liveHelpDiv);}
 	if($("div[id='pointer']").length == 0) { $("body").prepend(pointerDiv);} 
 	if($(".help").length > 0 && $("div[id='helpSelector']").length == 0) { $("#maincontent").prepend(helpSelectorDiv);} 
 	if($("div[id='overlay']").length == 0) { $("body").prepend(overlayDiv);} 
				  
  // initially hide help-related layers
  	$("#liveHelp").hide();
	
  // set help status according to cookie
  	checkHelp();

  // set function for helpSelector: show or hide help icons, change link text
   
  var $help = $(".helpIcon");

  $("#helpSelector").click(function () { 
    if ($help.is(":hidden")) {
      		$(this).html(helpOn);  
		  	$help.toggle();
		  	rememberHelp(1);
		  } 
	else {
   		   	$(this).html(helpOff);
  			$help.toggle();
		  	rememberHelp(0);
		  }
 	 });
  
 // set function for clicking question marks: extract URL, call function to build help bubble
 
	 $(".helpIcon").click(function () {
									
		// get coordinates							
		xcoord = $(this).offset().left;
    	ycoord = $(this).offset().top;	

		// extract URL from preceding element						
		var theURL = $(this).prev().attr("href");
		URL = theURL;
		var caller;
		
		// read function call	
		if ($(this).attr("name").length !=0) {
			caller = $(this).attr("name"); 
			}
		else {
			caller = $(this).prev().attr("rel");  
			}
		eval(caller);
			
		  }); 
	 
	});
		
// /////////// END execute when loaded	 //////////////////////////
	
	

// gather window size
 
function getBWSize()
	{
	var myWidth = $(window).width();
	var myHeight = $(window).height()
				
	return {width:myWidth, height:myHeight};
	}

// get scrolling info

function getScrollXY() {
 
   var scrOfY = $(window).scrollTop();
   var scrOfX =$(window).scrollLeft();
  
   return {SX:scrOfX, SY:scrOfY};
}


//////////// the help display function /////////////////////////

function explain(what,linkcode) {
	var offset = 0; //250;	
	var msg = "";
// get click coordinates	
	//alertCoord(arguments[0]);
	
	var orient = 'left';
	var pt = $("#pointer");
	var ptWidth = pt.width();
	
			
//get URL
	var Lnk = URL;

	// assemble help contents
	if (linkcode && linkcode != 'noLink' && linkcode != 'null') {
			var content = '<span class="tooltip"><span class="top"></span><span class="middle"><a href="javascript:remove();" class="closer">[Close]</a>' + what + '<a href="' + linkcode + '"><p>Click here to go &gt;&gt;&gt;</p></a></span><span class="bottom"></span></span>';
		}
	else if (linkcode == 'noLink') {  //  means: don't make a link
			var content = '<span class="tooltip"><span class="top"></span><span class="middle"><a href="javascript:remove();" class="closer">[Close]</a>' + what + '</span><span class="bottom"></span></span>';
		}
	else {	// no linkcode there, use extracted URL
		var content = '<span class="tooltip"><span class="top"></span><span class="middle"><a href="javascript:remove();" class="closer">[Close]</a>' + what + '<a href="' + Lnk + '"><p>Click here to go &gt;&gt;&gt;</p></a></span><span class="bottom"></span></span>';
		}		
// pass contents into help bubble
	$("#liveHelp").html(content);
	
// show layer, get height
	if(useOverlay){ $("#overlay").fadeIn(300); }
	$("#liveHelp").fadeIn(300);
		
	var bubbleHeight = $(".tooltip").height();
	var bubbleWidth = $(".tooltip").width();
	var qmarkWidth = 20;
	msg+="w: "+bubbleWidth+", h: "+bubbleHeight+"; ";
// determine orientation, calculate horizontal position	

	if (xcoord < (bubbleWidth + ptWidth)) { // the clicked help icon is too far left to fit bubble on the left side
		orient = "right";
		pt.addClass("pointRight");	
		ptLeft = xcoord+qmarkWidth;
		bubbleLeft = xcoord+ptWidth+qmarkWidth-10; // subtract 10px for overlap w. pointer
		msg+= "point right "+bubbleLeft+"; ";
		}
	else {	bubbleLeft = xcoord - ptWidth - bubbleWidth; 
			ptLeft = xcoord - ptWidth;
			msg+= "point left "+bubbleLeft+"; ";
		}
	
// calculate vertical position

	
	var scrolled = getScrollXY(); 
	var bubbleTop = ycoord-(bubbleHeight/2); 
	var bw = getBWSize();
	
	
	if (scrolled.SY-bubbleTop > 0){ // = top of bubble is too high
		bubbleTop += scrolled.SY-bubbleTop-offset;
		msg+= "high ";
		}
	else if (bubbleTop+bubbleHeight - bw.height+scrolled.SY > 0 ) { // = bottom of bubble is too low
		msg+= "low ";
		var adj = bubbleTop+bubbleHeight-bw.height-scrolled.SY;
		
		if(adj>0){ bubbleTop -= adj;  
			}
		}
		msg+= "top: "+bubbleTop;
	//adjust for IE	  
		//if(browserApp=="IE"){ bubbleTop-=36; }
	
	
	
// move layer into place
	$("#liveHelp").css({left: bubbleLeft+"px",top: bubbleTop+"px"});
	//alert(msg);
	
//set coordinates and show pointer

		pt.fadeIn(300).css({left: ptLeft+"px",top: ycoord-24+"px"});
}
		
function remove() {
  // clean up style and hide help-related layers 
  
  	$("#pointer").hide(); //fadeOut(300);
  	$("#pointer").removeClass("pointRight");		
	$("#liveHelp").hide();//fadeOut(300);
	if(useOverlay){$("#overlay").fadeOut(300);}
}