
var homeImages = {};
var buildingRowMinHeight = 80;

jQuery(function($)
{
	// accordions
	$(".accordion-controller").bind("click", function(){
		var accordion = $(this).parent().parent();
		if (accordion.hasClass("auto-close")) {
			$(".accordion-contents", accordion).slideUp();
			$(".controls .up", accordion).show();
			$(".controls .down", accordion).hide();
		}
		var contents = $(this).next();
		if (contents.is(":visible")) {
			contents.stop().slideUp();
			$(".controls .up", this).show();
			$(".controls .down", this).hide();
		}
		else {
			contents.stop().slideDown();
			$(".controls .up", this).hide();
			$(".controls .down", this).show();
		}
	});
	$(".accordion-contents").hide();
	$(".accordion-contents .save-continue").show();
	$(".accordion-contents .save-continue a").click( function(e){
		var accordionItem = $(this).parent().parent().parent();
		$(".accordion-controller", accordionItem).eq(0).click();
		$(".accordion-controller", accordionItem.next()).eq(0).click();
		return false;
	});
	$(".accordion-item.auto-open .accordion-controller").eq(0).click();
	
	enableSmoothScrolling();
	
	/* rounded corners */
	$(".rounded-corners").append('<div class="corner corner-tl"></div><div class="corner corner-tr"></div><div class="corner corner-bl"></div><div class="corner corner-br"></div>');
	$(".small-rounded-corners").append('<div class="corner corner-tl"></div><div class="corner corner-tr"></div><div class="corner corner-bl"></div><div class="corner corner-br"></div>');
	
	/* image rollovers */
	$(".fade-rollover").enableFadeRollover();
	
	/* Encoded email fields */
	$(".encoded").each(function(){ $(this).show().html( decode($(this).html()) ) });
	
	// contact form inline field labels
	$("form.enhanced-fields label").each(function(index, item){
		var setup = setupInlineFieldLabel( "#" + $(this).attr("for"), $(this).html() );
		if (setup) $(item).remove();
	});
	/*$("form.enhanced-fields").submit(function(e){
		var nopass = $(".intra-field-label:not:password", this);
		if(nopass.length > 0){
			nopass.val('');
		}
		return true;
	});*/
	
	// contact form CSS sprites
	$(".enhanced-fields input").setFormSprites();
	$(".enhanced-fields textarea").setFormSprites();
});

function checkNeighborhoodWidths() 
{
	// try to get Google Map info.
	var gMapBottom = 0;
	var gMapPos = $("#mapContainer").position();
	if (gMapPos) {
		gMapBottom = gMapPos.top + $("#mapContainer").height();
	}
	var fullWidth = "760px";
	var smallWidth = "390px";
	$(".neighborhood").each(function(i){
		$(this).css("width", smallWidth);
		if ($(this).position().top > gMapBottom) $(this).css("width", fullWidth);
		
		var showLessDiv = $(".controls .up", this);
		var showMoreDiv = $(".controls .down", this);
		
		var contentsContainer = $(".buildings", this);
		var contentsWrapper = $(".buildings .wrapper", this);
		
		// if they're bigger than the min height, then assume they're expanded.
		if (contentsContainer.height() > (buildingRowMinHeight + 20)) {
			showMoreDiv.hide();
			showLessDiv.show();
		}
		
		// otherwise they're a single row: assess the contents height.
		else {
			showLessDiv.hide();
			if (contentsWrapper.height() > (contentsContainer.height() + 20)) showMoreDiv.show();
			else showMoreDiv.hide();
		}
	});
}

function onBuildingsMoreClick (e) {
	var neighborhood = $(this).parent().parent().parent();
	var thisBuildings = $(".buildings", neighborhood);
	
	// go through all the buildings nodes, collapsing any which we did not click on.
	$(".buildings").each(function(i){
		var b = $(this);
		if (b[0]==thisBuildings[0]) b.animate({height: $(".wrapper", this).height()}, checkNeighborhoodWidths);
		else b.animate({height: buildingRowMinHeight}, checkNeighborhoodWidths);
	});
	
	return false;
}

function onBuildingsLessClick (e) {
	var neighborhood = $(this).parent().parent().parent();
	var buildings = $(".buildings", neighborhood);
	buildings.animate({height: buildingRowMinHeight}, checkNeighborhoodWidths);
	return false;
}

var onFeaturedBuildingsFormChange = function( e )
{
	// collect all the form data
	var types = new Array();
	$("#featured-building-form .type :checked").each(function(i){
		types.push( $(this).val() );
	});
	var ownerships = new Array();
	$("#featured-building-form .ownership :checked").each(function(i){
		ownerships.push( $(this).val() );
	});
	var ages = new Array();
	$("#featured-building-form .age :checked").each(function(i){
		ages.push( $(this).val() );
	});
	var features = new Array();
	$("#featured-building-form .features :checked").each(function(i){
		features.push( $(this).val() );
	});
	var pets = new Array();
	$("#featured-building-form .pets :checked").each(function(i){
		pets.push( $(this).val() );
	});
	
	// if "all manhattan" is checked, then just select ALL. otherwise just select checked boxes.
	var neighborhoods = new Array();
	var relevantCheckboxes = ($("#chkAllNeighborhoods").length > 0 && $("#chkAllNeighborhoods")[0].checked) 
		? $("#featured-building-form .neighborhood-options input")
		: $("#featured-building-form .neighborhood-options input:checked");
	relevantCheckboxes.each(function(i){
		neighborhoods.push( $(this).val() );
	});
	
	var matchedBuildings = [];
	
	$(".featured-building").each(function(i){
		var building = $(this);
		var htmlIDParts = $(this).attr("id").split("-");
		var databaseId = htmlIDParts.pop();
		var match = true;
		
		// do lazy matching: only do successive matches if we've not got FALSE yet.
		
		// look for single points of data in the record first...
		if (neighborhoods.length>0 && $.inArray( building.attr("data-neighborhood"), neighborhoods) == -1) {
			// console.log( "Building "+databaseId+" FAILED: neighborhood "+building.attr("data-neighborhood")+" not in "+neighborhoods );
			match = false;
		}
		
		else if (types.length>0 && $.inArray( building.attr("data-type"), types) == -1) {
			// console.log( "Building "+databaseId+" FAILED: type "+building.attr("data-type")+" not in "+types );
			match = false;
		}
		else if (ownerships.length>0 && $.inArray( building.attr("data-ownership"), ownerships) == -1) {
			// console.log( "Building "+databaseId+" FAILED: ownership "+building.attr("data-ownership")+" not in "+ownerships );
		 	match = false;
		}
		else if (ages.length>0 && $.inArray( building.attr("data-age"), ages) == -1) {
			// console.log( "Building "+databaseId+" FAILED: age "+building.attr("data-age")+" not in "+ages );
			match = false;
		}
		else if (pets.length>0 && $.inArray( building.attr("data-pets"), pets) == -1) {
			// console.log( "Building "+databaseId+" FAILED: pets "+building.attr("data-pets")+" not in "+pets );
			match = false;
		}
		
		// only look through features if needed.
		if (match && features.length > 0) {
			var featureString = "," + building.attr("data-features") + ",";
			for( var i in features )
			{
				if (featureString.indexOf(","+features[i]+",") < 0) {
					// console.log( "Building "+databaseId+" FAILED: feature "+","+features[i]+","+" not in "+featureString );
					match = false;
				}
			}
		}
		
		if (match) {
			matchedBuildings.push( databaseId );
			building.show();
			showMarkerForBuilding( databaseId );
		}
		else {
			building.hide();
			hideMarkerForBuilding( databaseId );
		}
	});
	
	$.cookie( 'FBSearchResults', matchedBuildings.join(","), { expires: 60, path: '/', domain: 'meiergroupnyc.com' } )
	$("#txtSearchResults").val( matchedBuildings.join(",") );
	closeAllInfoWindows();
	
	// for each neighborhood, hide or show depending on contents
	$(".results-list .neighborhood").each(function(i){
		$(this).show();
		var visibleBuildings = $(".featured-building:visible", this);
		if (visibleBuildings.length==0) $(this).hide();
		else {
			$(".count", this).html( "[" + visibleBuildings.length + "]" );
			$(".buildings", this).height( buildingRowMinHeight );
			$(this).show();
		}
	});
	
	checkNeighborhoodWidths();
};

function showFormFlash( holder, errorMsg ) 
{
	if ($(holder + " .form-flash").length==0) $(holder).prepend('<div class="form-flash"></div>');
	$(holder + " .form-flash").html(errorMsg).dequeue().stop().slideDown().idle(4000).slideUp();
}

function onAllNeighborhoodsClick(checkBox)
{
	$("#building-neighborhood input").attr("checked", $(checkBox).attr("checked"));
}

function onNeighborhoodClick( checkBox )
{
	$("#chkAllNeighborhoods").attr("checked", "checked");
	$("#building-neighborhood input").each(function(i, item){
		if (!$(this).attr("checked")) {
			$("#chkAllNeighborhoods").removeAttr("checked");
			return;
		}
	});
}

var decode = function( str )
{
	var r = "";
	var c = str.split(":");
	for( var i in c ) r += String.fromCharCode(Math.sqrt(parseInt(c[i],10) + 384));
	return r;
};

var setupInlineFieldLabel = function( fieldId, fieldLabel )
{
	// apply this on input:text, input:password and textarea ONLY
	var textInput = $("input"+fieldId+":text");
	var type = "text";
	if (textInput.length==0) {
		textInput = $("input"+fieldId+":password");
		type = "password";
	}
	if (textInput.length==0) {
		textInput = $("textarea"+fieldId);
		type = "textarea";
	}
	if (textInput.length==0) return false;
	
	/* add the field label css class to the form field and set the value */
	if (textInput.val()=="" || textInput.val()==fieldLabel) textInput.addClass("intra-field-label").val(fieldLabel);
	
	/* remove the placeholder string when field gets focus */
	textInput.focus(function()
	{
		if($(this).val() == fieldLabel ) $(this).removeClass("intra-field-label").val("");
	});
	
	/* add the field label string when field looses focus */
	textInput.blur(function()
	{
		if($(this).val() == "") $(this).addClass("intra-field-label").val( fieldLabel );
	});
	
	return true;
};

/* Smooth scrolling, see http://www.learningjquery.com/2007/10/improved-animated-scrolling-script-for-same-page-links */
function enableSmoothScrolling() {
	function filterPath(string) {
	    return string
	    .replace(/^\//, "")
	    .replace(/(index|default).[a-zA-Z]{3,4}$/, "")
	    .replace(/\/$/, "");
	}
	var locationPath = filterPath(location.pathname);
	$("a[href *= #]").each(function() {
	    var thisPath = filterPath(this.pathname) || locationPath;
	    if (locationPath == thisPath
	    && (location.hostname == this.hostname || !this.hostname)
	    && this.hash.replace(/#/, "")) {
	        var $target = $(this.hash),
	        target = this.hash;
	        if (target) {
	            var targetOffset = $target.offset().top;
	            $(this).click(function(event) {
	                event.preventDefault();
	                $("html").animate({
	                    scrollTop: targetOffset
	                },
	                400,
	                function() {
	                    location.hash = target;
	                });
	            });
	        }
	    }
	});
}

jQuery.fn.crossFadeImages = function(opts) 
{
	var self = this;
	
	// check global params
	var fade_ms = Math.round(opts.fade * 1000);
	var sleep = Math.round(opts.sleep * 1000);
	var caption = self.find(".alt-caption");
	
	// find images to animate and set initial css attributes
	self.css({position:"relative"});
	var imgs = self.find('img').css({
		position: 'absolute',
		display: 'block',
		visibility: 'hidden',
		top: 0,
		left: 0,
		border: 0
	});
	
	// show first image
	imgs.eq(0).css({ visibility: 'visible' });
	
	// create animation chain
	var countdown = true;
	function create_chain(i, chainf) 
	{
		// building the chain backwards, or inside out
		if (i % 2 == 0) 
		{	
			var i_sleep = i / 2,
					i_hide = (i_sleep - 1 + imgs.length) % imgs.length,
					img_sleep = imgs.eq(i_sleep),
					img_hide = imgs.eq(i_hide);
					
			var newf = function() {
				img_hide.css('visibility', 'hidden');
				setTimeout(chainf, sleep);
			};
		}
		else 
		{
			// still image cross-fade
			var i_from = Math.floor(i / 2),
				i_to = Math.ceil(i / 2) % imgs.length,
				img_from = imgs.eq(i_from),
				img_to = imgs.eq(i_to),
				from_anim = {},
				to_init = { visibility: 'visible' },
				to_anim = {};
				
			if (i_to > i_from) {
				to_init.opacity = 0;
				to_anim.opacity = 1;
			} else {
				from_anim.opacity = 0;
			}
			
			var newf = function() {
				img_to.css(to_init);
				if (from_anim.opacity != undefined)
					img_from.animate(from_anim, fade_ms, 'linear', chainf);
				else
					img_to.animate(to_anim, fade_ms, 'linear', chainf);
				caption.html( img_to.attr("alt") );
			};
		}
		
		// push a countdown check
		if (i == imgs.length * 2 - 2) {
			var newf_orig = newf;
			newf = function() { newf_orig(); }
		}
		
		if (i > 0) return create_chain(i - 1, newf);
		else return newf;
	}
	var animation = create_chain(imgs.length * 2 - 1, function() { return animation(); });
	
	// start animation
	animation();
	
	return self;
};
jQuery.fn.enableFadeRollover = function() 
{
	return this.each(function()
	{
		var opts = { suffix:"_o", fade:0.2 };
		
		var self = $(this);
		self.css("position", "relative");
		
		var imgs = self.find("img").css({
				position: 'absolute',
				display:"block",
				top: 0,
				left: 0
		});
		
		// ensure that the opacity never drops below 0.01, to avoid events being fired.
		imgs.eq(1).css({opacity:0.01});
		
		self.mouseover(function(){
			$(this).find("img").eq(1).stop().animate({opacity:1})
		});
		
		self.mouseout(function(){
			$(this).find("img").eq(1).stop().animate({opacity:0.01});
		});
	});
};
jQuery.fn.setFormSprites = function()
{
	return this.each(function()
	{
		var textInput = $(this);
		
		// ignore checkboxes and radio buttons
		switch ($(this).attr("type")) {
			case "checkbox":
			case "radio":
				return;
		}
		
		textInput.addClass("form-mouseout");
		textInput.mouseover(function() { 
			$(this).addClass("form-mouseover").removeClass("form-mouseout");
		});
		textInput.mouseout(function() { 
			$(this).removeClass("form-mouseover").addClass("form-mouseout");
		});
		textInput.focus(function() { 
			$(this).addClass("form-focus");
		});
		textInput.blur(function() {
			$(this).removeClass("form-focus");
		});
	});
};
jQuery.fn.idle = function(time)
{
	var o = jQuery(this);
	o.queue(function()
	{
		setTimeout(function() { o.dequeue(); }, time);
	});
	return this;
};
jQuery.fn.isEmail = function()
{
	if (/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test( $(this).val().trim() )) return true;
	return false;
};
