$(document).ready(function() {
	
	// Submit button - disable on click
	$('form').submit(function(){
		$('input[type=submit]:not(.no-disable)', this).attr('disabled', 'disabled');
	});
	
	// Error class on inputs before a field-error
	$('span.field-error').each(function() {
		$(this).parent().find('input,select,textarea').addClass('field-error');
		$(this).parent().next('td.field-info').prepend(this);
	});
	
	
	$('input[title]').each(function() {
		// on focus - make text empty if it is set to emptytext
		$(this).focus(function() {
			if ($(this).attr('value') == $(this).attr('title')) {
				$(this).attr('value', '').removeClass('placeholder-text');
			}
		});
		
		// on blur - make text emptytext if it is empty
		$(this).blur(function() {
			if ($(this).attr('value') == '') {
				$(this).attr('value', $(this).attr('title')).addClass('placeholder-text');
			}
		});
		
		// run the blur event
		$(this).blur();
	});
	
	// on submit - make text empty if it is set to emptytext 
	$('input[title]').closest('form').submit(function() {
		$(this).find('input[title]').each(function() {
			if ($(this).attr('value') == $(this).attr('title')) {
				$(this).attr('value', '');
			}
		});
	});
	
	
	// Expando divs
	$('div.expando').each(function() {
		var $div = $(this);
		var $expander = $(this).prev('h2, h3');
		
		if ($expander.length == 0) {
			$(this).before('<p><a href="javascript:;">' + ($(this).attr('title') ? $(this).attr('title') : 'More information') + '</a></p>');
			$expander = $(this).prev().find('a');
		}
		
		$expander.css('cursor', 'pointer');
		$expander.addClass('expando-open');
		
		$expander.click(function() {
			$div.toggle();
			$div.toggleClass('expanded');
			$expander.toggleClass('expanded');
			return false;
		});
		
		$div.hide();
		
		var $close = $('<p><a href="javascript:;">Close</a></p>');
		$close.appendTo($div);
		$close.addClass('expando-close');
		
		$close.click(function() {
			$div.hide();
			$div.removeClass('expanded');
			$expander.removeClass('expanded');
			return false;
		});
	});
	
	
	
	// Refine add
	$('div.refine-bar div.refine-add select').change(function() {
		if ($(this).val() == '') return;
		
		$('div.refine-bar div.refine-list > div.' + $(this).val()).show().find('input,select').focus();
		
		$('div.refine-bar div.refine-submit').show();
		
		$(this).val('');
	});
	
	// Refine remove
	$('div.refine-bar div.refine-list img.remove').click(function() {
		$(this).parent().find('input,select').val('');
		$(this).parent().hide();
		
		if ($('div.refine-bar div.refine-list > div:visible').length == 0) {
			$('div.refine-bar div.refine-submit').hide();
			$('div.refine-bar').parent('form').submit();
		}
	});
	
	// Hide the button if no refine fields
	if ($('div.refine-bar div.refine-list > div:visible').length == 0) {
		$('div.refine-bar div.refine-submit').hide();
	}
});

