// Toggles whether recurrence is on or off.
// Note: HTML formatted so inputs/labels are generally first on a line.
function SetRecurrence(ysn, eventBegins, eventEnds) {
	if (ysn == 1) {
		document.getElementById('tdWithLeftHorzBorder').style.borderColor = '#c0c0c0';
		document.getElementById('recur').innerHTML =
		'<input type="radio" id="rtcDaily" name="recurrenceType" style="margin-left: 0px;" onClick="SetRecurrenceType(0)" value="0" checked> &nbsp; <label for="rtcDaily" style="float: none; display: inline;">Daily</label><br>'+
		'<input type="radio" id="rtcWeekly" name="recurrenceType" style="margin-left: 0px;"onClick="SetRecurrenceType(1)" value="1"> &nbsp; <label for="rtcWeekly" style="float: none; display: inline;">Weekly</label><br>'+
		'<input type="radio" id="rtcMonthly" name="recurrenceType" style="margin-left: 0px;" onClick="SetRecurrenceType(2)" value="2"> &nbsp; <label for="rtcMonthly" style="float: none; display: inline;">Monthly</label><br>'+
		'<input type="radio" id="rtcYearly" name="recurrenceType" style="margin-left: 0px;" onClick="SetRecurrenceType(3)" value="3"> &nbsp; <label for="rtcYearly" style="float: none; display: inline;">Yearly</label><br><br>';
		document.getElementById('recurRange').innerHTML =
		'<table style="width: 100%; vertical-align: top; border-style: solid; border-left-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-top-width: 1px; border-color: #c0c0c0; padding-left: 0.1cm"><tr><td>Range of recurrences:<br><br></td></tr><tr><td valign="top">'+
		'<label for="dtiBeginningDate" style="float: none; display: inline;">Start:&nbsp;</label>'+
		'<input type="text" onFocus="this.select()" id="dtiBeginningDate" name="dtiBeginningDate" size="10" maxlength="14" value=""><span class="dateexample" style="position: static; margin-left: 6px;">[mm/dd/yyyy]</span></td><td width="280">'+
		'<input type="radio" name="endByDate" id="ebdBy" value="1" checked>&nbsp;&nbsp;'+
		'<label for="dtiEndingDate" onclick="this.form.endByDate[0].checked = true;" style="float: none; display: inline;">End by:</label>&nbsp;&nbsp;&nbsp;&nbsp;'+
		'<input type="text" onFocus="this.select()" id="dtiEndingDate" name="dtiEndingDate" size="10" maxlength="15" value="' + eventEnds + '"><span class="dateexample" style="position: static; margin-left: 6px;">[mm/dd/yyyy]</span><br>'+
		'<input type="radio" name="endByDate" id="ebdAfter" value="0">&nbsp;&nbsp;'+
		'<label for="endingRecurrence" onclick="this.form.endByDate[1].checked = true;" style="float: none; display: inline;">End after:&nbsp;</label>'+
		'<input type="text" onFocus="this.select()" id="endingRecurrence" name="endingRecurrence" size="2" maxlength="2" value="1"> recurrences<br></td></tr><tr><td colspan="2"><br>'+
		'<label for="eventLength" style="float: none; display: inline;">Length of each event in recurrence:&nbsp;</label><input type="text" onFocus="this.select()" id="eventLength" name="eventLength" size="2" maxlength="2" value="1">&nbsp;day(s)</td></tr></table>';
		SetRecurrenceType(0); // Daily.
		document.getElementById('recurType').style.display = 'block';
	}
	else {
		document.getElementById('tdWithLeftHorzBorder').style.borderColor = 'transparent';
		document.getElementById('recur').innerHTML =
		'<input type="hidden" name="eventDateType" value="4">'+
		'<label style="float: left; display: block; margin-top: 4px; width: 90px; margin-bottom: 2px; *margin-bottom: 0px;" for="dtiBeginningDate">Event&nbsp;Begins:</label>'+
		'<input type="text" onFocus="this.select()" id="dtiBeginningDate" name="dtiBeginningDate" size="10" maxlength="14" style="margin: 0px; margin-bottom: 2px; *margin-bottom: 0px;" value="' + eventBegins + '"><span class="dateexample">[mm/dd/yyyy]</span><br>'+
		'<label style="float: left; display: block; margin-top: 4px; width: 90px; margin-bottom: 2px; *margin-bottom: 0px;" for="dtiEndingDate">Event&nbsp;Ends:</label>'+
		'<input type="text" onFocus="this.select()" id="dtiEndingDate" name="dtiEndingDate" size="10" maxlength="15" style="margin: 0px; margin-bottom: 2px; *margin-bottom: 0px;" value="' + eventEnds + '"><span class="dateexample">[mm/dd/yyyy]</span>';
		document.getElementById('recurType').innerHTML ='';
		document.getElementById('recurRange').innerHTML ='';
		document.getElementById('recurType').style.display = 'none';
	}
}
// Sets recurrence type (use only if recurrence is on).
// Note: HTML formatted so inputs/labels are generally first on a line.
function SetRecurrenceType(recurType) {
	//alert(recurType);
	switch (recurType) {
		case 1:
			document.getElementById('recurType').innerHTML =
			'<input type="hidden" name="eventDateType" value="1">'+
			'<label for="weeklyGap" style="float: none; display: inline;">Recur every</label><input type="text" id="weeklyGap" name="weeklyGap" onfocus="this.select();" size="4" maxlength="4" value="1">&nbsp;&nbsp;&nbsp; week(s) on:<br><br>'+
			'<input type="checkbox" id="sun" name="sun" value="ON">&nbsp;<label for="sun" style="float: none; display: inline;">&nbsp; Sunday </label>&nbsp;&nbsp;&nbsp;'+
			'<input type="checkbox" id="mon" name="mon" value="ON">&nbsp;<label for="mon" style="float: none; display: inline;">&nbsp; Monday </label>&nbsp;'+
			'<input type="checkbox" id="tue" name="tue" value="ON">&nbsp;<label for="tue" style="float: none; display: inline;">&nbsp; Tuesday </label>&nbsp;'+
			'<input type="checkbox" id="wed" name="wed" value="ON">&nbsp;<label for="wed" style="float: none; display: inline;">&nbsp; Wednesday </label>&nbsp;<br>'+
			'<input type="checkbox" id="thu" name="thu" value="ON">&nbsp;<label for="thu" style="float: none; display: inline;">&nbsp; Thursday </label>&nbsp;'+
			'<input type="checkbox" id="fri" name="fri" value="ON">&nbsp;<label for="fri" style="float: none; display: inline;">&nbsp; Friday </label>&nbsp;&nbsp;&nbsp;'+
			'<input type="checkbox" id="sat" name="sat" value="ON">&nbsp;<label for="sat" style="float: none; display: inline;">&nbsp; Saturday </label>&nbsp;';
			break;
		case 2:
			document.getElementById('recurType').innerHTML =
			'<input type="hidden" name="eventDateType" value="2">'+
			'<input type="radio" style="margin-left: 0px;" name="monthlyOption" value="1" checked>&nbsp;&nbsp; '+
			'<label for="dayOfMonth" onclick="this.form.monthlyOption[0].checked = true;" style="display: inline; float: none;">Day</label>'+
			'<input type="text" name="dayOfMonth" onfocus="this.select();" id="dayOfMonth" size="2" maxlength="2">&nbsp;&nbsp;&nbsp; of every'+
			'<input type="text" name="monthlyGap" size="2" onfocus="this.select();" maxlength="2" value="1">&nbsp;&nbsp; month(s)<br><br>'+
			'<input type="radio" style="margin-left: 0px;" name="monthlyOption" value="0">&nbsp;&nbsp; '+
			'<label for="weekOfMonth" onclick="this.form.monthlyOption[1].checked = true;" style="display: inline; float: none;">The</label>'+
			'<select size="1" name="weekOfMonth" id="weekOfMonth"><option value="1">First</option><option value="2">Second</option><option value="3">Third</option><option value="4">Fourth</option><option value="5">Last</option></select>&nbsp;'+
			'<select size="1" name="dayOfweekInMonth"><option value="1">Sunday</option><option value="2">Monday</option><option value="3">Tuesday</option><option value="4">Wednesday</option><option value="5">Thursday</option><option value="6">Friday</option><option value="7">Saturday</option></select>&nbsp;&nbsp;&nbsp; of every'+
			'<input type="text" name="monthlyGap1" size="2" maxlength="2" value="1">&nbsp;&nbsp; month(s)';
			break;
		case 3:
			document.getElementById('recurType').innerHTML =
			'<input type="hidden" name="eventDateType" value="3">'+
			'<input type="radio" style="margin-left: 0px;" name="yearlyOption" value="1" checked>&nbsp;&nbsp; '+
			'<label for="monthOfYear" onclick="this.form.yearlyOption[0].checked = true;" style="display: inline; float: none;">Every</label>'+
			'<select size="1" name="monthOfYear" id="monthOfYear"><option value="1">January</option><option value="2">February</option><option value="3">March</option><option value="4">April</option><option value="5">May</option><option value="6">June</option><option value="7">July</option><option value="8">August</option><option value="9">September</option><option value="10">October</option><option value="11">November</option><option value="12">December</option></select>&nbsp;'+
			'<input type="text" name="dayOfMonthInYear" size="2" maxlength="2"><br><br>'+
			'<input type="radio" style="margin-left: 0px;" name="yearlyOption" value="0">&nbsp;&nbsp; '+
			'<label for="weekOfMonthInYear" onclick="this.form.yearlyOption[1].checked = true;" style="display: inline; float: none;">The</label>'+
			'<select size="1" name="weekOfMonthInYear" id="weekOfMonthInYear"><option value="1">First</option><option value="2">Second</option><option value="3">Third</option><option value="4">Fourth</option><option value="5">Last</option></select>&nbsp;'+
			'<select size="1" name="dayOfWeekInMonthInYear"><option value="1">Sunday</option><option value="2">Monday</option><option value="3">Tuesday</option><option value="4">Wednesday</option><option value="5">Thursday</option><option value="6">Friday</option><option value="7">Saturday</option></select>&nbsp;&nbsp;&nbsp; of'+
			'<select size="1" name="monthOfYear1"><option value="1">January</option><option value="2">February</option><option value="3">March</option><option value="4">April</option><option value="5">May</option><option value="6">June</option><option value="7">July</option><option value="8">August</option><option value="9">September</option><option value="10">October</option><option value="11">November</option><option value="12">December</option></select>';
			break;
		default:
			document.getElementById('recurType').innerHTML =
			'<input type="hidden" name="eventDateType" value="0">'+
			'<input type="radio" style="margin-left: 0px;" name="dailyOption" id="dailyOption1" value="0" checked><span>&nbsp;&nbsp; '+
			'<label for="dailyGap" onclick="this.form.dailyOption1.checked = true;" style="display: inline; float: none;">Every</label></span>'+
			'<input type="text" name="dailyGap" id="dailyGap" size="5" maxlength="5" onfocus="this.select();" value="1"><span>&nbsp;&nbsp;&nbsp; day(s)</span><br><br>'+
			'<input type="radio" style="margin-left: 0px;" name="dailyOption" id="dailyOption2" value="1">&nbsp;&nbsp; '+
			'<label for="dailyOption2" style="display: inline; float: none;">Every day</label>';
	}
}
function SQLSafeDate() {
    var dtiD = document.frmSetCalendar.dtiDate;

    if (dtiD.value.substring(0, 7).toLowerCase() == '[today:')
        dtiD.value = "";

    if (dtiD.value != "") {
        var d = new Date(dtiD.value);
        if (d.getFullYear() > 1752 && d.getFullYear() < 9999)
            return true;

        alert("Please enter a valid date");
        return false;
    }
    else
        return true;
}
function DisplayEvent(id) {
	location.replace('CurrentEvents.aspx?EID=' + id);
}
function TrimString(sInString) {
	return sInString.replace( /^\s+/g, "" ).replace( /\s+$/g, "" );
}
function isDate(varDateToCheck) {
    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
    var matchArray = varDateToCheck.match(datePat);
    if (matchArray == null)
        return false;

    //Parse date into variables
    month = matchArray[1];
    day = matchArray[3];
    year = matchArray[4];

    if (month < 1 || month > 12 || day < 1 || day > 31)
        return false;
    if (day == 31 && (month == 4 || month == 6 || month == 9 || month == 11))
        return false;
    if (month == 2) { //Check for february 29th
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day > 29 || (day == 29 && !isleap))
            return false;
    }
    return true;
}
function toSQLSafe(formvar){
	return ((String(formvar).replace(/'/gi,"&#39")).replace(/"/gi,"&#34")).replace(/\n/gi,"/n/f");
}
function dateDiff(dtiDateEntered, dtiDateToday) {
	  var date1 = new Date();
	  var date2 = new Date();
	  var diff  = new Date();
	  var date1temp = new Date(dtiDateEntered);
	  var date2temp = new Date(dtiDateToday);
	  date1.setTime(date1temp.getTime());
	  date2.setTime(date2temp.getTime());

	  // sets difference date to difference of first date and second date
	  diff.setTime(date1.getTime() - date2.getTime());
	  timediff = diff.getTime();
	  days = Math.floor(timediff / 86400000); // 1000 * 60 * 60 * 24
	  return days;
}
function checkNum(inputValue) {
	if (isNaN(inputValue))
		alert("All date, gap or recurrence related values should be integer number and cannot be empty.");
	else if (inputValue<=0)
		alert("All date, gap or recurrence related values should be larger than 0.");
	else
		return true;

	return false;
}
function checkRecurrence(timePeriod, gapLength) {
	if ((document.frmSettings.endByDate[0].checked && timePeriod / gapLength > 52) || (document.frmSettings.endByDate[1].checked && document.frmSettings.endingRecurrence.value > 52))
		alert("Only 52 recurring events can be setup at one time.");
	else
		return true;

	return false;
}
function checkEnding() {
	if (document.frmSettings.endByDate[0].checked) {
		if (document.frmSettings.dtiEndingDate.value=='') {
			alert("Please enter when the Event Ends.");
			document.frmSettings.dtiEndingDate.focus();
			return false;
		}
		if (document.frmSettings.dtiEndingDate.value!='' && isDate(document.frmSettings.dtiEndingDate.value)==false) {
			alert("Please enter a valid date for Event Ends field (mm/dd/yyyy).");
			document.frmSettings.dtiEndingDate.focus();
			return false;
		}
		else if (document.frmSettings.dtiEndingDate.value!='' && dateDiff(document.frmSettings.dtiBeginningDate.value,document.frmSettings.dtiEndingDate.value) > 0) {
			alert("The Event Beginning and Ending dates you entered are chronologically incorrect.");
			document.frmSettings.dtiEndingDate.focus();
			return false;
		}
	}
	else {
		if (document.frmSettings.endingRecurrence.value=='') {
			alert("Please enter the number of recurrences for your event.");
			document.frmSettings.endingRecurrence.focus();
			return false;
		}
		if (!checkNum(document.frmSettings.endingRecurrence.value))
			return false;
	}
	return true;
}
function CheckValues() {
	var frmSET = document.frmSettings;
	var objDate = new dateValidator();
	
	objDate.ysnAllowEqualDates = true;   
	objDate.strStartDateID = 'Event Begins value';
	objDate.strEndDateID = 'Event Ends value';
	objDate.setStartDate(frmSET.dtiBeginningDate.value);
	objDate.ysnStartDateRequired = true;
	objDate.ysnEndDateRequired = true;
	objDate.setEndDate(frmSET.dtiEndingDate.value);
	if (frmSET.endByDate)
		objDate.ysnEndDateRequired = frmSET.endByDate[0].checked;
	if (!objDate.dateOrderValidate()) {
		if (objDate.error) {
			alert(objDate.error);
			if (objDate.error.substr(0,12) == 'Event Begins')
				frmSET.dtiBeginningDate.focus();
			else
				frmSET.dtiEndingDate.focus();
		}
		else alert("Unknown date validation error!");
		return false;
	}
	
	var tmpArray = frmSET.txtEventTitle.value.split(' ');
	for(var i = 0; i < tmpArray.length; i++) {
		if (tmpArray[i].length > 30) {
			alert("Event Title contains more than 30 continuous characters.");
			frmSET.txtEventTitle.focus(); return false;
		}
	}
	
	while (true) {
		if (TrimString(frmSET.txtEventTitle.value)=='') {
			alert("Please enter an Event Title.");
			frmSET.txtEventTitle.focus();
		}
		else if (TrimString(frmSET.dtiBeginningDate.value)=='') {
			alert("Please enter when the event begins.");
			frmSET.dtiBeginningDate.focus();
		}
		else if (isDate(frmSET.dtiBeginningDate.value)==false) {
			alert("Please enter a valid date for Event Begins field (mm/dd/yyyy).");
			frmSET.dtiBeginningDate.focus();
		}
		else if (!emailValidate(frmSET.txtContactEmail.value)) {
			alert("Please enter a valid email address.");
			frmSET.txtContactEmail.focus();
		}
		else if (frmSET.txtContactEmail.value!='') {
			if (frmSET.txtContactEmailLinkText.value==''||TrimString(frmSET.txtContactEmailLinkText.value).length==0) {
				if (! confirm("Warning: you have not entered link text.  The email address will be used as link text, and will show on the public side.  Continue?")) {
					frmSET.txtContactEmailLinkText.focus(); 
					return false;
				}
			}
			else if ((frmSET.txtContactEmailLinkText.value).indexOf('@')>0) {
				if (! confirm("Warning: you have entered link text that is an email address.  This will show on the public side.  Continue?")) {
					frmSET.txtContactEmailLinkText.focus(); 
					return false;
				}
			}
			break;
		}
		else
			break;
		
		return false;
	}
	
	if (frmSET.eventDateType.value!='') {
		switch (frmSET.eventDateType.value) {
			case "0": {
				if (frmSET.dailyOption[0].checked)
					if (frmSET.dailyGap.value=='') {
						alert("Please enter the gap of your daily event");
						return false;
					}
				if (!checkEnding())
					return false;
				if (frmSET.dailyOption[0].checked&&!checkNum(frmSET.dailyGap.value))
					return false;
				if (frmSET.dailyOption[0].checked) {
					if (!checkRecurrence(dateDiff(frmSET.dtiEndingDate.value, frmSET.dtiBeginningDate.value), frmSET.dailyGap.value))
						return false;
				}
				else if (!checkRecurrence(dateDiff(frmSET.dtiEndingDate.value, frmSET.dtiBeginningDate.value), 1))
					return false;
				break;
			}
			case "1": {
				if (frmSET.weeklyGap.value=='') {
					alert("Please enter the gap of your weekly events");
					return false;
				}
				var tmprecurcount = 0;
				if (frmSET.sun.checked) tmprecurcount++;
				if (frmSET.mon.checked) tmprecurcount++;
				if (frmSET.tue.checked) tmprecurcount++;
				if (frmSET.wed.checked) tmprecurcount++;
				if (frmSET.thu.checked) tmprecurcount++;
				if (frmSET.fri.checked) tmprecurcount++;
				if (frmSET.sat.checked) tmprecurcount++;
				if (tmprecurcount < 1) {
					alert("Please check at least one day of a week");
					return false;
				}
				
				if (!checkEnding() || !checkNum(frmSET.weeklyGap.value)) 
					return false;
				if (!checkRecurrence(dateDiff(frmSET.dtiEndingDate.value,frmSET.dtiBeginningDate.value),frmSET.weeklyGap.value * 7 / tmprecurcount))
					return false;
				if (frmSET.endByDate[1].checked&&frmSET.endingRecurrence.value * tmprecurcount > 52) {
				    alert("Only 52 recurring events can be setup at one time.");
					return false;
				}
				break;
			}
			case "2": {
				if (frmSET.monthlyOption[0].checked&&frmSET.dayOfMonth.value=='') {
					alert("Please enter the day of the month of events");
					return false;
				}
				else if (frmSET.monthlyOption[0].checked&&frmSET.monthlyGap.value==''||frmSET.monthlyOption[1].checked&&frmSET.monthlyGap1.value=='') {
					alert("Please enter the gap of months of events");
					return false;
				}
				if (!checkEnding()) 
					return false;
				if (frmSET.monthlyOption[0].checked && (!checkNum(frmSET.dayOfMonth.value) || !checkNum(frmSET.monthlyGap.value)))
					return false;
				if (frmSET.monthlyOption[1].checked && (!checkNum(frmSET.monthlyGap1.value)))
					return false;
				if (frmSET.monthlyOption[0].checked) {
					if (!checkRecurrence(dateDiff(frmSET.dtiEndingDate.value,frmSET.dtiBeginningDate.value),frmSET.monthlyGap.value * 31))
						return false;
					}
				else if (!checkRecurrence(dateDiff(frmSET.dtiEndingDate.value,frmSET.dtiBeginningDate.value), frmSET.monthlyGap1.value * 31))
					return false;
				if (frmSET.monthlyOption[0].checked && frmSET.dayOfMonth.value > 31) {
					alert("Day of month is too large");
					return false;
				}
				break;
			}
			case "3": {
				if (frmSET.yearlyOption[0].checked&&frmSET.dayOfMonthInYear.value=='') {
					alert("Please enter the day of month for your event every year");
					return false;
				}
				if (!checkEnding())
					return false;
				if (frmSET.yearlyOption[0].checked&&!checkNum(frmSET.dayOfMonthInYear.value))
					return false;
				if (!checkRecurrence(dateDiff(frmSET.dtiEndingDate.value,frmSET.dtiBeginningDate.value),365))
					return false;
				if (frmSET.yearlyOption[0].checked) {
					var month = parseInt(frmSET.monthOfYear.value);
					var day = parseInt(frmSET.dayOfMonthInYear.value);
					
					if ((month==4||month==6||month==9||month==11)&&day==31) {
						alert("day of month too large")
						return false;
					}
					//else if (month==2) { //Check for Feb. 29th
					//	var isleap=(year%4==0&&(year%100!=0||year%400==0));
					//	if (day>29||(day==29&&!isleap)) {
					//		alert("day of month too large");
					//		return false;
					//	}
					//}
				}
				break;
			}
		} //end of switch
		if (frmSET.recurrence && frmSET.recurrence[1].checked) {
			if (!checkNum(frmSET.eventLength.value))
					return false;
		}
	}
	else {
		alert("Unexpected Condition Error: EventDateType Blank!");
		return false;
	}
	
	if (toSQLSafe(frmSET.txtBriefDescription.value).length > 1000) {
		alert("Brief Description is too long. Please shorten it.");
		frmSET.txtBriefDescription.focus();
	}
	else if (toSQLSafe(frmSET.txtEventLocation.value).length > 255) {
		alert("Location is too long. Please shorten it.");
		frmSET.txtEventLocation.focus();
	}
	else if (toSQLSafe(frmSET.txtEventTimes.value).length > 255) {
		alert("Times is too long. Please shorten it.");
		frmSET.txtEventTimes.focus();
	}
	else if (toSQLSafe(frmSET.txtEventCost.value).length > 100) {
		alert("Cost is too long. Please shorten it.");
		frmSET.txtEventCost.focus();
	}
	else if (frmSET.lngCalendarID.value == 0) {
		alert("Please select a calendar.");
		frmSET.lngCalendarID.focus();
	}
	else
		return true;
	
	return false;
}
function Cancel() {
	document.frmCancelAddEvent.submit();
}
