/**
addEvent('domready',function(){
	try {
		$$('.button').each(function(e){
			e.addEvents({
				'mouseover' : function(){
					e.addClass('hover');
				},
				'mouseout' : function(){
					e.removeClass('hover');
				}
			});
		});
	} catch (error){
	}
});
*/


/** 
 * Checks the user selected date. Make sure its valid.
 */
function checkDate(dateField, dateValue) {	;
	
	var dfrom = $('dfrom');
	var dto = $('dto');
	
	if (dateField.name == 'dfrom') {
		dfromValue = dateValue;
		dtoValue = dto.value;
	} else {
		dfromValue = dfrom.value;
		dtoValue = dateValue;
	}
	
	// need to check if any are empty. if so, we leave it alone
	if((dfromValue == 'dd/mm/yy' || dfromValue == '') || (dtoValue == 'dd/mm/yy' || dtoValue == '')) {
		return true;
	}
	
	//need to parse dates
	//if ((dto.value == 'dd/mm/yy' || dto.value == '' )  || 
	//	(dfrom.value == 'dd/mm/yy' || dfrom.value == '') ) {
	//	return true;
	//}
	
	dfromBits = dfromValue.split('/').map(function(item){return Number(item)});
	dtoBits = dtoValue.split('/').map(function(item){return Number(item)});
	
	//if the user selected the from field, make sure the to field is > and vice versa
	if (dtoBits[2] > dfromBits[2] ) {
		return true;
	} else if (dtoBits[2] == dfromBits[2] && dtoBits[1] > dfromBits[1]) {
		return true;
	} else if (dtoBits[2] == dfromBits[2] && dtoBits[1] == dfromBits[1] && dtoBits[0] >= dfromBits[0] ) {
		return true;
	} else {
		var msg = dateField.name == 'dfrom' ? 'Your from date must be less than the to date.' : 
											  'The to date must be greater than the from date.';
		alert(msg);									  
		return false;
	}
}

var AHH = {
	//Current active type
	activeCategory : 'everything',
	activeCharacteristic : '',
	previousValue :	'',
	toRange : 0,
	fromRange : 0,
	mouseOverSuggest : false,
	/**
	 * Initialization Function
	 */
	init : function(active, characteristic, fromRange, toRange){
		
		AHH.activeCharacteristic = characteristic || 'all';
		AHH.activeCategory = active || 'everything';
		AHH.toRange = toRange || 0;
		AHH.fromRange = fromRange || 0;
		//Grab our radio inputs and hide them. Attach events to the labels
		
		$$('#selection input').each(function(inp){
			
			inp.getParent().addEvents({
				'mouseover' : function(e){
					this.setStyle('cursor','pointer');
					if (!this.hasClass('active'))
						this.addClass('hover');
				},
				'mouseout' 	: function(e){
					this.removeClass('hover');
				},
				'click'	: function(e){
					AHH.activateCategory(this);
				}
			});
			inp.dispose();
		});
		
		//Add a hidden input to store category selection
		var typeInput = new Element('input',{
			'type'	: 'hidden',
			'id'	: 'type-input',
			'name'	: 'type',
			'value'	: AHH.activeCategory
		});
		typeInput.inject('selection');
		
		//Set Characteristics
		if (AHH.activeCategory != 'everything') {
			AHH.setCharacteristics();
		}
		
		//Stop form submission when the suggest box appears
		$('search-form').addEvent('submit', function(evt){
			if ($('active-suggestion')) {
				AHH.suggestUpdateLocation($('active-suggestion').name);	
				AHH.suggestTrash();
				$('location').focus();	
				return false;	
			}
			return true;
		});
		
		//Disable autocomplete on the location field
		$('location').setProperty('autocomplete','off');
		//Add suggestion events
		$('location').addEvents({
			'keyup': function(e){
				AHH.suggest(e, this);
				return false;
			}, 
			'blur' : function(e){
				if ($('suggestions')) {
					//If the user is clicking the mouse in the area of the suggestions box then ignore this
					if (!AHH.mouseOverSuggest) {
						AHH.suggestTrash();
					}
				}
			}
		});
		
		//Date selection
		var ds = $('date-selection');
		if (!$('search-time').checked)
			ds.setStyle('display','none');
				
		$('search-time').addEvent('click', function(){
			if (this.checked) {
				ds.setStyle('display','block');
			} else {
				ds.setStyle('display','none');
			}
		});
		
		var calClass = 'calendar-oth';
		if (Browser.Engine.trident5) {
			calClass = 'ie7';
		} else if (Browser.Engine.trident4) {
			calClass = 'ie6';
		} else if (Browser.Engine.webkit) {
			calClass = 'safari';
		}
		
		var calButtonA = new Element('img',{
			'src' : '/css/images/calendar.gif',
			'class' : 'calendar-icon '+calClass,
			'alt'	: 'calendar',
			'hspace' : '3', 
			'events' : {
					'click' : function(){
						return Calendar.initCal('search-form','dfrom','',2008,2009,this, "checkDate");
					}
				}
		});
		calButtonA.inject('dfrom','after');
		var calButtonB = new Element('img',{
			'src' : '/css/images/calendar.gif',
			'class' : 'calendar-icon '+calClass,
			'alt'	: 'calendar',
			'hspace' : '3', 
			'events' : {
					'click' : function(){
						return Calendar.initCal('search-form','dto','',2008,2009,this,"checkDate");
					}
				}
		});
		
		calButtonB.inject('dto','after');
		
		//Set price ranges
		var radioModes = $('search-form').elements['mode'];
		for (var i =0; i < radioModes.length; ++i){
			radioModes[i].onclick = function(){
				AHH.setPriceRange();
				var bedSleep = $('beds-sleeps');
				var bathrooms = $('bathrooms');
				
				if (this.value == 'rent') {
					bedSleep.set('text','Guests');
					bathrooms.style.display = 'none';
				} else {
					bedSleep.set('text','Beds');
					bathrooms.style.display = 'block';
				}
			};
		}
	AHH.setPriceRange();
	},
	messageTween : function() {
		var message = $('search-message');
		message.set('morph',{duration: 3000, transition: 'sine:out'});
		message.morph({'background-color': '#41B4ED'
						//, color: '#000'
						});
	},
	/**
	 * simple suggest stuff
	 */
	suggest : function(event, where) {

		if (event.key == 'enter') {
			$('location').focus();
			return;	
		}

		var whereCoords = where.getCoordinates();
		var bits = where.value.trim().split(',');
		AHH.whereVal = bits.pop().trim();
		
		//Handle up, down and enter keystrokes
		if ($('suggestions') && (event.key == 'up' || event.key == 'down'  || event.key == 'esc')) {
			if (event.key == 'esc') {
				AHH.suggestTrash();
			}
			try {
				if ($('suggestions').getFirst())
				AHH.suggestActions(event);	
			} catch (error){}
			
		}
		
		//if value hasnt changed dont bother refreshing
		if (AHH.whereVal == AHH.previousVal) return false;
		
		//set previous value
		AHH.previousVal = AHH.whereVal;
		
		//if empty then dispose of the suggestions box
		if (AHH.whereVal == '') {
			AHH.suggestTrash();
			return false;
		}
		
		if (!$('suggestions')) {
			var suggestBox = new Element('div',{
				'id' : 'suggestions',
				'styles' : {
						'top' : (whereCoords.top + 23)+'px',
						'left': (whereCoords.left + 1)+'px'
					},
				'events' : {
						'mouseover' : function(){
							AHH.mouseOverSuggest = true;
						},
						'mouseout' : function(){
							AHH.mouseOverSuggest = false;
						}
					}
			});
			suggestBox.inject(document.body);
			
		} else {
			var suggestBox = $('suggestions');
			//suggestBox.empty();
		}
		
		var strCheck = AHH.whereVal;
		if(strCheck.length > 20) {
			return;
		}
				
		var SuggestMe = new Request.HTML({'url' : '/suggest.php', 'update' : 'suggestions'}).get({'key' : AHH.whereVal});	
		
		SuggestMe.addEvents({
			'onComplete' : function(){
				
				suggestBox.setStyle('display','block');
				$$('#suggestions a').addEvents({
						'click' : function() {
							try {
								AHH.suggestUpdateLocation(this.name);
								AHH.suggestTrash();
								return false;
							} catch (error) {
								AHH.suggestTrash();
							}
							return false;
						},
						'mouseover' : function() {
							try {
							var activeS = $('active-suggestion');
							if (activeS) {
								activeS.erase('id');
							}
							this.set('id','active-suggestion');
							} catch (error) {
								
							}
						}
					});
				
				//suggestBox.set('html',where.value);
				//get suggest box dimension (need to hide select box in ie6)
				if (Browser.Engine.trident4) {
					//suggest box dimensions
					var sboxDim = $('suggestions').getSize();
					var suggestIframe = $('suggestions-iframe');
					if (!suggestIframe) {
						var suggestIframe = new Element('iframe',{
							'id' : 'suggestions-iframe',
							'styles' : {
								'top' : (whereCoords.top + 23)+'px',
								'left': (whereCoords.left + 1)+'px',
								'height' : sboxDim.y+'px'
								}
						});
						suggestIframe.inject(document.body);
					} else {
						suggestIframe.setStyle('height',sboxDim.y+'px')	
					}
				}
			}
		});
		
	},
	//Trash the suggest box
	suggestTrash : function() {
		try {
			if (Browser.Engine.trident4) {
				$('suggestions-iframe').dispose();
			}
			$('suggestions').dispose();	
			
		} catch (error) {
			
		}
	},
	/**
	 * 
	 */
	suggestActions : function(event) {
		var hasSelection = false;
		if ($('active-suggestion')) {
			hasSelection = true;
			var activeS = $('active-suggestion');
		}
		if (event.key == 'down') {
			if (!hasSelection) {
				$('suggestions').getFirst().set('id','active-suggestion');
			} else {
				activeS.erase('id');
				try {
					activeS.getNext().set('id','active-suggestion');	
				} catch (error) { 
					$('suggestions').getFirst().set('id','active-suggestion');
				}
			}
		} else if (event.key == 'up' && hasSelection) {
			activeS.erase('id');
			try {
				activeS.getPrevious().set('id','active-suggestion');	
			} catch (error) { 
				$('suggestions').getLast().set('id','active-suggestion');
			}
		} else if ((event.key == 'enter') && hasSelection) {
			AHH.suggestUpdateLocation(activeS.name);
			AHH.suggestTrash();
			
		} else if (event.key == 'esc') {
			AHH.suggestTrash();
		}
	},
	suggestUpdateLocation : function(value) {
		var loc = $('location');
		var bits = loc.value.trim().split(',');
		bits.pop();
		
		var suggestBits = value.trim().split(',');
		var len = bits.length;
		for (var i = 0; i < len;  ++i) {
			bits[i] = bits[i].trim();
		}
		
		suggestBits.each(function(b){
			if (bits.contains(b.trim()) == false){
				bits.push(b.trim());
			}	
		});
		loc.value = bits.join(', ');
		
		// bring focus back to the location field
		loc.focus();
	},
	/**
	 * Activate a search category, update characteristics etc
	 */
	activateCategory : function(e){
		AHH.activeCharacteristic = 'all';
		try {
			$('label-'+AHH.activeCategory).removeClass('active');	
		} catch (err) {
		}
		
		AHH.activeCategory = e.getParent().className;
		AHH.setCharacteristics();
	
		$('type-input').value = AHH.activeCategory;
		$('label-'+AHH.activeCategory).addClass('active');
	},
	/**
	 * Set Characteristics to current active category
	 */
	setCharacteristics : function() {
		var chSelect = $('characteristics');
		//Add characteristics
		var inx = 1;
		var selectedInx = 0;
		
		chSelect.options.length = 0;			
		chSelect.options[0] =  new  Option('All Characteristics','');
			
		if (AHH.activeCategory != 'everything') {
			Characteristics[AHH.activeCategory].each(function(ch){
				chSelect.options[inx]= new Option(ch.name, ch.id);
				if (AHH.activeCharacteristic == ch.id) {
					selectedInx = inx;
				}
				++inx;
			});
		}
		
		chSelect.selectedIndex = selectedInx;
	},
	attachTips : function(){
		var myTips = new Tips('ul.property-info li, #buy-label',{
			className : 'tool',
			onShow: function(toolTip) {
				toolTip.setStyle('opacity','.9');
			}
		});
	}, 
	/**
	 * Make the UL clickable
	 */
	activateLinks : function(){
		$$('#results .info, #results-other .info').each(function(li){
			var anc = li.getFirst().getFirst();
			li.getParent().addEvents({
				'click' : function(){
					window.location.href = anc.href;
				},
				'mouseover' : function(){
					this.addClass('hover');
				},
				'mouseout' : function(){
					this.removeClass('hover');
				}
			});
		});
	},
	/**
	 * Set Price Range
	 */
	setPriceRange : function() {
		var BuyRange = ['0', '50,000','100,000','150,000','200,000','250,000','300,000','350,000','400,000','450,000','500,000','600,000','700,000','800,000','900,000','1,000,000','1,250,000','1,500,000','2,000,000'	,'2,500,000','3,000,000+'];
		var RentRange = ['0','50','100','150','200','250','300','350','400','450','500','600','700','800','900','1,000', '1,500','2,000','2,500','3,000','3,500','4,000', '4,500', '5,000+'];
		
		var mode = 'all';
		//find what mode is currently selected
		
		
		/*
		var radioModes = $('search-form').elements['mode'];
		for (var i =0; i < radioModes.length; ++i){
			if (radioModes[i].checked) {
				var mode = radioModes[i].value;
			}
		}
		*/
		
		// using this until the buy option is available
		var mode = $('search-form').elements['mode'];
		mode = mode.value;
			
		if (mode == 'all'){
			return false;
		} else if (mode == 'rent') {
			var fromRange = RentRange.slice(0);
			var toRange = RentRange.slice(0);
			var txt = 'Price range per night';
		} else if (mode == 'buy') {
			var txt = 'Price range';
			var fromRange = BuyRange.slice(0);
			var toRange = BuyRange.slice(0);
		}
		
		//Set from range and to range
		
		fromRange.pop();
		toRange.shift();
		var priceFrom = $('price-from');
		var priceTo = $('price-to');
		priceFrom.options.length = 0;
		priceTo.options.length = 0;
		$('price-range-text').set('text',txt);
		
		fromRange.each(function(rng, inx){
			var val = rng.replace(/[+|,]/m,'');
			priceFrom.options[inx]= new Option(rng, val);
			if (AHH.fromRange == val) {
				priceFrom.selectedIndex = inx;
			}
		});
	
		priceTo.options[0] = new Option('All','All');
		
		toRange.each(function(rng, index){
			var val = rng.replace(/[+|,]/m,'');
			priceTo.options[index+1] = new Option(rng, val);
			if (AHH.toRange == val) {
				priceTo.selectedIndex = index+1;
			}
		});
	},
	setupPopularTabs : function() {
		var button = $('popular-tab').getPrevious();

		button.addEvent('click', function(e){
			if (this.hasClass('collapse')) {
				this.removeClass('collapse');
				$('popular-tab').setStyle('display','block');
			} else {
				this.addClass('collapse');
				$('popular-tab').setStyle('display','none');
			}
		});
		
		button.fireEvent('click');
	},
	/**
	 * Setup tabs in the property detail page
	 */
	setupTabs : function(propertyId){
		var tabs = ['availability','enquiry','website','owner','friend'];
		
		$$('.external').each(function(anc){
			anc.target = '_blank';
		});
		
		function addShowMore()
		{
			var showMore = $('show-more');
			var availInner = $('availability-inner');
			
			AHH.from = 4;
			
			if (!showMore && availInner) {
				
				var anc = new Element('a', {id: 'show-more'}).set('text','Show more months');
				anc.addEvent('click',function(){
					
					var myRequest = new Request({url: '/func/AHH.getAvailability'});
					myRequest.addEvent('success', function(responseText, responseXML){
						var availTab = $('availability-inner');
						availTab.set('html',availTab.get('html')+responseText);
						if (AHH.from > 12) {
							$('show-more').dispose();
						}
					});
					myRequest.send('id='+propertyId+'&from='+AHH.from);
					AHH.from +=4;
					
				});
				anc.inject('availability-tab');
			}
		}
		
		tabs.each(function(t){
			var tab = $(t+'-tab');
			if (tab) {
				tab.setStyle('display','none');
				
				var button = tab.getPrevious();
				button.addClass('collapse');

				button.addEvent('click', function(e){
					if (this.hasClass('collapse')) {
						this.removeClass('collapse');
						$(t+'-tab').setStyle('display','block');	
						//Increment counter
						if (t == 'website' || t == 'owner') {
							var myRequest = new Request({'method':'get','url' :'/func/AHH.counter/'});
							myRequest.send('id='+propertyId+'&type='+t);						
						}
					} else {
						this.addClass('collapse');
						if (t == 'availability') {
							$$('#more-information .more-months').dispose();
							addShowMore();
						}
						$(t+'-tab').setStyle('display','none');
					}
				});
				
				//Add show more months option
				if (t == 'availability') {
					addShowMore();
				}
			}
		});
	},
	/**
	 * Ajax request
	 */
	pagination : function(){
		var module = 'ModuleSearch';
		if (document.location.href.search(/favourites\//) != -1) {
			module = 'ModuleFavourites';
		}
		try {
			$$('.list-panel ul.pagination a').each(function(anc){
				if (anc.href) {
					anc.addEvent('click', function(e){
						Loader.display('list-container');
												
						var PageRequest = new Request.HTML({'url' : anc.href, 'update' : 'list-container'}).get({'ajaxModule' :module});	
						PageRequest.addEvents({
							'onComplete' : function(){
								AHH.pagination();
								Loader.clear('list-container');
								document.location.href='#property';
							}
						});
						return false;
					});
				}
			});
		} catch (error){
			
		}
	},
	preparePhotos : function(){
		//show a larger image on click.
		AHH.loaded = new Array();

		$$('#property-images a').each(function(el, key){
			el.addEvent('click',function(){
				//swap the large image.
				var largeImage = $('large-image');
				
				AHH.currentKey = key;
				
				if (largeImage.src.indexOf(PhotoList[key]) != -1) {
					return false;
				}
				largeImage.set('src',PhotoList[key]);
				var aClass = this.className;
				
				if (!AHH.loaded.contains(this.href)) {
					Loader.display('photo-frame');
					AHH.loaded.push(this.href);	
					largeImage.setStyle('opacity','.3');
				}
				
				largeImage.addEvent('load',function(){
					Loader.clear('photo-frame');
					this.setStyle('opacity',1);
					Loader.adjustFrameHeight();
				});
				$('photo-frame').className = aClass;
				return false;
			});
		});
	},
	
	agentField : function() {
		var agentNo = $('User_0__isAgent_2');
		
		if (agentNo) {
			if (agentNo.checked) {
				$('tradingName').className = 'hidden';
			}
			
			agentNo.addEvent('click',function(){
				if (this.checked) {
					document.getElementById('tradingName').className = 'hidden';
				}
			});
			
			$('User_0__isAgent_3').addEvent('click',function(){
				if (this.checked) {
					document.getElementById('tradingName').className = '';
				}
			});
		}
		AHH.termsAndCondition();
	},
	
	termsAndCondition : function() {
		$('tandc-display').setStyle('display','none');
		
		$('tandc-anch').addEvent('click',function(){
			var checkDisplay = $('tandc-display').getStyle('display');
			if(checkDisplay == 'block') {
				$('tandc-display').setStyle('display','none');
			} else {
				$('tandc-display').setStyle('display','block');
			}
		});
	}
}

AHHMap = {
	
	load : function(propertyId) {
		var gDiv = new Element('div',{
			'id' : 'google-map'
		});
		
		var gFrame = new Element('iframe',{
			'src' : '/map.php?propertyId='+propertyId,
			'frameborder' :'0',
			'scrolling' : 'no',
			'events' : {
					'load' : function(){
						$('spinner').dispose();
						this.setStyle('visibility','visible');
					}
				}
		});
		
		gDiv.inject('property-detail','after');
		//Add a loader
		var coords = gDiv.getCoordinates();
		var spinner = new Element('div',{
			'id' : 'spinner',
			'class' : 'busy-signal',
			'styles' : {
					'height' : '50px',
					'width'  : '50px',
					'top'	 : '150px',
					'left'	 : '150px'
				}
		})
		gFrame.inject('google-map');
		spinner.inject('google-map');
	}
}


var AHHFeature = new Class({ 
	timeoutId : 0, 
	initialize: function(){
        this.active = 0;
		this.request = false;
		this.storage = new Hash();
		$$('#feature-list a').each(function(e){
			
			var mouseleavefunc = function() {
				this.timeoutId = this.clear.delay(200,this);
			}
			
			e.addEvents({
				'mouseover' : this.load.bindWithEvent(this,e),
				'mouseleave': mouseleavefunc.bindWithEvent(this),
				'mousemove' : this.reposition.bindWithEvent(this)
			});
		}, this);
	},	
	reposition : function(evt) {
		var popup =  $('feature-popup');
		//calc position for the box to appear 
		if (popup) {
			popup.setStyle('left', evt.page.x- 340);
			popup.setStyle('top', evt.page.y - 50);	
		}
	},
	load : function(evt, e) {
		
		//clear existing timeouts
		$clear(this.timeoutId);
		
		//grab the id and display the info box.
		var id = e.id.substr(9);
		var popup =  $('feature-popup');
		//set interval that checks cursor position
		
		if (this.active == 0 || this.active != id) {
			
			this.active = id;
			
			//if the popup doesnt
			if (!popup) {
				var popup = new Element('div',{
					'id' : 'feature-popup',
					'class' : 'busy-signal',
					'styles' : {
						'left' : (evt.page.x - 340)+'px',
						'top'  : (evt.page.y - 50)+'px'	
					}
				});
				popup.inject(document.body);
			}
			
			var completefunc = function(responseText) {
				popup.removeClass('busy-signal');
				popup.set('html',responseText);
				this.storage.set('property'+id, responseText);
			}
			if (this.storage.has('property'+id)) {
				popup.removeClass('busy-signal');
				popup.set('html',this.storage.get('property'+id));			
			} else {
				this.request = new Request({method: 'get', url: '/func/AHH.feature/?id='+id});
				this.request.addEvent('onSuccess',completefunc.bindWithEvent(this));
				this.request.send();
			}
		}
	},
	clear : function(evt) {
		var popup =  $('feature-popup');
		//Make sure the mouse isnt over the feature box
		if (popup) {
			this.active = 0;
			if (this.request != false) {
				this.request.cancel();	
			}
			popup.dispose();
			this.request = false;
		}
	}
});

var Favourites = {
	
	init : function(area) {
		
		//Detail Screen
		if (area == 'detail') {
			var liList = document.getElementById("search-results").getElementsByTagName("li");
			
			for (var i=0; i<liList.length; i++) {
				if (Browser.Engine.trident4) {
					liList[i].onmouseover=function() {
						this.className += " hover";
					}
					liList[i].onmouseout=function() {
						this.className = this.className.replace(new RegExp(" hover\\b"), "");					
					}
				}
				liList[i].onclick = function(){
					document.location.href = this.firstChild.href;
				}
			}
			
			var favTab = $('favourite-tab');
			
			favTab.addEvent('click',function() {
				//if the class 'added' exists then remove the favourite tag from it. 
				var action = 'add';
				if (this.title == 'Remove favourite') {
					this.removeClass('is-favourite');
					this.title = 'Save to favourites';
					this.set('text','Save to favourites');
					action = 'remove';
				} else {
					this.addClass('is-favourite');
					this.title = 'Remove favourite';
					this.set('text','Remove favourite');
				}
				
				var propId = this.href.split('=');
				
				//need to grab property id
				var myRequest = new Request({
					method: 'get', 
					url: '/func/AHH.favourites/'}).send('action='+action+'&propertyId='+propId.pop());
				return false;
			});
		}
		/*
		var myTips = new Tips('.property-info span, .favourites',{
			className : 'tool',
			onShow: function(toolTip) {
				toolTip.setStyle('opacity','.9');
			}
		});*/
		
		$$('li.info-other a, #search-results .favourites').each(function(e){
			//e.store('tip:text', '');
			e.addEvent('click',function(){
				//if the class 'added' exists then remove the favourite tag from it. 
				var action = 'add';
				if (this.hasClass('active-fav')) {
					this.removeClass('active-fav');
					this.title = 'Add to favourites';
					this.set('text','Add to favourites');
					action = 'remove';
				} else {
					this.addClass('active-fav');
					this.title = 'Remove from favourites';
					this.set('text','Remove from favourites');
				}
				
				//this.store('tip:title', this.title);
				//need to grab property id
				var myRequest = new Request({
					method: 'get', 
					url: '/func/AHH.favourites/'}).send('action='+action+'&propertyId='+this.id.split('-')[1]);
				
				var hasCompleted = 0;
				myRequest.addEvent('complete', function(){
					if(window.location.href.match('/favourites') != null && hasCompleted == 0) {
						// we are on the favourites page, adding or removing a favourite
						if(action == 'remove') {
							if(e.getParent().className == 'first active' || e.getParent().className == 'active') {
								
								if(e.getParent().getNext()) {
									// there is another in list
									var anchorElement = e.getParent().getNext().getElement('a');
									if(anchorElement.href != '') {
										window.location.href=anchorElement.href;
									} else {
										window.location.href='/favourites/';
									}
								} else {
									// no others in list below
									if(e.getParent().getParent().getFirst() && (e.getParent().getParent().getFirst().className != 'first active' && e.getParent().getParent().getFirst().className != 'active')) {
										// there is a parent in list which is not selected
										var anchorElement = e.getParent().getParent().getFirst().getElement('a')
										if(anchorElement.href != '') {
											window.location.href=anchorElement.href;
											return false;
										} else {
											window.location.href='/favourites/';
										}
									} else {
										// no parent or selected
										window.location.href='/favourites/';
									}
								}
								
							} else {
								window.location.reload();
							}
						}
					}
					
					hasCompleted = 1;
				});
				
				return false;
			});
		});
	}
	
}

var Loader = {
	display : function(e) {
		var obj = $(e);
		var size = obj.getScrollSize();
		//var e = $('large-image').setStyle('opacity','.1');
		//Generate a prefix id for our feedback animation containers.
		var loading = new Element('div',{
			'id' : e+'-loader',
			'styles' : {
				'width' : (size.x - 12)+'px',
				'height': (size.y - 10)+'px',
				'margin': '0 6px',
				'position': 'absolute',
				'opacity' : '.5',
				'z-index' :	'4',
				'filter'  : 'alpha(opacity=100)',
				'background' : 'url(/css/images/spinner.gif) no-repeat 50% 50%'	
			}
		});
		
		loading.inject(obj,'top');				
	},
	
	clear : function(e) {
		if ($(e+'-loader')) {
			$(e+'-loader').dispose();
		}
	},

	adjustFrameHeight : function() {
		if (!$('large-image')) {
			return;
		}
		if ($('large-image').getStyle('cursor')=='pointer') {
			$$('span.image-note').setStyle('display', 'block');
		} else {
			$$('span.image-note').setStyle('display', 'none');
		}
		return;
	}
	
}


function correctScrollPosition() {
	urlAnchorPosition = window.location.href.lastIndexOf('#');
	if (urlAnchorPosition==-1){
		return;
	}
	scrollToAnchor = window.location.href.substr(urlAnchorPosition+1);
	for(idx=0; idx<document.anchors.length; idx++) {
		if (document.anchors[idx].name==scrollToAnchor) {
			break;
		}
	}
	window.scroll(0, findPos(document.anchors[idx])[1]);
	return;
}
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj && obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
}

window.addEvent('domready', function() {
	correctScrollPosition();
	Loader.adjustFrameHeight();
});

/*
function suppressError() {return true;}
window.onerror = suppressError;
*/