function jsChoixImage(evt)
{
	$.getJSON('listFiles.php',
		{
			'dir': '.',
			'types': '["gif","jpg","png"]'
		},
		function(data) {
			jsDisplayFiles(data, evt.data);
		}
	);
	return false;
}
function jsDisplayFiles(data, div)
{
	$.each(data, function (i,item) {
		if(typeof item == "string") {
			$('#console').append(item).append('<br />');
		} else {
			jsDisplayFiles(item);
		}
	});
}
function jsLog(msg,type)
{
	$('#console').append(msg+'<br/>');
}
	function jsNewDocument()
	{
		jsLoad(null);
	}
	function jsReady()
	{
		$('#waitDiv').fadeTo(1000,0,function() {
			$(this).remove();
		});
	}
	function jsWait()
	{
		var waitDiv = document.createElement('div');
		$(waitDiv).attr({id:'waitDiv'});
		$(waitDiv).css({backgroundColor:'white',zIndex:-1,width:'100%',position:'fixed',height:'100%' });
		$(document.body).append(waitDiv);
		$(waitDiv).fadeTo(1,0.8,function() {$(this).css({zIndex:100})});
	}
		
	function jsLoad(file)
	{
		jsWait();
		//$('#source').remove();

		if(win) $(win.document).empty();
 
		win = window.open('/nedit/html/'+file,'html');
		//win = window.open('http://www.debian.org','html');
		win.opener = window;
		window.win = win;
		//setTimeout("jsLoadDom(win)",10);
		$.get('/nedit/html/'+file,function() {
			jsLoadDom(window);
			$.ajaxSetup({async: true});
			jsLoadCss();
		});
		return false;
	}
	var n = 0;
	var reason = 10;
	function jsLoadDom(my)
	{
		try {
		//alert('trying '+n+' '+reason);
		$.ajaxSetup({async: false});
		var doc;
		var body;
		if (! my.win) {
			jsLog("fenetre vide");
			$.ajaxSetup({async: true});
			return;
		}

		doc = my.win.document;

		//if($(doc.body).children().size() <= 1) {
		if(! doc || doc.childNodes.length < 1) {
			if(! doc) reason = 9;
			else if(! doc.childNodes) reason = 8;
			else reason = doc.childNodes.length;
			n++;
			jsLog("pas encore de données ("+n+") ... rechargement");
			$.ajaxSetup({async: true});
			setTimeout(function() { jsLoadDom(my);},10);
			return;
		}
		var div = $('#source');
		div.empty();
		//alert('empty');

		var ul = document.createElement("ul");
		ul.setAttribute('class','ul');
		div.append(ul);
		elements = {};
		id = 0;
		jsDisplayNode(ul,doc,0);

		jsReady();

		$('.drop').droppable({
			hoverClass: 'overDroppable',
			drop: function(event,ui) {
				//$(this).css({backgroundColor: 'white'});
				try {
					jsDrop(event,ui,this,my.win);
				} catch (ex) {
					jsLog("ex (jsDrop) : "+ex.message);
				}
			},
			accept: '.objet,.newObjet,.outil'
		});
		//~ //$('.objet').draggable({revert: true});
		//jsLoadCss();
		//alert(n+' '+$(doc.body).children().size());

//alert('testing myTest');
//if(window.myTest) alert('ici0');
//if(window.win.myTest) alert('ici1 '+window.win.myTest);
//if(window.win.document.myTest) alert('ici2');
		//window.win.myTest();
		} catch (ex) {
			jsLog('ex (jsDom) : '+ex.message);
		} finally {
			$.ajaxSetup({async: true});
		}
		//alert('fin');
	}
	function jsDisplayNode(parent,obj,level)
	{
		var li = document.createElement("li");
		id++;
		var myId = "id"+id;

		var a = null;
		var b = null;
		var liClassName = null;

		if (obj.nodeName == '#text' || obj.nodeName == '#comment') {
			liClassName = 'nodrop'; 
			a = document.createElement("a"); 
			$(a).addClass('objet');
			var subtext = obj.data.substr(0,20);
			if(subtext.length >= 20) subtext += " ...";
			$(a).text(obj.nodeName+' ('+subtext+')');
			var ntext = obj.data.replace(/\n[ ]+/g,'<br/>&nbsp;&nbsp;&nbsp; ');
			var ntext = ntext.replace(/\n/g,'<br/>');
			//$(a).append('<span>'+ntext+'</span>');
			$(a).mouseover(function() {
				$('#infoBulle').html(ntext);
			});
			$(a).mouseout(function() {
				//$('#infoBulle').html('');
			});
		} else {
			liClassName = 'drop'; 
			a = document.createElement("a");
			$(a).attr({
				id: 'a'+myId
			});
			$(a).addClass('objet');
			$(a).text(obj.nodeName);
			$(a).mouseover(function() {
				$('#infoBulle').empty();
				var text = '<p>'+obj.nodeName+'</p>';
				text += '<dl>';
				for(var i = 0;i < obj.attributes.length;i++) {

					var attr = obj.attributes[i];
					text += '<dt>'+attr.nodeName+'</dt><dd>'+attr.nodeValue+'</dd>';
				}
				text += '</dl>';
				$('#infoBulle').append(text);
			});
			$(a).mouseout(function() {
				//$('#infoBulle').html('');
			});
		}
		$(a).draggable({revert: true, zIndex: 3002});
/*
		$(a).mouseover(function() {
			var position = {top: 100,left: 100};//$(obj).offset();
			var width = 100;//$(obj).width();
			var height = 200;//$(obj).height();
			var div = window.win.document.createElement('div');
			$(div).css({
				position: 'absolute',
				top: position.top+'px', 
				left:position.left+'px',
				width:width+'px',
				height:height+'px',
				border: '2px darkgreen dashed'
			});
			jsLog(div);
			window.win.document.appendChild(div);
		});
*/
		$(li).append(a);
		b = document.createElement("span");
		$(b).append('[Edit]');
		var nId = "d"+id;
		$(b).attr({id: nId});
		$(b).bind('click',jsNodeEdit);
		$(li).append(b);

		$(li).attr({
			id: myId, 
			name: obj.nodeName
		});
		$(li).addClass( liClassName);

		parent.appendChild(li);

		/*	if (obj.nodeName != '#text') { */
			elements[myId] = obj; 
			/////////jsSetDrop(myId);
		/*	} */

		///////// 	new Draggable(myId,{revert:true,	ghosting: true});
		if (! obj.childNodes.length) {
			return;
		}
		var ul = document.createElement('ul');
		$(ul).attr({
			className: 'ul'
		});
		/*var ulId = 'ul'+myId;*/
		/*ul.setAttribute('id',ulId);*/

		parent.appendChild(ul); 
    /*
    $.each($(obj).contents(),function(index,child) {
      jsDisplayNode(ul,child,level+1);
    });
		*/
		for(var child = obj.firstChild;child;child = child.nextSibling) {
			jsDisplayNode (ul,child,level+1);
		}
	}
var win = null;
var separateur = null;
function jsSetCss(prop,val)
{
	var str = "document.object.style.setProperty('"+prop+"','"+val+"','')";
	eval(str);
	jsEndInit();
}
function jsSetValue(val)
{
	//alert(val);
	document.object.nodeValue = val;
}
function jsSetAttribute(prop,val)
{	if(val) {
		$(document.object).attr(prop,val);
	} else {
		$(document.object).removeAttr(prop);
	}
}

function jsSetStyle(prop,val)
{
	if(prop == 'class') {
		$(document.object).attr(prop,val);
	} else {
		$(document.object).css(prop,val);
	}
}
function jsCssEdit(event,obj)
{
	document.object = obj;
	w = window.open("css.php","cssEdit","width=640,height=480");
	if (! w) return;
	w.opener = self;
}
function jsHREdit(obj)
{
	document.object = obj;
	w = window.open("styleSpan.php?","HR style","width=640,height=480");
	return w;
}
function jsSpanEdit(obj)
{
	document.object = obj;
	w = window.open("styleSpan.php?","style","width=640,height=480");
	return w;
}
function jsDivEdit(obj)
{
	document.object = obj;
	w = window.open("div.php?","style","width=640,height=480");
	return w;
}
function jsGetObj()
{
	return document.object;
}
function jsTextEdit(obj)
{
	var txt = prompt("texte de l'element",obj.nodeValue);
	obj.nodeValue = txt;
}
function toStr(obj)
{
	var elt = {name: obj.nodeName, attributes: [], children: [],data: ''};
	if(obj.attributes && obj.attributes.length) {
		//alert(obj.nodeName+' '+obj.attributes.length);
		for(var index = 0;index < obj.attributes.length;index++) {
			var attr = obj.attributes[index];
			elt.attributes.push({name:attr.nodeName,value:attr.nodeValue});
		}
	}
	/*
	if(obj.attributes) {
		$.each(obj.attributes,function(i,attr) {
			elt.attributes.push({name:attr.nodeName,value:attr.nodeValue});
		});
	}
	*/
	for(var child = obj.firstChild;child;child = child.nextSibling) {
		elt.children.push(toStr(child));
	}
	elt.data = obj.nodeValue;
	return elt;
}
function jsSave(file)
{
	var cssSheets = jsSaveCss();
	/*var str = encodeURIComponent(toStr(win.document));*/
	$.post('save.php', { 
		/*content:str,*/
		filename:'/nedit/html/'+file,
		css: $.toJSON(cssSheets),
		dom: $.toJSON(toStr(win.document))
	}, function() {
		alert('sauvegarde effectuée');
		jsLog('sauvegarde effectuée');
	});
	return false;
}

var id = 0;
var elements = {};
function table(params)
{
	var ctable = new CTable(params);
	return ctable.getObj();
}
function img(params)
{
	var cimg = new CImage(params);
	return cimg.getObj();
}
function a(params)
{
	var ca = new CA(params);
	return ca.getObj();
}
function CTable(params)
{
	this.params = {};
	var self = this;
	$.each(params, function(i,param) {
		self.params[param.name] = param.value;
		jsLog(param.name+' '+param.value);
	});
}
CTable.prototype.getObj = function()
{
	var table = document.createElement('table');
	var tbody = document.createElement('tbody');
	table.appendChild(tbody);
	
	if(this.params.header) { 
		var tr = document.createElement('tr');
		tbody.appendChild(tr);
		for(var ncol = 0;ncol < this.params.ncols;ncol++) {
			var th = document.createElement('th');
			tr.appendChild(th);
		}
	}
	for(var nrow = 0;nrow < this.params.nrows;nrow++) {
		var tr = document.createElement('tr');
		tbody.appendChild(tr);
		for(var ncol = 0;ncol < this.params.ncols;ncol++) {
			var td = document.createElement('td');
			tr.appendChild(td);
		}
	}
	return table;
}
function CImage(params)
{
	this.params = {};
	var self = this;
	$.each(params, function(i,param) {
		self.params[param.name] = param.value;
		jsLog(param.name+' '+param.value);
	});
}
CImage.prototype.getObj = function()
{
	var img = document.createElement('img');
	$(img).attr({
		alt: this.params.alt,
		src: this.params.image,
		title: this.params.hover
	});
	return img;
}
function CA(params)
{
	this.params = {};
	var self = this;
	$.each(params, function(i,param) {
		self.params[param.name] = param.value;
		jsLog(param.name+' '+param.value);
	});
}
CA.prototype.getObj = function()
{
	var a = document.createElement('a');
	$(a).html(this.params.txt);
	$(a).attr({href: this.params.href});
	return a;
}
function jsDropOutil(event,draggable,container,win) {
	jsLog(draggable);
	var nodeType = $(draggable).find('input[name="type"]').get(0);
	jsLog(nodeType+' '+$(nodeType).val());
	var node = document.createElement($(nodeType).val());
	nodeType = $(nodeType).val();

	node = window[nodeType]($(draggable).find('form').serializeArray());
	jsLog(node);
	return node;
}
function jsDropNewObjet(event,draggable,container,win) {
	var id = draggable.attr('id');
	var fn = 'window.'+id;
	if (eval('typeof '+fn) == 'function') {
		obj = win.document.createTextNode('toto');
	} else {
		obj = win.document.createElement(id);
	}
	return obj;
}
function jsDropObjet(event,parent,container,win) {
	var id = $(parent).attr('id');

	var obj = elements[id].cloneNode(true);
	var target_id = $(container).attr('id');
	var parent = elements[target_id];
	while (parent) {
		if (parent == elements[id]) return undefined;
		parent = parent.parentNode;
	}
	if (event.ctrlKey) {
		elements[id].parentNode.removeChild(elements[id]);
	}
	return obj;
}
function jsDrop(event,ui,container,win) {
	var draggable = ui.draggable;
	if(! draggable) {
		jsLog('no draggable');
		throw "no draggable";
		return;
	}
	var parent = draggable.parent();
	if(! parent) {
		jsLog('no parent');
		throw "no parent !!";
		return;
	}
	var target_id = $(container).attr('id');
	
	var obj = undefined;

	if(draggable.hasClass('outil')) {
		obj = jsDropOutil(event,parent,container,win);
	}
	if(draggable.hasClass('objet')) {
		obj = jsDropObjet(event,parent,container,win);
	}
	if(draggable.hasClass('newObjet')) {
		obj = jsDropNewObjet(event,draggable,container,win);
	}
	if (! obj) return;
	try {
		if (event.shiftKey) {
			$(obj).insertBefore(elements[target_id]);
		} else {
			elements[target_id].appendChild(obj);
		}
	} catch(ex) {
		jsLog("exception can't insert "+obj.nodeName+" vers "+target_id);
	}
	jsLoadDom(self);
	return true;
}

function jsSetDrop(target)
{
	Droppables.add(target,{
		accept : 'objet',
		onDrop: function (draggable, droppable, event) {
			var obj = null;
			var parent = draggable.parentNode;
			if(! parent) return;
			if (parent.getAttribute('id') && parent.getAttribute('id') == 'objets') {
				var id = draggable.getAttribute('id');
				var fn = eval('(window.'+id+')');
				if (fn) {
					obj = eval('('+fn+'())');
				} else {
					obj = document.createElement(id);
				}
			} else {
				obj = elements[draggable.getAttribute('id')].cloneNode(true);
				var parent = elements[target];
				while (parent) {
					if (parent == elements[draggable.getAttribute('id')]) return;
					parent = parent.parentNode;
				}
				if (event.ctrlKey) {
					elements[draggable.getAttribute('id')].parentNode.removeChild(elements[draggable.getAttribute('id')]);
				}
			}

			if (! obj) return;

			try {
				if (event.shiftKey) {
					elements[target].parentNode.insertBefore(obj,elements[target]);
				} else {
					elements[target].appendChild(obj);
				}
			} catch(ex) {
				if (elements[target].parentNode) {
					//elements[target].parentNode.insertBefore(obj,elements[target]);
				}
			}
			jsRefreshSource();
		},
		hoverclass : 'dragIsOn',
		overlap: 'vertical',
		onHover : function (element, target, overlap) {
			target.style.boder = '1px black solid';
		}
	});
}
function jsLoadCss()
{
	try {
		$.ajaxSetup({async: false});
		$('#css').empty();
		if(document.css == undefined) {
			document.css = [];
		}

		var sSheet = -1;
		for (sSheet=0; sSheet < win.document.styleSheets.length; sSheet++){
			var sheet = win.document.styleSheets[sSheet];

	//alert(sSheet);
			if(sheet['cssRules']) {
				//alert(typeof document.css);
				if(typeof document.css != 'object') alert('erreur');
				if(document.css[sSheet] == undefined) {
					if(sheet.href) {
						$.get(sheet.href, function() {
							//alert('styleSheet loaded');
							document.css[sSheet] = {complete:true};
							jsLog("rechargement feuille de style "+sheet.href+" demandé");
							setTimeout("jsLoadCss()",10);
						});
						return;
					} else {
						document.css[sSheet] = {complete:true};
					}
				}
				//alert(sSheet+' '+document.css[sSheet].complete);
		//alert(sSheet+' '+sheet.href);
				for (var iRule=0; iRule < sheet['cssRules'].length; iRule++) {
		//alert(iRule);
					var rule = sheet['cssRules'][iRule];
					var o = document.createElement("p");
					o.appendChild(document.createTextNode('href : '+sheet.href));
					o.appendChild(document.createElement('br'));
					o.appendChild(document.createTextNode('title : '+sheet.title));
					o.appendChild(document.createElement('br'));
					var a = document.createElement('a');
					$(a).attr({href:"#"});
					$(a).append(rule.selectorText);
					//alert(rule.selectorText);
					/*var a = new Element("a",{href: "#"}).insert(rule.selectorText);*/
					/*a.observe('click', function(event) { alert('coucou');jsCssEdit(event,rule); })*/
				
					$(o).append(a);
					$(o).append('<br />');
					var props = rule.style.cssText.split(/;/);

					$.each(props,function(i,val) {
						$(o).append(val).append('<br />');
					});
		/*			$(o).append(rule.style.cssText).append(document.createElement('br'));*/
					$(o).append('<br />');
					/*
					for (var i = 0;i < rule.style.length;i++) {
						txt = document.createTextNode(rule.style.cssText);
						$(o).append(txt);
						txt = document.createTextNode(rule.style.item(i)+" "+rule.style.getPropertyValue(rule.style.item(i)));
						$(o).append(txt);
						$(o).append('<br />');
					}
					*/
					$('#css').append(o);

				}
			} else {
				//for (var prop in sheet) { alert(prop+' '+sheet[prop]);}
				for (var iRule =0;iRule < sheet.rules.length;iRule++) {
		 //alert(iRule+' bis');
					var rule = sheet.rules[iRule];
					var o = '<p>'+sheet.href+'<br />'+sheet.title+'<a href="#">'+rule.selectorText+'</a><br />';
					/*
					var o = document.createElement("p");
					$(o).append(sheet.href).append('<br />');
					$(o).append(sheet.title).append('<br />');
					var a = document.createElement('a');
					$(a).attr({href: '#'}).append(rule.selectorText+'tt');
					//a.observe('click', function(event) { alert('coucou');jsCssEdit(event,rule); })
					$(o).append(a).append('<br />');
					for (var prop in rule) {
						alert(sheet.href+' '+prop+' === '+rule[prop]);
						//alert(sheet.rules[iRule].style.cssText+' '+sheet.rules[iRule].selectorText);
					}
					*/
					for (var prop in rule) {
						//alert(sheet.rules[iRule].style.cssText+' '+sheet.rules[iRule].selectorText);
					}
					for (var prop in rule.style) {
							//o += prop+':'+rule.style[prop]+'<br />';
						/*alert(sheet.href+' '+prop+' === '+rule[prop]);*/
						/*alert(sheet.rules[iRule].style.cssText+' '+sheet.rules[iRule].selectorText);*/
					}
					var props = rule.style.cssText.split(/;/);
					$.each(props,function(i,val) {
						o += val+'<br />';
					});
					$('#css').append(o);
				}
			}
		}
	}catch(ex) {
		jsLog('Exception : ('+sSheet+')'+ex);
		$.ajaxSetup({async: false});
		setTimeout("jsLoadCss()",10);
	} finally {
		$.ajaxSetup({async: false});
	}
}
function jsSaveCss()
{
	try {
		var doc = window.win.document;
	}catch(ex) {
		jsLog('Exception jsSaveCss : '+ex);
	} finally {
	}
	var css = [];
	for (var sSheet=0; sSheet < win.document.styleSheets.length; sSheet++){
		var sheet = win.document.styleSheets[sSheet];

		s = {};
		//alert('title '+sheet.title);
		//alert('href '+sheet.href);
		if(sheet.title) s.title = sheet.title;
		if(sheet.href) s.href = sheet.href;
		if(win.document.styleSheets[sSheet]['cssRules']) {
			s.rules = [];
			for (var iRule=0; iRule < win.document.styleSheets[sSheet]['cssRules'].length; iRule++) {
	 //alert(iRule);

				var rule = win.document.styleSheets[sSheet]['cssRules'][iRule];
				if(sheet.href) {
					// pour l'instant, on ne sait pas sauvegarder une feuille de style externe
					//continue;
				}
				
				// sheet.href
				// sheet.title
			
				var props = rule.style.cssText.split(/;/);
				var hprops = {};
				$.each(props,function(i,val) {
					var aVal = val.split(/:/);
					if(aVal[1]) hprops[aVal[0]] = aVal[1];
				});
				s.rules.push({selector: rule.selectorText, properties: hprops});
			}
		} else {
			//for (var prop in sheet) { alert(prop+' '+sheet[prop]);}
			for (var iRule =0;iRule < sheet.rules.length;iRule++) {
 //alert(iRule+' bis');
				var rule = sheet.rules[iRule];
				var o = '<p>'+sheet.href+'<br />'+sheet.title+'<a href="#">'+rule.selectorText+'</a><br />';
				/*
				var o = document.createElement("p");
				$(o).append(sheet.href).append('<br />');
				$(o).append(sheet.title).append('<br />');
				var a = document.createElement('a');
				$(a).attr({href: '#'}).append(rule.selectorText+'tt');
				//a.observe('click', function(event) { alert('coucou');jsCssEdit(event,rule); })
				$(o).append(a).append('<br />');
				for (var prop in rule) {
					alert(sheet.href+' '+prop+' === '+rule[prop]);
					//alert(sheet.rules[iRule].style.cssText+' '+sheet.rules[iRule].selectorText);
				}
				*/
				for (var prop in rule) {
					//alert(sheet.rules[iRule].style.cssText+' '+sheet.rules[iRule].selectorText);
				}
				for (var prop in rule.style) {
						//o += prop+':'+rule.style[prop]+'<br />';
					/*alert(sheet.href+' '+prop+' === '+rule[prop]);*/
					/*alert(sheet.rules[iRule].style.cssText+' '+sheet.rules[iRule].selectorText);*/
				}
				var props = rule.style.cssText.split(/;/);
				$.each(props,function(i,val) {
					o += val+'<br />';
				});
				$('#css').append(o);
			}
		}
		css.push(s);
	}
	return css;
}
var winEdit = {
	"#text":"textEdit"
};
var old_obj = null;
var old_color = null;
function jsOverNode(evt,obj)
{
	if(! evt) evt = window.event;
	if (obj.nodeName == '#text') return;
	if(dragObject)
	{
	}
	if (! obj.style) return;
	old_color = obj.style.backgroundColor;
	obj.style.backgroundColor = 'darkgray';
}
function jsOutNode(evt,obj)
{
	if(! evt) evt = window.event;
	if (! obj.style) return;
	if (obj.nodeName == '#text') return;
	obj.style.backgroundColor = old_color;
}
function jsNodeEdit(event)
{
	var obj = elements['i'+this.id];

	var form = document.createElement('form');
	$('#edition').empty().append(form);
	var balise = balises[obj.nodeName];
	if(! balise) return;
	jsLog(obj);
	balise.bind('validateDialog',$('#edition'));
	var code = balise.generate(obj);
	jsLog(code);
	$.each(code, function(i,c) {
		$(form).append(c);
	});

	$('#edition').dialog('option','title','&Eacute;dition '+obj.nodeName);
	$('#edition').dialog('open');
return;	var win = null;

	var obj = elements['i'+this.id];
	document.object = obj;
	if((fn = winEdit[obj.nodeName])) {
		win = window.open(fn+".php","style","width=800,height=600");
		if(win) win.opener = self;
	} else {
		win = window.open("nodeEdit.php","style","width=800,height=600");
		if(win) win.opener = self;
	}
	return win;

	if (old_obj) {
		old_obj.style.border = "";
	}
	obj.style.border = "1px black solid";
	old_obj = obj;
}
function jsShowText(event)
{
	var elt = event.element();
	elt.setAttribute('title',elt.data);
}
var dragObject = null;
function jsTest(evt)
{
	if(! evt) evt = window.event;
	/*
	if(dragObject && evt.target)
	alert(evt.target+' '+evt.target.nodeName);
	*/
}
function __jsDrop(evt)
{
	if(! evt) evt = window.event;
	if(dragObject && evt.target.nodeName == 'LI') {
		/*alert(evt.target+' '+evt.target.nodeName); // IE */
	}
}
function jsSelect(evt)
{
	if(! evt) evt = window.event;
	dragObject = evt.target;
}
function jsDeselect(evt)
{
	if(! evt) evt = window.event;
	dragObject = "null";
}

function text()
{
  return win.document.createTextNode('toto');
}
function comment()
{
  return win.document.createComment('this is a comment');
}

function jsCssEdit(event)
{
	var target = $(event.target);
	alert(target.html());
}
