// loads the resources set with ID, given, content into the document content
function updateResourcesSetContent( resourcesSetId )
{
  // checking the resources set's update time and, if it is bigger, then
  // the last update time for this page - updating this resources set
  if ( resourcesSetsLastUpdateTime[resourcesSetId] && ( resourcesSetsLastUpdateTime[resourcesSetId] >= resourcesSetsLastModificationTime[resourcesSetId] ) )
    return;
  
  // storing the resources set's last modification time as the last update time
  resourcesSetsLastUpdateTime[resourcesSetId] = resourcesSetsLastModificationTime[resourcesSetId];
  
  // updating the resources set content
  sendUrlResponseXmlToFunction
  ( 
    updateResourcesSetContentRequestUrl + resourcesSetId,
    function( response )
    {
      // an empty response comes from time to time. Retrying then
      if ( !response )
      {
        updateResourcesSetContent( resourcesSetId );
        return;
      };
      if ( typeof response != "object" && response == RESPONSE_RESOURCE_NOT_FOUND )
      {
        if ( USER_RIGHTS_MODERATE )
        {
          if ( confirm( "Глючный ресурс: " + resourcesSetId + ", удалить?" ) )
          {
            for ( var messageId in documentMap )
              if ( documentMap[messageId] == resourcesSetId )
                removeMessageWithId( messageId );
          };
        };
        for ( var messageId in documentMap )
          if ( documentMap[messageId] == resourcesSetId )
            documentContent[messageId] = RESPONSE_RESOURCE_NOT_FOUND;
        // updating the page content
        redrawDocument();
        return;
      };
      
      var messages = response.getElementsByTagName("resource");
      if ( messages.length > 0 )
      {
        for ( var messageI = 0; messageI < messages.length; messageI++ )
        {
          //if ( !( messages[messageI].getAttribute ) )
          //  continue;
          var messageId = messages[messageI].getAttribute( "id" );
          if ( !messageId )
            continue;
          if ( !(documentContent[messageId]) )
            documentContent[messageId] = Array();

          if ( messages[messageI].getElementsByTagName("name").length > 0 )
            documentContent[messageId]["name"] = messages[messageI].getElementsByTagName("name")[0].firstChild.nodeValue;
          // saving authors IDs
          if ( !documentContent[messageId]["authors"] )
            documentContent[messageId]["authors"] = new Array();
          if ( messages[messageI].getElementsByTagName("authors").length > 0 )
          {
            var authors = messages[messageI].getElementsByTagName("authors")[0].getElementsByTagName("item");
            if ( authors.length > 0 )
              for ( var authorI = 0; authorI < authors.length; authorI++ )
                documentContent[messageId]["authors"][authors[authorI].firstChild.nodeValue] = true;
          };
          // converting the UNIX time into the time string
          var date = new Date();
          if ( messages[messageI].getElementsByTagName("time").length > 0 )
          {
            if ( messages[messageI].getElementsByTagName("time")[0].getElementsByTagName("lastModification").length > 0 )
              date.setTime( 1000*messages[messageI].getElementsByTagName("time")[0].getElementsByTagName("lastModification")[0].firstChild.nodeValue );
            else if ( messages[messageI].getElementsByTagName("time")[0].getElementsByTagName("creation").length > 0 )
              date.setTime( 1000*messages[messageI].getElementsByTagName("time")[0].getElementsByTagName("creation")[0].firstChild.nodeValue );
            documentContent[messageId]["time"] = date.toLocaleDateString() + " " + date.toLocaleTimeString();
          };
          documentContent[messageId]["plaintext"] = "";
          if ( messages[messageI].getElementsByTagName("text").length > 0 )
          {
            var textParts = messages[messageI].getElementsByTagName("text")[0].childNodes;
            if ( textParts.length > 0 )
              for ( textPartI = 0; textPartI < textParts.length; textPartI++  )
                if ( textParts[textPartI].nodeValue )
                  documentContent[messageId]["plaintext"] += textParts[textPartI].nodeValue;
            // nicing-up the content
            documentContent[messageId]["text"] = prepareText( documentContent[messageId]["plaintext"] );
          };
        };
        // updating the page content
        redrawDocument();
      };
    }
  );
}

// generates the document content draws it
function redrawDocument()
{
  // finding the element
  var element = obtainElementById( "posts" );
  // checking
  if ( !element ) return;
  
  var content = "";
  if ( USER_RIGHTS_EDIT )
    content = "<div style='display:block; text-align:right'><img width='20' height='20' onclick='javascript: prepareCommentBoxForEditFunctionality()' src='"+MODULE_PATH+"edit.gif' onmouseover='javascript: placeElementWithContentOnTopFromMe( this, \"hintconstrain\", \"hintcontent\", \"Редактировать публикацию.<br />Для&nbsp;вызова этой функции можно также сделать двойной щелчёк на&nbsp;тексте.\", 0, 0, hintHidingDelay );' onmouseout='javascript: startHidingLastElement(\"hintconstrain\");'/></div>\n";
  content += "<div class='resourcetext' ondblclick='javascript: if ( USER_RIGHTS_EDIT ) prepareCommentBoxForEditFunctionality();'>\n";

  /*
  // the visible document part content
  var content = "<table border='0' width='100%'>\n";
  
  // the visible document part dimensions
  if ( numberOfPages < 1 ) return;
  var firstMessageNumber = 0;
  if ( pageNumber == <?php echo DEFAULT_PAGE_NUMBER?> )
    firstMessageNumber = Math.max( 0, numberOfResources - messagesPerPage );
  else
    firstMessageNumber = Math.min( numberOfResources - 1, max( 0, pageNumber * messagesPerPage ) );
  var lastMessageNumber = Math.min( numberOfResources - 1, firstMessageNumber + messagesPerPage - 1 );
  
  // generating the navigation links
  var links = "";
  for ( var i = 0; i < numberOfPages; i++ )
    links += "&nbsp;" + ( i == pageNumber ? "&gt;" : "" ) + "<a href='/<?php echo $DOCUMENT_PATH_STRING?>?<?php echo PARAM_RESOURCES_PER_PAGE?>=" + messagesPerPage + "&amp;<?php echo PARAM_PAGE_NUMBER?>=" + i + "'>" + (i+1) + "</a>" + ( i == pageNumber ? "&lt;" : "" ) + " \n";
    
  // adding links section
  content1 += "<tr><td style='padding:20px'><h3 style='display:inline'><a href='<?php echo$DOCUMENT_PATH_STRING?>/'>Последние сообщения</a> Страницы: " + links + "</h3> <small>(Ctrl&nbsp;+&nbsp;&larr;&nbsp;&mdash;&nbsp;предыдущая, Ctrl&nbsp;+&nbsp;&rarr;&nbsp;&mdash;&nbsp;следующая)</small></td><td style='text-align:right'><a href='<?php echo$DOCUMENT_PATH_STRING?>/?<?php echo PARAM_FUNCTION?>=<?php echo PARAM_FUNCTION_RSS?>'><img style='border:none' src='<?php echo$THEME_PATH?>rss.gif' widht='14' height='14' /></a></td></tr>\n";
  
  // generating the messages
  
  var messageNumber = -1;
  for ( var messageId in documentMap )
  {
    // skipping unwanted messages
    messageNumber++;
    if ( messageNumber < firstMessageNumber || messageNumber > lastMessageNumber )
      continue;

    content += "<tr><td>\n"
    if ( ( documentContent[messageId] ) )
    {
      content1 += "<tr><td style='padding-top:20px'><h2 style='display:inline;'>"+documentContent[messageId]['name']+"</h2>&nbsp; <small>(" + documentContent[messageId]['time'] + ")</small></td>\n<td align='right' valign='bottom' style='width:50px'><?php if ( $USER_RIGHTS_MODERATE ): ?><img width='20' height='18' onclick='javascript: removePostWithId( \""+messageId+"\" )' src='<?php echo $THEME_PATH?>moderate.gif' /><?php endif; ?></td></tr>\n";
      content += "<tr><td colspan='2' class='resourcetext' style='padding-left:30px; padding-right:30px'>"+documentContent[messageId]['text']+"</td></tr>\n";
    }
    else
    {
      updateResourcesSetContent( documentMap[messageId] )
      // returning to prevent the unformed document redrawing
      return;
    };
  }
  content += "</table>\n";
  */
  var documentNotLoadedFully = false;
  if ( documentContent[mainResourceId] != null && documentContent[mainResourceId] != RESPONSE_RESOURCE_NOT_FOUND )
    content += documentContent[mainResourceId]['text'];
  else if ( mainResourceId && documentContent[mainResourceId] != RESPONSE_RESOURCE_NOT_FOUND )
  {
    updateResourcesSetContent( documentMap[mainResourceId] )
    documentNotLoadedFully = true;
    //return;
  };
  // returning to prevent the unformed document redrawing
  if ( documentNotLoadedFully )
    return
    
  content += "</div>";
  
  if ( element.innerHTML != content )
  {
    // updating the content
    element.innerHTML = content;
    
    // refreshing the window
    refreshMainElementsPositions();
  };
}

// sends the new publication text
function sendPublicationText()
{
  var text = obtainElementById( 'textfield' ).value;
  //var name = obtainElementById( 'namefield' ).value;
  
  // checking to have something to do
  if ( text == "" || text == defaultTextFieldValue )
    return;
    
  // disabling the text field
  obtainElementById( 'textfield' ).disabled = true;
  
  // building the list of params
  var params = new Array();
  params[PARAM_PUBLICATION_TEXT] = decodeHtmlEntities( text );
  params[PARAM_DOCUMENT_PATH_STRING] = DOCUMENT_PATH_STRING;
  //params['<?php echo PARAM_USER_ID ?>'] = name;
  
  // adding the resource to the document
  sendUrlResponseTextToFunction
  ( 
    sendPublicationTextRequestUrl, 
    function( response )
    {
      if ( response == RESPONSE_REQUEST_PROCEEDED_SUCCESSFULLY )
      {
        // clearing the text field
        obtainElementById( 'textfield' ).value = "";
        // moving to the default (tracking last messages) page
        pageNumber = DEFAULT_PAGE_NUMBER;
        // updating the document
        updateCallback();
        // enabling back the text field
        obtainElementById( 'textfield' ).disabled = false;
        // focusing it to pretty-up
        //obtainElementById( 'namefield' ).focus();
        //obtainElementById( 'textfield' ).focus();
        obtainElementById( 'commentbox' ).style.display = 'none'
      }
      else
        alert( response );
    },
    params
  );
}

function prepareCommentBoxForEditFunctionality()
{
  obtainElementById( 'commentbox' ).style.display = "block";
  if ( documentContent[mainResourceId] )
    obtainElementById( 'textfield' ).value = decodeHtmlEntities( documentContent[mainResourceId]['plaintext'] );
  //obtainElementById( 'textfield' ).focus();
}

function prepareCommentBoxForDefaultFunctionality()
{
  obtainElementById( 'commentbox' ).style.display = "none";
  obtainElementById( 'commentboxheader' ).innerHTML = "Вам слово";
  obtainElementById( 'submitbutton' ).value = "Заменить (Ctrl+Enter)";
  obtainElementById( 'submitbutton' ).onclick = function(){sendPublicationText();};
  obtainElementById( 'textfield' ).value = defaultTextFieldValue;
  obtainElementById( 'cancelbuttoncontainer' ).style.display = "block";
  setElementHeightById( 'textfield', 800 );
  //obtainElementById( 'textfield' ).focus();
}

// moves to the previous page on Ctrl+<-
// moves to the next page on Ctrl+->
// sends the message on Ctrl+Enter
function globalKeysTreatment( event )
{
  event = (event) ? event : window.event;
  if ( event.ctrlKey && !( event.shiftKey || event.altKey ) ) 
    switch ( event.keyCode )
    {
      // submit
      case 13:
        var submitButton = obtainElementById( 'submitbutton' );
        if ( submitButton )
          submitButton.click();
        break;
    };
}

