/**
 * @author strumc7
 */
var geocoder = null;
var gbladdressfound = false;
var clickedsubmit= false;
jQuery.validator.addMethod("notequal", function(value, element) {
	return this.optional(element) || ($(element).attr("value") != "Type Address or Click point on map");
}, "");
jQuery.validator.addMethod("validaddress", function(value, element) {
	return this.optional(element) || ($("#addressfound").css("display") != "none");
}, "!");
$(document).ready(function() 
{
	$('#addpenform').validate({
            errorClass: "formerror",
			onsubmit:true,
            rules: {
                // simple rule, converted to {required:true}
                name:{
                    required: true
                },
				location:{
                    required: true,
					notequal: "",
                },
                emailaddress: {
                    required: true,
                    email: true
                },
				comment:
				{
					maxlength: 300
				}
            }
        });
	$("#addpenform").submit(submitCheck);
		$("#address").change(addressLookup).blur(addressLookup);//.keypress(addressLookup);
		$("#addresssearching").click(addressLookup);
		
	var sw = new GLatLng(39.1329803, -77.1370115); 
	var ne = new GLatLng(39.642149, -76.254236);
		var viewport = new GLatLngBounds(sw, ne);
            geocoder = new GClientGeocoder();
            geocoder.setViewport(viewport); //roughly big square around baltimore	
       if (window.location.search.match("address")) {
	   	addressLookup();//do one at first
				}
});
function submitCheck()
{
	console.log("submitted");
	clickedsubmit = true;
	if(gbladdressfound == false)
	{	
			console.log("not found yet");
		addressLookup();
		setTimeout(submitCheck, 1000);
		return false;
	}
	else
	{
		console.log("found, submitting");
		return true;
	}
}
function addressLookup()
{
	var address = $("#address").val();
	$("#addressfound").hide();
    $("#addresssearching").text("Searching...");
	$("#addresssearching").show();
	return showLocation(address);
}
function showLocation(location) {
 	var address = location;
 	geocoder.getLocations(address, addAddressToMap);
	return true;
}
function addAddressToMap(response) {
     if (!response || response.Status.code != 200) {
       $("#addresssearching").text("Address Not Found! Please Re-Enter It");
	gbladdressfound = false;
     } else {
       place = response.Placemark[0];
       point = new GLatLng(place.Point.coordinates[1],
                           place.Point.coordinates[0]);
		$("#lat").removeAttr("value").attr("value",place.Point.coordinates[1].toString());
		$("#long").removeAttr("value").attr("value",place.Point.coordinates[0].toString());
		$("#addresssearching").hide();
		$("#addressfound").show();
		gbladdressfound = true;
		if(clickedsubmit)
		{
			$("#addpenform").submit();
		}
     }
}