/* 
Zbig Rich Text Area
Written by Mike Rumble, Summer 2006.
USAGE : 
<script type="text/javascript">
new Zbig.RichTextEditorForm('form1', {ul: true, ol: true, only: 'editable', callback: function(value){ alert(value); });
</script>
*/

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}


if(!Zbig) var Zbig = {};

Zbig.RichTextEditorForm = Class.create();
Zbig.RichTextEditorForm.prototype = {
    initialize : function(element, options){
        this.options = Object.extend({
            bold: true,
            italic : true,
            link: true,
            width: '500px',
            height: '200px',
            horizontalrule :true,
            insertimage : true
        }, options || {});
        this.element = $(element);
        this.editors = Array();
        var textareas = this.element.getElementsByTagName('textarea');
        $A(textareas).each(function(textarea){
            if((this.options.only&&Element.hasClassName($(textarea), this.options.only))||!this.options.only){
                this.editors[this.editors.length] = new Zbig.RichTextEditor($(textarea), this.options);
            }
        }.bind(this));
        this.addListeners();
    },
    addListeners : function(){
        Event.observe(this.element, 'submit', this.save.bindAsEventListener(this));
    },
    save : function(){
        $A(this.editors).each(function(editor){
            editor.save();
        });
    }
}


Zbig.RichTextEditor = Class.create();
Zbig.RichTextEditor.prototype = {
    initialize : function(element, options) {
        this.options = Object.extend({
            bold: true,
            italic : true,
            link: true,
            unlink: true,
            width: '500px',
            height: '300px',
            horizontalrule :true,
            insertimage : true,
            speciallink : true
        }, options || {});
        this.element = $(element);
        this.parent = this.element.parentNode;
        this.HTML = this.element.innerHTML;
        this.iframe = document.createElement('iframe');
        this.iframe.className = 'w-iframe';
        this.iframe.id = this.element.id+"_rte";
        this.iframe.style.width = this.options.width;
        this.iframe.style.height = this.options.height;
        this.rte = document.createElement('div');
        this.rte.className = 'w-rte';
        var rteInner = document.createElement('div');
        this.controls();
        this.rte.appendChild(this.controlstrip);
        this.rte.appendChild(rteInner);
        rteInner.appendChild(this.iframe);
  	
        this.parent.insertBefore(this.rte, this.element.nextSibling);
        this.element.style.display='none';
        this.setup();
    },
    setup : function(){
        this.HTML = this.HTML.replace(/&gt;/g, '>');
        this.HTML = this.HTML.replace(/&lt;/g, '<');
        if(this.iframe.document){
            var index = document.frames.length - 1;
            document.frames[index].document.designMode="On";
            document.frames[index].document.open();
            document.frames[index].document.write(this.HTML);
            document.frames[index].document.close();
            this.doc = document.frames[index].document
            this.doc.body.style.border = '1px solid #A7A6AA';
            this.doc.body.style.fontFamily = 'Arial';
        }else{
            this.doc = this.iframe.contentDocument;
            this.doc.open();
            this.doc.write(this.HTML);
            this.doc.close();
            this.doc.body.style.cursor = 'text';
            this.doc.body.style.height = '100%';
            this.doc.body.style.fontFamily = 'Arial';
            this.iframe.style.border = '1px solid #ccc';
            this.iframe.height -= 2;
            this.iframe.width -= 2;
        }
        this.doc.body.style.fontSize = '12px';
        this.doc.body.style.margin = '0px';
        this.doc.designMode="On";
        this.doc.body.style.padding = '0px';
        if(!document.all){
            this.doc.execCommand('styleWithCSS', false, false);
        }
        this.addListeners();
    },
    addListeners : function(){
        if(this.options.bold == true){
            Event.observe(this.boldButton, 'click', this.bold.bindAsEventListener(this));
        }
        if(this.options.italic == true){
            Event.observe(this.italicButton, 'click', this.italic.bindAsEventListener(this));
        }
        if(this.options.link == true){
            Event.observe(this.linkButton, 'click', this.link.bindAsEventListener(this));
        }
        if(this.options.ul == true){
            Event.observe(this.ulButton, 'click', this.ul.bindAsEventListener(this));
        }
        if(this.options.ol == true){
            Event.observe(this.olButton, 'click', this.ol.bindAsEventListener(this));
        }
        if(this.options.strike == true){
            Event.observe(this.strikeButton, 'click', this.strike.bindAsEventListener(this));
        }
        if(this.options.superscript == true){
            Event.observe(this.superscriptButton, 'click', this.superscript.bindAsEventListener(this));
        }
        if(this.options.subscript == true){
            Event.observe(this.subscriptButton, 'click', this.subscript.bindAsEventListener(this));
        }
        if(this.options.underline == true){
            Event.observe(this.underlineButton, 'click', this.underline.bindAsEventListener(this));
        }
        if(this.options.unlink == true){
            Event.observe(this.unlinkButton, 'click', this.unlink.bindAsEventListener(this));
        }
        if(this.options.horizontalrule == true){
            Event.observe(this.horizontalruleButton, 'click', this.horizontalrule.bindAsEventListener(this));
        }
        if(this.options.insertimage == true){
            Event.observe(this.insertimageButton, 'click', this.insertimage.bindAsEventListener(this));
        }
        if(this.options.speciallink == true){
            Event.observe(this.speciallinkButton, 'click', this.speciallink.bindAsEventListener(this));
        }

    },
    removeListeners : function(){
	
    },
    inputhidden : function(hiddenname){
        var myhidden = document.createElement('input');
        myhidden.id = hiddenname;
        myhidden.setAttribute("type", "hidden");
        myhidden.setAttribute("value", "");

        return myhidden;
    },
    button : function(options){
        var button = document.createElement('a');
        button.id = options.id;
        button.className = 'w-controlbutton';
        button.href = '#';
        button.title = options.title;
        var text = document.createTextNode(options.value);
        button.appendChild(text);
        return button;
    },
    
    controls : function(){
        this.controlstrip = document.createElement('div');
        this.controlstrip.style.width = this.options.width;
        this.controlstrip.className = 'w-controlstrip';
        if(this.options.bold == true){
            this.boldButton = this.button({
                id: 'bold',
                title: 'Bold',
                value: 'B'
            });
            this.controlstrip.appendChild(this.boldButton);
        }
        if(this.options.italic == true){
            this.italicButton = this.button({
                id: 'italic',
                title: 'Italic',
                value: 'I'
            });
            this.controlstrip.appendChild(this.italicButton);
        }
        if(this.options.underline == true){
            this.underlineButton = this.button({
                id: 'underline',
                title: 'Underlinke',
                value: 'Underline'
            });
            this.controlstrip.appendChild(this.underlineButton);
        }
        if(this.options.strike == true){
            this.strikeButton = this.button({
                id: 'strikethrough',
                title: 'Strike',
                value: 'Strike'
            });
            this.controlstrip.appendChild(this.strikeButton);
        }
        if(this.options.link == true){
            this.linkButton = this.button({
                id: 'link',
                title: 'Insert link',
                value: 'A'
            });
            this.controlstrip.appendChild(this.linkButton);
        }
        if(this.options.unlink == true){
            this.unlinkButton = this.button({
                id: 'unlink',
                title: 'Unlink',
                value: 'Unlink'
            });
            this.controlstrip.appendChild(this.unlinkButton);
        }
        if(this.options.ul == true){
            this.ulButton = this.button({
                id: 'insertunorderedlist',
                title: 'Insert Unordered List',
                value: 'UL'
            });
            this.controlstrip.appendChild(this.ulButton);
        }
        if(this.options.ol == true){
            this.olButton = this.button({
                id: 'insertorderedlist',
                title: 'Insert Ordered List',
                value: 'OL'
            });
            this.controlstrip.appendChild(this.olButton);
        }
        if(this.options.subscript == true){
            this.subscriptButton = this.button({
                id: 'subscript',
                title: 'Subscript',
                value: 'Subscript'
            });
            this.controlstrip.appendChild(this.subscriptButton);
        }
        if(this.options.superscript == true){
            this.superscriptButton = this.button({
                id: 'superscript',
                title: 'Superscript',
                value: 'Superscript'
            });
            this.controlstrip.appendChild(this.superscriptButton);
        }
        if(this.options.horizontalrule == true){
            this.horizontalruleButton = this.button({
                id: 'horizontalrule',
                title: 'Horizontalrule',
                value: 'Horizontalrule'
            });
            this.controlstrip.appendChild(this.horizontalruleButton);
        }
        if(this.options.insertimage == true){
            this.insertimageButton = this.button({
                id: 'insertimage',
                title: 'Insertimage',
                value: 'Insertimage'
            });
            this.controlstrip.appendChild(this.insertimageButton);
        }
         if(this.options.speciallink == true){
            this.speciallinkButton = this.button({
                id: 'speciallink',
                title: 'speciallink',
                value: 'speciallink'
            });
            this.controlstrip.appendChild(this.speciallinkButton);
        }
        this.controlstrip.appendChild(this.inputhidden('hidden_qid'));
        this.controlstrip.appendChild(this.inputhidden('hidden_cat'));
        this.controlstrip.appendChild(this.inputhidden('hidden_sub'));
    },
    command : function(command, options){
        return this.doc.execCommand(command, false, options);
    },
    bold : function(ev){
        Event.stop(ev);
        this.command("bold", null);
    },
    italic : function(ev){
        Event.stop(ev);
        this.command("italic", null);
    },
    ol : function(ev){
        Event.stop(ev);
        this.command("insertorderedlist", null);
    },
    ul : function(ev){
        Event.stop(ev);
        this.command("insertunorderedlist", null);
    },
    strike : function(ev){
        Event.stop(ev);
        this.command("strikethrough", null);
    },
    subscript : function(ev){
        Event.stop(ev);
        this.command("subscript", null);
    },
    superscript : function(ev){
        Event.stop(ev);
        this.command("superscript", null);
    },
    underline : function(ev){
        Event.stop(ev);
        this.command("underline", null);
    },
    unlink : function(ev){
        Event.stop(ev);
        this.command("unlink", null);
    },
    horizontalrule : function(ev){

        Event.stop(ev);
        this.command("inserthorizontalrule", null);
    },
    speciallink : function(ev){
        Event.stop(ev);
        var q1 = "";
        
        if (window.getSelection) { // Firefox und co.
            q1 = this.doc.getSelection();
        } else if (document.selection) { // Internet Explorer
            s = this.doc.selection; // Hier stosse ich auch auf einen Fehler...
            q1 = s.createRange().text;
        }
        
        q1 = q1.trim();
        var q = prompt("Please enter a keyword or use selected:", q1);
        //this.myRef = window.open('http://whyzz3.local/home/speciallink/q/' + q1,'mywin','left=20,top=20,width=500,height=500,toolbar=1,resizable=0,scrollbars=1');

        //Event.observe(this.myRef, 'beforeunload', this.speciallinkinsert.bindAsEventListener(this));
        /*
        var win = new Window({className: "mac_os_x",
            title: "Choose one question",
            top:70, left:100, width:300, height:200,
            okLabel: "Close",
            url: "http://whyzz3.local/home/speciallink/q/" + q1,
            showEffectOptions: {duration:1.5}}
        );
            win.show();
*/
        
        Dialog.alert(
            {url: "/home/speciallink/q/" + q, options: {method: 'post'}},
            {className: "mac_os_x", top:70, left:100, width:500, height:400,
                okLabel: "just close"
                
            });
            
       

        
    },
    speciallinkinsert : function(ev){
        Event.stop(ev);
        alert('poszlo !!');
        var qid = $('hidden_qid').value;
        var cat = $('hidden_cat').value;
        var sub = $('hidden_sub').value;

        var theurl = "/answer/detail/category/" + cat + "/subcategory/" + sub + "/qid/" + qid;
        //alert(theurl);
        //this.myRef.close();
        
        if(theurl!=null&&theurl!=""){

            this.command("createLink",theurl);
        }else{
            return false;
        }
    },
    insertimage : function(ev){
        Event.stop(ev);
        var theurl = prompt("Please enter a URL:", "");
        if(theurl!=null&&theurl!=""){
            com = this.command("inserttable",theurl);
            //img = this.doc.body.getElementsByTagName("img")[0];
            //img.setAttribute("id","image1");
            //img.setAttribute("align","left");
        }else{
            return false;
        }
    },
    link : function(ev){

        Event.stop(ev);
        
        var theurl = prompt("Please enter a URL:", $('hidden_qid').value);
        if(theurl!=null&&theurl!=""){
            
            this.command("createLink",theurl);
            $('hidden_qid').value = "";
        }else{
            $('hidden_qid').value = "";
            return false;
        }
    },
    save : function(){
        var content = this.clean_html(this.doc.body.innerHTML);
        this.element.value = content;
        if(this.options.callback){
            this.options.callback(content);
        }
    },
    clean_html : function(html){
        // Ensure all tag names are lowercase
        var regex = /(<[^>\s]*)(\w)/gi
        var matches = html.match(regex);
        if(matches){
            for(i=0; i < matches.length; i++){
                html = html.replace(matches[i], matches[i].toLowerCase());
            }
        }
        // Ensure all attribute names are lowercase
        var regex = /([^>\s]*)(\w=)/gi
        var matches = html.match(regex);
        if(matches){
            for(i=0; i < matches.length; i++){
                html = html.replace(matches[i], matches[i].toLowerCase());
            }
        }
        // Remove non-standard tags...
        html = html.replace(/<o:p>\s*<\/o:p>/g, "") ;
        html = html.replace(/<o:p>.*?<\/o:p>/g, "&nbsp;") ;
        html = html.replace( /\s*MARGIN: 0cm 0cm 0pt\s*;/gi, "" ) ;
        html = html.replace( /\s*MARGIN: 0cm 0cm 0pt\s*"/gi, "\"" ) ;
        html = html.replace( /\s*TEXT-INDENT: 0cm\s*;/gi, "" ) ;
        html = html.replace( /\s*TEXT-INDENT: 0cm\s*"/gi, "\"" ) ;
        html = html.replace( /\s*TEXT-ALIGN: [^\s;]+;?"/gi, "\"" ) ;
        html = html.replace( /\s*PAGE-BREAK-BEFORE: [^\s;]+;?"/gi, "\"" ) ;
        html = html.replace( /\s*FONT-VARIANT: [^\s;]+;?"/gi, "\"" ) ;
        html = html.replace( /\s*tab-stops:[^;"]*;?/gi, "" ) ;
        html = html.replace( /\s*tab-stops:[^"]*/gi, "" ) ;
        html = html.replace( /\s*face="[^"]*"/gi, "" ) ;
        html = html.replace( /\s*face=[^ >]*/gi, "" ) ;
        html = html.replace( /\s*FONT-FAMILY:[^;"]*;?/gi, "" ) ;
        html = html.replace(/<(\w[^>]*) class=([^ |>]*)([^>]*)/gi, "<$1$3") ;
        html = html.replace( /<(\w[^>]*) style="([^\"]*)"([^>]*)/gi, "<$1$3" ) ;
        html = html.replace( /\s*style="\s*"/gi, '' ) ;
        html = html.replace( /<SPAN\s*[^>]*>\s*&nbsp;\s*<\/SPAN>/gi, '&nbsp;' ) ;
        html = html.replace( /<SPAN\s*[^>]*><\/SPAN>/gi, '' ) ;
        html = html.replace(/<(\w[^>]*) lang=([^ |>]*)([^>]*)/gi, "<$1$3") ;
        html = html.replace( /<SPAN\s*>(.*?)<\/SPAN>/gi, '$1' ) ;
        html = html.replace( /<FONT\s*>(.*?)<\/FONT>/gi, '$1' ) ;
        html = html.replace(/<\\?\?xml[^>]*>/gi, "") ;
        html = html.replace(/<\/?\w+:[^>]*>/gi, "") ;

        
        return html;
    }
}

function findSelection() {
    if (window.getSelection) { // Firefox und co.
        var selection = instance.contentWindow.getSelection();
        //var selection = document.getElementById("_rte").getSelection();
        var selectedRange = selection.getRangeAt(0);
        alert(selectedRange.cloneRange());
        //return a;
    } else if (document.selection) { // Internet Explorer
        var selection = document.getElementById("_rte").selection; // Hier stosse ich auch auf einen Fehler...
        return selection.createRange();
    }
}

function win(){
	var win = new Window({className: "mac_os_x", width:400, height:350, resizable: true,
		title: "Titel und so", showEffect:Effect.BlindDown, hideEffect: Effect.SwitchOff,
		url: "http://www.google.de"});

	win.show();

}


