//  Function to open a window
function windowOpen(window_url) {
  firsthalf='toolbar=yes,status=no,scrollbars=yes,menubar=yes,resizable=yes'
  secondhalf=',directories=no,location=no,width=550,height=400'
  whole = firsthalf + secondhalf
  helpWin = window.open(window_url,'',whole);
  if (document.images) { 
     if (helpWin) helpWin.focus()
  }
}

//  Function to disable the submit button after it is clicked.
function onesubmit() {
  document.forms[0].submitbutton.value = "Processing";
  document.forms[0].submitbutton.disabled = true;
  return true;
}

/*
 *  The following variables and functions are used for 1098-T.
 */
var htitle = new Array();
var hmsg = new Array();
function setmsgs() 
{
htitle["QualExp"] = "Qualified Tuition and Related Expenses";
hmsg["QualExp"] = 
"For Tax Year 2001 zeros are being reported." +
" Prior to tax year 2001, the reporting institution was not required to," +
" but may have provided information in this box.";
htitle["ReimbRef"] = "Reimbursments or Refunds";
hmsg["ReimbRef"] =
"For Tax Year 2001 zeros are being reported.";
htitle["ScholGrnt"] = "Scholarships or Grants";
hmsg["ScholGrnt"] = 
" For Tax Years 2002 and 2001, zeros are being reported." +
" Prior to tax year 2001, this amount was reported in Box 2 on Form 1098-T." +
" The reporting institution was not required to, but may have provided" +
" information in this box.";
htitle["HalfTimeInd"] = "Half-Time or Greater Indicator";
hmsg["HalfTimeInd"] = 
" This field contains an <b>X</b> if you are considered to be carrying at " +
" least one-half the normal full time work load for your course" +
" of study at the reporting institution. If you are at least a half-time" +
" student for at least one academic period beginning during the year, you" +
" meet one of the requirements for the Hope credit. You do not have to be a" +
" half-time student to qualify for the Lifetime Learning credit.";
htitle["GradStuInd"] = "Graduate Student Indicator";
hmsg["GradStuInd"] = 
" This field contains an <b>X</b> if you are considered to be" +
" enrolled exclusively in a program leading to a graduate degree," +
" graduate-level certificate, or other recognized graduate-level educational" +
" credential. If you are enrolled exclusively in a graduate program, you are" +
" not eligible for the Hope credit, but you may qualify for the" +
" Lifetime Learning credit.";
htitle["AmtBill"] = "Amount Billed for Qualified Tuition and Expenses";
hmsg["AmtBill"] = 
" This represents the amounts billed during the calendar year for" +
" qualified tuition and related expenses. The amount reported is the total" +
" amount billed less any reductions in charges made during the calendar" +
" year that relate to the amounts billed.";
htitle["AdjAmtBill"] = "Prior Year Adjustment to Amount Billed";
hmsg["AdjAmtBill"] = 
" This represents any reduction in charges made for qualified tuition" +
" and related expenses processed during the calendar year that relate to" +
" amounts billed that were reported for a prior year.";
htitle["ScholGrnt03"] = "Scholarships or Grants";
hmsg["ScholGrnt03"] = 
" This represents the total amount of any scholarships or grants " +
" administered and processed during the calendar year for the payment" +
" of cost of attendance.";
htitle["AdjScholGrnt"] = "Prior Year Adjustment to Scholarships or Grants";
hmsg["AdjScholGrnt"] = 
" This represents any reduction to the amount of scholarships or " +
" grants that were reported for a prior year.";
htitle["FirstQtrInd"] = "Amount Billed Includes 1st Quarter Next Year";
hmsg["FirstQtrInd"] = 
" This field contains an <b>X</b> if any amounts billed for qualified tuition" +
" and related expenses reported for the tax year relate to an academic" +
" period that begins in the 1st quarter (through March 31) of the next" +
" tax year.";
}
//
//
function get1098TTitle(msgindex)
{
   var title = htitle[msgindex];
   document.write(title);  
}
function get1098TMsg(msgindex)
{
   var msg = hmsg[msgindex];
   document.write(msg);  
}
/*
 *  End of 1098-T functions.
 */
 
//  Function to modify a Course section literal into a WebCT link 
function launchWebCT(ctitle, WebctInUseNoCP, WebctURL, DCode){
  var openNewWindow = " This link will open a new window.";
  if (WebctInUseNoCP == "true" && DCode == "WC") {
     document.write('<a href="'+ WebctURL + '" target="WebCT"' + 
     '" title="' + ctitle + openNewWindow +
     '" onMouseOver="window.status=(\'' + ctitle + openNewWindow +'\'); ' +
     'return true;" onMouseOut="window.status=\'\'; return true">' +
     ctitle + '</a>' ); }
  else { 
     document.write(ctitle);
     }
  }

//  Function to validate search criteria in Course Section Search. If 
//  successful, invoke onesubmit function.
function Crs_Srch_Validate()
{
  var SubjIx  = document.forms[0].Subject.selectedIndex;
  var Time1Ix = document.forms[0].StartTime1.selectedIndex;
  var Time2Ix = document.forms[0].StartTime2.selectedIndex;
  if (!document.forms[0].Mon.checked &&
      !document.forms[0].Tue.checked &&
      !document.forms[0].Wed.checked &&
      !document.forms[0].Thu.checked &&
      !document.forms[0].Fri.checked &&
      !document.forms[0].Sat.checked &&
      !document.forms[0].Sun.checked &&
      !document.forms[0].TBA.checked &&
      !document.forms[0].All.checked &&
       document.forms[0].Subject.options[SubjIx].value == "ALL" &&
       document.forms[0].StartTime1.options[Time1Ix].value == "ALL" &&
       document.forms[0].StartTime2.options[Time2Ix].value == "ALL")   
  {
    alert("Please select at least one of the first 4 options.");
    return false; 
  }
  else
  if (!document.forms[0].Mon.checked &&
      !document.forms[0].Tue.checked &&
      !document.forms[0].Wed.checked &&
      !document.forms[0].Thu.checked &&
      !document.forms[0].Fri.checked &&
      !document.forms[0].Sat.checked &&
      !document.forms[0].Sun.checked &&
      !document.forms[0].TBA.checked &&
      !document.forms[0].All.checked)
  {
    alert("At least one 'Day' option must be selected.");
    return false; 
  }
  else
  if (document.forms[0].StartTime1.options[Time1Ix].value != "ALL" && 
      document.forms[0].StartTime2.options[Time2Ix].value != "ALL" &&
      document.forms[0].StartTime1.options[Time1Ix].value > 
      document.forms[0].StartTime2.options[Time2Ix].value)
  {
   alert("The first Start Time can not be greater than the second Start Time.");
   return false;
  }
  else
  {
  onesubmit();
  }
}

// Function to check if a value entered is a currency value.
function isCurrency(amt)
{
	var nNum = 0;			// Total numbers for currency value.
	var nDollarSign = 0;	// Total times a dollar sign occurs.
	var nDecimal = 0;		// Total times a decimal point occurs.
	var nCommas = 0;		// Total times a comma occurs.
	var txtLen;				// Length of string passed.
	var xTxt;				// Assigned object passed.
	var sDollarVal;		// Assigned dollar amount with or without commas.
	var bComma;
	var decPos = 0;		// Assigned value of numbers or
	                     // positions after decimal point.
	var nNumCount = 0;	// Total number between commas.
	var i;					// For forloop indexing.
	var x;					// Assigned each individual character in string.

	// Set the xTxt variable to the object passed to this function.
	// Assign the length of the string to txtLen.
	xTxt = amt;
	txtLen = xTxt.length

	if(txtLen == 0) {
	   alert("ERROR! \n\nYou must enter a Payment Amount!");
		return false;
	}

	for(i = 0; i < txtLen; i++)
	{
		// Assign character in substring to x.
		x = xTxt.substr(i, 1);


		if(x == "$")
			nDollarSign = nDollarSign + 1; // Sum total times dollar sign occurs.
		else if(x == ".")
			nDecimal = nDecimal + 1; // Sum total times decimal point occurs.
		else if(x == ",")
			nCommas = nCommas + 1; // Sum total times comma occurs.
		else if(parseInt(x) >= 0 || parseInt(x) <= 9)
		   // If the character is a number sum total times a number occurs.
			nNum = nNum + 1;
		else
		{
			// Error occurs if any other character value is in the string
			// other then the valid characters.
			alert("ERROR! \n\nYou have entered an illegal value!\n" +
			     "Please enter only: Dollar Signs, Commas, " +
				  "Decimal Points, and numbers between 0 and 9!");
			return false;
		} // end else
	} // end for

	if(nDollarSign > 1)
	{
		alert("ERROR! \n\nYou have entered more then one dollar sign!\n" +
		      "Please only enter one!");
		return false;
	} // end if

	if(nDecimal > 1)
	{
		alert("ERROR! \n\nYou have entered more then one decimal point!\n" +
		      "Please only enter one!");
		return false;
	} // end if

	if(nDollarSign == 1)
	{
		// Make sure dollar sign in the first character in string
		// if there is a dollar sign present.
		if(xTxt.indexOf("$") != 0)
		{
			alert("ERROR!  \n\nThe dollar sign you entered is not in the " +
			      "correct position!");
			return false;
		} // end if
	}// end if

	if(nDecimal == 1)
	{
		// Get the number of numbers after the decimal point in
		// the string if there is a decimal point present
		decPos = (txtLen - 1) - xTxt.indexOf(".");

		// Floating point cannot be more then two.
		// Valid format after decimal point.
		/**********************************/
		/*   $#.##, $#.#, $.#, $#., $.##  */
		/**********************************/
		if(decPos > 2)
		{
			alert("ERROR! \n\nThe decimal point you entered is not in the " +
			      "correct position!");
			return false;
		} // end if
	} // end if

	if(nCommas == 0)
	{
		// If no commas are present value is a valid US
		// currency.
		return true;
	}
	else
	{
		// Get total number of dollar number(s), removing
		// floating point numbers or cents.
		nNum = nNum - decPos;

		// Determine if dollar sign is in string so to be
		// removed.
		// After determining dollar sign, assign sDollarVal
		// numbers and comma(s)
		if(xTxt.indexOf("$", 0) == 0)
			sDollarVal = xTxt.substr(1, (nNum + nCommas));
		else
			sDollarVal = xTxt.substr(0, (nNum + nCommas));

		// Determine if a zero is the first number or if a
		// comma is the first or last character in the string.
		if(sDollarVal.lastIndexOf("0", 0) == 0 )
		{
			alert("ERROR! \n\nYou cannot start the dollar amount " +
			      "with a zero!");
			return false;
		}
		else if(sDollarVal.lastIndexOf(",", 0) == 0)
		{
			alert("ERROR! \n\nYou cannot start the dollar amount " +
			      "with a comma!");
			return false;
		}
		else if(sDollarVal.indexOf(",", (sDollarVal.length - 1)) ==
		                                (sDollarVal.length - 1))
		{
			alert("ERROR! \n\nYou cannot end the dollar amount with a comma!");
			return false;
		}
		else
		{
			// Initialize bComma indicating a comma has not been
			// occured yet.
			bComma = false;
			for(i = 0; i < sDollarVal.length; i++)
			{
				// Assign character in substring to x.
				x = sDollarVal.substr(i, 1);

				if(parseInt(x) >= 0 || parseInt(x) <= 9)
				{
					// If x is a number add one to the number counter.
					nNumCount = nNumCount + 1;

					// Sense comma(s) are present number counter cannot
					// be more then three before the first or next comma.
					if(nNumCount > 3)
					{
						alert("ERROR! \n\nYou have a mis-placed comma!");
						return false;
					} // end if
				}
				else
				{
					// If the number counter is less then three and
					// the comma indicator is true the comma is either
					// mis-placed or there are not enough values.
					if(nNumCount != 3 && bComma)
					{
						alert("ERROR! \n\nYou have a mis-placed comma!");
						return false;
					} // end if

					// Reset the number counter back to zero.
					nNumCount = 0;

					// Set the comma indicator to true indicating
					// that the first comma has been found and that
					// there now MUST be three numbers after each
					// comma until the loop hits the end.
					bComma = true;
				} // end if
			} // end for

			// Determine if after the loop ended that there
			// was a total of three final numbers after the
			// last comma.
			if(nNumCount != 3 && bComma)
			{
				alert("ERROR! \n\nYou have a mis-placed comma!");
				return false;
			} // end if
		} // end if
	} // end if

	// Return true indicating that the value is a valid
	// currency.
	return true;
}  //end isCurrency


//  Function to trim non-numeric characters from numeric values.
function trimAmount(amt) {
   var newstr = "";
   var chr = "";
   len = amt.length;
   for (i=0;i<len;i++) {
     chr = amt.charAt(i);
     if ( chr == "0" ||
          chr == "1" ||
          chr == "2" ||
          chr == "3" ||
          chr == "4" ||
          chr == "5" ||
          chr == "6" ||
          chr == "7" ||
          chr == "8" ||
          chr == "9" ||
          chr == "." )
        {  newstr = newstr.concat(chr); }
   }
   return newstr;
}  //end trimAmount


//  Function to assure that a valid payment amount is sent to TPG. When
//  completed, invoke onesubmit function.
function checkamount() {
   // Set switch to allow overpayments
   var allowOverpayments = false;

   // Get payment amount from form.
   var pmtAmt = document.forms[0].PmtAmt.value;
   // If it is not a valid currency value, get out and return false.
   if (!isCurrency(pmtAmt)) return false;

   // We have a valid currency value, trim the non-numeric characters
   var trimPmtAmt = trimAmount(pmtAmt);

   // See if there is an AcctBal field.  If so, compare the pmtAmt to the
   // AcctBal value.
   var x=document.getElementsByName("AcctBal");
   var haveAcctBal=false;
   var acctBal;
   for (var i=0;i<x.length;i++) {
      if (x[i].type == 'hidden') {
         haveAcctBal = true;
         var acctBalString = x[i].value;
         acctBal = parseFloat(trimAmount(acctBalString));
         if (acctBalString.charAt(acctBalString.length - 1)=="-")
            acctBal *= -1;
      }
   }
   if (haveAcctBal) {
      if (acctBal < 0) {
         alert ('ERROR!  \n\nYou cannot make payments when you have '+
                'a credit balance!');
         return false;
      }
      if (parseFloat(trimPmtAmt) > acctBal && !allowOverpayments) {
         alert ('ERROR!  \n\nPayment amount cannot be greater than '+
                'account balance!');
         return false;
      }
   }

   // Payment amount is OK.  Set the value to trimmed value and
   // submit form.
   document.forms[0].PmtAmt.value = trimPmtAmt;
   return onesubmit();
}  //end checkamount

//  Function to convert a faculty email address into a link
function sendEmail(emailaddr){
  if (emailaddr == "Do not display")
     {
     document.write();
     }
  else
  if (emailaddr == "*** E-mail address not on file ***" ||
      emailaddr == "*** E-mail address is unavailable by faculty request ***")
     {
     document.write(emailaddr);
     }
  else {
     document.write('<a href="mailto:' + emailaddr + '">' + emailaddr +
     '</a>'); }
     }

// Create a cookie.
// - days parameter is the number of days the cookie is to remain active.
// - if you set the number of days to 0, the cookie is trashed when the
//   user closes the browser.
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}  //end createCookie

// Read for a cookie.
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}  //end readCookie

// Delete a cookie.
function eraseCookie(name) {
	createCookie(name,"",-1);
}  //end eraseCookie

// Global variable for the name of the "Drop and Add Classes" page.
// This should be kept in sync with the StuDropAddText environment
// variable in tsrvweb.ini.

var StuDropAddText='Drop and Add Classes';

// Function to write cookie containing the Registration Cart.
function saveRegCallNumber(callNum, crsNum) {
   var regCallNums = readCookie('sgRegCallNumbers');
   var regEntriesCount;
   var coursePluralText = 'e';

   newCallNum=callNum+'&'+crsNum;
   regEntriesCount=1;

   if (regCallNums != null) {

      var regEntries=regCallNums.split('|');
      regEntriesCount=regEntries.length;

      // Already maximum number of courses in Registration Cart.
      if (regEntriesCount > 9) {
         alert('You already have the maximum of 10 entries in your '+
         'Registration Cart.\n'+
         crsNum+' (Call Number = '+callNum+') has NOT been added to your '+
         'Registration Cart.\n'+
         'You must go to the Registration '+StuDropAddText+' page '+
         'to complete the registration process.');
         return;
      }

      // Check if course is already in Registration Cart.
      for (var i=0;i<regEntriesCount;i++) {
         var regEntry=regEntries[i].split('&');
         var regEntryCallNum=regEntry[0];
         if (regEntriesCount > 1) coursePluralText='es';
         // Course already in Registration Cart.
         if (regEntryCallNum == callNum) {
            alert(crsNum+' (Call Number = '+callNum+') is already in your '+
            'Registration Cart.\n'+
            crsNum+' (Call Number = '+callNum+') has NOT been added to your '+
            'Registration Cart.\n'+
            'You currently have '+ regEntriesCount + ' cours'+coursePluralText+
            ' in your Registration Cart.\n'+
            'You must go to the Registration '+StuDropAddText+' page '+
            'to complete the registration process.');
            return;
         }
      }

      // Add the new registration to the list.
      newCallNum = regCallNums + '|' + newCallNum;
      regEntriesCount++;
   }

   // Save the Registration Cart list.
   createCookie('sgRegCallNumbers', newCallNum, 0);
   var addlEntriesText = 'Your Registration Cart is now full.\n';
   if (regEntriesCount < 10) {
      addlEntriesText =
         'You may add additional courses to your Registration Cart.\n';
   }
   if (regEntriesCount > 1) coursePluralText='es';
   alert(crsNum+' (Call Number = '+callNum+
   ') has been added to your Registration Cart.\n'+
   'You currently have '+ regEntriesCount + ' cours'+coursePluralText+
   ' in your Registration Cart.\n'+addlEntriesText+
   'You must go to the Registration '+StuDropAddText+' page to complete '+
   'the registration process.');
}  //end saveRegCallNumber

// Function to display Registration Cart.
function displayRegCallNumber() {
   var regCallNums = readCookie('sgRegCallNumbers');
   var regEntriesCount;
   var coursePluralText = 'e';

   if (regCallNums == null) {
      alert('Your Registration Cart is empty.');
   } else {
      var regEntries=regCallNums.split('|');
      regEntriesCount=regEntries.length;
      if (regEntriesCount > 1) coursePluralText='es';
      var regCartText = 'You currently have '+ regEntriesCount +
      ' cours'+coursePluralText+' in your Registration Cart.\n\n';
      if (regEntriesCount == 10)
      regCartText += 'Your Registration Cart is now full.\n\n';

      // Check if course is already in Registration Cart.
      for (var i=0;i<regEntriesCount;i++) {
         var regEntry=regEntries[i].split('&');
         var regEntryCallNum=regEntry[0];
         var regEntryCrsID=regEntry[1];
         regCartText += '     '+regEntryCrsID+
                        ' (Call Number = '+regEntryCallNum+')\n';
      }
//    var isDropAddClassesPage =
//      document.getElementById("tserve_trans_config").value == "rstureg.cfg";
      var x=document.getElementsByName("tserve_trans_config");
      for (var i=0;i<x.length;i++) {
         if (x[i].type == 'hidden') {
            var isDropAddClassesPage = x[i].value == "rstureg.cfg";
            break;
         }
      }
      if (!isDropAddClassesPage) {
      regCartText += '\nYou must go to the Registration '+StuDropAddText+
      ' page to complete the registration process.';
      }
      alert(regCartText);
   }
}  //end displayRegCallNumber

// Function to fill in the Registration Cart call numbers on the
// Drop and Add Classes page.
function putRegCallNums() {
   var regCallNums = readCookie('sgRegCallNumbers');
   if (regCallNums == null) {
      document.getElementById("regcartlinks").style.display="none"
      return;
   }
   var regEntries=regCallNums.split('|');
   for (var i=0;i<regEntries.length;i++) {
      var regEntry=regEntries[i].split('&');
      var callNum=regEntry[0];
      var x=document.getElementsByName("Callnum");
      for (var j=0;j<x.length;j++) {
         if (x[j].type == 'text' && x[j].value == '') {
            x[j].value=callNum;
            break;
         }
      }
   }
}  //end putRegCallNums

// Empty the Registration Cart contents and blank out the
// course call numbers displayed on the page.
function emptyRegCart() {
   eraseCookie('sgRegCallNumbers');
   var x=document.getElementsByName("Callnum");
   for (var j=0;j<x.length;j++) {
      if (x[j].type == 'text' && x[j].value != '') {
         x[j].value='';
      }
   }
   alert('Cart is empty.');
} //end emptyRegCart

// Function to disable null calls to the Registration Cart function.
// This can happen when a course has multiple meeting time entries.  Each
// time entry comes over on its own ddo with no course section number or
// call number.  This function will change the CSS class of these multiple
// entries so that they do not display.
function hideDupCartEntries() {
   for (var j=0;j<document.links.length;j++) {
      var regevent = document.links[j].onclick;
      if (regevent != null) {
         regevent = regevent.toString();
         regevent = regevent.replace(/ "/g,"'");
         regevent = regevent.replace(/"/g,"'");
         if (regevent.indexOf("saveRegCallNumber('','')") != -1) {
            document.links[j].className = "regcartdisabledlink";
         }
      }
   }
}  //end hideDupCartEntries
