/**
 * Activate help bubble - uses the jquery "beauty tips" plugin
 */
var init_help_bubble = function () {
	/*$('.help_bubble_img').bt({		
		fill: 'rgba(242,242,242,1.0)'
	});*/
	
	$('.help_bubble_img').click(function (e) {
		e.stopPropagation();
		e.preventDefault();
		
		$('<div></div>').html($(this).attr('data-content')).dialog({
			modal: true,
			buttons: {"Ok" : function () { $(this).dialog('close'); } }
		});
		
		return false;
	});
};

/**
 * Activate the search box in the header of the front end website
 */
var init_search_box = function () {
	var form = $('form#global-search-form');
	if (!form) {
		return;
	}
	
	// On change
	$('select[name="type"]', form).change(function () {
		switch ($(this).val()) {
			/*
			case 'events' : 
				window.location.href = '/events'; 
			break;
			case 'results' : 
				window.location.href = '/results'; 
			break;
			*/
			case 'rankings' : 
				window.location.href = '/ranking'; 
			break;
		}
	});
	form.submit(function(){
		switch ( $(this).find('select').val() ){
			case 'articles':
				return true;
			break;
		
			case 'events':
				if ( $(this).find('input').val() != '' ){
					window.location.href = '/events?keywords=' + $(this).find('input').val();
				}
				return false;
			break;
			
			case 'results':
				if ( $(this).find('input').val() != '' ){
					window.location.href = '/events/results?keywords=' + $(this).find('input').val();
				}
				return false;
			break;
			
			case 'rankings':
				window.location.href = '/ranking';
			break;
		}
				
	});
};

/**
 * Activate jqueryui datepicker
 */
var init_jqueryui_datepicker = function () {
	var default_options = {
		//altFormat: 'yy-mm-dd', // The format that is sent to the server (Requires "altField" to be set - easier to do the conversion server side)
		changeMonth: true,
		changeYear: true,
		dateFormat: 'dd/mm/yy', // The format of date displayed to the user
		defaultDate: null, // Start from today
		duration: 'fast', // How fast the datepicker appears
		firstDay: 0, // First day of the week is Sunday (0)
		maxDate: null,
		minDate: null,
		yearRange: '-100:+10' // Used in conjunction with "changeYear"
	};
	
	// Select any date with current date as starting point
	$('input.jqueryui_datepicker').each(function () {		
		$(this).datepicker($.extend(default_options, {  
			maxDate: $(this).data('max-date') ? $(this).data('max-date') : null,
			minDate: $(this).data('min-date') ? $(this).data('min-date') : null
		}));
	});	
	$('input.jqueryui_datepicker').attr('autocomplete', 'off');
	
	// Only select dates in the past with current date as starting point
	$('input.jqueryui_datepicker_past').each(function () {
		$(this).datepicker($.extend(default_options, {
			maxDate: new Date(),
			minDate: $(this).data('min-date') ? $(this).data('min-date') : null
		}));
	});	
	$('input.jqueryui_datepicker_past').attr('autocomplete', 'off');
	
	// Only select dates in the future with current date as starting point
	$('input.jqueryui_datepicker_future').each(function () {		
		$(this).datepicker($.extend(default_options, {
			maxDate: $(this).data('max-date') ? $(this).data('max-date') : null,
			minDate: new Date()
		}));
	});
	$('input.jqueryui_datepicker_future').attr('autocomplete', 'off');
	
	// More specific datepickers should be activated near where they are used...
};

/**
 * Activate "anytime" datepicker
 */
var init_anytimec_datepicker = function () {
	var default_options = {
		format: "%e/%m/%Z %H:%i",
		labelTitle: "Select date and time"
	};
	
	// Select any date with current date as starting point
	$('input.anytimec_datepicker').AnyTime_picker($.extend(default_options, {}));
	
	// Only select dates in the past with current date as starting point
	$('input.anytimec_datepicker_past').AnyTime_picker($.extend(default_options, {
		// TODO
	}));
	
	// Only select dates in the future with current date as starting point
	$('input.anytimec_datepicker_future').AnyTime_picker($.extend(default_options, {
		// TODO
	}));
	
	// More specific datepickers should be activated near where they are used...
};

/**
 * Alias function for parseAjaxFormJSONResponse 
 * 
 * Basic convenience function to parse a json response from an ajax form submit and output a jQuery Dialog to show the result (success/error message)
 * 
 * data object should contain a data.success property if set to false the dialog is themed as an error message 
 * the data.message property can be set to output in the dialog body, this can be an array of strings or a string.
 * optional data.title can be set as the title of the dialog
 * 
 * data.success 	=> response success
 * data.success_js 	=> javacript to run when the ok button is clicked on the success dialog
 * data.title 		=> dialog title
 * data.message 	=> response message, can also be an array of messages
 * 
 * @param data JSON Response from ajax call
 * @return
 */
function parse_response(data) {
	parseAjaxFormJSONResponse(data);
}

function parseAjaxFormJSONResponse(data) {
	if (data != null) {
		var message = '';
		if (data.message != null && data.message[0] != null) {
			if (data.message[0].length > 1) {
				for (var i = 0; i < data.message.length; i++) {
					message += data.message[i]+'<br/>';
				}
			}
			else {
				message = data.message;
			}
		}
		
		if (data.success) {			
			if (message != '') {
				var dialog_title = data.title != null ? data.title : 'Success';
				$('<div></div>').html('<p>'+message+'</p>').dialog({
					title: dialog_title,
					modal: true, resizable: false, width: 500, buttons: {'Ok': function () {						
						if (typeof data.success_js != 'undefined') {
							eval(data.success_js);
						}
						else {
							$(this).dialog("close");
						}
					}}
				});
			}
		}
		else {
			var dialog_title = data.title != null ? data.title : 'There was a problem';
			$('<div></div>').html('<p>'+message+'</p>').dialog({
					title: dialog_title,
					modal: true, resizable: false, width: 500, buttons: {'Ok': function () { $(this).dialog("close"); }},
					dialogClass : 'error-dialog'
			});
		}
	}
	else {
		$('<div></div>').dialog({
			title: 'There was a problem',
			modal: true, resizable: false, width: 500, buttons: {'Ok': function () { $(this).dialog("close"); }},
			dialogClass : 'error-dialog'
		});
	}
}

/**
 * Activate default text on text inputs and textareas
 */
var init_default_input_text = function () {
	// Quick check to see if component is used
	var selector = 'input[type="text"].default_input_text, textarea.default_input_text';
	if ($(selector).length < 1) {
		return false;
	}
	
	$(selector).each(function () {
		if (!$(this).hasClass('default_input_text_idle')) {
			$(this).addClass('default_input_text_idle');
		}
		
		if ($(this).val() == '') {
			$(this).val($(this).attr('title'));
		}
	});
	
	$(selector).focus(function () {
		if ($(this).hasClass('default_input_text_idle')) {
			$(this).removeClass('default_input_text_idle');
		}
		
		if ($(this).val() == $(this).attr('title')) {
			$(this).val('');
		}
	});
	
	$(selector).blur(function () {
		if (!$(this).hasClass('default_input_text_idle')) {
			$(this).addClass('default_input_text_idle');
		}
		
		if ($(this).val() == '') {
			$(this).val($(this).attr('title'));
		}
	});
};

/**
 * Make fieldsets collapsible by clicking the legend
 */
var init_collapsible_fieldset = function () {
	$('fieldset.collapsible').collapse();
};

/**
 * Make dl dd's collapsible by clicking dt
 */
var ini_collapsible_dl = function () {
	$('dl.collapsible').each(function (index, dl) {
		$('dt', dl).click(function () {
			if ($(this).hasClass('opened')) {
				$(this).next('dd').hide();
				$(this).removeClass('opened');
			} else {
				$(this).next('dd').show();
				$(this).addClass('opened');
			}
		});
	});
};

/**
 * Activate 'check all' checkboxes in a table
 */
var init_table_list_check_all = function () {
	$('table').each(function (i, table) {
		$('thead th', table).each(function (j, th) {
			$('input[type="checkbox"]', th).each(function (k, checkbox) {
				// Check if the checkbox is marked with '_all' suffix (we're not strict on this appearing at the very end because we might add a number or something at the end to make it unique if displaying within a loop)
				if ($(checkbox).attr('name').match(/_all/)) {
					$(checkbox).attr('title', 'Toggle all');
					$(checkbox).click(function () {
						$('tbody td:nth-child(' + (j + 1) + ') input[type="checkbox"]', table).each(function () {
							if (!$(this).attr('disabled')) {
								$(this).attr('checked', $(checkbox).attr('checked'));
							}
						});
					});
				}
			});
		});
	});
};

/**
 * Activate jqueryui dialog
 */
var init_jqueryui_dialog = function () {
	$('dl.jqueryui_dialog').each(function () {
		var dialog_link = $('dt', this);
		var dialog = $('dd', this);
		
		dialog.dialog({
			autoOpen: false
		});
		
		dialog_link.click(function () {
			// Close all other dialogs first
			$('dl.jqueryui_dialog dd').not(this).dialog('close');
			
			// Basically this will right align just underneath this link
			// TODO: add more positioning options via classnames given to "dl.jqueryui_dialog dd"
			var x = $(this).offset().left + $(this).width() - $(document).scrollLeft() - dialog.dialog('option', 'width');
			var y = $(this).offset().top + $(this).height() - $(document).scrollTop();
			
			// Open current dialog where this link is
			dialog.dialog('option', 'position', [x, y]);
			dialog.dialog('open');
			return false;
		});
	});
};

/**
 * When confirm-link class applied to an <a> tag a confirmation prompt appears
 */
function init_confirm_link() {
	$('.confirm-link').click(function(event) {
		event.preventDefault();
		
		var link = $(this).attr('href'); 
		$('<div title="Confirm this action"></div>').html('Are you sure you want to do this?').dialog({ 
			modal: true,			
			buttons: { 				
				"Cancel" : function() {
					$(this).dialog("close");
				}, 
				"Yes": function() { 
					location.href = link; 
				} 
			} 
		});
		
		return false;
	});
}

/**
 * Make a table's tbody scrollable with the thead fixed at the top
 * Note: You MUST set max-height css property on the tbody
 */
var init_tbody_scrollable = function () {
	$('table.scrollable').each(function (i, table) {
		var max_height = $('tbody', table).css('max-height');
		if (!max_height || max_height == 'none') {
			return;
		} else if ($('tbody', table).height() <= max_height.replace(/px$/, '')) {
			return;
		}
		
		var column_widths = new Array();
		
		// Read in the auto generated column widths
		$('thead tr th', table).each(function (j, th) {
			// alert($(th).css('border-left'));
			column_widths.push($(th).width());
		});
		
		// Set the th widths
		$('tr', table).each(function (k, tr) {
			$('th', tr).each(function (m, td) {
				$(td).css('width', column_widths[m] + 'px');
			});
		});
		
		// Take 10 pixels off the last cell in the row to account for the scrollbar in tbody
		column_widths[column_widths.length - 1]-= 10;
		
		// Set the td widths
		$('tr', table).each(function (k, tr) {
			$('td', tr).each(function (m, td) {
				$(td).css('width', column_widths[m] + 'px');
			});
		});
		
		// Set the css to make the table scrollable
		$('thead tr', table).css('display', 'block');
		$('tbody', table).css({
			display: 'block',
			overflow: 'auto',
			width: '100%',
			height: max_height
		});
	});
}

/**
 * Prompt to submit form if changes have been made and the user leaves the page
 */
var init_form_prompt_on_exit = function () {
	$('form.prompt_on_exit').each(function (index, form) {
		$(form).data('form_changed', false);
		
		$('input[type="text"],input[type="radio"],input[type="checkbox"],input[type="hidden"],select,textarea', form).change(function () {
			$(form).data('form_changed', true);
		});
		
		$(form).submit(function () {
			$(form).data('form_changed', false);
		});
		
		window.onbeforeunload = function (e) {
			if ($(form).data('form_changed')) {
				var e = e || window.event;
				
				// For IE and Firefox prior to version 4
				if (e) {
					e.returnValue = 'Changes will not be saved.';
				}
				
				return 'Changes will not be saved.';
			}
		};
	});
};

/**
 * Toggle visibility of "extended info rows" in table.basic_list
 */
var init_basic_list_show_extended_info_link = function () {
	$('a.show_extended_info').live('click', function () {
		var link = $(this);
		var row = link.parents('tr');
		var row_extended_info = row.next();
		
		if (!row_extended_info || !row_extended_info.hasClass('extended_info')) {
			return true;
		}
		
		if (link.hasClass('show_extended_info_opened')) {
			link.removeClass('show_extended_info_opened');
			row.removeClass('active');
			row_extended_info.hide()
		} else {
			link.addClass('show_extended_info_opened');
			row.addClass('active');
			row_extended_info.show()
		}
		return false;
	});
};


$(document).ready(function () {
	init_help_bubble();
	init_search_box();
	init_jqueryui_datepicker();
	init_anytimec_datepicker();
	init_default_input_text();
	init_tbody_scrollable();
	init_collapsible_fieldset();
	ini_collapsible_dl();
	init_table_list_check_all();
	init_jqueryui_dialog();	
	init_confirm_link();
	init_form_prompt_on_exit();
	init_basic_list_show_extended_info_link();
});

