$(document).ready(function() {
	var lastY = false;
	var lastX = false;
	var isDragging = false;
	$(document).ready(function() {
		$('#slider').slider({
			value: 100,
			min: 100,
			max: 400,
			step: 100,
			orientation: 'vertical',
			slide: function(event, ui) {
				zoomMap(ui.value);
			}
		});
		plotPoints();
		adjustPosition();
	});
	$('a.search', '#mapContainer').click(function() {
		$('#searchPanel').slideDown();
		return false;
	});
	$('#viewport').mousedown(function(e) {
		lastY = e.clientY;
		lastX = e.clientX;
		isDragging = true;
	});
	$('#viewport').mouseup(function() {
		isDragging = false;
	});
	$('#viewport').mouseleave(function() {
		isDragging = false;
	});
	$('#viewport').mousemove(function(e) {
		if (isDragging) {
			setTop(e);
			setLeft(e);
		}
	});
	$('#viewport').dblclick(function() {
		zoomMap('+');
	});
	$('#mapSearchSubmit').click(function() {
		openMapModal('map/get.php?path=' + escape('practices/index/?' + $('#mapSearchForm').serialize()));
		$('#searchPanel').slideUp();
	});
	$('#mapSearchCancel').click(function() {
		$('#searchPanel').slideUp();
	});
	$('.point', '#canvas').mouseup(function() {
		openMapModal('map/get.php?path=' + escape('towns/view/' + $(this).attr('id').split('_')[1]));
	});
	$('.zoom-level', '#zoom').click(function(e) {
		zoomMap($(this).attr('id').split('_')[1]);
	});
	$('.zoom-in', '#zoom').click(function(e) {
		zoomMap('+');
	});
	$('.zoom-out', '#zoom').click(function(e) {
		zoomMap('-');
	});
	
	function zoomMap(level) {
		var levels = [100, 200, 300, 400];
		var currentLevel;
		var newLevel = level;
		
		// Find the new level.
		for (i in levels) {
			if ($('#canvas').hasClass('canvas_' + levels[i])) {
				var currentLevel = levels[i];
				$('#canvas').removeClass('canvas_' + levels[i]);
				if (level == '+') {
					if (parseInt(i) != levels.length - 1) {
						newLevel = levels[parseInt(i) + 1];
					} else {
						newLevel = levels[i];
					}
				} else if (level == '-') {
					if (parseInt(i) != 0) {
						newLevel = levels[i - 1];
					} else {
						newLevel = levels[i];
					}
				}
			}
		}
		
		// Find the center point of zoom.
		var actualCenterX = (parseInt($('#canvas').css('left')) * -1) +
				(parseInt($('#viewport').width()) / 2);
		var actualCenterY = (parseInt($('#canvas').css('top')) * -1) +
				(parseInt($('#viewport').height()) / 2);
		var zoomCenterX = Math.floor(actualCenterX / (currentLevel / 100));
		var zoomCenterY = Math.floor(actualCenterY / (currentLevel / 100));
		var newCenterX = zoomCenterX * (newLevel / 100);
		var newCenterY = zoomCenterY * (newLevel / 100);
		var newLeft = -1 * (newCenterX - 
				Math.floor(parseInt($('#viewport').width()) / 2));
		var newTop = -1 * (newCenterY - 
				Math.floor(parseInt($('#viewport').height()) / 2));
				
		/*$('#canvas').animate({
				width: '120%',
				height: '120%',
				}, 'def', false, function () {
		});*/
		
		// Zoom the map.
		$('#slider').slider('option', 'value', newLevel);
		$('#canvas').addClass('canvas_' + newLevel);
		$('#canvas').css('left', newLeft);
		$('#canvas').css('top', newTop);
		$('.zoom-level', '#zoom').attr('src', '/img/zoom-level.png');
		$('#zoomLevel_' + newLevel).attr('src', '/img/zoom-level-sel.png');
		plotPoints();
		adjustPosition();
	}
	
	function setTop(e) {
		var currentTop = parseInt($('#canvas').css('top'));
		var moveAmount = e.clientY - lastY;
		$('#canvas').css('top', currentTop + moveAmount);
		lastY = e.clientY;
		adjustPosition();
	}
	
	function setLeft(e) {
		var currentLeft = parseInt($('#canvas').css('left'));
		var moveAmount = e.clientX - lastX;
		$('#canvas').css('left', currentLeft + moveAmount);
		lastX = e.clientX;
		adjustPosition();
	}
	
	function adjustPosition() {
		var currentTop = parseInt($('#canvas').css('top'));
		var currentLeft = parseInt($('#canvas').css('left'));
		var maxTop = -1 * (parseInt($('#canvas').css('height')) - parseInt($('#viewport').css('height')));
		var maxLeft = -1 * (parseInt($('#canvas').css('width')) - parseInt($('#viewport').css('width')));
		if (currentTop > 0) {
			$('#canvas').css('top', 0);
		}
		if (currentLeft > 0) {
			$('#canvas').css('left', 0);
		}
		if (currentTop <= maxTop) {
			$('#canvas').css('top', maxTop);
		}
		if (currentLeft <= maxLeft) {
			$('#canvas').css('left', maxLeft);
		}
	}
	
	function plotPoints() {
		var currentZoom = parseInt($('#canvas').attr('class').split('_')[1]);
		var multiplier = currentZoom / 100;
		var pointPositions = {};
		$('.point', '#canvas').each(function() {
			var leftPos = parseInt($(this).attr('class').match(/x-[0-9]+/).
					toString().split('-')[1]);
			var topPos = parseInt($(this).attr('class').match(/y-[0-9]+/).
					toString().split('-')[1]);
			$(this).css('left', leftPos * multiplier);
			$(this).css('top', topPos * multiplier);
			pointPositions[$(this).attr('id')] = {left: leftPos, top: topPos};
		});
		$('.point', '#canvas').each(function() {
			var thisLeft = parseInt($(this).css('left'));
			var thisWidth = parseInt($(this).width());
			var thisTop = parseInt($(this).css('top'));
			for (i in pointPositions) {
				if ($(this).attr('id') != i && 
						(thisLeft <= pointPositions[i]['left']) &&
						(thisLeft + thisWidth > pointPositions[i]['left']) &&
						(Math.abs(thisTop - pointPositions[i]['top']) < 10)) {
					$(this).addClass('point-right');
					$(this).css('left', (thisLeft - thisWidth) * multiplier);
				}
				if ((thisLeft + thisWidth) > parseInt($('#canvas').width())) {
					$(this).addClass('point-right');
					$(this).css('left', (thisLeft - thisWidth) * multiplier);
				}
			}
		});
	}
	
	function openMapModal(loc) {
		$.get(loc, null, function(data) {
			$.modal(data, {
				onOpen: function (dialog) {
					dialog.overlay.fadeIn('fast', function () {
						dialog.container.height(dialog.data.height());
						dialog.data.hide();
						dialog.container.show('fast', function () {
							var newHeight = dialog.data.outerHeight(true);
							if (newHeight > 450) {
								newHeight = 450;
								dialog.data.find('ul').addClass('max-height');
							}
							var newTop = Math.floor((parseInt($(window).height()) - newHeight) / 2);
							dialog.container.animate({height: newHeight, top: newTop});
							dialog.data.fadeIn('fast');
						});
					})
				},
				onClose: function (dialog) {
					dialog.data.fadeOut('def', function () {
						dialog.container.hide('def', function () {
							dialog.overlay.fadeOut('fast', function () {
								$.modal.close();
							});
						});
					})
				}
			});
		});
	}
});
