var acceptForm;
var userForm;
function formCheck(){
    acceptForm = window.document.forms["acceptForm"];
    userForm = window.document.forms["user"];
    acceptForm.accept.onclick = function (){
        processCheck();
    }
    processCheck();
    defineGeoLocateEvents()
}
function processCheck(){
    if (optionChecked())
        enableUserFormFields();
    else
        disableUserFormFields();        
}

function optionChecked(){
    return acceptForm.accept.checked;
}
function disableUserFormFields(){
    changeDisabled(true);
}
function enableUserFormFields(){
    changeDisabled(false);
}
function changeDisabled(newValue){
    for (var i =0; i < userForm.elements.length; i++){
        userForm.elements[i].disabled = newValue;
    }
}


//AJAX Stuff
//Using new google geocoder
var attempts = 0;
var gLatFound = 0;   //latitude found by google
var gLongFound = 0;    //longitude found by google
function geoLocateAddress(attempts){
    if (typeof attempts == "undefined") attempts = 0;

    var params = "";
    if (haveFieldsForGeoLocate() >= 1
        && attempts <= 2)  params = userForm.zip.value;
    if (haveFieldsForGeoLocate() >= 3
        && attempts <= 1)  params = userForm.city.value +
                ", " + userForm.state.options[userForm.state.selectedIndex].value + " " + params;
    if (haveFieldsForGeoLocate() == 4 
        && attempts == 0) params = userForm.address.value +  " " +  params;

    if (params != ""){
//        alert("attempt=" + attempts + " and params =" +params);
        googleGeoCode(params);
    }
}
var geocoder;
function googleGeoCode(params){
    geocoder = new GClientGeocoder();
    geocoder.getLatLng(params,
    function(point) {
        processGeocoderResp(point);
    }
    );
}
function processGeocoderResp(point){
    if (!point) {
        if (attempts == 2)
            alert("Could not geolocate your address.\nMake sure you select it on the map.");
        else {
            attempts++;
            geoLocateAddress(attempts);
        }
    } else {
        locate(point.y, point.x, 15);
        setCoords(point);
        gLatFound = point.y;
        gLongFound = point.x;
    }
}


//Credits: http://developer.apple.com/internet/webcontent/xmlhttpreq.html
var req = false;
// 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, functName) {
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
	try {
        	req = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		req = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		req = false;
        	}
	}
    }
    if (req) {
        req.onreadystatechange = functName;
        req.open("GET", url, true);
        req.send(null);
    }
 }

//ORGANIZATION CATEGORY DESCRIPTION LOOKUP
function processReqChange() {
    // only if req shows "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            // ...processing statements go here...
            relocateMap();
        } else {
            //alert("There was a problem retrieving the description.");
        }
    }
}
function relocateMap(){
    xml = req.responseXML;
    if (xml.getElementsByTagName("lat").length == 0) {
        return;
    }
    lats = xml.getElementsByTagName("lat");
    longs = xml.getElementsByTagName("long");
//    alert(lats[0].firstChild.nodeValue);
//    locate(lats[0].textContent, longs[0].textContent, 3);
    var point = locate(parseFloat(lats[0].firstChild.nodeValue), parseFloat(longs[0].firstChild.nodeValue), 4);
    setCoords(point);
}
//function geoLocateAddressOLD(){
//    //var term = selObj.options[selObj.selectedIndex].text;
//    /*if (term.indexOf("\/") > -1 ){
//            var termArr = term.split("\/");
//            term = termArr[0];
//            term.replace(/ /, "");
//    }*/
//    var params = "street=" + userForm.address.value + 
//                "&city=" + userForm.city.value +
//                "&state=" + userForm.state.options[userForm.state.selectedIndex].value +
//                "&zip=" + userForm.zip.value;
//    if (haveFieldsForGeoLocate() > 0){
//        loadXMLDoc("../sharedfiles/geoLocate.jsp?" + params, processReqChange);
//    }
//}

//Returns a number code indicated what fields to look in the DB
function haveFieldsForGeoLocate(){
    if (userForm.address.value != "" && 
        userForm.city.value != "" &&
        userForm.state.options[userForm.state.selectedIndex].value != "" &&
        userForm.zip.value != "")
        return 4;
    else if (userForm.city.value != "" &&
        userForm.state.options[userForm.state.selectedIndex].value != "" &&
        userForm.zip.value != "")
        return 3;
    else if (userForm.zip.value != "")
        return 1;
    else 
        return -1;
}

//EVENTS FOR ADDRESS FIELDS
function defineGeoLocateEvents(){
    userForm.address.onchange = function() {geoLocateAddress()};
    userForm.city.onchange = function() {geoLocateAddress()};
    userForm.state.onchange = function() {geoLocateAddress()};
    userForm.zip.onchange = function() {geoLocateAddress()};
}