(function ($) {
	var methods = {
		clearForm : function()
		{
			return this.each(function(){
				clearForm(this);
			});
		},

		addRule : function(name, rule){
			rules[name] = rule;
		}
	};
	
	function clearForm ($form)
	{
		$form.find('input').each(function() {
			var $this = $(this);
			if($this.attr('type') != 'submit')
			{
				$this.val('');
			}
		});
	}
	
	function attachMsg($elem, mgs)
	{
		// Remove the old message
		$elem.parent().find('.error-msg').replaceWith('');
		$elem.after('<p class="error-msg">' + mgs + '</p>').show('slow');
	}
	
	var EvenstartForm = function($elem, options)
	{
		var thisClass = this;
		var $this = $elem;
		var rules = {};
		var settings = {
			rules : rules,
			success : null,
			html : 'html'
		};
		
		if (options)
		{
			settings = $.extend(true, settings, options);
		}

		$this.submit(function(event)
		{
			event.preventDefault();

			var action = $this.attr('action');

			if ($this.isValid())
			{
				var form_data = $this.serialize();
				ajaxCall($this, action, form_data);
			}
		});

		function ajaxCall($form, action, data)
		{

			$.post(action, data, settings.success);
		}

		this.valid = function()
		{
			return false;
		}
	};
	
	$.fn.isValid = function()
	{
		// Gets all of the inputs and
		this.find('.required, .email-required').each(function()
		{
			var $thisField = $(this);

			if ($thisField.hasClass('required'))
			{
				if ($thisField.val().trim() == '')
				{
					attachMsg($thisField, 'This field cannot be empty.');
					$thisField.addClass('field-error');
				}
				else
				{
					$thisField.removeClass('field-error');
				}
			}

			if ($thisField.hasClass('email-required'))
			{
				if ($thisField.val().trim() == '')
				{
					attachMsg($thisField, 'This field cannot be empty.');
					$thisField.addClass('field-error');
				}
				else
				{
					var thisFieldVal = $thisField.val();
					if (thisFieldVal != '' && !/.+@.+\.[a-zA-Z]{2,4}$/.test(thisFieldVal))
					{
						attachMsg($thisField, 'Please enter a valid email address.');
						$thisField.addClass('field-error');
					}
					else
					{
						$thisField.removeClass('field-error');
					}
				}
			}
		});

		// Check if there's any field with error.
		if (this.find('.field-error')[0] == undefined)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	$.fn.evenstartForm = function(options)
	{
		// Maintaining chainablity
		return this.each(function(){
			var $this = $(this);

			var evenstart = new EvenstartForm($this, options);
			$this.data('evenstartForm', evenstart);
		});
	};

})(jQuery);

var alternateRowColors = function($table) {
	$('tbody .odd', $table).removeClass('odd');
	$('tbody tr:odd', $table).addClass('odd');
};

$(document).ready(function(){
	$('#users tbody tr:odd').addClass('odd');

	$('#create-user').evenstartForm({
		success : function(result)
		{
			var query = this.data;
			var values = query.split('&');
			var data = {};
			for (var i = 0; i < values.length; i++)
			{
				var properties = values[i];
				var property = properties.split('=');

				data[property[0]] = property[1];
			}

			// Remove the old message
			$('#create-user').parent().find('.success-msg').replaceWith('');
			$('#create-user').before('<p class="success-msg">' + result + '</p>');
			var $row = $('tr.create-user-template').clone().removeClass('create-user-template').insertBefore('#users tbody tr:first');
			$row.find('td:first').html(data.username);
			$row.find('td:nth-child(3n)').html(data.group);
		}
	});

	$('#contact-form').evenstartForm({
		success : function(result)
		{
			$('#contact-form').before('<p style="color:green;font-size:18px;">' + result + '</p>');
		}
	});

	$('#user-login').submit(function(){
		return $('#user-login').isValid();
	});

	$('table.sortable').each(function() {
		var $table = $(this);
		
		$('th', $table).each(function(column) {
			if ($(this).is('.sort-alpha'))
			{
				$(this).find('a').click(function(){ return false; })
				$(this).addClass('clickable').hover(function()
				{
					$(this).addClass('hover');
				}, function(){
					$(this).removeClass('hover');
				}).click(function() {

					$(this).parent().find('th').removeClass('active');
					$(this).addClass('active');

					var rows = $table.find('tbody > tr').get();

					$.each(rows, function(index, row)
					{
						row.sortKey = $(row).children('td').eq(column).text().toUpperCase();
					});
					
					rows.sort(function(a, b)
					{
						if (a.sortKey < b.sortKey) return -1;
						if (a.sortKey > b.sortKey) return 1;
						return 0;
					});
					
					$.each(rows, function(index, row) {
						$table.children('tbody').append(row);
						row.sortKey = null;
					});

					alternateRowColors($table);
				});
			}
		});
	});

	/*
	 * Links Open In New Window
	*/
	$("a.blank[href^=]").click(

		function() {

			window.open(this.href);

			return false;
		}
	);

	/*
	 * Accordion Function 
	*/
	$("#accordion").addClass("ui-accordion");

	$("#accordion h3").each(function() {

		// Add UI Classes

		$(this).addClass("ui-state-default");

		$(this).next().addClass("ui-accordion-content");

		// Hide Next Div
		$(this).next().hide();

		// Click Event
		$(this).bind("click", function(e) {

			$(this).toggleClass("ui-state-default").toggleClass("ui-state-active");

			$(this).next().toggle('fast').toggleClass("ui-accordion-content-active");

			e.preventDefault();

		});
	});

	$("#accordionControl").bind('click', function(e) {

		$("#accordion h3").each(function() {

			$(this).next().toggle('fast');

			$(this).toggleClass("ui-state-default").toggleClass("ui-state-active");

		});

		e.preventDefault();

	});

	// Debug Info Window

	$("#contacts").hide();

	$(".contact").hide();

	$("#contacts").show();

	$("#contactList").bind("change select", function() {

		$("div.contact:visible").hide();

		$("#" + $(this).val()).show();

	});


	if (self.document.location.hash != '') {

		var id = Number(self.document.location.hash.substr(4));

		$("#accordion h3").filter(function (index) {

        	if (index == id) {

        		$(this).toggleClass("ui-state-default").toggleClass("ui-state-active");

		    	$(this).next().toggle('fast').toggleClass("ui-accordion-content-active");

		    }
        });
	}

});

function toggleInit(id) {

    $(id).toggleClass("ui-state-default").toggleClass("ui-state-active");

    $(id).next().toggle('fast').toggleClass("ui-accordion-content-active");
}

$('#users td:nth-child(4n), #users th:nth-child(4n)').addClass('last');

// Check if username already been taken
$('#create-user #username').blur(function(){
	var username = $('#username').val();

	$.post('admin/username_taken', {'username':username},
	function(result){

		 // clear any message that may have already been written
		$('.error-msg').replaceWith('');

		// if the result is TRUE write a message to the page
		if (result)
		{
			$('#username').after('<p class="error-msg">' +
			  'That Username is already taken.<br /> Please choose another.</p>');
		}
	});
});

$('form.remove-user').submit(function(event)
{
	var $thisForm = $(this);
	var username = $thisForm.parent().parent().find('td:first').html();
	var data = {'username' : username};

	$(this).find('input').each(function(){
		var $thisField = $(this);
		var fieldName = $thisField.attr('name');
		data[fieldName] = $thisField.val();
	});

	var r = confirm("Are you sure you want to remove user " + data.username + " ?");

	if (r)
	{
		$.post('admin/remove_user', data,
		function(result){
			// if the result is TRUE, remove the row it's on.
			if (result)
			{
				// Hide the entire row.
				$thisForm.parent().parent().hide('slow');
			}
			else
			{
				alert('Unable to remove user from database.');
			}
		});
	}

	return false;
});


