﻿///////////////////////////////////////////////////////////////////////////////
//
//  csPageManager.js
//
// © 2007-2009 Wco iEnterprise Solutions Pty Ltd. ALL RIGHTS RESERVED.
// This file is licensed as part of the DataPortal 2.0 Managed Web Presence Solution, for details look here: http://www.wco.com.au
//
///////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/*<remarks>
Method:      constructor
Description: Instantiates a new instance of the pageManager object, making it ready to receive and process calls to the DataPortal Web service.
Parameters:
             [none]
</remarks>*/
HtmlPageManagerObject = function() {
  // declare and initialise the pageManager's properties
  this.sectionId = 0;
  this.topicId = 0;

  // declare and initialise the current object properties
  this.currentObjectId = 0;
  this.currentObjectClass = '';
  this.currentObjectClassIsLeaf = false;
  this.currentObjectSortOrder = 1;

  // declare and initialise the background fetch engine's properties
  this.backgroundFetchList = null;
  this.backgroundObject = null;
  this.backgroundObjectId = 0;
  
  // declare and instantiate the pageManager's UI elements
  var html = '<div id="contentPanel" style="position:absolute; top:0px; left:0px; width:100%; height:100%; background-color:#74857d; background-image:url(\'ssl/images/bkg_duotone.jpg\'); background-position:center top; background-repeat:no-repeat; cursor:default;">';
  html += '';
  html += '';
  html += '</div>';
  var newContent = document.createElement('DIV');
  newContent.id = 'newContent';
  newContent.innerHTML = html;
  newContent.style.display = 'none';
  this.contentPane = newContent.childNodes[0];
  document.body.appendChild(this.contentPane);
  
  var html = '<div id="logoPanel" style="position:absolute; top:2px; left:0px; width:1186px; height:115px; background-image:url(\'ssl/images/cs_logo_panel.png\'); background-position:left top; background-repeat:no-repeat; z-index:1; display:none; cursor:default;">';
  html += '';
  html += '';
  html += '</div>';
  var newContent = document.createElement('DIV');
  newContent.id = 'newContent';
  newContent.innerHTML = html;
  newContent.style.display = 'none';
  this.titleElement = newContent.childNodes[0];
  this.contentPane.appendChild(this.titleElement);
  
  var html = '<div id="footerPanel" style="position:absolute; top:744px; left:0px; width:956px; height:24px; display:none; cursor:default;">';
  html += '<table cellpadding="0" cellspacing="0" style="width:100%; margin:0; padding:0;">';
  html += '<tr>';
  html += '<td class="Footer" style="text-align:left;">';
  html += 'CALL <b>(02) 9221 1933</b> FOR IMMEDIATE ADVICE';
  html += '</td>';
  html += '<td class="Footer" style="text-align:right;">';
  html += 'LEVEL 1, 195 MACQUARIE STREET, SYDNEY';
  html += '</td>';
  html += '</tr>';
  html += '<tr>';
  html += '<td class="FooterNotices" colspan="2" style="text-align:center; margin:0; padding:2px 0 0 0;">';
  html += '<b><a class="FooterNotices" href="http://www.apfa.org.au/members.html" onclick="javascript:this.href=\'javascript:void(0);\'; window.open(\'http://www.apfa.org.au/members.html\', \'_blank\'); return void(0);" alt="Open APFA home page in another window">Member of the Abortion Providers Federation of Australasia</a>.</b> | © copyright 2009 Femme Medical Pty Ltd. All rights reserved. | Web site designed and produced by <a class="FooterNotices" href="http://www.wco.com.au" onclick="javascript:this.href=\'javascript:void(0);\'; window.open(\'http://www.wco.com.au\', \'_blank\'); return void(0);" alt="Open Wco iEnterprise Solutions in another window">Wco iEnterprise Solutions</a>.';
  html += '</td>';
  html += '</tr>';
  html += '</table>';
  html += '</div>';
  var newContent = document.createElement('DIV');
  newContent.id = 'newContent';
  newContent.innerHTML = html;
  newContent.style.display = 'none';
  this.footerElement = newContent.childNodes[0];
  this.contentPane.appendChild(this.footerElement);
  
  this.languageCultureName = '';
//  this.splashScreen = new HtmlSplashObject(this);
//  this.locationNavigator = new HtmlLocationNavigatorObject(this);
  this.splashScreen = null;
  this.locationNavigator = null;
  this.sitemenu = null; // declare the site menu collection
  this.subjects = null; // declare the section collection
  this.tabs = null; // declare the tabs collection

  // initialise the communication link to the DataPortal
  //         init(<parent>, <portalGuid>, <websiteId>, <languageCultureName>)
  dataportal.init(this, '655BD726-8A3B-4C4C-89E1-427D8B44CEDD', 8, 'en-AU');
  
}

HtmlPageManagerObject.prototype = {
  /*<remarks>
  Method:      init
  Description: Initialises the module's members and runs through the required startup procedures.
  Parameters:
               [none]
  </remarks>*/
  init: function() {
    // first, immediately ensure that any existing calls to the dataportal are cancelled
    if (dataportal.request != null) {
      dataportal.cancelRequest();
    }
    
    // check for a specified language being requested and reset the module property if required
    if (arguments[0] != null) {
      this.languageCultureName = arguments[0];
    }
    
    // initialise the application
    // -- destroy the background fetch properties
    this.backgroundFetchList = null;
    this.backgroundObject = null;
    this.backgroundObjectId = 0;
    // -- remove all elements from the ui except the logo banner
    if (this.tabs != null) this.contentPane.removeChild(this.tabs.rootElement);
    if (this.sitemenu != null) this.contentPane.removeChild(this.sitemenu.rootElement);
    if (this.subjects != null) this.contentPane.removeChild(this.subjects.rootElement);
    if (this.splashScreen != null) this.contentPane.removeChild(this.splashScreen.rootElement);
    if (this.locationNavigator != null) this.contentPane.removeChild(this.locationNavigator.rootElement);
    this.splashScreen = null; // destroy the splash screen
    this.locationNavigator = null; // destroy the location navigator
    this.sitemenu = null; // destroy the site menu collection
    this.subjects = null; // destroy the section collection
    this.tabs = null;
    
    // -- instantiate the background fetch engine
    this.backgroundFetchList = null;
    this.backgroundObject = null;
    this.backgroundObjectId = 0;
    this.backgroundFetchList = new Array();
    // -- and instantiate the primary ui elements
    this.splashScreen = new HtmlSplashObject(this); // instantiate the splash screen
    this.locationNavigator = new HtmlLocationNavigatorObject(this); // instantiate the location navigator
    this.sitemenu = new HtmlSiteMenuCollection(this); // instantiate the site menu collection
    this.subjects = new HtmlSubjectCollection(this); // instantiate the section collection
    this.tabs = new HtmlSlideTabCollection(this); // instantiate the tabs collection
    
    // now, setup the secondary ui elements
    // -- instantiate the Contact Us slide-down tab
    
    // -- initialise the Clinic Tour slide-down tab
    
    // -- instantiate the Docment Library slide-down tab
    
    // initialise the layout of the ui
    this.redoLayout();
    this.splashScreen.show();
    positioning.showObject(this.titleElement);
    positioning.showObject(this.footerElement);
    this.locationNavigator.show();
    this.tabs.show();
    
    // **** and ACTIVATE THE WEBSITE by calling the DataPortal Web service and retrieving the Home Page data
    this.fetchObject(87699, 'Portal', false);
    
  },

  /*<remarks>
  Method:      redoLayout
  Description: Reformats the ui elements whenever the browser window is resized.
  Parameters:
               [none]
  </remarks>*/
  redoLayout: function() {
    var w = windowGeometry.getViewportWidth();
    var h = windowGeometry.getViewportHeight();
    
    positioning.setObjectWidth(this.titleElement, (w/2)+228);
    positioning.setObjectLeft(this.titleElement, (w/2)-228);
    positioning.setObjectLeft(this.footerElement, (w/2)-(956/2));
    
    // and bubble the reformat down through the section collection
    this.splashScreen.redoLayout();
    this.sitemenu.redoLayout();
    this.locationNavigator.redoLayout();
    this.subjects.redoLayout();
    this.tabs.redoLayout();
  },
  
  fetchObject: function(objId, objClass, objIsLeaf) {
    var objSortOrder = 0;
    var objParentId = 0;
    if (arguments[3] != null) { objSortOrder = arguments[3]; }
    if (arguments[4] != null) { objParentId = arguments[4]; }
    var objConcurrencyId = -1;
    
    if (objId == 0) {
      // display the Home Page splash screen
      this.splashScreen.show();
      return void(0);
    }
    
    //var isLeaf = false;
    switch (objClass) {
      case 'Portal':
        // do nothing
        break;
      case 'Section':
        objConcurrencyId = this.subjects.add(objId, objSortOrder);
        break;
      case 'Question':
        //if (objId = 235070) alert('About to fetch objId: ' + objId + '\nof parent objId: ' + objParentId);
        var thisSubject = this.subjects.itemById(objParentId);
        objConcurrencyId = thisSubject.topics.add(objId, objSortOrder);
        //objConcurrencyId = 1;
        break;
      default:
        // do nothing
        return void(0);
        break;
    }
    var usePagination = false;
    var paginationClassName = '';
    var paginationPageSize = 50;
    var paginationPageNo = 1;
    
    // remember the current object properties
    this.currentObjectId = objId;
    this.currentObjectClass = objClass;
    this.currentObjectClassIsLeaf = objIsLeaf;
    this.currentObjectSortOrder = objSortOrder;
    
//    alert('objId = ' + objId +
//          '\nobjParentId = ' + objParentId +
//          '\nobjClass = ' + objClass +
//          '\nobjIsLeaf = ' + objIsLeaf +
//          '\nobjSortOrder = ' + objSortOrder +
//          '\nobjConcurrencyId = ' + objConcurrencyId +
//          '\nusePagination = ' + usePagination + 
//          '\npaginationClassName = ' + paginationClassName + 
//          '\npaginationPageSize = ' + paginationPageSize + 
//          '\npaginationPageNo = ' + paginationPageNo
//          );
    // check whether the requested object is already fetched or not
    if (objConcurrencyId == -1) {
      // requested object is not available --
      // -- first, check if there is an existing request is progress
      if (dataportal.request != null) {
        // existing request processing - cancel it before proceeding with new request
        dataportal.cancelRequest();
        //alert('Background fetch cancelled for objId: ' + this.backgroundObjectId + '\nNow fetching objId: ' + objId);
        // also handle any interrupted background loading...
        if (this.backgroundObjectId != 0) {
          // put the background object properties back on the stack so we can try again later
          this.backgroundFetchList.unshift(this.backgroundObject);
          this.backgroundObject = null;
          this.backgroundObjectId = 0;
        }
        // also, as the only reason that an existing request is being interrupted is because a specific object
        // has been requested by a user, then the current object must be set to the requested object
        switch (objClass) {
          case 'Portal':
            // do nothing
            return void(0);
            break;
          case 'Section':
            // set the current object to requested Subject page
            this.subjects.setCurrentObject(objSortOrder);
            break;
          case 'Question':
            // set the current object to requested Topic tab on the relevant Subject page
            //alert('Set current object to topic id: ' + objId);
            var thisSubject = this.subjects.itemById(objParentId);
            thisSubject.topics.setCurrentObject(objId);
            break;
          default:
            // do nothing
            return void(0);
            break;
        }
      }
      // -- set the ParentId property of the DataPortal module
      dataportal.currentParentId = objParentId;
      // -- and make the call to the DataPortal
      dataportal.fetchObject(objId, objClass, objIsLeaf, usePagination, paginationClassName, paginationPageSize, paginationPageNo, this.languageCultureName);
    }
    else {
      // requested object is in the relevant content collection so just display it
      switch (objClass) {
        case 'Portal':
          // do nothing
          break;
        case 'Section':
          // display the requested Subject page
          this.subjects.setCurrentObject(objSortOrder);
          break;
        case 'Question':
          // display the requested Topic tab on the relevant Subject page
          //alert('Display topic id: ' + objId);
          this.subjects.currentObject.topics.setCurrentObject(objId);
          break;
        default:
          // do nothing
          break;
      }
    }
  },
  
  processBackgroundFetchList: function() {
    if (this.backgroundFetchList.length == 0) {
      dataportal.cancelRequest();
      //this.splashScreen.hide();
    }
    else {
      // pop the next item from the list
      var objProps = this.backgroundFetchList.shift().split(',');
      //alert(objProps + '\nid = ' + objProps[0] + '\nclassName = ' + objProps[1] + '\nisLeaf = ' + objProps[2] + '\nindex = ' + objProps[3] + '\nparentId = ' + objProps[4]);
      
      // confirm that this background object is not already captured
      var isObjectFetched = false;
      var objId = objProps[0];
      var className = objProps[1];
      switch (className) {
        case 'Portal':
          // do nothing
          break;
        case 'Section':
          // search the Subject collection for the requested object id
          for (var i=0; i<this.subjects.item.length; i++) {
            if (this.subjects.item[i].id == objId && this.subjects.item[i].concurrencyId > -1) {
              isObjectFetched = true;
              //alert('The background processing is attempting to fetch a Subject that has already been loaded!\nId = ' + objId);
            }
          }
          break;
        case 'Question':
          // search the relevant Topic collection for the requested object id
          var thisSubject = this.subjects.itemById(objProps[4]);
          for (var i=0; i<thisSubject.topics.item.length; i++) {
            if (thisSubject.topics.item[i].id == objId && thisSubject.topics.item[i].concurrencyId > -1) {
              isObjectFetched = true;
              //alert('The background processing is attempting to fetch a Topic that has already been loaded!\nId = ' + objId);
            }
          }
          break;
        default:
          // do nothing
          return void(0);
          break;
      }
      
      // and, if required, make the call to the DataPortal via the PageManager's fetchObject method
      //alert('isObjectFetched = ' + isObjectFetched);
      if (!isObjectFetched) {
        // the requested object is not loaded so make the call to the DataPortal via the PageManager's fetchObject method
        this.backgroundObject = objProps.join(','); // remember the background object properties
        this.backgroundObjectId = objProps[0];
        //alert('this.fetchObject(' + objProps[0] + ', ' + objProps[1] + ', ' + objProps[2] + ', ' + objProps[3] + ', ' + objProps[4] + ')');
        //   fetchObject(<objId>, <className>, <classIsLeaf>, <objIndex>, <objParentId>)
        this.fetchObject(objProps[0], objProps[1], objProps[2], objProps[3], objProps[4]);
      }
      else {
        // the requested object is already in the relevant content collection, so continue processing the background fetch list
        this.backgroundObject = null; // reset the background object properties pointers
        this.backgroundObjectId = 0;
        this.processBackgroundFetchList();
      }
    }
  },

  displayObject: function(content) {
    if (dataportal.isRequestCanceled) {
      return void(0);
    }
    this.languageCultureName = dataportal.sessionLanguageCultureName;
    
    //alert(content);
    var newContent = document.createElement('DIV');
    newContent.id = 'newContent';
    newContent.innerHTML = content;
    newContent.style.display = 'none';
    this.contentPane.appendChild(newContent);
    
    if (positioning.getObject('sectionCollection') != null) {
      // add menus items to the site menu collection
      var coll = positioning.getObject('sectionCollection');
      //alert(coll.innerHTML);
      for (var i=0; i<coll.childNodes.length; i++) {
        this.sitemenu.add(coll.childNodes[i]);
      }
      this.sitemenu.show();
      
      // re-initialise the layout of the ui with the new site menu in place
      this.redoLayout();
      
      // and add the top-level Section objects to the background processing list
      for (var i=0; i<coll.childNodes.length; i++) {
        var dataNode = coll.childNodes[i];
        //alert(dataNode.outerHTML);
        //                    <objId>,<className>,<isLeaf>,<index>,<parentId>
        //var dataPropertyStr = dataNode.attributes[0].nodeValue + ',' + dataNode.childNodes[4].innerHTML + ',' + dataNode.childNodes[5].innerHTML + ',' + (dataNode.childNodes[2].innerHTML - 1) + ',' + dataNode.childNodes[0].innerHTML;
        var dataPropertyStr = dataNode.attributes.getNamedItem('id').nodeValue + ',' + dataNode.childNodes[4].innerHTML + ',' + dataNode.childNodes[5].innerHTML + ',' + (dataNode.childNodes[2].innerHTML - 1) + ',' + dataNode.childNodes[0].innerHTML;
        //alert(dataNode.outerHTML + '\n\n' + dataPropertyStr);
        pageManager.backgroundFetchList.push(dataPropertyStr);
      }
      
      // and initialise the slideshow of the 'Tour the Clinic' tab
      if (positioning.getObject('imageLibrary') != null) {
        var collNode = positioning.getObject('imageLibrary');
        this.tabs.item[1].slideshow.init(collNode);
      }
      // and initialise the document list of the 'Document Library' tab
      if (positioning.getObject('documentLibrary') != null) {
        var collNode = positioning.getObject('documentLibrary');
//        alert(collNode.innerHTML);
        this.tabs.item[2].library.init(collNode);
      }
    }
    
    if (positioning.getObject('sectionObject') != null) {
      this.subjects.init(positioning.getObject('sectionObject'));
      // after the final Section page has been loaded, activate the app by displaying the Close/Start buttons on the splash screen
      if (this.subjects.item.length == 1 && this.splashScreen) {
        this.splashScreen.showButtons();
      }
    }
    
    if (positioning.getObject('questionObject') != null) {
      this.subjects.initTopic(positioning.getObject('questionObject').childNodes[0]);
    }
    
    // Now, check for any child ids to be added to the background processing list
    if (positioning.getObject('children') != null) {
      // add items to the background processing list
      var coll = positioning.getObject('children');
      
      // and add any topic objects to the background processing list
      for (var i=0; i<coll.childNodes.length; i++) {
        var dataNode = coll.childNodes[i];
        //                    <objId>,<className>,<isLeaf>,<index>,<parentId>
        //var dataPropertyStr = dataNode.attributes[0].nodeValue + ',' + dataNode.childNodes[4].innerHTML + ',' + dataNode.childNodes[5].innerHTML + ',' + (dataNode.childNodes[2].innerHTML - 1) + ',' + dataNode.childNodes[0].innerHTML;
        var dataPropertyStr = dataNode.attributes.getNamedItem('id').nodeValue + ',' + dataNode.childNodes[4].innerHTML + ',' + dataNode.childNodes[5].innerHTML + ',' + (dataNode.childNodes[2].innerHTML - 1) + ',' + dataNode.childNodes[0].innerHTML;
        pageManager.backgroundFetchList.push(dataPropertyStr);
      }
      //alert(pageManager.backgroundFetchList);
    }
    
    // and, finally, clean up the working objects and ui notification
    this.contentPane.removeChild(newContent);

    // CALL THE BACKGROUND LOADER
    this.processBackgroundFetchList();
  }

}