/**
 * FKCHelper.js
 *
 * Common functions that can be used in dealing with FCK editors
 *
 * $Revision: 1.2 $
 * $Date: 2009/08/11 19:11:22 $
 * Last edited by: $Author: jauldrid $
 */

var FCKHelper = {

  validateEditorValue : function( sInstanceName, oValidationRE )
  {
    var retval = true;
    if(( typeof FCKeditorAPI == 'object' ) &&
       ( typeof FCKeditorAPI.GetInstance == 'function' ))
    {
      var oEditor = FCKeditorAPI.GetInstance( sInstanceName );
      if( typeof oEditor != 'undefined' )
      {
        var sFieldValue = oEditor.GetHTML();
        var oRE         = oValidationRE || /^\s*<p\s*>(?:<br\s*\/?>|\s|&nbsp;)*<\/p>\s*$|^\s*(?:<br\s*\/?>|\s|&nbsp;)+\s*$/gim;
        if(( sFieldValue == '' ) ||
           ( oRE.test( sFieldValue )))
        {
          retval = false;
        }
        else
        {
          var field = oEditor.LinkedField;
          if( typeof field != 'undefined' )
          {
            field.value = sFieldValue;
          }
        }
      }
    }

    return retval;
  },

  FCKCleanup : function( sFormId )
  {
    var aIframe = [];

    /**
     * Need to do this in those cases where the form does not have
     * an id and what was passed in was an html element.
     */
    if( typeof sFormId === 'string' )
    {
      aIframe = $('#'+sFormId).find('iframe');
    }
    else if( typeof sFormId === 'object' )
    {
      if(( typeof sFormId.tagName !== 'undefined' ) &&
         ( sFormId.tagName.toLowerCase() == 'form' ))
      {
        aIframe = $(sFormId).find('iframe');
      }
      else if(( typeof sFormId.parentNode !== 'undefined' ) &&
              ( sFormId.parentNode.tagName.toLowerCase() == 'form' ))
      {
        aIframe = $(sFormId.parentNode).find('iframe');
      }
    }

    if( aIframe.length > 0 )
    {
      var iLength = aIframe.length;
      for( var x = 0; x < iLength; x++ )
      {
        try
        {
          var oIframe = aIframe[x];
          oIframe.parentNode.removeChild( oIframe );
        }
        catch( e ) {}
      }
    }

    try
    {
      if( typeof FCKIECleanup_Cleanup !== 'undefined' )
      {
        FCKIECleanup_Cleanup();
      }

      /**
       * Now try to get the focus out of any hidden editable iframes
       * that are still hanging out.
       */
      if( $( 'textarea:first', document.getElementById( sFormId )).focus().blur().length === 0 )
      {
        if( $('input[type="text"]:first').focus().blur().length === 0 )
        {
          $('input:first').focus().blur();
        }
      }
      document.body.focus();
    }
    catch( e ) {}
  }
};
