﻿var linkWizardWindow;
var attachmentWindow;
var imgWizardWindow;

function showLinkWizard(url) {
    if (linkWizardWindow && !linkWizardWindow.closed) {
        linkWizardWindow.focus();
    }
    else {
        linkWizardWindow = window.open(url, 'LinkWizard', 'width=500, height=550, scrollbars=yes');
    }
    return false;
}

function showAttachmentWizard(url) {
    if (attachmentWindow && !attachmentWindow.closed) {
        attachmentWindow.focus();
    }
    else {
        attachmentWindow = window.open(url, 'AttachmentWizard', 'width=350, height=220');
    }
    return false;
}

function showImgWizard(url) {
    if (imgWizardWindow && !imgWizardWindow.closed) {
        imgWizardWindow.focus();
    }
    else {
        imgWizardWindow = window.open(url, 'ImageWizard', 'width=570,height=575,location=false, status=false, scrollbars=false');
    }
    return false;
}

function isIE() {
    return (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
}

function initFrameAndSource(sourceTextId) {
    if (EditStyle != 's') {

        if (isIE()) {
            otherDoc = document.frames.TheFrame.document;
            otherDoc.onblur = savehtml;
        }
        else {
            document.getElementById("TheFrame").contentDocument.addEventListener("blur", savehtml, false);
            otherDoc = document.getElementById("TheFrame").contentDocument;

        }


        //otherDoc.body.onselect = showSelectionFont;


    }
    else {
        txtSource = document.getElementById(sourceTextId);
        if (isIE())
            txtSource.onblur = savehtml;
        else
            document.getElementById("TheFrame").contentDocument.addEventListener("blur", savehtml, false);

        //txtSource = document.all.<%= txtSourceID %>;

    }
}



function putintxt() {
    if (EditStyle != 's') {
        return document.getElementById('TheFrame').document.getElementById('TheBody').innerHtml;
    }
    else {
        return document.getElementById('<%= txtSourceID %>').value;
    }
}


function insertText(text) {
    if (isIE()) {
        TheFrame.focus();
        var sel = otherDoc.selection;
        var rng = sel.createRange();
        var t = rng.htmlText;
        rng.pasteHTML(text);

    }
    else {
        var f = document.getElementById('TheFrame');
        
        var oSel = f.contentWindow.getSelection();
        var oRange = oSel.getRangeAt(0);
        var oFragment = oRange.createContextualFragment(text);
        var oc = oRange.cloneContents();
        if (oc == "undefined") {
            oFragment.firstChild.appendChild(oc);
        }
        oRange.deleteContents();
        var oLastNode = oFragment.lastChild;
        oRange.insertNode(oFragment);
        oRange.setEndAfter(oLastNode);
        oRange.setStartAfter(oLastNode);
        oSel.removeAllRanges();
        f.contentWindow.focus();
    }

    setDirty();
}

function createLink(url, target, onClickScript) {

    var onClickAttr = '';
    if (onClickScript) {
        onClickAttr = ' onclick="' + onClickScript + '"';
    }

    try {
    
        if (isIE()) {

            try { TheFrame.document.execCommand('Unlink', false, null); } catch (err) { }
            var cursor; var t;
            cursor = TheFrame.document.selection.createRange();
            if (cursor.length > 1) {
                cleanSelectionForLinkIE(cursor);
            }
            t = cursor.htmlText;

            if (typeof t == 'undefined') {
                cursor = cursor.item(0);
                t = cursor.outerHTML; cursor.outerHTML = '<a href="' + url + '" ' + target + '>' + t + '</a>'
            }
            else {
                cursor.pasteHTML('<a href="' + url + '" ' + target + onClickAttr + ' >' + t + '</a>');
            }
        }
        else {
            var f = document.getElementById('TheFrame');
            f.contentWindow.document.execCommand('Unlink', false, null);

            //f.contentWindow.document.execCommand('CreateLink', false, url);
            wrap('<a href="' + url + '" ' + target + onClickAttr + '">', '');
        }

        setDirty();
    }
    catch (err) {
        alert(err + ':Der ausgewählte Inhalt kann nicht verlinkt werden.');
    }
}

function cleanSelectionForLinkIE(cursor) {

    //search for trailing empty tags and or brs
    //  1: <((([a-zA-Z]+)( [^>]*)?)>                => search any starttag with or without attributes, in combination with #2 and #3
    //  2: <\/\3>                                   => search a colsingtag for #1
    //  3: ((<[a-zA-Z]*[^>]*\/>)|<br>|(&nbsp;))*    => inside #1 and 2# only self-closing tags, <br> and nbsp; are allowed
    //  4: (<br>)*)                                 => after #2 match any trailing <br>s
    //  5: |(<br>)                                  => instead of #1-4 match trailing <br>a
    
    var trail =      /<((([a-zA-Z]+)( [^>]*)?)>((<[a-zA-Z]*[^>]*\/>)|<br>|(&nbsp;))*<\/\3>(<br>)*)|(<br>)*\s*$/i
    //search for the same as above and search for opening table- or td-tags at the beginning
    // see #1-4 above
    //  6: |(<(([a-zA-Z]+)( [^>]*)?)>)              => match any start-tag with or without attributes
    //  7: |((<table.*>)|(<td.*>))                  => match table or td start-tags
    
    var start = /^\s*((<(([a-zA-Z]+)( [^>]*)?)>((<[a-zA-Z]*[^>]*\/>)|<br>|(&nbsp;))*<\/\4>(<br>)*)|(<(([a-zA-Z]+)( [^>]*)?)>)|((<table.*>)|(<td.*>)))/i
    var startsWithImg = /^\s*<img/i

    var moveCount = 0;
    var moved = true;
    for (moveCount = 0; moveCount < 30 && moved; moveCount++) {
        moved = false;
   
        var match = trail.exec(cursor.htmlText);
        if(match != null){
            cursor.moveEnd('character', -1);
            moved = true;
        }

        // make sure not to remove a selected image
        var startImg = startsWithImg.exec(cursor.htmlText);
        if (startImg == null) {
            var match = start.exec(cursor.htmlText);
            if (match != null) {
                cursor.moveStart('character', 1);
                moved = true;
            }
        }
        
    }

}


function putinWYSIWYG() {
    //document.frames.TheFrame.document.body.innerHtml=document.getElementById('<%= txtSourceID %>').value;
}

function showSelectionFont() {
    var f;
    //f = otherDoc.queryCommandValue("FontName");
    if (!f)
        f = "null";
    // to lower the string before comparting it - use all lower for all id's.
    f = f.toLowerCase();

    c = FontSelection.all[f];

    if ((c) && (!c.selected)) {
        c.selected = true;
    }
}


function ObjectLeft(element) {
    var retval;
    retval = 0;
    if (element.offsetParent) {
        do {
            retval += element.offsetLeft;
        } while (element = element.offsetParent);
    }
    return retval;
}

function ObjectTop(element) {
    var retval;
    retval = 0;
    if (element.offsetParent) {
        do {
            retval += element.offsetTop;
        } while (element = element.offsetParent);
    }
    return retval;
}

function ToggleTableBorder() {

}

function InsertRowAbove() {
    TableRowAction("addAbove");
}

function InsertRowBelow() {
    TableRowAction("addBelow");
}

function DeleteRow() {
    TableRowAction("delete");
}

function InsertColBefore() {
    TableColAction("addBefore");
}

function InsertColAfter() {
    TableColAction("addAfter");
}

function DeleteCol() {
    TableColAction("delete");
}

function TableInDOM(cell) {
    var tbl = cell.parentElement
    while (tbl) {
        if (tbl.tagName == "TABLE") {
            return tbl;
        }
        tbl = tbl.parentElement;
    }
    return false;
}

function SetColWidth() {
    TheFrame.focus();
    var sel = otherDoc.selection.createRange();

    var idx = 0;
    var colindex = -1;
    var thiscell = sel.parentElement();
    var tr = thiscell.parentNode;
    var numcells = tr.childNodes.length;

    var tbl = TableInDOM(thiscell);
    if (tbl.childNodes[0].tagName != "TR") {
        tbl = tbl.childNodes[0];
    }

    if (!tbl)
        return;
    colindex = thiscell.cellIndex;

    var w = prompt('Breite der Spalte', '');
    if (w) {
        for (i = 0; i < tbl.childNodes.length; i++) {
            var cell;
            var cell = tbl.childNodes[i].childNodes[colindex];
            if (!cell)
                break;
            cell.setAttribute("width", w);
        }
    }

}

function TableAction(action) {
    TheFrame.focus();
    var sel = otherDoc.selection.createRange();

    var idx = 0;
    var colindex = -1;
    var thiscell = sel.parentElement();
    var tr = thiscell.parentNode;
    var numcells = tr.childNodes.length;

    var tbl = TableInDOM(thiscell);

    if (!tbl) {
        return;
    }

    if (action == "border") {
        var activeborder = "0";
        activeborder = tbl.getAttribute("border");

        if (activeborder == "1") {
            tbl.setAttribute("border", 0)
        }
        else {
            tbl.setAttribute("border", 1)
        }
    }

    if (action == "width") {
        var activewidth = "";
        activewidth = tbl.getAttribute("width");

        if (activewidth != "100%") {
            tbl.setAttribute("width", "100%")
        }
        else {
            tbl.setAttribute("width", "")
        }
    }
}

function TableRowAction(action) {
    TheFrame.focus();
    var sel = otherDoc.selection.createRange();

    // if (!this.tableCell)
    // return;

    // go back to TABLE def and keep track of cell index
    var idx = 0;
    var rowindex = -1;
    var thiscell = sel.parentElement();
    var tr = thiscell.parentNode;
    var numcells = tr.childNodes.length;


    while (tr) {
        if (tr.tagName == "TR")
            rowindex++;
        tr = tr.previousSibling;
    }

    var tbl = TableInDOM(thiscell);

    if (!tbl) {
        return;
    }

    if (action == "addBelow" | action == "addAbove") {
        var insind = rowindex;
        if (action == "addBelow")
            insind++;
        var r = tbl.insertRow(insind);
        for (var i = 0; i < numcells; i++) {
            r.insertCell();
            // var newtd = document.createElement("td");
            // var c = r.appendChild( newtd );

            //if (thiscell.parentNode.childNodes[i].colSpan)
            //c.colSpan = thiscell.parentNode.childNodes[i].colSpan;
        }
    } else {
        tbl.deleteRow(rowindex);
        //this.stopCellResize(true);
        //this.tableCell = null;
    }
}

function TableColAction(action) {
    TheFrame.focus();
    var sel = otherDoc.selection.createRange();

    var idx = 0;
    var colindex = -1;
    var thiscell = sel.parentElement();
    var tr = thiscell.parentNode;
    var numcells = tr.childNodes.length;

    var tbl = TableInDOM(thiscell);

    if (!tbl) {
        return;
    }
    colindex = thiscell.cellIndex;
    if (action == "addBefore" | action == "addAfter") {

        TableColHelper(tbl, colindex, action)

    }
    else {
        TableColHelper(tbl, colindex, "delete")
    }

}



function TableColHelper(tbl, cellindex, action) {
    for (i = 0; i < tbl.childNodes.length; i++) {
        if (tbl.childNodes[i].tagName == "TR") {
            var cell = tbl.childNodes[i].childNodes[cellindex];
            if (!cell)
                break;
            if (action == "addAfter") {
                cell.insertAdjacentElement("AfterEnd", this.document.createElement("TD"));
            }
            else if (action == "addBefore") {
                cell.insertAdjacentElement("BeforeBegin", this.document.createElement("TD"));

            }
            else {

                if (cell.rowSpan > 1) {
                    i += (cell.rowSpan - 1);
                }
                cell.removeNode(true);
            }
        } else {
            TableColHelper(tbl.childNodes[i], cellindex, action);
        }
    }


}


function selOn(ctrl) {
    ctrl.style.borderColor = '#000000';
    ctrl.style.backgroundColor = '#FFFFFF';
    ctrl.style.cursor = 'hand';
}

function selOff(ctrl) {
    ctrl.style.borderColor = '';
    ctrl.style.backgroundColor = '';
}

function selDown(ctrl) {
    ctrl.style.backgroundColor = '#8492B5';
}

function selUp(ctrl) {
    ctrl.style.backgroundColor = '#EFEBDE';
}


function doHead(hType) {
    if (hType != '') {
        //document.all.TheFrame.focus();
        otherDoc.execCommand('formatblock', false, hType);
        //doFont(selFont.options[selFont.selectedIndex].value); 
    }
}

function getImg() {
    TheFrame.focus();
    var result = null;
    var sel = null;

    if (isIE()) {
        sel = otherDoc.selection.createRange();
        result = sel.item(0);
    }
    else {
        var frame = document.getElementById('TheFrame');
        sel = frame.contentWindow.getSelection();
        result = getImgFromSelectionNonIE(sel);
    }
    
    return result;
}    
    
function getImgFromSelectionNonIE(sel)
{
    var selectedRange;
    if (sel && sel.rangeCount > 0) {
        selectedRange = sel.getRangeAt(0);
        if (selectedRange.startContainer.nodeType == 1) // element node
        {
            var aControl = selectedRange.startContainer.childNodes[selectedRange.startOffset];
            if (aControl && aControl.tagName && aControl.tagName.toLowerCase() == 'img')
                result = aControl
        }
    }
    
    return result
}

function getOuterHTML(object) {
    var element;
    if (!object) return null;
    element = document.createElement("div");
    element.appendChild(object.cloneNode(true));
    return element.innerHTML;
}

function PicLeft() {
    var n = getImg();
    n.setAttribute("align", "left");

}

function PicRight() {
    var n = getImg();
    n.setAttribute("align", "right");
}

function PicLine() {
    var n = getImg();
    n.setAttribute("align", "");
}


function InsertSelectContainer(starttag) {

    if (starttag.length > 0) {

        var clearMode = 'h';
        if (starttag.toLowerCase().indexOf('div') > 0) {
            clearMode = 'hsd';
        }
        wrap(starttag, clearMode);
    }
    else {
        unwrap('hsd');
    }

}

function addInlineStyle(attributeName, attributeValue) {
    var tag = '<span style=\'' + attributeName + ':' + attributeValue + '\'>';
    wrap(tag, 'hs');
}

function changeFontSize(fontSize) {

    if (fontSize && fontSize.length > 0) {
        var tag = '<span style=\'font-size:' + fontSize + '\'>';
        wrap(tag, 'hs');
    }
    else {
        removeFontSizeFromSelection();
    }
}


function wrap(startTag, clearMode) {
    if (startTag.length == 0) {
        unwrap(clearMode);
        return;
    }

    var n = startTag.indexOf(' ');
    if (n == -1)
        n = startTag.indexOf('>');

    var tagName = startTag.substr(1, n - 1);

    endTag = "</" + tagName + ">";

    var attNameInd = startTag.indexOf(' ') + 1;
    var attNameEndInd = startTag.indexOf('=') - 1;
    var attributeName = startTag.substr(attNameInd, attNameEndInd - attNameInd + 1);
    var attributeValue = startTag.substr(attNameEndInd + 2, startTag.length - attNameEndInd - 3);
    attributeValue = attributeValue.replace("\'", "").replace("\'", "").replace("\"", "");
    var parentElement = getSelectionParent();

    if (parentElement && parentElement.tagName.toLowerCase() == tagName.toLowerCase()) {
        changeNodeAttribute(parentElement, attributeName, attributeValue);
        return;
    }

    if (parentElement.parentNode && parentElement.parentNode.tagName.toLowerCase() == tagName.toLowerCase()) {
        changeNodeAttribute(parentElement.parentNode, attributeName, attributeValue);
        return;
    }

    if(isIE()) {
        var sel = TheFrame.document.selection;
        var selRange = sel.createRange();

        var length = selRange.text.length;
        if (length > 0) {
            unwrap(clearMode);

            var t = selRange.htmlText;
            
            selRange.pasteHTML(startTag + t + endTag);

            //selRange.moveStart('character', -1 * length);
            //selRange.select();
        }
    }
    else {
      
        var target = unwrap(clearMode);

        var frame = document.getElementById('TheFrame');
        var oSel = frame.contentWindow.getSelection();
        var oRange = oSel.getRangeAt(0);


        if (!target)
            target = oRange.cloneContents();

        oRange.deleteContents();
        var oFragment = oRange.createContextualFragment(startTag + endTag);

        oFragment.firstChild.appendChild(target);

        oRange.insertNode(oFragment);

    }
    setDirty();
}


function changeNodeAttribute(node, attributeName, attributeValue) {
    if (attributeName == "style") {
        var styles = attributeValue.split(";");

        for (i = 0; i < styles.length; i++) {
            var nameVal = attributeValue.split(":");
            $(node).css(nameVal[0], nameVal[1]);
        }
    }
    else {
        $(node).attr(attributeName, attributeValue);
    }

    setDirty();
}

function getSelectionParent() {
    var retval;
    
    if (isIE()) {
        var sel = TheFrame.document.selection;
        var selRange = sel.createRange();
        retval = selRange.parentElement();
    }
    else {
        var frame = document.getElementById('TheFrame');
        var oSel = frame.contentWindow.getSelection();
        var oRange = oSel.getRangeAt(0);

        var parent = oRange.startContainer;


        if (oRange.startContainer.nodeType != 3) {
            parent = parent.childNodes[oRange.startOffset];
        }

        while (parent && parent.nodeType != 1)
            parent = parent.parentNode;

        retval = parent;
    }

    return retval;
}

function getFormatParent(ele) {
    var parent = getSelectionParent();
    if (parent.tagName.toLowerCase() == 'a') {
        parent = parent.parentNode;
    }
    return parent;
}


function unwrap(clearMode) {

    var retval;

    if (isIE()) {

        var sel = TheFrame.document.selection;
        var selRange = sel.createRange();
        var parent = getFormatParent();

        if (!mustUnwrap(parent.tagName, clearMode))
            return;

        if (parent) {

            var t = parent.innerHTML;
            var length = parent.innerText.length;
            parent.parentNode.removeChild(parent);
            selRange.pasteHTML(t);

            //selRange.moveStart('character', -1 * length);
            //selRange.select();
        }
    }
    else {

        var parent = getFormatParent();

        var tagName = parent.tagName;

        if (!mustUnwrap(tagName, clearMode))
            return;

        // remove outer tags
        var oFragment = parent.ownerDocument.createDocumentFragment();

        for (var i = 0; i < parent.childNodes.length; i++)
            oFragment.appendChild(parent.childNodes[i].cloneNode(true));

        var movedText = parent.parentNode.replaceChild(oFragment, parent);

        //oRange.selectNode(movedText);
        document.getElementById('TheFrame').contentWindow.focus();

        retval = movedText;


    }

    setDirty();

    return retval;
}

function removeFontSizeFromSelection() {
    var parent = $(getFormatParent());
    parent.css("font-size", "");
    
    var noStyles = (parent.attr("style").length == 0);
    if (noStyles &&
        parent.attr("class").length == 0) {
        unwrap('hs');
    } else if (noStyles) {
        parent.removeAttr('style');
    }
}



function mustUnwrap(tagName, clearMode) {
    var ltn = tagName.toLowerCase();

    switch (clearMode) {
        case 'h':
            return (ltn == 'h1' || ltn == 'h2' || ltn == 'h3' || ltn == 'h4' || ltn == 'h5' || ltn == 'font' || ltn == 'blockquote');
            break;
        case 'hs':
            return (ltn == 'h1' || ltn == 'h2' || ltn == 'h3' || ltn == 'h4' || ltn == 'h5' || ltn == 'font' || ltn == 'blockquote' || ltn == 'span');
            break;
        case 'hsd':
            return (ltn == 'h1' || ltn == 'h2' || ltn == 'h3' || ltn == 'h4' || ltn == 'h5' || ltn == 'font' || ltn == 'blockquote' || ltn == 'span' || ltn == 'div');
            break;
        default:
            return false;
    }
}

function isFormatTag(tagName) {
    var lowerTagName = tagName.toLowerCase();

}

function pressresizer(mouse) {
    if (mousepressed) {
        var mousex;
        var mousey;
        var divtop;
        var divleft;
        var frTop;
        var n;
        n = document.getElementById('resizablecontainer');
        mousex = mouse.clientX;
        mousey = mouse.clientY;
        divtop = ObjectTop(n); //style.top;
        divleft = ObjectLeft(n); // n.style.left;

        var d;
        if ((mousex - divleft + 12) > 200) {
            n.style.width = (mousex - divleft + 20) + 'px';

        }
        var fr = document.getElementById('TheFrame');
        frTop = ObjectTop(fr);
        if ((mousey - frTop - 20) > 20) {
            fr.style.height = (mousey - frTop - 17) + 'px';
        }
        d = document.getElementById('dimensions');
        d.innerHTML = n.style.width + ' x ' + fr.style.height;


    }
}

// returns the computed value of a css-attribute of a given element
function getStyle(el, styleProp) {
    var x = document.getElementById(el);
    if (x.currentStyle)
        var y = x.currentStyle[styleProp];
    else if (window.getComputedStyle)
        var y = document.defaultView.getComputedStyle(x, null).getPropertyValue(styleProp);
    return y;
}



function adjustInPlaceEditor() {
    
    var currentLength = theBody.html().length;

    if (wysiwygChanged || currentLength != lastLength) {
        inPlaceFrame2Source();
        wysiwygChanged = false;
        lastLength = currentLength;
        
        adjustInPlaceDimensions();
    }

    adjustInPlaceToolbar();
}

function adjustInPlaceDimensions() {

    var dc = $("#dummyContent");
    dc.html(theBody.html());

    frame.height(dc.attr("scrollHeight"));
    frame.height(theBody.attr("scrollHeight"));
}


function adjustInPlaceToolbar() {

    var moduleFooterOutOfViewPort = frame.offset().top + frame.height() + toolbar.outerHeight() - $(document).scrollTop() > $(window).height();

    if (!toolbar.hasClass("inPlaceToolbarFixed") && moduleFooterOutOfViewPort) {
        toolbar.css("top", "");
        toolbar.css("bottom", "");
        toolbar.addClass("inPlaceToolbarFixed");

    }
    else if (toolbar.hasClass("inPlaceToolbarFixed") && !moduleFooterOutOfViewPort) {
        toolbar.removeClass("inPlaceToolbarFixed"); //.css("top", $(document).scrollTop() + $(window).height() - toolbar.height());
      
    }

    var marginLeft = -(toolbar.width() / 2 - frame.width() / 2);
    toolbar.css("marginLeft", marginLeft);

    if (toolbar.offset().left - $(document).scrollLeft() < 0) {
        toolbar.css("marginLeft", -frame.offset().left + $(document).scrollLeft());
    }

    else {

        if (toolbar.offset().left + toolbar.width() > $(window).width()) {

            var overlap = toolbar.offset().left + toolbar.width() - $(window).width();
            toolbar.css("marginLeft", marginLeft - overlap);
           // var newMarginLeft = frame.offset().left
        }
    }
    //TODO: rechte Seite prüfen
}

var toolbar;
var frame;
var theBody;

var lastLength = 0;
var wysiwygChanged = true;
var sourceChanged = false;


function setDirty() {
    wysiwygChanged = true;
}

function initInPlaceEditor(postback) {

    frame = $("#TheFrame");
    toolbar = $(".inPlaceToolbar");
    theBody = frame.contents().find("#TheBody");
    frame.attr("allowTransparency", "true");
    theBody.css("background-color", "transparent");
    theBody.css("background-image", "none");

    $(".wysiwygcontainer").css("background-color","transparent").parent().append("<div id='dummyContainer' style='height:1px;overflow:hidden;visibility:hidden'><div id='dummyContent' style='overflow:visible;overflow-y:hidden;overflow-x:visible;'></div></div>");

    // copy calculated styles from dummy container to wysiwyg-body
    mergeStyles($("#dummyContainer"), theBody);
    
    frame.css("width", "100%");
    adjustInPlaceEditor();

    setInterval('adjustInPlaceEditor()', 200);

    toolbar.css("opacity", "0");
    toolbar.css("visibility", "visible");

    if (!postback) {
        toolbar.animate({ opacity: 0.5 }, 1000);
    }
    else {
        toolbar.css("opacity", "1.0");
    }
    
    toolbar.mouseenter(function() { $(this).stop().animate({ opacity: 1.0 }, 100) });
    toolbar.mouseleave(function() { $(this).animate({ opacity: 0.5 }, 500) });

    $(".inPlaceToolbar").append("<div id='sourceContainer' style='display:none'></div>");
    var source = $(".inPlaceSource");
    source.text(theBody.html()).appendTo("#sourceContainer");
    $("#inPlaceSourceButtons").appendTo("#sourceContainer");

    $("#toggleInPlaceSource").click(toggleInPlaceSource);
    $("#updateSourceToFrame").click(inPlaceSource2Frame);
    source.blur(inPlaceSource2Frame);
    source.change(function() { sourceChanged = true; });
    $("#sourceReplaceBtn").click(inPlaceSourceReplace);

    $(".inPlaceToolbar .pbIcon_up").click(toggleToolbar);

    
    focusFrame();
    $('.wysiwygcontainer').css('visibility', 'visible');
    $('.wysiwygcontainer').append('<div id="divTime" style="display:none;">&nbsp;</div>');
    setTimeout(adjustInPlaceDimensions, 100);
}

function mergeStyles(from, to) {

    mergeStyle(from, to, "color");
    mergeStyle(from, to, "text-align");
    mergeStyle(from, to, "font-family");
    mergeStyle(from, to, "font-weight");
    mergeStyle(from, to, "line-height");
    mergeStyle(from, to, "letter-spacing");


    var fontSize;
    // here we have to determine font size for IE differently, due to jquery bug #4296
    if (from.attr('currentStyle')) {
        var d = $('<div/>').css({ position: 'absolute', top: 0, left: 0, height: '1.0em', visibility: 'hidden', lineHeight: '1.0em' }).text('M').appendTo(from);
        fontSize = d[0].style.pixelHeight + 'px';
        d.remove();
    }
    else {
        fontSize = from.css("font-size");
    }

    to.css("font-size", fontSize);
}

function mergeStyle(from, to, attribute) {
    var oldVal = to.css(attribute);
    var newVal = from.css(attribute);
    if (oldVal != newVal) {
        to.css(attribute, newVal);
    }
}

function focusFrame() {
    if (isIE()) {
        TheFrame.focus();
    }
    else {
        document.getElementById('TheFrame').contentWindow.focus();
    }
}

function toggleToolbar() {
  
    if ($(".inPlaceToolbar .pbIcon_down").length > 0) {
        $(".inPlaceToolbar .pbIcon_down").removeClass("pbIcon_down").addClass("pbIcon_up");
        $(".IconsArea").show();
    }
    else {
        $(".inPlaceToolbar .pbIcon_up").removeClass("pbIcon_up").addClass("pbIcon_down");
        $(".IconsArea").hide();
    }
    
    
}

function toggleInPlaceSource() {

    var source = $("#sourceContainer");
    if ($("#sourceContainer:visible").length > 0) {
        source.hide();
    }
    else {
        source.show();
    }

}

function inPlaceSource2Frame() {

    if (sourceChanged) {
        theBody.empty();
        var newHtml = $(".inPlaceSource").attr("value");

        theBody.empty();

        theBody.html(newHtml);
        $("#dummyContent").html(newHtml);
        adjustInPlaceDimensions();
        savehtml();
        sourceChanged = false;
    }
}

function inPlaceSourceReplace(){

    var searchString = $("#sourceSearch").attr("value");
    
    if (searchString && searchString.length > 0) {
        //var searchExpr = new RegExp(searchString, "g");
        var replaceString = $("#sourceReplace").attr("value");

        var oldText = $(".inPlaceSource").attr("value");
        //var newText = oldText.replace(searchString, replaceString);

        var newText = oldText.split(searchString).join(replaceString);
 
        $(".inPlaceSource").attr("value", newText);

        sourceChanged = true;
      
        //inPlaceSource2Frame();
    }

}

function inPlaceFrame2Source() {

    var source = $(".inPlaceSource");
    var sourceScrollTop = $(".inPlaceSource").scrollTop();
    source.attr('value', $("#TheFrame").contents().find("#TheBody").html()).scrollTop(sourceScrollTop);
}

function getAttribute(html, attributeName) {
    var searchExpr = new RegExp(attributeName + '="[^"]*"', 'g');
    var src = '';
    src = searchExpr.exec(html);
    if (src != null) {
        src = src.toString()
        src = src.substring(attributeName.length + 2, src.length - 1);
    }
    else {
        searchExpr = new RegExp(attributeName + '=[^ ]* ', 'g');
        src = searchExpr.exec(html);
        if (src != null) {
            src = src.toString()
            src = src.substring(attributeName.length + 1, src.length - 1);
        }
    }
    if (src == null)
        src = '';
    return src;
}

function getStyleAttribute(html, attributeName) {
    if (!isIE()) {
        attributeName = attributeName.toLowerCase();
    }   
    var searchExpr = new RegExp(attributeName + ':[^;^"]*[;"]', 'g');
    var src = '';
    src = searchExpr.exec(html);
    if (src != null) {
        src = src.toString()
        src = src.substring(attributeName.length + 1, src.length - 1);
    }
    if (src == null)
        src = '';
    return src;
}

function clearPixelUnit(unit) {
    var retval = unit.replace('px', '').replace(' ','');
    return retval;
}

