/*
	Multifaceted Lightbox
	by Greg Neustaetter - http://www.gregphoto.net
	
	INSPIRED BY (AND CODE TAKEN FROM)
	==================================
	The Lightbox Effect without Lightbox
	PJ Hyett
	http://pjhyett.com/articles/2006/02/09/the-lightbox-effect-without-lightbox
	

	Lightbox JS: Fullsize Image Overlays 
	by Lokesh Dhakar - http://www.huddletogether.com

	For more information on this script, visit:
	http://huddletogether.com/projects/lightbox/

	Licensend under:
	Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
	(basically, do anything you want, just leave my name and link)
	
*/

var MfLightbox = {
	lightboxType : null,
	lightboxCurrentContentID : null,
	
	showBoxString : function(content, boxWidth, boxHeight){
		this.setLightboxDimensions(boxWidth, boxHeight);
		this.lightboxType = 'string';
		if($('boxContents')) {
			var contents = $('boxContents');
			contents.innerHTML=content;
		}
		this.showBox();
		return false;
	},


	showBoxImage : function(href) {
		this.lightboxType = 'image';
		var contents = $('boxContents');
		var objImage = document.createElement("img");
		objImage.setAttribute('id','lightboxImage');
		contents.appendChild(objImage);
		imgPreload = new Image();
		imgPreload.onload=function(){
			objImage.src = href;
			MfLightbox.showBox();
		}
		imgPreload.src = href;
		return false;
	},

	showBoxByID : function(id, boxWidth, boxHeight) {
		this.lightboxType = 'id';
		this.lightboxCurrentContentID = id;
		this.setLightboxDimensions(boxWidth, boxHeight);
		var element = $(id);
		if($('boxContents')) {
			var contents = $('boxContents');
			contents.appendChild(element);
		}
		Element.show(id);
		this.showBox();
		return false;
	},

	showBoxByAJAX : function(href, boxWidth, boxHeight) {
		this.lightboxType = 'ajax';
		this.setLightboxDimensions(boxWidth, boxHeight);
		var contents = $('boxContents');
		var myAjax = new Ajax.Updater(contents, href, {method: 'get', evalScripts: true });
		this.showBox();
		return false;
	},
	
	setLightboxDimensions : function(width, height) {
		var windowSize = this.getPageDimensions();
		if(width) {
			if(width < windowSize[0]) {
				$('box').style.width = width + 'px';
			} else {
				$('box').style.width = (windowSize[0] - 50) + 'px';
			}
		}
		if(height) {
			if(height < windowSize[1]) {
				$('box').style.height = height + 'px';
			} else {
				$('box').style.height = (windowSize[1] - 50) + 'px';
			}
		}
	},


	showBox : function() {
		// disable flash
		$$('embed, object').invoke('hide');

		Element.show('mf_overlay');
		this.center('box');
		return false;
	},
	
	
	hideBox : function(){
		// reenable flash
		$$('embed, object').invoke('show');

		if($('boxContents')) {
			var contents = $('boxContents');
			if(this.lightboxType == 'id') {
				var body = document.getElementsByTagName("body").item(0);
				Element.hide(this.lightboxCurrentContentID);
				body.appendChild($(this.lightboxCurrentContentID));
			}
			contents.innerHTML = '';
		}

		$('box').style.width = null;
		$('box').style.height = null;
		Element.hide('box');
		Element.hide('mf_overlay');
		return false;
	},
	
	// taken from lightbox js, modified argument return order
	getPageDimensions : function(){
		var xScroll, yScroll;
	
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = document.body.scrollWidth;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		
		var windowWidth, windowHeight;
		if (self.innerHeight) {	// all except Explorer
			windowWidth = self.innerWidth;
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
		
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
	
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = windowWidth;
		} else {
			pageWidth = xScroll;
		}
		arrayPageSize = new Array(windowWidth,windowHeight,pageWidth,pageHeight) 
		return arrayPageSize;
	},
	
	center : function(element){
		try{
			element = document.getElementById(element);
		}catch(e){
			return;
		}
		var windowSize = this.getPageDimensions();
		var window_width  = windowSize[0];
		var window_height = windowSize[1];
		
		$('mf_overlay').style.height = windowSize[3] + 'px';
		
		element.style.position = 'absolute';
		element.style.zIndex   = 99;
	
		var scrollY = 0;
	
		if ( document.documentElement && document.documentElement.scrollTop ){
			scrollY = document.documentElement.scrollTop;
		}else if ( document.body && document.body.scrollTop ){
			scrollY = document.body.scrollTop;
		}else if ( window.pageYOffset ){
			scrollY = window.pageYOffset;
		}else if ( window.scrollY ){
			scrollY = window.scrollY;
		}
	
		var elementDimensions = Element.getDimensions(element);
		var setX = ( window_width  - elementDimensions.width  ) / 2;
		var setY = ( window_height - elementDimensions.height ) / 2 + scrollY;
	
		setX = ( setX < 0 ) ? 0 : setX;
		setY = ( setY < 0 ) ? 0 : setY;
	
		element.style.left = setX + "px";
		element.style.top  = setY + "px";
		Element.show(element);
	},
	
	init : function() {				  
		var lightboxtext = '<div id="mf_overlay" style="display:none" onClick="MfLightbox.hideBox()"></div>';
		lightboxtext += '<div id="box" style="display:none">';
		lightboxtext += '<img id="close" src="images/lightbox/mf_close.gif" onClick="MfLightbox.hideBox()" alt="Close" title="Close this window" />';
		lightboxtext += '<div id="boxContents"></div>';
		lightboxtext += '</div>';
		var body = document.getElementsByTagName("body").item(0);
		new Insertion.Bottom(body, lightboxtext);
	}
}


/**
 ======================================================================================
 === Glider ===========================================================================

 * @author Bruno Bornsztein <bruno@missingmethod.com>
 * @copyright 2007 Curbly LLC
 * @package Glider
 * @license MIT
 * @url http://www.missingmethod.com/projects/glider/
 * @version 0.0.4
 * @dependencies prototype.js 1.5.1+, effects.js
 */

/*  Thanks to Andrew Dupont for refactoring help and code cleanup - http://andrewdupont.net/  */

Glider = Class.create();
Object.extend(Object.extend(Glider.prototype, Abstract.prototype), {
	initialize: function(wrapper, options){
	    this.scrolling  = false;
	    this.wrapper    = $(wrapper);
	    this.scroller   = this.wrapper.down('div.scroller');
	    this.sections   = this.wrapper.getElementsBySelector('div.section');
	    this.options    = Object.extend({ controlsEvent:'click', duration: 1.0, frequency: 3 }, options || {});

	    this.sections.each( function(section, index) {
	      section._index = index;
	    });    

	    this.events = {
	      click: this.click.bind(this)
	    };

	    this.addObservers(this);
			if(this.options.initialSection) this.moveTo(this.options.initialSection, this.scroller, { duration:this.options.duration });  // initialSection should be the id of the section you want to show up on load
			if(this.options.autoGlide) this.start();
	  },
	
  addObservers: function(thisinstance) {
	  if($$('#slider div.controls').size()) {
		this.controls = this.wrapper.getElementsBySelector('.controls a');
		this.controls.each(function(n) {
			Event.observe(n, 'click', function(event) {
				Event.stop(event);
				var target=n.href.split("#")[1];
				thisinstance.moveTo(target, thisinstance.scroller, { duration:thisinstance.options.duration });

				thisinstance.controls.each(function(control){
					if (control == n) {
						control.addClassName("active")
					} else {
						control.removeClassName("active")
					}
				});
			});

		});
	  }
  },	

  click: function(event) {
		this.stop();
    var element = Event.findElement(event, 'a');
    if (this.scrolling) this.scrolling.cancel();
    
		moveTo = this.wrapper.down('#'+element.href.split("#")[1])
    this.moveTo(moveTo, this.scroller, { duration:this.options.duration });     
    Event.stop(event);

		this.controls.each(function(control){
			if (control == element) {
				control.addClassName("active")
			}else{
				control.removeClassName("active")
			}			
		});
  },

	moveTo: function(element, container, options){
			this.current = $(element);

			Position.prepare();
	    var containerOffset = Position.cumulativeOffset(container),
	     elementOffset = Position.cumulativeOffset($(element));

		  this.scrolling 	= new Effect.SmoothScroll(container, 
				{duration:options.duration, x:(elementOffset[0]-containerOffset[0]), y:(elementOffset[1]-containerOffset[1])});
		  return false;
		},
		
  next: function(desc){
    if (this.current) {
      var currentIndex = this.current._index;
      var nextIndex = (this.sections.length - 1 == currentIndex) ? 0 : currentIndex + 1;      
    } else var nextIndex = 1;

	if(this.controls) {
		this.controls.invoke('removeClassName', 'active');
		this.controls[nextIndex].addClassName("active");
	}

    this.moveTo(this.sections[nextIndex], this.scroller, { 
      duration: this.options.duration
    });

	this.stop();

	// VENUE HIRE - update image description
	var x = this.wrapper;
	var y = this.sections[nextIndex].down('img').readAttribute('alt');
	var z = this.sections[nextIndex].down('img').readAttribute('src');
	//if we have a main img - update that, else update slider
	if($('sldrimg')) {

		$('sldrimg').hide();
		small_preloader = new Image();
		// once image is preloaded, apply effects
		small_preloader.onload=function(){
			$('sldrimg').src=small_preloader.src;
			Effect.Appear($('sldrimg'));
		}
		small_preloader.src = z.replace(/\/[0-9]+\.jpg/gi, "/large/"+(nextIndex+1)+".jpg");
		$('sldrtxt').update(y);

	} else if(x.up(0).down('.text')) {
		x.up(0).down('.text').innerHTML=y;
	}

  },
	
  previous: function(){
    if (this.current) {
      var currentIndex = this.current._index;
      var prevIndex = (currentIndex == 0) ? this.sections.length - 1 : 
       currentIndex - 1;
    } else var prevIndex = this.sections.length - 1;

	if(this.controls) {
		this.controls.invoke('removeClassName', 'active');
		this.controls[prevIndex].addClassName("active");
	}

    this.moveTo(this.sections[prevIndex], this.scroller, { 
      duration: this.options.duration
    });

	this.stop();

	// VENUE HIRE - update image description
	var x = this.wrapper;
	var y = this.sections[prevIndex].down('img').readAttribute('alt');
	var z = this.sections[prevIndex].down('img').readAttribute('src');
	//if we have a main img - update that, else update slider
	if($('sldrimg')) {

		$('sldrimg').hide();
		small_preloader = new Image();
		// once image is preloaded, apply effects
		small_preloader.onload=function(){
			$('sldrimg').src=small_preloader.src;
			Effect.Appear($('sldrimg'));
		}
		small_preloader.src = z.replace(/\/[0-9]+\.jpg/gi, "/large/"+(prevIndex+1)+".jpg");
		$('sldrtxt').update(y);

	} else if(x.up(0).down('.text')) {
		x.up(0).down('.text').innerHTML=y;
	}

  },

	stop: function()
	{
		clearTimeout(this.timer);
	},
	
	start: function()
	{
		this.periodicallyUpdate();
	},
		
	periodicallyUpdate: function()
	{ 
		if (this.timer != null) {
			clearTimeout(this.timer);
			this.next();
		}
		this.timer = setTimeout(this.periodicallyUpdate.bind(this), this.options.frequency*1000);
	}

});

Effect.SmoothScroll = Class.create();
Object.extend(Object.extend(Effect.SmoothScroll.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    var options = Object.extend({
      x:    0,
      y:    0,
      mode: 'absolute'
    } , arguments[1] || {}  );
    this.start(options);
  },
  setup: function() {
    if (this.options.continuous && !this.element._ext ) {
      this.element.cleanWhitespace();
      this.element._ext=true;
      this.element.appendChild(this.element.firstChild);
    }
   
    this.originalLeft=this.element.scrollLeft;
    this.originalTop=this.element.scrollTop;
   
    if(this.options.mode == 'absolute') {
      this.options.x -= this.originalLeft;
      this.options.y -= this.originalTop;
    } 
  },
  update: function(position) {   
    this.element.scrollLeft = this.options.x * position + this.originalLeft;
    this.element.scrollTop  = this.options.y * position + this.originalTop;
  }
});


// -----------------------------------------------------------------------------------
//
//	Lightbox v2.02
//	by Lokesh Dhakar - http://www.huddletogether.com
//	3/31/06
//
//	For more information on this script, visit:
//	http://huddletogether.com/projects/lightbox2/
//
//	Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
//	
//	Credit also due to those who have helped, inspired, and made their code available to the public.
//	Including: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.org), Thomas Fuchs(mir.aculo.us), and others.
//
//
// -----------------------------------------------------------------------------------
/*

	Table of Contents
	-----------------
	Configuration
	Global Variables

	Extending Built-in Objects	
	- Object.extend(Element)
	- Array.prototype.removeDuplicates()
	- Array.prototype.empty()

	Lightbox Class Declaration
	- initialize()
	- start()
	- changeImage()
	- resizeImageContainer()
	- showImage()
	- updateDetails()
	- updateNav()
	- enableKeyboardNav()
	- disableKeyboardNav()
	- keyboardAction()
	- preloadNeighborImages()
	- end()
	
	Miscellaneous Functions
	- getPageScroll()
	- getPageSize()
	- getKey()
	- listenKey()
	- showSelectBoxes()
	- hideSelectBoxes()
	- pause()
	- initLightbox()
	
	Function Calls
	- addLoadEvent(initLightbox)
	
*/
// -----------------------------------------------------------------------------------

//
//	Configuration
//
var fileLoadingImage = "images/lightbox/loading.gif";		
var fileBottomNavCloseImage = "images/lightbox/closelabel.gif";

var resizeSpeed = 7;	// controls the speed of the image resizing (1=slowest and 10=fastest)

var borderSize = 10;	//if you adjust the padding in the CSS, you will need to update this variable

// -----------------------------------------------------------------------------------

//
//	Global Variables
//
var imageArray = new Array;
var activeImage;

if(resizeSpeed > 10){ resizeSpeed = 10;}
if(resizeSpeed < 1){ resizeSpeed = 1;}
resizeDuration = (11 - resizeSpeed) * 0.15;

// -----------------------------------------------------------------------------------

//
//	Additional methods for Element added by SU, Couloir
//	- further additions by Lokesh Dhakar (huddletogether.com)
//
Object.extend(Element, {
	getWidth: function(element) {
	   	element = $(element);
	   	return element.offsetWidth; 
	},
	setWidth: function(element,w) {
	   	element = $(element);
    	element.style.width = w +"px";
	},
	setHeight: function(element,h) {
   		element = $(element);
    	element.style.height = h +"px";
	},
	setTop: function(element,t) {
	   	element = $(element);
    	element.style.top = t +"px";
	},
	setSrc: function(element,src) {
    	element = $(element);
    	element.src = src; 
	},
	setHref: function(element,href) {
    	element = $(element);
    	element.href = href; 
	},
	setInnerHTML: function(element,content) {
		element = $(element);
		element.innerHTML = content;
	}
});

// -----------------------------------------------------------------------------------

//
//	Extending built-in Array object
//	- array.removeDuplicates()
//	- array.empty()
//
Array.prototype.removeDuplicates = function () {
	for(i = 1; i < this.length; i++){
		if(this[i][0] == this[i-1][0]){
			this.splice(i,1);
		}
	}
}

// -----------------------------------------------------------------------------------

Array.prototype.empty = function () {
	for(i = 0; i <= this.length; i++){
		this.shift();
	}
}

// -----------------------------------------------------------------------------------

//
//	Lightbox Class Declaration
//	- initialize()
//	- start()
//	- changeImage()
//	- resizeImageContainer()
//	- showImage()
//	- updateDetails()
//	- updateNav()
//	- enableKeyboardNav()
//	- disableKeyboardNav()
//	- keyboardNavAction()
//	- preloadNeighborImages()
//	- end()
//
//	Structuring of code inspired by Scott Upton (http://www.uptonic.com/)
//
var Lightbox = Class.create();

Lightbox.prototype = {
	
	// initialize()
	// Constructor runs on completion of the DOM loading. Loops through anchor tags looking for 
	// 'lightbox' references and applies onclick events to appropriate links. The 2nd section of
	// the function inserts html at the bottom of the page which is used to display the shadow 
	// overlay and the image container.
	//
	initialize: function() {	
		if (!document.getElementsByTagName){ return; }
		var anchors = document.getElementsByTagName('a');

		// loop through all anchor tags
		for (var i=0; i<anchors.length; i++){
			var anchor = anchors[i];
			
			var relAttribute = String(anchor.getAttribute('rel'));
			
			// use the string.match() method to catch 'lightbox' references in the rel attribute
			if (anchor.getAttribute('href') && (relAttribute.toLowerCase().match('lightbox'))){
				anchor.onclick = function () {myLightbox.start(this); return false;}
			}
		}

		// The rest of this code inserts html at the bottom of the page that looks similar to this:
		//
		//	<div id="overlay"></div>
		//	<div id="lightbox">
		//		<div id="outerImageContainer">
		//			<div id="imageContainer">
		//				<img id="lightboxImage">
		//				<div style="" id="hoverNav">
		//					<a href="#" id="prevLink"></a>
		//					<a href="#" id="nextLink"></a>
		//				</div>
		//				<div id="loading">
		//					<a href="#" id="loadingLink">
		//						<img src="images/loading.gif">
		//					</a>
		//				</div>
		//			</div>
		//		</div>
		//		<div id="imageDataContainer">
		//			<div id="imageData">
		//				<div id="imageDetails">
		//					<span id="caption"></span>
		//					<span id="numberDisplay"></span>
		//				</div>
		//				<div id="bottomNav">
		//					<a href="#" id="bottomNavClose">
		//						<img src="images/close.gif">
		//					</a>
		//				</div>
		//			</div>
		//		</div>
		//	</div>


		var objBody = document.getElementsByTagName("body").item(0);
		
		var objOverlay = document.createElement("div");
		objOverlay.setAttribute('id','overlay');
		objOverlay.style.display = 'none';
		objOverlay.onclick = function() { myLightbox.end(); return false; }
		objBody.appendChild(objOverlay);
		
		var objLightbox = document.createElement("div");
		objLightbox.setAttribute('id','lightbox');
		objLightbox.style.display = 'none';
		objBody.appendChild(objLightbox);
	
		var objOuterImageContainer = document.createElement("div");
		objOuterImageContainer.setAttribute('id','outerImageContainer');
		objLightbox.appendChild(objOuterImageContainer);

		var objImageContainer = document.createElement("div");
		objImageContainer.setAttribute('id','imageContainer');
		objOuterImageContainer.appendChild(objImageContainer);
	
		var objLightboxImage = document.createElement("img");
		objLightboxImage.setAttribute('id','lightboxImage');
		objImageContainer.appendChild(objLightboxImage);
	
		var objHoverNav = document.createElement("div");
		objHoverNav.setAttribute('id','hoverNav');
		objImageContainer.appendChild(objHoverNav);
	
		var objPrevLink = document.createElement("a");
		objPrevLink.setAttribute('id','prevLink');
		objPrevLink.setAttribute('href','#');
		objHoverNav.appendChild(objPrevLink);
		
		var objNextLink = document.createElement("a");
		objNextLink.setAttribute('id','nextLink');
		objNextLink.setAttribute('href','#');
		objHoverNav.appendChild(objNextLink);
	
		var objLoading = document.createElement("div");
		objLoading.setAttribute('id','loading');
		objImageContainer.appendChild(objLoading);
	
		var objLoadingLink = document.createElement("a");
		objLoadingLink.setAttribute('id','loadingLink');
		objLoadingLink.setAttribute('href','#');
		objLoadingLink.onclick = function() { myLightbox.end(); return false; }
		objLoading.appendChild(objLoadingLink);
	
		var objLoadingImage = document.createElement("img");
		objLoadingImage.setAttribute('src', fileLoadingImage);
		objLoadingLink.appendChild(objLoadingImage);

		var objImageDataContainer = document.createElement("div");
		objImageDataContainer.setAttribute('id','imageDataContainer');
		objImageDataContainer.className = 'clearfix';
		objLightbox.appendChild(objImageDataContainer);

		var objImageData = document.createElement("div");
		objImageData.setAttribute('id','imageData');
		objImageDataContainer.appendChild(objImageData);
	
		var objImageDetails = document.createElement("div");
		objImageDetails.setAttribute('id','imageDetails');
		objImageData.appendChild(objImageDetails);
	
		var objCaption = document.createElement("span");
		objCaption.setAttribute('id','caption');
		objImageDetails.appendChild(objCaption);
	
		var objNumberDisplay = document.createElement("span");
		objNumberDisplay.setAttribute('id','numberDisplay');
		objImageDetails.appendChild(objNumberDisplay);
		
		var objBottomNav = document.createElement("div");
		objBottomNav.setAttribute('id','bottomNav');
		objImageData.appendChild(objBottomNav);
	
		var objBottomNavCloseLink = document.createElement("a");
		objBottomNavCloseLink.setAttribute('id','bottomNavClose');
		objBottomNavCloseLink.setAttribute('href','#');
		objBottomNavCloseLink.onclick = function() { myLightbox.end(); return false; }
		objBottomNav.appendChild(objBottomNavCloseLink);
	
		var objBottomNavCloseImage = document.createElement("img");
		objBottomNavCloseImage.setAttribute('src', fileBottomNavCloseImage);
		objBottomNavCloseLink.appendChild(objBottomNavCloseImage);
	},
	
	//
	//	start()
	//	Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
	//
	start: function(imageLink) {	

		hideSelectBoxes();
		hideFlash();

		// stretch overlay to fill page and fade in
		var arrayPageSize = getPageSize();
		Element.setHeight('overlay', arrayPageSize[1]);
		new Effect.Appear('overlay', { duration: 0.2, from: 0.0, to: 0.8 });

		imageArray = [];
		imageNum = 0;		

		if (!document.getElementsByTagName){ return; }
		var anchors = document.getElementsByTagName('a');

		// if image is NOT part of a set..
		if((imageLink.getAttribute('rel') == 'lightbox')){
			// add single image to imageArray
			imageArray.push(new Array(imageLink.getAttribute('href'), imageLink.getAttribute('title')));			
		} else {
		// if image is part of a set..

			// loop through anchors, find other images in set, and add them to imageArray
			for (var i=0; i<anchors.length; i++){
				var anchor = anchors[i];
				if (anchor.getAttribute('href') && (anchor.getAttribute('rel') == imageLink.getAttribute('rel'))){
					imageArray.push(new Array(anchor.getAttribute('href'), anchor.getAttribute('title')));
				}
			}
			imageArray.removeDuplicates();
			while(imageArray[imageNum][0] != imageLink.getAttribute('href')) { imageNum++;}
		}

		// calculate top offset for the lightbox and display 
		var arrayPageSize = getPageSize();
		var arrayPageScroll = getPageScroll();
		var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 15);

		Element.setTop('lightbox', lightboxTop);
		Element.show('lightbox');
		
		this.changeImage(imageNum);
	},

	//
	//	changeImage()
	//	Hide most elements and preload image in preparation for resizing image container.
	//
	changeImage: function(imageNum) {	
		
		activeImage = imageNum;	// update global var

		// hide elements during transition
		Element.show('loading');
		Element.hide('lightboxImage');
		Element.hide('hoverNav');
		Element.hide('prevLink');
		Element.hide('nextLink');
		Element.hide('imageDataContainer');
		Element.hide('numberDisplay');		
		
		imgPreloader = new Image();
		
		// once image is preloaded, resize image container
		imgPreloader.onload=function(){
			Element.setSrc('lightboxImage', imageArray[activeImage][0]);
			myLightbox.resizeImageContainer(imgPreloader.width, imgPreloader.height);
		}
		imgPreloader.src = imageArray[activeImage][0];
	},

	//
	//	resizeImageContainer()
	//
	resizeImageContainer: function( imgWidth, imgHeight) {

		// get current height and width
		this.wCur = Element.getWidth('outerImageContainer');
		this.hCur = Element.getHeight('outerImageContainer');

		// scalars based on change from old to new
		this.xScale = ((imgWidth  + (borderSize * 2)) / this.wCur) * 100;
		this.yScale = ((imgHeight  + (borderSize * 2)) / this.hCur) * 100;

		// calculate size difference between new and old image, and resize if necessary
		wDiff = (this.wCur - borderSize * 2) - imgWidth;
		hDiff = (this.hCur - borderSize * 2) - imgHeight;

		if(!( hDiff == 0)){ new Effect.Scale('outerImageContainer', this.yScale, {scaleX: false, duration: resizeDuration, queue: 'front'}); }
		if(!( wDiff == 0)){ new Effect.Scale('outerImageContainer', this.xScale, {scaleY: false, delay: resizeDuration, duration: resizeDuration}); }

		// if new and old image are same size and no scaling transition is necessary, 
		// do a quick pause to prevent image flicker.
		if((hDiff == 0) && (wDiff == 0)){
			if (navigator.appVersion.indexOf("MSIE")!=-1){ pause(250); } else { pause(100);} 
		}

		Element.setHeight('prevLink', imgHeight);
		Element.setHeight('nextLink', imgHeight);
		Element.setWidth( 'imageDataContainer', imgWidth + (borderSize * 2));

		this.showImage();
	},
	
	//
	//	showImage()
	//	Display image and begin preloading neighbors.
	//
	showImage: function(){
		Element.hide('loading');
		new Effect.Appear('lightboxImage', { duration: 0.5, queue: 'end', afterFinish: function(){	myLightbox.updateDetails(); } });
		this.preloadNeighborImages();
	},

	//
	//	updateDetails()
	//	Display caption, image number, and bottom nav.
	//
	updateDetails: function() {
	
		Element.show('caption');
		Element.setInnerHTML( 'caption', imageArray[activeImage][1]);
		
		// if image is part of set display 'Image x of x' 
		if(imageArray.length > 1){
			Element.show('numberDisplay');
			Element.setInnerHTML( 'numberDisplay', "Image " + eval(activeImage + 1) + " of " + imageArray.length);
		}

		new Effect.Parallel(
			[ new Effect.SlideDown( 'imageDataContainer', { sync: true, duration: resizeDuration + 0.25, from: 0.0, to: 1.0 }), 
			  new Effect.Appear('imageDataContainer', { sync: true, duration: 1.0 }) ], 
			{ duration: 0.65, afterFinish: function() { myLightbox.updateNav();} } 
		);
	},

	//
	//	updateNav()
	//	Display appropriate previous and next hover navigation.
	//
	updateNav: function() {

		Element.show('hoverNav');				

		// if not first image in set, display prev image button
		if(activeImage != 0){
			Element.show('prevLink');
			document.getElementById('prevLink').onclick = function() {
				myLightbox.changeImage(activeImage - 1); return false;
			}
		}

		// if not last image in set, display next image button
		if(activeImage != (imageArray.length - 1)){
			Element.show('nextLink');
			document.getElementById('nextLink').onclick = function() {
				myLightbox.changeImage(activeImage + 1); return false;
			}
		}
		
		this.enableKeyboardNav();
	},

	//
	//	enableKeyboardNav()
	//
	enableKeyboardNav: function() {
		document.onkeydown = this.keyboardAction; 
	},

	//
	//	disableKeyboardNav()
	//
	disableKeyboardNav: function() {
		document.onkeydown = '';
	},

	//
	//	keyboardAction()
	//
	keyboardAction: function(e) {
		if (e == null) { // ie
			keycode = event.keyCode;
		} else { // mozilla
			keycode = e.which;
		}

		key = String.fromCharCode(keycode).toLowerCase();
		
		if((key == 'x') || (key == 'o') || (key == 'c')){	// close lightbox
			myLightbox.end();
		} else if(key == 'p'){	// display previous image
			if(activeImage != 0){
				myLightbox.disableKeyboardNav();
				myLightbox.changeImage(activeImage - 1);
			}
		} else if(key == 'n'){	// display next image
			if(activeImage != (imageArray.length - 1)){
				myLightbox.disableKeyboardNav();
				myLightbox.changeImage(activeImage + 1);
			}
		}


	},

	//
	//	preloadNeighborImages()
	//	Preload previous and next images.
	//
	preloadNeighborImages: function(){

		if((imageArray.length - 1) > activeImage){
			preloadNextImage = new Image();
			preloadNextImage.src = imageArray[activeImage + 1][0];
		}
		if(activeImage > 0){
			preloadPrevImage = new Image();
			preloadPrevImage.src = imageArray[activeImage - 1][0];
		}
	
	},

	//
	//	end()
	//
	end: function() {
		this.disableKeyboardNav();
		Element.hide('lightbox');
		new Effect.Fade('overlay', { duration: 0.2});
		showSelectBoxes();
		showFlash();
	}
}

// -----------------------------------------------------------------------------------

//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}

// -----------------------------------------------------------------------------------

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

// -----------------------------------------------------------------------------------

//
// getKey(key)
// Gets keycode. If 'x' is pressed then it hides the lightbox.
//
function getKey(e){
	if (e == null) { // ie
		keycode = event.keyCode;
	} else { // mozilla
		keycode = e.which;
	}
	key = String.fromCharCode(keycode).toLowerCase();
	
	if(key == 'x'){
	}
}

// -----------------------------------------------------------------------------------

//
// listenKey()
//
function listenKey () {	document.onkeypress = getKey; }
	
// ---------------------------------------------------

function showSelectBoxes(){
	selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "visible";
	}
}

function showFlash(){
	// show flash
	$$('.main embed, .main object').invoke('show');
}

// ---------------------------------------------------

function hideSelectBoxes(){
	selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "hidden";
	}
}

function hideFlash(){
	// disable flash
	$$('.main embed, .main object').invoke('hide');
}

// ---------------------------------------------------

//
// pause(numberMillis)
// Pauses code execution for specified time. Uses busy code, not good.
// Code from http://www.faqts.com/knowledge_base/view.phtml/aid/1602
//
function pause(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
			return;
	}
}

// ---------------------------------------------------



function initLightbox() { myLightbox = new Lightbox(); }
Event.observe(window, 'load', initLightbox, false);

// *=========================================================================================
// *=========================================================================================
// *=========================================================================================

function validate_enq(form) {

	var arr_date = $(form['date_arrive']);
	var dep_date = $(form['date_depart']);
	var rtype = $(form['room_type']);
	var fname = $(form['first_name']);
	var lname = $(form['last_name']);
	var phone = $(form['phone']);
	var email = $(form['email']);
	var nationality = $(form['nationality']);
	var course_duration = $(form['course_duration']);
	
	var sError = "";

	// Validate Dates
	if ( arr_date.value.length == 0 || arr_date.value=='Arriving' ) {
		sError += "Please provide your Check-in date\n";
	} 
	if ( dep_date.value.length == 0 || dep_date.value=='Departing' ) {
		sError += "Please provide your Check-out date\n";
	} 

	if(arr_date.value.length != 0 && dep_date.value.length != 0) {
		// check dates order
		arr=arr_date.value.split("/");
		dep=dep_date.value.split("/");
		arr_date=new Date(arr[2],arr[1],arr[0]);
		dep_date=new Date(dep[2],dep[1],dep[0]);

		if ( arr_date > dep_date ) {
			sError += "Check-out date cannot be earlier than check-in date.\n";
		}
	}

	// Validate Room Type
	if ( rtype.value.length == 0 ) {
		sError += "Please select Room Type.\n";
	}

	// Validate First Name
	if ( fname.value.length == 0 ) {
		sError += "Please enter your First Name.\n";
	}

	// Validate Last Name
	if ( lname.value.length == 0 ) {
		sError += "Please enter your Last Name.\n";
	}


	// Validate Phone
	if ( phone.value.length == 0 ) {
		sError += "Please provide your phone number.\n";
	} else {

		var str = phone.value;
		var newphone = str.replace(/(\s|\(|\)|-)/gi, "");
		var patt1 = new RegExp("[0-9]{10}");
		var result = patt1.test(newphone);
		if ( !result ) {
			sError += "This phone number is not valid.\n";
			phone.select();
		}
	}

	// Validate Email
	if ( email.value.length == 0 ) {
		sError += "Please enter your email address.\n";
	} else {

		var str = email.value;
		var patt1 = new RegExp("^[a-z][a-zA-Z0-9_.-]*@[a-zA-Z0-9_.-]+\.[a-z]{2,4}$");
		var result = patt1.test(str);
		if ( !result ) {
			sError += "The email is not valid.\n";
		}
	}

	// Validate Nationality
	if ( nationality.value.length == 0 ) {
		sError += "Please enter your Nationality.\n";
	}

	// Validate Course Duration
	if ( course_duration.value.length == 0 ) {
		sError += "Please enter the duration of your course.\n";
	}

	if ( sError.length == 0 ) {
		return true;
	}
	else {
		alert( sError );
		return false;
	}

}





// Slider
/*
function load_slider(cat) {

		this_slider=$$('.slider').find(function(n) {if(n.readAttribute('title')==cat) return true;});
		
		new Ajax.Updater(this_slider, 'ajax_slider.php', {
			parameters: { cat: cat }
		});


		// get slider
		new Ajax.Request('ajax_slider.php', {
			method: 'get',
			parameters: { cat: cat },
			onSuccess: function(transport) {
				this_slider.update(transport.responseText);
				// set description for the first image
				this_slider.next('.text').innerHTML=this_slider.down('img').readAttribute('alt');
			}
		});

}
*/

/* Google Map Functions */
function reset_box() {
	boxtext = '<img id="close" src="images/lightbox/mf_close.gif" onClick="MfLightbox.hideBox()" alt="Close" title="Close this window" />';
	boxtext += '<div id="boxContents"></div>';
	$('box').update(boxtext);
}

function gmap(id, map_container) {
  if (GBrowserIsCompatible()) {

	if(!map_container) map_container=$('box');
	var body = map_container;
	// var body = document.getElementById('map');
	var map = new GMap2(body);
	map.addControl(new GMapTypeControl());
	map.addControl(new GLargeMapControl());
	map.setCenter(new GLatLng(-37.74635,145.008261), 13);

	// Create our "tiny" marker icon
	var icon = new GIcon();
	icon.image = "http://www.google.com/mapfiles/ms/icons/red-pushpin.png";
	icon.shadow = "http://www.google.com/mapfiles/ms/icons/pushpin_shadow.png";
	icon.iconSize = new GSize(32, 32);
	icon.shadowSize = new GSize(59, 32);
	icon.iconAnchor = new GPoint(10, 32);
	icon.infoWindowAnchor = new GPoint(16, 1);


	// Creates a marker whose info window displays the given info
	function createMarker(point, info) {
	  // Create a lettered icon for this point using our icon class

	  var marker = new GMarker(point, icon);

	  GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(info);
	  });
	  return marker;
	}

	switch (id)
	{
	case 'ls8':
		// Le Student 8 Preston
		map.setCenter(new GLatLng(-37.74635,145.008261), 13);
		map.addOverlay(createMarker(new google.maps.LatLng(-37.74635,145.008261), "<div><B>Le Student 8</B><BR>215 Bell Street Preston VIC 3072<BR><B>Ph: +61 3 9485 0100</B><BR><BR><div style=\"clear:both\"></div></div>"));
	break;



	default:
		// Preston
		map.setCenter(new GLatLng(-37.74635,145.008261), 13);
		map.addOverlay(createMarker(new google.maps.LatLng(-37.74635,145.008261), "<div><B>Le Student 8</B><BR>215 Bell Street Preston VIC 3072<BR><B>Ph: +61 3 9485 0100</B><BR><BR><div style=\"clear:both\"></div></div>"));
	}


  }

	if($('box')) {
		var x='<img id="close" src="images/lightbox/mf_close.gif" onClick="MfLightbox.hideBox(); reset_box();" alt="Close" title="Close this window" style="position: absolute; right:0; top:0; z-index: 10000000;"/>';	
		$('box').insert({top: x});
	}
}

/* ------------------------------------------------------------------------------------------------ */



/* ================================================================================================ */
/* Scrolling News Ticker ========================================================================== */

// WebTicker by Mioplanet
// www.mioplanet.com

function load_ticker() {

	$('ticker').update('\
			<div style="padding: 0 900px;">\
				******\
				&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\
				&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\
\
				While our student accommodation is close to Melbourne tertiary institutions, it boasts many of the recreational facilities you\'d find at a university campus, as well as quality amenities, and quiet and privacy when you need it.\
			</div>\
	');

	// Insert Pause/Start button
	$('ticker').insert({'after':Builder.node('div', {id:'tickerpause'}, [Builder.node('img', {src:'images/pause.gif'})])});

	$('tickerpause').writeAttribute('style','float: right; color: #FFFFFF; padding: 9px 20px 0 0; font-weight: bold; cursor: pointer');

	// start-stop ticker
	$('tickerpause').observe('click', function(event) {
		if(TICKER_PAUSED) {
			TICKER_PAUSED=false;
			$('tickerpause').update('<img src="images/pause.gif">');
		} else {
			TICKER_PAUSED=true;
			$('tickerpause').update('<img src="images/play.gif">');
		}
	});



	ticker_start();
}

function ticker_start() {
	var tickerSupported = false;

	TICKER_PAUSED = false;

	TICKER_CONTENT = $('ticker').innerHTML;
	 
	TICKER_RIGHTTOLEFT = false;
	TICKER_SPEED = 2;
	TICKER_STYLE = "font-family:Verdana; font-size:11px; color:#FFFFFF";

	TICKER_WIDTH = $('ticker').style.width;

	// var img = "<img src='images/ticker_space.gif' width='"+TICKER_WIDTH+"' height='0'>";
	var img = "";

	// Firefox
	if (navigator.userAgent.indexOf("Firefox")!=-1 || navigator.userAgent.indexOf("Safari")!=-1) {
		$('ticker').innerHTML = "<TABLE  cellspacing='0' cellpadding='0' width='100%'><TR><TD nowrap='nowrap'>"+img+"<SPAN style='"+TICKER_STYLE+"' ID='TICKER_BODY' width='100%'>&nbsp;</SPAN>"+img+"</TD></TR></TABLE>";
		tickerSupported = true;
	}
	// IE
	if (navigator.userAgent.indexOf("MSIE")!=-1 || navigator.userAgent.indexOf("Opera")!=-1) {
		$('ticker').innerHTML = "<DIV nowrap='nowrap' style='width:100%;'>"+img+"<SPAN style='"+TICKER_STYLE+"' ID='TICKER_BODY' width='100%'></SPAN>"+img+"</DIV>";
		tickerSupported = true;
	}
	if(!tickerSupported) $('ticker').outerHTML = ""; else {
		$('ticker').scrollLeft = TICKER_RIGHTTOLEFT ? $('ticker').scrollWidth - $('ticker').offsetWidth : 0;
		document.getElementById("TICKER_BODY").innerHTML = TICKER_CONTENT;
		$('ticker').style.display="block";
		TICKER_tick();
	}
}

function TICKER_tick() {
	if(!TICKER_PAUSED) $('ticker').scrollLeft += TICKER_SPEED * (TICKER_RIGHTTOLEFT ? -1 : 1);
	if(TICKER_RIGHTTOLEFT && $('ticker').scrollLeft <= 0) $('ticker').scrollLeft = $('ticker').scrollWidth - $('ticker').offsetWidth;
	if(!TICKER_RIGHTTOLEFT && $('ticker').scrollLeft >= $('ticker').scrollWidth - $('ticker').offsetWidth) $('ticker').scrollLeft = 0;
	window.setTimeout("TICKER_tick()", 30);
}





/* ------------------------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------------------------- */



// Load Home Page Slider
function load_slider() {

	var sliders=new Hash();
	sliders.set('main', 3);
	sliders.set('main', 6);
	sliders.set('safety', 3);
	sliders.set('living-in-melbourne', 3);
	sliders.set('studying-in-australia', 3);
	sliders.set('rates-bookings', 3);
	sliders.set('rooms-facilities', 6);
	sliders.set('location', 5);
	sliders.set('transport', 3);
	sliders.set('universities', 3);

	// If we have content tabs - show first one, hide the rest
	if($$('.right .content div.tab').size()) {
		$$('.right .content div.tab').invoke('hide');
		$$('.right .content div.tab').first().show();
	}

	// Empty the slider contents
	$('slider').update('');

	// get slider type
	var slider_type='main';
	if($('slider').readAttribute('class')) slider_type=$('slider').readAttribute('class');

	// Build the slider structure
	$('slider').insert({top:
		Builder.node('div', { className:'big' }, [
			Builder.node('img', { id:'img_big', src:'images/slider/'+slider_type+'/1.jpg' }),
		])
	});


	$('slider').insert({bottom:
		Builder.node('div', { className:'controls' }, [
			Builder.node('span', { className:'active' }, ''),
		])
	});

	for(nn=sliders.get(slider_type)-1; nn>0; nn--) {
		$('slider').down('div.controls').insert({bottom:
				Builder.node('span', '')
		});
	}


	$('slider').down('div.controls').insert({bottom:
		//	Builder.node('div', {id:'prev'}, [Builder.node('img', { src:'images/prev_arrow.gif' })]),
			Builder.node('div', {id:'startstop'}, '')
		//	Builder.node('div', {id:'next'}, [Builder.node('img', { src:'images/next_arrow.gif' })]),
		
	});

	$('slider').insert({bottom:
		Builder.node('div', { className:'bottom_bar' }, '')
	});


	// Change slide
	slide_change=function(index) {

		// Big
		$('img_big').up('.big').hide().setStyle({top:'0',left:'0',height:'auto',width:'auto'});
		big_preloader = new Image();
		// once image is preloaded, apply effects
		big_preloader.onload=function(){
			$('img_big').src=$('img_big').src.replace(/(\/.)+?\.jpg/gi, "/"+(index+1)+".jpg");
			Effect.Appear($('img_big').up('.big'), { duration: 0.5 });
		}

		big_preloader.src = $('img_big').src.replace(/(\/.)+?\.jpg/gi, "/"+(index+1)+".jpg");

		// change active 
		$$('#slider .controls span').invoke('removeClassName', 'active');
		$$('#slider .controls span')[index].toggleClassName('active');

		// if we have hidden tabs - change tab
		if($$('.right .content div.tab').size()) {
			$$('.right .content div.tab').invoke('hide');
			$$('.right .content div.tab')[Math.floor(index/2)].show(); // change tab every 2 slides
		}
	}

	// Next Slide
	slide_next=function() {
		var controls=$$('#slider .controls span');
		var current_slide=controls.find(function(s) {
		  return s.hasClassName('active');
		});
		var new_index=controls.indexOf(current_slide)+1;
		if(new_index==controls.size()) new_index=0;
		slide_change(new_index);
	}

	// Start slideshow
	slider_start=function() {
		myslideshow= new PeriodicalExecuter(slide_next,10); // 10 second interval
		$('startstop').update('Stop')
	}

	// Stop slideshow
	slider_stop=function() {
		myslideshow.stop();
		$('startstop').update('Play');
	}

	// Set controls
	$$('#slider .controls span').each(function(n, index) {
		n.observe('click', function(event) {
			slide_change(index);
		});
	});

	// start-stop button
	$('startstop').observe('click', function(event) {
		if(myslideshow) {
			slider_stop();
			myslideshow=null;
		} else {
			slide_next();
			slider_start();
		}
	});
}



Event.observe(window, 'load', function() {

		// initialise mf_lightbox
		try {
			MfLightbox.init();
		} catch (e) {
			//Event.stop(e);
			// zzz
		}

		// Slider
		if($('slider')) {
			load_slider();

			slider_start();
		}

		// Scrolling Ticker
		if($('ticker')) {
			load_ticker();
		}

		// News
		if($('news')) {
			new Ajax.Request('ajax_news.php', {
				method: 'get',
				parameters: {
					preview:true
				},
				onSuccess: function(transport) {
					$('news').update(transport.responseText);
				}
			});
		}

		// Date Picker 
		if($('date_arrive')) {
			var date_arrive = new DatePicker({
				relative:'date_arrive',
				keepFieldEmpty:true,
				dateFormat:[ ["dd","mm","yyyy"], "/" ],
				dateFilter:DatePickerUtils.noDatesBefore(0)
			});
		}
		if($('date_depart')) {
			var date_depart = new DatePicker({
				relative:'date_depart',
				keepFieldEmpty:true,
				dateFormat:[ ["dd","mm","yyyy"], "/" ],
				dateFilter:DatePickerUtils.noDatesBefore(0)
			});
		}

		// Google Map
		if($('map')) {
			gmap('ls8',$('map'));

		}

});

