/*
Jquery and Rails powered default application.js
Easy Ajax replacement for remote_functions and ajax_form based on class name
All actions will reply to the .js format
Unostrusive, will only works if Javascript enabled, if not, respond to an HTML as a normal link
respond_to do |format|
	format.html
	format.js {render :layout => false}
end
*/

jQuery.ajaxSetup({ 'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript");} });

function _ajax_request(url, data, callback, type, method) {
		if (jQuery.isFunction(data)) {
				callback = data;
				data = {};
		}
		return jQuery.ajax({
				type: method,
				url: url,
				data: data,
				success: callback,
				dataType: type
				});
}

jQuery.extend({
		put: function(url, data, callback, type) {
				return _ajax_request(url, data, callback, type, 'PUT');
		},
		delete_: function(url, data, callback, type) {
				return _ajax_request(url, data, callback, type, 'DELETE');
		}
});

/*
Submit a form with Ajax
Use the class ajaxForm in your form declaration
<% form_for @comment,:html => {:class => "ajaxForm"} do |f| -%>
*/
jQuery.fn.submitWithAjax = function() {
	this.unbind('submit', false);
	this.submit(function() {
		$.post(this.action, $(this).serialize(), null, "script");
		return false;
	});

	return this;
};

/*
Retreive a page with get
Use the class get in your link declaration
<%= link_to 'My link', my_path(),:class => "get" %>
*/
jQuery.fn.getWithAjax = function() {
	this.unbind('click', false);
	this.click(function() {
		$.get($(this).attr("href"), $(this).serialize(), null, "script");
		return false;
	});
	return this;
};

/*
Post data via html
Use the class post in your link declaration
<%= link_to 'My link', my_new_path(),:class => "post" %>
*/
jQuery.fn.postWithAjax = function() {
	this.unbind('click', false);
	this.click(function() {
		$.post($(this).attr("href"), $(this).serialize(), null, "script");
		return false;
	});
	return this;
};

/*
Update/Put data via html
Use the class put in your link declaration
<%= link_to 'My link', my_update_path(data),:class => "put",:method => :put %>
*/
jQuery.fn.putWithAjax = function() {
	this.unbind('click', false);
	this.click(function() {
		$.put($(this).attr("href"), $(this).serialize(), null, "script");
		return false;
	});
	return this;
};

/*
Delete data
Use the class delete in your link declaration
<%= link_to 'My link', my_destroy_path(data),:class => "delete",:method => :delete %>
*/
jQuery.fn.deleteWithAjax = function() {
	this.removeAttr('onclick');
	this.unbind('click', false);
	this.click(function() {
		$.delete_($(this).attr("href"), $(this).serialize(), null, "script");
		return false;
	});
	return this;
};

/*
Ajaxify all the links on the page.
This function is called when the page is loaded. You'll probaly need to call it again when you write render new datas that need to be ajaxyfied.'
*/
function ajaxLinks(){
		$('.ajaxForm').submitWithAjax();
		$('a.get').getWithAjax();
		$('a.post').postWithAjax();
		$('a.put').putWithAjax();
		$('a.delete').deleteWithAjax();
}

$(document).ready(function() {
// All non-GET requests will add the authenticity token
 $(document).ajaxSend(function(event, request, settings) {
			 if (typeof(window.AUTH_TOKEN) == "undefined") return;
			 // IE6 fix for http://dev.jquery.com/ticket/3155
			 if (settings.type == 'GET' || settings.type == 'get') return;

			 settings.data = settings.data || "";
			 settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(window.AUTH_TOKEN);
		 });

	ajaxLinks();
});




/*
User Scripts
*/

$(document).ready(function() {
	var locale = '';
	if ($('body').hasClass('de-DE')) {
		locale = 'de';
	} else if ($('body').hasClass('en-US')) {
		locale = 'en';
	} else if ($('body').hasClass('fr-FR')) {
		locale = 'fr';
	} else {
		locale = 'de';
	};
	
	// #flash highlighten und ausblenden
	setTimeout(function() {
		$('#flash').fadeOut(2000);
	}, 1000);
	
	// toggle Zwischenstops
	var $rides_table = $('#ride_list');
	var $highlighted_rows = null;
	if ($rides_table.length) {
		$highlighted_rows = $('tr.highlight', $rides_table[0]);
		if ($highlighted_rows.length) {
			$('th.stops', $rides_table[0]).addClass('expanded');
			$('td.stops', $highlighted_rows).addClass('expanded');
		};

		$('th.stops .show', $rides_table[0]).click(function() {
			$('.stops', $rides_table[0]).addClass('expanded');
		});
		$('th.stops .hide', $rides_table[0]).click(function() {
			$('.stops', $rides_table[0]).removeClass('expanded');
		});

		$('td.stops .show', $rides_table[0]).click(function() {
			var $this = $(this);
			$this.parents('td').addClass('expanded');
			if ($('td.expanded', $rides_table[0]).length > 0) {
				$('th.stops', $rides_table[0]).addClass('expanded');
			};
		});
		$('td.stops .hide', $rides_table[0]).click(function() {
			var $this = $(this);
			$this.parents('td').removeClass('expanded');
			if ($('td.expanded', $rides_table[0]).length <= 0) {
				$('th.stops', $rides_table[0]).removeClass('expanded');
			};
		});
	};

	// location autocomplete
	$(".location input").autocomplete('/rides/locations');
	
	// Datepicker
	$(".time input").datepicker();
	
	// update number of seats
	var $update_number_of_seats = $('td form.edit_ride');
	if ($update_number_of_seats.length) {
		$('input[type="submit"]', $update_number_of_seats).hide();
		$('select', $update_number_of_seats).change(function() {
			$(this).parents('form').submit();
		});
	};

    // toggle ride_request_comment rows by click
    $(".ride_request_comment_row").prev().find("img").click(function() {
        $(this).toggle().siblings("img:first").toggle();
        $(this).parents("tr:first").next().toggle();
    });
	
	// create and edit rides form funcionality
	if ($('.ride_form form.new_ride, .ride_form form.edit_ride').length) {
		var $locations = $('fieldset.location p');
		var $empty_locations = null;
		var city_of_departure = {
			de: 'Abfahrtsort',
			en: 'City of Departure',
			fr: 'Lieu de départ'
		};
		var stopover = {
			de: 'Zwischenstop',
			en: 'Stopover',
			fr: 'Escale'
		};
		var destination = {
			de: 'Zielort',
			en: 'Destination',
			fr: 'Lieu de destination'
		};
		
		var init_empty_locations = function(){
			$empty_locations = $('fieldset.location p input[value=""]').parent();

			var start = ($empty_locations.length == $locations.length) ? 2 : 0;
			for (var i=start; i < $empty_locations.length; i++) {
				$($empty_locations[i]).addClass('empty').appendTo('fieldset.location');
			};
			
			$empty_locations = $('fieldset.location p.empty');
			
			// if ($empty_locations.length == 0) {
			// 	$('.add_stop').hide();
			// };
			
			update_positions();
			// console.log('init empty locations');
		};
		var update_empty_locations = function(){
			$empty_locations = $('fieldset.location p.empty');
			$empty_locations.appendTo('fieldset.location');
			// if ($empty_locations.length == 0) {
			// 	$('.add_stop').hide();
			// };
			update_positions();
			// console.log('update empty locations');
		};
		var update_positions = function(){
			$locations = $('fieldset.location p');
			var $last_visible_location = $('fieldset.location p:visible:last');
			var number_of_locations = $('fieldset.location p:visible').length;
			$locations.removeClass('last');
			$last_visible_location.addClass('last');
			$locations.find('label').text(stopover[locale]);
			$($locations[0]).find('label').text(city_of_departure[locale]);
			$last_visible_location.find('label').text(destination[locale]);
			// console.log('visible items: '+number_of_locations);
			if (number_of_locations <= 2) {
				$('fieldset.location').addClass('min');
			} else {
				$('fieldset.location').removeClass('min');
			};
			if (number_of_locations >= 8) {
				$('fieldset.location').addClass('max');
			} else {
				$('fieldset.location').removeClass('max');
			};
			$locations.each(function(index) {
				var $this = $(this);
				$this.attr('id', 'location_'+index);
				$('input', this).attr({
					// value: 'ride[ride_locations]['+index+'][title]',
					// id: 'ride_ride_locations_'+index+'_title',
					name: 'ride[ride_locations]['+index+'][title]'
				});
				$('label', this).attr('for', 'ride_ride_locations_'+index+'_title');
			});
			// console.log('update positions');
		};
		var add_location = function($e){
			var $location = $($empty_locations[0]);
			$e.after($location);
			$location.removeClass('empty');
			update_empty_locations();
			update_positions();
			// console.log('added location');
		};
		var remove_location = function($e){
			$e.addClass('empty');
			$('input', $e).val('');
			// console.log('removed location');
			update_empty_locations();
			update_positions();
		};
		
		
		init_empty_locations();
		
		// hide empty location fields
		
		// sort
		$locations.prepend('<a class="sort" href="#"><img alt="Sort" src="/images/icons/arrow_up_down.png" width="16" height="16" /></a>');
		$('fieldset.location p .sort').live('click', function(){
			return false;
		});
		$('fieldset.location').sortable( {
			axis: 'y',
			handle: '.sort',
			containment: 'parent',
			update: function(e, ui) {
				update_positions();
				// $('fieldset.location p .add_stop').show();
			},
			sort: function(e, ui) {
				// $('fieldset.location p .add_stop').hide();
			}
		});

		// add locations
		$locations.append('<a class="add_stop" href="#"><img alt="Edit" src="/images/icons/add.png" width="16" height="16" /></a><a class="remove_stop" href="#"><img alt="Remove" src="/images/icons/delete.png" width="16" height="16" /></a>');
		$locations.find('.add_stop').click(function() {
			var $e = $(this).parent();
			add_location($e);
			return false;
		});
		$locations.find('.remove_stop').click(function() {
			var $e = $(this).parent();
			remove_location($e);
			return false;
		});
	};
});