var Zofa = new Class({
	
	isGridLayout: false,
	isFixedGridLayout: false,
	
	initialize: function() {
		window.addEvent('domready', this.onDOMReady.bind(this));
		
		if(bertaGlobalOptions.environment == 'site') {
			BertaGallery = Zofa.BertaGallery;
		}
	},
	
	onDOMReady: function() {
		this.isGridLayout = $(document.body).hasClass('type-grid');
		this.isFixedGridLayout = $(document.body).hasClass('type-fixed');
		
		if(bertaGlobalOptions.sectionType == 'first-page') {
			var obj = new Swiff(bertaGlobalOptions.paths.template + 'pageflip_loader.swf', {
			    id: 'pageFlip',
			    width: 950,
			    height: 580,
				container: $('catalogueContainer'),
			    params: {
			        menu: "false",
					scale: "noScale",
					wmode: "transparent",
					allowFullscreen: "true",
					allowScriptAccess: "always",
					bgcolor: "#FFFFFF",
					base: bertaGlobalOptions.paths.template
			    },
			    vars: {}
			});
		}
		
		if(bertaGlobalOptions.environment == 'engine') {

		} else {
			this.evenImages();
			//this.placeCircles();
		}
	},
		
	evenImages: function() {
		if(this.isGridLayout && !this.isFixedGridLayout) {
			var maxH = 0, galleries = [], gH = [];
			$('pageEntries').getElements('.xEntry').each(function(item, idx) {
				if(idx > 0 && idx % 4 == 0) {
					galleries.each(function(item, jdx) {
						if(gH[jdx] < maxH) {
							item.setStyle('margin-top', (maxH - gH[jdx]) + 'px');
						}
					});
					galleries = [];
					gH = [];
					maxH = 0;
				}
				
				var g = item.getElement('.xGallery');
				if(g) {
					gH.push(g.getSize().y);
					galleries.push(g);
					maxH = Math.max(gH[gH.length - 1], maxH);
				}
				
			}, this);
			
		}
	},
	
	placeCircles: function() {
		if(!Browser.Engine.trident || Browser.Engine.version > 4) {
			this.circleNum = $(document.body).getClassStoredValue('colour');
			this.circles = [];
			this.drags = [];
			this.setDragMax();
			var c, src = bertaGlobalOptions.paths.template + 'colours/' + this.circleNum + '-c.png',
				b = $(document.body);
			for(var i = 0; i < 10; i++) {
				c = (new Element('div', {
					'class': 'zofaCircle',
					'styles': {
						'width': '22px', 'height': '22px',
						'left': Math.round(Math.random() * this.dragMaxX) + 'px',
						'top': Math.round(Math.random() * this.dragMaxY) + 'px',
						'background': 'url(' + src + ')'
					}
				}))/*.adopt(new Element('img', { 'src': src }))*/.inject(b);
				this.circles.push(c);
				this.drags.push(new Drag(c, {
					onStart: this.startDrag.bind(this),
					onComplete: this.stopDrag.bind(this),
					limit: { x: this.dragMaxX, y: this.dragMaxY }
				}));
			}
		
			$(window).addEvent('resize', this.onWindowResize.bind(this));
		}
	},
	startDrag: function(el) {
		var d = el.retrieve('zofaMove');
		if(d) d.stop();
		
		this.dragPos = el.getPosition();
		this.dragSpeed = { x: 0, y: 0 };
		this.dragging(el);
		this.dragIntervalId = this.dragging.periodical(10, this, el);
	},
	stopDrag:function(el) {
		$clear(this.dragIntervalId);
		if(this.dragSpeed.x == 0 && this.dragSpeed.x == 0) this.dragging(el);
		el.store('zofaMove', new ZofaMove(el, this.dragSpeed, this.dragMaxX, this.dragMaxY));
	},
	dragging:function(el) {
		var newPos = el.getPosition();
		this.dragSpeed.x = newPos.x - this.dragPos.x;
		this.dragSpeed.y = newPos.y - this.dragPos.y;
		this.dragPos.x = newPos.x;
		this.dragPos.y = newPos.y;
		//console.debug('dragging', newPos.x, newPos.y);
	},
	
	onWindowResize: function() {
		$clear(this.wTimeout);
		this.wTimeout = setTimeout(this.onWindowResizeDo.bind(this), 100);
	},
	onWindowResizeDo: function() {
		this.setDragMax();
		this.drags.each(function(d, idx) {
			d.detach();
		});
		this.drags = [];
		this.circles.each(function(c) {
			var cPos = c.getPosition();
			if(cPos.x > this.dragMaxX) c.setStyle('left', this.dragMaxX + 'px');
			if(cPos.y > this.dragMaxY) c.setStyle('top', this.dragMaxY + 'px');
			this.drags.push(new Drag(c, {
				onStart: this.startDrag.bind(this),
				onComplete: this.stopDrag.bind(this),
				limit: { x: this.dragMaxX, y: this.dragMaxY }
			}));
		}.bind(this));
	},
	
	
	setDragMax: function() {
		var wSize = $(window).getSize();
		var dSize = $('allContainer').getSize();
		//console.debug(wSize.y, dSize.y);
		this.dragMaxX = Math.max(wSize.x, dSize.x) - 25;
		this.dragMaxY = Math.max(wSize.y, dSize.y) - 25;
		//console.debug(this.dragMaxY);
	}
	

	

	
});

function ZofaMove(el, dragSpeed, dragMaxX, dragMaxY) {
	
	this.el = el;
	this.elPosition = el.getPosition();
	this.dragSpeed = dragSpeed;
	this.dragMaxX = dragMaxX;
	this.dragMaxY = dragMaxY;
	
	this.dampness = 0.9;
	
	this.start = function() {
		this.intervalId = this.iterate.periodical(10, this);
	};
	
	this.iterate = function() {
		this.elPosition.x += this.dragSpeed.x;
		this.elPosition.y += this.dragSpeed.y;
		
		if(this.elPosition.x < 0) {
			this.dragSpeed.x = - this.dragSpeed.x;
			this.elPosition.x += this.dragSpeed.x - this.elPosition.x;
			if(this.elPosition.x < 0) this.elPosition.x = 0;
		}
		if(this.elPosition.x > this.dragMaxX) {
			this.dragSpeed.x = - this.dragSpeed.x;
			this.elPosition.x += this.dragSpeed.x + (this.elPosition.x - this.dragMaxX);
			if(this.elPosition.x > this.dragMaxX) this.elPosition.x = this.dragMaxX;
		}
		if(this.elPosition.y < 0) {
			this.dragSpeed.y = -this.dragSpeed.y;
			this.elPosition.y += this.dragSpeed.y - this.elPosition.y;
			if(this.elPosition.y < 0) this.elPosition.y = 0;
		}
		if(this.elPosition.y > this.dragMaxY) {
			this.dragSpeed.y = -this.dragSpeed.y;
			//console.debug(this.elPosition.y, this.dragMaxY, this.dragSpeed.y, this.dragSpeed.y + (this.elPosition.y - this.dragMaxY));
			this.elPosition.y += this.dragSpeed.y + (this.elPosition.y - this.dragMaxY);
			if(this.elPosition.y > this.dragMaxY) this.elPosition.y = this.dragMaxY;
		}
		
		//console.debug(Math.round(this.elPosition.x), Math.round(this.elPosition.y), ' speed:', Math.round(this.dragSpeed.x), Math.round(this.dragSpeed.y));
		
		el.setStyles({
			'left': this.elPosition.x + 'px',
			'top': this.elPosition.y + 'px'
		});
		
		this.dragSpeed.x *= this.dampness;
		this.dragSpeed.y *= this.dampness;
		if(Math.abs(this.dragSpeed.x) < 0.3 && Math.abs(this.dragSpeed.y) < 0.3) {
			this.stop();
		}
	}
	
	this.stop = function() {
		$clear(this.intervalId);
		this.el = null;
	}
	
	this.start();
}






Zofa.BertaGallery = new Class({
	Implements: Options,
	
	initialize: function(container, options) {
		this.setOptions(options);
		
		this.container = container;
		this.entry = this.container.getParent('.xEntry');
		var mbId = 'multiBox' + this.entry.getClassStoredValue('xEntryId');
		
		this.imageContainer = this.container.getElement('div.xGallery');
		this.navContainer = this.container.getElement('ul.xGalleryNav');
		
		this.navContainer.getElements('li').each(function(li, idx) {
			var a = li.getElement('a');
			a.set('href', a.getClassStoredValue('xOrigHref'));
			a.set('id', mbId + '_' + idx);
			a.addClass(mbId);
			
			var titleHTML = '';
			if(this.entry.getElement('.cartTitle')) 
				titleHTML += '<h2>' + this.entry.getElement('.cartTitle').get('html') + '</h2>';
			if(this.entry.getElement('.description')) {
				var dimsDesc = this.entry.getElement('.description').get('html')
				if(dimsDesc) titleHTML += '<p class="sub">' + dimsDesc + '</p>';
			}
			a.set('title', titleHTML);
			
			var descEl = li.getElement('.xGalleryImageCaption');
			descEl.addClass(mbId + '_' + idx);
			//if(descEl.get('html') != '') new Element('HR').inject(descEl, 'top');
			
		}.bind(this));
		
		var o = new overlay({ tweenParams: { duration: 200, transition: Fx.Transitions.Quint.easeOut } });
		//o.container.set('fade', { duration: 200, transition: Fx.Transitions.Quint.easeOut });
		this.mbBox = new multiBox(mbId, {
			openFromLink: false,
			overlay: o,
			descClassName: 'xGalleryImageCaption'
		});
		
		var firstIm = this.imageContainer.getElement('div.xGalleryItem');
		firstIm.setStyle('cursor', 'pointer');
		firstIm.addEvent('click', this.openPopup.bind(this));
	},
	
	openPopup: function() {
		this.mbBox.open(this.mbBox.content[0]);
		//console.debug(this.mbBox );
		
	}
	
});






var zofa = new Zofa();
