/*		
 		console.log(moodboard.pages[0].boundaries.length);
		console.log(moodboard.pages[1].boundaries.length);
		moodboard.pages[0].boundaries.shift();
		console.log(moodboard.pages[0].boundaries.length);
		console.log(moodboard.pages[1].boundaries.length);
 */

var MoodboardOverlay = Class.create({
	overlay: null,
	contentOverlay: null,
	content: null,
	viewport: null,
	color: '#ffffff',
	contentFadeTimer: 1,
	overlayFadeTimer: 1,
	startDelay: 3,
	pe: null,
	
	initialize: function(moodboardContainer) {
		this.content = moodboardContainer.up('#visual');
		this.content.setStyle({
			position: 'relative',
			zoom: 1,
			zIndex: 501
		});
		
		var overlay = new Element('div');
		overlay.setStyle({
			width: '100%',
			height: '100%',
			position: 'absolute',
			top: '0px',
			left: '0px',
			backgroundColor: this.color,
			opacity: 1,
			zIndex: 500
		});
		
		$$('body').first().insert(overlay);
		this.overlay = $$('body').first().childElements().last();
		this.overlay.addClassName('moodboard-overlay');

		var contentOverlay = Element.clone(overlay, false);
		
		contentOverlay.setStyle({ zIndex: 502 });
		
		$$('body').first().insert(contentOverlay);
		this.contentOverlay = $$('body').first().childElements().last();
		this.contentOverlay.addClassName('moodboard-content-overlay');
	},
	
	start: function() {
		new Effect.Morph(this.contentOverlay, {
			style: 'opacity: 0',
			duration: this.contentFadeTimer,
			afterFinish: function() {
				this.contentOverlay.remove();
			}.bind(this)
		});

		this.pe = new PeriodicalExecuter(this.finish.bind(this), this.startDelay);
	},
	
	finish: function(trigger) {
		this.pe.stop();
		
		new Effect.Morph(this.overlay, {
			style: 'opacity: 0',
			duration: this.overlayFadeTimer,
			afterFinish: function() {
				this.overlay.remove();
				this.content.setStyle({ zIndex: 80 });
			}.bind(this)
		});
	}
});

var Moodboard = Class.create({
	container: null,
	wrapper: null,
	slider: null,
	pages: null,
	position: null,
	lastPosition: null,
	
	overlay: null,
	initBackground: null,
	
	boardWidth: null,
	moving: null,
	
	duration: 1,
	debug: null,
	
	initialize: function(container) {
		if(/debug=1/.test(window.location.href)) {
			this.debug = true;
		}
		this.container = container;
		this.wrapper = this.container.down('.fce-moodboard-content');
		this.slider = this.container.down('.fce-moodboard-slider');
		this.position = 0;
		this.pages = new Array();
		this.container.select('.fce-moodboard-content').first().select('.csc-default').each(function(item, index) {
			var imagesets = new Array();
			item.select('.fce-moodboard-set-image').each(function(imageset) {
				imagesets.push(new MoodboardImageset(imageset));
			});
			
			this.pages.push(new MoodboardPage(item, imagesets, index, item.getHeight()));
		}.bind(this));

		if(Object.isArray(this.pages) && this.pages.length) {
			this.boardWidth = this.pages.first().container.getWidth();
			this.wrapper.setStyle({ width: this.boardWidth+'px' });
			this.slider.setStyle({ width: (this.pages.length * this.boardWidth)+'px' });
		}
		this.addEventHandling();
		this.activatePage();

		Event.observe(window, 'load', function(event) {
				moodboard.overlay.start();
				if(Prototype.Browser.IE && (parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7)) {
					moodboard.overlay.finish();
				}
		});
	},
	
	addEventHandling: function() {
		try {
			this.container.down('.navigator-right').observe('click', this.next.bindAsEventListener(this));
			this.container.down('.navigator-left').observe('click', this.previous.bindAsEventListener(this));
			this.container.down('.navigator-right').setOpacity(0);
			this.container.down('.navigator-left').setOpacity(0);
			
			Event.observe(window, 'load', function(event) {
				new Effect.Morph(this.container.down('.navigator-right'), { style: 'opacity: 1', duration: 0.8 });
				new Effect.Morph(this.container.down('.navigator-left'), { style: 'opacity: 1', duration: 0.8 });
			}.bind(this));
		}
		catch(exception) {
			console.log(exception);
		}
	},
	
	next: function(event) {
		if(this.moving) {
			return;
		}
		this.lastPosition = this.position;
		this.position++;
		if(Object.isArray(this.pages) && this.position >= this.pages.length) {
			this.position = 0;
		}
		
		this.move();
	},
	
	previous: function(event) {
		if(this.moving) {
			return;
		}
		this.lastPosition = this.position;
		this.position--;
		if(Object.isArray(this.pages) && this.position < 0) {
			this.position = this.pages.length - 1;
		}

		this.move();
	},
	
	activatePage: function() {
		this.pages[this.position].activate();
	},
	
	deactivatePage: function() {
		this.pages[this.lastPosition].deactivate();
	},
	
	move: function() {
		this.deactivatePage();
		this.moving = true;
		var left = (this.boardWidth * this.position) * -1;
		new Effect.Morph(this.slider, {
			style: 'margin-left: '+left+'px',
			duration: this.duration,
			afterFinish: function() {
				this.activatePage();
				this.moving = false;
			}.bind(this)
		});
	}
});

var MoodboardPage = Class.create({
	container: null,
	imagesets: null,
	current: -1,
	
	index: null,
	pageHeight: null,
	
	pe: null,
	listener: null,
	boundaries: null,
	frequency: 0.1,
	
	initialize: function(container, imagesets, index, pageHeight) {
		this.container = container;
		this.imagesets = imagesets;
		this.index = index;
		this.pageHeight = pageHeight;
		this.gatherBoundaries();
	},
	
	gatherBoundaries: function() {
		this.boundaries = new Array();
		this.imagesets.each(function(imageset, index) {
			this.boundaries.push(imageset.getBoundary(this.index, this.pageHeight));
		}.bind(this));
	},
	
	activate: function() {
		this.pe = new PeriodicalExecuter(this.check.bind(this), this.frequency);
	},
	
	deactivate: function() {
		if(this.pe) {
			this.pe.stop();
		}
	},
	
	check: function() {
		var lp = lastCursorPosition;
		var inImageset = this.boundaries.indexOf(this.boundaries.find(function(boundary, index) {
			return (lp.x > boundary.x && lp.x < (boundary.x + boundary.width) && lp.y > boundary.y && lp.y < (boundary.y + boundary.height));
		}.bind(this)));

		//console.log('current: '+this.current+' inImageset: '+inImageset);
		if(this.current != -1 && inImageset == -1) {
			this.imagesets[this.current].mouseOut();
			this.current = -1;
		}
		if(this.current != -1 && inImageset != this.current) {
			this.imagesets[this.current].mouseOut();
			this.current = inImageset;
			this.imagesets[this.current].mouseOver();
		}
		if(this.current == -1 && inImageset != -1) {
			this.current = inImageset;
			this.imagesets[this.current].mouseOver();
		}
	},
	
	hide: function() {
		this.container.hide();
	}
});

var MoodboardImageset = Class.create({
	container: null,
	image: null,
	links: null,
	linksBackground: null,
	opacity: 0.5,
	margin: null,
	imageClass: null,
	imageClassConfig: new Array(0,11,8,4),

	initBackgroundColor: '#000000',
	fadeInDuration: 0.6,
	fadeInEffect: null,
	
	initialize: function(container) {
		this.container = container;
		this.image = this.container.down('img');
		this.getImageClass();
		this.links = this.container.down('.fce-moodboard-set-image-linklist');
		this.prepareContent();
	},
	
	addEventHandling: function() {
		this.image.observe('mouseover', this.mouseOver.bindAsEventListener(this));
		this.image.observe('mouseout', this.mouseOut.bindAsEventListener(this));
	},
	
	getImageClass: function() {
		var classNames = this.container.readAttribute('class');
		var indicator = classNames.split(' ').find(function(str) {
			return /imageborder-[0-9]{1,}/.match(str);
		});
		
		if(Object.isString(indicator) && indicator != '') {
			this.imageClass = indicator.split('-').last();
			this.margin = this.getImageMargin(this.imageClass);
		}
	},
	
	getImageMargin: function(imageClass) {
		if(Object.isArray(this.imageClassConfig) && this.imageClassConfig.length >= imageClass) {
			return this.imageClassConfig[imageClass];
		}
		return null;
	},
	
	prepareContent: function() {
		var bg = new Element('div');
		bg.addClassName('fce-moodboard-set-image-linklist-background');
		bg.setOpacity(this.opacity);
		
		this.links.up().insert(bg);
		this.linksBackground = this.links.next();
		//this.initBackgroundColor = this.linksBackground.getStyle('background-color');

		this.links.setStyle({
			width: Math.ceil(this.image.readAttribute('width')-(this.margin*2))+'px',
			height: Math.ceil(this.image.readAttribute('height')-(this.margin*2))+'px',
			top: '0px',
			left: '0px',
			margin: this.margin+'px',
			padding: this.margin+'px'
		});

		this.linksBackground.setStyle({
			width: Math.ceil(this.image.readAttribute('width')-(this.margin*2))+'px',
			height: Math.ceil(this.image.readAttribute('height')-(this.margin*2))+'px',
			top: '0px',
			left: '0px',
			margin: this.margin+'px',
			padding: this.margin+'px'
		});

		this.links.hide();
		this.linksBackground.hide();
	},
	
	getBoundary: function(index, pageHeight) {
		var co = this.container.cumulativeOffset();
		var rv = { x: co.left, y: co.top };	

		// substract the summary of all moodboard pages height before this one
		rv.y -= index * pageHeight;
		
		// fix for inaccurate data from the cumulativeOffset function
		if(Prototype.Browser.Opera) {
			rv.y += 1;
			rv.x += 8;
		}

		if(Prototype.Browser.Gecko) {
			rv.y += 1;
		}
		
		if(Prototype.Browser.IE8) {
			rv.y += 183;
			rv.x += -10;
		}
		
		if(Prototype.Browser.IE7) {
			rv.y += -1;
			rv.x += -3;
		}
		
		rv.width = this.container.getWidth();
		rv.height = this.container.getHeight();

		return rv;
	},
	
	mouseOver: function(event) {
		this.fadeIn();
		this.links.show();
		this.linksBackground.show();
	},
	
	mouseOut: function(event) {
		this.links.hide();
		this.linksBackground.hide();
	},
	
	fadeIn: function() {
		if(this.fadeInEffect) {
			this.fadeInEffect.cancel();
		}
		this.linksBackground.setStyle({ backgroundColor: '#ffffff', opacity: '1' });
		this.fadeInEffect = new Effect.Morph(this.linksBackground, {
			style: 'background-color: '+this.initBackgroundColor+'; opacity: '+this.opacity,
			duration: this.fadeInDuration
		});
	}
});

function getCursorPosition(e) {
    e = e || window.event;
    var cursor = {x:0, y:0};
    if (e.pageX || e.pageY) {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    } 
    else {
        var de = document.documentElement;
        var b = document.body;
        cursor.x = e.clientX + 
            (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        cursor.y = e.clientY + 
            (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    }
    return cursor;
}

var lastCursorPosition = {x:0, y:0};

Event.observe(document, 'mousemove', function(event) {
	 lastCursorPosition = getCursorPosition(event);
});

Event.observe(document, 'dom:loaded', function(event) {
	$$('.fce-moodboard-container').each(function(item, index) {
		moodboard = new Moodboard(item);
		if(index == 0) {
			moodboard.overlay = new MoodboardOverlay(item);
		}
	});
});
