var CM = {
	isiOS: navigator.userAgent.match(/iPod|iPad|iPhone/) !== null ? true : false,
	isIE: navigator.userAgent.match(/MSIE/) !== null ? true : false,
	opacity: $('html').hasClass('opacity'),
	MOUSEUP: this.isiOS ? 'touchend' : 'click',
	debugActive: false,
	orientationEvent: ('DeviceOrientationEvent' in window)
};

function trim(str, chars)
{
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars)
{
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars)
{
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

$(function() {
	if (CM.isiOS)
		$('body').addClass('iPad');

	$('input[type="password"], input[type="text"], input[type="email"]').each(function()
	{
		$(this).focus(function() { $(this).addClass('focus'); }).blur(function() { 	if (!$(this).val() || !$(this).val().length ) $(this).removeClass('focus'); });

		if ($(this).val() && $(this).val().length)
			$(this).addClass('focus');
	});

	// remove help bubbles if supported
	if (Modernizr.inputtypes.email == true)
		$('input[type="email"]').bind('invalid', function(event) { event.preventDefault(); $(this).parents('form').submit(); return false; });

	// adds placeholder like behaviour if not available
	if (!Modernizr.input.placeholder) {
		$('input[placeholder]').each(function() {
			var placeholder = $(this).attr('placeholder');
			if (!$(this).val() || !$(this).val().length)
				$(this).val(placeholder);
			$(this).data({placeholder: placeholder});
			$(this).focus(function() {
				if ($(this).val() == placeholder) {
					$(this).val('');
				}
			}).blur(function() {
				if (!$(this).val() || !$(this).val().length )
					$(this).val(placeholder);
			});
		});
	}

	/* main navigation */
	$('#header nav a, #footer nav a, a#videoPlizy').hover(function()
	{
		if (!$(this).hasClass('active'))
			$(this).addClass('over');
	},
	function() {
		$(this).removeClass('over');
	});

	// catch enter press on iPad: goto next input, or submit form if last element
	$('form').each(function()
	{
		var inputs = $(this).find('input[type=text],input[type=password],input[type=email]'),
			max = inputs.length - 1;

		inputs.each(function(i)
		{
			if (CM.isiOS)
			{
				$(this).data({pos: i});
				if (i < max) {
					$(this).keyup(function(event) {
						if (event.keyCode == 13)
						{
							event.stopImmediatePropagation();
							event.preventDefault();
							// triggering focus don't brings up the keyboard on iPad: need to find a way to do that
							// $(this).parent().parent().find('input[type=password],input[type=text]').eq($(this).data('pos') + 1).trigger('focus');
						}
					});
				}
			}
		});
	}).submit(function()
	{
		$(this).find('input[type=text],input[type=password],input[type=email]').each(function()
		{
			// trim input value
			$(this).val(trim($(this).val()));
		});	
	});
});
