//id of active editor

active_rich = null;



//prevent error messaging

window.onerror = no_error;



//root = "http://www.labotal.co.il/site/";

//context menu parser

function parse_context(){



  eval('mode = '+active_rich.name+'_rich_mode;'); //current mode



  //do nothing in source text editing mode

  if(!mode) return;



  sel = active_rich.document.selection;

  r = sel.createRange();



  if(sel.type == 'Control'){



    switch(r(0).tagName){

      case 'TABLE':

        show_dialog("EditTable", r(0)); //edit table

        break;

      case 'IMG':

        show_dialog("EditImage", r(0)); //edit image

        break;

      default:

        break;

    }



  }else{



    if(r.parentElement){ //edit table cell

      td = get_previous_object(r.parentElement(),'TD');

      if(td != null) show_dialog("EditCell", td);

    }



  }



  change_toolbar_state(); //set new states of toolbar buttons



}



//parses toolbar button press event

function do_action(action,value){



  active_rich.focus(); //set focus on active editor



  eval('mode = '+active_rich.name+'_rich_mode;'); //current mode



  //in source mode buttons do not work

  if(!mode) return;



  //check if any control element is active, e.g. image or table

  sel = active_rich.document.selection;

  r = sel.createRange();

  if(sel.type == 'Control') is_control = true;

    else is_control = false;



  found = true;

  switch(action){

    case 'Cut':                 //cut

    case 'Copy':                //copy

    case 'Paste':               //paste

    case 'Undo':                //undo previous action

    case 'Redo':                //redo last cancelled action

    case 'Bold':                //set/unset bold style

    case 'Italic':              //set/unset italic style

    case 'Underline':           //set/unset undeline style

    case 'JustifyLeft':         //justify left

    case 'JustifyCenter':       //justify center

    case 'JustifyRight':        //justify right

    case 'JustifyFull':         //justify full

    case 'InsertOrderedList':   //insert ordered list

    case 'InsertUnorderedList': //insert unordered list

    case 'Outdent':             //decrease indention

    case 'Indent':              //increase indention

    case 'InsertHorizontalRule'://insert horizontal line

    case 'RemoveFormat':        //remove text formatting

      break;

    case 'FormatBlock':         //set paragraph style

    case 'FontName':            //set font

    case 'FontSize':            //set font size

      value = value[value.selectedIndex].value;

      break;

    case 'ClassName':           //set class

      set_class(value[value.selectedIndex].value);

      break;

    case 'ForeColor':           //set foreground color

    case 'BackColor':           //set background color

      if(is_control) break;

      value = pick_color();

      break;

    case 'InsertRow':           //insert row in table

      if(is_control) break;

      insert_row();

      switch_borders(false); //redraw borders under current border mode

      found = false;

      break;

    case 'DeleteRow':           //delete row from table

      if(is_control) break;

      delete_row();

      found = false;

      break;

    case 'InsertColumn':        //insert column in table

      if(is_control) break;

      insert_column();

      switch_borders(false); //redraw borders under current border mode

      found = false;

      break;

    case 'DeleteColumn':        //delete column from table

      if(is_control) break;

      delete_column();

      found = false;

      break;

    case 'PasteWord':

      paste_word();

      found = false;

      break;

    case 'SwitchBorders':

      switch_borders(true);

      found = false;

      break;

    default:

      found = false;

      break;

  }



  active_rich.focus(); //set focus on active editor



  if(found) active_rich.document.execCommand(action, false, value);



  change_toolbar_state(); //set new states of toolbar buttons



}



//changes states of toolbar buttons, when they are pressed/released

function mouse_down(down){

  element = window.event.srcElement;



  if(element && element.tagName=='IMG'){

    pos = String('tbImage_').length;

    name = element.className.substring(pos);

    eval('mode = '+name+'_rich_mode;'); //current mode

  

    //in source mode toolbar buttons do not work

    if(!mode) return;



    if(down){ //pressed

      element.style.borderTop = '1px solid buttonshadow';

      element.style.borderLeft = '1px solid buttonshadow';

      element.style.borderBottom = '1px solid buttonhighlight';

      element.style.borderRight = '1px solid buttonhighlight';

    }else{    //released

      element.style.borderTop = '1px solid buttonhighlight';

      element.style.borderLeft = '1px solid buttonhighlight';

      element.style.borderBottom = '1px solid buttonshadow';

      element.style.borderRight = '1px solid buttonshadow';

    }



  }



}



//changes state of toolbar button, when mouse is over it

function mouse_over(over){



  element = window.event.srcElement;



  if(element && element.tagName=='IMG'){

    pos = String('tbImage_').length;

    name = element.className.substring(pos);

    eval('mode = '+name+'_rich_mode;'); //current mode



    eval('obj = '+name+'_id;'); //editor of the current button

  

    //in source mode toolbar buttons do not work

    if(!mode) return;



    if(over){ //mouse is over button

      element.style.borderTop = '1px solid buttonhighlight';

      element.style.borderLeft = '1px solid buttonhighlight';

      element.style.borderBottom = '1px solid buttonshadow';

      element.style.borderRight = '1px solid buttonshadow';

    }else{    //mouse is moved from the button

      id_name = String(element.id);

      action_name = id_name.substring(0,id_name.length-name.length-1);



      if(action_name == 'SwitchBorders'){//switch borders button

        eval('border_mode = '+obj.name+'_rich_border_mode;');

        old_active_rich = active_rich;

        active_rich = obj;

        set_state(action_name, border_mode);

        active_rich = old_active_rich;

      }else{//common buttons



        if(id_name == '' || !obj.document.queryCommandValue(action_name)){

          element.style.borderTop = '1px solid buttonface';

          element.style.borderLeft = '1px solid buttonface';

          element.style.borderBottom = '1px solid buttonface';

          element.style.borderRight = '1px solid buttonface';

        }else{ //do button pressed

          element.style.borderTop = '1px solid buttonshadow';

          element.style.borderLeft = '1px solid buttonshadow';

          element.style.borderBottom = '1px solid buttonhighlight';

          element.style.borderRight = '1px solid buttonhighlight';

        }



      }



    }



  }



}



//change current editor mode

function change_mode(){

  eval('obj = '+active_rich.name+'_id;');           //editor

  eval('mode = '+active_rich.name+'_rich_mode;');   //current mode

  eval('page_mode = '+active_rich.name+'_rich_page_mode;'); //current page mode

  //current border mode

  eval('border_mode = '+active_rich.name+'_rich_border_mode;');



  if(mode){ //switch in source mode



    //unset borders

    if(border_mode){

      set_borders(false);

    }



    if(!page_mode){

      active_rich.document.body.innerText = active_rich.document.body.innerHTML;

    }else{

      active_rich.document.body.innerText = active_rich.document.documentElement.outerHTML;

    }



    //do toolbar buttons inactive

    for(i=0;i<document.images.length;i++){

      if(document.images(i).className == 'tbImage_'+active_rich.name){

        document.images(i).style.filter = 'alpha(opacity=40)';

        document.images(i).style.cursor = 'default';

      }

    }



    //do all select elements inactive

    eval('document.all.FormatBlock_'+active_rich.name+'.disabled=true;');

    eval('document.all.FontName_'+active_rich.name+'.disabled=true;');

    eval('document.all.FontSize_'+active_rich.name+'.disabled=true;');

    eval('document.all.ClassName_'+active_rich.name+'.disabled=true;');



    eval(active_rich.name+'_rich_mode = false;');

  }else{    //switch in wysiwyg mode



    if(!page_mode){

      active_rich.document.body.innerHTML = '<body>'+active_rich.document.body.innerText+'</body>';

    }else{

      active_rich.document.body.innerHTML = active_rich.document.body.innerText;

    }



    //set borders

    if(border_mode){

      set_borders(true);

    }



    //do toolbar buttons active

    for(i=0;i<document.images.length;i++){

      if(document.images(i).className == 'tbImage_'+active_rich.name){

        document.images(i).style.filter = '';

        document.images(i).style.cursor = 'hand';

      }

    }



    //do all select elements active

    eval('document.all.FormatBlock_'+active_rich.name+'.disabled=false;');

    eval('document.all.FontName_'+active_rich.name+'.disabled=false;');

    eval('document.all.FontSize_'+active_rich.name+'.disabled=false;');

    eval('document.all.ClassName_'+active_rich.name+'.disabled=false;');



    eval(active_rich.name+'_rich_mode = true;');



    //update class info

    set_stylesheet_rules();

  }



}



//changes current states of toolbar buttons

//according to style of text in current position of cursor

function change_toolbar_state(what){



  eval('mode = '+active_rich.name+'_rich_mode;'); //current mode



  //in source mode toolbar buttons do not work

  if(!mode) return;



  if(!what || what == "FormatBlock")         set_style("FormatBlock", active_rich.document.queryCommandValue('FormatBlock'));

 //if(!what || what == "FontName")            set_style("FontName", active_rich.document.queryCommandValue('FontName'));
 if(!what || what == "FontName")
 {
 	eval('element = document.all.'+what+'_'+active_rich.name+';');
	
 	set_style("FontName", element.value);
	}

  if(!what || what == "FontSize")            set_style("FontSize", active_rich.document.queryCommandValue('FontSize'));

  if(!what || what == "ClassName")           set_style("ClassName", get_class());



  if(!what || what == "Bold")                set_state("Bold", active_rich.document.queryCommandValue('Bold'));

  if(!what || what == "Italic")              set_state("Italic", active_rich.document.queryCommandValue('Italic'));

  if(!what || what == "Underline")           set_state("Underline", active_rich.document.queryCommandValue('Underline'));

  if(!what || what == "JustifyLeft")         set_state("JustifyLeft", active_rich.document.queryCommandValue('JustifyLeft'));

  if(!what || what == "JustifyCenter")       set_state("JustifyCenter", active_rich.document.queryCommandValue('JustifyCenter'));

  if(!what || what == "JustifyRight")        set_state("JustifyRight", active_rich.document.queryCommandValue('JustifyRight'));

  if(!what || what == "JustifyFull")         set_state("JustifyFull", active_rich.document.queryCommandValue('JustifyFull'));

  if(!what || what == "InsertOrderedList")   set_state("InsertOrderedList", active_rich.document.queryCommandValue('InsertOrderedList'));

  if(!what || what == "InsertUnorderedList") set_state("InsertUnorderedList", active_rich.document.queryCommandValue('InsertUnorderedList'));



}



//changes state of button 'what' to value

function set_state(what, value){



  //object to change

  eval('element = document.all.'+what+'_'+active_rich.name+';');



  if(value){ //pressed

    element.style.borderTop = '1px solid buttonshadow';

    element.style.borderLeft = '1px solid buttonshadow';

    element.style.borderBottom = '1px solid buttonhighlight';

    element.style.borderRight = '1px solid buttonhighlight';

  }else{    //released

    element.style.borderTop = '1px solid buttonface';

    element.style.borderLeft = '1px solid buttonface';

    element.style.borderBottom = '1px solid buttonface';

    element.style.borderRight = '1px solid buttonface';

  }



}



//changes state of select element 'what' in value

function set_style(what, value){



  //object to change

  eval('element = document.all.'+what+'_'+active_rich.name+';');

  element.value = value;

}



//show dialog window to pick color

function pick_color(){

//  return showModalDialog(rich_path+"pick_color.php?4", "",

//                         "font-family:Times New Roman; font-size:12; dialogWidth:400px; dialogHeight:550px; status:no; scroll:no; help:no");

  return showModalDialog(rich_path+"pick_color.php?222222222", "",

                         "font-family:Times New Roman; font-size:12; dialogWidth:500px; dialogHeight:200px; status:no; scroll:no; help:no");

}



//show dialog window to create/edit objects (table, image)

function show_dialog(action, object){



  eval('mode = '+active_rich.name+'_rich_mode;'); //current mode



  //in source mode toolbar buttons do not work

  if(!mode) return;



  active_rich.focus(); //set focus on active editor



  //check, if any control element is active (i.e. image or table)

  sel = active_rich.document.selection;

  r = sel.createRange();

  if(sel.type == 'Control') is_control = true;

    else is_control = false;



  switch(action){

    case "CreateTable": //create table

      if(is_control) break;



      parameters = show_table_dialog("");



      if(parameters) create_table(parameters);

      break;



    case "EditTable": //edit table



      attrib = get_table(object); //get values of table attributes

      parameters = show_table_dialog(attrib);



      if(parameters) edit_object(object, parameters);

      break;



    case "EditCell": //edit table cell



      attrib = get_cell(object); //get values of table cell attributes

      parameters = showModalDialog(rich_path+"dialog_cell.php?eeeeeeeeee", attrib,

                                   "font-family:Times New Roman; font-size:12; dialogWidth:310px; dialogHeight:220px; status:no; scroll:no; help:no");

      if(parameters) edit_object(object, parameters);

      break;



    case "CreateImage": //create image

      if(is_control) break;



      parameters = show_image_dialog("");



      if(parameters) create_image(parameters);

      break;



    case "EditImage": //edit image



      attrib = get_image(object); //get values of image attributes

      parameters = show_image_dialog(attrib);



      if(parameters) edit_object(object, parameters);

      break;



    case "CreateLink": //create reference

      if(is_control) break;

      if(sel.type != 'Text') break; //no selected text



      if(r.parentElement){ //check, if there is a reference inside text

        link = get_previous_object(r.parentElement(),'A');

      }else link = null;



      if(link){ //it is a reference yet - edit it

        show_dialog("EditLink", link);

        break;

      }



      parameters = show_link_dialog("");



      if(parameters) create_link(parameters);

      break;

	  

    case "CreateTarget": //create a target

      if(is_control) break;

      //if(sel.type != 'Text') break; //no selected text



      if(sel.type=='Text' && r.parentElement){ //check, if there is a reference inside text

 						link = get_previous_object(r.parentElement(),'A');

      }else link = null;



      if(link){ //it is a reference yet - edit it

        show_dialog("EditTarget", link);

        break;

      }



      parameters = show_target_dialog("");



      if(parameters) 

      {create_target(parameters);}

      break;

	  

    case "EditLink": //edit reference



      attrib = get_link(object); //get values of image attributes



      parameters = show_link_dialog(attrib);



      if(parameters) edit_object(object, parameters);

      break;

    case "EditTarget": //edit reference



      attrib = get_target(object); //get values of image attributes

      parameters = show_target_dialog(attrib);



      if(parameters) edit_object(object, parameters);

      break;

    default:

      break;

  }



}



//creates table using parameters array params

function create_table(params){



  table = document.createElement("TABLE"); //create object - tag table



  //set values of given attributes

  for(i=0;i<params.length;i++){

    param = params[i].match(/([^=]*)=(.*)/);

    if(param[1] != 'rows' && param[1] != 'columns' &&

       param[1] != 'width' && param[1] != 'height'){

      if(param[2]) table.setAttribute(param[1], param[2]);

    }else{

      if(param[1] == 'rows') rows = param[2];

      if(param[1] == 'columns') columns = param[2];

      if(param[1] == 'width') width = param[2];

      if(param[1] == 'height') height = param[2];

    }

  }



  if( !(rows > 0 && columns > 0) ) return;



  if(width) table.style.width = width;

  if(height) table.style.height = height;



  table.removeAttribute('width');

  table.removeAttribute('height');



  //create necessary quantity of rows and columns

  for(i=0;i<rows;i++){

    row = document.createElement("TR");

    for(j=0;j<columns;j++){

      cell = document.createElement("TD");

      row.appendChild(cell);

    }

    table.appendChild(row);

  }



  selection = active_rich.document.selection;

  range = selection.createRange();

  range.pasteHTML(table.outerHTML);



}



//search among parents an object with tag tag_name

function get_previous_object(obj,tag_name) {



  if(obj){



    //to prevent search outside editor

    if(obj.className == "editor") return null;



    if(obj.tagName != tag_name){

      obj = get_previous_object(obj.parentNode, tag_name);

    }

  }

  return(obj);

}



//get values of attributes of table 'table'

function get_table(table){

  var attrib;

  attrib = new Array();



  attrib['rows'] = table.rows.length;

  attrib['columns'] = table.rows(0).cells.length;

  attrib['width'] = table.style.width;

  attrib['height'] = table.style.height;

  attrib['border'] = table.getAttribute('border');

  attrib['align'] = table.getAttribute('align');

  attrib['cellSpacing'] = table.getAttribute('cellspacing');

  attrib['cellPadding'] = table.getAttribute('cellpadding');

  attrib['background'] = table.getAttribute('background');

  attrib['bgColor'] = table.getAttribute('bgColor');

  attrib['borderColor'] = table.getAttribute('borderColor');

  attrib['borderColorLight'] = table.getAttribute('borderColorLight');

  attrib['borderColorDark'] = table.getAttribute('borderColorDark');

  return attrib;

}



//changes attributes of an object

function edit_object(object, params){



  //set values of given attributes

  for(i=0;i<params.length;i++){

    param = params[i].match(/([^=]*)=(.*)/);

    if(param[1] != 'rows' && param[1] != 'columns'){



      if((object.tagName == "TABLE" || object.tagName == "IMG") &&

         (param[1]=='width' || param[1]=='height')){

        //set width and height for image in style

        if(param[2]){

          eval("object.style."+param[1]+" = param[2];");

        }

      }else{

        if(param[2]) object.setAttribute(param[1], param[2]);

          else object.removeAttribute(param[1]);

				if(param[2] && param[1]=='href')

        	object.href=""+object.href+"";

        //if href attribute is empty, delete image

        if(param[1] == 'href' && !param[2]){

          object.removeNode(false);

          return;

        }

      }



    }

  }



}



//gets values of table cell 'object'

function get_cell(object){

  var attrib;

  attrib = new Array();



  attrib['width'] = object.getAttribute('width');

  attrib['height'] = object.getAttribute('height');

  attrib['vAlign'] = object.getAttribute('vAlign');

  attrib['bgColor'] = object.getAttribute('bgColor');

  return attrib;

}





//prepare parameters of dialog window to return in parent window

function get_parameters(){

  parameters = new Array();



  //array of flags for radio elements, to prevent multiple

  //writing information about chosen item of a radio item

  radio_done = new Array();



  j=0;

  for(i=0;i<form_name.length;i++){

    name = form_name[i].name;



    if(name){

      switch(form_name[i].type){

        case 'text':

        case 'select-one':

          parameters[j] = name+"="+(eval("form_name."+name+".value"));

          j++;

          break;

        case 'checkbox':

          parameters[j] = name+"=";

          is_checked = eval("form_name."+name+".checked");



          if(name == 'block_announce'){

            parameters[j] += is_checked;

          }else{

            if(is_checked){

              if(name == "background"){

                parameters[j] += (eval("form_name."+name+"_image.src"));

              }else{

                parameters[j] += (eval(name+"_table.bgColor"));

              }

            }

          }

          j++;

          break;

        case 'radio':

          if(!radio_done[name]){

            object = eval("form_name."+name);

  

            for(k=0;k<object.length;k++){

              if(object[k].checked){

                parameters[j] = name+"="+object[k].value;

                j++;

                break;

              }

            }

            radio_done[name] = true;

          }

          break;

        default:

          break;

      }

    }



  }



  return parameters;

}



//set color of the current element

function set_color(){

  if(window.event.srcElement.name){

    name = window.event.srcElement.name;

  }else{

    obj = get_previous_object(window.event.srcElement, "TABLE");

    name = obj.id;

    name = (name.split('_'))[0];

  }



  color = pick_color();

  if(color){

    eval(name+"_table.bgColor = '"+color+"';");

    eval("form_name."+name+".checked = true;");

  }

}



//choose image for table background

function set_image(){



  name = window.event.srcElement.name;

  if(window.event.srcElement.tagName == 'IMG'){

    name = (name.split('_'))[0];

  }else{

    name = window.event.srcElement.name;

  }



  eval("old_src = form_name."+name+"_image.src;");

  if(old_src.search("images/space.gif") < 0){

    old_params = new Array();

    old_params['src'] = old_src;

  }else old_params = "";



  params = show_image_dialog(old_params, "dialog");



  if(params){

    src = '';

    width = 0;

    height = 0;



    for(i=0;i<params.length;i++){

      param = params[i].match(/([^=]*)=(.*)/);

      switch(param[1]){

        case 'width':

        case 'height':

          if(param[2]) eval(param[1]+"="+param[2]+";");

          break;

        case 'src':

          eval(param[1]+"='"+param[2]+"';");

          break;

        default:

          break;

      }

  

    }



    if(src && width && height){

      set_preview_table_image(eval("form_name."+name+"_image"),

                              src, width, height);

      eval("form_name."+name+".checked = true;");

    }

  }

}



//initialize dialog window according to received parameters, if available

function init_dialog(form){

  //window.alert("init dialog");

  if(!window.dialogArguments) return false; //no parameters - creation mode



  //editing mode



  parameters = window.dialogArguments;



  for(i=0;i<form_name.length;i++){

    name = form_name[i].name;



    if(name){



      switch(form_name[i].type) {

        case 'text':

        case 'select-one':

          if(parameters[name]){



            eval("form_name."+name+".value = \""+parameters[name]+"\";");



            //make fields for setting numbers of rows and columns inactive

            if(name == "rows" || name == "columns"){

              eval("form_name."+name+".disabled=true;");

            }

          }

          break;

        case 'checkbox':

          if(parameters[name]){

            eval("form_name."+name+".checked = true;");

            if(name == "background"){ //load image for table background

              window.is_init = true;

              form_name.temp_image.src = parameters[name];

              //then parameters of preview image will be set

              //on parsing of event 'onload' for image 'temp_image'

            }else{

              eval(name+"_table.bgColor = '"+parameters[name]+"';");

            }

          }

          break;

        case 'radio':

          if(parameters[name]){

            eval("document.all."+name+"_"+parameters[name]+".checked=true;");

          }

          break;

        default:

          break;

      }

    }



  }



  return true; //editing mode



}



//inserts row into current table just after current row

function insert_row(){

  range = active_rich.document.selection.createRange();



  tr = get_previous_object(range.parentElement(),'TR');

  table = get_previous_object(tr,'TABLE');



  if(table != null){

    row = table.insertRow(tr.rowIndex+1); //create new row

    for(i=0;i<tr.childNodes.length;i++){ //fill the row with columns

      row.insertCell();

    }



  }



}



//deletes current row from current table

function delete_row(){

  range = active_rich.document.selection.createRange();



  tr = get_previous_object(range.parentElement(),'TR');

  table = get_previous_object(tr,'TABLE');



  if(table != null){

    if(table.rows.length <= 1){

      table.removeNode(true); //it is the last row - delete whole table

    }else{

      table.deleteRow(tr.rowIndex); //delete row

    }



  }



}



//insert column in current table just after current column

function insert_column(){

  range = active_rich.document.selection.createRange();



  td = get_previous_object(range.parentElement(),'TD');

  table = get_previous_object(td,'TABLE');



  if(table != null){

    //insert new cells in each row

    for(i=0;i<table.rows.length;i++){

      table.rows(i).insertCell(td.cellIndex+1);

    }

  }



}



//delete current column from current table

function delete_column(){

  range = active_rich.document.selection.createRange();



  td = get_previous_object(range.parentElement(),'TD');

  table = get_previous_object(td,'TABLE');



  if(table != null){



    //insert new cells in each row

    for(i=0;i<table.rows.length;i++){

      tr = table.rows(i);

      if(tr.childNodes.length<=1){

        //it is the last column in the row - delete table

        table.removeNode(true);

      }else{

        tr.deleteCell(td.cellIndex);

      }

    }



  }



}



//creates image using array of parameters 'params'

function create_image(params){



  image = document.createElement("IMG"); //create object - tag IMG



  //set values of the given attributes

  for(i=0;i<params.length;i++){

    param = params[i].match(/([^=]*)=(.*)/);



    if(param[1] != 'width' && param[1] != 'height'){

      if(param[2]) image.setAttribute(param[1], param[2]);

    }else{

      if(param[1] == 'width') width = param[2];

      if(param[1] == 'height') height = param[2];

    }



  }



  if(width) image.style.width = width;

  if(height) image.style.height = height;



  image.removeAttribute('width');

  image.removeAttribute('height');



  selection = active_rich.document.selection;

  range = selection.createRange();

  range.pasteHTML(image.outerHTML);



}



//get values of attributes of image 'image'

function get_image(image){

  var attrib;

  attrib = new Array();



  width = image.style.width;

  height = image.style.height;



  if(width) attrib['width'] = width;

  if(height) attrib['height'] = height;



  attrib['src'] = image.getAttribute('src');

  attrib['border'] = image.getAttribute('border');

  attrib['align'] = image.getAttribute('align');

  attrib['hspace'] = image.getAttribute('hspace');

  attrib['vspace'] = image.getAttribute('vspace');

  attrib['alt'] = image.getAttribute('alt');



  return attrib;

}



//make preview of the image chosen with size not exceeding 100x100

function set_preview_image(url, w, h){



  preview_size = 100;



  document.form_name.preview_image.width = 1;

  document.form_name.preview_image.height = 1;

  document.form_name.preview_image.src = url;



  w = parseInt(w);

  h = parseInt(h);



  if(!w || !h) return;



  if(w > h){ //ширина больше высоты

    document.form_name.preview_image.width = preview_size;

    document.form_name.preview_image.height = preview_size*h/w;

  }else{ //высота больше ширины

    document.form_name.preview_image.height = preview_size;

    document.form_name.preview_image.width = preview_size*w/h;

  }



}



//make preview of the image chosen for table backbround

//with size not exceeding 100x100

function set_preview_table_image(object, url, w, h){



  preview_size = 100;



  object.width = 1;

  object.height = 1;

  object.src = url;



  if(w > h){ //width > height

    object.width = preview_size;

    object.removeAttribute('height');

  }else{ //height > width

    object.height = preview_size;

    object.removeAttribute('width');

  }



  name = (object.name.split('_'))[0];

  eval("form_name."+name+".checked = true;");



}



//show dialog window to create/edit table

function show_table_dialog(attrib){

  return showModalDialog(rich_path+"dialog_table.php?files_path="+eval(active_rich.name+"_files_path")+"&files_url="+eval(active_rich.name+"_files_url")+"&77777777777777", attrib,

                               "font-family:Times New Roman; font-size:12; dialogWidth:330px; dialogHeight:520px; status:no; scroll:no; help:no");



}



//show dialog window to create/edit image

function show_image_dialog(attrib, name){

  if(!name) name = active_rich.name; //name of current editor

  return showModalDialog(rich_path+"dialog_image.php?files_path="+eval(name+"_files_path")+"&files_url="+eval(name+"_files_url")+"&777777", attrib,

                         "font-family:Times New Roman; font-size:12; dialogWidth:410px; dialogHeight:440px; status:no; scroll:no; help:no");



}



//show dialog window to create/edit reference

function show_link_dialog(attrib, name){

  if(!name) name = active_rich.name; //name of current editor

  if(!attrib)

  {

  	attrib = new Array();  	

  }

  attrib['anchors'] = active_rich.document.anchors;

  return showModalDialog(rich_path+"dialog_link.php?files_path="+eval(name+"_files_path")+"&files_url="+eval(name+"_files_url")+"&222", attrib,

                         "font-family:Times New Roman; font-size:12; dialogWidth:410px; dialogHeight:440px; status:no; scroll:no; help:no");



}

function show_target_dialog(attrib, name){

  if(!name) name = active_rich.name; //name of current editor

  //window.alert("showing target"+active_rich.document.anchors);



  return showModalDialog(rich_path+"dialog_target.php", attrib,

                         "font-family:Times New Roman; font-size:12; dialogWidth:410px; dialogHeight:440px; status:no; scroll:no; help:no");



}



//create reference using array of parameters 'params'

function create_link(params){



  link = document.createElement("A"); //create object - tag A



  //set values of the attributes given

  for(i=0;i<params.length;i++){

    param = params[i].match(/([^=]*)=(.*)/);



    if(param[1] == 'href' && !param[2]) return; //empty reference

      else if(param[2]) link.setAttribute(param[1], param[2]);



  }



  selection = active_rich.document.selection;

  range = selection.createRange();

  range.execCommand("UnLink");

  //range.execCommand("CreateLink",'',link.href);

  link.innerHTML = range.htmlText;

  //save normal href, and set a temporary idea for the link

  href = link.href;

  

  link.setAttribute('ID','lastlink');

  range.pasteHTML(link.outerHTML);

  //pastehtml screwsup the href so get the new element

	link = active_rich.document.getElementById('lastlink');  

	link.id='';

  //link.href = href;

  link.href = ""+href+"";

  

}



//create target reference using array of parameters 'params'

function create_target(params){





 //create object - tag A

  //set values of the attributes given

	var link;

  for(i=0;i<params.length;i++)

	{

    	//window.alert(params[i]);

   		param = params[i].match(/([^=]*)=(.*)/);

		 

     	if(param[1] == 'name' && !param[2]) return; //empty reference

      else

      {			

			   if(param[1]=='name')

				 {

				  link = document.createElement("A NAME="+param[2]);

				 }				 

			}





  }

  for(i=0;i<params.length;i++)

	{

 		param = params[i].match(/([^=]*)=(.*)/);

		if(param[2])

  					link.setAttribute(param[1], param[2]);

				 

	}





  

	

  selection = active_rich.document.selection;

  range = selection.createRange();



  range.execCommand("UnLink");

  link.innerHTML = range.htmlText;

  

  range.pasteHTML(link.outerHTML);



}





//gets values of attributes of reference 'link'

function get_link(link){

  var attrib;

  attrib = new Array();



  attrib['target'] = link.getAttribute('target');

  attrib['href'] = link.getAttribute('href');



  return attrib;

}



function get_target(link){

  var attrib;

  attrib = new Array();



  attrib['target'] = link.getAttribute('target');

  attrib['name'] = link.getAttribute('name');



  return attrib;

}



//saves text of all editors in textarea objects (for form submit)

function save_in_textarea_all(){



  for(i=0;i<document.all.length;i++){

    if(document.all(i).className == 'editor'){

      eval('mode = '+document.all(i).name+'_rich_mode;'); //current mode

      eval('page_mode = '+document.all(i).name+'_rich_page_mode;'); //current page mode

      //current border mode

      eval('border_mode = '+document.all(i).name+'_rich_border_mode;');



      name = document.all(i).name;

      eval("active_rich = "+document.all(i).id+";");

      if(!mode){ //jump in wysiwyg mode

        change_mode();

      }



      if(!page_mode){

        eval("document.all['"+name+"_area_id'].value="+name+"_id.document.body.innerHTML");

      }else{

        eval("document.all['"+name+"_area_id'].value="+name+"_id.document.documentElement.outerHTML");

      }



      if(border_mode) switch_borders(true); //turn borders off



    }

  }

}



//find all document stylesheet rules and add their names to select object

function set_stylesheet_rules(){

//asdf.document.body.innerText = asdf.document.body.outerHTML;

  var rule_values = new Array();

  var rule_found = false;



  sheets = active_rich.document.styleSheets;

  sheets_num = sheets.length;



  //there are some stylesheets

  if(sheets_num > 0){



    for(i=0;i<sheets_num;i++){

      rules = sheets(i).rules;

      rules_num = rules.length;



      for(j=0;j<rules_num;j++){

        rule_value = rules(j).selectorText

        //in rules of the type 'td.toolbar span.delimiter{...}'

        //ignore all chars after space char

        rule_value = (rule_value.split(' '))[0];



        //rules MUST have '.' in their names, as it is user defined rules

        if(rule_value.indexOf(".") >= 0){



          //there is ':' char found in the rule name

          if(rule_value.indexOf(":") >= 0){



            //there are both '.' and ':' chars in the rule name

            rule_value = rule_value.substring(rule_value.indexOf(".")+1,rule_value.indexOf(":"));



          }else{



            //name begins with '.'

            if(rule_value.indexOf(".") == 0){

              rule_value = rule_value.substring(1,rule_value.length);

            }else{

              //name do not begins with '.'

              if(rule_value.indexOf(".") > 0){

                rule_value = rule_value.substring(rule_value.indexOf(".")+1,rule_value.length);

              }

            }



          }



          //prevent adding the the same rule names

          for(k=0;k<rule_values.length;k++){

            if(rule_value == rule_values[k]){

              rule_found = true;

              break;

            }

          }



          //new rule

          if(rule_found != true){

            rule_values[rule_values.length] = rule_value;

          }

          rule_found = false;



        }



      }



    }



    //select object

    eval('rules_select = document.all.ClassName_'+active_rich.name+';');



    //delete old classes from the select object, except first

    while( rules_select.options[1] != null){

      rules_select.options[1].removeNode(true);

    }



    for(i=0;i<rule_values.length;i++){

      if(rule_values[i] != ''){

        option = document.createElement("option");

        option.value = rule_values[i];

        option.text = rule_values[i];

        rules_select.add(option);

      }

    } 



  }



}



//set class attribute for current text or control element

function set_class(rule_value){

var sel = active_rich.document.selection;

var range = sel.createRange();

var is_set;

var object;



  if(sel.type == "Control"){

    object = range.commonParentElement();

  }else{



    if(range.parentElement != null){



      parentTagName = range.parentElement().tagName.toUpperCase();



      if(range.htmlText == ""){

        object = range.parentElement();

      }else{

        if(parentTagName=="SPAN" || parentTagName=="A"){

  

          object = range.parentElement();

  

        }else{

          if(rule_value != ""){

            try{

              range.pasteHTML("<span class=" + rule_value + ">" + range.htmlText + "</span>");

            }catch(error){

              //do nothing on error, just prevent error message to user

            }

          }

          is_set = true

        }

  

      }

  

      if(rule_value == "" && parentTagName == "SPAN"){

        object.removeNode(false);

        is_set = true;

      }



    }



  }



  if(object != null && is_set != true){

    object.className = rule_value;

  }



}



//get class attribute for current text cursor position

function get_class(){

var sel = active_rich.document.selection;

var range = sel.createRange();

var object = null;



  if(sel.type == "Control"){

    object = range.commonParentElement();

  }else{

    object = range.parentElement();

  }



  if(object != null){

    return object.className;

  }

  return "";

}



function clean_code(code) {    

  // get rid of silly space tags

  code = code.replace(/&nbsp;/gi, "")

  // gets rid of all xml stuff... <xml>,<\xml>,<?xml> or <\?xml>

  code = code.replace(/<\\?\??xml[^>]*>/gi, "")

  // get rid of ugly colon tags <a:b> or </a:b>

  code = code.replace(/<\/?\w+:[^>]*>/gi, "")

  // removes all empty <p> tags

  code = code.replace(/<p([^>])*>(&nbsp;)*\s*<\/p>/gi,"")

  // removes all span tags

  code = code.replace(/<span[^>]*>([^<]*)<\/span>/gi,"$1")

  // removes all Class attributes on a tag eg. '<p class=asdasd>xxx</p>' returns '<p>xxx</p>'

  code = code.replace(/<([\w]+) class=([^ |>]*)([^>]*)/gi, "<$1$3")

  // removes all style attributes eg. '<tag style="asd asdfa aasdfasdf" something else>' returns '<tag something else>'

  code = code.replace(/<([^>]+) style="([^"]*)"([^>]*)/gi, "<$1$3")   



  return code

}



function paste_word(){

var sel = active_rich.document.selection.createRange();



  if(sel.parentElement){

    //paste in temporary element

    temp_div = document.all.rich_temp_div;

    temp_div.focus();

    temp_div.document.execCommand("SelectAll");

    temp_div.document.execCommand("Paste");



    sel.pasteHTML(clean_code(temp_div.innerHTML));

  }



  active_rich.focus(); //set focus on active editor



}



//show/hide borders of invisible objects

function set_borders(border_mode){

var tables = active_rich.document.body.getElementsByTagName("TABLE");

eval('page_mode = '+active_rich.name+'_rich_page_mode;'); //current page mode



  for(i=0;i<tables.length;i++){



    if(border_mode){

      tables[i].style.border = '1px dashed #CCCCCC';

    }else{

      width = tables[i].style.width;

      height = tables[i].style.height;



      tables[i].removeAttribute("style")



      if(width) tables[i].style.width = width;

      if(height) tables[i].style.height = height;

    }



    rows = tables[i].rows;

    for(j=0;j<rows.length;j++){

      cells = rows[j].cells;

      for(k=0;k<cells.length;k++){

        if(border_mode){

          cells[k].style.border = '1px dashed #CCCCCC';

        }else{

          cells[k].removeAttribute("style")

        }

      }

    }



  }



  if(!page_mode){

    active_rich.document.body.innerHTML = '<body>'+active_rich.document.body.innerHTML+'</body>';

  }else{

    active_rich.document.body.innerHTML = active_rich.document.body.innerHTML;

  }

}



//change border mode

function switch_borders(change){



  //current border mode

  eval('border_mode = '+active_rich.name+'_rich_border_mode;');



  if(change){//change border visibility

    border_mode = border_mode==true?false:true;

    set_state('SwitchBorders', border_mode);

    eval(active_rich.name+'_rich_border_mode = border_mode;');

  }



  set_borders(border_mode);



}



//error message handler

function no_error(){

  return true;

}
