// Find a class of a DOM element by regex pattern
function getClassByPattern(item, pattern)
{
	var classes = item.attr('class').split(' ');

	for (i in classes)
	{
		if (pattern.test(classes[i]))
		{
			return classes[i];
		}
	}

	return '';
}

function removeMessage() {
	return confirm("Do you really want to remove the message?");
}

function removeComment() {
	return confirm("Do you really want to remove the comment?");
}

function removeAccount() {
	return confirm("Do you really want to remove your account at Twitizer, including all submitted messages? Your Twitter account and tweets are not affected.");
}

function associateUploadButtonWithCabinet(button, hoverClass, activeClass) {
	var cabinet = button.closest('.upload-cabinet');
	cabinet.mouseover(function () {
		if (!button.data('active'))
		{
			button.addClass(hoverClass);
		}
		button.data('hover', true);
	});
	cabinet.mouseout(function () {
		button.removeClass(hoverClass); 
		button.data('hover', false);
	});
	cabinet.mousedown(function (e) {
		if (e.which == 1)
		{
			button.removeClass(hoverClass);
			button.addClass(activeClass);
			button.data('active', true);
		}
	});
	$(document).mouseup(function (e) {
		if (e.which == 1)
		{
			if (button.data('hover'))
			{
				button.addClass(hoverClass);
			}
			button.removeClass(activeClass);
			button.data('active', false);
		}
	});
}

function checkIfUploadFileHasFile() {
	var cabinet = $(this).closest('.upload-cabinet');
	if ($(this).val() != "")
	{
		cabinet.addClass('upload-cabinet-has-file');
	}
	else
	{
		cabinet.removeClass('upload-cabinet-has-file');
	}
}

$(function () {
	SI.Files.stylizeAll();

	$('.upload-button').each(function (index) {
		associateUploadButtonWithCabinet($(this), 'upload-button-hover', 'upload-button-active')
	});

	$('.submit-button').click(function () {
		var form = $(this).closest('form');
		var submitNameClass = getClassByPattern($(this), /^submit-name-.+$/);
		if (submitNameClass.length > 12)
		{
			var name = submitNameClass.substring(12);
			$('<input />').attr({
				type: 'hidden',
				name: name,
				value: $(this).text()
			}).appendTo(form);
		}
		var submitConfirmClass = getClassByPattern($(this), /^submit-confirm-.+$/);
		if (submitConfirmClass.length > 15)
		{
			var fun = submitConfirmClass.substring(15);
			if (!eval(fun + "()"))
			{
				return false;
			}
		}
		form.submit();
		return false;
	});

	$('.upload-file').click(checkIfUploadFileHasFile);
	$('.upload-file').change(checkIfUploadFileHasFile);
});

