var curHref = document.location.href;
var curHrefIndex = curHref.indexOf("/");
curHrefIndex = curHref.indexOf("/",curHrefIndex+1);
curHrefIndex = curHref.indexOf("/",curHrefIndex+1);
curHref = curHref.substr(0,curHrefIndex) + "/dms/";

var curHost = document.location.host;
//
//Be sure to run sniffer.js to get values for is_nav, etc. before running this script.
//
// Utility function returns rendered height of object content in pixels
function getObjHeight(obj) {
	if (is_nav) return obj.clip.height;
	else return obj.clientHeight;
}
// Utility function returns rendered width of object content in pixels
function getObjWidth(obj) {
	if (is_nav) return obj.clip.width;
	else return obj.clientWidth;
}
// Utility function returns the available content width space in browser window
function getInsideWindowWidth() {
	if (is_nav) return window.innerWidth;
	else return document.body.clientWidth;
}
// Utility function returns the available content height space in browser window
function getInsideWindowHeight() {
	if (is_nav) return window.innerHeight;
	else return document.body.clientHeight;
}
// Utility function to position an element at a specific x,y location
function shiftTo(obj, x, y) {
	if (is_nav)
		obj.moveTo(x, y);
	else {
		obj.pixelLeft = x;
		obj.pixelTop = y;
	}
}
// Special handling for CSS-P redraw bug in Nav4
function handleResize() {
	if (is_nav) {
		// causes extra re-draw
		location.reload();
	} else {
		centerIt();
	}
}
function generate_table(tableWidth, tableAlign, tableColor, tableBorder, tableCaption, captionAlign, cellPadding, colWidths, colAligns, colHeaders, colData){
	var tWidth = tableWidth;
	var tAlign = tableAlign;
	var tColor = tableColor;
	var tBorder = tableBorder;
	var tCaption = tableCaption;
	var capAlign = captionAlign;
	var cPadding = cellPadding;
	var cWidths = colWidths;
	var cAligns = colAligns;
	var cHeaders = colHeaders;
	var cData = colData;
	var columns = cData.length;
	var rows = cData[0].length;
	var table = "<table "
	if (tWidth > 0) table += "width=\"" + tWidth + "\"";
	table += " cols=\"" + cData.length + "\"";
	if (tBorder > 0) table += " border=\"" + tBorder + "\"";
	if (cPadding > 0) table += " cellpadding=\"" + cPadding + "\"";
	if (tAlign != '') table += " align=\"" + tAlign + "\"";
	table += " bgColor=\"" + tColor + "\">\n";
	if (tCaption.length != 0){ 
		table += "<caption";
			if (capAlign.length != 0) table += " align=" + capAlign + ">";
			else table+= ">";
		table += tCaption + "</caption>";
	}
	if (cHeaders != ''){
		table += "<tr>";
		for (t = 1; t <= columns; t++) {
			table += "<th";
			if (cAligns != '') table += " width=\"" + cWidths[t-1] + "\"";
			if (cAligns != '') table += " align=\"" + cAligns[t-1] + "\"";
			table += ">" + colHeaders[t-1] + "</th>";
		}
		table += "</tr>\n";
	}
	for (i = 1; i <= rows; i++) {
		table += "<tr>";
		for (t = 1; t <= columns; t++) {
			table += "<td";
			if (cWidths != '') table += " width=\"" + cWidths[t-1] + "\"";
			if (cAligns != '') table += " align=\"" + cAligns[t-1] + "\"";
			table += ">" + cData[t-1][i-1] + "</td>\n";
		}
		table += "</tr>\n"
	}
	table += "</table>\n"
	document.write(table);
}	
var startDate, stopDate, curTimeUsed, oldTimeUsed, newTime;
function init(){
	startDate = new Date();
}
function end(timer){
	stopDate = new Date();
	curTimeUsed = new Date();
	curTimeUsed.setTime(stopDate.getTime() - startDate.getTime());
	var value = Get_Cookie(timer);
	oldTimeUsed = new Date();
	oldTimeUsed.setTime(value);
	newTime = new Date();
	newTime.setTime(oldTimeUsed.getTime() + curTimeUsed.getTime());
	storeIntelligentCookie(timer,newTime.getTime());
}
// get a value from a string of name/value pairs
function getValue(string,elementName) {
    var startPos = string.indexOf(elementName + "=");
    if (startPos > -1) {
        startPos = startPos + elementName.length + 1;
        var endPos = string.indexOf("&",startPos);
        if (endPos == -1) endPos = string.length;
        var elementValue = unescape(string.substring(startPos,endPos));
        return elementValue;
    }
}

 var today = new Date();
// var zero_date = new Date(0,0,0);
// today.setTime(today.getTime() - zero_date.getTime());

 var todays_date = new Date(today.getYear(),today.getMonth(),today.getDate(),0,0,0);
 var expires_date = new Date(todays_date.getTime() + (30 * 86400000)); // = 30 days
// ************************************************************************************************************
//  Cookie Functions
//   Please use only the  Get_Cookie() and Set_Cookie() functions in your
//     pages.  These store cookie values for a user in a master cookie (called "MasterCookie")
//      in a long string delimited by # (for "=") and ! (for ";").  Obviously, you should not try to store
//      cookie values containing #, !, ; or = signs.
//   Functions setUserIDInCookie() and  getUserIDFromCookie() are also okay.  26Apr01
// ************************************************************************************************************
function Get_Cookie(name) {
	var masterCookie = GetMasterCookie();
	if  (masterCookie==null)  return null;
	return Get_From_Master_Cookie(masterCookie,name); } 
 function Set_Cookie(name,value) {
	var masterCookie = GetMasterCookie();
	var exp_date;
// no persistence	if  (masterCookie==null)  exp_date = new Date(todays_date.getTime()+86400000); //24 hours
	masterCookie = Set_In_Master_Cookie(masterCookie ,name,value); 
	StoreMasterCookie(masterCookie,exp_date); } 
 function Delete_Cookie(name) {
	var mstrCookie=GetMasterCookie();
	if (mstrCookie!=null) {
		mstrCookie = Delete_From_Master_Cookie(mstrCookie,name);
		if (mstrCookie!=null) {
			if (mstrCookie.indexOf("#")==-1) DeleteMasterCookie();
			else StoreMasterCookie(mstrCookie); } } }
 function setUserIDInCookie(userid) {
	Set_Cookie("user", userid); }
function getUserIDFromCookie() {
	return Get_Cookie("user"); }
// background functions
function GetMasterCookie() {
     var start = document.cookie.indexOf("MasterCookie=");
     var len = start + 13; //name.length+1;
     if (start == -1) return null;
     var end = document.cookie.indexOf(";",len);
     if (end == -1) end = document.cookie.length;
     return unescape(document.cookie.substring(len,end)); }
function StoreMasterCookie(value,expiration,path,domain,secure) {
      var mcookie = "MasterCookie=" +escape(value) ;
        if (expiration) mcookie += "; expires=" + expiration.toGMTString();
        mcookie +=  "; path=" + ((path) ? path : "/");
        if (domain) mcookie += "; domain=" +  domain;
         if (secure) mcookie += "; secure"; 
      document.cookie = mcookie;
}
function DeleteMasterCookie() {
     if (GetMasterCookie()!=null) document.cookie = "MasterCookie=" ; }
function Get_From_Master_Cookie(mstrCookie,subCookieName) {
     if (mstrCookie) {
          var first = mstrCookie.indexOf("!"+subCookieName+"#");
          if (first==-1) {
	first = mstrCookie.indexOf(subCookieName+"#");
	if (first==0) first = subCookieName.length+1;
	else return null;}
          else first += subCookieName.length+2;
          var last = mstrCookie.indexOf("!",first); 
          if (last==-1) last=mstrCookie.length;
          return unescape(mstrCookie.substring(first,last));}
     else {
          return null; } }
function Set_In_Master_Cookie(mstrCookie,subCookieName,subCookieValue) {
     var newMaster = "";
     if (mstrCookie) {
          var first = mstrCookie.indexOf("!"+subCookieName+"#");
          if (first==-1) {
               first = mstrCookie.indexOf(subCookieName+"#");
               if (first==0) {			//at start of MasterCookie
                    first = subCookieName.length+1;
                    var last = mstrCookie.indexOf("!",first); 
                    if (last==-1) last=mstrCookie.length;
                    newMaster += mstrCookie.substring(0,first);
                    newMaster += escape(subCookieValue);
                    newMaster += mstrCookie.substring(last,mstrCookie.length); }
               else {				//not in MasterCookie
                    newMaster += mstrCookie;
                    newMaster += "!";
                    newMaster += subCookieName;
                    newMaster += "#"; 
                    newMaster += escape(subCookieValue); }}
          else {				//in middle of MasterCookie
               first += subCookieName.length+2;
               var last = mstrCookie.indexOf("!",first); 
               if (last==-1) last=mstrCookie.length;
               newMaster += mstrCookie.substring(0,first);
               newMaster += escape(subCookieValue);
               newMaster += mstrCookie.substring(last,mstrCookie.length); } }
     else {
          newMaster = subCookieName + "#" + escape(subCookieValue); }
     return newMaster;} 
function Delete_From_Master_Cookie(mstrCookie,subCookieName) {
     var newMaster = "";
     if (mstrCookie) {
          var first = mstrCookie.indexOf(subCookieName+"#");
          if (first==-1)  return null;
          var last = mstrCookie.indexOf("!",first); 
          if (last==-1) {
               if (first>0) {
			        if (mstrCookie.substring(first-1,first)=="!") first--; }
               last=mstrCookie.length; }
          else {
               last+=1; }
          newMaster += mstrCookie.substring(0,first);
          newMaster += mstrCookie.substring(last,mstrCookie.length); }
     return newMaster;  } 

 // replaces any occurences of the text string within the string string with the by string.
function replace(str,text,by) {
// Replaces 'text' with 'by' in 'str'
    var i = str.indexOf(text);
    var newstr = '';
    if (i == -1) return str;
    newstr += str.substring(0,i) + by;

    if (i+text.length < str.length)
        newstr += replace(str.substring(i+text.length,str.length),text,by);
		
    return newstr;
}

// bool validateElement(Element element, long type, bool allowEmpty, String expression, long min, long max
function validateElement(element, type, allowEmpty, expression, min, max)
{
	if(element.value.length == 0)
	{
		if(allowEmpty == 1)
		{
			return 1;
		}
		else
		{
			return 0;
		}
	}
	
	switch(type)
	{	
		case "exp":
			return validString(element, expression);
			break;
		case "int":
			return validInteger(element, min, max);
			break;
	}
}

// sample regular expressions
//	re = /\(?\d{3}\)?([-\/\.])\d{3}\1\d{4}/; // phone number exp converted to constructor
//	re = "\\d{3}([-\\/\\.])\\d{3}\\1\\d{4}"; // phone number
//	re = "[-A-Za-z0-9]+"; // name
//	re = "^\\d{5}$|^\\d{5}-\\d{4}$"; // zip code
//	re = "[A-Za-z0-9_]+@[A-Za-z0-9_]+\\.[A-Za-z0-9_]+"; // email

// bool allowEmpty, Element element, long type, String expression, long min, long max
function validString(element, expression)
{
	re = new RegExp(expression);
	
	if(re.test(element.value))
	{
		return 1;
	}
	else
	{
		return 0;
	}
	
	return 1;
}

function validInteger(element, min, max)
{
	var n = parseInt(element.value, 10);
	
	if(isNaN(n)) return 0;
	
	if(n < min || n > max) return 0;
	
	return 1;
}

function getSearchAsArray()
{

   // Browser-sniffing variables.
   var minNav3 = (navigator.appName == "Netscape" && 
      parseInt(navigator.appVersion) >= 3);
   var minIE4 = (navigator.appName.indexOf("Microsoft") >= 0 && 
      parseInt(navigator.appVersion) >= 4);
   var minDOM = minNav3 || minIE4;   // Baseline DOM required for this function
  
   // Initialize array to be returned.
   var results = new Array();
   
   if (minDOM)
   {
      // Unescape and strip away leading question mark.
      var input = unescape(location.search.substring(1));
      
      if(input)
      {
         // Divide long string into array of name/value pairs.
         var srchArray = input.split("&");
         var tempArray = new Array();
         
         for (i = 0; i < srchArray.length; i++)
         {
            // Divide each name/value pair temporarily into a two-entry array.
            tempArray = srchArray[i].split("=");
            
            // Use temp array values as index identifier and value.
            results[tempArray[0]] = tempArray[1];
         }
      }
   }
   
   return results;
}

function loadSearchDataIntoForm(formNum, array)
{
	var i = 0;
	
	if(window.srchData)
	{
		for(i = 0; i < array.length; i++)
		{
			if(srchData[array[i]])
			{
				document.forms[formNum].elements[array[i]].value = srchData[array[i]];
			}
		}
	}
}

function toggle(name, num){
	if (box_checked[num-1] == 0){ 
		document.images[name].src=eval("imgs[" + ((num*2)-1) + "].src");
		box_checked[num-1] = true;
	}
	else{ 
		document.images[name].src=eval("imgs[" + ((num*2)-2) + "].src");
		box_checked[num-1] = false;
	}
}

function alpha_table() {
document.write('<table border=1 cellspacing=0 cellpadding=4><tr ALIGN=CENTER><td><font face="arial" size=-1><a href="#a">A<\/a><\/font><\/td><td><font face="arial" size=-1><a href="#b">B<\/a><\/font><\/td><td><font face="arial" size=-1><a href="#c">C<\/a><\/font><\/td><td><font face="arial" size=-1><a href="#d">D<\/a><\/font><\/td><td><font face="arial" size=-1><a href="#e">E<\/a><\/font><\/td><td><font face="arial" size=-1><a href="#f">F<\/a><\/font><\/td><td><font face="arial" size=-1><a href="#g">G<\/a><\/font><\/td><td><font face="arial" size=-1><a href="#h">H<\/a><\/font><\/td><td><font face="arial" size=-1><a href="#i">I<\/a><\/font><\/td><td><font face="arial" size=-1><a href="#j">J<\/a><\/font><\/td><td><font face="arial" size=-1><a href="#k">K<\/a><\/font><\/td><td><font face="arial" size=-1><a href="#l">L<\/a><\/font><\/td><td><font face="arial" size=-1><a href="#m">M<\/a><\/font><\/td><\/tr><tr ALIGN=CENTER><td><font face="arial" size=-1><a href="#n">N<\/a><\/font><\/td><td><font face="arial" size=-1><a href="#o">O<\/a><\/font><\/td><td><font face="arial" size=-1><a href="#p">P<\/a><\/font><\/td><td><font face="arial" size=-1><a href="#q">Q<\/a><\/font><\/td><td><font face="arial" size=-1><a href="#r">R<\/a><\/font><\/td><td><font face="arial" size=-1><a href="#s">S<\/a><\/font><\/td><td><font face="arial" size=-1><a href="#t">T<\/a><\/font><\/td><td><font face="arial" size=-1><a href="#u">U<\/a><\/font><\/td><td><font face="arial" size=-1><a href="#v">V<\/a><\/font><\/td><td><font face="arial" size=-1><a href="#w">W<\/a><\/font><\/td><td><font face="arial" size=-1><a href="#x">X<\/a><\/font><\/td><td><font face="arial" size=-1><a href="#y">Y<\/a><\/font><\/td><td><font face="arial" size=-1><a href="#z">Z<\/a><\/font><\/td><\/tr><\/table>');	
}

function getDocObString(id) {
  if (document.all) {
    	return document.all[id].style;
  } else if(document.layers) {
    	return document.layers[id];
  }
}

/*
if (document.layers) {
  var hidden = "hide";
  var visible = "show";
} else {
  var hidden = "hidden";
  var visible = "visible";
}
*/
/*var toggle = "toggle";
var count = 1;
function changeVisibility() {
  count ++;
  if (document.layers || document.all) {
    var index, length=arguments.length;
    for (index=0; index<length; index+=2) {
      var item = getDocObString(arguments[index]);
      if (arguments[index+1] == hidden) {
        item.visibility = hidden;
      } else if (arguments[index+1] == visible) {
        item.visibility = visible;
      } else if (arguments[index+1] == toggle) {
        if (item.visibility == visible) {
          item.visibility = hidden;
        } else if (item.visibility == hidden) {
          item.visibility = visible;
        }
      }
    }
  }
} */

function newImage(arg) {
	if (document.images) {
		imageOb = new Image();
		imageOb.src = arg;
		return imageOb;
	}
}
function changeImages() {
	if (document.images && (preloadFlag == true)) {
		for (var i=0; i<changeImages.arguments.length; i+=2) {
			document[changeImages.arguments[i]].src = changeImages.arguments[i+1];
		}
	}
}
function refreshImages() {
	for (var i=0;i<document.images.length;++i) {
		document.images[i].src=document.images[i].src; }
}

function firstSlide(filename) {
	var winH = 405;
	var winW = 600;
	if (document.all || (document.layers))
		var xLimit = screen.width, yLimit = screen.height;
	else
		var xLimit = 640, yLimit= 480;
	var xOffset = (xLimit - winW)/2, yOffset = ((yLimit - winH)/2)-20;
	var splash=window.open(filename, 'Show', 'width=' + winW + ',height=' + winH + ',' + 'screenX=' + xOffset + ',screenY=' + yOffset + ',' + 'top=' + yOffset + ',left=' + xOffset +''); 
	splash.focus();
 }
 
var moreWindow;
var newpage;
function doOpenMore(page, spartan) {
	var h;
	var w;
	newpage = page;
	if ((is_mac) || (is_macppc) || (is_mac68k)) {
		h = screen.height-96;
		w = screen.width-14;
	} else if (is_nav) {
		h = screen.height-120;
		w = screen.width-10;
	} else {
		h = screen.height-144;
		w = screen.width-10;
	}
	if (!moreWindow || moreWindow.closed) {
		if (spartan)
			moreWindow = open ("http://" + curHost + "/dms/outdmsspartan.html", "More", "toolbar=no,menubar=no,location=no,scrollbars=yes,resizable,left=0,screenX=0,top=0,screenY=0,height=" + h + ",width=" + w);
		else
			moreWindow = open ("http://" + curHost + "/dms/outdms.html", "More", "toolbar=yes,menubar=yes,location=no,scrollbars=yes,resizable,left=0,screenX=0,top=0,screenY=0,height=" + h + ",width=" + w);
	}
	else {
		// IE4 has a problem with focus() so don't call it for that browser - the new page gets loaded
		// but the window does not come up on top of the current window
		if (!is_ie4) moreWindow.focus();}
		setTimeout('moreDelay(0)',1000); // 3 sec needed on mac
	}
	
function openMore(page) {
	doOpenMore(page, false);
	}	

function openMoreSpartan(page) {
	doOpenMore(page, true);
	}	

function moreDelay(n) {
	if (n<20) {	//10 seconds max
		if (moreWindow) {
			if (moreWindow.partner) {
				moreWindow.partner.location.href=newpage;}
			else {
				setTimeout('moreDelay(' + (n+1) + ')',500); }}
		else {
			setTimeout('moreDelay(' + (n+1) + ')',500); }}}

function printinfo2(printOption){
	document.write('<div align="center">');
	document.write('<div style=');
	document.write('"font-family:');
	document.write("'Courier New'; font-size:8pt");
	document.write('">');
    	document.write('<table width="500" border="1"><tr><td class="wing">');
    	    		
	if (printOption=='Y') {
		if (is_mac || is_mac68k || is_macppc){
			document.write("When you see the report below, Choose 'Print...' from the 'File' menu on the menubar to print this report.<br><br>");	}
		else{
			document.write('When you see the report below, click <a href="javascript:window.print()">here</a> to print this report.<br><br>');	}
	}
}

function printinfo(){
	var printOption = Get_Cookie("hasPrint");
	printinfo2(printOption);
}



function download2(filename, saveOption, doClose){	
	if (saveOption == 'Y') {
		if (is_mac || is_mac68k || is_macppc) {
			if (is_ie)
				document.write("To download this HTML file: Choose 'Save As...' from the 'File' menu on the menubar. Select <strong>" + filename + "</strong> as File name. Make sure the Format is 'HTML'.");
			else
				document.write("To download this HTML file: Choose 'Save As...' from the 'File' menu on the menubar. Select <strong>" + filename + "</strong> as File name. Make sure the Format is 'Source'.");
		}
		
		else
			document.write("To download this HTML file: Choose 'Save As...' from the 'File' menu on the menubar. Select <strong>" + filename + "</strong> as File name.");
		
		document.write("<br><br>");
	}
	if (doClose == 'Y')
		document.write('Click <a href="javascript:window.close()">here</a> to close this report.');
	document.write("</td></tr></table></div></div>");
}

function download(filename){	
	var saveOption = Get_Cookie("hasSave");
	download2(filename, saveOption, 'Y');
}


//Check if Beatnik plug-in already installed or not
//True:  do not have Beatnik, please install.
//false: already installed
function needInstallBeatnik() {
	if (typeof (Music) != 'undefined'){
		return !(Music.isPlayerCompatible(null, true, false) && Music.clientSupported);}
	else return true;
}


//This part of script is used for the slides button on the pages which has slids show 
var hasSlides = Get_Cookie("hasSlides"); 
var hasSounds = Get_Cookie("hasSounds");

var imageoff = new Image(134, 106);
imageoff.src = 'dms/images/camera2.gif';
var imageon  = new Image(134, 106);
imageon.src = 'dms/images/camera.gif';

function change(image,ext){
	if (document.images)
		document.images[image].src = eval(image + ext + ".src");
}


var showstring;
function slidsShowButton(slide) {
	if ( hasSlides == "Y") {
		showstring = '<a href="javascript:firstSlide(';
		showstring += "'http://" + curHost + "/dms/";
		showstring += slide + "')";
		showstring += '" onMouseOver="change(';
		showstring += "'image','on')";
		
		//If sounds allowed in this SITE, set the sounds on the Slids Show button
		if (hasSounds=="Y")
			showstring += "; music.playNote (1,1, 99, 77, 120, 200)";
			
		showstring += '" onMouseOut="change(';
		showstring += "'image','off')";
		showstring += '"><IMG NAME=';
		showstring += '"image" src="dms/images/camera2.gif" width="134" height="106" alt="Show" border="0"></a>';
		document.write(showstring);
	}
	else {
		showstring = '<img src="dms/images/clearpixel.gif" width="1" height="1" alt="" border="0">';
		document.write(showstring);
	}
}

//---Set the sounds on if the sounds allowed in this particular SITE.
//---Refer SITE.all_sound=="Y", this is pull out through cookie hasSounds
function doPlayNote(bank,instrument,pitch,volume){
	if (hasSounds=="Y") {
		music.playNote (1,bank,instrument,pitch,volume,200);
	}
}

// *****************************************
// Generalized "show report in separate window" function, for section 5 High School Editor
// This should match the code in MenuBar.html doReport()
// *****************************************
function popupReport(reportUrl){
	var h;
	var w;
	
	if ((is_mac) || (is_macppc) || (is_mac68k)) {
		h = screen.height-60
		w = screen.width-10;
	} else if (is_nav) {
		h = screen.height-73; //was 102
		w = screen.width-10;
	} else {
		h = screen.height-200; 
		w = screen.width-150;
	}
	
	var features = '"';
	features += "toolbar=no,menubar=yes,location=no,scrollbars=yes,resizable,left=0,screenX=0,top=0,screenY=0,height=";
	features +=h;
	features +=",width=";
	features +=w;
	features += '"';
	
	var rptWindow = window.open(reportUrl, "Report", features);
}
