//===================================================
//===================================================

// When I say html I really mean script for rails
$.ajaxSettings.accepts.html = $.ajaxSettings.accepts.script;

// Always send the authenticity_token with ajax
$(document).ajaxSend(function(event, request, settings) {
    if (settings.type == 'post') {
        settings.data = (settings.data ? settings.data + '&' : '') + 'authenticity_token=' + encodeURIComponent( AUTH_TOKEN );
        request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    }
});

//===================================================
//===================================================

// Show the error or notice feedback div w appropriate message
function showFeedback(data, textStatus) {
	var tmp = data.split('[::]');
	var type = tmp[0];
	var msg = tmp[1];
	var delay = tmp[2] || 4000;
	var fadeout = tmp[3] || 3000;
	var id = 'flash_' + type;
	if (msg != 'data_exists') $('#' + id).html(msg)
	$('#' + id).slideDown().delay(delay).fadeOut(fadeout);
}

//===================================================
//===================================================

$(function() {
	
	// ===============
	// = APPLICATION =
	// ===============
	
	// Display feedback divs if their content is not empty
	if ($('#flash_notice').html() != '') showFeedback('notice[::]data_exists')
	if ($('#flash_error').html() != '') showFeedback('error[::]data_exists')
	
	// Setup tooltips
	$(".tooltip").tooltip({ 
		delay: 400,
		bodyHandler: function() {
			return $(this).attr("tooltip");
		}, 
		showURL: false,
		degrade: true
	});
	
	// ==============
	// = BRIEFCASES =
	// ==============
	
	$('input.star').rating({
		required: true,
		callback: function(value) {
			var tmp = $(this).attr('name').split('-');
			var item_id = tmp[1];
			var url = $('#briefcases_url').attr('value') + '/update_item/' + item_id + '?rating=' + value;
			$.ajax({url: url, type: 'post', dataType: 'html', success: showFeedback});
		}
	});
	
	// $('.editable').inlineEdit({
	// 	control: 'textarea',
	// 	save: function(e, data) {
	// 		var tmp = $(this).attr('name').split('-');
	// 		var item_id = tmp[1];
	// 		var val = data.value.replace(')', '');
	// 		val = val.replace('=', '');
	// 		val = val.replace('+', '');
	// 		val = val.replace('}', '');
	// 		val = val.replace('{', '');
	// 		val = val.replace('[', '');
	// 		val = val.replace(']', '');
	// 		var url = $('#briefcases_url').attr('value') + '/update_item/' + item_id + '?notes=' + val;
	// 		$.ajax({url: url, type: 'post', dataType: 'html', success: showFeedback});
	//     	}
	// });
	
	$('.editable').editInPlace({
		callback: function(element_id, enteredText) {
			var item_id = element_id.split('-')[1];
			var url = $('#briefcases_url').attr('value') + '/update_item/' + item_id + '?notes=' + enteredText;
			$.ajax({url: url, type: 'post', dataType: 'html', success: showFeedback});
			return enteredText;
		},
		bg_over: "#cff",
		field_type: "textarea",
		textarea_rows: "10",
		textarea_cols: "35"
	});
	$('editable').click(function(){ alert("hello!"); });
	//alert('hello');
	
	// Add all results to a briefcase (AJAX)
	$('#briefcase_add_all').click(function() {
		$('.icon_briefcase_add').hide('slow');
		var briefcase_id = $('#briefcase_id').attr('value');
		var briefcases_url = $('#briefcases_url').attr('value');
		var url = briefcases_url + '/' + briefcase_id + '/add_all';
		$.ajax({url: url, type: 'post', dataType: 'html', success: showFeedback});
	});
	
	// Add a single briefcase item (AJAX)
	$('.icon_briefcase_add').click(function() {
		$(this).hide('slow');
		var project_id = $(this).attr('name');
		var briefcase_id = $('#briefcase_id').attr('value');
		var briefcases_url = $('#briefcases_url').attr('value');
		var url = briefcases_url + '/' + briefcase_id + '/add_item/' + project_id;
		$.ajax({url: url, type: 'post', dataType: 'html', success: showFeedback});
	});
	
	// Remove a single item from a briefcase (HTTP)
	$('.icon_briefcase_remove').click(function() {
		$(this).hide('slow');
		var project_id = $(this).attr('name');
		var briefcase_id = $('#briefcase_id').attr('value');
		var briefcases_url = $('#briefcases_url').attr('value');
		var url = briefcases_url + '/' + briefcase_id + '/remove_item/' + project_id;
		window.location.replace(url);
	});
	
	// Remove all items from a briefcase (HTTP)
	$('#briefcase_remove_all').click(function() {
		if (confirm('Are you sure you want to remove all items from this briefcase?')) {
			$('.icon_briefcase_remove').hide('slow');
			var briefcase_id = $('#briefcase_id').attr('value');
			var briefcases_url = $('#briefcases_url').attr('value');
			var url = briefcases_url + '/' + briefcase_id + '/remove_all';
			window.location.replace(url);
		}
	});
	
	// ================
	// = Autocomplete =
	// ================
	var search_autocomplete_url = $('#root_url').attr('value') + 'browse/search_autocomplete';
	$('#searchbox').autocomplete(search_autocomplete_url, {
		width: 200,
		selectFirst: false
	});
	
	// ==============
	// = FANCYOXES (keep last) =
	// ==============
	
	// Setup fancyboxes
	$('.abstract_link a').fancybox({
		'hideOnOverlayClick': false,
		'hideOnContentClick': false
	});
	
	//No callbacks for Chrome, Safari, IE6 since it breaks
	if (($.browser.webkit) || ($.browser.msie && $.browser.version=="6.0")) {
		// $('.popup').fancybox({
		// 	'hideOnContentClick': false
		// });
		// $('.popup2').fancybox({
		// 	'frameWidth': 800,
		// 	'frameHeight': 500,
		// 	'hideOnContentClick': false
		// });
		$('.popup').fancybox({
			'hideOnContentClick': false,
			'hideOnOverlayClick': false
		});
		$('.popup2').fancybox({
			'hideOnContentClick': false,
			'hideOnOverlayClick': false		
		});
	} else {
		$('.popup').fancybox({
			'hideOnContentClick': false,
			'hideOnOverlayClick': false,
			'callbackOnShow': function() {
				$('.focus').focus();
				$(".tooltip").tooltip({ 
					delay: 400,
					bodyHandler: function() { return $(this).attr("tooltip"); }, 
					showURL: false,
					degrade: true
				});
			}
		});
		$('.popup2').fancybox({
			'frameWidth': 800,
			'frameHeight': 500,
			'hideOnContentClick': false,
			'hideOnOverlayClick': false,
			'callbackOnShow': function() {
				$(".tooltip").tooltip({ 
					delay: 400,
					bodyHandler: function() { return $(this).attr("tooltip"); }, 
					showURL: false,
					degrade: true
				});
			}
		});
	}
	
});