var smallTable = " height=6 cellpadding=0 cellspacing=0 ";
var urTable = "<table border=0 " + smallTable + " >";
var gCommNumber=0;
var keyupCheck = "onkeyup=\'checkLength( this, 4096 )\' ";
var xmlDocument; 
var gCommNumber = 0;
var Xcount = 1000;
var jsonR = {};

/*function idXMLHttpRequest( value ) {
  this.setValue( value );
}*/ 
//idXMLHttpRequest.inherits( XMLHttpRequest );
var XMLHttpRequestObject = new Array();
for( var xh=0; xh < Xcount; xh += 1 )
  XMLHttpRequestObject[xh] = false;

  
if (window.ActiveXObject) {
for( var xh=0; xh < Xcount; xh += 1 )
  XMLHttpRequestObject[xh] = new ActiveXObject("Microsoft.XMLHTTP");
} else  
if (window.XMLHttpRequest) {
for( var xh=0; xh < Xcount; xh += 1 )
  XMLHttpRequestObject[xh] =  new XMLHttpRequest();
  
}  

function getValue( temp )
{
  if( temp != null )
    return temp.value;
  return "";
}

var lastCommObjN;
function commXMLDocument( objN, context, url, sendMessage )
//  The context is needed so that it knows what function to call afterwards
{
  gCommNumber += 1;
  if( gCommNumber > 79 ) gCommNumber = 0;
  objN = gCommNumber;
  
  if(XMLHttpRequestObject[objN]) {    
    XMLHttpRequestObject[objN].open("POST", url);    
    XMLHttpRequestObject[objN].setRequestHeader('Content-Type',
      'application/x-www-form-urlencoded');
 
//    XMLHttpRequestObject[objN].id = objN;
    XMLHttpRequestObject[objN].onreadystatechange = function()
    {	
      if (XMLHttpRequestObject[objN].readyState == 4 &&
        XMLHttpRequestObject[objN].status == 200 ) {
		
          xmlDocument = XMLHttpRequestObject[objN].responseXML;
          var evaltar = XMLHttpRequestObject[objN].responseText;

          if( evaltar != '' && evaltar != undefined && 
              evaltar != null && evaltar.indexOf("[") != -1 )
            jsonR       = eval( "(" + evaltar + ")" );

//          if(window.ActiveXObject)
//            jsonR       = window.execScript( "(" + evaltar + ")" );
//          else

//          d( "recieved: " + xmlDocument + " objectNumber=" + getData( xmlDocument.getElementsByTagName( 'objectNumber' )[0] ) );
          if( xmlDocument == null ) d( "got a null xmlDocument<br>" );
          
          var on;
          if( xmlDocument != null ) 
            on = getData( xmlDocument.getElementsByTagName( 'objectNumber' )[0] );

          d( gCommNumber + ":" + on + "  " );

          if(( url.indexOf( "readFile" ) != -1 ) ||
              ( url.indexOf( "saveToFile" ) != -1 ))
          {
            if( on == gCommNumber ) 
            {
              d( "Going to: " );
	      if( context != none ) context();
            }
          } else
            if( context != none ) context();
     }	  
   }

    XMLHttpRequestObject[objN].send( sendMessage + "&objectNumber=" + objN );
    d( "sending message: " + sendMessage + "|" + url + "|" + objN + "|<BR>" );
  }
}

function debugAssist()
{
  document.getElementById("loginID").value = "bob1";
  document.getElementById("password").value = "p";
}

function isBefore( str1, str2 )
//  if str1 is before str2, alphabetically then return 1 else return 0;
{
  str1 = str1.toLowerCase();
  str2 = str2.toLowerCase();
  var a = new Array();
  a[0] = str1;
  a[1] = str2;
  a = a.sort();
  if( a[0] == str1 ) return 1;
  else return 0;
}

var logString = "";
function d( temp )
{	 
    if( "on" == debug )
    {
      logString = logString + temp;

    if( temp == "logNow" )
   {
       //  xml and & interfere with the parsing so we replace them
       logString = logString.replace( /xml/g, "qml" );
       logString = logString.replace( /&/g, "amp" );

       var d = new Date(); 

       commXMLDocument( 0, none, phpDir + "saveToFile.php",  
       "name=../Data/debug.html&encode=-2&xml=<html><body><font size=4 face=courier><code>" + 
       d.getDate() + logString + "</code></font></body></html>" );
   }
   }
}

var un=undefined;
function getData( temp )
{     
     if(( temp != null ) && ( temp != un ))
	   if (( temp.firstChild != null ) && ( temp.firstChild != undefined ))
		 return getRidOfSlashes( (temp.firstChild.data) );
		 
	 return "";
}

function getRidOfSlashes( word )
//  The server seems to places slashes \ before quotation marks.  I don't know
//  exactly how or why it happens; it's probably there for security reasons.
//  Anyway, it must be undone once the text is reloaded.
{
  var newWord = "";
  if( word == undefined )
    d( "warning: getRidOfSlashes: word is undefined." );
  else
  if( word.indexOf( '\\' ) != -1 )
  {
    for( var a=0; a < word.length; a += 1 )
      if( word.charAt( a ) != '\\' ) newWord += word.charAt( a );
      
    return newWord;
  }
 
  if( word == undefined ) return "";
  else return word;
}

function checkCharacters( str, astr )
//  if quotes are in the <a href=' asdfadsf' > argument,
//  the whole sting will fail to parse and the onclick won't work.
{
    if(( str == null ) || ( str == undefined ) || ( str == "" )) return 0;
    for( var a=0; a < str.length; a ++ )
      if( validChars.indexOf( str.charAt( a ) ) == -1 ) 
      {
         if(( astr == null ) || ( astr == undefined ) || ( astr == "" )) 
           alert( "Please use only alphanumeric characters (a-z, A-Z, 0-9, space,/-). " );
         else alert( astr );

         i = "";
         return 0;
      }

    return 1;
}

var validChars = "0123456789 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/-:";
var gNext;
function promptUser( first, second, next )
//  first:  	   prompt to the user
//  second: 	   default answer brovided in the text input
//  next:   	   function pointer, place to go after user clicks okay
//                 user reply gets passed back through argument
//  Postcondition: Don't allow emtpy inputs from the user, 
//                 keep asking for non-empty input
{
  //  safari won't allow us to pass this through an embedded argument
  gNext = next;  
  document.getElementById( "hint" ).style.visibility = 'visible';
  document.getElementById( "hint" ).style.left       = 350;
  document.getElementById( "hint" ).style.top        = 200;
  document.getElementById( "hint" ).style.width      = 280;
  document.getElementById( "hint" ).innerHTML = 
  "<table cellpadding=2><tr><td>" + first + 
  "<br><input type='text' style='width: 245px;' length=35 maxlength=35 "+
  " id='textinput' onKeyPress='if(1 == checkEnter(event)) promptUser2( \"\" "+
  ")' >" + "<font size=1><br><br></font>" + 
  "<table border=0><tr><td><input type='button' value='cancel' onclick='promptUser2( \"cancel\" " +
  " )' style='width: 120px;' >"+
  "</td><td><input type='button' value='OK' style='width: 120px;' " + 
  "onclick='promptUser2( \"\" )' ></td></tr></table></td></tr></table>";
  document.getElementById( 'textinput' ).value = second;
  document.getElementById( 'textinput' ).focus();
}

function promptUser2( i )
{
    if( i != "cancel" ) i = get( 'textinput' );
    if( i == "" ) alert( "Enter a string or cancel." );
    if( checkCharacters( i ) == 0 )  i = "";
    if( i != "" )
    {
      document.getElementById( "hint" ).style.visibility = 'hidden';
      document.getElementById( "hint" ).innerHTML = '';
    }
    if(( i != "cancel" ) && ( i != "" ))  gNext( i );
}

function none() 
{  //  this should never be called but is required so that it is recognized as function pointer
} 

function clear( divTag )
{
  var obj;
  if( divTag == "links" ) 
    obj = parent.topFrame.document.getElementById( divTag );
  else {
    if( parent.leftFrame == null )
       obj = document.getElementById( divTag );
    else
      obj = parent.leftFrame.document.getElementById( divTag );
  }

  if( obj != null )
    obj.innerHTML = "";
}

var tabNumber = 0;
var tabCache = new Array(4);
tabCache[0] = "";
tabCache[1] = "";
tabCache[2] = "";
tabCache[3] = "";
tabCache[4] = "";

function displayIt( divTag, contentsToDisplay, clearit, displayBrackets )
//  By default we dipslay the <br> tags in place of \n but for the divs
//  where there are textareas then we need to give -2 for diplayBrackets
//  because textarea does not translate <br> into line break so keep it as \n
{
//  if(( contentsToDisplay == undefined ) || ( contentsToDisplay == "undefined" ))
//  {  d( "not showing undefined." ); return; }

  contentsToDisplay = decodeBrackets( contentsToDisplay );
  if( displayBrackets == "nobreaks" )  //  means no html breaks
  {
    //  we need some of the existing line breaks (like the ones in the mult choice questions)
    //contentsToDisplay = String( contentsToDisplay ).replace( /<br>/g, "\n" );
  }
  else
  {
      contentsToDisplay = String( contentsToDisplay ).replace( /\n/g, "<br>" );
  }

//  alert( "con" + contentsToDisplay + "\n\n" + tabNumber + "\n\n" + tabCache );
  if(( divTag == "div0" ) && tabCache != undefined && tabNumber != undefined ) 
    tabCache[ tabNumber ] = contentsToDisplay;

  var obj;  
  if( divTag == "links" ) 
    obj = parent.topFrame.document.getElementById( divTag );
  else {


   if( parent == null )
     obj = document.getElementById( divTag );
   else
   if( parent.leftFrame == null )
     obj = document.getElementById( divTag );
   else
     obj = parent.leftFrame.document.getElementById( divTag );
  }

  if( divTag == "subDiv" )
    obj = document.getElementById( 'subFrame' ).contentWindow.document.getElementById( 'subDiv' );

  if(( obj != null ) && ( contentsToDisplay != "" ))
    if( clearit == "clear" )
    {
      obj.innerHTML = contentsToDisplay;
    } else
      obj.innerHTML = obj.innerHTML + contentsToDisplay;       
}

function CHECKN( xmlDoc, string1 )
{
  if( xmlDoc == null )
    d( string1 + " is null.  Usually caused if there is a syntax error in the php, causing it to return null or the php header was not added: header('Content-type: text/xml');." );
}

function ASSERTN( comparison, string )
{
  if( comparison )  d( string + " is not null. " );
    else d( string + " is null. " );
}

function ASSERTS( comparison, string1, string2 )
{
  if( comparison )  d( string1 );
  else d( string2 );
}

function getObjFromSub( string )
{
  if( document != null )
    return document.getElementById( 'subFrame' ).contentWindow.document.getElementById( string );
  else return "";
}

function getFromSub( string )
{
  if( document != null )
    return encodeBrackets(
      getValue( document.getElementById( 'subFrame' ).contentWindow.document.getElementById( string )));
  else return "";
}

function getn( string )
{
  if( document != null )
    return getValue(document.getElementById( string )) ;
  else return "";
}

function get( string )
{
  if( document != null )
    return encodeBrackets(
      getValue(document.getElementById( string )) );
  else return "";
}

function div( lookup )
{
  return get( lookup );
}

function encodeBrackets( str )
{
  //  the following are all problem characters that must be encoded
  //  because they confuse xml.

  if(( str == null ) || ( str == undefined ) || ( str == "" )) return str;
  str = String( str );
  str = str.replace( /</g, "#o#" ); 
  str = str.replace( />/g, "#c#" ); 
  str = str.replace( /\'/g, "#q#" ); 
  str = str.replace( /\"/g, "#d#" ); 
  str = str.replace( /\+/g, "#p#" ); 
  return str;
}

function decodeBrackets( str )
{
  if(( str == null ) || ( str == undefined ) || ( str == "" )) return str;
  str = String( str );
  str = str.replace( /#o#/g, "<" ); 
  str = str.replace( /#c#/g, ">" ); 
  str = str.replace( /#q#/g, "'" ); 
  str = str.replace( /#d#/g, '"' ); 
  str = str.replace( /#p#/g, "+" ); 
  return str;
}
function divNull()
{
  for( var iloop=0; iloop < 21; iloop++)
    document.getElementById( "div" + iloop ).innerHTML = "";
}

function space8()
{  
  return " &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp";  
}

function spacesToUnderscores( str )
{
  return str.replace( /\s/g, "_" );
}

// Removes leading whitespaces
function LTrim( value ) {
	
	var re = /\s*((\S+\s*)*)/g;
	return value.replace(re, "$1");
	
}

// Removes ending whitespaces
function RTrim( value ) {
	
	var re = /((\s*\S+)*)\s*/g;
	return value.replace(re, "$1");
	
}

// Removes leading and ending whitespaces
function trim( value ) {	
	return LTrim(RTrim(value));	
}

function schoolNameToCode( s )
{
    newString = '';

    var Length = s.length;
    if( Length > 8 ) Length = 8;

    for( var ii=0; ii < Length; ii += 1 )
    {
      newString += String.fromCharCode( s.charCodeAt(ii) + 4 );
    }
    newString = newString.toLowerCase();
    return newString;
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=")
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1
    c_end=document.cookie.indexOf(";",c_start)
    if (c_end==-1) c_end=document.cookie.length
    return unescape(document.cookie.substring(c_start,c_end))
    }
  }
return ""
}

function checkLength( obj, maxLength )
{
  if( obj.value.length > maxLength )  {
      alert( "You have reached the maximum text length. " );      obj.value = obj.value.slice(0, maxLength);
  }
}

function setCookie(cookieName,cookieValue,nDays) {
 var today = new Date();
 var expire = new Date();
 if (nDays==null || nDays==0) nDays=1;
 expire.setTime(today.getTime() + 3600000*24*nDays);
 document.cookie = cookieName+"="+escape(cookieValue)
                 + ";expires="+expire.toGMTString();
}

function getDate( format )
{
  var currentTime = new Date();
  var month = currentTime.getMonth() + 1;
  var day = currentTime.getDate();
  var year = currentTime.getFullYear();
  if (format == 2 )
    return year + "-" + month + "-" + day;
  else
    return month + "/" + day + "/" + year;
}

