jQuery( function($) {
	var $busy = jQuery('#busy');
	$busy.fadeOut('slow');
	$busy.ajaxStart(function() {$(this).fadeIn('slow');});
	$busy.ajaxStop(function() {$(this).fadeOut('slow');}); 
	
	$( window ).bind( 'hashchange', function(e) { 
		var href = e.getState();
		var param = [];
		for(i in href) if (href.hasOwnProperty(i))
		{
		    param.push(i);
		};
		type = param[0];
		if ( type == null ){
			return true;
		};
		switch (type) {
			case 'destination':
//				var id = href.destination;
//				var key = 'destination_' + id;
				Action.getDestination( href.destination );
			 break;
			case 'edit':
				Action.getEditDestination( href.edit );
			 break;
			case 'tour':
				var id = href.tour;
				var key = 'tour_' + id;
				if ( Action.cache[ key ] ){
					$('#tripmain').html( Action.cache[ key ] );
				} else {
					Action.getTourItin( id );
				};
			 break;
			case 'tourmap':
				Action.getTourMap( href.tourmap );
			 break;
			default:
				Action.getIndex();
			 break;
		};
		return false;
	 }); 
	$(window).trigger( 'hashchange' );
	$('a.history').live('click', function(e) {
		var href = $(this).attr('href').split('_');
		var type = href[0].replace( /^#/, '' );
		var id = href[1];
 		var state = {};
		state[ type ] = id;
		$.bbq.pushState( state, 2 );
	});
	$('div#profile-controls input[type=submit]').live('click', function(e) {
		var href = $(this).attr('href').split('_');
		var type = href[0].replace( /^#/, '' );
		var id = href[1];
 		var state = {};
		state[ type ] = id;
		$.bbq.pushState( state, 2 );
	});
	
//	Triplite.setupSamples();
//	if ($puzzle = jQuery('#puzzler')) {
//		$puzzle.attr('style', 'display: inherit;');
//	};
})
var Setup = {
	init: function(){
		Utility.galleryInit();
		Tour.init();
		Utility.tourSearchInit();
		Utility.countryInfoInit();
		Utility.searchResultsInit();
		Sundry.componentWidget();
		Mapping.connectionsLive();
		Mapping.localSearchLive();
		Triplite.addToTourSetUp();
		Triplite.startUp();
		Mapping.climateLive();
		jQuery('div#profile input[name^=Region]').live('click', function(e) {
			var element = $(this);
			if (element.attr('checked') == true ) {
				element.parents('ul').find('input').attr('checked', true ) ;
			} else {
				element.parents('ul').find('input').attr('checked', false ) ;
			}
		});
		jQuery('a#show-viewpoint').live('click', function(e) {
			var viewpoint = $('ul#viewpointer-radio input[name=viewpoint]:checked').attr('value')
			$('#upper_map').addClass('hidden');
			$('#lower_map').addClass('hidden');
			$('#local-results').html('Loading ...');
			$('#search-results').removeClass('hidden');
			Action.getViewpoint( viewpoint );
			return false;
		});
		jQuery('div#benefits a.register').live('click', function(e) {
			Action.newUser();
			return false;
		});
		jQuery('div#profile a.end').live('click', function(e) {
			Action.getIndex();
			$('div#profile-results').remove();
			return false;
		});
		jQuery('div#option-items ul#sortable-triplite-items input').live('click', function(e) {
			var id = $(this).parents('li').attr('id').replace(/[^0-9]/g, "");
			var destination_id = $(this).attr('id').replace(/[^0-9]/g, "");
			if ( $('#tourpad').attr('id') == 'tourpad' ) {
				Triplite.addTourpad( id );
			} else {
				if ( destination_id ) {
					var type = 'destination';
			 		var state = {};
					state[ type ] = destination_id;
					$.bbq.pushState( state, 2 );
				} else {
					Utility.flash("Please, use Travel Routes Wizard" );
				}
			}
			return false;
		});
		jQuery('div#home-menu input.Map').live('click', function(e) {
			var id = $( this ).attr('id').replace(/[^0-9]/g, "")
			Action.getTourMap(id);
			return false;
		});
		jQuery('ul#viewpointer-radio input').live('click', function(e) {
			var button = $( this ).index( 'ul#viewpointer-radio input' );
			$( 'div#viewpointer div.viewpoint, div#viewpointer img.vp-view' ).hide();
			$( 'div#viewpointer div.viewpoint' ).eq( button ).show();
			$( 'div#viewpointer img.vp-view' ).eq( button ).show();
		});
		jQuery('div#option-items span#radio-list input').live('click', function(e) {
			Triplite.getBasket( $(this).val() );
			return false;
		});
		jQuery('input#qsearch_submit, input#search_submit').live('click', function(e) {
			$('#local-results').html('Loading ...');
			$('#search-results').removeClass('hidden');
			$('#upper_map').addClass('hidden');
			$('#lower_map').addClass('hidden');
		});
		jQuery('.type-bar li, p.type-bar').live('mouseover', function(e) {
			$(this).find( 'span.buttontip' ).show() ;
		} );
		jQuery('.type-bar li, p.type-bar').live('mouseout', function(e) {
			$(this).find( 'span.buttontip' ).hide() ;
		} );
		jQuery('.checkbox-bar input').live('click', function(e) {
			$(e.target).toggleClass( 'selected' ) ;
			return false;
		} );
		jQuery('a.close-editor').live('click', function(e) {
			$(this).parents().find('.close').remove() ;
			return false;
		} );
		jQuery('div#tour-editor input[type=submit]').live('click', function(e) {
			$('div#tour-editor form').remove() ;
		} );
		jQuery('#colorbox input[type=submit]').live('click', function(e) {
			$.fn.colorbox.close() ;
		} );
		jQuery('.facelist-selection-item').live('click', function(e) { 
			id = $(this).siblings(':last').children(':last').attr('value');
		} );
		jQuery("a[rel='search-gallery']").colorbox({transition:"fade"});
		$('#country-tour-index').live( 'mouseover', function(){
			$(this).css({ 'z-index': '50000' });
		});
		$('#country-tour-index').live( 'mouseout', function(){
			$(this).css({ 'z-index': '1' });
		});
		$('div#breadcrumbs a, div#sidemenu div.map a').live('click', function(e){
			element = $( this );
			var id = element.attr('href').replace(/-.*$/, "").replace(/[^0-9]/g, "");
			if ( id == ""){
				return  true;
			};
	 		var state = {};
			state[ 'destination' ] = id;
			$.bbq.pushState( state, 2 );
			return false;
		});
		$('div#fliptour a' ).live('click', function(e){
			var id = $( this ).attr('id').replace(/[^0-9]/g, "");
			Action.fetchSupplier( id );
		});
		$('input.Commentary, div#pageflip a.commentary').live('click', function(e){
			var identity = $( this ).attr('id');
			var type = identity.replace(/[_0-9]/g, "");
			var id = identity.replace(/[^0-9]/g, "");
			Action.fetchComments(type, id);
		});
		$('div#pageflip a.malaria').live('click', function(e){
			alert('woof');
			var id = $( this ).attr('id').replace(/[^0-9]/g, "");
			$.ajax({
				type: 'GET',
				url: '/destinations/' + id,
				data: 'focus=' + 'malaria'
			});
		});
		$('div#destination-map-control li input.marker').live('click', function(e){
			var element = $(this);
			var type = element.attr('component');
			if (element.hasClass('selected')) {
				Destination.hideType(type);
				element.removeClass('selected');
			}
			else {
				Destination.showType(type);
				element.addClass('selected');
			};
		});
		Search.autoSuggestLive();
		jQuery("#map-display a").live('click', function(e){
			return false;
		});
		$('#map-query').live('click', function(e){
			Mapping.localSearch();
		});
		$('ul#destination-child-items input:checkbox').live('click', function(e){
			element = $( this );
			var id = element.attr('value');
			if (element.attr('checked') == false) { //checkbox is checked when function returns
				Mapping.unmapMarker(id);
			}
			else {
				Mapping.mapMarker( id );
			};
		});
		$('ul#destination-child-items li a.show').live('click', function(e){
			element = $( this );
			var tmp = $(this).attr('href').split('-');
			var id = tmp[0].replace(/[^0-9]/g, "");
			var type = 'destination';
	 		var state = {};
			state[ type ] = id;
			$.bbq.pushState( state, 2 );
			return false;
		});
		$('div#destination-tours li a.show').live('click', function(e){
			element = $( this );
			var id = element.attr('id').replace(/[^0-9]/g, "");
			var type = 'tour';
	 		var state = {};
			state[ type ] = id;
			$.bbq.pushState( state, 2 );
			return false;
		});
		$('div#destination-tours li a.showmap').live('click', function(e){
			element = $( this );
			var id = element.attr('id').replace(/[^0-9]/g, "");
			var type = 'tourmap';
	 		var state = {};
			state[ type ] = id;
			$.bbq.pushState( state, 2 );
			return false;
		});
		$('input#map-bound').live('click', function(e){
//			alert('woof');
			Mapping.boundMarkers();
		});
		$('input#map-ruler').live('click', function(e){
			Mapping.addRuler();
		});
		$('input#map-clear').live('click', function(e){
			Mapping.clearMarkers();
			Mapping.clearPolylines();
//			Mapping.clearResults();
			Mapping.clearCircles();
			Mapping.clearWaypoints();
			Mapping.clearDirections();
			Mapping.infoWindow = null;
			Mapping.lastMarker = null
			$('#destination-nav input:checkbox').attr('checked', false );
			$('#map_canvas span').remove();
		});
		$('input#map-hide').live('click', function(e){
			$.each( Mapping.markers, function(){
				this.setMap( null );
			});
			$.each( Mapping.circle, function(){
				this.setMap( null );
			});
			$.each( Mapping.polylines, function(){
				this.setMap( null );
			});
			$.each( Mapping.directionsDisplay, function(){
				this.setMap( null );
			});
			Mapping.clearWaypoints();
			$('#map_canvas span').hide();
			var localResults = "#" + Mapping.localResultsDiv;
			$(localResults).html("");
			$('div#tour-map-control input.marker').removeClass('selected');
			$('div#destination-map-control input.marker').removeClass('selected');
			$('ul#destination-child-items input[type=checkbox]').removeAttr('checked');
		});
		$('input#map-showall').live('click', function(e){
			$.each( Mapping.markers, function(){
				this.setMap( Mapping.map );
			});
			$.each( Mapping.polylines, function(){
				this.setMap( Mapping.map );
			});
			$.each( Mapping.directionsDisplay, function(){
				this.setMap( Mapping.map );
			});
			$('#map_canvas span').show();
			$('div#tour-map-control input.marker').addClass('selected');
		});		
		Form.loginSetup();
		Action.destinationInit();
		Search.similarDestinationLive();
		Sundry.initAssetImages();
		Picker.init();
//		alert('set');
	},
	adminInit: function(){
		$('ul#destination-child-items li.label a:first').live('click', function(e){
			var id = $(this).attr('href').replace(/[^0-9]/g, "");
			var type = 'edit';
	 		var state = {};
			state[ type ] = id;
			$.bbq.pushState( state, 2 );
			return false;
		});
		$('input#map-save-flag').live('click', function(e){
			$(e.target).toggleClass( 'selected' ) ;
		});
		$('#map-polyline').live('click', function(e){
			var mode = $('div#map-control ul.type-bar input.selected').attr('component');
			if ( Mapping.previousMarker == null || Mapping.lastMarker == null || mode == null ){
				Utility.flash("Connections require 2 ends & mode");
			} else {
				var idA = Mapping.previousMarker.subject_id;
				var idB = Mapping.lastMarker.subject_id;
				var index = idA + '_' + idB + '_' + mode;
				var directions_mode = 'standard';
				Mapping.addPolyLine( Mapping.previousMarker.position, Mapping.lastMarker.position, mode, index);
				if ($('input#map-save-flag').hasClass('selected')) {
					Connection.newConnexion(idA, idB, mode, directions_mode);
				};
			};
		});
		$('input#map-directions').live('click', function(e){
			var mode = $('div#map-control ul.type-bar input.selected').attr('component');
			if ( Mapping.previousMarker == null || Mapping.lastMarker == null ){
				Utility.flash("Directions require 2 ends");
			} else if ( mode != 'Walk' && mode != 'Drive' ) {
				Utility.flash("Drive/walk only for Directions");
			} else {
				var directionsMode = ( mode == 'Walk' ) ? "WALKING" : "DRIVING"
				var positionA = Mapping.previousMarker.position;
				var positionB = Mapping.lastMarker.position;
				var idA = Mapping.previousMarker.subject_id;
				var idB = Mapping.lastMarker.subject_id;
				var index = idA + '_' + idB + '_' + mode;
				Mapping.editDirectionsDisplay.suppressMarkers = false;
				Mapping.getDirections( positionA, positionB, Mapping.editDirectionsDisplay, idA, idB, mode, directionsMode );	
			};			
		});
		$('fieldset#map-tour-index input.Compass').live('click', function(e){
			if ( Mapping.waypoints.length > 0){
				var identity = $( this ).attr('id');
				var id = identity.replace(/[^0-9]/g, "");
				var type = identity.replace( /[0-9_]/g, "" );
				Mapping.updatePosition( type, id );
			} else {
				Utility.flash("Set waypoint first");
			};
		});
		$('div#map-div input#way-pointer').live('click', function(e){
			$(e.target).toggleClass( 'selected' ) ;
			if ( $( this ).hasClass('selected')  ) {
				Mapping.setWaypoint();
			} else {
				Mapping.unsetWaypoint();
			};
		});		
		$('ul#destination-child-items a.mapper').live('click', function(e){
			var id = $(this).attr('destination');
			if ( Mapping.waypoints[0]) {
				Mapping.updatePosition("Destination", id);
			} else { Utility.flash("No Waypoint") };
			return false;
		});		
		$('#supplier_id').live('change', function(){
			var id = $(this).find('option:selected').val();
			UI.getFacets( id, "Supplier");
			UI.getSupplierTours( id );
		});
		$('#tour_id').live('change', function(){
			var id = $(this).find('option:selected').val();
			UI.getDepartures( id );
		});		
		jQuery('a#new-shortcut').live('click', function(e) {
			destination = $('select#destination-shortcut').find( 'option:selected').attr('value');
			target = $('div#shortcut-control').attr('value');
			Utility.newShortcut( destination, target );
			return false;
		} );
		jQuery('div#shortcut-control a.delete-shortcut').live('click', function(e) {
			element = $( this ) ;
			id = element.attr('id').replace(/[^0-9]/g, "");
			Utility.deleteShortcut( id, element );
			return false;
		} );
		jQuery('#destination_sub_type').live('change', function(e){
			subType = $(this).find('option:selected').attr('value');
			Utility.subTypeAction(subType);
			return false;
		});
		jQuery('#destination_parent_id').live('change', function(e){
			type = $('#destination_destination_type').find('option:selected').attr('value');
			subType = $('#destination_sub_type').find('option:selected').attr('value');
			parent = Number($('#destination_parent_id').find('option:selected').attr('value'));
			Utility.updateCountry(subType, parent);
			if (type == 'attraction' || type == 'airport' || type == 'carhire') {
				Utility.updateShortcut(parent);
			};
			return false;
		});
		Action.countryEditLive();
		Mapping.pickerLive();
		Accounts.live();
		Picker.adminInit();
	}
}
var Plot = {
	xticks: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec' ],
	yticks: [0, 5, 10, 15, 20, 25, 30, 35, 40, 45],
	y2ticks: [0, 50, 100, 200],
	countryClimate: null,
	climateData: [],
	maxTempMonth: [],
	minTempMonth: [],
	maxPrecipitationMonth: [],
	maxHumidityMonth: [],
	loadClimates: function( climateData ){
		Plot.climateData = JSON.parse(climateData);
		var firstClimate = $('div#destination-nav li');
		var firstClimatePoint = firstClimate.find( 'input:first').attr('id').replace(/[^0-9]/g, "");
		var lat = firstClimate.find( 'span:first').attr('lat');
		var lng = firstClimate.find( 'span:first').attr('lng');
		if (firstClimatePoint) {
			Plot.plotClimate( firstClimatePoint, lat, lng );
		};
	},
	plotClimate: function( station, lat,lng ){
		$('div#chart-div').html("")
		var minTemp = Plot.climateData[ station ]['min_temp'].split(',');
		$.each( minTemp, function( key, value ){
			minTemp[ key ] = Number( value );
		});
		var deltaTemp = Plot.climateData[ station ]['delta_temp'].split(',');
		$.each( deltaTemp, function( key, value ){
			deltaTemp[ key ] = Number( value );
		});
		var precipitation = Plot.climateData[ station ]['precipitation'].split(',');
		var humidity = Plot.climateData[ station ]['humidity'] ? Plot.climateData[ station ]['humidity'].split(',') : " , , , , , , , , , , , ".split(',');
		var precipitation_days = Plot.climateData[ station ]['precipitation_days'].split(',');
		temperatures = $.jqplot('chart-div', [ minTemp,
											   deltaTemp, 
											   precipitation ], {
    	stackSeries: true,
	    seriesDefaults: {
	        renderer: $.jqplot.BarRenderer,
	        rendererOptions:{ barWidth: 8, shadow: false, barPadding: 0}
	    },
	  	series:[ 

				{ 
					disableStack: true,
					rendererOptions: {color: 'white'}, 
					yaxis:'yaxis',
					label: 'Min Temp', 
					pointLabels:{ labels: false }
				}, 
				{ 	
					disableStack: false,
					rendererOptions: {shadow: true, color: '#FFCC00'},
//		            shadowAngle:0, 
//		            shadowOffset:1.5, 
//		            shadowAlpha:.08, 
//		            shadowDepth:6,
					yaxis:'yaxis',
					label: 'Max Temp', 
					pointLabels:{ labels: humidity }
				},
				{ 	
					disableStack: true,
	        		renderer: $.jqplot.LineRenderer,
		            lineWidth:.5, 
					fill:true, 
    				fillToZero: true,
		            fillAlpha:.38, 
					showMarker:false, 
					color: '#99FFFF',
					yaxis:'y2axis',
					rendererOptions: { shadow: false }, 
					pointLabels:{ labels: precipitation_days }
				}

			],
	  	axesDefaults: {
    	  useSeriesColor: false,
	      tickRenderer: $.jqplot.CanvasAxisTickRenderer ,
	      tickOptions: {
	        angle: -45,
	        fontSize: '.8em'
	      }
	  	},
	  	axes: {
	    	xaxis: {
				ticks: Plot.xticks,
	      		renderer: $.jqplot.CategoryAxisRenderer
	    	},
	    	yaxis: {
	      		ticks: Plot.yticks,
			      tickOptions: {
			        angle: 0,
					formatString:'%.0f'
			      }
	    	},
	    	y2axis: {
	      		ticks: Plot.y2ticks,
			      tickOptions: {
			        angle: 0,
					formatString:'%.0f'
			      }
	    	}
		  }
		});
		Plot.adjustClimate( station, lat,lng);
	},	
	adjustClimate: function( station,lat,lng){
		$('div#chart-div div.jqplot-point-label:gt(11)').css({
			'background-color': '#CCFFFF',
			'border': '.5px solid #3366FF',
			'color': 'blue',
			'top': '20.5em'
		} );
		$('span#maxTempMonth').text( Utility.monthName[ Number( Plot.climateData[ station ][ 'max_temp_month' ]) ]);
		$('span#minTempMonth').text( Utility.monthName[ Number( Plot.climateData[ station ][ 'min_temp_month' ]) ]);
		$('span#maxRainMonth').text( Utility.monthName[ Number( Plot.climateData[ station ][ 'max_precipitation_month' ]) ]);
		$('span#maxHumidityMonth').text( Utility.monthName[ Number( Plot.climateData[ station ][ 'max_humidity_month' ]) ] );
		$('ul#chart-key li.climate-title span.title').text( Plot.climateData[ station ][ 'name' ] );
		Google.weather( Plot.climateData[ station ][ 'name' ], lat, lng );
	} 
}
var Utility = {
	monthName: ['January','February','March','April','May','June','July','August','September','October','November','December', '[not set]' ],
	makeCentrigrade: function( F ){
		return ( (F - 32) * 5 / 8 ).toFixed(0); 
	},
	pageTitle: function( title ){
		document.title = title + " | Wildlife Safari Sports Holidays &amp; Tours | TripScape by Detour UK";
	},
	pagePeel: function(){
		$("#pageflip").hover(function() { //On hover...
			$("#pageflip img , .msg_block").stop()
				.animate({ //Animate and expand the image and the msg_block (Width + height)
					width: '200px',
					height: '200px'
				}, 500);
			} , function() {
			$("#pageflip img").stop() //On hover out, go back to original size 50x52
				.animate({
					width: '50px',
					height: '52px'
				}, 220);
			$(".msg_block").stop() //On hover out, go back to original size 50x50
				.animate({
					width: '50px',
					height: '50px'
				}, 200); //Note this one retracts a bit faster (to prevent glitching in IE)
		});		
	},
	inspect: function(){
		ret = prompt("Enter object", "document");
		obj = eval(ret);
		var temp = "";
		for (x in obj) 
			temp += x + ": " + obj[x] + "\n";
		alert(temp);
	},
	tabSelect: function(tab, div){
		selected = 'div#' + div;
		jQuery('div#options-tabs li').removeClass('ui-tabs-selected').removeClass('ui-state-active');
		jQuery('div#options-tabs li').eq( tab ).addClass('ui-tabs-selected').addClass('ui-state-active');
		jQuery('div#options-tabs > div').addClass('ui-tabs-hide');
		jQuery(selected).removeClass('ui-tabs-hide');
	},
	tabSelectMatch: function(tab, div){
		selected = 'div#' + div;
		jQuery('div#profile-results li').removeClass('ui-tabs-selected').removeClass('ui-state-active');
		jQuery('div#profile-results li').eq( tab ).addClass('ui-tabs-selected').addClass('ui-state-active');
		jQuery('div#profile-results > div').addClass('ui-tabs-hide');
		jQuery( selected ).removeClass('ui-tabs-hide');
	},
	tourSearchInit: function(){
		jQuery('#tour-search').live('click', function(e){
			element = $(this)
			search = jQuery('#tour-searchbox').attr('value');
			id = element.attr('country');
			$.ajax({
				type: 'GET',
				url: '/destinations/' + id,
				data: 'focus=tours&search=' + search
			});
			return false;
		});
		return false;
	},
	countryInfoInit: function(){
		jQuery('#country-footer li').live('click', function(e){
			var element = $(this)
			var radio = element.find('input:radio');
			var id = element.attr('id').replace(/[^0-9]/g, "");
			var focus = radio.attr('value');
			if (focus == 'commentary') {
				$.ajax({
					type: 'GET',
					url: '/utility/commentary/' + id + '?type=Destination'
				});
			}
			else {
				$.ajax({
					type: 'GET',
					url: '/destinations/' + id,
					data: 'focus=' + focus
				});
			}
			radio.attr('checked', true);
		});
	},
	searchResultsInit: function(){
		jQuery('#quick-search-display .search-admin').live('click', function(e){
			$(e.target).find('span').show();
			return false;
		});
		jQuery('#quick-search-display .search-admin').live('dblclick', function(e){
			$(e.target).find('span').hide();
			return false;
		});
		jQuery('#quick-search-display p').live('mouseenter', function(e){
			var description = $(e.target).parents('.search-admin').find('div.description');
			if ( description.text() != "" ) {
				description.stop().show();
			};
		});
		jQuery('#quick-search-display p').live('mouseleave', function(e){
			var description = $(e.target).parents('.search-admin').find('div.description');
			description.stop().hide();
		});
		jQuery('#quick-search-display .search-admin').live('mouseout', function(e){
			$(e.target).find('div.description').hide();
			return false;
		});
	},
	galleryInit: function(){
		jQuery("#tripmain .gallery a").colorbox({
			transition: "fade"
		});
	},
	linkEditInit: function(){
		var links = jQuery("#map-display a");
		links.draggable({
			stop: function(event, ui){
				id = $(this).attr('link');
				Utility.updateLinkPosition(id, ui.position.left, ui.position.top);
			}
		});
	},
	updateLinkPosition: function(id, X, Y){
		$.ajax({
			type: 'POST',
			url: '/maplinks/move_link',
			data: 'id=' + id + '&X=' + X + '&Y=' + Y
		});
		
	},
	destinationEditInit: function( supplierId ){
		Utility.hideDestinationOptions();
		type = $('#destination_destination_type').find('option:selected').attr('value');
		subType = $('#destination_sub_type').find('option:selected').attr('value');
		if ( type == 'location' || type == 'attraction' || type == 'airport' ) {
			Utility.showDestinationOptions(subType, supplierId);
		};
       $("input#destination_event_date").datepicker( { dateFormat: 'yy-mm-dd' }  );		
	},
	newShortcut: function( destination, target ){
		$.ajax({
			type:		'POST',
			url:		'/shortcuts',
			data:		'destination_id=' + destination + '&target_id=' + target,
			complete:	function( data ){
				result = data.responseText;
				if ( result == 'oops' ) {
					Utility.flash('Sorry, there was problem');
				} else if ( result == 'dup' ) {
					Utility.flash('Shortcut already exists');
				} else {
					shortcuts = $('#shortcut-control ul').html();
					shortcuts += data.responseText;
					$('#shortcut-control ul').html(shortcuts);
				};
			}
		});	
	},
	deleteShortcut: function( id, element ){
		$.ajax({
			type:		'DELETE',
			url:		'/shortcuts/' + id ,
			complete:	function( data ){
				result = data.responseText;
				if ( result == 'ok' ) {
					element.parent().remove();
				} else {
					Utility.flash('Sorry, there was problem');
				};
			}
		});		
	},
	updateShortcut: function( parent ){
		$.ajax({
			type:		'GET',
			url:		'/destinations/' + parent + '/shortcut',
			complete:	function( data ){
				ancestors = JSON.parse(data.responseText);
//				console.log(ancestors);
				sOptions = "";
				for ( var i = 0; i < ancestors.length; i++ ){
					sOptions += "<option value='" + ancestors[i][0] + "'>" + ancestors[i][1] + "</option>";
				};
				$('#destination-shortcut').html( sOptions );
			}
		});		
	},
	hideDestinationOptions: function(){
		$('#capacity').hide();
		$('#address').hide();
		$('#supplier').hide();
		$('#country-options').hide();
		$('#contacts').hide();		
		$('#destination_category').hide();
		$('#tag-editor').hide();
		$('#country-editor').hide();
	},
	showDestinationOptions: function( subType, supplierId ){
		switch ( subType ) {
			case 'country' :
				$('#country-options').show();
				$('#country-editor').show();
				break;
			case 'accommodation' :
				$('#destination_category').show();
			case 'excursion' :
				$('#capacity').show();
			case 'golf' :
				$('#contacts').show();
				$('#address').show();
				$('#supplier').show();
				$('#tag-editor').show();
				Utility.checkSupplierSearch( subType, supplierId);
				break;	
			case 'reserve' :
				$('#contacts').show();
				$('#address').show();
				$('#supplier').show();
				$('#destination_category').show();
				$('#tag-editor').show();
				Utility.checkSupplierSearch( subType, supplierId);
				break;	
			case 'place' :
				$('#tag-editor').show();
				$('#destination_category').show();
				break;	
		};
		$('#tag-editor .tag-group').hide();
		tagType = '#tag-editor .' + subType
		$( tagType ).show();
	},
	updateCountry: function( subType, id ){ 
		$.ajax({
			type:		'GET',
			url:		'/destinations/' + id + '/get_bitcode',
			complete:	function( data ){
				result = JSON.parse(data.responseText);
				countryBitCode = result.bitcode;
//				console.log( result );
//				alert(result.bitcode);
				if ( $('#supplier').css('display') == 'block' && countryBitCode != "" ) {
					$('#destination_bitcode').val( countryBitCode );
					Utility.getDestinationSupplier( countryBitCode, subType );
				};	
			}
		});
	},
	checkSupplierSearch: function( subType, supplierId ) {
		countryBitCode = $('#destination_bitcode').attr('value');
		if ( countryBitCode > 0) {
			Utility.getDestinationSupplier( countryBitCode, subType, supplierId );
		};
	},
	getDestinationSupplier: function( countryBitCode, subType, supplierId ) {
		$.ajax({
			type:		'GET',
			url:		'/suppliers/offering_country',
			data:		'country_bitcode=' + countryBitCode + "&sub_type=" + subType,
			complete:	function( data ){
				var suppliers = JSON.parse(data.responseText);
				if (suppliers.length > 0) {
					Utility.setSupplierSelect(suppliers, supplierId);
				};
			}
		});
	},
	setSupplierSelect: function( suppliers, supplierId ) {
		sOptions = "<option value=''>Suppliers</option>";
//				alert( tOptions );
		for ( var i = 0; i < suppliers.length; i++ ){
			if ( suppliers[i].id == supplierId ) {
				selected = "selected='selected'"; 
			} else {
				selected = ""; 				
			};
			sOptions += "<option value='" + suppliers[i].id + "' " + selected + " >" + suppliers[i].name + "</option>";
//				alert(sOptions);
		};
		$('#destination_supplier_id').html( sOptions );
//				alert("Woof");
	},
	subTypeAction: function( subType ) {
		Utility.hideDestinationOptions();
		Utility.showDestinationOptions( subType );
	},
	inplaceInit: function( scope, ta_rows, ta_cols ){
		jQuery(function($){
			elements = $( scope ).find("p.inline-edit,span.inline-edit");
			elements.editInPlace({
			    url: "/utility/update",
				default_text: "[Edit]",
				bg_over: '#c0c0c0'
//				bg_out: '#fff'
			});
			elements = $( scope ).find("div.inline-edit");
			elements.editInPlace({
			    url: "/utility/update",
				default_text: "[Click to edit]",
				bg_over: '#c0c0c0',
				show_buttons: true,
//				bg_out: '#fff',
        		field_type: "textarea",
				textarea_rows: ta_rows,
				textarea_cols: ta_cols
			});
			elements = $( scope ).find("div[display=hidden]");
			elements.each( function(i){
				$( this ).hide();
			});
		 }); 
	},
	makeSelected: function( target ){
		element = $(target);
		element.toggleClass('selected').parent().siblings('li').find('input').removeClass('selected');
	},	
	resizeInit: function( target ){
		jQuery(function($){
			textareas = $( target ).find('textarea');
			textareas.expandable( { by: 1});
		});
	},
	stripeRows: function( list ){
		jQuery(function($){
			$( list ).find('li:even').addClass('even-row');
		});
	},
	flash: function( msg ) {
		if (msg == "")
			msg = "Successful Update";
		$('#flash').html( msg ).fadeIn( 1000 ); setTimeout( function() {$('#flash').effect('blind', 2000)}, 5000 ) ;
	},
	unhide: function( div ) {
		element = $( div );
		element.is( ':hidden' ) ? element.show() : $( element ).hide();
	},
	rehide: function( div ) {
		element = $( div );
		element.is( ':hidden' ) ? element.show() : $( element ).hide();
	},

//			elements = $( scope ).find("a.unhide");
//			elements.each( function(i){
//				element = $( this ); 
//				notes = '#SupplierConnection_' + element.attr('notes') ;
//				alert( notes );
//				target = $( eval( "'" + notes + "'" ) );
//				console.log( target );
//				element.live( 'click', function(){ target.show(); } );
//				alert("Bound");
//			} );

	areaBitSelect: function() {
		$("#bit_areas").autoSuggest( Search.getCountries(), 
					{ selectedItemProp: "name", 
					  searchObjProps: "name",
					  startText: "Country"
					} );
	}
}

var Picker = {
	init: function(){
		jQuery('#get_health_matters').live('click', function(e) {
			Action.getHealthMatters();
			return false;
		} );	
		jQuery('a#get_amazon_store').live('click', function(e) {
			Amazon.go(0);
			return false;
		} );	
		jQuery('a#close_amazon_store').live('click', function(e) {
			$('iframe#amazon').remove();
			Action.getIndex();
			return false;
		} );	
		jQuery('input#get_amazon').live('click', function(e) {
			Amazon.go(0);
			return false;
		} );	
		jQuery('#get_connections').live('click', function(e) {
			Action.getConnections();
			return false;
		} );
	},
	adminInit: function(){
		jQuery('#picker select').live('change', Search.pickerDestinationChange );
		jQuery('#option-utility select').live('change', Search.destinationChange );
		jQuery('#picker input[type=radio]').live('click', Search.pickerSelection );
		jQuery('#create_Destination').live('click', function(e) {
			Action.newDestination();
			return false;
		} );	
		jQuery('#create_Flight').live('click', function(e) {
			Action.newConnection( "flight" );
			return false;
		} );	
		jQuery('#edit_Destination').live('click', function(e) {
			Action.editDestination();
			return false;
		} );	
		jQuery('#create_Link').live('click', function(e) {
			Action.newConnection("link");
			return false;
		} );	
		jQuery('#delete_US').live('click', function(e) {
			Action.deleteUS();
			return false;
		} );	
		jQuery('#create_User').live('click', function(e) {
			Action.newUser();
			return false;
		} );	
		jQuery('#create_Supplier').live('click', function(e) {
			Action.newSupplier();
			return false;
		} );	

		jQuery('#get_articles').live('click', function(e) {
			var article_type = "article"
			var object = $('#ust-picked-object').attr('value');
			var supplier_id = ( object == "supplier") ? $('#ust-picked-id').attr('value') : "" ;
			var d_id = $('#destination-picked-id').attr('value');
			var match = $('#info-name').attr('value');
			Action.searchArticles( article_type, d_id, supplier_id, match );
			return false;
		} );	
		jQuery('#create_Article').live('click', function(e) {
			var object = $('#ust-picked-object').attr('value');
			var supplier_id = ( object == "supplier") ? $('#ust-picked-id').attr('value') : "" ;
			var d_id = $('#destination-picked-id').attr('value');
			var article_type = 'article';
			Action.newArticle( article_type, d_id, supplier_id );
			return false;
		} );	
		jQuery('#get_pages').live('click', function(e) {
			var match = $('#info-name').attr('value');
			Action.searchPages( match );
			return false;
		} );	
		jQuery('#create_Page').live('click', function(e) {
			Action.newPage();
			return false;
		} );	
		jQuery('#get_maps').live('click', function(e) {
			Action.getMaps();
			return false;
		} );	
	},
	ustAsUser: function(data) {
		$("input#pick-user").autoSuggest( Search.getClientelle(), 
					{ selectedItemProp: "name", 
					  searchObjProps: "name",
					  startText: "User name",
					  resultClick: function(data){ Picker.ustPicked(data, "user"); },
					  selectionClick: function(elem){ Action.editUser( elem); }
					} );
	},
	ustAsSupplier: function(data) {
		$("input#pick-supplier").autoSuggest( Search.getDirectory(), 
					{ selectedItemProp: "name", 
					  searchObjProps: "name",
					  startText: "Supplier name",
					  resultClick: function(data){ Picker.ustPicked(data, "supplier"); },
					  selectionClick: function(elem){ Action.editSupplier( elem); }
					} );
	},
	ustPicked: function( data, object ) {
		$('#ust-picker .as-input').hide();
		$('#ust-picked-object').val( object );
		$('#ust-picked-id').val( data.attributes.value );
	},
} 
var Destination = {
	init: function(){
		Mapping.clearArrays();
		Mapping.setupCircles();
		$('ul#destination-child-items input[lat]').each(function(){
			var element = $(this);
			var id = element.attr('value');
			if ( Number( element.attr('lat')) == 0 ){
				element.hide();
				return true;
			};
			var sub_type = element.attr('sub_type');
			var latLng = new google.maps.LatLng(element.attr('lat'), element.attr('lng'));
			if ( sub_type == 'airport') {
				title = element.parents('li').first().find('span').text();
			} else {
				title = element.parents('li').first().find('a.show').last().text();
			};
			Mapping.newMarkers.length = 0;
			switch (sub_type) {
				case 'activity':
					markerType = 'excursion';
					break;
				case 'place':
					markerType = 'location';
					break;
				case 'round':
				case 'golf':
					sub_type = 'course';
					markerType = 'course';
					break;
				default:
					markerType = sub_type;
					break;
			};
			Mapping.updateMarkerArray(title, id, latLng.lat(), latLng.lng());
			Mapping.addMarkersToMap(markerType);
			var marker = Mapping.markers[Mapping.markers.length - 1];
//			google.maps.event.addListener(marker, 'click', function(){
//				alert( "Woof" );
//			});			
			Mapping.itemsIndex[id] = marker;
			var typeIndex = "Mapping." + sub_type + "Index";
			eval(typeIndex).push(marker);
		});
		if ( Mapping.markers.length > 0){
			Mapping.doBoundMarkers(Mapping.markers);
			var zoom = Mapping.map.getZoom();
			if ( zoom > 10 ) {
				Mapping.map.setZoom( 10 );
			} else if ( zoom < 6){
				Mapping.map.setZoom( zoom + 1 );				
			};
			$.each( Mapping.markers, function(){
				this.setMap( null );
			});
			$('div#destination-map-control input.marker').removeClass('selected');
		};
		$('div#destination-map-control li input[component]').each(function(){
			var element = $(this);
			var type = element.attr('component');
			var typeIndex = "Mapping." + type.toLowerCase() + "Index";
			var length = eval(typeIndex).length;
			if (length == 0) {
// Selective hiding of markers - removed according to line above - hides all
//				if ( type == 'Regional' || type == 'Airstrip' || type == 'Restaurant' || type == 'Climate'  || type == 'Course' ){
//					$.each( eval(typeIndex), function(){
//						this.setMap(null);
//					});
//				} else {
//					element.addClass('selected');					
//				};
//			}
//			else {
				element.hide();
			};
		});
	},
	hideType: function(type){
		var typeLower = type.toLowerCase();
		var typeIndex = "Mapping." + typeLower + "Index";
		$.each(eval(typeIndex), function(){
			this.setMap(null);
		});
		var elements = 'fieldset#map-tour-index input.' + type ;
		elements = 'ul#destination-child-items input[sub_type=' + typeLower +']';
		$(elements).removeClass('checked');
	},
	showType: function(type){
		var typeIndex = "Mapping." + type.toLowerCase() + "Index";
		$.each(eval(typeIndex), function(){
			this.setMap(Mapping.map);
		});
		elements = 'fieldset#map-tour-index input.' + type;
		$(elements).addClass('selected');
//		alert(elements);
	},

}
var Form = {
	loginSetup: function(){
		$('input:submit[value=Login]').live( 'click', function(){
			$.validity.start();
			$("input").require();
			return  $.validity.end().valid; 
		});
	}	
}
var Tour = {
	clear: function(){
		Mapping.clearArrays();
	},
	init: function(){
		$('a#hide-details').live('click', function(e){
			element = $(this);
			element.hasClass('hidden') ? Tour.showAll() : Tour.hideAll();
			element.toggleClass('hidden');
			return false;
		});
		$('fieldset#map-tour-index input.Item[mapping=marker]').live('click', function(e){
			var element = $(this);
			Tour.hideAll();
			var id = element.attr('id');
			if (element.hasClass('selected') == false) {
				Tour.showItem(id);
				Mapping.mapMarker(id);
			}
			else {
				Mapping.unmapMarker(id);
			};
			element.toggleClass('selected');
		});
		$('fieldset#map-tour-index input.Item[mapping=standard]').live('click', function(e){
			var element = $(this);
			Tour.hideAll();
			var id = element.attr('id');
			var A = element.attr('A');
			var B = element.attr('B');
			var mode = element.attr('component');
			var index = A + "_" + B + "_" + mode + "_" + id;
			if (element.hasClass('selected') == false) {
				//				var item_id = id.replace(/[^0-9]/g, "");
				Tour.showItem(id);
				Mapping.showPolyLine(index);
			}
			else {
				Mapping.hidePolyLine(index);
			};
			element.toggleClass('selected');
		});
		$('fieldset#map-tour-index input.Item[mapping$=ING]').live('click', function(e){
			var element = $(this);
			Tour.hideAll();
			var id = element.attr('id');
			var A = element.attr('A');
			var B = element.attr('B');
			var mode = element.attr('component');
			var index = A + "_" + B + "_" + mode + "_" + id;
			if (element.hasClass('selected') == false) {
				//				var item_id = id.replace(/[^0-9]/g, "");
				Tour.showItem(id);
				Mapping.showDirectionsDisplay(index);
			}
			else {
				Mapping.hideDirectionsDisplay(index);
			};
			element.toggleClass('selected');
		});
		$('fieldset#map-tour-index a.show_item').live('click', function(e){
			var element = $(this);
			var id = element.attr('href');
			Tour.hideAll();
			Tour.showItem(id);
			return false;
		});
		$('fieldset#map-tour-index a.show_day').live('click', function(e){
			var id = $(this).attr('href');
			Tour.hideAll();
			Tour.showDay(id);
			return false;
		});
		$('fieldset#map-tour-index input.Day').live('click', function(e){
			var element = $(this);
			Tour.hideAll();
			var id = element.attr('id');
			if (element.hasClass('selected') == false) {
				Tour.showDay(id);
				Tour.mapDay(id);
			}
			else {
				Tour.unmapDay(id);
			};
			element.toggleClass('selected');
		});
		$('div#tour-map-control li input.marker').live('click', function(e){
			var element = $(this);
			var type = element.attr('component');
			if (element.hasClass('selected')) {
				Tour.hideType(type);
				element.removeClass('selected');
			}
			else {
				Tour.showType(type);
				element.addClass('selected');
			};
		});
		$('div#tour-map-control li input.connexion').live('click', function(e){
			var element = $(this);
			var type = element.attr('component');
			if (element.hasClass('selected')) {
				Tour.hideType(type);
				element.removeClass('selected');
			}
			else {
				element.addClass('selected');
				Tour.showType(type);
			};
		});
		$('div#tour-map-control input#map-days').live('click', function(e){
			var element = $(this);
			if (element.hasClass('selected')) {
				Tour.hideDays();
			}
			else {
				Tour.showDays();
			};
			element.toggleClass('selected');
		});
	},
	addTourMarkers: function(){
		$('fieldset#map-tour-index input.Day[lat]').each(function(){
			var element = $(this);
			var id = element.attr('id');
			var latLng = new google.maps.LatLng(element.attr('lat'), element.attr('lng'));
			var title = element.parents('li').first().find('a.show_day').text();
			marker = Mapping.addMarkerByNumber(latLng, "green", Number(element.attr('day')), title);
			google.maps.event.addListener(marker, 'click', function(){
				Tour.hideAll();
				Tour.showDay(id);
			});
			Mapping.markers.push(marker);
			Mapping.daysIndex[id] = marker;
			Mapping.dayIdsIndex.push(element.attr('id'));
		});
		$('fieldset#map-tour-index input[mapping=marker][lat]').each(function(){
			var element = $(this);
			var id = element.attr('id');
			var latLng = new google.maps.LatLng(element.attr('lat'), element.attr('lng'));
			var type = element.attr('component');
			Mapping.newMarkers.length = 0;
			var title = element.parents('li').first().find('a.show_item').text();
			switch (type) {
				case 'Activity':
					markerType = 'excursion';
					break;
				case 'Hop':
					type = 'flight';
					break;
				case 'Place':
					markerType = 'location';
					break;
				case 'Round':
					markerType = 'golf';
					break;
				case 'Stay':
					markerType = 'accommodation';
					break;
				case 'Inclusion':
					if ( element.hasClass('Facet') ){
						markerType = 'facet';
						type='Facet';
					} else { markerType = 'inclusion'};
					break;
				default:
					markerType = type;
					break;
			};
			Mapping.updateMarkerArray(title, id, latLng.lat(), latLng.lng());
			Mapping.addMarkersToMap(markerType);
			var marker = Mapping.markers[Mapping.markers.length - 1];
			google.maps.event.addListener(marker, 'click', function(){
				Tour.hideAll();
				Tour.showItem(id);
			});
			Mapping.itemsIndex[id] = marker;
			var typeIndex = "Mapping." + type.toLowerCase() + "Index";
			eval(typeIndex).push(marker);
		});
		$('fieldset#map-tour-index input[mapping=standard][a_lat][b_lat]').each(function(){
			var id = $( this ).attr('id');
			Tour.addTourConnexion( id );
		});
		$('fieldset#map-tour-index input[mapping$=ING]').each(function(){
			var id = $( this ).attr('id');
			Tour.addTourConnexion( id );
		});
		var daysDiv = $('div#tour-map-control input#map-days').first();
		if (Mapping.dayIdsIndex.length > 0) {
			daysDiv.addClass('selected');
		}
		else {
			daysDiv.hide();
		};
		$('div#tour-map-control li input[component]').each(function(){
			var element = $(this);
			var type = element.attr('component');
			var typeIndex = "Mapping." + type.toLowerCase() + "Index";
			var length = eval(typeIndex).length;
			if (length > 0) {
				element.addClass('selected');
			}
			else {
				element.hide();
			};
		});
		Mapping.doBoundMarkers(Mapping.markers);
	},
	addTourConnexion: function( id ){
		var item = "fieldset#map-tour-index input#" + id ;
		var element = $( item );
		var A = element.attr('A');
		var B = element.attr('B');
		var latLngA = new google.maps.LatLng( Number(element.attr('a_lat')), Number(element.attr('a_lng')) ); 
		var latLngB = new google.maps.LatLng(Number(element.attr('b_lat')), Number(element.attr('b_lng')) ); 
		var reverse = element.attr('reverse');
		if ( element.attr('waypoints') ) {
			Mapping.addWaypoints( element.attr('waypoints'));
		};
		var mode = element.attr('component');
		var mapping_type = element.attr('mapping');
		var index = A + "_" + B + "_" + mode + "_" + id;
		if ( mapping_type == "standard" ){	
			var typeIndex = "Mapping." + mode.toLowerCase() + "Index";
			var polyline = Mapping.addPolyLine( latLngA, latLngB, mode, index );
			eval(typeIndex).push( polyline);
			google.maps.event.addListener(polyline, 'click', function(){
				Tour.hideAll();
				Tour.showItem(id);
			});
		} else {
			var display = Mapping.newDirectionsDisplay();
			Mapping.directionsDisplayIndex[ index ] = Mapping.directionsDisplay.length - 1;
			display.suppressMarkers = true;
			display.setPanel(null);
			var saveFlag = false;
			Mapping.getDirections( latLngA, latLngB, display );
			eval(typeIndex).push( display );
			google.maps.event.addListener(display, 'click', function(){
				Tour.hideAll();
				Tour.showItem(id);
			});
		};
	},
	hideDays: function(){
		$.each(Mapping.dayIdsIndex, function(){
			Tour.unmapDay(this);
		});
		$('fieldset#map-tour-index input.Day').each(function(e){
			$( this ).removeClass('selected');
		});
	},
	showDays: function(){
		$.each(Mapping.dayIdsIndex, function(){
			Tour.mapDay(this);
		});
		$('fieldset#map-tour-index input.Day').each(function(e){
			$( this ).addClass('selected');
		});
	},
	hideType: function(type){
		var typeIndex = "Mapping." + type.toLowerCase() + "Index";
		$.each(eval(typeIndex), function(){
			this.setMap(null);
		});
//		elements = 'fieldset#map-tour-index input.' + type;
//		$(elements).removeClass('selected');
	},
	showType: function(type){
		var typeIndex = "Mapping." + type.toLowerCase() + "Index";
		$.each(eval(typeIndex), function(){
			this.setMap(Mapping.map);
		});
//		elements = 'fieldset#map-tour-index input.' + type;
//		$(elements).addClass('selected');
	},
	mapDay: function(id){
		if (Mapping.daysIndex[id] != null) {
			var marker = Mapping.daysIndex[id]
			marker.setMap(Mapping.map);
			Mapping.circle[0].setMap(Mapping.map);
			Mapping.circle[0].bindTo('center', marker, 'position');
			Mapping.map.setCenter(marker.position);
			;
		}
		else {
			Utility.flash("Sorry, Day has not been mapped")
		};
			},
	unmapDay: function(id){
		if (Mapping.daysIndex[id] != null) {
			Mapping.circle[0].setMap(null);
			Mapping.daysIndex[id].setMap(null);
		};
	},
	mapPolyline: function(id, element){
		alert("Polyline" + id);
	},
	mapDirections: function(id, element){
		alert("Directions " + id);
	},
	showItem: function(id){
		var item = "#" + id;
		$('div#tour-head').hide();
		var element = $(item);
		element.parents('div.day').show();
		element.show();
	},
	showDay: function(id){
		var item = "#" + id + " div.show_day";
		$('div#tour-head').hide();
		var element = $(item);
		element.parents('div.day').show();
		element.show();
	},
	showAll: function(){
		//		$('div#show-tour div#gallery-tour').show();
		$('div#show-tour div#header-2').show();
		$('div#show-tour div.day').show();
		$('div#show-tour div.show_day').show();
		$('div#show-tour div.show_item').show();
		$('div#show-tour div#tour-tail').show();
	},
	hideAll: function(){
		//		$('div#show-tour div#gallery-tour').hide();
		$('div#show-tour div#header-2').hide();
		$('div#tour-head').show();
		$('div#show-tour div.day').hide();
		$('div#show-tour div.show_day').hide();
		$('div#show-tour div.show_item').hide();
		$('div#show-tour div#tour-tail').hide();
	},
}

var Action = {
	cache: [],
	fetchSupplier: function(id){
		$.ajax({
			type: 'GET',
			url: '/suppliers/' + id,
			complete:	function( html ){
				$('#tripmain').html( html.responseText );	
			}
		});
	},
	fetchComments: function(type, id){
		$.ajax({
			type: 'GET',
			url: '/utility/commentary/' + id,
			data: 'type=' + type
		});
	},
	countryEditInit: function( id, health_matters, selected_matters ){
		var options = "";
		$.each( health_matters, function( key, value ){
			options += "<option value='" + value.id + "'>" + value.name + "</option>"
		});
		if (selected_matters) {
			$.each( selected_matters, function( key, value ){
				options += "<option value='" + value.id + "' selected='selected'>" + value.name + "</option>"
			});
		};
		var select = $("#matters");
		select.html( options );	
		select.multiselect2side({});	
		$('input#submit_health').bind( 'click', function(e){
			var selected = $('select#ms2side__dx option');
			var values = [];
			$.each( selected, function(){
				values.push( $(this).val() );
			});
			$.ajax({
				type: 'POST',
				url: '/countries/health/' + id,
				data: 'selected=' + values.join()
			});	
		});
		Utility.inplaceInit( '#country-editor', 6, 71 );
	},
	countryEditLive: function( id, health_matters, selected_matters ){
		$('input#country_submit').live('click', function(e){
			var selected = [];
			$('select#ms2side__dx option').each(function(){
				selected[ selected.length ] = $(this).attr('value');
			});
			Action.sendSelectedMatters( id, selected.join(',') );
			return false;
		});
	},
	sendSelectedMatters: function( id, selected ){
		$.ajax({
			type: 'PUT',
			url: '/countries/' + id,
			data: 'selected=' + selected
		});

	},
	linkASInit: function( type ){
		$("input#link-destinations").autoSuggest( Search.getConnectionPoints(), 
			{
				asHtmlID: "connection-point",
				minChars: 2, 
//				matchCase: true, 
				startText: "Find Destination",
			  	searchObjProps: "name",
				selectedValuesProp: "value",
				selectedItemProp: "name",
//				formatList: function(data, elem){
//				    var new_elem = elem.html("Which one?");
//				    return new_elem;
//				},
//				selectionAdded: function(elem){ console.log(elem); },
				resultClick: function(data){ Action.findLinkRoutes( data.attributes.name, data.attributes.value, true ); }
//				selectionClick: function(elem){ element = $(elem); Action.applyDestination( element.attr('values')) }
//				selectionAdded: function(elem){ Mapping.addConnectionPoint(); }
//				retrieveComplete: function(data){  console.log(data); alert( 'woof' ); }
//				selectionAdded: function(elem){ elem.fadeTo("slow", 0.33); },
//				selectionRemoved: function(elem){ elem.fadeTo("fast", 0, function(){ elem.remove(); }); }
		});	
		
	},
	applyDestination: function( id, name ){
		if ( $('input#d2').attr('checked') ) {
			$('input#component_destination_id').val( id );
			$('span#destination_name').text( name );
		}
		else {
			$('input#component_origin_id').val( id );				
			$('span#origin_name').text( name );
		};
	},
	findLinkRoutes: function(name, value){
		values = value.split("%");
		id = values[0];
		Action.applyDestination( id, name );
		mode = $('div#editor ul.type-bar input.selected').attr('mode');
		if ( !mode ) {
			mode = 'all';
		};
		Connection.getRoutes( id, 0, mode, 'link-routes', 'link' ); 		
	},
	setupConnectionPoints: function( type )	{
		$.ajax({
			type:		'GET',
			url:		'/destinations/places',
			complete:	function( data ){
				Search.setConnectionPoints( JSON.parse(data.responseText));
				switch (type){
					case 'map' :
						Action.connectionPointsInit();
							break;
					case 'link' :
						Action.linkASInit();
							break;
				};
			}
		});
	},
	tourHeadInit: function(){
       $("input#tour_start_date").datepicker( { dateFormat: 'yy-mm-dd' }  );
	   		
	},
	destinationInit: function(){
		jQuery('#create_destination_child input:submit').live('click', function(e) { 
			element = $( this );
			var parent_id = element.parents().find('ul').attr( 'value' );
			var type = element.attr('class');
			$.fn.colorbox({href:"/destinations/new?parent_id=" + parent_id + "&type=" + type , width: "60%", opacity: 0.8 });
		} );
		jQuery('#destination-nav li.reveal').live('click', function(e) { 
			var element = $( this );
//			element.find('a').attr('title', element.hasClass('selected') ? 'Show details' : 'Hide details').toggleClass('selected');
//			console.log(element.parent().next('div'));
			element.siblings('div').addClass('hidden');
			element.next('div').removeClass('hidden').show();
			return false;
		} );
	},
	connectionPointsInit: function() {
		$("input#map-destinations").autoSuggest( Search.getConnectionPoints(), 
			{
				asHtmlID: "connection-point",
				minChars: 2, 
//				matchCase: true, 
				startText: "Destination Search",
			  	searchObjProps: "name",
				selectedValuesProp: "value",
				selectedItemProp: "name",
//				formatList: function(data, elem){
//				    var new_elem = elem.html("Which one?");
//				    return new_elem;
//				},
//				selectionAdded: function(elem){ console.log(elem); },
				resultClick: function(data){ Action.connectionDestination( data.attributes.name, data.attributes.value, true, false ); },
				selectionClick: function(elem){ element = $(elem); Action.reselectMarker( element.attr('title'), element.attr('values')) }
//				selectionAdded: function(elem){ Mapping.addConnectionPoint(); }
//				retrieveComplete: function(data){  console.log(data); alert( 'woof' ); }
//				selectionAdded: function(elem){ elem.fadeTo("slow", 0.33); },
//				selectionRemoved: function(elem){ elem.fadeTo("fast", 0, function(){ elem.remove(); }); }
		});
	},
	reselectMarker: function( name, value ){
		id = value.split("%")[0];
		markerIndex = Mapping.markersIndex[id];
		if ( markerIndex != null ) {
			mode = Connection.getMode();
			Connection.getRoutes( id, 0, mode, 'local-results', 'map' ); 
			marker = Mapping.markers[markerIndex];
//			if (marker == Mapping.markers[markerIndex]) {
				Action.setCircles(marker);
				Action.gotoMarker(marker);
//			};		
		} else {
			Action.connectionDestination( name, value, false, false );
		};
	},
	connectionRoutes: function( elem ) {
//		console.log(elem);
	},
	connectionDestination: function( name, value, asSet, noRoutes ) {
		values = value.split("%");
		id = values[0];
		lat = values[1];
		lng = values[2];
		destinationType = values[3];
		subType = values[4];
		if ( destinationType != 'attraction' ) {
			subType = destinationType;
		};
		if (asSet) {
			liList = $('#as-selections-connection-point li');
			newItem = liList.length - 2;
			liList.eq(newItem).attr('title', name);
			liList.eq(newItem).attr('values', value);
		};
		mode = Connection.getMode();
		marker = Mapping.markers[ Mapping.markersIndex[ id ]];
		if ( marker != null ) {
			Action.gotoMarker( marker );
		} else { 
			marker = Action.newDestinationMarker( name, id, lat, lng, subType );
		};
		Action.setCircles( marker );
		if ( noRoutes != true ) {
			Connection.getRoutes( id, 0, mode, 'local-results', 'map' ); 
		};
		return marker;
	},
	setCircles: function( marker ){
		if ( Mapping.lastMarker != null ) {
			lastMarker = Mapping.lastMarker;
			Mapping.circle[1].setCenter( lastMarker.position );
			Mapping.circle[1].setMap( Mapping.map );
		};	
		Mapping.circle[0].setCenter( marker.position );
		Mapping.circle[0].setMap( Mapping.map );
		Mapping.previousMarker = Mapping.lastMarker;
		Mapping.lastMarker = marker;
	},
	gotoMarker: function( marker ) {
		Mapping.map.setCenter( marker.position );
	},
	newDestinationMarker: function( name, id, lat, lng, subType ) {
		Mapping.newMarkers = [];
		Mapping.updateMarkerArray( name, id, lat, lng );
		Mapping.addMarkersToMap( subType );
		Mapping.boundMarkers();
		var marker = Mapping.markers[ Mapping.markers.length - 1 ];
		google.maps.event.addListener( marker, 'click', function(){
			Action.setCircles( marker );
			id = $( this ).attr('subject_id');
			mode = Connection.getMode();
			Connection.getRoutes( id, 0, mode, 'local-results','map' ); 
		});
		return marker;
	},
	newDestination: function(){
		$.ajax({
			type:		'GET',
			url:		'/destinations/new',
			complete:	function( html ){
				$('#tripmain').html( html.responseText );	
			}
		});
	},
	getDestinations: function( partial ){
		$.ajax({
			type:		'GET',
			url:		'/destinations/' + partial 
		});
	},
	getDestination: function( id ){
		$.ajax({
			type:		'GET',
			url:		'/destinations/' + id 
		});
	},
	getTourItin: function( id ){
		var key = "tour_" + id;
		$.ajax({
			type:		'GET',
			url:		'/tours/' + id,
			complete:	function( html ){
				$('#tripmain').html( html.responseText );
				Action.cache[ key ] = html.responseText ;
			} 
		});
	},
	getTourMap: function( id ){
		$.ajax({
			type:		'GET',
			url:		'/tours/' + id + '/mapped'
		});
	},
	getViewpoint: function( viewpoint ){
		$.ajax({
			type:		'GET',
			url:		'/search/show_viewpoint',
			data: 		'viewpoint=' + viewpoint
		});
	},
	getIndex: function( id ){
		$.ajax({
			type:		'GET',
			url:		'/index',
			complete:	function( html ){
				$('#tripmain').html( html.responseText );	
			} 
		});
	},
	editDestination: function( element ){
		var id = $('#destination-picked-id').attr('value');
		if ( id == "" ) { 
			Utility.flash("Destination required"); 
			return false;
		};
		Action.getEditDestination(id);
	},
	getEditDestination: function( id ){
		$.ajax({
			type:		'GET',
			url:		'/destinations/' + id + '/edit'
		});
	},
	newConnection: function( mode ){
		$.ajax({
			type:		'GET',
			url:		'/connexions/manager',
			data: 		'mode=' + mode ,
			complete:	function( html ){
				$('#tripmain').html( html.responseText );	
			}
		});
	},
	newUser: function(){
		$.ajax({
			type:		'GET',
			url:		'/users/new'
		});
	},
	newSupplier: function(){
		$.ajax({
			type:		'GET',
			url:		'/suppliers/new'
		});
	},
	newArticle: function( article_type, destination_id, supplier_id ){
		if ( article_type == '') { article_type = 'article' };
		$.ajax({
			type:		'GET',
			url:		'/articles/new',
			data: 		'article_type=' + article_type + '&destination_id=' + destination_id + '&supplier_id=' + supplier_id,
			complete:	function( html ){
				$('#tripmain').html( html.responseText );	
			}
		});
	},
	searchArticles: function( article_type, destination_id, supplier_id, match ){
		if ( article_type == '') { article_type = 'article' };
		$.ajax({
			type:		'GET',
			url:		'/search/quick_article',
			data: 		'article_type=' + article_type + '&destination_id=' + destination_id + '&supplier_id=' 
				+ supplier_id + '&match=' + match,
			complete:	function( html ){
				$('#local-results').html( html.responseText );	
			}
		});
	},
	searchPages: function( match ){
		$.ajax({
			type:		'GET',
			url:		'/search/quick_page',
			data: 		'match=' + match,
			complete:	function( html ){
				$('#local-results').html( html.responseText );	
			}
		});
	},
	getMaps: function(){
		$.ajax({
			type:		'GET',
			url:		'/maps',
			complete:	function( html ){
				$('#tripmain').html( html.responseText );	
			}
		});
	},
	getConnections: function(){
		$.ajax({
			type:		'GET',
			url:		'/connexions' //,
//			complete:	function( html ){
//				$('#tripmain').html( html.responseText );	
//			}
		});
	},
	getHealthMatters: function(){
		$.ajax({
			type:		'GET',
			url:		'/health'
		});
	},
	newPage: function(){
		$.ajax({
			type:		'GET',
			url:		'/pages/new',
			complete:	function( html ){
				$('#tripmain').html( html.responseText );	
			}
		});
	},
	editUser: function( element ){
//		console.log( element);
		id = $('#ust-picked-id').attr('value');
		$.ajax({
			type:		'GET',
			url:		'/users/' + id + '/edit',
			complete:	function( html ){
				$('#tripmain').html( html.responseText );	
			}
		});
	},
	deleteUS: function( element ){
//		console.log( element);
		id = $('#ust-picked-id').attr('value');
		object = $('#ust-picked-object').attr('value');
		$.ajax({
			type:		'DELETE',
			url:		'/' + object + 's/' + id,
			complete:	function(){
				$('#ust-picked-id').html( "" );	
				$('#ust-picked-object').html( "" );	
				$('#ust-picker .as-selection-item').css( "background-color: red" );	
//				alert("Woofaf");
			}
		});
	},
	updateArray: function( object ){
//		alert( object );
		switch ( object ) {
			case 'user' :
				Search.fetchUsers();
				break;
			case 'supplier' :
				Search.fetchSuppliers();
				break;
		};
	},

	editSupplier: function( element ){
//		console.log( element );
		id = $('#ust-picked-id').attr('value');
		$.ajax({
			type:		'GET',
			url:		'/suppliers/' + id + '/edit',
			complete:	function( html ){
				$('#tripmain').html( html.responseText );	
			}
		});
	}
}
var Search = {
	gazeteer: [],
	folio: [],
	clientelle: [],
	directory: [],
	countries: [],
	airports: [],
	connectionPoints: [],
	init: function( locations, airports, countries, interests ) {
		this.gazeteer = locations ;		
		this.countries = countries ;
		this.airports = airports ;
		this.folio = interests ;
		jQuery(function(){
			jQuery('#quick-search').show();
		});
	},
	qsearchInit: function() {
		$('#upper_map').addClass('hidden');
		$('#lower_map').addClass('hidden');
		jQuery('fieldset#quick-search-display a.reveal').bind('click', function(e) { 
			$('#search-results').toggleClass('hidden');
			$('#upper_map').toggleClass('hidden');
			$('#lower_map').toggleClass('hidden');
			return false;
		} );
		jQuery('fieldset#quick-search-display a.close').bind('click', function(e) { 
			$('#quick-search-display').remove();
			$('#upper_map').removeClass('hidden');
			$('#lower_map').removeClass('hidden');
			return false;
		} );
		jQuery('a.applyArticle').bind('click', function(e) { 
			var id = $(this).attr('href').replace(/[^0-9]/g, "");
			Search.applyArticle( id );
		} );
	},
	locationDrivable : function( id ){
//		alert( id );
		if (this.gazeteer[id]) {
			result = (this.gazeteer[id][3] == 'area');
		} else { result = false };
		return ( result );
	},
	getCountries: function(){
		return this.countries;
	},
	getGazeteer: function(){
		return this.gazeteer;
	},
	getFolio: function(){
		return this.folio;
	},
	setClientelle: function( json){
		this.clientelle = json;
	},
	getClientelle: function(){
		return this.clientelle;
	},
	setConnectionPoints: function( json){
		this.connectionPoints = json;
	},
	findConnectionPoint: function( id ){
		result = -1;
//		console.log( this.connectionPoints );
		$.each( this.connectionPoints, function(){
			if ( this.id == id ){
				result = this.name + "&" + this.value  ;
			};
		});
		return result;
	},
	getConnectionPoints: function(){
		return this.connectionPoints;
	},
	setDirectory: function( json){
		this.directory = json;
//		console.log( this.directory );
	},
	getDirectory: function( json){
		return this.directory;
	},
	getAirport: function( id ){
		return Search.airports[id];
	},
	fetchUsers: function(){
		$.ajax({
			type:		'GET',
			url:		'/users/index_json_all',
			complete:	function( data ){
				Search.setClientelle(JSON.parse(data.responseText));
				Picker.ustAsUser(data);	
				if ( $( '#ac-picker' ) ) {
					Accounts.acAsUser(data);
				};
			}
		});
	},
	fetchSuppliers: function(){
	
		$.ajax({
			type:		'GET',
			url:		'/suppliers/index_json_all',
			complete:	function( data ){
				Search.setDirectory(JSON.parse(data.responseText));
				Picker.ustAsSupplier(data);	
				if ( $( '#ac-picker' ) ) {
					Accounts.acAsSupplier(data);
				};
			}
		});
	},
	autoSuggestInit: function(){
		if ( Search.getClientelle().length == 0 ) {
			Search.fetchUsers();
		} else
		{
			Picker.ustAsUser(data);	
		};
		if ( Search.getDirectory().length == 0 ) {
			Search.fetchSuppliers();
		} else
		{
			Picker.ustAsSupplier(data);
		};
	},
	autoSuggestLive: function(){
		jQuery('#ust-picker .as-close').live('mouseup', function(e) { 
			jQuery('#ust-picker input').show();
		} );
		jQuery('#list_tours').live('click', function(e) { 
			object = $('#ust-picked-object').attr('value');
			id = $('#ust-picked-id').attr('value');
			match = $('#pick-name').attr('value');
			$.ajax({
				type:		'GET',
				url:		'/search/quick_tour',
				data: 		'object=' + object + "&object_id=" + id + "&match=" + match
			});
		} );
		jQuery('#get_Views').live('click', function(e) { 
			var object = 'Destination';
			var id = $('#destination-picked-id').attr('value');
			$.ajax({
				type:		'GET',
				url:		'/search/quick_view',
				data: 		'object=' + object + "&object_id=" + id 
			});
		} );
		jQuery('#get_Climates').live('click', function(e) { 
			var id = $('#destination-picked-id').attr('value');
			var climate = /\(c\)/.test($('#destination-picked-name').attr('value')) ;
			if (climate && id != '') {
				$.ajax({
					type: 'GET',
					url: '/climates/' + id + '/editor',
				});
			} else { Utility.flash( 'Climate point must be selected' ) };
		} );
		jQuery('#ust_Views').live('click', function(e) { 
			object = $('#ust-picked-object').attr('value');
			id = $('#ust-picked-id').attr('value');
			match = $('#pick-name').attr('value');
			$.ajax({
				type:		'GET',
				url:		'/search/quick_view',
				data: 		'object=' + object + "&object_id=" + id + "&match=" + match
			});
		} );
		jQuery('#ust-picker input[value=Apply]').live('click', function(e) { 
			Search.applyUstPick();
		} );
	},
	tour: function( selector, intro, target ){
		jQuery(function(){
			switch (target) {
				case '#tb-outline':
					category = 'working';
					break;
				case '#tb-reference':
					category = 'reference';
					break;
			}

			$( selector ).faceList( "/tours/index_json", {  //$element.tours
				selectedItem: "name",
				searchObj: "name",
				selectedValues: "id",
				no_result: "No matching tour",
				intro_text: intro ,
				limit_warning: "Remove selected tour",
				resultClick:	function( data ){ 
					Triplite.getTour( data.attributes.id, target );
				},
				extraParams: "&cat=" + category,
				userID: "$('#tb-user input').last().attr('value')"
			});
		});
	},
	user: function( selector, intro ){
		
		jQuery(function( ){
			$( selector ).faceList( '/users/index_json', {
				selectedItem: "last_name",
				searchObj: "last_name",
				selectedValues: "id",
				no_result: "No matching client",
				intro_text: intro ,
				limit_warning: "Remove previous client"
			}); 
		});
	},
	destinationChange: function() {
		Search.updateDestinationSelect( this, 'location' );
	},
	pickerDestinationChange: function() {
		Search.updateDestinationSelect( this, 'picker' );
		$("#picker-attractions").html("");
		$('#mapped_country').val( "" );
		$('#mapped_parent').val( "" );
		$('#mapped_address').val( "" );
		$('#mapped_lat').val( "" );
		$('#mapped_lng').val( "" );
		$('#mapped_zoom').val( "" );
		$('#mapped_elevation').val( "" );
		value = $(this).attr('value');
		name = $(this).find( 'option:selected').text();
		id = value.replace(/[^0-9]/g, "");
		type = value.replace(/\d/g, "");
		switch ( type ) {
			case 'area' : 
				$.ajax({
					type:		'GET',
					url:		'/destinations/' + id + '/attractions',
					data: 		'type=' + type
				});
				break;
			case 'country' : 
			// considering chane to local data!!
				$.ajax({
					type:		'GET',
					url:		'/destinations/' + id + '/attractions',
					data: 		'type=' + type
				});
				break;
		};
		Search.pickerManager( id, name );
	},
	
	updateDestinationSelect: function( e, label ){
		element = $(e);
		parent = element.parent();
		parent.children('input').first().attr('checked', "checked" );
		id = element.attr('id');
		level = Number( id[ id.length - 1 ] ) + 1 ;
		levels = parent.nextAll( '.hierarchy' ).remove() ;
		clone = parent.clone();
		input_id = label + "_match_" + level;
		select_id = label + "_" + level;
		clone.children('input').first().attr('id', input_id );
		radioValue = ( label == "picker" ) ? -1 : level ; 
		clone.children('input').first().attr('value', radioValue );
		clone.children('input').first().attr('checked', "" );
		clone.children('select').first().attr('id', select_id );
//		console.log( parent );
		clone.insertAfter( parent );
		Search.location('#' + id, '#' + select_id, false);
	},
	pickerSelection: function(){
		radio = $(this); 
		radioValue =  radio.attr('value');
		name = radio.parent().text();
		$('#mapped_country').val( "" );
		$('#mapped_parent').val( "" );
		$('#mapped_address').val( "" );
		$('#mapped_lat').val( "" );
		$('#mapped_lng').val( "" );
		$('#mapped_zoom').val( "" );
		$('#mapped_elevation').val( "" );

		if ( radioValue == -1 ) {
			radioValue = radio.next('select').attr('value').replace(/[^0-9]/g, "" ) ;
			name = radio.next('select').find('option:selected').text();
//			alert( radioValue );
			drivable = ( radioValue == "" ) ? "" : Search.locationDrivable( radioValue );
			Mapping.getLocation( radioValue, name );
		} else {
			drivable = true;
			if ( $('#mapped_parent').length > 0 ) {
				$('#mapped_country').val( $('#picker select option:selected:eq(2)').text() );
				$('#mapped_address').val( $(this ).attr('address'));
				lat =  $(this ).attr('lat');
				if ( lat != "" ) {
					$('#mapped_lat').val( lat );
				};
				lng =  $(this ).attr('lng') ;
				if ( lng != "" ) {
					$('#mapped_lng').val( lng );
				};
				zoom = $(this ).attr('zoom');
				if ( lng != "" ) {
					$('#mapped_zoom').val( zoom );
				};
				map_type= $(this ).attr('map_type');
				if ( map_type != "" ) {
					$('#mapped_map_type').val( map_type );
				};
				$('#mapped_elevation').val( $(this ).attr('elevation'));
				area = $('#picker select option:selected:last' ).text();
				if ( area != 'area' ) {
					$('#mapped_parent').val( area );
				};
				if ( lat && lng ) {
					Mapping.addMarker( lat, lng, Number( zoom ) );
				}  else {
					address = name + ' ' + $('#mapped_parent').attr('value') + ' ' + $('#mapped_country').attr('value');
					$('input#geoAddress').val( address );
					Mapping.geocode( address );
				}				
			};
		};
		if (radioValue != "") {
			Search.pickerManager( radioValue, name, drivable );
		};
	},
	pickerManager: function( id, name, drivable ){
		context = $('#picked');
		d2 = $('#D2').attr('checked')
		switch ( context.parent().attr('id') ) {
			case  "flight-manager" :
				Connection.destinationChange( id, d2, "flight" );
				break;
			case  "link-manager" :
				Connection.destinationChange( id, d2, "link", name, drivable );
				break;
			default:
				Search.applyPick(id, name, "destination", d2);
				break;
		};
	},
	applyPick: function(id, name, type, d2){
		$('#destination-picked-id').val( id );
		$('#destination-picked-name').val( name );
		d2 ? Search.applyPick2(id, name, type) : Search.applyPick1(id, name, type);
	},
	applyPick1: function( id, name, type ){
		if ( id[0] == 'f' ) {
			$('#picked_id' ).val( id.replace(/[^0-9]/g, "") );
			$('#picked_object').val( "facet" ); 
			$('#picked_name').val( name.replace(/» /, "") ); 
		} else {
			$('#picked_id').val( id );
			$('#picked_object').val( type ); 
			$('#picked_name').val( name ); 
		};
	},
	applyPick2: function( id, name, type ){
		if ( id[0] == 'f' ) {
			$('#picked_id_2' ).val( id.replace(/[^0-9]/g, "") );
			$('#picked_object_2').val( "facet" ); 
			$('#picked_name').val( name.replace(/» /, "") ); 
		} else {
			$('#picked_id_2').val( id );
			$('#picked_object_2').val( type ); 
			$('#picked_name_2').val( name ); 
		};
	},
	applyUstPick: function(){
		$('#picked_id').val( $('#ust-picked-id').attr('value') );
		$('#picked_object').val( $('#ust-picked-object').attr('value') ); 
	},
	applyArticle: function( id ){
		$('#picked_id').val( id );
		$('#picked_object').val( 'article' ); 
	},

	location: function( parent_element, child_element, static_select ){
		$element = this;
		this.areaFlag = false;
		this.areaOptions = null;
		this.static_select = static_select;
		this.findAreas = function() {
			areas = Search.getGazeteer();
			$element.areaFlag = false;
			parent_id = $( parent_element ).attr('value').replace( /[^0-9]/g, ""  );
			$element.areaOptions = "<option value=''>area</option>";
			for (i in areas) {
			    if ( areas[i][0] == parent_id) {
			       $element.areaOptions += "<option value='" + areas[i][1] + areas[i][3] + "'>" + areas[i][2] + "</option>";
				   $element.areaFlag = true;
			    }
		 	};
			local_select = jQuery(child_element);
			if ( $element.areaFlag ) {
				local_select.html( $element.areaOptions );
			    local_select.show();
			} else {
			    if ( $element.static_select ) 
					{ 
					local_select.hide() 
				} 
				else 
				{ 
					local_select.parent().remove() 
				} ;
			};
		};
		jQuery(function(){
			$element.findAreas();
			if ( $element.static_select )
				$( parent_element ).live('change', $element.findAreas );
		});		
	},
//	location: function(){
//		$element = this;
//		this.areas = this.Gazeteer;
//		this.areaFlag = false;
//		this.areaOptions = null;
//		
//		this.findAreas = function( gazeteer ) {
//			$element.areaFlag = false;
//			$parent_id = jQuery('#qsearch_national').attr('value');
//			$element.areaOptions = "<option value=''>area</option>";
////			alert( $element.areas.length );
//			for (i in $element.areas ) {
//			    if ( $element.areas[i][0] == $parent_id) {
//			       $element.areaOptions += "<option value='" + $element.areas[i][1] + "'>" + $element.areas[i][2] + "</option>";
//				   $element.areaFlag = true;
//			    }
//		 	};
//			local_select = jQuery("#qsearch_local");
//			if ( $element.areaFlag ) {
//				local_select.html( $element.areaOptions );
//			    local_select.show();
//			} else {
//			    local_select.hide();
//			}
//		};
//		
//		jQuery(function(){
//			$element.findAreas( $element.gazeteer );
//			jQuery('#qsearch_national').live('change', $element.findAreas );
//		});		
//	},
	interests: function(){
		$element = this;
		this.folio = Search.getFolio(); ;
		jQuery(function(){
			jQuery("#qsearch_name").faceList($element.folio, {selectedItem: "tag", 
															  searchObj: "tag", 
															  selectedValues: "tag",
															  selectionLimit: 5});
		});
	},
	similarDestinationLive: function(){
		var element = this;
		$('div#option-utility ul.type-bar input').live('click', function(){
			Utility.makeSelected( this );
			$('#component_type').val( $( this).attr('class').replace(/ selected/, "") );
		} );
	},
	similarDestination: function(){
		var element = this;
		this.folio = Search.getFolio(); ;
		jQuery(function(){
			jQuery("#search_tags").faceList( element.folio, {selectedItem: "tag", 
															  searchObj: "tag", 
															  selectedValues: "tag",
															  selectionLimit: 5});
		});
	},
	hideAdmin: function() { $(this).find('.admin').stop().fadeOut('slow') },	
	showAdmin: function() { $(this).find('.admin').stop().fadeIn('slow') },
	hideDescription: function() { $(this).find('.description').stop().hide() },	
	showDescription: function() { 
		description = $(this).find('.description');
		if (description.html() != "") {
			description.stop().show()
		} 
	}
}

var Connection = {
	routes: [],
	getMode: function(){
		mode = $('div#map-control ul.type-bar input.selected').attr('component');
		if ( !mode ) {
			mode = 'all';
		};
		return mode;
	},
	getModeColour: function(mode){
		colour = "gray";
		switch (mode) {
			case 'Cruise':
			case 'Waterway':
				colour = "#9900FF";
				break;
			case 'Train':
				colour = "black";
				break;
			case 'Walk':
				colour = "#666600";
				break;
			case 'Hop':
			case 'Internal':
			case 'Flight':
				colour = "red";
				break;
			case 'Transfer':
			case 'Drive':
				colour = "blue";
				break;
		};
		return colour;
	},
	destinationChange: function( id, d2, mode, name, drivable  ){
		switch ( mode ) {
			case 'flight' :
				var destination = Search.getAirport( id );
				if ( destination) {
					Connection.processChange(  id, d2, mode  );
					Search.applyPick( id, destination[1], "airport", d2 );
				} else 	{
					Utility.flash("Selection must be an airport");
				};
				break;
			case 'link' :
				if ( drivable) {
					Connection.processChange( id, d2, mode  );
					Search.applyPick( id, name, "location", d2 );
				} else 	{
					Utility.flash("Selection must be a destination");
				};
				break;
		}
			
	},
	processChange: function( id, d2, mode ) {	
		remote = d2 ? $('#picked_id').attr('value') : $('#picked_id_2').attr('value') ;
		if ( remote == "" ) {
			Connection.getRoutes( id, d2, mode, "connection-reference",'map' );
		} else if ( id != remote ) {
			Connection.newRoute( remote, id, mode );
		};
	},
	newConnexion: function(  A, B, mode, directions_mode ) {
//		alert(A);
//		alert(B);
//		alert(mode);
		var waypointStr = Mapping.waypoints.length > 0 ? Mapping.getWaypointStr() : "";
		$.ajax({
			type:		'GET',
			url:		'/connexions/new',
			data:		'mode=' + mode + '&A=' + A + '&B=' + B  + '&directions_mode=' + directions_mode + '&waypoints=' + waypointStr 
		});
	},
	newRoute: function( A, B, mode ) {
		$.ajax({
			type:		'GET',
			url:		'/connexions/new',
			data:		'mode=' + mode + '&A=' + A + '&B=' + B ,
			complete:	function( html ){
				$('#connection-display').html( html.responseText );
			}
		});
	},
	getRoutes: function( id, d2, mode, div, context ) {
		div = '#' + div;
		$.ajax({
			type:		'GET',
			url:		'/connexions/' + id + '/routes',
			data:		'mode=' + mode + '&context=' + context,
			complete:	function( html ){
				element = $( div );
				element.html( html.responseText );
			}
		});
	}
}

var UI = {
	woof: function(  ){
		alert("Woof");
	},
	activityInit: function(  ){
		$("#supplier").autocomplete({
			source: "/suppliers?return=id&offers=activities",
			minLength: 2
		});
	},
	carhireInit: function(  ){
		$("#supplier").autocomplete({
			source: "/suppliers?return=id&offers=carhires",
			minLength: 2
		});
	},
	flightInit: function(  ){
		$("#supplier").autocomplete({
			source: "/suppliers?return=id&offers=flights",
			minLength: 2
		});
	},
	roundInit: function(  ){
		$("#supplier").autocomplete({
			source: "/suppliers?return=id&offers=rounds",
			minLength: 2
		});
	},
	stayInit: function(  ){
		$("#supplier").autocomplete({
			source: "/suppliers?return=id&offers=stays",
			minLength: 2
		});
	},
	inclusionInit: function(  ){
		$("input#inclusion-destination").autoSuggest( "/destinations", 
			{ selectedItemProp: "name", 
			  searchObjProps: "name",
			  startText: "Destination name",
			  queryParam: 'search',
			  extraParams: '&json=true',
			  selectionLimit: 1,
			  resultClick: function(data){ UI.getFacets(data.attributes.id, "Destination"); }
	//	  ,selectionClick: function(elem){ Action.editSupplier( elem); }
		});
	},
	getFacets: function( id, object ){
		$.ajax({
			type:		'GET',
			url:		'/facets/',
			data:		'object=' + object + '&id=' + id,
			complete: function(data){
				var facets = JSON.parse(data.responseText);
				var options = "<option value=''>Facets</option>";
				for (var i = 0; i < facets.length; i++) {
					options += "<option value='" + facets[i].id + "'>" + facets[i].name + "</option>";
				};
				$('#facet_id').html(options);
			} 
		});
	},
	getDepartures: function( id ){
		console.log(id);
		$.ajax({
			type:		'GET',
			url:		'/departures/',
			data:		'id=' + id,
			complete: function(data){
				var departures = JSON.parse(data.responseText);
				var options = "<option value=''>Departures</option>";
				for (var i = 0; i < departures.length; i++) {
					options += "<option value='" + departures[i].id + "'>" + departures[i].start_date + "</option>";
				};
				$('#departure_id').html(options);
			} 
		});
	},
	getSupplierTours: function( id ){
		$.ajax({
			type:		'GET',
			url:		'/tours/index_json',
			data:		'supplier=' + id,
			complete:	function( data ){
				var tours = JSON.parse(data.responseText);
				var options = "<option value=''>Tours</option>";
				for ( var i = 0; i < tours.length; i++ ){
					options += "<option value='" + tours[i].id + "'>" + tours[i].name + "</option>";
				};
				$('#tour_id').html( options );
			}
		});
	},
	transferInit: function(  ){
		$("#supplier").autocomplete({
			source: "/suppliers?return=id&offers=transfers",
			minLength: 2
		});
	},
	linkInit: function(  ){
	},
	placeInit: function(  ){
	},
	linkEditorInit: function() {
		Action.setupConnectionPoints('link');
	},
}

var Triplite = {
	startUp	: function(){
		jQuery('#tb-outline-delete').live('click', function(e) { 
			var tree = $.tree.reference("#tb-outline");
			var items = $.tree.plugins.checkbox.get_checked( tree );
			if ( tree.get_type(items[0]) == 'tour') {
				id_str = $( items[0] ).attr('id');
				var id = id_str.substring(5, (id_str.length));
				Triplite.deleteTour( id );
			}
			else {
				$.each(items, function(){
					id_str = $(this).attr('id');
					switch (tree.get_type(this)) {
						case 'day':
							var id = id_str.substring(4, (id_str.length));
							Triplite.deleteDay( id );
							break;
						case 'item':
							var id = id_str.substring(5, (id_str.length));
//							if ( items.indexOf( tree.parent( this ) ) == -1 ) {
								Triplite.deleteItem( id );
//							}
							break;
					};
				});
			};
			items.remove();
		} ); 
		jQuery('#tb-outline-refresh').live('click', function(e) { 
			$.tree.focused().refresh();
		} ); 
		jQuery('#tb-outline-deselect').live('click', function(e) { 
			$.tree.focused().deselect_branch($('#tb-outline .clicked'));
		} ); 
		jQuery('#tb-outline-search').live('click', function(e) { 
			$.tree.reference('tb-outline').search($(this).next().attr('value'));
		} );  
		jQuery('#tb-reference-search').live('click', function(e) { 
			$.tree.reference('tb-reference').search($(this).next().attr('value'));
		} );  
		jQuery('#tb-toolbar .component').live('click', function(e) { 
			component_type = $( this ).attr('rel');
			$.tree.reference("#tb-outline").create( {
				data: "New " + component_type ,
				attributes: {
						rel: "item",
						component_type : component_type,
						id : "new_" + $.password(8)
					}
				}, -1 );
		} );  
		
		jQuery('#tb-tool-day').live('click', function(e) { 
			$.tree.reference('tb-outline').create( {
				data: "New Day",
				attributes: {
						rel: "day",
						id : "new_" + $.password(8)
					}
				},
				 -1 
				);
		} );  
		jQuery('#tb-user .facelist-result-item').live('click', function(e) { 
			jQuery('#tb-user input').hide();
			jQuery('#tb-outline-chuser').show();
		} );
		jQuery('#tb-user .facelist-close').live('mousedown', function(e) { 
			jQuery('#tb-user input').show();
			jQuery('#tb-outline-chuser').hide();
			jQuery('#tb-user .facelist-values').hide();
		} );
		
		jQuery('#tb-tour li.facelist-original').live('focus', function(e) { 
			id = $('#tb-user input').last().attr('value') ; //siblings(':last').children(':last').attr('value')
			if ( id  != null ) {
				id = id.substring(0, id.length - 1);
			}
		} );
		jQuery('#tb-tour .facelist-result-item').live('click', function(e) { 
			jQuery('#tb-tour input').hide();
			jQuery('#tb-outline-ctrl').show();
			jQuery('#tb-outline-div').show();
			jQuery('#tb-drop-box').show();
		} );
		jQuery('#tb-tour2 .facelist-result-item').live('click', function(e) { 
			jQuery('#tb-tour2 input').hide();
			jQuery('#tb-reference-ctrl').show();
			jQuery('#tb-reference-div').show();
		} );
		jQuery('#tb-tour .facelist-close').live('mouseup', function(e) { 
			jQuery('#tb-tour input').show();
			jQuery('#tb-tour .facelist-values').hide();
			jQuery('#tb-drop-box').hide();
			jQuery('#tb-outline-div').hide();
		} );
		jQuery('#tb-tour2 .facelist-close').live('mouseup', function(e) { 
			jQuery('#tb-tour2 input').show();
			jQuery('#tb-tour2 .facelist-values').hide();
			jQuery('#tb-reference-div').hide();
		} );
		jQuery('#tb-utility-new-tour').live('click', function(e) { 
			userID = Triplite.getUserId();
			Triplite.newTour( userID, "#tb-outline", "0", 7 ); // send userID - wait tour & Tree it
		} );
		jQuery('#tb-utility-reindex-tours').live('click', function(e) { 
			$.ajax({
				type:		'POST',
				url:		'/tours/reindex'
			});
		} );
		jQuery('#tb-reference-copy').live('click', function(e) { 
			userId = Triplite.getUserId();
			tourId = Triplite.getReferenceTourId();
			Triplite.newTour( userId, "#tb-outline", tourId , 0 ); 
		} );   
		jQuery('#tb-outline-show').live('click', function(e) { 
			var id = Triplite.getOutlineTourId();
			$.fn.colorbox({href:"/tours/" + id , width: "60%", opacity: 0.8 });
		} );
		jQuery('#tb-outline-reload').live('click', function(e) { 
			var id = Triplite.getOutlineTourId();
			Triplite.getTour( id, '#tb-outline' );
		} );
		jQuery('#tb-reference-show').live('click', function(e) { 
			var id = Triplite.getReferenceTourId();
			$.fn.colorbox({href:"/tours/" + id , width: "60%", opacity: 0.8 });
		} );
		jQuery('#link-connections-list a[mode=forward]').live('click', function(e) { 
			var id = $( this ).parent().attr('id').replace(/[^0-9]/g, "");
			var mode = $( this ).parent().attr('id').replace(/[0-9_]/g, "");
			Triplite.applyRoute( id, mode, 'forward' );
			return false;
		} );
		jQuery('#link-connections-list a[mode=reverse]').live('click', function(e) { 
			var id = $( this ).parent().attr('id').replace(/[^0-9]/g, "");
			var mode = $( this ).parent().attr('id').replace(/[0-9_]/g, "");
			Triplite.applyRoute( id, mode, 'reverse' );
			return false;
		} );
		jQuery('ul#picked-suppliers a.apply').live('click', function(e) { 
			element = $( this );
			var id = element.attr('id');
			Triplite.applySupplier( id );
			return false;
		} );
	},
	applyRoute: function( id, mode, direction ){
		var reverse = ( direction == 'reverse' ) ? true : false;
		$('#destination').val( "(updated route)" );
		$('#component_connexion_id').val( id );
		$('#component_reverse').val( direction );
		$('#component_mode').val( mode );
		Triplite.getSuppliers( id );
	},
	applySupplier: function( id ){
		$('#component_supplier_id').val( id );
		$('#supplier').val( supplier );
	},	
	getSuppliers: function( id ){
		$.ajax({
			type:		'GET',
			url:		'/connexions/' + id + '/edit',
			data:		'no_show' 
		});
	},
	getOutlineTourId: function(){
		id_str = $('#tb-outline li[rel=tour]').attr('id');
		id = id_str.substring( 5, ( id_str.length ));
		return id;
	},
	getReferenceTourId: function(){
		id_str = $('#tb-reference li[rel=tour]').attr('id');
		id = id_str.substring( 5, ( id_str.length ));
		return id;
	},
	getUserId: function(){ 
		id_str = $('#tb-user input').last().attr('value');
		id = id_str.substring( 0, ( id_str.length - 1 ));
		return id;
	},
	addToTourSetUp: function(){
		jQuery('#sortable-triplite-items a.triplite').live('click', function(e) { 
			var name = this.rel + " " + this.name;
			if ( name.length > 23 )
				name = name.substring(0,22) + "..";
			$.tree.focused().create( {
				data: name ,
				attributes: {
						id : $.password(8) + '_basket_' + this.id,
						rel: "item",
						component_type: this.rel
					}
				}, -1 );
		} ); 
	},
	startImageDrop:  function(){
		$(function() {
			$("#tb-drop-box").droppable({
				accept: 'img.assetDrag',
				drop: function(event, ui) {
					$(this).addClass('ui-state-highlight').find('p').html('Dropped!');
					type = $( ui.draggable ).attr('id').replace( /[0-9_]/g, "" );
					target_object = Triplite.getTourTarget();
					target_id = target_object.replace( /[^0-9]/g, "" );
					target = target_object.replace( /[\d_]/g, "" );
					switch ( type ) {
						case 'asset' :
							Triplite.removeImageDropped( ui, target, target_id );
							break;
						default :
							Triplite.addImageDropped( ui, target, target_id );
							break;
					}
				}
			});
//			alert( $("#tb-drop-box").attr('id') );
		});
	},
	addImageDropped: function( ui, target, target_id ){
		image_id = $( ui.draggable ).attr('id').replace( /[^0-9]/g, "" );
//		alert( target_object );
		$.ajax({
			type:		'POST',
			url:		'/assets/create',
			dataType:	'html',
			data:		"image_id=" + image_id + "&target=" + target  + "&target_id=" + target_id,
			complete: 	function(html){
//				console.log(html);
					$('#tb-reference').html( html.responseText );
					$('#tb-reference-div').show();
			}
		});

	},
	removeImageDropped: function( ui, target, target_id ){
		element = $( ui.draggable );
		asset_id = element.attr('id').replace( /[^0-9]/g, "" );
		$.ajax({
			type:		'DELETE',
			url:		'/assets/' + asset_id,
			dataType:   'html',
			complete: 	function( html ){
				Utility.flash( html.responseText );
//				console.log(html);
				element.remove();
			}
		});

	},
	getTourTarget: function() {
//		target_id = $('#tb-outline *[rel^=day].clicked').first().parent().attr('id');
		selected = $('#tb-outline .clicked').first().parent();
		if ( selected.attr( 'rel' ) == 'day' ) {
			target_id = selected.attr('id');
		} else {
			target_id = $('*[rel=tour]').first().attr('id');
		};
//		console.log( target_id );
		return target_id;
	},
	startImageDrag:  function(){
		$(function() {
			$("#quick-search-display img").draggable({ revert: true, zIndex: 2700 }).addClass('assetDrag');
		});
	},
	sortableTourpad: function(){
		$(function() {
			$("#tourpad ul").sortable( {
				connectWith: '.tourpads',
				cancel: 'li.title',
				stop: function(event, ui) { 
				   	Triplite.updateTourpad(event, ui); 
				}
			}).disableSelection();
		});
	},                   //   .sortable( 'serialize' , [options] )
	sortableBasketItems: function(){
		$(function() {
			$("#sortable-triplite-items").sortable( {
				   stop: function(event, ui) { Triplite.updateBasketItems(event, ui); }
				});
//			$("#sortable-triplite-items").disableSelection();
		}).disableSelection();
	},                   //   .sortable( 'serialize' , [options] )
	sortableBasketTours: function(){
		$(function() {
			$("#sortable-triplite-tours").sortable( {
				   stop: function(event, ui) { Triplite.updateBasketTours(event, ui); }
				});
//			$("#sortable-triplite-tours").sortable();
//			$("#sortable-triplite-tours").disableSelection();
		}).disableSelection();
	},                   //   .sortable( 'serialize' , [options] )
	updateBasketLinks: function( event, ui ){
		$.ajax({
			type:		'POST',
			url:		'/triplites/sorted_links',
			data:		$('#sortable-triplite-links').sortable('serialize')
		});
	},
	updateTourpad: function( event, ui ){
//		console.log($('#tourpad ul#A').sortable('serialize').replace(/triplite/g,"A"));
//		console.log($('#tourpad ul#B').sortable('serialize').replace(/triplite/g,"B"));
//		console.log($('#tourpad ul#C').sortable('serialize').replace(/triplite/g,"C"));
//		console.log(ui);
		var data = $('#tourpad ul#A').sortable('serialize').replace(/triplite/g,"A");
		data += '&';
		data += $('#tourpad ul#B').sortable('serialize').replace(/triplite/g,"B");
		data += '&';
		data += $('#tourpad ul#C').sortable('serialize').replace(/triplite/g,"C");
		$.ajax({
			type:		'POST',
			url:		'/triplites/sorted_tourpads',
			data:		data
		});
	},
	addTourpad: function(id){
		$.ajax({
			type:		'GET',
			url:		'/triplites/add_tourpad/' + id
		});
	},
	getBasket: function( list_type ){
		$.ajax({
			type:		'GET',
			url:		'/triplites/index',
			data:		'list_type=' + list_type
		});
	},
	updateBasketItems: function( event, ui ){
		$.ajax({
			type:		'POST',
			url:		'/triplites/sorted_items',
			data:		$('#sortable-triplite-items').sortable('serialize')
		});
	},
	updateBasketTours: function( event, ui ){
		$.ajax({
			type:		'POST',
			url:		'/triplites/sorted_tours',
			data:		$('#sortable-triplite-tours').sortable('serialize')
		});
	},
	
	getTour : function( id, target ) {
		$element = this;
		$.ajax({
			type:		'GET',
			url:		'/tours/get_json/' + id,
			dataType:	'json',
			complete: 	function( json ){
				switch (target) {
					case '#tb-outline':
						Triplite.setupTourTree(JSON.parse(json.responseText), target);
						break;
					case '#tb-reference':
						Triplite.setupTourTree2(JSON.parse(json.responseText), target);
						break;
				}
			}
		});
	},
	newTour : function( userId, target, copyId, days ) {
		if ( Number(userId) == 0 ) userId = "0";
		$.ajax({
			type:		'POST',
			url:		'/tours/' + userId + '/create_json/',
			dataType:	'json',
			data:		"tourId=" + copyId + "&days=" + days ,
			complete: 	function( json ){
				$('#tb-outline-ctrl').show();
				Utility.flash( "Tour created" );
				switch (target) {
					case '#tb-outline':
						Triplite.setupTourTree(JSON.parse(json.responseText), target);
						break;
					case '#tb-reference':
						Triplite.setupTourTree2(JSON.parse(json.responseText), target);
						break;
				};
				jQuery('#tb-outline-ctrl').show();
				jQuery('#tb-outline-div').show();
			}
		});
	},
	
	setupTourTree : function( tourData, target ) {
		
		$("#tb-toolbar").show();
		$( target ).tree({
			data : { 
				type : "json",
				opts : {
					static : tourData
				}
			},
			plugins		: { 
				checkbox 		: { three_state : true },
				contextmenu: {
					items: {
						create : false,
						tb_view:{ 
							label   : "Views",
                        	icon    : "", // you can set this to a classname or a path to an icon like ./myimage.gif
	                        visible : function (NODE, TREE_OBJ) {
								if ( TREE_OBJ.get_type( NODE ) == 'item' ) return false;
	                            return true;
	                        },
	                        action  : function (NODE, TREE_OBJ) {
									$.ajax({
										type:		'GET',
										url:		"/views/" + $( NODE ).attr('id').replace(/[^0-9]/g, "") + "/display",
										data:		'type=' + TREE_OBJ.get_type( NODE )
									});
	                        },
	                        separator_before : false
						},
						tb_edit:{ 
							label   : "Editor",
                        	icon    : "", // you can set this to a classname or a path to an icon like ./myimage.gif
	                        visible : function (NODE, TREE_OBJ) {
	                            return 1;
	                        },
	                        action  : function (NODE, TREE_OBJ) {
								if ( TREE_OBJ.parent(NODE) == -1  && TREE_OBJ.get_type(NODE) != 'tour' ) {
									Utility.flash('Attached to Tour before edit')
									return false;
								};
								id_str = $( NODE ).attr('id');
								switch ( TREE_OBJ.get_type( NODE ) ) {
									case 'tour' :
										var id = id_str.substring( 5, ( id_str.length ));
										$.fn.colorbox({href:"/tours/" + id + "/edit_head", width: "60%" });
										break;
									case 'day' :
										var id = id_str.substring( 4, ( id_str.length ));
										$.fn.colorbox({href:"/days/" + id + "/tb_edit" });
										break;
									case 'item' :
										var id = id_str.substring( 5, ( id_str.length ));
										$.fn.colorbox({href:"/items/" + id + "/edit", height: 500 });
										break;
								}
	                        },
	                        separator_before : false
						},
						
						tb_show:{ 
							label   : "Quick View",
                        	icon    : "", // you can set this to a classname or a path to an icon like ./myimage.gif
	                        visible : function (NODE, TREE_OBJ) {
								if ( TREE_OBJ.get_type( NODE ) == 'tour' ) return false;
	                            return true;
	                        },
	                        action  : function (NODE, TREE_OBJ) {
								if ( TREE_OBJ.parent(NODE) == -1  && TREE_OBJ.get_type(NODE) != 'tour' ) {
									Utility.flash('Attached to Tour before edit')
									return false;
								};
								id_str = $( NODE ).attr('id');
								switch ( TREE_OBJ.get_type( NODE ) ) {
//									case 'tour' :
//										var id = id_str.substring( 5, ( id_str.length ));
//										$.fn.colorbox({href:"/tours/" + id + "/edit_head", width: "60%" });
//										break;
									case 'day' :
										var id = id_str.substring( 4, ( id_str.length ));
										$.ajax({
											type:		'GET',
											url:		"/days/" + id + "/tb_show",
											dataType:	'html',
											complete: 	function( data ){
//												console.log(data);
												$('#tb-reference').html( data.responseText );
											}
										});
										
										break;
									case 'item' :
										var id = id_str.substring( 5, ( id_str.length ));
										$.ajax({
											type:		'GET',
											url:		"/items/" + id + "/tb_show",
											dataType:	'html',
											complete: 	function( data ){
//												console.log(data);
												$('#tb-reference').html( data.responseText );
											}
										});
										break;
								}
	                        },
	                        separator_before : false
						},
						
//						rename : {
//							label	: "Change Title", 
//							icon	: "",
//							visible	: function (NODE, TREE_OBJ) { 
//								if(NODE.length != 1) return false; 
//								return TREE_OBJ.check("renameable", NODE); 
//							}, 
//							action	: function (NODE, TREE_OBJ) { 
//								if ( TREE_OBJ.parent(NODE) == -1 && TREE_OBJ.get_type(NODE) != 'tour' ) {
//									$('#flash').html('Attach to Tour before edit')
//									return false;
//								};
//								TREE_OBJ.rename(NODE); 
//								
//							},
//	                        separator_before : false 
//						},
						rename : false,
						remove : false
					}
				}
			},
			rules : {
				use_max_children : false,
				use_max_depth : true,
				max_depth: 3,
				multitree: "all"
			},
			types : {
				"tour" : {
					clickable	: true,
					renameable	: true,
					deletable	: true,
					creatable	: false,
					draggable	: false,
					max_children	: -1,
					max_depth	: -1,
					valid_children	: ["day"],
			
					icon : {
						image : false,
						position : false
					}
				},
				"day" : {
					clickable	: true,
					renameable	: true,
					deletable	: true,
					creatable	: true,
					draggable	: true,
					max_children	: -1,
					max_depth	: -1,
					valid_children	: ["item"],
			
					icon : {
						image : false,
						position : false
					}
				},
				"item" : {
					clickable	: true,
					renameable	: false,
					deletable	: true,
					creatable	: false,
					draggable	: true,
					max_children	: -1,
					max_depth	: -1,
					valid_children	: false,
					icon : {
						image : false,
						position : false
					}
				}
				
			}
			,
			callback : {
				beforecreate : function( NODE, REF_NODE, TYPE, TREE_OBJ ) { 
					return true;
				},
				beforemove : function( NODE, REF_NODE, TYPE, TREE_OBJ ) { 
					var children = TREE_OBJ.children(NODE);
//					if ( $.tree.reference('tb-outline') != $.tree.reference( NODE ) ) {
//						alert("From reference");
//					};
//					alert(TREE_OBJ.get_type( REF_NODE ) + " " + TYPE);
					switch ( TREE_OBJ.get_type( NODE ) ) {
						case 'day' :
							error_msg = "Days must be directly attached to the Tour";
							switch ( TREE_OBJ.get_type( REF_NODE ) ) {
								case 'tour' :
									if (TYPE != 'inside') {
										Utility.flash( error_msg );
										return false;
									}
									break;
								case 'day' :
									if ( TYPE == 'inside' ) {
										Utility.flash( error_msg );
										return false;
									};
									break;
								default :
									Utility.flash( error_msg );
									return false;
							};
							break;
						case 'item' :
							error_msg = "Items must be placed within a Day";
							switch ( TREE_OBJ.get_type( REF_NODE ) ) {
								case 'day' :
									if (TYPE != 'inside') {
										Utility.flash( error_msg );									
										return false;
									}
									break;
								case 'item' :
									if (TYPE == 'inside') {
										Utility.flash( error_msg );									
										return false;
									}
									break;
								default :
									Utility.flash( error_msg );									
									return false;
							};
							
							break;
					}
					return true;
				},
				onmove : function ( NODE, REF_NODE, TYPE, TREE_OBJ ) {
					Triplite.moveNode( NODE, REF_NODE, TYPE, TREE_OBJ );
					
				},
				oncopy : function(NODE, REF_NODE, TYPE, TREE_OBJ, RB) {
					Triplite.moveNode( NODE, REF_NODE, TYPE, TREE_OBJ );
				},
				onrename : function(NODE, TREE_OBJ, RB) { 
//					alert( "rename " + TREE_OBJ.get_type(NODE) + " " + TREE_OBJ.get_text( NODE) + " " + $(NODE).attr("id"));
					id_str = $(NODE).attr("id");
					name = TREE_OBJ.get_text( NODE );
					switch ( TREE_OBJ.get_type( NODE ) ) {
						case 'tour' :
							var id = id_str.substring( 5, ( id_str.length ));
							Triplite.renameTour( id, name );
							break;
						case 'day' :
							var id = id_str.substring( 4, ( id_str.length ));
							Triplite.renameDay( id, name );
							break;
					}

				 },
				onsearch : function (n,t) {
					t.container.find('.search').removeClass('search');
					n.addClass('search');
				},
			}
			}
		);
	},
	moveNode : function( NODE, REF_NODE, TYPE, TREE_OBJ ){
//		alert("move " + $(NODE ).parents('.tree').attr('id') + " NodeID " + $(NODE).attr("id") + " " + TYPE + " " + TREE_OBJ.get_type(REF_NODE) + " "
//				 + $(REF_NODE).attr("id")
//				 + " parent " + TREE_OBJ.parent( REF_NODE).attr("id") );
		id_str = $(NODE).attr("id");
		var id = $(NODE).attr("id");
		if ( id == "" ) id = "0";
		switch ( TREE_OBJ.get_type(NODE) ) {
			case 'day' :
				var tourId = TREE_OBJ.parent( REF_NODE).attr("id");
				var reference = $(REF_NODE).attr("id");
				var relation = TYPE;
				var name = TREE_OBJ.get_text(NODE)
				$.ajax({
					type:		'POST',
					url:		'/days/' + id + '/drag',
					data:		"tourId=" + tourId + "&reference=" + reference + "&relation=" + relation + "&name=" + name
				});
				break;
			case 'item' :
				var dayId = TREE_OBJ.parent( REF_NODE).attr("id");
				var reference = $(REF_NODE).attr("id");
				var dayId = ( TYPE == 'inside' ) ?  $( REF_NODE).attr("id") : TREE_OBJ.parent( REF_NODE).attr("id");
				var component = $(NODE).attr("component_type");
				var relation = TYPE;
				$.ajax({
					type:		'POST',
					url:		'/items/' + id + '/drag',
					data:		"dayId=" + dayId + "&reference=" + reference + "&relation=" + relation + "&component=" + component
				});
				break;
		};
				 
	},
	getTourHead : function( id ){
		$.ajax({
			type:		'GET',
			url:		'/tours/' + id + '/edit_head',
			dataType:	'html',
			complete: 	function( html ){
				$('#tb-reference').html( html.responseText );
			}
		});
	},
	getDay : function( id ){
		$.ajax({
			type:		'GET',
			url:		'/days/' + id + '/tb_edit',
			dataType:	'html',
			complete: 	function( html ){
//				console.log(html);
				$.fn.colorbox("woof");
//					$('#tb-reference').html( html.responseText );
//						$('#tb-reference').html( "Edit " + TREE_OBJ.get_type(NODE) );
			}
		});
	},
	getEditor : function (NODE, TREE_OBJ) { 
		$(NODE).colorbox({href:"/tours/" + id + "/edit_head", width: "60%", opacity: 0.85 });
	},
	copyDayItems : function (original, duplicate) {
		var children = $.tree.reference("#tb-outline").children( $( '#' + original ) );
		if ( children ) {
			$.each( children, function(){
				var item_id = $( this ).attr('id');
				var component = $( this ).attr("component_type");
				var relation = "inside";
				$.ajax({
					type:		'POST',
					url:		'/items/' + item_id + '_copy/drag',
					data:		"dayId=" + duplicate + "&reference=" + duplicate+ "&relation=" + relation + "&component=" + component
				});
			});
		};
	},
	getItem : function( id ){
		$.ajax({
			type:		'GET',
			url:		'/items/' + id + '/tb_edit',
			dataType:	'html',
			complete: 	function( html ){
//				console.log(html);
				$('#tb-reference').html( html.responseText );
			}
		});
	},
	renameTour : function( id, name ){
		$.ajax({
			type:		'POST',
			url:		'/tours/' + id + '/rename',
			data: 		'name=' + name 
		});
		
	},
	renameDay : function( id, name ){
		$.ajax({
			type:		'POST',
			url:		'/days/' + id + '/rename',
			data: 		'name=' + name 
		});
		
	},
	deleteTour: function( id ){
		$.ajax({
			type: 'DELETE',
			url: '/tours/' + id
		});
		
	},
	deleteDay: function( id ){
		$.ajax({
			type: 'DELETE',
			url: '/days/' + id
		});
		
	},
	deleteItem: function( id ){
		$.ajax({
			type: 'DELETE',
			url: '/items/' + id
		});
		
	},
	setupTourTree2 : function( tourData, target ) {
		$( target ).tree({
			data : { 
				type : "json",
				opts : {
					static : tourData
				}
			},
			plugins		: { 
				"checkbox" : { three_state : true } 
			},
			rules : {
				use_max_children : false,
				use_max_depth : true,
				max_depth: 3,
				multitree: "none",
				drag_copy : "on",
			},
			types : {
				"tour" : {
					clickable	: true,
					renameable	: false,
					deletable	: false,
					creatable	: false,
					draggable	: false,
					max_children	: -1,
					max_depth	: -1,
					valid_children	: ["day"],
			
					icon : {
						image : false,
						position : false
					}
				},
				"day" : {
					clickable	: true,
					renameable	: false,
					deletable	: false,
					creatable	: false,
					draggable	: true,
					max_children	: -1,
					max_depth	: -1,
					valid_children	: ["item"],
			
					icon : {
						image : false,
						position : false
					}
				},
				"item" : {
					clickable	: true,
					renameable	: false,
					deletable	: false,
					creatable	: false,
					draggable	: true,
					max_children	: -1,
					max_depth	: -1,
					valid_children	: false,
					icon : {
						image : false,
						position : false
					}
				}
				
			}
			,
			callback : {
				beforemove : function ( NODE, REF_NODE, TYPE, TREE_OBJ ) {
					return false;
				},
				beforecopy : function(NODE, REF_NODE, TYPE, TREE_OBJ, RB) {
					return false;
				},
				onsearch : function (n,t) {
//						$.tree.focused().close_all( $('attr[rel=day]' ) );
					t.container.find('.search').removeClass('search');
					n.addClass('search');
//						$.tree.focused().open_all( n );
				},
				ondelete  : function(NODE, TREE_OBJ, RB) { 
					id_str = $(NODE).attr("id");
					name = TREE_OBJ.get_type( NODE );
					switch ( TREE_OBJ.get_type( NODE ) ) {
						case 'tour' :
							var id = id_str.substring( 5, ( id_str.length ));
							Triplite.deleteTour( id );
							break;
						case 'day' :
							var id = id_str.substring( 4, ( id_str.length ));
							Triplite.deleteDay( id );
							break;
						case 'item' :
							var id = id_str.substring( 5, ( id_str.length ));
							Triplite.deleteItem( id );
							break;
					}

				 }
			}
		}
		);
	},
	setupSamples : function() {
//		alert("Hello");
		Triplite.setupSampleTree( '#tb-sample-tree' );
		var tree = $.tree.reference("#tb-sample-tree");
		if (tree) {
			tree.open_branch('#open-tour');
			tree.open_branch('#open-item');
		}
	},
	setupSamplebasket: function(target){
		
	},
	setupSampleTree : function( target ) {
		$( target ).tree({
			data: {
				type: "json",
				opts: {
					static: [{
						// Tour
						data: {
							title: "My Tour to Africa",
							attributes: {
								"id": "open-tour",
								"rel": "tour",
								"body": "Some introductory text"
							}
						},
						// Days
						children: [
							{
								data: {
									title: "Day 1: Depart UK",
									attributes: {
										"rel": "day",
										"body": "Some introductory text"
									}
								}, // Items
								children: [{
									data: {
										title: "Flight to Nairobi",
										attributes: {
											"rel": "item",
											"component_type": "flight",
											"body": "British Airways BA 101"
										}
									}
								}] // ends items
							},
							{
								data: {
									title: "Day 2: Arrive Nairobi",
									attributes: {
										"id" : "open-item",
										"rel": "day",
										"body": "Some introductory text"
									}
								}, // Items
								children: [{
										data: {
											title: "Transfer: Masai Mara",
											attributes: {
												"rel": "item",
												"component_type": "transfer",
												"body": "Drive to Game Reserve"
											}
										}
									},
									{
										data: {
											title: "Richards Camp",
											attributes: {
												"rel": "item",
												"component_type": "stay",
												"body": "At the Camp"
											}
										}
									},
									{
										data: {
											title: "Game Viewing",
											attributes: {
												"rel": "item",
												"component_type": "activity",
												"body": "..."
											}
										}
									}] // ends items
							},
							{
								data: {
									title: "Day 3: Full Day on Mara",
									attributes: {
										"rel": "day",
										"body": "..."
									}
								}, // Items
								children: [{
										data: {
											title: "Game Viewing",
											attributes: {
												"rel": "item",
												"component_type": "activity",
												"body": "At the Camp"
											}
										}
								}] // ends items
							},
							{
								data: {
									title: "Day 4: Great Rift Valley",
									attributes: {
										"rel": "day",
										"body": "..."
									}
								}, // Items
								children: [{
									data: {
										title: "Transfer Lake Naivasha",
										attributes: {
											"rel": "item",
											"component_type": "stay",
											"body": "...."
										}
									}
								},
									{
									data: {
										title: "Rift Valley Lodge",
										attributes: {
											"rel": "item",
											"component_type": "stay",
											"body": "...."
										}
									}
								}] // ends items
							},
							{
								data: {
									title: "Day 5: Visit Lake Nakuru",
									attributes: {
										"rel": "day",
										"body": "Some introductory text"
									}
								}, // Items
								children: [{
									data: {
										title: "Lake Nakuru",
										attributes: {
											"rel": "item",
											"component_type": "activity",
											"body": "..."
										}
									}
								}] // ends items
							}] // ends days 
					}]  // ends STATIC 
				}
			},
			plugins		: { 
				"checkbox" : { three_state : true } 
			},
			rules : {
				use_max_children : false,
				use_max_depth : true,
				max_depth: 3,
				multitree: "all"
			},
			types : {
				"tour" : {
					clickable	: true,
					renameable	: true,
					deletable	: true,
					creatable	: false,
					draggable	: false,
					max_children	: -1,
					max_depth	: -1,
					valid_children	: ["day"],
			
					icon : {
						image : false,
						position : false
					}
				},
				"day" : {
					clickable	: true,
					renameable	: true,
					deletable	: true,
					creatable	: true,
					draggable	: true,
					max_children	: -1,
					max_depth	: -1,
					valid_children	: ["item"],
			
					icon : {
						image : false,
						position : false
					}
				},
				"item" : {
					clickable	: true,
					renameable	: false,
					deletable	: true,
					creatable	: false,
					draggable	: true,
					max_children	: -1,
					max_depth	: -1,
					valid_children	: false,
					icon : {
						image : false,
						position : false
					}
				}
				
			}
		});
	}
	

}


var Data = {
	sampleTree: {
		data : { 
			type : "json",
			opts : {
				static : [
					{ 
						// the short format demo
						data : "A node", 
						// here are the children
						children : [
							{ data : "Child node 1" },
							{ data : "Child node 2" },
							{ data : "Child node 3" }
						]
					},
					{ 
						attributes : { "id" : "li.node.id" }, 
						// this is the long data format
						data : { 
							title : "Long format demo", 
							attributes : { "href" : "http://jstree.com" } 
						} 
					}
				]
			}
		}
	}
}

var Sundry = {
	Puzzle: function(){
		this.moves = 0;
		this.p = jQuery('#puzzle');
		this.info =  jQuery('#puzzleinfo');
		this.p.sortable();
		var puzzle = this;
		
		this.init = function(){
			this.p.bind('sortstop', function(event, ui){
//				console.log(puzzle.p.sortable('toArray'));
//				alert( puzzle.p.sortable('serialize') );
				puzzle.drop();
			});
		};
		this.getMoves = function(){
			return this.moves;
		};
		this.drop = function(){
			this.moves++;
			this.info.html('You have made ' + this.moves + ' moves' );
		}
	},
	componentWidget: function(){	
		jQuery('#component-index input').live('click', function(e) { 
			className = $( this ).attr('class');
		    Utility.makeSelected( this );
			switch ( className ) {
				case 'Tour' :
					msg = "Tailormade Tours";
					break;
				case 'Airport' :
					msg = "Flight Connections";
					break;
				case 'Drive' :
					msg = "Self-Drive Routes &amp; Car Hire";
					break;
				case 'Location' :
					msg = "Destination Guide";
					break;
				case 'Stay' :
					msg = "Accommodation Choices";
					break;
				case 'Reserve' :
					msg = "Wildlife Reserves";
					break;
				case 'Activity' :
					msg = "Recommended Excursions";
					break;
				case 'Event' :
					msg = "Festivals &amp; Events";
					break;
				case 'Round' :
					msg = "Golfing Holidays";
					break;
				case 'Climate' :
					msg = "Climate Information";
					break;
				case 'Practical' :
					msg = "Red Tape, Money & Health";
					break;
				case 'Sports' :
					msg = "Sports Tours";
					break;
				default :
					msg = "";
			};
			$('#component-banner').html( msg ).show()   //.effect( "fade", {}, 3000 );
		} );
	},
	initAssetImages:  function(){
		$(function() {
//			$("#asset-images img").draggable({ revert: true, zIndex: 2700 }).addClass('assetDrag');
			Sundry.setAssetSortable();
			$('#assetSortToggle').live( 'click', function( e ){ 
				if ( $('#assetSortToggle').attr('checked') ) {
					Sundry.setAssetSortable();
				} else {
					Sundry.setAssetDraggable();
				};
			} );
		});
	},
	setAssetSortable:   function(){
		$("#asset-images img").draggable("destroy");		
		$("#asset-images").sortable( {
			stop: function(event, ui) {
				Sundry.updateAssetImagePositions();
			 }
		});
	},
	setAssetDraggable:   function(){
		$("#asset-images").sortable( "destroy" );
		$("#asset-images img").draggable({ revert: true, zIndex: 2700 }).addClass('assetDrag');
	},
	updateAssetImagePositions:  function( event, ui ){
		$.ajax({
			type:		'POST',
			url:		'/assets/sorted',
			dataType:	'json',
			data:		$('#asset-images').sortable('serialize')
		});			
	},

}

//function Puzzle(){
//	p = jQuery('#puzzle');
//	info = jQuery('#puzzleinfo');
//	moves = 0;
//	
//	p.sortable({
//		stop: function() { moves++; info.html("You have made " + moves + " moves") }
//	});
//	p.disableSelection();
//	
//}
//		puzzleDrop: function() {
//			alert("Woof");
//		}

//
