/* utilities.js */
String.prototype.trim=function(){return this.replace(/^\s*|\s*$/g,"");}

/* webEffects.js */
cfactor = {};

/* richMediaManager.js */
/**
 * @namespace
 * The Rich Media Manager namespace implements an object to package all rich media
 * classes, methods and properties.
 */
var RMM = {};

/**
 * A collection of urls used for performing various rich media actions.
 * @static
 * @type AssociativeArray
 */
RMM.actionUrls = {};

/**
 * A collection containing all the window content URLs.
 * @static
 * @type AssociativeArray
 */
RMM.windowUrls = {};

/**
 * A collection containing all the windows used by the rich media manager (these
 * are implemented using dynamic content layers).
 * @static
 * @type AssociativeArray
 */
RMM.windows = {
  'rmmTag'                 : null,
  'rmmTags'                : null,
  'rmmText'                : null,
  'rmmTextarea'            : null,
  'rmmRichText'            : null,
  'rmmRating'              : null,
  'rmmConfirm'             : null,
  'rmmAlert'               : null,
  'rmmLOV'                 : null,
  'rmmLogin'               : null,
  'rmmUpload'              : null,
  'rmmComPrivs'            : null,
  'rmmDocument'            : null,
  'rmmAddBookmark'         : null,
  'resourceManageFolder'   : null,
  'resourceMove'           : null,
  'rmmPrivileges'          : null,
  'rmmPictureViewer'       : null,
  'rmmInappropriate'       : null,
  'rmmCaptureInformation'  : null,
  'photoAlbumManageItem'   : null,
  'photoAlbumUploadPhotos' : null
};

/**
 * Hides all rich media management windows.
 */
RMM.hideWindows = function(excludedWindows)
{
  // Don't perform any actions while we're uploading a file.
  if (RMM.uploading)
  {
    return;
  }

  if (typeof excludedWindows == 'undefined')
  {
    if (excludedWindows instanceof Array)
    {}
    else if (excludedWindows instanceof String)
    {
      excludedWindows = [excludedWindows];
    }
    else
    {
      excludedWindows = [];
    }
  }
  else
  {
    excludedWindows = [];
  }

  for (var name in RMM.dynamicContentLayers)
  {
    if (!excludedWindows.contains(name) && RMM.windows[name] != null)
    {
      RMM.windows[name].hide();
    }
  }
};

/**
 * The edit method sets up a rich media editor interface for the user to manage
 * rich text elements of a cfactor portal.
 * @param {String} mediaType               Specifies the type of rich media being edited.
 *                                         Options: BLOG, FORUM, PROFILE_ATTRIBUTE
 * @param {String} actionUrl               The url which will be used for posting
 *                                         edit changes to cfactor.
 * @param {String} subjectFieldLabel       Provides the label text to be inserted for
 *                                         display of the optional "subject" text field.
 *                                         in the user's media editor interface.
 * @param {String} windowTitle             Specifies the text string to set as the title of the
 *                                         rich media editor window.
 * @param {String} textSourceElementId     Specifies the dom element id for retrieval of html text
 *                                         to set as the editing string of the rich text editor.
 * @param {String} subjectFieldValue       Specifies the string to set as the value of the subject field.
 */
RMM.edit = function(mediaType, actionUrl, subjectFieldLabel, windowTitle, textSourceElementId, subjectFieldValue)
{
  var initialized = false;

  // Don't perform any actions while we're uploading a file.
  if (RMM.uploading)
  {
    return;
  }

  // Check if the user has a session first, and if not we need to capture their information.
  if (!RMM.hasSession)
  {
    RMM.captureInformation(informationCaptureUrl, 'Enter Your Information', 'You are required to enter your first name, last name, and email address before you can comment.', ['First Name', 'Last Name', 'Email Address'], ['firstName', 'lastName', 'emailAddress'], [RMM.getCookie('firstName'), RMM.getCookie('lastName'), RMM.getCookie('emailAddress')], RMM.sessionCreatedResponse, 'edit', [mediaType, actionUrl, subjectFieldLabel, windowTitle, textSourceElementId, subjectFieldValue]);
    return;
  }

  // If this function was called after window creation then the arguments would have been passed
  // as one big array.
  if (mediaType instanceof Array)
  {
    actionUrl = mediaType[1];
    subjectFieldLabel = mediaType[2];
    windowTitle = mediaType[3];
    textSourceElementId = mediaType[4];
    subjectFieldValue = mediaType[5];
    mediaType = mediaType[0];
  }
  // Force a recreate on the window everytime so that the iframes don't get messed up.
  else if (RMM.windows['rmmRichText'] != null)
  {
    initialized = true;
  }

  // Create the alert window first if neccessary.
  if (RMM.createWindow('rmmAlert', 'edit', [mediaType, actionUrl, subjectFieldLabel, windowTitle, textSourceElementId, subjectFieldValue]))
  {
    // If we had to create the window then the creating function will re-call this
    // function after the window is created and we have access to all it's objects.
    return;
  }
  else
  {
    document.getElementById('rmmAlert_closeIcon').style.visibility = 'hidden';
    document.getElementById('rmmAlert_ok').style.visibility = 'hidden';
    RMM.windows['rmmAlert'].setTitle('Please Wait');
    RMM.windows['rmmAlert'].setBodyText('Please wait while the rich text editor is loaded ...');
    RMM.windows['rmmAlert'].show();
  }

  // Create the window if neccessary.
  if (RMM.createWindow('rmmRichText', 'edit', [mediaType, actionUrl, subjectFieldLabel, windowTitle, textSourceElementId, subjectFieldValue]))
  {
    // If we had to create the window then the creating function will re-call this
    // function after the window is created and we have access to all it's objects.
    return;
  }
  else
  {
    RMM.windows['rmmAlert'].hide();
    document.getElementById('rmmAlert_closeIcon').style.visibility = 'visible';
    document.getElementById('rmmAlert_ok').style.visibility = 'visible';
  }

  // Create the confirm window because we might need it.
  RMM.createWindow('rmmConfirm');

  // Hide any open manager windows.
  RMM.hideWindows();

  // Show the rich text window close icon and frame area.
  document.getElementById('rmmRichText_closeIcon').style.visibility = 'visible';

  // Set the title on the upload window.
  RMM.windows['rmmRichText'].setTitle(windowTitle);

  // Grab a handle on the rich text editor value if a source element id was specified.
  if (textSourceElementId != '')
  {
    RMM.richText = document.getElementById(textSourceElementId).innerHTML;
  }
  else
  {
    RMM.richText = '&#160;';
  }

  // Set the text in edtiro.
  if (initialized)
  {
    RMM.initEditor();
  }

  // Setup the subject field.
  if (subjectFieldLabel == null)
  {
    document.getElementById('rmmRichText_subjectFieldArea').style.display = 'none';
    document.getElementById('rmmRichText_subjectField').style.display = 'none';
    document.getElementById('rmmRichText_subjectField').value = '';
  }
  else
  {
    document.getElementById('rmmRichText_subjectFieldArea').style.display = 'block';
    document.getElementById('rmmRichText_subjectField').style.display = 'block';
    document.getElementById('rmmRichText_subjectFieldLabel').innerHTML = subjectFieldLabel;
    if (mediaType == 'WIKI' && subjectFieldValue != '')
    {
      document.getElementById('rmmRichText_subjectField').value = document.getElementById(subjectFieldValue).innerHTML.trim();
    }
    else
    {
      document.getElementById('rmmRichText_subjectField').value = subjectFieldValue;
    }
    if (mediaType == 'PROFILE_ATTRIBUTE')
    {
      document.getElementById('rmmRichText_subjectField').setAttribute('disabled', 'disabled');
    }
    else
    {
      document.getElementById('rmmRichText_subjectField').removeAttribute('disabled');
    }
  }

  // Set the callback function on the editor window submit button.
  document.getElementById('rmmRichText_submit').callbackFunction = function(event)
  {
    // Don't perform any actions while we're uploading a file.
    if (RMM.uploading)
    {
      return;
    }

    // Set the parameters we need for submission
    objectText = RMM.richTextEditor.getHTML();
    objecTitle = document.getElementById('rmmRichText_subjectField').value;
    var params = {};
    switch (mediaType)
    {
      case 'BLOG':
        params.blogPostText = objectText;
        params.blogPostTitle = objecTitle;
        params.blogCommentText = objectText;
        RMM.crntActionUrl = RMM.actionUrls['blogEdit'];
        break;
      case 'FORUM':
        params.forumDescription = objectText;
        params.forumName = objecTitle;
        params.forumTopicSubject = objecTitle;
        params.forumPostText = objectText;
        RMM.crntActionUrl = RMM.actionUrls['forumEdit'];
        break;
      case 'WIKI':
        params.collaborationSource = objectText;
        params.collaborationName = objecTitle;
        RMM.crntActionUrl = RMM.actionUrls['wikiEdit'];
        break;
      case 'PROFILE_ATTRIBUTE':
        params.valueText = objectText;
        RMM.crntActionUrl = RMM.actionUrls['profileEdit'];
        break;
      case 'ENTITY_IMAGE_CAPTION':
        params.caption = objectText;
        RMM.crntActionUrl = RMM.actionUrls['profileEdit'];
        break;
    };
    if (mediaType == 'WIKI')
    {
      RMM.performAction(actionUrl, params, function()
      {
        RMM.windows['rmmAlert'].setBodyText('Your wiki topic has been successfully submitted.');
        RMM.windows['rmmAlert'].show();
        RMM.performActionResponse();
      });
    }
    else
    {
      RMM.performAction(actionUrl, params);
    }

    // Remove temp variables.
    params = null;
  };

  // Set the callback function on the editor window cancel button.
  document.getElementById('rmmRichText_cancel').callbackFunction = function(event)
  {
    // Hide the rich text and alert window.
    RMM.windows['rmmRichText'].hide();
    RMM.windows['rmmAlert'].hide();
  };

  // Show the editor window.
  RMM.windows['rmmRichText'].show();
};

/**
 * The remove method allows a user to delete any rich media content.
 * @param {String} mediaType            Specifies the type of rich media being deleted.
 *                                      Options: BLOG, BLOG_POST, FORUM
 * @param {String} actionUrl            The url to used to send the delete request to cfactor.
 * @param {String} windowTitle          The text string to set as title of the delete confirmation window.
 * @param {String} windowBody           The text string to set as the body (message) of the delete confirmation window.
 * @param {Function} responseFunction   The function to perform after the removal has been complete.
 */
RMM.remove = function(mediaType, actionUrl, windowTitle, windowBody, responseFunction)
{
  // Don't perform any actions while we're uploading a file.
  if (RMM.uploading)
  {
    return;
  }

  // If this function was called after window creation then the arguments would have been passed as one big array.
  if (mediaType instanceof Array)
  {
    actionUrl = mediaType[1];
    windowTitle = mediaType[2];
    windowBody = mediaType[3];
    responseFunction = mediaType[4];
    mediaType = mediaType[0];
  }

  // Create the window if neccessary.
  if (RMM.createWindow('rmmConfirm', 'remove', [mediaType, actionUrl, windowTitle, windowBody, responseFunction]))
  {
    // If we had to create the window then the creating function will re-call this
    // function after the window is created and we have access to all it's objects.
    return;
  }

  // Create the alert because we might need it.
  RMM.createWindow('rmmAlert');

  // Hide any open manager windows.
  RMM.hideWindows();

  // Set the title and body text on the confirm window.
  RMM.windows['rmmConfirm'].setTitle(windowTitle);
  RMM.windows['rmmConfirm'].setBodyText(windowBody);

  // Set the callback function on the confirm window buttons.
  document.getElementById('rmmConfirm_ok').callbackFunction = function(confirm)
  {
    if (confirm == true && !RMM.uploading)
    {
      switch (mediaType)
      {
        case 'BLOG':
        case 'BLOG_POST':
          RMM.crntActionUrl = RMM.actionUrls['blogDelete'];
          break;
        case 'BLOG_COMMENT':
          RMM.crntActionUrl = RMM.actionUrls['blogCommentDelete'];
          break;
        case 'WIKI':
          RMM.crntActionUrl = RMM.actionUrls['wikiDelete'];
        case 'FORUM':
        case 'FORUM_TOPIC':
          RMM.crntActionUrl = RMM.actionUrls['forumDelete'];
        case 'FORUM_TOPIC_REPLY':
          RMM.crntActionUrl = RMM.actionUrls['forumReplyDelete'];
          break;
      }

      // Send the request which will delete media item.
      RMM.performAction(actionUrl, null, responseFunction);

      RMM.windows['rmmConfirm'].hide();
    }
    else
    {
      RMM.windows['rmmConfirm'].hide();
    }
  }
  document.getElementById('rmmConfirm_cancel').callbackFunction = document.getElementById('rmmConfirm_ok').callbackFunction;
  RMM.windows['rmmConfirm'].show();
};

/**
 * The tag method sets up a user interface for providing a search engine tag on rich media content.
 * @param {String} actionUrl        Specifies the url to request for submitting a tag.
 * @param {String} windowTitle      Specifies a text string to display as the title text
 *                                  of the tagging window.
 * @param {String} objectTypeCode   Specifies the type of rich media object being tagged.
 */
RMM.tag = function(actionUrl, windowTitle, objectTypeCode)
{
  // Don't perform any actions while we're uploading a file.
  if (RMM.uploading)
  {
    return;
  }

  // If this function was called after window creation then the arguments would have been passed as one big array.
  if (actionUrl instanceof Array)
  {
    windowTitle = actionUrl[1];
    objectTypeCode = actionUrl[2];
    actionUrl = actionUrl[0];
  }

  // Create the window if neccessary.
  if (RMM.createWindow('rmmTag', 'tag', [actionUrl, windowTitle, objectTypeCode]))
  {
    // If we had to create the window then the creating function will re-call this
    // function after the window is created and we have access to all it's objects.
    return;
  }

  // Create the alert and confirm windows because we might need those.
  RMM.createWindow('rmmAlert');
  RMM.createWindow('rmmConfirm');

  // Hide any open manager windows.
  RMM.hideWindows();

  // Set the title and body text on the tag window.
  RMM.windows['rmmTag'].setTitle(windowTitle);

  // Set the value on the tag field in the tag window.
  document.getElementById('rmmTag_text').value = '';

  // Set the callback function on the rating window submit button.
  document.getElementById('rmmTag_submit').callbackFunction = function(event)
  {
    // Don't perform any actions while we're uploading a file.
    if (RMM.uploading)
    {
      return;
    }

    // Make sure the user entered a tag, and if not let them know about it.
    if (document.getElementById('rmmTag_text').value == '')
    {
      RMM.windows['rmmAlert'].setTitle(windowTitle);
      RMM.windows['rmmAlert'].setBodyText('Sorry, but you must enter a tag before you can continue.');
      RMM.windows['rmmAlert'].show();
    }
    else
    {
      // Set the parameters we need for submission
      var params = {
        tagText:              document.getElementById('rmmTag_text').value,
        searchObjectTypeCode: objectTypeCode
      };

      // Send the request which will add / edit this blog post or comment.
      RMM.crntActionUrl = null;
      RMM.performAction(actionUrl, params, function()
      {
        RMM.windows['rmmAlert'].setTitle(windowTitle);
        RMM.windows['rmmAlert'].setBodyText('Your tag has been successfully added.');
        RMM.windows['rmmAlert'].show();
      });

      // Hide the tag and alert window.
      RMM.windows['rmmTag'].hide();
      RMM.windows['rmmAlert'].hide();

      // Remove temp variables.
      params = null;
    }
  };

  // Set the callback function on the tag window cancel button.
  document.getElementById('rmmTag_cancel').callbackFunction = function(event)
  {
    // Hide the tag window.
    RMM.windows['rmmTag'].hide();
    RMM.windows['rmmAlert'].hide();
  };

  // Show the tag window.
  RMM.windows['rmmTag'].show();
};

/**
 * The report inappropriate content method sets up a user interface for reporting rich media content
 * as inappropriate.
 * @param {String} mediaType        Specifies the type of rich media object being reported.
 * @param {String} actionUrl        Specifies the url for reporting inappropriate content.
 * @param {String} refreshUrl       Specifies the url for refreshing the page after the report has been
 *                                  submitted.
 */
RMM.reportInappropriateContent = function(mediaType, actionUrl, refreshUrl)
{
  // Don't perform any actions while we're uploading a file.
  if (RMM.uploading)
  {
    return;
  }

  // If this function was called after window creation then the arguments would have been passed as one big array.
  if (mediaType instanceof Array)
  {
    actionUrl = mediaType[1];
    refreshUrl = mediaType[2];
    mediaType = mediaType[0];
  }

  // Create the window if neccessary.
  if (RMM.createWindow('rmmInappropriate', 'reportInappropriateContent', [mediaType, actionUrl, refreshUrl]))
  {
    // If we had to create the window then the creating function will re-call this
    // function after the window is created and we have access to all it's objects.
    return;
  }

  // Create the alert and confirm windows because we might need those.
  RMM.createWindow('rmmAlert');
  RMM.createWindow('rmmConfirm');

  // Set the value on the reason field in the inappropriate window.
  document.getElementById('rmmInappropriate_reason').value = '';

  // Set the callback function on the confirm window buttons.
  document.getElementById('rmmInappropriate_ok').callbackFunction = function(confirm)
  {
    // Don't perform any actions while we're uploading a file.
    if (RMM.uploading)
    {
      return;
    }

    // Make sure the user entered a reason, and if not let them know about it.
    if (document.getElementById('rmmInappropriate_reason').value == '')
    {
      RMM.windows['rmmAlert'].setTitle('Report Inappropriate Content');
      RMM.windows['rmmAlert'].setBodyText('Sorry, but you must indicate why you think this content is inappropriate.');
      RMM.windows['rmmAlert'].show();
    }
    else
    {
      // Set the parameters we need for submission
      var params = {
        objectTypeCode: mediaType,
        statusCategory: 'CONTENT RATING',
        statusType:     'INAPPROPRIATE',
        reason:         document.getElementById('rmmInappropriate_reason').value
      };

      // Send the request which will report this content as inappropriate.
      RMM.crntActionUrl = null;
      RMM.performAction(actionUrl, params, function()
      {
        if (refreshUrl == null)
        {
          document.location.reload();
        }
        else
        {
          document.location.replace(refreshUrl);
        }
      });

      // Hide the inappropriate and alert windows.
      RMM.windows['rmmInappropriate'].hide();
      RMM.windows['rmmAlert'].hide();

      // Remove temp variables.
      params = null;
    }
  };

  // Set the callback function on the inappropriate window cancel button.
  document.getElementById('rmmInappropriate_cancel').callbackFunction = function(event)
  {
    // Hide the inappropriate window.
    RMM.windows['rmmInappropriate'].hide();
    RMM.windows['rmmAlert'].hide();
  };

  // Show the inappropriate window.
  RMM.windows['rmmInappropriate'].show();
};

/**
 * Launches a document in a task window, the documents window, or just a new browser window (depending on
 * what is available to use).
 * @param {String} url                         The document url.
 * @param {String} name                        The document name.
 * @param {boolean} forceRefresh               Indicates if we should force a load of the document.
 * @param {boolean} destroyOnClose             Indicates if we should empty the document contents when the window is closed.
 * @param {int} windowWidth                    Specifies the width of the document window.
 * @param {int} windowHeight                   Specifies the height of the document window.
 */
RMM.viewDocument = function(url, name, forceRefresh, destroyOnClose, windowWidth, windowHeight)
{
  // Don't perform any actions while we're uploading a file.
  if (RMM.uploading)
  {
    return;
  }

  // If this function was called after window creation then the arguments would have been passed as one big array.
  if (url instanceof Array)
  {
    name = url[1];
    forceRefresh = url[2];
    destroyOnClose = url[3];
    windowWidth = url[4];
    windowHeight = url[5];
    url = url[0];
  }

  // Create the window if neccessary.
  if (RMM.createWindow('rmmDocument', 'viewDocument', [url, name, forceRefresh, destroyOnClose, windowWidth, windowHeight]))
  {
    // If we had to create the window then the creating function will re-call this
    // function after the window is created and we have access to all it's objects.
    return;
  }

  // Create the alert and confirm windows because we might need those.
  RMM.createWindow('rmmAlert');
  RMM.createWindow('rmmConfirm');

  // Hide any open manager windows.
  RMM.hideWindows();

  // Resize the window.
  if (typeof windowWidth != 'undefined' && windowWidth != null && !isNaN(windowWidth))
  {
    document.getElementById('rmmDocument').style.width = windowWidth + 'px';
    document.getElementById('rmmDocument').style.marginLeft = (windowWidth / 2 * -1) + 'px';
    document.getElementById('rmmDocument_frame').style.width = windowWidth + 'px';
  }
  if (typeof windowHeight != 'undefined' && windowHeight != null && !isNaN(windowHeight))
  {
    document.getElementById('rmmDocument').style.height = windowHeight + 'px';
    document.getElementById('rmmDocument').style.marginTop = (windowHeight / 2 * -1) + 'px';
    document.getElementById('rmmDocument_frame').style.height = (windowHeight - 20) + 'px';
  }

  // Set the callback function on the document window close icon.
  document.getElementById('rmmDocument_closeIcon').callbackFunction = function()
  {
    RMM.windows['rmmDocument'].hide();
    if (destroyOnClose)
    {
      document.getElementById('rmmDocument_frame').src = 'cfactor/images/spacer.gif';
    }
  };

  // Show the document.
  if (url.toUpperCase().indexOf('HTTP') != 0)
  {
    url = rinc.rootPath + url;
  }
  if (document.getElementById('rmmDocument_frame').src != url || (typeof forceRefresh == 'boolean' && forceRefresh == true))
  {
    document.getElementById('rmmDocument_frame').src = url;
    RMM.windows['rmmDocument'].setTitle(name);
    setTimeout('RMM.windows[\'rmmDocument\'].show()', 500);
  }
  else
  {
    RMM.windows['rmmDocument'].show();
  }
};

/**
 * Capture some information then perform the action we were going to do.
 * @param {String} windowTitle             Specifies the text string to set as the title of the
 *                                         information capture window.
 * @param {String} windowTitle             Specifies the text string to set as the body of the
 *                                         information capture window.
 * @param {Array} labelNames               Specifies the labels for the fields in the window.
 * @param {Array} paramNames               Specifies the names for the fields when submitting the window.
 * @param {Array} paramValues               Specifies the values for the fields in the window.
 * @param {String} responseFunction        The function to execute after information has been captured.
 * @param {String} functionName            The original Rich Media Manager function.
 * @Param {String} functionArgs            The original function arguments.
 * @Param {String} manager                 The name of the manager that contains the original function.
 */
RMM.captureInformation = function(actionUrl, windowTitle, windowText, labelNames, paramNames, paramValues, responseFunction, functionName, functionArgs, manager)
{
  // Don't perform any actions while we're uploading a file.
  if (RMM.uploading)
  {
    return;
  }

  // If this function was called after window creation then the arguments would have been passed as one big array.
  if (actionUrl instanceof Array)
  {
    windowTitle = actionUrl[1];
    windowText = actionUrl[2];
    labelNames = actionUrl[3];
    paramNames = actionUrl[4];
    paramValues = actionUrl[5];
    responseFunction = actionUrl[6];
    functionName = actionUrl[7];
    functionArgs = actionUrl[8];
    manager = actionUrl[9];
    actionUrl = actionUrl[0];
  }

  // Create the window if neccessary.
  if (RMM.createWindow('rmmCaptureInformation', 'captureInformation', [actionUrl, windowTitle, windowText, labelNames, paramNames, paramValues, responseFunction, functionName, functionArgs, manager]))
  {
    // If we had to create the window then the creating function will re-call this
    // function after the window is created and we have access to all it's objects.
    return;
  }

  // Create the alert and confirm windows because we might need those.
  RMM.createWindow('rmmAlert');
  RMM.createWindow('rmmConfirm');

  // Hide any open manager windows.
  RMM.hideWindows();

  // Set the title and body text on the window.
  RMM.windows['rmmCaptureInformation'].setTitle(windowTitle);
  document.getElementById('rmmCaptureInformation_bodyText').innerHTML = windowText;

  // Show the close icon and show / hide the appropriate containers.
  document.getElementById('rmmCaptureInformation_closeIcon').style.visibility = 'visible';
  document.getElementById('rmmCaptureInformation_captureArea').style.display = 'block';
  document.getElementById('rmmCaptureInformation_progress').style.display = 'none';
  document.getElementById('rmmCaptureInformation_complete').style.display = 'none';

  // Show all the fields we need and set the labels.
  for (var i = 1; i <= 5; i++)
  {
    if (typeof labelNames[i-1] == 'undefined' || labelNames[i-1] == null)
    {
      document.getElementById('rmmCaptureInformation_field' + i + 'Label').style.display = 'none';
      document.getElementById('rmmCaptureInformation_field' + i + 'Label').innerHTML = '';
      document.getElementById('rmmCaptureInformation_field' + i).style.display = 'none';
      document.getElementById('rmmCaptureInformation_field' + i).value = '';
    }
    else
    {
      document.getElementById('rmmCaptureInformation_field' + i + 'Label').style.display = 'block';
      document.getElementById('rmmCaptureInformation_field' + i + 'Label').innerHTML = labelNames[i-1];
      document.getElementById('rmmCaptureInformation_field' + i).style.display = 'block';
      document.getElementById('rmmCaptureInformation_field' + i).value = paramValues[i-1];
    }
  }

  // Set the callback function on the window submit button.
  document.getElementById('rmmCaptureInformation_submit').callbackFunction = function(event)
  {
    // Don't perform any actions while we're uploading a file.
    if (RMM.uploading)
    {
      return;
    }

    // Make sure the user entered information in all the fields, and if not let them know about it.
    if ((document.getElementById('rmmCaptureInformation_field1').value == '' && typeof labelNames[0] != 'undefined' && labelNames[0] != null) ||
        (document.getElementById('rmmCaptureInformation_field2').value == '' && typeof labelNames[1] != 'undefined' && labelNames[1] != null) ||
        (document.getElementById('rmmCaptureInformation_field3').value == '' && typeof labelNames[2] != 'undefined' && labelNames[2] != null) ||
        (document.getElementById('rmmCaptureInformation_field4').value == '' && typeof labelNames[3] != 'undefined' && labelNames[3] != null) ||
        (document.getElementById('rmmCaptureInformation_field5').value == '' && typeof labelNames[4] != 'undefined' && labelNames[4] != null))
    {
      RMM.windows['rmmAlert'].setTitle(windowTitle);
      RMM.windows['rmmAlert'].setBodyText('Sorry, but you must enter information in all the fields.');
      RMM.windows['rmmAlert'].show();
    }
    else
    {
      // Set the parameters we need for submission
      var params = {};
      for (var i = 0; i < paramNames.length; i++)
      {
        params[paramNames[i]] = document.getElementById('rmmCaptureInformation_field' + (i + 1)).value;
      }

      // Hide the close icon and show / hide the appropriate containers.
      document.getElementById('rmmCaptureInformation_closeIcon').style.visibility = 'hidden';
      document.getElementById('rmmCaptureInformation_captureArea').style.display = 'none';
      document.getElementById('rmmCaptureInformation_progress').style.display = 'block';
      document.getElementById('rmmCaptureInformation_complete').style.display = 'none';

      // Send the request which will capture this information.
      RMM.crntActionUrl = null;
      RMM.performAction(actionUrl, params, function(responseLoader)
      {
        if (responseFunction(responseLoader))
        {
          // Hide the window.
          RMM.windows['rmmCaptureInformation'].hide();
          RMM.windows['rmmAlert'].hide();

          // Execute the function that was running before we called this.
          if (typeof functionName != 'undefiend')
          {
            if (typeof functionArgs == 'undefined' || functionArgs == null)
            {
              functionArgs = [];
            }
            if (typeof manager != 'undefined' && manager == 'PhotoAlbumManager' && typeof PhotoAlbumManager[functionName] == 'function')
            {
              PhotoAlbumManager[functionName](functionArgs);
            }
            else if (typeof manager != 'undefined' && manager == 'ResourceManager' && typeof ResourceManager[functionName] == 'function')
            {
              ResourceManager[functionName](functionArgs);
            }
            else if (typeof RMM[functionName] == 'function')
            {
              RMM[functionName](functionArgs);
            }
          }
        }
        else
        {
          // Show the close icon and show / hide the appropriate containers.
          document.getElementById('rmmCaptureInformation_closeIcon').style.visibility = 'visible';
          document.getElementById('rmmCaptureInformation_captureArea').style.display = 'none';
          document.getElementById('rmmCaptureInformation_progress').style.display = 'none';
          document.getElementById('rmmCaptureInformation_complete').style.display = 'block';
        }
      });

      // Hide the alert window.
      RMM.windows['rmmAlert'].hide();

      // Remove temp variables.
      params = null;
    }
  };

  // Set the callback function on the window cancel button.
  document.getElementById('rmmCaptureInformation_cancel').callbackFunction = function(event)
  {
    // Hide the window.
    RMM.windows['rmmCaptureInformation'].hide();
    RMM.windows['rmmAlert'].hide();
  };

  // Set the callback function on the window ok button.
  document.getElementById('rmmCaptureInformation_ok').callbackFunction = function(event)
  {
    // Hide the window.
    RMM.windows['rmmCaptureInformation'].hide();
    RMM.windows['rmmAlert'].hide();
  };

  // Show the upload window.
  RMM.windows['rmmCaptureInformation'].show();
};

/**
 * Check the upload status.
 * param responseLoader               The status Ajax response object.
 */
RMM.sessionCreatedResponse = function(responseLoader)
{
  try
  {
    RMM.hasSession = (responseLoader.getXml().getElementsByTagName('userRegistration')[0].getAttribute('success') == 'true');
  }
  catch (e)
  {
    RMM.hasSession = false;
  }
  return RMM.hasSession;
};

/**
 * The login method creates a login window for the user to log into the portal.
 * @param {String} loginUrl         Specifies the url used for processing a login.
 * @param {String} windowTitle      Specifies a text string to display as the title text
 *                                  of the login window.
 * @param {String} windowText       Specifies a text string to display as the body text
 *                                  of the login window.
 */
RMM.login = function(loginUrl, windowTitle, windowText)
{
  // Don't perform any actions while we're uploading a file.
  if (RMM.uploading)
  {
    return;
  }

  // If this function was called after window creation then the arguments would have been passed as one big array.
  if (loginUrl instanceof Array)
  {
    windowTitle = loginUrl[1];
    windowText = loginUrl[2];
    loginUrl = loginUrl[0];
  }

  // Create the window if neccessary.
  if (RMM.createWindow('rmmLogin', 'login', [loginUrl, windowTitle, windowText]))
  {
    // If we had to create the window then the creating function will re-call this
    // function after the window is created and we have access to all it's objects.
    return;
  }

  // Create the alert and confirm windows because we might need those.
  RMM.createWindow('rmmAlert');
  RMM.createWindow('rmmConfirm');

  // Hide any open manager windows.
  RMM.hideWindows();

  // Show the close icon and show / hide the appropriate containers.
  document.getElementById('rmmLogin_closeIcon').style.visibility = 'visible';
  document.getElementById('rmmLogin_form').style.display = 'block';
  document.getElementById('rmmLogin_progress').style.display = 'none';

  // Set the title and body text on the window.
  RMM.windows['rmmLogin'].setTitle(windowTitle);
  document.getElementById('rmmLogin_bodyText').innerHTML = windowText;

  // Reset the value on the username and password fields.
  document.getElementById('rmmLogin_username').value = '';
  document.getElementById('rmmLogin_password').value = '';

  // Reset the login status.
  document.getElementById('rmmLogin_status').innerHTML = '';

  // Set the callback function on the window submit button.
  document.getElementById('rmmLogin_submit').callbackFunction = function(event)
  {
    // Don't perform any actions while we're uploading a file.
    if (RMM.uploading)
    {
      return;
    }

    // Make sure the user entered a username and password, and if not let them know about it.
    if (document.getElementById('rmmLogin_username').value == '' || document.getElementById('rmmLogin_password').value == '')
    {
      RMM.windows['rmmAlert'].setTitle(windowTitle);
      RMM.windows['rmmAlert'].setBodyText('Sorry, but you must enter your username and password before you can continue.');
      RMM.windows['rmmAlert'].show();
    }
    else
    {
      // Set the parameters we need for submission
      var params = {
        username: document.getElementById('rmmLogin_username').value,
        password: document.getElementById('rmmLogin_password').value
      };

      // Hide the close icon and show / hide the appropriate containers.
      document.getElementById('rmmLogin_closeIcon').style.visibility = 'hidden';
      document.getElementById('rmmLogin_form').style.display = 'none';
      document.getElementById('rmmLogin_progress').style.display = 'block';

      // Send the request which will add / edit this blog post or comment.
      RMM.crntActionUrl = null;
      RMM.performAction(loginUrl, params, function(responseLoader)
      {
        try
        {
          var loginNode = responseLoader.getXml().getElementsByTagName('login')[0];
          var statusMessageNode = loginNode.getElementsByTagName('statusMessage')[0];
          if (loginNode.getAttribute('success') == 'true')
          {
            document.location.reload();
          }
          else
          {
            document.getElementById('rmmLogin_username').value = '';
            document.getElementById('rmmLogin_password').value = '';
            document.getElementById('rmmLogin_status').innerHTML = statusMessageNode.firstChild.nodeValue;

            // Show the close icon and show / hide the appropriate containers.
            document.getElementById('rmmLogin_closeIcon').style.visibility = 'visible';
            document.getElementById('rmmLogin_form').style.display = 'block';
            document.getElementById('rmmLogin_progress').style.display = 'none';
          }
        }
        catch (e)
        {
          document.getElementById('rmmLogin_username').value = '';
          document.getElementById('rmmLogin_password').value = '';
          document.getElementById('rmmLogin_status').innerHTML = 'There was an error processing your login. Please try again. If the problem persists, contact technical support.';

          // Show the close icon and show / hide the appropriate containers.
          document.getElementById('rmmLogin_closeIcon').style.visibility = 'visible';
          document.getElementById('rmmLogin_form').style.display = 'block';
          document.getElementById('rmmLogin_progress').style.display = 'none';
        }
      });

      // Hide the alert window.
      RMM.windows['rmmAlert'].hide();

      // Remove temp variables.
      params = null;
    }
  };

  // Set the callback function on the window cancel button.
  document.getElementById('rmmLogin_cancel').callbackFunction = function(event)
  {
    // Hide the login window.
    RMM.windows['rmmLogin'].hide();
    RMM.windows['rmmAlert'].hide();
  };

  // Show the tag window.
  RMM.windows['rmmLogin'].show();
};

/**
 * Get a cookie value.
 * param name                         The name of the cookie.
 */
RMM.getCookie = function(name)
{
  var cookieValue = '';
  var cookies = document.cookie.split(/\;/g);
  var cookie;

  for (var i = 0; i < cookies.length; i++)
  {
    cookie = cookies[i].split(/=/g);
    if (cookie[0].trim() == name)
    {
      cookieValue = cookie[1].trim();
      break;
    }
  }

  cookies = cookie = null;

  return cookieValue;
};

/**
 * The inititialize editor method waits for the rich text editor widget to fully initialize prior
 * to setting its default editor value (HTML).
 * @param {guifactor.widget.RichTextEditor} editorWidget
 */
RMM.initEditor = function(editorWidget)
{
  if (typeof editorWidget == 'object')
  {
    RMM.richTextEditor = editorWidget;
  }

  if (RMM.richTextEditor.initialized == false)
  {
    window.setTimeout(RMM.initEditor, 10);
    return;
  }
  // Set the value on the textarea field in the editor window.
  try
  {
    RMM.richTextEditor.setHTML(RMM.richText);
  }
  catch (e)
  {
    setTimeout(RMM.initEditor, 10);
  }
};

/**
 * Sends a request with the given url and params to the cfactor portal.
 * @param {String} url                 The url to send post information to.
 * @param {AssociativeArray} params    A collection of request parameters to post to
 *                                     the requested url.
 * @param {Function} responseFunction  An optional function to call on response of a
 *                                     request to the specified url.
 */
RMM.performAction = function(url, params, responseFunction)
{
  // Don't perform any actions while we're uploading a file.
  if (RMM.uploading)
  {
    return;
  }

  if (document.getElementById('rmmUpload_progress'))
  {
    document.getElementById('rmmUpload_progress').style.display = 'block';
  }

  var queryUri = new rinc.Uri(rinc.rootPath, url);
  var httpLoader = new rinc.HttpLoader('RMM_HTTP_LOADER');
  httpLoader.setUri(queryUri);
  queryUri.setParams(params);

  rinc.removeAllImportListeners('RMM_HTTP_LOADER');
  if (typeof responseFunction == 'function')
  {
    rinc.addImportListener('RMM_HTTP_LOADER', null, responseFunction);
  }
  else
  {
    rinc.addImportListener('RMM_HTTP_LOADER', null, RMM.performActionResponse);
  }

  httpLoader.post();

  queryUri = httpLoader = null;
};

/**
 * Function which is called after a manager action has been performed.
 */
RMM.performActionResponse = function()
{
  // Don't perform any actions while we're uploading a file.
  if (RMM.uploading)
  {
    return;
  }

  // Hide the rich text and alert window.
  if( RMM.windows['rmmRichText'] != null )
  {
    RMM.windows['rmmRichText'].hide();
  }
  if( RMM.windows['rmmAlert'] != null )
  {
    RMM.windows['rmmAlert'].hide();
  }

  // Refresh the page.
  if (RMM.crntActionUrl != null)
  {
    RMM.refreshPage(RMM.crntActionUrl);
  }
};

/**
 * Refreshes a rich media page which is rendered using dynamic gui widgets.
 * @param {String} pageUrl            The url to request for refreshing the page.
 */
RMM.refreshPage = function(pageUrl)
{
  // Don't perform any actions while we're uploading a file.
  if (RMM.uploading)
  {
    return;
  }

  document.location = pageUrl;
};

/**
 * Create a window (if neccessary) then call back the function that called
 * this upon creation.
 * @param windowName         The name of the window.
 * @param functionName       The original Rich Media Manager function.
 * @Param functionArgs       The original function arguments.
 */
RMM.createWindow = function(windowName, functionName, functionArgs, manager)
{
  // Check if the window has been created, and if not create it.
  if (RMM.windows[windowName] == null)
  {
    RMM.windows[windowName] = new DynamicContentLayer();
    RMM.windows[windowName].contentLoadedCallback = function()
    {
      var window = document.getElementById(windowName);
      var frames = window.getElementsByTagName('iframe');
      var inputs = window.getElementsByTagName('input');
      var loaded = true;

      // If the dynamic content loaded contains iframes then wait til those
      // are rendered before continuing on.
      for (var i = 0; i < frames.length; i++)
      {
        if (frames[i].getAttribute('contentLoaded') && frames[i].getAttribute('contentLoaded').toUpperCase() == 'N')
        {
          loaded = false;
          break;
        }
      }

      if (loaded)
      {
        // Set the callback function on the close icon.
        if (document.getElementById(windowName + '_closeIcon'))
        {
          document.getElementById(windowName + '_closeIcon').callbackFunction = function()
          {
            RMM.windows[windowName].hide();
          };
        }

        // Initialize the callback functions on any buttons in the window.
        for (var i = 0; i < inputs.length; i++)
        {
          if (inputs[i].getAttribute('type') && inputs[i].getAttribute('type').toUpperCase() == 'BUTTON' && typeof inputs[i].callbackFunction != 'function')
          {
            inputs[i].callbackFunction = function() {};
          }
        }

        // Define functions for setting title and body text.
        if (document.getElementById(windowName + '_windowTitle'))
        {
          this.setTitle = function(titleText)
          {
            document.getElementById(windowName + '_windowTitle').innerHTML = titleText;
          };
        }
        else
        {
          this.setTitle = function() {};
        }
        if (document.getElementById(windowName + '_bodyText'))
        {
          this.setBodyText = function(bodyText)
          {
            document.getElementById(windowName + '_bodyText').innerHTML = bodyText;
          };
        }
        else
        {
          this.setBodyText = function() {};
        }

        // Execute the function that was running before we called this.
        if (typeof functionName != 'undefiend')
        {
          if (typeof functionArgs == 'undefined' || functionArgs == null)
          {
            functionArgs = [];
          }
          if (typeof manager != 'undefined' && manager == 'PhotoAlbumManager' && typeof PhotoAlbumManager[functionName] == 'function')
          {
            PhotoAlbumManager[functionName](functionArgs);
          }
          else if (typeof manager != 'undefined' && manager == 'ResourceManager' && typeof ResourceManager[functionName] == 'function')
          {
            ResourceManager[functionName](functionArgs);
          }
          else if (typeof RMM[functionName] == 'function')
          {
            RMM[functionName](functionArgs);
          }
        }

        this.contentLoadedCallback = null;
      }
      else
      {
        setTimeout('DynamicContentLayer.layers[' + RMM.windows[windowName].index + '].contentLoadedCallback()', 100);
      }

      window = frames = inputs = null;
    };
    RMM.windows[windowName].loadResource(RMM.windowUrls[windowName]);
    return true;
  }
  return false;
};

/**********************/
    function getElementsByClass(className,node,tag) {
      var els = (node||document).getElementsByTagName(tag||"*");
      var len = els.length;
      var reg = new RegExp('(^|\\\\s)'+className+'(\\\\s|$)');
      var res = new Array();
      for (i = 0, j = 0; i < len; i++) {
        if (reg.test(els[i].className)) {
          res[j] = els[i];
          j++;
        }
      }
      return res;
    }
    function addEvent(elm, evType, fn, useCapture) {
      if(typeof useCapture=="undefined"){
        useCapture = false;
      }
      if (elm.addEventListener) {
        elm.addEventListener(evType, fn, useCapture);
        return true;
      }
      else if (elm.attachEvent) {
        var r = elm.attachEvent('on' + evType, fn);
        return r;
      }
      else {
        elm['on' + evType] = fn;
      }
    }

/**********************/
/*
 * From MSDN, this is a, supposedly, future-proof function to
 * detect IE and retreive the version number.
 * http://msdn.microsoft.com/en-us/library/ms537509.aspx
 */
function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure.
  if ( navigator.appName == 'Microsoft Internet Explorer' )
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}
/*
 * Suckerfish menu hover fix for older IE
 */
if (window.attachEvent&&getInternetExplorerVersion()<7) window.attachEvent("onload", function(){
  var els = document.getElementById("nav").getElementsByTagName("LI");
  for (var i=0; i<els.length; i++) {
    els[i].onmouseover=function() {
      this.className+=" sfhover";
    }
    els[i].onmouseout=function() {
      this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
    }
  }
});
/*
 * Hack for menus in IE7
 */
if (window.attachEvent&&getInternetExplorerVersion()==7) window.attachEvent("onload", function(){
  var els = document.getElementById("nav").getElementsByTagName("LI");
  for (var i=0;i<els.length;i++)
  {
    var sub = els[i].getElementsByTagName("UL");
    if (sub.length>0)
    {
      els[i].style.marginBottom = "-4px";
    }
  }
});

/************/

this.toggleSearchTips = function(){
  var searchTips = getElementsByClass("searchTips",document,"div");
  for (var i=0;i<searchTips.length;i++)
  {
    if (searchTips[i].style.display == "block")
    {
      searchTips[i].style.display = "none";
    }
    else
    {
      searchTips[i].style.display = "block";
    }
  }
};

var _c1="cfactorworks.com";
var _c2="@";
var _c3=":";
var _c4="lto";
var _c5="mai";
this.contact = function(id)
{
  window.location = _c5+_c4+_c3+id+_c2+_c1;
}

this.flashPlayer = function() {
  var player, play, stop, mute, muted;
  var muted = false;
  
  player = document.getElementById("player");
  if(player){
    swfobject.embedSWF("portal/swf/"+_swfFile, _swfElem, _swfW, _swfH, _swfV, "portal/swf/expressInstall.swf", {}, {wmode:"transparent"}, {id:"animation",name:"animation",wmode:"transparent"});
    if (swfobject.hasFlashPlayerVersion(_swfV))
    {
      (getElementsByClass("player",player))[0].style.backgroundPosition = "2px 12px";
      play = (getElementsByClass("play",player))[0];
      addEvent(play,"click",function(){
        document.getElementById("animation").playMovie();
        play.style.backgroundPosition = "0 -46px";
        stop.style.backgroundPosition = "0 0";
      });
      play.style.visibility = "visible";
      stop = (getElementsByClass("stop",player))[0];
      stop.style.backgroundPosition = "0 -46px";
      addEvent(stop,"click",function(){
        document.getElementById("animation").stopMovie();
        play.style.backgroundPosition = "0 0";
        stop.style.backgroundPosition = "0 -46px";
      });
      stop.style.visibility = "visible";
      mute = (getElementsByClass("mute",player))[0];
      addEvent(mute,"click",function(){
        document.getElementById("animation").muteMovie();
        if(muted){
          mute.style.backgroundPosition = "0 0";
          muted = false;
        } else {
          mute.style.backgroundPosition = "0 -46px";
          muted = true;
        }
      });
      mute.style.visibility = "visible";
    }
  }
};

this.init = function() {
  flashPlayer();
};
addEvent(window,"load",init);
