/*
	googlePoint is a global. It holds the result of the geocoding operation since we can not bind the object
	to the anonymous function. RESULT: Only one geo code operation per page.
	
	Dual functions as a semaphore. Setaddress won't run until its unfalsed..
*/
//var googlePoint ;

/*
	None object function for dynamic script inclusion. we use to include jquery as needed
*/
function include(script_filename) {
	//alert("INCLUDING");
    document.write('<' + 'script');
    document.write(' language="javascript"');
    document.write(' type="text/javascript"');
    document.write(' src="' + script_filename + '">');
    document.write('</' + 'script' + '>');
}

/*
Utility sleep function
*/
function pause(numberMillis) {
        var now = new Date();
        var exitTime = now.getTime() + numberMillis;
        while (true) {
            now = new Date();
            if (now.getTime() > exitTime)
                return;
        }
    }


// Moves map on manual lat long change event (onblur)
function latLongChange() {
    this.lat_value = document.getElementById("latitude").value;
    this.long_value = document.getElementById("longitude").value;
    if( this.checkRange(this.long_value, 180) && this.checkRange(this.lat_value, 90) ) { 
        this.setMapCenter(this.lat_value,this.long_value); 
    }
}
/* Manual press enter geolocate */
function geolocateOnEnter(e) {
    var key;
    if(window.event) key = window.event.keyCode; //IE
    else key = e.which; //firefox
    if(key==13){
    	//alert("ENTER PRESSED SEARCHING");
	this.showAddress(document.getElementById('geoLocateAddress').value, this);
    }
    return false;
    //return (key != 13);
}  

// Make sure the element is within a range (180:-180 and 90:-90, lat or long)
function checkRange(element, max){
        if( !isNaN(   parseFloat(element)   )  && ( ( element <= 0+max ) && ( element >= 0-max )  )   ) {
                return true;
        } else {
                return false;
        }
}
 

// Recenter map on non default coords
// Not currently used 11/14/08
function setMapCenter(inLat,inLong) {
    if(this.addrpnt){
        this.map.removeOverlay(addrpnt) ;
    }
    this.point = new GLatLng(inLat,inLong);
    try{
    this.map.setCenter(this.point, 5 ) ; // Global from calling code..
    } catch(err){
    	alert("Contact support@bepress.com-ERR:"+err.description);
    }
    this.addrpnt = new GMarker(this.point, {icon:this.icon, draggable: true,  title: this.address}) ;
    this.addrpnt.enableDragging() ;
    this.map.addOverlay(this.addrpnt) ;

	var mapObj = this; // Legacy for now, copy past coding..
	// Enable drag/drop Geolocating, uses global mapObj since its a callback
	// This is for revision
	GEvent.addListener(mapObj.addrpnt,'dragend',function() {
		mapObj.map.setCenter(mapObj.addrpnt.getPoint()) ;
		mapObj.populate();
		document.getElementById("results").innerHTML = "<p class='geo-results'>"+"Location moved to " + 
		mapObj.addrpnt.getPoint().toUrlValue() + "</p>";
		// Update the location search so we get what they actually selected
		document.getElementById("geoLocateAddress").value = mapObj.addrpnt.getPoint().toUrlValue();
	}) ;
}

 
// Ask google to load our kml file
// Google requests our our provided URL so it must be on the public internets
//   EG: It won't work on dev systems. Just provide a public version of the KML file to test.
function addKml(context) {
    var kmlUrl = "http://" + window.location.hostname + context;
    // Test URL for behind firewall 
    // kmlUrl = "http://new.fractalnet.org/article.kml";
    this.map.addOverlay(new GGeoXml(kmlUrl));
}

// MAIN-5838 Added support for toggle of clickable placemarks
function infoWindowStatus(status){
	if(status == 1 ){
		this.map.enableInfoWindow();
	} else {
		this.map.disableInfoWindow(); // Do not allow clickable placemarks if this is called, primarily for nav map
	}
}

function setAddress(){
	//this.point = googlePoint;

	if (!this.point) {
		document.getElementById('results').innerHTML = "<p class='error'>"+ this.address + " Not found.</p>";
	} else {
		if (this.addrpnt) {
			this.map.removeOverlay( this.addrpnt ) ;
		}
	}
	this.addrpnt = new GMarker(this.point, {icon:this.icon, draggable: true,  title: this.address}) ;
	//GEvent.addListener(this.addrpnt,'dragend',function() {this.newpoint()}) ;
	this.addrpnt.enableDragging() ;
	this.map.addOverlay(this.addrpnt) ;
	this.map.setCenter(this.point, this.ZOOM_LEVEL) ; 
	document.getElementById("results").innerHTML = "<p class='geo-results'>"+
	this.address + " is located at " + 
	this.addrpnt.getPoint().toUrlValue()  +"</p>";
	document.getElementById("latitude").value = this.point.lat();
	document.getElementById("longitude").value = this.point.lng();
}

// Find the address using the geocoder...
// Google returns 'Best Match' but we could catch the 602 if we wanted..
function showAddress(addr,mapObj) {
    this.address = addr ;
    this.ZOOM_LEVEL = 13; // Zoom in when we actually search, override caller
    this.geocoder.getLatLng( this.address,function(gpoint) {
            //googlePoint = gpoint;
            mapObj.point = gpoint;
            mapObj.setAddress();  // Call setAddress on the object when this event fires
            
            	// Enable drag/drop Geolocating, uses global mapObj since its a callback
            	// This is for initial submit
		GEvent.addListener(mapObj.addrpnt,'dragend',function() {
			mapObj.map.setCenter(mapObj.addrpnt.getPoint()) ;
			mapObj.populate();
			document.getElementById("results").innerHTML = "<p class='geo-results'>"+"Location moved to " + 
			mapObj.addrpnt.getPoint().toUrlValue() + "</p>";
			// Update the location search so we get what they actually selected
			document.getElementById("geoLocateAddress").value = mapObj.addrpnt.getPoint().toUrlValue();
		}) ;
          }
    ) ;
    
}

/*
// Set the user defined point
function newpoint( ) {
	alert("Picking new point now");
    this.map.setCenter(this.addrpnt.getPoint()) ;
    this.populate();
    document.getElementById("results").innerHTML = "<p class='geo-results'>"+"Location moved to " + 
    this.addrpnt.getPoint().toUrlValue() + "</p>";
}
*/

// Function to populate form
function populate(){
        document.getElementById("longitude").value = this.addrpnt.getPoint().lng().toFixed(6) ;
        document.getElementById("latitude").value  = this.addrpnt.getPoint().lat().toFixed(6) ;
}

function initialize() {
  	this.map = new GMap2(document.getElementById(this.DIV_ID));
    this.start = new GLatLng(0,0);
    this.map.setCenter(this.start, this.ZOOM_LEVEL); 
    this.map.setZoom(this.ZOOM_LEVEL);
    this.map.addMapType(G_PHYSICAL_MAP) ;
    this.map.addControl(new GSmallZoomControl()) ;
    this.geocoder = new GClientGeocoder() ;
    
    // Enable drag/drop Geolocating
    //GEvent.addListener(this.addrpnt,'dragend',function() {this.newpoint()}) ;
    
}

function googleMap(ZOOM_LEVEL, DIV_ID) {
    // Define object variables
    this.addrpnt ;
    this.geocoder ;
    this.address ;
    this.icon ;  // If we want a custom icon we populate this in initialize.
    this.map ;
    this.geoXml = false ;
    this.show_kml = true ;
    this.addrpnt ;
    this.lat_value;
    this.long_value;
    this.point;
    this.ZOOM_LEVEL = ZOOM_LEVEL;
    this.DIV_ID = DIV_ID;
    this.start;
    
    // Associate functions to object
    this.latLongChange = latLongChange;
    this.setMapCenter = setMapCenter;
    this.addKml = addKml;
    this.checkRange = checkRange;
    this.showAddress = showAddress;
    //this.newpoint = newpoint;
    this.populate = populate;
    this.setAddress = setAddress;
    this.initialize = initialize;
    this.geolocateOnEnter = geolocateOnEnter;
    this.infoWindowStatus = infoWindowStatus;
}
