/*
implementation notes: elements in the form should use class attributes to call these actions.

This file uses the filelib/jquery/functions.validation.php file to validate data, so new validation methods can be added there.

The submit button must use the class='submit-button'.

typical implementation <input class='jq-form-validation jq-validates-as-required jq-validates-as-text (validated or dovalidate)' id="sendername" type="text" name="sendername" value="some value, which can also be called from a class db query" max="75" size="40">

for each element to be validated, it must have a class of dovalidate or validated
onblur from any element causes a check for dovalidate class, if none, activate the submit button
when an element is validated, replace the class dovalidate with class validated
when the form is loaded, the parent form should run a script to assign validated class to any pre-loaded variables and disable the submit button
*/
$(function() {

	// common variables
	var page=document.location.href;
	page=page.replace("#","");// we'll post back to the originating page

/* common functions used in this file ######################################*/
	function checkSubmitButton(){
		var dovalidate=0;
		// check all of the elements to see if it's time to activate the submit button
		$('input').each(function(){
			if($(this).hasClass('dovalidate')){
				dovalidate=dovalidate+1;
			}
		});
		if(dovalidate==0){
			// activate the submit button - since there are two possible, active them both
			$('.submit-button').attr('disabled',false);
		}
		else{
			$('.submit-button').attr('disabled','disabled');
		}
	}

	function displayError(itemid){
		$('input#' + itemid).val('').addClass('required dovalidate').removeClass('validated');// return a blank to the form field and set the class to required and add the error to the validation div
		var divid='div'+itemid;
  		var divcontents=$('#' + divid).html();
		if(divcontents==null){
			$('#' + 'jq_' + itemid).append("<div class='shadows-10 validation-error' id='" + divid + "'>" + $('#' + 'jq_' + itemid).attr('data') + "</div>");
		}

	}

	function showErrors(data,itemid){
		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 divid="div" + itemid;

  		if(validated==1 && validresult==1){// this was successfully validated
  			$('input#' + itemid).val(validvalue).addClass('validated').removeClass('dovalidate');// assign the data to the input element if it is valid and add the validated class
  			$('#' + divid).remove();// remove any error message
  		}
  		else{
  			// the data was not validated or validation failed
  			if(validated==1 && validresult==0){
  				// data was validated, but is not valid
				displayError(itemid);
  			}
  			else{// the only remaining option is that the validation itself failed
				if(validerror==''){validerror='Validation has failed.  Please have your webmaster contact Satori Web Design is this continues';}
  				$('#dialog').html(validerror);
  			}
  			$('.submit-button').attr('disabled','disabled');// disable the submit button
  		}
	}

/* End common functions used in this file ####################################*/

	$('input.jq-form-validation:first').focus().addClass('active');// put the focus on the first element

	$('.jq-validates-as-required').each(function(){
		if($(this).val()!==''){// this is data from the db, so as long as it's present, we can use it
			$(this).addClass('validated required');
		}
		else{
			$(this).addClass('dovalidate required');
		}
	});// end each function for input-text

	// Dialog Link
	$('.jq_form_link').live('click',function(){
		var requesttype=$(this).attr('id');
		var attributes=$(this).attr('data');
		var title=$(this).attr('title');
		var editable=null;
		if(title!==''){
			$('#dialog').dialog('option', 'title', title);
		}
		if($(this).hasClass('modal')){
  			$('#dialog').dialog('option','modal',true);
		}

    	$('#dialog').load(page,{
			'ajaxrequest':requesttype,
			'attributes':attributes
			},
			function(data){
				if($('#dialog').dialog('isOpen')==false){
					$('#dialog').dialog('open');
					$('#dialog').focus();
				}
				$('#dialog').html(data);// add the data to the div
				$('.adddatepicker').addClass('datepicker').removeClass('adddatepicker');
				$('.datepicker').datepicker({
					inline:true,
					dateFormat: 'yy-mm-dd',
					altField:'#alternate',
					altFormat: 'DD, d MM, yy',
					changeYear:true,
					changeMonth:true
				});

				editable=$('#editable').val();// look for the editable hidden element
				if(editable=='no'){
					// set the elements that should not be edited to readonly if necessary
					$('.editable').each(function(){
						$('.editable').attr('readonly','readonly').removeClass('dovalidate').addClass('validated');
					});// end of editable function
				}

				checkSubmitButton();
			});
		return false;
	});// end form_link

	$('input.jq-validates-as-match').live('keyup',function(){
		var id=$(this).attr('id');
		var divid="div" + id;
		var id1=id.split("_");
		da[1]=$('#' + id1[0]).val();
		var matchvalue=$(this).val();
		if(matchvalue==da[1]){
			$('#' + id + 'ok').show('fast');
			$(this).removeClass('dovalidate').addClass('validated');
			$('#' + divid).hide('slow');
		}
		else{
			$('#' + id + 'ok').hide('fast');
			$(this).removeClass('validated').addClass('dovalidate');
		}
		checkSubmitButton();
	});// end of the validatates as match

	$('input.jq-form-validation').live('blur',function(){// this is the validation of a form.  This option has the form go back to its own page for validation, unlike the jq-form option below, which is only intended for optinprocessing
		if($(this).val().length<$(this).attr('min')){
			displayError($(this).attr('id'));
		}
		$(this).removeClass('active');// remove the active class when we leave a field

		// assign the variables needed for validation
		var itemid=$(this).attr('id');// with an id that goes through the processing file back to the originating form
		var itemclass=$(this).attr('class');
		var errormessage=$(this).attr('data');
		var matchvalue=null;
		var value=$(this).val();

		// if this is a must-match element, we have to find the value of the first item
		if($(this).hasClass('jq-validates-as-match')){
			var id1=itemid.split("_");
			matchvalue=$('#' + id1[0]).val();
		}

	    $.post(page,{
			'ajaxrequest':'validateinput',
			'validation':itemid,// this tells the originating form file that this is a validation action
			'value' : value,
			'attributes':matchvalue,
			'f':errormessage,
			'class' : itemclass
		},
			function(data){
				showErrors(data,itemid);
				checkSubmitButton();
			});// end input-text section
		});// end post and data function call for form self submission

	$('.submit-button').live('click',function(){// check the submit button to see if it should be activated
		$(this).attr('disabled','disabled');
		checkSubmitButton();
	});

	$('.googleid').live('keyup',function(){
		// extract the google id from the provided code and display an OK checkmark once validate
		var id=$(this).attr('id');
	    $.post(page,{
			'ajaxrequest':'googleanalytics_validate',
			'value' : $(this).val()
		},
			function(data){
				$('#' + id).val(data);
			});// end input-text section

	});

});// end main jquery call

