// the value of an empty text field for the resource text
var defaultTextFieldValue = "";
  
// the updating interval
var defaultUpdatingInterval = -1;
var maxUpdatingInterval = -1;
var updatingInterval = -1;
// the timer object
var updateTimer = 0;

// the maximal length of the word, which woun't be short-cutted
var maxWordLength = -1;
// the maximal width of the images in the document, after which
// the will be scaled to this width
var maxImageWidth = -1;

// the current page number (the default value is the one, set in the URL
var pageNumber = -1;
// 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 = -1;

// 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 document resource ID
var mainResourceId = 0;
// the main document resource's resource set ID
var mainResourceSetId = 0;

function initModuleHelperFunctions()
{

  defaultTextFieldValue = "Ваше сообщение";
    
  defaultUpdatingInterval = DEFAULT_UPDATE_PERIOD;
  maxUpdatingInterval = 50 * defaultUpdatingInterval;
  updatingInterval = defaultUpdatingInterval;
  updateTimer = 0;

  maxWordLength = MAX_WORD_LENGTH;
  maxImageWidth = MAX_IMAGE_WIDTH;

  pageNumber = PAGE_NUMBER;
  numberOfPages = 0;
  numberOfResources = 0;
  resourcesPerPage = RESOURCES_PER_PAGE;

  lastModificationTime = -1;
  resourcesSetsLastModificationTime = new Array();
  resourcesSetsLastUpdateTime = new Array();

  documentMap = new Array();
  documentContent = new Array();

  mainResourceId = DOCUMENT_MAIN_RESOURCE_ID;
  mainResourceSetId = DOCUMENT_MAIN_RESOURCES_SET_ID;
  
  // adding the main resource in the document map
  documentMap[mainResourceId] = mainResourceSetId;

  dependencyLoaded('moduleHelperFunctions');

}

// 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 )
            // only if the resource's resource set ID have been changed
            if ( 
              documentContent[resourceId] && 
              resourcesSetId == documentMap[resourceId] &&
              resourcesSetId != oldDocumentMap[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
  addDependentCallback(function(){
    redrawDocument();
  },'module,postsContainer');
  
  // 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;
    // optimization for the first run: trying to get the main resource's resources set
    if ( mainResourceSetId )
    {
      addDependentCallback(function(){
        updateResourcesSetContent(mainResourceSetId);
      },'module');
    }
    // building the document map
    buildDocumentMap(0);
  }
  else
  {
    // obtaining the last modification time
    sendUrlResponseTextToFunction
    ( 
      updateCallbackRequestUrl, 
      function( response )
      {
        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();
      }//,
      //true, // this request should be send as POST to make the IE not to cache it
      //true
    ); 
  }
}

// clears the document data to reload it
function clearDocumentData()
{
  documentMap = new Array();
  documentContent = new Array();
  lastModificationTime = -1;
  resourcesSetsLastUpdateTime = new Array();
  resourcesSetsLastModificationTime = new Array();
}

// INIT
addDependentCallback(function(){
  initModuleHelperFunctions();
},'constants, settings', false);


