// default empty value for fields (adapter from http://plugins.jquery.com/project/empty_value)
// hides default value when focusing on an object
$.fn.empty_value = function(empty_value, options)
{
	var settings = $.extend({
		'reset'			: true,
		'class_name'	: 'empty',
		'expand'		: false
	}, options);
	
	return this.each(function()
	{
		$(this).data('empty_value', empty_value);
		
		$(this).focus(function()
			{
				var elm = this;
				if ($(elm).hasClass(settings.class_name))
				{
					if ($(elm).data('passwordClone'))
					{
						var real = $('#' + $(elm).data('passwordClone'));
						$(elm).remove();
						elm = real.show().focus();
					}
					
					$(elm).removeClass(settings.class_name);
					if (settings.reset)
					{
						$(elm).val('').attr('title', '');
					}
					if (false !== settings.expand)
					{
						$(elm)
							.data('oldHeight', $(elm).height())
							.animate({ 'height': settings.expand }, 'fast');
					}
				}
			})
			.blur(function()
			{
				var val = $(this).val();
				if (!val || val == $(this).data('empty_value'))
				{
					var restore = function(elm)
					{
						$(elm)
							.addClass(settings.class_name)
							.val($(elm).data('empty_value'))
							.attr('title', $(elm).data('empty_value'));
						if ($(elm).attr('type').toLowerCase() == 'password')
						{
							var cloneId = $(elm).attr('id') + '_clone';
							$(elm)
								.data('hasClone', cloneId)
								.hide();
							$('<input/>')
								.attr('id', cloneId)
								.data('passwordClone', $(elm).attr('id'))
								.attr('type', 'text')
								.attr('class', $(elm).attr('class'))
								.empty_value($(elm).val(), settings)
								.appendTo($(elm).parent());
						}
					};
					if (false !== settings.expand && $(this).data('oldHeight'))
					{
						$(this).animate({
							'height': $(this).data('oldHeight') + 'px'
						}, 'fast', null, function() { restore(this); });
					}
					else
					{
						restore(this);
					}
				}
			})
			.blur();
	});
};

// add form validation (basic emptiness check)
$.fn.add_validation = function()
{
	return this.each(function()
	{
		
		// change the submit action
		$(this).submit(function(e)
		{
			// hide previous error messages
			$(this).find('.form_error').slideUp().remove();
			
			// find out required fields and stack them in required array
			var required = [];
			$(this).find('.required').each(function()
			{
				if ($(this).is('label'))
				{
					if ($(this).attr('for'))
					{
						required.push($(this).attr('for'));
					}
					else if ($(this).attr('disablefor'))
					{
						required.push($(this).parent().attr('id').replace(/\-label$/, ''));
					}
				}
				else if ($(this).is(':input') && $(this).attr('id'))
					{
					required.push($(this).attr('name'));
				}
			});
				
			// collect data
			var data = {};
			$(this).find(':input').each(function()
			{
				if (
					!$(this).hasClass('empty') &&
					$.trim($(this).val()) &&
					$(this).attr('name') &&
					(!$(this).is(':radio') || $(this).prop('checked'))
				)
				{
					data[$(this).attr('name')] = $(this).val();
				}
			});
			
			// set the data inside the form
			$(this).data('form_data', data);
			$(this).data('form_error', false);
			
			// do the required element check
			for (i in required)
			{
				var key = required[i];
				if (!(key in data) || data[key] == 'NONE')
				{
					
					$(this).data('form_error', true);
					
					var error_field = $(':input[name="' + key + '"]:first');
					
					if (!error_field.data('field_error'))
					{
						// remove clone if exists (see empty_value())
						if (error_field.data('hasClone'))
						{
							$('#' + error_field.data('hasClone')).remove();
						}
						
						
						// mark error
						error_field
							.data('field_error', true)
							.effect('highlight', {'color': '#da1a00'}, 2000,
									function() { $(this).data('field_error', false) })
							.focus();
						
						
						// create the error label in the begining of the form
						var label = $(this).find('label[for="' + key + '"]').text();
							$('<p/>')
								.append($('<span/>').addClass('ui-icon ui-icon-alert').css({'float': 'left', 'margin-right': '0.3em'}))
								.append($('<strong/>').text('Error:'))
								.append(' Required field(s) missing.')
								.addClass('ui-state-error form_error')
								.hide().prependTo($(this)).slideDown();
							
						
					}
					
					e.preventDefault();
					return false;
				}
				
			}
			
		//	e.preventDefault();
			
		});
		
		$(this).data('validation', true);
	});
};

// hold submit button disabled on submit
$.fn.holdSubmit = function()
{
	return $(this).each(function()
	{
		$(this).submit(function()
		{
			var _submit = $(this).find(':input[type="submit"]').prop( 'disabled', true );
			
			// release hold after 10 secs
			window.setTimeout(function() { _submit.prop( 'disabled', false ); }, 10000);
		});
	});
}

// submit forms by json
$.fn.jsonify = function(_callback, _post)
{
	// callback method for handling some general errors
	var callback = function(data)
	{
		if (!data.success)
		{
			// not logged in
			if (data.error && data.error.code && data.error.code == 001)
			{
				alert("We're sorry, you must be logged in to do that.\nYou will now be taken to the login page.");
				return window.document.location = '/login';
			}
		}
		
		$(':input[type="submit"]').prop( 'disabled', false );
		
		_callback(data);
	}
	
	return $(this).each(function()
	{
		if (!$(this).data('validation'))
		{
			$(this).add_validation();
		}
		
		$(this).submit(function(e)
		{
			if ((!$(this).data('form_error')) && $(this).data('form_data'))
			{
				$(':input[type="submit"]').prop( 'disabled', true );
				
				var data = $(this).data('form_data');
				data['json'] = 1;
				
				if (_post)
				{
					$.post($(this).attr('action'), data, callback, 'json');
				}
				else {
					$.getJSON($(this).attr('action'), data, callback);
				}
			}
			
			e.preventDefault();
		});
	});
};

$(document).ready(function(){
    // phone input controls
    $('.phone_control').each(function(){
        var inputs = $(this).find(':input');
        inputs.keyup(function(e){
            var _val = $(this).val().replace(/[^\d]/, '');
            $(this).val(_val);
            if (e.keyCode >= 45 && e.keyCode <= 110 &&
            _val.length >= $(this).attr('maxlength')) {
                $(this).next().focus();
            }
        });
    });
    
    // collapsible item fieldsets
    var collapsibles = $('fieldset.collapsible');
    if (collapsibles.length) {
        var hidden = 0;
        collapsibles.each(function(){
            if ($.trim($(this).find(':input:not(select):first').val()) == '') {
                hidden++;
                $(this).hide();
            }
        });
        if (hidden == collapsibles.length) {
            collapsibles.first().show();
        }
        if (hidden > 0) {
            $('<a/>').addClass('button_hover one_more').text('[+] Add another').attr('href', 'javascript://').insertBefore($('form .submit')).click(function(e){
                var left = collapsibles.filter(':hidden');
                if (left.length) {
                    left.first().slideDown('fast').find(':input:first').focus();
                    if (left.length == 1) {
                        $(this).remove();
                    }
                }
                e.preventDefault();
            });
        }
    }
});
