/*
    Display
    Configures and displays the editor according to values passed
*/
function Display(hidden_field,path,fwidth,fheight,content){
    hidden_name=hidden_field;   // use this to define the name of the field that contains the HTML on submission
    viewMode=1;                 // by default, set to design view
    wysiwyg_path=path;          // defines the path to use for the editor files (pallete, images, etc)
    frame_width=fwidth;         // sets the width of the editor on screen
    frame_height=fheight;       // sets the height of the editor on screen

    if( (browser.isWin32 && (browser.isGecko || browser.isIE5up))
            || ((browser.isMac || browser.isLinux || browser.isUnix) && browser.isGecko)) {
        DisplayEditor();
        LoadExistingContent(content);
        document.getElementById('wysiwyg_content').contentWindow.document.designMode='On';
        document.getElementById('wysiwyg_content').contentWindow.document.open();
        document.getElementById('wysiwyg_content').contentWindow.document.write('<head><style>P{MARGIN:0cm;} UL{MARGIN-TOP:0cm;MARGIN-BOTTOM:0cm;} BLOCKQUOTE{MARGIN-TOP:0cm;MARGIN-BOTTOM:0cm;} </style></head><body text="black" bgcolor="#FFFFCC" topmargin=40 rightmargin=40 bottommargin=40 leftmargin=40>' + content);
        document.getElementById('wysiwyg_content').contentWindow.document.close();
    }else{
        ta_rows=Math.round(fheight/15);
        ta_cols=Math.round(fwidth/8);
        DisplayTextArea();
        LoadExistingContent(content);
    }
}

/*
    DoTextFormat
    Performs specified commands on the selected text inside the IFRAME element
*/
function DoTextFormat(command, optn){
	if(document.getElementById('wysiwyg_content').contentWindow.document.queryCommandEnabled(command)){
		document.getElementById('wysiwyg_content').contentWindow.document.execCommand(command, false, optn);
		document.getElementById('wysiwyg_content').contentWindow.focus();
		return true;
	}else{
		document.getElementById('wysiwyg_content').contentWindow.focus();
		return false;
	}

}

/*
    SetColor
    Used to set the text or highlight color of the selected text in Gecko engine browsers
*/
function SetColor(color){
    elem=command+'0';
    document.getElementById('wysiwyg_content').contentWindow.focus();
    if(document.getElementById('wysiwyg_content').contentWindow.document.queryCommandEnabled(command)){
        document.getElementById('wysiwyg_content').contentWindow.document.execCommand(command, false, color);
    }else return false;
    document.getElementById('wysiwyg_content').contentWindow.focus();
    document.getElementById(elem).style.visibility='hidden';
    return true;
}

/*
    SetColorIE
    Used to set the text or highlight color of the selected text in MSIE - uses a different method for pop-up pallete window
*/
function SetColorIE(command,args){
    elem=command+'0';
    buttonElement=document.getElementById(elem);
    var color = showModalDialog("palette-ie.html", 0, 'resizable: no; help: no; status: no; scroll: no;');
    if(command=='hilitecolor') command='backcolor';
    if(document.getElementById('wysiwyg_content').contentWindow.document.queryCommandEnabled(command)){
        document.getElementById('wysiwyg_content').contentWindow.document.execCommand(command, false, color);
    }else return false;
    document.getElementById('wysiwyg_content').contentWindow.focus();
    return true;
}

/*
    GetOffsetTop
    Used to define position of pop-up pallete window in Gecko browsers
*/
function GetOffsetTop(elm){
    var mOffsetTop=elm.offsetTop;
    var mOffsetParent=elm.offsetParent;
    while(mOffsetParent){
        mOffsetTop += mOffsetParent.offsetTop;
        mOffsetParent=mOffsetParent.offsetParent;
    }
    return mOffsetTop;
}

/*
    GetOffsetLeft
    Used to define position of pop-up pallete window in Gecko browsers
*/
function GetOffsetLeft(elm){
    var mOffsetLeft=elm.offsetLeft;
    var mOffsetParent=elm.offsetParent;
    while(mOffsetParent){
        mOffsetLeft += mOffsetParent.offsetLeft;
        mOffsetParent=mOffsetParent.offsetParent;
    }
    return mOffsetLeft;
}

/*
    ProcessInfo
    Used in the onSubmit event for the form. Puts the HTML content into a hidden form field for the submission
*/
function ProcessInfo(){
    var htmlCode=document.getElementById('wysiwyg_content').contentWindow.document.body.innerHTML;
    document.getElementById('wysiwyg_hidden').value=htmlCode;
    return true;
}

/*
    LoadExistingContent
    Puts the passed content into the editor or textarea
*/
function LoadExistingContent(content){
    document.getElementById('wysiwyg_hidden').value=content;
}

/*
    ToggleMode
    Toggles between design view and source view in the IFRAME element    
*/
function ToggleMode(){
    if(browser.isIE5up){
        if(viewMode == 2){
            document.getElementById('wysiwyg_content').contentWindow.document.body.innerHTML = document.getElementById('wysiwyg_content').contentWindow.document.body.innerText;
            document.getElementById('wysiwyg_content').contentWindow.document.body.style.fontFamily = '';
            document.getElementById('wysiwyg_content').contentWindow.document.body.style.fontSize = '';
            document.getElementById('wysiwyg_content').contentWindow.focus();
            viewMode = 1; // WYSIWYG
        }else{
            document.getElementById('wysiwyg_content').contentWindow.document.body.innerText = document.getElementById('wysiwyg_content').contentWindow.document.body.innerHTML;
            document.getElementById('wysiwyg_content').contentWindow.document.body.style.fontFamily = 'monospace';
            document.getElementById('wysiwyg_content').contentWindow.document.body.style.fontSize = '10pt';
            document.getElementById('wysiwyg_content').contentWindow.focus();
            viewMode = 2; // Code
        }
    }else{
        if(viewMode == 2){
            var html = document.getElementById('wysiwyg_content').contentWindow.document.body.ownerDocument.createRange();
            html.selectNodeContents(document.getElementById('wysiwyg_content').contentWindow.document.body);
            document.getElementById('wysiwyg_content').contentWindow.document.body.innerHTML = html.toString();
            document.getElementById('wysiwyg_content').contentWindow.document.body.style.fontFamily = '';
            document.getElementById('wysiwyg_content').contentWindow.document.body.style.fontSize = '';
            document.getElementById('toolbars').style.visibility='visible';
            viewMode = 1; // WYSIWYG
        }else{
            var html = document.createTextNode(document.getElementById('wysiwyg_content').contentWindow.document.body.innerHTML);
            document.getElementById('wysiwyg_content').contentWindow.document.body.innerHTML = '';
            document.getElementById('wysiwyg_content').contentWindow.document.body.appendChild(html);
            document.getElementById('wysiwyg_content').contentWindow.document.body.style.fontFamily = 'monospace';
            document.getElementById('wysiwyg_content').contentWindow.document.body.style.fontSize = '10pt';
            document.getElementById('toolbars').style.visibility='hidden';
            viewMode = 2; // Code
        }
    }
}

/*
    CheckSpelling
    Uses the ieSpell Active X control for MSIE browsers.
*/
function CheckSpelling(){
    try{
        var tmpis = new ActiveXObject('ieSpell.ieSpellExtension');
        tmpis.CheckAllLinkedDocuments(document);
    }
    catch(exception){
        if(exception.number==-2146827859){
            if(confirm('ieSpell not detected.  Click Ok to go to download page.'))
                window.open('http://www.iespell.com/download.php','Download');
        }
        else
            alert('Error Loading ieSpell: Exception ' + exception.number);
    }
}

/*
    InsertTable
    Used with Gecko browsers for inserting a table into the IFRAME content window
*/
function InsertTable(border,padding,spacing){
    e = document.getElementById('wysiwyg_content');
    colstext = prompt('Enter the number of columns per row.');
    rowstext = prompt('Enter the number of rows to create.');
    rows = parseInt(rowstext);
    cols = parseInt(colstext);
    if((rows > 0) && (cols > 0)){
        table = e.contentWindow.document.createElement('table');
        table.setAttribute('border', border);
        table.setAttribute('cellpadding', padding);
        table.setAttribute('cellspacing', spacing);
        tbody = e.contentWindow.document.createElement('tbody');
        for (var i=0; i < rows; i++) {
            tr =e.contentWindow.document.createElement('tr');
            for (var j=0; j < cols; j++) {
                td =e.contentWindow.document.createElement('td');
                br =e.contentWindow.document.createElement('br');
                td.appendChild(br);
                tr.appendChild(td);
            }
            tbody.appendChild(tr);
        }
        table.appendChild(tbody);
        insertNodeAtSelection(e.contentWindow, table);
    }
}

/*
    insertNodeAtSelection
    Used in the Gecko browser InsertTable function
*/
function insertNodeAtSelection(win, insertNode){
    var sel = win.getSelection();           // get current selection
    var range = sel.getRangeAt(0);          // get the first range of the selection (there's almost always only one range)
    sel.removeAllRanges();                  // deselect everything
    range.deleteContents();                 // remove content of current selection from document
    var container = range.startContainer;   // get location of current selection
    var pos = range.startOffset;
    range=document.createRange();           // make a new range for the new selection

    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;

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

          var beforeNode = document.createTextNode(textBefore);
          var 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);
        }
    }
}

/*
    DisplayEditor
    Used to display the actual wysiwyg editor
*/
function DisplayEditor(){
    document.write('   <input type="hidden" name="'+hidden_name+'" id="wysiwyg_hidden">');
    document.write('   <table cellpadding="0" cellspacing="1" border="0" bgcolor="#cccccc">');
    document.write('    <tr>');
    document.write('     <td>');
    document.write('      <table width="100%" border="0" cellspacing="3" cellpadding="0">');
    document.write('       <tr>');
    document.write('        <td valign="top">');
    document.write('         <div id="toolbars">');
    document.write('          <select onChange="DoTextFormat(\'fontname\',this.options[this.selectedIndex].value);this.selectedIndex=0;">');
    document.write('           <option value="fuente">Tipo de letra</option>');
    document.writeln('         <option value="Arial, sans-serif">Arial</option>');
    document.writeln('         <option value="Times New Roman, serif">Times New Roman</option>');
    document.writeln('         <option value="Courier New, monospace">Courier New</option>');
    document.writeln('         <option value="Tahoma, sans-serif">Tahoma</option>');
    document.writeln('         <option value="Verdana, sans-serif">Verdana</option>');
    document.write('          </select>');
    document.write('          <select onChange="DoTextFormat(\'fontSize\',this.options[this.selectedIndex].value);this.selectedIndex=0;">');
    document.write('           <option value="tamano">Tamaño</option>');
    document.write('           <option value="1">1</option>');
    document.write('           <option value="2">2</option>');
    document.write('           <option value="3">3</option>');
    document.write('           <option value="4">4</option>');
    document.write('           <option value="5">5</option>');
    document.write('           <option value="6">6</option>');
    document.write('           <option value="7">7</option>');
    document.write('          </select>');
    document.write('          <img align="top" src="'+wysiwyg_path+'/imagenes/richtext/separator.png"><hr>');
    document.write('          <img align="top" alt="Negrita" title="Negrita" class="butClass" src="'+wysiwyg_path+'/imagenes/richtext/bold.png" onClick="DoTextFormat(\'bold\',\'\')">');
    document.write('          <img align="top" alt="Cursiva" title="Cursiva" class="butClass" src="'+wysiwyg_path+'/imagenes/richtext/italic.png" onClick="DoTextFormat(\'italic\',\'\')">');
    document.write('          <img align="top" alt="Subrayado" title="Subrayado" class="butClass" src="'+wysiwyg_path+'/imagenes/richtext/underline.png" onClick="DoTextFormat(\'underline\',\'\')">');
    document.write('          <img align="top" src="'+wysiwyg_path+'/imagenes/richtext/separator.png">');
    document.write('          <img align="top" alt="Izquierda" title="Izquierda" class="butClass" src="'+wysiwyg_path+'/imagenes/richtext/left.png" onClick="DoTextFormat(\'justifyleft\',\'\')">');
    document.write('          <img align="top" alt="Centrar" title="Centrar" class="butClass" src="'+wysiwyg_path+'/imagenes/richtext/center.png" onClick="DoTextFormat(\'justifycenter\',\'\')">');
    document.write('          <img align="top" alt="Derecha" title="Derecha" class="butClass" src="'+wysiwyg_path+'/imagenes/richtext/right.png" onClick="DoTextFormat(\'justifyright\',\'\')">');
    document.write('          <img align="top" alt="Ajustar" title="Ajustar" class="butClass" src="'+wysiwyg_path+'/imagenes/richtext/full.png" onClick="DoTextFormat(\'justifyfull\',\'\')">');
    document.write('          <img align="top" src="'+wysiwyg_path+'/imagenes/richtext/separator.png">');
    document.write('          <img align="top" alt="Crear lista" title="Crear lista" class="butClass" src="'+wysiwyg_path+'/imagenes/richtext/bullist.png" onClick="DoTextFormat(\'insertunorderedlist\',\'\')">');
    document.write('          <img align="top" alt="Sangría" title="Sangría" src="'+wysiwyg_path+'/imagenes/richtext/indent.png" class=butClass onClick="DoTextFormat(\'indent\',\'\')">');
    document.write('          <img align="top" alt="Quitar sangría" title="Quitar sangría" src="'+wysiwyg_path+'/imagenes/richtext/outdent.png" class=butClass onClick="DoTextFormat(\'outdent\',\'\')">');
    document.write('          <img align="top" src="'+wysiwyg_path+'/imagenes/richtext/separator.png">');
    document.write('          <img align="top" alt="Línea horizontal" title="Línea horizontal" class="butClass" src="'+wysiwyg_path+'/imagenes/richtext/rule.png" onClick="DoTextFormat(\'inserthorizontalrule\',\'\')">');
    document.write('          <img align="top" alt="Quitar formato" title="Quitar formato" class="butClass" src="'+wysiwyg_path+'/imagenes/richtext/unformat.png" onClick="DoTextFormat(\'removeformat\',\'\')">');
//    document.write('          <img align="top" src="'+wysiwyg_path+'/imagenes/richtext/separator.png">');
//    document.write('          <img align="top"  alt="Deshacer" title="Deshacer" class="butClass" src="'+wysiwyg_path+'/imagenes/richtext/undo.png" onClick="DoTextFormat(\'undo\',\'\')">');
//    document.write('          <img align="top"  alt="Rehacer" title="Rehacer" class="butClass" src="'+wysiwyg_path+'/imagenes/richtext/redo.png" onClick="DoTextFormat(\'redo\',\'\')">');
//    document.write('          <img align="top" src="'+wysiwyg_path+'/imagenes/richtext/separator.png">');
//    document.write('          <img align="top"  alt="Cortar" title="Cortar" class="butClass" src="'+wysiwyg_path+'/imagenes/richtext/cut.png" onClick="DoTextFormat(\'cut\',\'\')">');
//    document.write('          <img align="top"  alt="Pegar" title="Pegar" class="butClass"   src="'+wysiwyg_path+'/imagenes/richtext/paste.png" onClick="DoTextFormat(\'paste\',\'\')">');
//    document.write('          <img align="top"  alt="Copiar" title="Copiar" class="butClass" src="'+wysiwyg_path+'/imagenes/richtext/copy.png" onClick="DoTextFormat(\'copy\',\'\')">');
    document.write('         </div>');
    document.write('        </td>');
    document.write('       </tr>');
    document.write('      </table>');
    document.write('      <iframe id="wysiwyg_content" style="width:'+frame_width+'px; height:'+frame_height+'px;" scrolling="yes"></iframe>');
//    if(browser.isIE5up){
//       document.write('      <iframe width="175" height="125" id="forecolor0" src="'+wysiwyg_path+'/palette-ie.html" style="visibility:hidden; position: absolute; left: 0px; top: 0px;"></iframe>');
//        document.write('      <iframe width="175" height="125" id="hilitecolor0" src="'+wysiwyg_path+'/palette-ie.html" style="visibility:hidden; position: absolute; left: 0px; top: 0px;"></iframe>');
//    }else{
//        document.write('      <iframe width="175" height="125" id="forecolor0" src="'+wysiwyg_path+'/palette.html" style="visibility:hidden; position: absolute; left: 0px; top: 0px;"></iframe>');
//        document.write('      <iframe width="175" height="125" id="hilitecolor0" src="'+wysiwyg_path+'/palette.html" style="visibility:hidden; position: absolute; left: 0px; top: 0px;"></iframe>');
//    }
    document.write('      <table width="100%" border="0" cellspacing="3" cellpadding="0" bgcolor="#dfdfdf">');
    document.write('       <tr>');
    document.write('        <td>');
    document.write('        </td>');
    document.write('        <td align="right">');
//    if(browser.isIE5up)
//        document.write('         <img alt="Spell Check" title="Spell Check" class="butClass" src="'+wysiwyg_path+'/imagenes/richtext/spelling.png" onClick="CheckSpelling()">');
    document.write('         <img alt="Ver HTML" title="Ver HTML" class="butClass" src="'+wysiwyg_path+'/imagenes/richtext/mode.png" onClick="ToggleMode()">');
    document.write('        </td>');
    document.write('       </tr>');
    document.write('      </table>');
    document.write('     </td>');
    document.write('    </tr>');
    document.write('   </table>');
    document.write('   <br>');
}

/*
    DisplayTextArea
    Displays a textarea input as well as a generic message to the user letting them know their browser does not support the programming
*/
function DisplayTextArea(){
    document.write('<input type="hidden" name="CVRichText" value=0>');
    document.write('<textarea name="'+hidden_name+'" id="wysiwyg_hidden" rows="'+ta_rows+'" cols="'+ta_cols+'"></textarea><br>');
}




/*  UNUSED FUNCTIONS FROM OLD VERSION
function setFont(font){
    if(browser.isIE5up){
        //retrieve selected range
        var sel=document.getElementById('wysiwyg_content').contentWindow.document.selection;
        if(sel!=null){
            var newselectionRange=sel.createRange();
            newselectionRange.select();
        }
    }else{
        document.getElementById('wysiwyg_content').contentWindow.focus();
    }
    if(document.getElementById('wysiwyg_content').contentWindow.document.queryCommandEnabled(command)){
        document.getElementById('wysiwyg_content').contentWindow.document.execCommand(command, false, color);
    }else return false;
    document.getElementById('wysiwyg_content').contentWindow.focus();
    return true;
}

function doImage(mypic){
    document.getElementById('wysiwyg_content').contentWindow.focus()
    if(viewMode==1){
        thisimage=mypic.value;
        var x=document.getElementById('wysiwyg_content').contentWindow.document.selection.createRange();
        x.execCommand('insertimage', false, thisimage);
        x.select();
        document.getElementById('wysiwyg_content').contentWindow.focus()
        numPics++;
    }
}
*/

