/*
	=============================================================================================================
	rTforms
	=============================================================================================================
	- This file (rTform.js and the jQuery library is required to use rTforms).
	- The jQuery library can be obtained at www.jquery.com
	- You may also use the rTform.php file for form creation functions.

	Name: rTforms
	Version: Beta 1.0 
	Info: jQuery form validation and creation plug-in
	Created By: Ausgate Technologies
	Designer: Allan Gowen
	Web: www.ausgatedesign.com
	Email: allan@ausgatedesign.com
	Date: 9/9/2009
	Relies on: jQuery

	rTforms ©Copyright 2009 Ausgate Technologies

	This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser 
	General Public License as published by the Free Software Foundation; either version 2.1 of the License, 
	or (at your option) any later version.

	This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the 
	implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
	License for more details.

	You should have received a copy of the GNU Lesser General Public License along with this library; if not, 
	write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA

	Blah, Blah, Blah.  What it basically means is please leave the above information intact (but you're a designer
	like me, so I know it probably won't).

	If you do happen to use this code on your website... 
	let us know about it at admin@ausgate.net
	or link to us www.ausgatedesign.com


*/

$(document).ready(function(){

		function throwError(objID, objError) {

			if (window.lastError != "")
			{
				$("#" + window.lastError).removeClass();
				$("#" + window.lastError).addClass('required');
			}

			$("#" + objID + "_error").fadeOut("slow");
			$("#" + objID + "_error").html(objError);
			$("#" + objID).removeClass();
			$("#" + objID).addClass('error');
			$("#" + objID).focus();
			$("#" + objID + "_error").fadeIn("slow");

			window.lastError = objID;

		}

		function emailCheck(emailStr) {

				if ((emailStr != "")) {

				var emailPat		= /^(.+)@(.+)$/
				var specialChars	= "\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
				var validChars		= "\[^\\s" + specialChars + "\]"
				var quotedUser		= "(\"[^\"]*\")"
				var ipDomainPat		= /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
				var atom			= validChars + '+'
				var word			= "(" + atom + "|" + quotedUser + ")"
				var userPat 		= new RegExp("^" + word + "(\\." + word + ")*$")
				var domainPat		= new RegExp("^" + atom + "(\\." + atom +")*$")

				var matchArray=emailStr.match(emailPat)
				if (matchArray==null) {
					return "email address seems incorrect\ncheck that it contains one '@' and at least one full stop character";
				}

				var user 	= matchArray[1]
				var domain 	= matchArray[2]
				if (user.match(userPat)==null) {
					// user is not valid
					return "the username doesn't seem to be valid";
				}

				var IPArray = domain.match(ipDomainPat)
				if (IPArray!=null) {
					// this is an IP address
					  for (var i=1;i<=4;i++) {
						if (IPArray[i]>255) {
						return "destination IP address is invalid";
						}
					}
					return "";
				}

				var domainArray = domain.match(domainPat)
				if (domainArray==null) {
					return "The domain name doesn't seem to be valid.";
				}

				var atomPat = new RegExp(atom,"g")
				var domArr 	= domain.match(atomPat)
				var len		= domArr.length
				if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3) {
				   // the address must end in a two letter or three letter word.
				   return "The address must end in a three letter domain, or two letter country code";
				}

				if (len<2) {
				   return "This address appears to be missing a hostname";
				}

				return "";
			}
		}


		function rTvalidate(objID, objName, objRequired, objValidate, objValue, objError, objMin, objMax, objType) {

			if ( ( objRequired === true || objRequired === "true" ) && objValue == "") {

				throwError(objID, objError);

				return false;

			}


			objLength = objValue.length;

			if ( objType == "radio" || objType == "checkbox" ) {
				
				if ( ( !isNaN(parseInt(objMin)) && parseInt(objMin) > 0 ) && ( $("input[name=" + objName + "]:checked").length < parseInt(objMin) ) ) {

					throwError(objID, objError + " (you must select a minimum of " + objMin + " options)");
					return false;

				}

				if (  ( !isNaN(parseInt(objMax)) && parseInt(objMax) > 0 ) && objType == "checkbox" &&  $("input[name=" + objName + "]:checked").length > parseInt(objMax)  ) {

					throwError(objID, objError + " (you have selected too may options [" + $("input[name=" + objName + "]:checked").length + "])");

					return false;

				}

			} else {

				if ( objRequired === true && ( !isNaN(parseInt(objMin)) && parseInt(objLength) < parseInt(objMin) ) ) {

					throwError(objID, objError + " (minumum of " + objMin + " characters)");

					return false;

				}
			}


			if ( objType != "radio" && objType != "checkbox" ) {

				if (  !isNaN(parseInt(objMax)) && parseInt(objLength) > parseInt(objMax)  ) {

					throwError(objID, " There is a maximum of " + objMax + " characters allowed for this item. You are " + ( parseInt(objLength) - parseInt(objMax) ) + " characters over.");

					return false;

				}

			}

			if ( objValidate == "int" && isNaN(parseInt(objValue))) {

				throwError(objID, objError);

				return false;

			}

			if ( objValidate == "email" ) {


				var emailReturn = emailCheck(objValue)

				if (emailReturn != "") {

					throwError(objID, emailReturn);

					return false;

				}



			}

			return true;

		}

		// the ajax request
		function postFormByAjax(file, divID, dataStr) {

			$.ajax({
			  type: "POST",
			  url: file,
			  data: dataStr ,
			  success: function(data) {
				$(divID).html("")
				.append("")
				.hide()
				.fadeIn(500, function() {
				  $(divID).append(data);
				});
			  }
			});

			return false;
		}

		// capture the ajax call from the form
		$("form").submit(function() {

			var proceedWithProcess = true;
			var doValidate = true;
			if ( $("#UpdateDelete").length )
			{


				if ( $("#UpdateDelete").val() == "0" )
				{
					if ( confirm("WARNING: Deleting this record will remove all associated information.  This action CANNOT BE UNDONE.\n\nAre you sure you want to delete this item?\nOK: to delete\nCANCEL: Do not delete") )
					{
						proceedWithProcess = true;
						doValidate = false;
					} else {
						proceedWithProcess = false;
					}
				}
			}

			if (proceedWithProcess)
			{

				 // Disable submit button
				$("#submitBtn").toggleClass("disabled");
				$("error").addClass('required');

				$("#icon").fadeOut('slow');
				$("#loading").fadeIn('slow');

				var fCheck = true;
				var returnVal = "";

				// reset the hidden field
				$("#dataString").text("");
				$("[id*='_error']").fadeOut('slow');

				

				$("#dataString").append( 
					$("input, textarea, select").map(
						function(){
							if (fCheck) {

								if ( doValidate ) {
									fCheck = rTvalidate($(this).attr("id"), $(this).attr("name"), $(this).attr("required"), $(this).attr("validate"), $(this).attr("value"), $(this).attr("title"), $(this).attr("minlength"), $(this).attr("maxlength"), $(this).attr("type"));
								}
								
								if ( $(this).attr("type") == "radio" ) {
									returnVal = $(this).attr("name") + '=' +$(this + ":checked").val();
									returnVal = returnVal.replace(/&/gi, "*amp*");
									return returnVal;
								} else {
									returnVal = $(this).attr("name") + '=' +$(this).val();
									returnVal = returnVal.replace(/&/gi, "*amp*");
									return returnVal;
									//return $(this).attr("name") + '=' +$(this).val();
									
								}


							}
						}
					).get().join("&")
				);



				dataStr = $('#dataString').text();
				
				if (fCheck) {

					// check submit button for multi click
					if ( window.lastClickID != $("button", this).attr('id') ) {

						if (window.lastError != "")
						{
							$("#" + window.lastError).removeClass();
							$("#" + window.lastError).addClass('required');
						}

						var resultDiv = "#result";
						if ( $("#loadInto").attr('value') != "" )
						{
							resultDiv = "#" + $("#loadInto").attr('value');
						}
						postFormByAjax($(form).attr('action'), resultDiv, dataStr);

					}

				}


				$("#loading").fadeOut('slow');
				$("#icon").fadeIn('slow');

			}

			window.lastClickID = $("button", this).attr('id');

			return false;
		});


		$("#dataString").hide();
		$("[id*='_error']").hide();

	});


	// Reset the submit button AFTER something else has been done (received focus)
	$("input, textarea, select").focus(function(){

		window.lastClickID = "resetsubmit";

		// Re-enable submit button
		$("#submitBtn").removeClass("disabled");
		$("#submitBtn").addClass("positive");


	});
	// radio buttons and checkboxes need the onclick
	$("input, textarea, select").click(function(){

		window.lastClickID = "resetsubmit";

		// Re-enable submit button
		$("#submitBtn").removeClass("disabled");
		$("#submitBtn").addClass("positive");

	});

	// radio buttons and checkboxes need the onclick
	$("input, textarea, select").keypress(function(){

		window.lastClickID = "resetsubmit";

		// Re-enable submit button
		if ( $("#submitBtn").length )
		{
			$("#submitBtn").removeClass("disabled");
			$("#submitBtn").addClass("positive");
		}


	});

	// radio buttons and checkboxes need the onclick
	$("input, textarea").keyup(function(){

		if ( $(this).attr("name") == "ContentHeading" )
		{
			var newVal = $(this).attr("value");
			

			newVal = newVal.replace(/ /gi,'-'); 
			newVal = newVal.replace(/[^a-zA-Z0-9_-]/gi,''); 
			newVal = (newVal + '').toLowerCase();

			$("#Url-Rewrite").val(newVal);

		}

		if ( $("[parent*='" + $(this).attr("id") + "']").length )
		{
			$("[parent*='" + $(this).attr("id") + "']").html(  $("[parent*='" + $(this).attr("id") + "']").attr("count") - $(this).val().length  );
		}

		return false;
	});


//	// radio buttons and checkboxes need the onclick
//	$("input, textarea, select").change(function(){
//
//		var resultDiv = "#result";
//		if ( $("#loadInto").attr('value') != "" )
//		{
//			resultDiv = "#" + $("#loadInto").attr('value');
//		}
//
//		//$(resultDiv).html("<font color='red'>Changes made. Click the 'Save' button to save new changes.</font>");
//
//	});

	// form button redirect
//	$("[type*='button']").click(function(){
//
//		/* the action can be obtained with $(this).attr('action')  */
//		/* put in your own custom catching for buttons here        */
//		/* I am using the Ajax call I use for the rest of the site */
//
//		alert($(this).attr('action'));
//
//		ajaxify( $(this).attr('action') );
//
//	});



	// BETA - Update field direct to database when it loses focus (blur)
	$("input, textarea").live('blur', function(){

		var newValue = "";
		var hiddenID = "#orig_" + $(this).attr("id");
		var origValue = $(hiddenID).attr("value");
		var saveValues = "";

		if ( $(this).attr("type") == "radio" ) {
			newValue = $(this + ":checked").val()
		} else {
			newValue = $(this).attr("value")
		}


		// need to validate the item first before proceeding
		// add it here

		var saveto = "";

		//if ($(this).attr("saveTo").length)
		//{
			saveto = $(this).attr("saveTo");

		//}

		var resultDiv = "#result";
		if ( $("#autosave_" + $(this).attr("id")).length )
		{
			resultDiv = "#autosave_" + $(this).attr("id");

		}
 
		if ( saveto != "" )
		{

			if ( newValue != origValue ) {

				newValue = newValue.replace(/&/gi, "*amp*");

				saveValues = $("#contentID").val() + "~#~";
				saveValues += $(this).attr("saveTo") + "~#~";
				saveValues += newValue + "~#~";
				saveValues += $("#imageID").val();

				// set saving icon
				$(resultDiv).html("")
					.append("")
					.hide()
					.fadeIn(500, function() {
					  $(resultDiv).append("<img src='/_admin/_images/loading.gif' width='16' height='16'>");
				});


				$.ajax({
				  type: "POST",
				  url: "/_admin/modules/rTsaveField.php",
				  data: "data=" + saveValues,
				  success: function(data) {
					$(resultDiv).html("")
					.text("")
					.append("")
					.hide()
					.fadeIn(500, function() {
					  $(resultDiv).append(data);
					});
				  }
				});

				$(hiddenID).attr("value", newValue);

				//return false;

	
			}
		}

		

	});


	// BETA - Update select field direct to database when the value changes (onChange)
	$("select").change(function(){

		var newValue = "";
		var hiddenID = "#orig_" + $(this).attr("id");
		var origValue = $(hiddenID).attr("value");
		var saveValues = "";

		newValue = $(this).attr("value")

		// need to validate the item first before proceeding
		// add it here

		var saveto = "";

		if ($(this).attr("saveTo").length)
		{
			saveto = $(this).attr("saveTo");

		}

		var resultDiv = "#result";
		if ( $("#autosave_" + $(this).attr("id")).length )
		{
			resultDiv = "#autosave_" + $(this).attr("id");

		}
 
		if ( saveto != "" )
		{

			if ( newValue != origValue ) {

				saveValues = $("#contentID").val() + "~#~";
				saveValues += $(this).attr("saveTo") + "~#~";
				saveValues += newValue + "~#~";
				saveValues += $("#imageID").val();
			
				// set saving icon
				$(resultDiv).html("")
					.append("")
					.hide()
					.fadeIn(500, function() {
					  $(resultDiv).html("<img src='/_admin/_images/loading.gif' width='16' height='16'>");
				});


				$.ajax({
				  type: "POST",
				  url: "/_admin/modules/rTsaveField.php",
				  data: "data=" + saveValues,
				  success: function(data) {
					$(resultDiv).html("")
					.text("")
					.append("")
					.hide()
					.fadeIn(500, function() {
					  $(resultDiv).html(data);
					});
				  }
				});

				$(hiddenID).attr("value", newValue);

				//return false;

	
			}
		}

		
	window.lastClickID = "resetsubmit";
	window.lastError = "";

});

