function trim (str, charlist) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: mdsjack (http://www.mdsjack.bo.it)
    // +   improved by: Alexander Ermolaev (http://snippets.dzone.com/user/AlexanderErmolaev)
    // +      input by: Erkekjetter
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: DxGx
    // +   improved by: Steven Levithan (http://blog.stevenlevithan.com)
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // *     example 1: trim('    Kevin van Zonneveld    ');
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: trim('Hello World', 'Hdle');
    // *     returns 2: 'o Wor'
    // *     example 3: trim(16, 1);
    // *     returns 3: 6
 
    var whitespace, l = 0, i = 0;
    str += '';
    
    if (!charlist) {
        // default list
        whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
    } else {
        // preg_quote custom list
        charlist += '';
        whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
    }
    
    l = str.length;
    for (i = 0; i < l; i++) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(i);
            break;
        }
    }
    
    l = str.length;
    for (i = l - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    
    return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}
$(document).ready(function () {
	$('img[align=left]').addClass('float-left').removeAttr('align');
	$('img[align=right]').addClass('float-right').removeAttr('align');
	$.ajaxSetup({cache: false});
	//$(".sidebar-block").corners("9px");
	$(".sidebar-block").corner("9px");
	$("#nav a").hover(function () { $(this).parent().addClass('hover'); }, function () { $(this).parent().removeClass('hover'); });//.wrapInner('<span><span></span></span>');
	$('.radio-textbox').next().hide();
	$('.radio-textbox input').mouseup(function () {
		if($(this).val() == 'Yes')
			$(this).parents('div').next().show();
		else
			$(this).parents('div').next().hide();
	});
	$.fn.encapsulate = function () {
		return this.each(function () {
			$this = $(this);
			var $fieldsets = $this.children('fieldset');
			$fieldsets.each(function (index, dom) {
				$(dom).children('.form-row').wrapAll('<div class="padder"></div>');
			});
			$fieldsets.find('.padder').prepend('<div class="output"></div>').parent().not($this.children('fieldset:first')).children('.padder').hide();
			if($fieldsets.length > 1) {
				$('#signup-form fieldset:not(.no-slide) .padder').each(function (index, dom) {
					$(this).append('<div class="form-row form-row-last"><label>&nbsp;</label><span><button class="next-pane">Next Section</button></span></div>');
				});	
			}
		});
	};
	var $fieldsets = $('#signup-form fieldset');
	$fieldsets.each(function (index, dom) {
		$(dom).children('.form-row').wrapAll('<div class="padder"></div>');
	});
	$('#form-ajax-response, #signup-form fieldset .padder').prepend('<div class="output"></div>').parent().not('.first').children('.padder').hide();
	$('#signup-form fieldset:not(.no-slide) .padder').each(function (index, dom) {
		$(this).append('<div class="form-row form-row-last"><label>&nbsp;</label><span><button class="next-pane">Next Section</button></span></div>');
	});
	$("input").livequery(function () {
		$(this).focus(function() {
			// only select if the text has not changed
			$(this).addClass('focus');
			if(this.value === this.defaultValue)	{
				this.select();
			}
		});
	});
	$("input, textarea").livequery(function () {
		$(this).blur(function() {
			// only select if the text has not changed
			$(this).removeClass('focus');
		});
	});
	$("input:submit, button").livequery(function() {
		$(this).addClass('button');
	});
	$("input:checkbox").livequery(function() {
		$(this).addClass('checkbox');
	});
	$("input:radio").livequery(function() {
		$(this).addClass('radio');
	});
	$("input, button").livequery(function() {
		$(this).hover(function () {
			$(this).toggleClass('hover');
		},
		function () {
			$(this).toggleClass('hover');
		});
	});
	$("fieldset legend").livequery(function() {
		$(this).click(function () {
			$(this).next().slideToggle(500);
			$(this).find('input:first').focus();
		});
	});
	$('.next-pane').live('click', function (e) {
		var $fieldset = $(this).parents('fieldset');
		var paneSer = $fieldset.find('input').fieldSerialize() + '&checkmode=' + $fieldset.children('legend').text().replace(/[^A-Z0-9a-z-_]/, '+');
		var $loader = $('<img />').attr('src', '/themes/Buy Indianapolis Houses/_img/loader.gif');
		$(this).after($loader);
		$.post('/form-process.php', paneSer, function (data) {
			$loader.remove();
			if(data !== '1') {
				$output = $fieldset.find('.output');
				$output.slideUp('slow', function () {
					$output.hide().html(data+'<span class="skip-val">Don\'t care about this? Just want to see the other fields? Click <span>here</span> to see all the fields.</span>').slideDown('slow');
				});
				$.scrollTo($fieldset, 700);
				$fieldset.find('input:first').focus();
			}
			else {
				$fieldset.find('.output').slideUp('slow', function () { $(this).html('') });
				var $padd = $fieldset.next().children('.padder');
				$padd.slideDown(500, function () {
					$.scrollTo($padd.parent(), 700);
					$(this).find('input:first').focus();
				});
			}
		});
		e.preventDefault();
	});
	$('.skip-val span').live('click', function () {
		$(this).parents('fieldset').siblings('fieldset').children('.padder').slideDown();
	});
	$('.out-skip span').click(function () {
		$('#signup-form fieldset .padder').show();
		$.scrollTo($('#signup-form'), 700);
	});
	function handleJSONkickback () {
		$(document).data('showStopper', false);
		var $this = $(this);
		var queryString = $this.formSerialize();
		//var queryString = $.param(formData); 
		$.post('/form-process.php', queryString, function (data) {
			if(data.q !== 'yes') {
				$('legend').siblings('.padder').children('.output').html('');
				var each = data.each;
				var all = data.all;
				$.each(each, function (key, value) {
					var legend = key;
					var items = '';
					var this_error = 0;
					//console.log(legend, value);
					$.each(value, function (index, message) {
						if(typeof message !== 'undefined') {
							items = items + '<li>'+message+'</li>';
							$(document).data('showStopper', true);
							this_error = this_error + 1;
						}
					});
					items = '<ul>'+items+'</ul>';
					var $this_legend = $('legend:contains("'+legend+'")').siblings('.padder').children('.output');
					if(this_error > 0) {
						$this_legend.cmsMessage({ type: 'error', title : 'Whoops! There are some errors with your form!', content: items});
					}
					items = '';
				});
				if($(document).data('showStopper') === true) {
					$.scrollTo($('#signup-form'),700);
				}
			}
			else if(data.q == 'yes') {
				$('#form-ajax-response').cmsMessage('success', 'Success! Your data was submitted.', 'We will get back to you as soon as possible.');
			}
			//console.log(data);
		}, 'json');
		return false;
	}
	$('#form-ajax-response').html('');
	$('#signup-form').submit(handleJSONkickback);
	$('#slidey li').each(function (num, dom) {
		var $this = $(dom);
		var name = $this.text().replace(/[^A-Za-z0-9-_]/g,'-');
		$this.wrapInner('<a href="javascript:;" name="'+name+'"></a>').find('a').prepend('<span>(click to show info)</span>');
	});

	$('#slidey li a').click(function () {
		var $this = $(this);
		var name = trim($this.attr('name'), '-');
		var slide = '<div class="slidey-content"></div>';
		$('#slidey a').removeClass('selected');
		$this.addClass('selected');
		$('#slidey .slidey-content').not('[name='+name+']').slideUp();
		var $slidey = $this.parent().find('.slidey-content');
		if($slidey.length == 0)
			$this.parent().append(slide);
		$slidey = $this.parent().find('.slidey-content');
		$slidey.hide().html('<div>'+$('#hidden-content #'+name.toString()).html() +'</div>').slideToggle();
		
	});
	$('#sendEmail').click(function () {
		$.facebox({
			opacity: 0.5,
			width : '550px',
			dimTime: 400,
			lightenTime: 0,
			slideDownTime: 800,
			slideUpTime: 0,
			loadingImage: '/themes/Buy Indianapolis Houses/_js/facebox/loading.gif',
			closeImage: '/themes/Buy Indianapolis Houses/_js/facebox/closelabel.gif',
			ajax: $(this).attr('href')
		});
		return false;
	});
});