
var editingRegion = false;

function editRegion(regionid){
	if(editingRegion==true){
		alert('You are currently editing a different region, please save or cancel this before editing another.');
		return;
	}
	editingRegion = true;
	createForm(regionid);
}

function createForm(regionid){
	var editRegion = $('editable_' + regionid);
	var element = Builder.node('form', { id: 'editableRegionForm', onsubmit: 'return false;' }, [
	  Builder.node('label',  'Title'), 
	  Builder.node('input',{ id: 'editTitle', type: 'text', name : 'editTitle'}),
	  Builder.node('label',  'Content'), 
	  Builder.node('textarea',{ id: 'editContentArea', name : 'editContentArea' }),
	  Builder.node('input',{ id: 'saveContent', type: 'submit', value: 'Save' , onclick: 'saveForm(' + regionid +'); return false;'}),  
	  Builder.node('input',{ id: 'cancelContent', type: 'button', value: 'Cancel', onclick: 'cancelForm(' + regionid +')'}),
	]);
	editRegion.insert({ after: element });
	editRegion.hide();
	// AJAX Request for the content for this region, return html formatted region with no masks replaced, populate the 2 areas
	if(regionid!=0){
		new Ajax.Request('/incs/ajax/editor.php?contentRequest=' + regionid, {
				method: 'post',
				onComplete: populateForm
		});
	} else {
		// this is a new paragraph, no content to fetch
		setup();
	}
}

function populateForm(request){
	var paragraph =  request.responseText.evalJSON();
	$('editTitle').value = paragraph['title'];
	$('editContentArea').value = paragraph['content'];
	setup();
}

function saveForm(regionid){
	// AJAX send off the form
	var y =  tinyMCE.get('editContentArea').getContent();

	new Ajax.Request('/incs/ajax/editor.php?contentUpdate=' + regionid, {
	  method: 'post',
	  parameters: {newTitle: $('editTitle').value, newContent: y},
	  onComplete: updateRegion
	 });
	 return false;
}

function objectExists(Id)
{
  var o = document.getElementById(Id);
  if (o)
  {
		return true;
  }
  return false;
}

function updateRegion(request){
	var paragraph =  request.responseText.evalJSON();
	var editRegion = '';
	var newContent = '';
	var titleCode = '';
	var controls = '<p class="editorControls" id="controls_' + paragraph['paragraphid'] + '"><a href="#" class="edit" onClick="editRegion(' + paragraph['paragraphid'] + '); return false;">Edit</a></p>';
	var sortHandle = '<p class="handleContainer"><a class="sortHandle" onClick="return false;" href="#">#</a></p>';
	if(objectExists('item_' + paragraph['paragraphid'])){
		editRegion = $('editable_' + paragraph['paragraphid']);
		editRegion.innerHTML = '';
	} else {
		// this is a new paragraph being added to the page
		var element = Builder.node('li', { id: 'item_' + paragraph['paragraphid'] }, Builder.node('div', { id: 'editable_' + paragraph['paragraphid'], className: 'editableRegion'}));
		var  lastParagraph  = '';
		if(objectExists('item_' + paragraph['lastID'])){
			lastParagraph = $('item_' + paragraph['lastID']);
		} else {
			lastParagraph = $('editable_0');
		}
		lastParagraph.insert({ after: element });
		editRegion = $('editable_' + paragraph['paragraphid']);
	}
	// On complete update the innerHTML of editRegion
	$('editableRegionForm').remove();
	

	if(paragraph['title']!=''){
		titleCode = '<h2>' + paragraph['title'] + '</h2>';
	}
	// sortHandle has been removed for now, append to front of this following string
	newContent = controls + titleCode + paragraph['content'];
	
	editRegion.innerHTML = newContent;
	editRegion.show();
	Sortable.create("content_container", {
						  handles:$$("#content_container a.sortHandle"),
						  onUpdate: function() {
							  new Ajax.Request("/incs/ajax/editor.php", {
								  method: "post",
								  parameters: { data: Sortable.serialize("content_container") }
							  });
						  }
					  });	
	editingRegion = false;
}

function deleteRegion(regionid){
	var answer = confirm("Are you sure you want to remove this paragraph? This cannot be undone once you confirm.")
	if (answer){
		// AJAX request to remove the paragraph, then remove the para from the page
		new Ajax.Request('/incs/ajax/editor.php?contentRemoval=' + regionid, {
		  method: 'post',
		  onComplete: removeRegion
		});
	}else{
		// user cancelled, do nothing
	}
}

function removeRegion(req){
		var paragraph =  req.responseText;
		if(paragraph==0){
			alert("Something went wrong whilst attempting to remove this paragraph. Please contact support");
		} else {
			if(objectExists('item_' + paragraph)){
				$('item_' + paragraph).remove();
			} else {		
				$('editable_' + paragraph).remove();
			}
		}
}

function cancelForm(regionid){
	var editRegion = $('editable_' + regionid);
	$('editableRegionForm').remove();
	editRegion.show();
	editingRegion = false;
}

function setup() {
   tinyMCE.init({
      mode : "exact",
	  elements : "editContentArea",
      theme : "dfc",
	  width: "482",
	  plugins: "dfclink",
	  theme_advanced_disable : "strikethrough,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,outdent,indent,image,anchor,cleanup,help,code,hr,visualaid,sub,sup,charmap,seperator,removeformat",
	  forced_root_block : false,
	  force_br_newlines : true,
	  force_p_newlines : false
   });
}
