/*
 * WYMeditor : what you see is What You Mean web-based editor
 * Copyright (c) 2005 - 2009 Jean-Francois Hovinne, http://www.wymeditor.org/
 * Dual licensed under the MIT (MIT-license.txt)
 * and GPL (GPL-license.txt) licenses.
 *
 * For further information visit:
 *        http://www.wymeditor.org/
 *
 * File Name:
 *        jquery.wymeditor.hovertools.js
 *        hovertools plugin for WYMeditor
 *
 * File Authors:
 *        Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
 */

jQuery.extend(WYMeditor, {
  SELECTED_TEXT       : "{Wym_Selected_Text}"
});

//Extend WYMeditor
WYMeditor.editor.prototype.dialog = function(sType) {
  var sBodyHtml = "";
  var wym = this;
  var submitDialog = function(e) {};
  var closeDialog = function(e) {
    e.preventDefault();
    $.facebox.close();
  };

  switch(sType) {
    case(WYMeditor.DIALOG_LINK):
      sBodyHtml = wym._options.dialogLinkHtml;
      submitDialog = function(e) {
        var title = jQuery(wym._options.titleSelector).val();
        var sUrl = jQuery(wym._options.hrefSelector).val();
        if(sUrl.length > 0) {
          var sStamp = wym.uniqueStamp();
          if(document.selection) window.temporaryIESelection.select(); //IE workaround
          wym._exec(WYMeditor.CREATE_LINK, sStamp);

          jQuery("a[href=" + sStamp + "]", wym._doc.body)
              .attr(WYMeditor.HREF, sUrl)
              .attr(WYMeditor.TITLE, title);
        }
        
        closeDialog(e);
      };
    break;
  }
  var selectedText = '';
  if(document.selection) {//IE
    selectedText = wym._iframe.contentWindow.document.selection.createRange().text;
  } else {
    selectedText = wym._iframe.contentWindow.getSelection().toString();
  }

  //construct the dialog
  var dialogHtml = wym._options.dialogHtml;
  dialogHtml = WYMeditor.Helper.replaceAll(dialogHtml, WYMeditor.DIALOG_BODY, sBodyHtml);
  dialogHtml = WYMeditor.Helper.replaceAll(dialogHtml, WYMeditor.SELECTED_TEXT, selectedText);
  dialogHtml = wym.replaceStrings(dialogHtml);

  $(document).bind('reveal.facebox', function() {
    $('#facebox input.wym_submit').click(submitDialog);
    $('#facebox .wym_cancel').click(closeDialog);
    $('#facebox input.wym_title').focus();
  });

  //IE loses the selection when an input field in the same document gets focused
  //so we have to save it and re-select it in submitDialog()
  if(document.selection) window.temporaryIESelection = wym._iframe.contentWindow.document.selection.createRange();

  $.facebox(dialogHtml);
};
