// functions that return true or false indicating validity of a specific 
// type of input 
//
// to use, call the function and pass it input.
// 
// document.myForm.onSubmit = function() {
//	if (!isValidPhoneNumber(document.myForm.phone_number.value)) {
//		alert("the phone number you entered sucks!");
//		return false;
//	}
//	return true;
// }

function isValidPhoneNumber(s) {
	var temp = s.replace(/\D/g, "")
	return temp.length > 9 && temp.length < 26
}

function isValidZipCode(s) {
	var temp = s.replace(/\D/g, "")
	return temp.match(/^\d{5}$|^\d{9}$/) != null
}

function isValidSelectBox(o) {
	return (o.options[o.selectedIndex].value != "_none_" && 
			o.options[o.selectedIndex].value.trim() != "")
}

function isValidMultiSelectBox(s, allowBlank) {
  var i;
  for (i = 0; i < s.options.length; i++) {
    if (s.options[i].selected) {
      var value = s.options[i].value;
      if (allowBlank || (value !="_none_" && value != "")) {
        return true;
      }
    }
  }
  return false;
}

function isValidEmailAddress(s) {
	var temp = s.replace(/\s/g, "")
	return (temp.match(/^[\w\.\-]+\x40[\w\.\-]+\.\w{3}$/)) && 
			temp.charAt(0) != "." && !(temp.match(/\.\./))
}
	
function isRadioSet(radioArray) {
  for (i = 0; i < radioArray.length; i++) {
//debugPrint(radioArray[i].name + ":" " radioArray[i].value + ":" + radioArray[i].checked);
    if (radioArray[i].checked) {
      return true;
    }
  } 
  return false;
}	
	


// masking functions - attempt to parse and reformat 
// element's values as a specific datatype
// to use, tack them to the form field's onblur handler.
// document.myForm.phone_number.onblur = phoneFieldBlurHandler	
//   -> this field will now mask for phone numbers onblur
function textFieldBlurHandler() {
	this.value = this.value.trim()
}

function dateFieldBlurHandler() {
	var d = new Date(this.value)
	if (!isNaN(d)) {
		// if the user didn't specify the century/millenium,
		// then assume the present.
		if (this.value.search(/\d{3}/) == -1) 
			d.setYear(Math.floor((new Date()).getFullYear() / 100) * 100 + d.getFullYear() % 100);

		this.value = d.getHumanDateString()
	}
}

function timeFieldBlurHandler() {
	var t = new Time(this.value)
	if (!isNaN(t)) this.value = t.getHumanTimeString()
}

function phoneFieldBlurHandler() {
	var temp = this.value.replace(/\D/g, "")

	if (temp.length > 9 && temp.length < 26)
		if (temp.length == 10) {
			this.value = "(" + temp.substring(0,3) + ") " 
			this.value += temp.substring(3,6) + "-" + temp.substring(6,10)
		}
	}

function zipcodeFieldBlurHandler() {
	var temp = this.value.replace(/\D/g, "")

	if (temp.length == 5 || temp.length == 9) { 
		if (temp.length == 5) this.value = temp
		else this.value = temp.substring(0,5) + "-" + temp.substring(5,9)
	}
}


// convenience function.
// attaches textFieldBlurHandler to the onblur event 
// of every text or textarea element in f
// var myForm = document.myForm
// attachAllTextHandlers(myForm) 
//		-> every text element in myForm now will call 
//		   textFieldBlurHandler (above) onblur
function attachAllTextHandlers(f) {
	var el
	for (var i = 0; (el = f.elements[i]); i++) {
		if (el.type == "text" || el.type == "textarea") 
			el.onblur = textFieldBlurHandler
	}
}

// as convenient a place as any to store this...
var STD_ERROR_PREFIX = "There were one or more problems with the form values "
STD_ERROR_PREFIX += "you entered.\nPlease check the following and try submitting "
STD_ERROR_PREFIX += "the form again:\n\n"

// Extensions to the Date class:
// var myDate = new Date();
// myDate.getMonthName(); -> "February"
// myDate.getHumanDateString(); -> "February 29, 2000"
// myDate.getHumanTimeString(); -> "4:00 pm"

// returns the name of the month
Date.prototype.getMonthName = function() {
	return ["January","February","March","April","May","June","July","August",
			"September","October","November","December"][this.getMonth()]
}


// returns a nicely formatted date string
Date.prototype.getHumanDateString = function() {
return this.getMonthName() + " " + this.getDate() + ", " + this.getFullYear()
}


// returns a nicely formatted time string
Date.prototype.getHumanTimeString = function() {
	var h = this.getHours()
	var m = this.getMinutes()
	var t = h >= 12 ? "pm" : "am"

	if (h == 0) h = 24
	if (h > 12) h -= 12
	h = String(h)
	m = String(m)
	if (m.length == 1) m = "0" + m

	return h + ":" + m + " " + t
}


// Time is a wrapper class for the Date object
// it accepts a wide variety of strings representing the time
// and returns a date object representing the current date with the
// specified time.
//
// var myTime = new Time('4p');
// myTime now contains a date object representing today at 4PM.
//
// accepted formats include 4p, 4:p, 4:1p, 4:10p, 4:10pm, 16:00, 
// and a bunch more...
/*
function Time(sTimeStr) {
	var a = sTimeStr.match(/(\d{1,2})\s*\x3A?\s*(\d{0,2})\s*(am|pm|a|p)?/i)
	if (a) {
		var d = new Date()
		var h = a[1]
		var m = a[2]
		var t = a[3]
		if (t && t.charAt(0).toLowerCase() == "p") h = h % 12 + 12
		d.setHours(h)
		d.setMinutes(m)
		return d
	}
	return null
}
*/
function Time(sTimeStr) {
	if (sTimeStr.trim() != "")
	{
		var a = sTimeStr.match(/\d{1,2}/g)
		var t = sTimeStr.match(/(am|pm|a|p)/ig)
		if (a) {
			var d = new Date()
			var h = a[0]
			var m = a[1] ? a[1] : 0;
			if (t) t = String(t[0]);
			if (t && t.charAt(0).toLowerCase() == "p") h = h % 12 + 12
			d.setHours(h)
			d.setMinutes(m)
			return d
		}
		return null
	}
}




// Extensions to the String class:
// var myStr = "  yomomma.mpg "
// myStr.trim() -> myStr now contains "hotdogs!"
// myStr.hasFileExtension(".mpg") -> true


// like Trim( ) in vbscript. removes trailing and 
// leading whitespace from a string
String.prototype.trim = function() {
	return this.replace(/^\s*|\s*$/g, "")
}


// determines whether or not a filename has one of the specified extensions
String.prototype.endsWith = function() {
	var bOk = false
	for (var i = 0; i < arguments.length; i++) {
		if (this.indexOf(arguments[i]) == this.length - arguments[i].length) {
			bOk = true
			break
		}
	}
	return bOk
}



// push is a quite useful method of arrays in newer 
// javascript implementations, but not in ie5-
Array.prototype.push = function(v) {
	this[this.length] = v
	return v
}


function autonavdemo() {
if (document.nav.destination.options[document.nav.destination.selectedIndex].value) {
top.location = document.nav.destination.options[document.nav.destination.selectedIndex].value
}
}

function NewWindow(mypage,myname,w,h,scroll){
LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
settings =
'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable'
win = window.open(mypage,myname,settings)
}

function MM_openBrWindow(theURL,winName,features){
	window.open(theURL,winName,features);
}

function clickNav(nav_link) {
	document.location.href = nav_link;
}

function init() {
		var f = document.agentForm;
		// setup basic text handler on all text fields
		attachAllTextHandlers(f);
}

function validateBuy() {
		var f = document.agentForm;
		var errors = [];

		// Find a Agent Fields
		if ((f.buyFirstName.value) == "")	
			errors.push("Please enter a first name.");

		if ((f.buyLastName.value) == "")	
			errors.push("Please enter a last name.");
			
		if (!isValidPhoneNumber(f.buyHomePhone.value))	
			errors.push("Please enter a valid phone number.");
			
		if (!isValidEmailAddress(f.buyEmail.value))
			errors.push("Please enter a valid email address.");

    	var neighborhoods = getFormFieldByName(f, "buyNeighborhoods[]");
	    if (!isValidMultiSelectBox(neighborhoods, false)) {
			errors.push("Please select a neighborhood.");
    	}
    	
    	if(!(f.buyAnotherAgentToBuy[0].checked || f.buyAnotherAgentToBuy[1].checked)){
    		errors.push("Please indicate the status in working with an agent.");
    	}
    
		if (errors.length > 0) {
			alert(STD_ERROR_PREFIX + errors.join("\n"))
			return false;
		}

		else return true;
}
function validateSell() {
		var f = document.agentForm;
		var errors = [];

		// Find a Agent Fields
		if ((f.sellFirstName.value) == "")	
			errors.push("Please enter a first name.");

		if ((f.sellLastName.value) == "")	
			errors.push("Please enter a last name.");
			
		if (!isValidPhoneNumber(f.sellHomePhone.value))		
			errors.push("Please enter a valid phone number.");
			
		if (!isValidEmailAddress(f.sellEmail.value))
			errors.push("Please enter a valid email address.");

		if (errors.length > 0) {
			alert(STD_ERROR_PREFIX + errors.join("\n"))
			return false;
		}

		else return true;
}
function validateBuySell() {
		var f = document.agentForm;
		var errors = [];

		// Find a Agent Fields
		if ((f.buySellFirstName.value) == "")	
			errors.push("Please enter a first name.");

		if ((f.buySellLastName.value) == "")	
			errors.push("Please enter a last name.");
			
		if (!isValidPhoneNumber(f.buySellHomePhone.value))		
			errors.push("Please enter a valid phone number.");
			
		if (!isValidEmailAddress(f.buySellEmail.value))
			errors.push("Please enter a valid email address.");

    var neighborhoods = getFormFieldByName(f, "buySellNeighborhoods[]");
    if (!isValidMultiSelectBox(neighborhoods, false)) {
			errors.push("Please select a neighborhood.");
    }
		
    if (errors.length > 0) {
			alert(STD_ERROR_PREFIX + errors.join("\n"))
			return false;
		}

		else return true;
}
function validateRelocate() {
		var f = document.agentForm;
		var errors = [];

		// Find a Agent Fields
		if ((f.relocateFirstName.value) == "")	
			errors.push("Please enter a first name.");

		if ((f.relocateLastName.value) == "")	
			errors.push("Please enter a last name.");
			
		if (!isValidPhoneNumber(f.relocateHomePhone.value))		
			errors.push("Please enter a valid phone number.");
			
		if (!isValidEmailAddress(f.relocateEmail.value))
			errors.push("Please enter a valid email address.");

		if (errors.length > 0) {
			alert(STD_ERROR_PREFIX + errors.join("\n"))
			return false;
		}

		else return true;
}
function validateValue() {
		var f = document.agentForm;
		var errors = [];

		// Find a Agent Fields
		if ((f.valuePropertyAddress.value) == "")	
			errors.push("Please enter an address.");
			
		if ((f.valueFirstName.value) == "")	
			errors.push("Please enter a first name.");

		if ((f.valueLastName.value) == "")	
			errors.push("Please enter a last name.");
			
		//if (!isValidPhoneNumber(f.valueWorkPhone.value))	
		//	errors.push("Please enter a valid phone number.");
			
		if (!isValidEmailAddress(f.valueEmail.value))
			errors.push("Please enter a valid email address.");

      if (!isValidSelectBox(f.valuePropertyType)) {
        errors.push("Property Type is required.");
      }

      if (isRadioSet(f.valueBedrooms)) {
        errors.push("Please select a value for Bedrooms.");
      }

      if (!isRadioSet(f.valueBaths)) {
        errors.push("Please select a value for Baths.");
      }

      if (!isRadioSet(f.valueHalfBaths)) {
        errors.push("Please select a value for Half Baths.");
      }

      if (!isValidSelectBox(f.valueParkingType)) {
        errors.push("Please select a value for Parking Type.");
      }

      if (!isRadioSet(f.valueParkSpaces)) {
        errors.push("Please select a value for Parking Spaces.");
      }

      if (!isRadioSet(f.valueAnotherAgentToSell)) {
        errors.push("Please indicate if you are working with an agent.");
      }
		if (errors.length > 0) {
			alert(STD_ERROR_PREFIX + errors.join("\n"))
			return false;
		}

		else return true;
}

function getFormFieldByName(f, n) {
  var i;
  for (i = 0; i < f.elements.length; i++) {
    if (f.elements[i].name == n) {
      return f.elements[i];
    }
  }
}