

//image plugin for cleditor
(function(jQuery) {
	var myUrl = "http://rjmachine.ca";
	var html = jQuery("<div/>");
	var widthLabel = jQuery("<label/>").text("width");
	var widthInput = jQuery("<input/>").attr("type", "text").css("width", "50px").css("margin", "5px");
	var heightLabel = jQuery("<label/>").text("height");
	var heightInput = jQuery("<input/>").attr("type", "text").css("width", "50px").css("margin", "5px");
	var uploadSpan = jQuery("<span/>").addClass("uploadSpan");
	var uploadButton = jQuery("<button/>").button({"label":"upload files"});
	var messageSpan = jQuery("<label/>").text("Click on an image to insert it into the page").css("margin", "5px");
	var controlDiv = jQuery("<div/>").append(widthLabel, widthInput, heightLabel, heightInput, uploadSpan, uploadButton, messageSpan).css("padding", "5px");
	
	var fileName = jQuery("<span/>");
	var progressBar = jQuery("<div/>").addClass("progressBar");
	var statusDiv = jQuery("<div/>").append(fileName, progressBar).addClass("statusDiv").hide();
	
	var picturesTable = jQuery("<table/>");
	var html = jQuery("<div/>").append(controlDiv, statusDiv, picturesTable);
		  

	jQuery.cleditor.buttons.addImage = {
		name: "addImage", //name to add into the controls
		image: "insertImage.gif",
		title: "Insert Image",
		command: "inserthtml",
		popupName: "addImage",
		popupClass: "cleditorPrompt",
		popupContent: html.html(),
		buttonClick: addImageButtonClick
	  }; 
	  
	   // Add the button to the default controls
	  $.cleditor.defaultOptions.controls = $.cleditor.defaultOptions.controls
		.replace("rule ", "rule addImage "); //note, we replace a string with it plus what we want to add
		
		//handlers for swfupload
		var swfUploadLoaded = function()
		{
				
		}
		var fileQueued = function(file)
		{
								
		}
		var fileQueueError = function(file, errorCode, message)
		{
			alert("file queue error:" + message);
		}
		var uploadError = function(file, errorCode, message)
		{
			alert("upload error:" + message);	
		}
		var uploadSuccess = function(file, serverData, response)
		{
			//alert("uploadSuccess:" + serverData);
		}
		
		var fillImagesTable = function()
		{
			
			
			
		}
		
		var getImges = function(table, width, height, editor, data)
		{
			jQuery.post("./inc/cleditor.addimage.php", {"type":"getImages"}, function(server_data)
		 {
			 table.find("tr").remove();
			 
			 var row;
			  server_data = jQuery.parseJSON(server_data);
			 jQuery.each(server_data, function(index, value)
			{
				if(index % 4 == 0)
				{
					row = jQuery("<tr/>");
					table.append(row);
				}
				var image = jQuery("<img/>").attr("src", "./photos/" + value).attr("alt", value);
				var thumbnail = jQuery("<img/>").attr("src", "./photos/thumbnails/" + value).attr("alt", value);
				var cell = jQuery("<td/>").append(thumbnail);
				row.append(cell);
				thumbnail.click(function()
				{
					if(width.val() != "" && !isNaN(width.val() * 1))
					{
						image.attr("width", width.val());
					}
					if(height.val() != "" && !isNaN(height.val() * 1))
					{
						image.attr("height", height.val());
					}
					 editor.execCommand(data.command, jQuery("<div/>").append(image).html(), null, data.button);
					 editor.hidePopups();
					 editor.focus();
				});
			});
			 
			 
		 });
			
			
			
		}//end getImages
	
			
	   // Table button click event handler
	   //this is called when the toolbar button is clicked
	  function addImageButtonClick(e, data) 
	  {
		// Get the editor
		var editor = data.editor;
			
		//get our elements
		var table = jQuery(data.popup).find("table").eq(0);
		var width = jQuery(data.popup).find("input").eq(0);
		var height = jQuery(data.popup).find("input").eq(1);
		var uploadSpan = jQuery(data.popup).find(".uploadSpan").eq(0);
		var uploadButton = jQuery(data.popup).find("button").eq(0);
		
		var statusDiv = jQuery(".statusDiv").eq(0);
		var fileName = statusDiv.find("span").eq(0);
		var progressBar = statusDiv.find(".progressBar").eq(0);
		
		
		
		//as this is opened, we need to see how many swfuploaders have been initialized, and set
		//the unique id based on this.  We only do this once per editor
		//swfuplaod removes the span once it is initialized
		if(uploadSpan.length != 0)
		{
			uploadSpan.attr("id", "uploadSpan" + jQuery("object[id^=uploadSpan]").length);
			progressBar.progressbar({"value":0});
			//init the swf upload object
			jQuery.post("./inc/cleditor.addimage.php", {"type":"getSessionId"}, function(ajax_data)
		   {
				 ajax_data = jQuery.parseJSON(ajax_data);  
				 var swfu = new SWFUpload({ "upload_url" : myUrl + "/inc/upload.php", 
				"flash_url" : myUrl + "/inc/swfupload.swf", 
				"post_params": {"PHPSESSID" : ajax_data.sessionId, "type":"imageUpload"},
				"file_types" : "*.jpg;*.png",
				"button_placeholder_id" : uploadSpan.attr("id"),
				"button_width": uploadButton.width(),
				"button_height": uploadButton.height(),
				"button_window_mode": SWFUpload.WINDOW_MODE.TRANSPARENT,
				"button_cursor": SWFUpload.CURSOR.HAND,
				"custom_settings": {
					//these are used to send custom settings to the event handlers
					"progressTarget" : "fsUploadProgress",
					"cancelButtonId" : "btnCancel"
				},
				
				"swfupload_loaded_handler": swfUploadLoaded,
				"file_queued_handler": fileQueued,
				"file_queue_error_handler": fileQueueError,
				"file_dialog_complete_handler": function(numberSelected, numberQueued, queueSize)
												{
													swfu.startUpload();
												},
				"upload_start_handler" : function(file)
											{
												fileName.text("uploading: " + file.name);
												statusDiv.show();
												return true; //false cancells
												
											},
				"upload_progress_handler" : function(file, bytesComplete, totalBytes)
											{
												progressBar.progressbar("value", (bytesComplete / totalBytes) * 100); 
											},
				"upload_error_handler" : uploadError,
				"upload_success_handler" : uploadSuccess,
				"upload_complete_handler" : function(file)
											{
												var stats = swfu.getStats();
												if(stats.files_queued)
												{
													swfu.startUpload(); 
												}
												else //we're done uploading
												{
													getImges(table, width, height, editor, data);
													fileName.text("Upload(s) Complete");
													setTimeout(function(){statusDiv.hide("slow");}, 2000);
													
													
												}
												
											}
				}); //end new swfu.
				uploadButton.css("left", "-" +  uploadButton.width() + "px").css("z-index", "-1");	
				   
			}); 
			
		}//end if first time load
		
		getImges(table, width, height, editor, data);
		
		
    }	
  
})(jQuery);//end function($)


