/* -*- C++ -*- */

/* --------------------------------------------------------------------
 * Shine: The Become Interactive Client Application Framework
 * @(#) $Id$
 * --------------------------------------------------------------------
 * Copyright (c) 2006 Become Interactive
 * http://www.becomeinteractive.co.uk
 * All rights reserved.
 * --------------------------------------------------------------------
 * This software is the confidential and proprietary information of
 * Become Interactive ("Confidential Information").
 *
 * You shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement you
 * with the terms of the license agreement you entered into with
 * Become Interactive.
 * --------------------------------------------------------------------
 */

if(typeof com == "undefined") var com = new Object();
if(typeof com.uk == "undefined") com.uk = new Object();
if(typeof com.uk.become == "undefined") com.uk.become = new Object();
if(typeof com.uk.become.content == "undefined") com.uk.become.content = new Object();

com.uk.become.content.Core = function()
{
	var _this = this;
	
	this.editors = new Array();	
	this._editorInitIndex = 0;
	this.enableTinyMCE = false;
	this._tinyMCELoaded = false;
	this._tinyMCELoading = false;
	this._tinyMCESettings = {
		theme : "advanced",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left"
	};
	window.setInterval(function() { _this._onInterval(); }, 100); 					   
}
com.uk.become.content.Core.prototype._onContentSaved = function(Shine, req, ev)
{
	var c, n;
	
	n = ev.responseXML.documentElement;
	/* Content saved successfully */
	for(c = 0; c < n.childNodes.length; c++)
		{
			pn = n.childNodes.item(c);
			if(pn.tagName.toLowerCase() == 'div')
				{
					req.shineContentBlock.innerHTML = pn.innerHTML;
					Shine.setElementClass(req.shineContentBlock.parentNode, '', false);
					/* XXX: Destroy form */
					return true;
				}
		}
	window.location.reload();
}
com.uk.become.content.Core.prototype._onContentSaveError = function(Shine, req, ev)
{
	var src;

	Shine.debug('Failed to save content ' + ev.statusCode + ' (' + ev.statusText + ')');
	src = req.shineContentBlock;
	Shine.setElementClass(req.shineContentBlock.parentNode, 'shine-edit-inprogress', false);
	src.parentNode.parentNode.insertBefore(req.shineContentForm, src.parentNode);
}
com.uk.become.content.Core.prototype._onContentSave = function(Shine, sender, ev)
{
	var id, src, ta, req;
	
	id = sender.form.shineContentId;
	src = sender.form.shineContentBlock;
	ta = sender.form.shineContentEditor;
	Shine.debug('Saving content #' + id);
	sender.form.parentNode.removeChild(sender.form);
	Shine.setElementClass(src.parentNode, 'shine-edit-waiting', false);
	req = Shine.createRequest('POST', Shine.rootPath + 'com.uk.become.content.component/put');
	req.shineContentBlock = src;
	req.shineContentForm = sender.form;
	req.shineContentId = id;
	Shine.addEventHandler(req, 'load', { host: this, handler: this._onContentSaved });
	Shine.addEventHandler(req, 'error', { host: this, handler: this._onContentSaveError });
	req.formVars['save'] = 1;
	req.formVars['content_body'] = ta.value;
	req.formVars['content_id'] = id;
	req.open();	
}
com.uk.become.content.Core.prototype._onContentLoaded = function(Shine, req, ev)
{
	var editorform, editorset, src, n, pn, body, editorta, editortext;
	var buttonset, save, cancel, preview;
	
	/* Find the <content> block in the response */
	n = ev.responseXML.documentElement;
	pn = false;
	body = '';
	for(c = 0; c < n.childNodes.length; c++)
		{
			pn = n.childNodes.item(c);
			if(!body && pn.tagName.toLowerCase() == 'content')
				{
					if(!pn.childNodes.length)
						{
							continue;
						}
					body = pn.childNodes.item(0).data;
					break;
				}
		}
	Shine.debug('Editing content #' + req.shineContentId);
	src = req.shineContentBlock;
	Shine.setElementClass(src.parentNode, 'shine-edit-inprogress', false);
	editorform = document.createElement('form');
	editorform.shineContentId = req.shineContentId;
	editorform.shineContentBlock = src;
	Shine.setElementClass(editorform, 'shine-contentedit-form', true);
	editorset = document.createElement('fieldset');
	Shine.setElementClass(editorset, 'shine-edit-content', true);
	editorform.appendChild(editorset);	
	src.parentNode.parentNode.insertBefore(editorform, src.parentNode);
	editorta = document.createElement('textarea');
	Shine.setAttribute(editorta, 'id', 'content_body_' + req.shineContentId);
	editorform.shineContentEditor = editorta;
	editortext = document.createTextNode(body);
	editorta.appendChild(editortext);
	editorset.appendChild(editorta);
	buttonset = document.createElement('fieldset');
	Shine.setElementClass(buttonset, 'shine-edit-buttons', true);
	save = document.createElement('a');
	save.form = editorform;
/*	if(com.uk.become.Browser.isDOM)
		{
			save.setAttribute('href', 'javascript:void(0);');
		}
	else
		{
			save.href = 'javascript:void(0);';
		} */
	save.appendChild(document.createTextNode('Save changes'));
/*	Shine.addEventHandler(save, 'click', this, this._onContentSave); */
	Shine.addLinkHandler(save, { host: this, handler: this._onContentSave });
	buttonset.appendChild(save);
	editorform.appendChild(buttonset);
	this.editors[this.editors.length] = 
		{ 
			id: req.shineContentId,
			block: src,
			form: editorform,
			ta: editorta,
			active: true,
			wysiwyg: false
		};
}
com.uk.become.content.Core.prototype._onInterval = function()
{
	if(typeof tinyMCE == 'undefined')
		{
			return true;
		}
	if(!this._tinyMCELoading && tinyMCE && !tinyMCE.isLoaded)
		{
			Shine.debug('Content:', 'Initialising TinyMCE');
			tinyMCE.srcMode = '_src';
			tinyMCE.gzipMode = 0;			
			tinyMCE.baseURL = Shine.basePath + 'ext/tinymce/jscripts/tiny_mce';			
			tinyMCE.init(this._tinyMCESettings);
			tinyMCE.onLoad();
			this._tinyMCELoading = true;
			return true;
		}
	if(this._tinyMCELoading && tinyMCE.isLoaded && !this._tinyMCELoaded)
		{
			Shine.debug('Content:', 'TinyMCE load complete');
			this._tinyMCELoading = false;
			this._tinyMCELoaded = true;
		}
	if(!this._tinyMCELoaded)
		{
			return false;
		}
	for(; this._editorInitIndex < this.editors.length; this._editorInitIndex++)
		{
			Shine.debug('Content:', 'Enabling editor for content #' + this.editors[this._editorInitIndex].id);
			tinyMCE.addMCEControl(this.editors[this._editorInitIndex].ta, 'content_body_' + this.editors[this._editorInitIndex].id);
		}
	return true;
}
com.uk.become.content.Core.prototype._onContentError = function(Shine, req)
{
	Shine.setElementClass(req.shineContentBlock.parentNode, '', false);
}
com.uk.become.content.Core.prototype.editContentLinkHandler = function(Shine, sender, ev)
{
	var id, src, req;

	if (ev.shiftKey || ev.altKey || ev.ctrlKey || ev.metaKey)
		{
			return true;
		}
	Shine.debug('Content:', 'Preparing for in-place edit');
	if(!sender.shineLinkRef.match(/content_id=[0-9]+/))
		{
			Shine.debug('Content:', 'Failed to retrieve content ID from edit link', sender.shineLinkRef);
			return true;
		}
	id = sender.shineLinkRef.replace(/.*content_id=([0-9]+).*$/, "$1");
	src = document.getElementById('content--' + id);
	if(!src)
		{
			return true;
		}
	src.shineContentId = id;
	src.shineContentLink = sender;
	Shine.setElementClass(src.parentNode, 'shine-edit-waiting', false);
	req = Shine.createRequest('GET', Shine.rootPath + 'com.uk.become.content.component/get?content_id=' + id);
	req.shineContentBlock = src;
	req.shineContentLink = sender;
	req.shineContentId = id
	Shine.addEventHandler(req, 'load', { host: this, handler: this._onContentLoaded });
	Shine.addEventHandler(req, 'error', { host: this, handler: this._onContentError });
	req.open();
	return false;
}
com.uk.become.content.Core.prototype.ondocumentloaded = function(Shine, sender, ev, data)
{
	nodes = Shine.getElementsByClass(document, 'a', 'shine-contentedit-link');
	Shine.addLinkHandlers(nodes, { host: this, handler: this.editContentLinkHandler });
	if(this.enableTinyMCE)
		{
			Shine.require('ext/tinymce/jscripts/tiny_mce/tiny_mce_src.js', 1);
		}
}
Shine.addLoadHandler(new com.uk.become.content.Core());
