var map = null;

$(document).ready(function(){
	
	$("#street").focus();
	
	//add validation to the submit button
	$("#reportit").submit(function(){
		
		//clear any error messages
		$("#error").remove();		
	
		if(($("#polenumber").val().length > 0) && ($("#problemDescription").val().length > 0)) {
			return true;
		}else{
			if($("#polenumber").val().length == 0){				
				$("#reportit").prepend($("<div>You must select a street light from the map to continue</div>").attr("id","error").attr("tabindex","-1").addClass("error"));
				$("#error").focus();
			}else{
				$("#reportit").prepend($("<div>Please tell us what the problem is</div>").attr("id","error").attr("tabindex","-1").addClass("error"));
				$("#error").focus();
			}
			
			return false;
		}
	});
	
	if(GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.addControl(new GMapTypeControl(),new GControlPosition (G_ANCHOR_TOP_RIGHT, new GSize(8, 20)));
					
		// Get the list of map types      
      	var mt = map.getMapTypes();
      	// Overwrite the getMinimumResolution() and getMaximumResolution() methods
      	for (var i=0; i<mt.length; i++) {
	    	mt[i].getMinimumResolution = function() {return 12;}
    		mt[i].getMaximumResolution = function() {return 17;}
      	}	
		//map.addControl(new GLargeMapControl());
		map.addControl(new GLargeMapControl(),new GControlPosition (G_ANCHOR_TOP_LEFT, new GSize(8, 20)));
		 
		map.enableScrollWheelZoom();
					
					
		map.setCenter(new GLatLng(53.45340699712139, -2.7366256713867188), 12);
				
			/*
		var zoomdiv = $("<div>You must zoom in to show streetlights</div>")
        					.attr({ id:"zoomdiv" })
        					.addClass("message")
        					.css({top:$("#map").offset().top,
	    			  			left:$("#map").offset().left,
	    			  			width:$("#map").width()
	    			 		});
	    		
	    		
	    		
		$("#mapcontainer").append(zoomdiv);			*/
		
		mapMessage("You must zoom in to show streetlights");
				
		/**
		event listener to detect any move ends (pan zoom drag)
		**/
		GEvent.addListener(map, "moveend", function() {
			map.clearOverlays();
			var bounds = map.getBounds();
       		var southWest = bounds.getSouthWest();	
        	var northEast = bounds.getNorthEast();
				
			//get rid of the zoom message if its there
			$("#zoomdiv").remove();
					
					
			//prevent the zoom level going less than 12
			if(map.getZoom() < 12){
				map.setZoom(12);
			}
					
			if(map.getZoom() < 17){
				
				/*$("#zoomdiv").remove();	
				var zoomdiv = $("<div>You must zoom in to show streetlights</div>")
        							.attr({ id:"zoomdiv" })
        							.addClass("message")
        							.css({top:$("#map").offset().top,
	    					  			left:$("#map").offset().left,
	    					  			width:$("#map").width()
	    					 		});
	    		
				$("#mapcontainer").append(zoomdiv);	*/
    						
    			mapMessage("You must zoom in to show streetlights");			
    							
			}else{
        		getViewportData(southWest, northEast);
        		
			}
		});
				
	}
	
 });
 
 

 
var slicon = new GIcon();
slicon.image = "/CMSWEBNET/images/mapping/streetlight-icon.png";			
slicon.iconSize = new GSize(9,9);
slicon.iconAnchor = new GPoint(5,5);
slicon.infoWindowAnchor = new GPoint(5,5);
		
var slouticon = new GIcon();
slouticon.image = "/CMSWEBNET/images/mapping/streetlightout-icon.png";			
slouticon.iconSize = new GSize(9,9);
slouticon.iconAnchor = new GPoint(5,5);
slouticon.infoWindowAnchor = new GPoint(5,5);
	
 
 
function getViewportData(southWest, northEast){

	showLoading();
	
	$.getJSON("getstreetlights.do",
		{
			"swlat":southWest.lat(),
			"swlng":southWest.lng(),
			"nelat":northEast.lat(),
			"nelng":northEast.lng(),
			"_ts":new Date().getTime()
		},
		function(data){
			map.clearOverlays();	
					
			$.each(data.result, function(i, light){
				createMarker(light);
			});
				
			showLoading();
			
			mapMessage("Click on a streetlight to select it.");
			/*$("#zoomdiv").remove();	
			var zoomdiv = $("<div>Click on a streetlight to select it.</div>")
        							.attr({ id:"zoomdiv" })
        							.addClass("message")
        							.css({top:$("#map").offset().top,
	    					  			left:$("#map").offset().left,
	    					  			width:$("#map").width()
	    			 		});
	    		
			$("#mapcontainer").append(zoomdiv);
			*/	
		}
	);
	
}
  	
/**
	function to create a marker for the light passed in. once created it adds the marker to the map
**/
function createMarker(light){
				
		//check if the light is out and use the appropriate icon
	if(light.outrecorded){
		var marker = new GMarker(new GLatLng(light.lat,light.lng), {icon:slouticon});
			
		GEvent.addListener(marker, "click", function(latlng) {
					
		
			var html = "<p>A fault has already been reported on this light.</p>";
			html = html + "<p>Problem was reported on: " + light.outrecorded + "</p>";
			
			if(light.orderdate != "undefined" && light.orderdate != null){
				html = html + "<p> A replacement was ordered on "+ light.orderdate + " and it is due to be repaired by " + light.duedate + "</p> ";
			}
			
			html = html + "<p>The problem that was reported is: " + light.outdesc +"</p>";
			
			html = html + "<p>Click to close this message</p>";
			
			mapMessage(html);
			
			
		});
					
	}else{
		var marker = new GMarker(new GLatLng(light.lat,light.lng), {icon:slicon});
			 		
		//add a click event to the marker
		GEvent.addListener(marker, "click", function(latlng) {
			loadDetails(light.unitno, light.type, light.street, light.location);		
		});
	}
				
	map.addOverlay(marker);
				
}
			 
/**
 function to handle the adding and removal of the loading information over the map
**/
function showLoading(){
	if($("#loadingdiv").length > 0){
 		$("#loadingdiv").remove();
 	}else{
		var mappos = $("#map").offset();
		var loadingdiv = $("<div>Loading the streetlights...</div>")
				.attr({id:"loadingdiv"})
				.css({top:mappos.top,
	    			  left:mappos.left,
	    			  height:$("#map").height(),
	    			  width:$("#map").width()
    		});
		$("#mapcontainer").append(loadingdiv);
		
	}
}
			 
			 
function loadDetails(poleno, type, street, location){
	
	mapMessage("Please check the Streetlight Details and enter the problem");

		 	
	$("#polenumber").val(poleno);
	$("#type").val(type);
	$("#lstreet").val(street);
	$("#location").val(location);
			
	$("#problemDescription").focus();
}
		 

/*
adds a div with a mesage in it to the page
*/
function mapMessage(message){
	if($("#zoomdiv").length > 0){
		$("#zoomdiv").html(message);	
	}else{
		var zoomdiv = $("<div>"+message+"</div>")
        	.attr({ id:"zoomdiv" })
        	.addClass("message")
        	.css({top:$("#map").offset().top,
	    		  left:$("#map").offset().left,
	    		  width:$("#map").width()
	    	});
	    		
		$("#mapcontainer").append(zoomdiv);
		
		$("#zoomdiv").bind("click", function(){
    		$(this).remove();	
    	});
	}
	
}
		 
/*
zoom to the street selected
*/
function gotoStreet(startx, starty, endx, endy){
	map.setCenter(new GLatLng(startx, starty),17);
}


function validate(){
	if(($("#polenumber").val().length > 0) && 
		($("#problemDescription").val().legnth > 0)) {
	
		return true;
	}else{
		alert("not valid");
		return false;
	}
}

			
 

