// global variables
var map;
var request;
var gmarkers = [];
var labels = [];
var i = 0;
var y = 1;
var listings = "";
var lastCategory = "";
var marker=[];
var curmarker;
var geocoder;

function clearMap(){
    map.clearOverlays();
}

function jumpToAddress(address) {
	document.getElementById("GoogleMapDirectory_Results").innerHTML = "";
	if(curmarker != null) {
		curmarker.hide();
		map.removeOverlay(curmarker);
		curmarker = null;
	}
	if(address == null) {
		var x = document.getElementById("GoogleMapDirectory_AddressForm_Search");
		if(x == null) {
			return false;
		}
		address = x.value;
	}
	if(geocoder == null) {
		geocoder = new GClientGeocoder();
	}
	if(map == null) {
		alert('no map present!');
		return false;
	}
	var locstr = address.replace("<","&lt;","g").replace(">","&gt;","g");;
	geocoder.getLatLng(locstr,
			function(point) {
				if(point == null) {
					document.getElementById("GoogleMapDirectory_Results").innerHTML = 
						"Location '" + locstr + "' was not found.  Please be more specific.";
				} else {
					//map.setCenter(point);
					var Label  = '<div class="description">';
					Label += '<h2>'+locstr+'</h2>';
					Label += point.lat()+ ", " + point.lng() + "<br/>";
					Label += "</div>";
					Label += '<p><a href="extension.php?PostBackAction=GoogleMapDirectory_addLocation&MakeMarker=1&MarkerName=' + encodeURIComponent(address) + '&Latitude=' + point.lat() + "&Longitude=" + point.lng() + '">Add this location to the public list</a></p>';

					var title = locstr;
					curmarker = new GMarker(point,{title:title});
					map.addOverlay(curmarker);
					map.panTo(point);
					map.setZoom(15);
					curmarker.openInfoWindowHtml(Label, {maxWidth:200});
					GEvent.addListener(curmarker, "click", function(){
					  curmarker.openInfoWindowHtml(Label,{maxWidth:200});
					  });
				}
			}
	);
}

function getMap(height,width,lat,lon,zoom,search,jumptoloc) {

    if (GBrowserIsCompatible()){// resize the map
        var m = document.getElementById("map");
        m.style.height = height + "px";
        m.style.width = width + "px";
        map = new GMap(document.getElementById("map"));
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(lat,lon),zoom);
        GEvent.addListener(map, "zoom", setMapAttributes);
        GEvent.addListener(map, "moveend", setMapAttributes);
    } else {
        alert("your browser does not support Google Maps!");
    }
    getLocations(search,jumptoloc);
    if(search.length>0){
        document.getElementById('GoogleMapDirectory_Results').innerHTML = 'Search results for <strong><em>' + search + '</em></strong>';
    }
}

function setMapAttributes(){
    var center = map.getCenter();
    var lat = center.lat();
    var lon = center.lng();
    var zoom = map.getZoom();
	var allink = document.getElementById('GoogleMapDirectoryAddLocationLink');
	if(allink != null) {
		allink.href = 'extension.php?PostBackAction=GoogleMapDirectory_addLocation&Latitude='+lat+'&Longitude='+lon+'&Zoom='+zoom;
	}
}

function addLocation(height,width,lat,lon,zoom) {

    if (GBrowserIsCompatible()){// resize the map
        var m = document.getElementById("map");
        m.style.height = height + "px";
        m.style.width = width + "px";
        map = new GMap(document.getElementById("map"),{draggableCursor:'pointer'});
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(lat,lon),zoom);
        GEvent.addListener(map, "click", function(overlay, point){
        map.clearOverlays();
        if (point) {
            map.addOverlay(new GMarker(point));
            map.panTo(point);
            document.getElementById('Latitude').value=parseFloat(point.lat());
            document.getElementById('Longitude').value=parseFloat(point.lng());
        }
        });
    } else {
        alert("your browser does not support Google Maps!");
    }
}


function setLocation(height,width,zoom,lat,lon) {

    if (GBrowserIsCompatible()){// resize the map
		if(lat == null) {
			lat = document.getElementById("Latitude").value;
		} else {
			document.getElementById("Latitude").value = parseFloat(lat);
		}
		if(lon == null) {
			var lon = document.getElementById("Longitude").value;
		} else {
			document.getElementById("Longitude").value = parseFloat(lon);
		}
        var m = document.getElementById("map");
        m.style.height = height + "px";
        m.style.width = width + "px";
        map = new GMap(document.getElementById("map"),{draggableCursor:'pointer'});
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(lat,lon),zoom);
        map.addOverlay(new GMarker(new GPoint(lon,lat)));
        GEvent.addListener(map, "click", function(overlay, point){
        map.clearOverlays();
        if (point) {
            map.addOverlay(new GMarker(point));
            map.panTo(point);
            document.getElementById('Latitude').value=parseFloat(point.lat());
            document.getElementById('Longitude').value=parseFloat(point.lng());
        }
        });

    } else {
        alert("your browser does not support Google Maps!");
    }
}


function getLocations(search,jumptoloc){
    var dm = new DataManager();
    dm.RequestCompleteEvent = function(x) { _getLocations(x,jumptoloc);};
	dm.RequestFailedEvent = _getLocations_failure;
    dm.LoadData('extensions/GoogleMapDirectory/ajax.php?action=getLocations&Search='+search);
}

function _getLocations(request,jumptoloc){

	if(request.responseText!=""){

    var JSONObject = eval('(' + request.responseText + ')');
	var toopen, toopenlabel;
    
    for(x=0;x<JSONObject.locations.length;x++){

        var LocationID = JSONObject.locations[x].LocationID;
        var UserID = JSONObject.locations[x].UserID;
        var Name = Base64.decode(JSONObject.locations[x].Name);
        var LastEditedByName = Base64.decode(JSONObject.locations[x].LastEditedByName);
        var Title = Base64.decode(JSONObject.locations[x].Title);
        var Category = Base64.decode(JSONObject.locations[x].Category);
        var Description = Base64.decode(JSONObject.locations[x].Description);
        var Address = Base64.decode(JSONObject.locations[x].Address);
        var Telephone = Base64.decode(JSONObject.locations[x].Telephone);
     	var Link = Base64.decode(JSONObject.locations[x].Link);
        var Thread = Base64.decode(JSONObject.locations[x].Thread);
	    var Latitude = parseFloat(JSONObject.locations[x].Latitude);
	    var Longitude = parseFloat(JSONObject.locations[x].Longitude);
	    var CurrentUserID = JSONObject.locations[x].CurrentUserID;
	    var CurrentRoleID = JSONObject.locations[x].CurrentRoleID;
	    
	    var Label  = '<div class="description">';
        Label += '<h2>'+Title+'</h2>';
        Label += '<p><em>'+Category+'</em><br />'+Description+'</p></div>';
        Label += '<div class="info">';
	    if(Address.length>0){Label += '<p>'+Address+'</p>';}
        if(Telephone.length>0){Label += '<p>Tel:&nbsp;'+Telephone+'</p>';}
	    if(Link.length>0){Label += '<p><a href="'+Link+'">Website</a></p>';}
        if(Thread.length>0){Label += '<p><a href="'+Thread+'">Discussion Thread</a>';}
        if(CurrentUserID>0){Label += '<p><a href="extension.php?PostBackAction=GoogleMapDirectory_editLocation&Zoom=15&LocationID=' + LocationID + '">Edit this location</a></p>';}
		Label += '<p><a href="extension.php?PostBackAction=GoogleMapDirectory&LocationID=' + LocationID + '">Link to this location</a></p>';
        //if(CurrentUserID==UserID){Label += '<p><a href="javascript:deleteLocation(' + LocationID + ');">Delete this location</a></p>';}
        Label += '<p>Created by '+Name;
        if(LastEditedByName!=''){Label += ', Last edited by '+LastEditedByName;}
        Label += '</p>';
        Label += '</div>';
        var marker = createMarker(new GPoint(Longitude,Latitude),Title,Category,Label);
		if(jumptoloc != null && jumptoloc == LocationID) {
			toopen = marker;
			toopenlabel = Label;
		}
        map.addOverlay(marker);
        document.getElementById("GoogleMapDirectory_Locations").innerHTML = listings;

    }
	if(toopen != null) {
		toopen.openInfoWindowHtml(toopenlabel,{maxWidth:200});
	}
    return false;
	}
}

function _getLocations_failure(){
    return false;
}

function deleteLocation(LocationID){
    input_box=confirm("Are you sure you want to delete this location?");
	if (input_box==true){
        var dm = new DataManager();
        dm.RequestCompleteEvent = _deleteLocation;
        dm.RequestFailedEvent = _deleteLocation_failure;
        dm.LoadData('extensions/GoogleMapDirectory/ajax.php?action=deleteLocation&LocationID='+LocationID);
	}
}

function deleteThisLocation(LocationID){
    input_box=confirm("Are you sure you want to delete this location?");
	if (input_box==true){
        var dm = new DataManager();
        dm.RequestCompleteEvent = _deleteLocation;
        dm.RequestFailedEvent = _deleteLocation_failure;
        dm.LoadData('extensions/GoogleMapDirectory/ajax.php?action=deleteLocation&LocationID='+LocationID);
	}
}

function _deleteLocation(request){
	window.location.href="extension.php?PostBackAction=GoogleMapDirectory";
}
function _deleteLocation_failure(){
    return false;
}

// A function to create the marker and set up the event window
function createMarker(point,title,category,label) {
    var marker = new GMarker(point,{title:title});
    GEvent.addListener(marker, "click", function(){
      marker.openInfoWindowHtml(label,{maxWidth:200});
      });
    gmarkers[i] = marker;
    labels[i] = label;
    if((category!=lastCategory)&&(lastCategory!="")){listings += '</dd></dl></div>';y=1;}
    if(category!=lastCategory){listings += '<div class="GoogleMapDirectory_category"><dl><dt>' + category + '</dt><dd>';}
    if(y!=1){listings += ', ';}
    listings += '<a href="javascript:myclick(' + i + ')">' + title + '</a>';
    lastCategory = category;
    i++;
    y++;
    return marker;
}


// This function picks up the click and opens the corresponding info window
function myclick(i) {
    gmarkers[i].openInfoWindowHtml(labels[i],{maxWidth:200});
}

// check marker - this probably could be integrated into something in vanilla
function checkForm(){
	if(document.getElementById('Latitude').value==""){
        document.getElementById('Flash').innerHTML = '<div class="ErrorContainer"><span class="ErrorTitle">Please click on the map to create a marker</span></div>';
		return(false);
	}else if(document.getElementById('Title').value==""){
		document.getElementById('Flash').innerHTML = '<div class="ErrorContainer"><span class="ErrorTitle">Please give this location a Title</span></div>';
		return(false);
	}else if(document.getElementById('Category').value==""){
		document.getElementById('Flash').innerHTML = '<div class="ErrorContainer"><span class="ErrorTitle">Please choose a Category</span></div>';
		return(false);
	}
}

