var is_ie = '\v'=='v';
var CrossEditor = Class.create();
Event.observe(window, 'load', function(){
	editor = new CrossEditor;
});

CrossEditor.prototype = {
	initialize: function() {
		this.doc = $('edit').contentWindow.document;
		this.doc.designMode = 'on';
		this.haiga_path = 'http://nnkr.jp/tools/resource/haiga_m/';

		Event.observe($('reset_link'), 'click', this.resetHTML.bind(this));
		Event.observe(this.doc, 'keyup', function(event){
			this.makeHTML();
		}.bind(this));
		
		this.createMenu();
		this.createHaiga();
		var pallete = new ColorPallete('pallete_button', 'pallete', this);
	},
	
	createMenu: function(){
		var cmds = [
			{id:'undo', alt: '取り消し'},
			{id:'redo', alt: 'やり直し'},
			{id:'bold', alt: '太字'},
			{id:'underline', alt: '下線'},
			{id:'forecolor', alt: '文字色'},
			{id:'removeformat', alt: '装飾の取り消し'}
		];

		cmds.each(function(cmd){
			var menu = document.createElement('li');
			var icon = document.createElement('img');
			icon.src  = 'img/' + cmd.id + '.gif';
			icon.title = cmd.alt;
			icon.setAttribute('width', 16);
			icon.setAttribute('height', 16);
			menu.appendChild(icon);

			if(cmd.id=='forecolor'){
				menu.id = 'pallete_button';
				$('menu').appendChild(menu);
				return;
			}
			
			var opt = cmd.id == 'fontsize' ? '1' : false;
			Event.observe(menu, 'mousedown', function(){
				this.exCom(cmd.id, 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(){
		$('html').value = this.tagReplace(this.doc.body.innerHTML.toString());
		this.redrawPreview();
	},
	
	redrawPreview: function(){
		$('preview').innerHTML = $('html').value.replace(/¥n/g, '<br />');
	},
	
	resetHTML : function(){
		this.doc.body.innerHTML ='';
		this.makeHTML();
	},
	
	tagReplace: function(str){
		var RegExpCode = [
			['<P>|<DIV>|&nbsp;', ''],
			['<IMG', '<img'],
			['<img(.*?)>', '<img$1 />'],
			['<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>'],
			['</P>|</DIV>|<BR.*?>', '<br />']
		];
		
		if(is_ie){
			RegExpCode.push(['alt=(.*?) ', 'alt="$1" ']);
			RegExpCode.push(['width=(.*?) ', 'width="$1" ']);
			RegExpCode.push(['height=(.*?) ', 'height="$1" ']);
		}
		
		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);
			});
		});

		str = str.replace(/<SPAN class="Apple-style-span">|<.*SPAN>/g, '');
		str = str.replace(/¥n/g, '');
		return str;
	},
	
	insertHaiga: function(src, alt, w, h){
		$('edit').contentWindow.focus();
		this.doc.execCommand('insertImage', false, '#dummy#');
		
		var img = this.getElementByAttributeValue('img', 'src', '#dummy#');
		img.src = src;
		img.setAttribute('width', w);
		img.setAttribute('height', h);
		img.setAttribute('alt', alt);
		
		if (is_ie){
			var range = document.selection.createRange();
			range.move('character', this.doc.body.innerHTML.length);
			//適当。後で修正
			range.select();
		}
		
		this.makeHTML();
	},
	
	getElementByAttributeValue : function(tagName, attributeName, attributeValue ){
		var elements = this.doc.getElementsByTagName(tagName);
		
		for ( var i = 0; i < elements.length; i++ ){
			var value = elements[i].getAttribute(attributeName);
			if (is_ie) value = value.substr(value.length - attributeValue.length);
			if ( value == attributeValue ) return elements[i];
		}
		return false;
	},
        
	hai : {
		1:'man_1', 2:'man_2', 3:'man_3', 4:'man_4', 5:'man_5', 7:'man_6', 8:'man_7', 9:'man_8', 10:'man_9',
		11:'pin_1',12:'pin_2',13:'pin_3',14:'pin_4',15:'pin_5',17:'pin_6',18:'pin_7',19:'pin_8',20:'pin_9',
		21:'sou_1',22:'sou_2',23:'sou_3',24:'sou_4',25:'sou_5',27:'sou_6',28:'sou_7',29:'sou_8',30:'sou_9',
		31:'kaze_ton',32:'kaze_nan',33:'kaze_sha',34:'kaze_pei',
		35:'sangen_haku',36:'sangen_hatu',37:'sangen_chun',
		6:'aka_man_5',16:'aka_pin_5',26:'aka_sou_5',38:'ura'
	},
	
	hai_alt : {
		1:'1萬', 2:'2萬', 3:'3萬', 4:'4萬', 5:'5萬', 7:'6萬', 8:'7萬', 9:'8萬', 10:'9萬',
		11:'1筒',12:'2筒',13:'3筒',14:'4筒',15:'5筒',17:'6筒',18:'7筒',19:'8筒',20:'9筒',
		21:'1索',22:'2索',23:'3索',24:'4索',25:'5索',27:'6索',28:'7索',29:'8索',30:'9索',
		31:'東',32:'南',33:'西',34:'北',
		35:'白',36:'發',37:'中',
		6:'赤5萬',16:'赤5筒',26:'赤5索',38:'裏'
	},	
	
	createHaiga : function() {	
		var hai_normal_html = [];
		var hai_side_html = [];
		var sep  = [9,9,9,7];
		var c    = 0;
		var s    = 0;
		var w    = 26;
		var h    = 30;
		var x    = 40;
		var y    = 23;

		for(var i in this.hai){
			hai_normal_html.push('<div style="position:absolute; left:'+(w*c+x)+'px; top:'+y+'px"><img onclick="editor.insertHaiga(\' '+ this.haiga_path + this.hai[i] + '.gif \',\''+ this.hai_alt[i] +'\', 19,26)" src="'+this.haiga_path+this.hai[i]+'.gif" alt="'+this.hai_alt[i]+'" /></div>');
			hai_side_html.push('<div style="position:absolute; left:'+(w*c+x)+'px; top:'+y+'px"><img onclick="editor.insertHaiga(\' '+ this.haiga_path + this.hai[i] + '_y.gif \',\''+ this.hai_alt[i] +'\', 25,20)" src="'+this.haiga_path+this.hai[i]+'_y.gif" alt="'+this.hai_alt[i]+'" /></div>');
			c++;
			if(c >= sep[s]){
				c  = 0;
				y += h;
				s++;
			}
			if(s == 3){
				x = 300;
				y = 23;
			}
		}
		
		$('haiga_normal').innerHTML = hai_normal_html.join('');
		$('haiga_side').innerHTML = hai_side_html.join('');

	}
}


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 blogpost(){
	var livedoor_api = "http://cms.blog.livedoor.com/cms/article/add?bm=1&tb=0&l=&f=%24body%24&b=";
	var source = $('html').value;
	source = source.replace(';', '');
	source = source.replace('#', '');

	window.open(livedoor_api + source);
}
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);
}

