﻿var isDebugging = true;
var logToConsole = true;
var logJsErrors = false;

if (logJsErrors) {
    window.onerror = ErrorSetting;
}

$(document).ajaxError(function() {
    if (isDebugging) {
        alert("AJAX error has occured");

        if (window.console && window.console.error) {
            console.error(arguments);
        }
    }
});

var BrowserDetect = {
    init: function() {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function(data) {
        for (var i = 0; i < data.length; i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function(dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
    },
    dataBrowser: [
		{
		    string: navigator.userAgent,
		    subString: "Chrome",
		    identity: "Chrome"
		},
		{ string: navigator.userAgent,
		    subString: "OmniWeb",
		    versionSearch: "OmniWeb/",
		    identity: "OmniWeb"
		},
		{
		    string: navigator.vendor,
		    subString: "Apple",
		    identity: "Safari",
		    versionSearch: "Version"
		},
		{
		    prop: window.opera,
		    identity: "Opera"
		},
		{
		    string: navigator.vendor,
		    subString: "iCab",
		    identity: "iCab"
		},
		{
		    string: navigator.vendor,
		    subString: "KDE",
		    identity: "Konqueror"
		},
		{
		    string: navigator.userAgent,
		    subString: "Firefox",
		    identity: "Firefox"
		},
		{
		    string: navigator.vendor,
		    subString: "Camino",
		    identity: "Camino"
		},
		{		// for newer Netscapes (6+)
		    string: navigator.userAgent,
		    subString: "Netscape",
		    identity: "Netscape"
		},
		{
		    string: navigator.userAgent,
		    subString: "MSIE",
		    identity: "Explorer",
		    versionSearch: "MSIE"
		},
		{
		    string: navigator.userAgent,
		    subString: "Gecko",
		    identity: "Mozilla",
		    versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
		    string: navigator.userAgent,
		    subString: "Mozilla",
		    identity: "Netscape",
		    versionSearch: "Mozilla"
		}
	],
    dataOS: [
		{
		    string: navigator.platform,
		    subString: "Win",
		    identity: "Windows"
		},
		{
		    string: navigator.platform,
		    subString: "Mac",
		    identity: "Mac"
		},
		{
		    string: navigator.userAgent,
		    subString: "iPhone",
		    identity: "iPhone/iPod"
		},
		{
		    string: navigator.platform,
		    subString: "Linux",
		    identity: "Linux"
		}
	]

};
BrowserDetect.init();

function BrowserDetails() {
    return "Name=" + BrowserDetect.browser
                          + "&Version=" + BrowserDetect.version
                          + "&OS=" + BrowserDetect.OS
                          + "&CookiesEnabled=" + navigator.cookieEnabled; ;
};

function ErrorSetting(msg, file_loc, line_no) {
    var e_msg = msg;
    var e_file = file_loc;
    var e_line = line_no;
    var cookiesEnabled = navigator.cookieEnabled;
    var error_d = "Error in file: " + file_loc + "\nLine number: " + line_no + "\nMessage: " + msg;

    if (logJsErrors) {
        theData = "file=" + file_loc
                          + "&line=" + line_no
                          + "&err=" + msg
                          + "&browser=" + BrowserDetect.browser
                          + "&version=" + BrowserDetect.version
                          + "&os=" + BrowserDetect.OS
                          + "&cookies=" + cookiesEnabled;

        $.ajax({
            type: "POST",
            url: "/Debug/LogJavaScriptError",
            data: theData,
            success: function() {
                if (logToConsole) {
                    if (window.console && window.console.error) {
                        console.error(error_d);
                    }
                }

                if (isDebugging) {
                    alert("Error data saved to: /Logs/YOLJavaScriptErrors.log\n" + error_d);
                }
            }
        });
    }

    return true;
}

// Summary: This checks to see if authentication has timed out after doing an ajax request (ie you get the login page back in the response)
//          In your login page(s) just put:
//            <%
//                Response.AddHeader("IfAjaxRedirectTo", Url.Action("RedirectToCorrectGateway", "Security"));
//            %>
$(document).ajaxComplete(function(event, XMLHttpRequest, ajaxOptions) {
    if (XMLHttpRequest.getResponseHeader("IfAjaxRedirectTo")) {                
        if (XMLHttpRequest.getResponseHeader("Content-Type") != "text/javascript"
                && XMLHttpRequest.getResponseHeader("Content-Type") != "application/x-javascript") { // jqgrid loads its js resources by ajax            
            document.location = XMLHttpRequest.getResponseHeader("IfAjaxRedirectTo");
        }
    }
});

function dlsMvcAjaxForm_OnSubmit(form, url, preSubmitFunctionToRun, target, replacemode, postSubmitFunctionToRun, popuptoclose,commitSucceededFunctionToRun,commitFailedFunctionToRun) {
    try {
        // If we are using jquery validate, we do not want to submit the form from under its feet!
        try {
            if (!$(form).valid())
                return false;
        } catch (err) { }
       
        // preSubmit is a function which returns false if it wants to cancel form post
        if (preSubmitFunctionToRun) {
            if (!preSubmitFunctionToRun())
                return false;
        }

        var options = {
            url: url,
            success: function(response) {
                _processResponse(target, response, replacemode, postSubmitFunctionToRun, popuptoclose, commitSucceededFunctionToRun, commitFailedFunctionToRun);
            }
        }

        $(form).ajaxSubmit(options);
    }
    catch (errMsg) {
        alert("What the Javascript error. Details: " + errMsg);
    }
}

function dlsMvcAjaxLink_OnClick(link, url, preSubmitFunctionToRun, target, replacemode, postSubmitFunctionToRun, popuptoclose, commitSucceededFunctionToRun, commitFailedFunctionToRun) {
   
    // preSubmit is a function which returns false if it wants to cancel form post
    if (preSubmitFunctionToRun) {
        if (!preSubmitFunctionToRun())
            return false;
    }
    var resp = $.ajax({
        url: url,
        type: "POST",
        dataType: "html",
        data: {},
        success: function(response) {
                    _processResponse(target, response, replacemode, postSubmitFunctionToRun, popuptoclose, commitSucceededFunctionToRun, commitFailedFunctionToRun);
                }
    });            
}


function _processResponse(target, response, replacemode, postSubmitFunctionToRun, popuptoclose, commitSucceededFuntionToRun, commitFailedFunctionToRun) {

    // Add in additional replace modes later
    if (target) {
        if (replacemode == 'replace')
            $('#' + target).replaceWith(response);
        else
            $('#' + target).html(response);
    }
    
    if ($.cookie('CommitSucceeded') == 'True') {
        $.cookie('CommitSucceeded', null);
        if (commitSucceededFuntionToRun) {
            commitSucceededFuntionToRun(response);
        }
    }
    else if ($.cookie('CommitSucceeded') == 'False') {
        $.cookie('CommitSucceeded', null);
        if(commitFailedFunctionToRun) {
            commitFailedFunctionToRun();
        }
    }
    
    if (postSubmitFunctionToRun)
        postSubmitFunctionToRun(response);
     
    if (popuptoclose) {
        // The jqm re-register is here in case the popup has been re-rendered via the ajax call.
        $('#' + popuptoclose).jqm({ modal: true, overlay: 50, zIndex: 500 }).jqmHide();
        // We need to try to remove any left over overlay due to something to do with ajax re-rendering - HACK
        $('.jqmOverlay').remove();
    }

}

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
