jQuery(document).ready(function(){
        jQuery(".actionGroup button.ajax").on('click', null, function (e) { e.preventDefault(); });
        jQuery(".actionGroup :input").on('keypress', null, function (e) {
            if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
                jQuery(this).closest(".actionGroup").find("button").click();
                 e.preventDefault();
            }
        });
        
        jQuery(document).on("pfAjaxComplete", sonataAjaxComplete);
		jQuery(".ui-icon-toggle").on('mouseout', null, function (e) { jQuery(this).removeClass('ui-state-hover'); });
		jQuery(".ui-icon-toggle").on('mouseover', null, function (e) { jQuery(this).addClass('ui-state-hover'); });

		sonata.initFormEditingMode();
});

function disablePrimefaceCalendarDates(date, datesAllowed) {
	if(datesAllowed == "") {
		return [true, ''];
	} 
	var dayOfMonth = date.getDate();
	var datesAllowedArray = datesAllowed.split(/\s*,\s*/);
	valid = false;
	for(var i = 0; i < datesAllowedArray.length; i++) {
		var j = datesAllowedArray[i];
		if(j == dayOfMonth || j == 'EOM' && isEOM(date)) {
			valid = true;
		}
	}
	return [valid, ''];
};

/* Return true if the specified date is the last day of the month. */
function isEOM(date) {
	var lastDateOfMonth = new Date();
	lastDateOfMonth.setFullYear(date.getFullYear(), date.getMonth() + 1, 0);
	
	return date.getDate() == lastDateOfMonth.getDate();
} 

function sonataAjaxComplete(e, xhr, o) {
	if (xhr.status == "200" && o.args && o.args.userNotLoggedIn) {
		workingDialog.show();
		window.location.reload(true);
	}
	sonata.initFormEditingMode();
};

jQuery.fn.blink = function(highlightColor, duration) {
    var highlightBg = highlightColor || "#FFFFFF";
    var animateMs = (duration || 600) / 4;
    var originalBg = this.css("backgroundColor");
    this.animate({backgroundColor: highlightBg}, animateMs)
    		.animate({backgroundColor: originalBg}, animateMs)
    		.animate({backgroundColor: highlightBg}, animateMs)
    		.animate({backgroundColor: originalBg}, animateMs);
    return this;
};

jQuery.fn.reveal = function(completeCallBack) {
	var docHeight = jQuery(document).height();
	var wndTop = jQuery(window).scrollTop();
	var wndLeft = jQuery(window).scrollLeft();
	var wndHeight = jQuery(window).height();
	var wndWidth = jQuery(window).width();
	
	var elemTop = this.offset().top;
	var elemLeft = this.offset().left;
	var elemHeight = this.height();
	var elemWidth = this.width();
	
	var revStTop = wndTop;
	var revStLeft = wndLeft

	if (elemTop < wndTop) 
		revStTop = elemTop;
	else if (elemTop + elemHeight > wndTop + wndHeight)
		revStTop = elemTop + elemHeight * 2 - wndHeight;

	if (elemLeft < wndLeft) 
		revStLeft = elemLeft;
	else if (elemLeft + elemWidth > wndLeft + wndWidth)
		revStLeft = elemLeft + elemWidth * 2 - wndWidth;

	jQuery('html, body').animate({scrollTop : revStTop, scrollLeft: revStLeft}, "fast", completeCallBack);
	return this;
}

jQuery.fn.indicate = function(highlightColor, duration) {
	var thisRef = this;
	return this.reveal(function(){
		thisRef.tmpCbCounter = (thisRef.tmpCbCounter || 0) + 1;
		if (thisRef.tmpCbCounter == 1) {
			thisRef.blink(highlightColor, duration);
		}
	});
};

function add(amount1, amount2) {
	return (parseFloat(amount1) + parseFloat(amount2)).toFixed(2);
}

function nanAsZero(value) {
	return isNaN(parseFloat(value)) ? 0 : parseFloat(value).toFixed(2);
}

sonata.__on_form_submit = function(e) {
	setEditingMode(false);
}

sonata.__skip_cancel_confirm_in_this_tick = function(e) {
	var isinediting = sonata.editing;
    setTimeout(function() { setEditingMode(isinediting); }, 1);
    setEditingMode(false);
}

sonata.__on_click_cancel = function(e) {
	if (sonata.editing) {
		if (!window.confirm(sonata.messages.warningBeforeCancel)) {
			e.preventDefault();
			return false;
		}
		setEditingMode(false);
	}

	var oldHandler = e.currentTarget._onclick_deferred;
	if (oldHandler) {
		oldHandler(e);
	}
}

sonata.__on_exit_editing = function(e) {
    setTimeout(function() { workingDialog.hide(); }, 0);
    e.returnValue = sonata.messages.warningBeforeLeavingForm;
	return sonata.messages.warningBeforeLeavingForm;
}

sonata.initFormEditingMode = function() {
	var jq_skipconfirm = jQuery(".skip-auto-confirm");
	jq_skipconfirm.unbind("click", sonata.__skip_cancel_confirm_in_this_tick);
	jq_skipconfirm.bind("click", sonata.__skip_cancel_confirm_in_this_tick);

	var jq_allforms = jQuery("form");
	jq_allforms.unbind("submit", sonata.__on_form_submit);
	jq_allforms.bind("submit", sonata.__on_form_submit);

	if (sonata.autoDetectEditingMode) {
		setEditingMode(false);
	
		var jq_cancelbts = jQuery(".cancel-button:visible").not(jq_skipconfirm);
		
		if ((jq_cancelbts.length > 0 && jq_cancelbts.parent(".ui-dialog").length == 0)
				|| jQuery("form.warn-before-leaving:visible").length > 0) {
			setEditingMode(true);
			jq_cancelbts.unbind("click", sonata.__on_click_cancel);
			jq_cancelbts.bind("click", sonata.__on_click_cancel);
			jq_cancelbts.each(function(){
				var handler = this.onclick;
				if (handler) {
					this.onclick = null;
					this._onclick_deferred = handler;
				}
			});
		}
	}
}

function setEditingMode(editing) {
	sonata.editing = editing;
	if (editing) {
		if(window.addEventListener) {
			window.addEventListener("beforeunload", sonata.__on_exit_editing);
		} else if (window.atachEvent) {
			window.attachEvent("beforeunload", sonata.__on_exit_editing);
		}
	} else {
		if (window.removeEventListener) {
			window.removeEventListener("beforeunload", sonata.__on_exit_editing);
		} else if (window.detachEvent) {
			window.detachEvent("beforeunload", sonata.__on_exit_editing);
		}
	}
}

sonata.localAjaxStart = function(source, selector) {
	var s = (selector ? selector + ", " : "") + ".protected-on-local-ajax";
	jQuery(s).filter(":visible").not(jQuery(source)).not("button, input, select").addClass("protected-on-local-ajax-hidden").hide()
		.after("<img class='protected-on-local-ajax-status' src='" + sonata.contextPath + "/images/ajax-status.gif' />");
	
	jQuery(s).not("[disabled]").not(jQuery(source)).filter("button, input, select").prop("disabled", true)
		.addClass("ui-state-disabled").addClass('protected-on-local-ajax-input-disabled');
}

sonata.localAjaxComplete = function() {
	jQuery(".protected-on-local-ajax-hidden").not("button, input, select").show()
		.parent().find("img.protected-on-local-ajax-status").remove();
	
	jQuery(".protected-on-local-ajax-input-disabled").filter("button, input, select").prop("disabled", false)
		.removeClass("ui-state-disabled").removeClass("protected-on-local-ajax-input-disabled");
}

function isBlankSpace(e) {
	if (document.all) // Internet Explorer
		var whichCode = e.keyCode;
	else if(document.layers) // Nestcape
		var whichCode = e.which;
	else
		var whichCode = (window.Event) ? e.which : e.keyCode;

	if (whichCode == 0 || whichCode == 32) {
		return false;
	} else {
		return true;
	}
}

function disableCutCopyPaste(elemId){
	$(document).ready(function(){
		$(elemId).bind("cut copy paste",function(e) {
			e.preventDefault();
		});
	});		
}