var map, marker, center, customUI, zoom, lat, lon, $mapwindow, map_is_loaded;

var MEDIA_URL = 'http://dipsy-tc.pbs.org/nationalparks/media/';

$(function (){
		
	/* PARK SELECTOR WIDGET */
	$('#parks').parkpicker({src: MEDIA_URL+'js/parks.js'});

	/* FIELD VALIDATION */
	$("#storyshare_form").append("<p align=right id=error_summary></p>");
	$("#storyshare_form").validate({
		rules: {
			submission_first_name: {required: true},
			submission_last_name: {required: true},
			submission_email: {required: true, email: true},
			city: {required: true},
			state: {required: true},
			parks: {required: true},
			submission_title: {required: true, maxlength: 75},
			submission_short_desc: {required: true},
			terms_of_use: {required: true}
		},
		messages: {
			state: "Required",
			terms_of_use: "You must read and agree with our Privacy & Terms of Use Policy."
		},
		invalidHandler: function(form, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) {
				var message = errors == 1
				? 'Your story submission has one error.'
				: 'Your story submission has ' + errors + ' errors.';
				$("#error_summary").html(message+ " Items with an * are required.").show();
			} else {
				$("#error_summary").hide();
			}
		}
	});
	
	/* REPEATABLE FIELDS */
	function remove_repeated(){
		var response = true;
		var $container = $(this).parent('p');
		if ( $('input',$container).val() != '' ) { response = confirm("Are you sure?"); }
		if (response) { $container.remove(); }
		return false;
	}
	var $another = $('<button>Add Another</button>').click(function(){
		var $clone = $('div.repeatable p:first').clone();
		var $input = $clone.find('input');
		$input.val('');
		$input.attr('id', $input.attr('id') + '_' + (new Date().getTime()) );
		$clone.find('button').text('Remove').bind('click',remove_repeated);
		$('div.repeatable').append($clone);
		return false;
	});
	$('div.repeatable p:first').append($another);

	/* LOCATION - POPUP */
	map_is_loaded = false;
	$mapwindow = $('<div id=storyshare_map_dialog />');
	$('#doc').append($mapwindow);	
	$mapwindow.dialog({
		autoOpen: false,
		bgiframe: true,
		closeOnEscape: true,
		draggable: false, 
		resizable: false,
		modal: true,
		width: 565,
		title:'Find the latitude and longitude associated with your story'		
	});
	var $trigger = $('<a href="#" class="map">Find the latitude and longitude associated with your story</a>').click(function(){
		if (map_is_loaded == false) {
			// create the map markup and load the api
			$mapwindow.html('<p><strong>Set the location of your story by clicking and dragging the marker icon (<img src="'+MEDIA_URL+'images/red-dot.png" alt="Marker Icon" width="16" height="16" align="absbottom" />) around the map</strong>. To move to a different location, you can use the directional arrows in the upper right corner of the map, or click and drag anywhere on the map. To zoom in or out on the map use the +/- arrows on the left, or the scroll wheel on your mose. When you\'ve finished, press the "Update Location" button below the map to return to the form, or press "Cancel" to close this window.</p><div id="map_canvas"></div><form name="location_form" id="location_form"><p><button type="submit" class="button" id="update_location"><b><span>Update Location</span></b></button></p></form>');
			google.load("maps", "2", {"callback" : initialize_map});
		} 
		$mapwindow.dialog('open');
		return false;
	});
	$('<p />').append($trigger).appendTo('#storyshare_form .col.first');

});

/* LOCATION - MAP */
function initialize_map() { 
	map_is_loaded = true;
	// default is US centered
	lat = 40.313043208;
	lng = -94.39453125;
	zoom = 3;
	// if the visitor is in the US, use their current location as a starting point
	if (google.loader.ClientLocation && google.loader.ClientLocation.address.country_code == "US") {
		lat = google.loader.ClientLocation.latitude;
		lng = google.loader.ClientLocation.longitude;
		zoom = 5;
	}
	map = new GMap2(document.getElementById("map_canvas"));
	center = new GLatLng(lat, lng);
	marker = new GMarker(center, {draggable: true});
	customUI = map.getDefaultUI();
	customUI.maptypes.hybrid = false;
	customUI.zoom.doubleclick  = false;
	customUI.keyboard = false;
	customUI.controls.scalecontrol = false;
	map.setUI(customUI);
	map.setCenter(center, zoom);
	map.addOverlay(marker);
	$('#update_location').click(function(){
		var pos =  marker.getPoint();
		$('#latitude').val(pos.lat());
		$('#longitude').val(pos.lng());
		$mapwindow.dialog("close"); 
		return false;
	});
}
function GUnload(){ /* placeholder - overridden by GoogleMap API when loaded */ };
$().unload(GUnload);