var gaKey = "UA-7403156-1";

Element.addMethods({
	scrollTo: function(element){
		var element = $(element);
		var toElement = $(arguments[1]);
		var toPos = toElement.positionedOffset();
		var height = Math.max(toElement.getDimensions().height, 100) + "px";
		var left = (0-parseInt(toPos.left)) + "px";
		new Effect.Morph(element, {style: {left: left}, duration: 0.4, afterFinish: function(){$('formWrapper').morphHeight(toElement);}});
		return element;
	},
	morphHeight: function(element){
		var element = $(element);
		var toElement = $(arguments[1]);
		var duration = (arguments[2] != null ? arguments[2] : 0.3);
		var toPos = toElement.positionedOffset();
		var height = Math.max(toElement.getDimensions().height, 100) + "px";
		new Effect.Morph(element, {style: {height: height}, duration: duration, afterFinish: function(){new Effect.Morph($('formSlider'), {style: {height: height}, duration: 0.1});}});
		return element;
	},
	slideDown: function(element){
		var element = $(element);
		var toElement = $(arguments[1]);
		new Effect.Appear(element, {duration: 0.1, afterFinish: function(){$("formWrapper").morphHeight(toElement, 0.1);}});
	},
	slideUp: function(element){
		var element = $(element);
		var toElement = $(arguments[1]);
		new Effect.Fade(element, {duration: 0.1, afterFinish: function(){$("formWrapper").morphHeight(toElement, 0.1);}});
	}
});


var ContactForm = Class.create({
	initialize: function() {
		this.form = $('contact_form');
		this.sending = false;
		this.standbyScreen = $('contact_standby');
		this.thanksScreen = $('contact_thanks');
		this.errorScreen = $('contact_error');
		this.submitButton = $('contact_submit_img');
		Event.observe("contact_submit_img", "click", this.submit.bindAsEventListener(this));
		// Event.observe("subject_dd", "change", this.changeLayout.bindAsEventListener(this));
		var self = this;
		$$('.formmenu li.nolink').each(function(el){Event.observe(el, "click", self.switchTab.bindAsEventListener(self));});
		$$('.formmenu li.nolink a').each(function(el){Event.observe(el, "click", self.switchTab.bindAsEventListener(self));});

		$('rental_step1_othertype').hide();
		$('sale_step1_othertype').hide();
		$('sale_step1_commercialtype').hide();
		$('sale_step3_objective').hide();
		$('sale_step3_otherpurpose').hide();
		$('sale_step5_otherlocation').hide();
		$('land_step2_objective').hide();
		$('land_step2_otherpurpose').hide();
		$('land_step5_otherlocation').hide();
		Event.observe('rental_type_dd', "change", this.changeRentalType.bindAsEventListener(this));
		Event.observe('sale_type_dd', "change", this.changeSaleType.bindAsEventListener(this));
		Event.observe('sale_purpose_dd', "change", this.changeSalePurpose.bindAsEventListener(this));
		Event.observe('sale_location_dd', "change", this.changeSaleLocation.bindAsEventListener(this));
		Event.observe('land_purpose_dd', "change", this.changeLandPurpose.bindAsEventListener(this));
		Event.observe('land_location_dd', "change", this.changeLandLocation.bindAsEventListener(this));

		$("initMessage").hide();
		$("formSlider").hide();
		// $("penIcon").hide();
		$("generalFields").hide();
		if($('propertyref') || $('developmentref')){
			this.scrollToAndSetActiveTab("sales");
		}else if($('rentalref')){
			this.scrollToAndSetActiveTab("rental");
		}else if($('landref')){
			this.scrollToAndSetActiveTab("land");
		}else{
			$('subject_dd').value = "init";
			$("initMessage").show();
		}
	},
	changeRentalType: function(e){
		$('rental_step1_othertype').hide();
		if (e.target.value == "other") {
			$('rental_step1_othertype').slideDown("formSlideRental");
			$('rental_othertype_txt').focus();
		}else{
			$("formWrapper").morphHeight("formSlideRental");
		}
	},
	changeSaleType: function(e){
		$('sale_step1_othertype').hide();
		$('sale_step1_commercialtype').hide();
		if (e.target.value == "other") {
			$('sale_step1_othertype').slideDown("formSlideSale");
			$('sale_othertype_txt').focus();
		} else if (e.target.value == "commercial") {
			$('sale_step1_commercialtype').slideDown("formSlideSale");
			$('sale_commercialtype_txt').focus();
		}else{
			$("formWrapper").morphHeight("formSlideSale");
		}
		// if (e.target.value != "land"){
		// 	$('sale_step2').show();
		// 	$('sale_step8').show();
		// }
	},
	changeSalePurpose: function(e) {
		$('sale_step3_objective').hide();
		$('sale_step3_otherpurpose').hide();
		if (e.target.value == "investment") {
			$('sale_step3_objective').slideDown("formSlideSale");
		} else if (e.target.value == "other") {
			$('sale_step3_otherpurpose').slideDown("formSlideSale");
			$('sale_otherpurpose_txt').focus();
		}else{
			$("formWrapper").morphHeight("formSlideSale");
		}
	},
	changeSaleLocation: function(e) {
		if (e.target.value == "other") {
			$('sale_step5_otherlocation').slideDown("formSlideSale");
			$('sale_otherlocation_txt').focus();
		} else {
			$('sale_step5_otherlocation').slideUp("formSlideSale");
		}
	},
	changeLandPurpose: function(e) {
		$('land_step2_objective').hide();
		$('land_step2_otherpurpose').hide();
		if (e.target.value == "investment") {
			$('land_step2_objective').slideDown("formSlideLand");
		} else if (e.target.value == "other") {
			$('land_step2_otherpurpose').slideDown("formSlideLand");
			$('land_otherpurpose_txt').focus();
		}else{
			$("formWrapper").morphHeight("formSlideLand");
		}
	},
	changeLandLocation: function(e) {
		if (e.target.value == "other") {
			$('land_step5_otherlocation').slideDown("formSlideLand");
			$('land_otherlocation_txt').focus();
		} else {
			$('land_step5_otherlocation').slideUp("formSlideLand");
		}
	},
	switchTab: function(event){
		event.stop();
		var ob = $(event.target);
		if(ob.tagName == "A"){
			ob = ob.parentNode;
		}
		if($(ob).hasClassName("land")){
			this.scrollToAndSetActiveTab("land");
		}else if($(ob).hasClassName("sales")){
			this.scrollToAndSetActiveTab("sales");
		}else if($(ob).hasClassName("marketing")){
			this.scrollToAndSetActiveTab("marketing");
		}else{
			this.scrollToAndSetActiveTab("rental");
		}
		return false;
	},
	scrollToAndSetActiveTab: function(target){
		$("formSlider").show();
		$("initMessage").hide();
		// $("penIcon").show();
		$("generalFields").show();
		$$('.formmenu li').each(function(ob){ob.removeClassName("current");ob.removeClassName("norborder");});
		if(target == "land"){
			$$('.formmenu .land')[0].addClassName("current");
			$$('.formmenu .sales')[0].addClassName("norborder");
			$("formSlider").scrollTo("formSlideLand");
			$('subject_dd').value = "land";
		}else if(target == "sales"){
			$$('.formmenu .sales')[0].addClassName("current");
			$("formSlider").scrollTo("formSlideSale");
			$('subject_dd').value = "sale";
		}else if(target == "marketing"){
			$$('.formmenu .marketing')[0].addClassName("current");
			$$('.formmenu .rentals')[0].addClassName("norborder");
			$("formSlider").scrollTo("formSlideMarketing");
			$('subject_dd').value = "marketing";
		}else{
			$$('.formmenu .rentals')[0].addClassName("current");
			$$('.formmenu .land')[0].addClassName("norborder");
			$("formSlider").scrollTo("formSlideRental");
			$('subject_dd').value = "rental";
		}
	},
	changeLayout: function(event) {
		var propertyFs = $('propertyFieldset');
		var developmentFs = $('developmentFieldset');

		if(event.target.value == "propertyenquiry"){
			if(propertyFs) $('propertyFieldset').show();
			if(developmentFs) $('developmentFieldset').hide();
		}else if(event.target.value == "developmentenquiry"){
			if(propertyFs) $('propertyFieldset').hide();
			if(developmentFs) $('developmentFieldset').show();
		}else{
			if(propertyFs) $('propertyFieldset').hide();
			if(developmentFs) $('developmentFieldset').hide();
		}
	},
	submit: function(event) {
		if (this.sending) return false;
		// Specific field check
		switch($('subject_dd').value){
			case "sale":
				// Property type
				if($('sale_type_dd').value == ""){
					alert("Please select property type.");
					$('sale_type_dd').focus();
					return false;
				}else if($('sale_type_dd').value == "commercial" && !$('sale_commercialtype_txt').present()){
					alert("Please specify commercial details.");
					$('sale_commercialtype_txt').focus();
					return false;
				}else if($('sale_type_dd').value == "other" && !$('sale_othertype_txt').present()){
					alert("Please specify property type.");
					$('sale_othertype_txt').focus();
					return false;
				}
				// Number of bedrooms
				if($('sale_rooms_dd').value == ""){
					alert("Please select number of bedrooms.");
					$('sale_rooms_dd').focus();
					return false;
				}
				// Property purpose
				if($('sale_purpose_dd').value == ""){
					alert("Please select the purpose of your property.");
					$('sale_purpose_dd').focus();
					return false;
				}else if($('sale_purpose_dd').value == "investment" && $('sale_objective_dd').value == ""){
					alert("Please specify the investment objective.");
					$('sale_objective_dd').focus();
					return false;
				}else if($('sale_purpose_dd').value == "other" && !$('sale_otherpurpose_txt').present()){
					alert("Please specify the investment purpose.");
					$('sale_otherpurpose_txt').focus();
					return false;
				}
				// Price range
				if(!$('sale_from_txt').present()){
					alert("Please specify your price range.");
					$('sale_from_txt').focus();
					return false;
				}
				if(!$('sale_to_txt').present()){
					alert("Please specify your price range.");
					$('sale_to_txt').focus();
					return false;
				}
				// Timescale
				if($('sale_timescale_dd').value == ""){
					alert("Please specify your timescale.");
					$('sale_timescale_dd').focus();
					return false;
				}
				// Location
				if($('sale_location_dd').value == ""){
					alert("Please select preferred location.");
					$('sale_location_dd').focus();
					return false;
				}else if($('sale_location_dd').value == "other" && !$('sale_otherlocation_txt').present()){
					alert("Please specify preferred location.");
					$('sale_otherlocation_txt').focus();
					return false;
				}
				break;
			case "land":
				// Land size
				if(!$('land_landsizefrom_txt').present()){
					alert("Please specify the land size.");
					$('land_landsizefrom_txt').focus();
					return false;
				}
				if(!$('land_landsizeto_txt').present()){
					alert("Please specify the land size.");
					$('land_landsizeto_txt').focus();
					return false;
				}
				// Land purpose
				if($('land_purpose_dd').value == ""){
					alert("Please select the purpose of the land.");
					$('land_purpose_dd').focus();
					return false;
				}else if($('land_purpose_dd').value == "investment" && $('land_objective_dd').value == ""){
					alert("Please specify the investment objective.");
					$('land_objective_dd').focus();
					return false;
				}else if($('land_purpose_dd').value == "other" && !$('land_otherpurpose_txt').present()){
					alert("Please specify the investment purpose.");
					$('land_otherpurpose_txt').focus();
					return false;
				}
				// Price range
				if(!$('land_from_txt').present()){
					alert("Please specify your price range.");
					$('land_from_txt').focus();
					return false;
				}
				if(!$('land_to_txt').present()){
					alert("Please specify your price range.");
					$('land_to_txt').focus();
					return false;
				}
				// Timescale
				if($('land_timescale_dd').value == ""){
					alert("Please specify your timescale.");
					$('land_timescale_dd').focus();
					return false;
				}
				// Location
				if($('land_location_dd').value == ""){
					alert("Please select preferred location.");
					$('land_location_dd').focus();
					return false;
				}else if($('land_location_dd').value == "other" && !$('land_otherlocation_txt').present()){
					alert("Please specify preferred location.");
					$('land_otherlocation_txt').focus();
					return false;
				}
				break;
			case "rental":
				// Property type
				if($('rental_type_dd').value == ""){
					alert("Please select property type.");
					$('rental_type_dd').focus();
					return false;
				}else if($('rental_type_dd').value == "other" && !$('rental_othertype_txt').present()){
					alert("Please specify property type.");
					$('rental_othertype_txt').focus();
					return false;
				}
				// Number of bedrooms
				if($('rental_rooms_dd').value == ""){
					alert("Please select number of bedrooms.");
					$('rental_rooms_dd').focus();
					return false;
				}
				// Number of adults
				if(!$('rental_adults_dd').present()){
					alert("Please select number of adults.");
					$('rental_adults_dd').focus();
					return false;
				}
				// Number of children
				if(!$('rental_children_dd').present()){
					alert("Please select number of children.");
					$('rental_children_dd').focus();
					return false;
				}
				// Date range
				if(!$('rental_from_dd').present()){
					alert("Please specify your dates.");
					$('rental_from_dd').focus();
					return false;
				}
				if(!$('rental_to_dd').present()){
					alert("Please specify your dates.");
					$('rental_to_dd').focus();
					return false;
				}
				break;
		}

		// General field check
		if (!$('firstname_txt').present()) {
			alert("Please specify your name.");
			$('firstname_txt').focus();
			return false;
		}
		if (!$('lastname_txt').present()) {
			alert("Please specify your lastname.");
			$('lastname_txt').focus();
			return false;
		}
		if (!$('country_txt').present()) {
			alert("Please specify your country.");
			$('country_txt').focus();
			return false;
		}
		if (!$('email_txt').present()) {
			alert("Please specify an email address where we can contact you.");
			$('email_txt').focus();
			return false;
		}
		if (!$('phone_txt').present()) {
			alert("Please specify your phone number.");
			$('phone_txt').focus();
			return false;
		}
		if (!$('message_txt').present()) {
			alert("Please type your message.");
			$('message_txt').focus();
			return false;
		}		
		this.thanksScreen.hide();
		this.errorScreen.hide();
		this.standbyScreen.show();
	
		this.send();
		return true;
	},
	send: function() {
		this.sending = true;
		var me = this;
		new Ajax.Request("/addenquiry", {
			method: 'post',
			parameters: $('contact_form').serialize(),
			onSuccess: function(transport) {
				if (transport.responseText == "ok") {
					// me.thanksScreen.show();
					me.errorScreen.hide();
					me.standbyScreen.hide();
					me.submitButton.hide();
					window.location = '/contactus/success_' + $('subject_dd').value;
					// try {
					// 	var pageTracker = _gat._getTracker(gaKey);
					// 	pageTracker._initData();
					// 	pageTracker._trackEvent("formsubmit", "sent", "contactForm");
					// } catch(err) {console.log(err)}
				} else {
					me.thanksScreen.hide();
					me.errorScreen.show();
					me.standbyScreen.hide();	
				}
				$('firstname_txt').enable();
				$('lastname_txt').enable();
				$('email_txt').enable();
				$('message_txt').enable();
				$('subject_dd').enable();
				me.sending = false;
			},
			onFailure: function() {
				me.thanksScreen.hide();
				me.errorScreen.show();
				me.standbyScreen.hide();
				$('firstname_txt').enable();
				$('lastname_txt').enable();
				$('email_txt').enable();
				$('message_txt').enable();
				$('subject_dd').enable();
				me.sending = false;
			}
		});
		$('firstname_txt').disable();
		$('lastname_txt').disable();
		$('message_txt').disable();
		$('email_txt').disable();
		$('subject_dd').disable();
	}
})

function preloadImage(src) {
	var tmpImage = new Image();
	tmpImage.src = src;
}
function swapImage(obj, src) {
	
	obj.src = src;
}

function refSearch(event){
	var key = event.which || event.keyCode;
	if(key == Event.KEY_RETURN){
		event.stop();
		performSearchByRef(Event.element(event).name);
	}
}

var InvestmentForm = {
	initialize: function() {
		this.sending = false;
		this.standbyScreen = $('investment_standby');
		this.thanksScreen = $('investment_thanks');
		this.errorScreen = $('investment_error');
		this.submitButton = $('investment_submit_img');		
		$('investment_step1_othertype').hide();
		$('investment_step1_landsize').hide();
		$('investment_step1_commercialtype').hide();
		$('investment_step3_objective').hide();
		$('investment_step3_otherpurpose').hide();
		$('investment_step6_otherlocation').hide();
		$('investment_step7_othersituation').hide();
		Event.observe('type_dd', "change", this.changeType.bindAsEventListener(this));
		Event.observe('purpose_dd', "change", this.changePurpose.bindAsEventListener(this));
		Event.observe('location_dd', "change", this.changeLocation.bindAsEventListener(this));
		Event.observe('situated_dd', "change", this.changeSituated.bindAsEventListener(this));
		Event.observe('investment_submit_img', "click", this.submit.bindAsEventListener(this));
	},
	changeType: function(e) {
		$('investment_step1_othertype').hide();
		$('investment_step1_landsize').hide();
		$('investment_step1_commercialtype').hide();
		if (e.target.value == "land") {
			$('investment_step1_landsize').show();	
			$('landsizefrom_txt').focus();
			$('investment_step2').hide();
			$('investment_step8').hide();
		} else if (e.target.value == "other") {
			$('investment_step1_othertype').show();	
			$('othertype_txt').focus();
		} else if (e.target.value == "commercial") {
			$('investment_step1_commercialtype').show();	
			$('commercialtype_txt').focus();
		}
		if (e.target.value != "land"){
			$('investment_step2').show();
			$('investment_step8').show();
		}
	},
	changePurpose: function(e) {
		$('investment_step3_objective').hide();
		$('investment_step3_otherpurpose').hide();
		if (e.target.value == "investment") {
			$('investment_step3_objective').show();
		} else if (e.target.value == "other") {
			$('investment_step3_otherpurpose').show();
			$('otherpurpose_txt').focus();
		}
	},
	changeLocation: function(e) {
		if (e.target.value == "other") {
			$('investment_step6_otherlocation').show();
			$('otherlocation_txt').focus();
		} else {
			$('investment_step6_otherlocation').hide();
		}
	},
	changeSituated: function(e) {
		if (e.target.value == "other") {
			$('investment_step7_othersituation').show();
			$('othersituation_txt').focus();
		} else {
			$('investment_step7_othersituation').hide();
		}
	},
	submit: function(e) {
		if (this.sending) return false;
		try {
			// Check Property Type.
			var propertyType = $F('type_dd');
			if (propertyType == "") {
				$('type_dd').focus();
				throw("Please specify 'Property Type'");
			}
			if (propertyType == "commercial" && !$('commercialtype_txt').present()) {
				$('commercialtype_txt').focus();
				throw("Please provide more details about the commercial property");
			}
			if (propertyType == "other" && !$('othertype_txt').present()) {
				$('othertype_txt').focus();
				throw("Please specify more info about 'Property Type'");
			}
			if (propertyType == "land") {
				if (!$('landsizefrom_txt').present() || !$('landsizeto_txt').present()) {
					$('landsizefrom_txt').focus();
					throw("Please specify size of land");
				}
			}
			
			// Bedrooms.
			if (propertyType != "land") {
				if ($F('rooms_dd') == "") {
					$('rooms_dd').focus();
					throw("Please specify 'Minimum number of bedrooms'");
				}
			}
			
			// Purpose of investment.
			var purpose = $F('purpose_dd');
			if (purpose == "") {
				$('purpose_dd').focus();
				throw("Please specify 'Purpose of Investment'");
			}
			if (purpose == "other" && !$('otherpurpose_txt').present()) {
				$('otherpurpose_txt').focus();
				throw("Please specify information about 'Purpose of Investment'");
			}
			if (purpose == "investment") {
				if (!$('objective_dd').present()) {
					$('objective_dd').focus();
					throw("Please specify 'The Objective of the Investment'");
				}
			}
			
			// Price range.
			if (!$('from_txt').present() || !$('to_txt').present()) {
				$('from_txt').focus();
				throw("Please specify 'Your Price Range'");
			}
			
			// Timescale of Purchase.
			if (!$('timescale_dd').present()) {
				$('timescale_dd').focus();
				throw("Please specify 'Timescale of Purchase'");
			}
			
			// Location.
			var location = $F('location_dd');
			if (location == "") {
				$('location_dd').focus();
				throw("Please specify 'Preferred Location'");
			}
			if (location == "other" && !$('otherlocation_txt').present()) {
				$('otherlocation_txt').focus();
				throw("Please specify 'Where You Would Like to Invest'");
			}
			
			// Situated.
			var situated = $F('situated_dd');
			if (situated == "") {
				$('situated_dd').focus();
				throw("Please specify 'Situation of Investment'");
			}
			if (situated == "other" && !$('othersituation_txt').present()) {
				$('othersituation_txt').focus();
				throw("Please specify 'Situation of Investment'");
			}
			
			// Construction.
			if (propertyType != "land") {
				if (!$('construction_dd').present()) {
					$('construction_dd').focus();
					throw("Please specify 'Investment Stage'");
				}
			}
			
			// Name.
			if (!$('firstname_txt').present()) {
				$('firstname_txt').focus();
				throw("Please specify 'Your Name'");
			}
			if (!$('lastname_txt').present()) {
				$('lastname_txt').focus();
				throw("Please specify 'Your Last Name'");
			}
			// Country.
			if (!$('country_txt').present()) {
				$('country_txt').focus();
				throw("Please specify 'Your Country'");
			}
			// Email Address.
			if (!$('email_txt').present() || $F('email_txt').indexOf("@") == -1) {
				$('email_txt').focus();
				throw("Please specify 'Your Email Address'");
			}
			// Phone.
			if (!$('phone_txt').present()) {
				$('phone_txt').focus();
				throw("Please specify 'Your Phone Number'");
			}
			
			// All Good!
			this.thanksScreen.hide();
			this.errorScreen.hide();
			this.standbyScreen.show();
			this.send();
		} catch(e) {
			alert(e);
			return false;
		}
	},
	send: function() {
		this.sending = true;
		var me = this;
		new Ajax.Request("/property-club-signup", {
			method: 'post',
			parameters: $('investment_form').serialize(),
			onSuccess: function(transport) {
				if (transport.responseText == "ok") {
					me.thanksScreen.show();
					me.errorScreen.hide();
					me.standbyScreen.hide();
					me.submitButton.hide();
					window.location = '/brazil-investment-property-club/success';
					// try {
					// 						var pageTracker = _gat._getTracker(gaKey);
					// 						pageTracker._initData();
					// 						pageTracker._trackEvent("formsubmit", "sent", "investmentClubForm");
					// 					} catch(err) {console.log(err)}
				} else {
					me.thanksScreen.hide();
					me.errorScreen.show();
					me.standbyScreen.hide();	
				}
				me.sending = false;
			},
			onFailure: function() {
				me.thanksScreen.hide();
				me.errorScreen.show();
				me.standbyScreen.hide();
				me.sending = false;
			}
		});
	}
}

var DropDownControl = Class.create({
	initialize: function(id) {
		this.id = id;
		this.timeout = 200;
		this.menuItem = null;
		this.closeTimer = null;
		this.bindMouseOverMethod = this.open.bindAsEventListener(this);
		this.bindMouseOutMethod = this.closeDelay.bindAsEventListener(this);		
		Event.observe(id, "mouseover", this.bindMouseOverMethod);
		Event.observe(id, "mouseout", this.bindMouseOutMethod);
		Event.observe(id+"_dd", "mouseover", this.cancelClose.bindAsEventListener(this));
		Event.observe(id+"_dd", "mouseout", this.closeDelay.bindAsEventListener(this));		
	},
	open: function(event) {
		this.cancelClose();
		if (this.menuItem) this.menuItem.hide();
		this.menuItem = $(this.id+"_dd");
		this.menuItem.show();
		$(this.id).absolutize();
		var posX = $(this.id).getStyle("left");
		$(this.id).relativize();
		this.menuItem.setStyle({left: posX});
		if (this.id == "searchmenu_reference") {
			$('searchmenu_reference_value').focus();
		}
	},
	close: function() {
		if (this.menuItem != null) this.menuItem.hide();
		this.menuItem = null;
	},
	closeDelay: function() {
		var me = this;
		this.closeTimer = window.setTimeout(function() { me.close(); }, this.timeout);
	},
	cancelClose: function() {
		if (this.closeTimer) {
			window.clearTimeout(this.closeTimer);
			this.closeTimer = null;
		}
	}
})

var Search = {
	ref: "",
	type: "any",
	size: "any",
	bedrooms: "any",
	pricerange: "any",
	region: "any",
	init: function(type, bedrooms, size, pricerange, region){
		// Init values
		this.type = (type != "null" ? type : "any");
		this.bedrooms = (bedrooms != "null" ? bedrooms : "any");
		this.size = (size != "null" ? size : "any");
		this.pricerange = (pricerange != "" ? pricerange : "any");
		this.region = (region != "null" ? region : "any");
		
		// Init selects
		
		// Type
		var ob = $('searchmenu_type_val');
		if($('searchmenu_type_val')){
			for(i=0;i<ob.options.length;i++){
				if(ob.options[i].value == type){
					ob.selectedIndex = i;
				}
			}
		}
		
		// Bedrooms
		if(bedrooms != ""){
			var minMax = bedrooms.split("-");
			if(minMax.length > 0 && $('searchmenu_bedrooms_min_val')){
				var ob = $('searchmenu_bedrooms_min_val');
				var minVal = (minMax[0].indexOf("+") == -1) ? parseInt(minMax[0]) : ob.options[0].value;
				for(i=0;i<ob.options.length;i++){
					if(ob.options[i].value == minVal){
						ob.selectedIndex = i;
					}
				}
			}
			if(minMax.length > 1 && $('searchmenu_bedrooms_max_val')){
				var ob = $('searchmenu_bedrooms_max_val');
				var maxVal = (minMax[1].indexOf("+") == -1) ? parseInt(minMax[1]) : ob.options[ob.options.length-1].value;
				for(i=0;i<ob.options.length;i++){
					if(ob.options[i].value == maxVal){
						ob.selectedIndex = i;
					}
				}
			}
		}

		// Size
		if(size != ""){
			var minMax = size.split("-");
			if(minMax.length > 0 && $('searchmenu_size_min_val')){
				var ob = $('searchmenu_size_min_val');
				var minVal = (minMax[0].indexOf("+") == -1) ? parseInt(minMax[0]) : ob.options[0].value;
				for(i=0;i<ob.options.length;i++){
					if(ob.options[i].value == minVal){
						ob.selectedIndex = i;
					}
				}
			}
			if(minMax.length > 1 && $('searchmenu_size_max_val')){
				var ob = $('searchmenu_size_max_val');
				var maxVal = (minMax[1].indexOf("+") == -1) ? parseInt(minMax[1]) : ob.options[ob.options.length-1].value;
				for(i=0;i<ob.options.length;i++){
					if(ob.options[i].value == maxVal){
						ob.selectedIndex = i;
					}
				}
			}
		}

		// Price range
		if(pricerange != ""){
			var minMax = pricerange.split("-");
			if(minMax.length > 0){
				var ob = $('searchmenu_pricerange_min_val');
				var minVal = (minMax[0].indexOf("+") == -1) ? parseInt(minMax[0]) : ob.options[0].value;
				for(i=0;i<ob.options.length;i++){
					if(ob.options[i].value == minVal){
						ob.selectedIndex = i;
					}
				}
			}
			if(minMax.length > 1){
				var ob = $('searchmenu_pricerange_max_val');
				var maxVal = (minMax[1].indexOf("+") == -1) ? parseInt(minMax[1]) : ob.options[ob.options.length-1].value;
				for(i=0;i<ob.options.length;i++){
					if(ob.options[i].value == maxVal){
						ob.selectedIndex = i;
					}
				}
			}
			
			// Region
			var ob = $('searchmenu_region_val');
			for(i=0;i<ob.options.length;i++){
				// console.log(ob.options[i].value);
				if(ob.options[i].value == region.toLowerCase().replace(/ /g, "_")){
					ob.selectedIndex = i;
				}
			}
		}
	},
	toggleSearchType: function (type) {
		// $('searchmenu_type_label').update(type);
		this.type = type;
	},
	toggleSearchSizeMin: function(val) {
		var minVal = "";
		var maxVal = "";
		minVal = parseInt(val);
	
		// var currentValue = $('searchmenu_bedrooms_label').innerHTML;
		var currentValue = this.size;
		if (currentValue.indexOf(" - ") != -1) {
			var tmp = currentValue.split(" - ")[1];
			if (tmp != "2000000+") maxVal = parseInt(tmp);
		}

		var textVal = "";
		if (minVal > maxVal) maxVal = minVal;
		if (minVal == 0) textVal = "0 - "; else textVal = minVal + " - ";
		if (maxVal == "2000000+") textVal += "2000000+"; else textVal += maxVal;

		var ob = $('searchmenu_size_max_val');
		// var maxVal = maxVal;
		for(i=0;i<ob.options.length;i++){
			if(ob.options[i].value == maxVal){
				ob.selectedIndex = i;
			}
		}

		// $('searchmenu_bedrooms_label').update(textVal);
		this.size = textVal;
		// console.log("min size set");
	},
	toggleSearchSizeMax: function(val) {
		var minVal = "";
		var maxVal = (val.indexOf("+") == -1) ? parseInt(val) : val;
	
		// var currentValue = $('searchmenu_bedrooms_label').innerHTML;
		var currentValue = this.size;
		if (currentValue.indexOf(" - ") != -1) {
			var tmp = currentValue.split(" - ")[0];
			minVal = parseInt(tmp);
		}

		var textVal = "";
		if (minVal > maxVal) minVal = maxVal;
		if (minVal == 0) textVal = "0 - "; else textVal = minVal + " - ";
		if (maxVal == "2000000+") textVal += "2000000+"; else textVal += maxVal;

		var ob = $('searchmenu_size_min_val');
		// var minVal = minVal;
		for(i=0;i<ob.options.length;i++){
			if(ob.options[i].value == minVal){
				ob.selectedIndex = i;
			}
		}

		// $('searchmenu_bedrooms_label').update(textVal);
		this.size = textVal;
	},
	toggleSearchBedroomsMin: function(val) {
		var minVal = 0;
		var maxVal = 100;
		if (val == "Studio") minVal = 0;
		else minVal = parseInt(val);
	
		// var currentValue = $('searchmenu_bedrooms_label').innerHTML;
		var currentValue = this.bedrooms;
		if (currentValue.indexOf(" - ") != -1) {
			var tmp = currentValue.split(" - ")[1];
			if (tmp != "4+") maxVal = parseInt(tmp);
		}

		var textVal = "";
		if (minVal > maxVal) maxVal = minVal;
		if (minVal == 0) textVal = "Studio - "; else textVal = minVal + " - ";
		if (maxVal == 100) textVal += "4+"; else textVal += maxVal;

		var ob = $('searchmenu_bedrooms_max_val');
		// var maxVal = maxVal;
		for(i=0;i<ob.options.length;i++){
			if(ob.options[i].value == maxVal){
				ob.selectedIndex = i;
			}
		}

		// $('searchmenu_bedrooms_label').update(textVal);
		this.bedrooms = textVal;
	},
	toggleSearchBedroomsMax: function(val) {
		var minVal = 0;
		var maxVal = (val.indexOf("+") == -1) ? parseInt(val) : 100;
	
		// var currentValue = $('searchmenu_bedrooms_label').innerHTML;
		var currentValue = this.bedrooms;
		if (currentValue.indexOf(" - ") != -1) {
			var tmp = currentValue.split(" - ")[0];
			if (tmp != "Studio") minVal = parseInt(tmp);
		}

		var textVal = "";
		if (minVal > maxVal) minVal = maxVal;
		if (minVal == 0) textVal = "Studio - "; else textVal = minVal + " - ";
		if (maxVal == 100) textVal += "4+"; else textVal += maxVal;

		var ob = $('searchmenu_bedrooms_min_val');
		// var minVal = minVal;
		for(i=0;i<ob.options.length;i++){
			if(ob.options[i].value == minVal){
				ob.selectedIndex = i;
			}
		}

		// $('searchmenu_bedrooms_label').update(textVal);
		this.bedrooms = textVal;
	},
	toggleSearchBedroomsAny: function() {
		// $('searchmenu_bedrooms_label').update("Any");	
	},
	toggleSearchPriceMin: function(val) {
		var minVal = parseInt(val);
		var maxVal = "";
	
		// var currentValue = $('searchmenu_pricerange_label').innerHTML;
		var currentValue = this.pricerange;
		if (currentValue.indexOf(" - ") != -1) {
			var tmp = currentValue.split(" - ")[1];
			if (tmp != "500000+") maxVal = parseInt(tmp);
		}
		
		var textVal = "";
		if (minVal > maxVal) maxVal = minVal;
		if (minVal == 0) textVal = "0 - "; else textVal = minVal + " - ";
		if (maxVal == "500000+") textVal += "500000+"; else textVal += maxVal;
	
		var ob = $('searchmenu_pricerange_max_val');
		// var maxVal = maxVal;
		for(i=0;i<ob.options.length;i++){
			if(ob.options[i].value == maxVal){
				ob.selectedIndex = i;
			}
		}

		// $('searchmenu_pricerange_label').update(textVal);
		this.pricerange = textVal;
	},
	toggleSearchPriceMax: function(val) {
		var minVal = "";
		var maxVal = (val.indexOf("+") == -1) ? parseInt(val) : val;
	
		// var currentValue = $('searchmenu_pricerange_label').innerHTML;
		var currentValue = this.pricerange;
		if (currentValue.indexOf(" - ") != -1) {
			var tmp = currentValue.split(" - ")[0];
			// if (tmp != "0" && tmp != "") minVal = parseInt(tmp)*1000;
			minVal = parseInt(tmp);
		}
	
		var textVal = "";
		if (maxVal < minVal) minVal = maxVal;
		if (minVal == 0) textVal = "0 - "; else textVal = minVal + " - ";
		if (maxVal == "500000+") textVal += "500000+"; else textVal += maxVal;

		var ob = $('searchmenu_pricerange_min_val');
		// var minVal = minVal;
		for(i=0;i<ob.options.length;i++){
			// console.log(ob.options[i].value);
			if(ob.options[i].value == minVal){
				ob.selectedIndex = i;
			}
		}

		var ob = $('searchmenu_pricerange_max_val');
		// var maxVal = maxVal;
		for(i=0;i<ob.options.length;i++){
			if(ob.options[i].value == maxVal){
				ob.selectedIndex = i;
			}
		}
	
		// $('searchmenu_pricerange_label').update(textVal);
		this.pricerange = textVal;
	},
	toggleSearchPriceMinRentals: function(val) {
		var minVal = parseInt(val);
		var maxVal = "";
	
		// var currentValue = $('searchmenu_pricerange_label').innerHTML;
		var currentValue = this.pricerange;
		if (currentValue.indexOf(" - ") != -1) {
			var tmp = currentValue.split(" - ")[1];
			if (tmp != "400+") maxVal = parseInt(tmp);
		}
	
		var textVal = "";
		if (minVal > maxVal) maxVal = minVal;
		if (minVal == 0) textVal = "0 - "; else textVal = minVal + " - ";
		if (maxVal == "400+") textVal += "400+"; else textVal += maxVal;

		var ob = $('searchmenu_pricerange_max_val');
		// var maxVal = maxVal;
		for(i=0;i<ob.options.length;i++){
			if(ob.options[i].value == maxVal){
				ob.selectedIndex = i;
			}
		}
	
		// $('searchmenu_pricerange_label').update(textVal);
		this.pricerange = textVal;
	},
	toggleSearchPriceMaxRentals: function(val) {
		var minVal = 0;
		var maxVal = (val.indexOf("+") == -1) ? parseInt(val) : "400+";
	
		// var currentValue = $('searchmenu_pricerange_label').innerHTML;
		var currentValue = this.pricerange;
		if (currentValue.indexOf(" - ") != -1) {
			var tmp = currentValue.split(" - ")[0];
			if (tmp != "0") minVal = parseInt(tmp);
		}
	
		var textVal = "";
		if (maxVal < minVal) minVal = maxVal;
		if (minVal == 0) textVal = "0 - "; else textVal = minVal + " - ";
		if (maxVal == "400+") textVal += "400+"; else textVal += maxVal;

		var ob = $('searchmenu_pricerange_min_val');
		// var minVal = minVal;
		for(i=0;i<ob.options.length;i++){
			if(ob.options[i].value == minVal){
				ob.selectedIndex = i;
			}
		}
	
		// $('searchmenu_pricerange_label').update(textVal);
		this.pricerange = textVal;
	},
	toggleSearchPriceMinLand: function(val) {
		var minVal = parseInt(val);
		var maxVal = "";
	
		// var currentValue = $('searchmenu_pricerange_label').innerHTML;
		var currentValue = this.pricerange;
		if (currentValue.indexOf(" - ") != -1) {
			var tmp = currentValue.split(" - ")[1];
			if (tmp != "2000000+") maxVal = parseInt(tmp);
		}
		
		var textVal = "";
		if (minVal > maxVal) maxVal = minVal;
		if (minVal == 0) textVal = "0 - "; else textVal = minVal + " - ";
		if (maxVal == "2000000+") textVal += "2000000+"; else textVal += maxVal;
	
		var ob = $('searchmenu_pricerange_max_val');
		// var maxVal = maxVal;
		for(i=0;i<ob.options.length;i++){
			if(ob.options[i].value == maxVal){
				ob.selectedIndex = i;
			}
		}

		// $('searchmenu_pricerange_label').update(textVal);
		this.pricerange = textVal;
	},
	toggleSearchPriceMaxLand: function(val) {
		var minVal = "";
		var maxVal = (val.indexOf("+") == -1) ? parseInt(val) : val;
	
		// var currentValue = $('searchmenu_pricerange_label').innerHTML;
		var currentValue = this.pricerange;
		if (currentValue.indexOf(" - ") != -1) {
			var tmp = currentValue.split(" - ")[0];
			// if (tmp != "0" && tmp != "") minVal = parseInt(tmp)*1000;
			minVal = parseInt(tmp);
		}
	
		var textVal = "";
		if (maxVal < minVal) minVal = maxVal;
		if (minVal == 0) textVal = "0 - "; else textVal = minVal + " - ";
		if (maxVal == "2000000+") textVal += "2000000+"; else textVal += maxVal;

		var ob = $('searchmenu_pricerange_min_val');
		// var minVal = minVal;
		for(i=0;i<ob.options.length;i++){
			// console.log(ob.options[i].value);
			if(ob.options[i].value == minVal){
				ob.selectedIndex = i;
			}
		}

		var ob = $('searchmenu_pricerange_max_val');
		// var maxVal = maxVal;
		for(i=0;i<ob.options.length;i++){
			if(ob.options[i].value == maxVal){
				ob.selectedIndex = i;
			}
		}
	
		// $('searchmenu_pricerange_label').update(textVal);
		this.pricerange = textVal;
	},
	toggleSearchPriceAny: function() {
		// $('searchmenu_pricerange_label').update("Any");	
	},
	toggleSearchRegion: function(keyVal, realVal) {
		// $('searchmenu_region_keylabel').writeAttribute("value", keyVal);
		// $('searchmenu_region_label').update(realVal);
		this.region = keyVal;
	},
	performSearch: function(searchMethodType, justReturnString) {
		var str = "/"; //"/"+searchMethodType+"/search/";
		// Type.
		if(searchMethodType != "land-in-brazil"){
			if(this.type != "" && this.type != "null"){
				str += this.type;
				// Bedrooms.
				str += "/";
				// console.log("added type");
			}
			if(this.bedrooms != "" && this.bedrooms != "null"){
				var b = this.bedrooms;
				str += b.replace(/studio/gi, "0");
				str += "/";
				// console.log("added bedrooms");
			}
		}else{
			if(this.size != "" && this.size != "null"){
				str += this.size;
				// Size.
				str += "/";
				// console.log("added size");
			}
		}
		// Price Range.
		str += this.pricerange;
		// Region / Location.
		str += "/";
		// console.log("added price");
		// str += $F('searchmenu_region_keylabel');
		str += this.region;
		// Let's clean it up.
		// console.log("added region");
		str = str.toLowerCase();
		// Remove Whitespace.
		str = str.replace(/ /g, "");
		// Add SortOrder.
		str += "/";
		str += $F('sort_order');
		// Done.
	//	document.location.href = str;
		$('query').value = str;
		if (justReturnString === true)
			return str;
		$('searchForm').submit();
		return true;
	},
	getSortOrder: function() {
		return $F('sort_order');
	},
	performSearchByRef: function(searchMethodType) {
		var val = $F('searchmenu_reference_value');
		val = val.replace(/[ \W]/g, "");
		if (val == "") return false;
		document.location.href = "/"+searchMethodType+"/"+val;
		return true;
	}
}

/*
var AjaxSearch = Class.create({
	
	searchMethodType: "developments",
	currentPage: 1,
	searchQuery: "",
	searchUrl: "",
	hasMorePages: true,
	searching: false,
	statusDiv: "ajax-search-status",
	
	initialize: function() {
		console.log("AjaxSearch initialize");
		this.searchQuery = Search.performSearch(this.searchMethodType, true);
		this.searchUrl = "/"+this.searchMethodType+"/searchx/"+Search.getSortOrder()+"/";
		// Listen for scroll events.
		Event.observe(window, "scroll", this.onScroll.bind(this));
		
		var div = document.createElement("div");
		Element.extend(div);
		div.setAttribute("id", this.statusDiv);
		div.update("<p>Loading Results...</p>");
		document.body.appendChild(div);
		$(this.statusDiv).hide();
	},
	
	onScroll: function() {
		if (this.searching) return;
		if (!this.hasMorePages) {
			Event.stopObserving(window, "scroll");
			return;
		}
		var bodyHeight = $(document.body).getHeight();
		var viewportHeight = document.viewport.getHeight();
		var scrollOffset = document.viewport.getScrollOffsets().top;

		var p = ((scrollOffset + viewportHeight) / bodyHeight);
		if (p >= 1)
			this.search();
	},
	
	search: function() {
		if (this.searching) return;
		this.searching = true;
		var self = this;
		if (!this.hasMorePages) {
			console.info("AjaxSearch: No more pages available");
			return;
		}
		
		$(this.statusDiv).show();
		
		var url = this.searchUrl + (this.currentPage+1);
		new Ajax.Request(url, {
			parameters: {searchQuery: this.searchQuery},
			onSuccess: function(response) {
				self.currentPage++;
				self.onResults(response);
				self.hasMorePages = (response.getHeader("X-Search-More-Available") == "yes");
				self.searching = false;
			}
		});		
	},
	onResults: function(data) {
		$(this.statusDiv).hide();
		$("searchresults-listing").insert({bottom: data.responseText});
	}	
});
*/
function popupWindow(e){
	e.stop();
	window.open(e.target.href, e.target.title, 'width=1000,scrollbars=1');
}

var LazyLoad = Class.create({
	
	initialize: function(threshold) {
		$$("img[org]").each(function(img) {
			new LazyLoadImage(img, threshold);
		});
	}
	
});


var LazyLoadImage = Class.create({

	img: null,
	src: "",
	loading: false,
	loaded: false,
	scrollDelegate: null,
	threshold: 100,
	preloaderImage: null,
	
	initialize: function(img, threshold) {
		var self = this;
		this.img = img;
		this.src = img.readAttribute("org");
		this.threshold = threshold;
		this.preloaderImage = new Image();
		this.preloaderImage = $(this.preloaderImage);
		this.preloaderImage.setOpacity(0.0); // ie zoom:1
		this.img.addClassName("lazyload");
		
		this.preloaderImage.onload = function() {
			self.onImageLoaded();
		}
		this.preloaderImage.onerror = function() {
			self.onImageError();
		}
		
		var pos = Position.page(this.img).top;
		if (pos > -this.threshold && (pos < (document.viewport.getHeight()+this.threshold))) {
			this.loading = true;
			this.preloaderImage.src = this.src;
		} else {
			this.scrollDelegate = this.onScroll.bindAsEventListener(this);
			Event.observe(window, 'scroll', this.scrollDelegate, false);
		}
	},
	onScroll: function() {
		if ((this.loaded == false) && (this.loading != true)) {
			// Is it in view.
			var pos = Position.page(this.img).top;
			if (pos > -this.threshold && (pos < (document.viewport.getHeight()+this.threshold))) {
				this.loading = true;
				this.preloaderImage.src = this.src;
				// Stop observer.
				Event.stopObserving(window, 'scroll', this.scrollDelegate);
			}
		}
	},
	onImageLoaded: function() {
		var self = this;
		this.loaded = true;		
		// Write some attributes.
		if (this.img.hasAttribute("width"))
			this.preloaderImage.writeAttribute("width", this.img.readAttribute("width"));
		if (this.img.hasAttribute("height"))
			this.preloaderImage.writeAttribute("height", this.img.readAttribute("height"));
		if (this.img.hasAttribute("alt"))
			this.preloaderImage.writeAttribute("alt", this.img.readAttribute("alt"));
		if (this.img.hasAttribute("class"))
			this.preloaderImage.writeAttribute("class", this.img.readAttribute("class"));
		// Fade down image, replace the image and fade up.
		new Effect.Opacity(this.img, {duration: 0, from: 1.0, to: 0.0, afterFinish: function() {
			self.img.replace(self.preloaderImage);
			new Effect.Opacity(self.preloaderImage, {duration: 0.2, from: 0.0, to:1.0});
		}});
	},
	onImageError: function() {
		this.img.removeClassName("lazyload");
		this.loaded = true;
	}
	
});


document.observe("dom:loaded", function() {
	// Form.
	if ($('contact_form') != null) {
		var contactForm = new ContactForm();
	}
	if ($('searchmenu_reference') != null) {
		if($('searchmenu_type')) var searchTypeDropDown = new DropDownControl("searchmenu_type");
		if($('searchmenu_bedrooms')) var searchBedsDropDown = new DropDownControl("searchmenu_bedrooms");
		var searchPriceDropDown = new DropDownControl("searchmenu_pricerange");
		var searchRegionDropDown = new DropDownControl("searchmenu_region");
		var searchRefDropDown = new DropDownControl("searchmenu_reference");
		Event.observe('searchmenu_reference_value', "keydown", refSearch.bindAsEventListener(this));
	}
	if ($('investment_form') != null) {
		InvestmentForm.initialize();
	}
	
	$$('a.popup').each(function(ob){ Event.observe(ob, "click", popupWindow.bindAsEventListener(this)); });
	
	$$(".scroll-to-top").each(function(item) {
		item.observe("click", function() {
			window.scrollTo(0, 0);
		});
	});
		
	
	//var search = new AjaxSearch();
	
	new LazyLoad(300);
});