
var greenIcon = new GIcon();
greenIcon.image = "/images/icongreen.png";
greenIcon.shadow = "/images/iconshadow2.png";
greenIcon.iconSize = new GSize(15, 27);
greenIcon.shadowSize = new GSize(27, 27);
greenIcon.iconAnchor = new GPoint(4, 19);
greenIcon.infoWindowAnchor = new GPoint(4, 1);

var redIcon = new GIcon();
redIcon.image = "/images/iconred.png";
redIcon.shadow = "/images/iconshadow.png";
redIcon.iconSize = new GSize(39, 36);
redIcon.shadowSize = new GSize(39, 36);
redIcon.iconAnchor = new GPoint(13, 34);
redIcon.infoWindowAnchor = new GPoint(12, 1);

function debug(msg){
    if(window.location.href.indexOf('staging.') > 0) GLog.write(msg)
}


function createMarkerFromXML(markerXML){
    var point = new GLatLng(parseFloat(markerXML.getAttribute("lat")),parseFloat(markerXML.getAttribute("lng")));
    var zoom = markerXML.getAttribute("zoom");
    var id = markerXML.getAttribute("id");
    var name = markerXML.getAttribute("name");
    var children = markerXML.getAttribute("children");
    var parentName = markerXML.getAttribute("parent");
    currentParentName = parentName;//set the global too
    var text = '<b>'+name+'</b>';
    var marker;
    if(children > 0){
	marker = new GMarker(point,redIcon);
	if(markerXML.getAttribute('type') == 'cluster')
	{
	    text = '';
	    text += children + " Location";
	    if(children != 1) text += "s";
	    for(var i = 40; i < name.length; i++)
	    {
		if(name.charAt(i) == ' ')
		{
		    name = name.substring(0, i) + "<br>" + name.substring(i+1);
		    break;
		}
	    }
	    text += '<br><small>' + name + '</small>';
	}
	else
	{
	    text += '<br>'+children + " Location";
	    if(children != 1) text += "s";
	}
        text += '<br><a href="#" onclick="map.setCenter(new GLatLng('+point.lat()+','+point.lng()+'),'+zoom+');map.closeInfoWindow();return false;">Zoom</a>';
    }else{
        marker = new GMarker(point,greenIcon);
        text += '<br><a href="#" onclick="map.setCenter(new GLatLng('+point.lat()+','+point.lng()+'),'+zoom+');">Zoom</a>';
        text += '<br><a href="/wiki/index.php/'+name+'-'+parentName+'">Site Information</a>';
        text += '<br><small><a href="#" onclick="window.open(\'report.php?node='+id+'\',\'Report\',\'left=20,top=20,width=600,height=300,toolbar=0,resizable=0\');">Report this as wrong.</a></small>';
    }
    text = '<div align="left" style="white-space:nowrap;">'+text+'</div>';
    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(text);
    });
    return marker;
}

var markerManager;


var markersAdded = 0;
var sessionId = Math.round(Math.random()*1000000000);

var minimumZoomForAdding = 7;

function handleZoom(){

    if(!markerManager) markerManager = new MarkerManager(map);
    var sw = map.getBounds().getSouthWest();
    var ne = map.getBounds().getNorthEast();
    
    var request = GXmlHttp.create();
    request.open("GET", "getchildnodesall.php?session=" + sessionId + "&zoom="+map.getZoom() + "&swlat=" + sw.lat() + "&swlng=" + sw.lng() + "&nelat=" + ne.lat() + "&nelng=" + ne.lng() , true);
 
    request.onreadystatechange = function() {
        var alaskaMarker;
        if (request.readyState == 4) {
            var xmlDoc = request.responseXML;       
            var markers = xmlDoc.documentElement.getElementsByTagName("marker");
	    var start = new Date();
            for (var i = 0; i < markers.length; i++) {
                var marker = createMarkerFromXML(markers[i]);
		var maxZoom = markers[i].getAttribute('maxZoom');
		if(maxZoom != 100)
		    markerManager.addMarker(marker, markers[i].getAttribute('minZoom'), maxZoom);
		else
		    markerManager.addMarker(marker, markers[i].getAttribute('minZoom'));
                //alaska kitefest
                if(alaska && markers[i].getAttribute('name') =='Alaska')
                {
                    debug("set alaska");
                    alaskaMarker = marker;
                }
            }
            
            
	    markersAdded += markers.length;
	    if(markers.length > 0) markerManager.refresh();
	    debug("got " + markers.length + " markers, total download: " + markersAdded + " in " + ((new Date() - start)/1000));
            if(alaskaMarker)
            {
                GEvent.trigger(alaskaMarker, 'click');
                alaska = false;
            }
        }
    }
    request.send(null);
    
    if(addControl)
    {
	if(map.getZoom() >= minimumZoomForAdding) addControl.enable();
	else addControl.disable();
    }
    
    window.location.hash = map.getCenter().lat() + "," + map.getCenter().lng() + "," + map.getZoom();
}
var doneRegions = false;
function plotRegions()
{
    //if(doneRegions) return;
    doneRegions = true;
    //init
    var colours = ['#ff3333', '#33ff33', '#3333ff', '#ffff00', '#00ffff', '#ff00ff', '#ccffcc', '#ffffaa','#aaffff','#ff0000'];
    GEvent.addListener(map, "mousemove", function(e){
	E('debug').innerHTML = e.lat() + "," + e.lng();
    });
   
    //iterate through locations
    var bounds = map.getBounds();
    map.clearOverlays();
    var blockSize = Math.abs(bounds.getSouthWest().lat() - bounds.getNorthEast().lat())/15;
    var request = GXmlHttp.create();
    request.open("GET", "getregions.php");
    request.onreadystatechange = function() {
	if (request.readyState == 4) {
	    var xmlDoc = request.responseXML;       
            var rawMarkers = xmlDoc.documentElement.getElementsByTagName("marker");
	    var markers = new Array();
	    for(var i = 0; i < rawMarkers.length; i++)
	    {
		markers[i] = new GMarker(new GLatLng(rawMarkers[i].getAttribute('lat'),rawMarkers[i].getAttribute('lng')));
		markers[i].wm_parent = rawMarkers[i].getAttribute('id');
		map.addOverlay(markers[i]);
		var marker = markers[i];
		GEvent.addListener(marker, "click", function() {
		    marker.openInfoWindowHtml(rawMarkers[i].getAttribute('id') +"<br>" + rawMarkers[i].getAttribute('lat') + "," + rawMarkers[i].getAttribute('lng'));
		});
	    }
	   
            var minLng = bounds.getSouthWest().lng();
            var maxLng = bounds.getNorthEast().lng();
            if(minLng > 0 && maxLng < 0)
            {
                maxLng = 180 + (180 - maxLng);
                debug("maxLng now " + maxLng);
            }
            debug(minLng + " to " + maxLng);
	    for(var lat = bounds.getSouthWest().lat(); lat < bounds.getNorthEast().lat(); lat+= blockSize)
	    {
		var prevNearestMarker = -1;
		for(var lngR  = minLng; lngR < maxLng; lngR+= blockSize)
		{
                    if(lngR > 180)
                    {
                        lng = lngR - 360;
                    }
                    else lng = lngR;
		    var altLng = lng;
		    if(Math.abs(lat % 2) == 1) altLng = -lng;
		    var currentPoint = new GLatLng(lat, altLng);
		    var closest = 1000000000000;
		    
		    for(var m = 0; m < markers.length; m++)
		    {
			var distance = markers[m].getLatLng().distanceFrom(currentPoint);
			if(distance < closest)
			{
			    closest = distance;
			    nearestMarker = markers[m].wm_parent;
			}
		    }
		    
		    map.addOverlay(new GPolygon([
				    new GLatLng(currentPoint.lat() + (blockSize/2), currentPoint.lng() - (blockSize/2)),
				    new GLatLng(currentPoint.lat() + (blockSize/2), currentPoint.lng() + (blockSize/2)),
				    new GLatLng(currentPoint.lat() - (blockSize/2), currentPoint.lng() + (blockSize/2)),
				    new GLatLng(currentPoint.lat() - (blockSize/2), currentPoint.lng() - (blockSize/2)),
				 ], '#000000;', 0, 0.5, colours[nearestMarker % colours.length], 0.5));
		}
	    }
	}
    }
    request.send(null);
}

function addLocation(name, lat, lng){
    urchinTracker('/js/addlocation');
    var request = GXmlHttp.create();
    var theCentre = map.getCenter();
    var queryString = "?lat="+lat+"&lng="+lng+"&name="+escape(name)+"&zoom="+map.getZoom();
    
    request.open("GET", "addnode.php"+queryString, true);
    
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            handleZoom();
        }
    }
    request.send(null);
}

function getll(){
    var theCentre = map.getCenterLatLng();
    var e = document.getElementById("latlong");
    e.innerHTML = theCentre.x + "," + theCentre.y + "," + map.getZoomLevel();
}

var initialZoom = 1;
var initialLat = 40.1875;
var initialLng = 3.5134210456400443;

/******************* utils *******************************************/
function E(id){
    return document.getElementById(id);
}

function removeChildren(e)
{
    while (e.hasChildNodes())
	e.removeChild(e.firstChild);
}

function createInputButton(text)
{
    var button = document.createElement('INPUT');
    button.setAttribute('type', 'submit');
    button.setAttribute('value', text);
    return button;
}

/*************************** custom add location control ************************/
var addControl;
function AddLocationControl(){
    addControl = this;    
}

/** inherit from GControl() **/
AddLocationControl.prototype = new GControl();

AddLocationControl.prototype.getStepText = function(step)
{
    var text = '<div style="color:#999;font-weight:bold;font-size:120%;">';
    for(var i = 1; i < 4; i++)
    {
	if(i == step) text += '<span style="color: black;">' + i + "</span> ";
	else text += i + " ";
	text += "&nbsp;"
    }
    return text + "</div>";
}

AddLocationControl.prototype.enable = function()
{
    if(!this.adding)
    {
	this.button.disabled = false;
	this.button.innerHTML = 'Add a location';
    }
}

AddLocationControl.prototype.disable = function()
{
    if(!this.adding)
    {
	this.button.disabled = true;
	this.button.innerHTML = 'Zoom in to add a site';
    }
}

AddLocationControl.prototype.initialize = function(map)
{
    var control = document.createElement('DIV');
    //instructions
    var instructions = document.createElement('DIV');
    instructions.style.padding = "5px;"
    
    var self = this;
    
    //button to start adding a site
    var button = document.createElement('BUTTON');
    this.button = button;
    this.disable();
    this.adding = false;
    button.onclick = function(){
	//step 1
	self.adding = true;
	control.style.height="150px";
	control.style.border = "1px solid #333";
	control.style.background = "white";
	button.disabled = true;
	instructions.innerHTML = self.getStepText(1);
	instructions.innerHTML += "Zoom in close and click on the map where you want to add the site<br/>";
	var clickHandler = GEvent.addListener(map, "click", function(overlay, point){
	    //step 2
	    GEvent.removeListener(clickHandler);
	    instructions.innerHTML = self.getStepText(2) + 'Enter the name of the site<br>';
	    var inputBox = document.createElement('INPUT');
	    inputBox.setAttribute('type', 'text');
	    instructions.appendChild(inputBox);
	    var submitName = document.createElement('INPUT');
	    submitName.setAttribute('type','submit');
	    submitName.setAttribute('value','Add It');
	    instructions.appendChild(submitName);
	    var errors = document.createElement('DIV');
	    errors.style.color = '#ff3300';
	    instructions.appendChild(errors);
	    inputBox.focus();
	    submitName.onclick = function()
	    {
		//step 3
		if(inputBox.value.length < 3)
		{
		    errors.innerHTML = 'Please enter a longer name';
		    return;
		}
		marker = new GMarker(point,greenIcon);
		map.addOverlay(marker);
		marker.openInfoWindowHtml(inputBox.value);
		instructions.innerHTML = self.getStepText(3) + "Is this added correctly?";

		var ok = createInputButton('Yes');
		instructions.appendChild(ok);
		var cancel = createInputButton('Cancel');
		instructions.appendChild(cancel);
		ok.onclick = function(){
		    //do the add
		    marker.closeInfoWindow();
		    map.removeOverlay(marker);
		    debug('removed');
		    instructions.innerHTML = '';
		    control.style.background = 'none';
		    control.style.border = 'none';
		    addLocation(inputBox.value, point.lat(), point.lng());
		    self.adding = false;
		    
		    handleZoom();
		    
		};
		cancel.onclick = function(){
		    //remove instructions, hide the marker, don't add it
		    marker.closeInfoWindow();
		    map.removeOverlay(marker);
		    instructions.innerHTML = '';
		    control.style.background = 'none';
		    control.style.border = 'none';
		    self.adding = false;
		    handleZoom();
		    
		    
		};
	    }
				    
	    
	});
    }
    control.appendChild(button);
    control.appendChild(instructions);
    control.style.width = "200px";
    map.getContainer().appendChild(control);
    return control;
}

AddLocationControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(5, 30));
}

AddLocationControl.prototype.printable = function(){return false;}
AddLocationControl.prototype.selectable = function(){return false;}

/************ Zoom/sizing functions ****************************/
function bodyResize(){

    var newWidth, newHeight;
    if(document.body.clientWidth){
	newWidth = document.body.clientWidth - 50;
    }else{
	newWidth = window.innerWidth - 50;
    }
    E('container').style.width = newWidth+"px";
    E('map').style.width = newWidth +"px";
    
    newHeight = getWindowHeight() - 150;
    
    E('container').style.height = newHeight+"px";
    E('map').style.height = newHeight +"px";
    adjustZoom(newWidth);
    
}

function getWindowHeight()
{
    //FF, safari
    if(window.innerHeight){
       return window.innerHeight;          
    }else{//IE
	return document.documentElement.clientHeight;
    }
}

function adjustZoom(width)
{
    if(width > 950) initialZoom = 2;
}