
var map;
var startLoc = new GLatLng(0.0, 18.0);
var startZoom = 3;
var deselectCurrent = function() {};
var removePolyline = function() {};
var EARTH_RADIUS = 6378137; //meters
var polyline = null;
var BaseIcon = new GIcon();
//var BaseUrl = 'https://rpm.nrel.gov/public/pvgraph';
//var BaseUrl = 'http://appsdev.nrel.gov/poweringhealth/';
var GeoCoder = new GClientGeocoder();

var mapDivId = 'map';

// these two are linked, we separate to make drawing easier
var latlngs= [];
var marker;


var skipFridge = false;

var gmapLat = null;
var gmapLong = null;


function changeBodyClass( from, to)  {
    //document.body.className = document.body.className.replace( from, to );
    return false;
}

function initMap()  {
    map = new GMap2( document.getElementById(mapDivId) );
    
    if (gmapLat && gmapLong) {
    	startLoc = new GLatLng(gmapLat, gmapLong);
    }
    
    map.setCenter(startLoc, startZoom);
    map.setMapType(G_HYBRID_MAP);
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());

    GEvent.addListener( map, 'click', handleMapClick );
    
    if (gmapLat && gmapLong) {
    	skipFridge = true;
    	handleMapClick(marker, new GLatLng(gmapLat, gmapLong));
    	skipFridge = false;
    }
}

function handleMapClick(marker, latlng) {
    if(!marker) {
        var id = latlngs.length; // will be new id after push()
        latlngs.push(latlng);
        initializePoint(id);
                
        document.getElementById('location').innerHTML = latlng.lat().toFixed(3) + ' , ' + latlng.lng().toFixed(3);
        
        if (!skipFridge) {
        	// WORKS except on IE
        	document.getElementById('input_hiddenelement').value = loadXMLDoc('get_fridge.php?latlon=' + document.getElementById('location').innerHTML + '');
        }
        
        //alert(document.getElementById('input_hiddenelement').value);
        //alert(document.getElementById('input_hiddenelement').value.toString());
        
        // Check location versus time zone
        check_timezone(latlng.lng().toFixed(3));
    }
}

function initializePoint(id) {
    //var letter = String.fromCharCode("A".charCodeAt(0) + id);
    //var letteredIcon = new GIcon(G_DEFAULT_ICON);
    //letteredIcon.image = "images/identify_off.2.gif";
    //letteredIcon.iconSize = new GSize(30, 35);
    
    if (marker) {
       map.removeOverlay(marker);
       marker = null;
    }
    
    marker = new GMarker(latlngs[id], {draggable: true});

   	map.addOverlay(marker);
}

    
function check_timezone ( longitude ) {

// Checks if the timezone agrees with longitude
// Based on function in HOMER by Tom Lambert

	// Initialize variables
	//var longitude = 0;
	var timezoneoffset = 0;
	var calculatedoffsetdegrees = 0;
	var time_offset_error = 0
	var degrees_error = 0;
	
	var user_timezone_offset_hours = 0;
	var user_timezone_offset_degrees = 0;
	
	var calc_timezone_offset_hours = 0;
	var calc_timezone_offset_degrees = 0;
	
	var str_message = "";
		
	// Get the longitude from the Google Map
	//longitude = latlng.lng().toFixed(3);
	calc_timezone_offset_hours = longitude / 15;
	//alert('Calculated hours offset (longitude/15): ' + calc_timezone_offset_hours);

	// Get time zone offset from web page
	timezoneoffset = document.getElementById('time_zone').value
	//alert( 'Time zone offset: ' + timezoneoffset);

	//calculatedoffsetdegrees = timezoneoffset * 15;
	//alert( 'Calculated offset degrees: ' + calculatedoffsetdegrees );

	//Calculate difference between longitude and standard meridian implied by time zone on web page
	//degrees_error = calculatedoffsetdegrees - longitude;
	time_offset_error = timezoneoffset - calc_timezone_offset_hours;
	//alert('Hours error: ' + time_offset_error);
	



/*
	CString strMessage, strLongitude, strStandardMeridian;

        //float fTimeZoneOffsetHours = float(fabs(m_Locale.GetCivilTimeOffset()));
        //float fTimeZoneOffsetDegrees = fTimeZoneOffsetHours * 15;


        if (fTimeZoneOffsetHours > 4.0f)  {

            strMessage = "The time zone does not agree with the longitude.  The longitude of ";
            strMessage += longitude + " is separated from the time zone's standard meridian of ";
            strMessage += strStandardMeridian + " by " + AutoFormat(fTimeZoneOffsetDegrees, AF_MAXSIGDIG) + " degrees.\n\n";
            strMessage += "Please change either the longitude or the time zone.";
            alert(str_message);

            exit;

        }

        if (fTimeZoneOffsetHours > 2.0f)  {

            strMessage = "The time zone does not agree very closely with the longitude.  The longitude of ";
            strMessage += longitude + " is separated from the time zone's standard meridian of ";
            strMessage += strStandardMeridian + " by " + AutoFormat(fTimeZoneOffsetDegrees, AF_MAXSIGDIG) + " degrees.\n\n";
            strMessage += "Do you want to continue anyway?";

            //if (IDYES != AfxMessageBox(strMessage, MB_ICONEXCLAMATION|MB_YESNO))

		var answer = confirm("Are you sure you want to proceed?")
		if (answer){
			alert("Good luck!")
			window.location = "http://www.google.com/";
		}
		else{
			alert("Please adjust the time zone before proceeding.")
		}
            

            return;

        }
        
*/
	
}


jQuery(document).ready(
    // inits after doc loads
    function() {
    	if (jQuery('#'+mapDivId)[0]) {
			initMap();
			
			window.onunload = GUnload;
		}
    }
);

