/* Author: Brendan Benson



*/
var CrowdCal = {
	latitude: null,
	
	longitude: null,
	
	zip: null,
	
	zipSubmitted: false,
	
	map: null,
	
	markers: Array(),
	
	eventFreq: Object(),
	
	topEvents: Array(),
	
	dateLow: new Date("1975/01/01 03:00:00"),
	
	dateHigh: new Date("2050/01/01 03:00:00"),
	
	filterText: '',
	
	mapOptions: {
	    zoom: 4,
	    center: new google.maps.LatLng(38, -97),
	    mapTypeId: google.maps.MapTypeId.ROADMAP
	},
	
	initializeMap: function() {
		this.map = new google.maps.Map(document.getElementById("map_canvas"), this.mapOptions);
	},
		
	setLocation: function(zip, rng, lim) {
		//Set the zip if we retrieved it from the user
		var range = (rng == undefined) ? "0" : rng;
		var limit = (lim == undefined) ? "0" : lim;
		
		if (zip != null) {
			this.zip = zip;
			this.fetchEvents(range, limit);
			return;
		}
		
		/*
		// Try W3C Geolocation (Preferred)
		if(navigator.geolocation) {
		    browserSupportFlag = true;
		    navigator.geolocation.getCurrentPosition(function(position) {
		      initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
		      CrowdCal.latitude = position.coords.latitude;
		      CrowdCal.longitude = position.coords.longitude;
		      CrowdCal.map.setCenter(initialLocation);
		      CrowdCal.map.setZoom(14);
		      CrowdCal.fetchEvents(range, limit);
		    }, function() {
		      //handleNoGeolocation(browserSupportFlag);
		      CrowdCal.promptLocation(browserSupportFlag);
		    });
		  // Try Google Gears Geolocation
		  } else if (google.gears) {
		    browserSupportFlag = true;
		    var geo = google.gears.factory.create('beta.geolocation');
		    geo.getCurrentPosition(function(position) {
		      initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
		      CrowdCal.latitude = position.coords.latitude;
		      CrowdCal.longitude = position.coords.longitude;
		      CrowdCal.map.setCenter(initialLocation);
		      CrowdCal.map.setZoom(14);
		      CrowdCal.fetchEvents(range, limit);
		    }, function() {
		      //handleNoGeoLocation(browserSupportFlag);
		      CrowdCal.promptLocation(browserSupportFlag);
		    });
		  // Browser doesn't support Geolocation
		  } else {
		    browserSupportFlag = false;
		    //handleNoGeolocation(browserSupportFlag);
		    CrowdCal.promptLocation(browserSupportFlag);
		  }
		  */
		  browserSupportFlag = false;
	      CrowdCal.promptLocation(browserSupportFlag);
		  /*
		  CrowdCal.latitude = $("#h_lat").val();
		  CrowdCal.longitude = $("#h_lon").val();
		  CrowdCal.fetchEvents(range, limit);
		  initialLocation = new google.maps.LatLng(CrowdCal.latitude, CrowdCal.longitude);
		  CrowdCal.map.setCenter(initialLocation);
		  CrowdCal.map.setZoom(14);
		  */
	},
	
	promptLocation: function(browserSupportFlag) {
		//alert('promptLocation');
		$('#dialog').append(
			'Enter your ZIP to find events in your area:<br/><input style="margin:20px 0px 0px 100px;'
			+ 'height:30px; text-align:center; width: 120px;" type="text" name="loc" id="loc" maxlength="5" />'
		).dialog({ 
			modal: true,
			height: 220,
			width: 350,
			closeOnEscape: false,
			buttons: {
				"Search": function() {
					//Validate the ZIP code from the user
					userZip = $('#loc').val();
					CrowdCal.submitZip(userZip);
				}
			},
			//Hide the close button
			open: function(event, ui) { 
				$(".ui-dialog-titlebar-close").hide();
			} 
		}).keydown(function(k) {
			//Close the dialog on keypress Enter			
			if (k.which == 13) {
				userZip = $('#loc').val();
				CrowdCal.submitZip(userZip);
			}
		});
	},
	
	validateZip: function(zip) {
		//Validate the ZIP code from the user
		if (zip.match(/(^\d{5}$)|(^\d{5}-\d{4}$)/)) {
			return true;
		}
		return false;
	},
	
	submitZip: function(zip) {
		if (CrowdCal.validateZip(zip)) {
			CrowdCal.zipSubmitted = true;
			CrowdCal.setLocation(zip);
			$('#dialog').empty().dialog("close");
		} else {
			//Show the error message if not already shown
			if (!CrowdCal.zipSubmitted) {
				CrowdCal.zipSubmitted = true;
				$('#dialog').append('<br /><span class="error">Invalid ZIP</span>');
			}
		}
	},
	
	fetchEvents: function(rng, lim) {
		var location;
		var range = (rng == undefined) ? 0 : rng;
		var limit = (lim == undefined) ? 0 : lim;

		if (this.latitude != null) {
			location = {
				lat: this.latitude,
				lon: this.longitude,
				rng: range,
				lim: limit
			};
			$.getJSON('events/loadEvents/latlon', location, this.showEvents);
		} else {
			location = {
				zip: this.zip,
				rng: range,
				lim: limit
			}
			$.getJSON('events/loadEvents/zipcode', location, this.showEvents);
		}
	},
	
	showEvents: function(data, textStatus, jqXHR) {
		//Temporary for Demo
 var image = new google.maps.MarkerImage('http://www.jmeed.com/1000pitches-logo-small.png',
      // This marker is 20 pixels wide by 32 pixels tall.
      new google.maps.Size(20, 32),
      // The origin for this image is 0,0.
      new google.maps.Point(0,0),
      // The anchor for this image is the base of the flagpole at 0,32.
      new google.maps.Point(0, 32));



  var myLatLng = new google.maps.LatLng(42.275086,-83.741248);
  var beachMarker = new google.maps.Marker({
      position: myLatLng,
      map: CrowdCal.map,
      icon: image,
	  zIndex: 10
  });		
	
		//console.log(data);
		if (CrowdCal.zip != null) {
			var latlon = data[1];
			var centerLatlng = new google.maps.LatLng(latlon[0], latlon[1]);
			CrowdCal.map.setCenter(centerLatlng);
			CrowdCal.map.setZoom(14);	
		}
		
		data = data[0];
		var locBounds = new google.maps.LatLngBounds();
		$.each(data, function(key, val) {
			val = val.events;
			var contentString = '<div class="eventinfo">' +
				'<strong>' + val.name + '</strong><br />' +
				CrowdCal.formatDate(val.start_time) + '<br />' +
				CrowdCal.formatDate(val.end_time) + '<br />' +
				'</div>';
				
			val.lat = (Math.random()-.5)/5000 + parseFloat(val.lat);
			val.lon = (Math.random()-.5)/5000 + parseFloat(val.lon);
			var eventLatlng = new google.maps.LatLng(val.lat, val.lon);
			
			locBounds.extend(eventLatlng);
			
			CrowdCal.markers[key] = {
				marker: new google.maps.Marker({
					position: eventLatlng,
					map: CrowdCal.map, 
					title: val.name,
					zIndex: 1
				}),
				info: val
			};
			
			google.maps.event.addListener(CrowdCal.markers[key].marker, 'mouseover', function() {
				thumb_box(val.eid, function(photoArr)
				{
					var p = "";
					var _height = 100;
					var _yPos = 490;

					if(photoArr.length)
					{
						p = "<div class='pop-photos'>";
						$.each(photoArr, function(key, val)
						{
							p = p + "<img style='margin:8px 8px 0px 0px;' src='"+val+"'></img>";
						});
						p = p + "</div>";
						_height = 150;
						_yPos = 433;
					}

					console.log(_yPos);

					$('#eventwindow').empty().append(contentString).append(p)
					.dialog({
						modal: false,
						height: _height,
						width: 330,
						position: [(window.innerWidth - 345), _yPos],
						dialogClass: 'alert',
						open: function(event, ui) {
							$(".ui-dialog-titlebar-close").hide();
						}
					});
				});
			});
			
			google.maps.event.addListener(CrowdCal.markers[key].marker, 'mouseout', function() {
				$('#eventwindow').dialog('close');
			});
			
			google.maps.event.addListener(CrowdCal.markers[key].marker, 'click', function() {
				var popup = window.open('http://www.facebook.com/' + val.eid);
				popup.focus();
			});
		});
		
		//CrowdCal.map.fitBounds(locBounds);

		CrowdCal.showTopKeywords();
	},
	
	formatDate: function(d) {
		//0123456789012345678
		//2012-03-18 20:30:00
		var ampm;
		var hours;
		if (parseInt(d.substr(11,2)) < 12) {
			ampm = 'am';
			hours = parseInt(d.substr(11,2));
		} else {
			ampm = 'pm';
			hours = parseInt(d.substr(11,2)) - 12;
		}
		if (hours == 0) {
			hours = 12;
		}
		var newdate = d.substr(5,2) + '/' + d.substr(8,2) + '/' + d.substr(0,4) + ' ' + hours + d.substr(13,3);
		return newdate;
	},
	
	filterEvents: function() {
		$.each(this.markers, function(key, val) {
			var eventName = val.info.name.toLowerCase();
			var startDate = new Date(val.info.start_time.replace(/-/g,"/"));
			if (eventName.indexOf(CrowdCal.filterText) == -1 || startDate < CrowdCal.dateLow || startDate > CrowdCal.dateHigh) {
				val.marker.setVisible(false);
			} else {
				val.marker.setVisible(true);
			}
		});
	},
	
	showTopKeywords: function() {
		//Build a frequency Object
		$.each(this.markers, function(key, val) {
			var desc = val.info.name.toLowerCase();
			var words = desc.split(' ');
			$.each(words, function(key, val) {
				if (val.length >= 3 && val != 'and' && val != 'the' && val != 'for' && val != 'with') {
					if (CrowdCal.eventFreq[val] == undefined) {
						CrowdCal.eventFreq[val] = 1;
					} else {
						CrowdCal.eventFreq[val]++;
					}
				}
			});
		});
		//console.log(CrowdCal.eventFreq);
		
		//Build an array of objects
		
		var i = 0;
		$.each(this.eventFreq, function(key, val) {
			var freqObj = new Object({
				word: key,
				frequency: val
			});
			CrowdCal.topEvents[i] = freqObj;
			i++;
		});
		
		function sortEvent(a, b) {
			return b.frequency - a.frequency;
		}
		
		//Now display the top events
		//console.log(CrowdCal.topEvents.sort(sortEvent));
		
		CrowdCal.topEvents.sort(sortEvent);
		
		for(var i = 0; i < 25; i++) {
			$('#column3').append(
				'<div class="topkeyword">' + CrowdCal.topEvents[i].word + '</div>'
			);
		}
		$('.topkeyword').click(function() {
			//console.log($(this).text());
			$('#filtertext').val($(this).text()).change();
		});
	}
	
};

function thumb_box(eid, callback)
{
	var url = "/" + eid + "/attending?limit=5";
	var finalizer = (function()
	{
		var photoURLs = [];
		return {
			"add" : function(d) { photoURLs.push(d); },
			"end" : function() { callback(photoURLs); }
		};
	})();
	
	FB.api(url, function(data)
	{
		if(data.error != undefined)
		{
			finalizer.end();
			return;
		}

		var len = data.data.length > 5 ? 5 : data.data.length;
		var watcher = len;

		for(var i = 0; i < len; i++)
		{
			var url = "/" + data.data[i].id + "&fields=picture";
			FB.api(url, function(data2){
				watcher--;
				finalizer.add(data2.picture);
				if(watcher == 0)
					finalizer.end();
			});
		}
	});
}

$(document).ready(function() {
	
	//$('#tip').delay(3000).show('slow').delay(10000).hide('slow');
	
	CrowdCal.initializeMap();
	CrowdCal.setLocation();
	
	$('#filtertext').keyup(function() {
		CrowdCal.filterText = $(this).val();
		CrowdCal.filterEvents();
	});
	
	$('#filtertext').change(function() {
		CrowdCal.filterText = $(this).val();
		CrowdCal.filterEvents();
	});
	
	$('#ziptext').click(function() {
		$('#ziptext').val('');
	});
	$('#zipclick').click(function() {
		CrowdCal.zip = $('#ziptext').val();
		CrowdCal.latitude = null;
		CrowdCal.fetchEvents(0, 0);
		
	});
	$('#clearfiltertext').click(function() {
		$('#filtertext').val('');
		CrowdCal.filterText = '';
		CrowdCal.filterEvents();
	});
	
	var fbInit = function() {
	
		$("#fblogin").click(function(e)
		{
			FB.login(function(d)
			{
				//console.log(d);
				
				//Send a POST request to /login with auth_token
				var authData = {
					access_token: d.authResponse.accessToken
				};
				$.ajax('/login', {
					type: 'POST',
					data: authData,
					dataType: "json",
					url: '/login',
					success: function(data) {
						//console.log(data);
					}
				});
				
			}, {"scope" : "offline_access,email,friends_events"});
		});
	};
	fbInit();
	
	$(function() {
		var dates = $( "#from, #to" ).datepicker({
			changeMonth: true,
			minDate: new Date(),
			onSelect: function( selectedDate ) {
				/*
				var option = this.id == "from" ? "minDate" : "maxDate",
					instance = $( this ).data( "datepicker" ),
					date = $.datepicker.parseDate(
						instance.settings.dateFormat ||
						$.datepicker._defaults.dateFormat,
						selectedDate, instance.settings );
				dates.not( this ).datepicker( "option", option, date );
				*/
				if (this.id == 'from') {
					CrowdCal.dateLow = new Date(selectedDate);
				}
				if (this.id == 'to') {
					CrowdCal.dateHigh = new Date(selectedDate);
					CrowdCal.dateHigh.setTime(CrowdCal.dateHigh.getTime() + 86400000);
				}

				//console.log(CrowdCal);

				CrowdCal.filterEvents();
			}
		});
	});
	
});

