//requires jquery, jquery ui, swfupload.swf, swfupload.js, and  and cleditor
var myURL = "http://rjmachine.ca"; //need for passing variables to the flash file

var cmsEditor = function(targetId, pagename)
{
	var me = this;
	this.ajaxfile = "./inc/ajax.php";
	this.targetId = targetId;
	this.pagename = pagename; //this is the name of the table in the database, too.
	this.width = jQuery("#" + me.targetId).width();
	this.height = jQuery("#" + me.targetId).height();
	this.textArea = jQuery("<textarea/>").val(jQuery("#" + targetId).html().replace('\\', '')).height(me.height).width(me.width);


	
	this.dialog;
	this.createDialog = function()
	{
		var dialog = jQuery("<div/>").attr("id", "cmsFor" + me.targetId).append(me.textArea);
		dialog.dialog(
		{	"title":"Edit Page",
			"autoOpen":false,
			"height":me.height + 250,
			"width": me.width + 50,
			"buttons":{"save":function()
			{
				jQuery.post(me.ajaxfile, 
							{
								"type":"saveContent", 
								"element": me.targetId, 
								"pageName":me.pagename,
								"content": me.textArea.val()
							},
							function(data)
							{
								rawdata=data;
								data = jQuery.parseJSON(data);
								if(data.success == "true")
								{
									jQuery("#" + me.targetId).html(me.textArea.val());	
									me.createEditButton();
									me.dialog.dialog("close");
								}
								else
								{

									alert("save failed! " + rawdata);	
								}
								
							});
			}}
		});
		return dialog;
	}//end createDialog
	this.createEditButton = function()
	{
		var editButton = jQuery("<button/>").button({"label":"Edit"}).click(function()
		 {
			 me.dialog.dialog("open");
		 });
		jQuery("#" + me.targetId).append(editButton);
	}
	
	this.createClEditor = function()
	{
		me.textArea.cleditor({
			width:        me.width, // width not including margins, borders or padding
			height:       me.height + 150, // height not including margins, borders or padding
			controls:     // controls to add to the toolbar
						  "bold italic underline strikethrough subscript superscript | font size " +
						  "style | color highlight removeformat | bullets numbering | outdent " +
						  "indent | alignleft center alignright justify | undo redo | " +
						  "rule link unlink | cut copy paste pastetext | print source | table | addImage",
			colors:       // colors in the color popup
						  "FFF FCC FC9 FF9 FFC 9F9 9FF CFF CCF FCF " +
						  "CCC F66 F96 FF6 FF3 6F9 3FF 6FF 99F F9F " +
						  "BBB F00 F90 FC6 FF0 3F3 6CC 3CF 66C C6C " +
						  "999 C00 F60 FC3 FC0 3C0 0CC 36F 63F C3C " +
						  "666 900 C60 C93 990 090 399 33F 60C 939 " +
						  "333 600 930 963 660 060 366 009 339 636 " +
						  "000 300 630 633 330 030 033 006 309 303",    
			fonts:        // font names in the font popup
						  "Arial,Arial Black,Comic Sans MS,Courier New,Narrow,Garamond," +
						  "Georgia,Impact,Sans Serif,Serif,Tahoma,Trebuchet MS,Verdana",
			sizes:        // sizes in the font size popup
						  "1,2,3,4,5,6,7",
			styles:       // styles in the style popup
						  [["Paragraph", "<p>"], ["Header 1", "<h1>"], ["Header 2", "<h2>"],
						  ["Header 3", "<h3>"],  ["Header 4","<h4>"],  ["Header 5","<h5>"],
						  ["Header 6","<h6>"]],
			useCSS:       false, // use CSS to style HTML when possible (not supported in ie)
			docType:      // Document type contained within the editor
						  '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
			docCSSFile:   // CSS file used to style the document contained within the editor
						  "", 
			bodyStyle:    // style to assign to document body contained within the editor
						  "margin:4px; font:10pt Arial,Verdana; cursor:text"
		});
	}
	
	this.dialog = this.createDialog();
	this.createClEditor();
	this.createEditButton();
	
	return me;
	
}

var slideShowEditor = function(slideShowId, targetId)
{
	var me = this;
	this.ajaxfile = "./inc/ajax.php";
	this.slideShowId = slideShowId;
	this.target = jQuery("#" + targetId);
	this.dialog = jQuery("<div/>").attr("id", "slideShowEditor" + slideShowId);
	this.mainDiv = jQuery("<div/>").addClass("slideShowEditorMain");
	var folders = jQuery("<select/>").addClass("cmsSelect");
	var files = jQuery("<select/>").addClass("cmsSelect");
	this.folder;
	
	me.slideShowTable = jQuery("<table/>");//used to edit the settings global to the slide show
	var slideShowDiv = jQuery("<div/>").addClass("editSlideShowDiv").append("<h1>Slide Show Settings</h1>").append(me.slideShowTable);
	var SlideShowBorder = jQuery("<div/>").addClass("editSlideShowDivBorder").append(slideShowDiv);//because gd IE can't pad properly
	
	var editImageTable = jQuery("<table/>");//used to edit settings specific to a slide image
	var editImageDiv = jQuery("<div/>").addClass("editImageInfo").append("<h1>Images Settings</h1>").append(editImageTable);
	var editImageBorder = jQuery("<div/>").addClass("editImageInfoBorder").append(editImageDiv);
	
	me.slideShowImagesList = jQuery("<ol/>").addClass("slideShowList")
	.sortable({"connectWith": ".slideShowList", 
			  "receive":function(event, ui)
				{
					jQuery.post(me.ajaxfile, {"type":"addImage", "id": me.slideShowId, "file":ui.item.find("img").attr("src")}, function(data)
					  {
						  data = jQuery.parseJSON(data);
						  ui.item.find("input").val(data.id);
						  ui.item.click(function(eventObject)
						  {
							  jQuery("img").removeClass("selectedImage");
							  ui.item.find("img").addClass("selectedImage");
							  getSlideInfo(data.id);
						  });
						  
						  //update the order - a recieve, even though it affects the order, is not a sort event.
						  jQuery.each(me.slideShowImagesList.find("li"), function(index, value)
					 	{
							var id = jQuery(value).find("input").val();
							jQuery.post(me.ajaxfile, {"type":"updateIndex", "id":id, "index":index}, function(data)
							{
								
							});
						});
						  
						
					  });//end post
					
				},//end recieve);
				"stop":function(event, ui)
				{
					jQuery.each(me.slideShowImagesList.find("li"), function(index, value)
					 {
							var id = jQuery(value).find("input").val();
							jQuery.post(me.ajaxfile, {"type":"updateIndex", "id":id, "index":index}, function(data)
							{
								
							});
						 
						 
					});
					
				
					
				}//end update
				});//end sortable
	var slideShowImagesDiv = jQuery("<div/>").addClass("editSlideShowImagesDiv").append("<h1>Slide Show Images</h1>").append(me.slideShowImagesList);
	
	this.imageBinList = jQuery("<ol/>").addClass("slideShowList").
		sortable({"connectWith": ".slideShowList", "receive":function(event, ui)
		{
			var id = ui.item.find("input").val();	
			deleteImageInfo(id);
																																	
		}//end receive function
		});
	var imageBinDiv = jQuery("<div/>").attr("id", "imageBin").append("<h1>Available Images</h1>").append(me.imageBinList);
	
	this.swfu = null;
	this.spanSWFUploadButton = jQuery("<span/>").attr("id", "spanSWFUploadButton" + slideShowId).append("Span");
	this.uploadFilesButton = jQuery("<button/>").button({"label":"Upload Files"}).css("position", "relative");
	
	this.statusDiv = jQuery("<div/>");
	this.fileName = jQuery("<span/>");
	this.progressBar = jQuery("<div/>").progressbar({"value":37});
	this.statusDiv = jQuery("<div/>").append(me.fileName, me.progressBar).hide();

	this.mainDiv.append(SlideShowBorder, editImageBorder, slideShowImagesDiv, imageBinDiv, me.spanSWFUploadButton, me.uploadFilesButton, me.statusDiv);
	this.dialog.append(me.mainDiv);
	
	var getSlideInfo = function(id)
	{
		me.imageId.val(id);
		jQuery.post(me.ajaxfile, {"type":"getImageInfo", "id":id}, function(data)
		{
			data = jQuery.parseJSON(data);
			me.imageTitle.val(data.title);
			me.imageCaption.val(data.caption);
			
		});
	
	}
	var deleteImageInfo = function(id)
	{
		if(id == "")
	   {
			return;   
	   }
	   jQuery.post(me.ajaxfile, {"type":"deleteImageInfo", "id":id}, function(data)
		{
			data = jQuery.parseJSON(data);
			if(data.result == "success")
			{
				var li = me.slideShowImagesList.find('li:has(input[value = "' + id + '"])').detach();
				me.imageBinList.append(li);
				li.find("img").removeClass("selectedImage");
				
			}
			
		});
		
		
	}
	
	
	var createEditImageTable = function()
	{
		 var titleRow = jQuery("<tr/>");
		 var titleLabel = jQuery("<label/>").text("Title");
		 var labelCell = jQuery("<td/>").append(titleLabel);
		 me.imageTitle = jQuery("<input/>").attr("type", "text").css("width", "300");
		 me.imageId = jQuery("<input/>").attr("type", "hidden");
		 var titleCell = jQuery("<td/>").append(me.imageTitle, me.imageId);
		 titleRow.append(labelCell, titleCell);
		 
	 
		 me.imageCaption = jQuery("<textarea/>").attr("cols", "30").attr("rows", "5").css("width", "300");
		 var captionLabel = jQuery("<label/>").text("Caption");
		 var captionCell = jQuery("<td/>").append(me.imageCaption);
		 var captionLabelCell = jQuery("<td/>").append(captionLabel);
		 var captionRow = jQuery("<tr/>").append(captionLabelCell, captionCell);
		 
		 var saveButton = jQuery("<button/>").button({"label":"Save"});
		 var deleteButton = jQuery("<button/>").button({"label":"Delete"});
		 var buttonCell = jQuery("<td/>").append(deleteButton).append(saveButton).attr("colspan", "2").attr("align", "right");
		 var buttonRow = jQuery("<tr/>").append(buttonCell);
		 
		 
		 editImageTable.append(titleRow, captionRow, buttonRow);
		 saveButton.click(function()
		   {
			   if(me.imageId.val() == "")
			   {
					return;   
			   }
			   
			   jQuery.post(me.ajaxfile, {"type":"saveImageInfo", 
						   "id":me.imageId.val(), 
						   "title":me.imageTitle.val(), 
						   "caption":me.imageCaption.val()}, 
						   function(data)
							{
								jQuery.parseJSON(data);
							});
			   
		   });
		 deleteButton.click(function()
		 {
			 	deleteImageInfo(me.imageId.val());
		 });
		 
		
	}
	
	var createEditSlideShowTable = function()
	{
		
		 var titleRow = jQuery("<tr/>");
		 var titleLabel = jQuery("<label/>").text("Title");
		 var labelCell = jQuery("<td/>").append(titleLabel);
		 me.slideShowTitle = jQuery("<input/>").attr("type", "text").css("width", "300");
		 var titleCell = jQuery("<td/>").append(me.slideShowTitle);
		 titleRow.append(labelCell, titleCell);
		 
		 me.slideShowImage = jQuery("<img/>");
		 var imageLabel = jQuery("<label/>").text("Image");
		 var imageLabelCell = jQuery("<td/>").append(imageLabel);
		 var imageCell = jQuery("<td/>").append(me.slideShowImage);
		 var imageRow = jQuery("<tr/>").append(imageLabelCell, imageCell);
		 
		 me.slideShowCaption = jQuery("<textarea/>").attr("cols", "30").attr("rows", "2").css("width", "300");
		 var captionLabel = jQuery("<label/>").text("Caption");
		 var captionCell = jQuery("<td/>").append(me.slideShowCaption);
		 var captionLabelCell = jQuery("<td/>").append(captionLabel);
		 var captionRow = jQuery("<tr/>").append(captionLabelCell, captionCell);
		 
		 var indexLabel = jQuery("<label/>").text("Display Index");
		 var indexLabelCell = jQuery("<td/>").append(indexLabel);
		 me.slideShowIndex = jQuery("<input/>").attr("type", "text").css("width", "50");
		 var indexCell = jQuery("<td/>").append(me.slideShowIndex);
		 var indexRow = jQuery("<tr/>").append(indexLabelCell, indexCell);
		 
		 var saveButton = jQuery("<button/>").button({"label":"Save"});
		 var deleteButton = jQuery("<button/>").button({"label":"Delete"});
		 var buttonCell = jQuery("<td/>").append(saveButton, deleteButton).attr("colspan", "2").attr("align", "right");
		 var buttonRow = jQuery("<tr/>").append(buttonCell)
		 
		 me.slideShowTable.append(titleRow, imageRow, captionRow, indexRow, buttonRow);
		 
		 saveButton.click(function()
			{
				jQuery.post(me.ajaxfile, {"type":"saveSlideShowInfo",
										"id": me.slideShowId,
										"title": me.slideShowTitle.val(),
										"caption":me.slideShowCaption.val(),
										"index":me.slideShowIndex.val()},
										function(data)
										{
											data = jQuery.parseJSON(data);
	
										});
				
			});
		 deleteButton.click(function()
			 {
				 jQuery.post(me.ajaxfile, {"type":"deleteSlideshow", "id":me.slideShowId}, function(data)
				{
					var row = jQuery("#" + me.slideShowId);
					row.remove();
					me.dialog.dialog("close");
					
				});
				 
			 });
		 
		
		
	}
	
	var getSlideShowInfo = function()
	{
		jQuery.post(me.ajaxfile, {"type":"getImagesForSlideShow", "id":me.slideShowId}, function(data)
						 {
							 data = jQuery.parseJSON(data);
							 if(data.length == 0)
								{
									alert("zero length slide show!")
									return;	
								}
								
							me.folder = data[0].folder;
							 //fill in the general info
							 me.slideShowTitle.val(data[0].title);
							 if(data[0].custom == "1")
							 {
								 me.slideShowImage.attr("src", "./photo_gallery/custom_work/" + data[0].title_image);
							 }
							 else
							 {
								 me.slideShowImage.attr("src", "./photo_gallery/" + data[0].folder + "/" + data[0].title_image);
							 }
							 me.slideShowCaption.val(data[0].caption);
							 me.slideShowIndex.val(data[0].index);
							 						
							 jQuery.post(me.ajaxfile, {"type":"getNewImageNames", "id":me.slideShowId}, function(images)
								{
									me.imageBinList.find("li").remove();
									  var fileNames = jQuery.parseJSON(images);
									  jQuery.each(fileNames, function(index, value)
										{
											var image = jQuery("<img/>")
											.attr("src", "./photo_gallery/" + data[0].folder + "/" + value)
											.attr("height", "96").attr("width", "128");
											var id = jQuery("<input/>").attr("type", "hidden");
											var li = jQuery("<li/>").append(image, id);
											me.imageBinList.append(li);
											
										});
								});
							
							 
							 //make our list
							 jQuery.post(me.ajaxfile, {"type":"getImagesForSlideShow", "id":me.slideShowId}, function(data)
							{
								me.slideShowImagesList.find("li").remove();
								data = jQuery.parseJSON(data);
								jQuery.each(data, function(index, value)
								{
									if(value.image == null)
									return true;
									
									var img = jQuery("<img/>")
									.attr("src", "./photo_gallery/" + value.folder + "/" + value.image)
									.attr("height", "96").attr("width", "128");
									var id = jQuery("<input/>").attr("type", "hidden").val(value.image_id);
									var li = jQuery("<li/>").append(img, id);
									me.slideShowImagesList.append(li);
									li.click(function(eventObject)
									{
										jQuery("img").removeClass("selectedImage");
										img.addClass("selectedImage");
										getSlideInfo(id.val());
										
									});
								
									
																	
								});
								
							});
							 
							 
							
						 });//end post
		
	}
	
	
	this.dialog.dialog({"title":"Gallery Editor",
					 "autoOpen":false,
					 "height":800,
					 "width":1024,
					 "position":"top",
					 "open":function()
					 {
						getSlideShowInfo();
					
						if(me.swfu == null)
						{
							jQuery.post(me.ajaxfile, {"type":"getSessionId"}, function(data)
						   {
								 data = jQuery.parseJSON(data);  
								 me.swfu = new SWFUpload({ "upload_url" : myURL + "/inc/upload.php", 
								"flash_url" : myURL + "/inc/swfupload.swf", 
								"post_params": {"PHPSESSID" : data.sessionId, "slideShowId":me.slideShowId},
								"file_types" : "*.jpg;*.png",
								"button_placeholder_id" : "spanSWFUploadButton" + me.slideShowId,
								"button_width": me.uploadFilesButton.width(),
								"button_height": me.uploadFilesButton.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": me.swfUploadLoaded,
								"file_queued_handler": me.fileQueued,
								"file_queue_error_handler": me.fileQueueError,
								"file_dialog_complete_handler": me.fileDialogComplete,
								"upload_start_handler" : me.uploadStart,
								"upload_progress_handler" : me.uploadProgress,
								"upload_error_handler" : me.uploadError,
								"upload_success_handler" : me.uploadSuccess,
								"upload_complete_handler" : me.uploadComplete
								}); //end new swfu.
								me.uploadFilesButton.css("left", "-" +  me.uploadFilesButton.width() + "px").css("z-index", "-1");	
								   
							}); //end post
						}//end if
					
						 
						 
					 }//end open
	 });//end dialog
	
	/*
	//set the events up
	this.folders.change(function()
	{
		jQuery.post(me.ajaxfile, {"type":"getImageNames", "folder":me.folders.find("option:selected").val()}, function(data)
		{
			me.files.find("li").remove();
			data = jQuery.parseJSON(data);
			 jQuery.each(data, function(index, value)
			{
				var option = jQuery("<option/>").attr("value", value).append(value);
				me.files.append(option);
				
			});
			
		});
	});
	*/
	//handlers for swfupload
		me.swfUploadLoaded = function()
		{
				
		}
		me.fileQueued = function(file)
		{
								
		}
		me.fileQueueError = function(file, errorCode, message)
		{
			alert("file queue error:" + message);
		}
		me.fileDialogComplete = function(numberSelected, numberQueued, queueSize)
		{
			//alert("" + numberQueued + " files queued");
			me.swfu.startUpload();
		}
		me.uploadStart = function(file)
		{
			me.fileName.text("uploading: " + file.name);
			me.statusDiv.show();
			return true; //false cancells
			
		}
		me.uploadProgress = function(file, bytesComplete, totalBytes)
		{
			me.progressBar.progressbar("value", (bytesComplete / totalBytes) * 100); 
			//alert("progress!" + bytesComplete);
		}
		me.uploadError = function(file, errorCode, message)
		{
			alert("upload error:" + message);	
		}
		me.uploadSuccess = function(file, serverData, response)
		{
			//alert("uploadSuccess:" + serverData);
		}
		me.uploadComplete = function(file)
		{
			var stats = me.swfu.getStats();
			if(stats.files_queued)
			{
				me.swfu.startUpload(); 
			}
			else //we're done uploading
			{
				me.fileName.text("Upload(s) Complete");
				jQuery.post(me.ajaxfile, {"type":"getNewImageNames", "id":me.slideShowId}, function(images)
								{
									me.imageBinList.find("li").remove();
									  var fileNames = jQuery.parseJSON(images);
									  jQuery.each(fileNames, function(index, value)
										{
											var image = jQuery("<img/>")
											.attr("src", "./photo_gallery/" + me.folder + "/" + value)
											.attr("height", "96").attr("width", "128");
											var id = jQuery("<input/>").attr("type", "hidden");
											var li = jQuery("<li/>").append(image, id);
											me.imageBinList.append(li);
											
										});
								});//end post
				setTimeout(function(){me.statusDiv.hide("slow");}, 2000);
				
			}
			
		}
	
	createEditSlideShowTable();
	createEditImageTable();
	return this.dialog;
	
}//end photoGalleryEditor
	
var newSlideShowDialog = function(targetId)
{
	var me = this;
	this.ajaxfile = "./inc/ajax.php";
	this.target = jQuery("#" + targetId);
	this.table = jQuery("<table/>");
	this.dialog = jQuery("<dialog/>").append(me.table);
	
	var createNewSlideShowTable = function()
	{
		
		 var titleRow = jQuery("<tr/>");
		 var titleLabel = jQuery("<label/>").text("Title");
		 var labelCell = jQuery("<td/>").append(titleLabel);
		 me.title = jQuery("<input/>").attr("type", "text").css("width", "300");
		 var titleCell = jQuery("<td/>").append(me.title);
		 titleRow.append(labelCell, titleCell);
		 
				
		 me.slideShowImage = jQuery("<img/>").attr("src", "./photo_gallery/custom_work/custom_work.png");
		 var imageLabel = jQuery("<label/>").text("Image");
		 var imageLabelCell = jQuery("<td/>").append(imageLabel);
		 var imageCell = jQuery("<td/>").append(me.slideShowImage);
		 var imageRow = jQuery("<tr/>").append(imageLabelCell, imageCell);
		 
		 me.caption = jQuery("<textarea/>").attr("cols", "30").attr("rows", "2").css("width", "300");
		 var captionLabel = jQuery("<label/>").text("Caption");
		 var captionCell = jQuery("<td/>").append(me.caption);
		 var captionLabelCell = jQuery("<td/>").append(captionLabel);
		 var captionRow = jQuery("<tr/>").append(captionLabelCell, captionCell);
		 
		 var indexLabel = jQuery("<label/>").text("Display Index");
		 var indexLabelCell = jQuery("<td/>").append(indexLabel);
		 me.index = jQuery("<input/>").attr("type", "text").css("width", "50");
		 var indexCell = jQuery("<td/>").append(me.index);
		 var indexRow = jQuery("<tr/>").append(indexLabelCell, indexCell);
		 
		 var saveButton = jQuery("<button/>").button({"label":"Save"});
		 var buttonCell = jQuery("<td/>").append(saveButton).attr("colspan", "2").attr("align", "right");
		 var buttonRow = jQuery("<tr/>").append(buttonCell)
		 
		 me.table.append(titleRow, imageRow, captionRow, indexRow, buttonRow);
		 
		 saveButton.click(function()
			{
				if(isNaN(me.index.val()) || me.index.val() == ""  ||  me.title.val().length <= 3)
				  {
					  alert("The Display Index must be a number and the title must be at leadst 3 characters");
					  return;
				  }
				
				jQuery.post(me.ajaxfile, {"type":"newSlideShow",
										"title": me.title.val(),
										"caption":me.caption.val(),
										"index":me.index.val()},
										function(data)
										{
											//repopulate the div that holds the galleries
											me.target.append(data);
											var row = me.target.find("tr:last");
											var slideShowId = row.find("input[type=hidden]").val();
											var editor = new slideShowEditor(slideShowId, "photoGalleries");
											var button = jQuery("<button/>").button({"label":"edit"});
											row.find("td:first").append(button);
											button.click(function()
											{
												editor.dialog("open");
											});
											me.dialog.dialog("close")
										});
				
			});
		 
		
		
	}
	
	this.dialog.dialog({"autoOpen":false, 
					   "title":"New Gallery",
					   "width":420, 
					   "open":function()
					   {
						   jQuery("input").val("");
									   
					   }//end open
					   }//end dialog options
					   );//end dialog
	
	createNewSlideShowTable();
	return this.dialog;
}
	
var logOutButton = function(divId)
{
	var me = this;
	this.ajaxfile = "./inc/ajax.php";
	var newButton = jQuery("<button/>").css("position", "absolute").css("z-index", "9999");
	jQuery("#" + divId).prepend(newButton);
	jQuery(newButton).button({"label":"Log Out"}).click(function()
	{
		jQuery.post(me.ajaxfile, {"type":"logOut"}, function(data)
		 {
			window.location = "index.php"; 
			 
		 });
	
	});	
	
}


var FileTableEditor = function(tableId, fileCellId, textCellId, manualId)
{
	var me = this;
	me.ajaxFile = "./inc/ajax.php";
	me.table = jQuery("#" + tableId);
	me.manualId = manualId;
	me.fileCell = jQuery("#" + fileCellId);
	me.textCell = jQuery("#" + textCellId);
	me.title = "Edit Manuals";
	me.dialog = jQuery("<div/>");
	me.fileSelect = jQuery("<select/>").addClass("cmsSelect").css("width", "587px");
	me.text = jQuery("<textarea/>").attr("cols", "60").attr("rows", "7").css("width", "585px");
	me.indexLabel = jQuery("<label/>").text("index");
	me.index = jQuery("<input/>").attr("type", "text").css("width", "30px");
	me.spanSWFUploadButton = jQuery("<span/>").attr("id", "spanSWFUploadButton" + manualId).append("Span");
	me.uploadFilesButton = jQuery("<button/>").button({"label":"Upload Files"}).css("position", "relative");
	
	me.statusDiv = jQuery("<div/>");
	me.fileName = jQuery("<span/>");
	me.progressBar = jQuery("<div/>").progressbar({"value":37});
	me.statusDiv = jQuery("<div/>").append(me.fileName, me.progressBar).hide();
	
	me.dialog.append(jQuery("<div/>").append(me.fileSelect), 
					jQuery("<div/>").append(me.text),  
					jQuery("<div/>").append(me.indexLabel, me.index), 
					jQuery("<div/>").append(me.spanSWFUploadButton, me.uploadFilesButton),
					me.statusDiv);
	
	
	me.dialog.dialog({"autoOpen":false, 
					   "title":me.title,
					   "width":620, 
					   "open":function()
					   {
						  jQuery.post(me.ajaxFile, {"type":"getManuals"}, function(data)
						   {
							   data = jQuery.parseJSON(data);
							   jQuery.each(data, function(index, value)
							  {
								  var option = jQuery("<option/>");
								  option.text(value).val(value);
								  me.fileSelect.append(option);
							  });
							   me.fileSelect.val(me.fileCell.find("a").text());
						   });//end post
						  
						  	me.text.val(me.textCell.text());
							
						//get the index
						jQuery.post(me.ajaxFile, {"type":"getManualIndex", "id":me.manualId}, function(data)
						  {
							  me.index.val(data);
						  });
						
						//ie gives and error if this isn't created in the open event.  
						//we only want to do it once.
						if(me.swfu == null)
						{
							jQuery.post(me.ajaxFile, {"type":"getSessionId"}, function(data)
						   {
								 data = jQuery.parseJSON(data);  
								 me.swfu = new SWFUpload({ "upload_url" : myURL + "/inc/upload.php", 
								"flash_url" : myURL + "/inc/swfupload.swf", 
								"post_params": {"PHPSESSID" : data.sessionId},
								"file_types" : "*.pdf",
								"button_placeholder_id" : "spanSWFUploadButton" + me.manualId,
								"button_width": me.uploadFilesButton.width(),
								"button_height": me.uploadFilesButton.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": me.swfUploadLoaded,
								"file_queued_handler": me.fileQueued,
								"file_queue_error_handler": me.fileQueueError,
								"file_dialog_complete_handler": me.fileDialogComplete,
								"upload_start_handler" : me.uploadStart,
								"upload_progress_handler" : me.uploadProgress,
								"upload_error_handler" : me.uploadError,
								"upload_success_handler" : me.uploadSuccess,
								"upload_complete_handler" : me.uploadComplete
								}); //end new swfu.
								me.uploadFilesButton.css("left", "-" +  me.uploadFilesButton.width() + "px").css("z-index", "-1");	
								   
							}); //end post
						}//end if
											
						
					 

							
												
						  
					   },//end open()
					   "buttons":{
						 "delete":function()
						 {
							 if(confirm("Really delete manual?"))
							{
							 //delete the database entry
								 jQuery.post(me.ajaxFile, {"type":"deleteManual", "id":me.manualId}, function(data)
								  {
									   //remove the row from the dom
									   //the manualId is the same as the row id
									   data = jQuery.parseJSON(data);
									   if(data.result == "success")
									   {
											jQuery("#" + me.manualId).remove();
									   }
									   else
									   {
											alert("error deleting manual!");   
									   }
									   me.dialog.dialog("destroy");
									   
									  
								  });
							}//end if
							 
							
							 
							 
						 },//end delete  
						   
						 "save":function()
						 {
							 jQuery.post(me.ajaxFile, {"type":"saveManual", 
														 "id":me.manualId, 
														 "fileName": me.fileSelect.val(), 
														 "text":me.text.val(),
														 "index":me.index.val()},
														 function(data)
														 {
															 data = jQuery.parseJSON(data);
															//update the page
															if(data.Success == 'true')
															{
																me.fileCell.html('<a href = "./' + data.manual_folder + '/' + me.fileSelect.val() + '">' + me.fileSelect.val() + '</a>');	
																me.textCell.html(me.text.val());
																me.dialog.dialog("close");
															}
															else
															{
																alert("error saving manual!");	
															}
															
															
														 });
							 
							 
							 
							 
						 } //end save
						   
					   }//end buttons
					   });//end dialog.dialog()
				


		//handlers for swfupload
		me.swfUploadLoaded = function()
		{
				
		}
		me.fileQueued = function(file)
		{
								
		}
		me.fileQueueError = function(file, errorCode, message)
		{
			alert("file queue error:" + message);
		}
		me.fileDialogComplete = function(numberSelected, numberQueued, queueSize)
		{
			//alert("" + numberQueued + " files queued");
			me.swfu.startUpload();
		}
		me.uploadStart = function(file)
		{
			me.fileName.text("uploading: " + file.name);
			me.statusDiv.show();
			return true; //false cancells
			
		}
		me.uploadProgress = function(file, bytesComplete, totalBytes)
		{
			me.progressBar.progressbar("value", (bytesComplete / totalBytes) * 100); 
			//alert("progress!" + bytesComplete);
		}
		me.uploadError = function(file, errorCode, message)
		{
			alert("upload error:" + message);	
		}
		me.uploadSuccess = function(file, serverData, response)
		{
			alert("uploadSuccess:" + serverData);
		}
		me.uploadComplete = function(file)
		{
			var stats = me.swfu.getStats();
			if(stats.files_queued)
			{
				me.swfu.startUpload(); 
			}
			else //we're done uploading
			{
				me.fileName.text("Upload(s) Complete");
				jQuery.post(me.ajaxFile, {"type":"getManuals"}, function(data)
						   {
							   me.fileSelect.find("option").remove();
							   data = jQuery.parseJSON(data);
							   jQuery.each(data, function(index, value)
							  {
								  var option = jQuery("<option/>");
								  option.text(value).val(value);
								  me.fileSelect.append(option);
							  });
							   me.fileSelect.val(file.name);
						   });//end post
				setTimeout(function(){me.statusDiv.hide("slow");}, 2000);
				
			}
			
		}

}//end fileTableEditor

var newManual = function(tableId)
{
	var table = jQuery("#" + tableId);
	jQuery.post("./inc/ajax.php", {"type":"newManual"}, function(data)
				 {
					 data = jQuery.parseJSON(data);
					 var fileCellId = "fileCell" + data.id;
					 var textCellId = "textCell" + data.id;
					 var row = jQuery("<tr/>").attr("id", data.id);
					 var fileCell = jQuery("<td/>").attr("id", fileCellId).text("new manual");
					 var textCell = jQuery("<td/>").attr("id", textCellId).text("new text");
					 row.append(fileCell, textCell);
					 table.append(row);
					 var fileTableEditor = new FileTableEditor(tableId, fileCellId, textCellId, data.id);
					 var editButton = jQuery("<botton/>").button({"label":"Edit"});
					 var editCell = jQuery("<td/>").append(editButton);
					 row.append(editCell);
					 editButton.click(function()
					  {
						  fileTableEditor.dialog.dialog("open");
						  
					  });
					 
				 });
	
	
	
}

	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

