﻿
// encapsulates methods required for cleanly interfacing with .net ashx handlers.
var ajaxHandler = function (options) {

	this.defaultOptions = {
		container: '#content',
		onTimeout: onTimeout,
		timeout: 30000,
		timeoutHtml: '<h1 class="title">Requested content unavailable.<h3>An error occured while trying to process your request:</h3><br /><blockquote>Request timed out.</blockquote></b><p>Please wait a few moments and try again.</p>',
		loadingHtml: '<div style="text-align:center;"><img src="/images/ajax-loading.gif" alt="loading..." /></div>'
	}

	var options = $.extend({}, this.defaultOptions, options);

	var $_container = $(options.container);

	var _this = this;
	var _timeout;

	this.render = render;
	this.canvas = $_container;

	function onTimeout() {
		$_container.empty().html(options.timeoutHtml);
	}

	function render(args) {

		if (args == null) args = {};
		if (options.url != null && args.url == null) args.url = options.url;
		if (args.url == null) return;

		clearTimeout(_timeout);
		_timeout = setTimeout(options.onTimeout, options.timeout + 100);

		$_container.empty().html(options.loadingHtml);

		$.ajax({
			url: args.url,
			data: args,
			cache: false,
			timeout: options.timeout,
			success: function (data) { $_container.empty().html(data); clearTimeout(_timeout); $(_this).trigger('renderComplete'); $('body').trigger('ajax'); $('body').addClass('rerender').removeClass('rerender'); }
		});

	}
};
