// <![CDATA[
/**
 * dependency of this plugin:
 *
 * //@var global string http_root
 * //@var global string rp_global_image
 * //@var global string image_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
        micro_menu_uploaded: function(options) {
		
			// Set the default values, use comma to separate the settings, example:
            var defaults = {
				popupEdit:				false,
				crop:					false,
				thumbnail:				false,
				widthPopupEdit:			600,
				widthPopupResult:		400 // The width of the edit form popup container.
            }
                 
            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.click(function(e){
				
				var object = $(this);
				
				// Remove any previous popup first.
				$("#popup-edit-uploaded").remove();
				$("#popup-result").remove();
				
				// Get the object info and data.
				var object_item = object.parents('.item-uploaded'); // The object entire item.
				var object_parent = object.parents('div:first'); // The closest div only.
				var target_html = object_parent.html();
				var path_object = object.attr("href");
				var path_edit = $('.edit-uploaded',object_parent).attr("href");
				var path_delete = $('.delete-uploaded',object_parent).attr("href");
				var path_rescale = $('.rescale-uploaded',object_parent).attr("href");
				var path_crop = $('.crop-uploaded',object_parent).attr("href");
				var path_createthumb = $('.createthumb-uploaded',object_parent).attr("href");
				var item_id = path_object.match(/=([^&]+)/)[1];
				
				if(o.popupEdit == false)
				{
					// Make an ajax gif.
					object_parent.html('<img src="'+http_root+rp_global_image+image_loader+'" alt="ajax loader" />');
					
					// Load the form.
					object_parent.load( path_object, {}, function(){
						
						// Attach the input hint.
						$('form *[title]').inputHint();
						
						// Attach the submit event.
						$("form",$(this)).submit(function(){
							
							// Get the info and data for submision.
							var object_submit = $(this);
							var path_post = object_submit.attr('action');
							var data_str = object_submit.serialize();
							
							// Post the form.
							$.post(path_post, data_str, function(xml){
								
								$("label",object_parent).removeClass('error');
								//process_update_upload(xml,w,h,path_edit,path_delete);
								
								// Procees the form output with the callback function.
								//process_update_uploadx(xml,object_parent,path_edit,path_delete,path_rescale,path_crop,path_createthumb);
								$.fn.micro_menu_uploaded.process_edit_upload[$cm.selector](xml,object_item,object_parent,path_edit,path_delete,path_rescale,path_crop,path_createthumb);
								
								return false;
							
							});
							
							return false;
							
						});
						
						// If the cancel button is clicked.
						$("input[name=cancel]",$(this)).click(function(){
							
							// Put the html back to the parent.
							object_parent.html(target_html);
							
							// Attach back the plugins or functions.
							$(".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});
							
							$('.delete-uploaded').delete_item({
								deleteItem:		'.item-uploaded', // The item for deletion, such as item held in li 
								deleteParent:	'.items-uploaded', // The parent that hold delete item, such as ul > li
								wrapperParent:	'.upload' // The wrapper that hold the parent, such as div > ul > li
							});
							
							return false;
						});
									
					});
				}
				
				if(o.popupEdit == true)
				{
					
					// Make a black-out layer.
					$.fn.make_blackout();
					
					// Now prepend a fresh popup.
					$(document.body).prepend("<div id='popup-edit-uploaded' class='popup'></div>");
					
					// Set the object parent.
					var object_parent = $('#popup-edit-uploaded').width(o.widthPopupEdit);
					
					// Set the popup css and hide it first.
					/*
					object_parent.css({
						display: 'block'
					});
					*/
					
					// Load the content into the popup.
					object_parent.load( path_object, {}, function(){
						
						$('.binder-form', object_parent).prepend("<div class='close'><a href='#' class='button-close'> x close </a></div>");	
					
						$('.binder-form', object_parent).css({
							padding:"20px", 
							backgroundColor:"#ffffff",
							overflow:'hidden'
						});
						
						
						//alert(object_parent.width());
						
						// Check if crop is set true.
						if(o.crop == true || o.thumbnail == true)
						{
							// The browser caches the images with the same file names. You can force the browser to reload the image by passing an extra variable like so:
							var date = new Date();
							
							// Set objects.
							// Generate random number between 1 and 1000.
							var cachekiller = Math.floor(Math.random()*1001);
							var object_crop = $('#cropbox',object_parent);
							var object_source = object_crop.attr("src");
							object_crop = object_crop.attr("src", object_source+'?'+ cachekiller);
							
							var object_width = object_crop.width();
							//alert(object_source);
							//alert(object_width);

							// Attach crop plugin.
							if(o.thumbnail == true)
							{
								object_crop.Jcrop({
									onChange:    showPreview,
									onSelect:	 showCoords,
									bgColor:     '#ffffff',
									bgOpacity:   .8,
									aspectRatio: 1
								});
							}
							else
							{
								object_crop.Jcrop({
									onChange:    showCoords,
									bgColor:     '#ffffff',
									bgOpacity:   .8,
									setSelect:   [ 100, 100, 50, 50 ]
								});
								/* or:
								// this method a problem.
								var jcrop_api = $.Jcrop(object_crop, {
									onChange:    showCoords,
									bgColor:     '#ffffff',
									bgOpacity:   .8,
									setSelect:   [ 100, 100, 50, 50 ]
								});
								*/
							}
							
							
							// Check if the object width is bigger than default width.
							// Extend the container width.
							// Add another 40 to the object with for the padding.
							// Add another 40 for the padding of the contanter.
							if((object_width + 40) >= o.widthPopupEdit) $(this).width(object_width + 40);
							
						}
						
						// Set the popup to the center of the page.
						// You must set the image height if you have images in your loaded content. for instance, width="100" height="100"
						$(this).set_center();
						
						// Attach close popup plugin to fade out the popup.
						$('.close',object_parent).close_popup({target:object_parent});
						
						// Put the input hint back in.
						$('input[title],textarea[title]',object_parent).inputHint();
						
						// Fade out the blackout after the timeout.
						var timer = setTimeout(function()
						{ 
							// Remove the black-out.
							// Must set the clear black out here if you use the function like this - clear_blackout();
							$.fn.make_blackout.remove_blackout();
							
						}, 500 ); 
						
						// Attach the submit event.
						$("form",object_parent).submit(function(){
							
							if(o.crop == true || o.thumbnail == true)
							{
								// when you want to remove it
								JcropAPI = object_crop.data('Jcrop');
								JcropAPI.destroy();
								// or:
								//jcrop_api.destroy();
							}
							
							// Get the info and data for submision.
							var object_submit = $(this);
							var path_post = object_submit.attr('action');
							var data_str = object_submit.serialize();
							//alert(data_str);
							
							// Post the form.
							$.post(path_post, data_str, function(xml){
								
								$("label",object_parent).removeClass('error');
								//process_update_upload(xml,w,h,path_edit,path_delete);
								
								// Procees the form output with the callback function.
								//process_update_uploadx(xml,object_parent,path_edit,path_delete,path_rescale,path_crop,path_createthumb);
								$.fn.micro_menu_uploaded.process_edit_upload[$cm.selector](xml,object_item,object_parent,path_edit,path_delete,path_rescale,path_crop,path_createthumb);
								
								return false;
							
							});
							
							return false;
							
						});
					});
				}
				
				// Keep the lines below for checking.
				//alert(o.popupEdit);
				//alert(path_rescale);
				//alert(path_edit);
				//alert(item_id);
				//alert(o.top);
				//alert($cm.selector);
					
				return false;
				
			});
			
			// Check if the property process_posted exists, and if not, creates it as a new empty object. The functions are then stored as properties of that new object.
			if(!$.fn.micro_menu_uploaded.process_edit_upload) $.fn.micro_menu_uploaded.process_edit_upload = {};
			
			// Callback function for proccesing the submitted form.
			//function process_update_uploadx(xml,object_parent,path_edit,path_delete,path_rescale,path_crop,path_createthumb)
			$.fn.micro_menu_uploaded.process_edit_upload[$cm.selector] = function(xml,object_item,object_parent,path_edit,path_delete,path_rescale,path_crop,path_createthumb)
			{
				// Remove any previous popup first.
				$('#popup-result').remove();
				
				// 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>\
				</div>\
				");
				
				// Set the target's value and set the target's width.
				var target_result = $('#popup-result').width(o.widthPopupResult);
				
				// 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 item_id = $(this).attr('itemid');
							var message = $(this).attr('message');
							
							// add an error class to each error element.
							$("#"+elementid+"_label",object_parent).addClass('error');

							// 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.
						$("#"+elementid+"_label",object_parent).addClass('error');
						
						// 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.
					target_result.set_center();
					
					// Put the input hint back in.
					$('input[title],textarea[title]',object_parent).inputHint();
					
					// Attach close popup plugin to fade out the popup.
					$('.close',target_result).close_popup({target:'#popup-result'});
					
					// Check if crop or thumbnail is set true.
					// Attach the jcrop plugin again.
					if(o.crop == true || o.thumbnail == true)
					{
						// Set the objects.
						var object_crop = $('#cropbox',object_parent);
						
						// Check which jcrop setting to use.
						if(o.thumbnail == true)
						{
							object_crop.Jcrop({
								onChange:    showCoords,
								onSelect:	 showPreview,
								bgColor:     '#ffffff',
								bgOpacity:   .8,
								aspectRatio: 1
							});
						}
						else
						{
							object_crop.Jcrop({
								onChange:    showCoords,
								bgColor:     '#ffffff',
								bgOpacity:   .8,
								setSelect:   [ 100, 100, 50, 50 ]
								//aspectRatio: 16 / 9
							});
						}
					}
				}
				
				// If security stage, and confirmation stage have passed, print the result.
				else if($(xml).find("result").length > 0)
				{	
				
					// Set the local variable.
					var message = $(xml).find("result").attr('message');
					var item_id = $(xml).find("result").attr('itemid');
					var item_title = $(xml).find("result").attr('itemtitle');
					var item_description = $(xml).find("result").attr('itemdescription');
					var item_href = $(xml).find("result").attr('itemhref');
					var item_category = $(xml).find("result").attr('itemcategory');
					//alert(item_href);
					
					// 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.
					target_result.set_center();
					
					// Attach close popup plugin to fade out the popup.
					$('.close',target_result).close_popup({target:'#popup-result'});
					
					// Put the input hint back in.
					$('input[title],textarea[title]',object_parent).inputHint();
					
					// Fade in the popup.
					target_result.fadeIn('fast', function(){
					
						if(o.popupEdit == false)
						{
							object_parent.html('\
								<ul class="menu-micro">\
									<li><a href="'+path_edit+'" class="edit-uploaded">EDIT</a><span class="separator">&#124;</span></li>\
									<li><a href="'+path_delete+'" class="delete-uploaded">DELETE</a><span class="separator">&#124;</span></li>\
									<li><a href="'+path_rescale+'" class="rescale-uploaded">RESCALE</a><span class="separator">&#124;</span></li>\
									<li><a href="'+path_crop+'" class="crop-uploaded">CROP</a><span class="separator">&#124;</span></li>\
									<li><a href="'+path_createthumb+'" class="createthumb-uploaded">CREATE THUMBNAIL</a></li>\
								</ul>\
								<h4>'+item_title+'</h4>\
								<p>'+item_description+'</p>\
								<p><a href="'+item_href+'" target="_balnk">'+item_href+'</a></p>\
							');
							
							
							// Attach the plugins or functions back.
							$(".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});
							
							$('.delete-uploaded').delete_item({
								deleteItem:		'.item-uploaded', // The item for deletion, such as item held in li 
								deleteParent:	'.items-uploaded', // The parent that hold delete item, such as ul > li
								wrapperParent:	'.upload' // The wrapper that hold the parent, such as div > ul > li
							});
							
							$(this).fadeOut(function(){
								$(this).remove();
							});
						}

						if(o.popupEdit == true)
						{
							// Clear the form's input.
							clear_form(object_parent);
							//alert($cm.selector);
							
							var timer = setTimeout(function()
							{ 
								target_result.fadeOut('slow',function(){
									target_result.remove();
								});
								
							}, 2000 ); 
						}
						
						// Check if crop or thumbnail is set true.
						// Attach the jcrop plugin again.
						if(o.crop == true || o.thumbnail == true)
						{
							// The browser caches the images with the same file names. You can force the browser to reload the image by passing an extra variable like so:
							date = new Date();
							
							// Set the objects.
							var itempath = $(xml).find("result").attr('itempath');
							var itemwidth = $(xml).find("result").attr('itemwidth');
							var itemheight = $(xml).find("result").attr('itemheight');
							
							// Check for which jcrop setting to use.
							if(o.thumbnail == true)
							{
								// Set the object.
								var object_crop = $('#cropbox',object_parent);
								
								// Check if the holder exists.
								if($('#viewer-current',object_parent).length > 0)
								{
									// Fade out the image.
									// Kill the image cache then fade it in.
									$('#current',object_parent).fadeOut('fast',function(){
										$(this).attr("src", itempath + '?' + date.getTime()).fadeIn('slow');
									});
								}
								else
								{
									// Insert the html after the object.
									$('<div style="width:'+itemwidth+'px;height:'+itemheight+'px;overflow:hidden; float:left; margin:0px 0px 5px 10px; border:1px solid #525252; display:none;" id="viewer-current"></div>').insertAfter("#viewer-preview",object_parent);
									
									// Append the image tag and add the image.
									// Fade in the holder.
									$('#viewer-current',object_parent).fadeIn('slow',function(){
										$(this).append('<img src="'+itempath+'" id="current"/>')
										$('#current',object_parent).hide().fadeIn('slow');	
									});
									
								}
								
								object_crop.Jcrop({
									onChange:    showCoords,
									onSelect:	 showPreview,
									bgColor:     '#ffffff',
									bgOpacity:   .8,
									aspectRatio: 1
								});
							}
							else
							{
								// Set the object.
								var object_crop = $('#cropbox',object_parent).attr("src", itempath + '?' + date.getTime());
								object_crop.width(itemwidth);
								object_crop.height(itemheight);
								//var object_viewer = $('#test',object_parent);
								
								object_crop.Jcrop({
									onChange:    showCoords,
									bgColor:     '#ffffff',
									bgOpacity:   .8,
									setSelect:   [ 100, 100, 50, 50 ]
									//aspectRatio: 16 / 9
								});
								
								// Get the item image url.
								// Force the browser to reload the image by passing an extra variable.
								var image_src = $('img',object_item).attr('src');
								$('img',object_item).attr("src", image_src + '?' + date.getTime());
							}
							
							//alert($('img',object_item).attr('src'));
							//object_item.css({background:'red'});
							//$('.item-uploaded-image',object_item).find('img').attr("src", itempath+'?'+date.getTime());
							//$("#myimg").attr("src", "/myimg.jpg?"+d.getTime());
						}
					
					});
				}
			}
			
			function updateCoords(c)
			{
				$('#x').val(c.x);
				$('#y').val(c.y);
				$('#w').val(c.w);
				$('#h').val(c.h);
			};
			
			// Show the selected coordinations.
			function showCoords(c)
			{
				$('#x1').val(c.x);
				$('#y1').val(c.y);
				$('#x2').val(c.x2);
				$('#y2').val(c.y2);
				$('#w').val(c.w);
				$('#h').val(c.h);
				
			};
			
			// Check before submiting the form.
			function checkCoords()
			{
				if (parseInt($('#x1').val())) return true;
				alert('Please select a crop region then press submit.');
				return false;
			};

			// Show the selected coordination on the preview.
			function showPreview(coords)
			{
				var imgwidth = $("#cropbox").attr('width');
				var imgheight = $("#cropbox").attr('height');
				var previewwidth = parseInt($("#preview").parent().css('width'),10);
				var previewheight = parseInt($("#preview").parent().css('height'),10);
				//alert(previewwidth);
				
				if (parseInt(coords.w) > 0)
				{
					var rx = previewwidth / coords.w;
					var ry = previewheight / coords.h;

					jQuery('#preview').css({
						width: Math.round(rx * imgwidth) + 'px',
						height: Math.round(ry * imgheight) + 'px',
						marginLeft: '-' + Math.round(rx * coords.x) + 'px',
						marginTop: '-' + Math.round(ry * coords.y) + 'px'
					});
					
				}
			}
			
        }
    });
     
//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);

// ]]>
