// Primary JavaScript file for UCMS. Standard, common actions.

// 1. Session Management
// 2. Basic Editing

// This method is used to store data from the database about the page into the JavaScript store
// so that it can be used in the JavaScript resources
$(function() { storeNow(); } );

// SECTION ONE
// Session Management

// Log In (Open Form)
$(function() {
	$("body").delegate("#logInLink", "click", function() {
		logInContents = $("<form id='logInForm' action='javascript:return false'><div><div class='usernameOuter'>&emsp;<span class='usernameInner'>Username: </span><input size=12 id='loginUsername' type='text' /></div>&emsp;\
					<div class='passwordOuter'><span class='passwordInner'>Password: </span><input id='loginPassword' type='password' size=12/></div>\
					<input value='Log In' id='logInButton' type='submit'></div></form>");
		$("#logInZone").empty().append(logInContents[0]);
		$("#loginUsername").focus();
		$("#logInLink").hide();
	});
});

// Log In (Form Submission)
$(function() {
	$("body").delegate("#logInButton", "click", function() {	
		$.post('../core/login.php', { action: 'logIn', loginUsername: $('#loginUsername').val(), loginPassword: $('#loginPassword').val(), ajax: 1, store: store },
			function(data) {
				$("#logInZone").empty();
				if(data === "1") {
					window.location.reload();
				} else {
					$("#logInZone").append("Login Error. Please try again.");
					$("#logInLink").show();
				}
			}
		);
	});
});

// Log Out
$(function() {
	$("body").delegate("#logOutLink", "click", function() {
		$.post('../core/login.php', { action: 'logOut', ajax: 1, store: store },
			function(data) {
				$("#helloZone").empty();
				if(data === "1") {
					window.location.reload();
				}
			}
		);
	});
});

// SECTION TWO
// Basic Editing

// Insert editor buttons
$(function() {
	titles = $("div[id^='item-editable']").children('.title');

	// it would be nice to generalize this out, but can't save this kind of thing that I have figured out
//	iid = $(this).parent().parent().attr('id').substring(13);

//	editButton.attr('id', 'editButton' + editButton.parent().parent().attr('id').substring(13));
	editButton = $("&emsp;<input type='button' class='editButton' value='Edit' />").appendTo(titles).attr('id', function() {
		return 'editButton' + $(this).parent().parent().attr('id').substring(13);
	});
	deleteButton = $("&emsp;<input type='button' class='deleteButton' value='Delete' />").appendTo(titles).attr('id', function() {
		return 'deleteButton' + $(this).parent().parent().attr('id').substring(13);
	});
	moveUpButton = $("&emsp;<input type='button' class='moveUpButton' value='Move Up' />").appendTo(titles.filter(':not(:first)')).attr('id', function() {
		return 'moveUpButton' + $(this).parent().parent().attr('id').substring(13);
	});
	moveDownButton = $("&emsp;<input type='button' class='moveDownButton' value='Move Down' />").appendTo(titles.filter(':not(:last)')).attr('id', function() {
		return 'moveDownButton' + $(this).parent().parent().attr('id').substring(13);
	});

	addButton = $("&emsp;<input type='button' class='addButton' value='Add Item' />").appendTo('#pagetitle-editable').attr('id', function() {
		return 'addButton' + store.ps.pid;
	});
});

// Start editing item
$(function() {
	$("body").delegate("input[id^='editButton']", "click", function() {

		$('input[id="editButton' + $(this).attr('id').substring(10) + '"]').hide();

		$.post('../core/ajax-edit.php', { action: 'editItem', iid: $(this).attr('id').substring(10), ajax: 1, store: store },
			function(data) {
				
				if(JSON.parse(data))
				{
					data = JSON.parse(data);
				
					// Hide stuff
					$('#body-editable' + data.iid).hide();
					$('#title-editable' + data.iid).hide();

					// todo: break this into separate method

		                        lines = data.content.split("\n");
					
		                        linelength = lines.length;
                  		        for (line in lines)
		                        {
                		                innerline = (lines[line].length / 80) + 1;
                                		linelength += innerline;
		                        }

					textarea = document.createElement('textarea');
					textarea.id = 'editItemTextarea' + data.iid;
					textarea.rows = linelength;
					var regEx = new RegExp ('<br>', 'gi');
					textarea.value = data.content.replace(regEx, '\n');

					$(textarea).width('98%');
					$(textarea).height('100%');

					titletextbox = document.createElement('input');
					titletextbox.type = 'text';
					titletextbox.id = 'editItemTitleTextbox' + data.iid;
					titletextbox.size = data.title.length + 2;
					titletextbox.value = unescape(data.title);

					activateTextboxResizing(data, '#editItemTitleTextbox' + data.iid, '#cancelButton' + data.iid);
					activateTextareaResizing(data, '#editItemTextarea' + data.iid, '#cancelButton' + data.iid);

					$('#body-editable' + data.iid).before(titletextbox);
					$('#body-editable' + data.iid).after(textarea);		
				
					saveButton = $("&emsp;<input type='button' class='editButton' value='Save' />").insertBefore('#body-editable' + data.iid);
					saveButton.attr('id', 'saveButton' + data.iid);
					cancelButton = $("&emsp;<input type='button' class='editButton' value='Cancel' />").insertBefore('#body-editable' + data.iid);
					cancelButton.attr('id', 'cancelButton' + data.iid);
				}
			}
		);
	});
});

// Activate the textbox resizing stuff
function activateTextboxResizing(data, textboxID, cancelID) {

	$("body").delegate(textboxID, "keydown", function(event) {

		if ((event.keyCode == 32) || (event.keyCode >= 46 && event.keyCode <= 111) || event.keyCode == 8 || (event.keyCode >= 184 && event.keyCode <= 200))
		{
			$(textboxID).attr('size', $(textboxID).val().length + 2);
			return true;
		}
	});
}

// Activate the textarea resizing stuff
// for the textareaID property, make sure you have a "#" in front of the ID!
function activateTextareaResizing(data, textareaID, cancelID) {

	$("body").delegate(textareaID, "keydown", function(event) {
		
		if ((event.keyCode == 32) || (event.keyCode >= 46 && event.keyCode <= 111) || event.keyCode == 8 || (event.keyCode >= 184 && event.keyCode <= 200))
		{
			
		}
		else if (event.keyCode == 13)
		{
			textareaHeight = $(textareaID).css('height').split('px')[0];
			textareaFontSize = $(textareaID).css('font-size').split('px')[0];
			$(textareaID).css('height', (parseInt(textareaHeight) + parseInt(textareaFontSize) + 5) + "px");

			outerHeight = $(textareaID).parent().parent().css('height').split('px')[0];
			outerFontSize = $(textareaID).parent().parent().css('font-size').split('px')[0];
			$(textareaID).parent().parent().css('height', (parseInt(outerHeight) + parseInt(outerFontSize) + 3) + 'px');

			return true;
		}
		// this does not work at the moment... did not investigate
		else if (event.keyCode == 27 && cancelID != null)
		{
			$(cancelID).click();
			return false;
		}
		return true;

	});

}

// Cancel editing item
$(function() {
	$("body").delegate("input[id^='cancelButton']", "click", function() {
		iid = $(this).parent().attr('id').substring(13);

		$('#body-editable' + iid).show();
		$('#title-editable' + iid).show();
		
		$('input[id="editButton' + iid + '"]').show();
		$('#saveButton' + iid).remove();
		$('#cancelButton' + iid).remove();
		$('#editItemTextarea' + iid).remove();
		$('#editItemTitleTextbox' + iid).remove();
	});
});
	

// Save item edits	
$(function() {
	$("body").delegate("input[id^='saveButton']", "click", function() {
		iid = $(this).parent().attr('id').substring(13);

                var regEx = new RegExp ('\\n', 'gi');
                content = $('#editItemTextarea' + iid).val().replace(regEx, '<br>');


		$.post('../core/ajax-edit.php', { action: 'saveItem', iid: iid, content: content, title: $('#editItemTitleTextbox' + iid).val(), ajax: 1, store: store },
			function(data) {
				if(data == 1) {
					$('#body-editable' + iid).html(content).show();
					$('#title-editable' + iid).html($('#editItemTitleTextbox' + iid).val()).show();

					editButton = $("&emsp;<input type='button' class='editButton' value='Edit' />").appendTo($('#title-editable' + iid)).attr('id', function() {
						return 'editButton' + $(this).parent().parent().attr('id').substring(13);
					});

					$('input[id="editButton' + iid + '"]').show();
					$('#saveButton' + iid).remove();
					$('#cancelButton' + iid).remove();
					$('#editItemTextarea' + iid).remove();
					$('#editItemTitleTextbox' + iid).remove();
				}
			}
		);
	
	});
});

// Delete item (show confirmation)
$(function() {
	$("body").delegate("input[id^='deleteButton']", "click", function() {
		iid = $(this).parent().attr('id').substring(14);

		$("input").attr('disabled', true);

		deleteConfirmationText = "";

		if($("#title-editable" + iid).text().length > 0)
		{
			deleteConfirmationText = $("#title-editable" + iid).text();
		}
		else
		{
			deleteConfirmationText = $("#body-editable" + iid).text().substring(0,50) + "...";
		}

		$('#message').append("<div class='dialogBoxTitle'>Delete Item</div>");
		$('#message').append("<div class='messageBoxFormLabel'>Are you sure you want to delete the item \"" + deleteConfirmationText + "\"?</div>");
		$('#message').append("<input type='button' class='editButton dialogButton' id='cancelDeleteButton" + iid + "' value='Cancel'>");
		$('#message').append("<input type='button' class='editButton dialogButton defaultDialogButton' id='confirmDeleteButton" + iid + "' value='Delete Item'>");
		$('#message').show();
	});
});

// Actually delete item
$(function() {
	$("body").delegate("input[id^='confirmDeleteButton']", "click", function() {
		iid = $(this).attr('id').substring(19);
		$.post('../core/ajax-edit.php', { action: 'deleteItem', iid: iid, ajax: 1, store: store },
			function(data) {
				if(data == 1)
				{
					$('#item-editable' + iid).next('img').remove();
					$('#item-editable' + iid).remove();

					// remove extra buttons
					titles = $("div[id^='item-editable']").children('.title');
					titles.filter(':first').children("input[id^='moveUpButton']").hide();
					titles.filter(':last').children("input[id^='moveDownButton']").hide();


				}
			}
		);

		// remove extra buttons

		$('#message').hide();
		$('#message').text('');
		
		$("input").removeAttr('disabled');

	});
});

// Cancel item deletion
$(function() {
	$("body").delegate("input[id^='cancelDeleteButton']", "click", function() {
		iid = $(this).attr('id').substring(18);

		$('#message').hide();
		$('#message').text('');
		
		$("input").removeAttr('disabled');
	});
});
		
// Move item up
$(function() {
	$("body").delegate("input[id^='moveUpButton']", "click", function() {
		iid = $(this).attr('id').substring(12);
		$.post('../core/ajax-edit.php', { action: 'moveUpItem', iid: iid, ajax: 1, store: store },
			function(data) {
				if(data == 1)
				{
					theParent = $('#item-editable' + iid).parent();
					previousElement = $('#item-editable' + iid).prevAll("div[id^='item-editable']").first();
					$('#item-editable' + iid).insertBefore(previousElement);
					$('#item-editable' + iid).nextAll('img').first().insertBefore(previousElement);

					$("input[id^='moveUpButton']").remove();
					$("input[id^='moveDownButton']").remove();

					titles = $("div[id^='item-editable']").children('.title');

					moveUpButton = $("&emsp;<input type='button' class='moveUpButton' value='Move Up' />").appendTo(titles.filter(':not(:first)')).attr('id', function() {
						return 'moveUpButton' + $(this).parent().parent().attr('id').substring(13);
					});
					moveDownButton = $("&emsp;<input type='button' class='moveDownButton' value='Move Down' />").appendTo(titles.filter(':not(:last)')).attr('id', function() {
						return 'moveDownButton' + $(this).parent().parent().attr('id').substring(13);
					});
				}
			}
		);
	});
});

// Move item down
$(function() {
	$("body").delegate("input[id^='moveDownButton']", "click", function() {
		iid = $(this).attr('id').substring(14);
		$.post('../core/ajax-edit.php', { action: 'moveDownItem', iid: iid, ajax: 1, store: store },
			function(data) {
				if(data == 1)
				{
					theParent = $('#item-editable' + iid).parent();
					nextElement = $('#item-editable' + iid).nextAll("div[id^='item-editable']").first();
					$('#item-editable' + iid).insertAfter(nextElement);
					$('#item-editable' + iid).prevAll('img').first().insertAfter(nextElement);

					$("input[id^='moveUpButton']").remove();
					$("input[id^='moveDownButton']").remove();

					titles = $("div[id^='item-editable']").children('.title');

					moveUpButton = $("&emsp;<input type='button' class='moveUpButton' value='Move Up' />").appendTo(titles.filter(':not(:first)')).attr('id', function() {
						return 'moveUpButton' + $(this).parent().parent().attr('id').substring(13);
					});
					moveDownButton = $("&emsp;<input type='button' class='moveDownButton' value='Move Down' />").appendTo(titles.filter(':not(:last)')).attr('id', function() {
						return 'moveDownButton' + $(this).parent().parent().attr('id').substring(13);
					});
				}
			}
		);
	});
});

// Add item (create adding box)
$(function() {
	$("body").delegate("input[id^='addButton']", "click", function() {
		pid = store.ps.pid;
		
		$("input").attr('disabled', true);

		$('#message').append("<div class='dialogBoxTitle'>Add New Item</div><div class='messageBoxFormLabel'>Item Title: <br><input size=40 id='newItemTitle" + pid + "' /><br><br>");
		$('#message').append("<div class='messageBoxFormLabel'>Item Text: <br><textarea rows=10 cols=52 valign=top id='newItemBody" + pid + "' /></div>");
		$('#message').append("<input type='button' class='editButton dialogButton' id='cancelAddItemButton" + pid + "' value='Cancel'>");
		$('#message').append("<input type='button' class='editButton dialogButton defaultDialogButton' id='addNewItemButton" + pid + "' value='Add Item'>");
		$('#message').show();
	});
});


// Cancel item creation 
$(function() {
	$("body").delegate("input[id^='cancelAddItemButton']", "click", function() {

		$('#message').hide();
		$('#message').text('');
		
		$("input").removeAttr('disabled');
	});
});

// Save new item
$(function() {
	$("body").delegate("input[id^='addNewItemButton']", "click", function() {
		pid = store.ps.pid;

                var regEx = new RegExp ('\\n', 'gi');
                content = $('#newItemBody' + pid).val().replace(regEx, '<br>');
		column = 'right';

		$.post('../core/ajax-edit.php', { action: 'addNewItem', content: content, title: $('#newItemTitle' + pid).val(), column: column, ajax: 1, store: store },
			function(data) {
				if(data == 1) {

					window.location.reload();
/*					$('#message').hide();
					$('#message').text('');
				
					$("input").removeAttr('disabled');


		We should be doing something like this, instead of refreshing the page.
					$('#body-editable' + iid).html(content).show();
					$('#title-editable' + iid).html($('#editItemTitleTextbox' + iid).val()).show();

					editButton = $("&emsp;<input type='button' class='editButton' value='Edit' />").appendTo($('#title-editable' + iid)).attr('id', function() {
						return 'editButton' + $(this).parent().parent().attr('id').substring(13);
					});

					$('input[id="editButton' + iid + '"]').show();
					$('#saveButton' + iid).remove();
					$('#cancelButton' + iid).remove();
					$('#editItemTextarea' + iid).remove();
					$('#editItemTitleTextbox' + iid).remove();
*/				}
			}
		);
	
	});
});

// Open box to edit all element infos
$(function() {
	$("body").delegate("input[id^='editElementContentButton']", "click", function() {
		pid = store.ps.pid;
		elementSchemaID = $(this).attr('id').split('-')[1];	
		elementSchemaName = $(this).attr('value').split('Edit ')[1];
		$("input").attr('disabled', true);

		$.post('../core/ajax-edit.php', { action: 'getAllElementData', schemaID: elementSchemaID, ajax: 1, store: store },
			function(data) {
				if(JSON.parse(data))
				{
					ordered = false;
					
					data = JSON.parse(data);
		
					var outtable = "<table id='elementTable'><tr id='pieceHeader'><th></th>";
	
					var schemaID = data.schema[0]["Schema ID"];

					for(var header in data.schema)
					{
						header = data.schema[header];
						
						if(header.Flags == 1)
						{
							ordered = true;
							continue;
						}

						outtable += "<th class='header' id='piece" + header.ID + "'>" + header.Label + "</th>";
					}

					outtable += "</tr>";
					outdata = new Array();
		
					var elementList = new Array();
					var orderedElements = new Array();
					
					
					for(var piecex in data.data)
					{
						piece = data.data[piecex];
						if(elementList[piece.ElID] == null || $.isArray(elementList[piece.ElID]) === -1)
						{
							elementList[piece.ElID] = new Array();
						}
						elementList[piece.ElID][piece["Piece ID"]] = piece;
						elementList[piece.ElID].ID = piece.ElID;
						
						if(piece.Flags == 1)
						{
							orderedElements[piece.Content] = elementList[piece.ElID];
							orderedElements[piece.Content].ID = piece.ElID;
						}						
					}
					
					if (ordered == true)
					{
						elementList = orderedElements;
					}
					
					var i = -1;
					var j = 0;
					
					while ( j < elementList.length - 1 )
					{		
						// EID is the ID of element X piece (the individual piece of text/content)
						// ElID is the actual Element ID
						
						i++;
						
						if(elementList[i] == undefined)
						{
							continue;
						}
						
						j++;
						
						element = elementList[i];
						ElID = element.ID;
								
						outdata[ElID] = "<tr id='elementTableRow" + ElID + "'><td class='elementInformation'><span id='elementID--" + ElID + "'>ID " + ElID + "</span>";
						
						if (schemaID != 4)
						{
							outdata[ElID] += "<div class='deleteElement' id='deleteElement--" + ElID + "'></div>";
						}
						
						upHide = "";
						downHide = "";
						
						if(j === 1)
						{
							upHide = "style='display: none;'";
						}
						if(j === elementList.length - 1)
						{
							downHide = "style='display: none;'";
						}
						
						if(ordered)
						{
							outdata[ElID] += "<div title='Move Row Up' " + upHide + " class='uparrow' id='moveElementUp--" + ElID + "'></div><div title='Move Row Down' " + downHide + " class='downarrow' id='moveElementDown--" + ElID + "'></div>";

						}
						
						
						outdata[ElID] += "</td>";				
						
						for (var eachPiece in data.schema)
						{
							
							piece = element[data.schema[eachPiece].ID];
						
							if(piece == null)
							{
								piece = { Content : "",
										  ElID : ElID,
										  EID : "NEW" + data.schema[eachPiece].ID,
										  Type : data.schema[eachPiece].Type,
										  Flags: data.schema[eachPiece].Flags };
										  
							}
							if(piece.Flags == 1)
							{
								continue;
							}
						
							
							// Types of edit controls
							if(piece.Type == 1) // text
							{
								outdata[ElID] += "<td><textarea id='elementEditor-" + piece.EID + "--" + piece.ElID + "' cols=30 rows=4>" + piece.Content + "</textarea></td>";
							}
							else if(piece.Type == 2) // upload
							{
								outdata[ElID] += "<td class='fileUploadColumn'><span id='elementEditor-" + piece.EID + "--" + piece.ElID + "'>" + piece.Content.split('/').splice(-1)[0] + "</span><br>";
								outdata[ElID] += "<form id='elementFileUploadForm-" + piece.EID + "--" + piece.ElID + "' method='post' enctype='multipart/form-data' action='../core/ajax-upload.php'><span id='elementFileUploadWarning-" + piece.EID + "--" + piece.ElID + "'></span>";
								outdata[ElID] += "<input name='file' class='compressedFilePickerButton' id='filePicker-" + piece.EID + "--" + piece.ElID + "' size='1' type='file' />";
								outdata[ElID] += "<input type='submit' class='compressedUploadButton' name='action' id='uploadButton-" + piece.EID + "--" + piece.ElID + "' value='Upload!' />";
								outdata[ElID] += "<iframe id='upload_target-" + piece.EID + "--" + piece.ElID + "' name='upload_target-" + piece.EID + "--" + piece.ElID + "' src='' style='width: 1px; height: 1px; border: 1px solid #ccc;'></iframe></form></td>";
							}
						
						}
						
						outdata[ElID] += "</tr>";
						
						outtable += outdata[ElID];
					
					}


					outtable += "</table>";
				
					var scrollerDiv = $('<div id="innerElementEditor" class="innerElementEditor"></div>');
					scrollerDiv.append(outtable);

					$("#message").append("<div class='dialogBoxTitle'>Edit " + elementSchemaName + "</div>");
					if (schemaID != 4)
					{
						$("#message").append("<input type='button' class='editButton addElementRowButton' id='addElementRowButtonToBottom" + data.schemaID + "' value='Add Row To Bottom'>");
						$("#message").append("<input type='button' class='editButton addElementRowButton' id='addElementRowButtonToTop" + data.schemaID + "' value='Add Row To Top'>");
					}					
					$("#message").append("<input type='hidden' id='schemaID' value='" + schemaID + "'>");
					$("#message").append(scrollerDiv);
					$("#message").append("<input type='button' class='editButton dialogButton' id='cancelEditElementsButton" + data.schemaID + "' value='Cancel'>");
					$("#message").append("<input type='button' class='editButton dialogButton defaultDialogButton' id='saveEditElementsButton" + data.schemaID + "' value='Save Changes'>");

					var savedEID = new Array();	
					for (var piecex in data.data) 
					    (function(piecex) {
							piece = data.data[piecex];
							// EID is the ID of the row in _elements
							// ElID is the actual Element ID
							if(piece.Type == 2) {
								$("#elementFileUploadForm-" + piece.EID + "--" + piece.ElID).attr('target', "upload_target-" + data.data[piecex].EID + "--" + data.data[piecex].ElID);
								$("#filePicker-" + piece.EID + "--" + piece.ElID).change(function() {
									$('#elementFileUploadWarning-' + data.data[piecex].EID + "--" + data.data[piecex].ElID).html('<span class="uploadReminder" id="uploadReminder-' + data.data[piecex].EID + "--" + data.data[piecex].ElID + '">Press "Upload" before saving!</span>');
								});
								$("#upload_target-" + piece.EID + "--" + piece.ElID).load(function() {
									$('#uploadReminder-' + data.data[piecex].EID + "--" + data.data[piecex].ElID).remove();
									uploadDone(data.data[piecex].EID + "--" + data.data[piecex].ElID);
								});
							}
						})(piecex);	

						$("#message").show();

					}
			});
	});
});


// Element Editing - move row up
$(function() {
	$("body").delegate("div[id^='moveElementUp']", "click", function() {
		elid = $(this).attr('id').substring(15);
		row = $(this).closest("tr[id^='elementTableRow']");
		prevRow = row.prev();
		row.insertBefore(prevRow);
		if(row.index() === 1)
		{
			$('#moveElementUp--' + elid).hide();
		}
		else
		{
			$('#moveElementUp--' + elid).show();
		}
		if(!row.is(":last-child"))
		{
			$('#moveElementDown--' + elid).show();
		}
		
		elidPrev = prevRow.attr('id').substring(15);
		if(prevRow.is(":last-child"))
		{
			$('#moveElementDown--' + elidPrev).hide();
		}
		else
		{
			$('#moveElementDown--' + elidPrev).show();
		}
		if(prevRow.index() !== 1)
		{
			$('#moveElementUp--' + elidPrev).show();
		}
	});
});

// Element Editing - move row down
$(function() {
	$("body").delegate("div[id^='moveElementDown']", "click", function() {
		elid = $(this).attr('id').substring(17);
		row = $(this).closest("tr[id^='elementTableRow']");
		nextRow = row.next();
		row.insertAfter(nextRow);
		if(row.is(":last-child"))
		{
			$('#moveElementDown--' + elid).hide();
		}
		else
		{
			$('#moveElementDown--' + elid).show();
		}
		if(row.index() !== 1)
		{
			$('#moveElementUp--' + elid).show();
		}
		
		elidNext = nextRow.attr('id').substring(15);
		if(nextRow.index() === 1)
		{
			$('#moveElementUp--' + elidNext).hide();
		}
		else
		{
			$('#moveElementUp--' + elidNext).show();
		}
		if(!nextRow.is(":last-child"))
		{
			$('#moveElementDown--' + elidNext).show();
		}
	});
});

// Element Editing - delete row
$(function() {
	$("body").delegate("div[id^='deleteElement']", "click", function() {
		elid = $(this).attr('id').substring(15);
		row = $(this).closest("tr[id^='elementTableRow']");
		row.remove();
		
		topRow = $('#elementTable').children('tbody').eq(0).children('tr').eq(1);
		topRowELID = topRow.attr('id').substring(15);
		
		lastRow = $('#elementTable:last tr:last');
		lastRowELID = lastRow.attr('id').substring(15);
		
		$('#moveElementUp--' + topRowELID).hide();
		$('#moveElementDown--' + lastRowELID).hide();
	});
});

// Element Editing - add row to top
$(function() {
	$("body").delegate("input[id^='addElementRowButtonToTop']", "click", function() {
	
		topRow = $('#elementTable').children('tbody').eq(0).children('tr').eq(1);
		topRowELID = topRow.attr('id').substring(15);
		
		newKey = Math.floor( Math.random() * 10000000);
		
		newRow = topRow.clone();
		newRow.attr('ID', 'elementTableRowNEW' + newKey );

		newRow.find("input, textarea, div, span").each(function() {
			pieceID = $('#pieceHeader').children().eq($(this).closest('td').index()).attr('id').substring(5);
			if($(this).attr('id').search(/elementEditor/i))
			{
				$(this).val('').attr('id', function(_, id) { a = id.split('--'); b = a[0].split('-'); return b[0] + '--NEW' + newKey; });
			}
			else
			{
				$(this).val('').attr('id', function(_, id) { a = id.split('--'); b = a[0].split('-'); return b[0] + '-' + pieceID + '--NEW' + newKey; });
			}
		}).end().insertBefore(topRow);
		newRow.find("span#elementID--NEW" + newKey).html("NEW");
		
		$('#moveElementUp--' + topRowELID).show();
	});
});


// Element Editing - add row to bottom
$(function() {
	$("body").delegate("input[id^='addElementRowButtonToBottom']", "click", function() {
	
		bottomRow = $('#elementTable tr:last');
		bottomRowELID = bottomRow.attr('id').substring(15);
		
		newKey = Math.floor( Math.random() * 10000000);
		
		newRow = bottomRow.clone();
		newRow.attr('ID', 'elementTableRowNEW' + newKey );
		
		newRow.find("input, textarea, div, span").each(function() {
			pieceID = $('#pieceHeader').children().eq($(this).closest('td').index()).attr('id').substring(5);
			if($(this).attr('id').search(/elementEditor/i))
			{
				$(this).val('').attr('id', function(_, id) { a = id.split('--'); b = a[0].split('-'); return b[0] + '--NEW' + newKey; });
			}
			else
			{
				$(this).val('').attr('id', function(_, id) { a = id.split('--'); b = a[0].split('-'); return b[0] + '-' + pieceID + '--NEW' + newKey; });
			}
		}).end().appendTo('#elementTable');
		newRow.find("span#elementID--NEW" + newKey).html("NEW");

		$('#moveElementDown--' + bottomRowELID).show();
	});
});


// Cancel element editing 
$(function() {
	$("body").delegate("input[id^='cancelEditElementsButton']", "click", function() {

		$('#message').hide();
		$('#message').text('');
		
		$("input").removeAttr('disabled');
	});
});


// Save element editing
$(function() {
	$("body").delegate("input[id^='saveEditElementsButton']", "click", function() {
		pid = store.ps.pid;

//                var regEx = new RegExp ('\\n', 'gi');
//                content = $('#newItemBody' + pid).val();
//		column = 'right';

		$('#innerElementEditor').before('<span style="color: darkred; font-size: 16px; font-weight: bold"><br>&emsp;&emsp; Saving...</span>');

		$("input").attr('disabled', true);
		
		var dataToReturn = {};
		
		
		$('#elementTable').find("tr").not(":first").each(function() {
			ElID = $(this).attr('id').substring(15);
			order = $(this).index();
			$(this).append("<tr><input type='hidden' id='elementEditor-ORDER--" + ElID + "' value='" + order + "'></tr>");
		});

		var x = 0;
		$("span[id^='elementEditor'], textarea[id^='elementEditor'], input[id^='elementEditor']").each(function() {
			
			ID = $(this).attr('id').split("--");
			ElID = ID[1];
			PieceID = ID[0].split("-");
			PieceID = PieceID[1];
			
			if(dataToReturn[ElID] == undefined)
			{
				dataToReturn[ElID] = {};
			}
			
			if(ElID.length > 0)
			{			
				if($(this).is('input') || $(this).is('textarea'))
				{
					dataToReturn[ElID][PieceID] = $(this).val();
				}
				else
				{
					dataToReturn[ElID][PieceID] = $(this).text();
				}
			}
		});

		for(var i = 0; i < 0; i++)
		{
			if($('#uploadReminder' + i).length && !$('#unsavedUploadsAlert').length)
			{
				$('#message').append("<span id='unsavedUploadsAlert' class='unsavedUploadsAlert'>You have unuploaded files. Please upload them before saving.</span>").after("input[id^='saveEditElementsButton']");
				$("input[id^='saveEditElementsButton']").attr('value', 'Save Anyway');
				$("input[id^='saveEditElementsButton']").css('color', 'red');

				return;
			}
			if($('#elementEditor' + i).length > 0)
			{
				if($('#elementEditor').is('input') || $('#elementEditor').is('textarea'))
				{
					dataToReturn[i] = $('#elementEditor' + i).val();
				}
				else
				{
					dataToReturn[i] = $('#elementEditor' + i).text();
				}
			}
		}
		
		dataToReturn['schemaID'] = $('#schemaID').val();
	
		
		$.post('../core/ajax-edit.php', { action: 'saveEditedElements', content: dataToReturn, ajax: 1, store: store },
			function(data) {
				if(data == 1) {
					$("input").removeAttr('disabled');
					window.location.reload();
				}
		});
	});
});

// Upload initialization (should be moved elsewhere?)
$(function() {
	$("body").delegate("form[name='elementFileUploadForm']", "load", function() {

	});
});

function uploadDone(EID) {

	ElID = EID.split('--')[1];
	EID = EID.split('--')[0];
	

	var output = document.getElementById('upload_target-' + EID + "--" + ElID).contentDocument;

	if(JSON.parse(output.firstChild.textContent))
	{
		data = JSON.parse(output.firstChild.textContent);
		
		if(data.success) {
			console.log("Success" + data.file_name + " " + data.size);
			$('#elementEditor-' + EID + "--" + ElID).html(data.file_name);
			$('#unsavedUploadsAlert').remove();
			$("input[id^='saveEditElementsButton']").attr('value', 'Save Changes');
			$("input[id^='saveEditElementsButton']").css('color', 'black');
		}
		else if(data.failure) {
			console.log("Failure" + data.failure);
		}
	}
	else {
		console.log("FAIL!!!");
	}
}

