/**
 * Slideshow
 * @version 1.0
 * @author John Noel <john.noel@rckt.co.uk>
 * @copyright Rckt http://www.rckt.co.uk/
 * @package Hot Box Stoves
 * @todo Previous / Next buttons
 */
var Slideshow = Class.create({
	elem: null,
	timer: null,
	transitioning: false,
	
	options: {
		transitionSpeed: 0.8,	// effect speed (seconds)
		itemSelector: ".slides_container > li",	// how to get slides
		play: 8,	// auto-advance and how long (seconds)
		createPagination: true	// create pagination list
	},
	
	initialize: function(elem, options) {
		this.elem = $(elem);
		if(!this.elem)
		{
				throw "Unable to bind to element";
		}
		
		this.options = Object.extend(this.options, options);
		
		if(this.options.createPagination)
		{
			this._createPagination();
		}
		
		if(this.options.play)
		{
			this.timer = setInterval(function() { this.transition(-1); }.bind(this), this.options.play * 1000);
		}
		
		this.elem.relativize().select(this.options.itemSelector).
			invoke("absolutize").
			invoke("setStyle", { left: 0, top: 0 }).
			invoke("hide").
			first().show();
	},
	
	// create pagination
	_createPagination: function() {
		var elems = this.elem.select(this.options.itemSelector);
		var paginationElem = $(document.createElement("ul")).addClassName("pagination");
		
		for(i = 1; i <= elems.size(); i++)
		{
			var liElem = $(document.createElement("li")).update('<a href="#slide'+i+'">'+i+'</a>');
			liElem.down("a").observe("click", function(evt) {
				evt.stop();
				if(!this.transitioning)
				{
					var liElem = evt.findElement("li");
					liElem.addClassName("current").siblings().invoke("removeClassName", "current");
					
					var target = liElem.previousSiblings().size();
					this.transition(target);
				}
			}.bind(this));
			
			paginationElem.insert(liElem);
		}
		
		paginationElem.down("li").addClassName("current");
		this.elem.insert(paginationElem);
	},
	
	// change the slide
	transition: function(target) {
		if(!this.transitioning)
		{
			var elems = this.elem.select(this.options.itemSelector);
			
			var toHide = elems.find(function(s) { return s.visible(); });
			var toShow = (target >= 0) ? elems[target] : toHide.next();
			toShow = (!toShow) ? elems.first() : toShow;
			
			var opts = {
				duration: this.options.transitionSpeed,
				beforeStart: function() { this.transitioning = true; }.bind(this),
				afterFinish: function() { this.transitioning = false; }.bind(this)
			};
			
			toHide.fade(opts);
			toShow.appear(opts);
			
			// TODO change this to just check for pagination
			if(this.options.createPagination)
			{
				var pages = this.elem.select(".pagination li");
				pages.invoke("removeClassName", "current");
				pages[toShow.previousSiblings().size()].addClassName("current");
			}
			
			if(this.options.play)
			{
				clearInterval(this.timer);
				this.timer = setInterval(function() { this.transition(-1); }.bind(this), this.options.play * 1000);
			}
		}
	}
});

/**
 * Scroller
 * @version 1.0
 * @author John Noel <john.noel@rckt.co.uk>
 * @copyright Rckt http://www.rckt.co.uk/
 * @package Hot Box Stoves
 * @todo Create rather than just use previous/next buttons
 */
var Scroller = Class.create({
	elem: null,
	transitioning: false,
	
	options: {
		transitionSpeed: 0.5,	// effect speed (seconds)
		scroll: 1,	// how many slides to scroll per click
		scrollOver: 3,  // how many items are required to initialise scrolling
		itemSelector: ".slides_container > li"	// how to get slides
	},
														
	initialize: function(elem, options) {
		this.elem = $(elem);
		if(!this.elem)
		{
			throw "Unable to bind to element";
		}
		
		this.options = Object.extend(this.options, options);
		if(this.elem.select(this.options.itemSelector).size() >= this.options.scrollOver)
		{
			this.elem.select(".next").invoke("observe", "click", this.advance.bindAsEventListener(this));
			this.elem.select(".prev").invoke("observe", "click", this.retreat.bindAsEventListener(this));
		}
		else
		{
			this.elem.select(".next, .prev").invoke("hide");
		}
		
		// deal with absolute slide linking from the document hash
		if(document.location.hash != '')
		{
			var h = document.location.hash.substr(1);
			if(e = $(h))
			{
				e.previousSiblings().reverse().each(function(s) {
					e.up().insert(s.remove());
				});
			}
		}
	},
	
	advance: function(evt) {
		if(evt)
		{
			evt.stop();
		}
		
		if(!this.transitioning)
		{
			this.elem.select(this.options.itemSelector).slice(0, this.options.scroll).each(function(e) {
				new Effect.Tween(e, 0, (0 - e.measure("margin-box-width")), {
					duration: this.options.transitionSpeed,
					queue: { position: "end", scope: "scroller" },
					beforeStart: function(elem) {
						this.transitioning = true;
						// clone to allow for some situations of infinite scrolling
						var newElem = elem.cloneNode(true);
						// insert the clone as the last slide
						elem.up().insert($(newElem).setStyle({marginLeft: 0}));
					}.bind(this, e),
					afterFinish: function(elem) {
						this.transitioning = false;
						// remove the original, leave the clone
						elem.remove();
					}.bind(this, e)
				}, function(p) {
					this.setStyle({marginLeft: p+"px"});
				});
			}.bind(this));
		}
	},
	
	retreat: function(evt) {
		if(evt)
		{
			evt.stop();
		}
		
		if(!this.transitioning)
		{
			this.elem.select(this.options.itemSelector).slice(0 - this.options.scroll).reverse().each(function(e) {
				var ml = (0 - e.measure("margin-box-width"));
				
				var newElem = e.cloneNode(true);
				e.up().insert({ top: e.setStyle({ marginLeft: ml+"px" }) });
				e.up().insert(newElem);
				
				new Effect.Tween(e, ml, 0, {
					duration: this.options.transitionSpeed,
					queue: { position: "end", scope: "scroller" },
					beforeStart: function() { this.transitioning = true; }.bind(this),
					afterFinish: function(elem) {
						this.transitioning = false;
						elem.remove();
					}.bind(this, newElem)
				}, function(p) {
					this.setStyle({marginLeft: p+"px"});
				});
			}.bind(this));
		}
	}
});

if(elem = $("slideshow")) {
	new Slideshow(elem);
}

if(elem = $("scroller")) {
	new Scroller(elem);
}

if(elem = $("installationSteps")) {
	new Scroller(elem);
}

if(elem = $$("#stovesAndAccessories, #product").first())
{
	var selected = elem.select("#sidebarLeft li.on");
	var all = elem.select("#sidebarLeft > ul > li > ul");
	
	// this is to improve the slide functions
	// script.aculo.us really needs to start using the .measure() functions
	all.each(function(s) {
		s.up().insert(
			$(document.createElement("div")).
				setStyle({height: s.measure("border-box-height")+"px"}).
				hide().
				insert(s.remove())
		);
	});
	
	if(selected.size() > 0)
	{
		selected.first().addClassName("open").down("div").show();
	}
	else
	{
		all.first().up("div").show().up("li").addClassName("open");
	}
	
	elem.select("#sidebarLeft > ul > li > a").invoke("observe", "click", function(evt) {
		evt.stop();
		var toToggle = evt.findElement("li").down("div");
		
		if(toToggle.visible())
		{
			evt.findElement("li").removeClassName("open");
			Effect.SlideUp(toToggle, { duration: 0.5 });
		}
		else
		{
			evt.findElement("li").addClassName("open");
			Effect.SlideDown(toToggle, { duration: 0.5 });
		}
	});
}

if(elem = $("product"))
{
	elem.select(".thumbnails li a").invoke("observe", "click", function(evt) {
		evt.stop();
		
		var liElem = evt.findElement("li");
		liElem.addClassName("on").siblings().invoke("removeClassName", "on");
		
		var index = liElem.previousSiblings().size();
		var largeElems = elem.select(".large li");
		
		var toHide = largeElems.find(function(n) { return n.visible(); });
		var toShow = largeElems[index];
		
		Effect.Fade(toHide, { duration: 0.5 });
		Effect.Appear(toShow, { duration: 0.5 });
	});
	
	// fancyzoom
	FancyZoomBox.directory = "/assets/templates/hotboxv1/images/fancyzoom";
	
	elem.select(".large li a").each(function(s) {
		var divElem = $(document.createElement("div")).hide();
		divElem.insert('<img src="'+s.readAttribute("href")+'" alt="" />');
		var ayeDee = divElem.identify();
		
		s.up().insert(divElem);
		s.writeAttribute("href", "#"+ayeDee);
		new FancyZoom(s);
	});
}


if($("googleMap"))
{
	var latlng = new google.maps.LatLng(54.02854, -1.09617);
	var mapOpts = {
		zoom: 11,
		center: latlng,
		mapTypeControl: false,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	
	// styles
	var styles = [ { featureType: "all", elementType: "all", stylers: [ { lightness: 25 }, { saturation: -100 } ] } ];
	var mapType = new google.maps.StyledMapType(styles, { name: "hotboxstoves" });
	
	var map = new google.maps.Map(document.getElementById("googleMap"), mapOpts);
	map.mapTypes.set("hotboxstoves", mapType);
	map.setMapTypeId("hotboxstoves");
	
	var marker = new google.maps.Marker({
		position: latlng, 
		map: map, 
		title: "Hotbox Stoves",
		icon: "http://www.hotboxstoves.co.uk/assets/templates/hotboxv1/images/icon-mapmarker.png"
	});  
}

// use window.load rather than dom loaded to make sure images are in
Event.observe(window, "load", function() {
	// footer on every page
	$$("footer ul").each(function(s) {
		var visWidth = s.measure("border-box-width");
		var actualWidth = 0;
		s.immediateDescendants()
			.each(function(n) { actualWidth += n.measure("border-box-width"); });
		actualWidth += (s.immediateDescendants().length * 3); // counters inline-block's innante margin
		var diff = actualWidth - visWidth;
		
		var advance = function(diff) {
			new Effect.Tween(this, 0, (0 - diff), {
				duration: 30,
				transition: Effect.Transitions.linear,
				afterFinish: function() { setTimeout(retreat, 5000); }
			}, function(p) {
				this.setStyle({marginLeft: p+"px"});
			});
		}.bind(s.down(), diff);
		
		var retreat = function(diff) {
			new Effect.Tween(this, (0 - diff), 0, {
				duration: 30,
				transition: Effect.Transitions.linear,
				afterFinish: function() { setTimeout(advance, 5000); }
			}, function(p) {
				this.setStyle({marginLeft: p+"px"});
			});
		}.bind(s.down(), diff);
		
		setTimeout(advance, 5000);
	});
});
/*
transitions.js

Based on Easing Equations v2.0
(c) 2003 Robert Penner, all rights reserved.
This work is subject to the terms in http://www.robertpenner.com/easing_terms_of_use.html

Adapted for Scriptaculous by Ken Snyder (kendsnyder ~at~ gmail ~dot~ com) June 2006
*/

/*
Gradual Transitions
*/
// EaseFromTo (adapted from "Quart.EaseInOut")
Effect.Transitions.EaseFromTo = function(pos) {
		if ((pos/=0.5) < 1) return 0.5*Math.pow(pos,4);
		return -0.5 * ((pos-=2)*Math.pow(pos,3) - 2);
};
// EaseFrom (adapted from "Quart.EaseIn")
Effect.Transitions.EaseFrom = function(pos) {
		return Math.pow(pos,4);
};
// EaseTo (adapted from "Quart.EaseOut")
Effect.Transitions.EaseTo = function(pos) {
		return Math.pow(pos,0.25);
};
