// global variables
var map;
var request;
var gmarkers = [];
var categories = [];
var labels = [];
var i = 0;
var y = 1;
var listings = "";
var lastCategory = "";
var marker=[];
var BaseUrl;
var FriendlyUrls = 0;

function InitialiseSettings(baseurl,friendlyurls){
	BaseUrl = baseurl;
	if (friendlyurls == 'mod_rewrite') {
		FriendlyUrls = 1;
	}
}

function clearMap(){
    map.clearOverlays();
}

function getMap(height,width,lat,lon,zoom,search,control,baseurl,friendlyurls) {
	InitialiseSettings(baseurl,friendlyurls);
    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"));
		if (control == 2) {
			map.addControl(new GLargeMapControl());
		}else if(control == 1){
			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);
    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();
    document.getElementById('GoogleMapDirectoryAddLocationLink').href = 'extension.php?PostBackAction=GoogleMapDirectory_addLocation&Latitude='+lat+'&Longitude='+lon+'&Zoom='+zoom;
}

function addLocation(height,width,lat,lon,zoom,control,baseurl,friendlyurls) {
	InitialiseSettings(baseurl,friendlyurls);
    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'});
        if (control == 2) {
			map.addControl(new GLargeMapControl());
		}else if(control == 1){
			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,control,baseurl,friendlyurls) {
	InitialiseSettings(baseurl,friendlyurls);
    if (GBrowserIsCompatible()){// resize the map
        var lat = document.getElementById("Latitude").value;
        var lon = document.getElementById("Longitude").value;
        var m = document.getElementById("map");
        m.style.height = height + "px";
        m.style.width = width + "px";
        map = new GMap(document.getElementById("map"),{draggableCursor:'pointer'});
        if (control == 2) {
			map.addControl(new GLargeMapControl());
		}else if(control == 1){
			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){
    var dm = new DataManager();
    dm.RequestCompleteEvent = _getLocations;
	dm.RequestFailedEvent = _getLocations_failure;
    dm.LoadData(BaseUrl+'extensions/GoogleMapDirectory/ajax.php?action=getLocations&Search='+search);
}

function _getLocations(request){

	if(request.responseText!=""){

    var JSONObject = eval('(' + request.responseText + ')');
    
    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) {
			if (FriendlyUrls > 0) {
				Label += '<p><a href="?PostBackAction=GoogleMapDirectory_editLocation&LocationID=' + LocationID + '">Edit this location</a></p>';
			}else {
				Label += '<p><a href="extension.php?PostBackAction=GoogleMapDirectory_editLocation&LocationID=' + LocationID + '">Edit 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);
        map.addOverlay(marker);
        document.getElementById("GoogleMapDirectory_Locations").innerHTML = listings;

    }
    return false;
	}
}

function _getLocations_failure(){
    return false;
}


function getCategoryLocations(category){
    var dm = new DataManager();
	clearMap(); 
    dm.RequestCompleteEvent = _getCategoryLocations;
	dm.RequestFailedEvent = _getCategoryLocations_failure;
    dm.LoadData(BaseUrl+'extensions/GoogleMapDirectory/ajax.php?action=getCategoryLocations&category='+category);
}

function _getCategoryLocations(request){

	if(request.responseText!=""){
    var JSONObject = eval('(' + request.responseText + ')');
    
    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){
			if (FriendlyUrls > 0) {
				Label += '<p><a href="?PostBackAction=GoogleMapDirectory_editLocation&LocationID=' + LocationID + '">Edit this location</a></p>';
			}else{
				Label += '<p><a href="extension.php?PostBackAction=GoogleMapDirectory_editLocation&LocationID=' + LocationID + '">Edit 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);
        map.addOverlay(marker);
        document.getElementById("GoogleMapDirectory_Locations").innerHTML = listings;

    }
    return false;
	}
}

function _getCategoryLocations_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(BaseUrl+'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(BaseUrl+'extensions/GoogleMapDirectory/ajax.php?action=deleteLocation&LocationID='+LocationID);
	}
}

function _deleteLocation(request){
	if (FriendlyUrls > 0) {
		window.location.href = "?PostBackAction=GoogleMapDirectory";
	}else{
		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;
	categories[i] = category;
    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) {
	getCategoryLocations(categories[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);
	}	
}

