/************************************************************************

	Copyright (C) 2007 Olympia Computing Company. All Rights Reserved. 
	http://www.schoolmaster.com/

	WARNING: This software program is protected by copyright law 
	and international treaties. Unauthorized modification, reproduction or
	distribution of this program, or any portion of it, may result
	in severe civil and criminal penalties, and will be prosecuted
	to the maximum extent possible under the law.

*************************************************************************/

		
	// returns a String: blank if the user's browser is supported
	// or a warning if their browser is not supported
	function browserWarning() {
		var warning = "";
		var isIE = browserIsIE();
		var isFF = browswerIsFF();
		
		var warningText = "This application is optimized for use with IE 7, FireFox 2 or FireFox 3. Use of other browsers or earlier versions of IE may produce unexpected results.";
		
		if (isIE) {
			var versionNum = getIEVersionNumber();
			if (versionNum < 7) {
				warning = warningText;
			}
		} else
		{
			 if(isFF)
			{
				var versionNum = getFFVersionNumber();
				
				if(versionNum < 1.5)
				{
					warning = warningText;
				}
			
			}else 
			{
				warning = warningText;
			}
		}
		
		return warning;
	}		
	
	function browserIsIE() {
		var ua = navigator.userAgent;
		var MSIEOffset = ua.indexOf("MSIE ");
		if (MSIEOffset == -1) {
			return false;
		} else {
			return true;
		}
	}
		
	function getIEVersionNumber() {
		var ua = navigator.userAgent;
		var MSIEOffset = ua.indexOf("MSIE ");
		if (MSIEOffset == -1) {
			return 0;
		} else {
			return parseFloat(ua.substring(MSIEOffset + 5, ua.indexOf(";", MSIEOffset)));
		}
	} 
	
	function browswerIsFF() {
		var ua = navigator.userAgent;
		var FFOffset = ua.indexOf("Firefox");
		
		if (FFOffset == -1) {
			return false;
		} else {
			return true;
		}
	} 
    
    function getFFVersionNumber()
    {
		var ua = navigator.userAgent;
		
		var version = ua.indexOf('firefox/');
        if(version == -1)
        {
			version = ua.indexOf('Firefox/');
        }
        
        if(version != -1)
        {
			version = ua.substring(version+8);
		}
		return parseFloat(version);
    }
    
    // returns true if the String passed in 
    // as a param is empty/nothing but whitespaces
    function isBlank(s) {
		var blank = true;
		if (s == null) {
			blank = true;
		} else {
			for (var n=0; n<s.length; n++ ) {
				var c = s.charAt(n);
				if ( (c != ' ') && (c != '\n') && (c != '\t') ) {
					blank = false;
					break;
				}			
			}
		}
		
		return blank;
    }
    
	// returns a String containing the number of 
	// decimal places requested in the numOfPlaces
	// parameter, based on the value in the 
	// markToDisplay parameter
	// the markToDisplay parameter should be a 
	// String which can be parsed into a float
	function fixDecPlaces(markToDisplay, numOfPlaces) {
		var fixedString = markToDisplay;
		
		var markNum = parseFloat(markToDisplay);
		if (!isNaN(markNum)) {
			// make sure the number has the designated
			// number of decimal places
			var indexOfDec = markToDisplay.indexOf(".");
			if (indexOfDec < 0) {				
				// add a dec point and trailing zeros
				var decStr = "";
				for (var n=0; n<numOfPlaces; n++) {
					decStr = decStr + "0";
				}
				if (decStr.length > 0) {
					fixedString = fixedString + "." + decStr;
				}
			} else {
				// compare the actual # of decimal places
				// to the desired # of decimal places
				var actualNumOfPlaces = 
					(markToDisplay.substring
						(indexOfDec + 1, markToDisplay.length)).length;								
				
				// if there are too many dec places
				// then round to the correct # of places
				if (actualNumOfPlaces > numOfPlaces) {
					var multiplyByStr = "1";
					for (var n=0; n<numOfPlaces; n++) {
						multiplyByStr = multiplyByStr + "0";
					} 
					var multiplyBy = parseFloat(multiplyByStr);					
					var roundedNum = Math.round(markNum*multiplyBy)/multiplyBy;
					fixedString = roundedNum + "";
					
					// now call this function recursively to make
					// sure the rounded number has the correct
					// # of decimal places showing
					fixedString = fixDecPlaces(fixedString, numOfPlaces);
				}		
						
				// if there are not enough dec places
				// then append some trailing zeros
				else if (actualNumOfPlaces < numOfPlaces) {
					var difference = numOfPlaces - actualNumOfPlaces;
					var zeros = "";
					for (var n=0; n<difference; n++) {
						zeros = zeros + "0";
					}
					fixedString = markToDisplay + zeros;
				}
			}
		}
		
		return fixedString;
	} 
	
	// sDate must be in the format MM/DD/YYYY 
	// found this code here: http://www.codingforums.com/archive/index.php/t-14325.html
	function isDate(sDate) {	
		if (sDate == null) {
			return false;
		}
		var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/
		if (re.test(sDate)) {
			var dArr = sDate.split("/");
			var d = new Date(sDate);
			return d.getMonth() + 1 == dArr[0] && d.getDate() == dArr[1] && d.getFullYear() == dArr[2];
		}
		else {
			return false;
		}
	}
	
	function isDateInRange(testDateStr, startDateStr, endDateStr) {
		var isInRange = false;
		
		try {
			var testDate = new Date(testDateStr);
			var startDate = new Date(startDateStr);
			var endDate = new Date(endDateStr);
			
			isInRange = testDate >= startDate && 
						testDate <= endDate;
		} catch (ex) {
			// ignore ex, just return false
		}
		
		return isInRange;
	}
	
	// returns true if the str passed in contains
	// any alpha char in either upper or lower case
	function containsAlpha(str) {
		return containsLowerAlpha(str) || containsUpperAlpha(str);
	}
	
	// returns true if the str passed in contains
	// any alpha char in lower case
	function containsLowerAlpha(str) {
	    if (str == null) {
	        str = "";
	    }
		var myRegExp = new RegExp("[a-z]");
		return myRegExp.test(str);
	}
		
	// returns true if the str passed in contains
	// any alpha char in upper case
	function containsUpperAlpha(str) {
	    if (str == null) {
	        str = "";
	    }
		var myRegExp = new RegExp("[A-Z]");
		return myRegExp.test(str);
	}
			
	// returns true if the str passed in contains
	// any numeric char 
	function containsNumeric(str) {
		if (str == null) {
	        str = "";
	    }
		var myRegExp = new RegExp("[0-9]");
		return myRegExp.test(str);
	}
	
	function isNumber(sNum) {
	    if (sNum == null) {
	        sNum = "";
	    }
		var isANumber = false;
		
		// parseFloat returns a float consisting
		// of the first number chars in the string
		// even if they are trailed by non-number chars
		var num = parseFloat(sNum);
		if (!isNaN(num)) {
			isANumber = true;
			
			// now see if there were any String
			// chars that were thrown away by parseFloat,
			// and if so, return false
			if(sNum.length != num.toString().length) {
				isANumber = false;
			}
		}
		
		return isANumber;
	}
	
	// if fixMe ends in a period, that trailing period is
	// stripped off of the string returned
	function removeTrailingPeriod(fixMe) {
	    if (fixMe == null) {
	        fixMe = "";
	    }
		var fixed = trim(fixMe);

		var indexOfLast = fixMe.length -1;
		if (fixMe.charAt(indexOfLast) == '.') {
			fixed = fixMe.substring(0, indexOfLast);
		}

		return fixed;
	}
	
		
	// if fixMe ends in "px", that trailing "px" is
	// stripped off of the string returned
	function removeTrailingPx(fixMe) {
	    if (fixMe == null) {
	        fixMe = "";
	    }
		var fixed = trim(fixMe);

		var indexOfLast = fixMe.length -1;
		if (fixMe.charAt(indexOfLast) == 'x' && fixMe.charAt(indexOfLast-1) == 'p') {
			fixed = fixMe.substring(0, indexOfLast-1);
		}

		return fixed;
	}

	// removes leading and trailing whiteshpace
	function trim(sInString) {
	    if (sInString == null) {
	        sInString = "";
	    }
		sInString = sInString.replace( /^\s+/g, "" );// strip leading
		return sInString.replace( /\s+$/g, "" );// strip trailing
	}
	
	// return a string of non-breaking spaces, &nbsp;, 
	// the returned string contains the number of spaces
	// designated by the parameter passed in
    function getNbspStr(numOfSpaces) {
	    var str = "";

	    for (var n=0; n<numOfSpaces; n++) {
		    str = str + "&nbsp;";
	    }
	    return str;	
    }
	
	function jsQuoteToHtml(fixMe) {
	    if (fixMe == null) {
	        fixMe = "";
	    }
	    var fixed = fixMe;
	    
	    var patternDouble = new RegExp("\"", "g");
	    var patternSingle = new RegExp("\'", "g");
	    
	    fixed = fixed.replace(patternDouble, "&quot;");
	    fixed = fixed.replace(patternSingle, "&lsquo;");

        return fixed;
	}

	function htmlQuoteToJS(str) {
	    if (str == null) {
	        str = "";
	    }
		var fixedStr = str.replace("&lsquo;", "\\'");
		var fixedStr = fixedStr.replace("&quot;", "\\'");
		return fixedStr;
	}
	
	function encodeHtmlQuotes(str) {
	    if (str == null) {
	        str = "";
	    }
		var pattern = new RegExp("\"", "g");
		var fixedStr = str.replace(pattern, "&quot;");
		
		pattern = new RegExp("\'", "g");
		fixedStr = fixedStr.replace(pattern, "&lsquo;");
		
		return fixedStr;
	}
	
	function unencodeHtmlQuotes(str) {
	    if (str == null) {
	        str = "";
	    }
		var pattern = new RegExp("&quot;", "g");
		var fixedStr = str.replace(pattern, "\"");
		
		pattern = new RegExp("&lsquo;", "g");
		fixedStr = fixedStr.replace(pattern, "\'");
		
		pattern = new RegExp("&#039;", "g");
		fixedStr = fixedStr.replace(pattern, "\'");
		
		pattern = new RegExp("&apos;", "g");
		fixedStr = fixedStr.replace(pattern, "\'");
		
		return fixedStr;
	}
	
	function unencodeSlashes(str) {
	    if (str == null) {
	        str = "";
	    }
		var pattern = new RegExp("&#047;", "g");
		var fixedStr = str.replace(pattern, "/");
		
		pattern = new RegExp("&#092;", "g");
		fixedStr = fixedStr.replace(pattern, "\\");
		
		pattern = new RegExp("%2F", "g");
		fixedStr = fixedStr.replace(pattern, "/");
		
		return fixedStr;
	}
	
	function changeBrToNewLine(str) {
	    if (str == null) {
	        str = "";
	    }
		var pattern = new RegExp("<br>", "g");
		var fixedStr = str.replace(pattern, "\n");
		
		return fixedStr;
	}


	function addEvent(obj, evType, fn){
		if (obj.addEventListener)
		{
   			obj.addEventListener(evType, fn, false);
   			return true;
		}
		else if (obj.attachEvent)
		{
   			var r = obj.attachEvent("on"+evType, fn);
   			return r;
 		}
 		else
 		{
   			return false;
 		}
	}
	
	// returns, as a String, the value of the 
	// selected option from the selectObj
	// passsed in as a parameter
	function getSelectedValue(selectObj) {
		var selectedValue = "";
		if (selectObj != null) {
			var options = selectObj.options;
			for (var n=0; n<options.length; n++) {
				if (options[n].selected) {
					selectedValue = options[n].value;
					break;
				}
			}	
		}
		return selectedValue;
	}
	
	// sets the selected option in the selectObj passed in
	// to the option which has the value of valueToSelect
	function setSelectedValue(selectObj, valueToSelect)
	{
		if (selectObj != null && valueToSelect != null) {
			var optLength = selectObj.options.length;
			for(var i = 0; i < optLength; i++)
			{
				if(selectObj.options[i].value == valueToSelect)
				{
					selectObj.options[i].selected = true;
					return;
				}
			}
		}
	}
	
	// returns the value from the queryStr passed in
	// for the key passed in
	function getValueFromQueryStr(key, queryStr) {
	    if (queryStr == null) {
	        queryStr = "";
	    }
		var value = null;
		var keyValPairs = queryStr.split("&");
		
		var thePair = null;
		var size = keyValPairs.length;
		for (n=0; n<size; n++) {
			if (keyValPairs[n].indexOf(key) == 0) {
				thePair = keyValPairs[n];
				break;
			}
		}
		
		if (thePair != null) {
			var keyAndValue = thePair.split("=");
			if (keyAndValue.length == 2) {
				value = keyAndValue[1];
			}
		}
		return value;	
	}
   //Returns the military hours so even if the user types in anything greater
    //than 24.  This will calculate it to the correct number like 25 is 0100 am.
    function GetHours(first,second)
    {
        var strHours = "";
        var Hours=0;
        strHours = first + "" + second + "";
        try
        {
            Hours = parseInt(strHours);//allow javascript to cast it to numeric.
         }
         catch(Err)
         {
            Hours=7;
         }
        if( Hours < 48)
            Hours = Hours - 24;
        else if(Hours < 72)
            Hours = Hours - 48;
        else if(Hours == 97 || Hours == 98 || Hours == 99)
            Hours = 7;
        else
            Hours = Hours - 72;
        return Hours;
    }
    //Function to check if text is numeric.
    function IsNumeric(sText)
    {
       var ValidChars = "0123456789.";
       var IsNumber=true;
       var Char;
       for (i = 0; i < sText.length && IsNumber == true; i++) 
          { 
          Char = sText.charAt(i); 
          if (ValidChars.indexOf(Char) == -1) 
             {
               IsNumber = false;
             }
          }
       return IsNumber;
       
       }

     //This function converts the time passed in.  This function expects a number.
     function ConvertNumberToTime(value)
     {
        var strReturn ="";
        if(!IsNumeric(value))
        {//
            return "Invalid Date";
        }
        if(value == 0)
            return "12:00 AM";
        
        var blnIsPM= false;
        //Force the value to have four digits.
        if(value.length == 1)
        {
           value =  "0" + value + "0" + "0";
        }
        if(value.length ==2)
             value = value + "0" + "0" ;
        if(value.length ==3)
            if(value >= 100 && value <= 999)
                value = "0" + value;//100 will be 1:00 and so forth.
            else
             value = value + "0";
        if(value.length >= 4)
        {  
            //Turn first two values (Hours) into proper values
            var firstHour,SecondHour = 0;
            var firstMin,SecondMin=0;
            try
            {
                firstHour =parseInt(value.charAt(0));
                SecondHour =parseInt(value.charAt(1));
                firstMin=parseInt(value.charAt(2));
                SecondMin=parseInt(value.charAt(3));
               
            }
            catch(Err)
            {
                firstHour = 0;
                SecondHour = 7;
                firstMin=0;
                SecondMin=0;
            }
            var Hours = 0;
            if(firstHour ==0 && SecondHour ==0)
            {
                Hours=24;
            }
            if(firstHour >= 2 && SecondHour > 4)
            {//check if it greater than 24hrs.
                Hours =GetHours(firstHour, SecondHour);
            }
            else
            {
                var str = "";
                if(firstHour == 0)
                    str= SecondHour + "";
                else
                    str= firstHour + "" + SecondHour;
                Hours = parseInt(str);
            }
            if(firstMin > 5)
            {
                firstMin=0;
            }
            var strHours ="";
            if(Hours >= 12 && Hours < 24)
             {
                 blnIsPM=true;
                 if(Hours> 12)
                    Hours = Hours - 12;
             }
             if(Hours == 24)
                Hours = 12;
            if(Hours < 10)
            {
                strHours = "0" + Hours;
            }
            else
                strHours = Hours;
            strReturn =strHours + ":" + firstMin + SecondMin; 
            if(blnIsPM)
                strReturn += " PM";
            else
                strReturn += " AM";
            
            return strReturn;
        }
        
        return strReturn;
     }
    //This function will return a properly formatted date if it cannot format the data passed in then 07:00 am gets sent back.
    function FixTime(obj)
    {
        var time =null;
        if(obj!= null)
            time = obj.value;
        
        var defaultHours = "07";
        var defaultMinutes = "00";
        //if null or blank return default value;
        var checkReturn = time.toLowerCase();
        if((checkReturn.indexOf("pm")>= 0 || checkReturn.indexOf("am")>= 0) 
                && checkReturn.indexOf(":")>= 0 && (checkReturn.length ==8 
                    || checkReturn.length ==7)) {
                    
            // make sure all the hrs and mins are actually numbers    
            var numeric = false;
            var testForNumeric = checkReturn;
            testForNumeric = testForNumeric.replace("pm", "");
            testForNumeric = testForNumeric.replace("am", "");
            testForNumeric = testForNumeric.replace(":", "");
            testForNumeric = trim(testForNumeric);
            
            if (IsNumeric(testForNumeric)) {
                numeric = true;
            }
                 
            if (numeric) {  
                return false;//it is good.
            } 
            // otherwise, the logic below is executed
        }
        if(time == null || time =='')//return and don't check
        {
            return false;
        }
        //see if it is all numbers.
       if(IsNumeric(time))//This will only convert the first 4 and chop off the rest.
       {
            time = ConvertNumberToTime(time);
            obj.value= time;
            return false;
       }
       else
       {//Checks to see if the user typed in : or am or pm or all and if they did and the numbers are valid I will count it.
       //else return a default date of 0700 am.
            //Strip all to make a number then convert the date.
            var replaceNone = "";//Varible to replace unwanted characters. 
            var myOldString = time.toLowerCase();
            var newTime = myOldString.replace(":", replaceNone);
            var blnADD12= false;
            var blnADD12ToFront=false;
            var blnADD0ToFront=false;
            var blnMakeIt24 = false;
            var intLength= 0;
            intLength =  newTime.length;
            //Checks to see if they typed in an am or pm to convert it properly to a date.
            if(newTime.indexOf("pm")>= 0 && intLength == 3)
            {//allows a user to type in 1pm and translate it to 13:00PM
                blnADD12=true;
            }
            if(newTime.indexOf("pm")>= 0 && intLength == 4 && newTime.indexOf(" ")>= 0)
            {//allows a user to type in 1 pm and translate it to 13:00PM
                 blnADD12=true;
            }
            
            //allows the user to enter a 3 digit number with an am or pm. 
            //for example 123pm = 01:23PM
            if(newTime.indexOf("pm")>= 0 && intLength == 5 && newTime.indexOf(" ")== -1)
            {//allows a user to type in 123pm and translate it to 13:23PM
                blnADD12ToFront=true;
                //remove letters and space then add 
            }
            
  
            if(newTime.indexOf("pm")>= 0 && intLength == 6 && newTime.indexOf(" ")>= 0)
            {//allows a user to type in 123 pm and translate it to 13:23PM
                blnADD12ToFront=true;
            }
             if(newTime.indexOf("pm")>= 0 && intLength == 6 && newTime.charAt(0) == '0' && newTime.indexOf(" ")== -1)
             {//allows a user to type in 0123pm and translate it to 13:23PM
                var tmp ="";//remove the zero.
                for(var i=1; i < intLength;i++)
                {
                    tmp += newTime.charAt(i);
                  
                }
                newTime = tmp;//swap
                 blnADD12ToFront=true;//now you can add twelve to the front.
             }
            
            if(newTime.indexOf("am")>= 0 && intLength == 3)
            {//allows a user to type in 1am and translate it to 0100AM
                blnADD0ToFront=true;
            }
            if(newTime.indexOf("am")>= 0 && intLength == 4 && newTime.indexOf(" ")>= 0)
            {//allows a user to type in 1 am and translate it to 0100AM
                blnADD0ToFront=true;
            }
           if(myOldString.indexOf("am")>= 0 && intLength == 6 && newTime.indexOf(" ")>= 0)
            {//allows a user to type in 123 am and translate it to 01:23AM
                blnADD0ToFront=true;
            }
             if(newTime.indexOf("am")>= 0 && intLength == 4 &&  newTime.charAt(0) == '1' && newTime.charAt(1) == '2')
             {//allows user to type 12am and translate to 12:00AM
                blnMakeIt24=true;
             }
            if(newTime.indexOf("am")>= 0 && intLength == 5 &&  newTime.charAt(0) == '1' && newTime.charAt(1) == '2' && newTime.indexOf(" ")>= 0)
             {//allows user to type 12 am and translate to 12:00AM
                blnMakeIt24=true;
             }
           if(newTime.indexOf("am")>= 0 && intLength == 6 && newTime.charAt(0) == '1' && newTime.charAt(1) == '2'  && newTime.indexOf(" ")== -1)
             {//allows a user to type in 1223am and translate it to 12:23AM
                blnMakeIt24=true;
             }
           if(newTime.indexOf("am")>= 0 && intLength == 7 && newTime.charAt(0) == '1' && newTime.charAt(1) == '2'  && newTime.indexOf(" ")== 0)
             {//allows a user to type in 1223 am and translate it to 12:23AM
                blnMakeIt24=true;
             }
            //allows the user to enter a 3 digit number with an am or pm. 
            //for example 123am = 01:23am
            if(newTime.indexOf("am")>= 0 && intLength == 5  && newTime.indexOf(" ")== -1)
            {//allows a user to type in 123am and translate it to 01:23AM
                    blnADD0ToFront=true;
                //remove letters and space then add 
            } 
            //strip all unwanted characters...  
            newTime = newTime.replace("am",replaceNone);
            newTime = newTime.replace("pm",replaceNone);
            newTime = newTime.replace(" ",replaceNone);
              
            if(IsNumeric(newTime))
            {

                  if(blnADD12)
                  {
                    var addHours= 0;
                    addHours = parseInt(newTime)+ 12;
                    newTime = addHours + "" ;
                   }
                   if(blnADD0ToFront)
                   {
                    newTime= "0" + newTime;
                    
                   }
                  if(blnADD12ToFront)
                   {
                    var addFrontHours= 0;
                    addFrontHours = parseInt(newTime.charAt(0))+ 12;                    
                    newTime = addFrontHours + newTime.charAt(1)+ newTime.charAt(2)+ "" ;
                   }
                   if(blnMakeIt24)
                   {
                        var min1,min2=0;

                        if(newTime.charAt(2) =='' || newTime.charAt(2) == null)
                            min1=0;
                        else
                            min1=newTime.charAt(2);
                        if(newTime.charAt(3) =='' || newTime.charAt(3) == null)
                            min2=0;
                        else
                            min2=newTime.charAt(3);
                            
                       newTime = "24" + min1 + min2;
                   }
                  newTime = ConvertNumberToTime(newTime);
                  obj.value= newTime;
            }
            else
            {
                  obj.value = defaultHours + ":" + defaultMinutes + " AM";
                  return false;
            }
 
       }

        
        return false;
        
        
    }
    
    function GetTimeOfDay()
    {
        var timeOfDay="";//initialize it to a string.
        var currentTime = new Date();
        var hours = currentTime.getHours();
        var minutes = currentTime.getMinutes();
        if (minutes < 10)
        minutes = "0" + minutes;
         timeOfDay= hours + ":" + minutes + "";
        if(hours > 11)
        {
         timeOfDay += " PM";
        } else 
        {
         timeOfDay +=" AM";
        }
        return timeOfDay;
    }

    function getNowString()
    {
        var nowStr = "";//initialize it to a string.
        var currentTime = new Date();
        var month = currentTime.getMonth() + 1;
        var day = currentTime.getDate();
        var year = currentTime.getFullYear();
        nowStr = month + "/" + day + "/" + year;
        return nowStr;
    }
    
function opacity(id, opacStart, opacEnd, millisec) {
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
}

//change the opacity for different browsers
function changeOpac(opacity, id) {
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
} 
