/*
Copyright 2009 IWD Studio
*/
var gmarkers = [];
var bubble_content = [];
var items = [];
var i = 0;
var lat;
var lng;
var filter;
var tmpmarker;
var map;


var prev_letter = '1';

var name;
var construction_begin;
var construction_end;
var height;
var latitude;
var longitude;
var url;
var project_status;



var ConstructionIcon = new GIcon();
ConstructionIcon.image = "i/orange-dot.png";
ConstructionIcon.shadow = "i/msmarker.shadow.png";
ConstructionIcon.iconSize=new GSize(32,32);
ConstructionIcon.shadowSize=new GSize(56,32);
ConstructionIcon.iconAnchor=new GPoint(16,32);
ConstructionIcon.infoWindowAnchor=new GPoint(16,0);

var CompleteIcon = new GIcon();
CompleteIcon.image = "i/green-dot.png";
CompleteIcon.shadow = "i/msmarker.shadow.png";
CompleteIcon.iconSize=new GSize(32,32);
CompleteIcon.shadowSize=new GSize(56,32);
CompleteIcon.iconAnchor=new GPoint(16,32);
CompleteIcon.infoWindowAnchor=new GPoint(16,0);

var ProposalIcon = new GIcon();
ProposalIcon.image = "i/ltblue-dot.png";
ProposalIcon.shadow = "i/msmarker.shadow.png";
ProposalIcon.iconSize=new GSize(32,32);
ProposalIcon.shadowSize=new GSize(56,32);
ProposalIcon.iconAnchor=new GPoint(16,32);
ProposalIcon.infoWindowAnchor=new GPoint(16,0);

var AbandonedIcon = new GIcon();
AbandonedIcon.image = "i/blue-dot.png";
AbandonedIcon.shadow = "i/msmarker.shadow.png";
AbandonedIcon.iconSize=new GSize(32,32);
AbandonedIcon.shadowSize=new GSize(56,32);
AbandonedIcon.iconAnchor=new GPoint(16,32);
AbandonedIcon.infoWindowAnchor=new GPoint(16,0);
	
var ApprovedIcon = new GIcon();
ApprovedIcon.image = "i/yellow-dot.png";
ApprovedIcon.shadow = "i/msmarker.shadow.png";
ApprovedIcon.iconSize=new GSize(32,32);
ApprovedIcon.shadowSize=new GSize(56,32);
ApprovedIcon.iconAnchor=new GPoint(16,32);
ApprovedIcon.infoWindowAnchor=new GPoint(16,0);	



	$(function() {


		
		$('#add-proj').click(function() {
			$('#dialog').dialog('open');
		})

		.hover(
			function(){ 
				$(this).addClass("ui-state-hover"); 
			},
			function(){ 
				$(this).removeClass("ui-state-hover"); 
			}
		).mousedown(function(){
			$(this).addClass("ui-state-active"); 
		})
		.mouseup(function(){
				$(this).removeClass("ui-state-active");
		});

	});
function addProject()
{		
		$("#dialog").dialog('destroy');

		$("#dialog").attr("title", "Add project");		
		$("#dialog").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 300,
			modal: true,
			buttons: {
				'Add': function() {
					var bValid = true;
					
					if (bValid) {

						
						$.post("json.php", { "functionName": "addProject", "name" : $("#name").val(), "construction_begin" : $("#construction-begin").val(), "construction_end" : $("#construction-end").val(), "latitude" : $("#latitude").val(), "longitude" : $("#longitude").val(), "height" : $("#height").val(), "url" : $("#url").val(), "project_status" : $("#project_status").val()        },function(data){callback_result(data)},"json");
						
						$(this).dialog('close');
						init();
					}
				},
				Cancel: function() {
					$(this).dialog('close');
					map.removeOverlay(tmpmarker);
					//$(this).dialog('destroy');
				}
			},
			close: function() {
			map.removeOverlay(tmpmarker);
			}
		});
		$('#dialog').dialog('open');
}

function handleClicks(marker, point){
	if (null != point)
	{
		lat.value=point.lat();
		lng.value=point.lng();
	}
		

}
function callback_result(data)
	{
	$("#message").dialog('destroy');
	//alert(data.RESULT);	
		if(data.RESULT)
		{ // Error occured
			$("#message_icon").removeClass('ui-icon-circle-check');
			$("#message_icon").addClass('ui-icon-circle-minus');
			
			$("#message_content").html("An error occured.<br /><b>Error</b>: " + data.MESSAGE);
			// and display it
			$("#message").dialog({
				bgiframe: true,
				modal: true,
				buttons: {
					Ok: function() {
						$(this).dialog('close');
					}
				}
			});

		}
		else
		{ // OK
		//alert(data.MESSAGE);
			$("#message_icon").removeClass('ui-icon-circle-minus');
			$("#message_icon").addClass('ui-icon-circle-check');	
			
			$("#message_content").html("The project was added/updated sucessfully.");
			
			// and display it
			$("#message").dialog({
				bgiframe: true,
				modal: true,
				buttons: {
					Ok: function() {
						$(this).dialog('close');
					}
				}
			});

		}
	}
				
function statusToText(status)
{
	if(status == "COMPLETE")
		return "Complete";
	if(status == "PROPOSED")
		return "Proposed";
	if(status == "APPROVED")
		return "Approved";
	if(status == "ABANDONED")
		return "Abandoned";
	if(status == "POSTPONED")
		return "Postponed";
	if(status == "UNDER_CONSTRUCTION")
		return "Under Construction";
		
	return "All";
	
}	

function clearForm()
{
	name.value = "";
	construction_begin.value = "";
	construction_end.value = "";
	height.value = "";
	url.value = "";

}

function EditEntry(id)
{
	name.value = items[parseInt(id)].name;
	construction_begin.value = items[parseInt(id)].construction_begin;
	construction_end.value = items[parseInt(id)].construction_end;
	height.value = items[parseInt(id)].height;
	latitude.value = items[parseInt(id)].latitude;
	longitude.value = items[parseInt(id)].longitude;
	url.value = items[parseInt(id)].link;
	
	if(undefined == items[parseInt(id)].link)
	url.value = "";
	for(var i=0; i < project_status.length; i++)
	{
		if(project_status.options[i].value == items[parseInt(id)].status)
		{
			   project_status.options[i].selected = true;
		}
	}


	$("#dialog").dialog('destroy');

	$("#dialog").attr("title", 'Edit project');

	$("#dialog").dialog({
		bgiframe: true,
		autoOpen: false,
		height: 300,
		modal: true,
		buttons: {
			'Submit': function() {

					$.post("json.php", { "functionName": "updateProject", "id" : items[parseInt(id)].id ,"name" : $("#name").val(), "construction_begin" : $("#construction-begin").val(), "construction_end" : $("#construction-end").val(), "latitude" : $("#latitude").val(), "longitude" : $("#longitude").val(), "height" : $("#height").val(), "url" : $("#url").val(), "project_status" : $("#project_status").val()        },function(data){ callback_result(data);  },"json");
					
					
					
					//init();
					
				//change the message
				$("#message_content").text("Update was sucessful. An administrator will need to approve the edit before it becomes active.");
				// and display it
				$("#message").dialog({
					bgiframe: true,
					modal: true,
					buttons: {
						Ok: function() {
							$(this).dialog('close');
						}
					}
				});
				$(this).dialog('close');
				//$(this).dialog('destroy');
			},
			'Cancel': function() {
			$(this).dialog('close');
			}

		},
		close: function() {
			//allFields.val('').removeClass('ui-state-error');
		}
	});
	$('#dialog').dialog('open');

}

function setFilter(status)
{
	filter = status;
	init();
}

function init()
{
	if (GBrowserIsCompatible()) {
	
    
	ClearDiv("side");
     // define where lat/long is
	lat = document.getElementById("latitude");
	lng = document.getElementById("longitude");


	name = document.getElementById("name");
	construction_begin = document.getElementById("construction-begin");
	construction_end = document.getElementById("construction-end");
	height = document.getElementById("height");
	latitude = document.getElementById("latitude");
	longitude = document.getElementById("longitude");
	url = document.getElementById("url");
	project_status = document.getElementById("project_status");


	// create the map
	map = new GMap2(document.getElementById("map"));
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.setCenter(new GLatLng( 49.26045,-123.11394), 11);

	map.enableScrollWheelZoom();






				//GEvent.addListener(map, "click", handleClicks);
				// Load info for the specified item
				/*
				GEvent.addListener(map, "singlerightclick", function(marker, point) { 
					clearForm();
				lat.value = map.fromContainerPixelToLatLng(point).lat();
				lng.value = map.fromContainerPixelToLatLng(point).lng();
				
				
				$('#dialog').dialog('open');
		
			
			
			});
			*/
				GEvent.addListener(map, "click", function (marker, point) { 
				clearForm();
				// Make sure click on not on a marker
				if (null != point)
				{
					lat.value=point.lat();
					lng.value=point.lng();
					addProject();
					//$('#dialog').dialog('open');
					tmpmarker = new GMarker(point);
					map.addOverlay(tmpmarker);					
				}				


			
			
			});
		  
			GEvent.addListener(map, "dblclick", function() {
				map.zoomIn();
			});


			 
			  
		  //GDownloadUrl("feed.php?s=<?=$_GET['s'];?>", process_it);
		function processit(data){
			//$("#side").toggle();
			// If there was an error, let us know.
			if (data.RESULT == 1)
				alert("Error occured: " + data.MESSAGE);
		
			var ch;
			var highest = 0;
			var average = 0;
			var j = 0;
			
			
			$("#side").html("<b>Showing " + statusToText(filter) + " Projects<br />");
			
			
			// For each project
			$.each(data.items, function(i,item){
			if(undefined == filter || filter == item.status)
			{
				
				// Check the first letter header;
				if (undefined != item.name.charAt(0))
				if(  ch != item.name.charAt(0).toUpperCase())
				{
					$("<b>" +  item.name.charAt(0).toUpperCase() + "</b><br />").appendTo("#side");
					ch =  item.name.charAt(0).toUpperCase();
				}
				
				$('<b>&middot; </b> ').appendTo("#side");
				$("<a>" + item.name + "</a>").attr("href", 'javascript:DisplayBubble(' + item.id + ');').appendTo("#side");
				//$("<a>[edit]</a> ").attr("href", 'javascript:EditEntry(' + item.id + ');').appendTo("#side");
				$("<br />").appendTo("#side");
						  
				var lat = parseFloat(item.latitude);
				var lng = parseFloat(item.longitude);
				
					if(parseInt(item.height) > 10 && highest < parseInt(item.height))
					{
						$("#highest").html("<b>" + item.height + " m</b>");
						highest = parseInt(item.height);
					}	
						j++;
			
						if(parseInt(item.height) > 1)
							average=average+parseInt(item.height);
						$("#average").html("<b>" + Math.round(average/j) + " m</b>");
						
						$("#numproj").html("<b>" + j + "</b>");
					
					
					
				
				

				var point = new GLatLng(lat,lng);
				// create the marker
				var marker = createMarker(point, item);
				
				map.addOverlay(marker);

				}
			
			 });
			  
			  $("#side").fadeIn("slow");

	  }
		  // Get all the data and process it
		$.post("json.php", { "functionName": "getProjects" },processit,"json");
		
		
		 
  
    }

    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }
	
	
	




	

}
	


// Google stuff


	


	  
function createMarker(point,item) {
		var marker;
		var html = item.name;
		var status = item.status;
		var html = '<b>' + item.name + '</b> <a href="javascript:EditEntry(' + item.id + ');">(edit)</a><br />Height: ' + item.height + '<br />Begin: ' + item.construction_begin + '<br />End: ' + item.construction_end + '<br />Status: ' + statusToText(item.status) + '<br /><a href="' + item.link + '">Link</a>';
	
		if (item.status == "UNDER_CONSTRUCTION")
		{
			marker = new GMarker(point, ConstructionIcon);
		}
		else if(item.status == "PROPOSED")
		{
			marker = new GMarker(point, ProposalIcon);
		}
		else if(item.status == "APPROVED")
		{
			marker = new GMarker(point, ApprovedIcon);
		}	   
		else if(item.status == "COMPLETE")
		{
			marker = new GMarker(point, CompleteIcon);
		}
		else if(item.status == "ABANDONED")
		{
			marker = new GMarker(point, AbandonedIcon);
		}
		else if(item.status == "POSTPONED")
		{
			marker = new GMarker(point, AbandonedIcon);
		}		
		else
		{
			marker = new GMarker(point, ConstructionIcon);
		}
		GEvent.addListener(marker, "click", function() {
		
		
		  marker.openInfoWindowHtml(html);
		  
		  
		  /*
		            var tabs = [];
					  var labels = ['General', 'Pictures'];
					var htmls = [html, '<b>September 07</b><br /><img src="http://www.iwdstudio.com/slike/rav/9/3.jpg" alt="" width="50">   <b>September 08</b><br /><img src="http://www.iwdstudio.com/slike/rav/9/2.jpg" alt="" width="50">    <b>September 09</b><br /><img src="http://www.iwdstudio.com/slike/rav/9/1.jpg" alt="" width="50">'];
					

			          for (var i=0; i<htmls.length; i++) {
					    htmls[i] = '<div style="width:'+htmls.length*88+'px; height: 200px">' + htmls[i] + '</div>'; //numpics*value
			            tabs.push(new GInfoWindowTab(labels[i],htmls[i]));
			          }

		
		  
		  marker.openInfoWindowTabsHtml(tabs);
		  */
		});


		gmarkers[parseInt(item.id)] = marker;
		bubble_content[parseInt(item.id)] = html;
		items[parseInt(item.id)] = item;

		return marker;
      }
	  
	  
function DisplayBubble(i) {
	gmarkers[i].openInfoWindowHtml(bubble_content[i]);
}

function ClearDiv(thediv) {
	document.getElementById(thediv).innerHTML = "";
}
