/// <reference name="MicrosoftAjax.js"/>
/// <reference name="StackTrace.js" assembly="ErrorHandlerLibrary"/>

ErrorHandler = function ErrorHandler() {
  ///<summary>
  ///Publisher for handled and unhandled exceptions
  ///</summary>
  ErrorHandler.initializeBase(this);
  this._disableErrorPublication = false;
};

ErrorHandler.prototype = {
  initialize: function ErrorHandler$initialize() {
    Sys.Debug.trace("ErrorHandler was initialized");
    ErrorHandler.callBaseMethod(this, 'initialize');
    window.onerror = Function.createDelegate(this, this._unhandledError);
  },
  dispose: function ErrorHandler$dispose() {
    Sys.Debug.trace("ErrorHandler was disposed");
    window.onerror = null;
    ErrorHandler.callBaseMethod(this, 'dispose');
  },
  
  get_disableErrorPublication: function() { 
    return this._disableErrorPublication;
  },

  set_disableErrorPublication: function(value) {
    if (!this.get_updating()) {
      this.raisePropertyChanged("disableErrorPublication");
    }
    this._disableErrorPublication = value;
  },
    
  _unhandledError: function ErrorHandler$_unhandledError(msg, url, lineNumber) {
    try {
      var stackTrace = StackTrace.createStackTrace(arguments.callee);
      if (!this._disableErrorPublication) {
        ErrorDataService.PublishError(stackTrace, msg, url, lineNumber);
      }      
      var args = new ErrorEventArgs(stackTrace, msg, url, lineNumber);
      this._raiseUnhandledErrorOccured(args);
    }
    catch (e) { }
  },
    
  add_unhandledErrorOccurred: function(handler) {
    this.get_events().addHandler("unhandledErrorOccurred", handler);
  },
    
  remove_unhandledErrorOccurred: function(handler) {
    this.get_events().removeHandler("unhandledErrorOccurred", handler);
  },
    
  _raiseUnhandledErrorOccured: function(args) {
    var evt = this.get_events().getHandler("unhandledErrorOccurred");
    if (evt !== null) {
      evt(this, args);
    }
  },
    
  publishError: function ErrorHandler$handledError(error) {
    /// <summary>Publishes a handled error to the server</summary>
    /// <param name="error" type=”Error” />
    try {
      var e = Function._validateParams(arguments, [
        {name: "error", type: Error }
      ]);
      if (e) throw e;
      
      var stackTrace;
      if (error.stack) {
        stackTrace = error.stack;
      }
      else { 
        stackTrace = StackTrace.createStackTrace(arguments.callee);
      }
      ErrorDataService.PublishError(stackTrace, null, null, null);
    }
    catch (e) { }
  }
};
ErrorHandler.registerClass('ErrorHandler', Sys.Component);

ErrorEventArgs = function(stackTrace, message, url, lineNumber) {
  ErrorEventArgs.initializeBase(this);
  this._message = message;
  this._stackTrace = stackTrace;
  this._url = url;
  this._lineNumber = lineNumber;
}
ErrorEventArgs.registerClass("ErrorEventArgs", Sys.EventArgs);

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();