// the value of an empty text field for the resource text
var defaultTextFieldValue = "Ваше сообщение";
  
// the updating interval
var defaultUpdatingInterval = DEFAULT_UPDATE_PERIOD;
var maxUpdatingInterval = 50 * defaultUpdatingInterval;
var updatingInterval = defaultUpdatingInterval;
// the timer object
var updateTimer = 0;

// the maximal length of the word, which woun't be short-cutted
var maxWordLength = MAX_WORD_LENGTH;
// the maximal width of the images in the document, after which
// the will be scaled to this width
var maxImageWidth = MAX_IMAGE_WIDTH;

// the current page number (the default value is the one, set in the URL
var pageNumber = PAGE_NUMBER;
// the number of pages in the document
var numberOfPages = 0;
// number of resources in the document
var numberOfResources = 0;
// the number of resources per page
var resourcesPerPage = RESOURCES_PER_PAGE;

// the last resources in the guest book update time
var lastModificationTime = -1;
// the same for every resources set of the document
var resourcesSetsLastModificationTime = new Array();
// the last time, the resources sets have been updated
var resourcesSetsLastUpdateTime = new Array();

// the map of the document
var documentMap = new Array();
// the document resources content array
var documentContent = new Array();

// the main publication resource ID
var mainResourceId = 0;

// loads the document map, (the array will be fully refreshed)
function buildDocumentMap( givenLastModificationTime )
{
  sendUrlResponseXmlToFunction
  ( 
    // randomizing by the last modification time, to make the cache word right
    buildDocumentMapRequestUrl + lastModificationTime, 
    function( response )
    {
    try {
      // an empty response comes from time to time. Retrying then
      if ( !response )
      {
        buildDocumentMap( givenLastModificationTime );
        return;
      };
      buildDocumentMapFromXml( response, givenLastModificationTime );
    } catch (e) { window.status=e.message };
    }//,
    //true // this request should be send as POST to make the IE not to cache it
  );
}

// builds the document map from the XML document, got as the response
// from the sendUrlResponseXmlToFunction()
function buildDocumentMapFromXml( response, givenLastModificationTime )
{
  // the document's map should be recreated
  var oldDocumentMap = documentMap;
  delete documentMap;
  documentMap = new Array();
  var resourcesSets = response.getElementsByTagName("resourcesSet");

  if ( resourcesSets && resourcesSets.length > 0 )
  {
    for ( var resourcesSetI = 0; resourcesSetI < resourcesSets.length; resourcesSetI++ )
    {
      var resourcesSet = resourcesSets[resourcesSetI];
      var resourcesSetId = resourcesSet.getAttribute( "id" );
      if ( !resourcesSetId )
        continue;

      var resourcesIds = resourcesSet.getElementsByTagName("resource");
      
      if ( resourcesIds && ( resourcesIds.length > 0 ) )
        for ( var resourceI = 0; resourceI < resourcesIds.length; resourceI++ )
          if (true|| resourcesIds[resourceI].getAttribute )
          {
            var resourceId = resourcesIds[resourceI].getAttribute( "id" );
            if ( resourceId )
              documentMap[resourceId] = resourcesSetId;
          };
      
      // storing the last modification times for resources sets
      // to hack the situation with zero times for the undefined times,
      // setting the default time to 1
      if ( resourcesSet.getElementsByTagName("lastModificationTime").length == 1 )
      {
        var newLastModificationTime = max( 1, parseInt( resourcesSet.getElementsByTagName("lastModificationTime")[0].firstChild.nodeValue ) );
        // checking, if the resources set had been updated, and
        // saying, that the resources in this resources set should be updated
        if ( resourcesSetsLastModificationTime[resourcesSetId] && newLastModificationTime != resourcesSetsLastModificationTime[resourcesSetId] || !resourcesSetsLastModificationTime[resourcesSetId] )
        {
          for ( var resourceId in documentMap )
            if ( documentContent[resourceId] && resourcesSetId == documentMap[resourceId] )
              delete documentContent[resourceId];
        };
        // saving the new last modification time
        resourcesSetsLastModificationTime[resourcesSetId] = newLastModificationTime;
      }
      else
        resourcesSetsLastModificationTime[resourcesSetId] = 1;

    };
    
    // the document dimensions
    numberOfResources = 0;//documentMap.length;
    for ( var resourceId in documentMap )
      numberOfResources++;
    numberOfPages = Math.ceil( numberOfResources / resourcesPerPage );
    
    // loading the main resource ID
    if ( response.getElementsByTagName("mainResourceId").length > 0 )
      mainResourceId = response.getElementsByTagName("mainResourceId")[0].firstChild.nodeValue;

  };
  
  // updating the page content
  redrawDocument();
  
  // this is the last time, where the document on the server has been modificated
  lastModificationTime = max( 1, givenLastModificationTime );
}

// performs the default initialization for the empty document
function buildEmptyDocumentMap( givenLastModificationTime )
{
  // the document's map should be recreated
  var oldDocumentMap = documentMap;
  delete documentMap;
  documentMap = new Array();
  
  // the document dimensions
  numberOfResources = 0;
  numberOfPages = 1;
  
  // updating the page content
  redrawDocument();
  
  // this is the last time, where the document on the server has been modificated
  lastModificationTime = max( 1, givenLastModificationTime );
}

// the callback for the timer
function updateCallback( updateAnyWay )
{
  // to force the document page regeneration, simply
  // nulling the last update time
  if ( updateAnyWay )
    lastModificationTime = -1;

  // obtaining the last modification time
  sendUrlResponseTextToFunction
  ( 
    updateCallbackRequestUrl, 
    function( response )
    {
    try {
      if ( response != RESPONSE_DOCUMENT_NOT_FOUND )
      {
        var newLastModificationTime = 0;
          newLastModificationTime = parseInt( response );
        if ( lastModificationTime != newLastModificationTime )
        {
          // redrawing
          buildDocumentMap( newLastModificationTime );
          // the last modification time will be updated in the buildDocumentMap()
        };
      }
      else
        buildEmptyDocumentMap();
    } catch (e) { window.status=e.message };
    }//,
    //true, // this request should be send as POST to make the IE not to cache it
    //true
  );
}
