/**
 * Jumix.core
 *
 * @author			Varvanets Konstantin
 * @copyright		Copyright (c) 2009-2010, Jumix
 * @tutorial		http://jumix.ru/manual/
 * @link			http://jumix.ru/
 * @version			1.0.1
 *
 */

$(document).ready(function(){
	$(document).ajaxSend(function(evt, request, settings) {
		if(settings.loader==undefined || settings.loader==true) $.jxInterface.loaderShow();
	});
	$(document).ajaxError(function(evt, request, settings, thrownError) {
		alert("Error requesting page");
		if(settings.loader==undefined || settings.loader==true) $.jxInterface.loaderHide();
	});
	$(document).ajaxComplete(function(evt, request, settings) {
		if(settings.loader==undefined || settings.loader==true) $.jxInterface.loaderHide();
	});
	$(window).bind("resize", $.jxInterface.setBoxCenter);
});

(function($) {
	$.jxInterface = {
		loaderCycle: 0,
		
		// Открытие окна
		openBox: function(name, options) {
			var self = this;
			name = 'jx-interface-box-'+name;
			
			var options = $.extend({
				modal: true,
				width: 'auto',
				height: 'auto',
				content: null,
				closer: true
			}, options || {});
			
			var box = $('#'+name);
			if(box.length==0) {
				var box = $('<div>').attr({'id':name, 'class':'jx-interface-box-container jx-interface-radius-6 jx-interface-shadow'}).css('z-index', self.defMaxZIndex('.jx-interface-box-container:visible')+1000);
				$('body').prepend(box);
				if(options.content!=null) box.html(options.content);
				
				if(options.closer) {
					var closer = $('<div>').attr({'class':'jx-interface-box-closer', 'title':'Close'});
					box.prepend(closer);
					closer.click(function(){
						self.closeBox(box);
					});
				}
			}
			
			// Определение ширины и высоты окна
			box.css({
				width: options.width,
				height: options.height
			});			
			
			// Вывод бокса
			box.show();
			 
			// Установка бокса по центру
			self.setBoxCenter();
			
			// Определение модальности окна
			if(options.modal) box.addClass('jx-interface-box-modal');
			
			self.modalUpdate();
		},
		// Закрытие и удаление окна
		closeBox: function(box) {
			var self = this;
			
			box.remove();
			self.modalUpdate();
		},
		
		// Определение максимального z-index
		defMaxZIndex: function(selector) {
			var result = 0;
			$(selector).each(function(){
				if(result<parseInt($(this).css('z-index')||0)) {
					result = parseInt($(this).css('z-index')||0);
				}
			});
			return result;
		},
		
		// Открытие лоадера
		loaderShow: function() {
			var self = this;
			self.loaderCycle++;
			self.openBox('loader', {width: 'auto', height: '40px', modal: true, closer: false, content: 'Загрузка данных...'});
		},
		// Закрытие лоадера
		loaderHide: function() {
			var self = this;
			
			if(self.loaderCycle>0) {
				self.loaderCycle--;
				if(self.loaderCycle==0) {
					self.closeBox($('#jx-interface-box-loader'));
				}
			}
		},
		
		// Выравнивание бокса по середине окна
		setBoxCenter: function() {
			$('.jx-interface-box-container:visible').each(function(){
				$(this).css({
					left: $(window).width()/2 - ($(this).width() + parseInt($(this).css('padding-left')||0) + parseInt($(this).css('padding-right')||0))/2,
					top: $(window).height()/2 - ($(this).height() + parseInt($(this).css('padding-top')||0) + parseInt($(this).css('padding-bottom')||0))/2
				});
			});
		},
		
		// Открытие ссылки
		requestServer: function(url, requestType) {
			var self = this;
			
			if(requestType==undefined) requestType = 'json';
			$.ajax({
				type:"GET", url:url, dataType:requestType, timeout:180*1000, cache: false, loader: true,
				success:function(result) {
					$.jxInterface.requestServerSuccess(result);
				}
			});
		},
		
		// Обработка результата запроса к серверу
		requestServerSuccess: function(json) {
			var self = this;
			
			// Открытие бокса alert
			if(json.alert!=undefined) {
				alert(json.alert);
			}
			// Открытие бокса подтверждения действия
			if(json.confirm!=undefined) {
				if(confirm(json.confirm.message)) {
					if(json.confirm.ok) $.jxInterface.requestServerSuccess(json.confirm.ok);
				} else {
					if(json.confirm.cancel!=undefined) $.jxInterface.requestServerSuccess(json.confirm.cancel);
				}
			} else {
				// Открытие бокса
				if(json.openBox!=undefined) {
					box = json.openBox;
					self.openBox(box.name||'newWindow', {'width':box.width||'auto', 'height':box.height||'auto', 'closer':box.closer||true, 'modal':box.modal||true, 'content':box.content||'NULL'})
				}
				// Открытие бокса
				if(json.message!=undefined) {
					self.openBox('messageBox', {'closer':true, 'modal':true, 'content':json.message||'NULL'})
				}
				// Перейти по ссылке
				if(json.location!=undefined) {
					if(json.location=="") {
						window.location = crmCurrentLink;
					} else {
						window.location = json.location
					}
				}
				// Выполнить запрос к серверу
				if(json.request!=undefined) {
					$.jxInterface.requestServer(json.request);
				}
			}
		},
		
		// Определение модальности
		modalUpdate: function() {
			var self = this;
			
			var modal = $('#jx-interface-modal');
			if(modal.length==0) {
				var modal = $('<div>').attr({id:'jx-interface-modal'});
				$('body').prepend(modal);
			}
			
			if($('.jx-interface-box-modal:visible').length==0) {
				modal.hide();
			} else {
				modal.show();
				modal.css({zIndex: self.defMaxZIndex('.jx-interface-box-modal:visible')-1});
			}
		}
	};
})(jQuery);
