QuickEdit = Class.create();

QuickEdit.instances = new Array();

Object.extend(QuickEdit.prototype, {
    
    initialize: function(element, cid, name, disableToolbar) {
        
        QuickEdit.instances.push(this);
        
        this.element   = $(element);
        this.name      = name;
        this.eid       = this.element.id;
        this.cid       = cid;
        this.parent    = this.element.parentNode;
        this.editMode  = false;
        this.disableToolbar = disableToolbar || false;
        
        this.contentLocker = new ContentLocker(this.cid);
        
        // iframe generieren
        this.frm = this.element.parentNode.appendChild(document.createElement('iframe'));
        
        // id + name vergeben
        this.frm.id    = 'frm_' + this.eid + this.name;
        this.frm.name  = 'frm_' + this.eid + this.name;
        
        // allgemeine styles + attribute setzen
        this.frm.style.width = this.element.offsetWidth - 2 + 'px';
        this.frm.style.padding  = '0px';
        this.frm.style.margin   = '0px';
        this.frm.style.border   = '0px none';
        this.frm.setAttribute('border',       '0');
        this.frm.setAttribute('frameborder',  '0');
        this.frm.setAttribute('marginWidth',  '0');
        this.frm.setAttribute('marginHeight', '0');
        this.frm.setAttribute('leftMargin',   '0');
        this.frm.setAttribute('topMargin',    '0');
        this.frm.setAttribute('allowtransparency', 'true');
        this.frm.setAttribute('scrolling',    'no');
        
        // randmarkierung des Elementes,  zur Optischen Identifizierung von Editierbarem Content
        this.element.style.borderLeft = '2px dotted #00498C';
        this.element.style.paddingLeft = '2px';
        
        // wir brauchen wegen IE das frame mittels document.getElementById + mittels document.frames
        this.frmObj = this.frm;
        if (document.all) {
            this.frm = document.frames[this.frm.name];
            this.getDoc().designMode = 'On';
        }
        
        // basis-seite laden
        this.getDoc().location.href = qeCfg['base_href'] + 'quickEdit_blank.html';
        
        this.frmObj.style.display = 'none';
        
        // event-callbacks binden
        this.eventShow  = this.showEditable.bind(this);
        this.eventHide  = this.hideEditable.bind(this);
        this.eventKeyUp = this.updateSize.bind(this);
        
        this.eventKeyPress = QuickEdit.Shortcuts.handleKey.bind(QuickEdit.Shortcuts);
        
        // doppelklick-event auf element
        Event.observe(this.element, 'dblclick', this.eventShow);
    },
    
    updateSize: function() {
        // iframe höhe setzen
        if (document.all) {
            this.frmObj.style.height = this.getDoc().body.scrollHeight * 1.1 + 'px';
        } else {
            this.frmObj.style.height = this.getDoc().body.scrollHeight + 1 +
                parseInt(this.getDoc().body.style.marginBottom) +
                parseInt(this.getDoc().body.style.marginTop) + 'px';
        }
        
        // zum linken oberen ecken springen
        if (this.frm.scrollTo) {
            this.frm.scrollTo(0, 0);
        } else {
            if (this.contentWindow.scrollTo) {
                this.contentWindow.scrollTo(0, 0);
            }
        }
    },
    
    updateStyles: function() {
        // styles nur das erste mal ins iframe schreiben
        if (!this.doc) {
            
            if (this.element.className) {
                Element.Class.add(this.getDoc().body, this.element.className, 'bodyclass');
            }

            this.getDoc().body.id = this.element.id;

            for (var s = 0; s < document.styleSheets.length; s++) {
                if (document.all) {
                    for (var r = 0; r < document.styleSheets[s].rules.length; r++) {
                        if (document.styleSheets[s].rules[r].selectorText && document.styleSheets[s].rules[r].selectorText.toUpperCase() == this.element.nodeName) {
                            this.getDoc().styleSheets[0].addRule('body', document.styleSheets[s].rules[r].style.cssText);
                        }
                    }
                } else {
                    for (var r = 0; r < document.styleSheets[s].cssRules.length; r++) {
                        if (document.styleSheets[s].cssRules[r].selectorText && document.styleSheets[s].cssRules[r].selectorText.toUpperCase() == this.element.nodeName) {
                            this.getDoc().body.style.cssText = this.getDoc().body.style.cssText + document.styleSheets[s].cssRules[r].style.cssText;
                        }
                    }
                }
            }

            if (Element.getStyle(this.element, 'font')) {
                this.getDoc().body.style.font = Element.getStyle(this.element, 'font');
            }

            if (Element.getStyle(this.element, 'font-size')) {

                var fs = Element.getStyle(this.element, 'font-size');

                if (fs.indexOf('em') > -1) {

                    if ($(qeCfg['container'])) {
                        if (Element.getStyle(this.element, 'font-size') != Element.getStyle($(qeCfg['container']), 'font-size')) {
                            this.getDoc().body.style.fontSize = 
                                parseFloat(Element.getStyle($(qeCfg['container']), 'font-size')) * 
                                parseFloat(Element.getStyle(document.body, 'font-size')) * 
                                parseFloat(Element.getStyle(this.element, 'font-size')) + 'pt';
                        } else {
                            this.getDoc().body.style.fontSize = 
                                parseFloat(Element.getStyle($(qeCfg['container']), 'font-size')) * 
                                parseFloat(Element.getStyle(document.body, 'font-size')) + 'pt';
                        }
                    } else {
                        this.getDoc().body.style.fontSize = 
                            parseFloat(Element.getStyle(document.body, 'font-size')) + 'pt';
                    }
                } else {
                    this.getDoc().body.style.fontSize = Element.getStyle(this.element, 'font-size');
                }
            }
            
            if (Element.getStyle(this.element, 'font-weight')) {
                this.getDoc().body.style.fontWeight    = Element.getStyle(this.element, 'font-weight');
            }
            
            if (Element.getStyle(this.element, 'line-height')) {
                this.getDoc().body.style.lineHeight    = Element.getStyle(this.element, 'line-height');
            }
            
            if (Element.getStyle(this.element, 'padding-top')) {
                this.getDoc().body.style.paddingTop    = Element.getStyle(this.element, 'padding-top');
            }
            
            if (Element.getStyle(this.element, 'padding-right')) {
                this.getDoc().body.style.paddingRight  = Element.getStyle(this.element, 'padding-right');
            }
            
            if (Element.getStyle(this.element, 'padding-bottom')) {
                this.getDoc().body.style.paddingBottom = Element.getStyle(this.element, 'padding-bottom');
            }
            
            if (Element.getStyle(this.element, 'padding-left')) {
                this.getDoc().body.style.paddingLeft   = Element.getStyle(this.element, 'padding-left');
            }
            
            if (Element.getStyle(this.element, 'margin-top')) {
                this.getDoc().body.style.marginTop     = Element.getStyle(this.element, 'margin-top');
            }
            
            if (Element.getStyle(this.element, 'margin-right')) {
                this.getDoc().body.style.marginRight   = Element.getStyle(this.element, 'margin-right');
            }
            
            if (Element.getStyle(this.element, 'margin-bottom')) {
                this.getDoc().body.style.marginBottom  = Element.getStyle(this.element, 'margin-bottom');
            }
            
            if (Element.getStyle(this.element, 'margin-left')) {
                this.getDoc().body.style.marginLeft    = Element.getStyle(this.element, 'margin-left');
            }
            
            this.getDoc().body.style.border = '2px inset #333333';
        }
        
        // IE braucht für gewissen dinge frame.document
        if (document.all) {
            this.doc = this.frm.document;
        } else {
            this.doc = this.getDoc();
        }
        
        if ($(this.eid + '_button')) {
            Element.show(this.eid + '_button');
            Event.observe($(this.eid + '_button'), 'click', this.eventHide);
        }
        
        // doppelklick-event auf frame
        Event.observe(this.doc, 'dblclick', this.eventHide);
        
        // keyup-event auf frame
        Event.observe(this.doc, 'keypress', this.eventKeyUp);
        
        // keypress-event auf frame
        Event.observe(this.doc, 'keypress', this.eventKeyPress);
    },
    
    showEditable: function() {
        var fieldValue = '';
        if ((fieldValue = this.contentLocker.readField(this.cid, this.name, {lock: true, onTimeout: this.hideEditable.bind(this)}, this.disableToolbar)) === false)
        {
            //alert(fieldValue);
            var fieldValue2 = this.contentLocker.readField(this.cid, 'checkout_username',{});
            if( fieldValue2 != false)
            {
                alert('Der Textbaustein wird zur Zeit von "'+ fieldValue2 +'" bearbeitet.\n');
            }
            else
            {
                alert('Der Textbaustein ist zur Zeit von einem anderen Benutzer in bearbeitung.\n');
            }
            return;
        }
        // Set the Base href to the base href of the current document
        if (document.getElementsByTagName('base') && document.getElementsByTagName('base')[0])
        {
            if (document.getElementsByTagName('base')[0].href)
            {
                if (this.getDoc().getElementsByTagName('base') && this.getDoc().getElementsByTagName('base')[0])
                {
                    this.getDoc().getElementsByTagName('base')[0].href = document.getElementsByTagName('base')[0].href;
                }
            }
        }

	   this.getDoc().body.innerHTML = fieldValue;

        for (var i = 0; i < QuickEdit.instances.length; i++) {
            if (QuickEdit.instances[i] !== this) {
                QuickEdit.instances[i].hideEditable();
            }
        }
        if (!this.disableToolbar) {
            document.tb.show(this);
        }

        this.updateStyles();

        this.element.style.display = 'none';
        this.frmObj.style.display = 'block';
        this.updateSize();
        this.getDoc().designMode = 'On';
        if (!document.all) {
            // firefox sagen, er soll wie IE auch hauptsächlich font-tags statt css verwenden
            this.getDoc().execCommand('useCSS', false, true);
        }
        
        this.editMode = true;
        this.updateSize();
    },
    
    hideEditable: function() {
        if (!this.editMode) {
            return;
        }
        
        // content speichern
        if (this.contentLocker.saveField(this.cid, this.name, this.getDoc().body.innerHTML, this.disableToolbar)) {
            this.element.innerHTML = this.getDoc().body.innerHTML;
        }
        
        Element.hide(this.frmObj);
        if ($(this.eid + '_button')) {
            Element.hide(this.eid + '_button');
        }
        document.tb.hide();
        
        this.editMode = false;
        
        this.element.style.display = 'block';
        this.frmObj.style.display = 'none';
        
        // IE-Bug:
        // wenn diese icms-spezifischen tags sowie alle kommentare und unnützen white-spaces
        // nicht gelöscht werden, wird plötzlich ein zusätzlicher umbruch erzeugt
        var elm = this.element.previousSibling;
        while (elm) {
            var nelm = elm.previousSibling;
            if (elm.nodeName == 'WRITEACCESS')  {elm.parentNode.removeChild(elm);}
            if (elm.nodeName == '/WRITEACCESS') {elm.parentNode.removeChild(elm);}
            if (elm.nodeName == 'BODYTEXT1')    {elm.parentNode.removeChild(elm);}
            if (elm.nodeName == '/BODYTEXT1')   {elm.parentNode.removeChild(elm);}
            if (elm.nodeName == 'PICTURE1')     {elm.parentNode.removeChild(elm);}
            if (elm.nodeName == '/PICTURE1')    {elm.parentNode.removeChild(elm);}
            if (elm.nodeName == 'SUBTITLE')     {elm.parentNode.removeChild(elm);}
            if (elm.nodeName == '/SUBTITLE')    {elm.parentNode.removeChild(elm);}
            if (elm.nodeName == 'TOPTITLE')     {elm.parentNode.removeChild(elm);}
            if (elm.nodeName == '/TOPTITLE')    {elm.parentNode.removeChild(elm);}
            if (elm.nodeName == '#comment')     {elm.parentNode.removeChild(elm);}
            
            if (elm.nodeName == '#text' && elm.nodeValue.replace(/^\s$/, '') == '') {
                elm.parentNode.removeChild(elm);
            }
            
            elm = nelm;
        }
    },
    
    getDoc: function() {
        // contentWindow & contentDocument setzen
        // contentDocument wird gleich zurückgegeben
        
        if (document.all) {
            this.contentDocument = this.frm.window.document;
            this.contentWindow   = this.frm.window;
        } else {
            this.contentDocument = this.frm.contentDocument;
            this.contentWindow   = this.frm.contentWindow;
        }
        
        return this.contentDocument;
    },
    
    getFocusElement: function() {
        if (document.all) {
            var doc = this.getDoc();
            var rng = doc.selection.createRange();
            
            if (rng.collapse)
            rng.collapse(true);
            
            var elm = rng.item ? rng.item(0) : rng.parentElement();
        } else {
            var sel = this.getSel();
            var elm = (sel && sel.anchorNode) ? sel.anchorNode : null;
        }
        
        return elm;
    },
    
    getSel: function() {
        // selektion im frame zurückgeben
        
        if (document.all) {
            return this.getDoc().selection;
        } else {
            this.getDoc();
            return this.contentWindow.getSelection();
        }
    },
    
    getElementsByAttributeValue: function(node, element_name, attrib, value) {
        var elements = new Array();
    
        if (node && node.nodeName.toLowerCase() == element_name) {
            if (node.getAttribute(attrib) && node.getAttribute(attrib).indexOf(value) != -1)
                elements[elements.length] = node;
        }
    
        if (node.hasChildNodes) {
            for (var x=0, n=node.childNodes.length; x<n; x++) {
                var childElements = this.getElementsByAttributeValue(node.childNodes[x], element_name, attrib, value);
                for (var i=0, m=childElements.length; i<m; i++)
                    elements[elements.length] = childElements[i];
            }
        }
    
        return elements;
    }
    
});
