/// <reference path="BrowserServices.js"/>
/// <reference path="ErrorServices.js"/>
/// <reference path="ClientProxyServices.js"/>

/* *********************************************************************************** 
-  Global variables
************************************************************************************ */                   

//LaunchNetClientContext, main facade to all these lovely javascript services
var __context = null;

//the following are variables for which values are injected by the platform
var __pageLoadEventSubscribers = '';
var __pageClickEventSubscribers = '';
var __validationRequiredCheckSubscribers = '';
var __validateLaunchNetElementsSubscribers = '';

//used for registration; should be set to custom method(s) to call for registration
var RegUserFunct;

//obsc_colldiscriptor properties (do not remove, even if they seem to do nothing!!)
var ScrRes = screen.width + 'x' + screen.height;  //screen resolution
var user_type = '';


//TODO prevent multiple submits?
//var handlingPageClick = false;
//var pageSubmitted = false;

function LaunchNetClientContext(clientProxyServices, errorServices)
{
  //constructor
  this.Init = Init(clientProxyServices, errorServices);
  
  //public methods
  this.CanHaveCookies = CanHaveCookies;
  this.CookieExists = CookieExists;
  this.ExpireSiteIfSessionDead = ExpireSiteIfSessionDead;
  this.IsSessionAlive = IsSessionAlive;
  this.ExpireSite = ExpireSite;
  this.ClientRedirect = ClientRedirect;
  this.UsingService = UsingService;
  this.GetServiceProviders = GetServiceProviders;
  this.GetServiceClientProxy = GetServiceClientProxy;
  this.GetPlatformServicesClientProxy = GetPlatformServicesClientProxy;
  this.GetContentServicesClientProxy = GetContentServicesClientProxy;
  this.GetObservationServicesClientProxy = GetObservationServicesClientProxy;
  this.GetSurveyServicesClientProxy = GetSurveyServicesClientProxy;
  this.GetFicoServicesClientProxy = GetFicoServicesClientProxy;
  this.ThrowError = ThrowError;
  this.RedirectToErrorPage = RedirectToErrorPage;
  
  // Property Getters
  this.GetBrowserServices = GetBrowserServices; 
  function GetBrowserServices()
  {
    return _browserServices;
  }  

  //private members
  var _clientProxyServices;
  var _errorServices;
  var _browserServices;

  //constructor def
  function Init(clientProxyServices, errorServices)
  {
    ExtendObjects();

    var browserServicesFactory = new BrowserServicesFactory();
    _browserServices  = browserServicesFactory.CreateBrowserServices();
    
    _clientProxyServices = clientProxyServices;
    _errorServices = errorServices;
  }
  
  function ExtendObjects()
  {
    //This will fix the deficient string object in JavaScript by
    //adding trim functions to string  
    // ========================================
    //        STRING FUNCTION EXTENTIONS
    // ========================================
    // ========================================
    //            TRIM FUNCTIONS
    // ========================================
    String.prototype.trim = function() 
    {                
      return this.replace(/^\s+|\s+$/g,"");
    }
    String.prototype.ltrim = function() {
      return this.replace(/^\s+/,"");
    }
    String.prototype.rtrim = function() {
      return this.replace(/\s+$/,"");
    }

    // ========================================
    //        ARRAY FUNCTION EXTENTIONS
    // ========================================
    // ========================================
    //          INDEXOF FUNCTIONS
    // ========================================
    // ===========================================================================
    // Function indexOfString - Find the position of the given string in an array. 
    // Parameters: inval - String to loacte in the array.    
    //             begin - Begin position in the array zero based.
    // ===========================================================================
    Array.prototype.indexOfString = function( inval, begin ) 
    {
      for( var i = + begin || 0, l = this.length; i < l; i++ ) 
      {
        if(this.charAt(i).toLowerCase() == inval.toLowerCase())
        {
          return i; 
        }
      }
      return -1;
    };
  
    if (!Array.prototype.contains)
    {
      Array.prototype.contains = function(obj)
      {
        var len = this.length;
        for (var i = 0; i < len; i++)
        {
          if(this[i]===obj)
          {
            return true;
          }
        }
        return false;
      };
    }

    if(!Array.prototype.containsAny)
    {
      Array.prototype.containsAny = function(obj)
      {
        if(isArray(obj))
        {
          for(var i=0;i<obj.length;i++)
          {
            if (this.contains(obj[i]))
            {
              return true;
            }
          }
          return false;
        }
        else
        {
          throw new TypeError();
        }
      }
    }
  }    

  function CanHaveCookies()
  {
    return navigator.cookieEnabled;
  }

  function CookieExists(cookieName)
  {
    var arg = cookieName + "=";
    var arlen = arg.length;
    var clen = document.cookie.length;
    var i = 0;

    while (i < clen)
    {
      var j = i + arlen;
      if(document.cookie.substring(i, j) == arg)
      {
        //cookie found
        return true;
      }
      i = document.cookie.indexOf(" ", i) + 1;
      
      if(i == 0)
      {
        break;
      }

    }
    //no cookie
    return false;        
  }     

  function ExpireSiteIfSessionDead(eventToCancelIfSessionDead)
  {
    if (!IsSessionAlive())
    {
      ExpireSite(eventToCancelIfSessionDead);
    }
  }
  
  function IsSessionAlive()
  {
    return GetPlatformServicesClientProxy().CheckSession().value;
  }
  
  function ExpireSite(eventToCancel)
  {
    //put out alert
    alert("This site has expired.  It will be refreshed by clicking OK.");
    //if this is an event cancel it
    if(eventToCancel != null)
    {
      _browserServices.CancelEvent(eventToCancel);
    }
    ClientRedirect(__homeUrl + "?breadcrumb=" + __sessionPk);
  }
  
  function ClientRedirect(location)
  {
    window.location.href = location;
  }
  
  function UsingService(serviceName)
  {
    return _clientProxyServices.UsingService(serviceName);
  }
  
  function GetServiceProviders()
  {
    return _clientProxyServices.GetServiceProviders();
  }
  
  function GetServiceClientProxy(serviceName)
  {
    return _clientProxyServices.GetServiceClientProxy(serviceName);
  }
  
  function GetPlatformServicesClientProxy()
  {
    return GetServiceClientProxy('PlatformServices');
  }
  
  function GetSurveyServicesClientProxy()
  {
    return GetServiceClientProxy('SurveyServices');
  }
  
  function GetFicoServicesClientProxy()
  {
    return GetServiceClientProxy('FicoServices');
  }
  
  function GetObservationServicesClientProxy()
  {
    return GetServiceClientProxy('ObservationServices');
  }
  
  function GetContentServicesClientProxy()
  {
    return GetServiceClientProxy('ContentServices');
  }
  
  function ThrowError(errorMessage, handleOnServerSide)
  {
    return _errorServices.ThrowError(errorMessage, handleOnServerSide);
  }
  
  function RedirectToErrorPage()
  {
    window.location = __defaultErrorPage;
  }
}

