var map, box, geocoder;
var draggable = false, resizable = false;
var mouseX, mouseY, drawnX, drawnY;
var resizedX, resizedY;
var reversegeocoder;

addLoadListener( function() {
    
    // Make the variable box global
    //box = document.getElementById("drag");
    // Register mouse move listener
    document.onmousemove = watchMouse;
    // add new geocoder
    if(GBrowserIsCompatible()) {
        geocoder = new GClientGeocoder();
        showLocationInForm();
    }
    // remember the form input
    if(typeof rememberFormInputs == 'function') { 
        rememberFormInputs("add_user_webcam", "input-"); 
    }
});


window.onunload = function() {
    // Make sure that GUnload() is called when necessary on unload
    if(box.style.visibility == "visible")
        GUnload();
}


// Mouse move listener
function watchMouse(e) {
    
    // Include possible scroll values
    var sx = window.scrollX || document.documentElement.scrollLeft|| 0;
    var sy = window.scrollY || document.documentElement.scrollTop|| 0;
    
    if(!e) e = window.event; // IEs event definition
    mouseX = e.clientX + sx;
    mouseY = e.clientY + sy;
    
    // How far has the box been resized?
    var deltaX = mouseX - resizedX;
    var deltaY = mouseY - resizedY;
    // Store the difference in global variables
    resizedX = mouseX;
    resizedY = mouseY;
    
    if(resizable) { // The resize button is being held
        
        changeMapSize(deltaX, deltaY);
    }
    
    if(draggable) { // The box is being dragged
        
        box.style.left= (mouseX - drawnX) + "px";
        box.style.top = (mouseY - drawnY) + "px";
    }
}


function dragstart(e) { // Calculate mouse position for dragging
    
    draggable = true;
    
    /* Avoid selecting the content
     * of the box while dragging
     */
    if(e.cancelable) { e.preventDefault(); }
    if(window.event) { box.onselectstart = new Function("return false"); }
    
    drawnX = mouseX - parseInt(box.style.left);
    drawnY = mouseY - parseInt(box.style.top);
    
    // The box is being dropped
    box.onmouseup = function() { draggable = false; }
}


function loadMap(lat, lng, name) {
    if(GBrowserIsCompatible()) {
        
        var point = new GLatLng(lat, lng);
        map = new GMap2(document.getElementById("map"));
        map.setCenter(point, 12, G_NORMAL_MAP);
        map.addControl(new GSmallZoomControl());
        var marker = new GMarker(point);
        map.addOverlay(marker);
        GEvent.addListener(marker, "click", function() {
                           marker.openInfoWindowHtml(name);
                           });
        // Add the self created ResizeControl
        map.addControl(new ResizeControl());
        box.style.visibility = "visible";
    }
}

function loadMap() {
    if(GBrowserIsCompatible()) {
	document.getElementById("box").style.visibility = "visible";
        // define the crosshair tile layer and its required functions
        var crossLayer = new GTileLayer(new GCopyrightCollection(""), 0, 12);
        crossLayer.getTileUrl =  function(tile, zoom) {
            return "./include/tile_crosshairs.png";
        }
        crossLayer.isPng = function() {return true;}
        
        // Create a new map type incorporating the tile layer
        var layerTerCross = [ G_PHYSICAL_MAP.getTileLayers()[0],
                             crossLayer ];
        
        var point = new GLatLng(0, 0);
        map = new GMap2(document.getElementById("map"));
        map.addMapType(G_PHYSICAL_MAP);
        map.setCenter(point, 12, G_NORMAL_MAP);
        map.addControl(new GLargeMapControl())
        
        var mapControl = new GHierarchicalMapTypeControl();
        
        // Set up map type menu relationships
        mapControl.clearRelationships();
        mapControl.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, "Labels", false);
        
        // Add control after you've specified the relationships
        map.addControl(mapControl);
        
        // Add the self created ResizeControl
        map.addControl(new ResizeControl());
        //box.style.visibility = "visible";
        // now show location
        showLocation();
    }
}

function hideMap() {
    document.getElementById("box").style.visibility = "hidden";
    GUnload();
}

function getAddress() {
    // create selection
    var selectedCountryIndex = document.add_user_webcam.id_country.selectedIndex;
    var selectedCountryValue = document.add_user_webcam.id_country.options[selectedCountryIndex].value;
    var selectedCountry;
    if(selectedCountryValue == '-2') {
        // New Country
        selectedCountry = document.add_user_webcam.name_country.value;
    } else {
        selectedCountry = document.add_user_webcam.id_country.options[selectedCountryIndex].text;
    }
    var selectedStateIndex = document.add_user_webcam.id_state.selectedIndex;
    var selectedStateValue = document.add_user_webcam.id_state.options[selectedStateIndex].value;
    var selectedState;
    if(selectedStateValue == '-2') {
        // New State
        selectedState = document.add_user_webcam.name_state.value;
    } else if(selectedStateValue == '-1') {
        // No State
    } else {
        selectedState = document.add_user_webcam.id_state.options[selectedStateIndex].text;
    }
    var selectedCityIndex = document.add_user_webcam.id_city.selectedIndex;
    var selectedCityValue = document.add_user_webcam.id_city.options[selectedCityIndex].value;
    var selectedCity;
    if(selectedCityValue == '-2') {
        // New City
        selectedCity = document.add_user_webcam.name_city.value;
    } else if(selectedCityValue == '-1') {
        // No City
    } else {
        selectedCity = document.add_user_webcam.id_city.options[selectedCityIndex].text;
    }
    // create address
    var address;
    if(selectedCountry && (selectedCountry.length > 1)) {
        address = selectedCountry;
    }
    if(selectedState && (selectedState.length > 1)) {
        if(selectedCountry && (selectedCountry.length > 1)) {
            address = ', ' + address; 
        }
        address = selectedState + address;
    }
    if(selectedCity && (selectedCity.length > 1)) {
        if(selectedState && (selectedState.length > 1)) {
            address = ', ' + address;
        }
        address = selectedCity + address;
    }
    // alert(address);
    return address;
}
function showLocationInForm() {
    var address = getAddress();
    geocoder.getLocations(address, addAddressToForm);
}

// showLocation() is called when you click on the Search button
// in the form.  It geocodes the address entered into the form
// and adds a marker to the map at that location.
var addressLevel = 0;
function showLocation() {
    var address = getAddress();
    addressLevel = address.split(",").length;
    geocoder.getLocations(address, addAddressToMap);
}

// addAddressToMap() is called when the geocoder returns an
// answer.  It adds a marker to the map with an open info window
// showing the nicely formatted version of the address and the country code.
function addAddressToMap(response) {
    map.clearOverlays();
    if (!response || response.Status.code != 200) {
        alert("Sorry, we were unable to geocode that address");
    } else {
        place = response.Placemark[0];
	var lat = place.Point.coordinates[1];
	var lng = place.Point.coordinates[0];
	/*var preLat = parseFloat(document.add_user_webcam.gps_lat.value);
	var preLng = parseFloat(document.add_user_webcam.gps_lon.value);
	if(!isNaN(preLat) && !isNaN(preLng)) {
	    lat = preLat;
	    lng = preLng;
	}
	alert(lat + "_" + lng);
*/
        point = new GLatLng(lat,lng);
        // set new center
        map.setCenter(point, 12, G_NORMAL_MAP);
        // setup reversegeocoder
/*        reversegeocoder = new GReverseGeocoder(map);
        GEvent.addListener(reversegeocoder, "load", function(placemark) {
                           marker.openInfoWindowHtml(placemark.address);
                           });
        GEvent.addListener(reversegeocoder, "error", function(lastpoint) {
                           var address = getAddress();
                           if(lastpoint) {
                           var lat = Math.round(lastpoint.lat() * 100) / 100;
                           var lng = Math.round(lastpoint.lng() * 100) / 100;
                           marker.openInfoWindowHtml(address + "<br><b>Info:</b> Reverse geocoding not possible for<br>coordinates " + lat + ", " + lng + ".");
                           } else {
                           marker.openInfoWindowHtml(address + "<br><b>Info:</b> Reverse geocoding not possible.");
                           }
                           });
*/
        // set marker
        marker = new GMarker(point, {draggable: true});
        GEvent.addListener(marker, "dragstart", function() {
                           map.closeInfoWindow();
                           });
        GEvent.addListener(marker, "dragend", function() {
            point = marker.getLatLng();
            document.add_user_webcam.gps_lat.value = point.lat();
            document.add_user_webcam.gps_lon.value = point.lng();
//            reversegeocoder.reverseGeocode(point);
                           });
        map.addOverlay(marker);
        marker.openInfoWindowHtml(place.address + '<br>' +
                                  '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode);
        document.add_user_webcam.gps_lat.value = place.Point.coordinates[1];
        document.add_user_webcam.gps_lon.value = place.Point.coordinates[0];
    }
}

function addAddressToForm(response) {
    if (response && (response.Status.code == 200)) {
        place = response.Placemark[0];
        document.add_user_webcam.gps_lat.value = place.Point.coordinates[1];
        document.add_user_webcam.gps_lon.value = place.Point.coordinates[0];
        // alert("address " +  place.Point.coordinates[1] + " - " +  place.Point.coordinates[0]);
    }
}

// Resizing
function ResizeControl(){}
ResizeControl.prototype= new GControl();

ResizeControl.prototype.initialize=function(map) {
    
    var resizeButton = document.createElement("div");
    resizeButton.setAttribute("style", "width:20px; height:20px; background-image:url('resize.gif')");
    resizeButton.onmousedown = function() { resizable = true; }
    resizeButton.onmouseup = function() { resizable = false; }
    var container = map.getContainer();
    container.appendChild(resizeButton);
    
    /* Move the 'Terms of Use' 25px to the left
     * to make sure that it's fully readable
     * (Changed since v136)
     */
    var terms = container.firstChild.nextSibling.nextSibling;
    terms.style.marginRight = "25px";
    
    return resizeButton;
}


ResizeControl.prototype.getDefaultPosition=function() {
    return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT,new GSize(0,0));
}

var typecontrol = new GMapTypeControl(true);

// Resizes the map's width and height by the given increment
function changeMapSize(dx, dy) {
    
    var mapdiv = map.getContainer();
    var width = parseInt(mapdiv.style.width);
    var height =  parseInt(mapdiv.style.height);
    
    /* Take care that the map's width or height do not get
     * a negative value. Unexpected things will happen.
     */
    if(width < 50) { width = 50; resizable = false; }
    if(height < 50) { height = 50; resizable = false; }
    
    if(width > 400) map.addControl(typecontrol); // Switch map types
    
    if(width < 400) map.removeControl(typecontrol);
    
    mapdiv.style.width = (width + dx) + "px";
    mapdiv.style.height= (height + dy) + "px";
    map.checkResize();
}
function closeBox() {
    document.getElementById("box").visibility = "hidden";
}