window.onload = function() {
  setLinks();
};

function setLinks() {
  if (!document.getElementsByTagName) return false;
  var links = document.getElementsByTagName("a");
  if (links.length == 0) return false;
  for (var i = 0; i < links.length; i++) {
    var relation = links[i].getAttribute("rel");
    if (relation == "external") {
      links[i].onclick = function() {
        return !window.open(this.href);
      };
    }     
  }
}

var glob = new Array();
glob['counter_form'] = '';
glob['counter_elm'] = '';
glob['counter_cnt'] = 0;

var tempX = 0;
var tempY = 0;

function getMouseXY(e)
{
  if (IE)
  	{ 	// grab the x-y pos.s if browser is IE
	    tempX = event.clientX + document.body.scrollLeft;
	    tempY = event.clientY + document.body.scrollTop;
	} 
  else 
	{	// grab the x-y pos.s if browser is NS
	    tempX = e.pageX;
	    tempY = e.pageY;
	}  
  
  if (tempX < 0){tempX = 0;} // catch possible negative values in NS4
  if (tempY < 0){tempY = 0;}  

  return true;
}

function checkIt(string) // Pattern matching routine
{
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

var detect = navigator.userAgent.toLowerCase(); // Detect Web Browser routine
var OS,browser,version,total,thestring;

if (checkIt('konqueror'))
{
	browser = "Konqueror";
	OS = "Linux";
}
else if (checkIt('safari')) browser = "Safari";
else if (checkIt('omniweb')) browser = "OmniWeb";
else if (checkIt('opera')) browser = "Opera";
else if (checkIt('webtv')) browser = "WebTV";
else if (checkIt('icab')) browser = "iCab";
else if (checkIt('msie')) browser = "Internet Explorer";
else if (!checkIt('compatible'))
{
	browser = "Netscape Navigator";
	version = detect.charAt(8);
}
else browser = "An unknown browser";

if (!version) version = detect.charAt(place + thestring.length);

if (!OS)
{
	if (checkIt('linux')) OS = "Linux";
	else if (checkIt('x11')) OS = "Unix";
	else if (checkIt('mac')) OS = "Mac";
	else if (checkIt('win')) OS = "Windows";
	else OS = "an unknown operating system";
}

function clearInput(obj, defaultvalue) // Clears the input on field focus
{
	if(obj.value == defaultvalue)
		obj.value = "";
}

function checkEnter(obj, evt, act) // Check event keypress for enter button
{
	
	var netscape = 0; // Backward compatibility for netscape
	if(browser == "Netscape" && version >= 3)
		netscape = 1;	
	
	if (netscape) // Grab client input event
	{
		code = evt.which;
	}
	else
	{
		code = evt.keyCode;		
	}
	
	if (code == 13) // If client inputs enter key
	{
		switch(act)
		{
			case 'next':
				var next = obj.tabIndex;
				next++;
		  		if (next < obj.form.length)
					obj.form.elements[next].focus();
				break;
			case 'submit':
				obj.form.submit();
				break;				
			default:
				// do nothing
				break;
		}
	}
}

function package_buy(package, typ) // Check which package client can purchase
{
	var url = 'subscribe';
	var method = "start";
	if (typ == 'gift')
	{
		url = 'gifts';
		method = 'register';
	}
	document.location.href = '/' +url+ '/' + method + '/' + package;
}

function showDiv(what, prefix, showobj) // Drop down payment details based on payment type
{
	// what		=> form element
	// prefix 	=> id prefix to hide/show
	// showobj	=> object to auto show when any pattern is matched
	 
	var divs = document.getElementsByTagName('div');
	var show = document.getElementById(showobj);
	
	for(var i = 0; i < divs.length; i++) // Iterate through div elements
	{
		var elm = divs[i];
		if(elm.id.match(eval("/^" +prefix+ "_/"))) // Match object prefix
			if(elm.id == prefix +"_" + what.value)
				elm.style.display = "";
			else
				elm.style.display = "none";
	}
	if(what.value != "")
		show.style.display = "";
	else
		show.style.display = "none";		
}

function modexample(frm, obj, act, example)
{
	var frm = eval('document.' + frm);
	var obj = eval('frm' + '.' + obj);
	obj.value = example;
	frm.action = act;
	frm.submit();
}

function initialize_quickstart()
{
	var parentshow = document.getElementById("parent");	
	var indstudentshow = document.getElementById("independent_student");		
	indstudentshow.style.display = "none";	
	parentshow.style.display = "none";	
	
	var selectObj = document.getElementById("1001");
	selectObj.selectedIndex = 0;		
}

function show_quickstart(selectObj)
{
	var selectValue = selectObj.options[selectObj.selectedIndex].value;	
	var parentshow = document.getElementById("parent");	
	var indstudentshow = document.getElementById("independent_student");		
	
	if (selectValue == 2)
	{
		parentshow.style.display = "";
		indstudentshow.style.display = "none";
	}
	else if (selectValue == 3)
	{
		parentshow.style.display = "none";
		indstudentshow.style.display = "";		
	}
	else
	{
		indstudentshow.style.display = "none";	
		parentshow.style.display = "none";			
	}	
}

function skipInterviewQuestion(qid)
{
	var elm = document.forms[0];
	qid = parseInt(qid) + 1;
	elm.action = '/interview/nextquestion/' + qid;
	elm.submit();	
}

function addLightbox(title,strHref,boxWidth, boxHeight,close) // FUNC: Lightbox Creator
{
//Explicitly set our Javascript domain to allow interaction with iframe hosted under a subdomain
document.domain='starquestdance.com';
	
var overlay = document.getElementById('screenoverlay'); //Make sure we have screenoverlay and topbox
if (overlay == null) {
	overlay = document.createElement('div');
	overlay.setAttribute('id', 'screenoverlay');
	document.body.appendChild(overlay);
}
overlay.style.visibility = "hidden";
//overlay.style.width = "100%";
//overlay.style.height = "100%";

var topbox = document.getElementById('topbox');
if (topbox == null) {
	topbox = document.createElement('div');
	topbox.setAttribute('id', 'topbox');
	document.body.appendChild(topbox);
}
topbox.style.visibility = "hidden";
overlay.style.width = boxWidth;
overlay.style.height = boxHeight;
topbox.style.left= "50%";
topbox.style.top = "50%";
topbox.style.marginLeft = 0;
topbox.style.marginTop = 0;

var myForm = document.createElement("form");
myForm.method="POST";
myForm.action = "/tests/lightbox/showVariableIframe" ;
myForm.setAttribute('id', 'jsLightboxForm');
var myInput = document.createElement("input") ;
myInput.setAttribute("name", "lightboxtitle");
myInput.setAttribute("type", "hidden");
myInput.setAttribute("value", title);
myForm.appendChild(myInput);
var myInput = document.createElement("input") ;
myInput.setAttribute("name", "iframehref");
myInput.setAttribute("type", "hidden");
myInput.setAttribute("value", strHref);
myForm.appendChild(myInput);
var myInput = document.createElement("input") ;
myInput.setAttribute("name", "iframewidth");
myInput.setAttribute("type", "hidden");
myInput.setAttribute("value", boxWidth-10);
myForm.appendChild(myInput);
var myInput = document.createElement("input") ;
myInput.setAttribute("name", "iframeheight");
myInput.setAttribute("type", "hidden");
myInput.setAttribute("value", boxHeight-50);
myForm.appendChild(myInput);
var myInput = document.createElement("input") ;
myInput.setAttribute("name", "lightboxclosable");
myInput.setAttribute("type", "hidden");
myInput.setAttribute("value", close);
myForm.appendChild(myInput);
document.body.appendChild(myForm);

xmlhttpSubmit("jsLightboxForm", "topbox", myForm.action, myForm.method);
showTop(boxWidth, boxHeight, false);
return false;
}

function xmlhttpHref(res, strHref, clearhtml) // FUNC: AJAX Page Changer
{
/****************************************
 res            = Destination ID
 strHref        = Target File
****************************************/
  var self = new Object; // *VI* Variable Initialization
  self = this;

  if(clearhtml) // Blank out object
    document.getElementById(res).innerHTML = '';

  self = openAJAX(self);
  
  self.xmlHttpReq.open("GET", strHref, true); // Establish connection to static destination

  self.xmlHttpReq.onreadystatechange = function()
  {
    if (self.xmlHttpReq.readyState == 4)
      {
    	if (self.xmlHttpReq.status == 200)
    	{
    		updatepage('', res, self.xmlHttpReq.responseText, clearhtml); // Move along to next page, if successful,
    	}
    	else
    	{
    		alert('There was a problem with the request.'); // otherwise fall back to an error
    	}
      }
  };
  self.xmlHttpReq.send(null); // GET submission
}


function xmlhttpSubmit(frm, res, strHref, PostGet, clearhtml) // FUNC: AJAX Universal Submission
{
/****************************************
 frm            = Source Form ID
 res            = Destination ID
 strHref        = Submission Target File
 PostGet        = GET  : 0 / undefined
                  POST : 1
****************************************/
  var self        = new Object; // *VI* Variable Initialization
  self = this;
  
  if(clearhtml)
    document.getElementById(res).innerHTML = ''; // Blank out object
  
  fType = "GET";
  if(PostGet) fType = "POST"; // Determine if POST or GET to be utilized
  else strHref += "?" + makeQuery(frm); // Append url query to url for GET

  self = openAJAX(self);
  self.xmlHttpReq.open(fType, strHref, true); // Establish connection to submission destination
  self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // Send Headers
  self.xmlHttpReq.onreadystatechange = function()
  {
    if (self.xmlHttpReq.readyState == 4)
    {
      if (self.xmlHttpReq.status == 200)
      {
        updatepage(frm, res, self.xmlHttpReq.responseText, clearhtml); // Move along to next page, if successful,
      }
      else
      {
        alert('There was a problem with the request.'); // otherwise fall back to an error
      } 
    }
  };
  
  if(PostGet) // Sends the request (if necessary)
    self.xmlHttpReq.send(makeQuery(frm)); // POST submission
  else
    self.xmlHttpReq.send(null); // GET submission
}

function makeQuery(frm) // FUNC: URL query generator
{
/***************************************
 frm            = Source Form ID
****************************************/
  frm = document.getElementById(frm);
  var myQuery = "";
  for (i = 0; i < frm.elements.length; i++) // Loop through form elements
  {
    myElm = frm.elements[i];
    switch (myElm.type)
    {
      case "text":
      case "select-one":
      case "hidden":
      case "password":
      case "textarea":
        myQuery += myElm.name + "=" + escape(myElm.value) + "&";
        break;
      case "checkbox":
        if(myElm.checked)
          myQuery += myElm.name + "=" + escape(myElm.value) + "&";
        break;
      case "select-multiple":
        var csv = "";
        for(n = 0; n < myElm.length; n++)
        {
          if(myElm.options[n].selected)
          {
            if(csv) csv += "|";
            csv += myElm.options[n].value;
          }
        }
        myQuery += myElm.name + "=" + escape(csv) + "&";
        break;
    }
  }
  return (myQuery);
}

function updatepage(frm, elm, str) // FUNC: Updates content within target object
{
/***************************************
 frm            = Source Form ID
 elm            = Element to update
 str            = Content
****************************************/
  
  var tname       = new String; // *VI* Variable Initialization
  var newtitle    = new String;

  
  if(str.substring(0, 11) == '<!--AUTH-->') // Login verification test
  {
		document.getElementById(elm).innerHTML = 'Invalid user detected, redirecting...';
		window.location.href = "/member/relogin"; 
		return;
  }
	
  document.getElementById(elm).innerHTML = str;	// Update element content
}

function openAJAX(obj) // FUNC: Open AJAX Object
{
/****************************************
 obj            = AJAX object
****************************************/
  if (window.XMLHttpRequest)
  {
    obj.xmlHttpReq = new XMLHttpRequest(); // Mozilla/Safari/Opera?
    if(obj.xmlHttpReq.overrideMimeType)
      obj.xmlHttpReq.overrideMimeType("text/html"); // Declare as text/html content only
  }
  else if (window.ActiveXObject) // Active X, IE.. what other browser could it be..
  {
      try
      {
        obj.xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP"); // MS XML v2
      } catch (e)
      {
        try
        {
          obj.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); // MS XML v1 (backward compatable w/ IE 5.5)
        } catch (e)
        {}
      }
  }
  return obj;
}

function showTop(boxWidth, boxHeight, usemousexy, disableOverlay)
{
	//Position the topBox. In this example I am just centering it on the screen
	if(!boxWidth)
	{
		boxWidth = 550;
		boxHeight = 200;
	}

	var topbox = document.getElementById('topbox');
	var coords = findPos(topbox);
	
	var leftEdge = coords[0];
	var topEdge = coords[1];
	
	document.getElementById('topbox').style.width = boxWidth + 'px';
	document.getElementById('topbox').style.height = boxHeight + 'px';
		
	if(usemousexy)
	{
		// Position container to the top left user input location
		xPos = tempX - (boxWidth/2) - 15;
		yPos = tempY - boxHeight - 25;
		
		// Ensure entire container is always visible regardless of mouse position
		if(xPos < 5) xPos = 5;
		if(yPos < 5) yPos = 5;
		
		// Perform positioning
		document.getElementById('topbox').style.left=xPos + 'px';
		document.getElementById('topbox').style.top=yPos + 'px';
	} else {
		
		//Move topbox left and up to center it in the viewport
		var leftAdjustment = boxWidth * -0.5;
		if((leftEdge + leftAdjustment) < 0){
			//Don't go off the screen
			document.getElementById('topbox').style.left= 0;
			document.getElementById('topbox').style.marginLeft = 0;
		}
		else{
			document.getElementById('topbox').style.left= "50%";
			document.getElementById('topbox').style.marginLeft = leftAdjustment + 'px';
		}

		var topAdjustment = boxHeight * -0.5;
		if((topEdge + topAdjustment) < 0){
			//Don't go off the screen
			document.getElementById('topbox').style.top = 0;
			document.getElementById('topbox').style.marginTop = 0;
		}
		else{
			document.getElementById('topbox').style.top = "50%";
			document.getElementById('topbox').style.marginTop = topAdjustment + 'px';
		}
	}
	
	var arrayPageSize = getPageSize();
	
	//Show the background overlay and topbox...
	if(!disableOverlay)
	{
		document.getElementById('screenoverlay').style.visibility = 'visible';
		//document.getElementById('screenoverlay').style.height = (arrayPageSize[1] + 'px');
	}
	document.getElementById('screenoverlay').style.height = "100%";
	document.getElementById('screenoverlay').style.width = "100%";
	document.getElementById('topbox').style.visibility = 'visible';
}

function findPos(obj)
{
	var curleft = curtop = 0;
	if (obj.offsetParent)
	{
		do
		{
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
		while (obj = obj.offsetParent);
	}
	return [curleft, curtop];
}

function delayedShowTop(seconds)
{
	setTimeout("showTop()", seconds*1000);
}

function closeTop() //Hide the overlay and topbox...
{
	document.getElementById('screenoverlay').style.visibility = 'hidden';
	document.getElementById('topbox').style.visibility = 'hidden';
	document.getElementById('calbox').style.visibility = 'hidden';
}

function closeMiniCal() //Hide the overlay and topbox...
{
	document.getElementById('calbox').style.visibility = 'hidden';
}

function getPageSize()
{
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY)
	{	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	}
	else if (document.body.scrollHeight > document.body.offsetHeight) // all but Explorer Mac
	{
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	}
	else // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
	{ 
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;

	if (self.innerHeight) // all except Explorer
	{
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight) // Explorer 6 Strict Mode
	{
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	}
	else if (document.body) // other Explorers
	{
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight)
	{
		pageHeight = windowHeight;
	}
	else
	{ 
		pageHeight = yScroll;
	}
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth)
	{	
		pageWidth = windowWidth;
	}
	else
	{
		pageWidth = xScroll;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
}

function miniCal(datetime, elm, frmobj) // Show mini calendar for date input fields
{
	var e = document.getElementById(elm);
	
	var calbox = document.getElementById('calbox');
	document.getElementById('calbox').style.left = getX(e) + 'px';
	document.getElementById('calbox').style.top = (getY(e) + e.offsetHeight + 1) + 'px';
	calbox.style.visibility = 'visible';
	
	if(datetime == 0)
	{
		var frm = eval("document.calevent." + frmobj);
		var myDate = new Date(frm.value); // Your timezone!
		var myEpoch = myDate.getTime()/1000.0;
		datetime = myEpoch;
	}
	xmlhttpHref('calbox', ('/tools/calendar/minical/' + datetime + '/' + elm + '/' + frmobj), 1);
	
}

function getY( oElement )
{
	var iReturnValue = 0;
	while( oElement != null ) {
		iReturnValue += oElement.offsetTop;
		oElement = oElement.offsetParent;
	}
	return iReturnValue;
}

function getX( oElement )
{
	var iReturnValue = 0;
	while( oElement != null ) {
		iReturnValue += oElement.offsetLeft;
		oElement = oElement.offsetParent;
	}
	return iReturnValue;
}

