var Partial = Class.create({
  
  events: [],
  
  /**
   * Constructor...
   * @param {String} domElementId The id of an element to verify.
   */
  initialize: function(partialLoadedId) {
    this.partialLoadedId = partialLoadedId;
    this.onLoadComplete();
    EventManager.addObserver("LoadComplete", this.onLoadComplete, this);
  },
  
  /**
   * Handler for the LoadComplete event.
   * LoadComplete fires when a page is loaded, when an AJAX call completes, 
   * & when cached data is displayed.
   */
  onLoadComplete: function() {
    // verify that the expected DOM elements are loaded for this partial
    // before wiring up the observers
    if (this.uiLoaded()) {
      EventManager.addObservers(this.events, this);
      try {
        this.prepare();
      } catch(ex) {
        alert("Prepare failed for partial: " + this.partialLoadedId + "\n\n" + ex.name + ": " + ex.message);
      }
    } else {
      // DOM not loaded remove observers
      EventManager.removeObservers(this.events, this);
    }
  },
  
  /**
   * Stub used to prepare this script for work.
   * You should implement prep logic in your sub classes.
   */
  prepare: function() {
    
  },
  
  uiLoaded: function() {
    if (this.partialLoadedId) {
      //alert(this.partialLoadedId + ": " + ($(this.partialLoadedId) != null));
      return $(this.partialLoadedId) != null;
    }
    
    return false;
  },
  
  /**
   * Returns an object that represents JSON. 
   * Exposes both a string and hash value for the JSON.  
   * Allows you to pass either of these arguments as well. */
  jsonMeta: function(obj) {
    var value = {string: null, hash: null}
    
    if (obj) {
      if (typeof(obj) == "string") {
        value.string = obj;
        value.hash = obj.evalJSON();
        
      } else {
        value.string = $H(obj).toJSON();
        value.hash = obj;
      }
    }
    
    return value;
  },
  
  /**
   * Indicates if the events list contains the passed event name.
   * @param {String} eventName The event name to find.
   */
  eventsContain: function(eventName) {
    var rex = new RegExp("^" + eventName + "|," + eventName +",|" + eventName + "$");
    return rex.test(this.events.join(","));
  } 
  
});

/**
 * Indicates if a partial is loaded and has its UI components loaded into the DOM as well.
 * NOTE: You must pass an element id to the constructor for this to work as expected. */
Partial.isLoadedAndVisible = function(name) {
  if (!name) return false;
  var names = name.split(".");
  var len = names.length;
  var context = window;
  
  for (var i = 0; i < len; i++) {
    if (!context) return false;
    var curName = names[i];
    context = context[curName];
  }
  
  if (context.instance) return context.instance.uiLoaded();
  return false;
}
