// 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/
//
// This library is free software; you can redistribute it and/or modify 
// it under the terms of the GNU Lesser General Public License as published 
// by the Free Software Foundation; either version 2.1 of the License, or 
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but 
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License along 
// with this library; if not, write to the Free Software Foundation, Inc., 59 
// Temple Place, Suite 330, Boston, MA 02111-1307 USA 


/* ---------------------------------------------------------------------- *\
  Global Variables: Set global variables such as images directory, 
	                  WYSIWYG Height, Width, and CSS Directory.
\* ---------------------------------------------------------------------- */

// Images Directory
imagesDir = "http://sitedynamo.com/controlpanel/images/";

// CSS Directory
cssDir = "http://sitedynamo.com/controlpanel/styles/";

// Popups Directory
//popupsDir = "popups/";
popupsDir = "http://sitedynamo.com/controlpanel/";

// WYSIWYG Width and Height
wysiwygWidth = 500;
wysiwygHeight = 300;

// Include Style Sheet
document.write('<link rel="stylesheet" type="text/css" href="' +cssDir+ 'styles.css">\n');


/* ---------------------------------------------------------------------- *\
  Toolbar Settings: Set the features and buttons available in the WYSIWYG
	                  Toolbar.
\* ---------------------------------------------------------------------- */

//var parm = location.search;
//parm = parm.substr(1);
//document.write(parm);
var author_value = getQuerystring2('moduleid');


function getQuerystring2(key, default_) {
    if (default_ == null) {
        default_ = "";
    }
    var search = unescape(location.search);
    if (search == "") {
        return default_;
    }
    search = search.substr(1);
    var params = search.split("&");
    for (var i = 0; i < params.length; i++) {
        var pairs = params[i].split("=");
        if (pairs[0] == key || pairs[0]=="ModuleID" ) {
            return pairs[1];
        }
    }
    return default_;
}

//function getQuerystring(key, default_) {
//    if (default_ == null) default_ = "";
//    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
//    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
//    var qs = regex.exec(window.location.href);
//    if (qs == null)
//        return default_;
//    else
//        return qs[1];
//}


var selectedTable;
	var selectedTR;
	var selectedTD;
	var currframe;
	var browserNames;
	browserNames = navigator.appName;
	var varModuleId;
	var varTextAreaID;
// List of available font types
  var Fonts = new Array();
  Fonts[0] = "Arial";
  Fonts[1] = "Sans Serif";
  Fonts[2] = "Tahoma";
  Fonts[3] = "Verdana";
  Fonts[4] = "Courier New";
  Fonts[5] = "Georgia";
  Fonts[6] = "Times New Roman";
  Fonts[7] = "Impact";
  Fonts[8] = "Comic Sans MS";
  Fonts[9] = "Trebuchet MS";
  Fonts[10] = "Garamond";
  Fonts[10] = "Book Antiqua";

// List of available block formats (not in use)
var BlockFormats = new Array();
  BlockFormats[0]  = "Address";
  BlockFormats[1]  = "Bulleted List";
  BlockFormats[2]  = "Definition";
	BlockFormats[3]  = "Definition Term";
	BlockFormats[4]  = "Directory List";
	BlockFormats[5]  = "Formatted";
	BlockFormats[6]  = "Heading 1";
	BlockFormats[7]  = "Heading 2";
	BlockFormats[8]  = "Heading 3";
	BlockFormats[9]  = "Heading 4";
	BlockFormats[10] = "Heading 5";
	BlockFormats[11] = "Heading 6";
	BlockFormats[12] = "Menu List";
	BlockFormats[13] = "Normal";
	BlockFormats[14] = "Numbered List";


	//added by dastgir List of available styles
	var Styles = new Array();
	Styles[0] = "Paragraph";
	Styles[1] = "Heading 1";
	Styles[2] = "Heading 2";
	Styles[3] = "Heading 3";
	Styles[4] = "Normal";
	Styles[5] = "Clear Format";
    // List of available font sizes
    var FontSizes = new Array();
    FontSizes[0]  = "1";
    FontSizes[1]  = "2";
    FontSizes[2]  = "3";
	FontSizes[3]  = "4";
	FontSizes[4]  = "5";
	FontSizes[5]  = "6";
	FontSizes[6]  = "7";

// Order of available commands in toolbar one
var buttonName = new Array();

  buttonName[0]  = "bold";
  buttonName[1]  = "italic";
  buttonName[2]  = "underline";
  buttonName[3]  = "forecolor";
	buttonName[4]  = "backcolor";
	buttonName[5]  = "strikethrough";
  buttonName[6]  = "seperator";
	buttonName[7]  = "subscript";
	buttonName[8]  = "superscript";
	buttonName[9]  = "seperator";
	buttonName[10]  = "justifyleft";
	buttonName[11]  = "justifycenter";
	buttonName[12] = "justifyright";
	buttonName[13] = "justify";		
//	buttonName[11] = "seperator";
//	buttonName[12] = "unorderedlist";
//	buttonName[13] = "orderedlist";
//	buttonName[14] = "outdent";
//	buttonName[15] = "indent";

// Order of available commands in toolbar two
var buttonName2 = new Array();
//  buttonName2[0]  = "forecolor";
//	buttonName2[1]  = "backcolor";
//	buttonName2[2]  = "seperator";
//	buttonName2[0]  = "cut";
//	buttonName2[1]  = "copy";
//	buttonName2[2]  = "paste";
//	buttonName2[3]  = "seperator";
//  buttonName2[4]  = "undo";
//	buttonName2[5]  = "redo";
//  buttonName2[6]  = "seperator";
	buttonName2[0]  = "inserttable";
	buttonName2[1]  = "ModifyTable";
  buttonName2[2]  = "InsertColumnRight";
  buttonName2[3]  = "InsertColumnLeft";
  buttonName2[4]  = "InsertRowAbove";
  buttonName2[5]  = "InsertRowBelow";
   buttonName2[6]  = "DeleteRow";
    buttonName2[7]  = "DeleteColumn";
  //buttonName2[8]  = "insertimage";
//  buttonName2[7]  = "createlink";
//	buttonName2[8]  = "seperator";
//	buttonName2[9]  = "deletelink";
 // buttonName2[7]  = "help";
//  buttonName2[17]  = "ModifyTable";
//  buttonName2[18]  = "InsertColumnRight";
//  buttonName2[19]  = "InsertColumnLeft";
//  buttonName2[20]  = "InsertRowAbove";
//  buttonName2[21]  = "InsertRowBelow";
  
  // Order of available commands in toolbar two
var buttonName3 = new Array();
  buttonName3[0]  = "cut";
  buttonName3[1]  = "copy";
	buttonName3[2]  = "paste";
  buttonName3[3]  = "undo";
	buttonName3[4]  = "redo";
  	buttonName3[5]  = "seperator";
  	buttonName3[6]  = "inserthorizontalrule";
  	buttonName3[7] = "unorderedlist";
	buttonName3[8] = "orderedlist";
	buttonName3[9] = "outdent";
	buttonName3[10] = "indent";
	buttonName3[11]  = "insertimage";
  buttonName3[12]  = "createlink";
	buttonName3[13]  = "deletelink";
	buttonName3[14] = "calender";

 var buttonName4 = new Array();
 buttonName4[0]  = "viewSource";	
	
// List of available actions and their respective ID and images
var ToolbarList = {
//Name              buttonID                 buttonTitle           buttonImage                            buttonImageRollover
  "bold":           ['Bold',                 'Bold',               imagesDir + 'bold.jpg',               imagesDir + 'bold1.jpg'],
  "italic":         ['Italic',               'Italic',             imagesDir + 'italic.jpg',            imagesDir + 'italic1.jpg'],
  "underline":      ['Underline',            'Underline',          imagesDir + 'underline.jpg',          imagesDir + 'underline1.jpg'],
	"strikethrough":  ['Strikethrough',        'Strikethrough',      imagesDir + 'strikethrough.jpg',      imagesDir + 'strikethrough1.jpg'],
	"seperator":      ['',                     '',                   imagesDir + 'seperator.gif',          imagesDir + 'seperator.gif'],
	"subscript":      ['Superscript',            'Superscript',          imagesDir + 'Sub_script.jpg',          imagesDir + 'Sub_script1.jpg'],
	"superscript":    ['Subscript',          'Subscript',        imagesDir + 'Super_script.jpg',        imagesDir + 'Super_script1.jpg'],
	"justifyleft":    ['Justifyleft',          'Align Left',        imagesDir + 'align_left.jpg',       imagesDir + 'align_left1.jpg'],
	"justifycenter":  ['Justifycenter',        'Align Center',      imagesDir + 'align_center.jpg',     imagesDir + 'align_center1.jpg'],
	"justifyright":   ['Justifyright',         'Align Right',       imagesDir + 'align_right.jpg',      imagesDir + 'align_right1.jpg'],
	"justify":  	  ['JustifyFull',          'Justify',           imagesDir + 'justify.jpg',      imagesDir + 'justify1.jpg'],
	"unorderedlist":  ['InsertUnorderedList',  'Insert UnorderedList',imagesDir + 'bullets.jpg',     imagesDir + 'bullets1.jpg'],
	"orderedlist":    ['InsertOrderedList',    'Insert OrderedList',  imagesDir + 'Numbering.jpg',       imagesDir + 'Numbering1.jpg'],
	"outdent":        ['Outdent',              'Outdent',            imagesDir + 'decrease_indent.jpg',        imagesDir + 'decrease_indent1.jpg'],
	"indent":         ['Indent',               'Indent',             imagesDir + 'increase_indent.jpg',       imagesDir + 'increase_indent1.jpg'],
	"cut":            ['Cut',                  'Cut',                imagesDir + 'cut.jpg',                imagesDir + 'cut1.jpg'],
	"copy":           ['Copy',                 'Copy',               imagesDir + 'Editorcopy.jpg',               imagesDir + 'Editorcopy1.jpg'],
  "paste":          ['Paste',                'Paste',              imagesDir + 'paste.jpg',              imagesDir + 'paste1.jpg'],
	"forecolor":      ['ForeColor',            'Fore Color',          imagesDir + 'text_color.jpg',          imagesDir + 'text_color1.jpg'],
	"backcolor":      ['BackColor',            'Back Color',          imagesDir + 'shading_color.jpg',          imagesDir + 'shading_color1.jpg'],
	"undo":           ['Undo',                 'Undo',               imagesDir + 'undo.jpg',               imagesDir + 'undo1.jpg'],
	"redo":           ['Redo',                 'Redo',               imagesDir + 'redo.jpg',               imagesDir + 'redo1.jpg'],
	"inserttable":    ['InsertTable',          'Insert Table',        imagesDir + 'insert_table.jpg',       imagesDir + 'insert_table1.jpg'],
	"insertimage":    ['InsertImage',          'Insert Image',        imagesDir + 'images.jpg',     imagesDir + 'images1.jpg'],
	"createlink":     ['CreateLink',           'Create Link',         imagesDir + 'links.jpg',   imagesDir + 'links1.jpg' ],
	"deletelink":     ['DeleteLink',           'Delete Link',         imagesDir + 'link_delete.jpg',        imagesDir + 'link_delete1.jpg'],
	"viewText":       ['ViewText',             'View Text',           imagesDir + 'view_text.gif',          imagesDir + 'view_text_on.gif'],
//	"help":           ['Help',                 'Help',               imagesDir + 'Help-and-Support.gif',               imagesDir + 'Help-and-Support.gif'],
	"ModifyTable":    ['ModifyTable',          'Modify Table',        imagesDir + 'eraser.jpg',       imagesDir + 'eraser1.jpg'],	
	"selectfont":     ['SelectFont',           'Select Font',         imagesDir + 'text_style.jpg',        imagesDir + 'text_style1.jpg'],
	"selectsize":     ['SelectSize',           'Select Size',         imagesDir + 'size.jpg',        imagesDir + 'size.jpg'],
	"viewSource":     ['ViewSource',           'View Source',         imagesDir + 'show_code.jpg',        imagesDir + 'show_code1.jpg'],
	"InsertColumnRight":    ['InsertColumnRight',          'Insert Column Right',        imagesDir + 'insert_col_right.jpg',       imagesDir + 'insert_col_right1.jpg'],	
	"InsertColumnLeft":    ['InsertColumnLeft',          'Insert Column Left',        imagesDir + 'insert_col_left.jpg',       imagesDir + 'insert_col_left1.jpg'],	
	"InsertRowAbove":    ['InsertRowAbove',          'Insert Row Above',        imagesDir + 'insert_row_above.jpg',       imagesDir + 'insert_row_above1.jpg'],	
	"InsertRowBelow":    ['InsertRowBelow',          'Insert Row Below',        imagesDir + 'insert_row_below.jpg',       imagesDir + 'insert_row_below1.jpg'],
	"DeleteRow":    ['DeleteRow',          'DeleteRow',        imagesDir + 'deleterow.jpg',       imagesDir + 'deleterow1.jpg'],
	"DeleteColumn":    ['DeleteColumn',          'Delete Column',        imagesDir + 'deletecolumn.jpg',       imagesDir + 'deletecolumn1.jpg'],	
	"inserthorizontalrule":    ['InsertHorizontalRule',          'Line',        imagesDir + 'line.jpg',       imagesDir + 'line1.jpg'],
	"calender":      ['calender',      'Date',       imagesDir + 'cal.jpg',       imagesDir + 'cal1.jpg'],
	"leftcurve":    ['LeftCurve',          'LeftCurve',        imagesDir + 'leftbg_curve.jpg',       imagesDir + 'leftbg_curve.jpg']			
	
};



/* ---------------------------------------------------------------------- *\
  Function    : insertAdjacentHTML(), insertAdjacentText() and insertAdjacentElement()
  Description : Emulates insertAdjacentHTML(), insertAdjacentText() and 
	              insertAdjacentElement() three functions so they work with 
								Netscape 6/Mozilla
  Notes       : by Thor Larholm me@jscript.dk
\* ---------------------------------------------------------------------- */
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;


/* this is to fill the font size*/ 
function OpenEditior(id)
{
    //alert('1');
    window.opener.SendTitle(id);
}
function fillFontSize()
{
    var optionValues;
    var i;
    optionValues = "<option value='0'>None</option>";
    for(i=1 ; i <= 7 ; i++)
    {
            optionValues += "<option value=" + i + ">" + i + "</option>";
    }
    //optionValues = "<option value='1'>1</option>";
    return optionValues;
    
}
//added by dastgir to fill Style Dropdown from Styles Array
function fillStyles() {
    //Styles
    var optionValues;
    var i;
    optionValues = "<option value='N'>None</option>";
    for (i = 0; i < Styles.length; i++)
     {
        optionValues += "<option value=" + i + ">" + Styles[i] + "</option>";
     }
    return optionValues;
}

// this to fill font name from Fonts Array
function fillFontName()
{
    //Fonts
     var optionValues;
    var i;
    optionValues = "<option value='Times'>Default Font</option>";
    for(i=0 ; i < Fonts.length ; i++)
    {
            optionValues += "<option value='" + Fonts[i] + "'>" + Fonts[i] + "</option>";
    }
    //optionValues = "<option value='1'>1</option>";
    return optionValues;
}

/**/
function TitleEditor(n, wysiwygWidth, wysiwygHeight, moduleId) {

    varModuleId = moduleId;
    var iframe = '<table cellpadding="0" cellspacing="0" border="0" style="width:' + wysiwygWidth + 'px; height:' + wysiwygHeight + 'px;border: 0px; float:left;"><tr><td valign="top">\n'
  + '<iframe style="border:0px none #ffffff;background-color:white;"  frameborder="0" id="wysiwyg' + n + '"></iframe>\n'
  + '</td></tr></table>\n';

  // Insert after the textArea both toolbar one and two
  if(navigator.appName == 'Netscape')
  {
    document.getElementById(n).insertAdjacentHTML("afterEnd",iframe);
    //this.insertAdjacentElement("afterEnd",toolbar + toolbar2 + toolbar3 + iframe)
  }
  else
  {
    document.getElementById(n).insertAdjacentHTML("afterEnd",iframe);
  }  
	
  // Insert the Font Type and Size drop downs into the toolbar
//	outputFontSelect(n);
//	outputFontSizes(n); 
	
  // Hide the dynamic drop down lists for the Font Types and Sizes
//  hideFonts(n);
//	hideFontSizes(n);
	
	// Hide the "Text Mode" button
	document.getElementById(n).style.display = 'none'; 
	
	// 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;
 //content = "Vanchi";	
	// 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";
}
/**/


/* ---------------------------------------------------------------------- *\
  Function    : generate_wysiwyg()
  Description : replace textarea with wysiwyg editor
  Usage       : generate_wysiwyg("textarea_id");
  Arguments   : textarea_id - ID of textarea to replace
\* ---------------------------------------------------------------------- */
function generate_wysiwyg(textareaID,editorWidth, editorHeight, toolVisible, toolBlock, moduleID) {
        varModuleId = moduleID;
    var parent;
 	// Hide the textarea 
	document.getElementById(textareaID).style.display = 'none';

	// Pass the textareaID to the "n" variable.
  var n = textareaID;
  wysiwygWidth = editorWidth;
  wysiwygHeight = editorHeight;
	
	// Toolbars width is 2 pixels wider than the wysiwygs
	toolbarWidth = parseFloat(wysiwygWidth) + 2;
	
  // Generate WYSIWYG toolbar one
  var toolbar;
  toolbar = '<div style="float:left;  width:835px; height:35px;"><table id="tableFirstToolBar" align="left"  cellpadding="0" cellspacing="0" border="0" style="width:' + toolbarWidth + 'px;visibility:'+ toolVisible +';display:'+ toolBlock +'"><tr>';
  
	// Create IDs for inserting Font Type and Size drop downs
	toolbar += '<td  style="width:4px;" align="left"><img src="'+ imagesDir +'leftbg_curve.jpg" border="0" unselectable="on" width="4" height="27" hspace="0" unselectable="on"></td>';
	toolbar += '<td background="'+ imagesDir +'table_bg.jpg" style="width:80px; font-weight:bold; font-size: 11px; color: #333333; font-family: Arial, Verdana;">&nbsp;Font Names :&nbsp;</td>';
	//toolbar += '<td background="images/table_bg.jpg" style="width: 25px;"><select onChange=formatText("FontName","textarea1",this.value) name="select" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px" id="ddlFontName"><option value=Times New Roman>Default Font</option><option value=Arial>Arial</option><option value = Arial Black>Arial Black</option><option value =Verdena>Verdena</option></select></td>';
	toolbar += '<td background="' + imagesDir + 'table_bg.jpg" style="font-weight:bold; width:110px;"><select onChange=formatText("FontName","' + n +'",this.value) name="select" style="font-family:Arial, Verdana; font-size:11px; font-weight:bold; width:110px;" id="ddlFontName">' + fillFontName() + '</select></td>';
	toolbar += '<td background="'+ imagesDir +'table_bg.jpg" style="width:45px; font-weight:bold; text-align:right; font-size:11px; color:#333333; font-family:Arial, Verdana;">&nbsp;Size :&nbsp;</td>';
	//toolbar += '<td background="images/table_bg.jpg" style="width: 25px;"><select onChange=formatText("FontSize","textarea1",this.value) name="select2" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px" id="ddlFontSize"><option value = 5>None</option><option value = 6>6</option value = 7><option>7</option><option value = 8>8</option><option value = 9>9</option><option value = 10>10</option><option value = 11>11</option><option value = 12>12</option><option value = 13>13</option><option value = 14>14</option><option value = 15>15</option><option value = 16>16</option><option value = 17>17</option><option value = 18>18</option></select></td>';
	toolbar += '<td background="' + imagesDir + 'table_bg.jpg" style="width:60px;"><select onChange=formatText("FontSize","' + n + '",this.value) name="select2" style="font-family:Arial, Verdana; font-size:11px; font-weight:bold; width:60px;" id="ddlFontSize">' + fillFontSize() + '</select></td>';


    //added by dastgir for Style Dropdown into the ToolBar
	toolbar += '<td background="' + imagesDir + 'table_bg.jpg" style="width:45px; font-weight:bold; text-align:right; font-size:11px; color:#333333; font-family:Arial, Verdana;">Styles :&nbsp;</td>';
	toolbar += '<td background="' + imagesDir + 'table_bg.jpg" style="width:80px;"><select onChange=formatText("Styles","' + n + '",this.value) name="select3" style="font-family:Arial, Verdana; font-size:11px; font-weight:bold; width:80px;" id="ddlFontStyles">' + fillStyles() + '</select></td>';
    
    
	// Output all command buttons that belong to toolbar one
	for (var i = 0; i <= buttonName.length;) { 
    if (buttonName[i]) {
	    var buttonObj            = ToolbarList[buttonName[i]];
		  var buttonID             = buttonObj[0];
	    var buttonTitle          = buttonObj[1];
      var buttonImage          = buttonObj[2];
		  var buttonImageRollover  = buttonObj[3];
		  //varModuleId
		  if (buttonName[i] == "seperator") {
		      toolbar += '<td background="' + imagesDir + 'table_bg.jpg" style="width: 12px;" align="center"><img src="' + buttonImage + '" border=0 unselectable="on" width="2" height="27" hspace="2" unselectable="on"></td>';
		  }
		  else if (buttonName[i] == "leftcurve") {
		      toolbar += '<td background="' + imagesDir + 'table_bg.jpg" style="width: 12px;" align="center"><img src="' + buttonImage + '" border=0 unselectable="on" width="6" height="18" hspace="2" unselectable="on"></td>';
		  }
		  else {
		      toolbar += '<td background="' + imagesDir + 'table_bg.jpg" style="width: 22px;"><img src="' + buttonImage + '" width="25" height="23" border=0 unselectable="on" title="' + buttonTitle + '" id="' + buttonID + '" class="button" onClick="formatText(this.id,\'' + n + '\');" onmouseover="if(className==\'button\'){className=\'buttonOver\'}; this.src=\'' + buttonImageRollover + '\';" onmouseout="if(className==\'buttonOver\'){className=\'button\'}; this.src=\'' + buttonImage + '\';" unselectable="on" width="25" height="23"></td>';
		  }
    }
    i++;
  }
  
  toolbar += '<td><img src="'+ imagesDir +'rightbg_curve.jpg" border="0" unselectable="on" width="4" height="27" hspace="0" unselectable="on"></td></tr></table></div>';  

// Generate WYSIWYG toolbar two
  var toolbar2;
  toolbar2 = '<div style="float:left; border:0px solid red; height:35px; width:280px;"><table id="tableSecondToolBar" cellpadding="0" cellspacing="0" border="0"  style="text-align:left; visibility:'+ toolVisible +';display:'+ toolBlock +'"><tr>';
 toolbar2 += '<td align="left"><img src="'+ imagesDir +'leftbg_curve.jpg" border=0 unselectable="on" height="27" hspace="0" unselectable="on"></td>';
  // Output all command buttons that belong to toolbar two
  for (var j = 0; j < buttonName2.length;) {
  
    if (buttonName2[j]) {
 
	    var buttonObj            = ToolbarList[buttonName2[j]];
		  var buttonID             = buttonObj[0];
	    var buttonTitle          = buttonObj[1];
      var buttonImage          = buttonObj[2];
		  var buttonImageRollover  = buttonObj[3];
		  //inserttable
		  if (buttonName2[j] == "seperator") {
		      toolbar2 += '<td background="' + imagesDir + 'table_bg.jpg" style="width:12px;" align="left"><img src="' + buttonImage + '" border=0 unselectable="on" width="12" height="18" hspace="2" unselectable="on"></td>';
		  }
		  else if (buttonName2[j] == "inserttable" && varModuleId == '') {
		  toolbar2 += '<td background="' + imagesDir + 'table_bg.jpg" style="width:61px;"><img src="' + buttonImage + '" border=0 unselectable="on" title="' + buttonTitle + '" id="' + buttonID + '" class=" " onmouseover="if(className==\'button\'){className=\'buttonOver\'}; this.src=\'' + buttonImageRollover + '\';" onmouseout="if(className==\'buttonOver\'){className=\'button\'}; this.src=\'' + buttonImage + '\';" unselectable="on" height="23"></td>';
		  }
		  else {
		      toolbar2 += '<td background="' + imagesDir + 'table_bg.jpg" style="width:61px;"><img src="' + buttonImage + '" border=0 unselectable="on" title="' + buttonTitle + '" id="' + buttonID + '" class=" " onClick="formatText(this.id,\'' + n + '\');" onmouseover="if(className==\'button\'){className=\'buttonOver\'}; this.src=\'' + buttonImageRollover + '\';" onmouseout="if(className==\'buttonOver\'){className=\'button\'}; this.src=\'' + buttonImage + '\';" unselectable="on" height="23"></td>';
		  }
    }
    j++;
}
  toolbar2 += '</tr></table>&nbsp;</div>';  
  
  // Generate WYSIWYG toolbar three
  var toolbar3;
  toolbar3 = '<div style="float:left; width:360px; border:0px solid blue; height:35px;"><table width="310" id="tableThirdToolBar" cellpadding="0" cellspacing="0" border="0"  style="visibility:'+ toolVisible +';display:'+ toolBlock +'"><tr>';
 toolbar3 += '<td background="'+ imagesDir +'table_bg.jpg" style="width:5px;" align="center"><img src="images/leftbg_curve.jpg" border=0 unselectable="on" width="5" height="27" hspace="2" unselectable="on"></td>';
  // Output all command buttons that belong to toolbar three
  for (var j = 0; j < buttonName3.length;) {
  
    if (buttonName3[j]) {
 
	    var buttonObj            = ToolbarList[buttonName3[j]];
		var buttonID             = buttonObj[0];
	    var buttonTitle          = buttonObj[1];
        var buttonImage          = buttonObj[2];
		var buttonImageRollover  = buttonObj[3];

		if (buttonName3[j] == "seperator") {
		    toolbar3 += '<td background="' + imagesDir + 'table_bg.jpg" style="width: 12px;" align="center"><img src="' + buttonImage + '" border=0 unselectable="on" width="5" height="23" hspace="2" unselectable="on"></td>';
		}
		
		else {
		    toolbar3 += '<td background="' + imagesDir + 'table_bg.jpg" style="width: 22px;"><img src="' + buttonImage + '" border=0 unselectable="on" title="' + buttonTitle + '" id="' + buttonID + '" class="button" onClick="formatText(this.id,\'' + n + '\');" onmouseover="if(className==\'button\'){className=\'buttonOver\'}; this.src=\'' + buttonImageRollover + '\';" onmouseout="if(className==\'buttonOver\'){className=\'button\'}; this.src=\'' + buttonImage + '\';" unselectable="on" width="25" height="23"></td>';
		}
    }
    j++;
}
   toolbar3 += '<td ><img  src="' + imagesDir + 'rightbg_curve.jpg" border=0 unselectable="on" width="5" height="27" hspace="0" unselectable="on"></td></tr></table></div>';

	// Create iframe which will be used for rich text editing
	var iframe = '<table cellpadding="0" cellspacing="1" border="0" style="width:760px; height:' + wysiwygHeight + 'px;border: 0px solid #CCCCCC; float:left;"><tr><td valign="top">\n'
  + '<iframe frameborder="0" id="wysiwyg' + n + '" style="border:1px solid #c0c0c0;background-color:white;"></iframe>\n'
  + '</td></tr></table>\n';


 var toolbar4;
 
 var toolBarTop;
 
toolbar4 = '<div style = "margin-left:20px;padding-bottom:10px;float:left;width:40px;" >';
//toolbar4 = '<div style = "float:right; " >';
 toolbar4  += '<table  cellpadding="0" cellspacing="0" border="0" ><tr>';
 toolbar4 += '<td></td>';
 
  for (var j = 0; j < buttonName4.length;) {
   
     if (buttonName4[j]) {
  
 	    var buttonObj            = ToolbarList[buttonName4[0]];
 	    var buttonID             = buttonObj[0];
 	    var buttonTitle          = buttonObj[1];
     	    var buttonImage          = buttonObj[2];
 	    var buttonImageRollover  = buttonObj[3];
 	     
 	 if (buttonName4[0] == "seperator") {
 		    toolbar4 += '<td background="'+ imagesDir +'table_bg.jpg" style="width: 12px;" align="center"><img src="' +buttonImage+ '" border=0 unselectable="on" width="2" height="18" hspace="2" unselectable="on"></td>';
 			}
 	    else if (buttonName4[0] == "viewSource"){
 	    
 		    toolbar4 += '<td  style="width: 5px;" align="left">';
 		    
 		toolbar4 += '<span style="width:92px;" id="HTMLMode' + n + '"><img src="'  +buttonImage+  '" border=0 unselectable="on" title="' +buttonTitle+ '" id="' +buttonID+ '" class="EditorButton" onClick="formatText(this.id,\'' + n + '\');" onmouseover="if(className==\'button\'){className=\'buttonOver\'}; this.src=\'' +buttonImageRollover+ '\';" onmouseout="if(className==\'buttonOver\'){className=\'button\'}; this.src=\'' + buttonImage + '\';" unselectable="on" width="60" ></span>';
    	toolbar4 += '<span style="width:92px;" id="textMode' + n + '"><img src="' +imagesDir+ 'Show_Text.jpg" border=0 unselectable="on" title="viewText" id="ViewText" class="EditorButton" onClick="formatText(this.id,\'' + n + '\');" onmouseover="if(className==\'button\'){className=\'buttonOver\'}; this.src=\'' +imagesDir+ 'Show_Text1.jpg\';"    onmouseout="if(className==\'buttonOver\'){className=\'button\'}; this.src=\'' +imagesDir+ 'Show_Text.jpg\';" unselectable="on" width="60"  ></span>';
		
 	        toolbar4 += '</td>';
 			}
 	    else {
 		    toolbar4 += '<td background="'+ imagesDir +'table_bg.jpg" style="width: 22px;"><img src="' +buttonImage+ '" border=0 unselectable="on" title="' +buttonTitle+ '" id="' +buttonID+ '" class="button" onClick="formatText(this.id,\'' + n + '\');" onmouseover="if(className==\'button\'){className=\'buttonOver\'}; this.src=\'' +buttonImageRollover+ '\';" onmouseout="if(className==\'buttonOver\'){className=\'button\'}; this.src=\'' + buttonImage + '\';" unselectable="on" width="25" height="23"></td>';
 	    }
     }
     j++;
  }
  
 toolbar4 += '<td ></td></tr></table></div>';

var finaltoolbar = '<div style="padding:4px; width:760px;height:65px; border:1px solid #000; background:#f4f4f4;">' ;
    finaltoolbar += toolbar + toolbar2 + toolbar3 + toolbar4 ;
    finaltoolbar += '</div>';  
  // Insert after the textArea both toolbar one and two
  if(navigator.appName == 'Netscape')
  {
    document.getElementById(n).insertAdjacentHTML("afterEnd", finaltoolbar + iframe);
    //this.insertAdjacentElement("afterEnd",toolbar + toolbar2 + toolbar3 + iframe)
  }
  else
  {
    document.getElementById(n).insertAdjacentHTML("afterEnd", finaltoolbar + iframe );
  }  
	
  // Insert the Font Type and Size drop downs into the toolbar
//	outputFontSelect(n);
//	outputFontSizes(n); 
	
  // Hide the dynamic drop down lists for the Font Types and Sizes
//  hideFonts(n);
//	hideFontSizes(n);
	
	// Hide the "Text Mode" button
	document.getElementById("textMode" + n).style.display = 'none'; 
	
	// 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;
	content = "Enter content";
	document.getElementById(n).style.backgroundColor = '#ffffff';
	// 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
  var browserName = navigator.appName;
  if (browserName == "Microsoft Internet Explorer") {
    for (var idx=0; idx < document.forms.length; idx++) {
      document.forms[idx].attachEvent('onsubmit', function() { updateTextArea(n); });
    }
  }
  else {
  	for (var idx=0; idx < document.forms.length; idx++) {
    	document.forms[idx].addEventListener('submit',function OnSumbmit() { updateTextArea(n); }, true);
    }
  }
 	

};
/*------------------Function for global setting --------------------
Description : background color, back color for div
*/
//function formatTextGlobal(id, n, selected) 
//{   
//     if(id=='bcolor')
//     {   
//      var w = screen.availWidth;
//      var h = screen.availHeight;
//      var popW = 200, popH = 325;
//      var leftPos = (w-popW)/2, topPos = (h-popH)/2;
//	    window.open('CustomColors.aspx?&ToDo=' + id +'&ObjName='+ currentColor +','','location=0,status=0,scrollbars=0,width=' + popW + ',height=350,top=100,left=200');//?wysiwyg=textarea1&ToDo=' + id  + '&ObjName='','popup','location=0,status=0,scrollbars=0,width=' + popW + ',height=' + popH + ',top=' + topPos + ',left=' + leftPos);    
//     }
//}   

/* ---------------------------------------------------------------------- *\
  Function    : formatText()
  Description : replace textarea with wysiwyg editor
  Usage       : `(id, n, selected);
  Arguments   : id - The execCommand (e.g. Bold)
                n  - The editor identifier that the command 
								     affects (the textarea's ID)
                selected - The selected value when applicable (e.g. Arial)
\* ---------------------------------------------------------------------- */
function formatText(id, n, selected) {

    // When user clicks toolbar button make sure it always targets its respective WYSIWYG
    varTextAreaID = n;
  document.getElementById("wysiwyg" + n).contentWindow.focus();
	
	// When in Text Mode these execCommands are disabled
	var formatIDs = new Array("ModifyTable","InsertColumnRight","InsertColumnLeft","InsertRowAbove","InsertRowBelow","FontSize","FontName","Bold","Italic","Underline","Subscript","Superscript","Strikethrough","Justifyleft","Justifyright","Justifycenter","JustifyFull","InsertUnorderedList","InsertOrderedList","Indent","Outdent","ForeColor","BackColor","InsertImage","InsertTable","CreateLink","InsertHorizontalRule","Sytles");
  
	// Check if button clicked is in disabled list
	for (var i = 0; i <= formatIDs.length;) {
		if (formatIDs[i] == id) {
			 var disabled_id = 1; 
		}
	  i++;
	}

	// Check if in Text Mode and disabled button was clicked
	if (viewTextMode == 1 && disabled_id == 1) {
	  alert ("You are in HTML Mode. This feature has been disabled.");	
	}
	
	else {

	    // FontSize
	    if (id == "FontSize")
	     {
	        document.getElementById("wysiwyg" + n).contentWindow.document.execCommand("FontSize", false, selected);
         }
	  
		// FontName
      else if (id == "FontName")
	   {
         document.getElementById("wysiwyg" + n).contentWindow.document.execCommand("FontName", false, selected);
       }
      // Styles
      //added by dastgir For Style
      else if (id == "Styles") 
      {
          InsertStyles(selected);
      }
      //calender date
      else if (id == "calender")
      {
          document.getElementById('ctl00_pchContent_imgEditorCalendar').click();
      }
      	  
	
	  // ForeColor and BackColor
    else if (id == 'ForeColor' || id == 'BackColor') {
      var w = screen.availWidth;
      var h = screen.availHeight;
      var popW = 200, popH = 325;
      var leftPos = (w-popW)/2, topPos = (h-popH)/2;
      var currentColor = _dec_to_rgb(document.getElementById("wysiwyg" + n).contentWindow.document.queryCommandValue(id));
   
	    window.open('CustomColors.aspx?wysiwyg=textarea1&ToDo=' + id  + '&ObjName=' + currentColor ,'popup','location=0,status=0,scrollbars=0,width=' + popW + ',height=' + popH + ',top=' + topPos + ',left=' + leftPos);
    }
   	  
		// InsertImage
	  else if (id == "InsertImage") {
	  
      window.open('UploadImage.aspx?From=' + varModuleId +  '&Type=&ImgUrl=&WhichSection=ed','popup','scrollbars=1, width=810px, height=540px, top=50, left=130');
	  }
	  
		// InsertTable
	  else if (id == "InsertTable") {
	    //window.open(popupsDir + 'InsertTable.aspx?wysiwyg=' + n,'popup','status=0,scrollbars=0,resizable=yes,width=500,height=400');
	    handlemenu(1);
	  }
	  // modify table
	  else if (id == "ModifyTable") {
	    handlemenu(2);
	    //window.open(popupsDir + 'InsertTable.aspx?wysiwyg=' + n + '&Type=Modify','popup','status=0,scrollbars=0,resizable=yes,width=500,height=400');
	    //viewDivContext(event);
	  }
	  
	  // insert column to right
	  else if (id == "InsertColumnRight") {
	    handlemenu(4);
	  }
	  
	  	  // insert column to Left
	  else if (id == "InsertColumnLeft") {
	    handlemenu(5);
	  }
	  
	  // insert Row Above
	  else if (id == "InsertRowAbove") {
	    handlemenu(6);
	  }
	  
	  // insert Row Above
	  else if (id == "InsertRowBelow") {
	    handlemenu(7);
	  }
	  
	  else if (id == "DeleteRow") {
	    handlemenu(8);
	  }
	  
	  else if (id == "DeleteColumn") {
	    handlemenu(9);
	  }
	  
		// CreateLink
	  else if (id == "CreateLink") {             //Code modified by Sachin on 8 Oct 2008 and also added flag
	  var browserName = navigator.appName;
            if(browserName == "Microsoft Internet Explorer")
            {
                var selectedText;
                selectedText = document.getElementById("wysiwyg" + n).contentWindow.document.selection.createRange().text;
                
                if(selectedText != '' && selectedText != undefined){
                    window.open('AttachPage2Links.aspx?flag=0&From=C&ModuleID=' + author_value + '', 'popup', 'location=0,status=0,scrollbars=1,resizable=1,width=770,height=530,top=100');
            /*       
                    var behID="AttachDetachCat";
                    var ifrm="";   
                        ifrm = document.createElement("IFRAME"); 
                        ifrm.setAttribute("src", 'AttachPage2Links.aspx?flag=0&From=C&ModuleID=' + author_value + ''); 
                        ifrm.style.width = 790+"px"; 
                        ifrm.style.height = 485+"px"; 
                        ifrm.style.border = 0+"px";
                 
                         var varContent = document.getElementById('dyncontent').innerHTML;    
                        if (varContent !=null && varContent.trim()!= "" )
                         {  //    alert('not empty'); //alert(dyncontent.lastChild);
                            //document.getElementById('dyncontent').removeChild(dyncontent);
                          document.getElementById('dyncontent').innerHTML="";
                         }
                       
                            document.getElementById('dyncontent').appendChild(ifrm);   
                       
                        $find(behID).show();
                        */
                    return false;
    
                }
                else if(selectedText == undefined)   //added by sachin on 27 Jan 2009(starts)
                {
                    alert('You Can Not Link To Internal / External Links');
                }
                else                                //added by sachin on 27 Jan 2009(ends)
                {
                    alert('Please Select The Text To Link');
                }
            }    
            else 
            { 
                var selectedText;
                //selectedText = window.frames[0].getSelection();
                selectedText = document.getElementById("wysiwyg" + n).contentWindow.document.getSelection();
                if(selectedText != '' && selectedText != undefined)
                {
                    window.open('AttachPage2Links.aspx?flag=0&From=C','popup','location=0,status=0,scrollbars=0,resizable=0,width=750,height=430,top=100');
                }
                else if( selectedText == undefined)            //added by sachin on 27 Jan 2009(starts)
                {
                    alert('You Can Not Link To Internal / External Links');
                }
                else                                           //added by sachin on 27 Jan 2009(ends)
                {
                    alert('Please Select The Text To Link');
                }
            }
	  }
	  // DeleteLink
	  else if (id == "DeleteLink") {
	    //document.execCommand('unlink');
	  //document.getElementById("wysiwyg" + n).contentWindow.document.execCommand('unlink');
	  document.getElementById("wysiwyg" + n).contentWindow.document.execCommand('unlink', false, null);
	  }
	  
		// ViewSource
    else if (id == "ViewSource") {
	    viewSource(n);
	  }
		
		// ViewText
		else if (id == "ViewText") {
	    viewText(n);
	  }

		// Help
		else if (id == "Help") {
	    window.open('about.html','popup','location=0,status=0,scrollbars=0,resizable=0,width=400,height=330');
	  }
	  else {
	     

	      if (id.toLowerCase() != 'justifyleft' && id.toLowerCase() != 'justifyright' && id.toLowerCase() != 'justifycenter' && id.toLowerCase() != 'justifyfull') {
	          document.getElementById("wysiwyg" + n).contentWindow.document.execCommand(id, false, null);
	         
	      }
	      else {
	          document.getElementById("wysiwyg" + n).contentWindow.document.execCommand(id, false, null);
	      }
		   }
  }
};

//Modifying the Table and Cell Properties 

function ChangeTableProperites(paraValues,editorID)
{
    var checkCondition;
    var tcolor;
    var retVal;
    var allVal;
  var width;
  var border;
  var padding;
  var spacing;
  var bgcolor;
  var height;

  allVal  = new Array();
  allVal = paraValues.split('$');
  if(navigator.appName == "Microsoft Internet Explorer")
  {
    
      if (isTableSelected() || isCursorInTableCell()) {
      if(allVal[0] != '')
      {
        tcolor= allVal[0];
      }
       else
       {
        tcolor = '';
       }
       if (tcolor != '') {
        	    selectedTable.bgColor =tcolor;
        } else {
            selectedTable.removeAttribute('bgColor',0);
        }
            selectedTable.cellPadding = allVal[2];
            selectedTable.cellSpacing = allVal[1];
            selectedTable.border = allVal[3];
            if(allVal[4] != 0)
                selectedTable.width = allVal[4];
            if(allVal[5] != 0)
                selectedTable.height = allVal[5];
            selectedTable.align = allVal[6];
            if(allVal[7] != '')
              {
	            bgcolor=allVal[7];
               }
               else
               {
                bgcolor = '';
               }
               
       if (bgcolor != '') {
       selectedTable.borderColor ="" ;
        	    selectedTable.borderColor =bgcolor;
        } else {
            selectedTable.removeAttribute('borderColor',0);
        }
        selectedTable.style.borderStyle = allVal[8];
        selectedTD.align = allVal[9];
        selectedTD.vAlign = allVal[10];
        //alert(allVal[11]);
        selectedTD.style.width = allVal[11];
        selectedTD.style.height = allVal[12];
        selectedTD.rowSpan= allVal[13];
        selectedTD.colSpan= allVal[14];
        
        if(allVal[15] == "true")
        {
            selectedTD.noWrap = "nowrap";
        }
        else
        {
            selectedTD.removeAttribute('noWrap');
        }
      }
  }
  else
  {
    if (window.getSelection)
        { 
            var selected_obj = document.getElementById('wysiwygtextarea1').contentWindow.window.getSelection().focusNode;
        }
        else if (document.getSelection)
        { 
            var selected_obj = document.getElementById('wysiwygtextarea1').contentWindow.document.getSelection().focusNode;
        }
        else if (document.selection)
        { 
            var selected_obj = document.getElementById('wysiwygtextarea1').contentWindow.document.selection.createRange().parentElement();
        }
        current_tag = selected_obj; 
        while(current_tag.tagName != "TABLE")
            { 
            
                if (current_tag.tagName == "TR") 
                    {
                         //RowIndex = current_tag.rowIndex;
                         //selected_obj = current_tag;
                    }
                if (current_tag.tagName == "TBODY") 
                    { 
                        //RowTotal = current_tag.parentNode.rows.length; var x=current_tag.parentNode; x.deleteRow(RowIndex);
                    }
                    
                current_tag = current_tag.parentNode;
                //alert(current_tag.tagName);
                if (current_tag.tagName == "TD") 
                    { 
                        getSelectedTD = current_tag;
                        getSelectedTD.align = allVal[9];
                        getSelectedTD.vAlign = allVal[10];
                        getSelectedTD.style.width = allVal[11];
                        getSelectedTD.style.height = allVal[12];
                        getSelectedTD.rowSpan= allVal[13];
                        getSelectedTD.colSpan= allVal[14];
                        if(allVal[15] == "true")
                        {
                            getSelectedTD.noWrap = "nowrap";
                        }
                        else
                        {
                            getSelectedTD.removeAttribute('noWrap');
                        }
                    }
           }
          if(allVal[0] != '')
          {
	        tcolor= allVal[0];
           }
           else
           {
            tcolor = '';
           }
           current_tag.style.borderStyle = allVal[8];
       if (tcolor != '') {
        	    current_tag.bgColor =tcolor;
        } else {
            current_tag.removeAttribute('bgColor',0);
        }
            current_tag.cellPadding = allVal[2];
            current_tag.cellSpacing = allVal[1];
            current_tag.border = allVal[3];
            if(allVal[4] != 0)
                current_tag.width = allVal[4];
            if(allVal[5] != 0)
                current_tag.setAttribute('height',allVal[5]);
            current_tag.align = allVal[6];
            if(allVal[7] != '')
              {
	            bgcolor=allVal[7];
               }
               else
               {
                bgcolor = '';
               }
       if (bgcolor != '') {
                //current_tag.bordercolor ="" ;
        	    //current_tag.bordercolor =bgcolor;
        	    current_tag.removeAttribute('borderColor',0);
        	    current_tag.setAttribute('borderColor',bgcolor);
        } else {
            current_tag.removeAttribute('borderColor',0);
        }
  }
}

/* ---------------------------------------------------------------------- *\
  Function    : insertHTML()
  Description : insert HTML into WYSIWYG in rich text
  Usage       : insertHTML(<b>hello</b>, "textareaID")
  Arguments   : html - The HTML being inserted (e.g. <b>hello</b>)
                n  - The editor identifier that the HTML 
								     will be inserted into (the textarea's ID)
\* ---------------------------------------------------------------------- */
function insertHTML(html, n) {
  var browserName = navigator.appName;
	 	 
	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.setAttribute("Id","divSample");
		div.innerHTML = html;
		var node = insertNodeAtSelection(div, n);		
	}
}


/* ---------------------------------------------------------------------- *\
  Function    : insertNodeAtSelection()
  Description : insert HTML into WYSIWYG in rich text (mozilla)
  Usage       : insertNodeAtSelection(insertNode, n)
  Arguments   : insertNode - The HTML being inserted (must be innerHTML 
	                           inserted within a div element)
                n          - The editor identifier that the HTML will be 
								             inserted into (the textarea's ID)
\* ---------------------------------------------------------------------- */
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    : _dec_to_rgb
  Description : convert a decimal color value to rgb hexadecimal
  Usage       : var hex = _dec_to_rgb('65535');   // returns FFFF00
  Arguments   : value   - dec value
\* ---------------------------------------------------------------------- */

function _dec_to_rgb(value) {
  var hex_string = "";
  for (var hexpair = 0; hexpair < 3; hexpair++) {
    var myByte = value & 0xFF;            // get low byte
    value >>= 8;                          // drop low byte
    var nybble2 = myByte & 0x0F;          // get low nybble (4 bits)
    var nybble1 = (myByte >> 4) & 0x0F;   // get high nybble
    hex_string += nybble1.toString(16);   // convert nybble to hex
    hex_string += nybble2.toString(16);   // convert nybble to hex
  }
  return hex_string.toUpperCase();
};



/* ---------------------------------------------------------------------- *\
  Function    : outputFontSelect()
  Description : creates the Font Select drop down and inserts it into 
	              the toolbar
  Usage       : outputFontSelect(n)
  Arguments   : n   - The editor identifier that the Font Select will update
	                    when making font changes (the textarea's ID)
\* ---------------------------------------------------------------------- */
function outputFontSelect(n) {

  var FontSelectObj        = ToolbarList['selectfont'];
  var FontSelect           = FontSelectObj[2];
  var FontSelectOn         = FontSelectObj[3];
  
	Fonts.sort();
	var FontSelectDropDown = new Array;
	FontSelectDropDown[n] = '<table border="0" cellpadding="0" cellspacing="0"><tr><td onMouseOver="document.getElementById(\'selectFont' + n + '\').src=\'' + FontSelectOn + '\';" onMouseOut="document.getElementById(\'selectFont' + n + '\').src=\'' + FontSelect + '\';"><img src="' + FontSelect + '" id="selectFont' + n + '" width="85" height="20" onClick="showFonts(\'' + n + '\');" unselectable="on"><br>';
	FontSelectDropDown[n] += '<span id="Fonts' + n + '" class="dropdown" style="width: 145px;">';

	for (var i = 0; i <= Fonts.length;) {
	  if (Fonts[i]) {
      FontSelectDropDown[n] += '<button type="button" onClick="formatText(\'FontName\',\'' + n + '\',\'' + Fonts[i] + '\')\; hideFonts(\'' + n + '\');" onMouseOver="this.className=\'mouseOver\'" onMouseOut="this.className=\'mouseOut\'" class="mouseOut" style="width: 120px;"><table cellpadding="0" cellspacing="0" border="0"><tr><td align="left" style="font-family:' + Fonts[i] + '; font-size: 12px;">' + Fonts[i] + '</td></tr></table></button><br>';	
    }	  
	  i++;
  }
	FontSelectDropDown[n] += '</span></td></tr></table>';
	document.getElementById('FontSelect' + n).insertAdjacentHTML("afterBegin", FontSelectDropDown[n]);
};



/* ---------------------------------------------------------------------- *\
  Function    : outputFontSizes()
  Description : creates the Font Sizes drop down and inserts it into 
	              the toolbar
  Usage       : outputFontSelect(n)
  Arguments   : n   - The editor identifier that the Font Sizes will update
	                    when making font changes (the textarea's ID)
\* ---------------------------------------------------------------------- */
function outputFontSizes(n) {

  var FontSizeObj        = ToolbarList['selectsize'];
  var FontSize           = FontSizeObj[2];
  var FontSizeOn         = FontSizeObj[3];

	FontSizes.sort();
	var FontSizesDropDown = new Array;
	FontSizesDropDown[n] = '<table border="0" cellpadding="0" cellspacing="0"><tr><td onMouseOver="document.getElementById(\'selectSize' + n + '\').src=\'' + FontSizeOn + '\';" onMouseOut="document.getElementById(\'selectSize' + n + '\').src=\'' + FontSize + '\';"><img src="' + FontSize + '" id="selectSize' + n + '" width="49" height="20" onClick="showFontSizes(\'' + n + '\');" unselectable="on"><br>';
  FontSizesDropDown[n] += '<span id="Sizes' + n + '" class="dropdown" style="width: 170px;">';

	for (var i = 0; i <= FontSizes.length;) {
	  if (FontSizes[i]) {
      FontSizesDropDown[n] += '<button type="button" onClick="formatText(\'FontSize\',\'' + n + '\',\'' + FontSizes[i] + '\')\;hideFontSizes(\'' + n + '\');" 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>';	
    }	  
	  i++;
  }
	FontSizesDropDown[n] += '</span></td></tr></table>';
	document.getElementById('FontSizes' + n).insertAdjacentHTML("afterBegin", FontSizesDropDown[n]);
};



/* ---------------------------------------------------------------------- *\
  Function    : hideFonts()
  Description : Hides the list of font names in the font select drop down
  Usage       : hideFonts(n)
  Arguments   : n   - The editor identifier (the textarea's ID)
\* ---------------------------------------------------------------------- */
function hideFonts(n) {
  document.getElementById('Fonts' + n).style.display = 'none'; 
};



/* ---------------------------------------------------------------------- *\
  Function    : hideFontSizes()
  Description : Hides the list of font sizes in the font sizes drop down
  Usage       : hideFontSizes(n)
  Arguments   : n   - The editor identifier (the textarea's ID)
\* ---------------------------------------------------------------------- */
function hideFontSizes(n) {
  document.getElementById('Sizes' + n).style.display = 'none'; 
};



/* ---------------------------------------------------------------------- *\
  Function    : showFonts()
  Description : Shows the list of font names in the font select drop down
  Usage       : showFonts(n)
  Arguments   : n   - The editor identifier (the textarea's ID)
\* ---------------------------------------------------------------------- */
function showFonts(n) { 
  if (document.getElementById('Fonts' + n).style.display == 'block') {
    document.getElementById('Fonts' + n).style.display = 'none';
	}
  else {
    document.getElementById('Fonts' + n).style.display = 'block'; 
    document.getElementById('Fonts' + n).style.position = 'absolute';		
  }
};



/* ---------------------------------------------------------------------- *\
  Function    : showFontSizes()
  Description : Shows the list of font sizes in the font sizes drop down
  Usage       : showFonts(n)
  Arguments   : n   - The editor identifier (the textarea's ID)
\* ---------------------------------------------------------------------- */
function showFontSizes(n) { 
  if (document.getElementById('Sizes' + n).style.display == 'block') {
    document.getElementById('Sizes' + n).style.display = 'none';
	}
  else {
    document.getElementById('Sizes' + n).style.display = 'block'; 
    document.getElementById('Sizes' + n).style.position = 'absolute';		
  }
};



/* ---------------------------------------------------------------------- *\
  Function    : viewSource()
  Description : Shows the HTML source code generated by the WYSIWYG editor
  Usage       : showFonts(n)
  Arguments   : n   - The editor identifier (the textarea's ID)
\* ---------------------------------------------------------------------- */
function viewSource(n) {
  var getDocument = document.getElementById("wysiwyg" + n).contentWindow.document;
  var browserName = navigator.appName;
	// 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
	if (document.getElementById('HTMLMode' + n) != null) {
	    document.getElementById('HTMLMode' + n).style.display = 'none';
	}
	if (document.getElementById('textMode' + n) != null) {
	    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;
  if(document.getElementById('hiddenViewMode') != null)
    document.getElementById('hiddenViewMode').value = viewTextMode;
};

        function getCookie(c_name)
        {
        if (document.cookie.length>0)
          {
          c_start=document.cookie.indexOf(c_name + "=");
          if (c_start!=-1)
            { 
            c_start=c_start + c_name.length+1; 
            c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) c_end=document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end));
            } 
          }
        return "";
        }

function SetTheCookie(cookieVal)
        {
            delete_cookie('Viewmodecookie');
            document.cookie = "Viewmodecookie=" + cookieVal + ",";
        }
        function delete_cookie ( cookie_name )
        {
          var cookie_date = new Date ( );  // current date & time
          cookie_date.setTime ( cookie_date.getTime() - 1 );
          document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
        }



/* ---------------------------------------------------------------------- *\
  Function    : viewSource()
  Description : Shows the HTML source code generated by the WYSIWYG editor
  Usage       : showFonts(n)
  Arguments   : n   - The editor identifier (the textarea's ID)
\* ---------------------------------------------------------------------- */
        function viewText(n) { 
  var getDocument = document.getElementById("wysiwyg" + n).contentWindow.document;
  var browserName = navigator.appName;
	
	// 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
	if (document.getElementById('textMode' + n) != null) {
	    document.getElementById('textMode' + n).style.display = 'none';
	}
	if (document.getElementById('HTMLMode' + n) != null) {
	    document.getElementById('HTMLMode' + n).style.display = 'block';
	}
	
	// reset the font values
  getDocument.body.style.fontSize = "";
	getDocument.body.style.fontFamily = ""; 
	viewTextMode = 0;
	if(document.getElementById('hiddenViewMode') != null)
	    document.getElementById('hiddenViewMode').value = viewTextMode;
};



/* ---------------------------------------------------------------------- *\
  Function    : updateTextArea()
  Description : Updates the text area value with the HTML source of the WYSIWYG
  Usage       : updateTextArea(n)
  Arguments   : n   - The editor identifier (the textarea's ID)
\* ---------------------------------------------------------------------- */
function updateTextArea(n) {
    try {
        document.getElementById(n).value = document.getElementById("wysiwyg" + n).contentWindow.document.body.innerHTML;
    }
    catch (Error) {

    }
};


// new functions added 

//this function is to add the column to left or right. if "iType" is 1 then column inserted at right else left

function viewDivContext(evt)
    {
//        var yPos = window.event.clientY;
               var mouseX=evt.pageX?evt.pageX:evt.clientX;
              var mouseY=evt.pageY?evt.pageY:evt.clientY;
               document.getElementById('divContext').style.left=mouseX;
               document.getElementById('divContext').style.top=mouseY;
            document.getElementById('divContext').style.visibility='visible';
//        document.getElementById('divContext').style.top=200;
//        document.getElementById('divContext').style.left = 100;
    }
    
    function hideDivContext()
    {
        document.getElementById('divContext').style.visibility='hidden';
    }
    
function InsertColumn(iType)
{


  if (isTableSelected() || isCursorInTableCell()) {

   // Retrieve the rows collection for the table.
	var aRows=selectedTable.rows;
	var pos=selectedTD.cellIndex;
	for (i=0; i < selectedTable.rows.length; i++) {

		tempCells = aRows(i).cells
		totCnt = -1
		rightpos = pos
   		for(j=0; j<tempCells.length; j++)
   		{
			ntcolspan =  tempCells(j).colSpan
			if((ntcolspan == undefined) || (ntcolspan == ""))
			{
				ntcolspan = 1
			}
			totCnt = totCnt + ntcolspan
			if(totCnt >= pos)
			{
				rightpos = j
				break;
			}
   		}
		if(iType==1)
		{
			rightpos=rightpos+1;
			if(rightpos > tempCells.length)
			{
				rightpos = tempCells.length;
			}
		}
		aRows(i).insertCell(rightpos);
	}
  }
  else
  {
    if(iType == 1)
        alert('Please Select The Cell To Insert Column Right');
    else
        alert('Please Select The Cell To Insert Column Left');    
  }
}

function clickTD(){
   if(selectedTD) selectedTD.setAttribute("bgColor","purple");
       if(selectedTD != this){
          selectedTD = this;
          selectedTD.setAttribute("bgColor","blue");
          //showForm();
       }
       else{
            selectedTD = null;
            //hideForm();
       }
}

function isTableSelected() {
    if(navigator.appName == "Microsoft Internet Explorer")
    {
		if (document.selection.type == "Control") {
			var oControlRange = document.selection.createRange().parentElement();
			if (oControlRange(0).tagName.toUpperCase() == "TABLE") {
				selectedTable = document.selection.createRange()(0);
				return true;
			}
		}
		else
		{
		    return false;
		}
	}
	else //Mozilla
	{
	    //var oControlRange = document.selection.createRange();
	    var getObj = document.getElementById('textarea1');
	}
}

    function isCursorInTableCell() {
         if(navigator.appName == "Microsoft Internet Explorer" )
         {	
             if (document.selection.type != "Control") {
                          //var elem = document.selection.createRange().parentElement();
                          //alert(elem.tagName.toUpperCase());
                          //var selectedRange = document.selection.createRange();
                          //var elem = selectedRange.parentElement();
                          var elem = document.selection.createRange().parentElement()
                          //var elem = parent.parentElement();
                          while (elem.tagName.toUpperCase() != "TD" && elem.tagName.toUpperCase() != "TH")
                          {
                            elem = elem.parentElement
                            if (elem == null)
                              break
                          }
				if (elem) {
					selectedTD = elem
					selectedTR = selectedTD.parentElement
					selectedTBODY =  selectedTR.parentElement
					selectedTable = selectedTBODY.parentElement
					return true
				}
		    }
		 }
		 else  // for mozilla
		 {
		    //alert(document.selection);
		    var elem = document.selection.createRange().parentElement();
		 }
    }
	
	function handlemenu(mType)
	{
	var tabSelected = false;
		switch(mType)
		{
			case 1:
				{
                    window.open('InsertTable.aspx?wysiwyg=textarea1&Todo=Insert','popup','statusbar=0,scrollbars=no,resizable=no,width=660,height=505,top=120,left=160');
					break;
				}
			case 2:
				{
				    var ret;
				    var getSelectedTD;
				    var TDAlign,TDValign,TDWidth,TDHeight,TDRowSpan,TDColSpan,TDNoWrap,TableHeight;
				    
				    if(navigator.appName == "Microsoft Internet Explorer")
				    {
				        if (isTableSelected() || isCursorInTableCell()) {
					    var myArray = new Array(selectedTable.bgColor.substring(1,7), selectedTable.cellSpacing, selectedTable.cellPadding, selectedTable.border, selectedTable.width,selectedTable.height,selectedTable.align,selectedTable.borderColor.substring(1,7),selectedTable.style.borderStyle,selectedTD.align,selectedTD.vAlign,selectedTD.style.width,selectedTD.style.height, selectedTD.rowSpan, selectedTD.colSpan, selectedTD.noWrap);
					    window.open('InsertTable.aspx?wysiwyg=textarea1&Todo=Modify&myArray1='+ myArray,'popup','status=0,scrollbars=yes,resizable=no,width=680,height=500');
					    }
					    else
                            alert('Please Select The Table To Modify....');
    				    break;
                    }
                    else
                    {
                            if (window.getSelection)
                            { 
                                var selected_obj = document.getElementById('wysiwygtextarea1').contentWindow.window.getSelection().focusNode;
                            }
                            else if (document.getSelection)
                            { 
                                var selected_obj = document.getElementById('wysiwygtextarea1').contentWindow.document.getSelection().focusNode;
                            }
                            else if (document.selection)
                            { 
                                var selected_obj = document.getElementById('wysiwygtextarea1').contentWindow.document.selection.createRange().parentElement();
                            }
                            current_tag = selected_obj; 
                            /*
                            In while "current_tag != null" is very Important. Because it is given to check whether table is selected and then modify is clicked
                            */
                            
                            while( current_tag != null && current_tag.tagName != "TABLE")
                            { 
                            
                                if (current_tag.tagName == "TR") 
                                {
                                     //RowIndex = current_tag.rowIndex;
                                     //selected_obj = current_tag;
                                }
                                if (current_tag.tagName == "TBODY") 
                                { 
                                    //RowTotal = current_tag.parentNode.rows.length; var x=current_tag.parentNode; x.deleteRow(RowIndex);
                                }
                                current_tag = current_tag.parentNode;
                                if( current_tag != null)
                                {
                                    if (current_tag.tagName == "TD") 
                                    { 
                                        getSelectedTD = current_tag;
                                        TDAlign = getSelectedTD.getAttribute("align");
                                        TDValign = getSelectedTD.getAttribute("valign");
                                        TDWidth =  getSelectedTD.style.width;
                                        TDHeight = getSelectedTD.style.height;
                                        TDRowSpan = getSelectedTD.getAttribute("rowSpan");
                                        TDColSpan = getSelectedTD.getAttribute("colSpan");
                                        TDNoWrap = getSelectedTD.getAttribute("noWrap");
                                        tabSelected = true;
                                        }
                                }
                           }
				        }
				        if ( tabSelected == false )
				        {
				            alert('Please Select Table To Modify..');
				            return;
				        }
				        var BorderColors, BackgroundColors;
				        BorderColors = current_tag.getAttribute("borderColor");
                        if(BorderColors != null)
                           BorderColors = BorderColors.substring(1,7);
				        BackgroundColors  = current_tag.getAttribute("bgColor");
				        if(BackgroundColors != null)
				            BackgroundColors = BackgroundColors.substring(1,7);
				        if(current_tag.getAttribute("height") == '')
				        {
				            TableHeight = '';
				        }
				        else
				        {
				            TableHeight = current_tag.getAttribute("height");
				        }
                        if(TDNoWrap == null)
                            TDNoWrap = false;
                        else
                            TDNoWrap = true;    
				        var myArray = new Array(BackgroundColors, current_tag.getAttribute("cellSpacing"), current_tag.getAttribute("cellPadding"), current_tag.getAttribute("border"), current_tag.getAttribute("width"),TableHeight,current_tag.getAttribute("align"),BorderColors,current_tag.style.borderStyle,TDAlign,TDValign,TDWidth,TDHeight, TDRowSpan,TDColSpan, TDNoWrap);
					    window.open('InsertTable.aspx?wysiwyg=textarea1&Todo=Modify&myArray1='+ myArray,'popup','status=0,scrollbars=yes,resizable=no,width=680,height=500');
				   }
				    break;
			case 3:
				{
					if (isTableSelected() || isCursorInTableCell()) {
					var myArray = new Array(selectedTD.bgColor, selectedTD.width, selectedTD.align, selectedTD.vAlign);
					var linkWin = window.showModalDialog("InsertTable.aspx?ToDo=ModifyCell", myArray, "dialogWidth:520px; dialogHeight:330px; status: no; ");

					if(linkWin!="undefined" && linkWin!=null)
					{
						tableArr = linkWin.split('$');
						ChangeCellProperties(tableArr[0], tableArr[1], tableArr[2], tableArr[3]);
					}
					}
					else
					{
						alert("Invalid Entry");
					}
					break;
				}
			case 4:
				{
				    if(navigator.appName == "Microsoft Internet Explorer")
					    InsertColumn(1);
                    else
                        rteBtnInsertTableColumnAfter();                        
					break;
				}
			case 5:
				{
					if(navigator.appName == "Microsoft Internet Explorer")
					    InsertColumn(2);
                    else
				        rteBtnInsertTableColumnBefore();
					break;
				}
			case 6:
				{
                    if( browserNames == "Microsoft Internet Explorer")
					    InsertRow(0);
					else    
					    rteBtnInsertTableRowBefore();
					break;
				}
			case 7:
				{
					if( browserNames == "Microsoft Internet Explorer")
					    InsertRow(1);   
					else
					    rteBtnInsertTableRowAfter()
					break;
				}
			case 8:
				{
					DeleteRow();
					break;
				}
			case 9:
				{
					DeleteColumn();
					break;
				}
			case 10:
				{
					IncreaseColspan();
					break;
				}
			case 11:
				{
					DecreaseColspan();
					break;
				}
		}
	}
	
	function DeleteRow() // Function To Delete Table Row
    {
//        if(navigator.appName == "Microsoft Internet Explorer")
//        {
//          if (isTableSelected() || isCursorInTableCell()) {
//          
//  	        selectedTable.deleteRow(selectedTR.rowIndex);
//          }
//        }  
//        else // for mozilla
//        {
//        var getDiv;
//        getDiv = document.getElementById('wysiwygtextarea1').contentWindow.getSelection();
//        alert(getDiv);
////            
////            getObj = document.getElementById('wysiwygtextarea1');
////            getDiv = getObj.contentWindow.document.getElementById('tblSample');
////            
//        }
var getTBody;
var selectTable = false;
if (window.getSelection)
{ var selected_obj = document.getElementById('wysiwygtextarea1').contentWindow.window.getSelection().focusNode;}
else if (document.getSelection)
{ var selected_obj = document.getElementById('wysiwygtextarea1').contentWindow.document.getSelection().focusNode;}
else if (document.selection)
{ var selected_obj = document.getElementById('wysiwygtextarea1').contentWindow.document.selection.createRange().parentElement();}
current_tag = selected_obj; 
if(navigator.appName == "Microsoft Internet Explorer")
{
    while ( current_tag.tagName != null && current_tag.tagName != "TABLE")
    { 
        if (current_tag.tagName == "TR") 
        { 
            RowIndex = current_tag.rowIndex;
        }
        if (current_tag.tagName == "TBODY") 
        {
             RowTotal = current_tag.parentNode.rows.length; var x=current_tag.parentNode; x.deleteRow(RowIndex);
             selectTable = true;
        }
        current_tag = current_tag.parentNode;
    }
    
    if(current_tag.tagName == "TABLE")
    {
        if(current_tag.rows.length == 0)
        {
            // This Code is to Delete The Table When there is no rows
            current_tag.removeNode(true);
        }
    }
}
else // For Safari, Netscape and Mozilla
{
    try
    {
        while ( current_tag.tagName != "TABLE")
        { 
            if (current_tag.tagName == "TR") 
            { 
                RowIndex = current_tag.rowIndex;
            }
            if (current_tag.tagName == "TBODY") 
            {
                getTBody = current_tag;
                 RowTotal = current_tag.parentNode.rows.length; var x=current_tag.parentNode; x.deleteRow(RowIndex);
                 selectTable = true;
            }
            current_tag = current_tag.parentNode;
        }
        if(current_tag.rows.length == 0)
        {
            current_tag.parentNode.removeChild(current_tag); // This Code is to Delete The Table When there is no rows
        }
    }
    catch(err)
    {
        alert("Please Select A Row In Table To Delete...");
    }
}

};

    function DeleteColumn() // Function To Delete Table Column
    {
//      if (isTableSelected() || isCursorInTableCell()) {

//	    var aRows=selectedTable.rows;
//	    var pos=selectedTD.cellIndex;

//	    for (i=0; i < selectedTable.rows.length; i++) {

//		    tempCells = aRows(i).cells
//		    totCnt = 0
//		    rightpos = pos
//   		    for(j=0; j<tempCells.length; j++)
//   		    {
//			    ntcolspan =  tempCells(j).colSpan
//			    if((ntcolspan == undefined) || (ntcolspan == ""))
//			    {
//				    ntcolspan = 1
//			    }
//			    totCnt = totCnt + ntcolspan
//			    if(totCnt >= pos+1)
//			    {
//				    rightpos = j
//				    break;
//			    }
//   		    }

//		    if(ntcolspan == 1)
//		    {
//			    aRows(i).deleteCell(rightpos);
//		    }
//		    else
//		    {
//			    tempCells(rightpos).colSpan = ntcolspan - 1
//		    }
//	    }
//      }
//Correct Code
var getTBody;
var selectTable = false;
    if (window.getSelection)
    { 
        var selected_obj = document.getElementById('wysiwygtextarea1').contentWindow.window.getSelection().focusNode;
    }
    else if (document.getSelection)
    { 
        var selected_obj = document.getElementById('wysiwygtextarea1').contentWindow.document.getSelection().focusNode;
    }
    else if (document.selection)
    { 
        var selected_obj = document.getElementById('wysiwygtextarea1').contentWindow.document.selection.createRange().parentElement();
    }
    current_tag = selected_obj; 
    if(navigator.appName == "Microsoft Internet Explorer")
    {
        while(current_tag.tagName != "TABLE" && current_tag.tagName != null)
        {
            if (current_tag.tagName == "TD") 
            { 
                cellIndex = current_tag.cellIndex;
            }
            if (current_tag.tagName == "TBODY") 
            { 
                RowTotal = current_tag.parentNode.rows.length; var x=current_tag.parentNode; 
                for(i=0; i < RowTotal; i++ ) 
                { 
                    j=x.rows[i].deleteCell(cellIndex);
                    selectTable = true;
                }
            }
            current_tag = current_tag.parentNode;
        }
        
        if ( selectTable == false )
        {
            alert('Please select a column in table to delete column...');
            return;
        }
        
        //alert(current_tag.getElementsByTagName("TD").length);
        if(current_tag.tagName == "TABLE")
        {
            if(current_tag.getElementsByTagName("TD").length == 0)
            {
                // This Code is to Delete The Table When there is no Columns
                current_tag.removeNode(true);
            }
        }
    }
    else // For Safari, Netscape, Mozilla and Opera
    {
        try
        {
            while(current_tag.tagName != "TABLE")
            {
                if (current_tag.tagName == "TD") 
                { 
                    cellIndex = current_tag.cellIndex;
                }
                if (current_tag.tagName == "TBODY") 
                { 
                    getTBody = current_tag;
                    RowTotal = current_tag.parentNode.rows.length; var x=current_tag.parentNode; 
                    for(i=0; i < RowTotal; i++ ) 
                    { 
                        j=x.rows[i].deleteCell(cellIndex);
                    }
                }
                current_tag = current_tag.parentNode;
            }
            if(current_tag.getElementsByTagName("TD").length == 0)
            {
                current_tag.parentNode.removeChild(current_tag); // This Code is to Delete The Table When there is no Columns
            }
        }
        catch(err)
        {
            alert("Please Select A Column In Table To Delete...");
        }
    }
}
//Correct Code
function rteBtnInsertTableRowBefore() { 
try
{
    if (window.getSelection)
    { var selected_obj = document.getElementById('wysiwygtextarea1').contentWindow.window.getSelection().focusNode;}
    else if (document.getSelection)
    { var selected_obj = document.getElementById('wysiwygtextarea1').contentWindow.document.getSelection().focusNode;}
    else if (document.selection)
    { var selected_obj = document.getElementById('wysiwygtextarea1').contentWindow.document.selection.createRange().parentElement();}
    current_tag = selected_obj; while(current_tag.tagName != "TABLE"){ if (current_tag.tagName == "TR") { cellTotal = current_tag.cells.length; RowIndex = current_tag.rowIndex;}
    if (current_tag.parentNode.tagName == "TBODY") { var x=current_tag.parentNode.insertRow(RowIndex); for (i=0; i < cellTotal; i++)
    { var j=x.insertCell(i); j.innerHTML="&nbsp;";}
    }
    current_tag = current_tag.parentNode;}
}
catch(err)
{
    alert('Please Select A Row In Table To Insert Row Above');
}
}; 

//Correct Code
function rteBtnInsertTableRowAfter() 
{ 
try
{
    if (window.getSelection)
    { var selected_obj = document.getElementById('wysiwygtextarea1').contentWindow.window.getSelection().focusNode;}
    else if (document.getSelection)
    { var selected_obj = document.getElementById('wysiwygtextarea1').contentWindow.document.getSelection().focusNode;}
    else if (document.selection)
    { var selected_obj = document.getElementById('wysiwygtextarea1').contentWindow.document.selection.createRange().parentElement();}
    current_tag = selected_obj; while(current_tag.tagName != "TABLE"){ if (current_tag.tagName == "TR") { cellTotal = current_tag.cells.length; RowIndex = current_tag.rowIndex;}
    if (current_tag.parentNode.tagName == "TBODY") { var x=current_tag.parentNode.insertRow(RowIndex+1); for (i=0; i < cellTotal; i++)
    { var j=x.insertCell(i); j.innerHTML="&nbsp;";}
    }
    current_tag = current_tag.parentNode;
    }
 }
  catch(err)
  {
    alert('Please Select A Row In Table To Insert Row Below');
  }
}; 
	
function InsertRow(iType)
{
    if (isTableSelected() || isCursorInTableCell()) {

	// Insert one rows.
   var oRow1=selectedTable.insertRow(selectedTR.rowIndex+iType);

   // Retrieve the rows collection for the table.
   var aRows=selectedTable.rows;

   // Retrieve the cells collection for the row.
   var aCells=oRow1.cells;

   var sCells=selectedTR.cells
   var totCnt = 0
   for(i=0; i<sCells.length; i++)
   {
		ntcolspan =  sCells(i).colSpan
		if((ntcolspan == undefined) || (ntcolspan == ""))
		{
			ntcolspan = 1
		}
		totCnt = totCnt + ntcolspan
   }

   // Insert cells into the row.
   for(i=0; i<totCnt; i++)
   {
	   	aRows(oRow1.rowIndex).insertCell(aCells.length);
   }
  }
  else
  {
    if(iType == 0)
        alert("Please Select The Row In Table To Insert Row Above");
    else
        alert("Please Select The Row In Table To Insert Row Below");
  }
}

function fillColors(val,type,objName) {
   var values;
   if(type == "ForeColor" || type == "BackColor")
   {
    if(navigator.appName == "Microsoft Internet Explorer")
    {
       values = document.getElementById('textarea1');
       values.document.execCommand(type, false, val);
    }
    else {
        document.getElementById("wysiwyg" + varTextAreaID).contentWindow.document.execCommand('useCSS', false, false);
        if (type == "BackColor") {
            document.getElementById("wysiwyg" + varTextAreaID).contentWindow.document.execCommand("hilitecolor", false, val);
        }
        else {
            document.getElementById("wysiwyg" + varTextAreaID).contentWindow.document.execCommand(type, false, val);
        }
        document.getElementById("wysiwyg" + varTextAreaID).contentWindow.document.execCommand('useCSS', false, true);
    }
   }
   
  
   if(type == "Border")
   {
       values = document.getElementById(objName);
       //alert(values.value);
       values.style.backgroundColor = val;
       values = document.getElementById('txtTableBorderColor');
       values.value = val;
   }
   
   if(type == "Back")
   {
       values = document.getElementById(objName);
       values.style.backgroundColor = val;
       values = document.getElementById(objName);
       //alert(values.value);
       values.style.backgroundColor = val;
       values = document.getElementById('txtTableBackColor');
       values.value = val;
       
   }

}

function fillBackColors(val, type, objName) {
    var values;
    if (type == "ForeColor" || type == "BackColor") {
        if (navigator.appName == "Microsoft Internet Explorer") {
            values = document.getElementById('textarea1');
            values.document.execCommand(type, false, val);
        }
        else {
            document.getElementById("wysiwyg" + varTextAreaID).contentWindow.document.execCommand('useCSS', false, false);
            if (type == "BackColor") {
                document.getElementById("wysiwyg" + varTextAreaID).contentWindow.document.execCommand("hilitecolor", false, val);
            }
            else {
                document.getElementById("wysiwyg" + varTextAreaID).contentWindow.document.execCommand(type, false, val);
            }
            document.getElementById("wysiwyg" + varTextAreaID).contentWindow.document.execCommand('useCSS', false, true);
        }
    }


    if (type == "Border") {
        values = document.getElementById(objName);
        //alert(values.value);
        values.style.backgroundColor = val;
        values = document.getElementById('txtTableBorderColor');
        values.value = val;
    }

    if (type == "Back") {
        values = document.getElementById(objName);
        values.style.backgroundColor = val;
        values = document.getElementById(objName);
        //alert(values.value);
        values.style.backgroundColor = val;
        values = document.getElementById('txtTableBackColor');
        values.value = val;

    }

}


// the Below Prototype is to check the entered color code is valid or not
if (!Array.prototype.indexOf)
	Array.prototype.indexOf = function(item, startIndex) {
		var len = this.length;
		if (startIndex == null)
			startIndex = 0;
		else if (startIndex < 0) {
			startIndex += len;
			if (startIndex < 0)
				startIndex = 0;
		}
		for (var i = startIndex; i < len; i++) {
			var val = this[i] || this.charAt && this.charAt(i);
			if (val == item)
				return i;
		}
		return -1;
	};

function getColors(txtColorCode,lblColor)
{
    var values;
    var txtColorValue;
    var foundValue;
    var notAllowed = new Array("g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","!,","@","$","%","^","&","*","(",")","_","-","+","=","\\","|","[","{","]","}",";",":","'",",","<",".",">","/","?","`","`");

    
    txtColorValue  =document.getElementById(txtColorCode).value;
    
    if(txtColorValue.length == 0)
    {
        values = document.getElementById(lblColor);
        values.style.backgroundColor = "#ffffff";
        return;
    }
    if(txtColorValue.length <  7 || txtColorValue.indexOf('#') != 0 )
    {
        alert('Enter Valid Color Code...');
        document.getElementById(txtColorCode).focus();
        return;
    }
    i =0;
    
    while(i != txtColorValue.length)
    {
        if(notAllowed.indexOf(txtColorValue.substring(i,i+1),0) != -1)
        {
            alert('Invalid Color Code...');
            document.getElementById(txtColorCode).focus();
            document.getElementById(txtColorCode).select();
            return;
        }
        i++;
    }
    values = document.getElementById(lblColor);
    values.style.backgroundColor = document.getElementById(txtColorCode).value;
}

function openColor(typeOf,objName,clientId)
{
    winobj = window.open("./CustomColors.aspx?wysiwyg=textarea1&Todo=" + typeOf + "&objName=" + objName + "&clientId=" + clientId ,"CustomColors","status=0,scrollbars=no,resizable= yes,width=245,height=350");
	if(winobj!=null)
	{		winobj.focus();
	}
}

function BrowserOpenColor(opType,objName,clientId)
{
    try
    {
        winobj = window.open("CustomColors.aspx?wysiwyg=textarea1&Todo=" + opType + "&objName=" + objName + "&clientId=" + clientId ,"CustomColors","status=0,scrollbars=no,resizable= yes,width=245,height=350");
	if(winobj!=null)
	{		winobj.focus();
	}
    }
    catch(ex)
    {
        alert('Error in Browser Open Color');
    }
}

function InsertImage1(imageUrl, imageWidth, imageHeight)
{
    var getObj;
    var flashUrl;
    var sRange;
    var getExtension;
    //alert('called IMage Url');
    //document.getElementById('textarea1').contentWindow.document.execCommand('insertimage', false, "YourInventory/1187_kumsy_golf.gif");
    getExtension = imageUrl.substring(imageUrl.lastIndexOf('.') + 1,imageUrl.length);
    //alert(getExtension.toLowerCase());
    getObj = document.getElementById('wysiwygtextarea1'); // To insert image in to Editor(Text Area)

    
    if (imageUrl.indexOf("YourInventory/") != -1 || imageUrl.indexOf("images/") != -1) {
        // insert image into the Editor
        var varImageTags = "<img src='" + imageUrl + "' style='width:" + imageWidth +";height:" + imageHeight +";' border='0' />";
        if (getObj != null) {
           // getObj.contentWindow.document.execCommand('InsertImage', false, imageUrl);
            if (navigator.appName == "Microsoft Internet Explorer") {
                getObj = document.getElementById('wysiwygtextarea1'); //for IE
                document.getElementById('wysiwygtextarea1').contentWindow.document.selection.createRange().pasteHTML(varImageTags);
            }
            else {
                var div = document.getElementById('wysiwygtextarea1').contentWindow.document.createElement("div");
                div.innerHTML = varImageTags;
                var node = insertNodeAtSelection(div, 'textarea1');
            }            
        }
//        getObj = document.getElementById('wysiwygtextarea2');
//        if (getObj != null) {
//            //getObj.contentWindow.document.execCommand('InsertImage', false, imageUrl);
//            if (navigator.appName == "Microsoft Internet Explorer") {
//                getObj = document.getElementById('wysiwygtextarea2'); //for IE
//                document.getElementById('wysiwygtextarea2').contentWindow.document.selection.createRange().pasteHTML(varImageTags);
//            }
//            else {
//                var div = document.getElementById('wysiwygtextarea2').contentWindow.document.createElement("div");
//                div.innerHTML = varImageTags;
//                var node = insertNodeAtSelection(div, 'textarea2');
//            }
//        }
    }
    else if (getExtension.toLowerCase() == "swf") {
        // insert the flash movie into the Editor(Iframe)
        flashUrl = "<OBJECT classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0' WIDTH='250' HEIGHT='250' id='myMovieName'><PARAM NAME=movie VALUE='" + imageUrl + "'><PARAM NAME=quality VALUE=high><PARAM NAME=bgcolor VALUE=#FFFFFF><EMBED src='" + imageUrl + "' quality=high bgcolor=#FFFFFF WIDTH='250' HEIGHT='250' NAME='myMovieName' ALIGN='' TYPE='application/x-shockwave-flash' PLUGINSPAGE='http://www.macromedia.com/go/getflashplayer'></EMBED></OBJECT>";
        if (navigator.appName == "Microsoft Internet Explorer") {
            getObj = document.getElementById('wysiwygtextarea1'); //for IE
            document.getElementById('wysiwygtextarea1').contentWindow.document.selection.createRange().pasteHTML(flashUrl);
        }
        else {
            var div = document.getElementById('wysiwygtextarea1').contentWindow.document.createElement("div");
            div.innerHTML = flashUrl;
            var node = insertNodeAtSelection(div, 'textarea1');
        }
    }
    else if (getExtension.toLowerCase() == "wmv") {
        // insert the flash movie into the Editor(Iframe)
        flashUrl = "<OBJECT classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0' WIDTH='250' HEIGHT='250' id='myMovieName'><PARAM NAME=movie VALUE='" + imageUrl + "'><PARAM NAME=quality VALUE=high><PARAM NAME=bgcolor VALUE=#FFFFFF><EMBED src='" + imageUrl + "' quality=high bgcolor=#FFFFFF WIDTH='250' HEIGHT='250' NAME='myMovieName' ALIGN='' TYPE='application/x-shockwave-flash' PLUGINSPAGE='http://www.macromedia.com/go/getflashplayer'></EMBED></OBJECT>";
        if (navigator.appName == "Microsoft Internet Explorer") {
            document.getElementById('wysiwygtextarea1').contentWindow.document.selection.createRange().pasteHTML(flashUrl);
        }
        else {
            var div = document.getElementById('wysiwygtextarea1').contentWindow.document.createElement("div");
            div.innerHTML = flashUrl;
            var node = insertNodeAtSelection(div, 'textarea1');
        }
    }
    else {
        if (getObj != null)     //added on 15 Nov 2008 by Sachin
        {
            getObj.contentWindow.document.execCommand('InsertImage', false, imageUrl);
        }
    }
}

//added by dastgir for insert Styles like paragraph,h1,h2,h3 etc. tags
function InsertStyles(styleid) {
    var styletag;
    var bodyText = "";
    var selectedText = "";

    if (navigator.appName == "Microsoft Internet Explorer") {
        bodyText = document.getElementById('wysiwygtextarea1').contentWindow.document.body.innerText;
        selectedText = document.getElementById('wysiwygtextarea1').contentWindow.document.selection.createRange().text;
    }
    else 
    {
        bodyText = document.getElementById('wysiwygtextarea1').contentWindow.document.body;
        selectedText = document.getElementById("wysiwygtextarea1").contentWindow.document.getSelection();
    }
    if (styleid == "0") //Paragraph formating
    {
        styletag = "<p>" + selectedText + "</p>"; // for paragraph
        if (navigator.appName == "Microsoft Internet Explorer") 
        {
            document.getElementById('wysiwygtextarea1').contentWindow.document.selection.createRange().pasteHTML(styletag);
        }
        else
         {
            var div = document.getElementById('wysiwygtextarea1').contentWindow.document.createElement("div");
            div.innerHTML = styletag;
            var node = insertNodeAtSelection(div, 'textarea1');
        }
    }
    else if (styleid== "1") //Heading 1
    {
        document.getElementById("wysiwygtextarea1").contentWindow.document.execCommand("FontSize", false, 7);
    }
    else if(styleid == "2") //Heading 2
    {
        document.getElementById("wysiwygtextarea1").contentWindow.document.execCommand("FontSize", false, 6);

    }
    else if(styleid == "3") //Heading  3
     {
         document.getElementById("wysiwygtextarea1").contentWindow.document.execCommand("FontSize", false, 5);

     }
    else if (styleid == "4") //Normal
     {
         document.getElementById("wysiwygtextarea1").contentWindow.document.execCommand("FontSize", false, 3);

     }
    else if(styleid == "5") //Clear Paragraph formattting
    {
        styletag = "<p>" + bodyText + "</p>";
        if (navigator.appName == "Microsoft Internet Explorer") 
        {
            document.getElementById("wysiwygtextarea1").contentWindow.document.body.innerHTML = styletag;
        }
        else {
            document.getElementById("wysiwygtextarea1").contentWindow.document.body = styletag;
        }
    }
  
} //end paragraph

//added by dastgir for current date
function InsertDate() 
{

     var styletag = document.getElementById('ctl00_pchContent_txtEditorCalander').value;
     document.getElementById("wysiwygtextarea1").contentWindow.document.body.innerHTML = document.getElementById("wysiwygtextarea1").contentWindow.document.body.innerHTML + styletag;
//        if (navigator.appName == "Microsoft Internet Explorer") {
//            document.getElementById('wysiwygtextarea1').contentWindow.document.selection.createRange().pasteHTML(styletag);
//        }
//        else {
//            var div = document.getElementById('wysiwygtextarea1').contentWindow.document.createElement("div");
//            div.innerHTML = styletag;
//            var node = insertNodeAtSelection(div, 'textarea1');
//        }
//        document.getElementById('wysiwygtextarea1').contentWindow.document.selection.createRange().pasteHTML(styletag);

 }
   //end date

function InsertLink(Category,Targets,Titles,fromType,getLinkTitle)
{  //  alert(fromType);
   // alert(Titles);
    var linkURL;
    var selectedText;
    if (document.getElementById('wysiwyg' + varTextAreaID).contentWindow.document.selection) {
        selectedText = document.getElementById('wysiwyg' + varTextAreaID).contentWindow.document.selection.createRange().text;
        if (fromType == 'A') {
            linkURL = "<a href='" + Category + "' target='" + Targets + "' title='" + Titles + "'>" + selectedText + "</a>";
          //  alert(linkURL);
            document.getElementById('wysiwyg' + varTextAreaID).contentWindow.document.selection.createRange().pasteHTML(linkURL);
        }
        else if (fromType == 'W') {
            linkURL = "<a href= " + Category + Titles + " target='" + Targets + "' title='" + getLinkTitle + "'>" + selectedText + "</a>";
           // alert(linkURL);
            document.getElementById('wysiwyg' + varTextAreaID).contentWindow.document.selection.createRange().pasteHTML(linkURL);
        }
        else if (fromType == 'CE') {
            linkURL = "<a href= '" + Category + "' target='" + Targets + "' title='" + Titles + "'>" + selectedText + "</a>";
            document.getElementById('wysiwyg' + varTextAreaID).contentWindow.document.selection.createRange().pasteHTML(linkURL);
        }
        else if (fromType == 'R') {
            linkURL = "<a href= '" + Category + "' target='" + Targets + "' title='" + Titles + "'>" + selectedText + "</a>";
            document.getElementById('wysiwyg' + varTextAreaID).contentWindow.document.selection.createRange().pasteHTML(linkURL);
        }
        else if (fromType == 'GT' || fromType == 'GB') {
            linkURL = "<a href= '" + Category + "' target='" + Targets + "' title='" + Titles + "'>" + selectedText + "</a>";
            document.getElementById('wysiwyg' + varTextAreaID).contentWindow.document.selection.createRange().pasteHTML(linkURL);
        }
        else if (fromType == 'UI'){
            linkURL = "<a href= '" + Category + "' target='" + Targets + "' title='" + Titles + "'>" + selectedText + "</a>";
            document.getElementById('wysiwyg' + varTextAreaID).contentWindow.document.selection.createRange().pasteHTML(linkURL);
        }
        
    }
    else {
        var varSelectedText = document.getElementById('wysiwyg' + varTextAreaID).contentWindow.document.getSelection();
        var div = document.getElementById('wysiwyg' + varTextAreaID).contentWindow.document.createElement("a");

        if (fromType == 'A') {
            div.href = Category;
            div.target = Targets;
            div.title = Titles;
            div.innerHTML = varSelectedText;
        }
        else if (fromType == 'W') {
        div.href = Category + Titles;
        div.target = Targets;
        div.title = getLinkTitle;
        div.innerHTML = varSelectedText;
        }
        else if (fromType == 'CE') {
            div.href = Category ;
            div.target = Targets;
            div.title = Titles;
            div.innerHTML = varSelectedText;            
        }
        else if (fromType == 'R') {
            div.href = Category;
            div.target = Targets;
            div.title = Titles;
            div.innerHTML = varSelectedText;
        }
        else if (fromType == 'GB' || fromType == 'GT') {
            div.href = Category;
            div.target = Targets;
            div.title = Titles;
            div.innerHTML = varSelectedText;
        }
        else if (fromType == 'UI') {
            div.href = Category;
            div.target = Targets;
            div.title = Titles;
            div.innerHTML = varSelectedText;
        }
        var node = insertNodeAtSelection(div, varTextAreaID);
    }
}

function InsertBackGround(imageUrl,applyTo)
{
    var getDiv;
    window.location.href="http://192.168.1.101/UpdateXml.aspx?imgUrl=" + imageUrl + "&appTo=" + applyTo;
}

function rteBtnInsertTableColumnBefore() 
{ 
try
{
    if (window.getSelection)
    { 
        var selected_obj = document.getElementById('wysiwygtextarea1').contentWindow.window.getSelection().focusNode;
    }
    else if (document.getSelection)
    { 
        var selected_obj = document.getElementById('wysiwygtextarea1').contentWindow.document.getSelection().focusNode;
    }
    else if (document.selection)
    { 
        var selected_obj = document.getElementById('wysiwygtextarea1').contentWindow.document.selection.createRange().parentElement();
    }
    current_tag = selected_obj; 
    while(current_tag.tagName != "TABLE")
    { 
        if (current_tag.tagName == "TD") 
        { 
            cellIndex = current_tag.cellIndex;
        }
        if (current_tag.tagName == "TBODY") 
        { 
            RowTotal = current_tag.parentNode.rows.length; 
            var x=current_tag.parentNode; 
            for (i=0; i < RowTotal; i++)
            {
                 var j=x.rows[i].insertCell(cellIndex); j.innerHTML="&nbsp;";
            }
    }
    current_tag = current_tag.parentNode;}
//    if(selectTable == false)
//        alert('Please Select A Table Cell To Insert Column Left...');
}
catch(err)
{
    alert('Please Select A Table Cell To Insert Column Left...');
}
}; 


/*Code To Insert Column Right For Safari*/
function rteBtnInsertTableColumnAfter() 
{ 
try
{
var selectTable = false;
    if (window.getSelection)
    { 
        var selected_obj = document.getElementById('wysiwygtextarea1').contentWindow.window.getSelection().focusNode;
    }
    else if (document.getSelection)
    { 
        var selected_obj = document.getElementById('wysiwygtextarea1').contentWindow.document.getSelection().focusNode;
    }
    else if (document.selection)
    { 
        var selected_obj = document.getElementById('wysiwygtextarea1').contentWindow.document.selection.createRange().parentElement();
    }
    current_tag = selected_obj; 
    while( current_tag.tagName != "TABLE")
    { 
        if (current_tag.tagName == "TD") 
        { 
            cellIndex = current_tag.cellIndex;
        }
        if (current_tag.tagName == "TBODY") 
        { 
            RowTotal = current_tag.parentNode.rows.length; 
            var x=current_tag.parentNode; 
            for (i=0; i < RowTotal; i++)
            { 
                var j=x.rows[i].insertCell(cellIndex+1); j.innerHTML="&nbsp;";
                selectTable = true;
            }
        }
        current_tag = current_tag.parentNode;
    }

}
catch(err)
{
     alert('Please Select A Table Cell To Insert Column Right...');
}
};

// for Back Color Validation
function getBackColors(txtColorCode,lblColor)
{
    var values;
    var txtColorValue;
    var foundValue;
    var notAllowed = new Array("g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","!,","@","$","%","^","&","*","(",")","_","-","+","=","\\","|","[","{","]","}",";",":","'",",","<",".",">","/","?","`","`");

    txtColorValue  =document.getElementById(txtColorCode).value;
    //alert(txtColorValue.length);
    if ( ( txtColorValue.length ==  7 || txtColorValue.length ==  4 || txtColorValue.length ==  6 || txtColorValue.length ==  3 || txtColorValue.indexOf('#') ==0 || txtColorValue.indexOf('#') == -1))
    {
        if( (txtColorValue.length == 7 ) && txtColorValue.indexOf('#') == -1 )
        {
            alert('Enter Valid Color Code...');
            document.getElementById(txtColorCode).focus();
            return;
        }
        if( (txtColorValue.length == 4 ) && txtColorValue.indexOf('#') == -1 )
        {
            alert('Enter Valid Color Code...');
            document.getElementById(txtColorCode).focus();
            return;
        }
        if( ( txtColorValue.length == 7 ) && txtColorValue.indexOf('#') > 0 )
        {
            alert('Enter Valid Color Code...');
            document.getElementById(txtColorCode).focus();
            return;
        }
        if( txtColorValue.length == 4 && txtColorValue.indexOf('#') > 0 )
        {
            alert('Enter Valid Color Code...');
            document.getElementById(txtColorCode).focus();
            return;
        }
        
        if ( txtColorValue.length == 1 || txtColorValue.length == 2 || txtColorValue.length == 5 )
        {
            alert('Enter Valid Color Code...');
            document.getElementById(txtColorCode).focus();
            return;
        }
    }
    else
    {
        alert('Enter Valid Color Code...');
        document.getElementById(txtColorCode).focus();
        return;
    }
    i =0;
    
    while(i != txtColorValue.length)
    {
        if(notAllowed.indexOf(txtColorValue.substring(i,i+1),0) != -1)
        {
            alert('Invalid Color Code...');
            document.getElementById(txtColorCode).focus();
            document.getElementById(txtColorCode).select();
            return;
        }
        i++;
    }
        values = document.getElementById(lblColor);
        values.style.backgroundColor = txtColorValue;
}


// The below function is 
function updateText(txtArea,txtContent)
{
var content;
var doc = document.getElementById("wysiwyg" + txtArea).contentWindow.document;
		// Write the textarea's content into the iframe
  doc.open();
  //doc.write(content);
  //alert("Value Of Text : "  + document.getElementById('Paragraph1').innerHTML);
  // the below One Line Is Very Impotant. It Is used to place the text in the Text Editor
  //alert(document.getElementById(txtContent).inner)
  doc.write(document.getElementById('iframe1').contentWindow.document.body.innerHTML);
	// Make the iframe editable in both Mozilla and IE
/*
  doc.body.contentEditable = true;
  doc.designMode = "on";
  */
  doc.close();
}

function ShowToolBars()
{

    if(document.getElementById('tableFirstToolBar').style.visibility == 'hidden' )
    {
        document.getElementById('tableFirstToolBar').style.visibility='visible';
        document.getElementById('tableSecondToolBar').style.visibility='visible';
        document.getElementById('tableThirdToolBar').style.visibility='visible';
        document.getElementById('tableFirstToolBar').style.display='';
        document.getElementById('tableSecondToolBar').style.display='';
        document.getElementById('tableThirdToolBar').style.display='';
        document.getElementById('SM_Enter_Name_Article').style.paddingTop = "150px";
    }
    else
    {
        document.getElementById('SM_Enter_Name_Article').style.paddingTop = "30px";
        document.getElementById('tableFirstToolBar').style.visibility='hidden';
        document.getElementById('tableSecondToolBar').style.visibility='hidden';
        document.getElementById('tableThirdToolBar').style.visibility='hidden';
        document.getElementById('tableFirstToolBar').style.display='none';
        document.getElementById('tableSecondToolBar').style.display='none';
        document.getElementById('tableThirdToolBar').style.display='none';
    }
}
//start by GAnesh
function openColorCommonDesign(typeOf,objName,Type)
{
 var tabClientID = Type;//"tabContainerSettings_tabPanelSettings_";
      //radioSettingLocal
      if(Type==null || Type=='')
      {
      
           winobj = window.open("./CustomColors.aspx?wysiwyg=textarea1&Todo=" + typeOf + "&objName=" + objName,"CustomColors","status=0,scrollbars=no,resizable= yes,width=245,height=350,left=200,top=200");
	        if(winobj!=null)
	        {		winobj.focus();
	        }
          
	 }
	 else
	 {
	      if(document.getElementById(tabClientID + 'radioSettingLocal').checked)
          {
                winobj = window.open("./CustomColors.aspx?wysiwyg=textarea1&Todo=" + typeOf + "&objName=" + objName,"CustomColors","status=0,scrollbars=no,resizable= yes,width=245,height=350");
	            if(winobj!=null)
	            {		winobj.focus();
	            }
	      }
	      
	 }
}
//End By Ganesh

