/// <reference path="jquery-1.3.2.min.js" />
/* Nothing fancy here, just some quick jquery functions so that you can see what css needs to change, and to just have something to start with*/

$(document).ready(function() {

    //Enable select state on inputs
    $('input, textarea, select', '.form fieldset')
    .bind('focus', function(){$(this).parents('div.field').addClass('selected')})
    .bind('blur', function(){$(this).parents('div.field').removeClass('selected')});

    //Zebra stripe tables
    $('tr:even', 'table').addClass('alt');

    //Enable "Select All" for table checkboxes
//    $('th:first input').click(
//      function(e){
//        $("input[type='checkbox']", $(this).parents('table'))
//          .attr('checked', $(this).attr("checked"))                
//        });
        
    //Enable navigation sections
//    $('.list', '.nav-section').each(function(){
//       var $list = $(this);
//       $('.heading', $list.parent()).click(
//         function(e){
//           var $wrapper = $list.parents('.nav-section');
//           if ($wrapper.hasClass('expanded')){
//               $list.slideUp(250);
//               $wrapper.removeClass('expanded');
//           }
//           else{
//            $list.slideDown(250);
//            $wrapper.addClass('expanded');
//           }    
//           e.preventDefault(); 
//           return false;
//         });
//    });

    $('.root > li', '.top-nav').hover(	
	    function() { $(this).toggleClass('over') },
	    function() { $(this).toggleClass('over') }
	  ); 
   });

   var D = {};
   D.closeMB = function(link) {
   	var link = $(link);
   	var container = link.parent(".message");
   	container.hide(100);
   	return false;
   };

D.htmlEncode = function( value )
{
	return value.replaceAll( "&", "&amp;" ).replaceAll( "<", "&lt;" ).replaceAll( ">", "&gt;" ).replaceAll( " ", "&nbsp;" );
}

D.htmlDecode = function( value )
{
	return value.replaceAll( "&nbsp;", " " ).replaceAll( "&gt;", ">" ).replaceAll( "&lt;", "<" ).replaceAll( "&amp;", "&" );
}

D.SimulatedForm = function(form, initOptions) {
	///	<summary>
	///		Javascript container for helping with ajax postbacks..
	///	</summary>
	///	<param name="form" type="Object">The parent container for the simulated form</param>
	///	<param name="initOptions" type="Object">The options array:\n
	///		1. url - the url to post to.
	///		2. success - When the response is valid, this function will be called.
	///		3. error - When the response is not valid, this function will be called.
	///		4. assignResults - When true, if the model is valid each value with be set the same.
	///     5. confirmation - When assigned a value (a string message to present to the user), the user is prompted to confirm before proceeding with the button's action.
	/// </param>
	///	<returns type="Object" />
	this.form = $(form);
	this.formValues = null;
	this.initOptions = initOptions;
	this.submitButton = $("input[type='submit']", form);
	this.response = null;
	this.messageBar = null;
	this.responseData = null;

	if (!initOptions.url) alert("Error. Missing url parameter.");


	this.addButton = function(button, options) {
		button = $(button);
		//means default values weren't done.
		if (button.type != "submit")
			button.click(this.submitClick);
		button.data("options", options);
		button.data("controller", this);
		if (!options.fields) alert("Missing the list of postable fields.  Something won't work.");
		if (!options.url) alert("Missing url.  Won't work.");

	}

	this.process = function(response, options) {
		this.response = response;
		if (response.Data)
			this.responseData = response.Data;
		else
			this.responseData = null;

		if (this.messageBar)
			this.messageBar.hide();

		//mark the error fields.
		for (var i = 0; i < this.response.Errors.length; i++) {
			var error = this.response.Errors[i];
			var control = $("#" + error.Field);
			if (control.length == 0) continue;

			control.parent(".field").removeClass("invalid");
			if (error.Error.length != 0)
				control.parent(".field").addClass("invalid");
		}

		var list = [];
		if (response.IsValid)
			list.push('<div class="message">');
		else
			list.push('<div class="message error">');

		list.push('<h2 class="title">');
		list.push(D.htmlEncode(response.Message));
		list.push('</h2>');

		var paragraphs = [];
		if (false == response.IsValid) {
			for (var i = 0; i < response.Errors.length; i++) {
				paragraphs.push(response.Errors[i].Error);
			}
		}

		for (var i = 0; i < paragraphs.length; i++) {
			if (paragraphs[i] == null || paragraphs[i].length == 0) continue;

			list.push('<p>');
			list.push(D.htmlEncode(paragraphs[i]));
			list.push("</p>");
		}

		list.push('<a class="close" href="#" onclick="return D.closeMB(this);">X</a>');

		list.push("</div>");

		this.messageBar = this.submitButton.parent(".buttons").before(list.join('')).prev();

		if (response.IsValid && this.responseData != null && options.assignResults) {
			for (var i in this.responseData) {
				var control = $('#' + i).val(this.responseData[i]);
			}
		}

		if (response.IsValid && typeof (options.success) == "function")
			options.success(this);
		if (response.IsValid == false && typeof (options.error) == "function")
			options.error(this);

		return;
	};

	this.submitClick = function(e) {

		var controller = $(this).data("controller");
		var customOptions = $(this).data("options");

		if (customOptions && customOptions.confirmation) {
			if (!confirm(customOptions.confirmation)) return false;
		}

		var data = null;

		var options = {
			type: "POST",
			dataType: "json"
		};

		if (customOptions) {
			data = {};
			for (var i = 0; i < customOptions.fields.length; i++) {
				var name = customOptions.fields[i];
				data[name] = $("#" + name).val();
			}

			options.url = customOptions.url;
			options.data = data;
			options.success = function(r) { controller.process(r, customOptions); }
		}
		else {
			data = D.getFormValues(controller.form);
			controller.formValues = data;

			options.url = controller.initOptions.url;
			options.data = data;
			options.success = function(r) { controller.process(r, controller.initOptions); }
		}

		D.ajax(options);
		return false;

	};

	this.submitButton.data("controller", this);
	this.submitButton.click(this.submitClick);

};


D.Message = function(actionResponse, allowClose) {
	this.response = actionResponse;
	this.allowClose = allowClose;
	this.messageBar = null;
};

D.Message.prototype = {

	setResponse: function(actionResponse) {
		this.response = actionResponse;
		this.title = actionResponse.Message;
		this.isValid = actionResponse.IsValid;

		this.paragraphs = [];

		if (false == actionResponse.IsValid) {
			for (var i = 0; i < actionResponse.Errors.length; i++) {
				this.paragraphs.push(actionResponse.Errors[i].Error);
			}
		}
	}

	, getHtml: function() {
		var list = [];
		if (this.isValid)
			list.push('<div class="message">');
		else
			list.push('<div class="message error">');

		list.push('<h2 class="title">');
		list.push(D.htmlEncode(this.title));
		list.push('</h2>');

		for (var i = 0; i < this.paragraphs.length; i++) {
			if (this.paragraphs[i] == null || this.paragraphs[i].length == 0) continue;
			
			list.push('<p>');
			list.push(D.htmlEncode(this.paragraphs[i]));
			list.push("</p>");
		}

		if (this.allowClose)
			list.push('<a class="close" href="#" onclick="return D.closeMB(this);">X</a>');

		list.push("</div>");

		return list.join('');
	}

	, processErrors: function() {
		for (var i = 0; i < this.response.Errors.length; i++) {
			var error = this.response.Errors[i];
			var control = $("#" + error.Field);
			if (control.length == 0) continue;

			control.parent(".field").removeClass("invalid");
			if (error.Error.length != 0)
				control.parent(".field").addClass("invalid");
		}
	}

	, clearPrevious: function(buttonControl) {
		if (this.messageBar)
			this.messageBar.hide();
	}

	, injectMessage: function(buttonControl) {
		buttonControl = $(buttonControl);
		var container = buttonControl.parent(".buttons").before(this.getHtml());
		this.messageBar = container.prev();
	}
}

D.getFormValues = function(parentControl) {
	parentControl = $(parentControl);
	var inputControls = $("input", parentControl);
	var selectControls = $("select", parentControl);
	var textControls = $("textarea", parentControl);

	var options = {};

	for (var i = 0; i < inputControls.length; i++) {
		var control = inputControls[i];

		if (control.type != "button" && control.type != "submit") {
			if (control.name)
				options[control.name] = control.value;
			else
				options[control.id] = control.value;
		}
	}

	for (var i = 0; i < selectControls.length; i++) {
		var control = selectControls[i];
		if (control.name)
			options[control.name] = control.value;
		else
			options[control.id] = control.value;
	}

	for (var i = 0; i < textControls.length; i++) {
		var control = textControls[i];
		if (control.name)
			options[control.name] = control.value;
		else
			options[control.id] = control.value;
	}

	return options;
}

String.prototype.replaceAll = function( replace, replaceWith )
{
	var text = this;
	text = text.split( replace ).join( replaceWith );
	return text;
};

D.ajax = function(jqueryOptions) {
	if (typeof (jqueryOptions.error) == "undefined")
		jqueryOptions.error = function(request, status, error) {
			alert("Error occurred: " + status + " on this url " + this.url);
		};

	$.ajax(jqueryOptions);
}