// JavaScript Document
function isInteger(theNum) {
	var validChars = "0123456789"
	//check that all characters in number are OK
	for (var i = 0; i < (theNum.length); i++) { 
		testChar = theNum.charAt(i)
		if (validChars.indexOf(testChar) == "-1") { //testChar is not valid
			return false
		}
	}	
	return true
}

function isPNFloat(theNum) { // verifies that theNum is a positive or negative float value and does not contain text
	var validChars = "0123456789."
	var decimalCount = 0
	//check that all characters in number are OK
	for (var i = 0; i < (theNum.length); i++) { 
		testChar = theNum.charAt(i)
		if(i == 0 && testChar == "-") {
		} else {
			if (validChars.indexOf(testChar) == "-1") { //testChar is not valid
			return false
		}
		if(testChar == ".") { decimalCount++ }
		//alert(theNum.charAt(i))
		if (decimalCount > 1) { return false }
		}
	}
	return true	
}

function isFloat(theNum) { // verifies that theNum is a positive float value and does not contain text
	var validChars = "0123456789."
	var decimalCount = 0
	//check that all characters in number are OK
	for (var i = 0; i < (theNum.length); i++) { 
		testChar = theNum.charAt(i)
		if(theNum.charAt(i) == ".") { decimalCount++ }
		//alert(theNum.charAt(i))
		if (decimalCount > 1) { return false }
		if (validChars.indexOf(testChar) == "-1") { //testChar is not valid
			return false
		}
	}
	return true	
}

function optionalIntegers(theValue) { // validates optional integer value fields
	if(theValue == "" ) {
		return true
	}
	else {
		if(!isInteger(theValue)) {
			return false
		}
		else {
			return true
		}
	}
}

function optionalPhoneNum(theValue) { // validates optional phone number fields
	if(theValue == "" ) {
		return true
	}
	else {
		if(!validatePhone(theValue)) {
			return false
		}
	}
	return true
}

function fixDecimals(theValue) { // returns the value with two decimal places by adding zeros where needed
	theValue = theValue * 100
	theValue = Math.round(theValue)
	theValue = String(theValue/100)
	if(theValue.indexOf(".") == -1) { // no decimals at all; add two zeroes
		return theValue + ".00" }
	else if(theValue.lastIndexOf(".") == (theValue.length -2))  { // only one decimal; add one zero
		return theValue + "0" }
	else {
		return theValue
	}	
}

function validateDept(form) {
	var validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
	var dept = form.Dept.value
	if(dept.length == 0) {
			alert("Please enter a department.")
			return false 
	}
	if (dept.length > 5) { 
		alert("You entered an invalid department!")
		return false 
	}
	//check that all characters in department are OK
	for (var i = 0; i < (dept.length); i++) { 
		testChar = dept.charAt(i)
		if (validChars.indexOf(testChar) == -1) { //testChar is not valid
			alert("You entered an invalid department! Please make sure the format of your department is 'ABCD' with no more than 5 characters.")
			return false
		}
	}	
	return true
}

function validatePhone(form) {
	var validChars = "0123456789"
	var phoneNum = form.Phone.value
	if (phoneNum.length == 0) {
			alert("Please enter a phone number.")
			return false 
	}
	if (phoneNum.length != 4) { 
		alert("You entered an invalid phone number!")
		return false 
	}
	//check that all characters in number are OK
	for (var i = 0; i < (phoneNum.length); i++) { 
		testChar = phoneNum.charAt(i)
		if (validChars.indexOf(testChar) == -1) { //testChar is not valid
			alert("You entered an invalid phone number!")
			return false
		}
	}	
	return true
}

function validateEmail(form) {
	var emailad = form.Email.value
	if (emailad.indexOf("@") == -1) { // not valid email address
		alert("You entered an invalid email address!")
		return false
	}
	var emailLength = emailad.length
	if (emailad.lastIndexOf(".") != emailLength-4) { // not valid
		alert("You entered an invalid email address!")
		return false
	}
	return true
}

function checkDaysInMonth(form, inOut) {
	monthLengthArray = [31,28,31,30,31,30,31,31,30,31,30,31]
	if (eval("form.Year"+inOut+".options")[eval("form.Year"+inOut+".selectedIndex")].value % 4 == 0) {
		monthLengthArray[1] = 29
	}
	monthNum = eval("form.Month"+inOut+".options")[eval("form.Month"+inOut+".selectedIndex")].value
	monthDays = monthLengthArray[monthNum-1]
	if (eval("form.Day"+inOut+".options")[eval("form.Day"+inOut+".selectedIndex")].value > monthDays) {
		alert ("The month you selected only has " + monthDays + " days in it.")
		eval("form.Day"+inOut+".options")[monthDays-1].selected = true
		eval("form.Day"+inOut+".focus()")
	}
}

function daysInMonth(theDate) {
	monthLengthArray = [31,28,31,30,31,30,31,31,30,31,30,31]
	if (eval(theDate[2]) % 4 == 0) {
		monthLengthArray[1] = 29
	}
	monthNum = eval(theDate[0])
	monthDays = monthLengthArray[monthNum-1]
	if (theDate[1] > monthDays) {
		alert ("The month you selected only has " + monthDays + " days in it.")
		return false
	} else {
		return true
	}
}

function validateDate(date) {
	var dateArray = date.split("/")

	if (isNaN(dateArray[0]) || isNaN(dateArray[1]) || isNaN(dateArray[2])) {
		alert("Invalid date! Date must in the form of mm/dd/yy.")
		return false
	}
	if (dateArray[0] == null || dateArray[1] == null || dateArray[2] == null) {
		alert("Invalid date! Date must in the form of mm/dd/yy.")
		return false
	}
	if (dateArray[0] == "" || dateArray[1] == "" || dateArray[2] == "") {
		alert("Invalid date! Date must in the form of mm/dd/yy.")
		return false
	}
	//check month is between 1 and 12
	if (eval(dateArray[0]) < 1 || eval(dateArray[0]) > 12) { 
		alert("You entered an invalid month!")
		return false
	}
	//check if days in month correct
	if (!(daysInMonth(dateArray))) {
		//alert ("The month you selected only has " + monthDays + " days in it.")
		return false
	}
	//check year is between 2001 and 2009
	if (eval(dateArray[2]) > 2000) {
		dateArray[2] = (dateArray[2]-2000)
	}
	if (eval(dateArray[2]) < 1 || eval(dateArray[2]) > 10) {
		alert("Invalid year!")
		return false
	} 
	return true
}

function validateTimes(form) { // validates that check in time is after the check out time
	var dayOut = form.resDateOut.value 
	var timeOutString = form.TimeOut.value
	var timeOut = timeOutString.substring(0,timeOutString.indexOf(":"))
	if (timeOutString.indexOf("P") != -1 && timeOut != 12) { timeOut = parseInt(timeOut)+12 }
	var dayIn = form.DateIn.value
	var timeInString = form.TimeIn.value
	var timeIn = timeInString.substring(0,timeInString.indexOf(":"))
	if (timeInString.indexOf("P") != -1 && timeIn != 12) { timeIn = parseInt(timeIn)+12 }
	//alert("'" + timeOut + "'" + timeIn + "'")
	if (Date.parse(dayIn) == Date.parse(dayOut) && parseInt(timeIn) <= parseInt(timeOut)) { 
		alert("The check in time must be after the check out time.")
		return false 
	}	
	return true
}

function hourDisplay(hour) { //coverts numeric hour into standard time display: e.g., 14 = 2:00 PM
	if (hour == 0 || hour == 24) {
		document.write("12:00 AM")
	} else if (hour < 13) {
		document.write(hour + ":00 AM")
	} else {
		document.write(hour-12 + ":00 PM")
	}
}

function convertYear(firstYear,secondYear) {
	//convert inputted year to a four digit year
	if (firstYear.length == 2) {
		firstYear = "20" + firstYear
	}
	if (secondYear.length == 2) {
		secondYear = "20" + secondYear
	}	
	//check if year is in correct format
	if (firstYear.length == 1 || firstYear.length == 3) {
		alert("Invalid date! Date must in the form of mm/dd/yy.")
		return false
	}
	if (secondYear.length == 1 || secondYear.length == 3) {
		alert("Invalid date! Date must in the form of mm/dd/yy.")
		return false
	}				
	return true
}

function consecutiveDates(startDate, endDate) {
	var startDateArray = startDate.split("/")
	var endDateArray = endDate.split("/")
	//store date parts for start and end year in individual variables
	var startMonth = eval(startDateArray[0]) 
	var endMonth = eval(endDateArray[0]) 
	var startDay = eval(startDateArray[1]) 
	var endDay = eval(endDateArray[1]) 
	var startYear = startDateArray[2] 
	var endYear = endDateArray[2] 
	//convert inputted year to a four digit year
	if (startYear.length == 2) {
		startYear = "20" + startYear
	}
	if (endYear.length == 2) {
		endYear = "20" + endYear
	}	
	//check if year is in correct format
	if (startYear.length == 1 || startYear.length == 3) {
		alert("Invalid date! Date must in the form of mm/dd/yy.")
		return false
	}
	if (endYear.length == 1 || endYear.length == 3) {
		alert("Invalid date! Date must in the form of mm/dd/yy.")
		return false
	}				
	//check if start date is greater than today
	var myDate = new Date(Date())
	var thisMonth = eval(myDate.getMonth() + 1)
	var thisDay = myDate.getDate()
	var thisYear = eval(myDate.getYear() + 1900)
	if (startYear > thisYear) {
		alert("Start date must be prior to today's date")
		return false
	}
	if (startYear == thisYear && startMonth > thisMonth) {
		alert("Start date must be prior to today's date")
		return false
	}
	if (startYear == thisYear && startMonth == thisMonth && startDay > thisDay) {
		alert("Start date must be prior to today's date")
		return false
	}
	if (startYear == thisYear && startMonth == thisMonth && startDay == thisDay) {
		alert("Start date must be prior to today's date")
		return false
	}
	//check if start year is greater than end year
	if (startYear > endYear) {
		alert("Start date must be earlier than the end date.")
		return false
	}
	// check if start month is greater than end month when years are equal
	if (startYear == endYear && startMonth > endMonth) {
		alert("Start date must be earlier than the end date.")
		return false
	}
	//check if start day is greater than end day when years and months are equal
	if (startYear == endYear && startMonth == endMonth && startDay > endDay) {
		alert("Start date must be earlier than the end date.")
		return false
	}
	//check if dates are equal
	if (startYear == endYear && startMonth == endMonth && startDay == endDay) {
		alert("Start date must be earlier than the end date.")
		return false
	}
	if (startYear > endYear && startMonth > endMonth && startDay > endDay) {
		alert("Start date must be earlier than the end date.")
		return false
	}
	return true
}


// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// the remaining functions were written specifically for the TLP Equipment Checkout Database
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function validExtendCheckout(pickUpDate,returnDate,maxReturnDate) { // verifies that an extended checkout or recurring reservation isn't for longer than a 6 month period
	var pickUpDateArray = pickUpDate.split("/")
	var returnDateArray = returnDate.split("/")
	var maxReturnDateArray = maxReturnDate.split("/")
	
	//store date and time parts in individual variables
	var pickUpMonth = eval(pickUpDateArray[0]) 
	var returnDateMonth = eval(returnDateArray[0]) 
	var maxReturnDateMonth = eval(maxReturnDateArray[0]) 
	var pickUpDay = eval(pickUpDateArray[1]) 
	var returnDateDay = eval(returnDateArray[1]) 
	var maxReturnDateDay = eval(maxReturnDateArray[1]) 
	var pickUpYear = pickUpDateArray[2] 
	var returnDateYear = returnDateArray[2] 
	var maxReturnDateYear = maxReturnDateArray[2] 
	
	//convert inputted year to a four digit year
	if (returnDateYear.length == 2) {
		returnDateYear = "20" + returnDateYear
	}
	if (maxReturnDateYear.length == 2) {
		maxReturnDateYear = "20" + maxReturnDateYear
	}	
	//check if year is in correct format
	if (returnDateYear.length == 1 || returnDateYear.length == 3) {
		alert("Invalid date! Date must in the form of mm/dd/yy.")
		return false
	}
	if (maxReturnDateYear.length == 1 || maxReturnDateYear.length == 3) {
		alert("Invalid date! Date must in the form of mm/dd/yy.")
		return false
	}				

	//check if start year is greater than end year
	if (pickUpYear > returnDateYear) {
		alert("The ending date of the reservation must occur after the pick up date.")
		return false
	}
	if (returnDateYear > maxReturnDateYear) {
		alert("The ending date must end by " + maxReturnDate + ". A reservation may not be made for longer than a 6 month period.")
		return false
	}
	// check if start month is greater than end month when years are equal
	if (pickUpYear == returnDateYear && pickUpMonth > returnDateMonth) {
		alert("The ending date must occur after the pick up date.")
		return false
	}
	if (returnDateYear == maxReturnDateYear && returnDateMonth > maxReturnDateMonth) {
		alert("The ending date must end by " + maxReturnDate + ". A reservation may not be made for longer than a 6 month period.")
		return false
	}
	//check if start day is greater than end day when years and months are equal
	if (pickUpYear == returnDateYear && pickUpMonth == returnDateMonth && pickUpDay > returnDateDay) {
		alert("The ending date must occur after the pick up date.")
		return false
	}
	if (returnDateYear == maxReturnDateYear && returnDateMonth == maxReturnDateMonth && returnDateDay > maxReturnDateDay) {
		alert("The ending date must end by " + maxReturnDate + ". A reservation may not be made for longer than a 6 month period.")
		return false
	}
	//check if dates are equal
	if (pickUpYear == returnDateYear && pickUpMonth == returnDateMonth && pickUpDay == returnDateDay) {
		alert("The ending date must occur after the pick up date.")
		return false
	}
	if (returnDateYear == maxReturnDateYear && returnDateMonth == maxReturnDateMonth && returnDateDay == maxReturnDateDay) {
		return true
	}
	//check if month,day, and year are all greater
	if (pickUpYear > returnDateYear && pickUpMonth > returnDateMonth && pickUpDay > returnDateDay) {
		alert("The ending date must occur after the pick up date.")
		return false
	}
	if (returnDateYear > maxReturnDateYear && returnDateMonth > maxReturnDateMonth && returnDateDay > maxReturnDateDay) {
		alert("The ending date must end by " + maxReturnDate + ". A reservation may not be made for longer than a 6 month period.")
		return false
	}
	return true
}

function validRecurTimes(timeOut,timeIn,dateOut,dateIn) {
	var outDateArray = dateOut.split("/")
	var inDateArray = dateIn.split("/")
	var theTimeOut = eval(timeOut*24)
	var theTimeIn = eval(timeIn*24) 
	
	// if the dates for pickup and return are the same, make sure the return time occurs after the end time
	if (outDateArray[0] == inDateArray[0] && outDateArray[1] == inDateArray[1] && outDateArray[2] == inDateArray[2] && theTimeIn <= theTimeOut) {
		alert("Please choose an ending time that occurs after the beginning time.")
		return false
	}
	return true
}

function compareDates(returnDate,nextResDate,returnTime,nextResTime) {
	var returnDateArray = returnDate.split("/")
	var nextResDateArray = nextResDate.split("/")
	var nextResTimeArray = nextResTime.split(" ")
	var nextResTimeSplit = nextResTimeArray[0].split(":")
	
	//store date and time parts in individual variables
	var returnDateMonth = eval(returnDateArray[0]) 
	var nextResDateMonth = eval(nextResDateArray[0]) 
	var returnDateDay = eval(returnDateArray[1]) 
	var nextResDateDay = eval(nextResDateArray[1]) 
	var returnDateYear = returnDateArray[2] 
	var nextResDateYear = nextResDateArray[2] 
	var theHour = Number(nextResTimeSplit[0])
	var theMinute = Number(nextResTimeSplit[1])
	
	if (nextResTimeArray[1] == 'PM' && theHour < 12) {
		theHour = theHour + 12
	}
	
	if (theMinute == 30) {
		theMinute = .5
	}
	else {
		theMinute = 0 
	}
	var theNextResTime = (theHour + theMinute)/24
	
	//convert inputted year to a four digit year
	if (returnDateYear.length == 2) {
		returnDateYear = "20" + returnDateYear
	}
	if (nextResDateYear.length == 2) {
		nextResDateYear = "20" + nextResDateYear
	}	
	//check if year is in correct format
	if (returnDateYear.length == 1 || returnDateYear.length == 3) {
		alert("Invalid date! Date must in the form of mm/dd/yyyy.")
		return false
	}
	if (nextResDateYear.length == 1 || nextResDateYear.length == 3) {
		alert("Invalid date! Date must in the form of mm/dd/yy.")
		return false
	}				

	//check if start year is greater than end year
	if (returnDateYear > nextResDateYear) {
		alert("The ending date you chose for an extended checkout occurs after an upcoming reservation. Please choose a date and time before " + nextResDate + " at " + nextResTime + ".")
		return false
	}
	// check if start month is greater than end month when years are equal
	if (returnDateYear == nextResDateYear && returnDateMonth > nextResDateMonth) {
		alert("The ending date you chose for an extended checkout occurs after an upcoming reservation. Please choose a date and time before " + nextResDate + " at " + nextResTime + ".")
		return false
	}
	//check if start day is greater than end day when years and months are equal
	if (returnDateYear == nextResDateYear && returnDateMonth == nextResDateMonth && returnDateDay > nextResDateDay) {
		alert("The ending date you chose for an extended checkout occurs after an upcoming reservation. Please choose a date and time before " + nextResDate + " at " + nextResTime + ".")
		return false
	}
	//check if dates are equal
	if (returnDateYear == nextResDateYear && returnDateMonth == nextResDateMonth && returnDateDay == nextResDateDay) {
		if (returnTime >= theNextResTime) {
			alert("The ending date you chose for an extended checkout occurs after an upcoming reservation. Please choose a date and time before " + nextResDate + " at " + nextResTime + ".")
			return false
		}
	}
	if (returnDateYear > nextResDateYear && returnDateMonth > nextResDateMonth && returnDateDay > nextResDateDay) {
		alert("The ending date you chose for an extended checkout occurs after an upcoming reservation. Please choose a date and time before " + nextResDate + " at " + nextResTime + ".")
		return false
	}
	return true
}
