﻿(function ($) {
	$.fn.loadingImg = function (settings) {
		if ($(this).length < 1) return;
		var def = {
			imgUrl: '/_Themes/Default/Content/images/loading.gif'
		};
		this.options = $.extend({}, def, settings);
		var _plugin = this, exist = false, needShow = false;
		if (this.data("loadImg")) {
			_plugin = this.data("loadImg");
			exist = true;
		}
		else
			this.data("loadImg", _plugin);
		if ($('img.ajax-load-img').length < 1) {
			var loadImg = $('<img class="ajax-load-img" src="' + this.options.imgUrl + '"/>');
			$('body').append(loadImg);
		}
		else
			var loadImg = $('img.ajax-load-img');
		loadImg.hide();
		if (!exist) {
			$('body').ajaxStart(function () { if (needShow) showLoadImg(true) }).ajaxStop(function () { showLoadImg(false) });
			$(window).resize(function () { if (_plugin.isVisible()) loadImg.css({ margin: getImgMargin() }) });
		}
		function getImgMargin() {
			var d = $('body>div.load-img-back');
			return ((d.height() - loadImg.height()) / 2) + "px " + ((d.width() - loadImg.width()) / 2) + "px"
		}
		function showLoadImg(show) {
			if (show && !_plugin.isVisible()) {
				var d = $('<div class="load-img-back"></div>').append(loadImg.show());
				$("body").prepend(d);
				loadImg.css({ margin: getImgMargin() })
			} else
				if (_plugin.isVisible()) {
					$('body').append(loadImg.hide());
					$('body>div.load-img-back').empty().remove();
				}
		}
		this.canShows = function (yes) {
			needShow = !(typeof (yes) === 'undefined' || yes == null || !yes);
			if (!needShow && _plugin.isVisible()) showLoadImg(false);
		}
		this.isVisible = function (yes) {
			if (typeof (yes) === 'undefined' || yes == null) {
				var d = $('body>div.load-img-back');
				return d && d.length > 0
			}
			showLoadImg(yes);
			return _plugin;
		}
		return _plugin;
	}
})(jQuery);
