Event.observe(window, 'load', function(){
	var editor = new CrossEditor;
});

function setDefault(){
	$('edit').contentWindow.document.body.innerHTML = [
		'簡単な使い方',
		'<img height=16 alt=bold src="http://a-h.parfe.jp/einfach/archives/editor/img/bold.gif" width=16> <strong>強調できます</strong>',
		'<img height=16 alt=underline src="http://a-h.parfe.jp/einfach/archives/editor/img/underline.gif" width=16> <u>下線を引けます</u>',
		'<img height=16 alt=forecolor src="http://a-h.parfe.jp/einfach/archives/editor/img/forecolor.gif" width=16> <font color="#0066ff">色をつけることもできます</font>',
		'<img height=20 alt=removeformat src="http://a-h.parfe.jp/einfach/archives/editor/img/removeformat.gif" width=20> 装飾を解除できます(Safariは未対応)',
		'<input type=checkbox checked value=checkbox name=checkbox> コードを整える のチェックを外すとブラウザ本来のhtmlコードになります。'
	].join('<br>');
}

var CrossEditor = Class.create();

CrossEditor.prototype = {
	initialize: function() {
		this.doc = $('edit').contentWindow.document;
		this.doc.designMode = 'on';

		Event.observe($('translate'), 'click', this.makeHTML.bind(this));

		Event.observe(this.doc, 'keyup', function(event){
			this.makeHTML();
			/*
			if(this.doc.body.innerHTML.match(/<P>/))
				this.doc.body.innerHTML = $('html').value.replace(/¥n/gm, '<br>');
			*/
		}.bind(this));
		
		this.createMenu();

		var pallete = new ColorPallete('pallete_button', 'pallete', this);
	},
	createMenu: function(){

		var cmds = ['undo',
		'redo',
//		'fontsize',
		'increasefontsize',
		'decreasefontsize',
		'bold',
		'underline',
		'forecolor',
		'removeformat' ];

		cmds.each(function(cmd){
			var menu = document.createElement('li');
			var icon = document.createElement('img');
			icon.src  = '/einfach/archives/editor/img/' + cmd + '.gif';
			icon.alt = cmd;
			menu.appendChild(icon);

			if(cmd=='forecolor'){
				menu.id = 'pallete_button';
				$('menu').appendChild(menu);
				return;
			}

			if(cmd=='fontsize')
				var opt = '1';
			else
				var opt = false;


			Event.observe(menu, 'mousedown', function(){
				this.exCom(cmd, opt)
			}.bind(this));
			
			$('menu').appendChild(menu);
			
		}.bind(this));
	},
	exCom: function(cmd, opt){
		try{
			this.doc.execCommand(cmd, false, opt);
			this.makeHTML();
		}catch(e){
			alert('このブラウザではサポートされていないコマンドです。')
		}
	},
	makeHTML: function(){
		if($('translate').checked){
			$('html').value = this.tagReplace(this.doc.body.innerHTML.toString());
		}else{
			$('html').value = this.doc.body.innerHTML.toString();
		}
		this.redrawPreview();
	},
	redrawPreview: function(){
		$('preview').innerHTML = $('html').value.replace(/¥n/g, '<br />');
	},
	tagReplace: function(str){
		var RegExpCode = [
			['<(.*?)P>|</DIV>|&nbsp;', ''],
			['<STRONG>(.*?)<.STRONG>', '<strong>$1</strong>'],
			['<U>(.*?)</U>', '<span style="text-decoration: underline;">$1</span>'],
			['<span style="font-weight: bold;">(.*?)</span>', '<strong>$1</strong>'],
			['<span styl.*"font-weight: normal;">(.*?)</span>', '$1'],
			['<FONT color="?#(.*?)"?>(.*?)</FONT>', '<span style="color: #$1">$2</span>'],
			['<SPAN class="Apple-style-span" style="(.*?)">(.*?)</SPAN>', '<span style="$1">$2</span>'],
			//['<BR class="khtml-block-placeholder">', '¥n'],
			['<DIV>|<BR.*?>', '<br>']
		];
		RegExpCode.each(function(e){
			var code = new RegExp(e[0], 'igm');
			str = str.replace(code, e[1]);
		});

		var RegExpCode = [
			['(<BIG>)+(.*?)(<.BIG>)+', '<span style="font-size:%#size#%em">$2</span>','<BIG>'],
			['(<SMALL>)+(.*?)(<.SMALL>)+', '<span style="font-size:%#size#%em">$2</span>','<SMALL>']
		];
		RegExpCode.each(function(e){
			var tagPattern = new RegExp(e[0], 'igm');
			var tag = new RegExp(e[2], 'igm');
			str = str.replace(tagPattern, function(matchText){
				var num = matchText.split(tag).length - 1;
				var size = (e[2] == '<BIG>') ? Math.pow(1.4, num) :  Math.pow(0.85, num);
				var pattern = e[1].replace(/%#size#%/, roundMath(size));
				return matchText.replace(tagPattern, pattern);
			});
		});
/*
		var e = ['(<FONT size="?(.*?)"?>)+(.*?)(<¥/FONT>)+', '<span style="font-size:%#size#%em">$3</span>','<¥/FONT>'];
		var tagPattern = new RegExp(e[0], 'igm');
		var tag = new RegExp(e[2], 'igm');
		str = str.replace(tagPattern, function(matchText){
		//log(arguments);
			var num = arguments[2];
			var size = (e[2] == '<BIG>') ? Math.pow(1.4, num) :  Math.pow(0.85, num);
			var pattern = e[1].replace(/%#size#%/, roundMath(size));
			return matchText.replace(tagPattern, pattern);
		});
*/
		
		//Safari対策
		str = str.replace(/<SPAN class="Apple-style-span">|<.*SPAN>/g, '');
		str = str.replace(/¥n/g, '');
		return str;
	}
}


var ColorPallete = Class.create();

ColorPallete.prototype = {
	initialize: function(button, area, editor) {
		this.div = $(area);
		this.div.innerHTML = this.create();
		Event.observe(document, 'keydown', this.hotkey.bind(this), false);
		this.button = $(button);
		Event.observe(button, 'click', this.toggle.bind(this));
		this.editor = editor;
		this.setEvent();
	},
	create: function() {
		var source = '<table><tbody>';
		var color='';
		var hex = new Array('f','c','9','6','3','0')
		for(j=0;j<6;j++){
			for(k=0;k<6;k++){
				for(l=0;l<6;l++){
					var hexColor = hex[j]+hex[j]+hex[k]+hex[k]+hex[l]+hex[l];
					color+='<td style="background-color: #'+hexColor+'"></td>';
				}
			}
			source+='<tr>'+color+'</tr>';
			color='';
		}
		for(i=0;i<6;i++){
			var hexColor = hex[i]+hex[i]+hex[i]+hex[i]+hex[i]+hex[i];
			color+='<td style="background-color: #'+hexColor+'" colspan="6"></td>';
		}
		source+='<tr>'+color+'</tr>';
		source+='</tbody></table>';
		return source;
	},
	show: function(){
		var pallete = this.div.style;
		pallete.top = this.button.offsetTop + 30 + 'px';
		pallete.left = this.button.offsetLeft + 'px';
		pallete.display = 'block';
	},
	hide: function(){
		var pallete = this.div.style;
		pallete.display = 'none';
	},
	toggle: function(){
		if(this.div.style.display != 'block'){
			this.show();
		}else{
			this.hide();
		}
	},
	hotkey: function(event){
		if(event.keyCode == 27){ // 'Esc'
			this.hide();
		}
	},
	setEvent: function(){
		Event.observe(document.body, 'mousedown' ,function(e){
			e = e || window.event;
			var element = e.target || e.srcElement;
			var tag = element.tagName.toLowerCase();
			if(tag == 'td' && element.offsetParent.parentNode.id == 'pallete'){
				var cmd = 'forecolor';
				var opt = element.style.backgroundColor;
				this.editor.exCom(cmd, opt);
				this.editor.makeHTML();
				this.hide();
			}else if(tag == 'body'){
				this.hide();
			}
		}.bind(this));
	}
}



function createlink(){
	var image_url = prompt('画像のURLを入力してください。','http://');
	execCommand('createlink', image_url);
}
function remakeHTML(){
	doc.body.innerHTML = $('html').value.replace(/¥n/g, '<br>');
	redrawPreview();
}
function roundMath(num){
	return Math.round(num * 100) / 100;
}
function log(obj){
	return console.log(obj);
}
