/*
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 id='swd-submit'.

typical implementation <input class='text-input swd-validates-as-required swd-validates-as-text' id="sendername" type="text" name="sendername" value="some value, which can also be called from a class db query" max="75" size="40">

changelog: 2010/12/30 added function for call to class .swd-validates-as-selected, which came from satori-contact-validation.js
changelog: 2010/07/26 changed button actions in swd-submit to only click and reversed the blur and disable actions.
*/
jQuery(document).ready( function($) {
	// define functions
	function decodeURLencode(data){
		// this function decodes data that has been encoded in php using rawurlencode()
		decoded=unescape(data);
		decoded=decoded.replace(/%40/g,"@").replace(/%2A/g,"*").replace(/%2B/g,"+").replace(/%2F/g,"/").replace(/\\/g,"");
		return decoded;
	}

	function fillFields(id,classes){
		var carray=classes.split(" ");
		var clength=carray.length;
		var mid=$('#' + id).attr('data');
		var currentformid=$('#' + id).closest('form').attr('id');// get the current form id
		var fillfielddata=$('#' + currentformid + '-fillfielddata').html();// this is the location of the id of the element where the ajaxrequest info (callfile_public-optin-golf-registration_fillfield) is located along with the

		$.post(page,{
		   'ajaxrequest':fillfielddata,
		   'mid':mid
		   },
		   function(data){
			var darray=data.split(",");// split the data on the commas to get the parts
			dalength=darray.length;

			for(x=0;x<clength;x++){
			// iterate through each field that is named by fillfield-
				if(carray[x].substring(0,10)=="fillfield-"){
					pair=carray[x].split("-");// get the names of the elements that are to be filled.  this will also be the id. the value we need is in the 2nd part of the class
					thisid=pair[1];

					// when the data comes back, it has been prepared with rawurlencode and is in a string like homephone=rawurlencode($homephone),etc.
					for(y=0;y<dalength;y++){
						// unescape the element then split the element into its key and value
						ypair=darray[y].split("=");// split the parts on the = to get the key
						if(ypair[0]==thisid){
							value=decodeURLencode(ypair[1]);// and rawurldecode the value
							$('#' + thisid).val(value);	// assign the value to the field
						}
					}

				}// end of carray substring if statement
				$('#' + thisid).blur();
			}// end of for statement fo clength
		   }
		);
	}

	// define global variables
	var page=document.location.href;
	page=page.replace("#","");

	// autocomplete function to return member name to the text field and the member number to a hidden field.  This requires that we have siteuser in a hidden field so we can pass to the function
	$('.memberlookup').live('focus',function(){
	//	$(this).removeClass('domemberlookup').addClass('memberlookup');
		var siteuser=$('#siteuser').val();
		var memberlookupid=$(this).attr('id');
		$("input.memberlookup").autocomplete({
			//define callback to format results
		source: function(req, add){
			//pass request to server
			$.getJSON("http://satoricontentmanager.net/filelib/jquery/autocomplete-widget.php?siteuser=" + siteuser + "&callback=?", req, function(data) {
			//create array for response objects

			var suggestions = [];
			i=0;
			//process response
			$.each(data, function(i, val){
				suggestions[i]=val;
				i++;
			});
			add(suggestions);
			});
		},

		//define select handler
		select: function(e, ui) {
			var inputid=$(this).attr('id');// get the ids of the input elements
			var guestname=ui.item.label;// assign the variables
			var guestid=ui.item.value;
			$(this).attr('data',guestid);// assign the suggestion value to the mid field
			$(this).val(guestname);
			$(this).blur();
		}
		,
		close: function() {
			$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
			if($(this).hasClass('fillfields')){
				var classes=$(this).attr('class');
				fillFields(memberlookupid,classes);
			}
		}
		});// end post


	});

	// put the focus on the first required element
	$('input.text-input').live('focus',function(){// when the element gets focus, highlight it
		$(this).css({backgroundColor:"#EAEAFF",border:'2px inset black',fontWeight:'bold',color:'#000033'});
		$(".swd-validation-errors").show();
		var id=$(this).attr('id');
		$('#swd_' + id + '_error').remove();
	});

	$('input.text-input').live('blur',function(){
		var itemid=$(this).attr("id");// assign the id of the input element to the variable itemid
		var thiserror=itemid;// set the current error to the itemid
		var itemclass=$(this).attr("class");// get the class of the element and assign it to a variable
		var pd=$('#swd-processing-data').html();
		pdarray=pd.split(':');
		var errors='';
		if($('#swd-errors').val()=='start'){
			$('#swd-errors').val('');// clear the initial value of the swd-error log since processing has now started
		}

		$(this).css({backgroundColor:"#FFFFFF",fontWeight:'normal',color:'#000000'});
		$('#' + itemid + '-modify').checked='';
		    $.post(page,{
				'ajaxrequest':pdarray[0],
				'attributes':pd,
				'f':itemid,
				'value' : $('input#' + itemid).val(),
				'class' : itemclass,
				'id' : itemid},
				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
					errors=$("#swd-errors").val();// get the existing errors
					var found=errors.indexOf(itemid);// check the existing errors for a match with the itemid
					var divid="div" + itemid;
					var newerrorcount='';
					var errorarray='';
					var newerrorstring='';
					if(validated==1 && validresult==1){// this was successfully validated
						$('input#' + itemid).val(validvalue);// assign the data to the input element if it is valid
						thiserror='';// the current is set to blank
						if(found>=0){// if the error already exists, we now need to remove it since the error has been corrected
							if(errors.length>0){
								errorarray=errors.split('&&' + itemid);// split the original errors with the itemid
								newerrorcount=errorarray.length;
							}
							else{
								errorarray='';
								newerrorcount=0;
							}
							if(errorarray.length==2){
								if(errorarray[0].length>0){
									newerrorstring=errorarray[0];
								}
								else{
									newerrorstring='';
								}

								if(errorarray[1].length>0){
									newerrorstring=newerrorstring+errorarray[1];
								}

							}
						}
					}
					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 there is an error for this itemid, do nothing, otherwise, add it to the error string
							if(found<0){// add the error to the end of the string
								newerrorstring=errors + "&&" + itemid;
								if($("#swd_" + itemid + "_error").length==0){
									$('#swd_' + itemid).after("<div id='swd_" + itemid + "_error' style='background-color:#FFFFB9;color:red;font-weight:bold;border:1px solid red;width:200px;position:relative;top:-5px;left:30px;'>" + $('#swd_' + itemid).attr('data') + "</div>");
								}
							}
						}
						else{// the only remaining option is that the validation itself failed
							$('#swd-validation-errors').append("<div id='" + divid + "' style='background-color:blue;color:red'>Fatal Error - Validation Failed</div>");
						}
					}

					if(data=='invalid'){
						newerrorstring=errors + '&&Fatal Validation Error';
					}

					if(newerrorstring!=''){
						$("#swd-errors").val(newerrorstring);// replace the error string in the form
						if($("#swd_" + itemid + "_error").length==0 && itemid==thiserror){
							$('#swd_' + itemid).after("<div id='swd_" + itemid + "_error' style='background-color:#FFFFB9;color:red;font-weight:bold;border:1px dashed red;width:200px;position:relative;top:-5px;left:30px;'>" + $('#swd_' + itemid).attr('data') + "</div>");
						}
					}
					else {// if there are no errors, clear the field and hide it
						$(".swd-validation-errors").hide();
						$('.swd-validation-errors').html(newerrorstring);
						$('#swd-errors').val('');
					}// end newerrorstring if statement

				});// end post and data function call

			});// end input.text function

	$('#bccs').live('blur',function(){
		if($('#bccs').val()!=''){
			var string=$('#bccs').val().replace(",",";");
			string=string.replace(";","<br>");
			if($("#swd_bccs_error").length==0){//display a warning if they are adding bccs
				$('#swd_bccs').after("<div id='swd_bccs_error' style='background-color:#FFFFB9;color:red;font-weight:bold;border:1px dashed red;width:200px;position:relative;top:-5px;left:30px;'>" + $('#swd_bccs').attr('data') + "You entered:<br>" + string + "<br>Click here to remove this message.</div>");
			}
		}
	});// end of the bccs section

	$("#swd_bccs_error").live('click',function(){
		$("#swd_bccs_error").remove();
	});//end of the bccs error section

	// send the message if validation shows no errors
	// check for an instance of the text editor since this will indicate that javascript is working, they have focused on the subject field and must have started the validation routine

	$('#swd-submit-enable').live('click',function(){
		$('#processgroupemail').attr('disabled',false);
		$('#dialog_messages').dialog('close');

	});

	$('.swd-submit').live('click',function(){

		if($('#swd-errors').val()=="")
		{
			$(this).attr('disabled','disabled').blur();

			var datalist='';
			if (typeof(WPro) != 'undefined' && typeof(WPro.editors['editor']) != 'undefined'){
				if(WPro.editors['editor'] )
				{
					datalist='message=' + WPro.editors['editor'].getValue();
				}
			}
			else{
				if($( ':input.jquery_ckeditor' ).val()!=undefined){
					datalist = 'message=' + $( ':input.jquery_ckeditor' ).val();
				}

			}


			$(':input.formfield').each(function(){
				datalist=datalist + '%%' + $(this).attr('name') + '=' + $(this).val();
			}); // end each statement

			// get the radio buttons
			$("input:radio:checked").each(function(){
				datalist=datalist + '%%' + $(this).attr('name') + '=' + $(this).val();
			});// end radio button section

			// get the checkboxes
			$("input:checkbox:checked").each(function(){
				datalist=datalist + '%%' + $(this).attr('name') + '=' + $(this).val();
			});// end checkbox section

			// get the delivery date and time and create the senddate
			var ddate=$('#deliverydate').val();
			var dtime=$('#deliverytime').val();
			var senddate=ddate + " " + dtime;
			datalist=datalist + "%%senddate=" + senddate;
			var id=$(this).attr('id');

			$.post(page,{
			   'ajaxrequest':id,
			   'datalist':datalist
			   },
			   function(data){
				array=data.split("::");// the data field must contain the slidedown action, so we need to ignore it
				var destination_id=array[1];
				if($('#dialog_messages').length==1){
					$('#dialog_messages').dialog({autoOpen:false,dialogClass:'dialogboxbold',title:'Message Sending Results',width:600}).dialog('open').html(array[3]);
				}
				else{
					$('#dialog_messages').dialog('open').html(array[3]);
				}
			   }
			);

		}// check for errors in the error log (swd-errors)
		else{
			// there are still errors, show an alert
			if($('#dialog_messages').length==1){$('#dialog_messages').dialog({autoOpen:false,dialogClass:'dialogboxbold',title:'Message Errors',width:'300'}).dialog('open').html('There are still errors that must be fixed before you can send this message.  Please fix the errors and try again.');// replaced the alert with a dialog box
			}
			else{
				$('#dialog_messages').dialog('open').html(array[3]);
			}

		}

	});// end of the swd-submit loop

	$('.closemc').live('click',function(){
		if (typeof(WPro) != 'undefined' && typeof(WPro.editors['editor']) != 'undefined'){
			WPro.deleteEditor('editor');
			$('.wproEditor').first().hide();

		}

		if($('#message').hasClass('jquery_ckeditor')){
			//get editor instance, which will always be message for message center
			var editor = CKEDITOR.instances.message;
	        
	        //remove the editor instance
			CKEDITOR.remove(editor);
		}

		$('#messagecenter').slideUp('1000').empty();
		$('#dialog_messages').dialog('close');
		$('#mask').hide();
		return false;
	});// end of the closeall loop

// this is used for the web mail form on public pages
	$(".swd-validates-as-selected").live('click',function() {
			var done=0;// this variable is used
		// validate and process form if there are no errors.  First, check for errors, then proceed if there are none
//		$(this).select().focus();
		var checkrequired='';
		$('.swd-validates-as-required').each(function(){// check to see if all required field are completed.  if not, set a value for the missing fields
			if($(this).is(".text-input")){
				if($(this).val()==''){
					$(this).focus();
					$(this).css({'border':'2px solid red'});// highlight the field in red
					checkrequired=checkrequired + '&&' + $(this).attr('id');
				}
			}

		});
		
		if(checkrequired!=''){$('#swd-errors').val(checkrequired);}

		if($('#swd-errors').val()==''){// if there are no validation errors allow the sending of the form
//			$(".swd-validation-errors").empty();
			// first hide any error messages

			var datalist='';
			var processingpage=$('.swd-processing-page').html();
			if(done==0){
				done=1;
				$('.text-input').each(function(){
				datalist=datalist + '%%' + $(this).attr('name') + '=' + $(this).val();
				}); // end each statement

					$.post(page,{
					ajaxrequest:processingpage,
					datalist:datalist
				},
				function(data){
						if(data=='close'){
							$('#dialog').empty();
							// this is for a dialog box, so close the box
							$('#dialog').dialog('close');
						$('#swd-errors').empty();
						done=0;
						}
					else{
						var darray=data.split(':');
						if(darray[0]=='replace'){
							$('#dialog').html(darray[1]);
						}

					}
				});// end function and post
			}// end if statement (done==0) for processing
 //  return false;
			}
		else{// this is the option to show validation errors
		$(".swd-validation-errors").html("<p style='color:red'>There are validation errors.  Please fix the fields outlined in red</p>");
		}
	});// end swd-validates-as-selected loop

});// end main jquery call

