// constructor
function IEditor(iframe, input) {
    this.editor = iframe;
    this.input = input;

    this.editor.innerHTML = input.value;
    this.editor.contentEditable = true;

    // at start set editor in visual mode
    this.viewMode = 1;

    // prototypes
    this.fontnames = {
        "Arial":           "arial, helvetica, sans-serif",
        "Courier New":     "courier new, courier, mono",
        "Georgia":         "Georgia, Times New Roman, Times, Serif",
        "Tahoma":          "Tahoma, Arial, Helvetica, sans-serif",
        "Times New Roman": "times new roman, times, serif",
        "Verdana":         "Verdana, Arial, Helvetica, sans-serif",
        "Impact":          "impact",
        "WingDings":       "WingDings"
    };
    this.fontsizes = {
        "1 (8 pt)":  "1",
        "2 (10 pt)": "2",
        "3 (12 pt)": "3",
        "4 (14 pt)": "4",
        "5 (18 pt)": "5",
        "6 (24 pt)": "6",
        "7 (36 pt)": "7"
    };
    this.doHover = ieditor_dohover;
    this.doPress = ieditor_dopress;
    this.saveDocument = ieditor_savedocument;
    this.doExec = ieditor_doexec;
    this.switchView = ieditor_switchview;
    this.newDocument = ieditor_newdocument;
    this.insertLink = ieditor_insertlink;
    this.insertHTML = ieditor_inserthtml;
    this.insertTable = ieditor_inserttable;
    this.getCurrentCell = ieditor_getcurrentcell;
    this.getCurrentTable = ieditor_getcurrenttable;
    this.addColumn = ieditor_addcolumn;
    this.delColumn = ieditor_delcolumn;
    this.insertCol = ieditor_insertcol;
    this.removeCol = ieditor_removecol;
    this.insertRow = ieditor_insertrow;
    this.removeRow = ieditor_removerow;
    this.splitRow = ieditor_splitrow;
    this.joinRow = ieditor_joinrow;
    this.changeTextColor = ieditor_changetextcolor;
    this.changeBgColor = ieditor_changebgcolor;
    this.specialSymbol = ieditor_specialsymbol;
    this.removeTags = ieditor_removetags;
    this.help = ieditor_help;
}

// IEditor.changeTextColor()
function ieditor_changetextcolor() {
    if (this.viewMode == 1) {
        result = showModalDialog('ie/color.html', window, 'status:no; dialogWidth:265px; dialogHeight:255px; help:no');
        if (result) {
            this.editor.focus();
            document.execCommand('forecolor', false, result);
        }
    }
}

// IEditor.changeBgColor()
function ieditor_changebgcolor() {
    if (this.viewMode == 1) {
        result = showModalDialog('ie/color.html', window, 'status:no; dialogWidth:265px; dialogHeight:255px; help:no');
        if (result) {
            this.editor.focus();
            document.execCommand('backcolor', false, result);
        }
    }
}

// IEditor.specialSymbol()
function ieditor_specialsymbol() {
    if (this.viewMode == 1) {
        result = showModalDialog('ie/specsymb.html', window, 'status:no; dialogWidth:100px; dialogHeight:220px; help:no');
        if (result) this.insertHTML(result);
    }
}

function ieditor_help() {
    if (this.viewMode == 1) {
        showModalDialog('ie/help.html', window, 'status:no; help:no');
    }
}

// IEditor.getCurrentCell()
function ieditor_getcurrentcell() {
    this.editor.focus();
    cursorPos = document.selection.createRange();
    var element = cursorPos.parentElement();
    while (element && element.tagName != 'TD') {
        if (element.tagName == 'DIV') return null;
        element = element.parentElement;
    }
    return element;
}

// IEditor.getCurrentTable(cell)
function ieditor_getcurrenttable(cell) {
    var element = cell.parentElement;
    while (element && element.tagName != 'TABLE') {
        element = element.parentElement;
    }
    return element ? element : null;
}

// IEditor.addColumn(element, cell)
function ieditor_addcolumn(element, cell) {
    if (!element.childNodes.length) return;
    for (var i = 0; i < element.childNodes.length; i++) {
        if (element.childNodes[i].tagName == 'TR') {
            var c = element.childNodes[i].childNodes[cell.cellIndex];
            if (!c) break;
            var td = document.createElement('TD');
            td.className = cell.className;
            c.insertAdjacentElement('AfterEnd', td);
        } else {
            this.addColumn(element.childNodes[i], cell);
        }
    }
}

// IEditor.delColumn(element, index)
function ieditor_delcolumn(element, index) {
    if (!element.childNodes.length) return false;
    for (var i = 0; i < element.childNodes.length; i++) {
        if (element.childNodes[i].tagName == 'TR') {
            if (!element.childNodes[i].childNodes[index]) {
                alert('Не могу удалить столбик проходящий через объединенную ячейку');
                return false;
            }
        } else {
            if (!this.delColumn(element.childNodes[i], index)) {
                return false;
            }
        }
    }
    for (var i = 0; i < element.childNodes.length; i++) {
        if (element.childNodes[i].tagName == 'TR') {
            element.childNodes[i].childNodes[index].removeNode(true);
        } else {
            delColumn(element.childNodes[i], index);
        }
    }
}

// IEditor.insertCol()
function ieditor_insertcol() {
    cell = this.getCurrentCell();
    if (cell == null) return;
    table = this.getCurrentTable(cell);
    if (table == null) return;
    this.addColumn(table, cell);
}

// IEditor.removeCol()
function ieditor_removecol() {
    cell = this.getCurrentCell();
    if (cell == null) return;
    table = this.getCurrentTable(cell);
    if (table == null) return;
    this.delColumn(table, cell.cellIndex);
}

// IEditor.insertRow()
function ieditor_insertrow() {
    cell = this.getCurrentCell();
    if (cell == null) return;
    var rowidx = -1;
    var tr = cell.parentNode;
    var numCells = tr.childNodes.length;
    while (tr) {
        if (tr.tagName == 'TR') rowidx++;
        tr = tr.previousSibling;
    }
    table = this.getCurrentTable(cell);
    if (table == null) return;
    var row = table.insertRow(rowidx);
    for(var i = 0; i < numCells; i++) {
        var c = row.appendChild(document.createElement('TD'));
        if (cell.parentNode.childNodes[i].colSpan)
            c.colSpan = cell.parentNode.childNodes[i].colSpan;
        c.className = cell.className;
    }
}

// IEditor.removeRow()
function ieditor_removerow() {
    cell = this.getCurrentCell();
    if (cell == null) return;
    var rowidx = -1;
    var tr = cell.parentNode;
    var numCells = tr.childNodes.length;
    while (tr) {
        if (tr.tagName == 'TR') rowidx++;
        tr = tr.previousSibling;
    }
    table = this.getCurrentTable(cell);
    if (table == null) return;
    table.deleteRow(rowidx);
}

// IEditor.splitRow()
function ieditor_splitrow() {
    cell = this.getCurrentCell();
    if (cell == null) return;
    if (cell.colSpan < 2) {
        alert('Эта ячейка не была обьединена');
        return;
    }
    cell.colSpan = cell.colSpan - 1;
    var td = document.createElement('TD');
    td.className = cell.className;
    cell.parentNode.insertBefore(td, cell);
}

// IEditor.joinRow()
function ieditor_joinrow() {
    cell = this.getCurrentCell();
    if (cell == null) return;
    if (!cell.nextSibling) return;
    cell.innerHTML += cell.nextSibling.innerHTML;
    cell.colSpan += cell.nextSibling.colSpan;
    cell.nextSibling.removeNode();
}

// IEditor.insertHTML(text)
function ieditor_inserthtml(text) {
    this.editor.focus();
    var sel = document.selection.createRange();
    sel.pasteHTML(text);
}

// IEditor.insertTable()
function ieditor_inserttable() {
    if (this.viewMode == 1) {
        result = showModalDialog('ie/table.html', window, 'status:no;dialogWidth:450px;dialogHeight:168px;help:no');
        if (result) this.insertHTML(result);
    }
}

// IEditor.insertLink()
function ieditor_insertlink() {
    if (this.viewMode == 1) {
        this.editor.focus();
        document.execCommand('CreateLink',1);
    }
}

// IEditor.newDocument()
function ieditor_newdocument() {
    if (confirm('Очистить старый документ?')) {
        this.editor.innerHTML = "";
        this.editor.focus();
    }
}

// IEditor.switchView()
function ieditor_switchview() {
    if(this.viewMode == 1) {
        this.editor.innerText = this.editor.innerHTML;
        this.editor.innerHTML = ccParser(this.editor.innerHTML);
        document.all.t1.className = 'disabled';
        document.all.t2.className = 'disabled';
        document.all._fontname.disabled = true;
        document.all._fontsize.disabled = true;
        this.editor.focus();
        this.viewMode = 2;
    } else {
        this.editor.innerHTML = this.editor.innerText;
        document.all.t1.className = 'bar';
        document.all.t2.className = 'bar';
        document.all._fontname.disabled = false;
        document.all._fontsize.disabled = false;
        this.editor.focus();
        this.viewMode = 1;
    }
}

// IEditor.removeTags()
function ieditor_removetags() {
    if(this.viewMode == 1) {
        var html = this.editor.innerHTML;

        var htmltag = /<\/?((font)|(span)|([\w]+:[\w]+))[^>]*>/gi;
        html = html.replace(htmltag,"");

        var htmlstyle = / style="[^"]*"/gi;
        html = html.replace(htmlstyle,"");

        this.editor.innerHTML = html;
        this.editor.focus();
    }
}

// IEditor.doExec(command)
function ieditor_doexec(command) {
    if (this.viewMode == 1) {
        this.editor.focus();
        document.execCommand(command);
    }
}

// IEditor.saveDocument()
function ieditor_savedocument() {
    if (this.viewMode == 1) {
        this.input.value = this.editor.innerHTML;
    } else {
        this.input.value = this.editor.innerText;
    }
}

// IEditor.doHover(state)
function ieditor_dohover(state) {
    if(this.viewMode == 1) {
        var element = window.event.srcElement;
        if (element && !element.disabled && element.nodeName == "IMG") {
            if (state) {
                element.className = 'hover';
            } else {
                element.className = element.defaultState;
            }
        }
    }
}

// IEditor.doPress(state)
function ieditor_dopress(state) {
    var element = window.event.srcElement;
    if (element && !element.disabled && element.nodeName == "IMG" && element.id != 'switcher') {
        if (state) {
            if (this.viewMode == 1) {
                element.className = "down";
            } else {
                element.className = "";
                alert("Редактирование невозможно в режиме просмотра HTML-кода.\n Переключитесь в режим визуального форматирования");
            } 
        } else {
            element.className = element.className == "down" ? "hover" : element.defaultState;
        }
    }
}

function ccParser(html) {
    html = html.replace(/@/gi,"_AT_");
    html = html.replace(/#/gi,"_HASH_");

    var htmltag = /(&lt;[\w\/]+[ ]*[\w\%\=\"\'\.\/\;\: \)\(-]*&gt;)/gi;
    html = html.replace(htmltag,"<span class=tag>$1</span>");

    var parameter = /=("[ \w\%\'\.\/\;\:\)\(-]+"|'[ \w\%\"\.\/\;\:\)\(-]+')/gi;
    html = html.replace(parameter,"=<span class=param>$1</span>");

    html = html.replace(/_AT_/gi,"@");
    html = html.replace(/_HASH_/gi,"#");
    
    return html;
}

function supportEditing() {
    var opera = window.opera ? 1 : 0;
    var ie = document.all;
    var ce = document.body && document.body.contentEditable ? 1 : 0;
    return ie && ce && !opera;
}
