/* common.js */
function pageInit() {
	setupNav();
	setBodyHeight();
}


function setupNav() {
	$$('#nav_wrapper a').each(function(item) {
		item.addEvent('mouseenter', function() {
			item.tween('color', '#f8bdbd');
		});
		item.addEvent('mouseleave', function() {
			item.tween('color', '#898989');
		});
	});
}


function setBodyHeight() {
	if ($('copyright'))
	{
		var page = $('page_wrapper').getHeight();
		var body = $('body_wrapper').getHeight();
		var window = $(document.body).getHeight();
		var copyright = $('copyright').getHeight();
		if (window > page) {
			var diff = (window - page);
			
			$('body_wrapper').setStyles({
				'height': (diff+body)
			});
		}
	}
}

/*
 * remove system message
 */
function removeSystemMessage() {
	if ($('system_message'))	{
		$('system_message').destroy();
	}
}

/**
 * setup form submit
 * this function allows a page to setup multiple forms to submit via ajax
 * to obtain a json response. passing root id of the elements will setup the 
 * form and button, the success function is an optional function name that will 
 * execute upon success. 
 * Note: This function expects a common naming convention and relys on the function 
 * showSystemMessage()
 */
function setupFormSubmit(id, successFunction) {
	$(id+'_form').addEvent('submit', function(e) {
		// stop the normal submit
		if (e)
		{
			e.stop();
		}
		
		$$('.'+id+'_btn').each(function(el) {
			el.disabled = true;
		});
		// clear any existing errors
		$$('.field_error').each(function(item) {
			item.removeClass('field_error');
		});
		
		this.set('send', {
			onComplete: function(response) { 
				response = JSON.decode(response);
				if (response.success == true) {
					if ($('system_message')) {
						$('system_message').destroy();
					}
					
					if (successFunction != '') {
						window[successFunction](response);
					}
				} else {
					
					showSystemMessage(response.error_message, id+'_form', 'error');
					if (response.errors)
					{
						for(var i=0; i<response.errors.length; i++) {
							if ($(response.errors[i]))
							{
								$(response.errors[i]).addClass('field_error');
							}
						}
					}
					
				}
				$$('.'+id+'_btn').each(function(el) {
					el.disabled = false;
				});
			}
		});
		
		//Send the form.
		this.send();
	});
}

/**
 * show error
 * will inject a div into the identified section of the page using containing 
 * the error text passed.
 * message_type = (error, success, notice)
 */
function showSystemMessage(message_text, section, message_type) {
	removeSystemMessage();
	
	var system_message = new Element('div', {
		'id' : 'system_message',
		'class' : message_type
	});
	system_message.set('html', message_text);
	system_message.inject(section, 'top');
	window.scrollTo(0, system_message.getPosition().y-150);
	//window.scrollTo(0, 0);
}