jQuery(document).ready( function($) {


$(function() {
	var newerrorstring="";
	var done=0;
	var nodata=0;
  $('.error').hide();

  $('input.text-input').css({backgroundColor:"#FFFFFF"});

  $('.modify').focus(function(){
		if($(this).checked=='checked'){
			var thiskey=$(this).attr('id');
			var modifyclientid=$(this).val();
			$.post("../wp-content/plugins/booktracker/functions.booktracker.php",{
				'f':'modify',
				'infotype':thiskey,
				'modifyclientid':modifyclientid,
		   		'value':$('#' + thiskey).val()
				}
			);

		}

  });

  $('input.text-input').focus(function(){

    $(this).css({backgroundColor:"#FFDDAA",border:'2px inset black'});
//	$(".swd-validation-errors").show();
  });

  $('.getinfolink').focus(function(){
	$(".swd-validation-errors").hide();
  });

  $('input.text-input').blur(function(){
	var itemid=$(this).attr("id");// assign the id of the input element to the variable itemid
	var itemclass=$(this).attr("class");// get the class of the element and assign it to a variable
	$(this).css({backgroundColor:"#FFFFFF"});
	$('#' + itemid + '-modify').checked='';

    $.post("../wp-content/plugins/booktracker/functions.validation.php",{
			'f':itemid,
			'value' : $('input#' + itemid).val(),
			'class' : itemclass},
			function(data){
		        var dataarray=data.split("&&");// split the returned message into an array
				// the array that is returned the keys will be in this format:
				// validated=0, valid-result=1,valid-value=2
				var validated=dataarray[0].substring(10);// 0 (validation failed) or 1 (validation occured)
				var validresult=dataarray[1].substring(13);// 0 (invalid) or 1 (valid)
				var validvalue=dataarray[2].substring(12);// value of the data
				var validerror=dataarray[3].substring(12);// the error message from validation
				var errors=$(".swd-validation-errors").html();// get the existing errors
				var found=errors.match(itemid);// this gives us the matched value of the error if it exists in the error string
				var divid="div" + itemid;

				if(validated==1 && validresult==1){// this was successfully validated
					$('input#' + itemid).val(validvalue);// assign the data to the input element if it is valid
	  		   		if(found==itemid){// there is a match and the value has been validated, so remove the entry from the list
						var replaceitem='&amp;&amp;' + itemid;
						newerrorstring=errors.replace(replaceitem,'');// if there is an error for this itemid, remove it from the error string
				 	}
				}
				else{
					// the data was not validated or validation failed
					if(validated==1 && validresult==0){
						// data was validated, but is not valid
						$('input#' + itemid).val('');// return a blank to the form field
						$('input#' + itemid).css({'border':'2px solid red'});// highlight the field in red
						if(found!=itemid){// there is no match and the value has failed validation, so add the entry to the list
						newerrorstring=errors + '&&' + itemid;// if there is an error for this itemid, add it to the error string
				 	}

					}
					else{// the only remaining option is that the validation itself failed
						$('#swd_div_id_name_first').append("<div id='" + divid + "' style='background-color:blue;color:red'>Fatal Error - Validation Failed</div>");
						newerrorstring=errors + '&&Fatal Validation Error';
					}

				}

				$(".swd-validation-errors").html(newerrorstring);// move var to form for use outside of function

			});// end main function call - function vars no longer defined and end of post
		});// end input blur function
	// cut from here

	// begin processing
//	$(".swd-validation-errors").show();// here for debugging

	$(".swd-validates-as-selected").bind('click',function() {
       	newerrorstring=$(".swd-validation-errors").html();// assign the form value to the variable

		// test to see if there are blank fields if the error string is blank
		if(newerrorstring.length==0){
			$("input.swd-validates-as-required").each(
				function(){
					if($(this).val()==''){
						nodata=1;// mark this so we know there's a missing field
					}
				}
			);
			if(nodata==1){// check for the missing field flag
				alert('There are required fields that have not been completed.  Please complete the required fields.');
				done=1;// set the done var
				nodata=0;// reset the nodata var
			}
			else done=0;// passed all fields completed, change done back to 0
		}

		if(newerrorstring.length==0){
			// validate and process form
			// first hide any error messages
	    	$('.error').hide();

			if(done==0){
				done=1;
		//   		alert('processing' + newerrorstring + ' with length ' + newerrorstring.length);
	$.post("../wp-content/plugins/booktracker/functions.booktracker.php",{
		'f':'addres',
		'name_first':$("#name_first").val(),
		'name_last':$("#name_last").val(),
	  	'email':$("#email").val(),
	  	'phone1':$("#phone1").val(),
	  	'phone2':$("#phone2").val(),
		'book_id':$("#book_id").val(),
		'client_id':$("#clientid").val(),
		'activity_title':$("#activity_title").val(),
		'activity_location':$(this).val(),
		'rememberme':$("#rememberme").val()
		},
		function(activity_location){
	 	  alert('Your request has been submitted.  The ' + activity_location + ' library will contact you when your selection becomes available');
 		  window.location='http://saddlebrookelibraries.org/?page_id=14';

		}
     );
	 		}// end if statement for processing
  //  return false;

		}

	else{
		// highlight the first validation error in red
		var highlights=newerrorstring.split("&amp;&amp;");// split the returned message into an array
		var highlight=highlights[1];// get the name of the first field
		$('input#' + highlight).val('');// return a blank to the form field
		$('input#' + highlight).css({'border':'2px solid red'});// highlight the field in red
		alert('There are validation errors. Please fix the field outlined in red.');
		done=0;
	}

	});


//$(".swd-debug").html(' newerrorstring is ' + newerrorstring);

		 //	});

  });

  $("#rememberme").click(function(){
  	$("#rememberme").val('1');
  });


$(".ajax-loader").ajaxStart(function(){// show the animated gif when loading ajax
   $(this).show();
 });

$(".ajax-loader").ajaxStop(function(){// hide the animated gif
   $(this).hide();
 });


//});// end main function call

runOnLoad(function(){

  $("input#name_first").select().focus();

});

$('.swd-validates-as-selected').click(function(){
	$(this).select().focus();
});

});// end main jquery call

