//
// openWYSIWYG v1.01 Copyright (c) 2006 openWebWare.com
// This copyright notice MUST stay intact for use.
//
// An open source WYSIWYG editor for use in web based applications.
// For full source code and docs, visit http://www.openwebware.com/
//

/* ---------------------------------------------------------------------- *\
  Global Variables: Set global variables such as images directory, 
	                  WYSIWYG Height, Width, and CSS Directory.
\* ---------------------------------------------------------------------- */


imagesDir = "icons/";// Images Directory
cssDir = "styles/";// CSS Directory
popupsDir = "popups/";// Popups Directory

// WYSIWYG Width and Height
wysiwygWidth = 600;
wysiwygHeight = 200;

// Include Style Sheet
document.write('<link rel="stylesheet" type="text/css" href="' +cssDir+ 'styles.css">\n');

// emotion table
var Emotion1 = [10,3];

// Browset type
var browserName = navigator.appName;

// List color
var ColorLists = new Array();
    ColorLists[0] = ['#000000','#993300','#333300','#003300','#003366','#000080','#333399','#333333'];
    ColorLists[1] = ['#800000','#FF6600','#808000','#008000','#008080','#0000FF','#666699','#808080'];
    ColorLists[2] = ['#FF0000','#FF9900','#99CC00','#339966','#33CCCC','#3366FF','#800080','#999999'];
    ColorLists[3] = ['#FF00FF','#FFCC00','#FFFF00','#00FF00','#00FFFF','#00CCFF','#993366','#C0C0C0'];
    ColorLists[4] = ['#FF99CC','#FFCC99','#FFFF99','#CCFFCC','#CCFFFF','#99CCFF','#666699','#FFFFFF'];
// List of font sizes
var FontSizes = ['1','2','3','4','5','6','8'];
    
// toolbar one
var buttonName = new Array();
  	buttonName[0]  = "size";
  	buttonName[1]  = "bold";
  	buttonName[2]  = "italic";
  	buttonName[3]  = "underline";
  	buttonName[4]  = "seperator";
	buttonName[5]  = "forecolor";
	buttonName[6]  = "backcolor";
	buttonName[7]  = "seperator";
	buttonName[8]  = "justifyleft";
	buttonName[9]  = "justifycenter";
	buttonName[10] = "justifyright";
	buttonName[11]  = "seperator";
    buttonName[12]  = "cut";
	buttonName[13]  = "copy";
	buttonName[14]  = "paste";
	buttonName[16]  = "seperator";
  	buttonName[17]  = "undo";
	buttonName[18]  = "redo";
  	buttonName[19]  = "seperator";
  	buttonName[20]  = "insertimage";
  	buttonName[21]  = "createlink";
	buttonName[22]  = "seperator";
	buttonName[23]  = "emotion1";
	//buttonName[24]  = "emotion2";
	buttonName[25]  = "seperator";
	buttonName[26]  = "viewSource";
	buttonName[27]  = "seperator";
  	buttonName[28]  = "help";
	
// List of available actions and their respective ID and images
var ToolbarList = {
//Name              buttonID                 buttonTitle           buttonImage                            buttonImageRollover
    "font":         ['FontSelect',           'FontSelect',         imagesDir + 'select_font.gif',        imagesDir + 'select_font_on.gif'],
    "size":         ['FontSizes',            'FontSizes',          imagesDir + 'select_size.gif',        imagesDir + 'select_size_on.gif'],
  	"bold":         ['Bold',                 'Bold',               imagesDir + 'bold.gif',               imagesDir + 'bold_on.gif'],
  	"italic":       ['Italic',               'Italic',             imagesDir + 'italics.gif',            imagesDir + 'italics_on.gif'],
  	"underline":    ['Underline',            'Underline',          imagesDir + 'underline.gif',          imagesDir + 'underline_on.gif'],
	"strikethrough": ['Strikethrough',        'Strikethrough',      imagesDir + 'strikethrough.gif',      imagesDir + 'strikethrough_on.gif'],
	"seperator":      ['',                     '',                   imagesDir + 'seperator.gif',          imagesDir + 'seperator.gif'],
	"subscript":      ['Subscript',            'Subscript',          imagesDir + 'subscript.gif',          imagesDir + 'subscript_on.gif'],
	"superscript":    ['Superscript',          'Superscript',        imagesDir + 'superscript.gif',        imagesDir + 'superscript_on.gif'],
	"justifyleft":    ['Justifyleft',          'Justifyleft',        imagesDir + 'justify_left.gif',       imagesDir + 'justify_left_on.gif'],
	"justifycenter":  ['Justifycenter',        'Justifycenter',      imagesDir + 'justify_center.gif',     imagesDir + 'justify_center_on.gif'],
	"justifyright":   ['Justifyright',         'Justifyright',       imagesDir + 'justify_right.gif',      imagesDir + 'justify_right_on.gif'],
	"unorderedlist":  ['InsertUnorderedList',  'InsertUnorderedList',imagesDir + 'list_unordered.gif',     imagesDir + 'list_unordered_on.gif'],
	"orderedlist":    ['InsertOrderedList',    'InsertOrderedList',  imagesDir + 'list_ordered.gif',       imagesDir + 'list_ordered_on.gif'],
	"outdent":        ['Outdent',              'Outdent',            imagesDir + 'indent_left.gif',        imagesDir + 'indent_left_on.gif'],
	"indent":         ['Indent',               'Indent',             imagesDir + 'indent_right.gif',       imagesDir + 'indent_right_on.gif'],
	"cut":            ['Cut',                  'Cut',                imagesDir + 'cut.gif',                imagesDir + 'cut_on.gif'],
	"copy":           ['Copy',                 'Copy',               imagesDir + 'copy.gif',               imagesDir + 'copy_on.gif'],
    "paste":          ['Paste',                'Paste',              imagesDir + 'paste.gif',              imagesDir + 'paste_on.gif'],
	"forecolor":      ['ForeColor',            'ForeColor',          imagesDir + 'forecolor.gif',          imagesDir + 'forecolor_on.gif'],
	"backcolor":      ['BackColor',            'BackColor',          imagesDir + 'backcolor.gif',          imagesDir + 'backcolor_on.gif'],
	"undo":           ['Undo',                 'Undo',               imagesDir + 'undo.gif',               imagesDir + 'undo_on.gif'],
	"redo":           ['Redo',                 'Redo',               imagesDir + 'redo.gif',               imagesDir + 'redo_on.gif'],
	"inserttable":    ['InsertTable',          'InsertTable',        imagesDir + 'insert_table.gif',       imagesDir + 'insert_table_on.gif'],
	"insertimage":    ['InsertImage',          'InsertImage',        imagesDir + 'insert_picture.gif',     imagesDir + 'insert_picture_on.gif'],
	"createlink":     ['CreateLink',           'CreateLink',         imagesDir + 'insert_hyperlink.gif',   imagesDir + 'insert_hyperlink_on.gif'],
	"viewSource":     ['ViewSource',           'ViewSource',         imagesDir + 'view_source.gif',        imagesDir + 'view_source_on.gif'],
	"viewText":       ['ViewText',             'ViewText',           imagesDir + 'view_text.gif',          imagesDir + 'view_text_on.gif'],
	"emotion1":       ['Emotion1',             'Emotion',            imagesDir + 'em1.gif',                imagesDir + 'em1_on.gif'],
	"emotion2":       ['Emotion2',             'Onion Emotion',      imagesDir + 'onion.gif',              imagesDir + 'onion_on.gif'],
	"help":           ['Help',                 'Help',               imagesDir + 'help.gif',               imagesDir + 'help_on.gif'],
	"selectsize":     ['SelectSize',           'SelectSize',         imagesDir + 'select_size.gif',        imagesDir + 'select_size_on.gif']
};

if(typeof HTMLElement!="undefined" && !HTMLElement.prototype.insertAdjacentElement){
    HTMLElement.prototype.insertAdjacentElement = function (where,parsedNode) {
	  switch (where){
		case 'beforeBegin':
			this.parentNode.insertBefore(parsedNode,this)
			break;
		case 'afterBegin':
			this.insertBefore(parsedNode,this.firstChild);
			break;
		case 'beforeEnd':
			this.appendChild(parsedNode);
			break;
		case 'afterEnd':
			if (this.nextSibling) 
                this.parentNode.insertBefore(parsedNode,this.nextSibling);
			else this.parentNode.appendChild(parsedNode);
			break;
		}
	}
	HTMLElement.prototype.insertAdjacentHTML = function (where,htmlStr) {
		var r = this.ownerDocument.createRange();
		r.setStartBefore(this);
		var parsedHTML = r.createContextualFragment(htmlStr);
		this.insertAdjacentElement(where,parsedHTML)
	}
	HTMLElement.prototype.insertAdjacentText = function (where,txtStr)
	{
		var parsedText = document.createTextNode(txtStr)
		this.insertAdjacentElement(where,parsedText)
	}
};

// Create viewTextMode global variable and set to 0
// enabling all toolbar commands while in HTML mode
viewTextMode = 0;

popup = "";

function generate_wysiwyg(textareaID) { 
	document.getElementById(textareaID).style.display = 'none'; // Hide the textarea
    var n = textareaID;                                         // Pass the textareaID to the "n" variable.
	toolbarWidth = parseFloat(wysiwygWidth) + 2;                // Toolbars width is 2 pixels wider than the wysiwygs
	
// Generate WYSIWYG toolbar one
    var toolbar;
    toolbar =  '<table cellpadding="0" cellspacing="0" border="0" class="toolbar1" width=' + toolbarWidth + 'px><tr><td width=6px></td>';
  
	// Output all command buttons that belong to toolbar one
	for (var i = 0; i <= buttonName.length;i++) { 
    	if (buttonName[i]) {
	    	var buttonObj            = ToolbarList[buttonName[i]];
			var buttonID             = buttonObj[0];
	    	var buttonTitle          = buttonObj[1];
      		var buttonImage          = buttonObj[2];

			if (buttonName[i] == "seperator")
		    	toolbar += '<td width=12px align="center"><img src="' +buttonImage+ '" ></td>';
		    else if (buttonName[i] == "viewSource"){
		        toolbar += '<td style="width: 22px;">'
				+ '<span id="HTMLMode' + n + '"><img src="'  +buttonImage+  '" title="' +buttonTitle+ '" id="' +buttonID+ '" class="button" '
				+ 'onClick="formatText(this.id,\'' + n + '\');" '
				+ 'onmouseover="className=\'buttonOver\';" '
				+ 'onmouseout="className=\'button\';" height="20"></span>'
				
				+ '<span id="textMode' + n + '"><img src="' +imagesDir+ 'view_text.gif" title="viewText" id="ViewText" class="button" '
				+ 'onClick="formatText(this.id,\'' + n + '\');" '
				+ 'onmouseover="className=\'buttonOver\';" '   
				+ 'onmouseout="className=\'button\';" height="20"></span></td>';
			    }
	            else {  toolbar += '<td width=22px><span id="' + buttonID + n + '"><img src="' +buttonImage+ '" title="' +buttonTitle+ '" id="' +buttonID+ '" class="button" '
	                +'onClick="formatText(this.id,\'' + n + '\');" '
	                +'onmouseover="className=\'buttonOver\';" '
	                +'onmouseout="className=\'button\';" '
	                +' height="20"></span></td>';
                 }
        }
    }
    toolbar += '<td>&nbsp;</td></tr></table>';  

// Generate WYSIWYG toolbar two
     
// Create iframe which will be used for rich text editing
	var iframe = '<table cellpadding="0" cellspacing="0" border="0" style="width:' + wysiwygWidth + 'px; height:' + wysiwygHeight + 'px;border: 1px inset #CCCCCC;"><tr><td valign="top">\n'
    + '<iframe frameborder="0" id="wysiwyg' + n + '"></iframe>\n'
    + '</td></tr></table>\n';
    
    document.getElementById(n).insertAdjacentHTML("afterEnd", toolbar + iframe); // Insert after the textArea both toolbar one and two
	
    // Insert the Font Type and Size drop downs into the toolbar
	outputPopUp('FontSizes',n);
	outputPopUpColor('ForeColor',n);
	if (browserName == "Microsoft Internet Explorer") {	  
	  outputPopUpColor('BackColor',n); 
	}
	outputEmotion1('Emotion1',n)
	document.getElementById("textMode" + n).style.display = 'none'; // Hide the "Text Mode" button
	
	// Give the iframe the global wysiwyg height and width
    document.getElementById("wysiwyg" + n).style.height = wysiwygHeight + "px";
    document.getElementById("wysiwyg" + n).style.width = wysiwygWidth + "px";
	
	// Pass the textarea's existing text over to the content variable
    var content = document.getElementById(n).value;
	
	var doc = document.getElementById("wysiwyg" + n).contentWindow.document;
	
	// Write the textarea's content into the iframe
    doc.open();
    doc.write(content);
    doc.close();
	
	// Make the iframe editable in both Mozilla and IE
    doc.body.contentEditable = true;
    doc.designMode = "on";
	
  	// Update the textarea with content in WYSIWYG when user submits form
    
    //for (var idx=0; idx < document.forms.length; idx++) {
    //    document.forms[idx].attachEvent('onsubmit', function() { updateTextArea(n); });
    //}
};


function formatText(id, n, selected) {

    // When user clicks toolbar button make sure it always targets its respective WYSIWYG
    document.getElementById("wysiwyg" + n).contentWindow.focus();
	// Check if in Text Mode and disabled button was clicked
	if (viewTextMode == 1  && !(id == "ViewText") )
	    alert ("You are in HTML Mode");
	else {
	    up =""
	    if (popup){
	        up = popup
            hideItem(popup);
        }
	    if (id == "FontSizes") { //fontSizeShow
	        if(up != "Sizes" + n){
	        showItem("Sizes" + n);
	        }
	    }
	    else if (id == "FontSize") { // FontSize
        document.getElementById("wysiwyg" + n).contentWindow.document.execCommand(id, false, selected);
	    }
        else if (id == 'ForeColor'){ //showForeColor
            if(up != 'ForeColors' + n){
            showItem('ForeColors' + n);
            }
        }
        else if (id == 'ForeColors'){
        document.getElementById('wysiwyg' + n).contentWindow.document.execCommand('ForeColor', false, selected);
        }
        else if (id == 'BackColor') {  // showBackColor
            if(up != 'BackColors' + n){
            showItem('BackColors' + n);
            }
        }
        else if (id == 'BackColors') { 
        document.getElementById('wysiwyg' + n).contentWindow.document.execCommand('BackColor', false, selected);      
        }
	    else if (id == "InsertImage") {
        window.open(popupsDir + 'insert_image.html?wysiwyg=' + n,'popup','location=0,status=0,scrollbars=0,resizable=0,width=400,height=190');
	    }
	    else if (id == "CreateLink") {
	    document.open(popupsDir + 'insert_hyperlink.html?wysiwyg=' + n,'popup','location=0,status=0,scrollbars=0,resizable=0,width=300,height=150');
	    }
	    else if (id == "Emotion1"){
	        if(up != 'Emotion1s' + n ){
	        showItem('Emotion1s' + n);
	        }
	    }
	    else if (id == "Emotion1s"){
	    var image = '<img src="icons/emotion1/'+selected+'"/>';
	    insertHTML(image, n);
	    hideItem(id + n);
	    }
	    else if (id == "Emotion2"){
	    document.open(popupsDir + 'insert_emotion.html?wysiwyg=' + n,'popup','location=0,status=0,scrollbars=0,resizable=0,width=550,height=600');
	    }
        else if (id == "ViewSource") {
	    viewSource(n);
	    }
		else if (id == "ViewText") {
	    viewText(n);
	    }
		else if (id == "Help") {
	    window.open(popupsDir + 'about.html','popup','location=0,status=0,scrollbars=0,resizable=0,width=400,height=330');
	    }
	    else {// Every other command
        document.getElementById("wysiwyg" + n).contentWindow.document.execCommand(id, false, null);
		}
  }
};

function insertHTML(html, n) {
	if (browserName == "Microsoft Internet Explorer") {	  
	  document.getElementById('wysiwyg' + n).contentWindow.document.selection.createRange().pasteHTML(html);   
	} 
	else {
	  var div = document.getElementById('wysiwyg' + n).contentWindow.document.createElement("div");
		div.innerHTML = html;
		var node = insertNodeAtSelection(div, n);		
	}   
}

function insertNodeAtSelection(insertNode, n) {
  // get current selection
  var sel = document.getElementById('wysiwyg' + n).contentWindow.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);
  }
  sel.addRange(range);
}

function outputPopUp(id , n) {
	    var FontSelectDropDown = '<br><span id="Sizes' + n + '" class="dropdown" style="width: 170px;">';
	    for (var i = 0; i < FontSizes.length;i++) {
            FontSelectDropDown += '<button type="button" onClick="formatText(\'FontSize\',\'' + n + '\',\'' + FontSizes[i] + '\')\;" onMouseOver="this.className=\'mouseOver\'" onMouseOut="this.className=\'mouseOut\'" class="mouseOut" style="width: 145px;"><table cellpadding="0" cellspacing="0" border="0"><tr><td align="left" style="font-family: arial, verdana, helvetica;"><font size="' + FontSizes[i] + '">size ' + FontSizes[i] + '</font></td></tr></table></button><br>';	  
        }
        document.getElementById(id + n).insertAdjacentHTML('beforeEnd', FontSelectDropDown + '</span>');
        hideItem('Sizes' + n);
};
function outputPopUpColor(id , n) {
    var ColorDropDown = '<br><table id="'+id + 's' + n + '" border="0" cellpadding="0" cellspacing="0" class="selectColor"> ';
    for (var i = 0; i < ColorLists.length;i++) {
        ColorDropDown += '<tr> ';
        for (var j = 0; j < ColorLists[i].length;j++) {
            ColorDropDown += '<td class="selectColorBorder" onMouseOver="this.className = \'selectColorOn\';" onMouseOut="this.className = \'selectColorOff\'" >'
            + '<button type="button" onClick="formatText(\''+id+'s'+'\',\'' + n +'\',\''+ ColorLists[i][j] +'\');hideItem(\'' + id + 's' + n + '\');" style=" background-color:' + ColorLists[i][j] + ';" class="selectColorBox"/></td>';
        }
        ColorDropDown +='</tr> ';
    }
    document.getElementById(id + n).insertAdjacentHTML("beforeEnd", ColorDropDown + '</table>');
    hideItem(id + 's' + n);
}
function outputEmotion1(id , n) {
    var Emotion = '<br><table id="'+id + 's' + n + '" border="0" cellpadding="0" cellspacing="0" class="selectColor"> ';
    var counter = 0;
    for (var i = 0; i < Emotion1[1];i++) {
        Emotion += '<tr> ';
        for (var j = 0; j < Emotion1[0];j++) {
            Emotion += '<td class="selectColorBorder" '
            + 'onMouseOver="this.className = \'selectColorOn\';" onMouseOut="this.className = \'selectColorOff\'" >'
            + '<img  src="'+imagesDir+'emotion1/em1('+counter+').gif" class="selectColorBox" style="height: 20px; width: 20px;" '
            + 'onClick="formatText(\''+id+'s'+'\',\'' + n +'\',\'em1(' + counter + ').gif\');" /></td>';
            counter++;
        }
        Emotion +='</tr> ';
    }
    document.getElementById(id + n).insertAdjacentHTML("beforeEnd", Emotion + '</table>');
    hideItem(id + 's' + n);
}
function hideItem(id) { //Hide Item popup
  document.getElementById(id).style.display = 'none'; 
  popup = null;
};
function showItem(id) { //Show Item popup
  if (document.getElementById(id).style.display == 'block') {
    document.getElementById(id).style.display = 'none';
    popup = null;
	}
  else {
    document.getElementById(id).style.display = 'block'; 
    document.getElementById(id).style.position = 'absolute';
    popup = id;		
  }
};

function viewSource(n) {
  var getDocument = document.getElementById("wysiwyg" + n).contentWindow.document;
  
	// View Source for IE 	 
    if (browserName == "Microsoft Internet Explorer") {
        var iHTML = getDocument.body.innerHTML;
        getDocument.body.innerText = iHTML;
	}
	// View Source for Mozilla/Netscape
    else {
        var html = document.createTextNode(getDocument.body.innerHTML);
        getDocument.body.innerHTML = "";
        getDocument.body.appendChild(html);
	}
  
	// Hide the HTML Mode button and show the Text Mode button
    document.getElementById('HTMLMode' + n).style.display = 'none'; 
	document.getElementById('textMode' + n).style.display = 'block';
	
	// set the font values for displaying HTML source
	getDocument.body.style.fontSize = "12px";
	getDocument.body.style.fontFamily = "Courier New"; 
	
  viewTextMode = 1;
};

function viewText(n) {
  var getDocument = document.getElementById("wysiwyg" + n).contentWindow.document;
	
	// View Text for IE 	  	 
    if (browserName == "Microsoft Internet Explorer") {
        var iText = getDocument.body.innerText;
        getDocument.body.innerHTML = iText;
	}
	// View Text for Mozilla/Netscape
    else {
        var html = getDocument.body.ownerDocument.createRange();
        html.selectNodeContents(getDocument.body);
        getDocument.body.innerHTML = html.toString();
	}
  
	// Hide the Text Mode button and show the HTML Mode button
  document.getElementById('textMode' + n).style.display = 'none'; 
	document.getElementById('HTMLMode' + n).style.display = 'block';
	
	// reset the font values
  getDocument.body.style.fontSize = "";
	getDocument.body.style.fontFamily = ""; 
	viewTextMode = 0;
};

function updateTextArea(n) {
    if (viewTextMode != 1)  viewSource(n);
    var str =document.getElementById("wysiwyg" + n).contentWindow.document.body.innerHTML;
    str =str.replace(/<BR>/g,'&lt;BR&gt;');
    document.getElementById(n).value = str ;
    viewText(n);
};
