﻿/**
 * MediumEditor
 * v1.0
 *
 **/

var MediumEditor={
	location      : 'http://localhost/mediumeditor',
	usrStyles     : 'usrstyles.css',

	editorBorder  : 'solid 1px gray',
	editorBg      : 'white',
	editorFontSize: 12,

	toolbarHeight  : 24,
	toolbarBtnPadd : 3,
	toolbarBgColor : '#efefef',
	toolbarIconExt : 'gif',
	toolbarHasSize : false,
	toolbarSizePx  : true,
	toolbarUsrStyle: false,

	editors : new Array(),
	content : new Array(),
	buttons : new Array(
		'bold','italic','underline',
		'justifyleft','justifycenter','justifyright',
		'insertunorderedlist',
		'outdent','indent',
		'undo'
	),
	captions : new Array(
		'félkövér','dőlt','aláhúzás',
		'balra igazítás','középre igazítás','jobba igazítás',
		'számozatlan lista',
		'kisebb margó','behúzás',
		'mégse'
	),
	styleDef : [
		['akármilyen', 'valamilyen'],
		['másik fajta', 'masik']
	],
	windowRef : null,

	init : function(){
		var txtArea=document.getElementsByTagName('textarea');
		for(var i=0;i<txtArea.length;i++)
			if(txtArea[i].getAttribute('replace')=='mediumeditor')
				this.editors[this.editors.length]=txtArea[i].id;

		var editor,content,iView,newSS;
		for(var i=0;i<this.editors.length;i++){
			txtArea=document.getElementById(this.editors[i]);
			content=txtArea.value;
			editor=this.createEditor(txtArea);

			txtArea.parentNode.replaceChild(editor,txtArea);

			iView=document.getElementById(this.editors[i]);
			iView.contentWindow.document.write('<span style="font-size: '+this.editorFontSize+'px;">'+content+'</span>');
			iView.contentWindow.document.close();
			iView.contentWindow.document.designMode="on";
			iView.contentWindow.document.onclick=this.evtOnClick;

			if(this.isIE()){
				iView.contentWindow.document.onclick=this.evtOnClick;

			} else {
				iView.contentWindow.document.addEventListener('click',this.evtOnClick,false);
			}

			iView.contentWindow.myView=iView;

			this.prepareForm(this.findForm(editor));
		}
	},

	loadCSS : function(filename,frameName){
		var ss = document.createElement('<link href="'+filename+'" type="text/css" rel="stylesheet" media="all"/>');

		var iframe=(document.frames)?document.frames[frameName]:window.frames[frameName];
		alert('ok');
		if(document.all)iframe.document.createStyleSheet(filename);
		else iframe.document.getElementsByTagName("head")[0].appendChild(ss);
		alert('ok');
	},

	onsubmit : function(frm){
		var hidden;
		for(var i=0;i<this.editors.length;i++){
			hidden=document.getElementById('content_'+this.editors[i]);
			hidden.value=document.getElementById(this.editors[i]).contentWindow.document.body.innerHTML;
		}
	},

	evtOnClick : function(e){
		var e,tg;
		if (!e){
			e = MediumEditor.getEventSource();
			tg = e.srcElement;
		} else tg = e.target;

		MediumEditor.checkFontSize(tg);
	},

	getEventSource : function(){
		var iframes=document.getElementsByTagName('iframe');
		var event;
		for(var i=0;i<iframes.length;i++)
			if(iframes[i].contentWindow.event) event=iframes[i].contentWindow.event;

		return event;
	},

	doEvent : function(btn){
		var id=btn.getAttribute('id').substr(4);
		var iframes=btn.parentNode.parentNode.getElementsByTagName('iframe');
		var iView=iframes[0];

		switch(id){
		case 'image':
			var params=new Array();
			params['iframe']=iView;

			var width=600;
			var height=700;
			var left=parseInt((screen.width-width)/2);
			var top=parseInt((screen.height-height)/2);

			this.windowRef=window.open('dialog/insert_image.php?'+Math.random(),'dialog','left='+left+',top='+top+',width='+width+',height='+height+',toolbar=0,resizable=0,status=0,menubar=0,scrollbars=0');
			this.windowRef.myCallback=this.insertImage;
			this.windowRef.params=params;
			this.windowRef.isIE=this.isIE();
			break;
		case 'code':
			alert(iView.contentWindow.document.body.innerHTML);
			break;
		default:
			iView.contentWindow.document.execCommand(id, false, null);
		}
	},

	format : function(source){
		var iframes=source.parentNode.parentNode.getElementsByTagName('iframe');
		var iView=iframes[0];
		var range=this.getRange(iView);
		var cont,tmp;
		var id=source.getAttribute('id');

		if(!source.options.selectedIndex) return false;
		if(this.isIE()){
			range.execCommand("FontSize",false,1);
			tmp=iView.contentWindow.document.body.innerHTML;
			tmp=tmp.replace(/<FONT size=1>/g,'<span style="font-size: '+source.options[source.options.selectedIndex].value+'px;">');
			tmp=tmp.replace(/<\/FONT>/g,'</span>');
			iView.contentWindow.document.body.innerHTML=tmp;
		} else {
			cont=(range.collapsed)?range.startContainer.parentNode:range.cloneContents();
			for(var i=0;i<cont.childNodes.length;i++){
				switch(cont.childNodes[i].nodeType){
				case 1:
					switch(id){
					case 'fontSize':
						cont.childNodes[i].style.fontSize=source.options[source.options.selectedIndex].value+'px'; break;
					case 'usrStyle':
						cont.childNodes[i].setAttribute('class',source.options[source.options.selectedIndex].value); break;
					}
					break;
				case 3:
					var span=document.createElement('span');
					switch(id){
					case 'fontSize':
						span.style.fontSize=source.options[source.options.selectedIndex].value+'px'; break;
					case 'usrStyle':
						span.setAttribute('class',source.options[source.options.selectedIndex].value); break;
					}
					span.appendChild(document.createTextNode(cont.childNodes[i].nodeValue));
					cont.childNodes[i].parentNode.replaceChild(span,cont.childNodes[i]);
					break;
				}
			}
			range.deleteContents();
			range.insertNode(cont);
		}
	},

	checkFontSize : function(tg){
		var obj=tg;
		while(!obj.style.fontSize) obj=obj.parentNode;
		var size=obj.style.fontSize.substr(0,this.strpos(obj.style.fontSize,'p'));

		var win=this.getWindow(obj);
		var toolbar=win.parent.document.getElementById('toolbar_'+win.myView.getAttribute('id'));
		for(var i=0;i<toolbar.childNodes.length;i++){
			if(toolbar.childNodes[i].getAttribute('id')=='fontSize'){
				for(var j=0;j<toolbar.childNodes[i].options.length;j++)
					toolbar.childNodes[i].options[j].selected=(toolbar.childNodes[i].options[j].value==size);
			}
		}
	},

	insertImage : function(arg,params){
		var range=null;
		var img=null;
		var iView=params['iframe'];

		if(MediumEditor.isIE()){
			img='<img src="'+arg['src']+'" style="width:'+arg['width']+'px;height:'+arg['height']+'px;border: solid '+arg['border']+'px;margin='+arg['margin']+';float:'+arg['float']+';">';
			iView.contentWindow.focus();
			range=iView.contentWindow.document.selection.createRange();
			range.pasteHTML(img);
		} else {
			img=document.createElement('img');
			img.setAttribute('src',arg['src']);
			img.setAttribute('alt',arg['alt']);
			img.style.width=arg['width']+'px';
			img.style.height=arg['height']+'px';
			img.style.border='solid '+arg['border']+'px';
			img.style.margin=arg['margin']+'px';
			img.style.cssFloat=arg['float'];
			iView.contentWindow.focus();
			range=iView.contentWindow.getSelection().getRangeAt(0);
			range.insertNode(img);
		}
	},

	select : function(select){
		var cursel = select.selectedIndex;
		var iframes=select.parentNode.parentNode.getElementsByTagName('iframe');
		var iView=iframes[0];
		if (cursel != 0) {
			var selected = select.options[cursel].value;
			iView.contentWindow.document.execCommand(select.getAttribute('command'), false, selected);
			select.selectedIndex = 0;
		}
		iView.contentWindow.focus();
	},

	prepareForm : function(frm){
		if(!frm||(frm.getAttribute('prepared')=='ok')) return false;
		var oldQueue = frm.onsubmit? frm.onsubmit: function() {};
	    frm.onsubmit = function() {
	    	eval("MediumEditor.onsubmit(this)");
	        oldQueue();
	    }
	    frm.setAttribute('prepared','ok');
		return true;
	},

	findForm : function(elm){
		if(!elm) return false;
		return (elm.tagName.toLowerCase()=='form')?elm:this.findForm(elm.parentNode);
	},

	getWindow : function(elm){
		if(!elm) return false;
		else if(elm.defaultView) return elm.defaultView;
		else if(elm.parentWindow) return elm.parentWindow;
		else return this.getWindow(elm.parentNode);
	},

	getSelection : function(iView){
		iView.contentWindow;
		iView.contentWindow.document;
		var selection = null;
		var range = null;

		if (typeof iView.contentWindow.getSelection != "undefined") return iView.contentWindow.getSelection();
		else if (typeof iView.contentWindow.document.selection != "undefined") return iView.contentWindow.document.selection;
		else return false;
	},

	getRange : function(iView){
		var selection=this.getSelection(iView);
		var range;

    	if (typeof selection.getRangeAt != "undefined") range = selection.getRangeAt(0);
		else if (typeof selection.baseNode != "undefined") {
			range = iView.contentWindow.document.createRange();
			range.setStart(selection.baseNode, selection.baseOffset);
			range.setEnd(selection.extentNode, selection.extentOffset);

			if (range.collapsed){
				range.setStart(selection.extentNode, selection.extentOffset);
				range.setEnd(selection.baseNode, selection.baseOffset);
			}
		} else if (typeof iView.contentWindow.document.selection != "undefined"){
			range = selection.createRange();
		} else return false;

		return range;
	},

	createEditor : function(txtArea){
		var editor,toolbar,iView,hidden;

		if(this.isIE()){
			editor=document.createElement('<div class="mediumeditor">');
			toolbar=document.createElement('<div class="toolbar" id="toolbar_'+txtArea.getAttribute('id')+'">');
			iView=document.createElement('<iframe id="'+txtArea.getAttribute('id')+'">');
			hidden=document.createElement('<input type="hidden" name="'+txtArea.name+'" id="content_'+txtArea.getAttribute('id')+'" value="'+txtArea.value+'" />');
		} else {
			editor=document.createElement('div');
			editor.setAttribute('class','mediumeditor');
			toolbar=document.createElement('div');
			toolbar.setAttribute('class','toolbar');
			toolbar.setAttribute('id','toolbar_'+txtArea.getAttribute('id'));
			iView=document.createElement('iframe');
			iView.setAttribute('id',txtArea.getAttribute('id'));
			hidden=document.createElement('input');
			hidden.setAttribute('type','hidden');
			hidden.setAttribute('name',txtArea.name);
			hidden.setAttribute('id','content_'+txtArea.getAttribute('id'));
			hidden.setAttribute('value',txtArea.value);
		}

		editor.style.width=txtArea.offsetWidth+'px';
		editor.style.height=(txtArea.offsetHeight+this.toolbarHeight)+'px';
		editor.style.border=this.editorBorder;
		editor.style.background=this.editorBg;

		iView.style.position='relative';
		iView.style.width=(txtArea.offsetWidth-1)+'px';
		iView.style.height=(txtArea.offsetHeight-2)+'px';
		iView.style.top='0px';
		iView.style.left='0px';
		iView.style.border='0px';
		iView.style.background='none';

		editor.appendChild(toolbar);
		editor.appendChild(iView);
		editor.appendChild(hidden);

		this.createToolBar(toolbar);

		return editor;
	},

	createToolBar : function(toolbar){
		var btn,btnImage,selSize,selStyle;

		toolbar.style.position='relative';
		toolbar.style.width='100%';
		toolbar.style.height=this.toolbarHeight+'px';
		toolbar.style.top='0px';
		toolbar.style.left='0px';
		toolbar.style.background=this.toolbarBgColor;

		if(this.toolbarHasSize){
			if(this.isIE()){
				selSize=document.createElement('<select onchange="MediumEditor.select(this)" command="fontsize">');
			} else {
				selSize=document.createElement('select');
				selSize.setAttribute('onchange','MediumEditor.select(this)');
				selSize.setAttribute('command','fontsize');
			}

			selSize.options[0]=new Option('méret',0);
			for(var i=1;i<7;i++)
				selSize.options[i] = new Option(i,i);

			selSize.style.margin='2px';
			selSize.style.height=(this.toolbarHeight-4)+'px';
			selSize.style.fontSize='10px';
			selSize.style.textAlign='center';
			if(this.isIE()) selSize.style.styleFloat='left';
			else selSize.style.cssFloat='left';

			toolbar.appendChild(selSize);
		}

		if(this.toolbarSizePx){
			if(this.isIE()){
				selSize=document.createElement('<select id="fontSize" onchange="MediumEditor.format(this)">');
			} else {
				selSize=document.createElement('select');
				selSize.setAttribute('onchange','MediumEditor.format(this)');
				selSize.setAttribute('id','fontSize');
			}

			selSize.options[0]=new Option('méret',0);
			for(var i=1;i<13;i++)
				selSize.options[i] = new Option((i+8)+'px',i+8);

			selSize.style.margin='2px';
			selSize.style.height=(this.toolbarHeight-4)+'px';
			selSize.style.fontSize='10px';
			selSize.style.textAlign='center';
			if(this.isIE()) selSize.style.styleFloat='left';
			else selSize.style.cssFloat='left';

			toolbar.appendChild(selSize);
		}

		if(this.toolbarUsrStyle){
			if(this.isIE()){
				selStyle=document.createElement('<select id="usrStyle" onchange="MediumEditor.format(this)">');
			} else {
				selStyle=document.createElement('select');
				selStyle.setAttribute('onchange','MediumEditor.format(this)');
				selStyle.setAttribute('id','usrStyle');
			}

			selStyle.options[0]=new Option('stílus',0);
			for(var i=0;i<this.styleDef.length;i++)
				selStyle.options[i+1] = new Option(this.styleDef[i][0],this.styleDef[i][1]);

			selStyle.style.margin='2px';
			selStyle.style.height=(this.toolbarHeight-4)+'px';
			selStyle.style.fontSize='10px';
			selStyle.style.textAlign='center';
			if(this.isIE()) selStyle.style.styleFloat='left';
			else selStyle.style.cssFloat='left';

			toolbar.appendChild(selStyle);
		}

		for(var i=0;i<this.buttons.length;i++){
			if(this.isIE()){
				btn=document.createElement('<div id="btn_'+this.buttons[i]+'" class="button">');
				btnImage=document.createElement('<img src="images/mediumeditor/'+this.buttons[i]+'.'+this.toolbarIconExt+'" alt="'+this.buttons[i]+'" title="'+this.captions[i]+'" />');
			} else {
				btn=document.createElement('div');
				btn.setAttribute('id','btn_'+this.buttons[i]);
				btn.setAttribute('class','button');

				btnImage=document.createElement('img');
				btnImage.setAttribute('src','images/mediumeditor/'+this.buttons[i]+'.'+this.toolbarIconExt);
				btnImage.setAttribute('alt',this.buttons[i]);
				btnImage.setAttribute('title',this.captions[i]);
			}

			btnImage.style.height=(this.toolbarHeight-(2*this.toolbarBtnPadd)-2)+'px';

			btn.style.width=(this.isIE())?(this.toolbarHeight-2)+'px':(this.toolbarHeight-(2*this.toolbarBtnPadd)-2)+'px';
			btn.style.border='solid 1px '+this.toolbarBgColor;
			btn.style.padding=this.toolbarBtnPadd+'px';
			btn.style.cursor=(this.isIE())?'hand':'pointer';
			btn.style.overflow='hidden';
			if(this.isIE()) btn.style.styleFloat='left';
			else btn.style.cssFloat='left';
			btn.onmouseover=function(){ this.style.border='solid 1px blue'; }
			btn.onmouseout=function(){ this.style.border='solid 1px '+MediumEditor.toolbarBgColor; }
			btn.onmousedown=function(e){
				var evt = e ? e : window.event;

				this.style.border="inset 1px";
				if(evt.returnValue) evt.returnValue = false;
				else if(evt.preventDefault) evt.preventDefault( );
				else return false;
			}
			btn.onmouseup=function(){ this.style.border='solid 1px blue'; }
			btn.onclick=function(){ MediumEditor.doEvent(this); }

			btn.appendChild(btnImage);
			toolbar.appendChild(btn);
		}
	},

	isIE : function(){
		return (this.strpos(navigator.userAgent.toLowerCase(),"msie",0)>0);
	},

	strpos : function( haystack, needle, offset){
	    var i = haystack.indexOf( needle, offset ); // returns -1
	    return i >= 0 ? i : false;
	},

	str_replace : function(search, replace, subject) {
	    var f = search, r = replace, s = subject;
	    var ra = r instanceof Array, sa = s instanceof Array, f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;

	    while (j = 0, i--) {
	        if (s[i]) {
	            while (s[i] = (s[i]+'').split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
	        }
	    };

	    return sa ? s : s[0];
	},

	addInit : function(){
	    var oldQueue = window.onload? window.onload: function() {};
	    window.onload = function() {
	    	eval("MediumEditor.init()");
	        oldQueue();
	    }
	}
}

