// <![CDATA[
/**
 * dependency of this plugin:
 *
 * //@var global string http_root
 * //@var global string rp_global_image
 * //@var global string img_loader
 * //@var global string rp_cms
 *
 * //@function close_popup()
 *
*/

// You need an anonymous function to wrap around your function to avoid conflict
(function($){
 
    // Attach this new method to jQuery
    $.fn.extend({ 
         
        // This is where you write your plugin's name
       post_form: function(options) {
		
			// Set the default values, use comma to separate the settings, example:
            var defaults = {
				top:			250, // The top of the proceesing popup and the result popup.
				width:			400, // The width of the proceesing popup and the result popup.
				textEditor:		'none'
            }
                 
            var options =  $.extend(defaults, options);
            
			// return this.click(function(){ // original
			// "this" is already a jQuery object: 
			// When you create the click function you can assign that element to a variable and reference it within:
			var $cm = this.submit(function(e){
				
				var o = options;
				var object = $(this);
				
				// Remove all the popup result first.
				$("#popup-result").remove();
				$("#popup-processing").remove();
				
				// Append a fresh popup process
				$(document.body).append("<div id='popup-processing' class='popup-outer'><div id='processing' class='popup-inner'></div></div>");
				
				// Get the path from attribute of action in the form.
				var target_postpath = object.find('form').attr('action');
				//var form_data = object.find('form').serialize();
				
				var top = o.top;
				var width = o.width;
				var scroll_top = $(window).scrollTop();
				var scroll_left = $(window).scrollLeft();
				var margin_left = "-"+((scroll_left + width + 20)/2);
				
				// Keep the lines below for checking.
				//alert(form_data);
				//alert(target_postpath);
				//alert($cm.selector);
				//var margin_left = "-"+ ((scroll_left + width)/2);
				//alert(o.textEditor);
				
				// Set the popup processing's css.
				$('#popup-processing').css({
					top:(scroll_top + top) + "px", 
					left:"50%",
					marginLeft:margin_left + "px",
					width:width + "px",
					zIndex:"11"
				});
				
				// Make a gif loader.
				$('#processing').html('<div class="ajaxloader"><img src="'+http_root+rp_global_image+img_loader+'"/> loading</div>');
				
				// Set the loader's css.
				$('.ajaxloader').css({
					padding:"10px", 
					textAlign:"center",
					backgroundColor:"#ffffff"
				});
				
				// Check if tiny mce is on or off.
				// When a textarea is replaced by TinyMCE, it's actually hidden and TinyMCE editor (an iframe) is displayed instead.
				// However, it's this textarea's contents which is sent when the form is submitted. Consequently its contents has to be 
				// updated before the form submission.
				// For a standard form submission , it's handled by TinyMCE . For an Ajax form submission, you have to do it manually, 
				// by calling (before the form is submitted): tinyMCE.triggerSave();
				// @source: http://maestric.com/doc/javascript/tinymce_jquery_ajax_form
				if(o.textEditor == 'mce-basic') tinyMCE.triggerSave(true,true);
				//alert(o.textEditor);
				
				// Post the form.
				// You must serialise the form after tinyMCE.triggerSave() if tiny mce is in use. 
				$.post(target_postpath, object.find('form').serialize(),function(xml){
					
					// Remove any previous error and the popup processing
					$("label").removeClass('error');
					$('#popup-processing').remove();
					
					//tinyMCE.execCommand('mceFocus', false, 'content-1-mce'); 
					//tinyMCE.execCommand('mceRemoveControl', false, 'content-1-mce');
					
					// Procees the form output with the callback function.
					process_posted(xml,top,width);
				});
			
				// Disable the submit button so that you won't click it twice while the ajax is processing the form
				$('input[type=submit]',$cm.selector).attr('disabled', 'disabled').css({opacity:0.4});
				
				return false;
				
			});
			
			
			
			// Callback function for proccesing the deleted item.
			function process_posted(xml,top,width)
			{
				// Keep the lines below for checking.
				//alert($cm.selector);
				//alert(top);
				
				// Remove any previous popup first.
				$('#popup-result').remove();
				
				// Append a popup div.
				$(document.body).append("<div id='popup-result' class='popup-outer'><div class='popup-inner'><div class='close'><a href='#' class='button-close'>x Close </a></div><div class='result'></div></div></div>");
				
				var popup_result = $('#popup-result');
				var scroll_top = $(window).scrollTop();
				var scroll_left = $(window).scrollLeft();
				var margin_left = "-"+ ((scroll_left + width)/2);
				
				// Set the popup result's css.
				popup_result.css({
					top:(scroll_top + top) + "px", 
					left:"50%",
					marginLeft:margin_left + "px",
					width:width + "px",
					zIndex:"11",
					display:"none"
				});
					
				// Loop for any error messages.
				$("error", xml).each(function(){
					$('form *[title]').inputHint();
					var elementid = $(this).attr('elementid');
					var message = $(this).attr('message');
					$("#"+elementid+"_label").addClass('error');
					$(".result").append("<img src='"+http_root+rp_global_image+"attention.png' /> <b>" + message + "</b> <br />");
					popup_result.fadeIn('slow', function(){	
						close_popup(popup_result);
						
						// Enable the submit button again after processing the xml output.
						// Must use true or false in jquery 1.6 above.
						$('input[type=submit]').attr('disabled', false).css({opacity:1});
					});
				});
				
				
				// Loop for any positive results.
				$("result", xml).each(function(){
				
					// Store the result node.
					var message = $(this).attr('message');
					var path = $(this).attr('path');
					var action = $(this).attr('action');
					var itemid = $(this).attr('itemid');
					var itemtitle = $(this).attr('itemtitle');
					var itemhide = $(this).attr('itemhide');
					var itemcategory = $(this).attr('itemcategory');
					var itemcleanurl = $(this).attr('itemcleanurl');
					var itemupdatedon = $(this).attr('itemupdatedon');
					var basename = $(this).attr('basename');
					
					// Keep the lines below for checking.
					//alert(message);
					//alert(itemupdatedon);
					
					// Append the positive messages in the result class.
					$(".result").append("<img src='"+http_root+rp_global_image+"info.png' /> <b>" + message + "</b> <br />");
					
					// Display the messages by fading them in.
					popup_result.fadeIn('fast', function(){
		
						// Check if the posted action is for adding or to sending content.
						if((action == 'add')||(action == 'send'))
						{
							setTimeout(function(){
								popup_result.fadeOut("slow", function(){
									popup_result.remove();
								});	
							},2000);
							
							// Keep the line below for testing.
							//alert($cm.selector);
							
							$($cm.selector).load(http_root+path, {}, function(){
								
								// Attach other functions and plugins.
								//load_edit_popup();
								//list_item_bypost();
								sortOrders();
								toggle_children();
								toggle_nextparent();
								
								$('.edit-listed').edit_listed({
									top:70, // The top of the edit form popup container.
									width:1050 // The width of the edit form popup container.
								});
								
								$('.delete-listed').delete_item({
									deleteItem:		'.item-listed', // The item for deletion, such as item held in li 
									deleteParent:	'.items-listed', // The parent that hold delete item, such as ul > li
									wrapperParent:	'.list' // The wrapper that hold the parent, such as div > ul > li
								});
								
								$('#form-sort-account').list_item_onsubmit();
								$('#form-sort-contact').list_item_onsubmit();
								$('#form-sort-member').list_item_onsubmit();
								$('#form-sort-page').list_item_onsubmit();
								$('#form-search-page').list_item_onsubmit();
								
								// Check if the form search page exists.
								if($('.form-search-admin').length > 0)
								{
									// Attach autocomplete when there is a change on the option.
									// Serialise the form.
									$("select[name=search]").change(function () {
										
										//alert('1');
										// alert($("option:selected", this).val());
										var object_data = $('.form-search-admin').serialize();
										//alert(object_data);
										
										// Unbind any previous attached plugin.
										$("#name_search").unbind();
										
										$("#name_search").autocomplete(http_root + rp_cms + $("input[name=autocomplete]").val() + '?' + object_data, {
											width: 304,
											matchContains: true,
											//mustMatch: true,
											//minChars: 0,
											//multiple: true,
											//highlight: false,
											//multipleSeparator: ",",
											selectFirst: true
										});
										
										$('form *[title]').inputHint();
									  
									}).trigger('change');
								}
								
							});	
							
							
						}
						else
						{
							// Set timeout for fading out the popup.
							setTimeout(function(){
							
								// Fade out the popup result.
								popup_result.fadeOut("slow", function(){
									
									// Fade out the targeted container whether it is a popup or embeded into the body.
									$($cm.selector).fadeOut("slow");
									//alert($cm.selector);
									
									// Check if path exists.
									// Site basic setting needs this after updating each time.
									if(path) 
									{
										$($cm.selector).load(http_root+path, function(){ 
											$($cm.selector).fadeIn('fast'); 
											
											// Attach other functions and plugins.
											$('form *[title]').inputHint(); 
											//toggle_nextparent();
											disable();
											restore();
											restoreAll();
										});
									}
									
									// Check if the item title is not empty.
									if(itemtitle)
									{
										// Change the item's title.
										// Target the element but not its nested element.
										//$(".items-listed #item_"+itemid+" h1:first").text(itemtitle);
										
										// This is a bit longer because it explicitly searches for text nodes.
										// nodeType is the type of the node (it can be an element, a document, a text node, etc). 3 is for text node. Not all browsers have constants of these, thus using the number directly.
										//$(".items-listed #item_"+itemid+" h1:first").contents().filter(function() {
										//	return this.nodeType == 3; 
										//}).replaceWith(itemtitle);
										
										// Select the first child:
										$(".items-listed #item_"+itemid+" h1")[0].firstChild.nodeValue = itemtitle; // plain js + jquery
										//$(".items-listed #item_"+itemid+" h1").first().contents().first().replaceWith(itemtitle); // jquery
									}
									
									// Check if the item clean url is not empty.
									if(itemcleanurl){
										
										// Set the parent of currnet item.
										var this_parent = $(".items-listed #item_"+itemid+"");
										
										// Change the url in the edit button.
										$('.edit-listed',this_parent).attr("href", http_root+rp_cms+"form_page_update.php?pg_url="+itemcleanurl);
										//$('.edit',this_parent).css('background','red');
										
									}
									
									// Check if the item category is empty.
									if(itemcategory){
										$(".items-listed #item_"+itemid+" span:first").text(itemcategory);
									}
									
									// Check if the item hide is empty.
									
									if(itemhide)
									{
										if (itemhide == '1') 
										{
											var target = $(".items-listed #item_"+itemid+" > div:last");
											$('.disable', target).text('ENABLE');
										}
										
										else if (itemhide == '0') 
										{
											var target = $(".items-listed #item_"+itemid+" > div:last");
											$('.disable', target).text('DISABLE');
										}
										
										else if (itemhide == 'on') 
										{
											itemhide = 'Private';
											
											$(".items-listed #item_"+itemid+" .visibility:first").text(itemhide);
										} 
										else 
										{
											itemhide = 'Published';
											$(".items-listed #item_"+itemid+" .visibility:first").text(itemhide);
										}
										
									}

									// Check if the item updatedon is not empty.
									if(itemupdatedon){
										$(".items-listed #item_"+itemid+" .updated-on").text('Updated on' + itemupdatedon);
									}
									
								});	
							},2000);
						}
							
						$('form *[title]').inputHint();
						close_popup(popup_result);
					
					});

				});
			}
			
			
			
        }
    });
     
//pass jQuery to the function, 
//So that we will able to use any valid Javascript variable name 
//to replace "$" SIGN. But, we'll stick to $ (I like dollar sign: ) )       
})(jQuery);

// ]]>
