(function($) {

	/*
	 * jQuery plugin for terrace stuff
	 */
	$.fn.terraceSearch = function(options) {
		var settings = {
			terrace: 'listings.remaxbangor.com'
    		};

		$.extend(settings, options);

		return this.each(function() {
			$.terraceSearch.settings = settings;
			$.terraceSearch.init($(this));
		});
	};

	/*
	 * this is the object that will run the stuff
	 */
	$.terraceSearch = {
		/*
		 * will set this later
		 */
		jObj: {},

		/*
		 * passed from the jQuery plugin
		 */
		settings: {},

		/*
		 * starts it off
		 */
		init: function(jObj){ 
			$.terraceSearch.jObj = jObj;

			$.terraceSearch.bind();
		},

		/*
		 * binds all of the various actions
		 */
		bind: function() { 
			$.terraceSearch.jObj.submit(function() { 
				return $.terraceSearch.form();
			});

			$.terraceSearch.jObj.find('input[name=town]').autocomplete({
				source: 'http://' + $.terraceSearch.settings.terrace + '/properties/townLookup'
			});

			$.terraceSearch.jObj.find('input[name=mls]').change(function() { 
				$.terraceSearch.jObj.find('label.terraceSearch').remove();
			});
		},

		/*
		 * this is for the mls search
		 */
		form: function() { 
			var mls = $.terraceSearch.jObj.find('input[name=mls]').val();

			// If we have an mls number do a lookup, else just submit the form
			if (mls.length) { 
				$.terraceSearch.mls();
				return false;
			} else { 
				return true;
			}
		},

		/*
		 * this will lookup the mls to see if it's real
		 */
		mls: function() { 
			var url = 'http://' + $.terraceSearch.settings.terrace + '/properties/getMls';
			$.ajax({
				url: url,
				type: 'post',
				data: {
					mls: $.terraceSearch.jObj.find('input[name=mls]').val()
				},
				success: function(data) {
					window.location = data;
				},
				error: function() { 
					$.terraceSearch.jObj.find('input[name=mls]').after('<label class="error terraceSearch">MLS Not Found</label>');
				}
			});
		}

	};

})(jQuery);

