var deviceIphone = "iphone";
var deviceIpod = "ipod";
var deviceIpad = "ipad";

//Initialize our user agent string to lower case.
var uagent = navigator.userAgent.toLowerCase();

//**************************
// Detects if the current device is an iPhone.
function DetectIphone()
{
   if (uagent.search(deviceIphone) > -1)
      return true;
   else
      return false;
}

//**************************
// Detects if the current device is an iPod Touch.
function DetectIpod()
{
   if (uagent.search(deviceIpod) > -1)
      return true;
   else
      return false;
}

//**************************
// Detects if the current device is an iPod Touch.
function DetectIpad()
{
   if (uagent.search(deviceIpad) > -1)
      return true;
   else
      return false;
}

//**************************
// Detects if the current device is an iPhone or iPod Touch.
function DetectIphoneOrIpod()
{
    if (DetectIphone())
       return true;
    else if (DetectIpod())
       return true;
    else if (DetectIpad())
       return true;
    else
       return false;
}

function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}



// Email Spam hiding.
function popMail(host,user) {
	var acct = user +'@'+ host;
	self.location.href = 'mailto:'+ acct;
}
function linkMail(host,user,cls) {
	document.write('<a href="javascript:popMail(\''+ host +'\',\''+ user +'\');"');
	if (cls) {
		document.write(' class="'+ cls +'"');
	}
	document.write('>');
	showMail(host,user);
	document.write('</a>');
}
function showMail(host,user) {
	var acct = user +'@'+ host;
	document.write(acct);
}

function disableButton(id)
{
	$('nav_item_' + id).removeClassName('on');
}

function enableButton(id)
{
	$('nav_item_' + id).addClassName('on');
}

function showVideo(mls, id)
{
	_showMedia(mls,id,'video')
}

function showPicture(mls, id)
{
	//880
	_showMedia(mls,id,'picture')
}

function hideAll(mls,type)
{
	var on = $$('#feature_' + mls + ' .full .' + type);
	on.each(function(elm){
		if(elm.visible()) {
			Effect.Fade(elm.identify(), {duration: .25});
		}
	});
}

function _showMedia(mls,id,type)
{
	//alert($('feature_08-4163').getWidth());
	hideAll(mls,'picture');
	hideAll(mls,'video');
	Effect.Appear(type + '_' + id, {duration: .25});
}

var feature_slider_position = 1;
var hasMoved = navigator.userAgent.indexOf("Firefox") > 0 ? true : false;

function featureSlider(direction)
{
	if(direction == 'previous') {
		if(feature_slider_position != 1) {
			switchFeature(feature_slider_position - 1);
		}
	} else if(direction == 'next') {
		if(feature_slider_position != max_feature_slider_position) {
			switchFeature(feature_slider_position + 1);
		}
	}
}

function switchFeature(new_feature_slider_position)
{
	var change = feature_slider_position - new_feature_slider_position;
	var position = (change * 890);
	if(feature_slider_position == 1 && false == hasMoved) {
		position = position + 5;
		hasMoved = true;
		$('features_all').setStyle({marginTop: '5px'});
	}
	if(new_feature_slider_position > feature_slider_position) {
	}
	if(new_feature_slider_position != feature_slider_position) {
		new Effect.Move($('features_all'), {x: position});
	}
	_setPositionLink(new_feature_slider_position);
}

function _setPositionLink(new_feature_slider_position)
{
	$('feature_select_' + feature_slider_position).removeClassName('on');
	$('feature_select_' + new_feature_slider_position).addClassName('on');
	feature_slider_position = new_feature_slider_position;
}

function expandRegion(id)
{
	id = id + '_description';
	elm = $(id);
	var visible = elm.visible();
	_shrinkRegions();

	if(!elm.visible() && false == visible) {
		Effect.BlindDown(id, {duration: .25});
	}
}

function _shrinkRegions()
{
	var divs = $$('#region_info li div');
	divs.each(function(elm){
		if(elm.visible()) {
			Effect.BlindUp(elm.identify(), {duration: .25});
		}
	})
}

function clearField(elm,text)
{
	if(elm.value == text) {
		elm.value = '';
	}
}

function resetField(elm,text)
{
	if(elm.value == '') {
		elm.value = text;
	}
}

function submitShortContact()
{
	var name = $F('short_contact_input_name') == 'Name:' ? '' : $F('short_contact_input_name');
	var email = $F('short_contact_input_email') == 'Email:' ? '' : $F('short_contact_input_email');
	var phone = $F('short_contact_input_phone') == 'Phone:' ? '' : $F('short_contact_input_phone');
	var url = '/contact/submit?form=short&name=' + name +
			  '&email=' + email +
			  '&phone=' + phone;
	new Ajax.Request(url, {
		  method: 'post',
		  onSuccess: function(response) {
		    $('short_contact_form').innerHTML = response.responseText;
		  },
		  onFailure: function(response) {
			    $('short_contact_error').innerHTML = 'There was an error submitting the form.<br />Please try again later.';
			    $('short_contact_error').setStyle({display: 'block'});
			  }
		});

}

function toggleSearchOption(id)
{
	var parent = $(id);
	var optionsDiv = $('options_' + id)

	if(optionsDiv.visible()) {
		_hideSearchOption(parent,optionsDiv);
	} else {
		_hideAllSearchOptions();
		_showSearchOption(parent,optionsDiv)
	}
}

function closeOptions()
{
	_hideAllSearchOptions();
}

function _getOptionsDiv(id)
{
	var optionsDivs = $$('#' + id + ' .property_search_options');
	return optionsDivs[0];
}

function _hideAllSearchOptions()
{
	var parents = $$('#property_search_inner .property_option.selected');
	parents.each(function(elm){
		_hideSearchOption(elm,_getOptionsDiv(elm.identify()));
	});
}

function _hideSearchOption(parent,optionsDiv)
{
	parent.removeClassName('selected');
	optionsDiv.hide();
	$$('.home_right.selected,.home_left.selected').each(function(elm){
		elm.removeClassName('selected');
	});
}

function _showSearchOption(parent,optionsDiv)
{
	parent.addClassName('selected');
	var ancestors = parent.ancestors();
	ancestors[0].addClassName('selected');
	optionsDiv.show();
}

function changeSelect(id)
{
	var selects = $$('#' + id + ' select');
	var selected = null;
	selects.each(function(elm){
		if(elm.getValue() == 0 && selected == null) {
			selected = false;
		} else if(elm.getValue() > 0) {
			selected = true;
		}
	});
	var span = $$('#' + id + ' span.add');
	span[0].innerHTML = true == selected ? 'Edit' : 'Add';
}

function changeInput(id)
{
	var inputs = $$('#' + id + ' input');
	var selected = null;
	inputs.each(function(elm){
		if(elm.checked == false && selected == null) {
			selected = false;
		} else if(elm.checked == true) {
			selected = true;
		}
	});
	var span = $$('#' + id + ' span.add');
	span[0].innerHTML = true == selected ? 'Edit' : 'Add';
}

function clearSearch(id)
{
	jQuery('#propertySearchForm li.checked').click();
	jQuery('#searchPropertyOptionsBedsSelect').val('All');
	jQuery('#searchPropertyOptionsBathsSelect').val('All');
	jQuery('#searchPropertyOptions_regions').removeClass('edit');
	jQuery('#searchPropertyOptions_features').removeClass('edit');
}

function searchReset()
{
	var sections = $$('.property_option');
	sections.each(function(elm){
		clearSearch(elm.identify());
	});
}

function submitSearch()
{
	var regions = _getSearchCheckboxes('#options_towns_and_neighborhoods input');
	var types = _getSearchCheckboxes('#options_property_type input');
	var features = _getSearchCheckboxes('#options_features_and_amenities .features input');
	var amenities = _getSearchCheckboxes('#options_features_and_amenities .amenities input');
	var minprice = $F('search_price_min');
	var maxprice = $F('search_price_max');
	var beds = $F('search_beds');
	var baths = $F('search_baths');

	var qs = '/';

	if(false != regions) {
		qs += 'regions/' + regions + '/';
	}
	if(false != types) {
		qs += 'types/' + types + '/';
	}
	if(false != features) {
		qs += 'features/' + features + '/';
	}
	if(false != amenities) {
		qs += 'amenities/' + amenities + '/';
	}
	if(minprice > 0) {
		qs += 'minprice/' + minprice + '/';
	}
	if(maxprice > 0) {
		qs += 'maxprice/' + maxprice + '/';
	}
	if(beds > 0) {
		qs += 'beds/' + beds + '/';
	}
	if(baths > 0) {
		qs += 'baths/' + baths + '/';
	}
	url = '/jackson-hole-property/search' + qs;
	window.location = url;

}

function _getSearchCheckboxes(selector)
{
	var inputs = $$(selector);
	var selectedInputs = new Array();
	var x = 0;
	inputs.each(function(input){
		if(input.checked) {
			selectedInputs[x] = input.value.replace(/\//g,'\\');
			x++;
		}
	});
	if(selectedInputs.length > 0) {
		return selectedInputs.join('|');
	}
	return false;
}

function enableTab(elm)
{
	_hideContent();
	_deactivateTabs();
	$(elm).addClassName('on');
	var classes = String($(elm).classNames());
	classes = classes.split(' ');
	$(classes[1]).show();
	if($(elm).hasClassName('map')) {
		//console.info('map tab click');
		initialize();
	}
}

function _hideContent()
{
	var contents = $$('#tabs_container .content .citem');
	contents.each(function(content){
		if(content.visible()) {
			content.hide();
		}

	});
}

function _deactivateTabs()
{
	var tabs = $$('#tabs_container .tabs .tab');
	tabs.each(function(tab){
		tab.removeClassName('on');
	});
}

function propertyLeftSetHeight()
{
	$('property_left').setStyle({height: $('property_detail').getHeight() + 'px'});
}

var shadowHeight = {};

function expander(elm)
{
	var container = $(elm).up('.collapsible_list');
	//while(!container.hasClassName('collapsible_list')) {
	//	container = container.up();
	//}
	var contentBox = container.up('.contentBox');
	var shadow = contentBox.down('.shadow');

	$$('#' + container.identify() + ' ul.on div.expander').each(function(expander){
		if(expander.visible()) {
			Effect.BlindUp(expander.identify(), {duration: .5});
			var parents = $(expander).ancestors();
			parents[1].removeClassName('on');
			shadow.setStyle({height: shadowHeight[contentBox.identify()] + 'px'});
		}
	});
	var parents = $(elm).ancestors();
	$(elm).siblings().each(function(item){
		if(item.hasClassName('expander')) {
			if(!item.visible()) {
				Effect.BlindDown(item.identify(), {duration: .5});
				parents[1].addClassName('on');
				var timeoutCallback = function() {
					shadow.setStyle({height: (contentBox.getHeight() + 8) + 'px'});
				}
				shadowHeight[contentBox.identify()] = shadow.getHeight();
				setTimeout(timeoutCallback, 600);
			}
		}
	});
	return false;
}

function swapOverviewImage(id)
{
	$$('#overview_images .container .full div').each(function(img){
		if(img.visible()) {
			Effect.Fade(img.identify(), {duration: .25});
		}
	});
	Effect.Appear('img_' + id, {duration: .25});
	return false;
}

function playVideo()
{
	//var video = { movie:"http://www.circumerrovideo.com/v/c/programid=133540&projectid=43375",
	var video = {
		movie:"http://www.circumerrovideo.com/v/c/projectid=43375&programid=inuog1bc",
		width:"480",
		height:"310",
		majorversion:"8",
		build:"0",
		wmode:"transparent",
		bgcolor: "none",
		quality: "high",
		allowFullScreen: "true",
		align: "middle"
	};
	UFO.create(video,'video_container_inner');
}

function featureToggle(onElm, offElm)
{
	$(onElm).addClassName('on');
	$(onElm + 'Link').addClassName('on');
	$(onElm + 'Cell').setStyle({
						  display: 'block'
					  });

	$(offElm).removeClassName('on');
	$(offElm + 'Link').removeClassName('on');
	$(offElm + 'Cell').setStyle({
						  display: 'none'
					  });
}

var scrollSlideshowTimeout = null;

var scrollSlideshow = function(event)
{
	var scrollContainer = event.target.adjacent('.scrollContainer')[0];
	var scrollArea = scrollContainer.childElements()[0];
	var currentPosition = parseInt(scrollArea.getStyle('left'));
	if(isNaN(currentPosition)) {
		currentPosition = 0;
	}
	var images = scrollArea.childElements();
	var lastImage = images[images.length - 1];
	var direction = -1;

	if($(event.target).hasClassName('left')) {
		direction = 1;
	}

	if('mousedown' == event.type) {
		move();
	} else if('mouseup' == event.type) {
		clearTimeout(scrollSlideshowTimeout);
	}

	function move()
	{
		currentPosition = currentPosition + direction;
		if(currentPosition > 0 || currentPosition <= (scrollArea.getWidth() - scrollContainer.getWidth()) * -1) {
			return;
		}

		scrollArea.setStyle({left: currentPosition + 'px'});
		scrollSlideshowTimeout = setTimeout(move, 5);
	}
}

function swapSlideshowImage(id, elm)
{
	elm = $(elm);
	var fullImg = $('image_' + id);

	if(fullImg.visible()) {
		return;
	}

	fullImg.siblings().each(function(item) {
		if(item.visible()) {
			Effect.Fade(item.identify(), {duration: .25});
		}
	});
	Effect.Appear('image_' + id, {duration: .25});
}

var touchStartX = 0;
var scrollAreaStart = 0;

function touchMoveSlideshow(event) {
	event.preventDefault();
	var currentX = event.targetTouches[0].pageX;
	var amountMoved = null;
	var newPosition = null;

	var scrollArea = $(event.target).up();
	while(false == scrollArea.hasClassName('scrollArea')) {
		scrollArea = scrollArea.up();
	}

	if(currentX < touchStartX) {
		amountMoved = touchStartX - event.targetTouches[0].pageX;
		newPosition = scrollAreaStart - amountMoved;
	} else if(currentX > touchStartX) {
		amountMoved = event.targetTouches[0].pageX - touchStartX;
		newPosition = scrollAreaStart + amountMoved;

	}
	if(newPosition > 0 || newPosition <= (scrollArea.getWidth() - scrollArea.up().getWidth()) * -1) {
		return;
	}
	scrollArea.setStyle({left: newPosition + 'px'});
}

function touchStartSlideshow(event) {
	touchStartX = event.targetTouches[0].pageX;
	var scrollArea = $(event.target).up();
	while(false == scrollArea.hasClassName('scrollArea')) {
		scrollArea = scrollArea.up();
	}
	scrollAreaStart = scrollArea.getStyle('left') == null ? 0 : parseInt(scrollArea.getStyle('left'));
}

var openedTabs = [];

function headerTabClick(event) {

	var li;
	if('li' != $(event.target).tagName) {
		li = $(event.target).up();
	} else {
		li = $(event.target);
	}
	var id = li.identify().substring(0, li.identify().length - 3);
	var modal = $(id + 'HeaderTabModal');

	closeHeaderTabModals();

	if(!modal.visible()) {
		if(true !== openedTabs[id]) {
			$('tabsContainer').setStyle({width: $('tabsContainer').getWidth() + 'px'});
			var listItems = li.up().childElements();
			for(x = listItems.length - 1;x >= 0;x--) {
				listItems[x].absolutize();
			}
			//li.absolutize();
			li.addClassName('on');

			var docWidth = document.viewport.getWidth();
			var headerWidth = $('header_inner').getWidth();
			var offset = (docWidth - headerWidth) / 2;
			if(0 > offset) {
				offset = 0;
			}
			modal.setStyle({right: offset + 'px'});
			$('headerTabModalForm_success').hide();
			$('headerTabModalForm_error').hide();
			$('headerTabModalForm').show();
		}
		var img = li.down();
		img.src = img.src.replace('.png', 'On.png');
		modal.show();

		if(true !== openedTabs[id]) {
			openedTabs[id] = true;
			var inner = modal.down('.innerContainer');
			inner.setStyle({
				height: (modal.down('.outerContainer').getHeight() - parseInt(inner.getStyle('padding-top'))) + 'px'
			});
			var shadow = modal.down('.shadow');
			shadow.setStyle({
				width: (modal.getWidth() + 8) + 'px',
				height: (modal.getHeight() + 8) + 'px'
			});
		}
	}
}

function closeHeaderTabModals()
{
	$$('.headerTabModal').each(function(item) {
		item.hide();
	});
	$$('#tabsContainer li').each(function(item) {
		item.removeClassName('on');
		var img = item.down();
		img.src = img.src.replace('On.png', '.png');
	});
}

function closeSearchTabModal()
{
	var modal = jQuery('.searchTabModal:visible');
	if(0 < jQuery('#featuresSearchTabModal div.toggle:visible').length) {
		toggleFeatures()
	}
	var numSelections = modal.find('li.checked').length;
	if(0 < numSelections) {
		modal.parents('.searchPropertyOptions').addClass('edit');
		modal.parents('.searchPropertyOptions').removeClass('add');
	} else {
		modal.parents('.searchPropertyOptions').removeClass('edit');
		modal.parents('.searchPropertyOptions').addClass('add');
	}
	modal.hide();
}

function submitHeaderModalContactForm(event)
{
	Event.stop(event);

	var form = $(event.target);
	var formValues = {};

	form.getElements().each(function(elm) {
		elm.removeClassName('error');
		if(elm.getValue() != headerTabFormDefaults[elm.name]) {
			formValues[elm.name] = elm.getValue();
		}
	});

	new Ajax.Request(form.action, {
		method: form.method,
		parameters: formValues,
		onSuccess: function() {
			$('headerTabModalForm_success').show();
			$('headerTabModalForm').hide();
		},
		onFailure: function(transport) {
			$('headerTabModalForm_error').show();
			transport.responseJSON.each(function(name) {
				var elm = $('headerTabModalForm_contact_input_' + name);
				if(elm) {
					elm.addClassName('error');
				}
			});
		}
	});
}

function swapSothebysListings(elm)
{
	elm = $(elm);
	$$('#sothebysSelect .sothebysListingsSelect').each(function(select) {
		select.disable();
	});
	var valueArr = elm.getValue().split('_');

	new Ajax.Request('/page/get-sothebys-listings', {
		method: 'post',
		parameters: {
			criteria: valueArr[0],
			order: valueArr[1]
		},
		onSuccess: function(response) {
			$('sothebeysListings').update(response.responseText);
			$$('#sothebysSelect .sothebysListingsSelect').each(function(select) {
				select.enable();
				select.value = elm.getValue();
			});
		},
		onFailure: function(transport) {
			var previousVal;
			if('sothebysListingsHead' == elm.identify()) {
				previousVal = $('sothebysListingsFoot').getValue();
			} else {
				previousVal = $('sothebysListingsHead').getValue();
			}
			$('headerTabModalForm_error').show();
			alert("There was an error retrieving the property list.\nPlease try again.");
			elm.value = previousVal;
			$$('#sothebysSelect .sothebysListingsSelect').each(function(select) {
				select.enable();
			});
		}
	});
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function selectpropertySearchItem(event)
{
	var element = jQuery(event.target);

	while('li' != element.attr('tagName').toLowerCase()) {
		element = element.parent();
	}

	if(element.hasClass('checked')) {
		element.removeClass('checked');
		element.addClass('unchecked');
	} else {
		element.removeClass('unchecked');
		element.addClass('checked');
	}

	propertySearch.count();
}

function openPropertySearchOptionModal(event)
{
	closeSearchTabModal();
	var element = jQuery(event.target);
	if(!element.hasClass('searchPropertyOptions')) {
		element = element.parents('.searchPropertyOptions');
	}

	var type = element.attr('id').split('_')[1];

	var modal = jQuery('#' + type + 'SearchTabModal');
	modal.show();

	if(7 == getInternetExplorerVersion()) {
		modal.find('.innerContainer').height('125px');
	}
	var outerContainer = modal.children('.outerContainer');
	var modalHeight = outerContainer.height() + element.height() + 1;

	var searchTab = modal.find('.searchTab');
	var right = parseInt(searchTab.css('right')) + 15;
	var shadow = modal.children('.shadow');
	if(jQuery('#propertyDetailSearch').length) {
		modalHeight += 5
	}
	shadow.height(modalHeight);
	shadow.width(modal.width() + 10);
	if(jQuery('#propertyDetailSearch').length) {
		modalHeight = 20;
		right = modal.width();
	}
	modal.css({
		top: (modalHeight * -1) + 'px',
		right: (right * -1) + 'px'
	});
}

var propertySearchClass = function() {

	var _searchUrl = '/jackson-hole-property/search/';
	var _countUrl = '/property/count/';
	var _doingAjax = false;
	var _nextCall = null;

	this.submit = function(event)
	{
		event.preventDefault();
		document.location = _searchUrl + _getQuery();
	}

	this.count = function()
	{
		_nextCall = _countUrl + _getQuery();
		_getCount();
	}

	function _getCount()
	{
		if(false == _doingAjax && null != _nextCall) {
			_doingAjax = true;
			url = _nextCall;
			_nextCall = null;

			jQuery.ajax({
				url: url,
				type: 'GET',
				success: function(data) {
					if(null == _nextCall) {
						jQuery('#searchCount span').text(data);
						_doingAjax = false;
					} else {
						_doingAjax = false;
						_getCount();
					}
				}
			});
		}
	}

	function _getQuery()
	{
		return _getTypes()+ _getPrice() + _getBaths() + _getBeds() + _getRegions() + _getAmenities() + _getFeatures();
	}

	function _getTypes()
	{
		var types = [];
		jQuery('#searchPropertyType li.checked span.value').each(function() {
			types.push(jQuery(this).html());
		});
		if(types.length < 1) {
			return '';
		}
		return 'types/' + types.join('|') + '/';
	}

	function _getRegions()
	{
		var regions = [];
		jQuery('#regionsSearchTabModal li.checked span.value').each(function() {
			regions.push(jQuery(this).html());
		});
		if(regions.length < 1) {
			return '';
		}
		return 'regions/' + regions.join('|') + '/';
	}

	function _getPrice()
	{
		var price = {};
		price.minprice = parseInt(jQuery('#searchPropertyOptionsPrice .min').html().replace(/[^0-9]/g, ''));
		price.maxprice = parseInt(jQuery('#searchPropertyOptionsPrice .max').html().replace(/[^0-9]/g, ''));

		var pricePath = 'minprice/' + (isNaN(price.minprice) ? 0 : price.minprice);
		pricePath += '/maxprice/' + (isNaN(price.maxprice) ? 0 : price.maxprice) + '/';

		return pricePath;
	}

	function _getBeds()
	{
		var beds = parseInt(jQuery('#searchPropertyOptionsBedsSelect').val());
		return isNaN(beds) ? '' : 'beds/' + beds + '/';
	}

	function _getBaths()
	{
		var baths = parseInt(jQuery('#searchPropertyOptionsBathsSelect').val());
		return isNaN(baths) ? '' : 'baths/' + baths + '/';
	}

	function _getAmenities()
	{
		var amenities = [];
		jQuery('#featuresSearchTabModal li.checked span.value.a').each(function() {
			amenities.push(jQuery(this).html())
		});
		if(amenities.length < 1) {
			return '';
		}
		return 'amenities/' + amenities.join('|') + '/';
	}

	function _getFeatures()
	{
		var features = [];
		jQuery('#featuresSearchTabModal li.checked span.value.f').each(function() {
			features.push(jQuery(this).html())
		});
		if(features.length < 1) {
			return '';
		}
		return 'features/' + features.join('|') + '/';
	}
}

function clearOptions(elm)
{
	var elm = jQuery(elm).parents('.searchPropertyOptionsModal').find('li.checked');
	elm.removeClass('checked');
	elm.addClass('unchecked');
	propertySearch.count();
}

function toggleFeatures()
{
	var toggleSection = jQuery('#featuresSearchTabModal div.toggle');
	var togleSectionHeight = toggleSection.height();

	if(7 == getInternetExplorerVersion()) {
		var togleSectionHeight = 204;
		if(!jQuery('#featuresSearchTabModal div.toggle:visible').length) {
			jQuery('#featuresSearchTabModal .innerContainer').height(jQuery('#featuresSearchTabModal .innerContainer').height() + togleSectionHeight);
			jQuery('#featuresSearchTabModal div.toggle').css({
				top: '125px',
				position: 'absolute'
			});
		} else {
			jQuery('#featuresSearchTabModal .innerContainer').height(jQuery('#featuresSearchTabModal .innerContainer').height() - togleSectionHeight);
		}
	}
	var shadowHeight = jQuery('#featuresSearchTabModal .shadow').height();
	var newHeight;


	if(0 < jQuery('#featuresSearchTabModal div.toggle:visible').length) {

		jQuery('#featuresSearchTabModal').css({
			top: parseInt(jQuery('#featuresSearchTabModal').css('top')) + togleSectionHeight + 'px'
		});
		newHeight = shadowHeight > togleSectionHeight ? shadowHeight - togleSectionHeight : togleSectionHeight - shadowHeight;
		jQuery('#featuresSearchTabModal .shadow').height(newHeight);
	} else {
		jQuery('#featuresSearchTabModal').css({
			top: parseInt(jQuery('#featuresSearchTabModal').css('top')) - togleSectionHeight + 'px'
		});
		newHeight = shadowHeight + togleSectionHeight;
		jQuery('#featuresSearchTabModal .shadow').height(newHeight);
	}
	toggleSection.toggle();
	jQuery('#featuresSearchTabModal .seeMore').toggle();
	jQuery('#featuresSearchTabModal .seeLess').toggle();
}

var featuredSlideshowControllerClass = function(page)
{
	var _features = jQuery('#featuredPropertyInnerContainer .feature');
	var _currentFeature = 0;
	var _numFeatures = _features.length - 1;
	var _isActive = false;
	var _play = true;
	var _timeout;

	this.play = (function()
	{
		if(_currentFeature == _numFeatures) {
			return;
		}
		_play = true;
		jQuery('#featuredControlButtonsInner img.pause').show();
		jQuery('#featuredControlButtonsInner img.play').hide();
		this.next();
	}).bind(this);

	this.pause = function()
	{
		clearTimeout(_timeout);
		_play = false;
		jQuery('#featuredControlButtonsInner img.pause').hide();
		jQuery('#featuredControlButtonsInner img.play').show();
	}

	this.prev = function()
	{
		if(_currentFeature == 0 || true == _isActive) {
			return;
		}
		var properties = {
			"left": "+=" + _getCurrentItemWidth() + "px"
		};
		_isActive = true;
		jQuery('#featuredPropertyInnerContainer').animate(properties, _options);
		_currentFeature--;
	}

	this.next = function()
	{
		if(_currentFeature == _numFeatures || true == _isActive) {
			return;
		}
		_isActive = true;
		var properties = {
			"left": "-=" + _getCurrentItemWidth() + "px"
		};
		jQuery('#featuredPropertyInnerContainer').animate(properties, _options);
		_currentFeature++;
	}

	function _getCurrentItemWidth()
	{
		var width = jQuery(_features[_currentFeature]).width();
		if(jQuery(_features[_currentFeature]).parents('#propertyIndexTop').length) {
			width += 15;
		}
		return width;
	}

	var _timeoutCallback = (function() {

		this.next();

	}).bind(this);

	var _completeCallback = (function() {

		if(true == _play && _currentFeature < _numFeatures) {
			_timeout = setTimeout(_timeoutCallback, 4000);
		}
		_isActive = false;

		if( _currentFeature == _numFeatures) {
			this.pause();
		}
	}).bind(this)

	var _options = {
		duration: 1000,
		complete: _completeCallback
	};

	_timeout = setTimeout(_timeoutCallback, 4000);
}

var modalClass = function()
{
	var _url;
	this.varr = '/val';

	function _createModal()
	{
		_close();
		var blackout = jQuery('<div id="blackout" />');
		blackout.width(jQuery(document).width());
		blackout.height(jQuery(document).height());
		jQuery('body').append(blackout);

		var outerContainer = jQuery('<div id="OuterContainer" style="height: 150px"></div>');
		jQuery('body').append(outerContainer);

		var innerContainer = jQuery('<div id="InnerContainer"><div id="innerModalShadow" /><div id="modalOuterContent"><div id="modalInnerContent" /></div></div>');
		outerContainer.append(innerContainer);
	}

	function _loadAjax()
	{
		jQuery.ajax({
			url: _url,
			type: 'GET',
			success: function(data) {
				_createModal();
				jQuery('#modalInnerContent').html('<div class="close"></div>' + data);
				jQuery('#innerModalShadow').height(jQuery('#modalOuterContent').height() + 15);
				jQuery('#modalInnerContent .close').click(_close);
				jQuery('#modalInnerContent #form').submit(_submitModal);
			},
			error: function() {
				console.info('error');
			}
		});
	}

	function _close()
	{
		jQuery('#blackout').remove();
		jQuery('#OuterContainer').remove();
	}

	function _submitModal(event)
	{
		event.preventDefault();
		jQuery.ajax({
			url: event.target.action,
			type: event.target.method,
			data: jQuery(event.target).serialize(),
			success: function(data) {
				jQuery('#modalInnerContent').html('<div class="close"></div>' + data);
				jQuery('#innerModalShadow').height(jQuery('#modalOuterContent').height() + 15);
				jQuery('#modalInnerContent .close').click(_close);
				jQuery('#modalInnerContent #form').submit(_submitModal);
			},
			error: function() {
				//console.info('error')
			}
		});
	}

	this.launch = function(url)
	{
		_url = url;
		_loadAjax();
	};
}

function clickMlsInput()
{
	if('MLS or JHSIR ID #' == jQuery('#mlsSearchInput').val()) {
		jQuery('#mlsSearchInput').val('');
	}
}

function blurMlsInput()
{
	if('' == jQuery.trim(jQuery('#mlsSearchInput').val())) {
		jQuery('#mlsSearchInput').val('MLS or JHSIR ID #');
	}
}

var mlsSearch = function()
{
	function _getProperty(mls)
	{
		jQuery.ajax({
			url: '/property/mls-search/',
			data: {mls: mls},
			type: 'POST',
			success: function(data) {
				window.location = data;
			},
			error: function() {
				alert('No property with this MLS or JHSIR Number could be found.');
			}

		});
	}

	this.submit = function(event)
	{
		event.preventDefault();
		var mls = jQuery('#mlsSearchInput').val();
		if(mls == 'MLS or JHSIR ID #') {
			alert('You must enter an MLS Number.');
			return false;
		}
		_getProperty(mls);
	}
}
