jQuery.fn.center = function () { this.css("position","absolute"); this.css("top", ( $(window).height() - this.height() ) / 2 + $(window).scrollTop() + "px"); this.css("left", ( $(window).width() - this.width() ) / 2 + $(window).scrollLeft() + "px"); return this; };

// SHOW MESSAGE
function showMessage(json) {
	$('#messageBackground').css('display', 'none');
	$('#messageBackground').css('width', ($(window).width() + $(window).scrollLeft()) + 'px');
	$('#messageBackground').css('height', ($(document).height()) + 'px');
	$('#messageBackground').show().animate({ opacity : 0.5 });
	var closeHtml = '<div class="messageClose"><a href="javascript:void(hideMessage());"><img src="/www/images/close.png" border="0" /></a></div>';
	if (typeof(json.callback) != 'undefined' && json.callback != '') { closeHtml = '<div class="messageClose"><a href="' + json.callback + '"><img src="/www/images/close.png" border="0" /></a></div>'; }
	$('#message').html('');
	if (json.title != '') { $('#message').html() + $('#message').html('<div class="messageTitle">' + json.title + '</div>'); }
	$('#message').html(closeHtml + $('#message').html() + '<div class="messageContainer">' + json.message + '</div>');
	var positionTop =  0;
	if (json.position == 'center') { $('#message').center(); } else { alert('toto pos top'); }
	$('#message').show().animate({ opacity : 1.0 });
	if (json.autoClose == 'true') { $('#message').fadeIn('slow').animate({opacity: 1.0}, 2500).fadeOut('slow', function() { hideMessage(); }); }
}

// SHOW POPUP
function showPopup(json) {
	$('#messageBackground').css('display', 'none');
	$('#messageBackground').css('width', ($(window).width() + $(window).scrollLeft()) + 'px');
	$('#messageBackground').css('height', ($(document).height()) + 'px');
	$('#messageBackground').show().animate({ opacity : 0.5 });
	var closeHtml = '<div class="popupClose"><a href="javascript:void(closePopup());"><img src="/www/images/close.png" border="0" /></a></div>';
	if (typeof(json.callback) != 'undefined' && json.callback != '') { closeHtml = '<div class="popupClose"><a href="' + json.callback + '"><img src="/www/images/close.png" border="0" /></a></div>'; }
	$('#popup').html('');
	if (json.title != '') { $('#popup').html() + $('#popup').html('<div class="popupTitle">' + json.title + '</div>'); }
	$('#popup').html(closeHtml + $('#popup').html() + '<div class="popupContainer">' + json.message + '</div>');
	var positionTop =  0;
	$('#popup').css('width', json.width + 'px');
	$('#popup').center();
	$('#popup').show().animate({ opacity : 1.0 });
	if (json.autoClose == 'true') { $('#popup').fadeIn('slow').animate({opacity: 1.0}, 2500).fadeOut('slow', function() { 
			if (json.callback == null || json.callback.length <= 0) { closePopup(); return; } else { doRedirect(json.callback); }
		}); 
	}
}

function hideMessage() { $('#message').hide(); $('#message').html(''); $('#messageBackground').hide(); }
function closePopup() { $('#popup').hide(); $('#popup').html(''); $('#messageBackground').hide(); }

function showSmallLoading(iParentElement) {
	if (iParentElement == null || !existsElement(iParentElement)) { return; }
	var iPos = $('#' + iParentElement).offset();
	$('#smallLoading').css('left', (iPos.left + $('#' + iParentElement).width() + 22) + 'px');
	$('#smallLoading').css('top', (iPos.top) + 'px');
	$('#smallLoading').show().animate({ opacity : 0.5 }, 10);
}

function hideSmallLoading() { $('#smallLoading').hide(); }

// SHOW DIALOG WITH TECHNICAL EXCEPTION
function showException(sTitle, sMessage) {
	$('#exception').html('');
	if (sTitle != '') { $('#exception').html('<div class="exceptionTitle">' + sTitle + '</div>'); }
	$('#exception').html($('#exception').html() + '<div class="exceptionContainer">' + sMessage + '</div>');
	$('#exception').center();
	$('#exception').show().animate({ opacity : 1.0 });
	$.ajax({ url : "/www/ajax/error.php", type : "POST", data : ({title : sTitle, message : sMessage }) });
}

function hideException() { $('#exception').hide(); }

// DO JS REDIRECT
function doRedirect(sUrl) { $('body').html('<div id="redirectLoading">' + $('#redirectLoading').html() + '</div>'); $('#redirectLoading').center(); $('#redirectLoading').show(function() { window.top.location.href=sUrl; }); return false; }

// SHOW MODAL DIALOG WHEN USER SUBMIT INFORMATIONS
function showSubmitFormDialog(formName) { 
	if (formName != null && formName.length > 0) { 
		if ($('form#' + formName + ' .button').length > 0) { 
			$('form#' + formName + ' .button').animate({opacity: 0.2}); 
		}
	}
}

// CLOSE MODAL DIALOG WHEN USER SUBMIT INFORMATIONS
function closeSubmitFormDialog(formName) { if (formName != null && formName.length > 0) { $('form#' + formName + ' .button').animate({opacity: 1.0}, 0); $('form#' + formName + ' .button').attr('disabled', false); $('#submitLoading').hide(); }}

function getLoading() { return $('#loading').html(); }

// GENERIC AJAX LOAD CONTENT
(function($){  
	$.fn.extend({   
		ajaxLoadContent : function(sUrl, dData, containerId, callerId, callbackFunction) {
			var returnedData = null; 
			$.ajax({ type : "POST", url : sUrl, data : dData, dataType : "json",
				beforeSend : function() { 
					hideErrors(); 
					hideException(); 
					if (containerId != null) { $('#' + containerId).animate({opacity:0.2}); }
					showSmallLoading(callerId); },
				error : function(xhr, err, e) { 
					hideSmallLoading(); 
					if (containerId != null) { $('#' + containerId).html(''); } 
					showException('Url not found', xhr.responseText); },
				success : function(json) {
					returnedData = json;
					hideSmallLoading();
					if (json.type == 'returnValue') {
						if (containerId != null) { 
							$('#' + containerId).animate({opacity:1.0}, function() {
								$(this).html(json.value);
								$(this).show();
							});
						}
						if (callbackFunction != null) { eval(callbackFunction); }
					}
					handleJSONType(json);
					if (callbackFunction != null && (json.type == 'popup' || json.type == 'message')) {
						eval(callbackFunction); 
					}					
				}
			});
		}
	});
})(jQuery);

// GENERIC AJAX POST REQUEST
(function($){  
	$.fn.extend({   
		ajaxSubmitForm : function(sUrl, formName, dData, callbackFunction) {
			var returnedData = null;
			$.ajax({ 
				type : "POST", 
				url : sUrl, 
				data : dData, dataType : "json",
				beforeSend : function() { hideErrors(); showSubmitFormDialog(formName); hideException(); },
				error : function(xhr, err, e) { closeSubmitFormDialog(formName); showException('Url not found', xhr.responseText); },
				success : function(json) {
					closeSubmitFormDialog(formName);
					handleJSONType(json);
					if (callbackFunction != null && json.type != 'formErrors' && json.type != 'redirect' && json.type != 'exception') {
						eval(callbackFunction);
					}					
				}
			});
		}
	});
})(jQuery);

function handleJSONType(json) {
	if (json.error) { showException('JSON Error', json.error); return; }
	if (json.type == 'formErrors') { showFormErrors(json); return; }					
	if (json.type == 'message') { showMessage(json); return; }
	if (json.type == 'popup') { showPopup(json); return; }
	if (json.type == 'exception') { showException(json.title, json.message); return; }
	if (json.type == 'redirect') { doRedirect(json.value); return; }
	if (json.type != 'returnValue') { showException('Unvalid response', json); return; }
}

function hideErrors() { 
	$(".fieldError:visible").hide(); 
	$("input[class$='error']").removeClass('error'); 
	$("select[class$='error']").removeClass('error'); 
	$("textarea[class$='error']").removeClass('error'); 
}

function showFormErrors(json) {
	for (var i = 0; i < json.errors.length; i++) { var formError = json.errors[i]; showFormError(json.formName, formError.field, formError.message, formError.reset); if (formError.highlightFields.length > 0) { for (var j = 0; j < formError.highlightFields.length; j++) { highligthField(json.formName, formError.highlightFields[j].field, 'false'); }}}
	if (typeof(json.showContainer) != 'undefined' && json.showContainer != '') { $('#' + json.showContainer).show(); }	
	if (typeof(json.scrollTo) != 'undefined' && json.scrollTo != '') { scrollTo(json.scrollTo); }
}

function highligthField(formId, elementId, bReset) { var fieldId = formId + '_' + elementId; if (!existsElement(fieldId)) { return; } $('#' + fieldId).addClass("error"); if (bReset == 'true') { $('#' + fieldId).val(''); }}
function showFormError(formId, elementId, sMessage, bReset) { highligthField(formId, elementId); var fieldId = formId + '_' + elementId; $('#error_' + fieldId).html('<div class="fieldErrorContainer">' + sMessage + '</div>'); $('#error_' + fieldId).show(); }
function existsElement(elementId) { return ($('#' + elementId).length > 0) ? true : false; }
function isChecked(elementName) { return $('input#' + elementName).is(':checked'); }
function toggleCheckbox(elementName) { if (isChecked(elementName)) { $('#' + elementName).checkbox('uncheck'); } else { $('#' + elementName).checkbox('check'); } } 
function radioValue(formName, elementName) { return $('form#' + formName + ' input[type=radio][name=' + elementName + ']:checked').attr('value'); }
function setRadioValue(formName, elementName, value) { jQuery.each($('form#' + formName + ' input[type=radio][name=' + elementName + ']'), function() { if ($(this).attr('value') == value) { $(this).checkbox('check'); } else { $(this).checkbox('uncheck'); } }); }

