//Constants
var INITIAL_ZOOM = 14;
var ST_IDLE = 0;
var ST_INSERTING_MARK = 1;
var ST_INSERTING_AREA_POINT = 2;
var ST_INSERTING_DIRECTION = 3;
var ST_INSERTING_MARCO = 4;
var STATE_EVENT_LEAVING = 100;
var STATE_EVENT_ENTERING = 101;

var MWMARKER_TYPE_BASE             = 0;
var MWMARKER_TYPE_MARKER           = 7;
var MWMARKER_TYPE_MY_MARKER        = 7;
var MWMARKER_TYPE_AREA_MARKER      = 6;
var MWMARKER_TYPE_MY_AREA_MARKER   = 6;
var MWMARKER_TYPE_SEGURANCA        = 1;
var MWMARKER_TYPE_INFRA_ESTRUTURA  = 2;
var MWMARKER_TYPE_SERVICOS_PUBLICO = 3;
var MWMARKER_TYPE_ENTRETENIMENTO   = 4;
var MWMARKER_TYPE_INSTITUICAO      = 5;

var MWMARKER_TYPE_DIRECTION_START  = 8;
var MWMARKER_TYPE_DIRECTION_MIDDLE = 9;
var MWMARKER_TYPE_DIRECTION_END    = 10;

var MWMARKER_TYPE_DEFAULT_MARCO            = 11;
var MWMARKER_TYPE_RESIDENCIA_MARCO         = 12;
var MWMARKER_TYPE_TRABALHO_MARCO 		   = 13;
var MWMARKER_TYPE_INSTITUICAO_ENSINO_MARCO = 14;
var MWMARKER_TYPE_OUTRO_MARCO			   = 15;	

var OP_SEARCH_ADDRESS = 18;
var OP_START_BUILD_AREA = 19;
var OP_END_BUILD_AREA = 20;
var OP_VIEW_GRAPHIC = 21;
var OP_VIEW_POINT = 22;
var OP_HIDE_CATEGORIES = 23;
var OP_SHOW_CATEGORIES = 24;
var OP_HIDE_ALL_CATEGORIES = 25;
var OP_SHOW_ALL_CATEGORIES = 26;
var OP_BACK_FROM_COMPLETE_POINT = 27;
var OP_FILTER_BY_DATE = 29;
var OP_START_ENTER_POINT = 30;
var OP_ACCESS_KEYWORD_RESULT = 33;
var OP_ACCESS_ADDRESS_RESULT = 34;
var OP_OPEN_GRAPHIC_WINDOW = 38;


//Global variables
var map;
var currentState = ST_IDLE;
var editingAreaMarkers = new Array();
var clickedPoint;
var clickedArea;
var areaMarkersId = -1;
var areaId = -1;
var intervalMarker = null;
var hiddenCategories = new Array();
var filterDates = new Array(2);
var markerTemporario;
var marcoTemporario; 
var loadingCounter = 0;
var savingCounter = 0;
var filtros;
var tempArea = null;

/* ============================================================
                             Directions
   ============================================================ */
// ===== Icons =====

/*
var iconStart = G_START_ICON;

var icon2 = new GIcon();
	icon2.image = "http://maps.google.com/intl/en_ALL/mapfiles/dd-via.png";
	icon2.shadow = "http://maps.google.com/intl/en_ALL/mapfiles/dd-via-transparent.png";
	icon2.iconSize = new GSize( 11, 11 );
	icon2.shadowSize = new GSize( 11, 11 );
	icon2.iconAnchor = new GPoint( 5, 5 );
	icon2.infoWindowAnchor = new GPoint( 5, 5 );
	icon2.imageMap = [0,0,0,10,10,10,10,0];

var iconEnd = G_END_ICON;
*/

// ===== Array to contain the points of the path =====
var NUM_DIRECTIONS = -1;
var NUM_ROUTES     = 1;

var ID             = 0;
var NAME           = 1;
var POLYLINE       = 2;
var ROUTES         = 3;

var ROUTE          = 0;
var START_MARKER   = 1;
var END_MARKER     = 2;

var directions  = new Array();
var newPolyline = null;

// ====== Array for decoding the failure codes ======
var reasons = [];
reasons[G_GEO_SUCCESS]            = "Success";
reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
reasons[G_GEO_UNKNOWN_DIRECTIONS] = "The GDirections object could not compute directions between the points.";

var bounds = new GLatLngBounds();

// ====== Create a Client Geocoder ======
var geo = new GClientGeocoder( new GGeocodeCache() ); 
geo.setBaseCountryCode( 'BR' );

// ====== Create a GDirections Object ======
var gdir;

// ====== GDirections Polyline ======
//var poly;

// ====== Array with all directions from database ======
var DBDIRECTIONS_POS = -1;
var dbDirections = new Array();
var DBDIR_ID   = 0;
var DBDIR_NAME = 1;
var DBDIR_LATS = 2;
var DBDIR_LNGS = 3;

// ====== Directions that has been loaded (if new, -1) ======
var loadedDirection = -1;

/* ============================================================
                             Directions
   ============================================================ */

var cities = [{name: 'Belo Horizonte', lat: -19.815731, lng: -43.954223}, 
			  {name: 'Brasília', lat: -15.802990114706807, lng: -47.87618637084961}, 
			  {name: 'Recife', lat: -8.052770867957172, lng: -34.892921447753906}, 
			  {name: 'Rio de Janeiro', lat: -22.903539, lng: -43.209587},
			  {name: 'São Paulo', lat: -23.548943, lng: -46.638818}];

window.onunload = function() {
	if (map !== null) {
		map.unload();
	}
};

/**
 * Map related functions
 */

function load() {
	filtros = $( '#lat-esq' ).html();
	
	loading(true);
	
	if ( $( '#googlemap' ).get()[0] ) {
		map = new MW.Map( $( '#googlemap' ).get()[0], handleEvent, true );
		
		var mapCenter = $.cookie( 'mw_center' );
		var mapZoom   = $.cookie( 'mw_zoom' );
		
    if ( ( mapCenter === null ) || ( mapCenter == '( 0, undefined )' ) ) 
    {
      mapCenter = zeroLat;
      $.cookie( 'mw_center', mapCenter, { path : '/', expires : 30 } );
    } 
    else 
    {
//      try
//      {
        mapCenter = eval( ' new GLatLng' + mapCenter + ';' );
//      }
//      catch(err)
//      {
//        mapCenter = zeroLat;
//        $.cookie( 'mw_center', mapCenter, { path : '/', expires : 30 } );
//      }
    }
		if ( ( mapZoom === null ) || ( mapZoom == '( 0, undefined )' ) ) {
			mapZoom = INITIAL_ZOOM;
			$.cookie( 'mw_zoom'  , mapZoom  , { path : '/', expires : 30 } );
		} else {
			mapZoom = parseInt( mapZoom );
		}
		
		map.setCenter( mapCenter, mapZoom );
		
		initIcons();
		
		gdir = new MW.Directions( loadDirectionCallback, errorDirectionCallback );
	}
	
	loading(false);
}

function initIcons() {
	var data = {shadow: {file: '', width: 0, height: 0},
				icon: {file: '', width: 0, height: 0},
				anchor: {x: 0, y: 0},
				windowAnchor: {x: 0, y: 0}};
	
	//Security marker icon
	data.icon.file = '/img/ico_cat1.gif';
	data.icon.width = 10;
	data.icon.height = 14;
	data.anchor.x = 5;
	data.anchor.y = 14;
	data.windowAnchor.x = 5;
	data.windowAnchor.y = 14;
	map.addIcon(MWMARKER_TYPE_SEGURANCA, data);
	
	//Infra marker icon
	data.icon.file = '/img/ico_cat2.gif';
	map.addIcon(MWMARKER_TYPE_INFRA_ESTRUTURA, data);
	
	//Services marker icon
	data.icon.file = '/img/ico_cat3.gif';
	map.addIcon(MWMARKER_TYPE_SERVICOS_PUBLICO, data);
	
	//Entertainment marker icon
	data.icon.file = '/img/ico_cat4.gif';
	map.addIcon(MWMARKER_TYPE_ENTRETENIMENTO, data);
	
	//Institutions marker icon
	data.icon.file = '/img/ico_cat5.gif';
	map.addIcon(MWMARKER_TYPE_INSTITUICAO, data);
	
	//Direction Start
	data.icon.file = '/img/trajeto1_p.gif';
	map.addIcon( MWMARKER_TYPE_DIRECTION_START, data );
	
	//Direction End
	data.icon.file = '/img/trajeto2_p.gif';
	map.addIcon( MWMARKER_TYPE_DIRECTION_END, data );
	
	//Generic area marker icon
	data.icon.file = '/imagens/marker_area.gif';
	data.icon.width = 11;
	data.icon.height = 11;
	data.anchor.x = 6;
	data.anchor.y = 6;
	data.windowAnchor.x = 6;
	data.windowAnchor.y = 6;
	map.addIcon(MWMARKER_TYPE_AREA_MARKER, data);
	
	//Generic marker icon
	data.icon.file = '/img/ico_default_small.gif';
	data.icon.width = 9;
	data.icon.height = 14;
	data.anchor.x = 5;
	data.anchor.y = 14;
	data.windowAnchor.x = 5;
	data.windowAnchor.y = 14;
	map.addIcon(MWMARKER_TYPE_MARKER, data);
	
	//Residencia marco icon
	data.icon.file = '/img/marco12.gif';
	data.icon.width = 23;
	data.icon.height = 27;
	data.anchor.x = 10;
	data.anchor.y = 30;
	data.windowAnchor.x = 10;
	data.windowAnchor.y = 30;
	map.addIcon(MWMARKER_TYPE_RESIDENCIA_MARCO, data);
	
	//Trabalho marco icon
	data.icon.file = '/img/marco13.gif';
	data.icon.width = 23;
	data.icon.height = 27;
	data.anchor.x = 10;
	data.anchor.y = 30;
	data.windowAnchor.x = 10;
	data.windowAnchor.y = 30;
	map.addIcon(MWMARKER_TYPE_TRABALHO_MARCO, data);
	
	//Instituicao de ensino marco icon
	data.icon.file = '/img/marco14.gif';
	data.icon.width = 23;
	data.icon.height = 27;
	data.anchor.x = 10;
	data.anchor.y = 30;
	data.windowAnchor.x = 10;
	data.windowAnchor.y = 30;
	map.addIcon(MWMARKER_TYPE_INSTITUICAO_ENSINO_MARCO, data);
	
	//Outro marco icon
	data.icon.file = '/img/marco15.gif';
	data.icon.width = 23;
	data.icon.height = 27;
	data.anchor.x = 10;
	data.anchor.y = 30;
	data.windowAnchor.x = 10;
	data.windowAnchor.y = 30;
	map.addIcon(MWMARKER_TYPE_OUTRO_MARCO, data);	
		
	//Generic marco icon
	data.icon.file = '/img/default_marco.gif'
	data.icon.width = 23;
	data.icon.height = 27;
	data.anchor.x = 10;
	data.anchor.y = 30;
	data.windowAnchor.x = 10;
	data.windowAnchor.y = 30;
	map.addIcon(MWMARKER_TYPE_DEFAULT_MARCO, data);
	
	//Direction Middle
	data.icon.file = 'http://maps.google.com/intl/en_ALL/mapfiles/dd-via.png';
	data.icon.width = 11;
	data.icon.height = 11;
	/*
	data.shadow.file = 'http://maps.google.com/intl/en_ALL/mapfiles/dd-via-transparent.png';
	data.shadow.width = 11;
	data.shadow.height = 11;
	*/
	data.anchor.x = 5;
	data.anchor.y = 5;
	data.windowAnchor.x = 5;
	data.windowAnchor.y = 5;
	map.addIcon( MWMARKER_TYPE_DIRECTION_MIDDLE, data );
}

function handleEvent(event, overlay, point, others) {
	switch( currentState ) {
		case ST_IDLE:
			if (event == STATE_EVENT_ENTERING) {
				closeHelpWindow();

				map.enableMarkersDrag(MWMARKER_TYPE_MY_MARKER);
				map.enableMarkersDrag(MWMARKER_TYPE_MY_AREA_MARKER);

			} else if (event == MWMAP_MAP_MOVE_END) {
				loadNearOverlays();
				/*
				loadNearMarkers( map.getCenter() );
				loadNearAreas( map.getCenter() );
				loadNearDirections( map.getCenter() );
				*/
				$.cookie( 'mw_center', map.getCenter(), { path : '/', expires : 30 } );
				$.cookie( 'mw_zoom'  , map.getZoom()  , { path : '/', expires : 30 } );
				
			} else if (event == MWMAP_MARKER_DRAG_END) {
				remoteUpdateMarkerPosition(overlay);
				remoteUpdateMarcoPosition(overlay);
				
			} else if (event == MWMAP_MARKER_DRAG_START) {
				removeMarcoArea(tempArea);	
				
			} else if (event == MWMAP_MARKER_CLICK) {
				clickedPoint = overlay.getPoint();
				openMarkerWindow(overlay);
				
			} else if (event == MWMAP_MARCO_CLICK) {
				clickedPoint = overlay.getPoint();
				openMarcoWindow(overlay);

			} else if (event == MWMAP_AREA_CLICK) {
				clickedArea = overlay;
				openAreaWindow(point, overlay);

			} else if (event == MWMAP_AREA_MARKER_DRAG_END) {
				if (overlay.area) {
					map.redrawArea(overlay.area);
					if (overlay.area.id !== null) {
						remoteUpdateAreaMarkerPosition(overlay);
					}
				}
			} else if ( event == MWMAP_DIRECTION_CLICK ) {
				// abre a caixa de diálogo para salvar a direção.
				openDirectionWindow( point, overlay );
				
			} else if ( event == MWMAP_MARCO_WINDOW_CLOSE){
			//	removeMarcoArea(tempArea);
				
			} else if ( event == MWMAP_ONMOUSEOUT_MARCO){
				removeMarcoArea(tempArea);
				
			} else if ( event == MWMAP_ONMOUSEOVER_MARCO){
				buildAreaInMarcoBounds(overlay);
				
			}
			break;
		case ST_INSERTING_MARK:
			if (event == STATE_EVENT_ENTERING) {
				closeHelpWindow();
				map.disableMarkersDrag(MWMARKER_TYPE_MY_AREA_MARKER);

			} else if (event == MWMAP_MAP_CLICK) {
				clickedPoint = point;
				changeState(ST_IDLE);
				openMarkerCreateWindow();
				var dados = { name:'temp', type: MWMARKER_TYPE_MY_MARKER };
				markerTemporario = map.addMarker(clickedPoint,dados);
				map.setCenter(clickedPoint);
				$.cookie( 'mw_center', map.getCenter(), { path : '/', expires : 30 } );
				$.cookie( 'mw_zoom'  , map.getZoom()  , { path : '/', expires : 30 } );
			} else if (event == MWMAP_MARKER_DRAG_END) {
				remoteUpdateMarkerPosition(overlay);
				remoteUpdateMarcoPosition(overlay);
			} else if (event == MWMAP_MAP_MOVE_END) {
				loadNearOverlays();
				/*
				loadNearMarkers( map.getCenter() );
				loadNearAreas( map.getCenter() );
				loadNearDirections( map.getCenter() );
				*/
			}
			break;
		case ST_INSERTING_AREA_POINT:
			if (event == STATE_EVENT_ENTERING) {
				openHelpWindow(currentState);
				map.disableMarkersDrag(MWMARKER_TYPE_MY_MARKER);

				log(OP_START_BUILD_AREA, true, '');

			} else if (event == STATE_EVENT_LEAVING) {
				for (i = editingAreaMarkers.length - 1; i >= 0; i--) {
					m = editingAreaMarkers.pop();
					map.removeMarker(m);
				}
				areaMarkersId = -1;

			} else if (event == MWMAP_MAP_CLICK || event == MWMAP_AREA_CLICK) {
				if (point) {
					m = map.addAreaMarker(point.lat(), point.lng(), true, MWMARKER_TYPE_MY_AREA_MARKER, areaMarkersId);
					areaMarkersId--;
					editingAreaMarkers.push(m.marker);
				}

			} else if (event == MWMAP_AREA_MARKER_DRAG_END) {
				if (overlay.area) {
					map.redrawArea(overlay.area);
					if (overlay.area.id !== null) {
						remoteUpdateAreaMarkerPosition(overlay);
					}
				}

			} else if ( ( event == MWMAP_AREA_MARKER_DBL_CLICK ) || ( event == MWMAP_MARKER_CLICK ) ) {
				if (editingAreaMarkers.length > 2) {
					buildArea();

					//Re-init area creation variables
					editingAreaMarkers = new Array();
					areaMarkersId = -1;

					log(OP_END_BUILD_AREA, true, '');

					changeState(ST_IDLE);
				}

			} else if (event == MWMAP_MAP_SINGLE_RIGHT_CLICK) {
				map.removeMarker(overlay);

			} else if (event == MWMAP_MAP_MOVE_END) {
				loadNearOverlays();
				/*
				loadNearMarkers( map.getCenter() );
				loadNearAreas( map.getCenter() );
				loadNearDirections( map.getCenter() );
				*/
			}
			break;
			
		case ST_INSERTING_DIRECTION:
			if ( event == STATE_EVENT_ENTERING ) {
				openHelpWindow( currentState );
			} else if ( event == STATE_EVENT_LEAVING ) {
				closeHelpWindow();
			} else if (event == MWMAP_MAP_MOVE_END) {
				loadNearOverlays();
				/*
				loadNearMarkers( map.getCenter() );
				loadNearAreas( map.getCenter() );
				loadNearDirections( map.getCenter() );
				*/
			}
			break;
		case ST_INSERTING_MARCO:
			if (event == STATE_EVENT_ENTERING) {
				openHelpWindow(currentState);
			//	closeHelpWindow();
			//	map.disableMarkersDrag(MWMARKER_TYPE_MARCO);

			} else if (event == MWMAP_MAP_CLICK) {
				clickedPoint = point;
				changeState(ST_IDLE);
				openMarcoCreateWindow();
				var dados = { name:'temp', type: MWMARKER_TYPE_DEFAULT_MARCO};
				marcoTemporario = map.addMarco(clickedPoint,dados);
				map.setCenter(clickedPoint);
				$.cookie( 'mw_center', map.getCenter(), { path : '/', expires : 30 } );
				$.cookie( 'mw_zoom'  , map.getZoom()  , { path : '/', expires : 30 } );
			} else if (event == MWMAP_MARKER_DRAG_END) {
				remoteUpdateMarcoPosition(overlay);

			} else if (event == MWMAP_MAP_MOVE_END) {
				loadNearOverlays();
				/*
				loadNearMarkers( map.getCenter() );
				loadNearAreas( map.getCenter() );
				loadNearDirections( map.getCenter() );
				*/
			}
			break;
	}
}

function loadNearOverlays() {
	updateMacroArea();
//	loadNearMarkers( map.getCenter() );
//	loadNearAreas( map.getCenter() );
//	loadNearDirections( map.getCenter() );
	
}

function updateMacroArea() {
	var bounds = map.getBounds();

	loading(true);
	$.get('/index/update_macro_area/' + bounds.getNorthEast().lat()
		+ "/" + bounds.getNorthEast().lng() + "/" + bounds.getSouthWest().lat()
		+ "/" + bounds.getSouthWest().lng() + "/", function(name) {
			loading(false);
			if (name) {
				//change city combobox
				$('#find_city').selectOptions(name, true);
				//update last_included, most_commented, most_viewed
				$('#last_included').load('/index/get_last_included');
				$('#most_commented').load('/index/get_most_commented');
				$('#most_viewed').load('/index/get_most_viewed');
			}
			loadNearMarkers(map.getCenter());
		});
}

function loadNearMarkers(currentCenter) {
	//requests all markers that are within a certaing distance from the map's center
	var bounds = map.getBounds();

	loading(true);
	var a = new GDownloadUrl("/security_points/get_inside/" + bounds.getNorthEast().lat()
		+ "/" + bounds.getNorthEast().lng() + "/" + bounds.getSouthWest().lat()
		+ "/" + bounds.getSouthWest().lng() + "/", loadNearMarkersCallback);
}

//callback function for the near markers request
function loadNearMarkersCallback(data, status){
	var xml = GXml.parse(data);
	var markers = xml.documentElement.getElementsByTagName("marker");
	for (var i = 0; i < markers.length; i++) {

		if(markers[i].getAttribute('private_point') == 'false' || (markers[i].getAttribute('draggable') == 'true')){
			var titulo = markers[i].getAttribute("name");
			var point = map.getPoint(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng")));
			
			if (markers[i].getAttribute('draggable') == 'true') {
				if (map.hasMarker(markers[i].getAttribute("id"))) {
					var t = map.getMarker(markers[i].getAttribute("id"));
					t.enableDragging();
					t.owner = true;
				}
			}

			if (!map.hasMarker(markers[i].getAttribute("id"))) {
//				var dados = { name: titulo, type: MWMARKER_TYPE_MARKER}; //, icon: map.markerIcon };
				var dados = { name: titulo, type: markers[i].getAttribute("icon")}; //, icon: map.markerIcon };
				if (markers[i].getAttribute('draggable') == 'true') {
//					dados = { name: titulo, type: MWMARKER_TYPE_MY_MARKER}; //, icon: map.myMarkerIcon };
					dados = { name: titulo, type: markers[i].getAttribute("icon"), draggable: true }; //, icon: map.myMarkerIcon };
				}
			
				var pointMarker = map.addMarker(point, dados);
				pointMarker.show();
				pointMarker.id = markers[i].getAttribute('id');
				pointMarker.sec_id = markers[i].getAttribute('sec_id');
				
				if (markers[i].getAttribute('crime_date')) {
					pointMarker.data_crime = JS.Date.parse(markers[i].getAttribute('crime_date'));
				}
				if (markers[i].getAttribute('draggable') == 'true') {
					pointMarker.enableDragging();
					pointMarker.owner = true;
				} else {
					pointMarker.disableDragging();
					pointMarker.owner = false;
				}
	
				pointMarker.category = markers[i].getAttribute('category_id');
				pointMarker.parent_category = markers[i].getAttribute('parent_category_id');
				for (var j = 0; j < hiddenCategories.length; j++) {
					if (hiddenCategories[j] == pointMarker.category) {
						pointMarker.hide();
						break;
					}
				}
			}
		} 
	}
	updateStats();
	loading(false);
	
	loadNearMarcos( map.getCenter() );
}

function loadNearMarcos(currentCenter) {
	//requests all markers that are within a certaing distance from the map's center
	var bounds = map.getBounds();

	loading(true);
	var a = new GDownloadUrl("/marcos/get_inside/" + bounds.getNorthEast().lat()
		+ "/" + bounds.getNorthEast().lng() + "/" + bounds.getSouthWest().lat()
		+ "/" + bounds.getSouthWest().lng() + "/", loadNearMarcosCallback);
}

function loadNearMarcosCallback(data, status){
	var xml = GXml.parse(data);
	var marcos = xml.documentElement.getElementsByTagName("marco");
	for (var i = 0; i < marcos.length; i++) {
		if(marcos[i].getAttribute('draggable') == 'true'){
			var titulo = marcos[i].getAttribute("name");
			var point = map.getPoint(parseFloat(marcos[i].getAttribute("lat")),parseFloat(marcos[i].getAttribute("lng")));

			if (!map.hasMarker(marcos[i].getAttribute("id"))) {
				var dados = { name: titulo, type: marcos[i].getAttribute("icon")}; //, icon: map.markerIcon };
				if (marcos[i].getAttribute('draggable') == 'true') {
					dados = { name: titulo, type: marcos[i].getAttribute("icon"), draggable: true }; //, icon: map.myMarkerIcon };
				}
				
				var pointMarco = map.addMarco(point, dados);
				pointMarco.show();
				pointMarco.id = marcos[i].getAttribute('id');
				//pointMarco.marco_id = marcos[i].getAttribute('marco_id');
				pointMarco.sec_id = marcos[i].getAttribute('marco_id');
				if (marcos[i].getAttribute('draggable') == 'true') {
					pointMarco.enableDragging();
					pointMarco.owner = true;
				} else {
					pointMarco.disableDragging();
					pointMarco.owner = false;
				}
			}
		} 
	}

	loading(false);
//		alert("error");
	loadNearAreas( map.getCenter() );
}

function loadNearAreas(currentCenter) {
	//requests all markers that are within a certaing distance from the map's center
//	GDownloadUrl("/security_areas/get/" + currentCenter.lat() + "/" + currentCenter.lng(), loadNearAreasCallback);
	var bounds = map.getBounds();

	loading(true);
	var a = new GDownloadUrl("/security_areas/get_inside/" + bounds.getNorthEast().lat()
		+ "/" + bounds.getNorthEast().lng() + "/" + bounds.getSouthWest().lat()
		+ "/" + bounds.getSouthWest().lng() + "/", loadNearAreasCallback);
}

//callback function for the near markers request
function loadNearAreasCallback(data, status){
	var xml = GXml.parse(data);
	var localAreas = xml.documentElement.getElementsByTagName("area");
	var id, name, owner, lats, longs, ids;
	for ( var i = 0 ; i < localAreas.length ; i++ ) {
		id = localAreas[i].getAttribute("id");
		
		if ( ! map.hasArea( id ) ) {
			name  = localAreas[i].getAttribute( 'name'  );
			owner = localAreas[i].getAttribute( 'owner' );
			lats  = localAreas[i].getAttribute( 'lats'  );
			longs = localAreas[i].getAttribute( 'longs' );
			ids   = localAreas[i].getAttribute( 'ids'   );
			
			createArea(id, name, lats, longs, owner, ids);
		}
	}
	loading(false);
	
	loadNearDirections( map.getCenter() );
}

function loadNearDirections(currentCenter) {
	//requests all directions that are within a certaing distance from the map's center
	var bounds = map.getBounds();
	
	loading(true);
	
	DBDIRECTIONS_POS = -1;
	dbDirections = new Array();
	
	var a = new GDownloadUrl("/security_directions/get_inside/" + bounds.getNorthEast().lat()
		+ "/" + bounds.getNorthEast().lng() + "/" + bounds.getSouthWest().lat()
		+ "/" + bounds.getSouthWest().lng() + "/", loadNearDirectionsCallback);
}

//callback function for the near markers request
function loadNearDirectionsCallback(data, status){
	var xml = GXml.parse(data);
	var localDirections = xml.documentElement.getElementsByTagName("direction");
	var id, name, owner, lats, longs, ids;
	for (var i = 0; i < localDirections.length; i++) {
		id = localDirections[i].getAttribute("id");
		
		var LatsLngs = new Array( 4 );
		LatsLngs[ DBDIR_ID   ] = localDirections[i].getAttribute("id");
		LatsLngs[ DBDIR_NAME ] = localDirections[i].getAttribute("name");
		LatsLngs[ DBDIR_LATS ] = localDirections[i].getAttribute("lats");
		LatsLngs[ DBDIR_LNGS ] = localDirections[i].getAttribute("longs");
		dbDirections.push( LatsLngs );
		
		/*
//		if (!map.hasDirection(id)) {
			name  = localDirections[i].getAttribute("name");
			owner = localDirections[i].getAttribute("owner");
			lats  = localDirections[i].getAttribute("lats");
			longs = localDirections[i].getAttribute("longs");
			ids = localDirections[i].getAttribute('ids');
			
			createDirection(id, name, lats, longs, owner, ids);
//		}
		*/
	}
	processDirections();
	
	updateComboStats();
	loading(false);
}

function buildAreaInMarcoBounds(marco){
	
	removeMarcoArea(tempArea);
	
	var lat = parseFloat(marco.getLat());
	var lng = parseFloat(marco.getLong());
	var point = new GLatLng(lat, lng);

	// radius 1,5 km
	var r1 = 1500; 
	
	var vertexCount = 50 //number of vertex 
	 
// calculate Circle points	
	var points = new Array();
	var latConv = point.distanceFrom(new GLatLng(point.lat() + 0.1, point.lng())) * 10;
	var lngConv = point.distanceFrom(new GLatLng(point.lat(), point.lng() + 0.1)) * 10;
	var step = (360/vertexCount) || 10;

	
	for(var i = 0; i <= 360.001; i += step) {
		var y = r1 * Math.cos(i * Math.PI/180);
		var x = r1 * Math.sin(i * Math.PI/180);
		var lng = (x * Math.cos(0) - y * Math.sin(0))/lngConv;
		var lat = (y * Math.cos(0) + x * Math.sin(0))/latConv;

		points.push(new GLatLng(point.lat() + lat, point.lng() + lng));
	}
	/*
	if(marco.type == 1){
		var area = new MW.Area(points, "#ff0000", 0, 0.8, "#ff3000", 0.4);
	
	}else if(marco.type == 12 || marco.type == 13 || marco.type == 14 || marco.type == 15){
		var area = new MW.Area(points, "#00609B", 1, 0.8, "#00609B", 0.4);
	}
	*/
	var area = new MW.Area(points, "#ff0000", 0, 0.8, "#ff3000", 0.4);
	map.addMarcoArea ( area );
	tempArea = area;
}

function removeMarcoArea(area){
	if(area){
		map.removeArea(area);
		tempArea = null;
	}
}

function createArea(id, name, lats, longs, owner, ids){
	var latsArray = new Array();
	var longsArray = new Array();
	
	latsArray = lats.split(",");
	longsArray = longs.split(",");
	ids = ids.split(",");
	
	markers = map.addAreaMarkers(latsArray, longsArray, owner, MWMARKER_TYPE_AREA_MARKER, ids);
	
	//creates a new polygon, put it on the map and push it on the areas array
	var area = new MW.Area(markers.points, "#ff0000", 1, 0.8, "#00ff00", 0.4);
	area.id   = id;
//	area.name = name;
	
	//all area markers relative to this area will be inserted in the markersArray attribute
	area.markers = markers.markers;
	
	area.setName( name );
	
	for (var i = 0; i < markers.markers.length; i++) {
		markers.markers[i].area = area;
	}
	
	map.addArea(area);
}

function buildArea() {
	
	//if the last element in 'editingAreaMarkers' array is not equal to the first,
	//inserts a copy of the first element at the end of array, closing the sequence
	//points that form a area on the map.
	if ( editingAreaMarkers.length > 0 ) {
		if ( editingAreaMarkers[0] != editingAreaMarkers[ editingAreaMarkers.length - 1 ] ) {
			editingAreaMarkers.push( editingAreaMarkers[0] );
		}
	}
	
	var points = new Array();
	for (var i = 0; i < editingAreaMarkers.length; i++) {
		points.push(editingAreaMarkers[i].getPoint());
	}
	var area = new MW.Area(points, "#ff0000", 1, 0.8, "#00ff00", 0.4);
	area.id = areaId;
	areaId--;
	
	//all area markers relative to this area will be inserted in the markersArray attribute
	area.markers = editingAreaMarkers;
	for (var i = 0; i < editingAreaMarkers.length; i++) {
		editingAreaMarkers[i].area = area;
	}
	map.addArea( area );
}

/* ============================================================
                             Directions
   ============================================================ */
function getDirections( from, to ) {
	
	NUM_DIRECTIONS++;
	directions.push( new Array( 4 ) );								// { id ; name ; polyline ; routes }
	directions[ NUM_DIRECTIONS ][ ID ] = -1;
	directions[ NUM_DIRECTIONS ][ NAME ] = '';
	directions[ NUM_DIRECTIONS ][ POLYLINE ] = null;
	directions[ NUM_DIRECTIONS ][ ROUTES ] = new Array();
	directions[ NUM_DIRECTIONS ][ ROUTES ][ 0 ] = new Array( 3 );	// { route ; start_marker ; end_marker }
	
	from = from + ', ' + $( '#find_city' ).val() + ', Pernambuco, Brazil';
	to   = to   + ', ' + $( '#find_city' ).val() + ', Pernambuco, Brazil';
	
	initGeo( from, true  );
	initGeo( to  , false );
}

function loadDirectionCallback() {
	
	var directionLoaded;
	if ( loadedDirection == -1 ) {
		directionLoaded = NUM_DIRECTIONS;
	} else {
		directionLoaded = loadedDirection;
	}
	
	directions[ directionLoaded ][ POLYLINE ] = gdir.getPolyline();
	
	map.addOverlay( directions[ directionLoaded ][ POLYLINE ] );
	
	for ( i = 0 ; i < gdir.getNumRoutes() ; i++ ) {
		var route = gdir.getRoute( i );
		directions[ directionLoaded ][ ROUTES ][ i ][ ROUTE ] = route;
	};
	/*
	for ( var i = 0 ; i < directions[ directionLoaded ][ ROUTES ].length ; i++ ) {
		
		var route = directions[ directionLoaded ][ ROUTES ][ i ][ ROUTE ];
		
		var arrayVertex = new Array( route.getNumSteps() );
		
		arrayVertex[ 0 ] = directions[ directionLoaded ][ ROUTES ][ i ][ START_MARKER ].getLatLng();
		for ( var j = 0 ; j < route.getNumSteps() ; j++ ) {
			arrayVertex[ j + 1 ] = route.getStep( j ).getLatLng();
		}
		arrayVertex[ arrayVertex.length ] = directions[ directionLoaded ][ ROUTES ][ i ][ END_MARKER ].getLatLng();
		
		var dirLats = '';
		var dirLngs = '';
		for ( var j = 0 ; j < arrayVertex.length ; j++ ) {
			dirLats += arrayVertex[ j ].lat() + ',';
			dirLngs += arrayVertex[ j ].lng() + ',';
		}
		for ( var j = ( arrayVertex.length - 2 ) ; j >= 0 ; j-- ) {
			dirLats += arrayVertex[ j ].lat() + ',';
			dirLngs += arrayVertex[ j ].lng() + ',';
		}
		dirLats = dirLats.substr( 0, ( dirLats.length - 1 ) );
		dirLngs = dirLngs.substr( 0, ( dirLngs.length - 1 ) );
		
		/*
		 * Traçar uma área 'virtual' envolvendo a rota
		 */
		/*
		var id  = '1000';
		var ids = '';
		for ( var j = 0 ; j < arrayVertex.length ; j++ ) {
			ids += id + ',';
		}
		for ( var j = ( arrayVertex.length - 2 ) ; j >= 0 ; j-- ) {
			ids += id + ',';
		}
		ids = ids.substr( 0, ( ids.length - 1 ) );
		createArea( id, 'rota', dirLats, dirLngs, false, ids );
		*/
		/*
		 * FIM
		 */
		/*
		var markers = map.getMarkersInBoundaries();
		var pointsTitle = '';
		var pointsLat   = '';
		var pointsLng   = '';
		for ( var k = 0 ; k < markers.length ; k++ ) {
			pointsTitle += markers[ k ].getTitle() + ',';
			pointsLat   += markers[ k ].getLatLng().lat() + ',';
			pointsLng   += markers[ k ].getLatLng().lng() + ',';
		}
		pointsTitle = pointsTitle.substr( 0, ( pointsTitle.length - 1 ) );
		pointsLat   = pointsLat.substr( 0, ( pointsLat.length - 1 ) );
		pointsLng   = pointsLng.substr( 0, ( pointsLng.length - 1 ) );
		
		$.ajax({
			async: false,
		    url: '/security_directions/isClose/',
		    type: 'GET',
		    data: { dirLats : dirLats , dirLngs : dirLngs ,
						pointsTitle : pointsTitle , pointsLat : pointsLat , pointsLng : pointsLng , offSet : 150 },
		    dataType: 'json',
		    timeout: 5000,
		    error: function( XMLHttpRequest, textStatus, errorThrown ) {
		    	
		    	alert( XMLHttpRequest );
		    	alert( textStatus );
		    	alert( errorThrown );
		    	
		    },
		    success: function( data, textStatus ) {
		    	
		    	alert( textStatus );
		    	alert( data );
		    	
		    }
		});
		*/
		/*
		$.get( '/security_directions/isClose/',
				{ dirLats : dirLats , dirLngs : dirLngs ,
						pointsTitle : pointsTitle , pointsLat : pointsLat , pointsLng : pointsLng , offSet : 150 },
				function( data ) {
					alert( data );
				}
		);
		*/
		/*		if ( newPolyline != null ) {
			map.removeOverlay( newPolyline );
		}
		newPolyline = new MW.Polyline( arrayVertex.slice(), '#ff0000' );
		map.addOverlay( newPolyline );
		
		var markers = map.getMarkersInBoundaries();
		var markersIn  = new Array();
		var markersOut = new Array();
		
		for ( var k = 0 ; k < markers.length ; k++ ) {
			if ( newPolyline.contains( map, markers[ k ].getLatLng(), 35 ) ) {
				markersIn.push( markers[ k ].getTitle() );
			} else {
				markersOut.push( markers[ k ].getTitle() );
			}
		}
		alert( 'Points inside: ' + markersIn.join( ',' ) );
		alert( 'Points outside: ' + markersOut.join( ',' ) );
		* /
	}
	*/
	GEvent.addListener( directions[ directionLoaded ][ POLYLINE ], 'click', function( latlng ) {
		
		var pointInsideRoute = -1;
		
		for ( i = 0 ; i < directions[ directionLoaded ][ ROUTES ].length ; i++ ) {
			
			var route = directions[ directionLoaded ][ ROUTES ][ i ][ ROUTE ];
			
			var arrayVertex = new Array( route.getNumSteps() );
			
			arrayVertex[ 0 ] = directions[ directionLoaded ][ ROUTES ][ i ][ START_MARKER ].getLatLng();
			for ( var j = 0 ; j < route.getNumSteps() ; j++ ) {
				arrayVertex[ j + 1 ] = route.getStep( j ).getLatLng();
			}
			arrayVertex[ arrayVertex.length ] = directions[ directionLoaded ][ ROUTES ][ i ][ END_MARKER ].getLatLng();
			
			var clickedPolyline = new MW.Polyline( arrayVertex.slice() );
			
			if ( clickedPolyline.contains( map, latlng, 6 ) ) {
				pointInsideRoute = i;
				break;
			}
		}
		if ( pointInsideRoute > -1 ) {
//			insertPoint( directionLoaded, pointInsideRoute, createMarker(
//					directions[ directionLoaded ][ ID ], directions[ directionLoaded ][ NAME ], latlng, icon2, true ) );
			insertPoint( directionLoaded, pointInsideRoute, createMarker(
					directions[ directionLoaded ][ ID ], directions[ directionLoaded ][ NAME ], latlng,
					map.getIcon( MWMARKER_TYPE_DIRECTION_MIDDLE ), true ) );
		}
	});
	
	processDirections();
}

function errorDirectionCallback() {
	var code = gdir.getStatus().code;
	var reason = "Code " + code;
	
	if ( reasons[ code ] ) {
		reason = "Code " + code + " : " + reasons[ code ];
	} 
	alert( "Failed to obtain directions, " + reason );
}

// ============================================================ //

function insertPoint( numDirection, pointInsideRoute, marker ) {
	
	var newRoutes = new Array( directions[ numDirection ][ ROUTES ].length + 1 );
	for ( i = 0 ; i < ( directions[ numDirection ][ ROUTES ].length + 1 ) ; i++ ) {
		newRoutes[ i ] = new Array( 3 );
	}
	
	for ( i = 0 ; i < directions[ numDirection ][ ROUTES ].length ; i++ ) {
		if ( i < pointInsideRoute ) {
			newRoutes[ i ] = directions[ numDirection ][ ROUTES ][ i ];
		} else if ( i == pointInsideRoute ) {
			newRoutes[ i ][ ROUTE ] = directions[ numDirection ][ ROUTES ][ i ][ ROUTE ];
			newRoutes[ i ][ START_MARKER ] = directions[ numDirection ][ ROUTES ][ i ][ START_MARKER ];
			newRoutes[ i ][ END_MARKER ] = marker;
			
			newRoutes[ i + 1 ][ START_MARKER ] = marker;
			newRoutes[ i + 1 ][ END_MARKER ] = directions[ numDirection ][ ROUTES ][ i ][ END_MARKER ];
		} else {
			newRoutes[ i + 1 ] = directions[ numDirection ][ ROUTES ][ i ];
		}
	}
	
	directions[ numDirection ][ ROUTES ] = newRoutes;
}

function removePoint( numDirection, marker ) {
	
	var newRoutes = new Array( directions[ numDirection ][ ROUTES ].length - 1 );
	for ( i = 0 ; i < ( directions[ numDirection ][ ROUTES ].length - 1 ) ; i++ ) {
		newRoutes[ i ] = new Array( 3 );
	}
	
	directions[ numDirection ][ ROUTES ]
	
	var deleted = false;
	for ( i = 0 ; i < directions[ numDirection ][ ROUTES ].length ; i++ ) {
		
		if ( directions[ numDirection ][ ROUTES ][ i ][ END_MARKER ] === marker ) {
			
			if ( i < ( directions[ numDirection ][ ROUTES ].length - 1 ) ) {
				newRoutes[ i ][ ROUTE ]        = directions[ numDirection ][ ROUTES ][ i ][ ROUTE ];
				newRoutes[ i ][ START_MARKER ] = directions[ numDirection ][ ROUTES ][ i ][ START_MARKER ];
				newRoutes[ i ][ END_MARKER ]   = directions[ numDirection ][ ROUTES ][ i + 1 ][ END_MARKER ];
				i++;
			}
			
			deleted = true;
		} else {
			if ( deleted ) {
				newRoutes[ i - 1 ] = directions[ numDirection ][ ROUTES ][ i ];
			} else {
				newRoutes[ i ] = directions[ numDirection ][ ROUTES ][ i ];
			}
		}
		
	}
	
	directions[ numDirection ][ ROUTES ] = newRoutes;
}

function initGeo( address, startPoint ) {
	geo.getLatLng( address, function ( point ) {
		if ( point ) {
			if ( startPoint ) {
				doStart( point );
			} else {
				doEnd( point );
			}
		} else {
			if ( geo.getCache() ) {
				var result = geo.getCache().get( address );
				if ( result ) {
					var reason = "Code " + result.Status.code;
					if ( reasons[ result.Status.code ] ) {
						reason = reasons[ result.Status.code ];
					}
				} else {
					var reason = "";
				} 
				alert( 'Could not find "' + address + '" ' + reason );
			}
		}
	});
}

function processDirections() {
	DBDIRECTIONS_POS++;
	if ( ( dbDirections.length > 0 )
			&& ( dbDirections.length > DBDIRECTIONS_POS ) ) {
		buildDirection( dbDirections[ DBDIRECTIONS_POS ][ DBDIR_ID ],
				dbDirections[ DBDIRECTIONS_POS ][ DBDIR_NAME ],
				dbDirections[ DBDIRECTIONS_POS ][ DBDIR_LATS ],
				dbDirections[ DBDIRECTIONS_POS ][ DBDIR_LNGS ] );
	}
}

function getDirectionPosById( directionId ) {
	
	var result = -1;
	
	for ( var i = 0 ; i < directions.length ; i++ ) {
		if ( directions[ i ][ ID ] == directionId ) {
			result = i;
			break;
		}
	}
	
	return result;
}

var returnMarkers = null;
function getMarkersNearDirection( direction, offSet ) {
	
	returnMarkers = new Array();
	var arrayVertex = new Array();
	
	for ( var i = 0 ; i < direction[ ROUTES ].length ; i++ ) {
		
		var route = direction[ ROUTES ][ i ][ ROUTE ];
		
		if ( route != null ) {
			for ( var j = 0 ; j < route.getNumSteps() ; j++ ) {
				arrayVertex[ arrayVertex.length ] = route.getStep( j ).getLatLng();
			}
		}
	}
	
	var dirLats = '';
	var dirLngs = '';
	for ( var j = 0 ; j < arrayVertex.length ; j++ ) {
		dirLats += arrayVertex[ j ].lat() + ',';
		dirLngs += arrayVertex[ j ].lng() + ',';
	}
	for ( var j = ( arrayVertex.length - 2 ) ; j >= 0 ; j-- ) {
		dirLats += arrayVertex[ j ].lat() + ',';
		dirLngs += arrayVertex[ j ].lng() + ',';
	}
	dirLats = dirLats.substr( 0, ( dirLats.length - 1 ) );
	dirLngs = dirLngs.substr( 0, ( dirLngs.length - 1 ) );
	
	/*
	 * Traçar uma área 'virtual' envolvendo a rota
	 */
	/*
	var id  = '1000';
	var ids = '';
	for ( var j = 0 ; j < arrayVertex.length ; j++ ) {
		ids += id + ',';
	}
	for ( var j = ( arrayVertex.length - 2 ) ; j >= 0 ; j-- ) {
		ids += id + ',';
	}
	ids = ids.substr( 0, ( ids.length - 1 ) );
	createArea( id, 'rota', dirLats, dirLngs, false, ids );
	*/
	/*
	 * FIM
	 */
	
	var markers = map.getMarkersInBoundaries();
	var pointsTitle            = '';
	var pointsParentCategories = '';
	var pointsLat              = '';
	var pointsLng              = '';
	for ( var k = 0 ; k < markers.length ; k++ ) {
		pointsTitle            += markers[ k ].getTitle() + ',';
		pointsParentCategories += markers[ k ].parent_category + ',';
		pointsLat              += markers[ k ].getLatLng().lat() + ',';
		pointsLng              += markers[ k ].getLatLng().lng() + ',';
	}
	pointsTitle            = pointsTitle.substr( 0, ( pointsTitle.length - 1 ) );
	pointsParentCategories = pointsParentCategories.substr( 0, ( pointsParentCategories.length - 1 ) );
	pointsLat              = pointsLat.substr( 0, ( pointsLat.length - 1 ) );
	pointsLng              = pointsLng.substr( 0, ( pointsLng.length - 1 ) );
	
	$.ajax({
		async: false,
	    url: '/security_directions/isClose/',
	    type: 'POST',
	    data: { dirLats : dirLats , dirLngs : dirLngs ,
					pointsTitle : pointsTitle , pointsParentCategories : pointsParentCategories ,
					pointsLat : pointsLat , pointsLng : pointsLng , offSet : offSet },
	    dataType: 'json',
	    timeout: 5000,
	    error: function( XMLHttpRequest, textStatus, errorThrown ) {
	    	/*
	    	alert( XMLHttpRequest );
	    	alert( textStatus );
	    	alert( errorThrown );
	    	*/
	    },
	    success: function( data, textStatus ) {
	    	/*
	    	alert( textStatus );
	    	alert( data );
	    	*/
	    	returnMarkers = returnMarkers.concat( data );
	    }
	});
	
	/*
	$.get( '/security_directions/isClose/',
			{ dirLats : dirLats , dirLngs : dirLngs ,
					pointsTitle : pointsTitle , pointsLat : pointsLat , pointsLng : pointsLng , offSet : 150 },
			function( data ) {
				alert( data );
			}
	);
	*/
	
	return returnMarkers;
}

function buildDirection( id, name, lats, lngs ) {
	
	// Do not build a direction twice.
	if ( getDirectionPosById( id ) > -1 ) {
		processDirections();
		return;
	}
	
	NUM_DIRECTIONS++;
	directions.push( new Array( 4 ) );								// { id ; name ; polyline ; routes }
	directions[ NUM_DIRECTIONS ][ ID ] = id;
	directions[ NUM_DIRECTIONS ][ NAME ] = name;
	directions[ NUM_DIRECTIONS ][ POLYLINE ] = null;
	directions[ NUM_DIRECTIONS ][ ROUTES ] = new Array();
	directions[ NUM_DIRECTIONS ][ ROUTES ][ 0 ] = new Array( 3 );	// { route ; start_marker ; end_marker }
	
	var arrayLats = lats.split( ',' );
	var arrayLngs = lngs.split( ',' );
	var newRoutes = new Array( arrayLats.length - 1 );
	for ( var i = 0 ; i < ( arrayLats.length - 1 ) ; i++ ) {
		newRoutes[ i ] = new Array( 3 );
	}
	
	for ( var i = 0 ; i < arrayLats.length ; i++ ) {
		
		var point     = new GLatLng( arrayLats[ i ], arrayLngs[ i ] );
		var icon      = null;
		var removable = false;
		if ( i == 0 ) {
			icon = map.getIcon( MWMARKER_TYPE_DIRECTION_START );	//iconStart;
			removable = false;
		} else if ( i == ( arrayLats.length - 1 ) ) {
			icon = map.getIcon( MWMARKER_TYPE_DIRECTION_END );		//iconEnd;
			removable = false;
		} else {
			icon = map.getIcon( MWMARKER_TYPE_DIRECTION_MIDDLE );	//icon2;
			removable = true;
		}
		
		var marker = createMarker( id, name, point, icon, removable );
		
		if ( i == 0 ) {
			newRoutes[ i ][ START_MARKER ] = marker;
		} else if ( i == ( arrayLats.length - 1 ) ) {
			newRoutes[ i - 1 ][ END_MARKER ] = marker;
		} else {
			newRoutes[ i ][ START_MARKER ] = marker;
			newRoutes[ i - 1 ][ END_MARKER ] = marker;
		}
	}
	
	directions[ NUM_DIRECTIONS ][ ROUTES ] = newRoutes;
	
	/*
	 * Traçar uma área 'virtual' envolvendo a rota
	 */
	/*
	var ids = '';
	for ( var i = 0 ; i < arrayLats.length ; i++ ) {
		ids += id;
		if ( i < ( arrayLats.length - 1 ) ) {
			ids += ',';
		}
	}
	createArea( id, name, lats, lngs, false, ids );
	
	var latLngBounds = new GLatLngBounds();
	latLngBounds.extend( directions[ NUM_DIRECTIONS ][ ROUTES ][ 0 ][ START_MARKER ].getLatLng() );
	latLngBounds.extend( directions[ NUM_DIRECTIONS ][ ROUTES ][ 0 ][ END_MARKER ].getLatLng() );
	
	var markers = map.getMarkersInBoundaries();
	
	var markersIn  = new Array();
	var markersOut = new Array();
	
	for ( var i = 0 ; i < markers.length ; i++ ) {
		if ( latLngBounds.contains( markers[ i ].getLatLng() ) ) {
			markersIn.push( markers[ i ].id );
		} else {
			markersOut.push( markers[ i ].id );
		}
	}
	alert( 'Points inside: ' + markersIn.join( ',' ) );
	alert( 'Points outside: ' + markersOut.join( ',' ) );
	*/
	/*
	 * Fim
	 */
	
	loadedDirection = -1;
	traceDirections();
}

function doStart( point ) {
//	directions[ NUM_DIRECTIONS ][ ROUTES ][ directions[ NUM_DIRECTIONS ][ ROUTES ].length - 1 ][ START_MARKER ] = createMarker(
//			directions[ NUM_DIRECTIONS ][ ID ], directions[ NUM_DIRECTIONS ][ NAME ], point, iconStart, false ); 
	directions[ NUM_DIRECTIONS ][ ROUTES ][ directions[ NUM_DIRECTIONS ][ ROUTES ].length - 1 ][ START_MARKER ] = createMarker(
			directions[ NUM_DIRECTIONS ][ ID ], directions[ NUM_DIRECTIONS ][ NAME ], point,
			map.getIcon( MWMARKER_TYPE_DIRECTION_START ), false ); 
}

function doEnd( point ) {
//	directions[ NUM_DIRECTIONS ][ ROUTES ][ directions[ NUM_DIRECTIONS ][ ROUTES ].length - 1 ][ END_MARKER ] = createMarker(
//			directions[ NUM_DIRECTIONS ][ ID ], directions[ NUM_DIRECTIONS ][ NAME ], point, iconEnd, false );
	directions[ NUM_DIRECTIONS ][ ROUTES ][ directions[ NUM_DIRECTIONS ][ ROUTES ].length - 1 ][ END_MARKER ] = createMarker(
			directions[ NUM_DIRECTIONS ][ ID ], directions[ NUM_DIRECTIONS ][ NAME ], point,
			map.getIcon( MWMARKER_TYPE_DIRECTION_END ), false );
	loadedDirection = -1;
	traceDirections();
}

function createMarker( numDirection, nameDirection, point, icon, removable ) {
	var marker = new MW.Marker( point, { draggable:true, icon:icon } );
	marker.direction_id = numDirection;
	marker.direction_name = nameDirection;
	marker.owner = true;
	
	GEvent.addListener( marker, 'dragend', function() {
		var directionPos = getDirectionPosById( this.direction_id );
		if ( directionPos > -1 ) {
			map.removeOverlay( directions[ directionPos ][ POLYLINE ] );
			loadedDirection = directionPos;
			traceDirections();
		}
	});
	if ( removable ) {	// Pontos Intermediários
		GEvent.addListener( marker, 'dblclick', function() {
			var directionPos = getDirectionPosById( this.direction_id );
			if ( directionPos > -1 ) {
				removePoint( directionPos, this );
				map.removeOverlay( this );
				map.removeOverlay( directions[ directionPos ][ POLYLINE ] );
				loadedDirection = directionPos;
				traceDirections();
			}
		});
	} else {			// Pontos Inicial e Final
		GEvent.addListener( marker, 'click', function() {
			handleEvent( MWMAP_DIRECTION_CLICK, this, this.getPoint() );
		});
	}
	map.addOverlay( marker );
	
	return marker;
}

function traceDirections() {
	
	var directionLoaded;
	if ( loadedDirection == -1 ) {
		directionLoaded = NUM_DIRECTIONS;
	} else {
		directionLoaded = loadedDirection;
	}
	
	/*
	bounds.extend( routes[ NUM_ROUTES - 1 ][ START_MARKER ].getPoint() );
	bounds.extend( routes[ NUM_ROUTES - 1 ][ END_MARKER ].getPoint()   );
	map.setZoom( map.getBoundsZoomLevel( bounds ) );
	map.setCenter( bounds.getCenter() );
	*/
	
	var query = 'from: ';
	var first = true;
	for ( i = 0 ; i < directions[ directionLoaded ][ ROUTES ].length ; i++ ) {
		if ( ! first ) {
			query += ' to: ';
		}
		query += directions[ directionLoaded ][ ROUTES ][ i ][ START_MARKER ].getPoint().toUrlValue( 6 );
		first = false;
	}
	query += ' to: ' + directions[ directionLoaded ][ ROUTES ][ directions[ directionLoaded ][ ROUTES ].length - 1 ][ END_MARKER ].getPoint().toUrlValue( 6 );
	gdir.load( query, { locale:'pt_BR', getPolyline:true, getSteps:true, preserveViewport:false } );
}

// ============================================================ //

function goToPointFromSearchResult(id) {
	goToPoint(id);
	log(OP_ACCESS_KEYWORD_RESULT, true, id);
}

function goToPoint(id) {
	var ret = map.goToMarker(id);
	if (!ret) {
		loading(true);
		$.get('/points/getById/'+ id, null, function(data) {
			var coords = data.split(',');
			map.moveTo(coords[0], coords[1], 0);
			if (intervalMarker == null) {
				intervalMarker = window.setInterval(function() {
					goToPoint(id);
				}, 5000);
			}
			loading(false);
		});
	} else {
		clearInterval(intervalMarker);
		intervalMarker = null;
	}
	return ret;
}

function goToAddress(address) {
	if (address) {
		loading(true);
		var geocoder = new GClientGeocoder();
		address = address.substr(0, 5) + ' - ' + address.substr(5, 3);
		geocoder.getLocations(address + ', Brazil', function (response) {
			if (response && response.Status.code == 200 && response.Placemark.length > 0) {
				var point = new GLatLng(response.Placemark[0].Point.coordinates[1], response.Placemark[0].Point.coordinates[0]);
				map.addOnlyShowMarker(point);
				//map.setCenter(point, 15);
			}
			loading(false);
		});
	}
}

function openAreaWindow(point, area) {
	var areaWindowHtml = "<h4>Área</h4>";
	var ownerAreaWindowHtml = "<div id='formArea'><form id='frmArea'>Nome:<input type='text' id='areaName' value='%s' /><input type='button' id='btnSalvarArea' value='Salvar' onClick='salvarArea();'/></form></div>";

	var name = "";
	if (area.id > 0) {
		name = area.getName();
	}
	areaWindowHtml += ownerAreaWindowHtml.replace('%s', name);

	log(OP_OPEN_GRAPHIC_WINDOW, true, area.id);

	map.openWindow(point, areaWindowHtml);
}

function openDirectionWindow( point, marker ) {
	var directionWindowHtml = '<div id="formDirection"><form id="frmDirection">Nome:<input type="text" id="directionName" value="' + marker.direction_name + '" /><input type="button" id="btnSalvarDirection" value="Salvar" onClick="salvarDirection( ' + marker.direction_id + ' );" /></form></div>';
	
	log(OP_VIEW_GRAPHIC, true, '');
	
	map.openWindow( point, directionWindowHtml );
}

function buildGraphic(values) {
	var colours = new Array("#CC0000", "#CC6600", "#669900", "#FF3366", "#006699");
	var labels = new Array("SEGURAN&Ccedil;A", "INFRA-ESTRUTURA", "SERVI&Ccedil;OS", "ENTRETENIMENTO", "INSTITUI&Ccedil;&Otilde;ES");

	var html = '<table border="0">';

	for(var i = 0; i < labels.length; i++) {
		html += '<tr><td style="background: #cccccc; font-weight: bold; color: #666666; padding: 0 5px 0">';
		html += labels[i];
		html += '</td><td style="font-weight: bold; color:' + colours[i]
			+ '"><div style="background: ' + colours[i]
			+ '; width: ' + (values[i] * 10) + 'px; float:left">&nbsp;</div>&nbsp;'
			+ values[i] + '</td></tr>';
	}
	html += '</table>';
	document.getElementById('graph').innerHTML = html;
}

function openMarkerCreateWindow() {
	  // Shows the loading message...
		loading(true);
	  
	  // Requests HTML form .
		$.get('/security_points/open_edit_window', function(data) {
			
	    // Show form.
	    markerTemporario.showWindow(data);
	    
	    // Requests HTML behavior...
	    $.get('/security_points/open_edit_window_script', 
	        function(data) 
	        {
	          try
	          {
	            // Applies the behavior.
	            eval(data);
	          }
	          catch (e)
	          {
	          }
	        
	          $(".thickbox").click(
	              function()
	              {
	                markerTemporario.hideWindow();
	                map.removeMarker(markerTemporario);
	              }
	            );
	      /*
	          $("#googlemap").click(function(){
	            markerTemporario.hideWindow();
	            map.removeMarker(markerTemporario);
	          })
	      */
	          
	    		$('#crime_date').datepicker({
	    			closeText: 'x',
	    			clearText: ' ',
	    			hideIfNoPrevNext: true,
	    			showOtherMonths: true,
	    			prevText: '<',
	    			nextText: '>',
	    			showOn: 'both',
	    			buttonImage: '/img/ico_calendar.gif',
	    			buttonImageOnly: true
	    		})
	          
	          loading(false);
	        }
	      );

		});
		log(OP_START_ENTER_POINT, true, '');
	}

function openMarcoCreateWindow(){
	loading(true);
	$.get('/marcos/open_marco_edit_window', function(data) {
		marcoTemporario.showWindow(data);
		
		$(".thickbox").click(function(){
			marcoTemporario.hideWindow();
			map.removeMarker(marcoTemporario);
		})
				
		loading(false);
	});
	log(OP_START_ENTER_POINT, true, '');
}

function openMarkerEditWindow(id) {
	loading(true);
	$.get("/security_points/open_edit_window/" + id, 
      function(data) 
      {
        markerTemporario.showWindow(data);
        // Requests HTML behavior...
        $.get("/security_points/open_edit_window_script/" + id, 
            function(data) 
            {
              try
              {
                // Applies the behavior.
                eval(data);
              }
              catch (e)
              {
              }
            }
          );
        loading(false);
      }
	  );
}

function openMarcoEditWindow(id) {
	loading(true);
	$.get("/marcos/open_marco_edit_window/"+ id, function(data) {
		marcoTemporario.showWindow(data);
		loading(false);
	});
}

function openMarkerWindow(marker) {
	markerTemporario = marker;
	if (marker.sec_id !== null) {
		loading(true);
		$.get("/security_points/show_details/"+ marker.sec_id, function(data) {
			marker.showWindow(data);
			loading(false);

			log(OP_VIEW_POINT, true, '');
	
			tb_init('.thickbox');
			$(".thickbox").click(function(){
				marker.hideWindow();
			})
	
	
			// comportamento das tabs do balao
			$("#baloon ul.tabs li").click(function() {
				if (classe != 'report_fake') {
					$('#baloon div.content').css('backgroundColor', '#F3FBFE');
				}
	
				$('#baloon ul.tabs li').css('backgroundColor', 'white')
				$('#baloon ul.tabs li').css('borderBottomColor', '#3366CC')
				$('#baloon ul.tabs li').css('fontWeight', 'normal')
	
				var classe = $(this).attr('class')
				$('#baloon ul.tabs li.'+classe).css('fontWeight', 'bold')
				$('#baloon ul.tabs li.'+classe).css('backgroundColor', '#F3FBFE')
				$('#baloon ul.tabs li.'+classe).css('borderBottomColor', '#F3FBFE')
				$('#baloon div.content div').css('display', 'none')
				$('#baloon div.content div#'+classe).css('display', 'block')
	
				if (classe == 'report_fake') {
					$('#baloon div.content').css('backgroundColor', '#FFF1EE');
					$('#baloon ul.tabs li.'+classe).css('backgroundColor', '#FFF1EE')
					$('#baloon ul.tabs li.'+classe).css('borderBottomColor', '#FFF1EE')
				}
			});
	
			$("#_ver_denunciar").click(function() {
				loading(true);
			 	$.get('/security_points/show_report_fake/'+ marker.sec_id, null, function(data){
					$("div#lat-esq").html(data);
					marker.hideWindow();
					loading(false);
				});
			});
		});
	}
}

function openMarcoWindow(marco) {
	marcoTemporario = marco;
	if (marco.point !== null) {
		loading(true);
		$.get("/marcos/show_marco_details/"+ marco.sec_id, function(data) {
			marco.showWindow(data);
			
			loading(false);

			log(OP_VIEW_POINT, true, '');

			tb_init('.thickbox');
			$(".thickbox").click(function(){
				marco.hideWindow();
			})
		});
	}
}

function openHelpWindow( state ) {
	var txt = '';
	
	switch ( state ) {
		case ST_INSERTING_AREA_POINT:
			txt = '<div><h4>Criar uma &aacute;rea:</h4><p>Para criar uma &aacute;rea, marque os pontos que delimitam a &aacute;rea e depois d&ecirc; um duplo clique no ponto inicial para fechar a &aacute;rea.</p><input type="button" value="ok"  class="user_button" onclick="$(\'#pt1\').css(\'display\', \'none\')" /></div>';
			break;
			
		case ST_INSERTING_DIRECTION:
//			txt = '<fieldset class="find"><label>Origem: </label><input type="text" id="origem" name="origem" style="width: 265px" value="Rua do Sol, 143, Recife" /><label>Destino: </label><input type="text" id="destino" style="width: 265px" value="Rua do Brum, Recife" /><input type="image" src="/img/btn_go.png" class="btn_go" id="find_direction" onclick="getDirections( $(\'#origem\').val(), $(\'#destino\').val() ); changeState( ST_IDLE ); $(\'#pt1\').css(\'display\', \'none\');" /></fieldset></p>';
			txt = '<fieldset class="find"><label>Origem: </label><input type="text" id="origem" name="origem" style="width: 235px" value="" /><label>Destino: </label><input type="text" id="destino" style="width: 235px" value="" /><input type="image" src="/img/btn_go.png" class="btn_go" id="find_direction" onclick="getDirections( $(\'#origem\').val(), $(\'#destino\').val() ); changeState( ST_IDLE ); $(\'#pt1\').css(\'display\', \'none\');" /></fieldset></p>';
			break;
			
		case ST_INSERTING_MARCO:
			txt = '<div><h4>Adicionar marco:</h4><p>Marcos s&atilde;o pontos especiais relacionados a cada usu&aacute;rio e vis&iacute;veis apenas pelos mesmos. Para adicionar um marco, basta clicar no mapa e preencher o formul&aacute;rio.</p><input type="button" value="ok"  class="user_button" onclick="$(\'#pt1\').css(\'display\', \'none\')" /></div>';
			break;
	}
	
	if ( txt ) {
		$( '#pt1' ).html( txt );
		$( '#pt1' ).css( 'display', 'block' );
	}
}

function closeHelpWindow() {
	$('#pt1').html('');
	$('#pt1').css('display','none');
}

function remoteUpdateMarcoPosition(marco) {
	loading(true);
	$.post("/marcos/move",
		{id: marco.sec_id, lat: marco.getLat(), lng: marco.getLong()},
		function() { loading(false); });
		updateStatsViewPort();
}

function remoteUpdateMarkerPosition(marker) {
	loading(true);
	$.post("/security_points/move",
		{id: marker.sec_id, lat: marker.getLat(), lng: marker.getLong()},
		function() { loading(false); });
	updateStats();
}

function remoteUpdateAreaMarkerPosition(marker) {
	loading(true);
	$.post("/points/update",
		{id: marker.id, lat: marker.getLat(), lng: marker.getLong()},
		function() { loading(false); });
	updateStatsArea();
}

function changeState(state) {
	handleEvent( STATE_EVENT_LEAVING );
	if ( currentState == state ) {
		currentState = ST_IDLE;
	} else {
		currentState = state;
	}
	setControlImages( currentState );
	handleEvent( STATE_EVENT_ENTERING );
}

function setControlImages( state ) {
//	$('#point').css('background', 'none');
	$('#point img').attr('src', '/img/bot_relato.gif');
//	$('#area').css('background', 'none');
	$('#area img').attr('src', '/img/bot_area.gif');
//	$('#marco').css('background', 'none');	
	$('#marco img').attr('src', '/img/bot_marco.gif');
//	$('#direction').css('background', 'none');
	$('#googlemap *').css('cursor',"url(/imagens/openhand.cur), default");
	if (state == ST_INSERTING_MARK) {
//		$('#point').css('background', "#E9F6FE");
		$('#point img').attr('src', '/img/bot_relato_press.gif');
		$('#googlemap *').css('cursor','crosshair');
	} else if (state == ST_INSERTING_AREA_POINT) {
//		$('#area').css('background', "#E9F6FE");
		$('#area img').attr('src', '/img/bot_area_press.gif');
		$('#googlemap *').css('cursor','crosshair');
	} else if (state == ST_INSERTING_DIRECTION) {
//		$('#direction').css('background', "#E9F6FE");
		$('#googlemap *').css('cursor','crosshair');
	} else if (state == ST_INSERTING_MARCO) {
		$('#marco img').attr('src', '/img/bot_marco_press.gif');
		$('#googlemap *').css('cursor','crosshair');
	}
}

/**
 * Form-related functions
 */

function initLogin() {
/*
	$("form #login").submit(
	    function() {
	        $.post('/users/login', {
	            email: $('#email').val(),
	            pass: $('#pass').val()
	            }, function(response) {
	                if (response.indexOf('erro_login') > 0) {
	                    //$("#form_login").html($("#form_login").html() + response)
	                    $("#div_login_message").html(response);
	                } else {
	                    window.location = '/users/my_map';
	                }
	            }
	        );
	        return false;
	    }
	);
*/
}

function initLostPassword() {
	$("#link_lost_password").click(
	    function() {
	        $.post('/users/lostPassword', {
	            email: $('#email').val()
	            }, function(response) {
	                if (response.indexOf('erro_login') > 0 || response.indexOf('info_login') > 0) {
	                    $("#div_login_message").html(response);
	                }
	            }
	        );
	        return false;
	    }
	);
}

function cancel_add_marker() {
	$('#pt1').css('display','none');
	if (markerTemporario) {
		map.removeMarker(markerTemporario);
	}
	if (marcoTemporario){
		map.removeMarker(marcoTemporario);
	}
}

function loadMyMap() {
	$.getJSON('/users/get_my_points', function(res) {
		/*
		DBDIRECTIONS_POS = -1;
		dbDirections = new Array();
		*/
		if (res.points) {
			var html = '';
			for (i in res.points) {
				if (res.points[i].type == 'point') {
					html += '<p class="meu_ponto"><img src="/img/ico_cat' + res.points[i].icon
						+ '.gif" /> <a href="#" onclick="goToPoint(' + res.points[i].point_id
						+ ')">' + res.points[i].name
						+ '</a> <span>' + res.points[i].date + '</span></p>';
				} else if ( res.points[i].type == 'area' ) {
					html += '<p class="minha_area"><img src="/img/ico_area.gif" /> <a href="#" onclick="moveTo('
						+ res.points[i].lat + ',' + res.points[i].lng
						+ ', \'\', false)">' + res.points[i].name
						+ '</a> <span>' + res.points[i].date + '</span></p>';
				} else if ( res.points[i].type == 'direction' ) {
					html += '<p class="minha_direcao"><img src="/img/ico_trajeto.gif" /> <a href="#" onclick="moveTo(' 
						+ res.points[i].lat + ',' + res.points[i].lng
						+ ', \'\', false)">' + res.points[i].name
						+ '</a> <span>' + res.points[i].date + '</span></p>';
				} else if(res.points[i].type == 'marco' ){
					html += '<p class="meu_marco"><img src="/img/marco' + res.points[i].icon 
						+ '.gif" /> <a href="#"	onclick="goToPoint(' + res.points[i].point_id	
						+ ')">' + res.points[i].name
						+ '</a> <span>' + res.points[i].date + '</span></p>';
					/*
					/*
					var LatsLngs = new Array( 3 );
					LatsLngs[ DBDIR_NAME ] = res.points[i].name;
					LatsLngs[ DBDIR_LATS ] = res.points[i].lats;
					LatsLngs[ DBDIR_LNGS ] = res.points[i].lngs;
					dbDirections.push( LatsLngs );
					*/
				} else if (res.points[i].type != 'point' || res.points[i].type != 'area' || res.points[i].type != 'direction' ) {
					html += '<p> <b>Usu&aacute;rio n&atilde;o possui pontos, areas ou trajetos. Para adicionar relatos clique no bot&atilde;o &quot;Adicionar Relato&quot; e em seguida clique no mapa para preencher o formul&aacute;rio com os dados do seu relato.</b> </p>';	
				}
			}
			
			//processDirections();
			
			$('#meuMapaHits').html(html);
		} else if (res.error) {
			$('#meuMapaHits').html('<h2>'+ res.error +'</h2>');
			tb_init('a.thickbox, area.thickbox, input.thickbox');
			
			$("#meuMapaHits .thickbox").click(function(){
				elem = $('#tab_index').get();
				elem.id = 'tab_index';
				toggleTabs(elem);
			})
		}
	});
}

function enviar_form_insert_marker(point) {
	loading(true);

	$("#lat").attr("value",point.lat());
	$("#lng").attr("value",point.lng());

	$.post('/security_points/add', $('#create_point').formSerialize(), function(req) {
			var result = eval('(' + req + ')');
			if (result.error) {
				txtErrors = '';
				for (var i = 0; i < result.errors.length; i++) {
					txtErrors += '<li>' + result.errors[i] + '</li>';
				}
				$('#errors').html(txtErrors);
			} else {
			//	//$('#pt1').css('display','none');
				
		        if (map.hasMarker(result.id)) 
		        {
		          var oldMarker = map.getMarker(result.id);
		          oldMarker.hide();
		          map.removeMarker(oldMarker)
		        }
		        
		        var dados = { name: result.name, type: result.icon };
		        var marker = map.addMarker(point, dados);
		        marker.enableDragging();
		        marker.owner = true;
		        if (result.date != null && result.date != "")
		        {
		          marker.data_crime = JS.Date.parse(result.date);
		        }
		        else
		        {
		          marker.data_crime = "";
		        }
		        marker.id = result.id;
		        marker.sec_id = result.sec_id;
		        if ((!result.editing) && (markerTemporario != null))
		        {
		          map.removeMarker(markerTemporario);	
		        }
		        marker.show();
			/* OLD
				if (!result.editing) {
					var dados = { name: result.name, type: result.icon };
					var marker = map.addMarker(point, dados);
					marker.enableDragging();
					marker.data_crime = JS.Date.parse(result.date);
					marker.id = result.id;
					marker.sec_id = result.sec_id;
					map.removeMarker(markerTemporario);	
					marker.show();
					//update recent reports								
					$('#last_included').load('/index/get_last_included');								
				}
			*/
				if (markerTemporario) {
					markerTemporario.hideWindow();
				}
				
				if (marker.type == 1){
					openIterativePrecintAskWindow(marker);
				}

			}
			loading(false);
	});

	return false;
}

function openIterativePrecintAskWindow(marker) {
	markerTemporario = marker;
	if (marker.sec_id !== null) {
		loading(true);

			data = '<div id="iterativePrecintDialog">'

							+'<p id="success"> Seu relato foi adicionado com sucesso <img src="/img/ico_success.gif" /> </p>'
							+'<p id="question">J&aacute; registrou essa ocorr&ecirc;ncia na delegacia iterativa?</p>'
							+'<a href="http://www.delegaciainterativa.am.gov.br/" alt="www.google.com" ><img src="/img/bot_delegacia.gif" /></a>'
					+'</div>'

			marker.showWindow(data);
			loading(false);

			tb_init('.thickbox');
			$(".thickbox").click(function(){
				marker.hideWindow();
			})


	}
}

function enviar_form_insert_marco(point) {
	loading(true);

	$("#lat").attr("value",point.lat());
	$("#lng").attr("value",point.lng());

	$.post('/marcos/add', $('#create_marco').formSerialize(), function(req) {
			var result = eval('(' + req + ')');
			if (result.error) {
				txtErrors = '';
				for (var i = 0; i < result.errors.length; i++) {
					txtErrors += '<li>' + result.errors[i] + '</li>';
				}
				$('#errors').html(txtErrors);
			} else {
				//$('#pt1').css('display','none');
				if (!result.editing) {
				//	map.removeMarker(map.getMarker(result.id));
				
					var dados = { name: result.name, type: result.icon };
					var marco = map.addMarco(point, dados);
					marco.enableDragging();
					marco.owner = true;
					marco.sec_id = result.id;
					map.removeMarker(marcoTemporario);	
					marco.show();
					$('#last_included').load('/index/get_last_included');
				}
				
				if (marcoTemporario) {
					marcoTemporario.hideWindow();
				}

			}
			loading(false);
	});

	return false;
}

function openEditWindow(id) {
	loading(true);
	$('#pt1').load('/security_points/open_edit_window/'+id, null, function(){
		$('#pt1').css('display', 'block');
		map.closeWindow();
		loading(false);
	});
}

function showComments(target) {
	if (target == 'comments') {
		$('#add_comments_form_div').css('display', 'none');
		$('.pt-com-cont').css('display', 'block');

		$('#comments').addClass('slct');
		$('#add_comments').removeClass('slct');
	} else if (target == 'add_comments') {
		$('#add_comments_form_div').css('display', 'block');
		$('.pt-com-cont').css('display', 'none');

		$('#comments').removeClass('slct');
		$('#add_comments').addClass('slct');
	}
}

function add_comment_submit() {
	$.post('/security_points/add_comment/',
		{id: $('#comments_field_id').val(), comment: $('#comments_field_comments').val()},
		function(data) {
			var ret = eval('( ' + data + ' )');
			$('#comments').prepend(ret.data.new_comment);
			$('#comments_count').html(ret.data.num_comments);
			$('#baloon .tabs .comments').css('display', 'block');
			$('#comment_form').css('display', 'none');
			$('#new_comment .comment_accepted').css('display', 'block');
		});
	return false;
}

function report_fake_submit() {
		$.post('/security_points/report_fake/',
		{id: $('#fake_report_field_id').val(), comment: $('#fake_report_field_comments').val()},
		function(data) {
			$('#report_fake .report_form').css('display', 'none');
			$('#report_fake .report_accepted').css('display', 'block');
		});
	return false;
}

function send_point_submit() {
	
	var message = $( '#send_point_field_userName' ).val()
			+ ' lhe enviou o seguinte ponto de interesse:\r\n\r\n'
			+ $( '#send_point_field_permalink' ).val();
	
	if ( $( '#send_point_field_comment' ).val() != '' ) {
		message += '\r\n\r\n\r\nComentários:\r\n\r\n' + $( '#send_point_field_comment' ).val();
	}
	$.post( '/security_points/send_point/',
			{ id : $( '#send_point_field_id' ).val(),
					emails : $( '#send_point_field_emails' ).val(),
					message : message },
			function( data ) {
				$( '#send_point .send_form' ).css( 'display', 'none' );
				$( '#send_point .send_accepted' ).css( 'display', 'block' );
			});
}

function deletePoint( id ) {
//	$.post( '/security_points/delete/' + id,
	$.get( '/security_points/delete/' + id,
			null,
			function( data, status ) {
				markerTemporario.hideWindow();
				map.removeMarker(markerTemporario);
				markerTemporario = null;
				//Update reports. If removed marker is a recent, most commented or most viwed report it will removed from de report list -> new_index.thtml -> Relatos
				$('#last_included').load('/index/get_last_included');
				$('#most_commented').load('/index/get_most_commented');
				$('#most_viewed').load('/index/get_most_viewed');
			}
	);		
}

function deleteMarco( id ){
	$.post( '/marcos/delete/' + id,
			null,
			function( data, status ) {
				map.removeMarker(marcoTemporario);
				marcoTemporario = null;				
			});
		//	removeMarcoArea(tempArea);
}

/*
function deactivatePoint( id ) {
	$.ajax({
	    url: '/security_points/deactivate/' + id,
	    type: 'POST',
	    dataType: 'text',
	    timeout: 5000,
	    error: function( XMLHttpRequest, textStatus, errorThrown ) {
	    	
	    	alert( XMLHttpRequest );
	    	alert( textStatus );
	    	alert( errorThrown );
	    	
	    },
	    success: function( data, textStatus ) {
	    	
	    	alert( textStatus );
	    	alert( data );
	    	
	    }
	});		
}
*/
//function searchByTag(tag) {
//	$.get("/security_points/search_by_tag/"+tag, null, function(data) {
//		if ($('#divSearch').size()) {
//			$('#divSearch').html(data);
//		} else {
//			var html = '<div class="titulos">Pontos</div><div class="bsc"><div id="divSearch" class="bsc_rst">';
//			html += data;
//			html += '</div></div></div>';
//			$('#lat-esq').html(html);
//		}
//	});
//}

function findAddress() {
    var address = $('#rua').val() + ' ' + $('#find_city').val() + ', Brazil';
	
	var geocoder = new GClientGeocoder();
	geocoder.getLocations(address, findAddressCallback);
	
	return false;
}

function findAddressCallback(response) {
	if (!response || response.Status.code != 200) {
		alert("Desculpe, houve problemas no servidor. Tente de novo em alguns segundos.");
		log(OP_SEARCH_ADDRESS, false, response.toString());
    } else {
		log(OP_SEARCH_ADDRESS, true, '');
	    //insert all possible addresses in the page's HTML.
	    var str = "<ul>";
	    for(var i = 0; i < response.Placemark.length; i++){

		    str += "<li><a href='#' onclick=\"moveTo(" +  response.Placemark[i].Point.coordinates[1] + ",";
		    str += response.Placemark[i].Point.coordinates[0] +  ",";
		    str += response.Placemark[i].Point.coordinates[2] + ",";
		    str += "'" + response.Placemark[i].address  + "', false); $('#findAddressResult').css('display', 'none'); return false\">" + response.Placemark[i].address + "</a></li>";

	    }

	    str += "</ul>";
		str += '<span class="close"><input type="button" onclick="$(\'#findAddressResult\').css(\'display\', \'none\'); return false" value="fechar" /></span>';
		//this is probably a not very good way to insert HTML in the page because it can be difficult to read the HTML in the str var
	    $('#findAddressResult').css('display','block');
	    $('#findAddressResult').html(str);
    }
}

function showRegularSearch() {
	$('#advanced_catgrs').css('display', 'none');
	$('#advanced_inf-fltr').css('display', 'none');
	$('#regular_catgrs').css('display', 'block');
	$('#regular_inf-fltr').css('display', 'block');

	return false;
}

function showAdvancedSearch() {
	$('#advanced_catgrs').css('display', 'block');
	$('#advanced_inf-fltr').css('display', 'block');
	$('#regular_catgrs').css('display', 'none');
	$('#regular_inf-fltr').css('display', 'none');

	return false;
}

function viewCases(searchMode) {
	$.post("/security_points/search",
		$('#view_points_' + searchMode).formSerialize(),
		function(data) {
			$('#divSearch').html(data);
		});
}

function searchByDate() {
	$.post("/security_points/search_by_date",
		$('#search_by_date').formSerialize(),
		function(data) {
			$('#divSearch').html(data);
		});
}

function hideSearchResults() {
	$('#divSearch').css('display','none');
}

function salvarArea() {
	var lats = '';
	var lngs = '';
	var area = clickedArea;
	
	loading(true);
	area.setName( $( '#areaName' ).val() );
	for (i = 0; i < area.markers.length; i++) {
		lats += area.markers[i].getPoint().lat() + ',';
		lngs += area.markers[i].getPoint().lng() + ',';
	}
	lats = lats.substr(0, (lats.length - 1));
	lngs = lngs.substr(0, (lngs.length - 1));
	if (area.id > 0) {
		$.post('/security_areas/edit',
			{id: area.id, name: area.getName(), lats: lats, longs: lngs},
			function(data) {
				salvarAreaCallback(area, data);
			});
	} else {
		$.post('/security_areas/add',
			{name: area.getName(), lats: lats, longs: lngs},
			function(data) {
				salvarAreaCallback(area, data);
			});
	}

}

function salvarAreaCallback(area, data) {
	ret = eval('('+ data +')');
	if (ret.errors) {
		msg = '';
		for (i = 0; i < ret.errors.length; i++) {
			msg += ret.errors[i] + "\n";
		}
		alert(msg);
	} else {
		area.id = ret.id;
		alert('Área salva com sucesso.');
	}
	loading(false);
}

function salvarDirection( direction_id ) {
	
	var directionPos = getDirectionPosById( direction_id );
	if ( directionPos == -1 ) {
		directionPos = NUM_DIRECTIONS;
	}
	
	var lats = '';
	var lngs = '';
	var directionName = $( '#directionName' ).val();
	
	loading(true);
	
	for ( i = 0 ; i < directions[ directionPos ][ ROUTES ].length ; i++ ) {
		lats += directions[ directionPos ][ ROUTES ][ i ][ START_MARKER ].getPoint().lat() + ',';
		lngs += directions[ directionPos ][ ROUTES ][ i ][ START_MARKER ].getPoint().lng() + ',';
		
	}
	lats += directions[ directionPos ][ ROUTES ][ directions[ directionPos ][ ROUTES ].length - 1 ][ END_MARKER ].getPoint().lat();
	lngs += directions[ directionPos ][ ROUTES ][ directions[ directionPos ][ ROUTES ].length - 1 ][ END_MARKER ].getPoint().lng();
	
	if ( direction_id > -1 ) {
		
		$.post( '/security_directions/edit',
				{ id: direction_id, name: directionName, lats: lats, longs: lngs},
				function( data ) {
					salvarDirectionCallback( directionPos, data );
				});
		
	} else {
		
		$.post( '/security_directions/add',
				{ name: directionName, lats: lats, longs: lngs},
				function( data ) {
					salvarDirectionCallback( directionPos, data );
				});
		
	}
}

function salvarDirectionCallback( directionPos, data ) {
	var ret = eval('('+ data +')');
	var msg = '';
	
	if ( ret.errors ) {
		for (i = 0; i < ret.errors.length; i++) {
			msg += ret.errors[i] + "\n";
		}
		alert( msg );
	} else {
		
		for ( var i = 0 ; i < directions[ directionPos ][ ROUTES ].length ; i++ ) {
			directions[ directionPos ][ ROUTES ][ i ][ START_MARKER ].direction_id = ret.id;
			directions[ directionPos ][ ROUTES ][ i ][ END_MARKER ].direction_id = ret.id;
		}
		
		alert( 'Trajeto salvo com sucesso.' );
	}
	loading(false);
}

function moveTo(x, y, z, strTitle, displayMarker) {
	map.moveTo(x, y, z);
	map.setZoom(16);
	log(OP_ACCESS_ADDRESS_RESULT, true, strTitle);
}

/**
 * Show "loading" message to user. Should be used when any AJAX request is made.
 * For each start call, only one finish call should exist. It works with a global counter
 * (increment and decrement by each request), so one request won't hide the message showed
 * for another request.
 */
function loading(start) {
	if (start) {
		loadingCounter++;
	} else {
		loadingCounter--;
	}
	if (loadingCounter > 0) {
		$('#loading_message').css('display', 'block');
	} else {
		$('#loading_message').css('display', 'none');
		loadingCounter = 0;
	}
}

/**
 * Show "saving" message to user. Should be used when any AJAX request is made.
 * For each start call, only one finish call should exist. It works with a global counter
 * (increment and decrement by each request), so one request won't hide the message showed
 * for another request.
 */
function saving(start) {
	if (start) {
		savingCounter++;
	} else {
		savingCounter--;
	}
	if (savingCounter > 0) {
		$('#saving_message').css('display', 'block');
	} else {
		$('#saving_message').css('display', 'none');
		savingCounter = 0;
	}
}

/* util vars and functions */
d=document;
byId=function(idObj){var obj = d.getElementById(idObj);    return obj;};
byTag=function(_parent,_tagName){var obj = _parent.getElementsByTagName(_tagName);return obj;};
byClass=function(_parent,_tagName,_className){objReturn = new Array(); obj = _parent.getElementsByTagName(_tagName); for(i=0 ; i < obj.length; i++){if(obj[i].className ==_className){objReturn.push(obj[i])}}return objReturn;};
/* util vars and functions */

function initBoxes() {
	var boxes = byClass(d, 'div', 'janela');
	for (var i = 0; i < boxes.length; i++) {
		var openButton = byClass(boxes[i], 'img', 'janela_maximizar');
		_initBoxOpen(openButton[0], boxes[i]);
		var closeButton = byClass(boxes[i], 'img', 'janela_minimizar');
		_initBoxClose(closeButton[0], boxes[i]);
		var options = byClass(boxes[i], 'input', 'citix_category');

		for (var j = 0; j < options.length; j++) {
			_initOptions(options[j]);
		}
//		var button = byClass(boxes[i], 'img', 'janela_visualizar');
//		_initBoxToggleView(button[0], boxes[i]);
	}
}

function _initBoxOpen(elem, box) {
	elem.onclick = function() { openBox(elem, box); };
}

function openBox(elem, box) {
	elem.style.display = 'none';
	var closeButton = byClass(box, 'img', 'janela_minimizar');
	closeButton[0].style.display = 'inline';
	var content = byClass(box, 'div', 'janela_conteudo');
	content[0].style.display = 'block';
}

function _initBoxClose(elem, box) {
	elem.onclick = function() { closeBox(elem, box); };
}

function closeBox(elem, box) {
	elem.style.display = 'none';
	var openButton = byClass(box, 'img', 'janela_maximizar');
	openButton[0].style.display = 'inline';
	var content = byClass(box, 'div', 'janela_conteudo');
	content[0].style.display = 'none';
}

function _initOptions(elem) {
	elem.onclick = function() { toggleOption(elem); };
}

function toggleOption(elem) {
	if (elem.checked) {
		removeFromHiddenCategories(elem.value);

		log(OP_SHOW_CATEGORIES, true, elem.value);
	} else {
		hiddenCategories.push(elem.value);

		log(OP_HIDE_CATEGORIES, true, elem.value);
	}
	map.hideBy(hiddenCategories, filterDates[0], filterDates[1]);
}

function _initBoxToggleView(elem, box) {
	elem.onclick = function() { toggleView(elem, box); };
}

function toggleView(elem, box) {
	var options = byClass(box, 'input', 'citix_category');
	if (elem.className == 'janela_visualizar') {
		elem.className = 'opacity';
		for (var j = 0; j < options.length; j++) {
			options[j].checked = false;
			map.hideByCategory(options[j].value);
			hiddenCategories.push(options[j].value);
		}
	} else {
		elem.className = 'janela_visualizar';
		for (var j = 0; j < options.length; j++) {
			options[j].checked = 'checked';
			map.showByCategory(options[j].value);
			removeFromHiddenCategories(options[j].value);
		}
	}
}

function toggleView2(elem, box) {
	var options = byClass(byId(box), 'input', 'citix_category');
	if (elem.className == "checked") {
		for (var j = 0; j < options.length; j++) {
			options[j].checked = false;
			map.hideByCategory(options[j].value);
			hiddenCategories.push(options[j].value);
			elem.className = "unchecked";
		}

		log(OP_HIDE_ALL_CATEGORIES, true, box);
	} else {
		for (var j = 0; j < options.length; j++) {
			options[j].checked = 'checked';
			map.showByCategory(options[j].value);
			removeFromHiddenCategories(options[j].value);
			elem.className = "checked";
		}

		log(OP_SHOW_ALL_CATEGORIES, true, box);
	}
}

function toggleSubcategories(elem, catClass) {
	var options = $('input.'+catClass);

	if ($(elem).attr('checked')) {
		for (var j = 0; j < options.length; j++) {
			options[j].checked = 'checked';
//			excludeFromBlacklist( options[j].value );
			map.showByCategory(options[j].value);
			removeFromHiddenCategories(options[j].value);
			elem.checked = 'checked'
		}
		log(OP_SHOW_ALL_CATEGORIES, true, elem);
	} else {
		for (var j = 0; j < options.length; j++) {
			options[j].checked = false;
//			includeInBlacklist( options[j].value );
			map.hideByCategory(options[j].value);
			hiddenCategories.push(options[j].value);
			elem.checked = false
		}
		log(OP_HIDE_ALL_CATEGORIES, true, elem);
	}
}

function toggleMyPointsOnly(elem){

	if ($(elem).attr('checked')) {
			map.hideByOwner();
			elem.checked = 'checked'
			updateStats();		
	} else {
			map.showAllMarkers();
			elem.checked = false
			updateStats();
	}
}

function toggleCheck(elem) {
	if ($(elem).attr('checked')) {
		map.showByCategory(elem.value);
		removeFromHiddenCategories(elem.value);
		elem.checked = 'checked'
	} else {
		map.hideByCategory(elem.value);
		hiddenCategories.push(elem.value);
		elem.checked = false
	}
}

function removeFromHiddenCategories(id) {
	for (var i = 0; i < hiddenCategories.length; i++) {
		if (hiddenCategories[i] == id) {
			hiddenCategories.splice(i, 1);
		}
	}
}

function removeFromHiddenCategoriesArray( ids ) {
	for ( var i = 0 ; i < ids.length ; i++ ) {
		removeFromHiddenCategories( ids[ i ] );
	}
}

/*
function initUserAddForm() {
	$('#user_add_cep').blur(function () {
		if (this.value) {
			var geocoder = new GClientGeocoder();
			geocoder.getLocations(this.value + ', Brazil', function (response) {
				if (response && response.Status.code == 200 && response.Placemark.length > 0) {
					var address = response.Placemark[0].address;
					alert(address);
					$('#user_add_address').val(address);
				}
			});
		}
	});
}
*/

var JS = {};
JS.Date = function() {};
JS.Date.parse = function(date) {
	var parts = date.split(' ');
	var dateParts = parts[0].split('/');
	var text = dateParts[1] +'/'+ dateParts[0] +'/'+ dateParts[2] +' '+ parts[1];
	return new Date(text);
};
JS.Date.checkHour = function(hour) {
	var ret = false;
	var parts = hour.split(':');
	if ((parts.length == 2) && (parts[0] >= 0 && parts[0] <= 24) && (parts[1] >= 0 && parts[1] <= 59)) {
		ret = true;
	}
	return ret;
};
JS.Date.checkDate = function (day, month, year) {
	var ret = false;
	var date = new Date(month + '/' + day + '/' + year);
	if ((date !== null) && (date.getDate() == day) && (date.getMonth() == (month - 1))) {
		newYear = date.getYear();
		if (((year > 1999) && (year == (newYear + 1900))) || ((year <=1999) && (year == newYear))) {
			ret = true;
		}
	}
	return ret;
};

function filterByDate() {
	var fields = $('#search_by_date').formToArray();
	var firstDate = new Array(5);
	var secondDate = new Array(5);
	var filterDates = new Array();

	for (var i = 0; i < fields.length; i++) {
		switch (fields[i].name) {
			case 'dia_inicial':
				firstDate[0] = fields[i].value;
				break;
			case 'mes_inicial':
				firstDate[1] = fields[i].value;
				break;
			case 'ano_inicial':
				firstDate[2] = fields[i].value;
				break;
			case 'hora_inicial':
				firstDate[3] = fields[i].value;
				break;
			case 'minuto_inicial':
				firstDate[4] = fields[i].value;
				break;
			case 'dia_final':
				secondDate[0] = fields[i].value;
				break;
			case 'mes_final':
				secondDate[1] = fields[i].value;
				break;
			case 'ano_final':
				secondDate[2] = fields[i].value;
				break;
			case 'hora_final':
				secondDate[3] = fields[i].value;
				break;
			case 'minuto_final':
				secondDate[4] = fields[i].value;
				break;
		}
	}

	//Validate dates
	var datesAsString = '';
	filterDates[0] = null;
	if (JS.Date.checkDate(firstDate[0], firstDate[1], firstDate[2]) && JS.Date.checkHour(firstDate[3] + ':' + firstDate[4])) {
		filterDates[0] = new Date(firstDate[1] + '/' + firstDate[0] + '/' + firstDate[2] + ' ' + firstDate[3] + ':' + firstDate[4]);
		datesAsString += '1: ' +  filterDates[0].toString();
	}
	filterDates[1] = null;
	if (JS.Date.checkDate(secondDate[0], secondDate[1], secondDate[2]) && JS.Date.checkHour(secondDate[3] + ':' + secondDate[4])) {
		filterDates[1] = new Date(secondDate[1] + '/' + secondDate[0] + '/' + secondDate[2] + ' ' + secondDate[3] + ':' + secondDate[4]);
		datesAsString += ' - 2: ' +  filterDates[1].toString();
	}
	if ((filterDates[0] !== null) && (filterDates[1] !== null) && (filterDates[0] > filterDates[1])) {
		alert( 'Intervalo inválido.' );

		log(OP_FILTER_BY_DATE, false, datesAsString);
	} else {
		map.hideBy(hiddenCategories, filterDates[0], filterDates[1]);

		log(OP_FILTER_BY_DATE, true, datesAsString);
	}
}

function voltar() {
	$("#lat-esq").html(filtros);

	log(OP_BACK_FROM_COMPLETE_POINT, true, '');
}

function log(op, success, comments) {
	$.post('/index/log_action/', {op: op, success: success, comments: comments});
}

function update_stats(id) {
	var div = $('#' + id).get();
	var form = $('.stats_form', div).get()[0];
	var select = $('.stats_selection', div).get()[0];

	$.getJSON(form.action + id, {date_period: select.value}, function(result) {
		if (!result.error) {
			var table = $('.stats_table', div).get()[0];
			$('tr', table).remove();
			if (result.length > 0) {
				for (var i = 0; i < result.length; i++) {
					$(table).append('<tr><td>'+ result[i][0] +'</td><td>' + result[i][1] + '</td></tr>');
				}
			} else {
				$(table).append('<tr><td colspan=2>N&atilde;o h&aacute; resultados para este per&iacute;odo</td></tr>');
			}
		}
	});
}

// funcoes pra tela de login
function esqueciSenha() {
	// TODO: verificar se o email Ã© vÃ¡lido / fazer um if
//	$("#login_message").text("Informe um email, por favor.")
	$.get("/users/lostPassword/"+byId('email').value, null, function(data) {
		$("form#login #login_message").html(data);
	})
}

function toggleTabs(elem) {
	$('#tabs li').removeClass('active');
	$(elem).addClass('active');

	if (elem.id == 'tab_index') {
		$('#conteudo_index').css('display', 'block');
		$('#conteudo_meu_mapa').css('display', 'none');
	} else {
		$('#conteudo_index').css('display', 'none');
		$('#conteudo_meu_mapa').css('display', 'block');

		$("#meuMapaHits").empty();
    	$("#meuMapaHits").append('<h2><img src="/imagens/loading2.gif" /> Pesquisando...</h2>');
    	loadMyMap();
	}
}

function selectMyMapViews(elem) {
	switch (elem.value) {
		case 'pontos':
			$('#meuMapaHits .meu_ponto').css('display', 'block');
			$('#meuMapaHits .minha_area').css('display', 'none');
			$('#meuMapaHits .meu_marco').css('display', 'none');
			$('#meuMapaHits .minha_direcao').css('display', 'none');		
			break;
		case 'areas':
			$('#meuMapaHits .meu_ponto').css('display', 'none');
			$('#meuMapaHits .minha_area').css('display', 'block');
			$('#meuMapaHits .meu_marco').css('display', 'none');
			$('#meuMapaHits .minha_direcao').css('display', 'none');		
			break;
		case 'marcos':
			$('#meuMapaHits .meu_ponto').css('display', 'none');
			$('#meuMapaHits .minha_area').css('display', 'none');
			$('#meuMapaHits .meu_marco').css('display', 'block');
			$('#meuMapaHits .minha_direcao').css('display', 'none');
			break;		
		case 'direcoes':
			$('#meuMapaHits .meu_ponto').css('display', 'none');
			$('#meuMapaHits .minha_area').css('display', 'none');
			$('#meuMapaHits .meu_marco').css('display', 'none');					
			$('#meuMapaHits .minha_direcao').css('display', 'block');		
			break;
		default:
			$('#meuMapaHits .meu_ponto').css('display', 'block');
			$('#meuMapaHits .minha_area').css('display', 'block');
			$('#meuMapaHits .meu_marco').css('display', 'block');
			$('#meuMapaHits .minha_direcao').css('display', 'block');		
	}
}

function updatePeriodText() {
	//(<strong>17/02/2008</strong> a <strong>23/02/2008</strong>, das <strong>6:00</strong> ï¿½s <strong>12:00</strong>)
	text = '(<strong>';
	date = null;
	startHour = '00:00';
	endHour = '24:00';

	switch($('#periodDaySelect').val()) {
		case 'last_6_months':
			date = (6).months().ago();
			text += (6).months().ago().toString('dd/MM/yyyy') + '</strong> a <strong>';
			break;
		case 'last_3_months':
			date = (3).months().ago();
			text += (3).months().ago().toString('dd/MM/yyyy') + '</strong> a <strong>';
			break;
		case 'last_month':
			date = (1).months().ago();
			text += (1).months().ago().toString('dd/MM/yyyy') + '</strong> a <strong>';
			break;
		case 'last_week':
			date = Date.today();
			text += Date.today().last().week().toString('dd/MM/yyyy') + '</strong> a <strong>';
			break;
	}
	text += Date.today().toString('dd/MM/yyyy') + '</strong>';

	switch($('#periodHourSelect').val()) {
		case 'morning':
			text += ', das <strong>6:00</strong> &agrave;s <strong>12:00</strong>';
			startHour = '06:00';
			endHour = '12:00';
			break;
		case 'evening':
			text += ', das <strong>12:00</strong> &agrave;s <strong>18:00</strong>';
			startHour = '12:00';
			endHour = '18:00';
			break;
		case 'night':
			text += ', das <strong>18:00</strong> &agrave;s <strong>24:00</strong>';
			startHour = '18:00';
			endHour = '24:00';
			break;
		case 'early_morning':
			text += ', das <strong>0:00</strong> &agrave;s <strong>6:00</strong>';
			startHour = '00:00';
			endHour = '06:00';
			break;
	}
	text += ')';
	$('#periodText').html(text);
  if (map !== null)
  {
    map.hideByHourPeriod(hiddenCategories, date, startHour, endHour);
  }
	updateStats();
	log(OP_FILTER_BY_DATE, true, '');
}


/*
function updateStats() {
	
    var html = '';
	var parentCategories = new Array();
	parentCategories[1] = 0;
	parentCategories[9] = 1;
	parentCategories[17] = 2;
	parentCategories[24] = 3;
	parentCategories[31] = 4;
	
	var colours = new Array("#FF0000", "#FF9900", "#339900", "#CC00CC", "#00609B");
	var labels = new Array("Seguran&ccedil;a", "Infra-estrutura", "Servi&ccedil;os P&uacute;blicos", "Entretenimento", "Institui&ccedil;&otilde;es");
	
    //Find points in area
	var values = new Array(0,0,0,0,0);
	
	//calculate visible occorrences in area
	//var markers = map.getMarkersInArea(area);
	var markers = map.getMarkersInBoundaries();
	var total = markers.length;
	if (total > 0) {
		var sum = new Array(0,0,0,0,0);
		for (var i = 0; i < total; i++) {
			sum[parentCategories[markers[i].parent_category]]++;
		}
		values = sum;
	}
	
    $('#stats .bar').remove();
	
	for(var i = 0; i < labels.length; i++) {
	    size = ((100 * values[i]) / total);
		
		// reduce size to make space to number appear in same line
		if (size > 80) {
			size = 80;
		}
		html += '<li class="bar"><div class="stats_bar" style="background-color:';
		html += colours[i];
		html += '; min-width:1px; width:' + size;
		html += '%;">&nbsp;</div>&nbsp; '+ values[i] +'&nbsp;<strong>'+ labels[i] +'</strong></li>';
	}
	
	$( '#stats li.footer' ).before( html );
	$( '#stats #stats_count' ).html( total );
}
*/

function updateStats() {
	
	var selected = $( '#stats_select' ).val();
	var type     = $( '#stats_select option:selected' ).attr( 'title' );
	
	if ( selected != undefined
			&& type != undefined ) {
		if ( selected == 'visible'
				|| type == 'all' ) {
		//	removeMarcoArea(tempArea);
			updateStatsViewPort();
		} else {
			if ( type == 'area' ) {
				removeMarcoArea(tempArea);
				updateStatsArea( selected );
			} else if ( type == 'direction' ) {
				removeMarcoArea(tempArea);
				updateStatsDirection( selected );
			} else if (type == 'marco'){
				buildAreaInMarcoBounds(map.getMarker(selected));
				updateStatsMarco(selected);
			} 
		}
	}
}

function updateStatsViewPort() {
	var parentCategories = new Array();
	parentCategories[1] = 0;
	parentCategories[9] = 1;
	parentCategories[17] = 2;
	parentCategories[24] = 3;
	parentCategories[31] = 4;
	
    //Find points in area
	var values = new Array( 0, 0, 0, 0, 0 );
	
	//calculate visible occorrences in area
	//var markers = map.getMarkersInArea(area);
	var markers = map.getMarkersInBoundaries();
	var total = markers.length;
	if (total > 0) {
		var sum = new Array( 0, 0, 0, 0, 0 );
		for (var i = 0; i < total; i++) {
			sum[parentCategories[markers[i].parent_category]]++;
		}
		values = sum;
	}
	updateStatsByValues( values, total );
}

function updateStatsMarco( marcoId ) {
	var parentCategories = new Array();
	parentCategories[1] = 0;
	parentCategories[9] = 1;
	parentCategories[17] = 2;
	parentCategories[24] = 3;
	parentCategories[31] = 4;
    //Find points in area
	var values = new Array( 0, 0, 0, 0, 0 );
	//calculate visible occorrences in area
	var marco = map.getMarker( marcoId );
	if ( marco != null ) {
		var markers = map.getMarkersInMarcoBoundaries( marco );
		var total = markers.length;	
		if (total > 0) {
			var sum = new Array( 0, 0, 0, 0, 0 );
			for (var i = 0; i < total; i++) {
				sum[parentCategories[markers[i].parent_category]]++;
			}
			values = sum;			
		}
		updateStatsByValues( values, total );
	}
}

function updateStatsArea( areaId ) {
	var parentCategories = new Array();
	parentCategories[1] = 0;
	parentCategories[9] = 1;
	parentCategories[17] = 2;
	parentCategories[24] = 3;
	parentCategories[31] = 4;
	
    //Find points in area
	var values = new Array( 0, 0, 0, 0, 0 );
	
	//calculate visible occorrences in area
	var area = map.getArea( areaId );
	if ( area != null ) {
		var markers = map.getMarkersInArea( area );

		var total = markers.length;

		if (total > 0) {
			var sum = new Array( 0, 0, 0, 0, 0 );
			for (var i = 0; i < total; i++) {
				sum[parentCategories[markers[i].parent_category]]++;
			}
			values = sum;
		}	
		updateStatsByValues( values, total );
	}
}

function updateStatsDirection( directionId ) {
	var parentCategories = new Array();
	parentCategories[1] = 0;
	parentCategories[9] = 1;
	parentCategories[17] = 2;
	parentCategories[24] = 3;
	parentCategories[31] = 4;
	
    //Find points in area
	var values = new Array( 0, 0, 0, 0, 0 );
	
	//calculate visible occorrences near direction
	var directionPos = getDirectionPosById( directionId );
	var direction    = null;
	if ( directionPos > -1 ) {
		direction = directions[ directionPos ];
	}
	if ( direction != null ) {
		var markers = getMarkersNearDirection( direction, 200 );
		var total = markers.length;
		if ( total > 0 ) {
			var sum = new Array( 0, 0, 0, 0, 0 );
			for ( var i = 0 ; i < total ; i++ ) {
				sum[ parentCategories[ markers[ i ].parent_category ] ]++;
			}
			values = sum;
		}
		var marcos = map.getMarcosInBoundaries();
		total = total - marcos.length;
		updateStatsByValues( values, total );
	}
}

/*
 * values -> Array( 0, 0, 0, 0, 0 )
 *                  |  |  |  |  |
 *                  |  |  |  |  \-> Instituições
 *                  |  |  |  \----> Entretenimento
 *                  |  |  \-------> Serviços Públicos
 *                  |  \----------> Infra-estrutura
 *                  \-------------> Segurança
 *
 * total  -> quantidade total de pontos compondo a estatística
 */
function updateStatsByValues( values, total ) {
    var html = '';
    
	var colours = new Array("#FF0000", "#FF9900", "#339900", "#CC00CC", "#00609B");
	var labels = new Array("Seguran&ccedil;a", "Infra-estrutura", "Servi&ccedil;os P&uacute;blicos", "Entretenimento", "Institui&ccedil;&otilde;es");
	
    $('#stats .bar').remove();

	if(total < 0){
		total = 0 ;
	}
	
	for(var i = 0; i < labels.length; i++) {
	    size = ((100 * values[i]) / total);
		
		// reduce size to make space to number appear in same line
		if (size > 80) {
			size = 80;
		}
		html += '<li class="bar"><div class="stats_bar" style="background-color:';
		html += colours[i];
		html += '; min-width:1px; width:' + size;
		html += '%;">&nbsp;</div>&nbsp; '+ values[i] +'&nbsp;<strong>'+ labels[i] +'</strong></li>';
	}
	
	$( '#stats li.footer' ).before( html );
	$( '#stats #stats_count' ).html( total );
}

function updateComboStats() {
	
	var localAreas      = map.getAreasInBoundaries();
	var localDirections = map.getDirectionsInBoundaries( directions );
	var localMarcos		= map.getMarcosInBoundaries();
		
	$( '#stats_select option' ).remove();
	
	for ( var i = 0 ; i < localAreas.length ; i++ ) {
		if ( localAreas[ i ].id >= 0 ) {
			$( '#stats_select' ).append( '<option title="area" value="' + localAreas[ i ].id + '">' + localAreas[ i ].getName() + '</option>' );
		}
	}
	
	for ( var i = 0 ; i < localDirections.length ; i++ ) {
		if ( localDirections[ i ][ ID ] >= 0 ) {
			$( '#stats_select' ).append( '<option title="direction" value="' + localDirections[ i ][ ID ] + '">' + localDirections[ i ][ NAME ] + '</option>' );
		}
	}
	
	for ( var i = 0 ; i < localMarcos.length ; i++ ) {
		if ( localMarcos[ i ].id >= 0 ) {
			$( '#stats_select' ).append( '<option title="marco" value="' + localMarcos[ i ].id + '">' + localMarcos[ i ].getName() + '</option>' );
		}
	}	
	$( '#stats_select' ).append( '<option selected="selected" title="all" value="visible">da &aacute;rea vis&iacute;vel</option>' );
	updateStats();
}

function moveToSelectedCity() {
	var cityName = $('#find_city').selectedValues();
	cityName = cityName[0];
	
	for (var i = 0; i < cities.length; i++) {
		if (cities[i].name == cityName) {
			map.moveTo(cities[i].lat, cities[i].lng, 0);
			map.setZoom(13);			
			break;
		}
	}
}

function loadBlacklist() {
	
	$.ajax({
		async: false,
		url: '/users/load_blacklist/',
		type: 'POST',
		data: { },
		dataType: 'text',
		timeout: 5000,
		error: function( XMLHttpRequest, textStatus, errorThrown ) {
			//alert( XMLHttpRequest ); alert( textStatus ); alert( errorThrown );
		},
		success: function( data, textStatus ) {
			//alert( 'loadBlacklist (success) - ' + data );
			var blacklist = null;
      
      try
      {
        blacklist = eval( '(' + data + ')' );
      }
      catch (error)
      {
      }
      
			
			if ((blacklist != null) && (blacklist.status)) {
				for ( var i = 0 ; i < blacklist.blacklist.length ; i++ ) {
					var crimeTypeId = blacklist.blacklist[ i ][ 0 ].crime_type_id;
					$( '#category' + crimeTypeId ).attr( 'checked', false );
					$( '#subcategory_' + crimeTypeId ).attr( 'checked', false );
					
					map.hideByCategory( crimeTypeId );
					hiddenCategories.push( crimeTypeId );
				} 
			}
		}
	});
	
}

function includeInBlacklist( crimeType ) {
	saving( true );
	
	$.ajax({
		async: true,
		url: '/users/include_in_blacklist/',
		type: 'POST',
		data: { crimeType : crimeType },
		dataType: 'text',
		timeout: 5000,
		error: function( XMLHttpRequest, textStatus, errorThrown ) {
			saving( false );
			//alert( XMLHttpRequest ); alert( textStatus ); alert( errorThrown );
		},
		success: function( data, textStatus ) {
			hiddenCategories.push( crimeType );
			saving( false );
			//alert( textStatus ); alert( data );
		}
	});
}

function includeInBlacklistArray( crimeTypes ) {
	saving( true );
	
	$.ajax({
		async: true,
		url: '/users/include_in_blacklist_array/',
		type: 'POST',
		data: { crimeTypes : crimeTypes.join( ',' ) },
		dataType: 'text',
		timeout: 5000,
		error: function( XMLHttpRequest, textStatus, errorThrown ) {
			saving( false );
			//alert( XMLHttpRequest ); alert( textStatus ); alert( errorThrown );
		},
		success: function( data, textStatus ) {
			hiddenCategories = hiddenCategories.concat( crimeTypes );
			saving( false );
			//alert( textStatus ); alert( data );
		}
	});
}

function excludeFromBlacklist( crimeType ) {
	saving( true );
	
	$.ajax({
		async: true,
		url: '/users/exclude_from_blacklist/',
		type: 'POST',
		data: { crimeType : crimeType },
		dataType: 'text',
		timeout: 5000,
		error: function( XMLHttpRequest, textStatus, errorThrown ) {
			saving( false );
			//alert( XMLHttpRequest ); alert( textStatus ); alert( errorThrown );
		},
		success: function( data, textStatus ) {
			removeFromHiddenCategories( crimeType );
			saving( false );
			//alert( textStatus ); alert( data );
		}
	});
}

function excludeFromBlacklistArray( crimeTypes ) {
	saving( true );
	
	$.ajax({
		async: true,
		url: '/users/exclude_from_blacklist_array/',
		type: 'POST',
		data: { crimeTypes : crimeTypes.join( ',' ) },
		dataType: 'text',
		timeout: 5000,
		error: function( XMLHttpRequest, textStatus, errorThrown ) {
			saving( false );
			//alert( XMLHttpRequest ); alert( textStatus ); alert( errorThrown );
		},
		success: function( data, textStatus ) {
			removeFromHiddenCategoriesArray( crimeTypes );
			saving( false );
			//alert( textStatus ); alert( data );
		}
	});
}

function kraCitixMsnControll(){
	$('#msn_dialog').dialog({
		autoOpen: false,
		width: 300,

	});
	
	// Dialog Link
	$('#msn_dialog_link').click(function(){
		// msn do kra citix recife -> login: kracitix.recife@hotmail.co.uk | nunca por a senha aqui
		var txt = '<iframe src="http://settings.messenger.live.com/Conversation/IMMe.aspx?invitee=f60e37521ab06e25@apps.messenger.live.com&mkt=en-US" width="300" height="300" style="width: 300px; height: 300px;" frameborder="0"></iframe>';
		$('#msn_dialog').html(txt);
		$('#msn_dialog').dialog('open');
		return false;
	});
	
	//hover states on the static widgets
	$('#msn_dialog_link, ul#icons li').hover(
		function() { $(this).addClass('ui-state-hover'); }, 
		function() { $(this).removeClass('ui-state-hover'); }
	);
}

$( document ).ready( function() {
	load();
	
	kraCitixMsnControll();
	
	// categories behavior
	$("fieldset.categories a").click( function() { 
		$("#categoriesFilter").toggle()
	})
	$("span.close input").click ( function() { $("#categoriesFilter").css('display','none'); updateStats(); })
	$("ul.categoryMacro li").mouseover( function() {
		$("ul.categoryMacro li").css('backgroundColor', 'white');
		$(this).css('backgroundColor', '#C3E5FF');
		var _class = $(this).attr('class');
		$('ul.subcategories').css('display', 'none');
		$('ul.' + _class).css('display', 'block');
	});
	
	// expand and collapse stats
	$("#showHideStats").click( function() {
		if (  $("#showHideStats").attr('src') == '/img/arrow_right.png' )  {
			$("#stats").animate( { opacity:0 } ,500 )
			$("#googlemap").animate( { marginRight:"3px" } ,500)
			$("#showHideStats").animate( { right:"3px" })
			$("#showHideStats").attr('src','/img/arrow_left.png')
		} else {
			$("#showHideStats").attr('src','/img/arrow_right.png')
			$("#googlemap").animate( { marginRight:"125px" } ,500 )
			$("#showHideStats").animate( { right:"125px" })
			$("#stats").animate( { opacity:1 } ,500 )
		}
	});
	
	$('#tabs li').click( function() { toggleTabs(this) } );
	$('#meu_mapa_select').change( function() { selectMyMapViews(this) } );
	
	$('#periodDaySelect').change( function() { updatePeriodText() } );
	$('#periodHourSelect').change( function() { updatePeriodText() } );
	updatePeriodText();
	
	$( '#point'     ).click( function() { changeState( ST_INSERTING_MARK ) } );
	$( '#area'      ).click( function() { changeState( ST_INSERTING_AREA_POINT ) } );
	$( '#direction' ).click( function() { changeState( ST_INSERTING_DIRECTION ) } );
	$( '#marco'       ).click( function() { changeState( ST_INSERTING_MARCO ) } );
	
//	updateStats();
	
	$( '#find_address' ).click( function() { findAddress(); return false; });
	
	$( '#stats_select' ).change( function() { updateStats(); } );
	
	$('#find_city').change( function() { moveToSelectedCity(); });
	
	$( '#filters #categoriesFilter ul input' ).change( function() {
				var options = $( 'input.' + $( this ).attr( 'id' ) );
				
				var crimeTypes = new Array();
				crimeTypes.push( $( this ).val() );
				for ( var i = 0 ; i < options.length ; i++ ) {
					crimeTypes.push( options[ i ].value );
				}
				
				if ( $( this ).attr( 'checked' ) ) {
					excludeFromBlacklistArray( crimeTypes );
				} else {
					includeInBlacklistArray( crimeTypes );
				}
			}
	);
	
	$( '#filters #categoriesFilter ul.subcategories input' ).change( function() {
				if ( $( this ).attr( 'checked' ) ) {
					excludeFromBlacklist( $( this ).val() );
				} else {
					includeInBlacklist( $( this ).val() );
				}
			}
	);

	/*
      $( '#filters #find_address_form a' ).click( function() {
      */
	$( '#filters #find_address_form a' ).click( function() {
		/*
			$.ajax({
				async: false,
					url: '/index/get_feed/citIX.rss',
					type: 'POST',
					data: {  },
					dataType: 'xml',
					timeout: 5000,
					error: function( XMLHttpRequest, textStatus, errorThrown ) {
					alert( 'feed error' ); alert( XMLHttpRequest ); alert( textStatus ); alert( errorThrown );
					},
					success: function( data, textStatus ) {
					alert( 'feed sucess' ); alert( data ); alert( textStatus );
				}
			});
			*/
			window.open( '/index/get_feed/citIX.rss' );
		}
	);
	
	loadBlacklist();
	
	/*
	$('#rua').datepicker({
		closeText: 'x',
		clearText: ' ',
		hideIfNoPrevNext: true,
		showOtherMonths: true,
		prevText: '<',
		nextText: '>',
	})
	*/
});
