/*
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/07/26 changed button actions in swd-submit to only click and reversed the blur and disable actions.
*/
jQuery(document).ready( function($) {

	// 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='';
		var page=document.location.href;
		page=page.replace("#","");
		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-validation-errors").show();
				//	   	$(".swd-validation-errors").html('working on itemid of ' + itemid + ' and the errorcount is ' + newerrorcount + 'found is ' + found + ' for the errors ' + errors + ' and the errorstring is ' + newerrorstring).css({backgroundColor:'#FFFFFF'});
						$("#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 page=document.location.href;
			var id=$(this).attr('id');
			page=page.replace("#","");
			$.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();
		}
		$('#messagecenter').slideUp('1000').empty();
		$('#dialog_messages').dialog('close');
		$('#mask').hide();
	});// end of the closeall loop

});// end main jquery call
