// <![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
        delete_item: function(options) {
		
			// Set the default values, use comma to separate the settings, example:
            var defaults = {
				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
            }
                 
            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.click(function(e){
				
				// Remove any previous popup first.
				$("#popup-edit-uploaded").remove();
				
				var o = options;
				var object = $(this);
				var target_delete = object.parents(o.deleteItem); // The item for deletion, such as item held in li 
				var target_parent = object.parents(o.deleteParent); // The parent that hold delete item, such as ul > li
				var target_wrapper = object.parents(o.wrapperParent); // The wrapper that hold the parent, such as div > ul > li
				var target_loadin = object.parents('ul:first'); // To get the closest parent.
				var target_html = object.parents('ul:first').html();
				var target_loadpath = object.attr('href');
				var target_classname = object.attr('class');
				//alert(target_classname);
				//alert($cm.selector);
				
				// Make a gif loader.
				target_loadin.html('<img src="'+http_root+rp_global_image+img_loader+'" style="float:none;"/> loading');
				//alert(target_html);
				
				// Load the delete form.
				target_loadin.load(target_loadpath, function(){
					
					// When the yes button is triggered.
					$("input[type=submit][name=yes]",target_loadin).click(function(){

						// Get the path from attribute of action in the form.
						var target_postpath = $(this).parent('form').attr('action');
						//alert(target_postpath);
						
						// Make a gif loader.
						target_loadin.html('<div class="ajaxloader"><img src="'+http_root+rp_global_image+img_loader+'" style="float:none;"/> loading</div>');
						
						// Post the form.
						$.post(target_postpath, $(this).parent('form').serialize(), function(xml){

							// Procees the form output with the callback function.
							process_deleted(xml);
						});
						
						// Check if the target deleted item has children
						if (target_delete.nextAll('ul').size() > 0 ) 
						{
							// Slide up the children.
							target_delete.nextAll('ul').slideUp('fast');
							//alert('has child');
							
						}
						
						// Slide up the deleted target.
						target_delete.slideUp('fast', function() {
						
							// Remove its divs completely
							target_delete.remove();
							
							// Keep this alert for checking.
							//alert($(o.deleteItem,target_parent).length);

							// Count how many items left which have the same class name as the current deleted item     
							if($(o.deleteItem,target_parent).length == 0)
							{
								// Condition for upload when it is empty
								if($('.binder-row').length > 0)
								{
									$('.binder-row',target_wrapper).css({
										borderBottom: '0px solid #999', 
										padding: '0px 0px 0px 0px'
									});
								}
								
								// Condition for list when it is empty
								else
								{
									target_parent.html('<p class="note-empty">0 item left.</p>');
								}
							}

						});
						
						return false;
					});
					
					// When the no/cancel button is triggered.
					$("input[type=button][name=no]",target_loadin).click(function(){

						// The string will become ojects after spliting it into pieces with .split(),
						// so you must turn the object into string again with .toString().
						var selector_current = $cm.selector.split(' ').slice(-1).toString(); 
						
						// Return the html
						target_loadin.html(target_html);
						
						// Reload the delete function
						target_loadin.find(selector_current).delete_item({
							deleteItem:		o.deleteItem, 
							deleteParent:	o.deleteParent,
							wrapperParent:	o.wrapperParent
						});
						
						// Attach the Micro Menu plugin for uploaded files: images, documents and videos.
						$(".edit-uploaded").micro_menu_uploaded();
						$(".rescale-uploaded").micro_menu_uploaded({popupEdit:true});
						$(".crop-uploaded").micro_menu_uploaded({popupEdit:true,crop:true});
						$(".createthumb-uploaded").micro_menu_uploaded({popupEdit:true,thumbnail:true});
						
						// Unbind the click off the link first.
						$('.edit-listed').unbind('click');
						
						// Attach anew.
						$('.edit-listed').edit_listed({
							top:70, // The top of the edit form popup container.
							width:1050 // The width of the edit form popup container.
						});

						return false;
					});
				});
				
				return false;
				
			});
			
			// Callback function for proccesing the deleted item.
			function process_deleted(xml)
			{
				// 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 = $('#popup-result');
				var width = 400;
				var top = 220;
				var scrollTop = $(window).scrollTop();
				var scrollLeft = $(window).scrollLeft();
				var marginLeft = "-"+ ((scrollLeft + width)/2);
				
				popup.css({
					top:(scrollTop + top) + "px", 
					left:"50%",
					marginLeft:marginLeft + "px",
					width:width + "px",
					zIndex:"11",
					display:"none"
				});
					
				// Loop for any error messages.
				$("error", xml).each(function(){
					var elementid = $(this).attr('elementid');
					var message = $(this).attr('message');
					$("#"+elementid+"_label").addClass('error');
					$("#"+elementid+"_img").css({visibility:'visible'});
					$(".result").append("<img src='"+http_root+rp_global_image+"attention.png' /> <b>" + message + "</b> <br />");
					popup.fadeIn('slow', function(){	
						close_popup(popup);
					});	
				});
				
				// Loop for any positive results.
				$("result", xml).each(function(){
				
					// Store the result node.
					var message = $(this).attr('message');
					//alert(message);
					
					// 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.fadeIn('fast', function(){
						
						// Set the timeout to 1 minute to remove the popup
						setTimeout(function(){
							popup.fadeOut("slow",function(){
								popup.remove();
							});	
						},1000);	
						
						// Attach closePopup function.
						close_popup(popup);		
					});

				});
			}
			
        }
    });
     
//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);

// ]]>
