	// Append place row to the list
	function appendPlaceRow(placeId) {
		if (wtrTrip.tripStatus != 's' && wtrTrip.tripStatus != 'g' ) {
   			entry = "<tr id=\"row" + placeId + "\">"+
   					"<td style='width:30px;' class='dragHandle' title='Drag to re-order the trip'></td>"+
   					"<td style='width:100px;'>"+name+"</td>"+
   					"<td style='width:100px;'>"+country+"</td>"+
   					"<td style='width:70px;'>"+date+"</td>"+
   					"<td style='width:70px;'  class='focus_button' onmouseover=\"this.style.cursor = 'pointer';\" title='Center map on "+name+"'><a class='' href='#' onclick=\"panTo('"+placeId+"');return false;\">Focus</a></td>"+
   					"<td style='width:70px;'>" + 
   					"<select onblur=\"changePlaceLocType('"+placeId+"');return false;\" name='locType" + placeId +"'>";
   			if (locType == 'w') {
   				entry += "<option value='s'>Sight</option>" +
						 "<option value='w' selected>Mark</option>";
			}
			else {
   				entry += "<option value='s' selected>Sight</option>" +
						 "<option value='w'>Mark</option>";
			}
			entry += "</select>" +
					"</td>"+
   					"<td style='width:70px;'>" + 
   					"<select onblur=\"changePlaceMedType('"+placeId+"');return false;\" name='medType" + placeId +"'>";
   			if (medType == 'a') {
   				entry += "<option value='a' selected>Air</option>" +
				 "<option value='l'>Land</option>";
			}
			else {
   				entry += "<option value='a'>Air</option>" +
				 "<option value='l' selected>Land</option>";
			}
			entry += "</select>" +
					"</td>"+
   					"<td style='width:70px;' class='delete_button' onmouseover=\"this.style.cursor = 'pointer';\" title='Delete "+name+"'><a class='' href='#' onclick=\"deletePlace('"+placeId+"','"+name+"-"+date+"');return false;\">Delete</a></td>"+
   					"</tr>";
    	}
    	else if (generated == true) {
    		if (date == 'none') date = '';
   			entry = "<tr id=\"row" + placeId + "\">"+
   					"<td style='width:30px;' class=''></td>"+
   					"<td style='width:100px;'>"+name+"</td>"+
   					"<td style='width:100px;'>"+country+"</td>"+
   					"<td style='width:70px;'>"+date+"</td>"+
   					"<td style='width:70px;' class='focus_button' onmouseover=\"this.style.cursor = 'pointer';\" title='Center map on "+name+"'><a class='' href='#' onclick=\"panTo('"+placeId+"');return false;\">Focus</a></td>"+
   					"<td style='width:70px;'></td>"+
    				"<td style='width:70px;' class='delete_button'></td>"+
   					"</tr>";
    	}
    	else {
   			entry = "<tr id=\"row" + placeId + "\">"+
   					"<td style='width:30px;' class=''></td>"+
   					"<td style='width:100px;'>"+name+"</td>"+
   					"<td style='width:100px;'>"+country+"</td>"+
   					"<td style='width:70px;'>"+date+"</td>"+
   					"<td style='width:70px;' class='focus_button' onmouseover=\"this.style.cursor = 'pointer';\" title='Center map on "+name+"'><a class='' href='#' onclick=\"panTo('"+placeId+"');return false;\">Focus</a></td>"+
   					"<td style='width:70px;'></td>"+
   					"<td style='width:70px;' class='delete_button'>Delete</td>"+
   					"</tr>";
    	}
        $("#place_list tbody").append(entry);	
	}
	
	function changePlaceLocType(placeId) {
		var place = wtrTrip.places[placeId];
		place.locType = $("[name=locType"+placeId+"]").val();
		changeAlteredState(true);
	}
	
	function changePlaceMedType(placeId) {
		var place = wtrTrip.places[placeId];
		place.medType = $("[name=medType"+placeId+"]").val();
		changeAlteredState(true);
	}
	
	// Reset drag and drop
	function resetDnD() {
		if (wtrTrip.tripStatus != 's' && wtrTrip.tripStatus != 'g' ) {
			$("#place_list").tableDnD({
				onDrop: function(table, row) {
					mapper.reorder_markers($('#place_list').tableDnDSerialize()); 
					changeAlteredState(true);
				},
				dragHandle: "dragHandle"
			});
			$("#place_list tr").hover(function() {
		          $(this.cells[0]).addClass('showDragHandle');
		    }, function() {
		          $(this.cells[0]).removeClass('showDragHandle');
		    });
		}
		$("#place_list tr:even").addClass('alt');
	}
	
    // Attach map and list
    function attachMapAndList (){
        mapper          = new MapObject( map );
        mapper.map_node = document.getElementById('#trip_map');
        mapper.init_from_raw(itinerary);  

		// Need to keep the trip elements for saving later
		wtrTrip = new Wtr.wtrTrip();
       	wtrTrip.init(itinerary); // Add to trip for save reference
       	
       	// If work in progress set up GEvent to capture clicks on the map
		if (wtrTrip.tripStatus != 's' && wtrTrip.tripStatus != 'g' ) {			
			GEvent.addListener(map, 'click', function(overlay, latlng) {
			  var lat = latlng.lat();
			  var lon = latlng.lng();
			  createClickedPlace(lat,lon);
			});
		}
		
    	// fill entry list
    	$("place",itinerary).each(function(i) {  
  			place = $("place",itinerary).get(i);  
   			name = $("name", place).text();
   			country = $("country", place).text();
   			date = $("date", place).text();
   			placeId = $("journeyId", place).text();
   			locType = $("locType", place).text();
   			medType = $("medType", place).text();
   			if (placeId != '') {
   				appendPlaceRow(placeId);
			}
		});  
        resetDnD();
        if (generated == true) {
			if (wtrTrip.tripStatus != 'g' && wtrTrip.tripStatus != 's') {
				// We should not be here!!!
				alert ("navigation disabled");
    			document.location="/trip/trip.php";
			}
			if (wtrTrip.places.length == 1) { 
				mapper.focus_route();
	        	mapper.map.setZoom(6);
        	}
			else {
				mapper.focus_route();
			}
			// Populate personal panels
			if (wtrTrip.tripFlickr != '') {
				flickrHtml = "<object height=\"330\" width=\"330\"><param value=\"offsite=true&amp;lang=en-us&amp;page_show_url=%2Fphotos%2F" + wtrTrip.tripFlickr + "%2Fshow%2F&amp;page_show_back_url=%2Fphotos%2F" + wtrTrip.tripFlickr + "%2F&amp;set_id=" + wtrTrip.tripFlickrSet + "&amp;user_id=" + wtrTrip.tripFlickr + "&amp;jump_to=\" name=\"flashvars\"><param value=\"true\" name=\"allowFullScreen\">" +
					"<embed width=\"330\" height=\"330\" flashvars=\"offsite=true&amp;lang=en-us&amp;page_show_url=%2Fphotos%2F" + wtrTrip.tripFlickr + "%2Fshow%2F&amp;page_show_back_url=%2Fphotos%2F" + wtrTrip.tripFlickr + "%2F&amp;set_id=" + wtrTrip.tripFlickrSet + "&amp;user_id=" + wtrTrip.tripFlickr + "&amp;jump_to=\" allowFullScreen=\"true\" src=\"http://www.flickr.com/apps/slideshow/show.swf?\" type=\"application/x-shockwave-flash\"></embed>" + 
					"</object>";
				$("#flickr-main").append(flickrHtml);
			}
				
			if (wtrTrip.tripYouTube != '') {
				youTubeHtml = "<object height=\"330\" width=\"330\"><param value=\"http://www.youtube.com/" + wtrTrip.tripYouTube + "&amp;hl=en_GB&amp;fs=1\" name=\"movie\"><param value=\"true\" name=\"allowFullScreen\"><param value=\"always\" name=\"allowscriptaccess\">" +
					"<embed allowfullscreen=\"true\" allowscriptaccess=\"always\" height=\"330\" width=\"330\" type=\"application/x-shockwave-flash\" src=\"http://www.youtube.com/" + wtrTrip.tripYouTube + "&amp;hl=en_GB&amp;fs=1\"></embed>" +
					"</object>";
				$("#youtube-main").append(youTubeHtml);	
			}
			// Select default personal panel
			if (wtrTrip.tripFlickr != '') {
				choosePersonal('flickr');
			}
			else if (wtrTrip.tripYouTube != '') {
				choosePersonal('youtube');
			}
			else {
				choosePersonal('none');
			}
			// Show creator name
			//$("#trip-creator-span").append(wtrTrip.creatorName); done inwtrobjects but this may turn out to be a mistake!
			//document.title = "World Travel Routes - Trip - " + wtrTrip.name + " by " + wtrTrip.creatorName;
			selectLinks();
			selectMains();
        }
    }
    
	function choosePersonal(choice) {
		if (choice == 'flickr') {
			$('#flickr').show();
			$('#flickr-links').show();
			$('#youtube').hide();
			$('#youtube-links').hide();
			$('#noimage').hide();
			$('#noimage-links').hide();
		}
		else if (choice == 'youtube') {
			$('#flickr').hide();
			$('#flickr-links').hide();
			$('#youtube').show();
			$('#youtube-links').show();
			$('#noimage').hide();
			$('#noimage-links').hide();
		}
		else {
			$('#flickr').hide();
			$('#flickr-links').hide();
			$('#youtube').hide();
			$('#youtube-links').hide();
			$('#noimage').show();
			$('#noimage-links').show();
		}
	}

    function selectLinks() {
		// Hide editing facilities
		if (wtrTrip.creatorName != username) {
			if (generated == true) {
				$('#youtube-links-own').hide();
				$('#flickr-links-own').hide();
				$('#article-links-own').hide();
				$('#youtube-links-view').show();
				$('#flickr-links-view').show();
				$('#article-links-view').show();
			}
		}
		else if (wtrTrip.creatorName == username) {
			if (generated == true) {
				$('#youtube-links-own').show();
				$('#flickr-links-own').show();
				$('#article-links-own').show();
				$('#youtube-links-view').hide();
				$('#flickr-links-view').hide();
				$('#article-links-view').hide();
			}
		}
    }
    
    function selectMains() {
    	// Select appropriate main panels
		if (wtrTrip.creatorName != username) {
			if (generated == true) {
				$('#noimage-own').hide();
				$('#youtube-none-own').hide();
				$('#flickr-none-own').hide();
				$('#noimage-view').show();
				if (wtrTrip.tripYouTube != '') {
					$('#youtube-main').show();
					$('#youtube-none-view').hide();
				}
				else {
					$('#youtube-main').hide();
					$('#youtube-none-view').show();
				}
				if (wtrTrip.tripFlickr != '') {
					$('#flickr-main').show();
					$('#flickr-none-view').hide();
				}
				else {
					$('#flickr-main').hide();
					$('#flickr-none-view').show();
				}
			}
		}
		else if (wtrTrip.creatorName == username) {
			if (generated == true) {
				$('#noimage-view').hide();
				$('#youtube-none-view').hide();
				$('#flickr-none-view').hide();
				$('#noimage-own').show();
				if (wtrTrip.tripYouTube != '') {
					$('#youtube-main').show();
					$('#youtube-none-own').hide();
				}
				else {
					$('#youtube-main').hide();
					$('#youtube-none-own').show();
				}
				if (wtrTrip.tripFlickr != '') {
					$('#flickr-main').show();
					$('#flickr-none-own').hide();
				}
				else {
					$('#flickr-main').hide();
					$('#flickr-none-own').show();
				}
			}
		}
    }

    // Phase 1 of map javascript appending
    function Mapper_js_1() {
        if ($("#GMap_js").length === 0) {
            var script = document.createElement("script");
            script.id = "GMap_js"
            script.type = "text/javascript";
            script.src = "http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAeiPC5zXHNIxGW_X8Oh9fThQT_MVcdv-RAYbB4QI7ajAgZ93L3xTOkLyMsHaRxRgtdAffnbLix4-CRA&async=2&callback=Mapper_js_2";
            document.body.appendChild(script);
            $(window).unload( function () {
                GUnload(); //unload google maps
            });
            return;
        }
    }

    // Phase 2 of map javascript appending
    function Mapper_js_2() {
    	// Delayed loading of mapping functionality
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "/js/markermanager.js";
        document.body.appendChild(script);
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "/js/poly.js";
        document.body.appendChild(script);
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "/js/mapinclude.js";
        document.body.appendChild(script);
    }

    function GMap_initialize() {
		if (GBrowserIsCompatible()) {
			var map_canvas = document.getElementById("map_canvas");
			if (generated == true) {
				map = new GMap2(map_canvas, { size: new GSize(568,330) } );
				map.addControl( new GSmallMapControl());
			}
			else {
				map = new GMap2(map_canvas, { size: new GSize(948,550) } );
				map.addControl( new GLargeMapControl());
			}
			map.addControl( new GMenuMapTypeControl() );
			map.setCenter(new GLatLng(23, 15), 2);
			attachMapAndList();  
		}
		else {
		}
    }

    function createClickedPlace(lat,lon) {
        var baseDate = 'none';
	
		var userquery_url = '/trip/user_query.php';
		$.post(userquery_url,{  
			username: username
		}, function(user) {
			// Get user account status 
			type = $("type", user).text();
			// Get the limit to apply
			var limit = 11;
			if (type == 'p' || type == 'f') {
				limit = 101;
			}
			// Get current size
			var locations = getTripSize($('#place_list').tableDnDSerialize());
			// Warn if current add will leave no further locations to add
			if (limit - locations == 1) {
				warnUpgrade(type, 'add');
			}
			// Deny if no further locations to add
			else if (limit - locations < 1) {
				if(!denyUpgrade(type, 'add')) {
					return false;
				}
			}
				
	        var getclickedbase_url = '/trip/get_clicked_base.php';
	        $.post(getclickedbase_url,{  
	       		lat: lat,
	       		lon: lon,
	       		baseDate: baseDate
	       		  
	     	}, function(xml) {
	       		baseResponse = xml;  
		  		timestamp = $("time",baseResponse).text();
		  		getLocationName(timestamp);
	 		});   
 		});
    }
    
    function getLocationName(timestamp) {
    	action = 'getloc';
		// Ask for location name then callback promptCallback
		currentVal = timestamp;
		IEprompt('Name for location', currentVal);
    }
    
    function keepLocationName(val) {
		//NEED TO INJECT val into baseResponse and handle cancel better - also will need to be able to edit name after the event.
		$("place",baseResponse).each(function(i) {  
	  		place = $("place",baseResponse).get(i);  
   			name = $("name", place).text(val);
		});  

      	mapper.add_to(baseResponse);
      	wtrTrip.add_new(baseResponse); // Add to trip for save reference
       	$('#journey')[0].reset();
		changeAlteredState(true);
		createPlaceSuccess();
    }	     	  

    // WTR - Reorder markers from php table
    function getTripDetails(tableinfo) {
 		// Parse tableinfo string
    	// Remove 'place_list[]=row'
		var tableString = tableinfo.replace(/place_list/g, '');
    	// Collect indices using '&' as separator
		var splitResult = tableString.split("&");
 		var tripDetails = "";
		for(i = 0; i < splitResult.length; i++){
			var placeId = splitResult[i].substring(6);
			if (placeId != "") {
				var place = wtrTrip.places[placeId];
				tripDetails = tripDetails + place.toString();
			}
    	}
    	return tripDetails;
    }
    
    // Create new locations for 'User Generated' country places
    function createNewLocations(tableinfo) {
 		// Parse tableinfo string
    	// Remove 'place_list[]=row'
		var tableString = tableinfo.replace(/place_list/g, '');
    	// Collect indices using '&' as separator
		var splitResult = tableString.split("&");
		for(i = 0; i < splitResult.length; i++){
			var placeId = splitResult[i].substring(6);
			if (placeId != "") {
				var place = wtrTrip.places[placeId];
				if (place.country == 'User Generated' && (place.lat != '0' || place.long != '0')) {
			       	var locsave_url = '/trip/save_loc.php';
			        $.post(locsave_url,{  
			       		name: place.name,
			       		lat: place.lat,
			       		long: place.long,   
			       		tripId: wtrTrip.tripId     		  
			     	}, function(loc) {
						locationId = $("locationId", loc).text();
						lat = $("lat", loc).text();
						long = $("long", loc).text();
			 		});   
				}
			}
    	}
    }
    
    // A crap way of getting the table size - TODO look for better later
    function getTripSize(tableinfo) {
     	// Parse tableinfo string
    	// Remove 'place_list[]=row'
		var tableString = tableinfo.replace(/place_list/g, '');
    	// Collect indices using '&' as separator
		var splitResult = tableString.split("&");
		return splitResult.length - 1;
    }
    
	function getCookie(c_name)
	{
		if (document.cookie.length>0)
		  {
		  c_start=document.cookie.indexOf(c_name + "=");
		  if (c_start!=-1)
		    {
		    c_start=c_start + c_name.length+1;
		    c_end=document.cookie.indexOf(";",c_start);
		    if (c_end==-1) c_end=document.cookie.length;
		    return unescape(document.cookie.substring(c_start,c_end));
		    }
		  }
		return "";
	}

	function showLoginOverlay() {
		// Ask for logged out user to login/register
		$('.login-overlay').show();
    	$('.new_place').hide();
    	$("[name=username]").focus();
	}
	
	function saveOnLoggedIn() {
		if (isLoggedIn()) {
			llSaveTrip();
		}
		else
		{
			showLoginOverlay();
		}
	}
	
	function llSaveTrip() {
		var userquery_url = '/trip/user_query.php';
		$.post(userquery_url,{  
			username: username
		}, function(user) {
			wtrTrip.userId = $("userId", user).text();
			// Get user account status 
			type = $("type", user).text();
			// Get the limit to apply
			var limit = 5;
			if (type == 'p') {
				limit = 9999;
			}
			// Get trips_held
			var tripsHeld = $("tripsHeld", user).text();
			// Warn if current save will leave no further trips to be saved
			if (limit - tripsHeld == 1) {
				warnUpgrade(type, 'save');
			}
			// Deny if no space for new trip
			else if (limit - tripsHeld < 1) {
				if(!denyUpgrade(type,'save')) {
					alert('Suggestion: Make free space by deleting an existing trip');
					return false;
				}
			}
			var tableinfo = $('#place_list').tableDnDSerialize();
	 		var tripDetails = getTripDetails(tableinfo);
	       	var tripsave_url = '/trip/save_trip.php';
	        $.post(tripsave_url,{  
	       		userId: wtrTrip.userId,
	       		tripId: wtrTrip.tripId,
	       		name: wtrTrip.name,
	       		tripDetails: tripDetails        		  
	     	}, function(trip) {
				wtrTrip.tripId = $("tripId", trip).text();
				createNewLocations(tableinfo);
	       		mapper.focus_route();
				changeAlteredState(false);
				requestPlacesForCountryChange('departure', wtrTrip.tripId);
				// Recalculate trips_held
				calculateTripsHeld();
				$("#persist-generate a").focus();
	 		});   
		});   
	}
	function calculateTripsHeld() {
       	var counttrips_url = '/trip/count_trips.php';
        $.post(counttrips_url,{  
       		userId: wtrTrip.userId
     	}, function(response) { 
 		});   
	}
	
    function saveTrip() {
    	if (alteredState == false) {
    		alert("Tour trip has not changed");
    		return;
    	}
    	action = 'savetrip';
		// Deal with empty trip name
		if (wtrTrip.name == '') {
			// Ask for name of trip then callback promptCallback
			IEprompt('Please enter trip name to continue with save', '');
		}	
		else {
			$('#trip-name-span').html(wtrTrip.name);
	   		// Deal with user status
	   		saveOnLoggedIn();
		}	
    }
    
    function generateTrip() {
    	// If clicked when not available
    	if (alteredState == true || wtrTrip.tripId == '-1') {
    		alert("Consider saving your trip or rewinding to last save");
    		return;
    	}
    	if (confirm("Submit this trip for Google Earth tour generation?")) {    	
			var userquery_url = '/trip/user_query.php';
			$.post(userquery_url,{  
				username: username
			}, function(user) {
				wtrTrip.userId = $("userId", user).text();
				// Get user account status 
				type = $("type", user).text();
				// Get the limit to apply
				var limit = 3;
				if (type == 'p') {
					limit = 10;
				}
				// Get month_subs
				var monthSubs = $("monthSubs", user).text();
				// Get last_sub
				lastSub = $("lastSub", user).text();
				// If last_sub not in current month set month_subs to 0 
				if (!dateInCurrentMonth(lastSub)) {
					monthSubs = 0;
				}
				// Warn if current submit will leave no further submissions available in current month
				if (limit - monthSubs == 1) {
					warnUpgrade(type, 'generate');
				}
				
				// Deny if submissions for current month already used up
				else if (limit - monthSubs < 1) {
					if(!denyUpgrade(type, 'generate')) {
						return false;
					}
				}
				
				// Submit trip for generation
		       	var tripgenerate_url = '/trip/generate_trip.php';
		        $.post(tripgenerate_url,{  
		       		userId: wtrTrip.userId,
		       		tripId: wtrTrip.tripId
		     	}, function(insert) { 
		     		// lock trip and tidy up
    				document.location="/trip/generatedTrip.php?tripId="+wtrTrip.tripId;
					//	Increment month_subs and set last_sub
					monthSubs = 1 +(+monthSubs);
					setMonthSubs(monthSubs, true);
					alert("Your trip has been submitted. Your trip page is ready to view. Work on generation of your GEarth tour may take upto 1 week. You will be notified by email once this process is complete.");
		 		});   
			}); 
    	}    	
	}
	
	function warnUpgrade(type, warning) {
		var textWarn = "warnerror";
		if (warning == 'generate') {
			if (type == 'f') {
				textWarn = 'This is your last submission until next month. Get Pro Account upgrade?';
			}
			else {
				textWarn = 'This is your last submission until next month.';
			}
		}
		else if (warning == 'save') {
			textWarn = 'This will take you to your trip limit. Get Pro Account upgrade?';
		}
		else if (warning == 'add') {
			if (type == 'f') {
				saveTrip();
				textWarn = 'This is your last location for this trip. Get Pro Account upgrade?';
			}
			else if (type == 'p') {
				saveTrip();
				textWarn = 'This is your last location for this trip.';
			}
			else {
				saveTrip();
    			$('.new_place').show();
				return false;
			}
		}
    	if (confirm(textWarn)) {
    		if (type == 'f') {
    			document.location='/payment/upgrade.php';
			}
		}
	}
		
	function denyUpgrade(type, warning) {
		var textWarn = "denyerror";
		if (warning == 'generate') {
			if (type == 'f') {
				saveTrip();
				textWarn = 'You have no further submissions until next month. Get Pro Account upgrade or cancel this submission?';
			}
			else {
				saveTrip();
				textWarn = 'You have no further submissions until next month.';
			}
		}
		else if (warning == 'save') {
			textWarn = 'You have no trips remaining. Get Pro Account upgrade or cancel this trip?';
		}
		else if (warning == 'add') {
			if (type == 'f') {
				textWarn = 'You have no further locations to add for this trip. Get Pro Account upgrade or cancel adding this location?';
			}
			else if (type == 'p') {
				textWarn = 'You have no further locations to add for this trip. Consider breaking into two trips, or delete unnecessary locations.';
			}
		}
    	if (confirm(textWarn)) {
    		if (type == 'f') {
    			document.location='/payment/upgrade.php';
				return true;
			}
			else {
				return false;
			}
		}
		else {
			return false;
		}
	}

	function setMonthSubs(monthSubs, setLastSub) {
		var storeDate = 'not';
		if (setLastSub) {
			storeDate = 'store';
		}
       	var setmonthsubs_url = '/trip/set_month_subs.php';
        $.post(setmonthsubs_url,{  
       		userId: wtrTrip.userId,
       		monthSubs: monthSubs,
       		storeDate: storeDate
     	}, function(response) { 
 		});   
	}
	
	function dateInCurrentMonth(lastSub) {
  		var currentDate = new Date();
  		var month = currentDate.getMonth() + 1;
  		var lastMonth = lastSub.substr(3,2);
  		var inCurrentMonth = true;
  		if (month != lastMonth) {
  			inCurrentMonth = false;
		}
		return inCurrentMonth;
	}
	
	function switchToSubmittedMode() {
		// Toggle and disable onclick s
//		$("#last-save a").toggleClass("nolink", true);
//		$("#persist-save a").toggleClass("nolink", true);
//		$("#persist-generate a").toggleClass("nolink", true);
		$("#last-save").html('Last');
		$("#persist-save").html('Save');
		$("#persist-generate").html('Generate');
		
		$(".outer_new_place").hide();
	}
    
    function createPlace() {
		var base = $("[name=departurePlace]").val();
		var country = $("[name=departureCountry] option:selected").text();
		if (base == 'Select Value' || country == 'Select Value' || base == 'NULL') {
			alert("To 'add' select a place!");
   			// Tidy up display for re-entry
        	resetDnD();
			selectCountryOption(country);
        	requestPlacesForCountryChange('departure');
			$( "#locDate" ).datepicker( "option", "defaultDate", date );
			$("[name=departureCountry]").focus();
			$('#hidden-date').hide();
			$('#date-cover').show();
			return false;
		}
        var baseDate = $("[name=locDate]").val(); 
        if (baseDate == '') {
        	baseDate = 'none';
		}
	
		var userquery_url = '/trip/user_query.php';
		$.post(userquery_url,{  
			username: username
		}, function(user) {
			// Get user account status 
			type = $("type", user).text();
			// Get the limit to apply
			var limit = 11;
			if (type == 'p' || type == 'f') {
				limit = 101;
			}
			// Get current size
			var locations = getTripSize($('#place_list').tableDnDSerialize());
			// Warn if current add will leave no further locations to add
			if (limit - locations == 1) {
				warnUpgrade(type, 'add');
			}
			// Deny if no further locations to add
			else if (limit - locations < 1) {
				if(!denyUpgrade(type, 'add')) {
					return false;
				}
			}
				
	        var getnewbase_url = '/trip/get_new_base.php';
	        $.post(getnewbase_url,{  
	       		base: base,
	       		country: country,
	       		baseDate: baseDate
	       		  
	     	}, function(xml) {  
	       		baseResponse = xml;  
	       		mapper.add_to(baseResponse);
	       		wtrTrip.add_new(baseResponse); // Add to trip for save reference
	        	$('#journey')[0].reset();
				changeAlteredState(true);
				createPlaceSuccess();
	 		});   
 		});
    }
    
    function createPlaceSuccess ( ){
    	// fill entry list
    	$("place",baseResponse).each(function(i) {  
  			place = $("place",baseResponse).get(i);  
   			name = $("name", place).text();

   			country = $("country", place).text();
   			date = $("date", place).text();
   			locType = 's'; // default to sight on creation
   			medType = 'a'; // default to air on creation
   			placeId = $("time", baseResponse).text();
   			appendPlaceRow(placeId);
   			
   			// Tidy up display for next entry
        	resetDnD();
			selectCountryOption(country);
        	requestPlacesForCountryChange('departure');
			$( "#locDate" ).datepicker( "option", "defaultDate", date );
			$("[name=departureCountry]").focus();
			$('#hidden-date').hide();
			$('#date-cover').show();
		}); 
    }
    
    function selectCountryOption(country){
		$("[name=departureCountry]").each(
			function()
			{
				// get options
				var ops = this.options;
				for(var i = 0; i< ops.length; i++)
				{
					if(ops[i].text == country)
					{
						ops[i].selected = true;
					}
				}
			}
		);
		return this;
	};

    function deletePlace(placeId, ref){
    	// remove from list here
    	if (confirm("Delete "+ref+"?")) {
    		domid = "#row"+placeId;
    		$(domid).remove();
    		mapper.remove_from(placeId);
			changeAlteredState(true);
    	}
    	return false;
    }
    
    function panTo(placeId) {
    	mapper.pan_to(placeId);
    }
    
    function alertLogin() {
		var theusername = $("[name=username]").val();
		var password = $("[name=password]").val();

        var loginsubmit_url = '/trip/login_submit2.php';
        $.post(loginsubmit_url,{  
       		username: theusername,
       		password: password      		  
     	}, function(response) {
     		if (response.indexOf('ok') != -1) {
				username = theusername;
	     		if (action == 'savetrip') {
					llSaveTrip();
				}
				$('.close-overlay').click();
				showLoggedInState();
				selectLinks();
				selectMains();
 			}
 			else {
 				$('#login-error').html(response);
 				$('#login-error').show();  
			}
 		});   
    }

    function alertRegister() {
		var theusername = $("[name=reg_username]").val();
		var pass = $("[name=reg_pass]").val();
		var pass2 = $("[name=reg_pass2]").val();
		var email = $("[name=reg_email]").val();
		var email2 = $("[name=reg_email2]").val();

        var registersubmit_url = '/trip/register_submit.php';
        $.post(registersubmit_url,{  
       		username: theusername,
       		pass: pass,    		  
       		pass2: pass2,      		  
       		email: email,    		  
       		email2: email2      		  
     	}, function(response) {  
     		if (response.indexOf('ok') != -1) {
				username = theusername;
	     		if (action == 'savetrip') {
					llSaveTrip();
				}
				$('.close-overlay').click();
				showLoggedInState();
				selectLinks();
				selectMains();
 			}
 			else {
 				$('#reg-error').html(response);
 				$('#reg-error').show();  
			}
 		});   
    }

    function sendContactEmail() {
		var email = $("[name=email]").val();
		var name = $("[name=name]").val();
		var type = $("[name=type]").val();
		var message = $("[name=message]").val();

        var sendecontactemail_url = '/help/send_contact_email.php';
        $.post(sendecontactemail_url,{  
       		email: email,
       		name: name,    		  
       		type: type,      		  
       		message: message    		  
     	}, function(user) {
			document.location="/trip/home.php";
		}); 
		
    }
   
    function logInOut() {
    	if (isLoggedIn()) {
			// If we have the go ahead to alter
			if (isOkToAlter()) {
		        var logout_url = '/trip/logout2.php';
		        $.post(logout_url,{  
		     	}, function() { 
		     		newTrip();
		 		});
	 		}
 		} 
	 	else {
	 		showLoginOverlay();
	 	}      
    }
    
    function newTrip() {
		if (isOkToAlter()) {
    		document.location="/trip/trip.php";
		}
    	return;
    }
    
    function lastSave() { 
    	if (alteredState == true) {
    		document.location="/trip/trip.php?tripId="+wtrTrip.tripId;
    	}
    }
    
    function gotoMyTrips() {
    	// If not logged in return as we have no business here
    	if (!isLoggedIn()) {
    		return false;
    	}
		// If we have the go ahead to alter
		if (isOkToAlter()) {
    		document.location="/trip/myTrips.php";
		}
    }
    
    function isOkToAlter() {
    	var alterNow = false;
    	if (alteredState == true) {
	    	if (confirm("You have unsaved changes. Continue and lose?")) {
    			alterNow = true;
    			changeAlteredState(false);
	    	}
	    }
	    else {
    		alterNow = true;
		}
		return alterNow;
	}
	
	function isLoggedIn() {
		var loggedIn = false;
		username=getCookie('WTRID');
		if (username!=null && username!="") {
			loggedIn = true;
		}
		return loggedIn;
	}
	
	function showUpgradePanel() {
		if (isLoggedIn()) {
			var userquery_url = '/trip/user_query.php';
			$.post(userquery_url,{  
				username: username
			}, function(user) {
				// Get user account status 
				type = $("type", user).text();
				if (type == 'f') {
					$('#upgrade-panel').show();
				}
				else {
					$('#upgrade-panel').hide();
				}
			});
		}
		else {
			$('#upgrade-panel').hide();
		}
	}
	
	function changeAlteredState(newState) {
		alteredState = newState;
		var toggle = true;
		var notoggle = false;
		if (newState == true) {
			toggle = false;
			notoggle = true;
		}
		$("#last-save a").toggleClass("nolink", toggle);
		$("#persist-save a").toggleClass("nolink", toggle);
		$("#persist-generate a").toggleClass("nolink", notoggle);
	}
	
	function showLoggedInState() {
		if (isLoggedIn()) {
        	$('#user-name-span').html(username);	
        	$('#user-name-span').toggleClass("known", true);
			var userquery_url = '/trip/user_query.php';
			$.post(userquery_url,{  
				username: username
			}, function(user) {
				// Get user account status 
				type = $("type", user).text();
				var usertype = 'Free';
				if (type == 'p') {
					usertype = 'Pro';
					$('#user-type-span').toggleClass("known", true);
					$("#upgrade-link").html('membership');
				}
				$('#user-type-span').html(usertype);	
			});
        		
			$('.close-overlay').click();
			$("#admin-out a").html("Logout");
			$("#my-trips a").toggleClass("nolink", false);
		}
		else {
			$("#admin-out a").html("Login");
        	$('#user-name-span').toggleClass("unknown", true);	
        	$('#user-type-span').toggleClass("unknown", true);
			$("#my-trips a").toggleClass("nolink", true);
			$("#upgrade-link").html('membership');
		}
	}
	
    function changeFlickrUrl() {
		if (wtrTrip.creatorName != username) {
			alert ("navigation disabled");
			return false;
		}
    	action = 'changeflickr';
		// Ask for flickr url segment then callback promptCallback
		currentVal = wtrTrip.tripFlickr;
		if (wtrTrip.tripFlickrSet != '') {
			currentVal += '/sets/';
			currentVal += wtrTrip.tripFlickrSet;
		}
		IEprompt('Flickr URL segment', currentVal);
    }
    
    function changeYouTubeUrl() {
		if (wtrTrip.creatorName != username) {
			alert ("navigation disabled");
			return false;
		}
    	action = 'changeyoutube';
		// Ask for youtube url segment then callback promptCallback
		currentVal = wtrTrip.tripYouTube;
		IEprompt('YouTube URL segment', currentVal);
    }
    
	function promptCallback(val) {
		if (action == 'savetrip') {
			if (val == null || val == '') {saveTrip();}
			else {
				wtrTrip.name=val;
				$('#trip-name-span').html(wtrTrip.name);
		   		// Deal with user status
		   		saveOnLoggedIn();
			}
		}
		else if (action == 'changeflickr') {
			currentVal = wtrTrip.tripFlickr;
			if (wtrTrip.tripFlickrSet != '') {
				currentVal += '/sets/';
				currentVal += wtrTrip.tripFlickrSet;
			}
			if (val != currentVal) {
				saveFlickrUrl(val);
			}
		}
		else if (action == 'changeyoutube') {
			currentVal = wtrTrip.tripYouTube;
			if (val != currentVal) {
				saveYouTubeUrl(val);
			}
		}
		else if (action == 'getloc') {
			if (val == null || val == '') {getLocationName(val);}
			else {
				if (wtrTrip.containsLocationName(val)) {
					var d = new Date();
					randomnum = d.getTime();
					keepLocationName(val+randomnum);
				}
				else {
					keepLocationName(val);
				}
			}
		}
	}
	
	function saveFlickrUrl(flickrUrl) {
		if (flickrUrl==null) return;
       	var change_flickr_url = '/trip/change_flickr.php';
       	var flickr = "";
       	var flickrset = "";
		var splitResult = flickrUrl.split("/");
		if (splitResult.length == 1){
			flickr = splitResult[0];
    	}
		if (splitResult.length == 3){
			flickr = splitResult[0];
			flickrset = splitResult[2];
    	}
        $.post(change_flickr_url,{  
       		tripId: wtrTrip.tripId,
       		flickr: flickr,
       		flickrset : flickrset
     	}, function() { 
			flickrHtml = "<object height=\"330\" width=\"330\"><param value=\"offsite=true&amp;lang=en-us&amp;page_show_url=%2Fphotos%2F" + flickr + "%2Fshow%2F&amp;page_show_back_url=%2Fphotos%2F" + flickr + "%2F&amp;set_id=" + flickrset + "&amp;user_id=" + flickr + "&amp;jump_to=\" name=\"flashvars\"><param value=\"true\" name=\"allowFullScreen\">" +
				"<embed width=\"330\" height=\"330\" flashvars=\"offsite=true&amp;lang=en-us&amp;page_show_url=%2Fphotos%2F" + flickr + "%2Fshow%2F&amp;page_show_back_url=%2Fphotos%2F" + flickr + "%2F&amp;set_id=" + flickrset + "&amp;user_id=" + flickr + "&amp;jump_to=\" allowFullScreen=\"true\" src=\"http://www.flickr.com/apps/slideshow/show.swf?\" type=\"application/x-shockwave-flash\"></embed>" + 
				"</object>";
			$("#flickr-main").html(flickrHtml);
			wtrTrip.tripFlickr = flickr;
			wtrTrip.tripFlickrSet = flickrset;
			choosePersonal('flickr');
			selectMains();
 		});  	
	}
	
	function saveYouTubeUrl(youTubeUrl) {
		if (youTubeUrl==null) return;
       	var change_youtube_url = '/trip/change_youtube.php';
        $.post(change_youtube_url,{  
       		tripId: wtrTrip.tripId,
       		url: youTubeUrl
     	}, function() { 
			youTubeHtml = "<object height=\"330\" width=\"330\"><param value=\"http://www.youtube.com/" + youTubeUrl + "&amp;hl=en_GB&amp;fs=1\" name=\"movie\"><param value=\"true\" name=\"allowFullScreen\"><param value=\"always\" name=\"allowscriptaccess\">" +
				"<embed allowfullscreen=\"true\" allowscriptaccess=\"always\" height=\"330\" width=\"330\" type=\"application/x-shockwave-flash\" src=\"http://www.youtube.com/" + youTubeUrl + "&amp;hl=en_GB&amp;fs=1\"></embed>" +
				"</object>";
			$("#youtube-main").html(youTubeHtml);	
			wtrTrip.tripYouTube = youTubeUrl;
			choosePersonal('youtube');
			selectMains();
 		});  	
	}
	
	function fillTripList(tripLimit) {
    	// add generated
    	$(myTrips).find('trip').each(function(i) {  
    		trip = $(myTrips).find('trip').get(i); 
   			tripName = $("tripName", trip).text();
   			tripId = $("tripId", trip).text();
   			tripStatus = $("tripStatus", trip).text();
   			if (tripId != '' && tripStatus == 'g') {
   				appendTripRow();
				$("#trip_list tr:even").addClass('alt');
			}
		});  		
    	// add open
    	$(myTrips).find('trip').each(function(i) {  
    		trip = $(myTrips).find('trip').get(i); 
   			tripName = $("tripName", trip).text();
   			tripId = $("tripId", trip).text();
   			tripStatus = $("tripStatus", trip).text();
   			if (tripId != '' && tripStatus == 'o') {
   				appendTripRow();
				$("#trip_list tr:even").addClass('alt');
			}
		});  		
    	// add submitted
    	$(myTrips).find('trip').each(function(i) {  
    		trip = $(myTrips).find('trip').get(i); 
   			tripName = $("tripName", trip).text();
   			tripId = $("tripId", trip).text();
   			tripStatus = $("tripStatus", trip).text();
   			if (tripId != '' && tripStatus == 's') {
   				appendTripRow();
				$("#trip_list tr:even").addClass('alt');
			}
		});  		
	}
	
	function appendTripRow() {
		entry = "<tr id=\"row" + tripId + "\">"+
				"<td style='width:300px;'>"+tripName+"</td>";
				
		if (tripStatus == "s") {
			entry += "<td width:150px;'>";
			entry += "Page Generated";
		}
		else if (tripStatus == "o") {
			entry += "<td width:150px;'>";
			entry += "Work In Progress";
		}
		else if (tripStatus == "g") {
			entry += "<td style='color:#b000b0';width:150px;'>";
			entry += "Tour and Page Generated";
		}
		entry += "</td>"; 

		if (tripStatus == "o") {
			entry += "<td style='width:150px;' class='edit_button' onmouseover=\"this.style.cursor = 'pointer';\" title='Edit "+tripName+" itinerary'>";
			entry += "<a class='' href='#' onclick='editTrip("+tripId+")'>Edit Itinerary Page</a>";
		}
		else if (tripStatus == "s") {
			entry += "<td style='width:150px;' class='edit_button' onmouseover=\"this.style.cursor = 'pointer';\" title='Show generated page for "+tripName+"'>";
			entry += "<a class='' href='#' onclick='showTrip("+tripId+")'>Show Generated Page</a>";
		}
		else if (tripStatus == "g") {
			entry += "<td style='width:150px;' class='edit_button' onmouseover=\"this.style.cursor = 'pointer';\" title='Show generated page for "+tripName+"'>";
			entry += "<a class='' href='#' onclick='showTrip("+tripId+")'>Show Generated Page</a>";
		} 
		entry += "</td>"; 
	
		if (tripStatus == "g") {
			entry += "<td style='width:150px;' class='view_button' onmouseover=\"this.style.cursor = 'pointer';\" title='Launch "+tripName+" tour'>";
			entry += "<a class='' style='color:#b000b0;font-style:italic;' href='#' onclick='viewTrip("+tripId+")'>Launch Tour</a>";
            entry += "</td>";
		}
		else if (tripStatus == "o") {
			entry += "<td style='width:150px;'>&nbsp;</td>";
		}
		else {
			entry += "<td style='width:150px;'>&nbsp;</td>";
		}
		
		entry += "<td style='width:50px;' class='delete_button' onmouseover=\"this.style.cursor = 'pointer';\" title='Delete "+tripName+"'>";
		entry += "<a class='' href='#' onclick='deleteTrip("+tripId+")'>Delete</a>";
		entry += "</td>";

		entry += "</tr>";
        $("#trip_list tbody").append(entry);	
	}

	function editTrip(tripId) {
		document.location='/trip/trip.php?tripId='+tripId;
	}
	function showTrip(tripId) {
		document.location='/trip/generatedTrip.php?tripId='+tripId;
	}
	function viewTrip(tripId) {
		if (wtrTrip.tripStatus == 'g') {
			document.location='/trip/archive/trip'+tripId+'.kml';
	       	var gearthtrip_url = '/trip/gearth_trip.php';
	        $.post(gearthtrip_url,{  
	       		tripId: tripId        		  
	     	}); 
		}
		else {
			alert("Sorry your trip tour has not been generated yet. But you can still add articles to your trip below.");
		}
	}
	
	function deleteTrip(tripId) {
    	// remove from db
    	if (confirm("Delete trip?")) {
	       	var deletetrip_url = '/trip/del_trip.php';
	        $.post(deletetrip_url,{  
	       		tripId: tripId        		  
	     	}, function() { 
	    		domid = "#row"+tripId;
	    		$(domid).remove();
	 		});   
    	}
	}
	   
    function anotherTrip() {
    	document.location="/trip/trip.php";
    	return;
    }
    
    function helpSelect(page) {
    	if (page == 'flickr') {
    		document.location="/help/usingFlickr.html";
   		}
   		else if (page == 'youtube') {
    		document.location="/help/usingYouTube.html";
   		}
   		else if (page == 'gearth') {
    		document.location="/help/viewingTrip.html";
   		}
   		else if (page == 'trip-create') {
    		document.location="/help/tripCreation.html";
   		}
   		
    	return;
    }
    
    function helpView() {
    	document.location="/help/viewingTrip.html";
    	return;
    }
    
   	function showItinerary(decide) {
   		if (decide) {
			$('#no-itinerary').hide();
			$('#itinerary').show();
		}
		else {
			$('#no-itinerary').show();
			$('#itinerary').hide();
		}
	}

    function newRequestPlacesForCountryChange(formFieldRoot, tripId) {
		if ( tripId === undefined ) {
		   tripId = '-1';
		}
	    var countrySelection = $("[name=departureCountry]").val();
		var placesSelectorUrl = '/trip/places_selector.php';
	    if (countrySelection == 'NULL') {
	        $("[name=departureCountry]").focus();
	    }
		else if (countrySelection == 'ZZZ') {
	        $.post(placesSelectorUrl,{  
	       		country: countrySelection,
	       		formFieldRoot: 'departure',
	       		tripId: tripId        		  
	     	}, function(data) { 
			    placesFormField = 'departurePlace';
			    if (type != 'error') {
			        $("#departurePlace").html(data);
	        		$("[name=departurePlace]").focus();
			    }
	 		});   
		}
		else {
	        $.post(placesSelectorUrl,{  
	       		country: countrySelection,
	       		formFieldRoot: 'departure'        		  
	     	}, function(data) { 
			    placesFormField = 'departurePlace';
			    if (type != 'error') {
			        $("#departurePlace").html(data);
	        		$("[name=departurePlace]").focus();
			    }
	 		});   
		}
	}

    
	
