var cda = {
	c : function(){
		var html =
			'<form onsubmit="return cda.cC();"><table id="c"><tr>'+
			'<td>user </td><td><input id="id" type="text"></td></tr><tr>'+
			'<td>password </td><td><input id="ps" type="text"></td></tr><tr>'+
			'<td></td><td><input type="submit" value="enter" ></td>'+
			'</tr></table></form>';
		new DOMPopup({
			'target' : document.body,
			'id' : 'connexion',
			'title' : 'connexion',
			'size' : [220,78],
			'unique' : true,
			'html' : html,
			'containerClass' : 'popup_container',
			'captionClass' : 'popup_caption',
			'closeButtonClass' : 'popup_closebutton',
			'closeButtonHTML' : '<img src="__layout/popup_close.jpg" alt="" />',
			'bodyClass' : 'popup_body'
		})
		document.getElementById('id').focus();
	},
	cC : function(){
		var id = document.getElementById('id').value;
		var ps = document.getElementById('ps').value;
		if(id && ps){
			this.createForm({
				'form' : [{
					'action' : '__php/connexion.php',
					'method' : 'POST'
				}],
				'input' : [{
					'name' : 'c',
					'user' : id,
					'pass' : ps
				}]
			})
		};
		return false;
	},
	start : function(){
		this.container = document.getElementById('content');
		this.setImagepopup();
	},
	setImagepopup : function(){
		this.img = this.container.getElementsByTagName('img');
		for(var i=0; i<this.img.length; i++){
			if(this.img[i].className.match(/__popup/))
				this.img[i].onmousedown = function(){
					popup.init(this.src.replace(/mini_/,''))
				}
		}
	},
	openEdit : function(current){
		var _this = this;
		this.current = current;
		this.current.style.visibility = 'hidden';
		//this.container = document.getElementById('content');
		this.previousHtml = this.container.innerHTML;
		this.container.innerHTML = '';
		this.cc();
		xmlhttp.get(
			'__css/style.css',
			'',
			function(){},
			function(){
				_this.edit = new editor(
					_this.previousHtml,
					_this.c,
					xmlhttp.responseText,
					function(){ _this.closeEdit(); }
				);
			}
		)
	},
	closeEdit : function(){
		this.container.innerHTML = this.previousHtml;
		this.current.style.visibility = '';
	},
	cc : function(){
		this.c = document.createElement('div');
		this.c.setAttribute(
			'style',
			'position:absolute;'+
			'top:'+(this.container.getPosition().y-6)+'px;'+
			'width:545px;'+
			'bottom:10px;'+
			'left:'+(this.container.getPosition().x-6)+'px;');
		document.body.appendChild(this.c);
	},
	saveEditData : function(data){
		data = data.replace(/[\t|\n]/g,'');
		data = data.replace(/"/g,'&quot;');
		this.save2json(PHP_json,'data',currentObj,data);
		var strData = JSON.stringify(PHP_json,null,'\t');
		strData = strData.replace(/\n/g,'\\n');
		this.createForm({
			'form' : [{
				'action' : '__php/post.php',
				'method' : 'POST'
			}],
			'input' : [{
				'save_data' : strData
			}]
		})
	},
	save2json : function(obj,type,target,data){
		for(var i in obj){
			if(obj[i]==target){
				obj[i][type] = data;
			}else
				if(typeof obj[i]=='object') 
					cda.save2json(obj[i],type,target,data);
		}
	},
	createForm : function(obj){
		var form = document.createElement('form');
			form.style.display = 'none';
		for(i in obj){
			if(i=='form'){
				for(j in obj[i][0]){
					form.setAttribute(j,obj[i][0][j])
				}
			}
			if(i=='input'){
				for(j in obj[i][0]){
					var	input = document.createElement('input');
						if(j=='name'){
							input.setAttribute('name',obj[i][0][j])
						}else{
							input.setAttribute('name',j);
							input.setAttribute('value',obj[i][0][j])
						}
					form.appendChild(input);
				}
			}
		}
		document.body.appendChild(form);
		form.submit();
	}
}

var popup = {
	init : function(img){
		var _this = this;
		this.img = img;
		xmlhttp.get(
			'__php/xhr.php',
			'?image_size='+img,
			function(){},
			function(){
				_this.size = xmlhttp.responseText.split('|');
				_this.open();
			}
		)
	},
	open : function(){
		var param = 'width='+this.size[0]+',height='+this.size[1];
		this.popupImage = window.open('',this.img,param)
		this.html = '<HTML><HEAD><BODY LEFTMARGIN=0 MARGINWIDTH=0 TOPMARGIN=0 MARGINHEIGHT=0><IMG SRC="'+this.img+'" BORDER=0></BODY></HEAD></HTML>';
		this.popupImage.document.open();
		this.popupImage.document.write(this.html);
		this.popupImage.document.close();
	}
};

var editor = function(html,container,css,onExit){
	this.text = html;
	this.display = container;
	this.css = css;
	this.onExit = onExit;
	this.tb = document.getElementById('__tb');
	this.createToolbar();
	this.create();
};
editor.prototype.create = function(){
	this.iframe = document.createElement('iframe');
	this.iframe.className = "__iframe_edit";
	this.display.appendChild(this.iframe);
	this.editwin = this.iframe.contentWindow;
	this.editzone = this.iframe.contentDocument;
	this.html = '<html><head><style type="text/css">'+this.css+'</style></head><body class="__edit inner">'+this.text+'</body></html>';
	this.editwin.document.open();
	this.editwin.document.write(this.html);
	this.editwin.document.close();
	this.editzone.designMode = "On";
};
editor.prototype.createToolbar = function(){
	var _this = this;
	this.tbContainer = document.createElement('div');
	for(var i in this.toolbar2){
		if(typeof this.toolbar2[i]!='object') continue;
		var ul = document.createElement('ul');
		for(var j in this.toolbar2[i]){
			var	li = document.createElement('li');
			var 	a = document.createElement('a');
				a.innerHTML = this.toolbar2[i][j];
				a.name = j;
				a.href = '';
				a.onclick = function(){return false;};
				a.onmouseup = function(){ _this.format(this.name); }
			li.appendChild(a);
			ul.appendChild(li);
		}
		this.tbContainer.appendChild(ul);
	}
	this.tb.insertBefore(this.tbContainer, this.tb.firstChild);
};
editor.prototype.format = function(action){
	try{
		this.editwin.document.execCommand('styleWithCSS', false, null);
		this.editwin.document.execCommand("useCSS", false, null);
	}catch(error){}
	switch(action){
		default:
			this.editzone.execCommand(action, false, null);
		break;
		case 'h1':
		case 'h2':
		case 'h3':
		case 'p':
			this.editzone.execCommand('formatblock', false, action);
		break;
		case 'link':
			this.addlink();
		break;
		case 'save':
			this.save();
		break;
		case 'exit':
			this.exit();
		break;
		case 'image':
			this.image();
		break;
		case 'help':
			this.help();
		break;
		case 'float_left':
		case 'float_right':
		case 'normal':
		case 'fullsize':
		case 'fullsize_remove':
			this.formatimage(action);
		break;
	}
};
editor.prototype.addlink = function(){
	var l = prompt('','http://');
	if(l && l!='' && l.match(/w/g)){
		l = l.replace(/^\s+/g,'').replace(/\s+$/g,'');
		this.editzone.execCommand('createlink',false,l);
	}
};
editor.prototype.image = function(){
	var html =
	'<div style="position:absolute;top: 20px;right:2px;bottom:2px;left:2px;border:solid 1px">'+
	'<iframe id="media_popup" frameborder=0 style="width:100%;height:100%;" src="__php/media.iframe.php?instance='+this+'"></iframe>'+
	'</div>';
	this.mediaPop = new DOMPopup({
		'target' : document.body,
		'id' : 'media',
		'title' : 'Gestion des images',
		'size' : [300,450],
		'unique' : true,
		'savePosition' : true,
		'movable' : true,
		'html' : html,
		'containerClass' : 'popup_container',
		'captionClass' : 'popup_caption',
		'closeButtonClass' : 'popup_closebutton',
		'closeButtonHTML' : '<img src="__layout/popup_close.jpg" alt="" />',
		'bodyClass' : 'popup_body'
	});
};
editor.prototype.formatimage = function(pos){
	var _this = this;
	var getselection = this.editwin.getSelection();			
	if (getselection.rangeCount > 0) {
		var range = getselection.getRangeAt(0);
		if (range.startContainer.nodeType == 1){
			var selection = range.startContainer.childNodes[range.startOffset];
			if(pos=='float_left' || pos=='float_right'){
				selection.className = selection.className.replace(/__fleft|__fright/,'');
				if(pos=='float_left') selection.className = selection.className+' __fleft';
				if(pos=='float_right') selection.className = selection.className+' __fright';
			}else if(pos=='normal'){
				selection.className = selection.className.replace(/__fleft|__fright/,'');
			}else if(pos=='fullsize'){
				selection.className = selection.className+' __popup';
				alert('Agrandissement ajouté')
			}else if(pos=='fullsize_remove'){
				selection.className = selection.className.replace(/__popup/,'');
				alert('Agrandissement supprimé')
			}
		}
	}
	
};
editor.prototype.insertImage = function(file){
	this.editzone.execCommand('insertImage',false,file);
};
editor.prototype.save = function(){
	if(!confirm("Enregistrer la page ?")) return false;
	data = this.editzone.body.innerHTML;
	data = data.replace(/<p>/g,'');
	data = data.replace(/<\/p>/g,'');
	cda.saveEditData(data);
};
editor.prototype.exit = function(){
	if(document.getElementById('media')) document.body.removeChild(document.getElementById('media'));
	if(document.getElementById('help')) document.body.removeChild(document.getElementById('help'));
	this.display.removeChild(this.iframe);
	this.tb.removeChild(this.tbContainer)
	this.onExit();
};
editor.prototype.help = function(){
	var html =
	'<div style="position:absolute;top: 20px;right:2px;bottom:2px;left:2px;border:solid 1px">'+
	'<iframe id="media_popup" frameborder=0 style="width:100%;height:100%;" src="http://www.as-o.ch/helpfile/asojson/"></iframe>'+
	'</div>';
	this.mediaPop = new DOMPopup({
		'target' : document.body,
		'id' : 'help',
		'title' : 'help',
		'size' : [550,350],
		'unique' : true,
		'savePosition' : true,
		'movable' : true,
		'resize' : true,
		'html' : html,
		'containerClass' : 'popup_container',
		'captionClass' : 'popup_caption',
		'closeButtonClass' : 'popup_closebutton',
		'closeButtonHTML' : '<img src="__layout/popup_close.jpg" alt="" />',
		'bodyClass' : 'popup_body'
	});
};
editor.prototype.toolbar2 = {
	'1' : {
		'exit' : '<span title="quitter l\'éditeur">&#171; quitter</span>',
		'save' : 'sauver &#164;',
		'undo' : '<span title="annuler l\'action précédente">annuler</span>',
		'bold' : 'gras',
		'italic' : 'italic',
		'underline' : 'souligné', 
		'justifyleft' : 'gauche', 
		'justifyright' : 'droite', 
		'justifycenter' : 'centré',
		'justifyfull' : 'justifié',
		'h1' : '<span title="grand titre">h1</span>',
		'h2' : '<span title="sous-titre">h2</span>',
		'h3' : '<span title="petit titre">h3</span>'
	},
	'2' : {
		'p' : '<span title="paragraphe / suppression de titre">p</span>',
		'insertunorderedlist' : '<span title="liste à puces">puces</span>',
		'link' : '<span title="hyperlien">lien</span>',
		'image' : '<span title="insertion d\'images">image</span>',
		'float_left' : '<span title="image flottante à gauche">gauche</span>',
		'float_right' : '<span title="image flottante à droite">droite</span>',
		'normal' : '<span title="image position normale">normale</span>',
		'fullsize' : '<span title="lien sur agrandissement">agrandissement</span>',
		'fullsize_remove' : '<span title="suppression lien sur agrandissement">suppr. agrandissement</span>',
		'help' : 'help'
	}
}