(function($){

TravelPlanner.Map = {
	
	countries: {
		myanmar: {
			latLng: [18.10608879882466, 95.71678906250001],
			bounds: {
				sw: [9.710066405184499, 92.39174169921876],
				ne: [28.710758957581497, 101.18080419921876]
			}
		},
		thailand: {
			latLng: [15.413349698271704, 100.81444531250001],
			bounds: {
				sw: [5.442041694119696, 97.22572607421876],
				ne: [20.57204060195195, 106.01478857421876]
			}
		},
		laos: {
			latLng: [20.264172841719223, 102.57225781250001],
			bounds: {
				sw: [13.83374045194393, 100.00526708984376],
				ne: [22.54902004039199, 107.81654638671876]
			}
		},
		vietnam: {
			latLng: [15.243821823462362,108.37303906250001],
			bounds: {
				sw: [8.315790144381914, 101.91139501953126],
				ne: [23.539747950341436, 110.70045751953126]
			}
		},
		cambodia: {
			latLng: [13.541248190612267,104.50585156250001],
			bounds: {
				sw: [10.13753232946383, 102.22450537109376],
				ne: [14.781184095881748, 107.76161474609376]
			}
		},
		malaysia: {
			latLng: [5.661814341957593,102.22069531250001],
			bounds: {
				sw: [0.715116765812233, 100.06019873046876],
				ne: [7.396168393445947, 120.47279638671876]
			}
		},
		indonesia: {
			latLng: [-3.2919796479173713,119.79882031250001],
			bounds: {
				sw: [-11.500553456801995, 94.75380224609376],
				ne: [6.032329043012287, 132.23915380859376]
			}
		},
		'brunei darussalam': {
			latLng: [4.348511273430937,114.61327343750001],
			bounds: {
				sw: [3.987897297841477, 114.0643338623047],
				ne: [5.080337128171162, 115.40603918457032]
			}
		},
		singapore: {
			latLng: [0.8370372197648277,103.97850781250001],
			bounds: {
				sw: [1.2255628009405832, 103.60243124389649],
				ne: [1.477148184892722, 104.05252737426758]
			}
		},
		philippines: {
			latLng: [13.541248190612267,122.52342968750001],
			bounds: {
				sw: [5.096580688969594, 116.67049688720705],
				ne: [19.668609005013884, 127.72274298095702]
			}
		}
	},

	activities: {},

	init: function(){
		
		var center = TravelPlanner.Map.center = new google.maps.LatLng(8.67, 126.083);
		var map = TravelPlanner.map = new google.maps.Map($('#map')[0], {
			zoom: 4,
			center: center,
			disableDefaultUI: true,
			disableDoubleClickZoom: true,
			keyboardShortcuts: false,
			scrollwheel: false,
			mapTypeId: google.maps.MapTypeId.TERRAIN
		});
		
		/*
		google.maps.event.addListener(map, 'click', function(e){
			var ll = e.latLng;
			console.log(ll.lat() + ',' + ll.lng());
		});
		*/
		
		var tooltip = $('<div id="travelplanner-tooltip" style="display: none;"></div>').appendTo('body');
		
		var countryMarkers = TravelPlanner.countryMarkers = [];
		var i = 0;
		$.each(TravelPlanner.Map.countries, function(name, country){
			var ll = country.latLng;
			var marker = countryMarkers[i] = new google.maps.Marker({
				map: map,
				position: new google.maps.LatLng(ll[0], ll[1]),
				zIndex: 1
			});
			google.maps.event.addListener(marker, 'mouseover', function(e){
				var pageX = e.pageX || e.clientX + $(document).scrollLeft();
				var pageY = e.pageY || e.clientY + $(document).scrollTop();
				TravelPlanner.Map.showInfoPane(name.replace(/\s+/g, '-'));
				tooltip.text(name.replace(/\b[a-z]/g, function(match){
					return match.toUpperCase();
				})).show().css({
					left: pageX + 16,
					top: pageY
				});
			});
			google.maps.event.addListener(marker, 'mouseout', function(){
				tooltip.hide();
			});
			google.maps.event.addListener(marker, 'click', function(){
				tooltip.hide();
				TravelPlanner.Map.zoomToCountry(name);
			});
			i++;
		});
		
		var destinationMarkers = TravelPlanner.destinationMarkers = [];
		TravelPlanner._destinationMarkers = {};
		TravelPlanner.sub('loadDestinations', function(){
			var i = 0;
			$.each(TravelPlanner.destinations, function(id, destination){
				var marker = TravelPlanner._destinationMarkers[id] = destinationMarkers[i] = new google.maps.Marker({
					map: map,
					position: new google.maps.LatLng(destination.lat, destination.lng),
					visible: false,
					zIndex: 2
				});
				google.maps.event.addListener(marker, 'mouseover', function(e){
					var pageX = e.pageX || e.clientX + $(document).scrollLeft();
					var pageY = e.pageY || e.clientY + $(document).scrollTop();
					tooltip.text(destination.name).show().css({
						left: pageX + 16,
						top: pageY
					});
				});
				google.maps.event.addListener(marker, 'mouseout', function(){
					tooltip.hide();
				});
				google.maps.event.addListener(marker, 'click', function() {
					tooltip.hide();
					TravelPlanner.Map.showDestination(id);
				});
				// hook up extra data into the markup for awesomeness
				marker._travelplanner_country = destination.country.toLowerCase();
				i++;
			});
		});
		
		TravelPlanner.Map.setMapHeading();
		TravelPlanner.Map.setMapFilters();
		
		$('#map-filter .breadcrumb-sea a, #back-to-sea').live('click', function(){
			$('#map-overlay').addClass('hidden');
			TravelPlanner.Map.resetMap();
			return false;
		});
		
		$('#map-filter .breadcrumb-country a').live('click', function(){
			var country = $(this).text().toLowerCase();
			$('#map-overlay').addClass('hidden');
			TravelPlanner.Map.zoomToCountry(country);
			return false;
		});
		
		var filterLinks = $('#map-filter ol li a').live('mouseover', function(){
			var el = $(this);
			TravelPlanner.Map.showInfoPane(el.attr('id'));
			return false;
		}).live('click', function(){
			var el = $(this);
			TravelPlanner.Map.zoomToCountry(el.attr('id').replace('-', ' '));
			return false;
		});
		
		// randomly show one of the info panes
		$(filterLinks[Math.floor(Math.random()*filterLinks.length)]).trigger('mouseover');

		// hover on info pane shenanigans
		$('#map-info-pane').bind('mouseenter', function(){
			var el = $(this);
			el.addClass('hovered');
		}).bind('mouseleave', function(){
			var el = $(this);
			el.removeClass('hovered');
		}).live('click', function(){
			var country = $.trim($(this).find('h4').text());
			TravelPlanner.Map.zoomToCountry(country);
			return false;
		});
		
		$('#map-overlay-close').live('click', function(){
			$('#map-overlay').addClass('hidden');
			TravelPlanner.Map.zoomToCountry($('.breadcrumb-country a').text().toLowerCase());
			return false;
		});
		
		$('#close-info-pane').live('click', function(){
			$('#map-info-pane').addClass('hidden');
			return false;
		});
		
		$('#things-to-do ol li a').live('click', function(){
			el = $(this);
			$('.addToItinerary').hide();
			var activityInfo = TravelPlanner.Map.activities[el.attr('href').replace('#', '')];
			var country = $('.breadcrumb-country a').text();
			var content = $('#map-overlay-content');

			content.find('h3').html(activityInfo.title);

			var defaultPhotoUrl = 'url("/media/images/country/' + country.replace('-', ' ').toLowerCase() + '.jpg")';

			var currentPhotoUrl = '';
			
			console.log(el.data('prevImg'));
			
			if (el.data('prevImg')){
				currentPhotoUrl = el.data('prevImg');
			  content.find('a.prevImg').css('background-image','none').html('<img width="320px" height="170px" src="' + currentPhotoUrl + '" />');
			} else {
				currentPhotoUrl = el.css('background-image').replace('_t', '_m');
  			var photoUrl = (currentPhotoUrl.match("no_image") == null) ? currentPhotoUrl : defaultPhotoUrl;
  			content.find('a.prevImg').html('').css('background-image', photoUrl);
			}

			var new_el = $('<p></p>');
			new_el.html(activityInfo.info_html);
			content.find('p.activityDesc').html(TravelPlanner.Utils.wrapText(new_el.text(), 540, true));

			return false;
		});
		
		$('#map-overlay-content .slide-right-button').live('click', function(){
			var el = $(this);
			var imageSet = $('#things-to-do ol');
			el.addClass('busy');
			if(!imageSet.data('currentPage')) imageSet.data('currentPage', 1);
			if (el.hasClass('busy') && imageSet.data('pages') > imageSet.data('currentPage')){
				imageSet.animate({ left: '-=850'  }, 500, 'linear', function(){
					el.removeClass('busy');
					imageSet.data('currentPage', imageSet.data('currentPage') + 1);
				});
			}

			return false;
		});
		
		$('#map-overlay-content .slide-left-button').live('click', function(){
			var el = $(this);
			var imageSet = $('#things-to-do ol');
			el.addClass('busy');
			if(!imageSet.data('currentPage')) imageSet.data('currentPage', 1);
			if (el.hasClass('busy') && imageSet.data('currentPage') > 1){
				imageSet.animate({ left: '+=850'  }, 500, 'linear', function(){
					el.removeClass('busy');
					imageSet.data('currentPage', imageSet.data('currentPage') - 1);
				});
			}

			return false;
		});
		
		$('#map-overlay-content .addToItinerary').live('click', function(){
			var el = $(this);
			var htmlbody = $('html,body');
			if (!TravelPlanner.setHomeAirport){
				var homeAiport = $('#homeairport');
				htmlbody.animate({
					scrollTop: homeAiport.offset().top + homeAiport.outerHeight() - $(window).scrollTop()
				}, function(){
					$('#homeAirportField').focus().select();
					TravelPlanner.pub('message', ['error', 'noHomeAirport']);
				});
			} else {
				var id = el.attr('data-destination');
				var addDestination = $('#add-destination');
				htmlbody.animate({
					scrollTop: addDestination.offset().top + addDestination.outerHeight() - $(window).scrollTop()
				}, function(){
					$('#destinationsSelect').val(id).trigger('change');
					$('#travelplanner .link-accept-destination').click();
				});
			}
			$('#back-to-sea').hide();
			
			return false;
		});
		
		TravelPlanner.addedMarkers = [];
		TravelPlanner.sub('renderDestinations', function(){
			var destinations = TravelPlanner.Data.destinations;
			if (!destinations.length) return;
			
			var run = function(){
				if (!_.isNumber(destinations[0].location.lat)){
					setTimeout(run, 1000);
					return;
				}
				
				if (TravelPlanner.addedMarkers[0]) TravelPlanner.addedMarkers[0].setMap(null); // removes from the map
				
				// reset stuff
				TravelPlanner.addedMarkers = [];
				$.each(TravelPlanner.destinationMarkers, function(i, m){
					m.setZIndex(2);
					m.setVisible(false);
					m.setIcon('');
				});
				
				var path = [];
				$.each(destinations, function(i, destination){
					var l = destination.location;
					var latlng;
					if (i == 0){ // first destination, which is the home airport doesn't have id
						latlng = new google.maps.LatLng(l.lat, l.lng);
						TravelPlanner.addedMarkers[i] = new google.maps.Marker({
							map: TravelPlanner.map,
							position: latlng,
							title: l.name,
							icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_icon&chld=home|ff0',
							zIndex: 3,
							visible: true
						});
					} else {
						var marker = TravelPlanner.addedMarkers[i] = TravelPlanner._destinationMarkers[l.id];
						marker.setIcon('http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=' + i + '|ff0|000');
						marker.setZIndex(3);
						marker.setVisible(true);
						latlng = marker.getPosition();
					}
					path.push(latlng);
				});
				
				if (TravelPlanner.mapPolyline){
					TravelPlanner.mapPolyline.setPath(path);
				} else {
					TravelPlanner.mapPolyline = new google.maps.Polyline({
						path: path,
						strokeColor: '#5A524A',
						strokeOpacity: 0.7,
						strokeWeight: 2
					});
					TravelPlanner.mapPolyline.setMap(TravelPlanner.map);
				}
			};
			run();
		});
		
		TravelPlanner.sub('addDestination', function(e, id){
			var destination = TravelPlanner.destinations[id];
			if (!destination) return;
			$('#map-overlay').addClass('hidden');
			TravelPlanner.Map.zoomToCountry(destination.country.toLowerCase());
		});
		
		// preload country images AFTER the map tiles are loaded. Nice.
		google.maps.event.addListener(map, 'tilesloaded', function(){
			var countryImagesCache = [];
			$.each(TravelPlanner.countries, function(i, country){
				var img = document.createElement('img');
				img.src = '/media/images/country/' + country.replace(' ', '-') + '.jpg';
				countryImagesCache.push(img);
			});
		});
	},

	setMapHeading: function(country, city){
		if (city && city.length > 0){
			$('#map-filter ol').addClass('hidden');	
			html = _.template(TravelPlanner.Templates.mapHeading, {
				seaClass: '',
				countryClass: '',
				cityClass: 'active',
				countryName: country,
				cityName: city
			});
			$('#back-to-sea').hide();
		}else if (country && country.length > 0){
			$('#map-filter ol').addClass('hidden');	
			html = _.template(TravelPlanner.Templates.mapHeading, {
				seaClass: '',
				countryClass: 'active',
				cityClass: 'hidden',
				countryName: country,
				cityName: ''
			});
			$('#back-to-sea').show();
		}else{
			$('#map-filter ol').removeClass('hidden');	
			html = _.template(TravelPlanner.Templates.mapHeading, {
				seaClass: 'active',
				countryClass: 'hidden',
				cityClass: 'hidden',
				countryName: '',
				cityName: ''
			});
			$('#back-to-sea').hide();
		}
		$('#map-filter h3').html(html);
	},
	
	setMapFilters: function(){
		var html = '';
		var country_html = '';
		var countries = TravelPlanner.countries;
		$.each(countries.sort(), function(i, d){
			country_html = _.template(TravelPlanner.Templates.mapFilters, {
				countryName: d,
				countryID: d.replace(/\s/, '-')
			});
			html += country_html;
		});

		$('#map-filter ol').html(html);
	},

	showDestination: function(id){
		$('#map-info-pane').addClass('hidden');
		$('#map-overlay').removeClass('hidden');
		$('#things-to-do').slideUp();
		$('.addToItinerary').show();
		
		var destination = TravelPlanner.destinations[id];
		var html = '';
		var info_html = '';
		var info_html = _.template(TravelPlanner.Templates.mapOverlayContent, {
			infoTitle: destination.name,
			infoDesc: destination.desc,
			destinationID: id
		});
		$('#map-overlay-content').html(info_html);
		$('#map-overlay-content a.prevImg').css('background-image', 'url(/media/images/country/' + destination.country.replace(/\s/, '-').toLowerCase() + '.jpg)');

		TravelPlanner.Map.setMapHeading(destination.country, destination.name);
		TravelPlanner.Map.loadActivities(destination.country, destination.name);
	},
	
	loadActivities: function(country, destination){
		
		$.ajax({
			url: '/api/things_to_do?location='+destination,
			dataType: 'json',
			success: function(data){

				var allActivities = [];
				var activities_html = '';
				var filterArray = [];

				$.each(data, function(i, d){
					if (_.lastIndexOf(filterArray, d.title) == -1) {
						filterArray.push(d.title);
						allActivities.push(d);
						TravelPlanner.Map.activities[d.entry_id] = d;
					}
				});	

				if (allActivities.length > 0){

					// add the activities
					$.each(allActivities, function(i, d){
						activities_html += '<li><a href="#' + d.entry_id + '"></a><span>' + d.title + '</span></li>';
					});
					$('#things-to-do ol').html(activities_html)
						.css('width', function(){
							return (Math.ceil(allActivities.length / 5) * 860)  + 'px';
						})
						.data('pages', Math.ceil(allActivities.length / 5))
						.data('currentPage', 1);

					// add flickr images
					var apiKey = '8cc155723c86cd5dfedeeebdbbe1e917';
					var activityImage = $('#things-to-do ol li');
					
					// get from hero_image otherwise use flickr
					$.each(activityImage, function(i, el){
						
						var id = $(el).find('a').attr('href').split('#')[1];
						var root = TravelPlanner.rootURL.split('/index.php')[0];
						if (TravelPlanner.Map.activities[id]['hero_image_small'] && TravelPlanner.Map.activities[id]['hero_image_small'].length){
							$(el).find('a').css({
								'background-image': 'url(' + root + TravelPlanner.Map.activities[id]['hero_image_small'] + ')',
								'background-repeat': 'no-repeat',
								'background-position': 'center center'
							});

  						if (TravelPlanner.Map.activities[id]['hero_image'] && TravelPlanner.Map.activities[id]['hero_image'].length){
  							$(el).find('a').data('prevImg', root + TravelPlanner.Map.activities[id]['hero_image']);
  						}
						} else {
							var title = $(el).find('span').text();
							var imgUrl = 'http://api.flickr.com/services/rest/?method=flickr.photos.search'
								+ '&api_key=' + apiKey
								+ '&tags=' + title + ',' + country + '&tag_mode=all'
								+ '&format=json&sort=interestingness-desc'
								+ '&per_page=1&page=1&content_type=1&license=1&jsoncallback=?';

							$.getJSON(imgUrl, function(data){
								var photoUrl = '/media/images/no_image.gif';
								if (data && data.photos && data.photos.photo && data.photos.photo[0]){
									var photo = data.photos.photo[0];
									photoUrl = 'http://farm' + photo.farm + '.static.flickr.com/' + photo.server + '/' + photo.id + '_' + photo.secret + '_t.jpg';
								}
								$(el).find('a').css({
									'background-image': 'url(' + photoUrl + ')',
									'background-repeat': 'no-repeat',
									'background-position': 'center center'
								});
							});
						}

					});
				} else {
					$('#things-to-do').slideUp();
				}
			},
			error: function(){
				console.log('Error while calling http://www.southeastasia.org/geo.php/all_near_city?nearest_city='+destination.location.name);
			}
		});
	},

	showInfoPane: function(country){
		$('#map-info-pane').removeClass('hidden');
		var info_html = _.template(TravelPlanner.Templates.mapInfoPane, {
			infoCountry: country.replace('-', ' '),
			infoImage: '/media/images/country/' + country + '.jpg',
			infoDesc: TravelPlanner.Utils.wrapText(TravelPlanner.Countries[country], 360, true)
		});
		$('#map-info-pane-content').html(info_html);
	},
	
	zoomToCountry: function(country){
		if (!country) return;
		var c = TravelPlanner.Map.countries[country.replace('-', ' ')];
		if (!c) return;
		
		var map = TravelPlanner.map;
		var b = c.bounds;
		var sw = b.sw;
		var ne = b.ne;

		map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
		
		var bounds = new google.maps.LatLngBounds(new google.maps.LatLng(sw[0], sw[1]), new google.maps.LatLng(ne[0], ne[1]));
		map.fitBounds(bounds);
		var zoom = TravelPlanner.map.getZoom();
		map.setZoom(++zoom);
		
		// hide country markers
		$.each(TravelPlanner.countryMarkers, function(i, m){
			m.setVisible(false);
		});
		
		// show destination markers, only for /that/ country
		$.each(TravelPlanner.destinationMarkers, function(i, m){
			m.setVisible((m._travelplanner_country == country));
		});
		
		$.each(TravelPlanner.addedMarkers, function(i, m){
			m.setVisible(true);
		});
		
		TravelPlanner.Map.setMapHeading(country.replace(/\b[a-z]/g, function(match){
			return match.toUpperCase();
		}));

		$('#close-info-pane').click();
	},
	
	resetMap: function(){
		TravelPlanner.map.setZoom(4);
		TravelPlanner.map.setCenter(TravelPlanner.Map.center);
		TravelPlanner.map.setMapTypeId(google.maps.MapTypeId.TERRAIN);
		
		// show country markers
		$.each(TravelPlanner.countryMarkers, function(i, m){
			m.setVisible(true);
		});
		
		// hide destination markers
		$.each(TravelPlanner.destinationMarkers, function(i, m){
			m.setVisible(false);
		});
		
		$.each(TravelPlanner.addedMarkers, function(i, m){
			m.setVisible(true);
		});

		TravelPlanner.Map.setMapHeading();
	}

};

})(jQuery);

