﻿/* ****************************************************************************
 *
 * Copyright (c) 2010 Gabriel McAdams, http://www.thecodepage.com/
 *
 * This software is subject to the Microsoft Public License (Ms-PL). 
 * A copy of the license can be found in the license.htm file included 
 * in this distribution.
 *
 * You must not remove this notice, or any other, from this software.
 *
 * ***************************************************************************/
JSErrorNotifier = {
	initialized: false,
	id: null,
	exceptionMessage: null,

	//Called by script inserted by the server control
	initialize: function(control) {
		if (this.initialized === false) {
			this.initialized = true;

			this.id = control.id;
			this.exceptionMessage = control.exceptionMessage;

			//Add the error handler
			this.addOnErrorEventHandler(this.errorHandler);
		}
	},

	//The function that will be called in the event of a JavaScript error
	errorHandler: function(msg, url, line) {
		var argument = msg + ":||:" + url + ":||:" + line;
		try {
			//Perform an AJAX call to the server with information about the error that occurred
			//If the current browser is not IE6
			<!--[if !IE 6]><!-->
	            jQuery.ajax({	            
	                url: "/CaptureError.ashx/Capture", 
	                data: {'errorDetails': argument}
	                });		
	        <!--<![endif]-->
		} catch (e) {
			//In the case of an error calling the server, show the error message
			console.log(e);
			JSErrorNotifier.callbackErrorReturn();
		}
		return true;
	},

	callbackReturn: function(result, context) {
		if (result !== null && result.length > 0) {
			//alert(result);
		}
	},

	callbackErrorReturn: function(message, context) {
		JSErrorNotifier.callbackReturn(JSErrorNotifier.exceptionMessage);
	},

	//To ensure that our code doesn't disrupt any code already on the page,
	//This function adds our handler to any that might already exist
	addOnErrorEventHandler: function(fn) {
		var existingonerror = window.onerror;
		if (typeof window.onerror == 'function') {
			window.onerror = function() {
				existingonerror();
				fn();
			};
		} else {
			window.onerror = fn;
		}
	}
};
