//-----------------------------------------------------------------------------
// XET Toolkit 
// Copyright (c) 2006-2007 Xavier Amado (xavier@theadfirm.com || xamado@gmail.com)
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// Dynamic Forms v 1.0
// A dynamic form is composed by span and img tags marked as editable via the 
// name="editable" property. Such elements will be sent back to the callbackURL
// specified by the javascript save clicked action.
//-----------------------------------------------------------------------------

// Change List
// 26/01/07: Fixed bug with ampersand character in the postString
// 27/01/07: Fixed bug that eliminated <br>'s when editing. Do not use string.replace when using rich text editor

var gEditing = false;
var gEditingField = false;

function xet_dynamic_form_on_edit_clicked(actions, dynamicForm, saveCallbackURL, onSavedCallback)
{
	if(gEditing)
		return;
	else gEditing = true;
	
	// Let's just hide the action links
	actions.style.display = "none";
	
	// Add dotted line around the div
	dynamicForm.style.borderStyle = "dashed";
	dynamicForm.style.borderColor = "blue";
	dynamicForm.style.borderWidth = "2px";
	
	// Enable editing mode
	xet_dynamic_form_enable_edit_mode(dynamicForm, actions, saveCallbackURL);
	
	// Create the save button and add it to the action bar
	var saveButton = document.createElement("input");
	saveButton.setAttribute("type", "button");
	saveButton.setAttribute("value", "Save");
	saveButton.setAttribute("class", "savebtn");
	saveButton.setAttribute("className", "savebtn");
	saveButton.onclick = function() { xet_dynamic_form_on_save_clicked(this, dynamicForm, actions, saveCallbackURL, onSavedCallback); };
	dynamicForm.appendChild(saveButton);
}

function xet_dynamic_form_enable_edit_mode(dynamicForm, actions, saveCallbackURL)
{
	// Let's disable all hyperlinks
	var links = dynamicForm.getElementsByTagName("a");
	for(var i = 0; i < links.length; i++)
	{
		var link = links[i];
		if(link.getAttribute("name") == "editable")
		{	
			var div = document.createElement("div");
			
			while(link.childNodes.length)
			{
				var child = link.childNodes[0];
				div.appendChild(child);				
			}
			
			link.parentNode.insertBefore(div, link);			
		}
	}
	
	// Let's add link around all editable images
	var imgs = dynamicForm.getElementsByTagName("img");
	for(var i = 0; i < imgs.length; i++)
	{
		if(imgs[i].getAttribute("name") == "editable")
		{
			img = imgs[i];
			
			// Create the thumbnail with it's link
			var link = document.createElement("a");
			
			link.onclick = function () { xet_dynamic_form_on_image_clicked(img, img.getAttribute("uploaderurl")); };
					
			// Insert the link before the image and append the image to the link
			img.parentNode.insertBefore(link, img);
			link.appendChild(img);					
		}
	}
	
	// Let's enable the editing callbacks for our editable items
	// All spans that have a name of "editable" are treated as such
	var spans = dynamicForm.getElementsByTagName("span");
	for(var i = 0; i < spans.length; i++)
	{
		var span = spans[i];
		if(span.getAttribute("name") == "editable")
		{		
			span.onmouseover = function() { this.setAttribute("class", "editable"); };
			span.onmouseout = function() { this.setAttribute("class", ""); };
			span.onmousedown = function() { xet_dynamic_form_on_text_clicked(this); };
			
			if(span.innerHTML == "" || span.innerHTML == "<br>")
				span.innerHTML = "Click here to edit";
		}
	}
}

function xet_dynamic_form_disable_edit_mode(dynamicForm, actions, saveCallbackURL)
{
	// Let's remove the links around images
	var imgs = dynamicForm.getElementsByTagName("img");
	for(var i = 0; i < imgs.length; i++)
	{
		var img = imgs[i];
		if(img.getAttribute("name") == "editable")
		{
			// Grab the parent, it should be our link
			var link = img.parentNode;
			if(link.tagName != "a" && link.tagName != "A")
				continue;
			
			// Insert the image in the link's parent before the link and delete the link
			link.parentNode.insertBefore(img, link);
			link.parentNode.removeChild(link);
		}
	}
	
	// Let's re-enable all hyperlinks
	var links = dynamicForm.getElementsByTagName("a");
	for(var i = 0; i < links.length; i++)
	{
		var link = links[i];
		if(link.getAttribute("name") == "editable")
		{
			var div = link.previousSibling;
			
			while(div.childNodes.length)
			{
				var child = div.childNodes[0];
				link.appendChild(child);				
			}
			
			link.parentNode.removeChild(div);
		}
	}
	
	// Disable all the callbacks 
	var spans = dynamicForm.getElementsByTagName("span");
	
	for(var i = 0; i < spans.length; i++)
	{
		var span = spans[i];
		if(span.getAttribute("name") == "editable")
		{		
			span.onmouseover = 0;
			span.onmouseout = 0;
			span.onmousedown = 0;
		}
	}
}

function xet_dynamic_form_on_save_clicked(button, dynamicForm, actions, saveCallbackURL, onSavedCallback)
{
	if(gEditingField)
		return;

	if(gEditing)
		gEditing = false;
	else return;

	// Grab all the values in the dynamic form (spans with editable name)
	var postString = "";
	var spans = dynamicForm.getElementsByTagName("span");
	for(var i = 0; i < spans.length; i++)
	{
		var span = spans[i];
		if(span.getAttribute("name") == "editable")
		{		
			var id = span.getAttribute("id");
			var value = span.innerHTML;
			
			// Append the appropiate concatenation char
			if(postString != "")
				postString += "&";
			
			// Append the id/value key
			postString += id + "=" + encodeURIComponent(value);
		}
	}
	
	// Now grab all values from the images, like thumbnails 
	var imgs = dynamicForm.getElementsByTagName("img");
	for(var i = 0; i < imgs.length; i++)
	{
		var img = imgs[i];
		if(img.getAttribute("name") == "editable")
		{		
			var id = img.getAttribute("id");
			var value = img.getAttribute("src");
			
			// Append the appropiate concatenation char
			if(postString != "")
				postString += "&";
			
			// Append the id/value key
			postString += id + "=" + value;
		}
	}
	
	// Create the request object and set the recv callback
	var req;
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
	}
	else if (window.ActiveXObject) {
		req = new ActiveXObject("Microsoft.XMLHTTP");
	}
	req.onreadystatechange = function() { if(onSavedCallback) onSavedCallback(req); };
	
	// Form a correct link and send the get request
	var callbackURL = configBaseURL + saveCallbackURL;
	req.open("POST", callbackURL, true);
	req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	req.send(postString);
	
	// Change the border style of the div
	dynamicForm.style.borderStyle = "none";
	
	// Disable editing mode
	xet_dynamic_form_disable_edit_mode(dynamicForm, actions, saveCallbackURL);
	
	// Remove the button
	dynamicForm.removeChild(button);
	
	// And show the actions
	if(actions)
		actions.style.display = "block";
}

function xet_dynamic_form_on_text_clicked(editElem)
{
	// Grab the parent of the element to be edited. 
	var parent = editElem.parentNode;
	
	//	Grab some values provided by the element to be edited
	var textType = editElem.getAttribute("type");
	var textName = editElem.getAttribute("name");
	var nextElem = editElem.nextSibling;
	
	var textValue = editElem.innerHTML; // Not using nodeValue here since it screws up with new lines
	if(textType != "richtext")
		textValue = textValue.replace(/<br>/gi, "");
	
	// Now hide the element to be edited 
	editElem.style.display = "none";
	
	// Now replace it with a text form and a button
	var formElem = document.createElement("DIV");
	formElem.setAttribute("name", "currentForm");
	parent.insertBefore(formElem, nextElem);
	
	if(textType == "string")
	{
		var textElem = document.createElement("input");
		textElem.type = 'text';
		
		// Need a class name to differentiate this from other input fields for styling
		textElem.setAttribute("className", "text");
		textElem.setAttribute("class", "text");
		
		textElem.setAttribute("value", textValue);
		textElem.setAttribute("name", textName);
		formElem.appendChild(textElem);
	}
	else if(textType == "text" || textType == "richtext")
	{
		if(navigator.appVersion.indexOf("MSIE") != -1)
		{
			var textElem = document.createElement("<textarea type='text'>");
		}
		else {
			var textElem = document.createElement("textarea");
			textElem.setAttribute("type", "text");
		}

		textElem.setAttribute("name", textName);
		
		var textNode = document.createTextNode(textValue);
		textElem.appendChild(textNode);
		
		formElem.appendChild(textElem);
		
		// If using the XETRichTextEditor then replace the textarea now.
		if(textType == "richtext")
		{
			var uploaderURL = editElem.getAttribute("uploaderurl");
			xet_richtexteditor_init_textarea(textElem, uploaderURL);
		}
	}
	
	var buttonElem = document.createElement("INPUT");
	buttonElem.setAttribute("type", "button");
	buttonElem.setAttribute("class", "button");
	buttonElem.setAttribute("className", "button");
	buttonElem.setAttribute("value", "Ok");
	
	if(textType == "richtext")
		buttonElem.onclick = function() { 
			xet_richtexteditor_save_forms();
			xet_richtexteditor_remove();
			xet_dynamic_form_on_text_ok_clicked(formElem, editElem); 
		};
	else
		buttonElem.onclick = function() { xet_dynamic_form_on_text_ok_clicked(formElem, editElem); };
	formElem.appendChild(buttonElem);
	
	// Store some globals
	gEditingField = true;
}

function xet_dynamic_form_on_text_ok_clicked(formElem, originalElem)
{
	// Grab the new value from the form
	var fieldValue = formElem.childNodes[0].value;
	var fieldName = formElem.childNodes[0].getAttribute("name");

	// Remove the form 
	var parent = formElem.parentNode;
	parent.removeChild(formElem);
		
	// Finally update the content of the edited element and re-show it
	originalElem.innerHTML = fieldValue;
	originalElem.style.display = "block";
	
	gEditingField = false;
}

function xet_dynamic_form_on_image_clicked(img, uploaderURL)
{
	var callback = function(url) 
	{
		img.setAttribute("src", url);
	};
	
	xet_file_uploader_show(callback, uploaderURL); 
}

//-----------------------------------------------------------------------------
// This is crufty code I can't decide if this should be part of a xetDynamicForm
// or not...
//-----------------------------------------------------------------------------

function xet_dynamic_form_on_delete_clicked(link, dynamicForm, callbackURL, styleId)
{
	// Need you daddyyyyyy againnnnnnnnn
	var parent = dynamicForm.parentNode;
	
	// Let's just hide the link
	link.style.display = "none";
	
	// Add dotted line around the div
	dynamicForm.style.borderStyle = "dashed";
	dynamicForm.style.borderColor = "blue";
	dynamicForm.style.borderWidth = "2px";
	
	// Let's insert a small bar on the bottom to ask for confirmation
	var smallBar = document.createElement("div");
	smallBar.setAttribute("class", "confirmationBar");
	smallBar.setAttribute("className", "confirmationBar");
	smallBar.innerHTML = "Are you sure?";
	
	var yesLink = document.createElement("a");
	yesLink.setAttribute("href", "javascript:void(0);");
	yesLink.onmousedown = function() { style_on_delete_confirm_clicked(dynamicForm, callbackURL, styleId); };
	yesLink.innerHTML = "Yes";
	yesLink.style.marginleft = "10px";
	smallBar.appendChild(yesLink);
	
	var noLink = document.createElement("a");
	noLink.setAttribute("href", "javascript:void(0);");
	noLink.onmousedown = function() { style_on_delete_cancel_clicked(link, dynamicForm, smallBar); };
	noLink.innerHTML = "No";
	noLink.style.marginleft = "10px";
	smallBar.appendChild(noLink);
	
	dynamicForm.appendChild(smallBar);
}

function style_on_delete_confirm_clicked(dynamicForm, callbackURL, styleId)
{
	// Delete the whole div
	var parent = dynamicForm.parentNode;
	parent.removeChild(dynamicForm);
	
	// Create the request object and set the recv callback
	var req;
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
	}
	else if (window.ActiveXObject) {
		req = new ActiveXObject("Microsoft.XMLHTTP");
	}
	req.onreadystatechange = function() { if(req.responseText != "") parent.innerHTML = req.responseText; };

	// Form a correct link and send the get request
	var callbackURL = configBaseURL + callbackURL;
	var postData = "delete=" + styleId;
	req.open("POST", callbackURL, true);
	req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	req.send(postData);
}

function style_on_delete_cancel_clicked(link, dynamicForm, smallBar)
{
	// Show the link again
	link.style.display = "block";
	
	// Remove dotted line around the div
	dynamicForm.style.borderStyle = "none";
	
	// And delete the smallBar
	dynamicForm.removeChild(smallBar);
}

