var regExpression;
function regExpIs_valid(text,regExpression) {
	var regEx = regExpression;
	return !(regEx.test(text));
	}
function check_fields() { 
	var returnValue = false;
	var regExOpenText = /^[0-9a-zA-Z-'. ]*$/;
	var regExNumber = /^[0-9]*$/;
	var regExEmail = /^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;
	if (document.submit_school.school_name.value == "") {
		alert("Please enter a 'School Name'");
		document.submit_school.school_name.focus();
		}
	else if (document.submit_school.grade.value == "") {
		alert("Please enter a 'Grade'");
		document.submit_school.grade.focus();
		}
	else if (document.submit_school.class_count.value == "") {
		alert("Please enter your 'Number of Students'");
		document.submit_school.class_count.focus();
		}
	else if (regExpIs_valid(document.submit_school.class_count.value,regExNumber)) {
		alert("'Class Count' needs to be a number.  Please re-enter a number");
		document.submit_school.class_count.focus();
		}
	else if (document.submit_school.name.value == "") {
		alert("Please enter your 'First Name'");
		document.submit_school.name.focus();
		}
	else if (document.submit_school.name2.value == "") {
		alert("Please enter your 'Last Name'");
		document.submit_school.name2.focus();
		}
	else if (document.submit_school.email.value == "") {
		alert("Please enter your 'Email Address'");
		document.submit_school.email.focus();
		}
		
	else if (document.submit_school.random_id.value == "") {
		alert("Please enter the characters from the image.");
		document.submit_school.random_id.focus();
	}
	else if (regExpIs_valid(document.submit_school.email.value,regExEmail)) {
		alert("'Email Address' appears to be invalid.  Please check this field.");
		document.submit_school.email.focus();
	
		} else {
	returnValue = true;
	}
	return returnValue;
}

// Global storage for Location objects
var MBLocations = new Array();

// Storage for map object
var map;

// MapBuilder.net: Location Definition Class
function MBLocation (Latitude, Longitude, Address, City, State, Zip, Country) {
  this.Latitude = Latitude;
  this.Longitude = Longitude;
  this.Address = Address;
  this.City = City;
  this.State = State;
  this.Zip = Zip;
  this.Country = Country;

  // Create well formatted location address
  this.GetAddress = function() {
    var addressItem = '';

    if (this.Address != '') {
       addressItem = this.Address;
    }
    if (this.City != '') {
       addressItem = (addressItem=='') ? this.City : addressItem + ", " + this.City;
    }
    if (this != '') {
       addressItem = (addressItem=='') ? this.State : addressItem + ", " + this.State;
    }
    if (this.Zip != '') {
       addressItem = (addressItem=='') ? this.Zip : addressItem + ", " + this.Zip;
    }
    if (this.Country != '') {
       addressItem = (addressItem=='') ? this.Country : addressItem + ", " + this.Country;
    }

    return addressItem;
  }
}

// global flag
var isIE = false;

// global request and XML document objects
var req;

// retrieve XML document (reusable generic function);
// parameter is URL string (relative or complete) to
// an .xml file whose Content-Type is a valid XML
// type, such as text/xml; XML source must be from
// same domain as HTML file
function loadXMLDoc(url) {
  // branch for native XMLHttpRequest object
  if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
    req.onreadystatechange = processReqChange;
    req.open("GET", url, true);
    req.send(null);
  // branch for IE/Windows ActiveX version
  }
  else if (window.ActiveXObject) {
    isIE = true;
    req = new ActiveXObject("Microsoft.XMLHTTP");
    if (req) {
      req.onreadystatechange = processReqChange;
      req.open("GET", url, true);
      req.send();
    }
  }
}

// handle onreadystatechange event of req object
function processReqChange() {
  // only if req shows "loaded"
  if (req.readyState == 4) {
    // only if "OK"
    if (req.status == 200) {
      clearAll();
      buildGeoSuggestList();
      // Enable address
      document.LocationSearchForm.LocationSearch.removeAttribute("readonly");
    }
    else {
      alert("There was a problem retrieving the XML data:\n" +
          req.statusText);
      // Enable address
      document.LocationSearchForm.LocationSearch.removeAttribute("readonly");
    }
  }
}


// Retrieve text of an XML document element, including elements using namespaces
function getElementTextNS(prefix, local, parentElem, index) {
  var result = "";
  if (prefix && isIE) {
    // IE/Windows way of handling namespaces
    result = parentElem.getElementsByTagName(prefix + ":" + local)[index];
  }
  else {
    // the namespace versions of this method
    // (getElementsByTagNameNS()) operate
    // differently in Safari and Mozilla, but both
    // return value with just local name, provided
    // there aren't conflicts with non-namespace element
    // names
    result = parentElem.getElementsByTagName(local)[index];
  }
  if (result) {
    // get text, accounting for possible
    // whitespace (carriage return) text nodes
    if (result.childNodes.length > 1) {
        return result.childNodes[1].nodeValue;
    } else {
        if (result.firstChild == null) return '';
        return result.firstChild.nodeValue;            
    }
  }
  else {
    return "n/a";
  }
}

// Remove all previuos results from the screen
function clearAll() {
  clearSelect("GeoSuggestList");
  document.getElementById('searchInfo').innerHTML = '';
}

// Empty select list content
function clearSelect(select_name) {
  var select = document.getElementById(select_name);
  while (select.length > 0) {
    select.remove(0);
  }
}

// Add item to select element
function appendToSelect(select, value, content) {
  var opt;
  opt = document.createElement("option");
  opt.value = value;
  opt.appendChild(content);
  select.appendChild(opt);
}

// Fill Loactions select list with items from the XML document
function buildGeoSuggestList() {
  //Remove all markers from map
  //map.removeMarkersAll();
  
  document.getElementById('searchInfo').style.display = 'block';
  //document.getElementById("searchInfo").style.visibility = 'visible';
  
  var select = document.getElementById("GeoSuggestList");
  var errors = req.responseXML.getElementsByTagName("Error");
  // Do we have Error in xml?
  if (errors.length > 0) {
    document.getElementById('searchInfo').innerHTML = "<span style=\"color:red\">We returned the following error: " +
      getElementTextNS("", "Message", errors[0], 0) +
      "</span>";
    document.getElementById('GeoResults').style.display = 'none';
    document.getElementById("GeoSuggest").style.display = 'none';
    return;
  }

  var items = req.responseXML.getElementsByTagName("Result");
  
  /* Get precision attibutes.
  * Looks like yahoo return the same 'precision' attribute for multiple "Result" element
  */
  var precision = items[0].getAttribute('precision');

  // loop through <Result > elements, and add each nested to the "Suggest" drop down
  for (var i = 0; i < items.length; i++) {
    // Craete location object and store it in the array
    MBLocations[i] = new MBLocation
    (
      getElementTextNS("", "Latitude", items[i], 0),
      getElementTextNS("", "Longitude", items[i], 0),
      getElementTextNS("", "Address", items[i], 0),
      getElementTextNS("", "City", items[i], 0),
      getElementTextNS("", "State", items[i], 0),
      getElementTextNS("", "Zip", items[i], 0),
      getElementTextNS("", "Country", items[i], 0)
    );
    //Add node to the drop down
    appendToSelect(select, i, document.createTextNode(MBLocations[i].GetAddress()));
  }
  
  // Dump geocoding results
  // Show first available result
  DumpGeoInfo('0');
  
  // Do we have some suggestions from Yahoo?
  if (items.length > 1) {
    document.getElementById('searchInfo').innerHTML = 'We found multiple possible matches.  Please select one from the drop-down list:';
    document.getElementById("GeoSuggest").style.display = 'block';
  }
  else {
    document.getElementById('searchInfo').style.display = 'none';
    document.getElementById("GeoSuggest").style.display = 'none';
  }
}

// AJAX call to make geocoding
function GeoCode(address) {
  if (trim(address)=='') {
    alert ("Please specify address for your school.")
    return;
  }

  document.LocationSearchForm.LocationSearch.setAttribute("readonly","readonly");
  document.getElementById('searchInfo').innerHTML = 'Searching...';

  loadXMLDoc("service.yahoo.geocode.php?address=" + encode(address));
}

// Show geo information received from Geocode for the given ID of MBLocation object
function DumpGeoInfo(id) {
  document.getElementById("GeoResults").innerHTML =
  "<b>2. We mapped the following location:</b><br \>" +
  "<blockquote style='margin-left:25px;'>Latitude: " + MBLocations[id].Latitude  + "<br \>" +
  "Longitude: " + MBLocations[id].Longitude + "<br \>" +
  "Address: " + MBLocations[id].Address + "<br \>" +
  "City: " + MBLocations[id].City + "<br \>" +
  "State: " + MBLocations[id].State + "<br \>" +
  "Zip: " + MBLocations[id].Zip + "<br \>" +
  "Country: " + MBLocations[id].Country + "</blockquote><br />" +
  "<b>3. If the location on the map is accurate:</b><br />" +
  "<blockquote style='margin-left:25px;'>a. please zoom in as far as you can, and place the red 'X' directly on your school location,<br />" +
  "b. You may 'drag' the map by click-dragging on the map." +
  "<em><b>If the location is not accurate, please zoom out and then step in as close as possible on your location</b></em></blockquote>";

  document.getElementById("GeoResults").style.visibility = 'visible';
  document.getElementById("address_form").style.visibility = 'visible';
  var zoom = 12;
  // Center Map and show marker
  if (MBLocations[id].Address != "") {
  zoom = 15;
  } else if (MBLocations[id].City != "") {
  zoom = 10;
  } else if (MBLocations[id].State != "") {
  zoom = 6;
  }
showMarker(MBLocations[id].Latitude, MBLocations[id].Longitude, zoom, "x", document.getElementById("GeoResults").innerHTML); 
  document.getElementById("latitude").value = MBLocations[id].Latitude.toString();
  document.getElementById("longitude").value = MBLocations[id].Longitude.toString();
  document.getElementById("address").value = MBLocations[id].Address.toString();
  document.getElementById("city").value = MBLocations[id].City.toString();
  document.getElementById("state").value = MBLocations[id].State.toString();
  document.getElementById("zip").value = MBLocations[id].Zip.toString();
  document.getElementById("country").value = MBLocations[id].Country.toString();
}

// Get address, put it on the form and geocode
function ForceGeoCode(address) {
  document.LocationSearchForm.LocationSearch.value = address;
  GeoCode(address);
}

// encode the things to pass back and forth
// the escape() method in Javascript is deprecated -- should use encodeURIComponent if available
function encode( uri ) {
  if (encodeURIComponent) {
    return encodeURIComponent(uri);
  }

  if (escape) {
    return escape(uri);
  }
}
function trim(str)
{
  return str.replace(/^\s*|\s*$/g,"");
}
