//This script loads the mac stylesheet, needed to correct some font differences between the Mac and PC rendering of SAIF.com

platform = window.navigator.platform.toLowerCase();
if (platform.indexOf('mac') != -1) {
	document.write('<link rel="stylesheet" href="/saif_library/mac.css" type="text/css">');
};


/////////////////////////////////////////////////////
//// Date script                                 ////
//// From JavaScript Kit (www.javascriptkit.com) ////
/////////////////////////////////////////////////////

/*Current date script credit: 
JavaScript Kit (www.javascriptkit.com)
Over 200+ free scripts here!
*/

function footerDate() 
{
  var mydate=new Date()
  var year=mydate.getYear()
  if (year < 1000)
  year+=1900
  var day=mydate.getDay()
  var month=mydate.getMonth()
  var daym=mydate.getDate()
  if (daym<10)
  daym="0"+daym
  var dayarray=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
  var montharray=new Array("January","February","March","April","May","June","July","August","September","October","November","December")
  document.write(" on "+dayarray[day]+", "+montharray[month]+" "+daym+", "+year)
}

/////////////////////////////
//// Change popup links  ////
//// Must be run on load ////
/////////////////////////////

function changePopups()
{
   links = getElementsByClassName(document, 'a', 'popup');
   for(i = 0; i < links.length; i++)
   {
      links[i].target = '';
      links[i].href = 'Javascript: popUpPdf("' + links[i].href + '");';
   }
   links = getElementsByClassName(document, 'a', 'popupscroll');
   for(i = 0; i < links.length; i++)
   {
      links[i].target = '';
      links[i].href = 'Javascript: popUp("' + links[i].href + '");';
   }
}

function popUpPdf(fileName)
{
   window.open(fileName, null, 'directories=no, location=no, menubar=no, status=yes, titlebar=no, toolbar=no, resizable=yes, width=800, height=600');
}

function popUp(fileName)
{
   window.open(fileName, null, 'scrollbars=yes, directories=no, location=no, menubar=no, status=yes, titlebar=no, toolbar=no, resizable=yes, width=800, height=600');
}


function toggleLayers(layerToHide, layerToShow)
{
   layerToShow = document.getElementById(layerToShow);
   layerToHide = document.getElementById(layerToHide);
   layerToShow.style.visibility = 'visible';
   layerToHide.style.visibility = 'hidden';
   layerToShow.style.display = 'block';
   layerToHide.style.display = 'none';
}

function openLayer(layerToShow)
{
   layerToShow = document.getElementById(layerToShow);
   layerToShow.style.visibility = 'visible';
   layerToShow.style.display = 'block';
}

function closeLayer(layerToHide)
{
   layerToHide = document.getElementById(layerToHide);
   layerToHide.style.visibility = 'hidden';
   layerToHide.style.display = 'none';
}

// Used for the accordian panels in the right sidebar, the panel number that is sent in is revealed, the others are hidden and their button states revealed
function setSidebarPanels(panelToOpen)
{
  // find all elements
  buttonElements = getElementsByClassName(document, "div", "sidebar_button");
  for(i = 0; i < buttonElements.length; i++)
  {
    idNum = buttonElements[i].id.replace('accordian_button_', '');
	if (idNum == panelToOpen) 
	{
    	toggleLayers('accordian_button_' + idNum, 'accordian_panel_' + idNum);
	} 
	else 
	{
		toggleLayers('accordian_panel_' + idNum, 'accordian_button_' + idNum);
	}
  }
}

// Displays pop-up boxes - send the ID of the hidden layer - For example usage see the Register tab of training items: About link at bottom of page.
function openPopBox(layerToShow)
{
	// first, if the browser is IE lets hide any select boxes (In IE selects show over top of all other layers so they must be surpressed)
	platform = window.navigator.userAgent.toLowerCase();
	if (platform.indexOf('msie') != -1) {
	  elements = document.getElementsByTagName('select');
      for(i = 0; i < elements.length; i++)
      {
         elements[i].style.visibility = 'hidden';
      }
	};
	// Now lets show the pop box
    layerToHide = document.getElementById(layerToShow);
    layerToHide.style.visibility = 'visible';
    layerToHide.style.display = 'block';
}

// Displays pop-up boxes - send the ID of the layer to hide
function closePopBox(layerToHide)
{
	// first, if the browser is IE, lets unhide any select boxes (they were hidden by the open function)
	platform = window.navigator.userAgent.toLowerCase();
	if (platform.indexOf('msie') != -1) {
	  elements = document.getElementsByTagName('select');
      for(i = 0; i < elements.length; i++)
      {
         elements[i].style.visibility = 'visible';
      } 
	};
	// Now lets hide the pop box
    layerToHide = document.getElementById(layerToHide);
    layerToHide.style.visibility = 'hidden';
    layerToHide.style.display = 'none';
}

//Begin Javascript for tabs

// M-< C-space M-> C-x r t "<space>x80"

var tabSets = [];
var tabIDs = [];
var anchorNameId = [];
var highestID = 0;

//////////////////////
//// Class TabSet ////
//////////////////////

function TabSet(tabframe)
{
   this.tabframe = tabframe;
   this.links = [];
   this.bodies = [];
   this.ids = [];
}

TabSet.prototype.maxID = function()
{
   return this.ids[this.ids.length - 1];
}

TabSet.prototype.minID = function()
{
   return this.ids[0];
}

TabSet.prototype.hasID = function(idNum)
{
   return (this.minID() <= idNum && this.maxID() >= idNum);
}

TabSet.prototype.setUp = function()
{

   subDivs = this.tabframe.getElementsByTagName('div');
   hrefs = subDivs[0].getElementsByTagName('div')[0].getElementsByTagName('ul')[0].getElementsByTagName('li');
   divs = getElementsByClassName(this.tabframe, 'div', 'tabbody')[0];
   divs = getElementsByClassName(divs, 'div', 'tabarea');
   this.links = hrefs;
   this.bodies = divs;
   for(index = 0; index < hrefs.length; index++)
   {
	  localhref = hrefs[index].getElementsByTagName('a')[0];
	  //alert(localhref.href.indexOf("#") != -1);
	  //if (localhref.className != "linktab") // If this tab links to another page rather than loading a frame use the class "linktab"...
	  if (localhref.href.indexOf("#") != -1) // If this tab links to an outside page rather than to an internal anchor do not prep a frame. 
	   {
      	localdiv = divs[index];
      	id = getID();
      	localhref.id = 'link_' + id;
      	localdiv.id = 'body_' + id;
      	localhref.href = 'Javascript: showTab(' + id + '); ';
      	this.setAnchorNameId(localdiv, id);
      	this.ids[this.ids.length] = id;
	   }
	  else //Don't prepare a frame, just set the link ID. 
	   {
      	id = getID();
      	localhref.id = 'link_' + id;
      	this.ids[this.ids.length] = id;
	   }
   }
}

TabSet.prototype.setAnchorNameId = function(localdiv, id)
{
   anchors = localdiv.getElementsByTagName('a');
   for(i = 0; i < anchors.length; i++)
   {
      if(anchors[i].name != "")
      {
	 anchorNameId[anchors[i].name] = id;
	 return;
      }
   }
}

TabSet.prototype.showFirst = function()
{
   eval("document.getElementById('body_" + this.ids[0] + "').className = 'tabareaVisible';");
//   eval("document.getElementById('body_" + this.ids[0] + "').style.visibility = 'visible';");
//   eval("document.getElementById('body_" + this.ids[0] + "').style.display = 'block';");
   eval("document.getElementById('link_" + this.ids[0] + "').className = 'activetab';");
}

TabSet.prototype.hideAll = function()
{
   for(i = 0; i < this.links.length; i++)
   {
	  //substring(linkName.indexOf('#') + 1, linkName.length);
	  //if(document.getElementById('link_' + this.ids[i]).className != "linktab") //If this tab links to another page rather than loading a frame use the class "linktab"...
	  if(document.getElementById('link_' + this.ids[i]).href.toLowerCase().indexOf("javascript") == 0) //If the tab does not have a javascript handler then it does not have a tabarea to hide...
	  {
		eval("document.getElementById('body_" + this.ids[i] + "').className = 'tabarea';");
        //eval("document.getElementById('body_" + this.ids[i] + "').style.visibility = 'hidden';");
        //eval("document.getElementById('body_" + this.ids[i] + "').style.display = 'none';");
        eval("document.getElementById('link_" + this.ids[i] + "').className = '';");
		
	  }
   }
}

TabSet.prototype.showTab = function(idNum)
{
   this.hideAll();
   eval("document.getElementById('body_" + idNum + "').className = 'tabareaVisible';");
   eval("document.getElementById('link_" + idNum + "').className = 'activetab';");
   document.getElementById('PageTop').focus();

   // check to see if there's a form field requesting focus

   // In an attempt to work around the google toolbar, we are setting a reserved ID on the form field, then calling the following function after a short delay
   eval("focusElements = getElementsByClassName(document.getElementById('body_" + idNum + "'), '*', 'focused');");
   if(focusElements.length > 0)
   {
      focusElements[0].id = 'ObjectToSelectAndFocus';
      setTimeout("selectAndFocus();", 300);
   }

}

function selectAndFocus()
{
   formField = document.getElementById('ObjectToSelectAndFocus');
   formField.focus();
   formField.select(); 
}


///////////////////////
//// End of TabSet ////
///////////////////////

////////////////////////
//// Main functions ////
////////////////////////

function showTab(idNum)
{
   for(i = 0; i < tabSets.length; i++)
   {
      if(tabSets[i].hasID(idNum))
      {
	 tabSets[i].showTab(idNum);
	 break;
      }
   }
}

function runOnLoad()
{
   loadTabs();
   processHref(window.location);
   crossTabLinking();
   changePopups();
}

function crossTabLinking()
{
   crossTabLinks = getElementsByClassName(document, "a", "xtab");
   for(i = 0; i < crossTabLinks.length; i++)
   {
      linkName =  crossTabLinks[i].href; //.substring(1, localhref.length);
      linkName = linkName.substring(linkName.indexOf('#') + 1, linkName.length);
      crossTabLinks[i].href = "Javascript: displayAnchorTab('" + linkName + "'); ";
   }
}

function loadTabs()
{
   tabframes = getElementsByClassName(document, "div", "tabframe");
   for(i = 0; i < tabframes.length; i++)
   {
	  tabSets[i] = new TabSet(tabframes[i]);
      tabSets[i].setUp();
      tabSets[i].showFirst();
   }
}

function processHref(localhref)
{
   localhref = localhref.toString();
   if(-1 != localhref.indexOf('#'))
   {
      // anchorName = localhref.substring(localhref.indexOf('#'), localhref.length());
      anchorName = localhref.substring(localhref.indexOf('#') + 1, localhref.length);
      displayAnchorTab(anchorName);
   }
}

function displayAnchorTab(anchorName)
{
   if(anchorNameId[anchorName] != null)
   {
      showTab(anchorNameId[anchorName]);
   }
}


////////////////////////
//// Helper Methods ////
////////////////////////

function getElementsByClassName(oElm, strTagName, strClassName){
    var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/\-/g, "\\-");
    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
    var oElement;
    for(var i=0; i<arrElements.length; i++){
        oElement = arrElements[i];      
        if(oRegExp.test(oElement.className)){
            arrReturnElements.push(oElement);
        }   
    }
    return (arrReturnElements)
}

function getID()
{
   return highestID++;
}

// End Javascript for Tabs


///////////////////////////////////////
// Class Formcheck                  //
//////////////////////////////////////

// Run checkRegistrationForm on the submit and the return will be false unless all fields with the class 'required' are filled and 
// all fields with the class 'validateemail' have a valide email address (or none at all if they are not also classed 'required'
																		  

    function checkRegistrationForm()
    {
      // Let's reset the stage
	  validated = true;
	  document.getElementById('redtext').className = "hidden";
      document.getElementById('emailwarning').className = "hidden";
	  document.getElementById('requiredwarning').className = "hidden";
	  // Check that required fields are filled
      required_elements = getElementsByClassName(document, '*', 'required');
      for(i = 0; i < required_elements.length; i++)
      {
        if(required_elements[i].value == "")
        {
          validated = false;
          if (required_elements[i].className.indexOf(' unfilled') < 0) required_elements[i].className = required_elements[i].className + " unfilled";
          document.getElementById('redtext').className = "";
		  document.getElementById('requiredwarning').className = "";
        }
		else
		{
		  // Remove ' unfilled' from the class name if it exists 
		  eraseIndex = required_elements[i].className.indexOf(' unfilled')
		  if (eraseIndex >= 0) 
		  	{
			  cleanString = required_elements[i].className.substring(0,eraseIndex);
			  cleanString = cleanString + required_elements[i].className.substring(eraseIndex + 9);
			  required_elements[i].className = cleanString;
			}
		}
      }
	  // Validate email addresses
	  email_elements = getElementsByClassName(document, '*', 'validateemail');
      for(i = 0; i < email_elements.length; i++)
      {
        if(((email_elements[i].value!="") && emailcheck(email_elements[i].value)==false)) //If there is nothing in the field, and it is not a required field, then there is nothing to check
        {
          validated = false;
          if (email_elements[i].className.indexOf(' invalidemail') < 0) email_elements[i].className = email_elements[i].className + " invalidemail";
		  document.getElementById('redtext').className = "";
          document.getElementById('emailwarning').className = "";
        }
        else
		{
		  // Remove ' invalidemail' from the class name if it exists 
		  eraseIndex = email_elements[i].className.indexOf(' invalidemail')
		  if (eraseIndex >= 0) 
		  	{
			  cleanString = email_elements[i].className.substring(0,eraseIndex);
			  cleanString = cleanString + email_elements[i].className.substring(eraseIndex + 13);
			  email_elements[i].className = cleanString;
			}
		}
      }
      return validated;
    }
	
	
function emailcheck(str) {
// Used by checkRegistrationFrom function

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    return false
		 }

 		 return true					
	}
	
/////////////////////////////////////////////////
/// Home page loader  ///////////////////////////
/////////////////////////////////////////////////

function loadHomePageBackground(background) {
  myBackground = "url(" + background +")"
  myDiv = document.getElementById("content");
  myBreakout = document.getElementById("homepageBreakout");
  if ((window.navigator.userAgent.indexOf("MSIE")) > 0) 
  {
  	myDiv.filters.BlendTrans.Apply();
  	myDiv.style.backgroundImage = myBackground;
	myBreakout.style.backgroundImage = "none";
  	myDiv.filters.BlendTrans.Play();
  }
  else
  {
  	myDiv.style.backgroundImage = myBackground;
	myBreakout.style.backgroundImage = "none";
  };
}

function nothing() {
}
