/* WIP - WYSIWYG in Place
AJAX Edit in place with a XINHA "What You See Is What You Get" Editor
by Marco Rosella - http://lab.centralscrutinizer.it/wip-wysiwyg-in-place
   v0.3 - May 22, 2007
   v0.2 - December 7, 2006
   v0.1 - October 5, 2006
   
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA				   
*/

window.onload   = function() {
	wip.init();
};

var wip =   {
	//hoverColor : '#ffff99',  //the classic edit-in-place color
	hoverColor : '#bce0d7',	
	editableClass : 'edit',
	xinha_editors : [],
	xinha_config  : null,
	bg : null,
	ff : null,
	fs : null,
	fy : null,
	fw : null,
	fv : null,
	xa : null,
	tf : null,
	ow : null,
	oh : null,
	init : function() {
		var editElements = [];
		var els = document.getElementsByTagName('*');
		var elsLen = els.length;
		var patternEdit = new RegExp("(^|\\s)" + wip.editableClass + "(\\s|$)");
		for (i = 0, j = 0; i < elsLen; i++) {
			if ( patternEdit.test(els[i].className) ) {	
				editElements[j++] = els[i]; 
			} 	
		}		
		for(var i = 0; editel = editElements[i]; i++) { 
			wip.prepare(editel);
		}
	} ,	
	prepare : function(editel) {
		editel.onmouseover = function() {
			wip.bg = getCSSProp(this, "backgroundColor"); 
			this.style.backgroundColor = wip.hoverColor;
			// if you want to use the fade effect, comment the two lines above and uncomment the two ones below:
			/*if (!this.id) { this.id = new Date().getTime();}	
			mark.changeColors(this.id, 30, 200, mark.getBgcolor(this), wip.hoverColor);  */
		}
		editel.onmouseout = function() { 
			this.style.backgroundColor = wip.bg;
			//if you don't want to use the fade effect, comment the lines above and uncomment the one below:
			/* mark.changeColors(this.id, 30, 700, wip.hoverColor, mark.getBgcolor(this));*/
		}
		editel.ondblclick = function() {wip.edit(this);}
	},
	edit : function(elem) {
		elem.onmouseover = null;
		var parid = elem.id ? elem.id : new Date().getTime();
		ow = elem.offsetWidth;
		oh = elem.offsetHeight;
		wip.ff = getCSSProp(elem, "fontFamily");
		wip.fs = getCSSProp(elem, "fontSize");
		wip.fy = getCSSProp(elem, "fontStyle");
		wip.fw = getCSSProp(elem, "fontWeight");
		wip.fv = getCSSProp(elem, "fontVariant");
		wip.xa = getCSSProp(elem, "textAlign");
		wip.tf = getCSSProp(elem, "textTransform");
		var text = elem.innerHTML;
		var z = elem.parentNode;
		var frm = document.createElement('form');
		frm.setAttribute('id',parid);
		z.insertBefore(frm,elem);
		var tarea = document.createElement('textarea');
		tarea.style.width = ow + 'px';
		tarea.style.height = oh + 'px';
		tarea.style.fontFamily = wip.ff;
		tarea.style.fontSize = wip.fs;
		tarea.style.fontStyle = wip.fy;
		tarea.style.fontWeight = wip.fw;
		tarea.style.fontVariant = wip.fv;
		tarea.style.textAlign = wip.xa;
		tarea.style.textTranform = wip.tf;
		tarea.setAttribute('id',parid);
		tarea.setAttribute('name',parid);
		frm.appendChild(tarea);
		frm.onsubmit =  function() {
			wip.send(parid, this.getElementsByTagName('textarea')[0].value);
			return false;
		}
		var inpt = document.createElement('input');
		inpt.setAttribute('type','submit');
		inpt.setAttribute('value','Save');
		frm.appendChild(inpt);
		var inpt2 = document.createElement('input');
		inpt2.setAttribute('type','button');
		inpt2.setAttribute('value','Cancel');
		inpt2.onclick =  function() {
			wip.cancel(parid, elem.innerHTML);
			return false;
		}
		frm.appendChild(inpt2);		
		z.removeChild(elem);
		tarea.value = text;
		tarea.focus();
		wip.xinha_editors.push(parid);
		this.startXINHA();
	},	
	startXINHA: function() {
		var xinha_plugins =  ['CharacterMap'];
		if(!Xinha.loadPlugins(xinha_plugins, wip.startXINHA)) return;
		cinha_config = new Xinha.Config();
		cinha_config.toolbar =
		  [
			["bold","italic","underline","strikethrough","separator","subscript","superscript"],
			["linebreak","separator","insertorderedlist","insertunorderedlist","outdent","indent"],
			["separator","inserthorizontalrule","createlink","insertimage","inserttable"],
			["separator","undo","redo","selectall"], 
			["separator","htmlmode","about"]
		  ];
		cinha_config.pageStyle = 'body {font-family:'+wip.ff+'; font-size:'+wip.fs+'; font-style:'+wip.fy+'; font-weight:'+wip.fw+'; font-variant:'+wip.fv+'; text-align:'+wip.xa+'; text-transform:'+wip.tf+';}';
		cinha_config.width  = ow + 'px';
		if(document.all) { cinha_config.height = '200px';}
		cinha_config.statusBar = false;
		wip.xinha_editors   = Xinha.makeEditors(wip.xinha_editors, cinha_config, xinha_plugins);
		Xinha.startEditors(wip.xinha_editors);
		wip.xinha_editors = [];
	}, 
	send : function(id, text) {
		if (window.XMLHttpRequest) { 
		xmlhttp = new XMLHttpRequest();
		} else if (window.ActiveXObject) { 
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.open('GET', 'send.php?id='+id+'&text='+text, true);
		var form = document.getElementById(id);
		var ta = document.getElementById(id).getElementsByTagName('textarea')[0];
		var inputsave = document.getElementById(id).getElementsByTagName('input')[0];
		var inputcancel = document.getElementById(id).getElementsByTagName('input')[1];
		inputsave.disabled = true;
		inputcancel.disabled = true;
		var mask = document.createElement('div');
		mask.style.width = ta.offsetWidth + 'px';
		mask.style.height = ta.offsetHeight + 'px';
		mask.style.backgroundColor = '#666666';
		mask.style.opacity='0.50';
		mask.style.filter="alpha(opacity='50')";
		mask.style.position = 'absolute';
		mask.style.top = '0px';
		mask.style.left = '0px';
		mask.style.display = 'block';
		mask.style.zIndex = '2';
		var loading = document.createElement('img');
		loading.setAttribute('src','loading.gif');
		loading.style.position = 'absolute';
		loading.style.top = '60px';
		loading.style.left = '230px';		
		form.style.position = 'relative';
		form.appendChild(mask);
		form.appendChild(loading);
		xmlhttp.onreadystatechange = this.handle;
		xmlhttp.send(null); 
	},
	handle : function() {
		if (xmlhttp.readyState == 4) {
		if (xmlhttp.responseText.indexOf('invalid') == -1) {
			var resp =  xmlhttp.responseText;
			var pos = resp.indexOf(':');
			var parid = resp.substring(0, pos);
			var frmold = document.getElementById(parid); 
			var y = frmold.parentNode;
			var parnew = document.createElement('div');
			parnew.setAttribute('class',wip.editableClass);
			y.insertBefore(parnew,frmold);
			parnew.innerHTML = resp.substring(pos + 1);
			wip.prepare(parnew);
			y.removeChild(frmold);
			}
		}
	},
	cancel : function(id, text) {
		var frmold = document.getElementById(id); 
		var y = frmold.parentNode;
		var parnew = document.createElement('div');
		parnew.setAttribute('class',wip.editableClass);
		y.insertBefore(parnew,frmold);
		parnew.innerHTML = text;
		wip.prepare(parnew);
		y.removeChild(frmold);
	}	
}
	
function getCSSProp (element, prop) {
  if (element.style[prop]) {
	return element.style[prop];
  } else if (element.currentStyle) {
	return element.currentStyle[prop];
  } else if (document.defaultView && document.defaultView.getComputedStyle) {
	prop = prop.replace(/([A-Z])/g,"-$1");
	prop = prop.toLowerCase();
	return document.defaultView.getComputedStyle(element,"").getPropertyValue(prop);
  } else {
	return null;
  }
}

var mark = {  //based on The Fade Anything Technique by Adam Michela 
	req : 0,
	valop : 100,
	changeColors: function(id, fps, duration, from, to) {
		var frames = Math.round(fps * (duration / 1000));
		var interval = duration / frames;
		var delay = interval;
		var frame = 0;		
		if (from.length < 7) from += from.substr(1,3);
		if (to.length < 7) to += to.substr(1,3);		
		var rf = parseInt(from.substr(1,2),16);
		var gf = parseInt(from.substr(3,2),16);
		var bf = parseInt(from.substr(5,2),16);
		var rt = parseInt(to.substr(1,2),16);
		var gt = parseInt(to.substr(3,2),16);
		var bt = parseInt(to.substr(5,2),16);		
		var r,g,b,h;
		while (frame < frames) {
			r = Math.floor(rf * ((frames-frame)/frames) + rt * (frame/frames));
			g = Math.floor(gf * ((frames-frame)/frames) + gt * (frame/frames));
			b = Math.floor(bf * ((frames-frame)/frames) + bt * (frame/frames));
			h = this.makeHex(r,g,b); 		
			setTimeout("mark.setBgColor('"+id+"','"+h+"')", delay);
			frame++;
			delay = interval * frame; 
		}
		setTimeout("mark.setBgColor('"+id+"','"+to+"')", delay);
	},  
	makeHex: function(r,g,b) {
		r = r.toString(16); if (r.length == 1) r = '0' + r;
		g = g.toString(16); if (g.length == 1) g = '0' + g;
		b = b.toString(16); if (b.length == 1) b = '0' + b;
		return "#" + r + g + b;
	},
	setBgColor: function(id, c) {   
	    if(document.getElementById(id)) {
		var o = document.getElementById(id);
		o.style.backgroundColor = c;} else return;
	},
	getBgcolor: function(id)  { 
		var o = document.getElementById(id);
		while(o) {
			var c;
			if (window.getComputedStyle) c = window.getComputedStyle(o,null).getPropertyValue("background-color");
			if (o.currentStyle) c = o.currentStyle.backgroundColor;
			if ((c != "" && c != "transparent") || o.tagName == "BODY") { break; }
			o = o.parentNode;}
		if (c == undefined || c == "" || c == "transparent") c = "#FFFFFF";
		var rgb = c.match(/rgb\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)/);
		if (rgb) c = this.make_hex(parseInt(rgb[1]),parseInt(rgb[2]),parseInt(rgb[3]));
		return c;
	}
}