﻿/// <reference name="MicrosoftAjax.debug.js" />
/// <reference path="../MicrosoftAjaxAdoNet.debug.js" />
/// <reference path="../MicrosoftAjaxTemplates.debug.js" />

// Author: Kris
// Project: C:\code\RealosophyDotCom\RealosophyV2\
// Path: C:\code\RealosophyDotCom\RealosophyV2\javascripts\RealFramework
// Lines: 253
// Creation date: 8/30/2008 10:11 PM
// Last modified: 12/29/2008 1:11 AM

// Register our namespaces
Type.registerNamespace("Realosophy");
Type.registerNamespace("Realosophy.Web");
Type.registerNamespace("Realosophy.Web.Client");

Realosophy.Web.Client._System = function() 
{
  Realosophy.Web.Client._System.initializeBase(this);
  
  this._viewports = []; // Holds an array of Web Parts on a page for synchronization
  this._services = [];  // Holds an array of Application Services used by the applications (i.e. Maps, Search)
}

Realosophy.Web.Client._System.prototype =
{
  initialize: function() {
    Sys.Debug.trace("Initialize of Realosophy.Web.Client._System called.");
  },

  /* Start Properties */
  get_IsLocalhost: function() {
    return window.location.host.match(/^.*\b(localhost)\b.*$/);
  },
  
  get_IsTest: function() {
    return window.location.host.match(/^.*\b(test\.realosophy\.com)\b.*$/) || window.location.host.match(/^.*\b(cloudapp\.net)\b.*$/);
  },

  get_IsProduction: function() {
    return window.location.host.match(/^.*\b(realosophy\.com)\b.*$/);
  },

  get_currentHostName: function() {
    var currentHostName = window.location.host;
    if (this.get_IsLocalhost())
      currentHostName += "";
    else if (this.get_IsTest())
      currentHostName += "";

    return currentHostName;
  },

  get_viewport: function(viewportID) {
  },

  get_service: function(serviceName) {
    try {
      return this._services[serviceName];
    } catch (e) {
      trace(e);
    }
  },
  /* End Properties */

  /* Start Methods */
  registerViewport: function(viewport) {
    // TODO: Add a check for service interface
  },

  unregisterViewport: function(viewport) {
  },

  invokeGetWebRequest: function(getPage, onSuccess, userContext) {
    var wRequest = new Sys.Net.WebRequest();
    // Set the request Url.  
    wRequest.set_url(getPage);

    // Set the request verb.
    wRequest.set_httpVerb("GET");

    // Set the web request completed event handler,
    // for processing return data.
    wRequest.add_completed(onSuccess);

    if (userContext)
      wRequest.set_userContext(userContext);

    // Execute the request.
    wRequest.invoke();
  },

  add_service: function(serviceName, servicePtr) {
    if (Realosophy.Web.Client.IService.isImplementedBy(servicePtr))
      this._services[serviceName] = servicePtr;
    else
      this.trace("servicePtr must implement the Realosophy.Web.Client.IService Interface");
  },

  remove_service: function(serviceName) {
  },

  trace: function(e) {
    if (RealSystem.get_IsLocalhost())
      Sys.Debug.trace(e);
  },

  traceDump: function(e) {
    if (RealSystem.get_IsLocalhost())
      Sys.Debug.traceDump(e);
  },

  /**
  * Mimics the .NET function Page.ResolveClientUrl providing a relative reference to the root folder
  * @param url The URL that should be rebased.  Must start with a tilde (~) character
  */
  resolveClientUrl: function(url) {
    var result = "http://" + this.get_currentHostName();
    if (url.indexOf('~') >= 0) {  // Found a Tilde
      if (this.get_IsTest())
        result += url.substr(1, url.length - 1);
      else if (this.get_IsProduction())
        result += url.substr(1, url.length - 1);
      else
        result += url.substr(1, url.length - 1);
    }
    return result;
  },

  /**
  * Opens a popup window
  * @param url The URL that the popup should fetch
  * @param name The name of the popup window.  Repeat calls with the same name result
  * in the reuse of the named window.
  * @param height The height of the popup window
  * @param width The width of the popup window
  * @param options See javascript window.open for further details.
  */
  openWindow: function(url, name, height, width, options) {
    if (name == "")
      this.trace("name param must specify the name of the window.");
    if (url == "")
      this.trace("url param must specify the URL to open.");

    if (options == "")
      options = "menubar=no,toolbar=no,scrollbars,resizable";

    this._popupWindow = window.open(url, name, 'height=' + height + ',width=' + width + "," + options)

    if (this._popupWindow) // Need to check due to popup blockers.
      this._popupWindow.focus();

    return false;
  },

  URLEncode: function(plaintext) {
    // The Javascript escape and unescape functions do not correspond
    // with what browsers actually do...
    var SAFECHARS = "0123456789" + 				// Numeric
					  "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + // Alphabetic
					  "abcdefghijklmnopqrstuvwxyz" +
					  "-_.!~*'()"; 				// RFC2396 Mark characters
    var HEX = "0123456789ABCDEF";

    var encoded = "";
    for (var i = 0; i < plaintext.length; i++) {
      var ch = plaintext.charAt(i);
      if (ch == " ") {
        encoded += "+"; 			// x-www-urlencoded, rather than %20
      } else if (SAFECHARS.indexOf(ch) != -1) {
        encoded += ch;
      } else {
        var charCode = ch.charCodeAt(0);
        if (charCode > 255) {
          alert("Unicode Character '"
                          + ch
                          + "' cannot be encoded using standard URL encoding.\n" +
				            "(URL encoding only supports 8-bit characters.)\n" +
						    "A space (+) will be substituted.");
          encoded += "+";
        } else {
          encoded += "%";
          encoded += HEX.charAt((charCode >> 4) & 0xF);
          encoded += HEX.charAt(charCode & 0xF);
        }
      }
    } // for
    return encoded;
  },

  URLDecode: function(encoded) {
    // Replace + with ' '
    // Replace %xx with equivalent character
    // Put [ERROR] in output if %xx is invalid.
    var HEXCHARS = "0123456789ABCDEFabcdef";
    var plaintext = "";
    var i = 0;
    while (i < encoded.length) {
      var ch = encoded.charAt(i);
      if (ch == "+") {
        plaintext += " ";
        i++;
      } else if (ch == "%") {
        if (i < (encoded.length - 2)
					  && HEXCHARS.indexOf(encoded.charAt(i + 1)) != -1
					  && HEXCHARS.indexOf(encoded.charAt(i + 2)) != -1) {
          plaintext += unescape(encoded.substr(i, 3));
          i += 3;
        } else {
          alert('Bad escape combination near ...' + encoded.substr(i));
          plaintext += "%[ERROR]";
          i++;
        }
      } else {
        plaintext += ch;
        i++;
      }
    } // while
    return plaintext;
  },

  /**
  * Cleans up any resources consumed by the RealSystem object.  An override 
  * from Sys.Component that is automatically called by the ASP.NET AJAX Runtime.
  */
  dispose: function() {
    this.trace("Dispose has been called.  Killing " + this._services.length + " Services");
    for (var i in this._services) {
      this._services[i].dispose();
      delete this._services[i];
    }
  }
  /* End Methods */

  /* Start Event Delegates */
  /* End Event Delegates */
}

Realosophy.Web.Client._System.registerClass('Realosophy.Web.Client._System', Sys.Component, Sys.IDisposable);
RealSystem = new Realosophy.Web.Client._System();

/**
 * Define the standard interface for a Service that can be handled by the RealSystem class
 */
Realosophy.Web.Client.IService = function() 
{
  this.get_ServiceNameKey = Function.abstractMethod;
  this.get_ServiceName = Function.abstractMethod;
  this.get_ServiceDescription = Function.abstractMethod;
}
Realosophy.Web.Client.IService.registerInterface('Realosophy.Web.Client.IService');

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();