/*
 * Forms
 * form functionality
 */

$(document).ready(function(){

	/* set the find tab possession date to the current month */
	if ($('#posession-date #attrd_40_1860_1').length) {
		var d = new Date();
		$('#posession-date #attrd_40_1860_1').val(d.getMonth() + 1);
	}

	/* move find tab footnote outside of fieldset */
	var footnote = $('fieldset#form_search .footnote');
	if (footnote.length) {
		$('fieldset#form_search').after(footnote);
	}

	/* add class so can be styled like an input field */
	$('form input.form-password').addClass('form-text');

	/*
	 * Report Menu
	 * indent select option items
	 */
	$('select#ReportMenuReport option:contains("--")').each(function() {
		$(this).addClass('indent');
		$(this).text($(this).text().replace('--', '       '));
	});

	/*
	 * Home Page: Find Tab
	 */

	// disable homepage find tab 'Retail Space' radio button
/*
	$('form.fa_form_search #li_attri_40_1641_3 input').attr('disabled', 'disabled');
	$('form.fa_form_search #li_attri_40_1641_3 input').next().addClass('disabled').attr('title', 'Retail Space (Coming Soon)');
*/
	// add 'Class' to checkboxes (home & refine search)
	$('#attri_20_830 label').prepend('Class ');

	/*
	 * Form Labels
	 * remove colon
	 */
	/*$('form label:contains(":")').each(function() {
		var label = $(this).html().replace(':', '');
		$(this).text(label);
	});*/

	/*
	 * Required Fields
	 * currently required fields are just marked with a plain-text *. update these
	 * so that they are <span class="required">*</span>
	 *
	 * TODO: (DK) Form API to include SetRequired()
	 */
	$('form label:contains("* ")').each(function() {
		// get rid of the asterix
		var label = $(this).html().replace('* ', '');
		$(this).text(label);
		// add the revised markup
		$(this).append(' <span class="required">*</span>');
		// add the 'required' class to the input
		$(this).next().addClass('required');
	});

	/*
	 * Autocomplete
	 * disable autocomplete where we're using a custom one
	 * custom autocomplete doesn't work with IE6/7 so keep it on for them
	 */
	$('form.fa_form_search, form.ac-disabled').attr('autocomplete', 'off');

	if ($.browser.msie && jQuery.browser.version < 8) {
		$('form.fa_form_search').attr('autocomplete', 'on');
	}

	/*
	 * Form Sizing
	 * make input widths consistent
	 */
	$('form input.form-text').each(function() {

		if (!$(this).attr('size')) {
			$size = 20;
		} else if ($(this).attr('size') < 6) {
			$size = 5;
		} else if ($(this).attr('size') < 21) {
			$size = 20;
		} else {
			$size = 50;
		}
		$(this).attr('size', $size);
	});

	/*
	 * Form Hint Text
	 * convert title attributes to hint text
	 */
	$('form input[title!=""]').hint();

	/*
	 * Form Errors
	 * add a class to form elements that have errors so we can style them
	 */
	$('form .error').not('form .message.error').each(function() {
		// input element
		if ($(this).prev().attr('tagName') != 'SPAN') {
			$(this).prev().addClass('error');
		}

		// things like radios are hard to tell if there's an error, so throw
		// a class on the label
		$(this).parent().find('label').addClass('error');
		$(this).parent().find('.label').addClass('error');

		// element ordering isn't consistent, so move this to the end
		$(this).parent().after(this);

		// set the left margin to the position of the elements
		// note: normally would just find on label, but labels for radio/checkboxes
		//		   are <span class="label">
		var label = $(this).prev().find('.error');
		$(this).css('margin-left', label.outerWidth(true));
	});

	/*
	 * Form Element Ordering
	 * [ label ] [ descr ] [ select/ul/textarea ]
	 * [ label ] [ input ] [ descr ]
	 *
	 * the ordering of form elements isn't the same, which makes it difficult
	 * to style. move the descr to the end.
	 *
	 * [ error ] comes before [ descr ]
	 *
	 * [ label ] [ input/select/ul/textarea ] [ descr ] [ error ]
	 */
	$('form .form-item .descr').each(function() {
		// if we have something (ex./ select/ul) after .descr, move it before .descr
		if ($(this).next().length) {
			$(this).before($(this).next());
		}
	});

	/*
	 * Form Help
	 * if help text exists, add a link to the legend that shows the help on hover
	 *
	 * TODO: this is a demo on the home page 'find a broker' form. functionality
	 * 		 may change. we also need some pretty icons.
	 *
	 * TODO: help icon doesn't work with collapsible fieldsets. it appears, but
	 * 		 you don't see the hover tip
	 */
	$('form fieldset').each(function() {
		$help = $(this).find('div.help');
		if ($help.length) {
			$help.hide();

			// TODO: don't show this for 'Refine Search'
			if ($(this).find('legend').html() != 'Refine Search') {
				$(this).find('legend').append(' <span class="help">[?]</span>');
			}
		}
	});
	$('form fieldset legend .help').tooltip({
      bodyHandler: function() {
			$help = $(this).parents().find('div.help');
			var out = $help.html();
            return out;
        },
        track:true,
        delay:0,
        showURL:false,
        fade:400
    });

	/*
	 * Add a tooltip to perspective reports table header 'market'
	 * act like a form tooltip
	 */
	if ($('table.report').length) {
		// add the help icon & text
		$('table.report th.market').append('<span class="help">&nbsp;</span>');
    $('table.report th.market').append('<div class="help">Results for the geography selected are displayed below. To expand or refine your results where you have access, click on the geography labels in the Market column.</div>');
    $('table.report div.help').hide();

		$('table.report span.help').tooltip({
      bodyHandler: function() {
      $help = $(this).parents().find('div.help');
      var out = $help.html();
        return out;
      },
      track:true,
      delay:0,
      showURL:false,
      fade:400
    });
	}


	/*
	 * Form Help (Individual Field Tooltip)
	 *
	 * NOTE: something here is causing jumpy-ness in IE7/6 on tooltip hover
	 * IE7: space between left + content jumps back n' forth
	 * IE6: left sidebar jumps below bottom of content
	 *
	 * Apparently the above issue is caused by the 'fade' attr
	 */
	$('form .form-item .help').tooltip({
		track:true,
		delay:0,
		showURL:false,
		showBody:': '
	});

	/*
	 * Fieldset Collapse & Expand
	 * <fieldset class="collapsible"> <fieldset class="collapsible collapsed"> <fieldset class="collapsible expanded">
	 */
	$('form fieldset.collapsible').each(function() {
		var fieldset = $(this);
		var legend = $(this).find('legend');

		// wrap the contents in a div
		$(this).append($('<div class="fieldset-wrapper"></div>')
			   .append(fieldset.children(':not(legend):not(.help)')));

		// change the legend to a link & collapse by default
		if (!fieldset.hasClass('expanded')) {
		  	fieldset.addClass('collapsed');
			legend.prepend('<span class="toggle">&rsaquo;</span> ');
			$(this).find('.fieldset-wrapper').toggle();
		} else {
			legend.prepend('<span class="toggle">&lsaquo;</span> ');
		}

		legend.html('<a href="#">' + legend.html() + '</a>').click(function() {
			var fieldset = $(this).parent();
			fieldset.find('.fieldset-wrapper').toggle();

			if (fieldset.hasClass('collapsed')) {
				fieldset.removeClass('collapsed');
				fieldset.addClass('expanded');
				$(this).find('span.toggle').html('&lsaquo;');
			} else if (fieldset.hasClass('expanded')) {
				fieldset.removeClass('expanded');
				fieldset.addClass('collapsed');
				$(this).find('span.toggle').html('&rsaquo;');
			}
			return false;
		});
	});

});
