if(typeof Prototype != 'undefined') {
	Object.extend(Function.prototype, {
		onLoad: function() {
			Event.observe(window, "load", this);
		}
	});
}

if (typeof(Element) == "undefined")
	Element = {}

Element.infanticide = function(node) {
	node = $(node)
		if (node)
			while (node.hasChildNodes())
				node.removeChild(node.firstChild)
}
Element.staticize = function(element) {
	element = $(element);
	if (element.getStyle('position') == 'static') return;

	element.style.position = 'static';
	element.style.top    = "";
	element.style.left   = "";
	element.style.width  = "";
	element.style.height = "";
	return element;
};

var rotating_items = [];
var rotating_pos = 0;
var rotating_num = 0;

function rotateItems(el, num, options) {
	new ItemRotator(el, num, options || {});
}

if (typeof(Class) != "undefined") {
	var ItemRotator = Class.create({
		pos: 0,
		initialize: function (el, num) {
			this.options = Object.extend({
				num: num,
				duration: 10,
				async: false
			}, arguments[2] || { });
			this.el = $(el);
			this.items = $A(this.el.getElementsByClassName("rotate_item"));
			if (this.items.length <= this.options.num) {
				rotating_items.each(function(el) {
					Element.show(el);
				});
				return;
			}

			this.items.each(function(el) {
				Element.remove(el);
			});
			for (var n = 0; n < this.options.num; n++) {
				this.el.appendChild(this.items[n]);
				Element.show(this.items[n]);
			}
			if (!this.options.async)
				this.pos = n;
			window.setTimeout(this.performRotate.bind(this), this.options.duration * 1000);
			if (this.options.async)
				this.options.duration /= this.options.num;
		},
		performRotate: function() {
			this.options.async ? this.asyncRotate() : this.syncRotate();
		},
		syncRotate: function() {
			var to_hide = [];
			var to_show = [];
			this.items.each(function(el, n) { // Hide all items
				if (Element.visible(el))
					to_hide.push(n);
			});
			var hide_effects = [];
			var show_effects = [];
			to_hide.each(function(n) {
				var next_el = this.loop(n+this.options.num, this.items.length);
				hide_effects.push(new Effect.Fade(this.items[n], {
					sync: true,
					afterFinish: function() {
						this.items[n].insert({ before: this.items[next_el]});
						Element.remove(this.items[n]);
					}.bind(this)
				}));
				to_show.push(next_el);
			}.bind(this));
			new Effect.Parallel(hide_effects, {
				duration: 1,
				afterFinish: function() {
					to_show.each(function(n) {
						show_effects.push(new Effect.Appear(this.items[n], { sync: true }));
					}.bind(this));
					new Effect.Parallel(show_effects, {
						duration: 1,
						afterFinish: function() {
							window.setTimeout(this.performRotate.bind(this), this.options.duration * 1000);
						}.bind(this)
					});
				}.bind(this)
			});
		},
		asyncRotate: function() {
			// This should be easy
			$A(this.el.getElementsByClassName("rotate_item")).reverse().each(function(el) { el.absolutize() });
			new Effect.Fade(this.items[this.pos], {
				duration: 1,
				afterFinish: function() {
					// Append next
					var next_el = this.loop(this.pos + this.options.num, this.items.length);
					this.items[this.pos].insert({ before: this.items[next_el]});
					Element.remove(this.items[this.pos]);

					this.items[next_el].setOpacity(0);
					Element.show(this.items[next_el]);

					$A(this.el.getElementsByClassName("rotate_item")).reverse().each(function(el) { Element.staticize(el); });

					new Effect.Appear(this.items[next_el], {
						duration: 1,
						afterFinish: function() {
							window.setTimeout(this.performRotate.bind(this), this.options.duration * 1000);
							this.pos = this.loop(this.pos+1, this.items.length);
						}.bind(this)
					});
				}.bind(this)
			});
		},
		loop: function(n, max) {
			if (n >= max)
				n -= max;
			return n;
		}
	});
}

function selectInstructionType(el_avail, el_minprice, el_maxprice) {
	el_avail = $(el_avail);
	el_minprice = $(el_minprice);
	el_maxprice = $(el_maxprice);

	if (!el_avail || !el_minprice || !el_maxprice)
		return;
	switch ($F(el_avail)) {
		case "Sale":
			populatePrices(el_minprice, salePrices, "min");
			populatePrices(el_maxprice, salePrices, "max");
			break;
		case "Letting":
			populatePrices(el_minprice, letPrices, "min");
			populatePrices(el_maxprice, letPrices, "max");
			break;
	}
}

function addSelectOption(el, value, text) {
	o = new Option();
	o.text = text;
	o.value = value.toString();
	el.options[el.options.length] = o;
}

function populatePrices(el, prices, type) {
	el.options.length = 0;
	prices = $A(prices);
	if (type == "min")
		addSelectOption(el, "", "No Minimum");
	pound = html_entity_decode("&pound;");
	prices.each(function(price) {
			text = pound+number_format(price);
			addSelectOption(el, price, text);
	});
	if (type == "max") {
		addSelectOption(el, "", "No Maximum");
		el.selectedIndex = el.options.length-1;
	}
}

function number_format(a, b, c, d) {
	// number_format(number, decimals, comma, formatSeparator)
	//
	if (!b) b = 0;
	if (!c) c = ".";
	if (!d) d = ",";

	a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
	e = a.toString()
	f = e.split('.');
	if(!f[0]) f[0] = '0';
	if(!f[1]) f[1] = '';
	if(f[1].length < b){
		g = f[1];
		for(i = f[1].length + 1; i <= b; i++) {
			g += '0';
		}
		f[1] = g;
	}
	if(d != '' && f[0].length > 3) {
		h = f[0];
		f[0] = '';
		for(j = 3; j < h.length; j += 3) {
			i = h.slice(h.length - j, h.length - j + 3);
			f[0] = d + i +  f[0] + '';
		}
		j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
		f[0] = j + f[0];
	}
	c = (b <= 0) ? '': c;
	return f[0] + c + f[1];
}

function html_entity_decode(str) {
	var ta = document.createElement("textarea");
	ta.innerHTML=str.replace(/</g,"<").replace(/>/g,">");
	toReturn = ta.value;
	ta = null;
	return toReturn
}

if (typeof(Class) != "undefined") {
	var MultiLineInput = Class.create({
			initialize: function (el) {
				this.container = $(el);
				this.template = this.container.getElementsByTagName("li")[0].cloneNode(true);
				$A(this.container.getElementsByTagName("li")).each(function(line) { this.addHandlers(line) }.bind(this));
				this.num_inputs = this.template.getElementsByTagName("input").length;
				this.blank_at_end = 1;
				if (this.num_inputs = 1)
					this.blank_at_end = 2;
				this.rescan();
			},
			rescan: function() {
				var lines = $A(this.container.getElementsByTagName("li"));
				var nlines = lines.length;
				var remove = [];
				var blank_at_end = 0;
				lines.each(function(line, n) {
					var inputs = $A(line.getElementsByTagName("input"));
					blank = true;
					inputs.each(function(input) {
						if ($F(input).strip()) {
							blank = false;
							throw $break;
						} else {
							return;
						}
					});
					if (blank) {
						blank_at_end++;
						if (n < nlines-this.blank_at_end)
							remove.push(n);
					} else blank_at_end = 0;
				}.bind(this));
				remove.each(function(n) {
						Effect.Fade(lines[n], {
								duration: 0.5,
								afterFinish: function() {
									Element.remove(lines[n]);
								}
						});
				});
				if (blank_at_end < this.blank_at_end) {
					for (i = 0; i < this.blank_at_end-blank_at_end; i++) {
						var line = this.container.appendChild(this.template.cloneNode(true));
						Element.hide(line);
						Effect.Appear(line, {
								duration: 0.5
						});
						$A(line.getElementsByTagName("input")).each(function(input) {
								input.value = "";
						});
						this.addHandlers(line);
					}
				}
			},
			addHandlers: function(line) {
				$A(line.getElementsByTagName("input")).each(function(input) {
					Event.observe(input, "change", this.rescan.bind(this));
				}.bind(this));
			}
	});

	Event.observe(window, "load", function() {
			$$("ul.multiline-input").each(function(el) {
				new MultiLineInput(el);
			});
	});
}

function addToShortlist(id) {
	new Ajax.Request("/ajax/add_to_shortlist", {
		parameters: {
			id: id
		},
		onSuccess: updateShortlistCallback
	});
}

function deleteFromShortlist(id) {
	new Ajax.Request("/ajax/delete_from_shortlist", {
		parameters: {
			id: id
		},
		onSuccess: updateShortlistCallback
	});
}

function updateShortlistCallback(t) {
	data = eval('('+t.responseText+')');
	$("shortlist").update(data);
}


