var clickListener = null;
var map;
var mgr;
var zoom1 = 7;
var markerSet = false;
var loggedIn = false;
var infoWindowWidth = 100;
var placedLatLng = null;
var me;
var lastMsgDate = new Date();
var markers = new Array();
var hm = new Array();
var nmc = null;

$(document).ready(function(){
	document.title = "CTM - Fellowship Finder";
	$("#map-zoom").click(showMap );
	initialize();
	$("#message-list > ul").tabs();
	lastMsgDate.setTime(0);

});
   
   
  function showMarker(uuid) {
  	
    var target = markers[uuid];
    if (target != null) {
    	showMap();
    	map.setCenter(target.getLatLng(), 7);
    	
    }
  }
  
  function hideMap() {
  	$("#map-content").hide(250);
  	$("#map-zoom").show();
  }
  function showMap() {
  	$("#map-content").show(250);
  }
  
  function startPlaceMarker(overlay, latlng, overlaylatlng) {
  	removeClickListener();
  	if (markerSet)
  		return;
  	placedLatLng = latlng;
  	var s ='<div id="drop-marker-form">Enter a brief message that will be displayed when someone clicks your marker.<textarea id="drop-marker-msg" name="drop-marker-msg" rows=5 cols=20></textarea><br/><button type="button" id="drop-marker-submit" name="drop-marker-submit" value="submit" onclick="placeMarker();">Submit</button><button type="button" id="drop-marker-cancel" name="drop-marker-cancel" value="cancel" onclick="cancelPlaceMarker()" >Cancel</button></div>';
	
  	map.openInfoWindowHtml(latlng, s, { onCloseFn : cancelPlaceMarker });
   
  	placedLatLng = latlng;
  
  }
  function cancelPlaceMarker() {
  	map.closeInfoWindow();
    addClickListener();
  }
  function placeMarker() {
  	var msg = $("#drop-marker-msg").val();
  	$.ajax({
		type: "GET",
		url : "ajax-get-position.php",
		dataType : "json",
		async : true,
		data: {lat : placedLatLng.lat(), lng : placedLatLng.lng(), action : 'set-position', msg: msg },
		success: function(json){
			
			var latlng = new GLatLng(json.lat, json.lng);
			var letteredIcon = makeMyMarker();
    		marker     = new GMarker(latlng, {icon:letteredIcon, draggable: true});
			marker.ctm = json;
			me = marker;
			GEvent.addListener(marker,"click", myMarkerClick);
			GEvent.addListener(marker,"dragend", myMarkerMove);
			mgr.addMarker(marker, zoom1);
			markers[json.uuid] = marker;
			map.closeInfoWindow();
			//removeClickListener();
			getAllPositions();
			mgr.refresh();
			marked();
  		}
	});
  
  }
  function updateMarker() {
  	var msg = $("#drop-marker-msg").val();
  	$.ajax({
		type: "GET",
		url : "ajax-get-position.php",
		dataType : "json",
		async : true,
		data: {action : 'update-marker', msg: msg },
		success: function(json){
			me.ctm.msg = msg;
			map.closeInfoWindow();
  		}
	});
  
  }
  function deleteMyMarker() {
  	
  	$.ajax({
		type: "GET",
		url : "ajax-get-position.php",
		dataType : "json",
		async : true,
		data: {action : 'delete-marker' },
		success: function(json){
			window.location.reload();
  		}
	});
  
  }
  function myMarkerMove(latlng) {
  	$.ajax({
		type: "GET",
		url : "ajax-get-position.php",
		dataType : "json",
		async : false,
		cache: false,
		data: {lat : latlng.lat(), lng : latlng.lng(), action : 'update-position'},
		success: function(json){
			
			mgr.refresh();
			
  		}
	});
  
  }
  function marked() {
  		markerSet = true;
  		$("#nomarker").hide();
		removeClickListener();
  		map.addControl(new TextualZoomControl());
		$("#messages").show();
		map.removeControl(nmc);
  }
  function displayNoLogin() {
  	
  	map.addControl(new NoLoginControl());
  }
  
  function displayNoMarker() {
  	nmc = new NoMarkerControl();
  	map.addControl(nmc);
  	
  }
  function getAllPositions() {
  	$.ajax({
  		type: "GET",
		url : "ajax-get-position.php",
		dataType : "json",
		async: true,
		data: { action : 'get-all-positions'},
		success: function(json){
			
			for(var j in json) {
				var j = json[j];
				var blueIcon = new GIcon(G_DEFAULT_ICON);
				var latlng = new GLatLng(j.lat, j.lng);
				var marker = new GMarker(latlng, { icon:blueIcon , draggable: false});
				marker.ctm = j;
				GEvent.addListener(marker,"click", markerClick);
				mgr.addMarker(marker, zoom1);
				markers[j.uuid] = marker;
			} 
			getAllPositionsHigh();
			mgr.refresh();
  		}
  	});
  	
  }
  function highMarkerClick() {
  		var myHtml = "<div id=\"high-marker\">This region contains "+this.ctm.msg+" marker"+(this.ctm.msg>1?'s':'')+". <br/><a href=\"javascript:map.setZoom("+zoom1+")\">Zoom in closer to see individual markers</a></div>";
		this.openInfoWindowHtml(myHtml, { maxWidth: infoWindowWidth});
  
  }
  function markerClick() {
  	var tabs = new Array();
  	var tab1Str = "<div id=\"user-message-tab\">"+this.ctm.msg+"</div>";
  	var tab2Str = "<div id=\"send-message-tab\">Subject: <input id=\"subject\" name=\"subject\" size=20/><br/>";
  	tab2Str += "Message: <textarea id=\"message-text\" name=\"message-text\" rows=7 columns=30></textarea><br/><input type=button id=\"message-send\" name=\"message-send\" value='Send' onClick=\"sendMessage('"+this.ctm.uuid+"')\"></input><br/><div id=\"message-error\"></div></div>";
  	tabs.push(new GInfoWindowTab('Person', tab1Str));
  	var dt = new Date();
  	if (((lastMsgDate.getTime()/1000)+120) >= (dt.getTime()/1000)) {
  		tab2Str = "You must wait 2 minutes between messages to prevent spam.  Close this dialog and wait for the 2 minutes to pass.";
  	}
  	tabs.push(new GInfoWindowTab('Contact', tab2Str));
  	
  	
  	this.openInfoWindowTabsHtml(tabs,{ maxWidth: 500});
  }
  function myMarkerClick() {
  	var myHtml = "<div id=\"marker\">This is your marker.<br/>";
  	myHtml += "Edit the message below to change your greeting.</div>";
  	  	var s ='<div id="drop-marker-form">';
  	  	s += '<textarea id="drop-marker-msg" name="drop-marker-msg" rows=5 cols=20>';
  	  	s += me.ctm.msg;
  	  	s += '</textarea><br/>';
  	  	s += '<button type="button" id="drop-marker-submit" name="drop-marker-submit" value="submit" onclick="updateMarker();">Submit</button>';
  	  	s += '<button type="button" id="drop-marker-cancel" name="drop-marker-cancel" value="cancel" onclick="map.closeInfoWindow()" >Cancel</button>';
  	  	s += '<br/>';
  	  	s += 'To complely remove your information: <button type="button" id="drop-marker-delete" name="drop-marker-delete" value="Delete" onclick="$(\'#drop-marker-form\').hide();$(\'#delete-marker-warning\').show();" >Delete Marker</button></div>';
  	  	s += '<div id="delete-marker-warning" style="display: none" ><span class="warning">Deleting your marker will remove you from the map and erase all messages that you have sent or received.  Are you sure?</span>';
  	  	s += '<button type="button" id="delete-marker-cancel" name="delete-marker-cancel" value="cancel" onclick="map.closeInfoWindow()" >Cancel</button>';
  	  	s += '<button type="button" id="drop-marker-delete-yes" name="drop-marker-delete-yes" value="Delete" onclick="deleteMyMarker()" >Yes, Delete</button>';
  	  	s += '</div>';
	myHtml += s;
  	this.openInfoWindowHtml(myHtml,{ maxWidth: infoWindowWidth});
  }
  
  function reportAbuse(msgId) {
  	$.ajax({
  	 	type : "POST",
  	 	url : "ajax-sf-message.php",
  	 	dataType : "json",
  	 	async: true,
  	 	cache : false,
  	 	data : { msgId : msgId, action: 'report-abuse'},
  	 	success : function(json) {
  	 		if (json.status == "success") {
  	 			$("#envelope-actions").append("Abuse reported.  You may delete the offending message.");
  	 		} else {
  	 			$("#envelope-actions").append("Message not sent, something broke somewhere.");
  	 		}
  	 	}
  	 });
  }
  function replyTo(msgId) {
    f = '<div id="reply-'+msgId+'" class="message-reply"><label for="subject">Subject:</label><input name="subject" id="subject" value="Re: '+
    	$("#msgsubj-"+msgId).text()+'" size=40><br/>'+
    	'<label for="message-text">Message:</label>'+
    	'<textarea id="message-text" name="message-text" rows=10 cols=40></textarea><br/>'+
    	'<input type=button id="send-message" name="send-message" onclick="sendMessage(\''+$("#msguuid-"+msgId).text()+'\')" value="Send" />&nbsp;'+
    	'<input type=button id="cancel-message" name="cancel-message" onclick="cancelReply('+msgId+')" value="Cancel" />'+
    	'<span id="send-message-tab"></span>'+
    	'</div>';
  	$("#msgtext-"+msgId).append(f);
    me.replyToCallback = function() {
    	$("#reply-"+msgId).remove();
    	me.replyToCallback = null;
    };
  }
  function cancelReply(msgId) {
  	$("#reply-"+msgId).remove();
  
  }
  function deleteMessage(msgId) {
   $.ajax({
  	 	type : "POST",
  	 	url : "ajax-sf-message.php",
  	 	dataType : "json",
  	 	async: true,
  	 	cache : false,
  	 	data : { msgId : msgId, action: 'delete-message'},
  	 	success : function(json) {
  	 		if (json.status == "success") {
  	 			$("#msgrow-"+msgId).remove();
  	 		} else {
  	 			$("#send-message-tab").html("Message not sent, something broke somewhere.");
  	 		}
  	 	}
  	 });
  }
  function showMessage(msgUuid, received) {
  	 $.ajax({
  	 	type : "POST",
  	 	url : "ajax-sf-message.php",
  	 	dataType : "json",
  	 	async: true,
  	 	cache : false,
  	 	data : { msgId : msgUuid, action: 'get-message', received: received },
  	 	success : function(json) {
  	 		if (json.status == "success") {
  	 			$("[id^='msgtext-']").hide();
  	 			$(".message-reply").remove();
  	 			$("#msgtext-"+msgUuid).html(json.text).show();
  	 			$("#msgrow-"+msgUuid).removeClass("new-message");
  	 		} else {
  	 			$("#send-message-tab").html("Message not sent, something broke somewhere.");
  	 		}
  	 	}
  	 });
  
  }
  function sendMessage(toUuid, callback) {
  	 var msg = $("#message-text").val();
  	 var subject = $("#subject").val();
  	 if ((subject == "") || (msg == "")) {
  	 	$("#message-error").html("Please enter a subject and a brief message");
  	 	return;
  	 }
  	 $.ajax({
  	 	type : "POST",
  	 	url : "ajax-sf-message.php",
  	 	dataType : "json",
  	 	async: true,
  	 	cache : false,
  	 	data : { to: toUuid, from: me.ctm.uuid, msg: msg, subject: subject, action: 'send-message' },
  	 	success : function(json) {
  	 		if (json.status == "success") {
  	 			$("#send-message-tab").html("Message Sent Successfully");
  	 			lastMsgDate = new Date();
  	 			if (me.replyToCallback != null)
  	 				me.replyToCallback();
  	 		} else if (json.status == "toosoon") {
  	 			$("#send-message-tab").html("Message not sent, you must wait 2 minutes between messages to prevent spam.");
  	 		} else {
  	 			$("#send-message-tab").html("Message not sent, something broke somewhere.");
  	 		}
  	 	}
  	 });
  }
  function getAllPositionsHigh() {
  
  	$.ajax({
  		type: "GET",
		url : "ajax-get-position.php",
		dataType : "json",
		async: true,
		data: { action : 'get-all-positions-high'},
		success: function(json){
			
			for(var j in json) {
				var j = json[j];
				
				var baseIcon = new GIcon(G_DEFAULT_ICON);
				baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
				baseIcon.iconSize = new GSize(37, 34);
				baseIcon.shadowSize = new GSize(37, 34);
				baseIcon.iconAnchor = new GPoint(9, 34);
				baseIcon.infoWindowAnchor = new GPoint(9, 2);
				var letteredIcon = new GIcon(baseIcon);
				letteredIcon.image = "images/green.png";
				var latlng = new GLatLng(j.lat, j.lng);
				var marker = new GMarker(latlng, { icon:letteredIcon , draggable: false});
				marker.ctm = j;
				GEvent.addListener(marker,"click", highMarkerClick);

				mgr.addMarker(marker, 0, zoom1-1);
				hm[j.uuid] = marker;
				//markers[j.uuid] = marker;
			} 
			//mgr.refresh();
  		}
  	});
  }
  
  function makeMyMarker() {
  		var baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		baseIcon.iconSize = new GSize(37, 34);
		baseIcon.shadowSize = new GSize(37, 34);
		baseIcon.iconAnchor = new GPoint(9, 34);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);
		var letteredIcon = new GIcon(baseIcon);
		letteredIcon.image = "images/yellow-dot.png";
 		return letteredIcon;
  }
  function getMyPosition() {
  		$.ajax({
  		type: "GET",
		url : "ajax-get-position.php",
		dataType : "json",
		async: false,
		cache: false,
		data: { action : 'get-position'},
		success: function(json){
			//var blueIcon = new GIcon(G_DEFAULT_ICON);
			if (json.status == 'good') {
				markerSet = true;
				loggedIn = true;
				var latlng = new GLatLng(json.lat, json.lng);
				var letteredIcon = makeMyMarker();
				var marker = new GMarker(latlng, { icon:letteredIcon , draggable: true});
				marker.ctm = json;
				GEvent.addListener(marker,"click", myMarkerClick);
				GEvent.addListener(marker,"dragend", myMarkerMove);
				me = marker;
				me.replyToCallback = null;
				mgr.addMarker(marker, zoom1);
				markers[json.uuid] = marker;
				map.setCenter(latlng, 8);
				marked();
				map.addControl(new GLargeMapControl());
				
			} else if (json.status == 'nologin') {
				displayNoLogin();
			
			} else if (json.status == 'nomarker') {
				displayNoMarker();
				map.addControl(new GLargeMapControl());
				loggedIn = true;
			}
  		}
  	});
  
  }
  function removeClickListener() {
  	 if ((clickListener != null)) {
  		GEvent.removeListener(clickListener);
  		clickListener = null;
  	}
  }
  function addClickListener() {
  	if (loggedIn)
  		clickListener = GEvent.addListener(map, "click", startPlaceMarker);
  	
  }
  function zoomEnd(oldzoom, newzoom) {
  	$("#debug").text('zoom = '+newzoom);
  	if ((newzoom >= zoom1) && (clickListener == null) && (!markerSet)) {
  		$("#too-far").hide();
  		$("#close-enough").show();
  		addClickListener();
  	} else if ((newzoom < zoom1) && (clickListener != null)) {
  		$("#close-enough").hide();
  		$("#too-far").show();
  		removeClickListener();
  	}
  }
  
  function initializeMarkerManager() {
    mgr = new MarkerManager(map);
    getMyPosition();
    if (markerSet) 
    	getAllPositions();
  }
  // Call this function when the page has been loaded
  function initialize() {
    
    map = new GMap2(document.getElementById("map"));
    map.setCenter(new GLatLng(0, 0), 2);
    
    map.enableScrollWheelZoom();
   
    

    GEvent.addListener(map, "zoomend", zoomEnd);
    initializeMarkerManager();
    
  }


function TextualZoomControl() {
}


function NoLoginControl() {

}

function NoMarkerControl() {

}

NoLoginControl.prototype = new GControl();

NoLoginControl.prototype.initialize = function(map) {
  var container = document.createElement("div");

  var msgDiv = document.createElement("div");
  this.setButtonStyle_(msgDiv);
  container.appendChild(msgDiv);
  msgDiv.innerHTML = "You must be <a href=newuser.php>registered</a> or <a href=signin.php>logged in</a> to be able to use Fellowship Finder.<br/><br/><a href=signin.php>Login</a><br/><a href=newuser.php>Register</a> <br/> ";
  

  map.getContainer().appendChild(container);
  return container;
}

NoLoginControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 7));
}

NoLoginControl.prototype.setButtonStyle_ = function(button) {
  //button.style.textDecoration = "underline";
  button.style.color = "#4d4d4d";
  button.style.backgroundColor = "white";
  button.style.font = "small Arial";
  button.style.border = "1px solid black";
  button.style.padding = "2px";
  button.style.marginBottom = "3px";
  button.style.textAlign = "center";
  button.style.width = "12em";
  button.style.fontSize = "15px";
  
}

NoMarkerControl.prototype = new GControl();

NoMarkerControl.prototype.initialize = function(map) {
  var container = document.createElement("div");

  var msgDiv = document.createElement("div");
  this.setButtonStyle_(msgDiv);
  container.appendChild(msgDiv);
  msgDiv.innerHTML = "Use the map controls or your mouse to zoom and pan to your location.  Once you're close enough, click on the map to place your marker.<br/><div id=too-far>You are zoomed too far out to place your marker</div><div id=close-enough>You are now zoomed in close enough to drop your marker</div>";
  

  map.getContainer().appendChild(container);
  return container;
}

NoMarkerControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(70, 7));
}

NoMarkerControl.prototype.setButtonStyle_ = function(button) {
  //button.style.textDecoration = "underline";
  button.style.color = "#4d4d4d";
  button.style.backgroundColor = "white";
  button.style.font = "small Arial";
  button.style.border = "1px solid black";
  button.style.padding = "2px";
  button.style.marginBottom = "3px";
  button.style.textAlign = "center";
  button.style.width = "12em";
  button.style.fontSize = "15px";
  
}



// To "subclass" the GControl, we set the prototype object to
// an instance of the GControl object
TextualZoomControl.prototype = new GControl();

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.
TextualZoomControl.prototype.initialize = function(map) {
  var container = document.createElement("div");

  var msgDiv = document.createElement("div");
  this.setButtonStyle_(msgDiv);
  container.appendChild(msgDiv);
  msgDiv.appendChild(document.createTextNode("Check Messages"));
  GEvent.addDomListener(msgDiv, "click", function() {
  	hideMap();
    location.href = "#message-list";
  });

  map.getContainer().appendChild(container);
  return container;
}

// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
TextualZoomControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 7));
}

// Sets the proper CSS for the given button element.
TextualZoomControl.prototype.setButtonStyle_ = function(button) {
  button.style.textDecoration = "underline";
  button.style.color = "#4d4d4d";
  button.style.backgroundColor = "white";
  button.style.font = "small Arial";
  button.style.border = "1px solid black";
  button.style.padding = "2px";
  button.style.marginBottom = "3px";
  button.style.textAlign = "center";
  button.style.width = "6em";
  button.style.cursor = "pointer";
}
