﻿var hrefSelection;
var htmlEditDelayTimeout;
var IsSourceViewSwitching;

function HtmlEdit_Reset(id) {
    $(id).value = '';
    HtmlEdit_OnInitialise(id);
}
var css_location = '/v2.0/css/editor.css';

var editor_css = '<link rel="stylesheet" type="text/css" href="' + css_location + '" />';

function HtmlEdit_OnInitialise(id) {
    var editorFrame = $(id + '_window');
    if (editorFrame) {
        var documentContent = HtmlEdit_GetBody($(id).value);
        var doc = editorFrame.contentDocument ? editorFrame.contentDocument : editorFrame.contentWindow.document;
       
        $j(doc).unbind('keyup');
        $j(doc).unbind('blur');
        $j(doc).unbind('click');
        $j(doc).unbind('focusout'); 
        
        doc.open();
        doc.write(
            '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional //EN" "http://www.w3.org/TR/html4/loose.dtd">' +
            '<html><head><link rel="stylesheet" type="text/css" href="' + css_location + '" /><\/head><body><\/body><\/html>'
        );
        doc.close();

        $j(doc.body).html(documentContent);
        
        $(id + "_src").style.display = 'none';
        $(id + "_window").style.display = 'block';
        $(id + "_src").disabled = true;
        $j(doc.body).attr('designMode', 'on');
        $j(doc.body).attr('contentEditable', 'true');
        $j(doc).attr('editorID', id);
        $j(doc).bind('keyup', function() {
            HtmlEdit_OnSave($j(this).attr('editorID'));
        });
        $j(doc).bind('focusout', function() { HtmlEdit_OnSave($j(this).attr('editorID')); });
        $j(doc).bind('blur', function() { HtmlEdit_OnSave($j(this).attr('editorID')); });
        $j(doc).bind('click', function() { HtmlEdit_WindowClick($j(this).attr('editorID'));  }); 

    }
}
function HtmlEdit_OnSave(id) {
    //window.status = id + ' save ' + new Date();
    //alert(id+' save');
    var editorFrame = $(id + '_window');
    if (!editorFrame)
        return;
    var doc = editorFrame.contentDocument ? editorFrame.contentDocument : editorFrame.contentWindow.document;
    var html = $j(doc).html();

    if (doc.body) {
        if ($j(doc.body).text().replace(' ', '').length > 0
            || (html && html.indexOf('<img') > -1))
            $j('#' + id).val($j(doc.body).html());
        else
            $j('#' + id).val("");

    }
    //window.status = 'Saved '+(new Date());
}

function HtmlEdit_SourceView(event, id) {

    if (!document.all)
        event.preventDefault(); //FF,Safari
    event.returnValue = false;
   
    var editorFrame = $(id + '_window');
    var doc = editorFrame.contentDocument ? editorFrame.contentDocument : editorFrame.contentWindow.document;
    var IsSourceView = $(id + "_src").style.display == 'block';
    if (IsSourceView) {
        HtmlEdit_OnSourceChanged(id);
        HtmlEdit_OnInitialise(id);
    }
    else {
        IsSourceViewSwitching = true;
        $(id + "_src").value = $j(doc.body).html();
        $(id + "_window").style.display = 'none';
        $(id + "_src").style.display = 'block';
        $(id + "_src").disabled = false;
        $(id + "_src").focus();
        IsSourceViewSwitching = false;
    }
    
}

function HtmlEdit_OnSourceChanged(id) {
    if (IsSourceViewSwitching)
        return;
    $j('#' + id).val($j('#' + id + "_src").val());
}

function HtmlEdit_Focus(id) {
    if ($(id + '_holder'))
        $(id + '_holder').scrollIntoView()
    HtmlEdit_Do(null, id, 'SelectAll');
}
function HtmlEdit_Close(id) {
    if (!document.all)
        return;
    var editorFrame = $(id + '_window');
    if (editorFrame) {
        editorFrame.contentWindow.location.replace('/blank.htm');
    }
}

function HtmlEdit_WindowClick(id) {
   
    hrefSelection = null;
    var editorFrame = $(id + '_window');
    if (!editorFrame)
        return;

    var doc = editorFrame.contentDocument ? editorFrame.contentDocument : editorFrame.contentWindow.document;
    //alert('"' + $j(doc).text() + '"');
    var html = $j(doc).html();

    if ($j(doc).text().length == 0 && (!html || html.indexOf('<img')==-1))
        $j(doc.body).html("&nbsp;").focus();
    else
        $j(doc.body).focus();
    HtmlEdit_OnSave(id);
    
    // IE fix for RTE not editable after destory
    if (document.all) {
        var sel = doc.selection.createRange();
        if (sel && sel.text.length==0)
            sel.select();
    }
}

function HtmlEdit_Enable(id) {
    var editorFrame = $(id + '_window');
    var doc = editorFrame.contentDocument ? editorFrame.contentDocument : editorFrame.contentWindow.document;
    if (doc.designMode != 'on')
        doc.designMode = 'on';
}


function HtmlEdit_Do(event, id, command, args) {
    if (event) {
        if (!document.all)
            event.preventDefault(); //FF,Safari
        event.returnValue = false;
    }
    
    var editorFrame = $(id + '_window');
    var doc = editorFrame.contentDocument ? editorFrame.contentDocument : editorFrame.contentWindow.document;
    if (args)
        args = args.toString();
    // doc.focus();

    editorFrame.contentWindow.focus();
    doc.execCommand(command, false, args);
    //doc.focus();
    HtmlEdit_OnSave(id);
}

function HtmlEdit_GetBody(html) {
    if (!html)
        return "";

    var rx = new RegExp("<body.*?>(.*?)</body>", "g");
    var m = rx.exec(html);
    while (m != null
        && m.length > 0) {
        html = m[1];
        m = rx.exec(html);
    }
    
    html = html.replace(/^&nbsp;/, ''); 
    
    return html != ' ' && html != '&nbsp;' ? html : '';
}

function HtmlEdit_InsertImage(event, id) {
    if (!document.all)
        event.preventDefault(); //FF,Safari

    event.returnValue = false;

    var x = mouseX;
    var y = mouseY;

    var s = "";

    s += "<input type=\"hidden\" id=\"" + id + "_posX\" value=\"" + x + "\"/>";
    s += "<input type=\"hidden\" id=\"" + id + "_posY\" value=\"" + y + "\"/>";
    s += "<div id=\"" + id + "_InsertImageBalloon\" class=\"NewEntryBaloon\"><div class=\"Inner\">";
    s += "<a href=\"javascript:;\" onclick=\"HtmlEdit_BalloonClose('" + id + "');\" class=\"Close\"></a>";

    s += "<h2>Place an Image</h2>";

    s += "<div id=\"" + id + "_settings\"><table>";
    // s += "<tr valign=\"top\"><td>Select Image:</td>"
    //s += "<td><iframe id='"+id+"ImageUploadFrame' name='"+id+"ImageUploadFrame' src=\"/UploadEx?id=" + id + "&type=image\" style=\"width: 280px; height:50px;\" frameborder=\"0\"></iframe></td>";
    s += "<td>" + BuildFileUploader("image", id, "HtmlEdit_OnFileUploaded", "Select an Image ...") + "</td>"
    s += "</table></div>";
    s += "</div><div class=\"Triangle\"></div></div>";

    $(id + "_holder").innerHTML = s;


    HtmlEdit_PositionBalloon(id);
}



function HtmlEdit_CalculateDimensionsDelayed(id) {
    if (htmlEditDelayTimeout)
        clearTimeout(htmlEditDelayTimeout);

    var percentBox = $(id + "_percent");
    if (!percentBox)
        return;

    var originalWidth = parseInt($(id + "_originalWidth").value);
    var originalHeight = parseInt($(id + "_originalHeight").value);
    var percent = 100;
    try {
        percent = parseFloat(percentBox.value.replace(/%/g, '').replace(/ /g, ''));
    }
    catch (x) {
        $(id + "_width").value = originalWidth.toString();
        $(id + "_height").value = originalHeight.toString();
        return;
    }


    var width = parseInt(originalWidth * (percent / 100));
    var height = parseInt(originalHeight * (percent / 100));
    $(id + "_width").value = width.toString();
    $(id + "_height").value = height.toString();

    $(id + "_dimensionPreview").innerHTML = "(" + width.toString() + "x" + height.toString() + ")";
    $(id + "_linkToOriginal").disabled = percent == 100;

    var preview = $(id + "_thumb");
    preview.src = HtmlEdit_BuildImageUrl(id);
    preview.width = width;
    preview.height = height;

    var balloon = $(id + "_InsertImageBalloon");
    balloon.style.width = (width + 230) + "px";

    HtmlEdit_PositionBalloon(id);
}

function HtmlEdit_PositionBalloon(id) {
    var x = parseInt($(id + "_posX").value); //mouseX  <-- bad
    var y = parseInt($(id + "_posY").value); //mouseY  <-- bad

    y -= PosY($(id + "_holder"));
    x -= PosX($(id + "_holder"));

    var balloon = $(id + "_InsertImageBalloon");
    balloon.style.left = (x - 110) + "px";
    var top = (y - (GetHeight(balloon) + 30));
    //if (top<5) // required for image insert, stop it going out of bounds
    //

    balloon.style.top = top + "px";
    var py = PosY(balloon);
    if (py < 0)
        balloon.style.top = (top - py) + "px";
}

function HtmlEdit_CalculateDimensions(id) {
    if (htmlEditDelayTimeout)
        clearTimeout(htmlEditDelayTimeout);
    htmlEditDelayTimeout = setTimeout("HtmlEdit_CalculateDimensionsDelayed('" + id + "')", 2000);
}


function HtmlEdit_InsertFile(event, id) {
    if (!document.all)
        event.preventDefault(); //FF,Safari

    event.returnValue = false;

    var x = mouseX;
    var y = mouseY;

    var s = "";

    s += "<input type=\"hidden\" id=\"" + id + "_posX\" value=\"" + x + "\"/>";
    s += "<input type=\"hidden\" id=\"" + id + "_posY\" value=\"" + y + "\"/>";
    s += "<div id=\"" + id + "_InsertImageBalloon\" class=\"NewEntryBaloon\"><div class=\"Inner\">";
    s += "<a href=\"javascript:;\" onclick=\"HtmlEdit_BalloonClose('" + id + "');\" class=\"Close\"></a>";

    s += "<h2>Insert a File Link</h2>";

    s += "<div id=\"" + id + "_settings\"><table><tr><td>";
    //s += "<td><iframe id='"+id+"FileUploadFrame' name='"+id+"FileUploadFrame' src=\"/UploadEx?id=" + id + "&type=file\" style=\"width: 280px; height:50px;\" frameborder=\"0\"></iframe></td>";
    s += BuildFileUploader("file", id, "HtmlEdit_OnFileUploaded", "Select a document ...") 
    s += "<div id=\"RelatedFiles\"></div>";
    s += "</td></tr></table></div>";
    
    s += "</div><div class=\"Triangle\"></div></div>";

    GlobalCB('EntryEditor.OnGetRelatedFiles', id);
    $(id + "_holder").innerHTML = s;

    HtmlEdit_PositionBalloon(id);
}

function HtmlEdit_InsertHref(event, id) {
    if (!document.all)
        event.preventDefault(); //FF,Safari

    event.returnValue = false;
    var editorFrame = $(id + '_window');
    var doc = editorFrame.contentDocument ? editorFrame.contentDocument : editorFrame.contentWindow.document;
    if (!doc)
        return;

    hrefSelection = document.all ? doc.selection.createRange() : editorFrame.contentWindow.getSelection();


    var x = mouseX;
    var y = mouseY;

    var s = "";

    s += "<input type=\"hidden\" id=\"" + id + "_posX\" value=\"" + x + "\"/>";
    s += "<input type=\"hidden\" id=\"" + id + "_posY\" value=\"" + y + "\"/>";
    s += "<div id=\"" + id + "_InsertImageBalloon\" class=\"NewEntryBaloon\"><div class=\"Inner\">";
    s += "<a href=\"javascript:;\" onclick=\"HtmlEdit_BalloonClose('" + id + "');\" class=\"Close\"></a>";

    s += "<h2>Insert a Hyperlink</h2>";

    s += "<div id=\"" + id + "_settings\"><table>";
    s += "<tr><td colspan=\"2\" class=\"Tiny\" style=\"white-space: wrap;\"><b>Type or paste a URL below</b> and then press the <b>Place Hyperlink</b> button to insert the hyperlink at a specific location in your document. You can also <b>select a region of text before placing</b> to convert existing text into a hyperlink. </td></tr>";
    s += "<tr><td>Enter URL:</td><td><input type=\"text\" id=\"" + id + "_InsertHrefText\" onKeyDown=\"if (event.keyCode==13) { HtmlEdit_InsertHrefValue(event, '" + id + "'); return false; }\" value=\"http://www.\" style=\"width: 200px\"/><span id=\"" + id + "_InsertHrefFeedback\"></span></td></tr>"
    s += "<tr><td>&nbsp;</td><td><input type=\"button\" class=\"Button\" value=\" Place Hyperlink \" onclick=\"HtmlEdit_InsertHrefValue(event, '" + id + "');\"/></td></tr>";
    s += "<tr><td colspan=\"2\" class=\"Tiny\" style=\"white-space: wrap;\"><a href=\"javascript:;\" onclick=\"HtmlEdit_BalloonClose('" + id + "');\">Close this window</a> when you're done.</td></tr>";
    s += "</table></div>";
    s += "</div><div class=\"Triangle\"></div></div>";

    $(id + "_holder").innerHTML = s;

    HtmlEdit_PositionBalloon(id);
}

function HtmlEdit_InsertHrefValue(event, id) {
    if (!document.all)
        event.preventDefault(); //FF,Safari

    event.returnValue = false;

    var editorFrame = $(id + '_window');
    if (!editorFrame)
        return;

    var doc = editorFrame.contentDocument ? editorFrame.contentDocument : editorFrame.contentWindow.document;
    if (!doc)
        return;

    var url = $(id + "_InsertHrefText").value;

    if (url.length == 0) {
        $(id + "_InsertHrefFeedback").innerHTML = "<div class=\"Warning\">No URL was entered.</div>";
        return;
    }

    $(id + "_InsertHrefFeedback").innerHTML = "";

    var actualUrl = url;
    var res = actualUrl.search(/^\w+\:\/\//gi);
    if (res == -1)
        actualUrl = "http://" + url;

    if (document.all) {
        editorFrame.contentWindow.focus();
        var sel = hrefSelection ? hrefSelection : doc.selection.createRange();
        var inner = sel.htmlText;
        if (inner.length == 0)
            inner = url;
        var NewHTML = "<a href=\"" + actualUrl + "\" target=\"_blank\">" + inner + "</font>";
        sel.pasteHTML(NewHTML);
    }
    else {
        editorFrame.contentWindow.focus();
        var sel = hrefSelection ? hrefSelection : editorFrame.contentWindow.getSelection();
        var n = editorFrame.contentWindow.document.createElement("A");
        n.innerHTML = sel.toString();
        if (n.innerHTML.length == 0)
            n.innerHTML = url;
        n.href = actualUrl;
        n.target = "_blank";
        HtmlEdit_InsertNodeAtSelection(editorFrame.contentWindow, n);
        editorFrame.contentWindow.focus();
    }

    HtmlEdit_OnSave(id);

}

function HtmlEdit_RemoveQuotes(event, id) {
    if (!document.all)
        event.preventDefault(); //FF,Safari

    event.returnValue = false;

    var editorFrame = $(id + '_window');
    if (!editorFrame)
        return;

    var doc = editorFrame.contentDocument ? editorFrame.contentDocument : editorFrame.contentWindow.document;
    if (!doc)
        return;

    if (document.all) {
        editorFrame.contentWindow.focus();
        var sel = doc.selection.createRange();
        sel.expand("word");
        var inner = sel.htmlText;
        if (inner.length == 0)
            return;
        inner = inner.replace(/<\/?div[^>]+\>/gi, "");
        sel.pasteHTML(inner);
    }
    else {
        editorFrame.contentWindow.focus();
        var sel = editorFrame.contentWindow.getSelection();
        var n = editorFrame.contentWindow.document.createElement("span");
        var inner = sel.toString().replace(/\n/gi, "<br/>");
        //alert(inner);
        //inner = inner.replace(/<\/?div[^>]+\>/gi, "");
        // alert(inner);
        n.innerHTML = inner;
        HtmlEdit_InsertNodeAtSelection(editorFrame.contentWindow, n);
        editorFrame.contentWindow.focus();
    }
}

function HtmlEdit_InsertHtml(html, id) {
    var editorFrame = $(id + '_window');
    if (!editorFrame)
        return;

    var doc = editorFrame.contentDocument ? editorFrame.contentDocument : editorFrame.contentWindow.document;
    if (!doc)
        return;

    if (document.all) {
        // var m_scroll = doc.scrollTop;

        editorFrame.contentWindow.focus();
        editorFrame.contentWindow.focus();

        var sel = doc.selection.createRange();
        sel.pasteHTML(html);
        editorFrame.contentWindow.focus();

        // doc.scrollTop = m_scroll;

    }
    else {
        editorFrame.contentWindow.focus();
        var sel = editorFrame.contentWindow.getSelection();
        var n = doc.createElement("span");
        n.innerHTML = html;
        HtmlEdit_InsertNodeAtSelection(editorFrame.contentWindow, n);
        editorFrame.contentWindow.focus();
    }
    HtmlEdit_OnSave(id);
}

function HtmlEdit_InsertNodeAtSelection(win, insertNode) {
    // get current selection
    var sel = win.getSelection();

    // get the first range of the selection
    // (there's almost always only one range)
    var range = sel.getRangeAt(0);

    // deselect everything
    sel.removeAllRanges();

    // remove content of current selection from document
    range.deleteContents();

    // get location of current selection
    var container = range.startContainer;
    var pos = range.startOffset;

    // make a new range for the new selection
    range = document.createRange();

    if (container.nodeType == 3 && insertNode.nodeType == 3) {

        // if we insert text in a textnode, do optimized insertion
        container.insertData(pos, insertNode.nodeValue);

        // put cursor after inserted text
        range.setEnd(container, pos + insertNode.length);
        range.setStart(container, pos + insertNode.length);

    }
    else {

        var afterNode;
        if (container.nodeType == 3) {

            // when inserting into a textnode
            // we create 2 new textnodes
            // and put the insertNode in between

            var textNode = container;
            container = textNode.parentNode;
            var text = textNode.nodeValue;

            // text before the split
            var textBefore = text.substr(0, pos);
            // text after the split
            var textAfter = text.substr(pos);

            var beforeNode = document.createTextNode(textBefore);
            afterNode = document.createTextNode(textAfter);

            // insert the 3 new nodes before the old one
            container.insertBefore(afterNode, textNode);
            container.insertBefore(insertNode, afterNode);
            container.insertBefore(beforeNode, insertNode);

            // remove the old node
            container.removeChild(textNode);

        }
        else {

            // else simply insert the node
            afterNode = container.childNodes[pos];
            container.insertBefore(insertNode, afterNode);
        }

        //range.setEnd(afterNode, 0);
        //range.setStart(afterNode, 0);
    }
    if (range.endOffset > 0)
        sel.addRange(range);
}

function HtmlEdit_ForeColour(event, id) {
    if (!document.all)
        event.preventDefault(); //FF,Safari

    event.returnValue = false;

    HtmlEdit_BuildColorPicker(id, 'fg');
}

function HtmlEdit_Highlight(event, id) {
    if (!document.all)
        event.preventDefault(); //FF,Safari

    event.returnValue = false;

    HtmlEdit_BuildColorPicker(id, 'bg');
}

function HtmlEdit_FontSize(event, id) {
    if (!document.all)
        event.preventDefault(); //FF,Safari

    event.returnValue = false;

    HtmlEdit_BuildFontSizePicker(id);
}

function HtmlEdit_SetColour(event, id, type, colour) {
    if (!document.all)
        event.preventDefault(); //FF,Safari

    event.returnValue = false;

    var editorFrame = $(id + '_window');

    if (!editorFrame)
        return;

    var doc = editorFrame.contentDocument ? editorFrame.contentDocument : editorFrame.contentWindow.document;
    if (!doc)
        return;

   

    if (type == 'bg') {
        if (document.all) {
            
            var sel = doc.selection.createRange();
            var NewHTML = "<font style=\"background-color:" + colour + "\">" + sel.htmlText + "</font>";
            sel.pasteHTML(NewHTML);
        }
        else {
            var sel = editorFrame.contentWindow.getSelection();
            var n = editorFrame.contentWindow.document.createElement("font");
            n.innerHTML = sel.toString();
            if (n.innerHTML.length == 0)
                n.innerHTML = url;
            n.style.backgroundColor = colour;
            HtmlEdit_InsertNodeAtSelection(editorFrame.contentWindow, n);
        }
    }
    else {
        editorFrame.contentWindow.document.execCommand("forecolor", false, colour);
    }

    HtmlEdit_CloseColourPickerDelayed(id);
    HtmlEdit_OnSave(id);
}

function HtmlEdit_InsertHR(event, id) {
    if (!document.all)
        event.preventDefault(); //FF,Safari

    event.returnValue = false;

    HtmlEdit_InsertHtml("<hr size=\"1\"/>", id);
}

function HtmlEdit_InsertQuote(event, id) {
    if (!document.all)
        event.preventDefault(); //FF,Safari

    event.returnValue = false;

    var editorFrame = $(id + '_window');

    if (!editorFrame)
        return;

    var doc = editorFrame.contentDocument ? editorFrame.contentDocument : editorFrame.contentWindow.document;
    if (!doc)
        return;

    if (document.all) {
        editorFrame.contentWindow.focus();
        var sel = doc.selection.createRange();
        if (sel.htmlText.length == 0) {
            alert('Please highlight a selection of text that you wish to format as a quote, then try again.');
            return;
        }
        sel.expand("word");
        var NewHTML = "<blockquote type=\"cite\" class=\"Quote\">" + sel.htmlText + "</blockquote>";
        sel.pasteHTML(NewHTML);
    }
    else {
        editorFrame.contentWindow.focus();
        var sel = editorFrame.contentWindow.getSelection();
        var n = editorFrame.contentWindow.document.createElement("blockquote");
        if (sel.rangeCount > 0) {
            var range = sel.getRangeAt(0);
            var docFragment = range.cloneContents();
            var tmpDiv = document.createElement("div");
            tmpDiv.appendChild(docFragment);
            n.innerHTML = tmpDiv.innerHTML;
        }

       // n.innerHTML = sel.toString().replace(/\n/g, '<br />');
        $j(n).attr('type', 'cite');

        if (!n.innerHTML
            || n.innerHTML.length == 0) {
            alert('Please highlight a selection of text that you wish to format as a quote, then try again.');
            return;
        }
        n.className = "Quote";
        HtmlEdit_InsertNodeAtSelection(editorFrame.contentWindow, n);
    }
    HtmlEdit_OnSave(id);
}
function MakeHCommand(id, size) {
    if (document.all)
        return " onclick=\"HtmlEdit_Do(event, '" + id + "', 'FormatBlock', 'Heading " + size + "');\"";
    else
        return " onclick=\"HtmlEdit_Do(event, '" + id + "', 'FormatBlock', 'H" + size + "');\"";
}
function HtmlEdit_FontSizeApply(event, id, heading, pts) {
    HtmlEdit_Do(event, id, 'RemoveFormat');
    if (heading) {
        if (document.all)
            HtmlEdit_Do(event, id, 'FormatBlock', 'Heading ' + heading);
        else
            HtmlEdit_Do(event, id, 'FormatBlock', 'H' + heading);
    }
    else {
        HtmlEdit_Do(event, id, 'FormatBlock', '<p>');
        HtmlEdit_Do(event, id, 'FontSize', pts);
    }
}
function HtmlEdit_BuildFontSizePicker(id) {
    var editorFrame = $(id + '_window');
    if (!editorFrame)
        return;

    var atts = " unselectable=\"on\" onmouseover=\"this.style.border='1px solid #98B5E2';this.style.background='#C1D2EE url(/v2.0/images/menu/highlight.gif) repeat-x';\" onmouseout=\"this.style.border='1px solid transparent';this.style.background='none';\" style=\"padding: 2px; cursor: pointer; border: 1px solid transparent;\"";
    var s = "";
    s += "<div class=\"UserHtml\" id=\"" + id + "_table\" unselectable=\"on\" onmouseout=\"HtmlEdit_CloseColourPicker('" + id + "');\" onmousemove=\"HtmlEdit_ColourPickerCancelClose()\" style=\"position: absolute; border: 1px solid #d3d3d3; background-color: #fbfbfb; width: 200px;\">";
    s += "<div " + atts + " onclick=\"HtmlEdit_FontSizeApply(event, '" + id + "', 0, 'normal');\">Normal</div>";
    s += "<div " + atts + " onclick=\"HtmlEdit_FontSizeApply(event, '" + id + "', 0, '1');\"><font size=\"1\" unselectable=\"on\" style=\"margin:2px;\">Size 1</font></div>";
    s += "<div " + atts + " onclick=\"HtmlEdit_FontSizeApply(event, '" + id + "', 0, '2');\"><font size=\"2\" unselectable=\"on\" style=\"margin:2px;\">Size 2</font></div>";
    s += "<div " + atts + " onclick=\"HtmlEdit_FontSizeApply(event, '" + id + "', 0, '3');\"><font size=\"3\" unselectable=\"on\" style=\"margin:2px;\">Size 3</font></div>";
    s += "<div " + atts + " onclick=\"HtmlEdit_FontSizeApply(event, '" + id + "', 0, '4');\"><font size=\"4\" unselectable=\"on\" style=\"margin:2px;\">Size 4</font></div>";
    s += "<div " + atts + " onclick=\"HtmlEdit_FontSizeApply(event, '" + id + "', 0, '5');\"><font size=\"5\" unselectable=\"on\" style=\"margin:2px;\">Size 5</font></div>";
    s += "<hr/>";
    s += "<div " + atts + " onclick=\"HtmlEdit_FontSizeApply(event, '" + id + "', 4, '0');\"><h4 unselectable=\"on\" style=\"margin:2px;\">Heading 4</h4></div>";
    s += "<div " + atts + " onclick=\"HtmlEdit_FontSizeApply(event, '" + id + "', 3, '0');\"><h3 unselectable=\"on\" style=\"margin:2px;\">Heading 3</h3></div>";
    s += "<div " + atts + " onclick=\"HtmlEdit_FontSizeApply(event, '" + id + "', 2, '0');\"><h2 unselectable=\"on\" style=\"margin:2px;\">Heading 2</h2></div>";
    s += "<div " + atts + " onclick=\"HtmlEdit_FontSizeApply(event, '" + id + "', 1, '0');\"><h1 unselectable=\"on\" style=\"margin:2px;\">Heading 1</h1></div>";

    s += "</div>";

    $(id + "_holder").innerHTML = s;

    var table = $(id + "_table");
    //table.style.position = "absolute";
    table.style.top = (mouseY - PosY($(id + "_holder"))) + "px";
    table.style.left = (mouseX - PosX($(id + "_holder"))) + "px";
    table.style.zIndex = 200;
}

function HtmlEdit_BuildColorPicker(id, type) {
    var editorFrame = $(id + '_window');
    if (!editorFrame)
        return;

    var s = "";

    //var col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#D1ECF2,#CEE1CA,#EBE3F6,#DAD6EF,#F3E9C8,#C3C7D6,#CCD5D1,#D0EBD1,#E1D2DF,#E9D5C9,#EDC4DA,#E5E6E8,#C8F2DB,#E0D8EE,#FBF076,#FFFFFF";

    var top = "FFFFFF,000000,F6EAD2,1A3E72,527AAE,B84540,96B655,7F66A0,4AACC5,F59D56";
    var mid = "D2D2D2,BABABA,9A9A9A,828282,727272,"; // grays
    mid += "727272,6A6A6A,4E4E4E,363636,1E1E1E,";
    mid += "B6ADA6,9A968D,726F6A,4E4A47,363231,";
    mid += "C2CEDA,869AB5,4E6B97,122E53,0C1E32,";
    mid += "D2DEF4,A6BAD5,7A9AC1,3C557E,26364F,";
    mid += "EECECF,DA9E9E,CA726E,86332F,55221E,";
    mid += "E1EED2,CADAAB,AFC67E,6B823E,425126,";
    mid += "DFD9E7,BFB2CE,9F8DB7,5F4C79,403351,";
    mid += "D3EAF2,A5D5E3,78C1D4,388096,255664,";
    mid += "FCE7D6,FACEAB,F7B680,B77640,7A4E2B";

    var std = "B20D11,E9161D,FFB90B,FFFF00,96D642,19AA41,02B2EE,0072BB,2D3799,6F3098";

    var fieldID = id;

    s += "<div id=\"" + fieldID + "_table\" unselectable=\"on\" onmouseout=\"HtmlEdit_CloseColourPicker('" + fieldID + "');\" onmousemove=\"HtmlEdit_ColourPickerCancelClose()\" style=\"position: absolute;border: 1px solid #D3D3D3;background-color:#FBFBFB;width:174px;\">";
    {
        // top row
        s += "<div style='margin:1px' onmousemove=\"HtmlEdit_ColourPickerCancelClose()\">";
        {
            var ar = top.split(',');
            for (var i = 0; i < ar.length; i++)
                s += "<div onmousedown=\"HtmlEdit_SetColour(event, '" + id + "','" + type + "','#" + ar[i] + "')\" onmousemove=\"ColourPickerCancelClose()\" style='background-color:#" + ar[i] + ";width: 11px; height: 11px; cursor: pointer;border:1px solid #cccccc;margin:2px;float:left;'><img src=\"/v2.0/images/space.gif\" width=1 height=1/></div>";
        }
        s += "</div>";
        // middle
        s += "<div style='margin:1px' onmousemove=\"HtmlEdit_ColourPickerCancelClose()\">";
        {
            var ar = mid.split(',');
            s += "<div style=\"float:left; width:11px;border:1px solid #808080;margin:2px;\">";
            for (var i = 0; i < ar.length; i++) {
                if ((i % 5) == 0 && i > 0)
                    s += "</div><div style=\"float:left; width:11px;border:1px solid #808080;margin:2px;\">";
                s += "<div onmousedown=\"HtmlEdit_SetColour(event, '" + id + "','" + type + "','#" + ar[i] + "')\" onmousemove=\"HtmlEdit_ColourPickerCancelClose()\" style='background-color:#" + ar[i] + ";width: 11px; height: 11px; cursor: pointer;'><img src=\"/v2.0/images/space.gif\" width=1 height=1/></div>";
            }
            s += "</div>";
        }
        s += "</div>";
        // standard
        s += "<div style='margin:1px;' onmousemove=\"HtmlEdit_ColourPickerCancelClose()\">";
        {
            var ar = std.split(',');
            for (var i = 0; i < ar.length; i++)
                s += "<div onmousedown=\"HtmlEdit_SetColour(event, '" + id + "','" + type + "','#" + ar[i] + "')\" onmousemove=\"HtmlEdit_ColourPickerCancelClose()\" style='background-color:#" + ar[i] + ";width: 11px; height: 11px; cursor: pointer;border:1px solid #cccccc;margin:2px;float:left;'><img src=\"/v2.0/images/space.gif\" width=1 height=1/></div>";
        }
        s += "</div>";
    }
    s += "</div>";

    // var ar = colors.split(',');
    //    
    //    s += "<div id=\""+id+"_table\" unselectable=\"on\" onmouseout=\"HtmlEdit_CloseColourPicker('"+id+"');\" onmousemove=\"HtmlEdit_ColourPickerCancelClose()\" style=\"position: absolute; border: 1px solid #555555; background-color: #ffffff; width: 170px;\">";
    //   // s += "<tr>";
    //   
    //    for(var i=0;i<ar.length;i++)
    //    {
    //        //if ((i%10)==0 && i>0)
    //        //{
    //        //    s += "</tr><tr>";
    //        //}
    //        s += "<div onmousemove=\"HtmlEdit_ColourPickerCancelClose()\" unselectable=\"on\" style=\"float: left; width: 15px; height: 12px; cursor: pointer; margin: 1px; background-color:"+ar[i]+";\" onclick=\"HtmlEdit_SetColour(event, '"+id+"','"+type+"','"+ar[i]+"');\"></div>";
    //    }
    //    //s += "</tr>";
    //    s += "</div>";

    $(id + "_holder").innerHTML = s;

    var table = $(id + "_table");
    //table.style.position = "absolute";
    table.style.top = (mouseY - PosY($(id + "_holder"))) + "px";
    table.style.left = (mouseX - PosX($(id + "_holder"))) + "px";
    table.style.zIndex = 200;

}
var htmlEdit_colourPickerTimeout;
function HtmlEdit_ColourPickerCancelClose() {
    if (htmlEdit_colourPickerTimeout)
        clearTimeout(htmlEdit_colourPickerTimeout);
}

function HtmlEdit_CloseColourPicker(id) {
    HtmlEdit_ColourPickerCancelClose();
    htmlEdit_colourPickerTimeout = setTimeout("HtmlEdit_CloseColourPickerDelayed('" + id + "')", 500);
}
function HtmlEdit_CloseColourPickerDelayed(id) {
    $(id + '_holder').innerHTML = '';
}

function HtmlEdit_OnFileUploaded(o) {
    //imageguid, originalWidth, originalHeight, fileName, fileSize, type, id
    var settingsDiv = $(o.ID + "_settings");
    if (!settingsDiv)
        return;
    var id = o.ID;
    var s = "";
    s += "<input type=\"hidden\" id=\"" + id + "_guid\" value=\"" + o.Guid + "\"/>";
    s += "<input type=\"hidden\" id=\"" + id + "_filename\" value=\"" + HtmlEncode(o.Name) + "\"/>";
    s += "<input type=\"hidden\" id=\"" + id + "_filesize\" value=\"" + HtmlEncode(o.Size) + "\"/>";

    if (o.Type == "image") {
        var width = parseInt(o.Width), height = parseInt(o.Height);
        var percent = 100;
        if (width > 400 || height > 400) {
            var ratio = 400 / width;
            width = 400;
            height = parseInt(height * ratio);
            percent = parseInt(ratio * 100);
        }
        s += "<table><tr valign=\"top\">";
        s += "<td><img id=\"" + id + "_thumb\" src=\"/?SendFile=" + o.Guid + "&width=" + width + "&height=" + height + "&caption=Preview Only&border=1\" width=\"" + width + "\" height=\"" + height + "\" /></td>";
        s += "<td>";
        s += "<table>";
        s += "<tr><td nowrap=\"nowrap\">";

        s += "<input type=\"hidden\" id=\"" + id + "_originalWidth\" value=\"" + o.Width + "\"/>";
        s += "<input type=\"hidden\" id=\"" + id + "_originalHeight\" value=\"" + o.Height + "\"/>";
        s += "<input type=\"hidden\" id=\"" + id + "_width\" value=\"" + width + "\"/>";
        s += "<input type=\"hidden\" id=\"" + id + "_height\" value=\"" + height + "\"/>";

        s += "Original Size:</td><td><b>" + o.Width + "x" + o.Height + "</b></td></tr>";
        s += "<tr><td>Insert as:</td><td><input type=\"text\" style=\"width: 50px\" id=\"" + id + "_percent\" onKeyDown=\"return OnEnterKeyDown(event, function(){ HtmlEdit_CalculateDimensionsDelayed('" + id + "');HtmlEdit_PlaceImage('" + id + "'); });\" onkeyup=\"HtmlEdit_CalculateDimensions('" + id + "');\" value=\"" + percent + "\" />% <span id=\"" + id + "_dimensionPreview\">(" + width + "x" + height + ")</span></td></tr>"
        s += "<tr><td>Alignment:</td><td><select id=\"" + id + "_align\"><option value=\"\">In-line &nbsp;&nbsp;&nbsp;</option><option value=\"left\">Left</option><option value=\"right\">Right</option></select></td></tr>";
        s += "<tr><td>Caption:</td><td><input type=\"text\" id=\"" + id + "_caption\" onkeyup=\"HtmlEdit_CalculateDimensions('" + id + "')\" maxlength=\"50\" style=\"width: 150px\"/></td></tr>";
        s += "<tr><td>&nbsp;</td><td><input type=\"checkbox\" checked=\"checked\" onclick=\"HtmlEdit_CalculateDimensions('" + id + "')\" id=\"" + id + "_border\" value=\"1\" /> <label for=\"" + id + "_border\">Add a border</label></td></tr>";
        s += "<tr><td>&nbsp;</td><td><input type=\"checkbox\" " + (percent == 100 ? "disabled=\"disabled\"" : "checked=\"checked\"") + " id=\"" + id + "_linkToOriginal\" value=\"1\" /> <label for=\"" + id + "_linkToOriginal\">Create a link to the original sized file.</label></td></tr>";
        s += "<tr><td>&nbsp;</td><td><input type=\"button\" class=\"Button\" value=\" Place Image \" onclick=\"HtmlEdit_PlaceImage('" + id + "');\"/></td></tr>";
        s += "</table>";
        s += "</td></tr>";
        s += "<tr><td colspan=\"2\" class=\"Tiny\" style=\"white-space: wrap;\">When you're ready, <b>place your cursor into the editing window</b> and press <b>Place Image</b> to insert it at a specific location in your document. <b><a href=\"javascript:;\" onclick=\"HtmlEdit_BalloonClose('" + id + "');\">Close this window when you're done.</a></b></td></tr>";
        s += "</table>";

        settingsDiv.innerHTML = s;

        var balloon = $(id + "_InsertImageBalloon");
        balloon.style.width = (width + 230) + "px";
    }
    else {
        s += "<table>";
        s += "<tr valign=\"top\"><td>File Received:</td>";
        s += "<td>" + o.Name + " (" + o.Size + ")</td><td><input type=\"button\" class=\"Button\" value=\" Place File Link \" onclick=\"HtmlEdit_PlaceFile('" + id + "');\"/></td></tr>";
        s += "<tr><td colspan=\"3\" class=\"Tiny\">When you're ready, <b>place your cursor into the editing window</b> and press <b>Place File</b> to insert it at a specific location in your document. <b><a href=\"javascript:;\" onclick=\"HtmlEdit_BalloonClose('" + id + "');\">Close this window when you're done.</a></b></td></tr>";
        s += "</table>";
        settingsDiv.innerHTML = s;
    }

    HtmlEdit_PositionBalloon(id);

}

function HtmlEdit_BuildImageUrl(id) {
    var guid = $(id + "_guid").value;
    var width = $(id + "_width").value;
    var height = $(id + "_height").value;
    var caption = $(id + "_caption").value;
    var border = $(id + "_border").checked ? "1" : "";

    var s = "/?SendFile=" + guid;
    s += "&width=" + width;
    s += "&height=" + height;
    s += "&caption=" + URLEncode(caption);
    s += "&border=" + border;

    return s;
}

function HtmlEdit_PlaceImage(id) {
    var guid = $(id + "_guid").value;
    var width = $(id + "_width").value;
    var height = $(id + "_height").value;
    var caption = $(id + "_caption").value;
    var align = $(id + "_align").value;
    var link = $(id + "_linkToOriginal").checked;

    var s = "";

    if (link)
        s += "<a href=\"/?SendFile=" + guid + "\" target=\"_blank\">";

    s += "<img src=\"";
    s += HtmlEdit_BuildImageUrl(id);
    s += "\" width=\"" + width + "\" height=\"" + height + "\" border=\"0\" align=\"" + align + "\" alt=\"" + caption.replace(/>/g, "&gt;").replace(/</g, "&lt") + "\" />";

    if (link)
        s += "</a>";

    HtmlEdit_InsertHtml(s, id);
}
function HtmlEdit_PlaceFile2(id, guid, fileName, fileSize) {
    var s = "";
    s += "<a href=\"/?SendFile=" + guid + "\" class=\"FileLink\" target=\"_blank\">";
    s += fileName;
    s += "</a> (" + fileSize + ") ";

    HtmlEdit_InsertHtml(s, id);
}

function HtmlEdit_PlaceFile(id) {
    var guid = $(id + "_guid").value;
    var fileName = $(id + "_filename").value;
    var fileSize = $(id + "_filesize").value;
    var s = "";
    s += "<a href=\"/?SendFile=" + guid + "\" class=\"FileLink\" target=\"_blank\">";
    s += fileName;
    s += "</a> (" + fileSize + ") ";

    HtmlEdit_InsertHtml(s, id);
}

function HtmlEdit_BalloonClose(id) {
    $(id + "_holder").innerHTML = "";
}

