//Report an error to be logged
function reportError(message,forceErrorPage,parameters,sendParameters)
{
    //because we don't have jquery and the toJson plugin loaded on every page
    //we are using JXS for the AJAX lib and JSON2.js for the convert to JSON
    var jx={getHTTPObject:function(){var a=false;if(typeof ActiveXObject!="undefined"){try{a=new ActiveXObject("Msxml2.XMLHTTP")}catch(b){try{a=new ActiveXObject("Microsoft.XMLHTTP")}catch(c){a=false}}}else if(window.XMLHttpRequest){try{a=new XMLHttpRequest}catch(b){a=false}}return a},load:function(url,callback,format,method,opt){var http=this.init();if(!http||!url)return;if(http.overrideMimeType)http.overrideMimeType("text/xml");if(!method)method="GET";if(!format)format="text";if(!opt)opt={};format=format.toLowerCase();method=method.toUpperCase();var now="uid="+(new Date).getTime();url+=url.indexOf("?")+1?"&":"?";url+=now;var parameters=null;if(method=="POST"){var parts=url.split("?");url=parts[0];parameters=parts[1]}http.open(method,url,true);if(method=="POST"){http.setRequestHeader("Content-type","application/x-www-form-urlencoded");http.setRequestHeader("Content-length",parameters.length);http.setRequestHeader("Connection","close")}var ths=this;if(opt.handler){http.onreadystatechange=function(){opt.handler(http)}}else{http.onreadystatechange=function(){if(http.readyState==4){if(http.status==200){var result="";if(http.responseText)result=http.responseText;if(format.charAt(0)=="j"){result=result.replace(/[\n\r]/g,"");result=eval("("+result+")")}else if(format.charAt(0)=="x"){result=http.responseXML}if(callback)callback(result)}else{if(opt.loadingIndicator)document.getElementsByTagName("body")[0].removeChild(opt.loadingIndicator);if(opt.loading)document.getElementById(opt.loading).style.display="none";if(error)error(http.status)}}}}http.send(parameters)},bind:function(a){var b={url:"",onSuccess:false,onError:false,format:"text",method:"GET",update:"",loading:"",loadingIndicator:""};for(var c in b){if(a[c]){b[c]=a[c]}}if(!b.url)return;var d=false;if(b.loadingIndicator){d=document.createElement("div");d.setAttribute("style","position:absolute;top:0px;left:0px;");d.setAttribute("class","loading-indicator");d.innerHTML=b.loadingIndicator;document.getElementsByTagName("body")[0].appendChild(d);this.opt.loadingIndicator=d}if(b.loading)document.getElementById(b.loading).style.display="block";this.load(b.url,function(a){if(b.onSuccess)b.onSuccess(a);if(b.update)document.getElementById(b.update).innerHTML=a;if(d)document.getElementsByTagName("body")[0].removeChild(d);if(b.loading)document.getElementById(b.loading).style.display="none"},b.format,b.method,b)},init:function(){return this.getHTTPObject()}}
    var JSON;if(!JSON){JSON={}}(function(){function str(a,b){var c,d,e,f,g=gap,h,i=b[a];if(i&&typeof i==="object"&&typeof i.toJSON==="function"){i=i.toJSON(a)}if(typeof rep==="function"){i=rep.call(b,a,i)}switch(typeof i){case"string":return quote(i);case"number":return isFinite(i)?String(i):"null";case"boolean":case"null":return String(i);case"object":if(!i){return"null"}gap+=indent;h=[];if(Object.prototype.toString.apply(i)==="[object Array]"){f=i.length;for(c=0;c<f;c+=1){h[c]=str(c,i)||"null"}e=h.length===0?"[]":gap?"[\n"+gap+h.join(",\n"+gap)+"\n"+g+"]":"["+h.join(",")+"]";gap=g;return e}if(rep&&typeof rep==="object"){f=rep.length;for(c=0;c<f;c+=1){if(typeof rep[c]==="string"){d=rep[c];e=str(d,i);if(e){h.push(quote(d)+(gap?": ":":")+e)}}}}else{for(d in i){if(Object.prototype.hasOwnProperty.call(i,d)){e=str(d,i);if(e){h.push(quote(d)+(gap?": ":":")+e)}}}}e=h.length===0?"{}":gap?"{\n"+gap+h.join(",\n"+gap)+"\n"+g+"}":"{"+h.join(",")+"}";gap=g;return e}}function quote(a){escapable.lastIndex=0;return escapable.test(a)?'"'+a.replace(escapable,function(a){var b=meta[a];return typeof b==="string"?b:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+a+'"'}function f(a){return a<10?"0"+a:a}"use strict";if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(a){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(a){return this.valueOf()}}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;if(typeof JSON.stringify!=="function"){JSON.stringify=function(a,b,c){var d;gap="";indent="";if(typeof c==="number"){for(d=0;d<c;d+=1){indent+=" "}}else if(typeof c==="string"){indent=c}rep=b;if(b&&typeof b!=="function"&&(typeof b!=="object"||typeof b.length!=="number")){throw new Error("JSON.stringify")}return str("",{"":a})}}if(typeof JSON.parse!=="function"){JSON.parse=function(text,reviver){function walk(a,b){var c,d,e=a[b];if(e&&typeof e==="object"){for(c in e){if(Object.prototype.hasOwnProperty.call(e,c)){d=walk(e,c);if(d!==undefined){e[c]=d}else{delete e[c]}}}}return reviver.call(a,b,e)}var j;text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver==="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse")}}})()
     if(console.log)
     {
         console.log(message);
         if(parameters)
         {
             for(var i in parameters)
             {
                console.log(parameters[i]);
             }
         }
     }

     var params= "page="+encodeURIComponent(document.location.href)+
                 "&msg="+message;
     if(sendParameters)
     {
         params+="&params="+JSON.stringify(parameters);
     }
     jx.load('/errors/js.html?'+params,
                function(data)
                {
                    if(forceErrorPage) document.location.href="/error.html";
                },
                'text',
                'post');

}

//This is the default error handler if an uncaught error occurs
//thsi will get it. If the error is deteremined to be a syntax error
//opposed to a runtime error the user is redirected to the error page
//the error will be logged
var __FIRSTPASS = true; // This keeps the thing from firing in an endless loop!
window.onerror=function(errMsg, url, ln)
{
    if (__FIRSTPASS) // This keeps the thing from firing in an endless loop!
    {
        __FIRSTPASS = false; // This keeps the thing from firing in an endless loop!

        var message="Unhandled Javascript Error or Exception";
        var forceErrorPage=redirect;
        var parameters=[errMsg,url,ln];
        var sendParameters=true;

        var jx={getHTTPObject:function(){var a=false;if(typeof ActiveXObject!="undefined"){try{a=new ActiveXObject("Msxml2.XMLHTTP")}catch(b){try{a=new ActiveXObject("Microsoft.XMLHTTP")}catch(c){a=false}}}else if(window.XMLHttpRequest){try{a=new XMLHttpRequest}catch(b){a=false}}return a},load:function(url,callback,format,method,opt){var http=this.init();if(!http||!url)return;if(http.overrideMimeType)http.overrideMimeType("text/xml");if(!method)method="GET";if(!format)format="text";if(!opt)opt={};format=format.toLowerCase();method=method.toUpperCase();var now="uid="+(new Date).getTime();url+=url.indexOf("?")+1?"&":"?";url+=now;var parameters=null;if(method=="POST"){var parts=url.split("?");url=parts[0];parameters=parts[1]}http.open(method,url,true);if(method=="POST"){http.setRequestHeader("Content-type","application/x-www-form-urlencoded");http.setRequestHeader("Content-length",parameters.length);http.setRequestHeader("Connection","close")}var ths=this;if(opt.handler){http.onreadystatechange=function(){opt.handler(http)}}else{http.onreadystatechange=function(){if(http.readyState==4){if(http.status==200){var result="";if(http.responseText)result=http.responseText;if(format.charAt(0)=="j"){result=result.replace(/[\n\r]/g,"");result=eval("("+result+")")}else if(format.charAt(0)=="x"){result=http.responseXML}if(callback)callback(result)}else{if(opt.loadingIndicator)document.getElementsByTagName("body")[0].removeChild(opt.loadingIndicator);if(opt.loading)document.getElementById(opt.loading).style.display="none";if(error)error(http.status)}}}}http.send(parameters)},bind:function(a){var b={url:"",onSuccess:false,onError:false,format:"text",method:"GET",update:"",loading:"",loadingIndicator:""};for(var c in b){if(a[c]){b[c]=a[c]}}if(!b.url)return;var d=false;if(b.loadingIndicator){d=document.createElement("div");d.setAttribute("style","position:absolute;top:0px;left:0px;");d.setAttribute("class","loading-indicator");d.innerHTML=b.loadingIndicator;document.getElementsByTagName("body")[0].appendChild(d);this.opt.loadingIndicator=d}if(b.loading)document.getElementById(b.loading).style.display="block";this.load(b.url,function(a){if(b.onSuccess)b.onSuccess(a);if(b.update)document.getElementById(b.update).innerHTML=a;if(d)document.getElementsByTagName("body")[0].removeChild(d);if(b.loading)document.getElementById(b.loading).style.display="none"},b.format,b.method,b)},init:function(){return this.getHTTPObject()}}
        var JSON;if(!JSON){JSON={}}(function(){function str(a,b){var c,d,e,f,g=gap,h,i=b[a];if(i&&typeof i==="object"&&typeof i.toJSON==="function"){i=i.toJSON(a)}if(typeof rep==="function"){i=rep.call(b,a,i)}switch(typeof i){case"string":return quote(i);case"number":return isFinite(i)?String(i):"null";case"boolean":case"null":return String(i);case"object":if(!i){return"null"}gap+=indent;h=[];if(Object.prototype.toString.apply(i)==="[object Array]"){f=i.length;for(c=0;c<f;c+=1){h[c]=str(c,i)||"null"}e=h.length===0?"[]":gap?"[\n"+gap+h.join(",\n"+gap)+"\n"+g+"]":"["+h.join(",")+"]";gap=g;return e}if(rep&&typeof rep==="object"){f=rep.length;for(c=0;c<f;c+=1){if(typeof rep[c]==="string"){d=rep[c];e=str(d,i);if(e){h.push(quote(d)+(gap?": ":":")+e)}}}}else{for(d in i){if(Object.prototype.hasOwnProperty.call(i,d)){e=str(d,i);if(e){h.push(quote(d)+(gap?": ":":")+e)}}}}e=h.length===0?"{}":gap?"{\n"+gap+h.join(",\n"+gap)+"\n"+g+"}":"{"+h.join(",")+"}";gap=g;return e}}function quote(a){escapable.lastIndex=0;return escapable.test(a)?'"'+a.replace(escapable,function(a){var b=meta[a];return typeof b==="string"?b:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+a+'"'}function f(a){return a<10?"0"+a:a}"use strict";if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(a){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(a){return this.valueOf()}}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;if(typeof JSON.stringify!=="function"){JSON.stringify=function(a,b,c){var d;gap="";indent="";if(typeof c==="number"){for(d=0;d<c;d+=1){indent+=" "}}else if(typeof c==="string"){indent=c}rep=b;if(b&&typeof b!=="function"&&(typeof b!=="object"||typeof b.length!=="number")){throw new Error("JSON.stringify")}return str("",{"":a})}}if(typeof JSON.parse!=="function"){JSON.parse=function(text,reviver){function walk(a,b){var c,d,e=a[b];if(e&&typeof e==="object"){for(c in e){if(Object.prototype.hasOwnProperty.call(e,c)){d=walk(e,c);if(d!==undefined){e[c]=d}else{delete e[c]}}}}return reviver.call(a,b,e)}var j;text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver==="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse")}}})()

        var redirect=false;

        if(errMsg.indexOf("Uncaught SyntaxError")!=-1)
        {
            //chrome Syntax Error
            redirect=true;
        }
        else if(errMsg.indexOf("SyntaxError:")!=-1)
        {
            //safari Syntax Error
            redirect=true;
        }
        else if(document.all)
        {
            switch(errMsg)
            {
                case "Can't have 'break' outside of loop":
                case "Can't have 'continue' outside of loop":
                case "Conditional compilation is turned off":
                case "'default' can only appear once in a 'switch' statement":
                case "Expected '('":
                case "Expected ')'":
                case "Expected '/'":
                case "Expected ':'":
                case "Expected ';'":
                case "Expected '@'":
                case "Expected '@end'":
                case "Expected ']'":
                case "Expected '{'":
                case "Expected '}'":
                case "Expected '='":
                case "Expected 'catch'":
                case "Expected constant":
                case "Expected hexadecimal digit":
                case "Expected identifier":
                case "Expected identifier, string or number":
                case "Expected 'while'":
                case "Invalid character":
                case "Label not found":
                case "Label redefined":
                case "'return' statement outside of function":
                case "Syntax error":
                case "Throw must be followed by an expression on the same source line":
                case "Unterminated comment":
                case "Unterminated string constant":
                    redirect=true;
                    break;
            }
        }
        else
        {
            //firefox syntax errors
            switch(errMsg)
            {
                case "malformed formal parameter":
                case "too many constructor arguments":
                case "too many function arguments":
                case "unterminated thetical":
                case "trailing \\ in regular expression":
                case "invalid range in character class":
                case "unmatched : in regular expression":
                case "missing ( before formal parameters":
                case "missing formal parameter":
                case "missing : after formal parameters":
                case "missing { before function body":
                case "missing } after function body":
                case "missing ( before condition":
                case "missing : after condition":
                case "missing name in import statement":
                case "missing name after . operator":
                case "missing ] in index expression":
                case "missing name in export statement":
                case "missing ( before switch expression":
                case "missing : after switch expression":
                case "missing { before switch body":
                case "missing : after case label":
                case "missing while after do-loop body":
                case "missing ( after for":
                case "missing ; after for-loop initializer":
                case "missing ; after for-loop condition":
                case "missing : after for-loop control":
                case "missing { before try block":
                case "missing } after try block":
                case "missing ( before catch":
                case "missing identifier in catch":
                case "missing : after catch":
                case "missing { before catch block":
                case "missing } after catch block":
                case "missing { before finally block":
                case "missing } after finally block":
                case "missing catch or finally after try":
                case "missing ( before with-statement object":
                case "missing : after with-statement object":
                case "missing } in compound statement":
                case "missing variable name":
                case "missing : in conditional expression":
                case "missing : after argument list":
                case "missing ] after element list":
                case "missing : after property id":
                case "missing } after property list":
                case "missing : in thetical":
                case "missing ; before statement":
                case "missing ] after attribute expression":
                case "missing name after .. operator":
                case "missing } in XML expression":
                case "missing = in XML attribute":
                case "invalid import expression":
                case "more than one switch default":
                case "invalid switch statement":
                case "invalid for/in left-hand side":
                case "catch after unconditional catch":
                case "catch without try":
                case "finally without try":
                case "label not found":
                case "invalid break":
                case "invalid continue":
                case "invalid return":
                case "invalid label":
                case "duplicate label":
                case "invalid variable initialization":
                case "invalid assignment left-hand side":
                case "invalid property id":
                case "syntax error":
                case "invalid sharp variable definition":
                case "missing exponent":
                case "unterminated string literal":
                case "unterminated comment":
                case "unterminated regular expression literal":
                case "invalid flag after regular expression":
                case "overlarge sharp variable number":
                case "illegal character":
                case "non-octal digit in an escape sequence that doesn't match a back-reference":
                case "back-reference exceeds number of capturing theses":
                case "trailing comma is not legal in ECMA-262 object initializers":
                case "invalid for each loop":
                case "too many local variables":
                    redirect=true;
                    break;
            }
            if(!redirect)
            {
                if(errMsg.indexOf("invalid quantifier")!=-1) redirect=true;
                else if(errMsg.indexOf("overlarge minimum")!=-1) redirect=true;
                else if(errMsg.indexOf("overlarge maximum")!=-1) redirect=true;
                else if(errMsg.indexOf("zero quantifier")!=-1) redirect=true;
                else if(errMsg.indexOf("unterminated quantifier")!=-1) redirect=true;
                else if(errMsg.indexOf("unterminated character class")!=-1) redirect=true;
                else if(errMsg.indexOf("invalid regular expression flag")!=-1) redirect=true;
                else if(errMsg.indexOf("no input for /")!=-1) redirect=true;
                else if(errMsg.indexOf(" is a reserved identifier")!=-1) redirect=true;
                else if(errMsg.indexOf("is not a legal ECMA-262 octal constant")!=-1) redirect=true;
                else if(/maximum .+ less than minimum/.test(errMsg)) redirect=true;
                else if(/invalid .+ operand/.test(errMsg)) redirect=true;
            }
        }

        if(console.log)
        {
             console.log(message);
            if(parameters)
            {
                 for(var i in parameters)
                {
                    console.log(parameters[i]);
                }
            }
        }

        var params= "page="+encodeURIComponent(document.location.href)+
                     "&msg="+message;
        if(sendParameters)
        {
            params+="&params="+JSON.stringify(parameters);
        }

        jx.load('/errors/js.html?'+params,
                function(data)
                {
                    if(forceErrorPage) document.location.href="/error.html";
                },
                'text',
                'post');
    }
}
