/*
    Contains common JS functions for use by LiveSite components, including
    required functions for components distributed in foundation.spar.
*/

// wrap in private namespace (does not require Ext)
var IW_FOUNDATION = function() {

  // holds initiation code for components to be executed on page load
  var inits = new Array();
  
  
  // AJAX request vars
  var MSXMLHttpLabels = [
    "MSXML2.XMLHttp.5.0",
    "MSXML2.XMLHttp.4.0",
    "MSXML2.XMLHttp.3.0",
    "MSXML2.XMLHttp",
    "Microsoft.XMLHttp"];
  MSXMLHttpKey=-1; // so we don't have to check every time
  var READY_STATE_UNINITIALIZED = 0;
  var READY_STATE_LOADING = 1;
  var READY_STATE_LOADED = 2; // not safe on all browsers
  var READY_STATE_INTERACTIVE = 3; // not safe on all browsers
  var READY_STATE_COMPLETE = 4;



  return {

    // add initiation code to the list of calls to be executed on page load
    addInit: function(initCode) {
      inits[inits.length] = initCode;
    },
    
    // client error reporting here - use an empty method to squelch errors
    showError: function(e) {
      alert(e);
    },

    // initialization code - run once on startup of the page
    init: function(arg) {
      
      // initialize the individual components if they used addInit()
      for (i=0; i<inits.length; i++) {
        try {
          eval(inits[i]);
        } catch (e) {
          IW_FOUNDATION.showError(inits[i] + " : " + e);
        }
      }
      
    },
    
    
    
    /* Functions below contain AJAX related JavaScript.
       Example of AJAX usage:
        function sendReq() {
          var req = IW_FOUNDATION.createGet("ajaxServerUrl");
          IW_FOUNDATION.registerResponseAction(req, "myCallback");
          req.send(null);
        }
    
        function myCallback(res) {
          var aHeader = res.getResponseHeader("Content-Type");
          var text = res.responseText;
          var xmlDOM = res.responseXML;
          // do something with response
        }
    */
    // create an AJAX request
    createRequest: function(reqType, targetURL, isAsync) {
      var req = null;
      if (typeof XMLHttpRequest != "undefined") {
        // IE7, mozilla, firefox, safari, opera
        req = new XMLHttpRequest();
      }
      else if (window.ActiveXObject) {
        // MSIE 6 and lower
        if (MSXMLHttpKey==-1) {
          for (i=0; i<MSXMLHttpLabels.length; i++) {
            try {
              req = new ActiveXObject(MSXMLHttpLabels[i]);
              MSXMLHttpKey = i;
              break;
            } catch (e) {
              // try next version
            }
          }
        }
        else {
          req = new ActiveXObject(MSXMLHttpLabels[MSXMLHttpKey]);
        }
      }
      if (req!=null) {
        if (reqType) {
          req.open(reqType, targetURL, isAsync);
        }
        return req;
      }
    },
    
    // create an AJAX GET request
    createGet: function(targetURL, isAsync) {
      var async = true; // default to async
      if (isAsync!=null && isAsync==false) async = false;
      return IW_FOUNDATION.createRequest ("get", targetURL, async);
    },
    
    // create an AJAX POST request
    createPost: function(targetURL, isAsync) {
      var async = true; // default to async
      if (isAsync!=null && isAsync==false) async = false;
      return IW_FOUNDATION.createRequest ("post", targetURL, async);
    },
    
    // register a callback function for an AJAX request completion
    registerResponseAction: function(httpRequest, functionName, allowBadResponses) {
      if (!allowBadResponses) {
        httpRequest.onreadystatechange = function() {
          if (httpRequest.readyState==READY_STATE_COMPLETE && httpRequest.status==200) {
            eval(functionName+"(httpRequest)");
          }
        }
      } else {
        httpRequest.onreadystatechange = function() {
          if (httpRequest.readyState==READY_STATE_COMPLETE) {
            eval(functionName+"(httpRequest)");
          }
        }
      }
    },
    
    // register all callback functions for an AJAX request
    registerAllResponseActions: function(httpRequest, functionNames) {
      httpRequest.onreadystatechange = function() {
        if (httpRequest.readyState==READY_STATE_UNINITIALIZED && functionNames[READY_STATE_UNINITIALIZED]!=null){
          eval(functionNames[READY_STATE_UNINITIALIZED]+"(httpRequest)");
        }
        else if (httpRequest.readyState==READY_STATE_LOADING && functionNames[READY_STATE_LOADING]!=null){
          eval(functionNames[READY_STATE_LOADING]+"(httpRequest)");
        }
        else if (httpRequest.readyState==READY_STATE_LOADED && functionNames[READY_STATE_LOADED]!=null){
          eval(functionNames[READY_STATE_LOADED]+"(httpRequest)");
        }
        else if (httpRequest.readyState==READY_STATE_INTERACTIVE && functionNames[READY_STATE_INTERACTIVE]!=null){
          eval(functionNames[READY_STATE_INTERACTIVE]+"(httpRequest)");
        }
        else if (httpRequest.readyState==READY_STATE_COMPLETE && functionNames[READY_STATE_COMPLETE]!=null){
          eval(functionNames[READY_STATE_COMPLETE]+"(httpRequest)");
        }
      }
    },

    // Loads a client cookie using the given name and returns its value.
    getCookie: function(cookieName) {
      var cookieString = document.cookie;
      if (cookieString!=null) {
        var cookieCrumbs = cookieString.split(";");
        var key = cookieName + "=";
        var crumbOffset = 0;
        for (c=0; c<cookieCrumbs.length; c++) {
          var crumb = cookieCrumbs[c];
          var pos = crumb.indexOf(key);
          if (pos!=-1) {
            return unescape(crumb.substring(key.length+crumbOffset));
          }
          crumbOffset = 1;
        }
      }
      return null;
    },
    
    // Saves a cookie to the client using the given name, value,
    // and optional lifespan in days.  If no lifespan is given,
    // the cookie will be terminate at the end of the session.
    setCookie: function(cookieName, cookieValue, cookieLifespan) {
      var cookieString = cookieName+"="+escape(cookieValue);
      if (cookieLifespan) {
        var endDate = new Date();
        var t = endDate.getTime() + (cookieLifespan*24*60*60*1000);
        endDate.setTime(t);
        cookieString += "; expires=" + endDate.toGMTString();
      }
      cookieString += "; path=/";
      document.cookie = cookieString;
    },
    
    // Removes a cookie from the client.
    expireCookie: function(cookieName) {
      IW_FOUNDATION.setCookie(cookieName, "", -1);
    },
    
    // Strips leading and trailing spaces from a string.
    trim: function(input) {
      if (input==null || input=="") {
        return input;
      }
      var t = input;
      try {
        while (t.charAt(0)==" ") {
          t = t.substring(1);
        }
      } catch (e) {}
      try {
        while (t.charAt(t.length-1)==" ") {
          t = t.substring(0,t.length-1);
        }
      } catch (e) {}
      return t;
    },


    Browser: {

      name : null,
      version : null,
      os : null,

      userAgent : navigator.userAgent,
      appName : navigator.appName,
      appVersion : navigator.appVersion,
      product : navigator.product,
      vendor : (""+navigator.vendor).toLowerCase(),
      platform : (""+navigator.platform).toLowerCase(),

      setName: function(n) {
        this.name = n;
      },
      setVersion: function(v) {
        try {
          this.version = parseFloat(v);
        } catch(e) {
          this.version = -1;
        }
      },
      setOs: function(o) {
        this.os = o;
      },
      toString: function() {
        return this.name + " " + this.version + " for " + this.os;
      },

      detect: function() {
    
        // Determine Name and Version
        try {
          if (this.userAgent.indexOf("Opera")!=-1 && window.opera) { // Opera
            this.setName("Opera");
            this.setVersion(this.userAgent.substring(this.userAgent.indexOf("Opera")+6));
          } else if (this.vendor.indexOf("apple")!=-1) { // Safari
            this.setName("Safari");
            this.setVersion(this.appVersion);
          } else if (this.vendor.indexOf("camino")!=-1) { // Camino
            this.setName("Camino");
            this.setVersion(this.appVersion);
          } else if (this.vendor.indexOf("kde")!=-1) { // Konquerer
            this.setName("Konqueror");
            this.setVersion(this.appVersion);
          } else if (this.userAgent.indexOf("MSIE")!=-1 && document.all) { // Internet Explorer
            this.setName("MSIE");
            this.setVersion(this.userAgent.substring(this.userAgent.indexOf("MSIE")+4));
          } else if (this.userAgent.indexOf("Firefox")!=-1) { // Firefox
            this.setName("Firefox");
            this.setVersion(this.userAgent.substring(this.userAgent.indexOf("Firefox")+8));
          } else if (product=="Gecko") { // Netscape 6.x / Mozilla / other Gecko-based
            this.setName("Mozilla");
            this.setVersion(this.userAgent.substring(this.userAgent.indexOf("rv")+3));
          } else if (this.appName=="Netscape" && document.layers) { // Netscape 4.x
            this.setName("Netscape")
            this.setVersion(this.appVersion);
          } else { // Other
            this.setName(this.appName);
            this.setVersion(this.appVersion);
          }
        } catch(e) {
          this.setName("unknown");
          this.setVersion(-1);
        }
    
        // Determine OS
        try {
          if (this.platform.indexOf("win")!=-1) {
            this.setOs("Windows");
          } else if (this.platform.indexOf("mac")!=-1) {
            this.setOs("MacOS");
          } else if (this.platform.indexOf("linux")!=-1) {
            this.setOs("Linux");
          } else if (this.platform.indexOf("unix")!=-1
                  || this.platform.indexOf("sunos")!=-1
                  || this.platform.indexOf("bsd")!=-1
                  || this.platform.indexOf("sco")!=-1) {
            this.setOs("Unix");
          } else {
            this.setOs("unknown");
          }
        } catch(e) {
          this.setOs("unknown");
        }

      }  // end detect method

    } // end Browser object




	};
}();
IW_FOUNDATION.Browser.detect();

try {
  // if using Ext...
  
  // points to 1x1 transparent spacer image used for styling
  Ext.BLANK_IMAGE_URL = '../images/default/s.gif';

  // creates private Ext namespace to accompany IW_FOUNDATION
  // Note: not all implementations will use Ext
  Ext.namespace('IW', 'IW.FOUNDATION');
  
  // run init in the Ext.onReady event handler
  Ext.onReady(IW_FOUNDATION.init);
} catch (NoExt) {
  // if not using Ext, run init from the browser built in event handlers
  
  if (window.attachEvent) { 
    // MSIE & Opera
    window.attachEvent('onload',IW_FOUNDATION.init);
  } else if (window.addEventListener) {
    // Firefox, Opera, & most other modern browsers
    window.addEventListener('load', IW_FOUNDATION.init, false);
  } else {
    // legacy fallback using 3 second delay instead of page load
    // Don't use document.body.onload=IW_FOUNDATION.init
    // to define it directly, inline calls may be overwritten.
    setTimeout('IW_FOUNDATION.init()', 3000);
  }
  
  
}

