// -------------------------------------------------------------------
// Project Yonks Content Management System
// Copyright (C) 2007 by PCMED.
// http://www.pcmed.org/
// -------------------------------------------------------------------
// LICENSE
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License (GPL)
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// To read the license please visit http://www.gnu.org/copyleft/gpl.html
// -------------------------------------------------------------------



jQuery.ToolbarItems = {
  options : {
    imagesLocation  : 'js/yonks_wysiwyg/images/',
    imagesExtension : '.gif',
    controlSelector : [
      'bold', 'italic', 'underline', 'vide',
      'insertorderedlist', 'insertunorderedlist', 'vide',
      'justifyleft', 'justifycenter', 'justifyright', 'vide',
      'createlink', 'vide'
    ],
    formatFont : [
      'Arial, Helvetica, sans-serif', 'Courier New, Courier, mono', 'Times New Roman, Times, serif', 'Verdana, Arial, Helvetica, sans-serif'
    ],
    formatSelector : [
      'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
    ]
  }
};
var options = jQuery.ToolbarItems.options;

$.fn.ToolbarItems = function () {
  var base = options.imagesLocation;
  var ext = options.imagesExtension;
  var ToolbarContent = "";
  var ToolbarFont = "";
  var ToolbarFormat = "";
  ToolbarFont += "<select id='FontName' onchange='$.fn.editorSelect(this.id);'>";
  ToolbarFont += "<option value=''>Font</option>";
  for (var i = 0; i < options.formatFont.length; i++) {
    var action = options.formatFont[i];
    var label = options.formatFont[i];
    ToolbarFont += "<option value='" + action+ "'>" + label + "</option>";
  }
  ToolbarFont += "</select>";
  ToolbarContent += ToolbarFont;

  ToolbarFormat += "<select id='formatblock' onchange='$.fn.editorSelect(this.id);'>";
  ToolbarFormat += "<option value=''>Format</option>";
  for (var i = 0; i < options.formatSelector.length; i++) {
    var action = options.formatSelector[i];
    var label = options.formatSelector[i];
    ToolbarFormat += "<option value='<" + action+ ">'>" + label + " Heading</option>";
  }
  ToolbarFormat += "</select>";
  ToolbarContent += ToolbarFormat;
  

  for (var i = 0; i < options.controlSelector.length; i++) {
    var action = options.controlSelector[i];
    var label = options.controlSelector[i];
    if ( label != 'vide' ) {
        ToolbarContent += "&nbsp;<img alt='"+ label + "' class='img_toolbar' id='"+ action + "' src='"+ base + label + ext +"' height='24' width='25' />";
    } else {
        ToolbarContent += "&nbsp;";
    }
  };
  return ToolbarContent;
};

var design, hdn, on, win;

$.fn.getIFrameDocument = function(frm) {
  if (document.getElementById(frm).contentDocument){
    on = "on";
    design = document.getElementById(frm).contentDocument;
    win = document.getElementById(frm).contentWindow;
  } else { // IE
    on = "On";
    design = frames[frm].document;
    win = frames[frm];
  }
  return { design:design, on:on, win:win };
};

$.fn.editorCmd = function(cmd, opt, win) {
  if ( cmd == "createlink" ) {
    opt = prompt("Enter a URL:", "http://");
    try { win.document.execCommand("Unlink", false, null); } catch( E ) {}
  }
  try {
    win.focus();
    if ( cmd == "bold" || cmd == "italic" || cmd == "underline") {
      if ( $.browser.msie ) {
        win.document.execCommand( cmd, false, opt );
      } else {
        win.document.execCommand("useCSS", false, 0);
        win.document.execCommand( cmd, false, opt );
      }
    } else {
      win.document.execCommand( cmd, false, opt );
    }
    win.focus();
  } catch (E) { } // No alert {alert(E);}
};

$.fn.editorSelect = function(selectname) {
  var select_idx = document.getElementById(selectname).selectedIndex;
  if (select_idx != 0) {
    var selec_value = document.getElementById(selectname).options[select_idx].value;
    $.fn.editorCmd(selectname, selec_value, win);
    document.getElementById(selectname).selectedIndex = 0;
  }
};

$.fn.editorSubmit = function(frm, hdn, win) {
  if (hdn.value == null) hdn.value = "";
  if (document.all) {
    hdn.value = frames[frm].document.body.innerHTML;
  } else {
    hdn.value = win.document.body.innerHTML;
  }
  hdn.value = $.fn.SaveXhtml(hdn.value);
  if ((stripHTML(hdn.value) == "") || (escape(hdn.value) == "%3Cbr%3E%0D%0A%0D%0A%0D%0A")) hdn.value = "";
};

$.fn.LoadXhtml = function(TidyHdn) { // Function à améliorer par ajout d'autres Balises.
  var avant = new Array('<strong>', '</strong>');
  var apres = new Array('<b>', '</b>');
  for (var i = 0; i < apres.length; i++) {
    reg = new RegExp(avant[i],"ig")
    TidyHdn = TidyHdn.replace(reg, apres[i]);
  }
  return TidyHdn;
};

$.fn.SaveXhtml = function(TidyHdn) { // Function à améliorer par ajout d'autres Balises.
  var avant = new Array('<STRONG>', '</STRONG>', '<b>', '</b>', '<br>', '<br/>', '_moz_dirty=""');
  var apres = new Array('<strong>', '</strong>', '<strong>', '</strong>', '<br />', '<br />', '');
  for (var i = 0; i < apres.length; i++) {
    reg = new RegExp(avant[i],"ig")
    TidyHdn = TidyHdn.replace(reg, apres[i]);
  }
  return TidyHdn;
};



function editorCreate( forme, frm, height, xheight ) {
  if ( $.browser.mozilla || $.browser.msie || $.browser.opera ) { // Test Navigateur Mozilla, Msie ou Opera alors OK.
  
    var width = $('#web' + frm).width();    
    
    var ToolbarContent = $.fn.ToolbarItems();
    var yheight = height-xheight;
    var ywidthi = width-18;
    var ywidth = width+2;
    $('#' + forme).find('#web' + frm).hide(); // Find les Inputs frm. Si JavaScript Ok alors Hide Input TextArea.
    $('#web' + frm).before('<div class="Toolbar_Class" style="width:' + ywidth + 'px">' + ToolbarContent + '</div>');
    $('#web' + frm).before('<div class="iframe_over" style="height:' + yheight + 'px; overflow-x: hidden; overflow-y: visible; width:' + ywidth + 'px"><iframe id="' + frm + '" name="' + frm + '" height="1000px" width="' + ywidthi + 'px"></iframe></div>');
    $('#' + forme).getIFrameDocument(frm);
    
    $("#" + frm).css('background-color', '#CCCCCC').css('border', '0').css('color', '#000000');
    $(".Toolbar_Class").css('background', 'transparent url('  + options.imagesLocation + '/bg_toolbar.jpg) repeat-x left').css('padding-top', '3px').css('position', 'relative');
    
    hdn = document.getElementById('web' + frm); // Id Input Hidden
    hdn.value = $.fn.LoadXhtml(hdn.value);
    var html = hdn.value; // Input Hidden Content Value
    if ( ! document.all ) enableDesign();
    win.document.open();
    win.document.write(
      "<html id='" + frm + "'>" +
      "<head><link href='frame.css' media='screen' rel='stylesheet' type='text/css' /></head>" +
      "<body>" + html + "</body>" +
      "</html>"
    );
    win.document.close();
    if ( document.all ) enableDesign();

    $(".img_toolbar").hover(function() {
      $(this).css({border:'1px outset #000000',cursor:'help'});
      },function() {
        $(this).css({border:'1px solid #D3D3D3',cursor:'help'});
    });

    $(".img_toolbar").click(function() {
      $('img').editorCmd(this.id, null, win);
    });
    
    $(".img_toolbar").css('border', '1px solid #D3D3D3').css('cursor', 'help').css('overflow', 'hidden');

    $('#' + forme).submit(function(){
       $.fn.editorSubmit(frm, hdn, win);
    });

    $('#formatblock').css('font-size', '10px').css('cursor', 'help').css('height', '20px').css('position', 'absolute').css('top', '5px').css('right', '2px').css('width', '60px');
    $('#FontName').css('font-size', '10px').css('cursor', 'help').css('height', '20px').css('position', 'absolute').css('top', '5px').css('right', '60px').css('width', '60px');

  }
};

function enableDesign() {
  try { design.designMode = on; } catch ( E ) {
    setTimeout("enableDesign();", 10);
  }
}
function stripHTML(oldString) {
 return oldString.replace("&nbsp;", " ").replace(/(<([^>]+)>)/ig,"")
   .replace(/\r\n/g," ").replace(/\n/g," ").replace(/\r/g," ")
   .replace(/^\s+/g,'').replace(/\s+$/g,'').replace(/  /g,' ');
}
