var directionsService, directionDisplay, classLocation, map, errCode=[];

function computeDirections() {
	directionsService.route({
			origin: $("#from").val(),
			destination: classLocation,
			travelMode: google.maps.DirectionsTravelMode.DRIVING,
			region: "GB"
		},
		displayDirections);
	return false;
}

function displayDirections(response,status) {
	$("#error").hide();
	if( status == google.maps.DirectionsStatus.OK ) {
		directionsDisplay.setMap(map);
		directionsDisplay.setPanel(document.getElementById('directions_panel'));
		directionsDisplay.setDirections(response);
		$('html, body').animate({scrollTop: $("#map_container").offset().top}, 1200);
		$.cookie("location", $("#from").val());
	} else {
		$("#error").html(errCode[status]).fadeIn(300);
		directionsDisplay.setMap(null);
		directionsDisplay.setPanel(null);
	}
}

function showMap(lat, lng, address) {
	classLocation = new google.maps.LatLng(lat,lng);

	map = new google.maps.Map(document.getElementById("map"), {
			zoom: 13,
			center: classLocation,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			scrollwheel: false
	});
	var addressWindow = new google.maps.InfoWindow({content: address});

	var marker=new google.maps.Marker({
		position: classLocation,
		map: map
	});

	addressWindow.open(map,marker);

	with( google.maps.DirectionsStatus ) {
		errCode[INVALID_REQUEST] = "Invalid request.";
		errCode[OVER_QUERY_LIMIT] = "Cannot obtain directions: Too many queries.";
		errCode[REQUEST_DENIED] = "Request denied.";
		errCode[UNKNOWN_ERROR] = "A connection error occurred while trying to obtain directions. Please try again.";
		errCode[ZERO_RESULTS] = "The route could not be calculated for the specified address.";
		errCode[NOT_FOUND] = "Address not found.";
	}
	
	$("#location_info").append(
		"<h3>Get driving directions</h3>                      \
		<form onsubmit='return computeDirections()'>          \
		   <fieldset>                                         \
		      <label for='from'>Start from</label>            \
		      <input id='from' type='text' />                 \
		      <input type='submit' value='Get directions' />  \
		   </fieldset>                                        \
		</form>                                               \
		<div id='error'></div>");

	$("#from").val($.cookie("location"));
	
	$("#map_container").after("<div id='directions_panel'></div>");
	
	google.maps.event.addListener(marker, 'click', function() {addressWindow.open(map,marker)});
	google.maps.event.addListener(map, 'click', function() {addressWindow.close()});

	directionsDisplay = new google.maps.DirectionsRenderer();
	directionsService = new google.maps.DirectionsService();
}

$.fn.center = function() {
	var w=$(window);
	return this.css({
		top:(w.height()-this.height())/2+w.scrollTop(),
		left:(w.width()-this.width())/2+w.scrollLeft()
	});
}

$(function() {
	if( document.getElementById("map") ) {
      showMap(lat, lng, address);
	}

	var main = $("#main");

	var preview = $("<img class='album' style='position:absolute'>")
		.hide()
		.appendTo("body");

	$("a[href$='jpg']").click(function() {
		main.addClass("loading");
		preview.attr("src",$(this).attr("href"))
			.load(function() {
				main.stop().fadeTo(200,0.5);
				preview.center().show();
				main.removeClass("loading");
			});
		return false;
	});

	$("body").click(function() {
		if( preview.is(":visible" )) {
			preview.fadeOut(300);
			main.stop().fadeTo(200,1);
			return false;
		}
	});

	$(window).scroll(function(){preview.center()});
});

$.cookie = function(name, value, options) {
	if( typeof value != 'undefined') { // name and value given, set cookie
		options = options || {};

		if (value === null) {
			value = '';
			options.expires = -1;
		}

		var expires = '';

		if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
			var date;
			if( typeof options.expires == 'number' ) {
				date = new Date();
				date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
			} else {
				date = options.expires;
			}
			expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
		}
	// CAUTION: Needed to parenthesize options.path and options.domain
	// in the following expressions, otherwise they evaluate to undefined
	// in the packed version for some reason...
		var path = options.path ? '; path=' + (options.path) : '';
		var domain = options.domain ? '; domain=' + (options.domain) : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
	} else { // only name given, get cookie
		var cookieValue = null;
		if( document.cookie ) {
			var cookies = document.cookie.split(';');
			for (var i = 0; i < cookies.length; i++) {
				var cookie = jQuery.trim(cookies[i]);
		// Does this cookie string begin with the name we want?
				if( cookie.substring(0, name.length + 1) == (name + '=') ) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		
		return cookieValue;
	}
}