var map;

$(document).ready(function(){
	$("span.tile img").imgCenter();

	$('#recent div a#zoom').click(function(e){
		e.preventDefault();
		$image = $(this).siblings('a').find('img').eq(0);
		$cache_image = $(this).siblings('img').eq(0)

		$current_url = $image.attr('src');
		$cache_url = $cache_image.attr('src');

		if($image.width() <= 500) {
			$image.attr('src', $cache_url);
			$cache_image.attr('src', $current_url);
			$image.animate({ 
	        	width: ($image.width()+400)+'px',
	        	maxWidth: ($image.width()+400)+'px',
				marginLeft: '-200px',
				marginTop: '-20px'
			}, 1500 );
		} else {
			$image.animate({
	        	width: '500px',
				marginLeft: '0',
				marginTop: '0'
			}, 1500, null, function() {
				$image.attr('src', $cache_url);
				$cache_image.attr('src', $current_url);
			});
		}
		if($image.width() <= 500) {
			$(this).animate({ 
				right: '-185px'
			}, 1500, null, function(){
				$(this).css('top', '-5px');
				$(this).toggleClass('in');
				$(this).text('Smaller');
			});
		} else {
			$(this).css('top', '15px');
			$(this).animate({
				right: '15px'
			}, 1500, null, function(){
				$(this).toggleClass('in');
				$(this).text('Larger');
			});
		}
	});
	
	$('#s').toggle();
	$('#search label img').click(function(){
		$('#s').animate({
			width: 'toggle'
		}, 500, null, function(){
			$('#search').toggleClass('closed');
			if($('#search').className == 'closed')
				$('#s').hide();
		});
	});
	
	$('.toggle-map').live('click', function(e){
		e.preventDefault();
		$.show_small_map();
	});

	$('.close').live('click', function(e){
		e.preventDefault();
		$('#map_canvas').hide_map();
	});

	$.place_map();

	$(window).resize(function(){
		$.place_map();
	});

	$(window).scroll(function(){
		$.place_map();
	});
	
	$.show_large_map();
	
});

$(window).load(function(){
	if(document.getElementById('photo') || document.getElementById('archives') || document.getElementById('search-results')) {
		$('.navigation, .navigation a').css('height', ($('#photo div, #archives, #search-results').eq(0).height()+20)+'px');
	} else if(document.getElementById('home')) {
		$('.navigation, .navigation a').css('height', ($('#recent div').eq(0).height()+40)+'px').css('padding', 0);
	}
})

jQuery.place_map = function() {
	var viewportWidth = $(window).width();
	var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height();
	
	var top = (viewportHeight - $('.photo #map').height() - (parseFloat($('#map').css('padding-top')) * 2)) * 0.5;
	var left = (viewportWidth - $('.photo #map').width() - (parseFloat($('#map').css('padding-left')) * 2)) * 0.5;
	
	$('.photo #map').animate(
		{
			'top': $(window).scrollTop() + top + 'px',
			'left': left + 'px'
		},
        {
        	queue: false,
        	duration: 250,
        }
	);
}

jQuery.show_small_map = function() {
	$('.photo #map').fadeIn('fast', function(){
		if($('.photo #map:empty')) {
			var lng = parseFloat($('input[name=longitude]').val());
			var lat = parseFloat($('input[name=latitude]').val());
			var latlng = new google.maps.LatLng(lat, lng);
			
			map = new google.maps.Map(document.getElementById("map_canvas"), {
				zoom: 13,
				center: latlng,
				disableDefaultUI: true,
				mapTypeId: google.maps.MapTypeId.ROADMAP      
			});
			
			var icon = image = "/wordpress/wp-content/themes/f-stop-theme/images/marker.png";
			var geocoder = new google.maps.Geocoder();
			geocoder.geocode({'latLng': latlng}, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					if (results[0]) {
						var title = results[0].formatted_address;
					} else {
						var title = results[1].formatted_address;
					}
					var marker = new google.maps.Marker({
						position: latlng,
						map: map,
						icon: icon,
						title: title
					});
				} else {
					alert("Geocoder failed due to: " + status);
				}
			});			
			$.create_map_controls();
			$(document).keyup(function(event){
			    if (event.keyCode == 27) {
			    	$('#map_canvas').hide_map();
			    }
			});
		}
	});
}

jQuery.show_large_map = function() {
	if(document.getElementById('photo-map')) {
		$.getJSON('/photos.json', function(data) {
			var latlng = new google.maps.LatLng(0, 0);
			map = new google.maps.Map(document.getElementById("map_canvas"), {
				zoom: 4,
				center: latlng,
				disableDefaultUI: true,
				mapTypeId: google.maps.MapTypeId.ROADMAP      
			});
			$.create_map_controls();

			var icon = image = "/wordpress/wp-content/themes/f-stop-theme/images/marker.png";
			var geocoder = new google.maps.Geocoder();
			var bounds = new google.maps.LatLngBounds();
			$.each(data.posts, function(i,post){
				latlng = new google.maps.LatLng(parseFloat(post.latitude), parseFloat(post.longitude));
				var marker = new google.maps.Marker({
					position: latlng,
					map: map,
					icon: icon,
					title: post.post_title
				});
				bounds.extend(marker.position)
				
				var content = '<div class="window">' + 
					'<h3><a href="/archives/' + post.post_name + '/">' + post.post_title + '</a></h3>' + 
					'<p><a href="/archives/' + post.post_name + '/"><img src="/wordpress/wp-content/photog/thumbnail/'+post.post_name+'.jpg" alt="'+post.post_title+'" /></a></p>' + 
					'<p>' + $.PHPDate('F j, Y', new Date($.mysqlTimeStampToDate(post.post_date))) + '</p>' + 
					'</div>';
				var infowindow = new google.maps.InfoWindow({ content: content });
				
				google.maps.event.addListener(marker, 'click', function() {
					infowindow.open(map,marker);
				});
			});
			map.setCenter(bounds.getCenter());
		});
		
	}
}

jQuery.fn.hide_map = function() {
	$('#map_canvas').empty();
	$(document).unbind('keyup');
	$('#map').fadeOut('normal');
}

jQuery.create_map_controls = function() {
	$('#mapcontrols button').click(function(e) { e.preventDefault(); });				
	$('#centerButton').click(function() { map.panTo(bounds.getCenter()); });
	$('#upButton').click(function() { map.panBy(0,-20); });
	$('#downButton').click(function() { map.panBy(0,20); });
	$('#rightButton').click(function() { map.panBy(20,0); });
	$('#leftButton').click(function() { map.panBy(-20,0); });
	$('#zoomInButton').click(function() { map.setZoom(map.zoom + 1); });
	$('#zoomOutButton').click(function() { map.setZoom(map.zoom - 1); });
}

jQuery.mysqlTimeStampToDate = function(timestamp) {
	//function parses mysql datetime string and returns javascript Date object
	//input has to be in this format: 2007-06-05 15:26:02
	var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
	var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
	return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
}