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

	$().ajaxSend(function(r,s){
		$("#loadingMessage").show();
	});// loading function to show loading

	$().ajaxStop(function(r,s){
		$("#loadingMessage").fadeOut("fast");
	}); // loading function to make loading disappear


	// Accordion
	$("#accordion").accordion({
		header: "h3",
		autoHeight: false
		 });

	$("#dynamicaccordion").accordion({
		active:0,
     	change: function() {
     		var active=($('.ui-state-active').attr('id'));
	        $.post('#',
				{'ajaxrequest':active
				},
				function(content){
					if(active){
						var idarray=active.split(":");
						$('#' + idarray[1]).html(content);
					}
				}
			);
},
		header: "h3",
		autoHeight:false,
		collapsible:true,
		navigation:true
	});
	/*
	this section handles sorting the officers list and passing updates to the db
################################################################################
	*/

	$(function() {
		$(".sortable").sortable(
			{
				handle:'.handle',
				update:function(){
					var order=$(this).sortable('serialize');
//					$("#info").html(order);// output the content to a div for viewing when debugging
					var requesttype=$(this).attr('id');
                	$.post('#',
						{'ajaxrequest':requesttype,
						'order':order
						}
					);
				}
			}

		);
		$(".sortable").disableSelection();
	});


/* end of section t handle sorting of officers list
################################################################################
*/
	// Tabs
	$('#tabs').tabs();


	// Dialog
	$('#dialog').dialog({
		autoOpen: false,
		width: 600,
		buttons: {
			"Cancel": function() {
				$(this).dialog("close");
			}
		}
	});

	$('.dialog_test').live('click',function(){
		var page=document.location.href;
		alert('on page ' + page);
		var requesttype=$(this).attr('id');

	   	$('#dialog').load(page,{
			'ajaxrequest':requesttype
			},
			function(data){
				$('#dialog').html(data);// add the data to the div
			}
		);
  		$('#dialog').dialog('open');
		$('#dialog').focus();

		return false;


	});

	// Dialog Link
	$('.dialog_link').live('click',function(){
		var requesttype=$(this).attr('id');
		var attributes=$(this).attr('data');
		var title=$(this).attr('title');
		if(title!=''){$('#dialog').dialog('option', 'title', title);}
		var page=document.location.href;
		page=page.replace("#","");

    	$('#dialog').load(page,{
			'ajaxrequest':requesttype,
			'attributes':attributes
			},
			function(data){
				$('#dialog').html(data);// add the data to the div
					$('.processvaluetrigger').bind('click',function(){
						$('#processvalue').val($(this).val());
					});

                	$('.ajaxupdate').bind('click',function(){
                		var msg='';
						$.post(page,
							{'ajaxrequest':requesttype,
							'requesttype':'process',
							'value':$('#processvalue').val()},
							function(data){
								if(data>0){
									$('#dialog').dialog("close");// close the dialog box
									var idarray=requesttype.split(":");
									if(idarray[4]){$('#' + idarray[4]).html($('#processvalue').val());}// set the value of the item in the list
								}
                                else if (data.substring(7,0)=='invalid'){
                                	msg=data.split(":");
									alert(msg[1]);
								}
								else if (data.substring(7,0)=='replace'){
									// replace the value in the dialog with the new html
									msg=data.split(":");
									var id=msg[1];
									var content=msg[3];
									$('#dialog').html(content);
                                    $('.ajaxupdate2').bind('click',function(){
										$.post('#',
											{'ajaxrequest':requesttype,
											'requesttype':'process',
											'value':$('#processvalue').val()},
											function(data){
                                                if(data>0){
													$('#dialog').dialog("close");// close the dialog box
													var idarray=requesttype.split(":");
													$('#' + idarray[4]).html($('#processvalue').val());// set the value of the item in the list
												}
				                                else if (data.substring(7,0)=='invalid'){
				                                	msg=data.split(":");
													alert(msg[1]);
												}
												else{
													$('#dialog').html('We apologize, but there was a problem in processing your request.  Please notify Satori Web Design, LLC of the problem.');		}
											});
									});

								}
								else if(data.substring(3,0)=='msg'){// an option to leave everything in place but return a msg alert
									msg=data.split(":");
									alert(msg[1]);
									if(msg[2]=='reload'){location.reload();}
								}
								else if(data.substring(7,0)=='element'){// replace an element in accordion with a new value
									msg=data.split(":");
									$('#' + msg[1]).html(msg[2]);
									if(msg[4]){
										// there is a second element to replace, is it data or another element?
										if(msg[4]=='data'){
											$('#' + requesttype).attr('data',msg[5]);
										}
										else{
										$('#' + msg[4]).html(msg[5]);
										}
									}
									if(msg[3] && msg[3]!=''){// if there is a msg 3 element and it is not blank, show the message as an alert
										$('#dialog').html(msg[3]);
									}
									else {$('#dialog').dialog("close");}// close the dialog box
								}
								else if(data.substring(7,0)=='message'){
									msg=data.split(":");
									$('#dialog').html(msg[1]);
								}
								else {$('#dialog').html('We apologize, but there was a problem in processing your request.  Please notify Satori Web Design, LLC of the problem.');}
						  //
							});
					return false;
					});// end ajaxupdate function

                	$('.ajaxadd').click(function(){
						$.post(page,
							{'ajaxrequest':requesttype,
							'requesttype':'process',
							'processkey':$('#processkey').val(),
							'parentid':$('#parentid').val(),
							'value':$('#processvalue').val()},
							function(data){
								if(data==-1){
									$('#dialog').html('We apologize, but there was a problem in processing your request.  Please notify Satori Web Design, LLC of the problem.');

									}
                                else if (data.substring(7,0)=='invalid'){
                                	var msg=data.split(":");
									alert(msg[1]);
								}
								else{
                  					$('#dialog').dialog("close");// close the dialog box
									var idarray=requesttype.split(":");
									// add a new element to the list
									$('#' + $('#parentid').val()).append(data);
									$('#parentid').sortable('refresh');
								}
							});
					return false;
					});// end ajaxadd function


                	$('.ajaxdelete').click(function(){
						$.post(page,
							{'ajaxrequest':requesttype,
							'requesttype':'process',
							'value':$('#processvalue').val()},
							function(data){
								if(data>0){
									$('#dialog').dialog("close");// close the dialog box
								/*	alert('You have deleted the entry ' + requesttype);*/
									var idarray=requesttype.split(":");
									$('#' + idarray[4]).remove();// set the value of the item in the list
									}
									else {$('#dialog').html('We apologize, but there was a problem in processing your request.  Please notify Satori Web Design, LLC of the problem.');}
						  //
							});
						return false;
					});// end ajaxdelete function

				$('.ajaxreload').click(function(){
					location.reload();
				});

		});

  		$('#dialog').dialog('open');
		$('#dialog').focus();

		return false;
	});

		$('.ajaxtest').live('click',function(){
			var id=$(this).attr('id');
  			alert('testing ' + id + ' and the parameters are: ' + $('#' + id + 'parameters').html());
			return false;
		});

		$('.ajaxquickcheck').live('click',function(){
			var id=$(this).attr('id');
			$.post('#',
				{
					'ajaxrequest':id
				},
				function (data){
					msg=data.split(":");
					if(msg[0]=="msg"){alert(msg[1]);}
				}
			);
		});// end ajaxquickcheck

		$('.ajaxchecktodb').live('click',function(){
			var id=$(this).attr('id');
			var value=$(this).val();
			var boxchecked=0;

			if($('#' + id).is(':checked')){
				boxchecked=1;
			}

  	   		var parameters=$('#' + id + 'parameters').html();
			if(value=="test"){alert("Debugging returns " + id + ' as the id and the value of ' + value + ' boxchecked equals ' + boxchecked + ' and parameters of ' + parameters);}


			var page=document.location.href;
			$.post(page,
				{
					'ajaxrequest':parameters,
					'id':id,
					'boxchecked':boxchecked,
					'value':value
				},
				function (data){
					msg=data.split(":");
					if(msg[0]=="msg"){alert(msg[1]);}
					if(msg[0]=="element"){$('#' + msg[1]).html(msg[2]);}// change out an element on the page
				}
			);
		});// end ajaxchecktodb

   		$('.ajaxradiotodb').live('click',function(){
			var id=$(this).attr('id');
			var radioname=$(this).attr('name');
			var value=$(this).val();
			var boxchecked=0;

			if($('#' + id).is(':checked')){
				boxchecked=1;
			}

  	   		var parameters=$('#' + radioname + 'parameters').html();
			if(value=="test"){alert("Debugging returns " + id + ' as the id and the value of ' + value + ' boxchecked equals ' + boxchecked + ' and parameters of ' + parameters);}


			var page=document.location.href;
			$.post(page,
				{
					'ajaxrequest':parameters,
					'id':id,
					'boxchecked':boxchecked,
					'value':value
				},
				function (data){
					msg=data.split(":");
					if(msg[0]=="msg"){alert(msg[1]);}
					if(msg[0]=="element"){$('#' + msg[1]).html(msg[2]);}// change out an element on the page
					if(msg[3]=="close"){$('#dialog').dialog('close');}
					if(msg[4]){
						// there is a second element to replace, is it data or another element?
						if(msg[4]=='data'){
							$('#' + requesttype).attr('data',msg[5]);
						}
						else{
						$('#' + msg[4]).html(msg[5]);
						}
					}
				}
			);
		});// end ajaxradiotodb


		// this function uses a parameter element to provide details about the transaction that cannot be provided in the id because jquery will not process correctly if there are : in the id.  Also, use a underscore in the id
		$('.ajaxcheckboxprocess').live('click',function() {
			var id=$(this).attr('id');
			var boxchecked=0;

			if($('#' + id).is(':checked')){
				boxchecked=1;
			}
  	   		var requesttype=$('#' + id + 'parameters').html();

			var page=document.location.href;
            $.post(page,
				{'ajaxrequest':requesttype + ':boxchecked=' + boxchecked
				},
				function(data){
					$('#' + id + 'content').html(data);
				}
			);

			});

		$('.hiddenmessage').live('click',function(){
				var hmname=$(this).attr('name');
				var hiddenmessageid=$(this).attr('name') + 'hiddenmessage';
				alert($("#" + hiddenmessageid).html());
				$('.' + hmname).removeClass('hiddenmessage');

			}); // end send hidden message

		$('.onetimemessage').live('click',function(){
			var hmname=$(this).attr('name');
			var hiddenmessageid=$(this).attr('name') + 'onetimemessage';
			alert($("#" + hiddenmessageid).html());
			$('.onetimemessage').removeClass('onetimemessage');
		});// END onetimemessage


		$('.ajaxformprocess').live('click',function(){
			// process a form
			var id=$(this).attr('id');
			var i=0;
			var datalist='';
			var page=document.location.href;

			$('.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 - untested, but should work as does radio buttons
			$("input:checkbox:checked").each(function(){
				datalist=datalist + '%%' + $(this).attr('name') + '=' + $(this).val();
			});// end checkbox section

/*			// get the select elements
			$("select.formselect option:selected").each(function(){
				datalist=datalist + '%%' + $(this).attr('name') + '=' + $(this).val();
			});// end checkbox section
*/
			if(id=='test'){alert('in test mode.  Datalist is ' + datalist);}

            $.post(page,{
			   'ajaxrequest':id,
			   'datalist':datalist
			   },
			   function(data){
				var msgarray=data.split(':');
				if(msgarray[0]=='msg'){
					alert(msgarray[1]);
					if(msgarray[2]){
					}
				}

				if(msgarray[0]=='dialog'){// display the dialog box with the message
					$('#dialog').html(msgarray[1]);// add the data to the div
					$('#dialog').dialog('open');
					$('#dialog').focus();
				}

				if(msgarray[0]=="refresh"){
					alert(msgarray[1]);

					$("#dynamicaccordion").accordion('destroy').accordion({
						active: 0,
				     	change: function() {
				     		var active=($('.ui-state-active').attr('id'));
					        $.post('#',
								{'ajaxrequest':active
								},
								function(content){
									if(active){
										var idarray=active.split(":");
										$('#' + idarray[1]).html(content);
									}
								}
							);
				},
						header: "h3",
						autoHeight:false,
						collapsible:true,
						navigation:true
					});

				};

				if(msgarray[0]=="reload"){
					alert(msgarray[1]);
					location.reload();
				};// end reload

				if(msgarray[0]=="replace"){
					// replace the html in the element
					var content=msgarray[1];
					contentarray=content.split("=");
					$('#' + contentarray[0]).html(contentarray[1]);
					if(msgarray[2]){
						var content2=msgarray[2];
						contentarray2=content2.split("=");
						$('#' + contentarray2[0]).html(contentarray2[1]);
					}

				}

				if(msgarray[0]=="confirm"){
					if(confirm(msgarray[1])){// show a confirm box
						requesttypearray=msgarray[2].split("=");
						var requesttype=requesttypearray[1];
						$.post('#',
							{
								'ajaxrequest':requesttype,
								'datalist':msgarray[3]
							},
							function(data){
								if(data=="reload"){location.reload();}
							}
					);// use a post to execute the action
				return false;
				}
			}// end the confirm option

			if(msgarray[2]=="msg"){
				alert(msgarray[3]);
			}

			   });
			$('#dialog').dialog("close");// close the dialog box
			return false;

		});// end ajaxformprocess


		$('.displaycontent').live('click',function() {
			var id=$(this).attr('id');
			var page=document.location.href;
			var requesttype=$('#' + id + 'parameters').html();
			if(id.substring(4,0)=='test'){alert('test and requesttype is ' + requesttype);}
            $.post(page,
				{'ajaxrequest':requesttype
				},
				function(data){
                	if(id.substring(4,0)=='test'){alert('returned data is ' + data);}

					$('#' + id + 'content').html(data);
				}
			);

			$('#' + id + 'content').toggle('slow');
			return false;
			});


		$('.placefile').live('click',function() {
			var id=$(this).attr('id');
			var requesttype=$('#' + id + 'parameters').html();
			var idarray=requesttype.split(":");
			var placeid=idarray[1];
            $.post('#',
				{'ajaxrequest':requesttype
				},
				function(data){
					$('#' + placeid).html(data);
				}
			);

			$('#' + placeid).show('slow');
			return false;
			});

		$('.showfile').live('click',function() {
			// the construction for the id is php-request-action_next-action_id-where-file-to-be-placed_parameters-if-needed
			var id=$(this).attr('id');
			var idarray=id.split("_");
			var requesttype=idarray[0];
			var nextaction=idarray[1];
			var placeid=idarray[2];
			var parameters='';
			var attributes=$(this).attr('data');
			var page=document.location.href;
			page=page.replace("#","");

            $.post(page,
				{'ajaxrequest':id,
				'attributes':attributes
				},
				function(data){
					$('#' + placeid).html(data);
				}
			);

			$('#' + placeid).show('slow');
			return false;
			});

		$(".showhelp").live('click',function(){
			var id=$(this).attr('id');
			var q=$(this).attr('data');
			$.post("http://satoricontentmanager.net/filelib/jquery/gethelp.php",{
				'q':q
				},function(data){
					$('#' + id).after("<span class='helpbox'>" + data + "</span>");
					$('#' + id).show('slow');
				}

			);

		});

		$(".helpbox").live('click',function(){
			$(this).hide('slow').empty();
		});
/* ########################### LIVE SORT ##################################### */
    	$(".livesort").live('mousedown',function() {
		$(".livesort").sortable(
			{
				handle:'.handle',
				update:function(event,ui){
					var order=$(this).sortable('serialize');
//					$("#info").html(order);// output the content to a div for viewing when debugging
					var requesttype=$(this).attr('id');
                	$.post('#',
						{'ajaxrequest':requesttype,
						'order':order
						}
					);
				}
			}

		);
		$(".livesort").disableSelection();
	});

//############################## LIVE PREPEND ##################################

       	$('.ajaxprepend').live('click',function(){

       		var requesttype=$(this).attr('id');
			var idarray=requesttype.split(":");
			var parentid=$('#parentid').val();
			var value=$('#processvalue').val();
			var processkey=$('#processkey').val();
			$.post('#',
				{'ajaxrequest':requesttype,
				'requesttype':'process',
				'processkey':processkey,
				'parentid':parentid,
				'value':value},
				function(data){
					if(data==-1){
						$('#dialog').html('We apologize, but there was a problem in processing your request.  Please notify Satori Web Design, LLC of the problem.');

						}
                             else if (data.substring(7,0)=='invalid'){
                             	var msg=data.split(":");
						alert(msg[1]);
alert('failure');
					}
					else{
						// data is returned from the post as a string. split the string using : to get the id, which will be the first element
						var dataarray=data.split("%%%");
						var newelementid=dataarray[0];
						var newcontent=dataarray[1];

       					$('#dialog').dialog("close");// close the dialog box
						// add a new element to the list
				   		$('#newelements').after("<div id='" + newelementid + "'></div>");
						// add the content to the element
				 		$('#' + newelementid).html(newcontent);
                        $('#dynamicaccordion').accordion('destroy').accordion({
			  				active:0,
					     	change: function() {
					     		var active=($('.ui-state-active').attr('id'));

						        $.post('#',
									{'ajaxrequest':active
									},
									function(content){
										var idarray=active.split(":");
										$('#' + idarray[1]).html(content);
									}
								);

							},
							header: "h3",
							autoHeight:false,
							collapsible:true,
							navigation:true
						});


					}
				});
		});// end ajaxadd function



// ############################################################################
	// cleardate
	$('.cleardate').live('click',function(){
		var targetarray=$(this).attr('name').split(":");// get the attributes from the name tag, which can be delineated by :
		var the_target=targetarray[0];// define the field to be updated
		if(targetarray[1]!='undefined'){// if there is a value provided, use it
			var the_value=targetarray[1];
		}
		else {the_value='0000-00-00';}// otherwise, set it to 0000-00-00
		$('#' + the_target).val(the_value);// set the value
		return false;// prevent the link from taking the default action
	});// end cleardate


	// datepicker class
	$('.datepicker').datepicker(
		{
			inline:true,
			dateFormat: 'yy-mm-dd'
		}
	);

	// Datepicker
	$('#datepicker').datepicker({
		inline: true
	});

	// Slider
	$(',slider').slider({
		range: true,
		values: [17, 67]
	});

	// Progressbar
	$("#progressbar").progressbar({
		value: 20
	});

	//hover states on the static widgets
	$('#dialog_link, ul#icons li').hover(
		function() { $(this).addClass('ui-state-hover'); },
		function() { $(this).removeClass('ui-state-hover'); }
	);

});

