﻿var calloutOpenFor;

function showCalloutsInternal(parentElement, calloutClassName, calloutStyle) {
	$(parentElement).find(calloutClassName).each(function () {
		var currentElement = $(parentElement).find('#' + $(this).attr('forElement'));
		var position = 'right';
		if ($(this).attr('position') != null) {
			position = $(this).attr('position');
		}
		var text = $(this).html();
		currentElement.callout({ position: position, msg: text, css: calloutStyle });
	});
}

function closeCalloutsInternal(parentElement, calloutClassName) {
	if (null == parentElement) {
		parentElement = $('body');
	}

	$(parentElement).find(calloutClassName).each(function () {
		var currentElement = $(parentElement).find('#' + $(this).attr('forElement'));
		currentElement.unbind('focus');
		currentElement.unbind('blur');
		currentElement.callout('destroy');
	});
}


function showCallouts(parentElement) {
	var firstElement = null;
	$(parentElement).find('.validationCallout').each(function () {

		var text = $(this).html();

		var currentElement = $(parentElement).find('#' + $(this).attr('forElement'));

		if (firstElement == null) { firstElement = currentElement; }

		var position = 'right';
		if ($(this).attr('position') != null) {
			position = $(this).attr('position');
		}
		currentElement.bind('focus', function () {
			$(this).callout({ position: position, msg: text, css: 'guessValidationCallout' });
			calloutOpenFor = $(this);
		});
		currentElement.bind('blur', function () {
			$(this).callout('destroy');
			calloutOpenFor = null;
		});
		if (currentElement.attr('type') == 'checkbox') {
			currentElement.mouseenter(function () {
				calloutOpenFor.blur();
				var el = $(this);
				setTimeout(function () {
					el.focus();
				}, 500);
			});
		}
	});
	if (firstElement != null) {

		setTimeout(function () {
			firstElement.focus();
		}, 500);
	}
	showCalloutsInternal(parentElement, '.confirmationCallout', 'guessValidationCallout');
}

function closeCallouts(parentElement) {
	closeCalloutsInternal(parentElement, '.validationCallout');
	closeCalloutsInternal(parentElement, '.confirmationCallout');
}

function showInfoCallouts(parentElement) {
	showCalloutsInternal(parentElement, '.infoCallout', 'guessValidationCallout');
}

function closeInfoCallouts(parentElement) {
	closeCalloutsInternal(parentElement, '.infoCallout');
}
