site={
	init: function () {
		// setup rotating background on homepage
		if ($('background'))	new Carousel($$('#background img'));
		// setup filtering on category pages
		if ($$('.filteredCategory').length > 0)	new Filtration($$('.filteredCategory')[0]);
		// setup collapsing footer
		if ($('collapsingFooter'))	new CollapsedFooter($('collapsingFooter'));
		// setup the product gallery
		if ($('main_gallery'))	new ProductGallery('main_gallery');
		// setup the product info tabs
		if ($('prodInfoDeliveryReturns'))	new Tabs('prodInfoDeliveryReturns');
		//
		if ($$('.mc_colourway_left_col').length > 0)	new fabric_wallpaper_zoom($$('.mc_colourway_left_col').getChildren('a')[0][0], {containerWidth:365, containerHeight:430});
		if ($$('.mc_wallpaper_left_col').length > 0)	new fabric_wallpaper_zoom($$('.mc_wallpaper_left_col').getChildren('a')[0][0], {containerWidth:$$('.mc_wallpaper_right_col')[0].getSize().size.x, containerHeight:430});
	}
}
window.addEvent('domready', site.init);

var fabric_wallpaper_zoom = new Class({
	initialize: function (el, options) {
		this.setOptions({
			loader:'#fff url(../_images/mc_images/loader.gif)'
		}, options);
		this.element = $(el);
		this.src = this.element.getProperty('rel');
		if (this.src != '') this.setup();
	},
	setup: function () {
			this.container = new Element('div').injectInside($('colourway_print').setStyle('position', 'relative')).setStyles({
			display:'none',
			position:'absolute',
			top:0, right:0,
			width: this.options.containerWidth, height:this.options.containerHeight,
			border:'1px solid #ccc',
			background:this.options.loader
		});		
		var loader = new Image();
			loader.src = this.src;
			
		this.element.addEvents({
			mouseenter:this.zoom.bindAsEventListener(this),
			mouseleave:this.close.bindAsEventListener(this),
			mousemove:this.move.bindAsEventListener(this)
		});
	},
	zoom:function (e) {
		this.container.setStyles({display:''});
		var image = new Image();
			image.src = this.src;
			if ( (!image.complete) || (typeof image.naturalWidth != "undefined" && image.naturalWidth == 0) ) {
					$(image).addEvent('load', function () {
						this.container.setStyles({backgroundImage:'url(' + this.src + ')'});
//						this.zoomArea.setStyle('display','block');
						this.move(e);
					}.bind(this));
			} else {
				this.container.setStyles({backgroundImage:'url(' + this.src + ')'});
				this.move(e);
			}
	},
	move:function (e) {
		var elSize = this.element.getFirst().getSize().size;
		var mousePos = this.getMousePosition(e);
		var mousePosProportional = {x:mousePos.x/elSize.x * 100, y:mousePos.y/elSize.y * 100};
		
//		this.zoomArea.setStyles({top:mousePos.y - 50, left:mousePos.x - 50});
		this.container.setStyle('backgroundPosition', mousePosProportional.x + '% ' + mousePosProportional.y + '%');
	},
	close:function() {
		this.container.setStyles({background:this.options.loader, display:'none'});
//		this.zoomArea.setStyle('display', 'none');
	},
	getMousePosition:function(e) {
		var scrollX = document.body.scrollLeft || document.documentElement.scrollLeft;
        var scrollY = document.body.scrollTop || document.documentElement.scrollTop;

        if (e.currentTarget) {
            var pos = e.currentTarget.getFirst().getPosition();
            return {
                x : e.clientX - pos.x + scrollX,
                y : e.clientY - pos.y + scrollY
            }
        }
        return {
            x : e.offsetX,
            y : e.offsetY
        }

	}
});
	fabric_wallpaper_zoom.implement(new Options);
	
var ProductGallery = new Class({
	loader:'#fff url(../_images/mc_images/loader.gif)',
	initialize: function(el) {
		this.element = $(el);
		this.images = $$('#main_gallery li a img');
		this.preload();
		this.container = new Element('div').injectInside($$('.mc_purchasable_product_main')[0].setStyle('position', 'relative')).setStyles({
			display:'none',
			position:'absolute',
			top:0, right:0,
			width: 460, height:340,
			border:'1px solid #ccc',
			background:this.loader
		});
		this.zoomArea = new Element('div').addClass('zoomarea').injectInside(this.element.getParent());
		this.images.addEvents({
			mouseenter:this.zoom.bindAsEventListener(this),
			mouseleave:this.close.bindAsEventListener(this),
			mousemove:this.move.bindAsEventListener(this)
		});
		
		this.thumbs = $('thumb_gallery').addEvent('click', this.swap.bindAsEventListener(this));
		this.thumbs.setStyle('width', this.thumbs.getChildren().length*92)
		var wrapper = new Element('div', {id:'thumb_gallery_wrapper'}).injectBefore(this.thumbs)
			.adopt(this.thumbs);
		if (this.thumbs.getChildren().length > 3) {
			wrapper
				.adopt(new Element('img', {src:'../_images/mc_images/rightArrow.png'}).addClass('forward').addEvents({
					mouseover: function () {this.tickerMotion = -2;}.bindAsEventListener(this),
					mouseout: function () {this.tickerMotion = false;}.bindAsEventListener(this)
				}))
				.adopt(new Element('img', {src:'../_images/mc_images/leftArrow.png'}).addClass('backward hide').addEvents({
					mouseover: function () {this.tickerMotion = 2;}.bindAsEventListener(this),
					mouseout: function () {this.tickerMotion = false;}.bindAsEventListener(this)
				}));
			this.ticker.periodical(12, this);
		}
	},
	preload: function () {
		var loader = new Image();
			loader.src = this.loader;
		this.images.each(function (image) {loader.src = image.getProperty('rel');});
	},
	zoom:function (e) {
		var src = $(new Event(e).target).getParent().getProperty('rel');
		if (src != '') {
			this.container.setStyles({display:''});
			var image = new Image();
				image.src = src;
			if ( (!image.complete) || (typeof image.naturalWidth != "undefined" && image.naturalWidth == 0) ) {
					$(image).addEvent('load', function () {
						this.container.setStyles({backgroundImage:'url(' + src + ')'});
//						this.zoomArea.setStyle('display','block');
						this.move(e);
					}.bind(this));
			} else {
				this.container.setStyles({backgroundImage:'url(' + src + ')'});
				this.move(e);
			}
		}
	},
	move:function (e) {
		var elSize = $('main_gallery').getSize().size;
		var mousePos = this.getMousePosition(e);
		var mousePosProportional = {x:mousePos.x/elSize.x * 100, y:mousePos.y/elSize.y * 100};
		
//		this.zoomArea.setStyles({top:mousePos.y - 50, left:mousePos.x - 50});
		if (mousePos.x > 0 && mousePos.y > 0)	this.container.setStyle('backgroundPosition', mousePosProportional.x + '% ' + mousePosProportional.y + '%');
	},
	close:function() {
		this.container.setStyles({background:this.loader, display:'none'});
//		this.zoomArea.setStyle('display', 'none');
	},
	swap:function(e) {
		var target = $(new Event(e).stop().target);
		if (target.getTag() == 'img') {
			$$('#main_gallery li').addClass('hide');
			li = target.getParent().getParent().addClass('thumbToActivate');
			$$('#thumb_gallery li').each(function (li, index) {
				if (li.hasClass('thumbToActivate'))	$$('#main_gallery li')[index].removeClass('hide');
			li.removeClass('thumbToActivate');
				});
		}
	},
	getMousePosition:function(e) {
		var scrollX = document.body.scrollLeft || document.documentElement.scrollLeft;
        var scrollY = document.body.scrollTop || document.documentElement.scrollTop;
		
        if (e.target) {
            var pos = $(e.target).getPosition();
            return {
                x : e.clientX - pos.x + scrollX,
                y : e.clientY - pos.y + scrollY
            }
        }
        return {
            x : e.offsetX,
            y : e.offsetY
        }

	},
	ticker: function () {
		if (this.tickerMotion) {
			var width = parseInt(this.thumbs.getStyle('width'))
			var pos = parseInt(this.thumbs.getStyle('left'));
			
			if (this.tickerMotion < 0 && (pos*-1 > width-360)) 	{$$('.forward').addClass('hide');}
			else if (this.tickerMotion > 0 && pos >=0)			{$$('.backward').addClass('hide');}
			else {
				this.thumbs.setStyle('left', pos + this.tickerMotion);
				$$('.backward').removeClass('hide');
				$$('.forward').removeClass('hide');
			}
		}
	}
});

var Tabs = new Class({
	initialize:function(el) {
		this.element = $(el);
		this.tabs = this.element.getChildren().map(function (li) {return li.getFirst();});
		this.panels = this.element.getChildren().map(function (li) {return li.getLast();});
		
		this.element.addEvent('click', function (e) {
			var target = $(new Event(e).target);
			if (target.getTag() == 'span') {
				this.tabs.each(function (tab) {tab.removeClass('on');});
				this.panels.each(function (panel) {panel.addClass('hide');});
				var tab = target.addClass('on');
				var panel = target.getNext().removeClass('hide');
			}
		}.bindAsEventListener(this));
		
		var maxHeight = 0;
		this.panels.each(function (panel) {
			var height = panel.getSize().size.y;
			if (height > maxHeight)	maxHeight = height;
		});
		this.element.setStyle('height', maxHeight + this.tabs[0].getSize().size.y);
		
		this.tabs[0].addClass('on');
		this.panels.each(function (panel) {panel.addClass('hide');})
		this.panels[0].removeClass('hide');
	}
});

var Filtration = new Class({
	initialize: function (container) {
		this.id = container.getProperty('id').replace(/\D/g, '');
		this.container = container.setStyle('background','#fff').setHTML('<p>refine selection:</p>');
		this.gallery = $$('.mc_pod_grid')[0];
		this.parameters = {
			ParentID:this.id,
			shopID:this.container.getProperty('title'),
			Filters:[],
			Sort:''
		};
		this.activate();
		this.initHistory();
	},
	activate: function () {
		this.container.addEvent('click', function (e) {
			var target = $(new Event(e).stop().target);
			if (target.getTag() == 'span') 	this.titleClicked(target);
			
			if (target.getTag() == 'img')	target = target.getParent();
			if (target.getTag() == 'a')		this.menuOptionClicked(target);
		}.bind(this));
	},
	titleClicked: function (span) {
		// if active, clear menu and remove entry from parameters, else toggle menu
		if (span.hasClass('active')) {
			span.removeClass('active').empty().setText(span.getNext().getProperty('id'));
			this.parameters.Filters.remove(span.getProperty('rel'));
			HistoryManager2.setValues('Filters', this.parameters.Filters);
			this.populate();
		} else {
			// toggle menu
			var list = span.getNext();
			if (list.hasClass('hidden')) {
				$$('.dropdown').addClass('hidden');
				$$('.open').removeClass('open');
				var position = span.getPositionedOffset();
				var height = span.getSize().size.y;
				list.setStyles({top:position.y + height - 1, left:position.x});
				list.toggleClass('hidden');
				span.toggleClass('open');
			} else {
				list.toggleClass('hidden');
				span.toggleClass('open');
			}
		}
	},
	menuOptionClicked: function (anchor) {
		var list = anchor.getParent().getParent();
		var title = list.getPrevious();
		var name = list.getProperty('id');
		
		// update filters
		var value = anchor.getParent().getProperty('id');
		if (name == 'sort') {
			this.parameters.Sort = value;
			HistoryManager2.setValue('Sort', 0, value);
		} else {
			this.parameters.Filters.include(value.replace(/\D/g, ''));
			HistoryManager2.setValues('Filters', this.parameters.Filters);
		}
	
		this.populate();
	},
	populate: function () {
		new Ajax('../_colony/meta-directory/classification/search.asp', {
			method:'post',
			data: this.parameters,
			onComplete: function (json) {			
				var json = Json.evaluate(json);
				
				// update gallery
				this.gallery.setHTML(unescape(json.gallery));
				
				// update dropdowns
				var dropdowns = new Hash(json.dropdowns);
				this.container.setHTML('<p>refine selection:</p>');
				dropdowns.each(function (html, name) {
					html = unescape(html);
					
					var title = new Element('span').setText(name).injectInside(this.container);
					var list = new Element('ul', {id:name}).setHTML(html).addClass('hidden dropdown').injectInside(this.container);
					
					if (name == 'sort') 			this.container.adopt(new Element('div').setStyle('float', 'right').adopt(new Element('p').setText('sort by:')).adopt([title, list]));
					if (html.contains('<img'))		list.addClass('imgDropdown');
					if (html.contains('filter_on') || html.contains('sort_on')) {
						var li = $$('#' + name + ' .filter_on, #' + name + ' .sort_on')[0];
						title.empty().setProperty('rel', li.id);
						if (name != 'sort')	title.addClass('active')
						if (img = li.getFirst().getFirst()) {
							title.adopt(img.clone());
						} else {
							title.setText(li.getText());
						}
					}
				}.bind(this));
			}.bind(this)
		}).request();
	},
	initHistory: function () {
		HistoryManager2.initialize();

		HistoryManager2.register(
			'Filters',
			[],
			function (values) {
				if (values)	this.parameters.Filters = values;
				this.populate();
			}.bind(this),
			function (values) {
				return 'Filters(' + values + ')';
			},
			/\d+(?!-|\|)/g
		);
		
		HistoryManager2.register(
			'Sort',
			[0],
			function (values) {
				if (values)	this.parameters.Sort = values;
				this.populate();
			}.bind(this),
			function (values) {
				return 'Sort|' + values + '|';
			},
			/\w-\w/
		);

		HistoryManager2.start();
	}
});

var FiltrationMultiSelect = new Class({
	initialize: function (container) {
		this.id = container.getProperty('id').replace(/\D/g, '');
		this.container = container.setStyle('background','#fff').setHTML('<p>refine selection:</p>');
		this.gallery = $$('.mc_pod_grid')[0];
		this.parameters = {
			ParentID:this.id,
			Filters:[],
			Sort:''
		};
		this.activate();
		this.initHistory();
	},
	activate: function () {
		this.container.addEvent('click', function (e) {
			var target = $(new Event(e).stop().target);
			if (target.getTag() == 'img')	target = target.getParent();
			if (target.getTag() != 'a')	return;
			target.getParent().toggleClass('filter_on');
			$$('.dropdown').addClass('hidden');
			$$('.open').removeClass('open');
			this.setParameters();
			this.populate();
		}.bind(this));
	},
	setParameters: function () {
		this.parameters.Filters = [];
		$$('.filter_on').each(function (el) {
			if (el.getParent().id == "sort") {
				var value = el.getProperty('id');
				this.parameters.Sort = value;
				HistoryManager2.setValue('Sort', 0, value);
			} else {
				var value = el.getProperty('id').replace(/\D/g, '');
				this.parameters.Filters.include(value);
			}
		}.bind(this));
		HistoryManager2.setValues('Filters', this.parameters.Filters);
	},
	populate: function () {
		new Ajax('../_colony/meta-directory/classification/search.asp', {
			method:'post',
			data: this.parameters,
			onComplete: function (json) {				
				var json = Json.evaluate(json);
				var dropdowns = new Hash(json.dropdowns);
				this.container.setHTML('<p>refine selection:</p>');
				dropdowns.each(function (html, name) {
					html = unescape(html);
					
					var list = new Element('ul', {id:name}).setHTML(html).addClass('hidden dropdown').injectInside(this.container);
					var title = new Element('span').setText(name).injectBefore(list).addEvent('click', function () {
						if (list.hasClass('hidden')) {
							$$('.dropdown').addClass('hidden');
							$$('.open').removeClass('open');
							var position = this.getPositionedOffset();
							var height = this.getSize().size.y;
							list.setStyles({top:position.y + height - 1, left:position.x});
							list.toggleClass('hidden');
							title.toggleClass('open');
						} else {
							list.toggleClass('hidden');
							title.toggleClass('open');
						}
					});
					if (name == 'sort') this.container.adopt(new Element('div').setStyle('float', 'right').adopt(new Element('p').setText('sort by:')).adopt([title, list]));
					
					if (html.contains('<img')) {
						$(name).addClass('imgDropdown');
					} else {
						$(name).removeClass('imgDropdown');
					}
				}.bind(this));
				this.gallery.setHTML(unescape(json.gallery));
			}.bind(this)
		}).request();
	},
	initHistory:function () {
		HistoryManager2.initialize();

		HistoryManager2.register(
			'Filters',
			[],
			function (values) {
				this.parameters.Filters = values;
				$$('.filter_on').removeClass('filter_on');
				values.each(function (el) {
					if ($(el))	$(el).addClass('filter_on');
				});
				this.populate();
			}.bind(this),
			function (values) {
				return 'Filters(' + values + ')';
			},
			/\d+(?!-|\|)/g
		);
		
		HistoryManager2.register(
			'Sort',
			[0],
			function (values) {
				if (values)	this.parameters.Sort = values;
				this.populate();
			}.bind(this),
			function (values) {
				return 'Sort|' + values + '|';
			},
			/\w-\w/
		);

		HistoryManager2.start();
	}
});

var Carousel = new Class({
	initialize: function (screens) {
		this.screens = screens.setStyle('opacity', 0);
		var lastActiveScreenPosition = parseInt(Cookie.get('lastActiveScreenPosition'));
		if (lastActiveScreenPosition >= this.screens.length-1) lastActiveScreenPosition = 0;
		this.activeScreen = screens[lastActiveScreenPosition+1 || 0].setStyle('opacity', 1);
		this.start();
	},
	start: function () {
		this.timer = (function () {
			var fade = new Fx.Style(this.activeScreen, 'opacity', {duration:1000});
				fade.start(1,0);
			var pos = this.screens.indexOf(this.activeScreen);
				pos = (pos == this.screens.length-1) ? 0 : pos + 1;
			this.activeScreen = this.screens[pos];
			Cookie.set('lastActiveScreenPosition', pos);
			var fade2 = new Fx.Style(this.activeScreen, 'opacity', {duration:1000});
				fade2.start(0,1);
		}.bind(this)).periodical(7000);
	}
});

var CollapsedFooter = new Class({
	initialize: function (el) {
		this.element = $(el);
		this.collapsedHeight = 25;
		this.height = this.element.getSize().size.y;
		this.width = 974;
		var scrollHeight = window.getScrollHeight();
		var windowWidth = window.getWidth();
		this.element.setStyles({
			height:this.collapsedHeight,
			overflow:'hidden',
			position:'absolute',
			top:scrollHeight - this.collapsedHeight,
			left:0
//			left:windowWidth/2 - this.width/2
		});
		this.isOpen = false;
		if ($('footer_banner'))	$('footer_banner').setStyle('bottom', 50);
		this.fx = new Fx.Styles(this.element);
//		this.element.addEvents({
//			mouseenter:this.open.bindAsEventListener(this),
//			mouseleave:this.close.bindAsEventListener(this)
//		});
		this.element.addEvent('click', this.toggle.bindAsEventListener(this));
		window.addEvents({
			scroll:this.setPosition.bindAsEventListener(this),
			resize:this.setPosition.bindAsEventListener(this)
		});
	},
	setPosition: function () {
		var scrollHeight = window.getScrollHeight();
		var windowHeight = window.getHeight();
		var targetHeight = scrollHeight <= windowHeight ? scrollHeight : windowHeight;
		this.fx.set({
			height: this.isOpen ? this.height : this.collapsedHeight,
			top:targetHeight-this.collapsedHeight
		});
        
//		var windowWidth = window.getWidth();
//		this.element.setStyle('left', windowWidth/2 - this.width/2);
	},
	open: function () {
		var scrollHeight = window.getScrollHeight();
		this.fx.start({
			height:this.height,
			top:scrollHeight-this.height
		});
		this.isOpen = true;
		$$('.mc_home_footer_title_item').each(function (div) {div.addClass('open');});
	},
	close: function () {
		var scrollHeight = window.getScrollHeight();
		this.fx.start({
			height:this.collapsedHeight,
			top:scrollHeight-this.collapsedHeight
		});
		this.isOpen = false;
		$$('.mc_home_footer_title_item').each(function (div) {div.removeClass('open');});
	},
	toggle: function (e) {
		if ($(new Event(e).target).getTag() == 'input')	return;
		this[this.isOpen ? 'close' : 'open']();
	}
});

if (window.ie6) {
	window.addEvent('domready', function(){
		$extend(kina,{
			bgs: $$('#bg img'),
			timer:setInterval(kina.fix, 200)
		});
	});

	kina={
		doc:{x:0,y:0},
		fix:function(){
			kina.bgs.each(function (kinaBG) {
				if(kinaBG.complete && ($(document.body).offsetWidth != kina.doc.x || $(document.body).offsetHeight != kina.doc.y || kina.fix.src != kinaBG.src)){
					var bg=$(kinaBG).getSize();
					kina.doc={x:$(document.body).offsetWidth,y:$(document.body).offsetHeight};
					kina.fix.src==kinaBG.src||$extend(kina.fix,{p:bg.size.x/bg.size.y,src:kinaBG.src});
					$(kinaBG).setStyles({
						width:(bg.size.y=kina.doc.x>(bg.size.x=Math.round(kina.doc.y*kina.fix.p)))?kina.doc.x:bg.size.x,
						height:bg.size.y?Math.round(kina.doc.x/kina.fix.p):kina.doc.y
					})
				}
			});
		}
	}
}



Element.extend({
	getPositionedOffset: function () {
		var left = 0, top = 0, element = this;
		do {
			left += element.offsetLeft || 0;
			top += element.offsetTop  || 0;

			element = $(element.offsetParent);
			if (element) {
				if (element.tagName == 'BODY') break;
				var p = element.getStyle('position');
				if (p == 'relative' || p == 'absolute') break;
			}
		} while (element);
		return {'x':left, 'y':top};
	}
});
