Array.implement({
	
	invoke: function(fn, args){
		var result = [];
		
		for (var i = 0, l = this.length; i < l; i++){
			if(this[i] && this[i][fn])
				result.push(args ? this[i][fn].pass(args, this[i])() : this[i][fn]());
		}
		return result;
	}
	
});

var CloudsEffect = new Class({
	
	Implements: Options,

	clouds: [],
	
	initialize: function(options) {
		this.setOptions(options);

		var bdy = $(document.body);
		for (var i = 1; i <= 3; i++) {
			this.clouds.push(new Element('div', {'id': 'cloud_'+i}));
		}
		
		var self = this;
		this.clouds.each(function(cloud) {
			bdy.adopt(cloud);
			if (Browser.Engine.trident) {
				var imgURL = cloud.getStyle('background-image');
				cloud.setStyles({
					'background-image': 'none',
					'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale', src="+imgURL+")"
				});
			}

			var settings = self.getNextSettings(cloud.getSize());
			
			cloud.setStyles({
				'top': settings.y,
				'left': settings.x,
				'visibility': 'visible',
				'opacity': settings.opacity
			});
			
			var fx = new Fx.Morph(cloud, {
				duration: settings.duration,
				onComplete: function(el) {
					self.moveCloud(el);
				}
			});
			cloud.store('fx', fx);
			
			self.moveCloud(cloud);
		});
	},
	
	getNextSettings: function(cloudSize) {
		return {
			x: $random(0, window.getSize().x-cloudSize.x),
			y: $random(-cloudSize.y, this.options.availableHeight-cloudSize.y),
			opacity: $random(40, 100)/100,
			duration: $random(20000,60000)
		};
	},
	
	moveCloud: function(el) {
		var fx = el.retrieve('fx');
		var settings = this.getNextSettings(el.getSize());

		fx.set('duration', settings.duration);
		fx.start({
			'top': settings.y,
			'left': settings.x,
			'opacity': settings.opacity
		});
	}
	
});

var DropMenu = new Class({
	
	initialize: function(ul) {
		var children = ul.getChildren('li');
		children.each(function(li) {
			var lists = li.getChildren('ul');
			if (lists.length > 0) {
				lists[0].set('tween', { duration: 300 }).fade('hide');
				li.addEvent('mouseover', function() {
					lists[0].fade('in');
				});
				li.addEvent('mouseout', function() {
					lists[0].fade('out');
				});
				
				new DropMenu(lists[0]);
			}
		});
	}

});

var GMapHandler = new Class({
	map: false,
	
	initialize: function(el, lat, long) {
		window.addEvent('unload', function() {
			GUnload();
		});
		
		if (GBrowserIsCompatible()) {		
			this.map = new GMap2($(el));
			this.map.addControl(new GSmallMapControl());
				
			var point = new GLatLng(parseFloat(lat), parseFloat(long));
			this.map.setCenter(point, 13);
			this.map.addOverlay(new GMarker(point));
		}
	}
});

var RoundedCorners = new Class({
	
	Implements: Options,
	options: {
		radius: '10'
	},
	
	initialize: function(divs, options) {
		this.setOptions(options);
	
		if (divs.length) {
			divs.each(function(div) {
				this.addCorners(div);
			}, this);
		}
	},
	
	addCorners: function(div) {
		if (Browser.Engine.gecko) {
			div.setStyle('-moz-border-radius', this.options.radius+'px')
		} else if (Browser.Engine.webkit) {
			div.setStyle('-webkit-border-radius', this.options.radius+'px')
		} else {
			/*
div.setStyle('position','relative');
			div.setStyle('z-index','1');
			var divBg = div.getStyle('background-color').substring(1);
			
			var corners = [];
			corners.include(new Element('div', {'class': 'r_topleft'}));
			corners.include(new Element('div', {'class': 'r_topright'}));
			corners.include(new Element('div', {'class': 'r_bottomleft'}));
			corners.include(new Element('div', {'class': 'r_bottomright'}));

			if (this.options.transparent) {
				var marginTop = this.getDivMargin(div,'top')+this.options.radius;
				div.setStyle('margin-top', marginTop);
				var marginBottom = this.getDivMargin(div,'bottom')+this.options.radius;
				div.setStyle('margin-bottom', marginBottom);
				
				var divWidth = div.getSize().x-(this.options.radius*2);
				
				var divTopCentre = new Element('div', {'class': 'r_topcenter'});
				divTopCentre.setStyle('width', divWidth);
				divTopCentre.setStyle('bottom','auto');

				var divBottomCentre = new Element('div', {'class': 'r_bottomcenter'});
				divBottomCentre.setStyle('width', divWidth);
				divBottomCentre.setStyle('top','auto');
				
				corners.include(divTopCentre); corners.include(divBottomCentre);
			}

			div.adopt(corners);

			corners.each(function(corner) {
				corner.addClass('sprite_'+divBg);
				if (this.options.transparent) {
					var property = (corner.className.contains('r_top')) ? 'top' : 'bottom';
					corner.setStyle(property, '-'+this.options.radius+'px');
				}
			}, this);
*/
		}
	},
	
	getDivMargin: function(div, margin) {
		return parseInt(div.getStyle('margin-'+margin));
	}
	
});

var Shared = new Class({

	initialize: function() {
		new CloudsEffect({availableHeight: $('header').getSize().y-100});
		
		new RoundedCorners($$('div.c480, div.c320, #body div.c960, #brands, #brands_home'));
		new RoundedCorners($$('div.product_full, div.product_half, div.product_third, div.product_quarter'));

		new DropMenu($('categories'));
	
		$('basket').addEvent('click', function() {
			document.location.href = '/shop/basket';
		});
		
		var basketAdded = null;
		if ((basketAdded = $('basket_added')) != null) {
			var coord = basketAdded.getCoordinates();
			var topBottom = (document.body.getStyle('background-image').contains('winter')) ? 'top' : 'bottom';
			var startVal = (topBottom == 'top') ? coord.top-coord.height : coord.bottom-coord.height;
			var endVal = (topBottom == 'top') ? coord.top : coord.bottom;

			basketAdded.setStyle(topBottom, startVal);
			basketAdded.setStyle('display','block');
			var fx = basketAdded.get('tween');
			fx.start(topBottom, endVal).chain(function() {
				(function() { fx.start(topBottom, startVal); }).delay(3000);
			});
		}
		
		var buttons = $$('.btn_delete');
		if (buttons.length) {
			buttons.each(function(btn) {
				btn.addEvent('click', function(e) {
					this.confirmDelete(e);
				}.bind(this));
			}.bind(this));
		}
		
		if ($('basket_contents')) {
			var btnDeletes = $('basket_contents').getElements('a.btn_delete');
			if (btnDeletes.length) {
				btnDeletes.each(function(btn) {
					btn.removeEvents('click');
					btn.addEvent('click', function(e) {
						if (this.confirmDelete(e)) {
							var row = $(e.target).getParent().getParent().getParent();
							var tbl = row.getParent().getParent();
							if (tbl.rows.length == 3) document.location.reload();
							else $('shipping_category').fireEvent('change');
						}
					}.bind(this));
				}.bind(this));
			}
			
			if ($('shipping_destination')) {
				var objDestination = $('shipping_destination');
				var objCategory = $('shipping_category');
				var objShippingPrice = $('shipping_price');
				var objTotalPrice = $('basket_total');
				
				objDestination.addEvent('change', function() {
					objCategory.empty();
					objShippingPrice.empty();
					new Element('div', {'class': 'spinner', 'html': '&nbsp;'}).inject(objShippingPrice);
					
					new Request.JSON({
						url: '/shop/update-basket',
						onSuccess: function(json) {
							json.categories.each(function(category)  {
								new Element('option', {'value': category.id, 'text': category.name}).inject(objCategory);
							});
							objCategory.fireEvent('change');
						}
					}).get({'action': 'shipping', 'destination_id': objDestination.get('value')});
				});
				
				objCategory.addEvent('change', function() {
					objShippingPrice.empty();
					new Element('div', {'class': 'spinner', 'html': '&nbsp;'}).inject(objShippingPrice);
					objTotalPrice.empty();
					new Element('div', {'class': 'spinner', 'html': '&nbsp;'}).inject(objTotalPrice);
	
					var date = new Date();
					new Request.JSON({
						url: '/shop/update-basket',
						onSuccess: function(json) {
							$('basket_items').set('html',json.basket_items);
							$('basket_items_price').set('html',json.basket_items_price);
							objShippingPrice.empty().set('html',json.shipping_price);
							objTotalPrice.empty().set('html',json.total_price);
						}
					}).get({'action': 'shipping', 'category_id': this.get('value'), 'time': date.getTime()});
				});
			}
			
			if ($('purchased_yes')) {
				var yesSlide = new Fx.Slide('purchased_yes');
				var noSlide = new Fx.Slide('purchased_no');
				var yesQuestion = $('already_purchased_yes');
				var noQuestion = $('already_purchased_no');
				if (yesQuestion.get('checked')) {
					noSlide.hide();
				}
				if (noQuestion.get('checked')) {
					yesSlide.hide();
				}
				yesQuestion.addEvent('click', function() {
					yesSlide.toggle();
					noSlide.toggle();
				});
				noQuestion.addEvent('click', function() {
					yesSlide.toggle();
					noSlide.toggle();
				});
			
				var registerForm = ($('purchased_no')) ? $('purchased_no') : $('confirm_details');
				var inputs = registerForm.getElements('input[type="text"]');
				inputs.each(function(input) {
					if (!input.get('name').contains('delivery_')) {
						input.addEvent('blur', function() {
							var sibling = $('delivery_'+input.get('name'));
							if (sibling && (sibling.get('value') == '')) sibling.set('value',input.get('value'));
						});
					}
				});
			}
		}
		
		if ($('gmap')) new GMapHandler('gmap', $('lat').get('value'), $('lon').get('value'));
		
		if ($('subcats')) {
			$('subcats').getElements('a').each(function(el) {
				el.addEvent('mouseenter', function() {
					el.get('tween', {property: 'padding-left'}).start('25px');
				});
				el.addEvent('mouseleave', function() {
					el.get('tween', {property: 'padding-left'}).start('0px');
				});
			});
		}
	},
	
	confirmDelete: function(e) {
		var btn = $(e.target).getParent();

		var parts = btn.get('title').split(' | ');
		switch (parts.length) {
			case 1: var msg = 'Are you sure you want to delete?'; break;
			case 2: var msg = 'Are you sure you want to delete this '+parts[1]+'?'; break;
			case 3: var msg = 'Are you sure you want to delete this '+parts[1]+'?\n- '+parts[2]; break;
		}
		
		if (!confirm(msg)) e.stop();
		else {
			if (btn.href.indexOf('xhr') > -1) {
				e.stop();
				var link = btn.href.split('&xhr');
				var parts = link[0].split('?');
				var date = new Date();
				parts[1] += '&rowIndex='+(btn.getParent().getParent().rowIndex-1)+'&time='+date.getTime();
				return new Request.JSON({
					method: 'get',
					url: parts[0],
					onSuccess: function(json) {
						if (json.status == 'deleted') {
							var row = btn.getParent().getParent();
							return this.removeTableRow(row);
						} else if (json.status == 'error') {
							alert('It was not possible to remove the item from your basket!');
							return false;
						}
					}.bind(this)
				}).send(parts[1]);
			}
		}
	},
	
	removeTableRow: function(row) {
		var children = row.getChildren();
		
		var cellHeight = 0;
		children.each(function(child) {
			if (parseInt(child.getStyle('height')) > cellHeight) cellHeight = parseInt(child.getStyle('height'));
		});
		children.invoke('setStyle', ['height',cellHeight]);

		var fx = new Fx.Tween(row);
		fx.start('opacity','0.2').chain(function() {
			var childFx = [];
			children.each(function(child) {
				childFx.push(new Fx.Tween(child));
			});
			children.invoke('set', ['html','']);
			childFx.invoke('start', ['height','0px']);
			
			this.start('border','0').chain(function() {
				row.dispose();
				return true;
			});
		});
	}

});

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