var clickHandler;
var map;
var lat;
var lng;
var locations;
var bounds;
var rand;



var baseIcon = new GIcon();
          baseIcon.iconSize=new GSize(32,32);
          baseIcon.shadowSize=new GSize(56,32);
          baseIcon.iconAnchor=new GPoint(16,32);
          baseIcon.infoWindowAnchor=new GPoint(16,0);
		  
var bsq = new GIcon(baseIcon, "http://www.pennineleague.co.uk/common/img/ball.png", null, "http://maps.google.com/mapfiles/kml/pal2/icon57s.png");

$(document).ready(function() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
    	map.setCenter(new GLatLng(0,0), 13);
		map.setMapType(G_HYBRID_MAP);
		processLocations();
        
    }
    
    $('a#new_location').click(function() {
        $('a#new_location').hide();
        $('div#info').show('slow');
        clickHandler = GEvent.addListener(map, "click", function(marker, point) {
            setNewMarker(point);
        });
    });
    
    $('a#save').click(function() {
        $('div#formular').hide('slow');
        $.post('/xml/generators/unapprovedLocations.php',
               { type: 'upload',
                 name: $('form').find('input').get(0).value,
                 latitude: lat,
                 longitude: lng
               }, processLocations() ); 
		processLocations();
    });
    
    $('a#cancel').click(function() {
        $('div#formular').hide('slow');
    });
    
    $('a#zoom_show_all').click(function() {
        zoomShowAll();
    });
});

function setNewMarker(point) {
    $('div#formular').show('slow');
    $('a#new_location').show();
    $('div#info').hide();
    lat = point.lat();
    lng = point.lng();
	$('p#newpointer').html('Latitude=<b>'+point.lat()+'</b>, Longitude=<b>'+point.lng()+'</b>');
    $('div#formular').show();
    GEvent.removeListener(clickHandler);
}

function createMarker(point,html,icon) {
	var marker = new GMarker(point,icon);
	GEvent.addListener(marker, "click", function() {
	  marker.openInfoWindowHtml(html);
	});
	return marker;
}
	  
function processLocations() {
	var rand = Math.random();
	
    $('#location_list').html('Loading Locations');
	
	var loadBasketURL = "/xml/approvedLocations.xml" + "?"+ rand;
	
	AJAX_Pull_XML(loadBasketURL, function(response) {
		AJAX_Pulling = true;
		
		var xmlDoc = response.getElementsByTagName('locations')[0];

		locations = xmlDoc.getElementsByTagName('location');
		
		$('#location_list').html('');
	
			for(var i = 0; i < locations.length; i++) {	
				if (locations[i].getAttribute("emblem") != '0') {
					var image ='<img src="common/scripts/phpThumb/phpThumb.php?src=../../../images/news/'+locations[i].getAttribute("emblem")+'&h=50&q=50" align="left" / >';
				}
				else {
					var image = '';
				}
			
				var point = new GLatLng(locations[i].getAttribute("latitude"), locations[i].getAttribute("longitude"));
				var marker = createMarker(point,''+image+'<a href="team.index.php?team='+locations[i].getAttribute("team_id")+'"><img src="common/img/bullet.gif" border="0"/> <b>'+locations[i].getAttribute("team_name")+'</b></a><br/>'+locations[i].getAttribute("ground")+'<br/>'+locations[i].getAttribute("gpc")+'', bsq);
				
				map.addOverlay(marker); 
				link = '<li><a href="#" onclick="moveMapTo('+i+')">'+locations[i].getAttribute("team_name")+'</a></li>';
				$('#location_list').append(link);	
			}
			

 	zoomShowAll();
	});
	

}
function moveMapTo(index) {
    map.panTo(new GLatLng(locations[index].getAttribute("latitude"), locations[index].getAttribute("longitude")));
	//map.panTo(new GLatLng(locations[index].latitude, locations[index].longitude));
}

function zoomShowAll() {
	bounds = new GLatLngBounds();
    map.setCenter(new GLatLng(0,0),0);
	
    for(var i = 0; i < locations.length; i++) {		
		bounds.extend(new GLatLng(locations[i].getAttribute("latitude"), locations[i].getAttribute("longitude")));	
	}
	
    map.setZoom(map.getBoundsZoomLevel(bounds));
    var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
    var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
    map.setCenter(new GLatLng(clat,clng));
}