$(function(){

	//Automatically focus an element on load
	$(".focus").focus();
	
	//Theme elements
	$(":button,:submit,:reset").each(function(){
		var meta = $(this).metadata();
		$(this).button(meta);
	});
	
	//Event handlers
	$(".event").each(function(){
		
		var meta = $(this).metadata();
		
		//onclick
		if(meta.clickHandler){
			$(this).bind('click', meta.clickArgs, meta.clickHandler);
		}
		
	});
	
	//Dialog initializations
	$(".dialog").each(function(){
		
		var meta = $(this).metadata();
		meta.autoOpen = false;
		$(this).dialog(meta);
		
		if(meta.dialogOK) $(this).bind('dialogOK', meta.dialogOK);
		if(meta.dialogCancel) $(this).bind('dialogCancel', meta.dialogCancel);
		
		$(this)
			.bind('dialogOK', dialogClose)
			.bind('dialogCancel', dialogClose)
			.bind('dialogopen', function(){
				//jQuery automatically focuses on the first focusable element
				//This blurs immediately after that.
				$(this).find(":tabbable:first").blur();
			});
		
	});
	
	//Form elements
	$("INPUT.calendar").each(function(){
		var meta = $(this).metadata();
		meta.ampm = true;
		if($(this).hasClass('time')){
			$(this).timepicker(meta);
		}else if($(this).hasClass('datetime')){
			$(this).datetimepicker(meta);
		}else{
			$(this).datepicker(meta);
		}
	});
	
	/*
	//Chrome UL.links fix (issue with ::first-child::before pseudoselector)
	$("UL.links>LI:first-child").addClass("bugfix");
	*/
	
	//fix for the jQuery accordion animation when the .text paragraph
	//jumps at the end of its slide down
	$('.list .news .text').each(function() {
		this.style.height = this.offsetHeight + 'px';
	});
	
	//only display the first accordion section on load, and hide the others
	$('.list').find('.news').not(':first').removeClass('on').find('.text').hide().end().end().end().show();
	
	//add the click handler onto the title of the accordion section
	//to show/hide the paragraph of text below it
	$('.title').click(function() {
		$(this).closest('.news').toggleClass('on').find('.text').slideToggle(300);
	});
	
	//same functionality as the handler above, except tied to the arrow image
	//rather than the accordion section title
	$('.view-more').click(function() {
		$(this).closest('.news').toggleClass('on').find('.text').slideToggle(300);
	});
	
	/**
	 * Watermark effect for input fields that have the title attribute set
	 */
	var watermark_class = "watermark";
	var watermark_selector = "input[title][type=text].watermarked, textarea[title].watermarked";
	$(watermark_selector)
		//Initializes the watermark as chrome remembers unsubmitted form values
		.each(function(){
			if($(this).val() == $(this).attr('title')){
				$(this).addClass(watermark_class);
			}
		})
		//Clears a watermark when element is focused
		.focus(function() {
			if ($(this).hasClass(watermark_class)) {
				$(this).val('').removeClass(watermark_class);
			}
		})
		//Adds a watermark if element is empty
		.blur(function(event) {
			if ($(this).val() == '') {
				$(this).val($(this).attr('title')).addClass(watermark_class);
			}
		})
		.not(":focus")
			.blur()
			.end()
		.closest('form') //Set an event handler on forms to ensure that watermarks are not submitted
			.submit(function(){
				$(this).find(watermark_selector).each(function(){
					if ($(this).hasClass(watermark_class)) $(this).val('');
				});
			})
	;
	
	//Cause forms marked as ajax to submit via AJAX
	$("FORM.ajax").submit(function(){
		//show the loading ajax gif animation
		$loadingImg = $(this).find('img');
		$loadingImg.removeClass('hidden');
		
		var $form = $(this);
		$form.find("[name=use_ajax]").val(1);
		
		var url = $.query.load($(this).prop('action')).set('ajax', 1);
		
		var data = $(this).serialize();
		$(this).find(watermark_selector).blur();
		$.post(url.toString(), data, function(data, textStatus, jqXHR){
			//Success handler
			$form.trigger('ajaxHandler', [data, textStatus, jqXHR]);
			
			//hide the loading ajax gif animation
			$loadingImg.addClass('hidden');
		});
		
		return false;
		
	}).each(function(){
		var meta = $(this).metadata();
		if(meta.ajaxHandler){
			$(this).bind('ajaxHandler', meta.ajaxHandler);
		}
	});
	
	
	/**
	 * qTip2 plugin to create tooltips on the lease management application form
	 * for fields that need descriptions
	 */
	$('.tooltip').qtip({
		show: 'mouseover',
		hide: 'mouseout',
		style: {
		      classes: 'ui-tooltip-dark ui-tooltip-shadow'
		},
		position: {
			my: 'bottom left',
			at: 'top right'
		}
	});
	
}); //End on ready function



//---------------------------------------
// Event Handlers
//---------------------------------------
function openDialog(event){
	$(event.data).dialog('open');
	return false;
}

function dialogClose(event){
	$(event.target).dialog('close');
}

function clearForm(event){
	$(event.target).closest("FORM")
		.find("INPUT:text,SELECT,TEXTAREA").val('').blur()
		.end().find(".focus").focus();
}

//Handles AJAX form submissions from dialogs
function ajaxContactFormHandler(event, data, textStatus){
	if(data.success){
		$(event.target).find(".error-container").html('');
		$(".dialog").dialog('close');
		clearForm(event);
		//open new thank you page
		window.location.href = "/thanks";
	}else{
		$(event.target).find(".error-container").html(data.errors);
	}
}

//---------------------------------------
// Dialog buttons
//---------------------------------------
btnOK = {
	text: "OK",
	click: function() {
		$(this).trigger('dialogOK');
	}
};
btnCancel = {
	text: "Cancel",
	click: function() {
		$(this).trigger('dialogCancel');
	}
};
