/*
---
description: Overlay

authors:
  - David Walsh (http://davidwalsh.name)

license:
  - MIT-style license

requires:
  core/1.2.1: '*'

provides:
  - Overlay
...
*/

var Overlay = new Class({
	
	Implements: [Options, Events],
	
	options: {
		id: 'overlay',
		color: '#000',
		duration: 500,
		opacity: 0.65,
		zIndex: 999/*,
		onClick: $empty,
		onClose: $empty,
		onHide: $empty,
		onOpen: $empty,
		onShow: $empty
		*/
	},
	
	initialize: function(container, options){
		this.setOptions(options);
		this.container = document.id(container);
		if (Browser.Engine.trident && Browser.Engine.version <= 6) this.ie6 = true;
		
		this.bound = {
			'window': {
				resize: this.resize.bind(this),
				scroll: this.scroll.bind(this)
			},			
			overlayClick: this.overlayClick.bind(this),
			tweenStart: this.tweenStart.bind(this),
			tweenComplete: this.tweenComplete.bind(this)	  
		};
		
		this.build().attach();
	},
	
	build: function(){
	  this.overlay = new Element('div', {
			id: this.options.id,
			opacity: 0,
			styles: {
				position: (this.ie6) ? 'absolute' : 'fixed',
				background: this.options.color,
				left: 0,
				top: 0,
				'z-index': this.options.zIndex
			}
		}).inject(this.container);
		this.tween = new Fx.Tween(this.overlay, { 
			duration: this.options.duration,
			link: 'cancel',
			property: 'opacity'
		});
	 return this;
	}.protect(),
	
	attach: function(){
		window.addEvents(this.bound.window);
		this.overlay.addEvent('click', this.bound.overlayClick);
		this.tween.addEvents({
			onStart: this.bound.tweenStart,
			onComplete: this.bound.tweenComplete
		});
	 return this;
	},
	
	detach: function(){
		var args = Array.prototype.slice.call(arguments);
		args.each(function(item){
			if(item == 'window') window.removeEvents(this.bound.window);
			if(item == 'overlay') this.overlay.removeEvent('click', this.bound.overlayClick);
		}, this);
		return this;
	},
	
	overlayClick: function(){
		this.fireEvent('click');
		return this;
	},
	
	tweenStart: function(){
		this.overlay.setStyles({
			width: '100%',
			height: this.container.getScrollSize().y
		});
	 return this;
	},
	
	tweenComplete: function(){
		this.fireEvent(this.overlay.get('opacity') == this.options.opacity ? 'show' : 'hide');
		return this;
	},
	
	open: function(){
		this.fireEvent('open');
		this.tween.start(this.options.opacity);
		return this;
	},
	
	close: function(){
		this.fireEvent('close');
		this.tween.start(0);
		return this;
	},
	
	resize: function(){
		this.fireEvent('resize');
		this.overlay.setStyle('height', this.container.getScrollSize().y);
		return this;
	},
	
	scroll: function(){
		this.fireEvent('scroll');
		if (this.ie6) this.overlay.setStyle('left', window.getScroll().x);
		return this;
	}
	
});

var GMapHandler = new Class({
	Implements: Options,
	options: {
		addMarkerToCentre: true,
		oLatitude: 'lat',
		oLongitude: 'lon',
		oMap: 'gmap',
		zoom: 14
	},

	map: false,
	
	initialize: function(options) {
		this.setOptions(options);
	
		var latitude = $(this.options.oLatitude).get('value').toFloat();
		var longitude = $(this.options.oLongitude).get('value').toFloat();
	    var myLatlng = new google.maps.LatLng(latitude, longitude);
	    var myOptions = {
			zoom: this.options.zoom,
			center: myLatlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP
	    }
	    var map = new google.maps.Map($(this.options.oMap), myOptions);
	    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map
        })
	}
	
});

var HomeShow = new Class({

	initialize: function() {
		var self = this;
	
		this.show = $('homeshow');
		this.showFrame = $('homeshow_frame');
		this.showLinks = $('homeshow_links');
		this.currentTab = 'btn_storsystem';
		
		this.showLinks.getElements('li').each(function(item, i) {
			var slideDiv = null;
			if (slideDiv = $(item.get('id')+'_products')) {
				item.store('fxslide',new Fx.Slide(slideDiv).hide());
				slideDiv.setStyle('display','block');
			}
			
			item.addEvents({
				'mouseenter': function() {
					if (self.currentTab != item.get('id')) {
						$(self.currentTab+'_desc').fade('hide')
						self.showFrame.get('tween', {transition: Fx.Transitions.Circ.easeInOut}).start('margin-left', -(i*self.showFrame.getElement('li').getStyle('width').toInt())).chain(
							function() {
								$(item.get('id')+'_desc').fade('in');
							}
						);
						var elCurrentTab = $(self.currentTab);
						elCurrentTab.removeClass('current');
						if (slide = elCurrentTab.retrieve('fxslide')) {
							slide.slideOut();
						}
						
						self.currentTab = item.get('id');
						item.addClass('current');
						
						if (slide = item.retrieve('fxslide')) {
							slide.slideIn();
						}
					}

					this.addClass('hover');
				},
				'mouseleave': function() {
					this.removeClass('hover');
				}
			});
			
			$(item.get('id')+'_frame').adopt(
				$(item.get('id')+'_desc').removeClass('grid_3').addClass('desc')
			);
			
			$(item.get('id')+'_desc').fade('hide');
		});

		$(this.currentTab+'_desc').fade('in');
	}

});

var HookOverlay = new Class({

	Implements: Options,
	
	options: {
		id: 'tray_calc',
		width: 400,
		height: 530,
		zIndex: 1000
	},

	initialize: function(options) {
		var self = this;
	
		this.setOptions(options);
	
		this.overlay = new Overlay(document.body, {
			duration: 400,
			onClick: function() {  return false; }
		});
		
		this.holder = new Element('div', {
			'id': this.options.id,
			'styles': {
				'width': this.options.width+'px',
				'height': this.options.height+'px',
				'z-index': this.options.zIndex,
				'display': 'none'
			}
		}).inject(document.body).fade('hide');
		
		this.contents = new Element('div', {
			'id': this.options.id+'_contents'
		}).inject(this.holder);

		var closeDiv = new Element('div', {
			'id':'tray_calc_close',
			'events': {
				'click': function() {
					self.hide();
				}
			}
		}).inject(this.holder);
	},
	
	hide: function() {
		this.holder.fade('out');
		this.overlay.close();
		this.contents.getChildren().inject(document.body).setStyle('display','none');
		
		return this;
	},
	
	show: function(id, options) {
		var self = this;
		
		if (options) {
			this.holder.setStyles({
				'width': options.width ? options.width+'px' : self.options.width+'px',
				'height': options.height ? options.height+'px' : self.options.height+'px'
			});
		}
	
		this.holder.setStyles({
			'display': 'block',
			'top': ((window.getHeight()-this.holder.getStyle('height').toInt())/2)+window.getScrollTop()+'px',
			'left': ((window.getWidth()-this.holder.getStyle('width').toInt())/2)+'px',
			'visibility': 'visible'
		});
		
		this.overlay.open();
		this.contents.empty().adopt($(id+'_content').setStyle('display','block'));
		this.holder.fade('in');
	}

});

var Shared = new Class({

	basketSlide: null,
	currentDetail: 'range',
	trayBuilder: null,
	windowScroller: null,

	initialize: function() {
		var self = this;
	
		this.basketSlide = new Fx.Slide('basket_slide');
		$('basket_slide').setStyle('margin','auto');
		this.windowScroller = new Fx.Scroll(window, {wheelStops: false});
	
		if ($('homeshow')) new HomeShow();
		if ($('homeslideshow')) this.initHomeSlideshow();
		
		var productDetails = $$('#product_view div.product_details');
		if (productDetails) this.initProductDetails(productDetails);
		
		var overlays = $$('div.hook_overlay');
		if (overlays.length) {
			this.hookOverlay = new HookOverlay();
			overlays.addEvent('click', function(e) {
				var options = {};
				if (this.get('id') == 'glide_tilt') {
					options = {
						'height': 430
					};
				}
				self.hookOverlay.show(this.get('id'), options);
			});
		}
		
		var slideshows = $$('div.slideshow');
		if (slideshows.length) {
			slideshows.each(function(show) {
				self.startShow(show.getElements('img'));
			});
		}
		
		var btnAddEnquiry = $$('input.add_to_enquiry');
		if (btnAddEnquiry.length) {
			this.trayBuilder = new TrayBuilder();
			btnAddEnquiry.each(function(btn) {
				if (btn.getPrevious().get('value') == 'storage') {
					btn.addEvent('click', function(e) { self.trayBuilder.show(e); });
				} else {
					btn.addEvent('click', function(e) { self.xhrAddToBasket(btn.getParent().getParent().getParent()); });
				}
			});
			
		}
		
		var basketContents = null;
		if (basketContents = $('basket_contents')) {
			basketContents.getElements('a.xhr_remove').addEvent('click', function(e) {
				new Event(e).stop();
				new Request.JSON({
					'url': this.get('href'),
					'onSuccess': function(json) {
						if (json.result == 'success') {
							$(e.target).getParent().getParent().getParent().dispose();
							self.updateBasketItems(json);
						}
					}
				}).send()
			});
		}
		
		if (document.location.href.contains('?sent')) { this.showSentEnquiry(); }
		
		if ($('gmap')) new GMapHandler();
		
		if ($$('dd.tray_colours')) {
			// changing the tray colour image with each change of the colour select
			$$('select.colours').addEvent('change', function() {
				this.getParent().getPrevious('dd.tray_colours').setStyle('background-image','url(/images/trays_'+this.get('value').toLowerCase()+'.png)');
			});
		}
	},
	
	initHomeSlideshow: function() {
		var frames = $('homeslideshow').getElements('div.frame');
		frames.each(function(frame) {
			frame.adopt(new Element('div', {
				'class': 'frame_desc'
			}).adopt($(frame.get('id').replace('_frame','')+'_desc').removeClass('grid_3').addClass('desc')));
			
			frame.addEvent('click', function() {
				document.location.href = this.get('rel');
			});
		});
		this.startShow(frames);
	},
	
	initProductDetails: function(divs) {
		var self = this;
		
		divs.each(function(div) {
			div.fade('hide');
			
			var divId = div.get('id');
			var parts = divId.split('_');
						
			$('thumbnail_'+parts[1]).addEvent('click', function(e) {
				e.stop();
				var currentThumb = this;
				
				self.windowScroller.toElement('product_title');
				
				if ($('thumbnail_'+self.currentDetail)) $('thumbnail_'+self.currentDetail).removeClass('current');
				this.addClass('current');
				
				$('details_'+self.currentDetail).fade('out').get('tween').chain(function() {
					var imgCode = currentThumb.getParent().getParent().getStyle('background-image').split('/').pop().split('_').pop().split('.');
					imgCode = imgCode[0];

					$('details_'+parts[1]).fade('in');
					$('details_'+parts[1]).setStyle('background-image','url("/images/products/product_'+imgCode+'.jpg")');
				});

				self.currentDetail = parts[1];
			});
		});
	},
	
	showSentEnquiry: function() {
		var overlay = new Overlay(document.body, { 
			duration: 400,
			onClick: function() {  return false; }
		}).open();
		
		var holder = new Element('div', {
			'id': 'tray_calc',
			'styles': {
				'width': '300px',
				'height': '150px',
				'opacity': '0'
			}
		}).inject(document.body).fade('in');

		holder.setStyles({
			'top': ((window.getHeight()-holder.getStyle('height').toInt())/2)+window.getScrollTop()+'px',
			'left': ((window.getWidth()-holder.getStyle('width').toInt())/2)+'px'
		});

		var closeDiv = new Element('div', {
			'id':'tray_calc_close',
			'events': {
				'click': function() {
					holder.fade('out');
					overlay.close();
				}
			}
		}).inject(holder);
		
		holder.adopt(new Element('h2', {
			'text': 'Price Enquiry Sent'
		})).adopt(new Element('p', {
			'class': 'instruction',
			'text': 'Your price enquiry was successfully sent. You will receive a response from one of our sales team as soon as possible.'
		}));
	},

	startShow: function(images) {
		/* settings */
		var showDuration = 5000;
		var currentIndex = 0;
		var interval;
		/* opacity and fade */
		images.each(function(img,i){ 
			if(i > 0) {
				img.set('opacity',0);
			}
			img.set('tween',{duration : 500});
		});
		/* 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);
		});
	},

	updateBasketItems: function(json) {
		var self = this;
	
		self.basketSlide.slideOut().chain(function() {
			$('basket_items').set('text',json.no_items+' item(s)');
			self.basketSlide.slideIn();
		});
	},
	
	xhrAddToBasket: function(form) {
		var self = this;
	
		var parts = [form.toQueryString()];
		if (arguments.length == 2) parts.push(arguments[1]);
		new Request.JSON({
			'url': '/basket',
			'onSuccess': function(json) {
				if (json.result == 'success') {
					self.windowScroller.toTop().chain(function() {
						self.updateBasketItems(json);
					});
				}
			}
		}).send('action=add&'+parts.join('&'));
	}

});

var TrayBuilder = new Class({
	colours: {
		'PR': 'Primary Red',
		'PY': 'Primary Yellow',
		'PB': 'Primary Blue',
		'PG': 'Primary Green',
		'LG': 'Light Grey',
		'BR': 'CFG Burgundy Red',
		'BU': 'CFG Dark Blue',
		'GN': 'CFG Jade Green',
		'DG': 'CFG Dark Grey',
		'CL': 'Clear',
		'TP': 'Translucent Pink',
		'TB': 'Translucent Blue',
		'TG': 'Translucent Green'
	},
	form: null,
	overlay: null,
	holder: null,
	remainingSpace: 0,
	storageTitle: null,
	storageRows: null,
	storageCols: null,
	storageFull: false,
	trayColours: null,
	
	initialize: function() {
		var self = this;
	
		this.overlay = new Overlay(document.body, { 
			duration: 400,
			onClick: function() {  return false; }
		});
		
		this.holder = new Element('div', {
			'id': 'tray_calc',
			'styles': {
				'display': 'none',
				'visibility': 'hidden'
			}
		}).inject(document.body).adopt($('popout_content').setStyle('display','block')).fade('hide');

		var closeDiv = new Element('div', {
			'id':'tray_calc_close',
			'events': {
				'click': function() {
					self.hide();
				}
			}
		}).inject(this.holder);
		
		var traySize = $('product_title').get('text').contains('SW') ? 'sw' : 'ew';
		new Request.JSON({
			'url': '/products/tray-colours',
			'onSuccess': function(json) {
				self.trayColours = json;
			}
		}).get({'size': traySize});
		
		$('tray_options').getElements('input[name=tray_size]').addEvent('click', function() {
			self.limitColours();
		});
		this.holder.getElement('input[name=add_tray]').addEvent('click', function() {
			self.addTrayToStorage();
		});
		$('tray_options').getElement('input[name=save_selection]').addEvent('click', function() {
			shared.xhrAddToBasket(self.form, self.toQueryString());
			self.hide();
		});
		
		this.showHideButtons();
	},
	
	addTrayToStorage: function(noCols, noRows) {
		var self = this;
	
		var noCols = this.storageCols;
		var noRows = this.storageRows;
	
		var traySize = this.holder.getElement('input[name=tray_size]:checked');
		var trayColour = this.holder.getElement('select[name=tray_colour]');

		var tray = new Element('div', {
			'class': 'tray tray_'+traySize.get('value')+' '+trayColour.get('value'),
			'rel': 'CE195'+(this.storageTitle.contains('A3') ? (traySize.get('value') == 'single' ? '6' : '8') : (traySize.get('value') == 'single' ? '0' : (traySize.get('value') == 'double' ? '2' : '4')))+trayColour.get('value'),
			'styles': {
				'display': 'block'
			}
		}).adopt(new Element('p', {
			'text': trayColour.get('value')
		})).adopt(new Element('div', {
			'class': 'icon_close_16',
			'html': '&nbsp;',
			'events': {
				'click': function() {
					this.getParent().dispose();
					self.storageFull = false;
					self.reorderTrays();
					self.showHideButtons();
				}
			}
		}));

		var added = this.insertTray(tray);
		this.reorderTrays();
		
		if (this.remainingSpace == 0) this.storageFull = true;
		this.showHideButtons();
		
		if (!added) {
			tray.dispose();
			alert('There is not enough space to enter your chosen tray size. Please select another size.');
		}
	},
	
	hide: function() {
		this.holder.fade('out');
		this.overlay.close();
		
		return this;
	},
	
	insertTray: function(tray) {
		var noCols = this.storageCols;
		var noRows = this.storageRows;

		// put tray in DOM so we can get height later
		tray.inject(this.holder);

		var added = false;
		this.remainingSpace = 0;
		var i = 1;
		var trayHeight = tray.getSize().y;

		while (i <= noCols) {
			var trayColumn = $('tray_column_'+i);
			var columnHeight = trayColumn.getStyle('height').toInt();
			
			var usedHeight = trayColumn.getElements('div.tray_single, div.tray_double, div.tray_quad').getHeight().sum();
			if (!added) {
				if (columnHeight >= usedHeight+trayHeight) {
					tray.inject(trayColumn).setStyle('display','block');
					usedHeight += trayHeight;
					added = true;
				}
			}
			this.remainingSpace += columnHeight-usedHeight;
			
			i++;
		}
		
		return added;
	},
	
	limitColours: function() {
		var self = this;
	
		var traySize = this.holder.getElement('input[name=tray_size]:checked').get('value');

		var colours = [];
		switch (traySize) {
			case 'single':
				colours = this.trayColours.single;
				break;
			case 'double':
				colours = this.trayColours.double;
				break;
			case 'quad':
				colours = this.trayColours.quad;
				break;
		}

		var sColours = this.holder.getElement('select[name=tray_colour]');
		sColours.getElements('option').dispose();
		colours.each(function(col) {
			sColours.adopt(new Element('option', {
				'value': col,
				'text': eval('self.colours.'+col.toUpperCase())
			}));
		});
	},
	
	limitTrays: function(dl) {
		this.storageTitle = dl.getElement('dt').get('text');
	
		var allowedTrays = [];
		if (this.storageTitle.contains('Midi')) allowedTrays.push('double');
		else if (this.storageTitle.contains('A3')) allowedTrays = ['single','double'];
		else if (this.storageTitle.contains('Maxi')) allowedTrays.push('quad');
		else allowedTrays = ['single','double','quad'];
		
		var i = 0;
		var radios = $('tray_options').getElements('input[name=tray_size]');
		radios.each(function(radio) {
			if (!allowedTrays.contains(radio.get('value'))) {
				radio.set('disabled', true);
				radio.setStyle('visibility','hidden');
				$('lbl_'+radio.get('id')).setStyle('visibility','hidden');
			} else {
				radio.set('disabled', false);
				radio.setStyle('visibility','visible');
				$('lbl_'+radio.get('id')).setStyle('visibility','visible');
				if (i == 0) {
					radio.set('checked',true).fireEvent('click');
					i++;
				}
			}
		});
	},
	
	reorderTrays: function() {
		var self = this;
	
		var unit = this.holder.getElement('div.storage');
		
		var quads = unit.getElements('div.tray_quad').dispose();
		var doubles = unit.getElements('div.tray_double');
		var singles = unit.getElements('div.tray_single');
		
		var trays = [quads, doubles, singles].flatten();
		trays.each(function(tray) {
			self.insertTray(tray);
		});
	},
	
	show: function(e) {
		var self = this;
	
		this.overlay.open();
		this.holder.setStyle('display','block').fade('in');
		this.storageFull = false;
		this.showHideButtons();
		
		this.form = $(e.target).getParent().getParent().getParent();
		var dl = this.form.getElement('dl');
		var productName = dl.getElement('dt').get('text');
		var noRows = dl.getElement('input[name="storage_rows"]').get('value');
		this.storageRows = noRows;
		var noCols = dl.getElement('input[name="storage_cols"]').get('value');
		this.storageCols = noCols;
		
		var designaRak = dl.getElement('input[name="storage_designarak"]');
		$('tray_options').getElement('fieldset.designarak').setStyle('display', designaRak ? 'block' : 'none');
		
		this.limitTrays(dl);

		var divOptions = $('tray_options');
		var divDiagram = $('tray_diagram');
		divDiagram.empty();

		var divStorage = new Element('div', {
			'class':'storage',
			'styles': {
				'width': ((productName.contains('Maxi') || productName.contains('Midi') || (noCols <= 3 && !productName.contains('Tall'))) ? noCols : noCols/2)*104+'px'
			}
		}).inject(divDiagram);
		for (var i = 0; i < noCols; i++) {
			new Element('div', {
				'class': 'tray_column',
				'id': 'tray_column_'+(i+1),
				'styles': {
					'height': noRows*25+'px'
				}
			}).inject(divStorage);
		}
		divStorage.adopt(new Element('div',{'class': 'clear'})).setStyle('left', ((divDiagram.getWidth()-divStorage.getStyle('width').toInt())/2)+'px');
		divDiagram.setStyle('height', ((divStorage.getHeight() > divOptions.getHeight()) ? divStorage.getHeight() : divOptions.getHeight())+'px');
		divStorage.setStyle('top', ((divDiagram.getHeight()-divStorage.getStyle('height').toInt())/2)+'px');
		divOptions.setStyle('height', divDiagram.getHeight()+'px');
		this.holder.setStyle('height', (divOptions.getHeight()+80)+'px');
		
		this.holder.setStyles({
			'top': ((window.getHeight()-this.holder.getStyle('height').toInt())/2)+window.getScrollTop()+'px',
			'left': ((window.getWidth()-this.holder.getStyle('width').toInt())/2)+'px',
			'visibility': 'visible'
		});
		
		return this;
	},
	
	showHideButtons: function() {
		if (this.storageFull) {
			// every slot now full, so disable buttons
			$('tray_options').getElement('input[name=add_tray]').set('disabled',true).fade(0.4);
			$('tray_options').getElement('input[name=save_selection]').set('disabled',false).fade('in');
		} else {
			$('tray_options').getElement('input[name=add_tray]').set('disabled',false).fade('in');
			$('tray_options').getElement('input[name=save_selection]').set('disabled',true).fade(0.4);
		}
	},
	
	toQueryString: function() {
		// run through trays in the unit and put them into a query string.
		var rtn = '';
		
		var designarak = $('tray_options').getElement('fieldset.designarak');
		if (designarak.getStyle('display') == 'block') {
			rtn = 'designarak='+designarak.getElement('input[name=tray_designarak]:checked').get('value')+'&';
		}
		
		var qs = [];
		this.holder.getElements('div.tray').each(function(tray) {
			qs.push(tray.get('rel'));
		});
		
		return rtn+'trays='+qs.join(',');
	}
	
});

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