// functions for Destination Finder
var destFuncs = {
	init: function() {
		destFuncs.ajaxCall(
			'', 
			function(res){
					$("#from-wrap").html('<select id="from">'+res+'</select>');
					// note: change event needs patch in jqTransform class!
					$('#from').change(destFuncs.departureObserver);
					});
		$('.more-destination').click(function() {
			var dest = $('#from').find('option:selected').val();
			if (dest) destFuncs.ajaxCall(
				'action=route&from=' + dest + '&to=',
				function(res){
						$(".col2").html(res);
						destFuncs.init_table();
				});
			$("#smallmap").show();
			return false;
		});
		// hide helper div for table sorting
		$('#fancy_wrap').css('display', 'none');
	},
	
	departureObserver: function(evt) {
		var dept = $(this).val();
		if (!dept) {
			$('#step2').css('display', 'none');
			return;
		}
		// load destinations pulldown
		$('#to-wrap').html='Loading...';
		var zIndex = $('#to-wrap').find('div').css('z-index');
		destFuncs.ajaxCall(
			'action=destinations&from='+dept, 
			function(res){
						$("#to-wrap").html('<select id="to">'+res+'</select>');
						$('#to').change(destFuncs.destinationObserver);
						// fix: restore z-index
						$('#to-wrap').find('div').css('z-index', zIndex);
						// some display stuff
						$('#step2').css('display', 'block');
						var departure = $('#from').find('option:selected').text(); // departure place
						$('.more-destination').text('View all possible destinations from ' + departure);
					});
	},

	destinationObserver: function(evt) {
		var dest = $(this).val();
		//console.log(dest);
		destFuncs.ajaxCall(
			'action=route&from=' + $('#from').find('option:selected').val() + '&to=' + dest,
			function(res){
						$(".col2").html(res);
						$("#smallmap").show();
						destFuncs.init_table();
					});
	},

	ajaxCall: function(params, callback) {
		$.ajax({
					type: 'GET',
					url: '/app/destinations.php', // FIXME
					data: params,
					dataType: 'html',
					success: callback,
					error: function(xhr, txt, err) {
						if (!txt) txt = err;
						$("#error").html('Error: ' + txt).addClass('error').removeClass('invisible');
					}
				});
	},
	
	// http://net.tutsplus.com/tutorials/javascript-ajax/using-jquery-to-manipulate-and-filter-data/
	init_table: function() {
		destFuncs.zebraRows('tr:odd td', 'odd');
		
		$('tbody tr').hover(function(){
		  $(this).find('td').addClass('hovered');
		}, function(){
		  $(this).find('td').removeClass('hovered');
		});
		
		//default each row to visible
		$('tbody tr').addClass('visible');
		
		//overrides CSS display:none property
		//so only users w/ JS will see the
		//filter box
		$('#search').show();
		
		$('#filter').keyup(function(event) {
			//if esc is pressed or nothing is entered
	    if (event.keyCode == 27 || $(this).val() == '') {
				//if esc is pressed we want to clear the value of search box
				$(this).val('');
				
				//we want each row to be visible because if nothing
				//is entered then all rows are matched.
	      $('tbody tr').removeClass('visible').show().addClass('visible');
	    }
	
			//if there is text, lets filter
			else {
	      destFuncs.filter('tbody tr', $(this).val());
	    }
	
			//reapply zebra rows
			$('.visible td').removeClass('odd');
			destFuncs.zebraRows('.visible:even td', 'odd');
		});
		
		//grab all header rows
		$('thead th').each(function(column) {
			$(this).addClass('sortable')
						.click(function(){
							var findSortKey = function($cell) {
								return $cell.find('.sort-key').text().toUpperCase() + ' ' + $cell.text().toUpperCase();
							};
							
							var sortDirection = $(this).is('.sorted-asc') ? -1 : 1;
							
							//step back up the tree and get the rows with data
							//for sorting
							var $rows		= $(this).parent()
																	.parent()
																	.parent()
																	.find('tbody tr')
																	.get();
							
							//loop through all the rows and find 
							$.each($rows, function(index, row) {
								row.sortKey = findSortKey($(row).children('td').eq(column));
							});
							
							//compare and sort the rows alphabetically
							$rows.sort(function(a, b) {
								if (a.sortKey < b.sortKey) return -sortDirection;
								if (a.sortKey > b.sortKey) return sortDirection;
								return 0;
							});
							
							//add the rows in the correct order to the bottom of the table
							$.each($rows, function(index, row) {
								$('tbody').append(row);
								row.sortKey = null;
							});
							
							//identify the column sort order
							$('th').removeClass('sorted-asc sorted-desc');
							var $sortHead = $('th').filter(':nth-child(' + (column + 1) + ')');
							sortDirection == 1 ? $sortHead.addClass('sorted-asc') : $sortHead.addClass('sorted-desc');
							
							//identify the column to be sorted by
							$('td').removeClass('sorted')
										.filter(':nth-child(' + (column + 1) + ')')
										.addClass('sorted');
							
							$('.visible td').removeClass('odd');
							destFuncs.zebraRows('.visible:even td', 'odd');
						});
		});
	},
	
	//used to apply alternating row styles
	zebraRows: function(selector, className)
	{
		$(selector).removeClass(className)
								.addClass(className);
	},

	//filter results based on query
	filter: function(selector, query) {
		query	=	$.trim(query); //trim white space
	  query = query.replace(/ /gi, '|'); //add OR for regex
	  
	  $(selector).each(function() {
	    ($(this).text().search(new RegExp(query, "i")) < 0) ? $(this).hide().removeClass('visible') : $(this).show().addClass('visible');
	  });
	}
};

$(document).ready(function() { destFuncs.init(); });






