var GMapHandler = new Class( {
	Implements: Options,
	
	options: {
		addMarkerToCentre: true,
		center: '',
		latitude: 'lon',
		longitude: 'lat',
		controls: false,
		oMap: 'gmap',
		zoom: 14
	},

	map: false,
	
	initialize: function(gmap, options) {
		var self = this;
	
		options.oMap = gmap;
		this.setOptions(options);

		latitude = this.options.latitude.toFloat();
		longitude = this.options.longitude.toFloat();
	    myLatlng = new google.maps.LatLng(latitude, longitude);

	    var myOptions = {
			zoom: this.options.zoom.toInt(),
			center: myLatlng,
			mapTypeControl: this.options.controls,
			mapTypeId: google.maps.MapTypeId.ROADMAP
	    }
		var points = this.options.oMap.getElements('span.marker');
	    this.map = new google.maps.Map((this.options.oMap), myOptions);
		if (points.length) {
			points.each(function(point){
				var options = JSON.decode(point.getAttribute('rel'));
				loc = new google.maps.LatLng(options.latitude, options.longitude);
				var info = point.get('html');
				if (options.marker !== false) {
				    var marker = new google.maps.Marker({
				        position: loc,
				        map: self.map
			        })
					if (info.length) {
				        var popup = new google.maps.InfoWindow({
				        	content: info
				        })
						google.maps.event.addListener(marker, 'click', function() {
							popup.open(self.map, marker);
						});
					}
				}
			});
		}
		
		gmap.store('gmap', this);
	},
	
	setCenter: function(lat, lon, zoom) {
		this.map.setCenter(new google.maps.LatLng(lat, lon));
		this.map.setZoom(zoom);
	}
	
});

var MooDropMenu = new Class({
		
	Implements: [Options,Events],
	
	options: {
		onOpen: function(el){
			// open the menu
			el.fade('in');
		},
		onClose: function(el){
			// close the menu
			el.fade('out');
		},
		onInitialize: function(el){
			// set menu to hide
			el.set('opacity',0);
			el.fade('hide').set('tween',{duration:200}); 
		},
		mouseoutDelay: 100,
		mouseoverDelay: 0
	},
	
	initialize: function(menu, options, level){
		this.setOptions(options);
		
		if ($type(level) == 'number') {
			this.menu = document.id(menu); //attach menu to object
			this.fireEvent('initialize',menu);
			
			// hook up menu's parent with event to trigger menu
			this.menu.pel.addEvents({
				
				'mouseover': function(){
					// Set the DropDownOpen status to true			
					this.menu.pel.mel.store('DropDownOpen',true);
					
					// Clear the timer of the delay
					$clear(this.timer);
					// Fire the event to open the menu
					this.timer = (function(){
						this.fireEvent('open',this.menu.pel.mel);
					}).delay(this.options.mouseoverDelay,this);		
					
				}.bind(this),
				
				'mouseout': function(){
					// Set the DropDownOpen status to false
					this.menu.pel.mel.store('DropDownOpen',false);
					
					// Clear the timer of the delay
					$clear(this.timer);
					// Build a delay before the onClose event get fired
					this.timer = (function(){
						if(!this.menu.pel.mel.retrieve('DropDownOpen')){
							this.fireEvent('close',this.menu.pel.mel);
						}
					}).delay(this.options.mouseoutDelay,this);		
					
				}.bind(this)				
			});
		}
		else {
			level = 0;
			this.menu = document.id(menu);
		}
		
		// grab all of the menus children - LI's in this case		
		// loop through children
		this.menu.getChildren('li').each(function(item, index){
			var list = item.getFirst('ul'); // Should be an A tag
			// if there is a sub menu UL
			if ($type(list) == 'element') {
				item.mel = list; // pel = parent element
				list.pel = item; // mel = menu element
				new MooDropMenu(list, options, level + 1); // hook up the subMenu
			}
		});			
	},
	
	toElement: function(){
		return this.menu
	}
	
});

var SimpleSlideshow = new Class({
	options: {
		showControls: false,
		showDuration: 4000,
		showTOC: false,
		tocWidth: 20,
		tocClass: 'toc',
		tocActiveClass: 'toc-active'
	},
	Implements: [Options,Events],
	initialize: function(container,elements,options) {
		//settings
		this.container = $(container);
		this.elements = $$(elements);
		this.currentIndex = 0;
		this.interval = '';
		if(this.options.showTOC) this.toc = [];
		
		//assign
		this.elements.each(function(el,i){
			if(this.options.showTOC) {
				this.toc.push(new Element('a',{
					text: i+1,
					href: '#',
					'class': this.options.tocClass + '' + (i == 0 ? ' ' + this.options.tocActiveClass : ''),
					events: {
						click: function(e) {
							if(e) e.stop();
							this.stop();
							this.show(i);
						}.bind(this)
					},
					styles: {
						left: ((i + 1) * (this.options.tocWidth + 10))
					}
				}).inject(this.container));
			}
			el.set('tween', {duration: 'long'});
			if(i > 0) el.set('opacity',0);
		},this);
		
		//next,previous links
		if(this.options.showControls) {
			this.createControls();
		}
		//events
		this.container.addEvents({
			mouseenter: function() { this.stop(); }.bind(this),
			mouseleave: function() { this.start(); }.bind(this)
		});

	},
	show: function(to) {
		this.elements[this.currentIndex].fade('out');
		if(this.options.showTOC) this.toc[this.currentIndex].removeClass(this.options.tocActiveClass);
		this.currentIndex = ($defined(to) ? to : (this.currentIndex < this.elements.length - 1 ? this.currentIndex + 1 : 0));
		this.elements[this.currentIndex].fade('in');
		if(this.options.showTOC) this.toc[this.currentIndex].addClass(this.options.tocActiveClass);
	},
	start: function() {
		this.interval = this.show.bind(this).periodical(this.options.showDuration);
	},
	stop: function() {
		$clear(this.interval);
	},
	//"private"
	createControls: function() {
		var next = new Element('a',{
			href: '#',
			id: 'next',
			text: '>>',
			events: {
				click: function(e) {
					if(e) e.stop();
					this.stop(); 
					this.show();
				}.bind(this)
			}
		}).inject(this.container);
		var previous = new Element('a',{
			href: '#',
			id: 'previous',
			text: '<<',
			events: {
				click: function(e) {
					if(e) e.stop();
					this.stop(); 
					this.show(this.currentIndex != 0 ? this.currentIndex -1 : this.elements.length-1);
				}.bind(this)
			}
		}).inject(this.container);
	}
});

var Shared = new Class({

	maxresults: 20,
	imgmax: 320, /* 200, 288, 320, 400, 512, 576, 640, 720, 800 */

	initialize: function() {
		new MooDropMenu($('nav'));
		
		var gmaps = $$('div.gmap');
		if (gmaps.length) {
			gmaps.each(function(gmap){
				var options = gmap.getAttribute('rel');
				options = JSON.decode(options);
				new GMapHandler(gmap, options);
			});
		}
		
		$$('div.gallery a').each(function(element) {
	        new ReMooz(element, {
	            centered: true,
	            origin: element.getElement('img')
	        });
	    });

		this.startShow();
		this.addAccordions();
		this.addImgCaptions();
	},
	
	addAccordions: function() {
			var accHeadings = $$('h2.acc_toggler');
			var accDivs = $$('div.acc_content');
			if (accHeadings.length && !accDivs.length) {
				accHeadings.each(function(heading) {
					var accContent = new Element('div', {'class': 'acc_content'});
					var el = heading.getNext();
	
					while (el && (el.get('tag') != 'h2') && (!el.hasClass('acc_toggler') && (el.getStyle('position') != 'absolute'))) {
						var next = el.getNext();
						accContent.adopt(el);
						el = next;
					}
					accContent.inject(heading,'after');
				});
				
				var acc = new Fx.Accordion($$('h2.acc_toggler'), $$('div.acc_content'), {
					onActive: function(toggler, element) {
						toggler.removeClass('acc_inactive');
					},
					onBackground: function(toggler, element) {
						toggler.addClass('acc_inactive');
					}
				});
				
				if (accHeadings.length) {
					var holder = accHeadings[0].getParent();
					holder.getElements('div.r_bottomleft').dispose();
					holder.getElements('div.r_bottomcenter').dispose();
					holder.getElements('div.r_bottomright').dispose();
				}
			}
	},
		
	addImgCaptions: function() {
		var img = $('bd').getElements('img').each(function(img){
			if(!img.hasClass('no_caption')){
				var caption = img.get('alt');
				if (caption){
					var holder = new Element('div', {'class': 'caption'});
					holder.setStyles({
						width: img.get('width')+'px',
						float: (img.hasClass('float_right' || 'right') ? "right" : "left")
					});
					var image = new Element('img', {'src': img.get('src')});
					image.addClass('no_outline').inject(holder);
					new Element('p').set('text', caption).inject(holder);
					holder.replaces(img);
				}
			}
		});
	},

	startShow: function() {
		/* settings */
		var showDuration = 3500;
		var container = $('banner');
		var images = container.getElements('img');
		var currentIndex = 0;
		var interval;
		/* opacity and fade */
		images.each(function(img,i){ 
			if(i > 0) {
				img.set('opacity',0);
			}
			img.set('tween',{duration : 2000});
		});
		/* worker */
		var show = function() {
			images[currentIndex].fade('out');
			images[currentIndex = currentIndex < images.length - 1 ? currentIndex+1 : 0].fade('in');
		};
		/* start once the page is finished loading */
		window.addEvent('load',function(){
			interval = show.periodical(showDuration);
		});
	}

});

var shared = null;
window.addEvent('domready', function() {
	shared = new Shared();
});
