// <![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_string: 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.
            }
                 
            var options =  $.extend(defaults, options);
			var o = 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){
				
				// This object always is the form itself which is <form>...</form>.
				var object = $(this);
				
				// Get the path from attribute of action in the form.
				var target_postpath = object.attr('action');
				var file_field = $('input[type=file]',object);
				var top = o.top;
				var width = o.width;
				
				$("#popup-result").remove();
				
				// Keep the lines below for checking.
				//alert(form_data);
				//alert(form_data_2);
				//alert(target_postpath);
				//alert($cm.selector);
				//var margin_left = "-"+ ((scroll_left + width)/2);
				//alert(usr_email);
				//alert(usr_reset);
				//alert(target_postpath);
				//alert(object.serialize());

				// Disable the submit button so that you won't click it twice while the ajax is processing the form.
				// Must use true or false for jquery > 1.6.
				$('input[type=submit]',object).attr('disabled', true).css({opacity:0.4});
				
				// Display the loading.
				$('.processing',object).html('<img src="'+http_root+rp_local_image+'ajax-loader-2.gif" style="float:none; border:0px solid #000;" class="string-ajax-loader"/>');
				
				// Check each of the input field - if it has the same value as in its title - empty it.
				// Must place it here before serialising the form.
				$('input, textarea',object).each(function(){
					if ($(this).val() == '' || $(this).val() == $(this).attr('title')) $(this).val('');
				});
				
				// Check if the <input type="file"> exist.
				if(file_field.length > 0)
				{
					// HTML5 form data object.
					var fd = new FormData();
					
					// total number of image you select.
					var file_length = file_field.get(0).files.length; 
					
					// The first data of the first selected file.
					var file_data = file_field.get(0).files[0];
					
					// appends the currently selected File of an <input type="file" id="file"> element to an FormData instance (which is later to be sent as multipart/form-data XHR request body).
					fd.append("file", file_data);
		
				}
				
				// Check if the <input type="file"> exist and no file selected.
				if(file_field.length > 0 && file_length == 0)
				{
					alert('Please select a photo from your computer.');
					
					// Remove the ajax loader.
					$('.string-ajax-loader',object).remove();
					
					// Enable the submit button again after processing the xml output.	
					// Must use true or false for jquery > 1.6.
					$('input[type=submit]',object).attr('disabled', false).css({opacity:1});
				}
				
				// Check if the the selected file is more than 0.
				else if(file_length > 0)
				{
					// jquery will then hanle the data.
					$.ajax({
						url: http_root + rp_public + "image_upload_needle_photo_json.php",
						type: "POST",
						data: fd,
						processData: false,  // tell jQuery not to process the data
						contentType: false,   // tell jQuery not to set contentType
						dataType: "json",
						success: function (jsonresponse) {
							
							// Convert the form data to json.
							var jsonform = object.serializeObject();
							
							// Post the form again.
							$.post(target_postpath,$.extend(true, jsonresponse[0], jsonform),function(xml){
								
								// Remove the file from screen.
								$.fn.get_file_onchange.remove_uploaded();
								
								// Remove any error class first.
								//$("input, textarea",$($cm.selector)).removeClass('error-local');
								$("input, textarea").removeClass('error-local');
								
								// Remove the ajax loader.
								$('.string-ajax-loader',object).remove();
								
								// Enable the submit button again after processing the xml output.	
								// Must use true or false for jquery > 1.6.
								$('input[type=submit]',object).attr('disabled', false).css({opacity:1});
								
								// Clear all the form accept the current object's form.
								// This creates a bug when you have many forms.
								//clear_form($('form').not($($cm.selector)));
								
								//process_posted_string(xml);
								//$.fn.post_string.process_posted_string(xml);
								$.fn.post_string.process_posted_string[$cm.selector](xml,object);
								
							});
						},
						complete: function () {
							//alert('Done!');
						}
					});
				}
				else
				{
					// Post the form .
					$.post(target_postpath,object.serialize(),function(xml){
						
						// Remove any error class first.
						//$("input, textarea",$($cm.selector)).removeClass('error-local');
						$("input, textarea").removeClass('error-local');
						
						// Remove the ajax loader.
						$('.string-ajax-loader',object).remove();
						
						// Enable the submit button again after processing the xml output.	
						// Must use true or false for jquery > 1.6.
						$('input[type=submit]',object).attr('disabled', false).css({opacity:1});
						
						// Clear all the form accept the current object's form.
						// This creates a bug when you have many forms.
						//clear_form($('form').not($($cm.selector)));
						
						//process_posted_string(xml);
						//$.fn.post_string.process_posted_string(xml);
						$.fn.post_string.process_posted_string[$cm.selector](xml,object);
						
					});
				}
				
				return false;
				
			});
			
			// Check if the property process_posted_string exists, and if not, creates it as a new empty object. The functions are then stored as properties of that new object.
			if(!$.fn.post_string.process_posted_string) $.fn.post_string.process_posted_string = {};
			
			// Callback function for proccesing the deleted item.
			//function process_posted_string(xml)
			//$.fn.post_string.process_posted_string = function(xml) 
			//$.fn.post_string.process_posted_string = function(xml) - can only store one function. The second time you call your plugin, this will be overwritten. In the form that works, you have a function that forms a closure over the value of the $cm variable - and you have one of these functions created for each call to post_string.
			$.fn.post_string.process_posted_string[$cm.selector] = function(xml,object)
			{
				// Append a popup for displaying the security checking form.
				$(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='respond-message'></div>\
						<div class='form-confirm'></div>\
					</div>\
				</div>\
				");

				// Set the target's value and set the target's width.
				var target_result = $('#popup-result').width(400);
				
				// Set the popup css and hide it first.
				target_result.css({
					display: 'none'
				});
				
				// If error found for email.
				if($(xml).find("error").length > 0)
				{
					//alert($(xml).find("error").length);
					
					// Check if the error node is more than 1.
					if($(xml).find("error").length > 1)
					{
						// Loop each node and append each of them.
						$("error", xml).each(function(){
			
							// Set the local variable.
							var elementid = $(this).attr('elementid');
							var message = $(this).attr('message');

							// add an error class to each error element.
							$("input[name="+elementid+"],textarea[name="+elementid+"]",object).addClass('error-local');
							
							// Append the message to the .result class.
							$(".respond-message", target_result).append("<img src='"+http_root+rp_global_image+"info.png' /> " + message + "<br />");
							
						});
					}
					else
					{
					
						// Set the local variable.
						var elementid = $(xml).find("error").attr('elementid');
						var message = $(xml).find("error").attr('message');
						
						// add an error class to each error element.
						$("input[name="+elementid+"],textarea[name="+elementid+"]",object).addClass('error-local');
						
						// Append the message to the .respond-message class.
						$(".respond-message", target_result).append("<img src='"+http_root+rp_global_image+"info.png' /> " + message);
						
					}
					
					// Set the popup to the center of the page.
					//set_center(target_result);
					target_result.set_center();
					
					// Put the input hint back in.
					$('input[title],textarea[title]',object).inputHint();
					
					// Attach close popup plugin to fade out the popup.
					//close_popup(target_result);
					$('.close',target_result).close_popup({target:'#popup-result'});
				}
				
				else if($(xml).find("result-string").length > 0)
				{
					//alert($cm.selector);
					
					// Clear the form's input.
					clear_form(object);
					
					// Reset the form's input height.
					$(".autogrow",object).css({height:'15px'});
					
					// Set the local variable.
					var item_id = $(xml).find("result-string").attr('itemid');
					var item_type = $(xml).find("result-string").attr('itemtype');
					var item_path = $(xml).find("result-string").attr('itempath');
					
					// Check if the type - if it is a needle.
					if(item_type == 'needle')
					{
						//$('<div class="item-needle"></div>').insertBefore(".item-needle:first").hide(); 
						if($('.item-needle-temp').length > 0) $(".item-needle-temp").filter(":first").before("<div class='item-needle-temp'></div>");
						else $(".item-needle").filter(":first").before("<div class='item-needle-temp'></div>"); // Alternatively (for better performance), use filter.
						
						// Hide the last item of .item-temp.
						$('.item-needle-temp:first').hide();
						
						// Load the content into the first item.
						$('.item-needle-temp:first').load( http_root+item_path, {}, function(){
						
							// Side down the this item.
							$(this).slideDown('slow', function(){
								
								$('form *[title]',$(this)).inputHint(); 
								
								$.fn.micromenu_string();
								
							});
							
						});
						
					}
					
					// Check if the type - if it is a thread.
					if(item_type == 'thread')
					{
						// Get the parent of this form and store it in the variable.
						var object_parent_thread = object.parents('.item-thread');
						var object_parent_needle = object.parents('.item-needle');
						
						// Inset a temporary div before the form's parent.
						object_parent_thread.before('<div class="item-thread-temp"></div>');
						
						// Hide the last item of .item-temp.
						$('.item-thread-temp:last',object_parent_needle).hide();
						
						//$('<div class="item-needle"></div>').insertBefore(".item-needle:first").hide(); 
						//$(".item").filter(":first").before("<div class='item'>0</div>"); // Alternatively (for better performance), use filter.
						
						// Load the content into the first item.
						$('.item-thread-temp:last',object_parent_needle).load( http_root+item_path, {}, function(){
						
							// Side down the this item.
							$(this).slideDown('slow', function(){
								
								$.fn.micromenu_string();;
							
							});
						});
					}
				}	
			}
        }
    });
     
//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);

// ]]>

$.fn.serializeObject = function()
{
   var o = {};
   var a = this.serializeArray();
   $.each(a, function() {
       if (o[this.name]) {
           if (!o[this.name].push) {
               o[this.name] = [o[this.name]];
           }
           o[this.name].push(this.value || '');
       } else {
           o[this.name] = this.value || '';
       }
   });
   return o;
};
