// Copyright (C) ZEROBASE Inc. http://zerobase.jp/
// $Id: dom2code.js,v 1.11 2006/03/27 03:28:56 hideto Exp $
// required: prototype.js http://prototype.conio.net/

var DOM2Code = Class.create();
DOM2Code.prototype = {
initialize : function (txta_in, txta_code) {
	this.txta_in = $(txta_in);
	this.txta_code = $(txta_code);
	this.div_html = document.createElement('div');
	this.onUpdate();
	Event.observe(this.txta_in, 'keyup', this.onUpdate.bindAsEventListener(this), false);
	Event.observe(this.txta_in, 'change', this.onUpdate.bindAsEventListener(this), false);
},
onUpdate : function () {
	this.div_html.innerHTML = this.txta_in.value;
	var dom_code = this.scanNodeTree(this.div_html);
	if (this.div_html.childNodes.length < 2) {
		dom_code = dom_code.replace(/var elm1 = document\.createElement\('DIV'\)\;\n/, '');
		dom_code = dom_code.replace(/elm1\.setAttribute\('id', '_html_out'\)\;\n/, '');
		dom_code = dom_code.replace(/elm1\.appendChild\(elm2\)\;\n/, '');
	}
	this.txta_code.value = dom_code;
	eval(dom_code);
},
scanNodeTree : function (elm, num) {
	var str = "";
	num = (num) ? num : 1;
	if (elm.nodeType == 1) {  // element node
		str += "var elm"+num+" = document.createElement('"+elm.nodeName+"');\n";
		if (elm.attributes) {
			for (var i = 0; i < elm.attributes.length; i++) {
				var a = elm.attributes[i];
				if (a.specified) {
					var text = this.escapeText(a.nodeValue);
					str += "elm"+num+".setAttribute('"+a.nodeName+"', '"+text+"');\n";
				}
			}
		}
	} else if (elm.nodeType == 3) {  // text node
		var text = this.escapeText(elm.nodeValue);
		str += "var elm"+num+" = document.createTextNode('"+text+"');\n";
	}
	if (elm.childNodes) {
		var cnum = num+1; // for each child
		for (var i = 0; i < elm.childNodes.length; i++) {
			str += this.scanNodeTree(elm.childNodes[i], cnum);
			str += "elm"+num+".appendChild(elm"+cnum+");\n";
			cnum++;
		}
	}
	return str;
},
escapeText : function (text) {
	text = text.replace(/'/g, '\\'+"'");
	text = text.replace(/\r/g, '\\'+'r');
	text = text.replace(/\n/g, '\\'+'n');
	return text;
}
}
