﻿
var ErrorLog = {
	errorUrl: '',
	sendErrors: function (errors) {
		if(typeof console != "undefined") console.log('Sending ' + errors.length + ' error(s) to the server');

		$.ajax({
			url: ErrorLog.errorUrl,
			type: 'POST',
			data: JSON.stringify(errors),
			dataType: 'json',
			contentType: 'application/json; charset=UTF-8'
		});
	},

	init: function (baseUrl) {
		ErrorLog.errorUrl = baseUrl + 'JavaScriptError/Log';
		var watcher = new ErrorWatcher();
	}
}

function ErrorWatcher() {
    var errors = [];
    var timeout = null;

    /* Override window.onerror instead of an event listener
    because firefox doesn't handle the event */
    var oldOnError = window.onerror;

    window.onerror = function (arg1, arg2, arg3) {
    	onError(arg1, arg2, arg3, stack);
    	if (oldOnError) oldOnError(arg1, arg2, arg3);

    	return true;
    }

    function onError(arg1, arg2, arg3) {
        if (arg1['message'] != undefined &&
            arg1['filename'] != undefined &&
            arg1['lineno'] != undefined) {

            addError(arg1.message, arg1.filename, arg1.lineno);
        } else {
            addError(arg1, arg2, arg3);
        }

    }

    function addError(msg, url, lineno) {
        if (timeout) clearTimeout(timeout);
        
        errors.push({
            message: msg,
            url: url,
            lineno: lineno
        });

        timeout = setTimeout(function () {
        	ErrorLog.sendErrors(errors);
        	errors = [];
        }, 5000);
    }    
}

