﻿//declare the global AJAX constants
var HANDLER_URL = '/Handlers/cta.ashx';
var DEBUG = false;

//when the document is ready we need to initialize our global ajaxManager object
$(document).ready(function() {
    
    // only do this if we haven't already init the ajaxManager
    if (!$.ajaxManager.ajaxSettings.arguments)
    {
		//initialize the ajaxManager
		$.ajaxManager.initialise({
			responseType: $.ajaxManager.dataType.JSON,
			requestType: $.ajaxManager.requestType.POST,
			requestUrl: HANDLER_URL,
			debug: DEBUG
		});
	}
    
    $.ajaxManager.onError = function(XMLHttpRequest, textStatus, errorThrown)
    {
		if(this.debug)
		{
			alert('firing on_Error');
			
			alert(errorThrown);
			alert(textStatus);
			alert(XMLHttpRequest);
		}
		
		// check if error is a timeout, if so redirect to timeout page
		var contentType = XMLHttpRequest.getResponseHeader('Content-Type');
		if (contentType.indexOf('text/html') >= 0 && mrm.global.utilities.workflow.getScopedWorkflowKeyFromUrl)
		{
			var currentUrl = this.ajaxSettings.requestArgs;
			var redirectUrl;
			var searchWkflow;
			var wkflow = mrm.global.utilities.workflow.getScopedWorkflowKeyFromUrl(currentUrl,null);
			
			// strip the wkflow back to the scoped search manager
			var wkflowCodes = wkflow.split("_");
			if (wkflowCodes.length >= 2)
			{
				searchWkflow = wkflowCodes[0] + "_" + wkflowCodes[1];
			}
			
			if (searchWkflow == "se_na")
			{
				redirectUrl = "/timeout.aspx?wkflw=" + searchWkflow + "_ti_vi";
			}
			else
			{
				redirectUrl = "/results.aspx?wkflw=" + searchWkflow + "_re_vi";
			}
			
			if(this.debug)
			{
				alert("searchWkflow = " + searchWkflow + ".\nredirectUrl = " + redirectUrl + ".");
			}
			
			// goto redirect page
			document.location = redirectUrl;
		}
    };
    
});
