
// VARIABLES //

var map = null;
var center = null;
var geocoder = null;
var prevPosition = null;
var openMarker = null;
var cookie = null;

var crimeMarkers = new Object();
var alertMarkers = new Object();
var linkMarkers = new Object();
var searchMarkers = new Object();
var placeMarkers = new Object();

var newCrimeMarker = new Object();
var newAlertMarker = new Object();
var newLinkMarker = new Object();

var crimeImage = null;
var alertImage = null;
var placeImage = null;
var newImage = null;

var rCircle = new Object();
var panorama = null;

var loggedIn = false;
var logInProvider = false;

var orange = "#FF9900";
var blue = "#6699FF";
var green = "#97BF0D";

var pleaseLogIn = "Please login or connect with facebook first, thank you";
var netWorkError = "Internal Error";
var note = "working";
var smallScreenWidth = 1000;

var ie = false;

var now = new Date();





// MINI PLUGINS //

	// Find background position
	(function($) {
		  jQuery.fn.backgroundPositionX = function() {
		    var p = $(this).css('background-position');
		    if(typeof(p) === 'undefined'){
		    	p = $(this).css('background-position-x') + ' ' + $(this).css('background-position-y');
		    }
		    p = p.split(" ");
		    return p[0];
		  };
		})(jQuery);
	
	// Cookies, set read and end
	(function($) { 
		jQuery.setCookie = function(name,value, expireIt) {
			if (expireIt) {
				var date = new Date();
				date.setTime(date.getTime()+(5*24*60*60*1000));
				var expires = "; expires="+date.toGMTString();
			}
			else{
				var expires = "";
			}
		value = JSON.stringify(value);
		document.cookie = name+"="+value+expires+"; path=/";
	};
	})(jQuery);

	(function($) {
		jQuery.getCookie = function(name) {
			var result = null;
			var nameEQ = name + "=";
			var ca = document.cookie.split(';');
			for(var i=0;i < ca.length;i++) {
				var c = ca[i];
				while (c.charAt(0)==' ') c = c.substring(1,c.length);
				if(c.indexOf(nameEQ) == 0){
					return JSON.parse(c.substring(nameEQ.length,c.length));
			}
		}
		return false;
	};
	})(jQuery);

	(function($) { 
		jQuery.endCookie = function(name) {
			var date = new Date();
			date.setTime(77771564221);
			document.cookie = name+"=; expires="+date.toGMTString()+"; path=/";
	};
	})(jQuery);
	
	// Open a window
	(function($) {
		  jQuery.window = function(url, title, w, h) {
			  var myWin = window.open(url, title, "toolbar=0, menubar=0, directories=0, width="+w+", height="+h+", left="+((screen.width/2)-(w/2)+", top="+((screen.height/2)-(h/2)+"\"")));
		  };
		})(jQuery);
        

// PLACES //
var setting_showPlaces = function(show){
	
	// Build Array
	placeMarkers[1] = new google.maps.Marker({position : new google.maps.LatLng(-29.829444, 31.030278), icon : placeImage, title : "Moses Mabhida Stadium"});
	placeMarkers[2] = new google.maps.Marker({position : new google.maps.LatLng(-26.234797, 27.982353), icon : placeImage, title : "Soccer City"});
	placeMarkers[3] = new google.maps.Marker({position : new google.maps.LatLng(-33.903461, 18.411153), icon : placeImage, title : "Cape Town Stadium"});
	placeMarkers[4] = new google.maps.Marker({position : new google.maps.LatLng(-26.197519, 28.060767), icon : placeImage, title : "Coca-Cola Park"});
	placeMarkers[5] = new google.maps.Marker({position : new google.maps.LatLng(-25.753214, 28.222986), icon : placeImage, title : "Loftus Versfeld Stadium"});
	placeMarkers[6] = new google.maps.Marker({position : new google.maps.LatLng(-33.937778, 25.598889), icon : placeImage, title : "Nelson Mandela Bay Stadium"});
	placeMarkers[7] = new google.maps.Marker({position : new google.maps.LatLng(-29.117292, 26.208847), icon : placeImage, title : "Free State Stadium"});
	placeMarkers[8] = new google.maps.Marker({position : new google.maps.LatLng(-23.925, 29.465), icon : placeImage, title : "Peter Mokaba Stadium"});
	placeMarkers[9] = new google.maps.Marker({position : new google.maps.LatLng(-25.461, 30.929), icon : placeImage, title : "Mbombela Stadium"});
	placeMarkers[10] = new google.maps.Marker({position : new google.maps.LatLng(-25.5786, 27.1607), icon : placeImage, title : "Royal Bafokeng Stadium"});
	placeMarkers[11] = new google.maps.Marker({position : new google.maps.LatLng(-29.849, 30.935), icon : placeImage, title : "The Pavilion"});
	placeMarkers[12] = new google.maps.Marker({position : new google.maps.LatLng(-29.726, 31.067), icon : placeImage, title : "Gateway Theatre of Shopping"});
	placeMarkers[13] = new google.maps.Marker({position : new google.maps.LatLng(-29.583, 30.378), icon : placeImage, title : "Midlands Mall"});
	placeMarkers[14] = new google.maps.Marker({position : new google.maps.LatLng(-29.109, 26.204), icon : placeImage, title : "Medi-Clinic"});
	placeMarkers[15] = new google.maps.Marker({position : new google.maps.LatLng(-29.868, 31.045), icon : placeImage, title : "UShaka Marine World"});
	placeMarkers[16] = new google.maps.Marker({position : new google.maps.LatLng(-29.614444, 31.116389),map : map, icon : placeImage, title : "Durban Airport"});
	
	placeMarkers[17] = new google.maps.Marker({position : new google.maps.LatLng(-26.1088784021082, 28.0571487131958),map : map, icon : placeImage, title : "Sandton Gautrain"});
	placeMarkers[18] = new google.maps.Marker({position : new google.maps.LatLng(-26.0832730872463, 28.1116887513047),map : map, icon : placeImage, title : "Marlboro Gautrain"});
	placeMarkers[19] = new google.maps.Marker({position : new google.maps.LatLng(-26.1276091093041, 28.2246674398422),map : map, icon : placeImage, title : "Rhodesfield Gautrain"});
	placeMarkers[20] = new google.maps.Marker({position : new google.maps.LatLng(-26.1332945629541, 28.2318530777931),map : map, icon : placeImage, title : "O.R. Tambo"});
	
	var gauTrainPoints = [
			placeMarkers[17].getPosition(),
			placeMarkers[18].getPosition(),
			placeMarkers[19].getPosition(),
			placeMarkers[20].getPosition()
        ];
        var gauTrainPath = new google.maps.Polyline({
        	geodesic:true,
        	path: gauTrainPoints,
        	strokeColor: "#333333",
        	strokeOpacity: .3,
        	strokeWeight: 4,
        	clickable: false
        });
        gauTrainPath.setMap(map);
	
	// Bind
	$("#showPlace").bind('change', function(){
		if($(this).is(":checked")){
			$.each(placeMarkers, function(i,v){
				this.setMap(map);
			});
		}else{
			$.each(placeMarkers, function(i,v){
				this.setMap(null);
			});
		}
	});
	
	// 1st time load
	if($("#showPlace").is(":checked")){
		$.each(placeMarkers, function(i,v){
			this.setMap(map);
		});
	}	
};





// FIXES //

	// Find the height of the window and match the canvas
	var fixDimensions = function() {
		
		var h = $("#toolBarTable").height() + $("#footerTable").height() + 18; /* 18 = spacing */
		if($.browser.msie){h += $("#notice").height();}
		
		$("#mapCanvas, #drawCanvas, #list").css("height", $(window).height()-h);
		$("#drawCanvas").css('width', $("#canvasTd").width());
		
		// Fix search position to middle of map
		$("#loader, #newPointButtons").css('left', ($("#canvasTd").width()/2)+4);
		
		// Fix logo position
		if($.browser.msie){$("#logo").css('bottom', 62);}
		
		
		// Let google know
		google.maps.event.trigger(map, 'resize');
	};








// COOKIES //
	
	// POSITION COOKIE: Initialize the position cookie that provides prev position and zoom values
  var initialiseCookie = function() {
	     
    if(mapSettings = $.getCookie("alertZaSetup")){
            
      // Run First time visit functions
      $("#changeMapType option[value="+mapSettings.mapType+"]").attr("selected","selected");
      $("#changeTheme option[value="+mapSettings.theme+"]").attr("selected","selected");
      if(mapSettings.showPlace == '1'){$("#showPlace").attr("checked","checked");}
    } 
    else {
    	 
      // Set settings
    	var settings = {lat:-29.93, lng:23.2, zoom:6, showPlace:1, mapType:1, theme:1, scrollwheel:1, fullScreen:0};
    	$.setCookie("alertZaSetup", settings, true);
      
      // Default Site Settings
    	$("#settings input[type=checkbox]").attr("checked", "checked");
    } 
  };

	
	
	
	
	
	
	
	
	
// FILE UPLOADS //
	var upload = function(e, a, data){
		
		// Upload file
		new AjaxUpload(e, {
			  action: 'index.php/'+a,
			  name: 'userfile',
			  data: data,
			  autoSubmit: true,
			  responseType: "json",
			  onChange: function(file, extension){},
			  onSubmit: function(file, extension) {
				  if (! (extension && /^(jpg|png|jpeg)$/i.test(extension))){
					  alert('Error: invalid file extension');
					  return false;
          		}else{
          			$('#loader').show();
              		}},
			  onComplete: function(file, response) {
	          	  if(response){
	          		$('#loader').hide();
	          		if(response == 'ERROR'){
	          			alert("File upload error!");
	          		}
	          	  }
			}
		});
	};










// SHAPES //

	// Creates a polygon array for a rCircle
	var findrCirclePolygons = function(point, r) {
		
		// Convert m to Km
		r = r * 1000;
		
		// Set options
		var options = {
	          center: point,
	          radius: r,
	          strokeWeight: 1
	        };
	
		// Return
		return options;
	};
	
	// Hides the cirlce
	var hideCircle = function(){
		if(rCircle.getMap()){rCircle.setMap(null);};
	};











// GEO CODING //

	// Address from point finder
	var geoReverse = function(point) {
	
		geocoder.geocode( {
			latLng : point
		}, function(results, status) {
	
			if (status == 'OK') {
				if(results.length == 0) {
					return false;
				} else {
					address[0] = results[0].formatted_address;
					address[1] = results[0].address_components[2].long_name;
					return address;
				}
			} else {
				return false;
			}
		});
	};
	
	// Find the user
	var findMe = function(){
		
		// Try W3C Geolocation (Preferred)
		  if(navigator.geolocation) {
		    browserSupportFlag = true;
		    navigator.geolocation.getCurrentPosition(function(position) {
		      initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
		      map.setCenter(initialLocation); 
		    }, function() {
		      handleNoGeolocation(browserSupportFlag);
		    });
		// Try Google Gears Geolocation
		  } else if (google.gears) {
		    browserSupportFlag = true;
		    var geo = google.gears.factory.create('beta.geolocation');
		    geo.getCurrentPosition(function(position) {
		      initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
		      map.setCenter(initialLocation);
		    }, function() {
		      handleNoGeoLocation(browserSupportFlag);
		    });
	    // Browser doesn't support Geolocation
		  } else {
		    browserSupportFlag = false;
		    handleNoGeolocation(browserSupportFlag);
		  }
		  
		  function handleNoGeolocation(errorFlag) {
			    if (errorFlag == true) {
			      alert("Geolocation service failed.");
			    } else {
			      alert("Your browser doesn't support geolocation. Try Google Chrome!");
			    }
			  }
	};
	
	
	
	
	
	
	
	

	
// AJAX REQUEST HANDLERS //

	var globalAjaxStart = function(){
		
		// @todo up the users timeout with every ajax call
		
		 $("#loader").bind("ajaxStart", function(){
			 
			 	// Show
				$(this).show(); 
				lockMap(); 
				$("#loaderText").html(note);
				$("#mapCanvas").addClass('ui-widget-overlay');
				
			 }).bind("ajaxComplete", function(){
				 
				 // Hide
				$(this).hide();
				unlockMap();
				colorSetText();
				$("#loaderText").empty(); note = "working";
				$("#mapCanvas").removeClass('ui-widget-overlay');
				
			 }).bind("ajaxError", function(e, xhr, settings, exception){
				 
				 // Error
				$(this).hide();
				alert("Error in: "+settings.url);
				$("#mapCanvas").removeClass('ui-widget-overlay');
				
			 });
	};










// INFO WINDOWS //
	
	// Hide info window
	var hideInfoWindow = function(){
		$("#mapCanvas").removeClass('ui-widget-overlay');
		$("#infoWindow").hide();
		$("#newPointButtons").fadeIn('fast');
	};
	
	// Update info window
	var upDateInfoWindowPosition = function(){
		
		// Hide canvas
		$("#drawCanvas").fadeOut('fast');
		
		if(openMarker){
					
			// Get dimensions
			var scale = Math.pow(2, map.getZoom());
			var nw = new google.maps.LatLng(
			    map.getBounds().getNorthEast().lat(),
			    map.getBounds().getSouthWest().lng()
			);
			var worldCoordinateNW = map.getProjection().fromLatLngToPoint(nw);
			var worldCoordinate = map.getProjection().fromLatLngToPoint(openMarker.getPosition());
			var pixelOffset = new google.maps.Point(
			    Math.floor((worldCoordinate.x - worldCoordinateNW.x) * scale),
			    Math.floor((worldCoordinate.y - worldCoordinateNW.y) * scale)
			);
			
			// Fixes
			if($.browser.msie){var offx = -198; var up = 105;}
			else{var offx = -198; var up = 75;}
			
			// Position y offset
			pixelOffset.y = $("#mapCanvas").height() - (pixelOffset.y-up);
			
			// Set it
			$("#infoWindow").css("left",pixelOffset.x+offx);
			$("#infoWindow").css("bottom",pixelOffset.y);
			
			// Button
			$("#close").click(function(){
				hideInfoWindow(); 
				newCrimeMarker.setMap(null);
				newAlertMarker.setMap(null);
				newLinkMarker.setMap(null);
			}).button({icons: {primary:'ui-icon-cancel'}, text:false});
		}
	};
	
	// Load info window
	var loadInfoWindow = function(marker, content, data) {
		
		// Hide new point buttons
		$("#newPointButtons").fadeOut('fast');
						
		// Call window content
		$.ajax({
			type : "POST",
			url : baseUrl + "index.php/" + content,
			data : data,
			dataType : "html",
			success : function(data) {
				openMarker = marker;
				$("#infoWindowHtml").html(data);
				upDateInfoWindowPosition();
				if(!$.browser.msie){$("#mapCanvas").addClass('ui-widget-overlay');}
				$("#infoWindow").fadeIn('fast');
			},
			error : function() {
				alert(netWorkError);
			}
		});
	};
	
	// Load dialog window
	var loadDialogWindow = function(title, content, data, height) {
	
		// Open Dialog with preloader
		//$("#dialogWindow").dialog('destroy');
		$("#dialogWindow").html("<div id='myDialogWindow'><img src='"+baseUrl+"img/ajax-loader-bar.gif' /></div>");
		
		$("#dialogWindow").dialog( {
			title: title,
			width: 600,
			height: height,
			modal: false,
			position: {y:100}
		});
	
		// Call window content
		if(content){
			$.ajax( {
				type : "POST",
				url : baseUrl + "index.php/" + content,
				data : data,
				dataType : "html",
				success : function(data) {
						$("#dialogWindow").html(data);
					},
				error : function(Xhr, textStatus, errorThrown){
						alert(errorThrown+': '+textStatus);
					}
				});
		}
	};
	
	var loadTweakWindow = function(){
		
		$("#tweakWindow").dialog( {
			title: 'Search Settings',
			width: 600,
			modal: false,
			buttons: {"Close": function(){$(this).dialog("close");}}
		});
	};
	
	// Panorama window
	var loadPanoramaWindow = function(){
						
		// Reload
		$("#panoramaWindow").dialog( {
			title: "Street View",
			width:425,
			height:240,
			modal: false
		});
	};

	// Flash Window
	var loadFlashWindow = function(title, data) {
		//$("#dialogWindow").dialog('destroy');
		$("#dialogWindow").html("<div id='myFlashWindow'>" + data + "</div>");
		$("#dialogWindow").dialog( {
			title : title,
			width : 400
		});
	};


	

	


	
	
	
	
	
	
	
	
	
// SEARCH FUNCTIONS //
	
	// Get all crime
	var getCrimePoints = function(o){
		
		// Set Status
		status = "Fetching crime list";
		
		// Set var
		var crimeArray = [];
		
		// Less icons for ie: 
		if ($.browser.msie){l=50;}else{l=150;}
			
		// Open lots of points
		$.ajax({
			type : "POST",
			url: baseUrl+"index.php/crime/getPoints",
			data:{limit:l},
			dataType: 'json',
			success: function(data){
				if(data){
					$.each(data, function(i, v){crimeArray[i] = {type:'c', data: v};});
						populateCrimeMapAndList(crimeArray);
					}
					$("#newPointButtons").fadeIn('fast');
				},
			complete: function(){
					  if(o){triggerCrimePointClick(o);}
				  }
			});		
	};
	
	// Get single crime point
	var getCrimePoint = function(o){
		
		// Set Status
		status = "Fetching crime info";
		
		// Set var
		var crimeArray = [];
			
		// Open lots of points
		$.ajax({
			type : "POST",
			url: baseUrl+"index.php/crime/getPoint",
			data:{point:o},
			dataType: 'json',
			success: function(data){
				if(data){
					$.each(data, function(i, v){crimeArray[i] = {type:'c', data: v};});
						populateCrimeMapAndList(crimeArray);
					}
					$("#newPointButtons").fadeIn('fast');
				},
			complete: function(){
					  if(o){triggerCrimePointClick(o);}
				  }
			});		
	};
	
	// Get all alerts
	var getAlertPoints = function(o) {
		
		// Hide new alert point marker
		newAlertMarker.setMap(null);
		
		// Check for logged user and give them some info if not.
		if (loggedIn == false){
			note = "Fetching info";
			$("#list").load(baseUrl+"index.php/alert/info");
			return;
		}
		
		// Set var
		note = "Fetching markers";
		var alertArray = [];
		
		$.ajax({
			  type : "POST",
			  url: baseUrl+"index.php/alert/getPoints",
			  dataType: 'json',
			  success: function(data){
				if(data){
				  $.each(data, function(i, v){alertArray[i] = {type:'a', data: v};});
				  populateAlertMapAndList(alertArray);
				}
				else{
					$("#list").load(baseUrl+"index.php/alert/info");
				}
				$("#newPointButtons").fadeIn('fast');
			  },
			 complete: function(){
				  if(o){triggerAlertPointClick(o);}
			  }
		});		
	};
	
	// Get all links
	var getLinkPoints = function(o){
		
		// Hide new alert point marker
		newLinkMarker.setMap(null);
		
		// Check for logged user and give them some info if not.
		if (loggedIn == false){
			note = "Fetching info";
			$("#list").load(baseUrl+"index.php/link/info");
			return;
		}
		
		// Set var
		note = "Fetching markers";
		var linkArray = [];
		
		$.ajax({
			  type : "POST",
			  url: baseUrl+"index.php/link/getPoints",
			  dataType: 'json',
			  success: function(data){
				if(data){
				  $.each(data, function(i, v){linkArray[i] = {type:'l', data: v};});
				  populateLinkMapAndList(linkArray);
				}else{
					$("#list").load(baseUrl+"index.php/link/info");
				}
				$("#newPointButtons").fadeIn('fast');
			  },
			 complete: function(){
				  if(o){triggerLinkPointClick(o);}
			  }
		});		
	};
	
	// Get single link point
	var getLinkPoint = function(o){
		
		// Set Status
		status = "Fetching link info";
		
		// Set var
		var linkArray = [];
			
		// Open lots of points
		$.ajax({
			type : "POST",
			url: baseUrl+"index.php/link/getPoint",
			data:{point:o},
			dataType: 'json',
			success: function(data){
				if(data){
					$.each(data, function(i, v){linkArray[i] = {type:'l', data: v};});
						populateLinkMapAndList(linkArray);
					}
					$("#newPointButtons").fadeIn('fast');
				},
			complete: function(){
					  if(o){triggerLinkPointClick(o);}
				  }
			});		
	};
	
	
	
	
	
	// Search Settings
	var findDMS = function(){

		// Decimal Degrees = degrees + (minutes / 60) + (seconds / 3600)
		var lat = $("[name=northSouth]:checked").val() + (eval($("#dmsTopDeg").val()) + eval($("#dmsTopMin").val() / 60) + eval($("#dmsTopSec").val() / 3600));
		var lng = $("[name=eastWest]:checked").val() + (eval($("#dmsBotDeg").val()) + eval($("#dmsBotMin").val() / 60) + eval($("#dmsBotSec").val() / 3600));
		
		$("#search").val(lat + ", " + lng);
		find();
	};
	
	
	
	


	// Find crime and geocode search
	var find = function() {
		
		// Set var
		var searchArray = [];
		var string = $('#search').val();
		var placeSearchArray = [];
		note = "Searching...";
		
		// Check for empty string
		if(string.length == 0){
			alert("Nothing to search for");
			return false;
		}
		
		// Hide infowindow and clear results
		hideInfoWindow();
		$("#list").empty();
		
		// Record this search in the database
		/*
		$.ajax({
			type : "POST",
			url: baseUrl+"index.php/search/insert",
			data: {search:string}
		});
		*/
		
		
		
		// INPUT TYPE CHECKS
		
			// Check for latLng input
			if ( string.match(/(\+|-)?[0-9]{2}[.][0-9]*[,](\s)?(\+|-)?[0-9]{2}[.][0-9]*/) ){
				
				// Split it
				latLngInput = string.split(",");
				psl = new google.maps.LatLng($.trim(latLngInput[0]), $.trim(latLngInput[1]));
				
				// Setup point info
				ps = new Object(); ps.geometry = new Object();
				ps.id = 1;
				ps.geometry.location = psl;
				ps.area = string;
				ps.formatted_address = "Lat Lng Search";
				ps.geometry.location_type = "Search";
				
				// Hide prev points and empty list
				hideCrimePoints(); hideSearchPoints(); hideLinkPoints(); $("#list").empty();
				
				// Add new point
				addSearchPoint(ps); addSearchItem(ps);
				return;
			}
		

  		// 1. Google Place Search
  		if(geocoder){
  			
  			// Define bounds of S.A (not that this seems to work Google?)
  			var ne = new google.maps.LatLng(-34.967, 16.2817);
  			var sw = new google.maps.LatLng(-22.124724, 33.0469);
			var classData = $("input[name='listRadio']:checked").val();
			var startDate = $("#tweakStartDate").val();
			var endDate = $("#tweakEndDate").val();
  		
  			// Geocode
			geocoder.geocode({'address':string+", South Africa", 'bounds':  new google.maps.LatLngBounds(sw, ne)},
					function(results, status){
						
						if (status == google.maps.GeocoderStatus.OK) {
							
								// Google Results
								$.each(results, function(i, v){v.id = i; placeSearchArray[i] = {type:'p', data:v};});
							
								// Search database
								$.ajax({
									  type : "POST",
									  url: baseUrl+"index.php/"+classData+"/findPoints",
									  dataType: 'json',
									  data: {search:string, startDate:startDate, endDate:endDate},
									  success: function(data){
										  
										// Loop
										  if(data){ 
											$.each(data, function(i, v){
											 searchArray[i] = {type:classData.substring(0,1), data: v};
											});
										  }else{
											  searchArray =  new Array(); // else create empty array
										  }
										  
											// Join arrays
											joinedSearchArray = placeSearchArray.concat(searchArray);
											
											// Populate
											switch(classData){
												case 'crime': populateCrimeMapAndList(joinedSearchArray); break;
												case 'alert' : populateAlertMapAndList(joinedSearchArray); break;
												case 'link': populateLinkMapAndList(joinedSearchArray); break;
											}
									  }
								});
						}
						else{
							
							// Search database
							$.ajax({
								  type : "POST",
								  url: baseUrl+"index.php/"+classData+"/findPoints",
								  dataType: 'json',
								  data: {search:string, startDate:startDate, endDate:endDate},
								  success: function(data){
									  
									  if(data){
										  
										  // Loop
										  $.each(data, function(i, v){
											  searchArray[i] = {type:classData.substring(0,1), data: v};
										  });
									  
										  // Join arrays
										  joinedSearchArray = placeSearchArray.concat(searchArray);
										
										  // Populate
										  switch(classData){
											case 'crime': populateCrimeMapAndList(joinedSearchArray); break;
											case 'alert' : populateAlertMapAndList(joinedSearchArray); break;
											case 'link': populateLinkMapAndList(joinedSearchArray); break;
										  }
									  }else{
										  $("#list").html("<p style='padding:8px;'>No results found.</p>");
									  }
								  }
							});
						}
					});
			}
			else{alert("Geocoder is missing?");}
	};
	
	// Loops to populate the crime map and list fields
	var populateCrimeMapAndList = function(data){
		
		// Hide old Points and results
		hideSearchPoints(); hideCrimePoints(); $("#list").empty(); $("#list").show(); 
		
		// Loop
		$.each(data, function(i, v) {
			
			switch(v.type){
				case 'c' : addCrimePoint(v.data); addCrimeItem(v.data); break;
				case 'p' : addSearchPoint(v.data); addSearchItem(v.data); break;
			}
		});
	};
	
	// Loops to populate the alert map and list fields
	var populateAlertMapAndList = function(data){
		
		// Hide old Points and results
		hideSearchPoints(); hideAlertPoints(); $("#list").empty(); $("#list").show();
		
		// Loop
		$.each(data, function(i, v) {
			
			switch(v.type){
				case 'a' : addAlertPoint(v.data); addAlertItem(v.data); break;
				case 'p' : addSearchPoint(v.data); addSearchItem(v.data); break;
			}
		});
	};
	
	var populateLinkMapAndList = function(data){
		
		// Hide old Points and results
		hideSearchPoints(); hideLinkPoints(); $("#list").empty(); $("#list").show();
		
		// Loop
		$.each(data, function(i, v) {
			
			switch(v.type){
				case 'l' : addLinkPoint(v.data); addLinkItem(v.data); break;
				case 'p' : addSearchPoint(v.data); addSearchItem(v.data); break;
			}
		});
	};
	
	var populateSearchMapAndList = function(data){
		
		// Hide old Points and results
		hideSearchPoints(); hideSearchItems(); $("#list").empty(); $("#list").show();
		
		// Loop
		$.each(data, function(i, v) {
			
			switch(v.type){
				case 'p' : addSearchPoint(v.data); addSearchItem(v.data); break;
			}
		});
	};
	
	// Load a single crime point
	var addCrimePoint = function(v) {
			
		// Make point
		latLng = new google.maps.LatLng(v.lat, v.lng);
	
		// Add marker
		crimeMarkers[v.id] = new google.maps.Marker( {
			id:v.id,
			tagIds: v.tagIds,
			position : latLng,
			map : map,
			icon : crimeImage,
			draggable : false,
			zIndex : 0,
			title : "#" + v.id + ": " + v.copy
		});
	
		// Marker Click
		google.maps.event.addListener(crimeMarkers[v.id], 'click', function() {
			data = {cId : v.id};
			hideInfoWindow();
			loadInfoWindow(crimeMarkers[v.id], "crime/getPointInfo", data);
		});
	};
	
	// Load a single alert point
	var addAlertPoint = function(v) {
	
		// Make point
		latLng = new google.maps.LatLng(v.lat, v.lng);
		
		// Add marker
		alertMarkers[v.id] = new google.maps.Marker( {
			position : latLng,
			map : map,
			icon : alertImage,
			draggable : false,
			radius : v.radius,
			aId : v.id,
			zIndex : 99,
			title : "Alert #" + v.id
		});
	
		// Marker Click
		google.maps.event.addListener(alertMarkers[v.id], 'click', function() {
			if(!rCircle.getMap()){rCircle.setMap(map);}
			rCircle.setOptions(findrCirclePolygons(this.position, this.radius));
			data = {aId : v.id};
			hideInfoWindow();
			loadInfoWindow(alertMarkers[v.id], "alert/getPointInfo", data);
		});
	
		// Add marker position changed functions
		google.maps.event.addListener(alertMarkers[v.id], 'drag', function() {
			rCircle.setOptions(findrCirclePolygons(this.getPosition(), this.radius));
			upDateInfoWindowPosition();
		});
		
		// Transparent
		google.maps.event.addListener(alertMarkers[v.id], 'dragstart', function() {$("#infoWindow").addClass('transparent');});
		google.maps.event.addListener(alertMarkers[v.id], 'dragend', function() {$("#infoWindow").removeClass('transparent');});
	
		// Stop Drag
		google.maps.event.addListener(alertMarkers[v.id], 'dragend', function() {
	
			// Save new position
				$.ajax( {
					type : "POST",
					url : baseUrl + "index.php/alert/updatePosition/",
					data : {
						latLng : "'" + this.getPosition() + "'",
						aId : this.aId
					},
					error : function() {
						alert("Error, could not save new maker position.");
					}
				});
			});
	};
	
	// Load a single search point
	var addLinkPoint = function(v) {
		
		// Make point
		latLng = new google.maps.LatLng(v.lat, v.lng);
				
		// Add marker
		linkMarkers[v.id] = new google.maps.Marker( {
			position : latLng,
			map : map,
			icon : linkImage,
			draggable : false,
			lId:v.id,
			zIndex : 0,
			title : "Link #" + v.id
		});
	
		// Marker Click
		google.maps.event.addListener(linkMarkers[v.id], 'click', function() {
			data = {lId : v.id};
			hideInfoWindow();
			loadInfoWindow(linkMarkers[v.id], "link/getPointInfo", data);
		});
		
		// Add marker position changed functions
		google.maps.event.addListener(linkMarkers[v.id], 'drag', function() {
			upDateInfoWindowPosition();
		});
		
		// Transparent
		google.maps.event.addListener(linkMarkers[v.id], 'dragstart', function() {$("#infoWindow").addClass('transparent');});
		google.maps.event.addListener(linkMarkers[v.id], 'dragend', function() {$("#infoWindow").removeClass('transparent');});
	
		
		// Stop Drag
		google.maps.event.addListener(linkMarkers[v.id], 'dragend', function() {
	
			// Save new position
				$.ajax( {
					type : "POST",
					url : baseUrl + "index.php/link/updatePosition/",
					data : {
						latLng : "'" + this.getPosition() + "'",
						lId : this.lId
					},
					error : function() {
						alert("Error, could not save new maker position.");
					}
				});
			});
	};
		
	// Load a single search point
	var addSearchPoint = function(v) {
				
		// Add marker
		searchMarkers[v.id] = new google.maps.Marker({
			position : v.geometry.location,
			map : map,
			icon : searchImage,
			draggable : false,
			zIndex : 0,
			title : "#" + v.id + ": " + v.geometry.location_type
		});
	
		// Marker Click
		google.maps.event.addListener(searchMarkers[v.id], 'click', function() {
			data = {sId : v.id};
			hideInfoWindow();
			loadInfoWindow(searchMarkers[v.id], "search/getPointInfo", data);
		});
	};
		
	// Ads crime item to list
	var addCrimeItem = function(v){
		
		// Null areas
		if(v.area == null){v.area = v.address;}
		
		// Append
		$("#list").append(
			"<div id='crimeItemDiv"+v.id+"' class='crimeItem' onClick=\"triggerCrimePointClick("+ v.id + ");\">" +
				"<table id='crimeItem"+v.id+"' class='pointer'>" +
				"<tr>" +
					"<td><div id='crimeItemSmallIcon"+v.id+"' class='crimeSmallMarker'></div></td>" +
					"<td><h3>"+v.area+"</h3><strong>"+v.tags+"</strong><br/><small>"+v.date+"</small></td>" +
					"</tr>" +
				"</table><br/>"+
			"</div>");
		
		// Mouse over
		$("#crimeItemDiv"+v.id).mouseenter(function(){
			updateLineCanvas(v.id, 'crime');
		}).mouseleave(function(){
			hideLineCanvas(v.id, 'crime');
		});
	};
		
	// Ads alert item to list
	var addAlertItem = function(v) {
		
		// Null titles
		if(v.title == null){v.title = 'New Alert #'+v.id;} // Fix null title
		
		// Append
		$("#list").append(
			"<div id='alertItemDiv"+v.id+"' class='alertItem' onClick=\"triggerAlertPointClick("+ v.id + ");\">" +
				"<table id='alertItem"+v.id+"' class='pointer'>" +
				"<tr>" +
				"<td><div id='alertItemSmallIcon"+v.id+"' class='alertSmallMarker'></div></td>" +
					"<td><h3 id='aId_title_"+v.id+"'>"+v.title+"</h3><strong>#"+v.id+"</strong><br/></td>" +					
					"</tr>" +
				"</table><br/>" +
			"</div>");
		
		// Mouse over
		$("#alertItem"+v.id).mouseover(function(){
			updateLineCanvas(v.id, 'alert');
		}).mouseout(function(){
			hideLineCanvas(v.id, 'alert');
		});
	};
	
	// Ads link item to list
	var addLinkItem = function(v) {
		
		// Null titles
		if(v.title == null){v.title = 'New Link #'+v.id;} // Fix null title
		
		// Append
		$("#list").append(
			"<div id='linkItemDiv"+v.id+"' class='linkItem' onClick=\"triggerLinkPointClick("+ v.id + ");\">" +
				"<table id='linkItem"+v.id+"' class='pointer'>" +
				"<tr>" +
				"<td><div id='linkItemSmallIcon"+v.id+"' class='linkSmallMarker'></div></td>" +
					"<td><h3>"+v.title+"</h3><span>"+v.subTitle+"</span></td>" +					
					"</tr>" +
				"</table><br/>" +
			"</div>");
		
		// Mouse over
		$("#linkItem"+v.id).mouseover(function(){
			updateLineCanvas(v.id, 'link');
		}).mouseout(function(){
			hideLineCanvas(v.id, 'link');
		});
	};
		
	// Ads search item to list
	var addSearchItem = function(v){
				
		// Null areas
		if(v.area == null){v.area = v.address;}
		
		// Append
		$("#list").append(
			"<div id='searchItemDiv"+v.id+"' class='searchItem' onClick=\"triggerSearchPointClick("+ v.id + ");\">" +
			"<table id='searchItem"+v.id+"' class='pointer'>" +
				"<tr>" +
				"<td><div id='searchItemSmallIcon"+v.id+"' class='searchSmallMarker'></div></td>" +
					"<td><h3>"+v.formatted_address.replace(', South Africa', "")+"</h3>"+v.geometry.location_type+"<br/>"+v.geometry.location+"</td>" +
				"</tr>" +
				"</table><br/>" +
			"</div>");
		
		// Mouse over
		$("#searchItem"+v.id).mouseover(function(){
			updateLineCanvas(v.id, 'search');
		}).mouseout(function(){
			hideLineCanvas(v.id, 'search');
		});
	};
		
	// Hides all the crime markers
	var hideCrimePoints = function() {
		$.each(crimeMarkers, function(i, v) {
			this.setMap(null);
		});
		//newCrimeMarker.setMap(null);
	};
	
	// Hides all the alert markers
	var hideAlertPoints = function() {
		if(rCircle.getMap()){rCircle.setMap(null);}
		$.each(alertMarkers, function(i, v) {
			this.setMap(null);
		});
		//newAlertMarker.setMap(null);
	};
	
	// Hides all the search markers
	var hideLinkPoints = function() {
		$.each(linkMarkers, function(i, v) {
			this.setMap(null);
		});
		//newLinkMarker.setMap(null);
	};
	
	// Hides all the search markers
	var hideSearchPoints = function() {
		$.each(searchMarkers, function(i, v) {
			this.setMap(null);
		});
	};

	// Removes all the search items injected into current list
	var hideSearchItems = function() {
		$(".searchItem").remove();
	};
	
	// Trigers the listening event on the chosen crime marker
	var triggerCrimePointClick = function(id) {
		google.maps.event.trigger(crimeMarkers[id], 'click');
		map.setCenter(crimeMarkers[id].getPosition());
		return false;
	};
	
	// Triggers the listening event on the chosen alert marker
	var triggerAlertPointClick = function(id) {
		google.maps.event.trigger(alertMarkers[id], 'click');
		map.setCenter(alertMarkers[id].getPosition());
		return false;
	};
	
	// Triggers the listening event on the chosen link marker
	var triggerLinkPointClick = function(id) {
		google.maps.event.trigger(linkMarkers[id], 'click');
		map.setCenter(linkMarkers[id].getPosition());
		return false;
	};
	
	// Trigers the listening event on the chosen search marker
	var triggerSearchPointClick = function(id) {
		google.maps.event.trigger(searchMarkers[id], 'click');
		map.setCenter(searchMarkers[id].getPosition());
		return false;
	};
	
	
	// New Crime Point
	var newCrimePoint = function(c) {
		
		if(c){
			var c = c.getPosition();
		}
		else{
			var c = map.getCenter();
		}
		
		// Place the marker and load the wizard
		newCrimeMarker.setOptions({map:map, position:c, zIndex:250});
		google.maps.event.trigger(newCrimeMarker, 'click');
	};
	
	// New Alert Point
	var newAlertPoint = function(a) {
		
		if(a){
			var a = a.getPosition();
		}
		else{
			var a = map.getCenter();
		}
		
		// Place the marker and load the wizard
		newAlertMarker.setOptions({map:map, position:a, zIndex:250});
		google.maps.event.trigger(newAlertMarker, 'click');
	};

	// New Link Point
	var newLinkPoint = function(l) {
		
		if(l){
			var l = l.getPosition();
		}
		else{
			var l = map.getCenter();
		}
		
		// Place the marker and load the wizard
		newLinkMarker.setOptions({map:map, position:l, zIndex:250});
		google.maps.event.trigger(newLinkMarker, 'click');
	};
	
	// Delete crime point
	var delCrimePoint = function(cId) {
		
		var cId = cId;
		
		$.ajax( {
			type : "POST",
			url : "index.php/crime/delPoint",
			data : {
				cId : cId
			},
			success : function() {
				crimeMarkers[cId].setMap(null);
				newCrimeMarker.setMap(null);
				$("#crimeItemDiv"+cId).remove();
				hideInfoWindow();
			},
			error : function() {
				alert(netWorkError);
			}
		});
	};
	
	// Delete alert point
	var delAlertPoint = function(aId) {
		
		var aId = aId;
		
		$.ajax( {
			type : "POST",
			url : "index.php/alert/delPoint",
			data : {
				aId : aId
			},
			success : function() {
				alertMarkers[aId].setMap(null);
				$("#alertItemDiv"+aId).remove();
				if(rCircle.getMap()){rCircle.setMap(null);}
				hideInfoWindow();
			},
			error : function() {
				alert(netWorkError);
			}
		});
	};
	
	// Delete link point
	var delLinkPoint = function(lId){
		
		var lId = lId;
		
		$.ajax( {
			type : "POST",
			url : "index.php/link/delPoint",
			data : {
				lId : lId
			},
			success : function() {
				linkMarkers[lId].setMap(null);
				$("#linkItemDiv"+lId).remove();
				hideInfoWindow();
			},
			error : function() {
				alert(netWorkError);
			}
		});		
	};
	
	// Delete search point (just a simple remove)
	var delSearchPoint = function(sId){
		
		var sId = sId;
		
		searchMarkers[sId].setMap(null);
		$("#searchItemDiv"+sId).remove();
		hideInfoWindow();	
	};
	
	// Edit Crime Point (rerun the wizard)
	var editCrimePoint = function(c, data) {
		// Place the marker and load the wizard
		newCrimeMarker.setOptions( {
			map : map,
			position : c
		});
		
		if(loggedIn){
			loadInfoWindow(newCrimeMarker, "report/step2", data);
		}else{
			alert(pleaseLogIn);
		}
	};
	


	

	

	

	

	
	
	













	
	
	
	
	
	
	
	
	
// USER //
		
	// Logs user into the site via the standard login form
	var connect = function(){
				
		// Get variables
		var email = $("#userLoginEmail").val();
		var password = $("#userLoginPassword").val();
		
		// Check it
		$.ajax( {
			type : "POST",
			url : baseUrl + "index.php/login/doLogin",
			data : {email:email, password:password},
			dataType : 'json',
			success : function(cookieString) {
				if(cookieString){
					setConnectCookie(cookieString);
					userSignin();
				}else{
					userSignout(); // make sure cookie is removed.
					alert("Thats not it."); // @todo bring in popup window.
				}
			},
			error : function() {
				userSignout(); // make sure cookie is removed.
				alert("Error, we could not log you in.");
			}
		});
				
	};
	
	// Sets the cookie to allow access when things get saved
	var setConnectCookie = function(string){
		
		// Set it
		$.setCookie("alertZaConnect", string, false);
		
		// Log user out when cookie expires
		setTimeout("userSignOut()",60000*60);
	};
	
	
	// Gets all user details
	var user_getDetails = function() {
	
		// Pull details
		$.getJSON(baseUrl+"index.php/user/getInfo", function(data) {
	
			if(data){
				
				// Set user's email and mobile number
				if(data.email){$("#userEmail").html(data.email);}
				if(data.mobile){$("#userMobile").html(data.mobile);}
				if(data.name){$("#userName").html(data.name); $("#userButton").button( "option", "label", data.name);}
				
				// Ask user to confirm email address
				if(data.eConfirmed == 0){
					$("#unconfirmedEmail").show().click(function(){loadDialogWindow("Resending email confirmation", 'email/setEmail', {email : data.email}, 120);});
				}				
								
				// Ask user to confirm mobile number
				if(data.mConfirmed == 0){
					$("#unconfirmedMobile").show().click(function(){loadDialogWindow("Setting Mobile Number", 'mobile/setMobile', {mobile : data.mobile}, 120);});
				}
				
				// Set users after hours settings.
				$("input[name='smsAfterHrsTimeFrame']").each(function(){
					if($(this).val() == data.smsAfterHrsTimeFrame){
						$(this).attr('checked', 'checked');
					}
				});
				
			}else{
				alert("No user data found?");
			}
			
		});
	};
	
	
	
	
	
	
	
	
	
	
// MAP PROPERTIES //

	// Load the google map with peroperties
	var initializeMap = function() {
	
		// Find prev position and zoom		
		var mapSettings = $.getCookie("alertZaSetup");
	
		// Options
		options = {
			mapTypeControl : false,
			navigationControl : true,
			streetViewControl: true,
			scrollwheel: mapSettings.scrollwheel,
			navigationControlOptions : {
				style : google.maps.NavigationControlStyle.LARGE,
				position : google.maps.ControlPosition.RIGHT
			},
			zoom : mapSettings.zoom,
			center : new google.maps.LatLng(mapSettings.lat, mapSettings.lng)
		};
	
		// Google map images
		crimeImage = new google.maps.MarkerImage(baseUrl + 'img/markers.png', new google.maps.Size(19, 32), new google.maps.Point(19, 0));
		alertImage = new google.maps.MarkerImage(baseUrl + 'img/markers.png', new google.maps.Size(19, 32), new google.maps.Point(38, 0));
		linkImage = new google.maps.MarkerImage(baseUrl + 'img/markers.png', new google.maps.Size(19, 32), new google.maps.Point(57, 0));
		searchImage = new google.maps.MarkerImage(baseUrl + 'img/markers.png', new google.maps.Size(19, 32), new google.maps.Point(0, 0));
		selectedImage = new google.maps.MarkerImage(baseUrl + 'img/markers.png', new google.maps.Size(19, 32), new google.maps.Point(0, 0));
		newImage = new google.maps.MarkerImage(baseUrl + 'img/markers.png', new google.maps.Size(19, 32), new google.maps.Point(76, 0));
		placeImage = new google.maps.MarkerImage(baseUrl + 'img/placeMarker.png', new google.maps.Size(16, 16), new google.maps.Point(0, 0), new google.maps.Point(8, 8));
		
		// Create Map
		map = new google.maps.Map(document.getElementById("mapCanvas"), options);
		google.maps.event.addListener(map, 'idle', upDateInfoWindowPosition);
		google.maps.event.addListener(map, 'center_changed', upDateInfoWindowPosition);
		google.maps.event.addListener(map, 'zoom_changed', changedZoom);
		google.maps.event.addListener(map, 'center_changed', changedCenter);
		
		geocoder = new google.maps.Geocoder();
		
		// Street view
		panoramaOptions = {position: map.getCenter(), pov: {heading: 34, pitch: 10, zoom: 1}};
		panorama = new google.maps.StreetViewPanorama(document.getElementById("panoramaWindow"));
		map.setStreetView(panorama);
	    google.maps.event.addListener(panorama, 'links_changed', function() {loadPanoramaWindow();});
	  
		// New Crime Marker properties
		newCrimeMarker = new google.maps.Marker({
			icon : newImage,
			draggable : true
		});
		
			google.maps.event.addListener(newCrimeMarker, 'click', function() {
				loadInfoWindow(newCrimeMarker, "report/step1");
			});
			
			google.maps.event.addListener(newCrimeMarker, 'drag', function() {
				upDateInfoWindowPosition();
			});
			
			google.maps.event.addListener(newCrimeMarker, 'dragstart', function() {
				$("#infoWindow").addClass('transparent');
			});
			
			google.maps.event.addListener(newCrimeMarker, 'dragend', function() {
				$("#infoWindow").removeClass('transparent');
			});
			
		// New Alert Marker properties
		newAlertMarker = new google.maps.Marker({
			icon : newImage,
			draggable : true
		});
		
			google.maps.event.addListener(newAlertMarker, 'click', function() {
				loadInfoWindow(newAlertMarker, "alert/newPoint", {position:"'"+newAlertMarker.getPosition()+"'"});
			});
			
			google.maps.event.addListener(newAlertMarker, 'drag', function() {
				upDateInfoWindowPosition();
			});
			
			google.maps.event.addListener(newAlertMarker, 'dragstart', function() {
				$("#infoWindow").addClass('transparent');
			});
			
			google.maps.event.addListener(newAlertMarker, 'dragend', function() {
				$("#infoWindow").removeClass('transparent');
			});
			
		// New Link Marker properties
		newLinkMarker = new google.maps.Marker({
			icon : newImage,
			draggable : true
		});
		
			google.maps.event.addListener(newLinkMarker, 'click', function() {
				loadInfoWindow(newLinkMarker, "link/newPoint", {position:"'"+newLinkMarker.getPosition()+"'"});
			});
			
			google.maps.event.addListener(newLinkMarker, 'drag', function() {
				upDateInfoWindowPosition();
			});
			
			google.maps.event.addListener(newLinkMarker, 'dragstart', function() {
				$("#infoWindow").addClass('transparent');
			});
			
			google.maps.event.addListener(newLinkMarker, 'dragend', function() {
				$("#infoWindow").removeClass('transparent');
			});
		
		// Alert Radius (rCircle)
		rCircle = new google.maps.Circle();
			
		// Set Center
		center = map.getCenter();
	
		// Update info
		changedCenter();
		changedZoom();
	};
	
	// Functions to run when the zoom is changed on the map
	var changedCenter = function() {
	
		// Update Center
		center = map.getCenter();
		
		// Remember Last Position
		j = $.getCookie("alertZaSetup");
		j.lat = map.getCenter().lat();
		j.lng = map.getCenter().lng();
		$.setCookie("alertZaSetup", j, true);
	
	};
	
	// Functions to run when the center is changed on the map
	var changedZoom = function() {
	
		// Remember Last Zoom
		j = $.getCookie("alertZaSetup");
		j.zoom = map.getZoom();
		$.setCookie("alertZaSetup", j, true);
	
	};
	
	// Lock map
	var lockMap = function(){
		map.setOptions({'draggable':false});
	};
	
	// unLock map
	var unlockMap = function(){
		map.setOptions({'draggable':true});
	};
	
	// Set and change colors (must be run after ajax is complete and after each call)
	var colorSetText = function(){
		
		// Find current Mode
		switch($("input[name='listRadio']:checked").val()){
			case "crime" :
				$("em, .crimeItem").removeClass("blue").removeClass("green");
				$(".crimeItem").hover(function(){$(this).addClass("orange");}, function(){$(this).removeClass("orange");});
				$("em").addClass("orange");
			break;

			case "alert" :
				$("em, .alertItem").removeClass("orange").removeClass("green");
				$(".alertItem").hover(function(){$(this).addClass("blue");}, function(){$(this).removeClass("blue");});
				$("em").addClass("blue");			
			break;
			
			case "link" :
				$("em, .linkItem").removeClass("orange").removeClass("blue");
				$(".linkItem").hover(function(){$(this).addClass("green");}, function(){$(this).removeClass("green");});
				$("em").addClass("green");			
			break;
		};
	};








	
	
// SETTINGS BUTTONS AND CLICKS //
	
	// Change Map Type
	var setting_changeMapType = function() {
		
		// Bind
		$("#changeMapType").bind('change', function(){
		
			var t = $("#changeMapType option:selected").val();
			switch (t) {
				case '1': map.setMapTypeId(google.maps.MapTypeId.ROADMAP); break;
				case '2': map.setMapTypeId(google.maps.MapTypeId.HYBRID); break;
				case '3': map.setMapTypeId(google.maps.MapTypeId.SATELLITE); break;
				case '4': map.setMapTypeId(google.maps.MapTypeId.TERRAIN); break;
			}
			
			// Remember Last Map Type
			j = $.getCookie("alertZaSetup");
			j.mapType = t;
			$.setCookie("alertZaSetup", j, true);
		});
		
		// 1st time load
		$("#changeMapType").trigger('change');
	};
	
	// Change Map Theme
	var setting_changeTheme = function() {
		
		// Bind
		$("#changeTheme").bind('change', function(){
		
			var t = $("#changeTheme option:selected").val();
			switch (t) {
				
				// Eggplant (Default)
				case '1': 
					$("#uiCustomStyle").attr("href", baseUrl+"system/application/front/views/templates/web/css/eggplant/jquery-ui-1.8.6.custom.css");
					$("#uiColorStyle").attr("href", "");
				break;
				
				// Redmond
				case '2': 
					$("#uiCustomStyle").attr("href", baseUrl+"system/application/front/views/templates/web/css/redmond/jquery-ui-1.8.6.custom.css");
					$("#uiColorStyle").attr("href", baseUrl+"system/application/front/views/templates/web/css/redmond/colors.css");
				break;
			}
			
			// Remember Last Theme
			j = $.getCookie("alertZaSetup");
			j.theme = t;
			$.setCookie("alertZaSetup", j, true);
		});
		
		// 1st time load
		$("#changeTheme").trigger('change');
	};
	
	// Stop mouse from zooming over google map
	var setting_scrollwheel = function(){
				
		// Bind
		$("#scrollwheel").bind('change', function(){
			if($(this).is(":checked")){
				
				// Set map option
				map.setOptions({'scrollwheel':true});
				
				// Set cookie
				j = $.getCookie("alertZaSetup");
				j.scrollwheel = 1;
				$.setCookie("alertZaSetup", j, true);
			}else{
				
				// Set map option
				map.setOptions({'scrollwheel':false});
				
				// set cookie
				j = $.getCookie("alertZaSetup");
				j.scrollwheel = 0;
				$.setCookie("alertZaSetup", j, true);
			}
		});
		
		// 1st time load
		j = $.getCookie("alertZaSetup");
		s = j.scrollwheel;
		if(s == 1){$("#scrollwheel").attr('checked',true);}else{$("#scrollwheel").removeAttr('checked');}
	};

        // Change from full screen mode
	var setting_fullScreen = function(){

		// Bind
		$("#fullScreen").bind('change', function(){
			if($(this).is(":checked")){

				// Set map option
				$("#wrapper").css('width', '100%');

				// Set cookie
				j = $.getCookie("alertZaSetup");
				j.fullScreen = 1;
				$.setCookie("alertZaSetup", j, true);
			}else{

				// Set map option
				$("#wrapper").css('width', smallScreenWidth);

				// set cookie
				j = $.getCookie("alertZaSetup");
				j.fullScreen = 0;
				$.setCookie("alertZaSetup", j, true);
			}

            // Fix screen width
            setTimeout("fixDimensions();",500);
		});

        // 1st time load
		$("#fullScreen").trigger('change');
	};










// USER BUTTONS, CLICKS AND LINKS //

	// Saving Email Address
	var user_saveEmail = function() {
		$("#userEmail").editable(function(v, s){
			loadDialogWindow("Setting Email Address", 'email/setEmail', {email : v});
			return(v);
	    },{
		    submit  : 'OK'
		});	
	};
	
	// Saving Mobile Number
	var user_saveMobile = function() {
		$("#userMobile").editable(function(v, s){
			loadDialogWindow("Setting Mobile Number", 'mobile/setMobile', {mobile : v});
			return(v);
	    },{
		    submit  : 'OK'
		});	
	};
	
	// Saving user Name
	var user_saveName = function(){
		$("#userName").editable(function(v, s){
			loadDialogWindow("Setting your name", 'user/setName', {name : v});
			return(v);
	    },{
		    submit  : 'OK'
		});	
	};
	
	// If the user needs there password reset
	var user_changePassword = function(){
		loadDialogWindow("Change Password", "user/changePassword", null, 300);
	};
	
	// If the user forgot there login details
	var userGetLoginDetails = function(){
		loadDialogWindow("Reset password", "user/getNewPassword", null, 300);
	};
	
	// Save afterHourAlerts time frame
	var user_smsAfterHrsTimeFrame = function(){	
		$("input[name='smsAfterHrsTimeFrame']").each(function(){
			$(this).click(function(){
				$.ajax( {
					type : "POST",
					url : baseUrl + "index.php/setting/smsAfterHrsTimeFrame/",
					data : {frame : $(this).val()},
					error : function() {alert(netWorkError);}
				});
			});
		});
	};
		
	// Logout
	var userSignout = function(){
		
		// Remove Cookie
		$.endCookie("alertZaConnect");
		
		// Set View State
		$("#signinDropdownButton").show();
		$("#signoutDropdownButton").hide();
		$("#userDropdownButton").hide();
		
		// Close tool bar
		toolBarToolsReset();
		
		// Let Js know
		loggedIn = false;
		
		// Trigger Current display mode
		triggerModeClick();
		
		// Show Welcome info
		$("#welcomeHolder").show();
	};
	
	// login
	var userSignin = function(){
		
		// Set View State
		$("#signinDropdownButton").hide();
		$("#signoutDropdownButton").show();
		$("#userDropdownButton").show();
		
		// Close tool bar
		toolBarToolsReset();
		
		// Populate the users properties
		user_getDetails();
		
		// Let Js know
		loggedIn = true;
		
		// Trigger Current display mode to refresh it
		triggerModeClick();
		
		// Hide Welcome info
		$("#welcomeHolder").hide();
	};
	
	// Register
	var userRegister = function(){
		hideInfoWindow();
		loadDialogWindow('Register', 'login/registerWindow', null, 360);
	};
	
	// Remove user logo
	var unlinkLogo = function(){
		$.ajax( {
			type : "POST",
			url : baseUrl + "index.php/user/unlinkLogo/",
			data : {frame : $(this).val()},
			error : function() {alert(netWorkError);}
		});
	};
	
	// Upload user logo

	// Terms
	var terms = function(){
		hideInfoWindow();
		loadDialogWindow('Terms of use', 'watch/terms', null, 550);
	};
	
	
	
	
	
	
	
	
	
// TOOL BAR //
		
	// Variables
	var toolBar = new Object(); toolBar.clicked=false; toolBar.active=false; toolBar.prev=false;
	
	// Working toolbar
	var toolBarTools = function(){
		
		// Toggle Click (Dont use jQuery toggle here)
		$(".toolsRadio").click(
			function(){ 
				if(toolBar.clicked == false){
					toolBar.clicked = true;
					$(this).trigger('mouseover');
				}else{
					toolBar.clicked = false;
					$("#"+toolBar.prev).slideUp('fast');
				}
			}
		);
				
		$(".toolsRadio").mouseover(function(){
			
			if(toolBar.clicked){
				
				toolBar.active = $(this).attr('value');
				
				if(toolBar.active !== toolBar.prev){
					$("#"+toolBar.prev).slideUp('fast');
				}
							
				$("#"+toolBar.active).css('left', $(this).offset().left+3);
				$("#"+toolBar.active).css('top', $(this).offset().top+35);
				$("#"+toolBar.active).slideDown('fast');
			
				toolBar.prev = toolBar.active;
			}
		});
		
		// Modify button properties
		$("#signinDropdownButton").button({icons: {primary:'ui-icon-key'}, text:true});
		$("#signoutDropdownButton").button({icons: {primary:'ui-icon-key'}, text:false});
		$("#userDropdownButton").button({icons: {primary:'ui-icon-person'}, text:true});
		$("#settingsDropdownButton").button({icons: {primary:'ui-icon-gear'}, text:false});
	};
	
	// Reset tool bar
	var toolBarToolsReset = function(){
		$("#"+toolBar.prev).slideUp('fast');
		toolBar.clicked=false; toolBar.active=false; toolBar.prev=false;
	};


	
	
	
// Attempts to fix anything gone funny
var refresh = function(){
	$('#loader').hide();
	$('#search').attr('value','');
	unlockMap();
	triggerModeClick();
};







/* MODE STATES */

	var triggerModeClick = function(){
		
		// Find current Mode
		switch($("input[name='listRadio']:checked").val()){
			case "crime" : modeCrime(); break;
			case "alert" : modeAlert(); break;
			case "link" : modeLink(); break;
		}
	};
	
	// Crime Mode
	var modeCrime = function(){
		$("#crimeNewPoint, #welcomeCrime").show();
		$("#alertNewPoint, #welcomeAlert").hide();
		$("#linkNewPoint, #welcomeLink").hide();
		hideInfoWindow();
		hideAlertPoints();
		hideLinkPoints();
		
		// Check for open point
		if(openCId > 0){
			getCrimePoint(openCId);
			openCId = 0; // clear, prevents from laoding open point when user changes mode
		}else{
			getCrimePoints();
		}
	};
	
	// Alert Mode
	var modeAlert = function(){
		$("#crimeNewPoint, #welcomeCrime").hide();
		$("#alertNewPoint, #welcomeAlert").show();
		$("#linkNewPoint, #welcomeLink").hide();
		hideInfoWindow();
		hideCrimePoints();
		getAlertPoints();
		hideLinkPoints();
	};
	
	// Link Mode
	var modeLink = function(){
		$("#crimeNewPoint, #welcomeCrime").hide();
		$("#alertNewPoint, #welcomeAlert").hide();
		$("#linkNewPoint, #welcomeLink").show();
		hideInfoWindow();
		hideCrimePoints();
		hideAlertPoints();
		getLinkPoints();
		
		// Check for open point
		if(openLId > 0){
			getLinkPoint(openLId);
			openLId = 0; // clear, prevents from laoding open point when user changes mode
		}
	};
	
	
	
	
	
	
	
	
	
/* CANVAS TAG */
	
	function updateLineCanvas(markerId, mode)
	{
		
		// Find current mode		
		switch(mode){
		
			case "crime" :
				var markerIcon = crimeMarkers[markerId];
				var markerItem = $("#crimeItem"+markerId);
				var markerItemSmallIcon = $("#crimeItemSmallIcon"+markerId);
				var lineColor = orange;
			break;
			
			case "alert" :
				var markerIcon = alertMarkers[markerId];
				var markerItem = $("#alertItem"+markerId);
				var markerItemSmallIcon = $("#alertItemSmallIcon"+markerId);
				var lineColor = blue;
			break;
			
			case "link" :
				var markerIcon = linkMarkers[markerId];
				var markerItem = $("#linkItem"+markerId);
				var markerItemSmallIcon = $("#linkItemSmallIcon"+markerId);
				var lineColor = green;
			break;
			
			case "search" :
				var markerIcon = searchMarkers[markerId];
				var markerItem = $("#searchItem"+markerId);
				var markerItemSmallIcon = $("#searchItemSmallIcon"+markerId);
				var lineColor = green;
			break;
		}
		
		// Set variables
		var canvasEl = $("#drawCanvas")[0];
		canvasEl.width=$("#drawCanvas").width();
		canvasEl.height=$("#drawCanvas").height();
		
		// Change z-index and icon
		markerIcon.setZIndex(250);
		
		// Change text
		//CmarkerItem.addClass('green');
		x=(markerItemSmallIcon.backgroundPositionX());
		markerItemSmallIcon.css('background-position', x+' 15px');
		
		// Ie does not support canvas
		if($.browser.msie){return;}
		
		// Find item offset
		var offset = markerItemSmallIcon.offset();
		
		// Get dimensions of map and find marker offset
		var scale = Math.pow(2, map.getZoom());
		var nw = new google.maps.LatLng(
		    map.getBounds().getNorthEast().lat(),
		    map.getBounds().getSouthWest().lng()
		);
		var worldCoordinateNW = map.getProjection().fromLatLngToPoint(nw);
		var worldCoordinate = map.getProjection().fromLatLngToPoint(markerIcon.getPosition());
		var pixelOffset = new google.maps.Point(
		    Math.floor((worldCoordinate.x - worldCoordinateNW.x) * scale),
		    Math.floor((worldCoordinate.y - worldCoordinateNW.y) * scale)
		);
		
		// Make sure we don't execute when canvas isn't supported		
		if (canvasEl.getContext){

		    // use getContext to use the canvas for drawing
		    var ctx = canvasEl.getContext('2d');
		    ctx.beginPath();
		    ctx.strokeStyle = lineColor;
		    ctx.lineWidth = 1.2;
		    ctx.moveTo(offset.left-20,offset.top-45);
		    ctx.bezierCurveTo(offset.left-20,offset.top-45,pixelOffset.x,offset.top-35,pixelOffset.x,pixelOffset.y);
		    ctx.stroke();
		  }
		
		// Show it
		$("#drawCanvas").show();
	}
	
	function hideLineCanvas(markerId, mode){
				
		// Hide canvas
		$("#drawCanvas").hide();
		
		// Find current mode
		switch(mode){
			
			case "crime" :
				var markerItemSmallIcon = $("#crimeItemSmallIcon"+markerId);
				var markerItem = $("#crimeItem"+markerId);
			break;
			
			case "alert" :
				var markerItemSmallIcon = $("#alertItemSmallIcon"+markerId);
				var markerItem = $("#alertItem"+markerId);
			break;
			
			case "link" :
				var markerItemSmallIcon = $("#linkItemSmallIcon"+markerId);
				var markerItem = $("#linkItem"+markerId);
			break;
			
			case "search" :
				var markerItemSmallIcon = $("#searchItemSmallIcon"+markerId);
				var markerItem = $("#searchItem"+markerId);
			break;
		}
		
		markerItem.removeClass('green');
		x=(markerItemSmallIcon.backgroundPositionX());
		markerItemSmallIcon.css('background-position', x+' 0px');
	}
	
	
	
	
	
	
	
	
	
	




// DOM IS READY //
$(document).ready(function() {
	
	// PAGE FUNCTIONS
	$(window).bind('resize', fixDimensions);
	
	
	// AJAX
	globalAjaxStart();
	
	
	// MAP
	initialiseCookie();
	initializeMap();
	setting_changeMapType();
	setting_changeTheme();
	setting_showPlaces();
	setting_scrollwheel();
    setting_fullScreen();
	
		
	// BUTTONS 
	
		// New Marker Buttons
		$("#crimeNewPoint").click(function(){newCrimePoint();}).button();
		$("#alertNewPoint").click(function(){newAlertPoint();}).button();
		$("#linkNewPoint").click(function(){newLinkPoint();}).button();
		
		// Tool Bar Mode Buttons
			
			// Crime check button
			$("#crimeListButton").bind('click', function(){
				if($("#crimeListButton").is(':checked')){
					modeCrime();
				}
			});
			
			// Alert check button
			$("#alertListButton").bind('click' ,function(){
				if($("#alertListButton").is(':checked')){
					modeAlert();
				}
			});

			// Links check button
			$("#linkListButton").bind('click', function(){
				if($("#linkListButton").is(':checked')){
					modeLink();
				}
			});
			
			$("#toolBarList").buttonset();
			

		// General
			toolBarTools();
		
		
		// Other Tool bar buttons
			
			// Find me button
			$("#findMeButton").click(function(e){
				e.preventDefault();
				findMe();
			}).button({icons: {primary:'ui-icon-radio-on'}, text:false});
			
			// Logo upload button
			upload('userLogo', 'user/fileUpload');
			
			// Logo Clear button
			$("#userLogoRemove").click(function(){unlinkLogo();});
			
			
	// LOGIN AND SETTINGS
				
			// Sign in button and key press
			$("#userButtonSignin").click(function(){connect();}).button();
			$("#userLoginPassword").keyup(function(event) {if (event.keyCode == 13) {connect();}});
			
			// Sign Out
			$("#userButtonSignOut").click(function(){userSignout();}).button();		
			
	// SEARCH BUTTONS
			$("#searchFindButton").click(function(e){e.preventDefault(); find();}).button({icons: {primary:'ui-icon-search'}, text:true});
			$("#searchTweekButton").click(function(e){e.preventDefault(); loadTweakWindow();}).button({icons: {primary:'ui-icon-wrench'}, text:false});
			$("#refreshButton").click(function(e){e.preventDefault(); refresh();}).button({icons: {primary:'ui-icon-refresh'}, text:false});
			$("#search").live('keypress', function(e) {if(e.keyCode == 13){e.preventDefault(); find();}});
			
		// Resiter buttons
			$("#userPassword").click(function(){user_changePassword();});
			$("#userForgot").click(function(){userGetLoginDetails();});
			
		// Other Buttons
		  $("#forumButton").button();
		
			user_saveEmail();
			user_saveMobile();
			user_saveName();
			user_smsAfterHrsTimeFrame();
			
			$(".terms").click(function() {terms(); return false;});	
			
		// General functions
			$(".radio, .group").buttonset();
				
		// Search Properties
			$("#tweakStartDate, #tweakEndDate").datepicker({dateFormat:'yy-mm-dd'});
			$("#tweakStartDate").datepicker( "setDate","2009-10-14");
			$("#tweakEndDate").datepicker( "setDate",now);
			$("#tweakDMSFind").click(function(){findDMS();}).button();
			
		// LOGGED USER
			if($.getCookie('alertZaConnect')){userSignin();}else{userSignout();} // runs first time run functions as well.
	

	
	// BROWSER DETECTION
		if($.browser.msie){
			$("#notice").html('<table><tr><td><img src=\'img/warning.gif\' /></td><td style=\'padding-top:4px;\'>For better performance and extra features please use an alternate browser such as <a target=\'_blank\' href=\'http://www.google.com/chrome\'>Google Chrome</a> or <a  target=\'_blank\' href=\'http://www.getfirefox.com\'>Fire Fox</a> to take full advantage. Not compatible with Internet Explorer 6 or 7</td></tr></table>').show();
		}
		
	// AGAIN
		fixDimensions();
});
