//  javascript file

var sDivOn = "form1";
var sDivTurnOn = "form1";
var oldid;

// turns divs on and off
function ToggleDiv(psID, psOffID){
	var psDisplay;
	var poElement = document.getElementById(psID);	
	var psDisplay2;
	var poElement2 = document.getElementById(psOffID);

	psDisplay2 = (poElement.style.display == "block" || poElement.style.display == "normal") ? "none" : "none";		
	poElement2.style.display = psDisplay2

	psDisplay = (poElement.style.display == "block" || poElement.style.display == "normal") ? "none" : "block";				
	poElement.style.display = psDisplay
		
	sDivOn = psID;		
}	

function ToggleDiv2(psID){
	var psDisplay;
	var poElement = document.getElementById(psID);	

	psDisplay = (poElement.style.display == "block" || poElement.style.display == "normal") ? "none" : "block";				
	poElement.style.display = psDisplay;	
}	

function ResetDropDown(id) 
{ 
	var dropdown = document.getElementById(id); 
    dropdown.item(0).selected="true"; 
}

function DoDelete(sDeleteName, sUrl, cUrl)
{
	if (confirm("Are you sure you want to delete " + sDeleteName + " from the database?")) 
	{
		window.location.href=sUrl;
		return true;
	}
	
	window.location.href=cUrl;
	return false;
}

var xmlHttpDate;

function CreateXMLHttpRequest()
{
	var xmlHttp;
	if (window.ActiveXObject){
		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	else if (window.XMLHttpRequest){
		xmlHttp = new XMLHttpRequest();
	}
	return xmlHttp;
}

function StartXMLHttpRequestGET(sPage, sFunc)
{	
	var timeStamp;
	timeStamp = new Date().getTime();
	sPage += "& timeStamp=" + timeStamp; // adding timestamp to prevent caching issues with urls
	xmlHttpDate = CreateXMLHttpRequest();
	xmlHttpDate.onreadystatechange = sFunc;
	xmlHttpDate.open("GET", sPage, true);
	xmlHttpDate.send(null);
}

function StartXMLHttpRequestPOST(sPage, sCallbackFunction, sPostParams)
{
	// sPage = URL for page to call	
	CreateXMLHttpRequest();
	xmlHttpDate.onreadystatechange = sCallbackFunction;
	xmlHttpDate.open("POST", sPage, true);
	xmlHttpDate.send(sPostParams);
}

function RemoveSpaces(strText) 
{
	strText = strText.replace(/ /g, "");
	return strText;
}

function SQLSafe(strText) 
{
	strText = strText.replace(/'/g, "''");
	return strText;
}

 function Go(sLocation)
 {
	if (sLocation) window.open(sLocation,this.target, 'width=400,height=300,left=300,top=300,scrollbars=yes');
 }
 
function Go2(sLocation)
{
	if (sLocation) location.href = sLocation;
}

function ErrorHandling(sErrorCode, sPageName, sPageAsp)
{
	if (sErrorCode == 1)
	{
	 alert("You cannot delete this " + sPageName + " because it is being referenced in the database.");
	 window.location.href = sPageAsp;
	}
	else if (sErrorCode == 2)
	{
	 alert("This " + sPageName + " already exists."); 
	 window.location.href = sPageAsp;
	}
	else if (sErrorCode == 3)
	{
	 alert("You can't uncheck the Active Season. To change the Active Season you must check the new season you want to be active."); 
	 window.location.href = sPageAsp;
	}	
}

// A utility function that returns true if a string contains only whitespace characters
function Isblank(s)
{
	for (var i = 0; i < s.length; i++) {
		var c = s.charAt(i);
		if ((c != ' ') && (c != '\n') && (c != '')){return false};
	}
	return true;
}

//Validates CheckBoxes so at least one is checked
function IsChecked(form,checkBoxArray,myMin)
{
	var _countChecked = 0;
	/* iterate through all the elements in the checkbox array */
	for(i = 0; i < document[form][checkBoxArray].length; i++)
	{
		/* and check to see if each is checked */
		if(document[form][checkBoxArray][i].checked==true)
			/* if it is, increment a counter */
			{ _countChecked++; }
	}
	if(_countChecked < myMin)
	{ 
		return true;
	}
} 
 
// This is a function that performs form verification. It is invoked from the onSubmit event handler. 
// The handler should return whatever value this function returns
function Verify(f)
{
	var msg;
	var empty_fields = "";
	var errors = "";
	var focusNumber = -1;
	var password1 = "";
	var password2 = "";
  
  // Loop through the elements of the form, looking for all Text and Textarea elements that don't
  // have an "optional" property defined. Then check for fields that are empty and make a list of them.
  // Also, if any of these elements have a "min" or "max" property defined, verify that they are numbers
  // and are in the right range. If the element has a "numeric" property defined, verify that it is a number
  // but don't check it's range. Put together error messages for fields that are wrong.
  
  for(var i = 0; i < f.length; i++) {
   var e = f.elements[i];   
   if (((e.type == "text") || (e.type == "file") || e.type == "password" || (e.type == "checkbox") || (e.type == "textarea") || (e.type == "select-one")) && (!e.optional && e.name.search("Optional") == -1 || e.value > "")) {
    //First check if the field is empty 
    if ((e.value == null) || (e.value == "") || Isblank(e.value)) {
     empty_fields += "\n          " + e.name;
		if(focusNumber == -1){
			focusNumber = i;
		}			
     continue;
    }      

	if (e.type == "password" && e.name == "password1")
	{		
		password1 = e.value; 
		
		if(e.value.length < 5)
		{
			errors += "- Password must to be at least 5 characters long.\n";
			if(focusNumber == -1) {
				focusNumber = i;
			}		
		}
	}
	
	if (e.type == "password" && e.name == "password2")
	{
		password2 = e.value;
		
		if (password1 != password2)
		{
			errors += "- Password-Verify doesn't match the Password field.\n";
			if(focusNumber == -1) {
				focusNumber = i;
			}
		}
	}	    
	
	if (e.name == "EmailAddress")
	{
											
		var emailReg = ".+@.+\\.[a-z]+";
		var regex = new RegExp(emailReg);
		if(!regex.test(e.value))
		{
			errors += "- Your email address is invalid.\n";
			if(focusNumber == -1) {
				focusNumber = i;		
			}			
		}
	}		
    
    //Now check for fields that are suppossed to be numeric
    if (e.numeric || (e.min != null) || (e.max != null) || (e.name.search("Numeric") != -1)) {
     var v = parseFloat(e.value);
     var re_numeric = /^\d+$/;
     
     if (isNaN(v) || !re_numeric.exec(e.value) ||
      ((e.min != null) && (v < e.min)) ||
      ((e.max != null) && (v > e.max))) {
      errors += "- The field " + e.name + " must be a number";
      if (e.min != null)
       errors += " that is greater than " + e.min;
      if (e.max != null && e.min != null)
       errors +=" and less than " + e.max;
      else if (e.max != null)
       errors +=" that is less than " + e.max;
      errors += ".\n";
		if(focusNumber == -1){
			focusNumber = i;
		}
     }
    }
    
    //Now Check to make sure all the date fields are correct
    if (e.date || e.name.search("Date") != -1)
    { 
		var re_date = /^(\d{1,2})\/(\d{1,2})\/(\d{4})+/;
		var firstSlash = e.value.indexOf("/");
		var secondSlash = e.value.lastIndexOf("/");
		var month = Number(e.value.substring(0,firstSlash));
		var day = Number(e.value.substring(firstSlash + 1,secondSlash));
		var year = Number(e.value.substring(secondSlash + 1,secondSlash + 7));	
		if ((!re_date.exec(e.value)) || (day<0) || (day>31) || (month<0) || (month>12) || (year<0) || (year>9999))
		{
			errors += "- The field " + e.name + " must be a valid date (ex: 1/1/2007)\n";	
			if(focusNumber == -1)
			{
				focusNumber = i;
			}
		}
		
		// months with 30 days 
		if (month==4 || month==6 || month==9 || month==11) 
		{ 
		    if (day>30)
		    {
		    	errors += "- The field " + e.name + " must have a valid day\n"; 
				if(focusNumber == -1)
				{
					focusNumber = i;
				}
			}
		} 
		// february, leap year 
		if (month==2) 
		{   
		    if (day>29) 
		    {
				errors += "- The field " + e.name + " must have a valid day\n"; 
				if(focusNumber == -1)
				{
					focusNumber = i;
				}
			}
		    if ((day==29) && ((Number(year) % 4) != 0)) 
		    {
				errors += "- The field " + e.name + " must have a valid day\n"; 
				if(focusNumber == -1)
				{
					focusNumber = i;
				}
			}
		} 
		
		if(isNaN(year) || isNaN(month) || isNaN(day))	
		{
				errors += "- The field " + e.name + " must have a valid date\n"; 
				if(focusNumber == -1)
				{
					focusNumber = i;
				}		
		}		
	}
   
   //Now check to make sure the money fields are correct
   if (e.money || (e.name.search("Money") != -1))
   {
	var money = e.value;
	
		if (isNaN(money))
		{
			errors += "- The field " + e.name + " must be a valid money value.\n";
			if(focusNumber == -1) {
				focusNumber = i;
			}
		}
   }
   
   }
  }
  // Now if there were any errors, display the messages, and return false to prevent the form
  // from being submitted. Otherwise, return true.
  if (!empty_fields && !errors) return true;
  
  msg  = "____________________________________________________ _\n\n";
  msg += "The form was not submitted because of the following error(s).\n";
  msg += "Please correct these error(s) and re-submit.\n";
  msg += "____________________________________________________ _\n\n";
  
  if (empty_fields) {
   msg += "- The following required field(s) are empty:"
     + empty_fields + "\n";
   if (errors) msg += "\n";
  }
  msg += errors;
  alert(msg);
  f.elements[focusNumber].focus();
  return false;
 } 
 

function show_calendar(str_target, str_datetime) {
	var arr_months = ["January", "February", "March", "April", "May", "June",
		"July", "August", "September", "October", "November", "December"];
	var week_days = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"];
	var n_weekstart = 1; // day week starts from (normally 0 or 1)

	var dt_datetime = (str_datetime == null || str_datetime =="" ?  new Date() : str2dt(str_datetime)); 
	var dt_prev_month = new Date(dt_datetime);
	dt_prev_month.setMonth(dt_datetime.getMonth()-1);
	var dt_next_month = new Date(dt_datetime);
	dt_next_month.setMonth(dt_datetime.getMonth()+1);
	var dt_firstday = new Date(dt_datetime);
	dt_firstday.setDate(1);
	dt_firstday.setDate(1-(7+dt_firstday.getDay()-n_weekstart)%7);
	var dt_lastday = new Date(dt_next_month);
	dt_lastday.setDate(0);
	
	// html generation (feel free to tune it for your particular application)
	// print calendar header
	var str_buffer = new String (
		"<html>\n"+
		"<head>\n"+
		"	<title>Calendar</title>\n"+
		"</head>\n"+
		"<body bgcolor=\"White\">\n"+
		"<table class=\"clsOTable\" cellspacing=\"0\" border=\"0\" width=\"100%\">\n"+
		"<tr><td bgcolor=\"#3329B4\">\n"+
		"<table cellspacing=\"1\" cellpadding=\"3\" border=\"0\" width=\"100%\">\n"+
		"<tr>\n	<td bgcolor=\"#3329B4\"><a href=\"javascript:window.opener.show_calendar('"+
		str_target+"', '"+ dt2dtstr(dt_prev_month)+"');\">"+
		"<img src=\"images/prev.gif\" width=\"16\" height=\"16\" border=\"0\""+
		" alt=\"previous month\"></a></td>\n"+
		"	<td bgcolor=\"#3329B4\" colspan=\"5\">"+
		"<font color=\"white\" face=\"tahoma, verdana\" size=\"2\">"
		+arr_months[dt_datetime.getMonth()]+" "+dt_datetime.getFullYear()+"</font></td>\n"+
		"	<td bgcolor=\"#3329B4\" align=\"right\"><a href=\"javascript:window.opener.show_calendar('"
		+str_target+"', '"+dt2dtstr(dt_next_month)+"');\">"+
		"<img src=\"images/next.gif\" width=\"16\" height=\"16\" border=\"0\""+
		" alt=\"next month\"></a></td>\n</tr>\n"
	);

	var dt_current_day = new Date(dt_firstday);
	// print weekdays titles
	str_buffer += "<tr>\n";
	for (var n=0; n<7; n++)
		str_buffer += "	<td bgcolor=\"#667AF1\">"+
		"<font color=\"white\" face=\"tahoma, verdana\" size=\"2\">"+
		week_days[(n_weekstart+n)%7]+"</font></td>\n";
	// print calendar table
	str_buffer += "</tr>\n";
	while (dt_current_day.getMonth() == dt_datetime.getMonth() ||
		dt_current_day.getMonth() == dt_firstday.getMonth()) {
		// print row heder
		str_buffer += "<tr>\n";
		for (var n_current_wday=0; n_current_wday<7; n_current_wday++) {
				if (dt_current_day.getDate() == dt_datetime.getDate() &&
					dt_current_day.getMonth() == dt_datetime.getMonth())
					// print current date
					str_buffer += "	<td bgcolor=\"#A0ADFB\" align=\"right\">";
				else if (dt_current_day.getDay() == 0 || dt_current_day.getDay() == 6)
					// weekend days
					str_buffer += "	<td bgcolor=\"#FFFFFF\" align=\"right\">";
				else
					// print working days of current month
					str_buffer += "	<td bgcolor=\"white\" align=\"right\">";

				if (dt_current_day.getMonth() == dt_datetime.getMonth())
					// print days of current month
					str_buffer += "<a href=\"javascript:window.opener."+str_target+
					".value='"+dt2dtstr(dt_current_day)+"'; window.close();\">"+
					"<font color=\"black\" face=\"tahoma, verdana\" size=\"2\">";
				else 
					// print days of other months
					str_buffer += "<a href=\"javascript:window.opener."+str_target+
					".value='"+dt2dtstr(dt_current_day)+"'; window.close();\">"+
					"<font color=\"gray\" face=\"tahoma, verdana\" size=\"2\">";
				str_buffer += dt_current_day.getDate()+"</font></a></td>\n";
				dt_current_day.setDate(dt_current_day.getDate()+1);
		}
		// print row footer
		str_buffer += "</tr>\n";
	}


	var vWinCal = window.open("", "Calendar", 
		"width=200,height=220,status=no,resizable=yes,top=200,left=500");
	vWinCal.opener = self;
	var calc_doc = vWinCal.document;
	calc_doc.write (str_buffer);
	calc_doc.close();
}
// datetime parsing and formatting routimes. modify them if you wish other datetime format
function str2dt (str_datetime) {
	var re_date = /^(\d+)\/(\d+)\/(\d+)+/;
	if (!re_date.exec(str_datetime))
		return alert("Invalid Datetime format: "+ str_datetime);

	return (new Date (RegExp.$3, RegExp.$1-1, RegExp.$2, RegExp.$4, RegExp.$5, RegExp.$6));
}
function dt2dtstr (dt_datetime) {
	return (new String (
			(dt_datetime.getMonth()+1)+"/"+dt_datetime.getDate()+"/"+dt_datetime.getFullYear()+" "));
}


 
// This is a function that performs form verification. It is invoked from the onSubmit event handler. 
// The handler should return whatever value this function returns
function Verify(f)
{
	var msg;
	var empty_fields = "";
	var errors = "";
	var focusNumber = -1;
	var password1 = "";
	var password2 = "";
  
  // Loop through the elements of the form, looking for all Text and Textarea elements that don't
  // have an "optional" property defined. Then check for fields that are empty and make a list of them.
  // Also, if any of these elements have a "min" or "max" property defined, verify that they are numbers
  // and are in the right range. If the element has a "numeric" property defined, verify that it is a number
  // but don't check it's range. Put together error messages for fields that are wrong.
  
  for(var i = 0; i < f.length; i++) {
   var e = f.elements[i];   
   if (((e.type == "text") || (e.type == "file") || e.type == "password" || (e.type == "checkbox") || (e.type == "textarea") || (e.type == "select-one")) && (!e.optional && e.name.search("Optional") == -1 || e.value > "")) {
    //First check if the field is empty 
    if ((e.value == null) || (e.value == "") || Isblank(e.value)) {
     empty_fields += "\n          " + e.name;
		if(focusNumber == -1){
			focusNumber = i;
		}			
     continue;
    }      

	if (e.type == "password" && e.name == "password1")
	{		
		password1 = e.value; 
		
		if(e.value.length < 5)
		{
			errors += "- Password must to be at least 5 characters long.\n";
			if(focusNumber == -1) {
				focusNumber = i;
			}		
		}
	}
	
	if (e.type == "password" && e.name == "password2")
	{
		password2 = e.value;
		
		if (password1 != password2)
		{
			errors += "- Password-Verify doesn't match the Password field.\n";
			if(focusNumber == -1) {
				focusNumber = i;
			}
		}
	}	    
	
	if (e.name == "EmailAddress")
	{
											
		var emailReg = ".+@.+\\.[a-z]+";
		var regex = new RegExp(emailReg);
		if(!regex.test(e.value))
		{
			errors += "- Your email address is invalid.\n";
			if(focusNumber == -1) {
				focusNumber = i;		
			}			
		}
	}		
    
    //Now check for fields that are suppossed to be numeric
    if (e.numeric || (e.min != null) || (e.max != null) || (e.name.search("Numeric") != -1)) {
     var v = parseFloat(e.value);
     var re_numeric = /^\d+$/;
     
     if (isNaN(v) || !re_numeric.exec(e.value) ||
      ((e.min != null) && (v < e.min)) ||
      ((e.max != null) && (v > e.max))) {
      errors += "- The field " + e.name + " must be a number";
      if (e.min != null)
       errors += " that is greater than " + e.min;
      if (e.max != null && e.min != null)
       errors +=" and less than " + e.max;
      else if (e.max != null)
       errors +=" that is less than " + e.max;
      errors += ".\n";
		if(focusNumber == -1){
			focusNumber = i;
		}
     }
    }
    
    //Now Check to make sure all the date fields are correct
    if (e.date || e.name.search("Date") != -1)
    { 
		var re_date = /^(\d{1,2})\/(\d{1,2})\/(\d{4})+/;
		var firstSlash = e.value.indexOf("/");
		var secondSlash = e.value.lastIndexOf("/");
		var month = Number(e.value.substring(0,firstSlash));
		var day = Number(e.value.substring(firstSlash + 1,secondSlash));
		var year = Number(e.value.substring(secondSlash + 1,secondSlash + 7));	
		if ((!re_date.exec(e.value)) || (day<0) || (day>31) || (month<0) || (month>12) || (year<0) || (year>9999))
		{
			errors += "- The field " + e.name + " must be a valid date (ex: 1/1/2007)\n";	
			if(focusNumber == -1)
			{
				focusNumber = i;
			}
		}
		
		// months with 30 days 
		if (month==4 || month==6 || month==9 || month==11) 
		{ 
		    if (day>30)
		    {
		    	errors += "- The field " + e.name + " must have a valid day\n"; 
				if(focusNumber == -1)
				{
					focusNumber = i;
				}
			}
		} 
		// february, leap year 
		if (month==2) 
		{   
		    if (day>29) 
		    {
				errors += "- The field " + e.name + " must have a valid day\n"; 
				if(focusNumber == -1)
				{
					focusNumber = i;
				}
			}
		    if ((day==29) && ((Number(year) % 4) != 0)) 
		    {
				errors += "- The field " + e.name + " must have a valid day\n"; 
				if(focusNumber == -1)
				{
					focusNumber = i;
				}
			}
		} 
		
		if(isNaN(year) || isNaN(month) || isNaN(day))	
		{
				errors += "- The field " + e.name + " must have a valid date\n"; 
				if(focusNumber == -1)
				{
					focusNumber = i;
				}		
		}		
	}
   
   //Now check to make sure the money fields are correct
   if (e.money || (e.name.search("Money") != -1))
   {
	var money = e.value;
	
		if (isNaN(money))
		{
			errors += "- The field " + e.name + " must be a valid money value.\n";
			if(focusNumber == -1) {
				focusNumber = i;
			}
		}
   }
   
   }
  }
  // Now if there were any errors, display the messages, and return false to prevent the form
  // from being submitted. Otherwise, return true.
  if (!empty_fields && !errors) return true;
  
  msg  = "____________________________________________________ _\n\n";
  msg += "The form was not submitted because of the following error(s).\n";
  msg += "Please correct these error(s) and re-submit.\n";
  msg += "____________________________________________________ _\n\n";
  
  if (empty_fields) {
   msg += "- The following required field(s) are empty:"
     + empty_fields + "\n";
   if (errors) msg += "\n";
  }
  msg += errors;
  alert(msg);
  f.elements[focusNumber].focus();
  return false;
 } 