var baseIcon = new GIcon(); 
baseIcon.shadow = "/maps/images/man.shadow.png";
baseIcon.iconSize = new GSize(27, 27);
baseIcon.shadowSize = new GSize(48, 27 );
baseIcon.iconAnchor = new GPoint(12, 25);
baseIcon.infoWindowAnchor = new GPoint(14, 6);
baseIcon.infoShadowAnchor = new GPoint(20, 23);

var blueIcon = new GIcon(baseIcon);
    blueIcon.image = "/maps/images/blue.png";
var yellowIcon = new GIcon(baseIcon);
    yellowIcon.image = "/maps/images/red.png";
var magentaIcon = new GIcon(baseIcon);
    magentaIcon.image = "/maps/images/magenta.png";
var greenIcon = new GIcon(baseIcon);
    greenIcon.image = "/maps/images/green.png";
var clusterIcon = new GIcon(baseIcon);
    clusterIcon.image = "/maps/images/cluster.png";
var editIcon = new GIcon(baseIcon);
    editIcon.image = "/maps/images/green.png";

var customIcons = [];
    customIcons["4"] = blueIcon;    		// staff - Admin
    customIcons["6"] = blueIcon;			// staff - SuperMod
    customIcons["8"] = blueIcon;		// staff - Senior Mod
    customIcons["10"] = blueIcon;		// staff - Expert
    customIcons["11"] = blueIcon;		// staff - Expert
    customIcons["12"] = blueIcon;		// staff - Expert
    customIcons["9"] = yellowIcon;		// Industry
    customIcons["14"] = magentaIcon;		// Team Wetpixel
    customIcons["default"] = greenIcon;	// Default
    customIcons["edit"] = greenIcon;		// For Editing


var colors = [];
    colors["4"] = "#0000FF";
    colors["6"] = "#0000FF";
    colors["8"] = "#0000FF";
    colors["10"] = "#0000FF";
    colors["11"] = "#0000FF";
    colors["12"] = "#0000FF";
    colors["9"] = "#FF0000";
    colors["14"] = "#FF00FF";
    colors["default"] = "#009933";

var map;
var geocoder;
var sidebar_html = "";
var gmarkers = [];
var mgr;
var find_id = -1;
var click_id;

function myclick(i) {
     map.setCenter(gmarkers[i].getPoint(), 8);

    GDownloadUrl("ajax_userinfo.php?user=" + gmarkers[i].id, function(data) {
	map.openInfoWindow(gmarkers[i].getLatLng(), data, {pixelOffset: new GSize(5,-20)});
    });
}

function loadmap() {
    if (GBrowserIsCompatible()) {

	var i = 0;

	// this function creates a marker on the screen and assembles
	// the sidebar HTML
	function createMarker(point, name, ibfid, sb_color, myIcon) {
	    var marker = new GMarker(point, {icon: myIcon, title: name});
	    marker.user = name;
	    marker.id = ibfid

	    if(find_id == ibfid) {
		click_id = i;	
		window.setTimeout(function() {
		    myclick(click_id);
		}, 2000);
	    }
	    // save the info we need to use later for the side_bar
	    gmarkers[i] = marker;

	    // add a line to the side_bar html
	    sidebar_html += '<a style="color: ' + sb_color + '";" href="javascript:myclick(' + i + ')">' + name + '</a><br>';
	    i++;
	    return marker;
	}

	// Start a map
        map = new GMap2(document.getElementById("map"));
	map.addMapType(G_PHYSICAL_MAP);
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
	map.addControl(new GScaleControl());
	map.enableScrollWheelZoom();
	map.setCenter(new GLatLng(32.41796892646607,8.9019622802734375), 2, G_SATELLITE_MAP);
        var mgrOptions = { borderPadding: 5};
	mgr = new MarkerManager(map, mgrOptions);

	// download the coordinates of wetpixel members 
        GDownloadUrl("ajax_coordinates.php", function(data) {
	    var xml = GXml.parse(data);
	    var markers = xml.documentElement.getElementsByTagName("marker");
	    var mgr_markers = [];
	    var mgr_clusters = [];
	    var icon;
	    // we have to initialize an array of array. JS sucks.
	    for (var k=0; k < 18; k++) {
                mgr_markers[k] = [];
                mgr_clusters[k] = [];
            }

	    for (var j = 0; j < markers.length; j++) {
		var name = markers[j].getAttribute("user");
		var ibfid = markers[j].getAttribute("ibfid");
		var type = markers[j].getAttribute("type");
		var group = markers[j].getAttribute("group");
		var minzoom = parseInt(markers[j].getAttribute("minzoom"));

		if(customIcons[group]) {
		    icon = customIcons[group];
		    side_bar_color = colors[group];
		} else {
		    icon = customIcons["default"];
		    side_bar_color = colors["default"];
		}
		
		var point = new GLatLng(parseFloat(markers[j].getAttribute("lat")), parseFloat(markers[j].getAttribute("lon")));
		var marker = createMarker(point, name, ibfid, side_bar_color,icon);
		mgr_markers[minzoom].push(marker);
	    }
	    // put the assembled side_bar_html contents into the side_bar div
	    document.getElementById("side_bar").innerHTML = sidebar_html;

	    // grab all the cluster icons
            var clusters = xml.documentElement.getElementsByTagName("cluster");
            for (var j = 0; j < clusters.length; j++) {
                var point = new GLatLng(parseFloat(clusters[j].getAttribute("lat")), parseFloat(clusters[j].getAttribute("lon")));

                var cluster = new GMarker(point,clusterIcon,true);
                var level = parseInt(clusters[j].getAttribute("level"));
                mgr_clusters[level].push(cluster);
            }

	    // draw the markers
            for(i=0; i< 18; i++ ) {
                mgr.addMarkers(mgr_markers[i],i);
                mgr.addMarkers(mgr_clusters[i],i,i);
            }
            mgr.refresh();

	    // grab the amount of users from the XML
	    var members = xml.documentElement.getElementsByTagName("members");
	    var num = members[0].getAttribute("num");
	    document.getElementById("map_count").innerHTML = num + " members";

        });

	// add a listener to the map that checks if a marker was clicked
	// if so, grab the info for this marker's wetpixel user 
	GEvent.addListener(map, "click", function(overlay, point, latlng) {
	    var id = "";
	    if (overlay){ // marker clicked
		if (overlay instanceof GMarker) {
		    GDownloadUrl("ajax_userinfo.php?user=" + overlay.id, function(data) {
			overlay.openInfoWindowHtml(data);   // open InfoWindow
		    });
		}
	    } else if (point) {   // background clicked
	    }
        });
    } else {
	alert("Your browser is not compatible");
    }
}

// the edit JS is slightly different
function editmap(user) {
    if (GBrowserIsCompatible()) {

	// start a map
	map = new GMap2(document.getElementById("map"));
	map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.enableScrollWheelZoom();
	map.setCenter(new GLatLng(52.41796892646607,4.9019622802734375), 2, G_SATELLITE_MAP);

	// add a GeoCoder object for address searches
	geocoder = new GClientGeocoder();
	
	// create a marker (if a user has one). No need to do a sidebar
        function createMarker(point, name, ibfid, myIcon) {
            var marker = new GMarker(point, {icon: myIcon, title: name});
            marker.user = name;
            marker.id = ibfid;

            return marker;
        }

	// see if this user has a marker already. 
	GDownloadUrl("ajax_user_coordinate.php?user=" + user, function(data) {
	    var xml = GXml.parse(data);
	    var markers = xml.documentElement.getElementsByTagName("marker");
	    for (var i = 0; i < markers.length; i++) {
		var name = markers[i].getAttribute("user");
		var ibfid = markers[i].getAttribute("ibfid");
		var icon = editIcon;
		var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lon")));
                var marker = createMarker(point, name, ibfid, icon);
                map.addOverlay(marker);
	    }
	});

	// this listener had two functions.
	// 1. check if a point was clicked, if so, delete is.
	// 2. if a map was clicked, remove all points and add a new one

        GEvent.addListener(map, "click", function(overlay, point) {
            var id = "";
            if (overlay){ // marker clicked
                if (overlay instanceof GMarker) {
		    map.removeOverlay(overlay);

		    GDownloadUrl("ajax_delete.php?user=" + overlay.id, function(data) {
		    });
                }
            } else if (point) {   // background clicked
		// first remove all overlays.
		map.clearOverlays();
		GDownloadUrl("ajax_delete.php?user=" + user, function(data) {
		});

		var m = new GMarker(point, {icon: editIcon});
		map.addOverlay(m);

		var lat = m.getPoint().lat();
		var lng = m.getPoint().lng();

		GDownloadUrl("ajax_add.php?user=" + user + "&lat=" + lat + "&lon=" + lng, function(data) {
                    });

            }
        });

    } else {
	alert("Your browser is not compatible");
    }
}

// This function handles the GeoCoding
function showAddress(address) {
    if (geocoder) {
	geocoder.getLatLng(address, function(point) {
	    if (!point) {
		alert(address + " not found");
            } else {
		map.setCenter(point, 15);
            }
        });
    }
}

function set_id(user) {
    find_id = user;
}

