;(function($) { 

$.extend($.expr[':'], { 
	submitable: function(a) { 
  	return !a.disabled&&(a.selected||a.checked||(a.nodeName.toUpperCase()=='TEXTAREA')||(a.nodeName.toUpperCase()=='INPUT'&&(a.type=='text'||a.type=='hidden'||a.type=='password'))); 
	}, 
	nothidden: function(a) { 
		return a.type&&a.type!='hidden'; 
	} 
})

$.fn.extend(
	{
		initForm: function()
		{
			return this.each(function()
			{
				var obj = $(this);
				obj.find("*[jqtitle]").initTitle();
				obj.find("*[jqtitle]").next("dl").hide();
				$(obj.find("*[jqtitle]").get(0)).click();

				if (obj.attr("jqfocus") != "false")
				{
					var form = obj.formToArray();
					obj.find("*[name=\"" + form[0]["name"] + "\"]").focus();
				}
				obj.find("*[name]").bind("blur.casper", function(e){$(this).validateControl(e)});
				if (obj.attr("jqno") != "true")
				{
					obj.bind("submit.casper", obj.validateForm);
					obj.append("<input type=\"hidden\" name=\"jQuery\"/>");
				}
			});
		}
		,
		initTitle: function()
		{
			return this.each(function()
			{
				var obj = $(this);
				obj.click(function()
				{
					if (obj.attr("jqOpen") != "true")
					{
						obj.attr("jqOpen", "true");
						obj.next().show();
						try
						{
							obj.next().find("*:submitable").get(0).focus();
						}
						catch(err){}
					}
					else
					{
						obj.attr("jqOpen", "false");
						obj.next().hide();
					}
				});
			});
		}
		,
		validateControl: function(e)
		{
			return this.each(function(e)
			{
				var obj = $(this);
				if (obj.attr("type") == "hidden")
				{
					obj.attr("jqval", "true");
					return;
				}
				var vali = obj.attr("jqtype");
				var req = obj.attr("jqrequired");
				var val = obj.val();

				if (obj.get(0).tagName == "TEXTAREA")
				{
					try
					{
						if (tinyMCE)
						{
							val = tinyMCE.get(obj.attr("id")).getContent();
						}
					}
					catch(err){}
				}

				if (req == "true" && val == "")
				{
					obj.markControl();
					obj.attr("jqval", "false");
					return;
				}

				var re;
				switch(vali)
				{
					case "int": re = /^(\+|\-)?\d+$/ig; break;
					case "float": re = /^(\+|\-)?\d+(\.\d+)?$/ig; break;
					case "zip": re = /^\d{4, 5}$/ig; break;
					case "email": re = /^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/ig; break;
					case "CC": re = /^\d{4}(\s|\-)?\d{4}(\s|\-)?\d{4}(\s|\-)?\d{4}$/ig; break;
					case "CSC": re = /^\d{3, 4}$/ig; break;
					case "phone": re = /^\+?\d+$/ig; break;
					case "time": re = /^\d{1,2}:\d{1,2}(\s(am|pm|AM|PM))?$/ig; break;
					case "date": re = /^\d{1,2}\/\d{1,2}\/\d{4}$/ig; break;
					case "text": re = /^(\s*\S+\s*)+$/ig; break;
				}
				if (re != null && val != "")
				{
					if (!val.match(re))
					{
						obj.markControl();
						obj.attr("jqval", "false");
						return;
					}
				}

				obj.unmarkControl();
				obj.attr("jqval", "true");
			});
		}
		,
		markControl: function()
		{
			this.parent().addClass("error");
//			this.parent().css("background-color", "red");
		}
		,
		unmarkControl: function()
		{
			this.parent().removeClass("error");
//			this.parent().css("background-color", "");
		}
		,
		validateForm: function(e)
		{
			var obj = $(this);
			var form = obj.formToArray();
			obj.find("*[name]").unbind("blur.casper");

			obj.find("input, select, textarea").validateControl();

			var error = obj.find("*[jqval=\"false\"]");
			if (error.length > 0)
			{
				$(error.get(0)).focus();
			}
			else
			{
				if ($.modalDialog != null)
				{
					$.modalDialog.parents(".ui-dialog:first").find(".ui-dialog-buttonpane button").attr("disabled", true);
				}
				obj.find("*:submit, *:image, button").attr("disabled", true);
				if (obj.attr("jqblock") == "full")
					$.blockUI();
				else
					obj.block();
				var ifv = false;
				if (obj.attr("enctype") == "multipart/form-data" && obj.attr("method") == "post")
					ifv = true;
				obj.find("*[name='jQuery']").val(Math.random());
		    obj.ajaxSubmit
		    ({
		    	iframe: ifv,
		    	dataType: "json",
		    	success: function(data, status, jqForm){ return obj.successForm(data, status, jqForm); },
		    	error: function(data, status, jqForm){ return obj.errorForm(data, status, jqForm); }
		    }); 
			}

			obj.find("*[name]").bind("blur.casper", function(e){$(this).validateControl(e)});
			return false;
		}
		,
	  errorForm: function(data, status, jqForm)
	  {
			if ($.modalDialog != null)
			{
				$.modalDialog.parents(".ui-dialog:first").find(".ui-dialog-buttonpane button").attr("disabled", false);
			}
			jqForm.find("*:submit,*:image").attr("disabled", false);
			if (jqForm.attr("jqblock") == "full")
				$.unblockUI();
			else
				jqForm.unblock();

			jqForm.find("*[id='globalError']").addClass("error").html("Form processign error: " + status);
	  }
	  ,
	  successForm: function(data, status, jqForm)
	  {
			if ($.modalDialog != null)
			{
				$.modalDialog.parents(".ui-dialog:first").find(".ui-dialog-buttonpane button").attr("disabled", false);
			}
			jqForm.find("*:submit,*:image").attr("disabled", false);
			if (jqForm.attr("jqblock") == "full")
				$.unblockUI();
			else
				jqForm.unblock();

			jqForm.find("*[id='globalError']").removeClass("error").html("");

			if (data["Message"] != "" && !(data["Message"] == undefined))
			{
				alert(data["Message"]);
				//TODO: show message
			}

			if (data["Status"] == "OK")
			{
				if (data["Type"] == 1)
				{
					if (data["URL"] == "")
					{
						window.location = "index.php";
					}
					else
					{
						window.location = data["URL"];
					}
				}
				if (data["Type"] == 2)
				{
					var obj = null;
					var filter = "";
					if (data["Control"] != null && data["Control"] != "")
					{
						obj = $(data["Control"]);
						filter = data["Control"];
					}
					else
					{
						obj = jqForm.parents("#jqrefresh");
						if (obj.length == 0)
						{
							obj = $("#jqrefresh");
						}
						else
						{
							obj = $(obj.get(0));
						}
						if (obj.length == 0)
						{
							obj = null;
						}
					}
					var url = data["URL"];
					if (url == null || url == "")
					{
						url = window.location.href;
					}
					if (obj == null)
					{
						window.location = url;
						return;
					}
					url = url + (url.indexOf("?") != -1 ? "&" : "?") + "jQuery=" + Math.random();
					if (filter != "")
						url = url + " " + filter;
					obj.load(url, null, function(data, status, ajax){
						obj.find("form").initForm();
					});
				}
				if (data["Type"] == 3)
				{
					var obj = null;
					if (data["Control"] != null && data["Control"] != "")
					{
						obj = $(data["Control"]);
					}
					else
					{
						obj = jqForm.parents("#jqrefresh");
						if (obj.length == 0)
						{
							obj = $("#jqrefresh");
						}
						else
						{
							obj = $(obj.get(0));
						}
						if (obj.length == 0)
						{
							obj = $(jqForm.parent().get(0));
						}
					}
					var cont = $(data["Content"]);
					cont.find("form").initForm();
					obj = obj.replaceWith(cont);
				}
				if (jqForm.attr("jqreset") != "false")
				{
        	jqForm.get(0).reset();
				}
				if (jqForm.attr("jqfocus") != "false")
				{
					var form = jqForm.formToArray();
					jqForm.find("*[name=\"" + form[0]["name"] + "\"]").focus();
				}
				$.unblockUI();
				if ($.modalDialog != null)
				{
					$.modalDialog.dialog("destroy");
					$.modalDialog = null;
				}
			}
			else if (data["Status"] == "Error")
			{
				try
				{
					var obj;
					for (var i in data["Error"])
					{
						if (i != "Global")
						{
							jqForm.find("*[name='" + i + "']").markControl();
							if (obj == null)
							{
								obj = jqForm.find("*[name='" + i + "']");
								obj.focus();
							}
						}
						else
						{
							jqForm.find("*[id='globalError']").addClass("error").html(data["Error"][i]);
						}
					}
					if (obj == null)
					{
						var form = jqForm.formToArray();
						jqForm.find("*[name=\"" + form[0]["name"] + "\"]").focus();
					}
				}
				catch(e){}
			}
	  }
	}
);

if ($.blockUI)
{
	$.blockUI.defaults.message = "<img src=\"/images/system/loading.gif\" style=\"width: 34px; height: 34px; padding: -1px; margin: -1px;\"/>";
	$.blockUI.defaults.css.border = "0px solid #000";
	$.blockUI.defaults.css.padding = "10px";
	$.blockUI.defaults.css.top = "0px";
	$.blockUI.defaults.css.left = "0px";
	$.blockUI.defaults.css.width = "auto";
	$.blockUI.defaults.css.height = "auto";
	$.blockUI.defaults.css.cursor = "auto";
	$.blockUI.defaults.css.textAlign = "";
	$.blockUI.defaults.fadeOut = 200;
	$.blockUI.defaults.overlayCSS.opacity = "0.5";
}

})(jQuery);

$().ready(function(){$("form").initForm()});

