var isEmailAFriendOpen = false;
function emailAFriend() {
	if (isEmailAFriendOpen) return;
	isEmailAFriendOpen = true;
	$('emailafriend').show();
	$('emailafriend').absolutize();
	var centerX = $('header').getWidth()/2;
	var boxX = (centerX - ($('emailafriend').getWidth()/2));
	boxX += $('header').viewportOffset().left;
	var boxY = (getWindowSize().height/2) - ($('emailafriend').getHeight()/2);
	if (boxY < 0) boxY = 0;
	$('emailafriend').setStyle({position: "fixed", left: boxX+"px", top: boxY+"px"});
	if (Prototype.Browser.IE) {
		if (navigator.appVersion.substr(navigator.appVersion.indexOf("MSIE ")+5,1) == "6") {
			$('emailafriend').setStyle({position: "absolute", left: boxX+"px", top: boxY+"px"});
			$('container').scrollTo();
		}
	}	
	preloadImage("/images/btn_useMail_ro.gif");
	preloadImage("/images/btn_closeMail_ro.gif");
}

function closeEmailAFriend() {
	if (!isEmailAFriendOpen) return;
	isEmailAFriendOpen = false;
	$('emailafriend').relativize();
	$('emailafriend').hide();
}

var isEnquiryWindowOpen = false;
function openEnquiryWindow(subjectStr) {
	if (isEnquiryWindowOpen) return;
	$('enquirywindow').show();
	$('enquirywindow').absolutize();
	var centerX = $('header').getWidth()/2;
	var boxX = (centerX - ($('enquirywindow').getWidth()/2));
	boxX += $('header').viewportOffset().left;
	var boxY = (getWindowSize().height/2) - ($('enquirywindow').getHeight()/2);
	if (boxY < 0) boxY = 0;
	$('enquirywindow').setStyle({position: "fixed", left: boxX+"px", top: boxY+"px"});
	if (Prototype.Browser.IE) {
		if (navigator.appVersion.substr(navigator.appVersion.indexOf("MSIE ")+5,1) == "6") {
			$('enquirywindow').setStyle({position: "absolute", left: boxX+"px", top: boxY+"px"});
			$('container').scrollTo();
		}
	}	
	if (subjectStr != null) $('subject_txt').value = subjectStr;
	preloadImage("/images/btn_sendEnquiry_ro.gif");
	preloadImage("/images/btn_closeMail_ro.gif");
	isEnquiryWindowOpen = true;
}

function closeEnquiryWindow() {
	if (!isEnquiryWindowOpen) return;
	isEnquiryWindowOpen = false;
	$('enquirywindow').relativize();
	$('enquirywindow').hide();
}

function getWindowSize() {
	var width, height;
	width = window.innerWidth || (window.document.documentElement.clientWidth || window.document.body.clientWidth);
	height = window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight);
	return { width: width, height: height };
}

function showPropertyThumbnail(uuid, size) {
	// Fix selection.
	var nodes = $('thumbnailList').select("li");
	var caption = "";
	nodes.each(function(node) {
		if (node.down().hasClassName("selected")) 
			node.down().removeClassName("selected");
		if (node.identify() == uuid+"_tb") {
			node.down().addClassName("selected");
			caption = node.down().readAttribute("alt");
		}
	});
	// Load image.
	$('bigImage').src = "/media/property/"+uuid+"/"+size+".jpg";
	// Caption.
	$('bigImageCaption').update(caption);
	// Scroll there.
	$('bigImageContainer').scrollTo();
}

function search() {
	//alert("searching...");
	// Check if we should search by reference.
	var searchRef = $("searchReferenceNumber");
	if (searchRef.present()) {
		document.location.href = "/properties/details/"+searchRef.getValue();
		return true;
	}	
	// Normal Search.	
	
	
	var searchStr = "/properties/search/";
	
	// PropertyType.
	if ($("searchPropertyType").present()) searchStr += $F("searchPropertyType")+"/";
	else searchStr += "all/";
	
	// Bedrooms.
	var minBeds = 0;
	var maxBeds = 0;
	if ($("searchMinBeds").present()) minBeds = parseInt($F("searchMinBeds"));
	if ($("searchMaxBeds").present())	maxBeds = parseInt($F("searchMaxBeds"));
	if (isNaN(minBeds)) minBeds = 0;
	if (isNaN(maxBeds)) maxBeds = 0;
	if (minBeds > maxBeds) {
		var tmp = minBeds;
		minBeds = maxBeds;
		maxBeds = tmp;
	}
	if (minBeds == 0 && maxBeds == 0) searchStr += "all/";
	else searchStr += minBeds+"-"+maxBeds+"/";
	
	// Bathrooms.
	var minBaths = 0;
	var maxBaths = 0;
	if ($("searchMinBaths").present()) minBaths = parseInt($F("searchMinBaths"));
	if ($("searchMaxBaths").present()) maxBaths = parseInt($F("searchMaxBaths"));
	if (isNaN(minBaths)) minBaths = 0;
	if (isNaN(maxBaths)) maxBaths = 0;
	if (minBaths > maxBaths) {
		var tmp = minBaths;
		minBaths = maxBeds;
		maxBaths = tmp;
	}
	if (minBaths == 0 && maxBaths == 0) searchStr += "all/";
	else searchStr += minBaths+"-"+maxBaths+"/";
	
	// Price.
	if ($('searchPrice').present()) searchStr += $F('searchPrice');
	else searchStr += "all/";

	document.location.href = searchStr;
	return true;//false;	
}

function numericalSort(a,b) {
	return a-b;
}

function toggleRadioSearch(prefix, nr) {
	var lo, hi = 0;
	var arr = [];
	if (prefix == "beds") prefix = "radioBed_";
	if (prefix == "baths") prefix = "radioBath_";
	var radio = $(prefix+nr);
	// Toggle on.
	if (nr == 5) {
		if (radio.hasClassName("radioPlus_on")) {
			radio.removeClassName("radioPlus_on");
			radio.toggleClassName("radioPlus_off");
			radio5 = false;
		} else {
			radio.removeClassName("radioPlus_off");
			radio.toggleClassName("radioPlus_on");
			radio5 = true;
		}
	} else {
		if (radio.hasClassName("radio"+nr+"_on")) {
			radio.removeClassName("radio"+nr+"_on");
			radio.toggleClassName("radio"+nr+"_off");
		} else {
			radio.removeClassName("radio"+nr+"_off");
			radio.toggleClassName("radio"+nr+"_on");
		}
	}
	
	if ($(prefix+'1').hasClassName("radio1_on")) arr.push(1);
	if ($(prefix+'2').hasClassName("radio2_on")) arr.push(2);
	if ($(prefix+'3').hasClassName("radio3_on")) arr.push(3);
	if ($(prefix+'4').hasClassName("radio4_on")) arr.push(4);
	if ($(prefix+'5').hasClassName("radioPlus_on")) arr.push(5);

	var len = arr.length;
	if (len > 0) {
		arr.sort(numericalSort);
		lo = arr[0];
		hi = arr[len-1];
	} else {
		lo = hi = 0;
	}
	
	// Fill in gaps.
	var classPrefix = "radio";
	for (var i=lo; i<hi; i++) {
		if (i == 5) { classPrefix = "radioPlus";
		} else { classPrefix = "radio"+i };
		if ($(prefix+i).hasClassName(classPrefix+"_off")) {
			$(prefix+i).removeClassName(classPrefix+"_off");
			$(prefix+i).toggleClassName(classPrefix+"_on");
		}
	}
	// Set Data.
	if (prefix == "radioBed_") {
		$('searchMinBeds').writeAttribute("value", lo);
		if (hi == 5) $('searchMaxBeds').writeAttribute("value", 20);
		else $('searchMaxBeds').writeAttribute("value", hi);
	} else if (prefix == "radioBath_") {
		$('searchMinBaths').writeAttribute("value", lo);
		if (hi == 5) $('searchMaxBaths').writeAttribute("value", 20);
		else $('searchMaxBaths').writeAttribute("value", hi);		
	}
}


var ContactForm = Class.create({
	initialize: function() {
		this.form = $('enquiry_form');
		this.sending = false;
		this.standbyScreen = $('enquiry_standby');
		this.thanksScreen = $('enquiry_thanks');
		this.errorScreen = $('enquiry_error');
		this.submitButton = $('enquiry_submit_img');
		Event.observe("enquiry_submit_img", "click", this.submit.bindAsEventListener(this));
		Event.observe("enquiry_close_img", "click", this.close.bindAsEventListener(this));
	},
	submit: function(event) {
		if (this.sending) return false;
		if (!$('name_txt').present()) {
			alert("Please specify your name.");
			$('name_txt').focus();
			return false;
		}
		if (!$('email_txt').present()) {
			alert("Please specify your email address.");
			$('email_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;
	},
	close: function() {
		closeEnquiryWindow();
	},
	send: function() {
		this.sending = true;
		var me = this;
		new Ajax.Request("/contact/addenquiry", {
			method: 'post',
			parameters: $('enquiry_form').serialize(),
			onSuccess: function(transport) {
				if (transport.responseText == "ok") {
					me.thanksScreen.show();
					me.errorScreen.hide();
					me.standbyScreen.hide();
					me.submitButton.hide();
				} else {
					me.thanksScreen.hide();
					me.errorScreen.show();
					me.standbyScreen.hide();	
				}
				$('name_txt').enable();
				$('email_txt').enable();
				$('subject_txt').enable();
				$('message_txt').enable();
				me.sending = false;
			},
			onFailure: function() {
				me.thanksScreen.hide();
				me.errorScreen.show();
				me.standbyScreen.hide();
				$('name_txt').enable();
				$('email_txt').enable();
				$('subject_txt').enable();
				$('message_txt').enable();
				me.sending = false;
			}
		});
		$('name_txt').disable();
		$('email_txt').disable();
		$('subject_txt').disable();
		$('message_txt').disable();
	}
})




var DropDownControl = Class.create({
	initialize: function(id, callback, toggleEventListeners) {
		this.id = id;
		this.timeout = 300;
		this.closeTimer = null;
		this.menuItem = null;
		this.items = new Hash();
		this.counter = 0;
		this.selectedItem = null;
		this.callback = callback;
		this.bindMouseOverMethod = this.open.bindAsEventListener(this);
		this.bindMouseOutMethod = this.closeDelay.bindAsEventListener(this);
		//this.toggleEventListeners = (toggleEventListeners == true);
		Event.observe(id, "mouseover", this.bindMouseOverMethod);
		Event.observe(id, "mouseout", this.bindMouseOutMethod);
		Event.observe(id+"Body", "mouseover", this.cancelClose.bindAsEventListener(this));
		Event.observe(id+"Body", "mouseout", this.closeDelay.bindAsEventListener(this));
	},
	open: function(event) {
		this.cancelClose();
		if (this.menuItem) this.menuItem.hide();
		this.menuItem = $(this.id+"Body");
		this.menuItem.show();
		//Event.stopObserving(this.id, "mouseover", bindMouseOverMethod);
		//Event.stopObserving(this.id, "mouseout", bindMouseOutMethod);
	},
	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;
		}
	},
	addItem: function(title, value) {
		var id = this.id+"_"+(this.counter++);
		$(this.id+"Body").insert("<a href='#' id='"+id+"'>"+title+"</a>");
		this.items.set(value, {title: title, value: value, id: id});
		Event.observe(id, "click", this.selectItemEvent.bindAsEventListener(this, value));
	},
	selectItem: function(value) {
		var obj = this.items.get(value);
		if (obj == null) return;
		if (this.selectedItem != null) this.selectedItem.removeClassName("selected");
		this.selectedItem = $(obj.id);
		if (!this.selectedItem.hasClassName("selected")) this.selectedItem.addClassName("selected");
		if (this.callback != null) this.callback(this, obj);
		$(this.id).update(obj.title);
		this.close();
	}, 
	selectItemEvent: function(event, value) {
		this.selectItem(value);
	}
})


function preloadImage(src) {
	var tmpImage = new Image();
	tmpImage.src = src;
}
function swapImage(obj, src) {
	obj.src = src;
//	alert("swapImage: "+obj+", "+src);
}


function onSelectPropertyType(control, data) {
	$('searchPropertyType').writeAttribute("value", data.value);
}

function onSelectPropertyPrice(control, data) {
	$('searchPrice').writeAttribute("value", data.value);
}






document.observe("dom:loaded", function() {
	// DropDowns.
	if ($('propertyTypeDD') != null) {
		var propertyTypeDropDown = new DropDownControl("propertyTypeDD", onSelectPropertyType, true);
		propertyTypeDropDown.addItem("All Types", "all");
		propertyTypeDropDown.addItem("Villas", "villa");
		propertyTypeDropDown.addItem("Apartments", "apartment");
		propertyTypeDropDown.addItem("Townhouses", "townhouse");
		propertyTypeDropDown.addItem("Commercial Properties", "commercialplot");
		if ($("contextSearchType") != null)
			propertyTypeDropDown.selectItem($F("contextSearchType"));
	
		var propertyPriceDropDown = new DropDownControl("propertyPriceDD", onSelectPropertyPrice);
		propertyPriceDropDown.addItem("Any Price Range", "all");
		propertyPriceDropDown.addItem("Up to 250,000&euro;", "0-250");
		propertyPriceDropDown.addItem("250,000 to 500,000&euro;", "250-500");
		propertyPriceDropDown.addItem("500,000 to 1,000,000&euro;", "500-1000");
		propertyPriceDropDown.addItem("Over 1,000,000&euro;", "1000-100000");
		if ($("contextSearchPrice") != null)
			propertyPriceDropDown.selectItem($F("contextSearchPrice"));

		// Radios.
		if ($("contextSearchBeds") != null && $F("contextSearchBeds") != "all") {
			var tmp = $F("contextSearchBeds").split("-");
			if (tmp.length == 2) {
				var lo = parseInt(tmp[0]);
				var hi = parseInt(tmp[1]);
				if (lo < 1) lo = 1;
				if (hi > 5) hi = 5;
				for (var i=lo; i<=hi; i++) {
					toggleRadioSearch('beds', i);
				}
			}
		}

		if ($("contextSearchBaths") != null && $F("contextSearchBaths") != "all") {
			var tmp = $F("contextSearchBaths").split("-");
			if (tmp.length == 2) {
				var lo = parseInt(tmp[0]);
				var hi = parseInt(tmp[1]);
				if (lo < 1) lo = 1;
				if (hi > 5) hi = 5;
				for (var i=lo; i<=hi; i++) {
					toggleRadioSearch('baths', i);
				}
			}
		}	
	}
	
	// Form.
	if ($('enquiry_form') != null) {
		var contactForm = new ContactForm();
	}
});
