/**
 * Common javascript functionality for the site.
 * Be sure to include the following files before this one in the theme template:
 *		- jquery.js
 *		- jquery-ui.js
 *		- jquery-idletimeout.js
 * @author Justin Cherniak <justin.cherniak@gmail.com>
 */

/**
 * Selects all other checkboxes in this form
 * @param DomObject checkbox that calls this function
 * @param string name of the form to check all checkboxes in
 */
function toggle_checkboxes(checkbox, form_name) {
	var checkboxes = $('form#' + form_name + ' input[type="checkbox"]');
	if (!checkboxes) {
		alert('No checkboxes found on form "' + form_name + '" found');
		return;
	}

	checkbox = $(checkbox);

	if (checkbox.attr('checked'))
		checkboxes.attr('checked', 'checked');
	else
		checkboxes.removeAttr('checked');
}

/**
 * Verifies input values of a form
 *
 * @param DomObject form form to verify
 * @param string error_div name of the div to post an error message to
 * @return true if the form passed all tests, false if it did not.
 */
function OnFormCheck(form, error_div) {
	error_div = $('#' + error_div);
	form = $(form);

	form.find('input').each(function() {
		$(this).removeClass('error ui-state-error');
		error_div.addClass('error');
		error_div.html('');
		error_div.hide();
	});

	var ret = true;
	form.find('input.numeric').each(function () {
		var value = $(this).val();
		if (value != null && value != '') {
			if (value != parseInt(value)) {
				error_div.show();
				error_div.addClass('error');
				error_div.html(error_div.html() + $(this).attr('name') + " must be a number.<br/>");
	
				$(this).addClass('error ui-state-error');
				ret = false;
			}
		}
	});

	form.find('input.required').each(function() {
		var value = $(this).val();
		if (value == null || value == '') {
			error_div.show();
			error_div.addClass('error');
			
			var title = $(this).attr('title');
			if (title != null && title != '')
				error_div.html(error_div.html() + 'You must enter a ' + title + '.<br/>');
			else
				error_div.html(error_div.html() + 'All fields with a * are required!<br/>');

			$(this).addClass('error ui-state-error');
			ret = false;
		}
	});

	form.find('select.required').each(function() {
		var value = $(this).children('option:selected');
		if (value.length == 0) {
			error_div.show();
			error_div.addClass('error');

			var title = $(this).attr('title');
			if (title != null && title != '')
				error_div.html(error_div.html() + 'You must enter a ' + title + '.<br/>');
			else
				error_div.html(error_div.html() + 'All fields with a * are required!<br/>');

			$(this).addClass('error ui-state-error');
			ret = false;
		} else {
			value = $(value[0]);
			if (value.hasClass('default')) {
				error_div.show();
				error_div.addClass('error');
			
				var title = $(this).attr('title');
				if (title != null && title != '')
					error_div.html(error_div.html() + 'You must enter a ' + title + '.<br/>');
				else
					error_div.html(error_div.html() + 'All fields with a * are required!<br/>');

				$(this).addClass('error ui-state-error');
				ret = false;
			}
		}
	});

	var regex = new RegExp('([1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\\d\\d');
	form.find('input.date').each(function() {
		var value = $(this).val();
		if (value != null && value != '') {
			if (!value.match(regex)) {
				error_div.show();
				error_div.addClass('error');

				var title = $(this).attr('title');
				if (title != null && title != '')
					error_div.html(error_div.html() + title + ' must be in mm/dd/yyyy format.<br/>');
				else
					error_div.html(error_div.html() + 'Date fields must be in mm/dd/yyyy format.<br/>');

				$(this).addClass('error ui-state-error');
				ret = false;
			}
		}
	});

	regex = new RegExp('^(20|21|22|23|[01]\\d|\\d)(([:][0-5]\\d){1,2})$');
	form.find('input.time').each(function() {
		var value = $(this).val();
		if (value != null && value != '') {
			if (!value.match(regex)) {
				error_div.show();
				error_div.addClass('error');
				
				var title = $(this).attr('title');
				if (title != null && title != '')
					error_div.html(error_div.html() + title + ' must be in HH:MM (24-hour) format.<br/>');
				else
					error_div.html(error_div.html() + 'Time fields must be in HH:MM (24-hour) format.<br/>');

				$(this).addClass('error ui-state-error');
				ret = false;
			}
		}
	});


	return ret; 
}

// Add trim functions to strings:
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g, "");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/, "");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/, "");
}

/**
 * Standard printf function with C# style {0}, {1} syntax
 * @return string formatted string
 */
function printf() { 
	var num = arguments.length; 
	var oStr = arguments[0];   
	for (var i = 1; i < num; i++) { 
		var pattern = "\\{" + (i-1) + "\\}"; 
		var re = new RegExp(pattern, "g"); 
		oStr = oStr.replace(re, arguments[i]); 
	} 
	return oStr; 
}

/**
 * Shows applicable lesson sub-categories based on the selected lesson group
 *
 * @param select group_select LessonGroup select
 * @param string subcategory_select_name Name of the sub-category select
 */
function update_sub_category_select(group_select, subcategory_select_name) {
	// Store the original contents of the select on the first call (simulate a static
	// variable through object member) and restore it on subsequent calls
	if (typeof update_sub_category_select.original_select == 'undefined') {
		update_sub_category_select.original_select = $('#' + subcategory_select_name).html();
	} else {
		$('#' + subcategory_select_name).html(update_sub_category_select.original_select);		
	}

	var selected = group_select.options[group_select.selectedIndex];
	var selected_id = $(selected).val();

	/* We cannot simply hide options as they will still show up when scrolled through
	   using the keyboard.  As a result, both hide and disabled them.  Disabled options
	   aren't selectable using the keyboard and thus, we get the desired result*/
	$('#' + subcategory_select_name + ' option')
		.hide()
		.attr('disabled', 'disabled');
	$('#' + subcategory_select_name + ' option.group-none')
		.show()	
		.attr('selected', 'selected')
		.attr('disabled', '');
	$('#' + subcategory_select_name + ' option.group-' + selected_id)
		.show()
		.attr('disabled','');
}

// Add session timeouts so the user is redirected to the main page once the timeout has expired
$(document).ready(function() {
	if (session_logged_in) {
		$(document).idleTimeout({
			inactivity: session_timeout - 30,
			sessionAlive: false,
			alive_url: session_keepalive_link,
			redirect_url: session_expired_link
		});
	}
});
