// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
//                    All Rights Reserved,  Alen  Pokos                              //
//                        contact :  ghosap@ghosap.com                               //
//    Copying, editing, or deleting of any portion of this script is forbbiden.      //
// Distibution is allowed only with expressed and detailed perrmision from author.   //
//                 For any questions or permisions contact author.                   //
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
//                    Sva prava zadrana ,  Alen  Pokos                              //
//                        Kontakt :  ghosap@ghosap.com                               //
// Svako koriranje, promjena ili brisanje bilo kojeg djela ove skripte je zabranjeno //
//                  Distribucija dozvoljena samo sa odobrenjem autora.               //
//                    Za sva pitanja kontaktirajte autora                            //
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
var config_rte_height = '210';
var config_rte_width = '310';
var config_rte_css = '/dizajn_css/rte_win.css';
var rte_blank = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">	<head>		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />		<link href="/dizajn_css/rte_win.css" rel="styleSheet" type="text/css" />	</head>	<body>	</body></html>';

function rte(toid){
	try{
		rteDraw(toid);
	}catch(err){
		alert("rte -> call:rteDraw, " + err.description);
	}
}
function rteDraw(rteId){
	var to = document.getElementById(rteId);
	//rte dimensions
	var rte_height = (to.style['height'])?to.style['height']:config_rte_height;
	var rte_width = (to.style['width'])?to.style['width']:config_rte_width;
	//rte classname
	var rte_className = to.className;
	
	//draw container
	var rteContainer = document.createElement('DIV');
	rteContainer.className = 'rteContainer';
	rteContainer.id = rteId+'_rteContainer';
	rteContainer.innerHTML = '';
	//draw toolbar
	var rteToolbar = document.createElement('DIV');
	rteToolbar.className = 'rteToolbar';
	rteToolbar.name = 'rteToolbar';
	rteToolbar.id = rteId+'_rteToolbar';
	rteToolbar.innerHTML += '<a href="javascript://" name="Bold" class="rteFuncButton rteIcon rteIconBold" onclick="rteToolbarFunEvent(&#039;'+rteId+'&#039;,this);"><img src="/ico/rte/bold.gif" alt=""></a>';
	rteToolbar.innerHTML += '<a href="javascript://" name="Italic" class="rteFuncButton rteIcon rteIconItalic" onclick="rteToolbarFunEvent(&#039;'+rteId+'&#039;,this);"><img src="/ico/rte/italics.gif" alt=""></a>';
	rteToolbar.innerHTML += '<a href="javascript://" name="Underline" class="rteFuncButton rteIcon rteIconUnderline" onclick="rteToolbarFunEvent(&#039;'+rteId+'&#039;,this);"><img src="/ico/rte/underline.gif" alt=""></a>';
	rteToolbar.innerHTML += '<a href="javascript://" name="Strikethrough" class="rteFuncButton rteIcon rteIconStrikethrough" onclick="rteToolbarFunEvent(&#039;'+rteId+'&#039;,this);"><img src="/ico/rte/strikethrough.gif" alt=""></a>';
	rteToolbar.innerHTML += '<a href="javascript://" name="JustifyLeft" class="rteFuncButton rteIcon rteIconJustifyLeft" onclick="rteToolbarFunEvent(&#039;'+rteId+'&#039;,this);"><img src="/ico/rte/justify_left.gif" alt=""></a>';
	rteToolbar.innerHTML += '<a href="javascript://" name="JustifyCenter" class="rteFuncButton rteIcon rteIconJustifyCenter" onclick="rteToolbarFunEvent(&#039;'+rteId+'&#039;,this);"><img src="/ico/rte/justify_center.gif" alt=""></a>';
	rteToolbar.innerHTML += '<a href="javascript://" name="JustifyRight" class="rteFuncButton rteIcon rteIconJustifyRight" onclick="rteToolbarFunEvent(&#039;'+rteId+'&#039;,this);"><img src="/ico/rte/justify_right.gif" alt=""></a>';
	rteToolbar.innerHTML += '<a href="javascript://" name="JustifyFull" class="rteFuncButton rteIcon rteIconJustifyFull" onclick="rteToolbarFunEvent(&#039;'+rteId+'&#039;,this);"><img src="/ico/rte/justify_full.gif" alt=""></a>';
	rteToolbar.innerHTML += '<a href="javascript://" name="indent" class="rteFuncButton rteIcon rteIconIndent" onclick="rteToolbarFunEvent(&#039;'+rteId+'&#039;,this);"><img src="/ico/rte/indent_right.gif" alt=""></a>';
	rteToolbar.innerHTML += '<a href="javascript://" name="outdent" class="rteFuncButton rteIcon rteIconOutdent" onclick="rteToolbarFunEvent(&#039;'+rteId+'&#039;,this);"><img src="/ico/rte/indent_left.gif" alt=""></a>';
	rteToolbar.innerHTML += '<a href="javascript://" name="InsertOrderedList" class="rteFuncButton rteIcon rteIconInsertOrderedList" onclick="rteToolbarFunEvent(&#039;'+rteId+'&#039;,this);"><img src="/ico/rte/list_ordered.gif" alt=""></a>';
	rteToolbar.innerHTML += '<a href="javascript://" name="InsertUnorderedList" class="rteFuncButton rteIcon rteIconInsertUnorderedList" onclick="rteToolbarFunEvent(&#039;'+rteId+'&#039;,this);"><img src="/ico/rte/list_unordered.gif" alt=""></a>';
	rteToolbar.innerHTML += '<a href="javascript://" name="Subscript" class="rteFuncButton rteIcon rteIconSubscript" onclick="rteToolbarFunEvent(&#039;'+rteId+'&#039;,this);"><img src="/ico/rte/subscript.gif" alt=""></a>';
	rteToolbar.innerHTML += '<a href="javascript://" name="Superscript" class="rteFuncButton rteIcon rteIconSuperscript" onclick="rteToolbarFunEvent(&#039;'+rteId+'&#039;,this);"><img src="/ico/rte/superscript.gif" alt=""></a>';
	rteToolbar.innerHTML += '<a href="javascript://" name="rteSelectFGColor" class="rteFuncButton rteIcon rteIconSelectFGColor" onclick="rteToolbarFunEvent(&#039;'+rteId+'&#039;,this);" title="Select foreground color"><img src="/ico/rte/forecolor.gif" alt=""></a>';
	rteToolbar.innerHTML += '<a href="javascript://" name="rteSelectBGColor" class="rteFuncButton rteIcon rteIconSelectBGColor" onclick="rteToolbarFunEvent(&#039;'+rteId+'&#039;,this);" title="Select background color"><img src="/ico/rte/backcolor.gif" alt=""></a>';
	rteToolbar.innerHTML += '<a href="javascript://" name="rteInsertTable" class="rteFuncButton rteIcon rteIconInsertTable" onclick="rteToolbarFunEvent(&#039;'+rteId+'&#039;,this);" title="Insert Table"><img src="/ico/rte/insert_table.gif" alt=""></a>';
	rteToolbar.innerHTML += '<a href="javascript://" name="rteInsertHyperlink" class="rteFuncButton rteIcon rteIconInsertHyperlink" onclick="rteToolbarFunEvent(&#039;'+rteId+'&#039;,this);" title="Insert Hyperlink"><img src="/ico/rte/insert_hyperlink.gif" alt=""></a>';
	rteToolbar.innerHTML += '<a href="javascript://" name="rteInsertImage" class="rteFuncButton rteIcon rteIconInsertImage" onclick="rteToolbarFunEvent(&#039;'+rteId+'&#039;,this);" title="Insert picture"><img src="/ico/rte/insert_picture.gif" alt=""></a>';
	rteToolbar.innerHTML += '<a href="javascript://" title="Clean up current text" name="rteCleanUp" class="rteFuncButton rteIcon rteCleanUp" onclick="rteToolbarFunEvent(&#039;'+rteId+'&#039;,this);"><img src="/ico/rte/cleanup.gif" alt=""></a>';
	rteToolbar.innerHTML += '<a href="javascript://" title="Remove formating" name="RemoveFormat" class="rteFuncButton rteIcon rteIconRemoveFormat" onclick="rteToolbarFunEvent(&#039;'+rteId+'&#039;,this);"><img src="/ico/rte/removeformat.gif" alt=""></a>';
	rteToolbar.innerHTML += '<br/>';
	rteToolbar.innerHTML += '<a href="javascript://" title="HTML" name="toogleSourceEdit" class="rteFuncButton toogleViewSource" onclick="rteToolbarFunEvent(&#039;'+rteId+'&#039;,this);">View HTML</a>';
	rteToolbar.innerHTML += '<select name="FontSize" class="rteFuncButton rteFontSize" onchange="rteToolbarFunEvent(&#039;'+rteId+'&#039;,this);"><option value="">Font size</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option></select>';
	
	rteContainer.appendChild(rteToolbar);
	
	rteContainer.innerHTML = rteContainer.innerHTML + '<iframe name="'+rteId+'_iframe" id="'+rteId+'_iframe" onload="rteOn(&#039;'+rteId+'&#039;);" frameborder="no" class="'+rte_className+' rte_iframe">'+rte_blank+'</iframe>';
	
	to.style['display']='none';
	to.parentNode.insertBefore(rteContainer,to);
	
	//rteToolbarInit(rteToolbar);
}
/*
function rteToolbarInit(to){
	var tbo = to.childNodes;
	var tbomax = tbo.length;
	for(var i = 0; i < tbomax; i++){
		if(tbo[i].className.match('rteFuncButton')){
			tbo[i].onclick=function(){rteToolbarFunEvent(this);return false;}
		}
	}
}*/
function rte_popup(sPopupFile,sPopupTitle,iWidth,iHeight,sRTEFunc,rteId){
	window.open(sPopupFile+'?rteId='+rteId+'&cmd='+sRTEFunc,'rtePopup','scrollbars=1,resizable=1,location=0,status=0,width=' + iWidth + ',height=' + iHeight);
}
function rteToolbarFunEvent(rteId,bo){
	switch(bo.name){
		case 'toogleSourceEdit':
			toogleSourceEdit(rteId,bo);
		break;
		case 'FontSize':
			if(getRte(rteId).title=='HTML'){return false;}
			rteCmd(rteId,'FontSize',bo.options[bo.selectedIndex].value);
			bo.selectedIndex = 0;
		break;
		case 'rteSelectFGColor':
			if(getRte(rteId).title=='HTML'){return false;}
			rte_popup('/korisnik/rte_popups/colorpicker.php','Select Foreground color',400,400,'rteSelectFGColor',rteId);
		break;
		case 'rteSelectBGColor':
			if(getRte(rteId).title=='HTML'){return false;}
			rte_popup('/korisnik/rte_popups/colorpicker.php','Select Background color',400,400,'rteSelectBGColor',rteId);
		break;
		case 'rteInsertTable':
			if(getRte(rteId).title=='HTML'){return false;}
			rte_popup('/korisnik/rte_popups/inserttable.html','Insert Table',350,250,'rteInsertTable',rteId);
		break;
		case 'rteInsertHyperlink':
			if(getRte(rteId).title=='HTML'){return false;}
			rte_popup('/korisnik/rte_popups/inserthyperlink.php','Insert Hyperlink',700,380,'rteInsertHyperlink',rteId);
		break;
		case 'rteInsertImage':
			if(getRte(rteId).title=='HTML'){return false;}
			rte_popup('/korisnik/rte_popups/insertimage.php','Insert Image',700,380,'rteInsertImage',rteId);
		break;
		case 'rteCleanUp':
			if(getRte(rteId).title=='HTML'){return false;}
			rteCleanUp(rteId);
		break;
		default:
			if(getRte(rteId).title=='HTML'){return false;}
			rteCmd(rteId,bo.name);
	}
	return true;
}
function rteOn(rteId){
	
		var to = document.getElementById(rteId);
		var ro = getRte(rteId);
		var fdoc = iframeDoc(ro);
		
	try{
		fdoc.innerHTLM = rte_blank;
	}catch(err){
		alert("rteOn -> setInnerHTMLDefault Fail, " + err.description);
	}
		
		var fdocBody = (fdoc.body)?fdoc.body:fdoc;
		fdoc = (fdoc.document)?fdoc.document:fdoc; //ie uses iframe.document, mozzila iframe.document.document
		fdocBody = (fdoc.body)?fdoc.body:fdoc;
		
	try{
		fdocBody.innerHTML = to.value;
	}catch(err){
		alert("rteOn -> setInnerHTMLTextarea Fail, " + err.description);
	}	
		
	try{
		fdoc.designMode='on';
	}catch(err){
		alert("rteOn -> designModeFail, " + err.description);
	}	
		
	
	try{
		ro.title='TEXT';
	}catch(err){
		alert("rteOn -> setTitle, " + err.description);
	}	
	
	try{
		if (config_rte_css && false) {
			var css = fdoc.createElement("LINK");
			css.href=config_rte_css;
			css.rel="stylesheet";
			css.type="text/css";
			fdoc.getElementsByTagName("head")[0].appendChild(css);
		}
	}catch(err){
		alert("rteOn -> DefaultCSS FAIL, " + err.description);
	}
	
	try{
		//form listner
		var browserName = navigator.appName;
		var formsCont = document.getElementsByTagName('FORM');
		var formsLen = formsCont.length;
		if (browserName == "Microsoft Internet Explorer") {
			for (var idx=0; idx < formsLen; idx++) {
				formsCont[idx].attachEvent('onsubmit', function() { rteUpdateTextarea(rteId); });
			}
		} else {
			for (var idx=0; idx < formsLen; idx++) {
				formsCont[idx].addEventListener('submit',function () { rteUpdateTextarea(rteId); }, true);
			}
		}
	}catch(err){
		alert("rteOn -> Listner Failed, " + err.description);
	}
}
function getRte(rteId){
	return document.getElementById(rteId+'_iframe');
}
function toogleSourceEdit(rteId,bo){
	var to = document.getElementById(rteId);
	var fdoc = iframeDoc(getRte(rteId));
	var fdocBody = (fdoc.body)?fdoc.body:fdoc;
	fdoc = (fdoc.document)?fdoc.document:fdoc; //ie uses iframe.document, mozzila iframe.document.document
	fdocBody = (fdoc.body)?fdoc.body:fdoc;
	var browserName = navigator.appName;
	
	if (getRte(rteId).title=="TEXT") {
		to.value = fdocBody.innerHTML;
		to.style['display']='block';
		getRte(rteId).style['display']='none';
		
		/*
		if (browserName == "Microsoft Internet Explorer") {
			var iHTML = fdocBody.innerHTML;
			fdocBody.innerText = iHTML;
		}else {
			var html = document.createTextNode(fdocBody.innerHTML);
			fdocBody.innerHTML = "";
			fdocBody.appendChild(html);
		}*/
		
		bo.innerHTML="View TEXT";
		getRte(rteId).title="HTML";
	} else {
		fdocBody.innerHTML = to.value;
		to.style['display']='none';
		getRte(rteId).style['display']='block';
		/*
		if (browserName == "Microsoft Internet Explorer") {
			var iText = fdocBody.innerText;
			fdocBody.innerHTML = iText;
		}else {
			var html = fdocBody.ownerDocument.createRange();
			html.selectNodeContents(fdocBody);
			fdocBody.innerHTML = html.toString();
		}*/
		bo.innerHTML="View HTML";
		getRte(rteId).title="TEXT";
	}
}
function rteCmd(rteId,cmd,parm){
	if (cmd.indexOf('<')==0){
		parm=cmd;
		cmd="FormatBlock";
	}
	var fdoc = iframeDoc(getRte(rteId));
	fdoc = (fdoc.document)?fdoc.document:fdoc; //ie uses iframe.document, mozzila iframe.document.document
	fdoc.execCommand(cmd,false,parm);

}
function rteInsertHtml(rteId,html){
    //ro.focus();
	var ro = iframeDoc(getRte(rteId));
	ro = (ro.document)?ro.document:ro; //ie uses iframe.document, mozzila iframe.document.document
	if(html.length<1){return false;}
	var agt=navigator.userAgent.toLowerCase();
	var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1)) ? 1 : 0;
	if (ro.selection && ro.selection.createRange && is_ie) {
		/*var oRng = ro.selection.createRange();
		oRng.pasteHTML(html);
		oRng.collapse(false);
		oRng.select();*/
		var oRng = ro.selection.createRange();
		
		try{
			if(oRng.htmlText.length<1){
				ro.body.innerHTML += html;
				return;
			}
		}catch(err){
			alert("insert -> prepAlter FAILED, " + err.description);
		}
		
		try{
			oRng.pasteHTML(html);
		}catch(err){
			alert("insert -> paste FAILED, " + err.description);
		}
		try{
			oRng.collapse(false);
		}catch(err){
			alert("insert -> collapse FAILED, " + err.description);
		}
		try{
			oRng.select();
		}catch(err){
			alert("insert -> select FAILED, " + err.description);
		}
	} else {
		try{
			ro.execCommand('insertHTML', false, html);
		}catch(e){
			alert("Your browser doesn't propery support this JavaScript option !");
		}
	}
	
   /* if (document.all && (oRng = ro.selection.createRange())) {
        //var oRng = ro.selection.createRange();
        oRng.pasteHTML(html);
        oRng.collapse(false);
        oRng.select();
    } else {
        ro.execCommand('insertHTML', false, html);
    }*/
}
function rteCleanUp(rteId){
	var fdoc = iframeDoc(getRte(rteId));
	var fdocBody = (fdoc.body)?fdoc.body:fdoc;
	fdoc = (fdoc.document)?fdoc.document:fdoc; //ie uses iframe.document, mozzila iframe.document.document
	fdocBody = (fdoc.body)?fdoc.body:fdoc;
	
	fdoc.execCommand("removeformat",false,null);
	//var h=fdocBody.innerHTML;
	
	/*var cstrict=confirm('Remove all styles and classes?');

	if (cstrict){ 
		h=h.replace(/<\/?(SPAN|DEL|INS|U|DIR)[^>]*>/gi, "")
		.replace(/\b(CLASS|STYLE)=\"[^\"]*\"/gi, "")
		.replace(/\b(CLASS|STYLE)=\w+/gi, "");
	}
	
	h=h.replace(/<\?FONT[^>]*>/gi, "");
	h=h.replace(/<\/?(FONT|SPAN|COL|XML|ST1|SHAPE|V:|O:|F:|F |PATH|LOCK|IMAGEDATA|STROKE|FORMULAS)[^>]*>/gi, "")
	.replace(/\bCLASS=\"?MSO\w*\"?/gi, "")
	.replace(/[]/g,'-') //long 
	.replace(/[]/g, "'") //single smartquotes  
	.replace(/[]/g, '"') //double smartquotes 
	.replace(/align="?justify"?/gi, "") //justify sends some browsers mad
	*/
	//.replace(/<(TABLE|TD|TH|COL)(.*)(WIDTH|HEIGHT)=["'0-9A-Z]*/gi, "<$1$2") //no fixed size tables (%OK) [^A-Za-z>]
	//.replace(/<([^>]+)>\s*<\/\1>/gi, ""); //empty tag
	
	var D=fdocBody.innerHTML;
	// make one line
        D = D.replace(/\r\n/g, '\[br\]').
            replace(/\n/g, ' ').
            replace(/\r/g, ' ').
            replace(/\&nbsp\;/g,' ');

        // keep tags, strip attributes
        D = D.replace(/ class=[^\s|>]*/gi,'').
            //replace(/<p [^>]*TEXT-ALIGN: justify[^>]*>/gi,'<p align="justify">').
            replace(/ style=\"[^>]*\"/gi,'').
            replace(/ align=[^\s|>]*/gi,'');

        //clean up tags
        D = D.replace(/<b [^>]*>/gi,'<b>').
            replace(/<i [^>]*>/gi,'<i>').
            replace(/<li [^>]*>/gi,'<li>').
            replace(/<ul [^>]*>/gi,'<ul>');

        // replace outdated tags
        D = D.replace(/<b>/gi,'<strong>').
            replace(/<\/b>/gi,'</strong>');

        // mozilla doesn't like <em> tags
        D = D.replace(/<em>/gi,'<i>').
            replace(/<\/em>/gi,'</i>');

        // kill unwanted tags
        D = D.replace(/<\?xml:[^>]*>/g, '').       // Word xml
            replace(/<\/?st1:[^>]*>/g,'').     // Word SmartTags
            replace(/<\/?[a-z]\:[^>]*>/g,'').  // All other funny Word non-HTML stuff
            replace(/<\/?font[^>]*>/gi,'').    // Disable if you want to keep font formatting
            replace(/<\/?span[^>]*>/gi,' ').
            replace(/<\/?div[^>]*>/gi,' ').
            replace(/<\/?pre[^>]*>/gi,' ').
            replace(/<(\/?)(h[1-6]+)[^>]*>/gi,'<$1$2>');

        // to get rid off silly word generated tags.
        D = D.replace(/<!--\[[^\]]*\]-->/gi,' ');

        //remove empty tags
        //D = D.replace(/<strong><\/strong>/gi,'').
        //replace(/<i><\/i>/gi,'').
        //replace(/<P[^>]*><\/P>/gi,'');
        D = D.replace(/<h[1-6]+>\s?<\/h[1-6]+>/gi, ''); // Remove empty headings

        // nuke double tags
        oldlen = D.length + 1;
        while(oldlen > D.length) {
            oldlen = D.length;
            // join us now and free the tags, we'll be free hackers, we'll be free... ;-)
            D = D.replace(/<([a-z][a-z]*)> *<\/\1>/gi,' ').
                replace(/<([a-z][a-z]*)> *<([a-z][^>]*)> *<\/\1>/gi,'<$2>');
        }
        D = D.replace(/<([a-z][a-z]*)><\1>/gi,'<$1>').
            replace(/<\/([a-z][a-z]*)><\/\1>/gi,'<\/$1>');

        // nuke double spaces
        D = D.replace(/  */gi,' ');

        // Split into lines and remove
        // empty lines and add carriage returns back
        var splitter  = /\[br\]/g;
        var emptyLine = /^\s+\s+$/g;
        var strHTML   = '';
        var toLines   = D.split(splitter);
        for (var i = 0; i < toLines.length; i++) {
            var line = toLines[i];
            if (line.length < 1) {
                continue;
            }

            if (emptyLine.test(line)) {
                continue;
            }

            line = line.replace(/^\s+\s+$/g, '');
            strHTML += line + '\n';
        }
        D = strHTML;
        strHTML = '';
	
	fdocBody.innerHTML=D;
	//fdocBody.innerHTML=h;
}
function rteUpdateTextarea(rteId){
	var fdoc = iframeDoc(getRte(rteId));
	var fdocBody = (fdoc.body)?fdoc.body:fdoc;
	fdoc = (fdoc.document)?fdoc.document:fdoc; //ie uses iframe.document, mozzila iframe.document.document
	fdocBody = (fdoc.body)?fdoc.body:fdoc;
	
	if(getRte(rteId).title=='HTML'){
	}else{
		document.getElementById(rteId).value = fdocBody.innerHTML;
	}
	
}
function boToif(bo){
	return retRTEIframe(bo.parentNode.parentNode.getElementsByTagName('IFRAME'));
}
function retRTEIframe(fa){
	for(var i=0;i<fa.length;i++){
		if(fa[i].name){if(fa[i].name=='rte_iframe'){return fa[i];}}
	}
}
function iframeDoc(i){
	if (i.contentDocument) {
		return i.contentDocument; 
	} else if (i.contentWindow) {
		return i.contentWindow;
	} else if (i.document) {
		return i.document;
	}
	return false;
}