﻿///////////////////////////////////////////////////////////////////////////////
//
//  wcoDataPortal.js
//
// © 2007-2010 Wco iEnterprise Solutions Pty Ltd. ALL RIGHTS RESERVED.
// This file is licensed as part of the Wco DataPortal 3.0 Web Presence Solution, for details look here: http://www.wco.com.au
//
///////////////////////////////////////////////////////////////////////////////

var dataportal = {
  parent: null,
  sessionIsNew: true,
  session: {
    SessionId: '',
    ClientGuid: '',
    IPAddress: '',
    PortalGuid: '',
    PortalId: 0,
    WebSiteId: 0,
    UserGuid: '',
    UserId: 0,
    UserFirstName: '',
    UserLastName: '',
    DefaultCultureId: 3081,
    DefaultCultureCode: 'en-AU',
    DefaultCultureName: 'English (Australia)',
    UserCultureId: 3081,
    UserCultureCode: 'en-AU',
    UserCultureName: 'English (Australia)',
    UserIsAnonymous: true,
    UserIsAuthenticated: false,
    UserRoles: ["Anonymous Site Visitor"]
  },
  currentQuery: {
    IsSuccess: false,
    Name: "FetchCurrentObject"
  },
  currentObject: null,
  childCollection: null,

  request: null,
  isRequestCanceled: false,
  queryResponse: '',
  queryResponseContentType: '',
  executeCallback: null,

  requestSslUrl: 'http://localhost/CS2009.SSL/Default.htm',
  sslOneTimeKey: '',
  isSecureConnection: false,
  isAspxError: false
};

/*<remarks>
Method: init
Description: Initialises the dataportal object, making it ready to receive and process calls.
Parameters:
parent: [Required] a reference to the parent object that contains the business rules on how to process the data retrieved from the DataPortal
isPaginationEnabledByDefault: [Optional] true/false flag indicating whether to fetch children of the current object in paginated batches or all together
paginationDefaultClassName: [Optional] the name of the default class to which pagination is to be applied
initialObjectId: [Optional] the id of the object to be retrieved from the DataPortal
</remarks>*/
dataportal.init = function (parent, portalGuid, websiteId, languageCultureName) {
  this.parent = parent;

  // initialise the session properties
  this.session.PortalGuid = portalGuid;
  this.session.WebSiteId = websiteId;

  if (languageCultureName != null) {
    this.session.UserCultureCode = languageCultureName;
  }
};

dataportal.setCallback = function (pointer) {
  this.executeCallback = pointer;
};

dataportal.fetchCurrentObject = function (parentClassTypeId,
                                          parentId,
                                          parentCustomObjectId,
                                          classTypeId,
                                          className,
                                          classId,
                                          objId) {
  this.currentQuery.Name = 'FetchCurrentObject';

  // prepare the xml-encoded request string to be sent to the DataPortal Wizard
  var sInput = '<?xml version="1.0" encoding="utf-8" standalone="yes" ?>';
  sInput += '<wcoDataPortal>';

  sInput += '<session>';
  sInput += '<portalGuid>' + this.session.PortalGuid + '</portalGuid>';
  sInput += '<websiteId>' + this.session.WebSiteId + '</websiteId>';
  if (this.session.UserGuid != '') {
    sInput += '<userGuid>' + this.session.UserGuid + '</userGuid>';
    sInput += '<sessionId>' + this.session.SessionId + '</sessionId>';
    sInput += '<clientGuid>' + this.session.ClientGuid + '</clientGuid>';
  }
  if (this.sslOneTimeKey != '') {
    sInput += '<sslOneTimeKey>' + this.sslOneTimeKey + '</sslOneTimeKey>';
  }
  sInput += '<sessionIsAuthenticated>' + this.session.UserIsAuthenticated.toString().replace(/t/, 'T').replace(/f/, 'F') + '</sessionIsAuthenticated>';
  if (this.session.UserCultureCode != '') {
    sInput += '<sessionLanguageCultureName>' + this.session.UserCultureCode + '</sessionLanguageCultureName>';
  }
  sInput += '</session>';

  sInput += '<action>' + this.currentQuery.Name + '</action>';

  sInput += '<currentObject>';

  sInput += '<parentClassTypeId>' + parentClassTypeId + '</parentClassTypeId>';
  sInput += '<parentId>' + parentId + '</parentId>';
  sInput += '<parentCustomObjectId>' + parentCustomObjectId + '</parentCustomObjectId>';
  sInput += '<classTypeId>' + classTypeId + '</classTypeId>';
  sInput += '<className>' + className + '</className>';
  sInput += '<classId>' + classId + '</classId>';
  sInput += '<objId>' + objId + '</objId>';

  sInput += '</currentObject>';
  sInput += '</wcoDataPortal>';

  //alert(sInput);
  this.httpRequest('POST', 'DataServer.aspx', true, sInput);
};

dataportal.signIn = function (userEmail,
                              userPassword,
                              persistenceLevel) {
  persistenceLevel = 0;
  this.currentQuery.Name = 'SignIn';

  // prepare the xml-encoded request string to be sent to the DataPortal Wizard
  var sInput = '<?xml version="1.0" encoding="utf-8" standalone="yes" ?>';
  sInput += '<wcoDataPortal>';

  sInput += '<session>';
  sInput += '<portalGuid>' + this.session.PortalGuid + '</portalGuid>';
  sInput += '<websiteId>' + this.session.WebSiteId + '</websiteId>';
  if (this.session.UserGuid != '') {
    sInput += '<userGuid>' + this.session.UserGuid + '</userGuid>';
    sInput += '<sessionId>' + this.session.SessionId + '</sessionId>';
    sInput += '<clientGuid>' + this.session.ClientGuid + '</clientGuid>';
  }
  if (this.sslOneTimeKey != '') {
    sInput += '<sslOneTimeKey>' + this.sslOneTimeKey + '</sslOneTimeKey>';
  }
  sInput += '<sessionIsAuthenticated>' + this.session.UserIsAuthenticated.toString().replace(/t/, 'T').replace(/f/, 'F') + '</sessionIsAuthenticated>';
  if (this.session.UserCultureCode != '') {
    sInput += '<sessionLanguageCultureName>' + this.session.UserCultureCode + '</sessionLanguageCultureName>';
  }
  sInput += '</session>';

  sInput += '<action>' + this.currentQuery.Name + '</action>';

  sInput += '<userAuth>';
  sInput += '<userEmail>' + userEmail + '</userEmail>';
  sInput += '<userPassword>' + userPassword + '</userPassword>';
  sInput += '<persistenceLevel>' + persistenceLevel + '</persistenceLevel>';
  sInput += '</userAuth>';

  sInput += '</wcoDataPortal>';

  //alert(sInput);
  this.httpRequest('POST', 'DataServer.aspx', true, sInput);
};

/*<remarks>
Method: fetchObject
Description: Takes the passed object id and retrieves all data required from the DataPortal to display a new language title page.
Parameters:
[0] objectId: [Required] the id of the object to be retrieved from the DataPortal
[1] currentObjectClass: [Required] the class of the current object being fetched - this property determines which page to be built by the DataPortal wizard
[2] currentObjectClassIsLeaf: [Required] flag indicating whether the current object is a leaf class or not - this property is used to control the identification of the relevant parent object of the leaf objects being fetched
[3] isPaginationEnabled: [Optional] true/false flag indicating whether to fetch children of the current object in paginated batches or all together
[4] paginationClassName: [Optional] the name of the default class to which pagination is to be applied
[5] paginationItemCount: [Optional] the number of items per paginated fetch to be retrieved
[6] paginationPageNo: [Optional] the paginated page number
[7] sessionLanguageCultureName: [Optional] the ll-rr name of the current language, e.g. en-AU
[8] isSignInFlagSet: [Optional] indicates whether the SignIn flag was retrieved from the url query string (if sent by the SSL application)
</remarks>*/
//dataportal.fetchObject = function () {

//  var objectId = 0;
//  this.isPaginationEnabled = false;
//  this.paginationPageNo = 1;
//  if (arguments[0]) { objectId = arguments[0]; }
//  if (arguments[3] != null) { this.isPaginationEnabled = arguments[3]; }
//  if (arguments[4] != null) { this.paginationClassName = arguments[4]; }
//  if (arguments[5] != null) { this.paginationItemCount = arguments[5]; }
//  if (arguments[6] != null) { this.paginationPageNo = arguments[6]; }
//  if (arguments[7] != null) { this.sessionLanguageCultureName = arguments[7]; }


//  if (objectId > 0) {
//    this.currentObjectId = objectId;
//    this.currentObjectClass = arguments[1];
//    this.currentObjectClassIsLeaf = arguments[2];
//    if (!this.currentObjectClassIsLeaf) {
//      this.previousObjectId = this.currentObjectId;
//    }

//    this.currentRequestAction = 'FetchCurrentObject';

//    // prepare the xml-encoded request string to be sent to the DataPortal Wizard
//    var sInput = '<?xml version="1.0" encoding="utf-8" standalone="yes" ?>';
//    sInput += '<wcoDataPortal>';

//    sInput += '<session>';
//    sInput += '<portalGuid>' + this.portalGuid + '</portalGuid>';
//    sInput += '<websiteId>' + this.websiteId + '</websiteId>';
//    if (this.sessionUserGuid != '') {
//      sInput += '<userGuid>' + this.sessionUserGuid + '</userGuid>';
//      sInput += '<sessionId>' + this.sessionId + '</sessionId>';
//      sInput += '<clientGuid>' + this.sessionClientGuid + '</clientGuid>';
//    }
//    if (this.sslOneTimeKey != '') {
//      sInput += '<sslOneTimeKey>' + this.sslOneTimeKey + '</sslOneTimeKey>';
//    }
//    sInput += '<sessionIsAuthenticated>' + this.sessionIsAuthenticated.toString().replace(/t/, 'T').replace(/f/, 'F') + '</sessionIsAuthenticated>';
//    if (this.sessionLanguageCultureName != '') {
//      sInput += '<sessionLanguageCultureName>' + this.sessionLanguageCultureName + '</sessionLanguageCultureName>';
//    }
//    sInput += '</session>';

//    sInput += '<action>' + this.currentRequestAction + '</action>';

//    sInput += '<currentObject>';
//    sInput += '<className>' + this.currentObjectClass + '</className>';
//    if (this.isPaginationEnabled) {
//      sInput += '<pagination isEnabled="True">';
//      sInput += '<appliesTo>' + this.paginationClassName + '</appliesTo>';
//      sInput += '<pageSize>' + this.paginationItemCount + '</pageSize>';
//      sInput += '<pageNo>' + this.paginationPageNo + '</pageNo>';
//      sInput += '</pagination>';
//    }
//    sInput += '<objId>' + this.currentObjectId + '</objId>';
//    //sInput += '<parentId>' + this.previousObjectId + '</parentId>';
//    sInput += '<parentId>' + this.currentParentId + '</parentId>';
//    sInput += '</currentObject>';
//    sInput += '</wcoDataPortal>';

//    //alert(sInput);
//    this.httpRequest('POST', 'DataServer.aspx', true, sInput);
//  }
//};

/*<remarks>
Method: execute
Description: Takes the passed email address and password and attempts to signin to the DataPortal.
Parameters:
action: [Required] the user email address registered with the DataPortal
inputXmlStr: [Required] the password of the user account registered with the DataPortal
</remarks>*/
//dataportal.execute = function(action, inputXmlStr, callback) {
//  
//  if (action == null || action == '' || inputXmlStr == null) {
//    // cannot attempt request
//    alert('CANNOT PROCEED\n\nNo input provided.');
//    return (false);
//  }
//  else {
//    this.currentRequestAction = action;
//    if (callback != null) {
//      this.executeCallback = callback;
//    }
//    else {
//      this.executeCallback = null;
//    }
//    //alert(this.executeCallback);
//    
//    // prepare the xml-encoded request string to be sent to the PageBuilder Wizard
//    var sInput = '<?xml version="1.0" encoding="utf-8" standalone="yes" ?>';
//    sInput += '<wcoDataPortal>';

//    sInput += '<session>';
//    sInput += '<portalGuid>' + this.portalGuid + '</portalGuid>';
//    sInput += '<websiteId>' + this.websiteId + '</websiteId>';
//    sInput += '<userGuid>' + this.sessionUserGuid + '</userGuid>';
//    sInput += '<sessionId>' + this.sessionId + '</sessionId>';
//    sInput += '<clientGuid>' + this.sessionClientGuid + '</clientGuid>';
//    if (this.sslOneTimeKey != '') {
//      sInput += '<sslOneTimeKey>' + this.sslOneTimeKey + '</sslOneTimeKey>';
//    }
//    sInput += '<sessionIsAuthenticated>' + this.sessionIsAuthenticated.toString().replace(/t/, 'T').replace(/f/, 'F') + '</sessionIsAuthenticated>';
//    sInput += '<sessionLanguageCultureName>' + this.sessionLanguageCultureName + '</sessionLanguageCultureName>';
//    sInput += '</session>';
//    
//    sInput += '<action>' + this.currentRequestAction + '</action>';
//    
//    sInput += '<currentObject>';
//    sInput += '<className>' + this.currentObjectClass + '</className>';
//    if (this.isPaginationEnabled) {
//      sInput += '<pagination isEnabled="True">';
//      sInput += '<appliesTo>' + this.paginationClassName + '</appliesTo>';
//      sInput += '<pageSize>' + this.paginationItemCount + '</pageSize>';
//      sInput += '<pageNo>' + this.paginationPageNo + '</pageNo>';
//      sInput += '</pagination>';
//    }
//    sInput += '<objId>' + this.currentObjectId + '</objId>';
//    sInput += '<parentId>' + this.previousObjectId + '</parentId>';
//    sInput += '</currentObject>';
//    
//    sInput += '<input>';
//    sInput += inputXmlStr;
//    sInput += '</input>';
//    sInput += '</wcoDataPortal>';
//    //alert(sInput);
//    
//    this.httpRequest('POST', 'DataServer.aspx', true, sInput);
//  }
//};

dataportal.execute = function (action, inputXmlStr, objXmlStr, callback) {

  if (action == null || action == '' || (inputXmlStr == null && objXmlStr == null)) {
    // cannot attempt request
    alert('CANNOT PROCEED\n\nNo input provided.');
    return (false);
  }
  else {
    this.currentRequestAction = action;
    if (callback != undefined) {
      this.executeCallback = callback;
    }
    else {
      this.executeCallback = null;
    }
    //alert(this.executeCallback);

    // prepare the xml-encoded request string to be sent to the PageBuilder Wizard
    var sInput = '<?xml version="1.0" encoding="utf-8" standalone="yes" ?>';
    sInput += '<wcoDataPortal>';

    sInput += '<session>';
    sInput += '<portalGuid>' + this.portalGuid + '</portalGuid>';
    sInput += '<websiteId>' + this.websiteId + '</websiteId>';
    sInput += '<userGuid>' + this.sessionUserGuid + '</userGuid>';
    sInput += '<sessionId>' + this.sessionId + '</sessionId>';
    sInput += '<clientGuid>' + this.sessionClientGuid + '</clientGuid>';
    sInput += '<sessionIsAuthenticated>' + this.sessionIsAuthenticated.toString().replace(/t/, 'T').replace(/f/, 'F') + '</sessionIsAuthenticated>';
    sInput += '<cultureId>' + this.sessionCultureId + '</cultureId>';
    sInput += '</session>';

    sInput += '<action>' + this.currentRequestAction + '</action>';

    if (objXmlStr != null) {
      sInput += objXmlStr;
    }
    //    sInput += '<currentObject>';
    //    sInput += '<className>' + this.currentObjectClass + '</className>';
    //    if (this.isPaginationEnabled) {
    //      sInput += '<pagination isEnabled="True">';
    //      sInput += '<appliesTo>' + this.paginationClassName + '</appliesTo>';
    //      sInput += '<pageSize>' + this.paginationItemCount + '</pageSize>';
    //      sInput += '<pageNo>' + this.paginationPageNo + '</pageNo>';
    //      sInput += '</pagination>';
    //    }
    //    sInput += '<objId>' + this.currentObjectId + '</objId>';
    //    sInput += '<parentId>' + this.previousObjectId + '</parentId>';
    //    sInput += '</currentObject>';

    sInput += '<input>';
    sInput += inputXmlStr;
    sInput += '</input>';
    sInput += '</wcoDataPortal>';
    //    alert(sInput);

    this.httpRequest('POST', 'DataServer.aspx', true, sInput);
  }
};

dataportal.cancelRequest = function () {
  dataportal.isRequestCanceled = true;
  this.executeCallback = null;
  if (this.request != null) {
    this.request.abort();
    this.request = null;
  }
}

dataportal.fetchCurrentObjectRequestHandler = function () {


  if (dataportal.request && !dataportal.isRequestCanceled) {

    if (dataportal.request.readyState == 4) {
      if (dataportal.request.status != 200)
      {
        alert(dataportal.request.status + ': ' + dataportal.request.statusText + '\n' + dataportal.request.responseText);
      }
      else {
        // the xmlhttp request has completed
        if (dataportal.request && !dataportal.isCanceled) {
          // confirm that the response is valid
          dataportal.isAspxError = eval(dataportal.request.getResponseHeader('IsAspxError'));

          // retrieve the request data
          var content = dataportal.request.responseText;
          var obj = eval('(' + dataportal.request.responseText + ')');
          dataportal.session = obj.DataPortalResults[0].Session[0];
          dataportal.currentQuery = obj.DataPortalResults[0].CurrentQuery[0];
          dataportal.currentObject = obj.DataPortalResults[0].CurrentObject[0];
          dataportal.childCollection = obj.DataPortalResults[0].ChildCollection;

          if (content == 'Failed' || dataportal.isAspxError) {
            return (false);
          }

          if (!dataportal.currentQuery.IsSuccess) {
            return (false);
          }

          dataportal.request = null;
          dataportal.sessionIsNew = false;

          if (dataportal.executeCallback != null) {
            dataportal.executeCallback(dataportal.currentObject, dataportal.childCollection, dataportal.session);
          }
          else {
            //alert(content);
            //dataportal.parent.displayObject(content);

            //window.document.open();
            //window.document.write(content);
            //window.document.close();

            //var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            //xmlDoc.async = "false";
            //xmlDoc.loadXML(content);
            //alert(xmlDoc.xml);
            //document.write(xmlDoc.xml);
          }

        }
      }
    }

  }

}

/*<remarks>
Method: httpRequest
Description: Wrapper function for constructing an AJAX request object.
Parameters:
reqType: The HTTP request type, such as GET or POST.
url: The URL of the server program.
asynch: Whether to send the request asynchronously or not.
param: The XML-encoded data string to be sent to the backed web service.
</remarks>*/
dataportal.httpRequest = function (reqType, url, asynch, param) {
  if (this.request) { this.request.abort(); this.request = null; }

  this.isRequestCanceled = false;

  //Mozilla-based browsers
  if (window.XMLHttpRequest) {
    this.request = new XMLHttpRequest();
  }
  else if (window.ActiveXObject) {
    this.request = new ActiveXObject("Msxml2.XMLHTTP");
    if (!this.request) {
      this.request = new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
  //the request object could still be null if neither ActiveXObject initialization succeeded
  if (this.request) {
    this.initRequest(reqType, url, asynch, param);
  }
  else {
    alert("Your browser does not permit the use of all " +
          "of this application's features!");
  }
};

/* Initialize a request object that is already constructed */
dataportal.initRequest = function (reqType, url, bool, param) {
  this.request.onreadystatechange = this.fetchCurrentObjectRequestHandler;
  this.request.open(reqType, url, bool);
  this.request.setRequestHeader('CONTENT-TYPE', 'text/utf-8');
  //this.request.setRequestHeader("Content-type", "application/json; charset=utf-8");

  //alert(param);

  // initiate the xmlhttp request
  this.request.send(param);
};


