var geo_cache = null;
var geo_map   = null;
var geo_map_office_windows = {};
var geo_map_terminal_windows = {};

function activate_geo()
{
	if (!!navigator.geolocation && !geo_cache) {
		$('#container>header').append('<a href="#" id="geo_find">Find Nearby Locations</a>');
		$('#geo_find').click(function () {
			get_locations_by_geo();
			return false;
		});
	}
	else if (geo_cache) {
		$.getJSON('/locations/api', geo_cache, function (data) {
			process_locations(data);
		});
	}
}

function get_locations_by_geo()
{
	navigator.geolocation.getCurrentPosition(function (data) {
		geo_cache = {
			'latitude': data.coords.latitude,
			'longitude': data.coords.longitude
		};
		
		$.getJSON('/locations-api', geo_cache, function (data) {
			process_locations(data);
		});
	});
}

function process_locations(locations)
{
	$('<div id="geo_map_container"><div id="geo_map"></div><a href="#" id="geo_map_close">close</a></div>').appendTo('body');
	$('#geo_map_container').css({
		'top': 0 - $('#geo_map_container').height() - 20,
		'left': ($(window).width() - $('#geo_map_container').outerWidth()) / 2
	}).animate({
		'top': 10
	}, 350);
	
	var myOptions = {
		zoom: 8,
		mapTypeId: google.maps.MapTypeId.TERRAIN,
		center: new google.maps.LatLng(geo_cache.latitude, geo_cache.longitude)
	};
	geo_map = new google.maps.Map(document.getElementById('geo_map'), myOptions);
	
	var you_are_here = new google.maps.Marker({
		map: geo_map, 
		position: new google.maps.LatLng(geo_cache.latitude, geo_cache.longitude),
		animation: google.maps.Animation.DROP,
		icon: new google.maps.MarkerImage("/assets/site/images/icon_you_are_here_2x.png", null, null, new google.maps.Point(20,28), new google.maps.Size(40,30))
	});
	
	var name, address, id, latitude, longitude;
	for (var i=0, len=locations.offices.length; i<len; i++) {
		(function () {
			var name      = locations.offices[i].name;
			var address   = locations.offices[i].full_address;
			var id        = locations.offices[i].id;
			var latitude  = locations.offices[i].latitude;
			var longitude = locations.offices[i].longitude;
			
			var marker = new google.maps.Marker({
				map: geo_map, 
				position: new google.maps.LatLng(latitude, longitude),
				animation: google.maps.Animation.DROP,
				icon: new google.maps.MarkerImage("/assets/site/images/icon_office_marker.png", null, null, new google.maps.Point(15,35), new google.maps.Size(30,40))
			});
			geo_map_office_windows[id] = {
				infoWindow: new google.maps.InfoWindow({
			    	content: '<div class="gmaps-tooltip"><strong>'+name+'</strong>' + '<br />' + address + '<br /> <a href="http://maps.google.com/maps?saddr='+geo_cache.latitude+','+geo_cache.longitude+'&daddr='+encodeURI(address)+'">Get Directions</a></div>'
			    }),
			    maxWidth: 150,
			    'marker': marker
			}
			google.maps.event.addListener(marker, 'click', function() {
				for (var i in geo_map_office_windows) {
					if (geo_map_office_windows[i].infoWindow) {
						geo_map_office_windows[i].infoWindow.close();
					}
				}
				for (var i in geo_map_terminal_windows) {
					if (geo_map_terminal_windows[i].infoWindow) {
						geo_map_terminal_windows[i].infoWindow.close();
					}
				}
				
				geo_map_office_windows[id].infoWindow.open(geo_map, marker);
			});
		})();
	}
	for (var i=0, len=locations.terminals.length; i<len; i++) {
		(function () {
			var name      = locations.terminals[i].name;
			var address   = locations.terminals[i].full_address;
			var id        = locations.terminals[i].id;
			var latitude  = locations.terminals[i].latitude;
			var longitude = locations.terminals[i].longitude;
			
			var marker = new google.maps.Marker({
				map: geo_map, 
				position: new google.maps.LatLng(latitude, longitude),
				animation: google.maps.Animation.DROP,
				icon: new google.maps.MarkerImage("/assets/site/images/icon_terminal_marker.png", null, null, new google.maps.Point(15,35), new google.maps.Size(30,40))
			});
			geo_map_terminal_windows[id] = {
				infoWindow: new google.maps.InfoWindow({
			    	content: '<div class="gmaps-tooltip"><strong>'+name+'</strong>' + '<br />' + address + '<br /> <a href="http://maps.google.com/maps?saddr='+geo_cache.latitude+','+geo_cache.longitude+'&daddr='+encodeURI(address)+'">Get Directions</a></div>'
			    }),
			    maxWidth: 150,
			    'marker': marker
			}
			google.maps.event.addListener(marker, 'click', function() {
				for (var i in geo_map_terminal_windows) {
					if (geo_map_terminal_windows[i].infoWindow) {
						geo_map_terminal_windows[i].infoWindow.close();
					}
				}
				for (var i in geo_map_office_windows) {
					if (geo_map_office_windows[i].infoWindow) {
						geo_map_office_windows[i].infoWindow.close();
					}
				}
				
				geo_map_terminal_windows[id].infoWindow.open(geo_map, marker);
			});
		})();
	}
	
	$(window).bind('resize.geo_map', function () {
		$('#geo_map_container').css({
			'left': ($(window).width() - $('#geo_map_container').outerWidth()) / 2
		});
	});
	
	$('#geo_map_close').click(function () {
		$('#geo_map_container').animate({
			'top': 0 - $('#geo_map_container').height() - 20
		}, 350, function () {
			$('#geo_map_container').remove();
		});
		
		$('body').unbind('geo_map');
		
		return false;
	});
}

var driver_application = {
	_form: null,
	_steps: null,
	_current: 0,
	init: function () {
		this._form  = $('.driver_application');
		this._steps = this._form.find('.step_set');
		
		this._form.append('<div id="driver_app_nav"><a href="#" class="previous">Previous</a> <a href="#" class="next">Next</a></div>');
		$('#driver_app_nav .previous').click(function () {
			driver_application.previousStep();
			return false;
		});
		$('#driver_app_nav .next').click(function () {
			driver_application.nextStep();
			return false;
		});
		
		this.showStep(0);
	},
	refreshNav: function () {
		if (!this.hasPreviousStep()) {
			$('#driver_app_nav .previous').hide();
		}
		else {
			$('#driver_app_nav .previous').show().text(this.hasPreviousStep());
		}
		if (!this.hasNextStep()) {
			$('#driver_app_nav .next').hide();
		}
		else {
			$('#driver_app_nav .next').show().text(this.hasNextStep());
		}
	},
	showStep: function (index) {
		if (this._steps.eq(index).size()) {
			this._steps.hide();
			this._steps.eq(index).show();
			
			this._current = index;
			
			this.refreshNav();
		}
	},
	hasNextStep: function () {
		return this._steps.eq(this._current + 1).size() ? this._current + 2 + '. ' +this._steps.eq(this._current + 1).attr('data-name') : false;
	},
	nextStep: function () {
		if (this.hasNextStep() && this.validateStep(this._current) == true) {
			this.showStep(this._current + 1);
		}
	},
	hasPreviousStep: function () {
		return this._steps.eq(this._current - 1).size() && this._current !== 0 ? this._current + '. ' +this._steps.eq(this._current - 1).attr('data-name') : false;
	},
	previousStep: function () {
		if (this.hasPreviousStep()) {
			this.showStep(this._current - 1);
		}
	},
	validateStep: function (index) {
		if (this._steps.eq(index).size()) {
			var step = this._steps.eq(index);
			var fields = step.find('[data-validate]');
			var errors = [];
			$.each(fields, function (i, field) {
				switch ($(field).attr('data-validate')) {
					case 'required':
						if ($(field).val() == '') {
							errors.push({
								'field': $(field)
							});
							$(field).addClass('error');
						}
						else {
							$(field).removeClass('error');
						}
					break;
				}
			});
			
			if (errors.length) alert('Certain fields are required. Those marked in red above still need to be filled out.');
			
			return errors.length ? errors : true;
		}
		return true;
	}
};

$(function () {
	if ($('.driver_application').size()) driver_application.init();
	
	$('.subpage_side_box .show_link').click(function () {
		if ($(this).parent().hasClass('open')) return false;
		
		//collapse open one
		$('.subpage_side_box.open').animate({
			height: 120
		}, 350);
		$('.subpage_side_box.open .copy').animate({
			opacity: 0
		}, function () {
			$(this).css({
				'display': 'none',
				'opacity': 1
			});
			
			$(this).parent().removeClass('open');
		});
		$('.subpage_side_box.open .show_link').animate({
			width: 280
		});
		
		//show this one
		$(this).css({
			width: 0
		});
		$(this).parent().find('.copy').css({
			'display': 'block',
			'opacity': 0
		});
		$(this).parent().find('.copy').animate({
			opacity: 1
		}, 350);
		$(this).parent().animate({
			height: $(this).parent().find('.copy').height() + 70
		}, 350, function () {
			$(this).addClass('open');
		});
		
		/*$('.subpage_side_box').removeClass('open');
		$(this).parent().addClass('open');*/
		
		return false;
	});
	
	activate_geo();
});
