﻿$.validator.unobtrusive.adapters.addBool("mandatory","required");$(function(){});
// Sanctions Search Controls by Nugo Ltd

var sanctionssearch = {};

(function ($) {

	sanctionssearch.url = "";

	sanctionssearch.controls = {

		messageBox: {
			success: function (title, message) {
				return "<div class='message-box-success message-box'><div class='title'>" + title + "</div><div class='content'>" + message + "</div><button type='button'><span>Close</span></button></div>";
			},
			error: function (title, message) {
				return "<div class='message-box-error message-box'><div class='title'>" + title + "</div><div class='content'>" + message + "</div><button type='button'><span>Close</span></button></div>";
			}
		}

	};

})(jQuery);

$(function () {

	// =======================================
	// Handler: Closing a message box instance
	// =======================================

	$(".message-box-container button").live('click', function (ev) {
		// Get the parent div of the clicked button
		var parent = $(this).closest("div.message-box");

		// Slide it up (closed) and remove it from the DOM
		parent.slideUp(function () {
			parent.remove();
		});
	});


});

$(function () {

	// ===================================================
	// Handler: Confirming a client was in the results
	// ===================================================

	$(".search-record button.client-in-results").live('click', function (ev) {

		// Confirm the search status through AJAX
		sanctionssearch.search.confirmSearchRecord(this, true, false);

	});

	// ===================================================
	// Handler: Confirming a client was not in the results
	// ===================================================

	$(".search-record button.client-not-in-results").live('click', function (ev) {

		// Confirm the search status through AJAX
		sanctionssearch.search.confirmSearchRecord(this, false, true);

	});

});

(function ($) {

    // ===================================================
    // FUNCTIONS
    // ===================================================

	sanctionssearch.search = {

		// Store a bulk search ID while processing
		bulkSearchId: 0,

		// This is used to store the set interval value for get status loops
		bulkSearchStatusInterval: null,

		// Store a value indicating if the system already processing an AJAX request
		bulkSearchAjaxPending: false,

		// Function to start or restart the processing of a bulk search
		startProcessingBulkSearch: function ()
		{
			// Set up JSON object
			var request = {
				BulkSearchId: sanctionssearch.search.bulkSearchId
			};

			// Send request to start processing
			$.ajax({
				url: sanctionssearch.url + "Members/BulkSearch/StartProcessing/",
				type: "POST",
				dataType: "json",
				data: JSON.stringify(request),
				contentType: 'application/json; charset=utf-8'
			});
		},

		// Get the status of the running bulk search
		getBulkSearchStatus: function ()
		{
			// Skip this request if we're still processing a request
			if (sanctionssearch.search.bulkSearchAjaxPending == true) return;

			// Make sure we notify the system that an AJAX request is now pending
			sanctionssearch.search.bulkSearchAjaxPending = true;

			// Set up JSON object
			var request = {
				BulkSearchId: sanctionssearch.search.bulkSearchId
			};

			// Hide any old message boxes and delay ajax request until animation has finished
			$(".message-box-container").slideUp(function () {
				$(".message-box-container").empty();

				// Send request to add new property
				$.ajax({
					url: sanctionssearch.url + "Members/BulkSearch/GetStatus/",
					type: "POST",
					dataType: "json",
					data: JSON.stringify(request),
					contentType: 'application/json; charset=utf-8',
					success: function (data) {
						if (data.Success === true) {

							var text;

							switch (data.Status) {
								case "N": // Not started
									text = "Processing is due to commence shortly";
									$("#processingStatus").css("color", "black");

									break;

								case "E": // Error
									text = "An error has occured: " + data.Message
									$("#processingStatus").css("color", "red");

									// The search is errored, cancel the status check loop
									clearInterval(sanctionssearch.search.bulkSearchStatusInterval);

									// Update the status of the search
									sanctionssearch.search.getBulkSearchStatus();

									break;

								case "P": // Processing
									text = "Processing records: " + data.Processed + "/" + data.Total + " records";
									$("#processingStatus").css("color", "orange");

									break;

								case "C": // Complete
									text = "Completed processing " + data.Processed + "/" + data.Total + " records";
									$("#processingStatus").css("color", "green");

									// The search is complete, cancel the status check loop
									clearInterval(sanctionssearch.search.bulkSearchStatusInterval);

									// Update the status of the search
									sanctionssearch.search.getBulkSearchStatus();

									break;

								case "R": // Restart Processing Required
									text = "Processing records: " + data.Processed + "/" + data.Total + " records";
									$("#processingStatus").css("color", "orange");

									// Start (restart) the processing of the search
									sanctionssearch.search.startProcessingBulkSearch();

									break;
							}

							$("#processingStatus").text(text);

						} else {
							// Show error message to user
							$(".message-box-container").append(data.Message);
							$(".message-box-container").slideDown();
							clearInterval(checkBulkStatus);
						}
                        
						// The AJAX request has finished
						sanctionssearch.search.bulkSearchAjaxPending = false;
					},
					error: function (jqXHR, textStatus, errorThrown) {
						// Show error message to user
						$(".message-box-container").append(sanctionssearch.controls.messageBox.error("Unexpected error", "Unable to process request, please try again"));
						$(".message-box-container").slideDown();

						// The request has failed, cancel the status check loop
						clearInterval(sanctionssearch.search.bulkSearchStatusInterval);
						
						// The AJAX request has failed
						sanctionssearch.search.bulkSearchAjaxPending = false;
					}
				}); // End Ajax Request
			}); // End SlideUp
		},

		// Confirm whether a search contained client details
        confirmSearchRecord: function (obj, clientInResults, clientNotInResults) {            
            
            // Get the parent div
            var parent = $(obj).closest("div.search-details");

			// Get the searchId
			var searchId = $(obj).attr("data-search-id");
			
            // Set up JSON object
            var request = { 
				SearchId: searchId,
				ClientInResults: clientInResults,
				ClientNotInResults: clientNotInResults
			};
            
            // Hide any old message boxes and delay ajax request until animation has finished
            $(".message-box-container").slideUp(function () {
                $(".message-box-container").empty();

                // Send request to add new property
                $.ajax({
                    url: sanctionssearch.url + "Members/Search/UpdateSearchStatus/",
                    type: "POST",
                    dataType: "json",
                    data: JSON.stringify(request),
                    contentType: 'application/json; charset=utf-8',
                    success: function (data) {
                        if (data.Success === true) {

                            // Close the parent
                            parent.slideUp(function () {
								parent.empty();

								// Add the returned html to the page
								parent.html(data.Message);

								// Slide open the parent to reveal the new message
								parent.slideDown();
							});
                        
                        } else {
                            // Show error message to user
                            $(".message-box-container").append(data.Message);
                            $(".message-box-container").slideDown();
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        // Show error message to user
                        $(".message-box-container").append(sanctionssearch.controls.messageBox.error("Unexpected error", "Unable to process request, please try again"));
                        $(".message-box-container").slideDown();
                    }
                }); // End Ajax Request
            }); // End SlideUp
        }

	};

})(jQuery);

$(function () {

//	// ===================================================
//	// Handler: Confirming a client was in the results
//	// ===================================================

//	$(".search-record button.client-in-results").live('click', function (ev) {

//		// Confirm the search status through AJAX
//		sanctionssearch.search.confirmSearchRecord(this, true, false);

//	});

//	// ===================================================
//	// Handler: Confirming a client was not in the results
//	// ===================================================

//	$(".search-record button.client-not-in-results").live('click', function (ev) {

//		// Confirm the search status through AJAX
//		sanctionssearch.search.confirmSearchRecord(this, false, true);

//	});

});

(function ($) {

	// ===================================================
	// FUNCTIONS
	// ===================================================

	sanctionssearch.clients = {

		// Array of all the search Ids
		searchIds: [],

		// This is used to store the set interval value for get status loops
		searchResultsInterval: null,

		// Store a value indicating if the system already processing an AJAX request
		searchResultsAjaxPending: false,

		// Get the search results for one of the searches in the searchIds array
		getSearchResults: function () {

			// Skip this request if we're still processing a request
			if (sanctionssearch.clients.searchResultsAjaxPending == true) return;

			// Make sure we notify the system that an AJAX request is now pending
			sanctionssearch.clients.searchResultsAjaxPending = true;

			// Cancel the processing if the array is empty
			if(sanctionssearch.clients.searchIds.length == 0)
			{			
				// Cancel the status check loop
				clearInterval(sanctionssearch.clients.searchResultsInterval);
				
				// Ajax request is no longer pending
				sanctionssearch.clients.searchResultsAjaxPending = false;

				// Hide the loading overlay
				$("div.loading-overlay").hide();

				// Invoke the print dialog
				//window.print();

				// don't continue any further
				return;
			}

			// Set up JSON object with an item from the search id list
			var request = {
				SearchId: sanctionssearch.clients.searchIds.pop()
			};

			// Send request to add new property
			$.ajax({
				url: sanctionssearch.url + "Members/History/GetSearchResults/",
				type: "POST",
				dataType: "html",
				data: JSON.stringify(request),
				contentType: 'application/json; charset=utf-8',
				success: function (data) {
						
					// Add the search results to the page
					$("tr#search-id-" + request.SearchId + " td").html(data);

					// Remove the css that hides the results row
					$("tr#search-id-" + request.SearchId).removeClass("search-results-empty");

					// Add a copy of the table headers
					$("tr#search-id-" + request.SearchId).after("<tr><th></th><th>Client</th><th>Name</th><th>Address</th><th>Date</th><th>Searched Lists</th><th>Results</th></tr>");
						
					// The AJAX request has finished
					sanctionssearch.clients.searchResultsAjaxPending = false;

				},
				error: function (jqXHR, textStatus, errorThrown) {
					// Show error message to user
					$(".message-box-container").append(sanctionssearch.controls.messageBox.error("Unexpected error", "Unable to process request, please try again"));
					$(".message-box-container").slideDown();

					// The request has failed, cancel the status check loop
					clearInterval(sanctionssearch.clients.searchResultsInterval);

					// The AJAX request has failed
					sanctionssearch.clients.searchResultsAjaxPending = false;
				}
			}); // End Ajax Request
		}

	};

})(jQuery);

$(function () {

	// ===================================================
	// Handler: Billing address country changed
	// ===================================================

	$(".billingAddress select#Country").live('change', function (ev) {

		// Update the billing address form
		sanctionssearch.billing.updateAddressForm(this);

	});

});

(function ($) {

    // ===================================================
    // FUNCTIONS
    // ===================================================

	sanctionssearch.billing = {
	
		// Confirm whether a search contained client details
        updateAddressForm: function (obj) {            
            
			// Get the selected Country Value
			var selectedValue = $(obj).val();

			// Display the address form only if a country has been selected
			if (selectedValue.length > 0)
                $("div#address-form").slideDown();
            else
                $("div#address-form").slideUp();

			// If the user is from the US display the list of US States
            if (selectedValue == "US") {
                $("select#State").show();
                $("select#State").removeAttr("disabled");
                $("select#State").selectedIndex = 0;
                $("input#State").hide();
                $("input#State").attr("disabled", "disabled");
            } else {
				// Otherwise display a textbox
                $("select#State").hide();
                $("select#State").attr("disabled", "disabled");
                $("input#State").show();
                $("input#State").removeAttr("disabled");
                $("input#State").val("");
            }
			
            // Update validators to reflect the hidden status
            $.validator.unobtrusive.parseDynamicContent("input#State, select#State");
			
        }

	};

})(jQuery);

