var ColNaviMarked 		= '#df0077';
var ColNaviNotMarked 	= '#999';

var markedSections;
var verticalPadding = 10;
var horizontalPadding = 10;
var itemField;


function markNavi(param){
	markedSections.empty();
	
	$$('#sections li a').each(function(ele){
		if(ele.get('class').contains(param)){
			ele.set({'styles':{'color': ColNaviMarked}});		
		} else {	
			ele.set({'styles':{'color': ColNaviNotMarked}});
		}					
	});
	
	markedSections.push(param);
	itemField.work();
};

function getMediaWidth(){
	var media = $('media');
	var mediacontainer = $('mediacontainer');
	var description = $('description');
	var margin = mediacontainer.getStyle('margin-left').toInt() * 2;
	return media.getSize().x - description.getSize().x - margin;
};

// ItemField
var ItemField = new Class({
	initialize: function(element, formatX, formatY){
		this.element = element;
		this.formatX = formatX;
		this.formatY = formatY;
		this.space = new Element('div', {'id': 'debugger'});
		this.space.inject($('navi'), 'top');
		this.space.setStyle('height', $(document.window).getSize().y + 1);
		
		this.items = element.getElements('.item');	
		this.weightItems = new Array();
		this.imageItems = new Array();
		this.currentFormat = new Object();
		
		this.horizontalPadding = 10;
		this.verticalPadding = 10;
		this.firstLaunch = true;
		this.width;
		this.itemWidth;
		this.activeItem = null;
		
	 	this.items.each(function(ele){
	 		var imageItem = new ImageItem(ele);
	 		
	 		ele.addEvent('click', function(event){
	 			if(this.activeItem == null){
	 				this.showItem(imageItem);
	 			} else {
	 				this.showItems();
	 			}
	 		}.bind(this));
	 		
	  	this.imageItems.push(imageItem);
	  }.bind(this));	
	},
	
	showItem: function(item){
		this.itemsToFade = 0;		
		this.imageItems.each(function(imageItem){
			if(imageItem != item){
				var fade = new Fx.Morph(imageItem.element, {link: 'chain', duration: 300, transition: Fx.Transitions.Linear});
				fade.start({ 'opacity': 0 }).chain(function(){this._showItem(item)}.bind(this));
				imageItem.highlight = false;
			} else {
				imageItem.element.setStyle('z-index', 0);
			}
		}.bind(this));
	},
	
	_showItem: function(item){
		this.itemsToFade++;
		if(this.itemsToFade < this.items.length - 1) return;
		item.morphSize(this.width, 300);
		var fade = new Fx.Morph(item.element, {duration: 300, transition: Fx.Transitions.Linear});
		fade.start({ 'opacity': 1, 'margin-top': 0, 'margin-left': 0 });
		item.element.setStyle('opacity', 1);
		this.activeItem = item;
	},
	
	showItems: function(){
		var fade = new Fx.Morph(this.activeItem.element, {link: 'chain', duration: 300, transition: Fx.Transitions.Linear});
		
		this.imageItems.each(function(imageItem){
			imageItem.highlight = true;
		});
		
		fade.start({ 'opacity': 0 }).chain(function(){
			this.activeItem.setSize(this.itemWidth);
			this.activeItem.element.setStyle('z-index', 0);
			this.activeItem = null;
			this.resize(this.width);
			this.positionItems('instant');
		}.bind(this));
	},
	
	resize: function(width){
		this.width = width;
		var ratio = $(document.window).getSize().x / $(document.window).getSize().y;
		
		if(this.imageItems.length > 1){
			if(ratio > 1) {
				this.currentFormat = this.generateFormat(this.formatX, this.formatY);
			} else {
				this.currentFormat = this.generateFormat(this.formatY, this.formatX);
			}

			this.itemWidth = (width - ((this.currentFormat.x - 1) * this.horizontalPadding)) / (this.currentFormat.x);
			
			if(this.activeItem === null){
				this.imageItems.each(function(ele){
					ele.element.setStyle('opacity', 0.1);
					ele.setSize(this.itemWidth);
				}.bind(this));
			} else {
				this.activeItem.setSize(this.width);
			}
		} else if(this.imageItems.length == 1) {
			this.itemWidth = width - (2 * this.horizontalPadding);// (width - ((this.currentFormat.x - 1) * this.horizontalPadding));
			if(this.activeItem === null){
				this.imageItems.each(function(ele){
					ele.element.setStyle('opacity', 0.1);
					ele.setSize(this.itemWidth);
				}.bind(this));
			} else {
				this.activeItem.setSize(this.width);
			}
		}
	},
	
	work: function(){
		if(this.activeItem === null){
			this.calcWeight();
			this.sortItems();
			this.interpretWeight();
			this.positionItems();
		}
	},
	
	getItemHeight: function(index){
		var row = Math.floor(index / this.currentFormat.x) % this.currentFormat.y;
		if (row < 1 || !this.items[index - this.currentFormat.x]) return 0;
		return (verticalPadding + this.items[index - this.currentFormat.x].getSize().y) + this.getItemHeight(index - this.currentFormat.x);
	},
	
	sortItems: function(){
		for(var i = 0; i < this.weightItems.length; i++){
			var j = i;
			var m = this.weightItems[i];
			var n = this.items[i];
			var o = this.imageItems[i];
			while(j > 0 && this.weightItems[j - 1] < m){
				this.weightItems[j] = this.weightItems[j - 1];
				this.imageItems[j] = this.imageItems[j - 1];
				this.items[j] = this.items[j - 1];
				j--;
			}
			this.weightItems[j] = m;
			this.items[j] = n;
			this.imageItems[j] = o;
		}
	},
	
	interpretWeight: function(){
		var maxWeight = this.weightItems[0];
		for (var i = 0; i < this.imageItems.length; i++) {
			this.imageItems[i].opacity = (this.weightItems[i] == 0) ? 0.1 : maxWeight / this.weightItems[i];
		}
	},
	
	calcWeight: function(){
		this.weightItems.empty();
				
		for(var a = 0; a < this.items.length; a++){
			var weight = 0;
			for(var i = 0; i < markedSections.length; i++){
				if(this.items[a].get('class').contains(markedSections[i])){
					weight++;
				}
			}
			this.weightItems.push(weight);
		}
	},
	
	positionItems: function(mode){
		if(mode == 'instant') this.firstLaunch = true;
		var maxWeight = this.weightItems[0];
		for (var i = 0; i < this.items.length; i++) {
			var itemX = (i % this.currentFormat.x) * (this.itemWidth + this.horizontalPadding);
			var itemY = this.getItemHeight(i);
			var item = this.items[i];
			var opacity = (this.weightItems[i] == 0) ? 0.1 : maxWeight / this.weightItems[i];
			if(this.firstLaunch === true){
				item.setStyles({'margin-left': itemX, 'margin-top': itemY});
			} else {
				item.set({'morph': { duration: 300, transition: Fx.Transitions.Linear }}).morph({'margin-left': itemX, 'margin-top': itemY});
			}
			item.set('tween', {duration: 300});
			item.tween('opacity', opacity);
		}
		this.firstLaunch = false;
	},
	
	generateFormat: function(formatX, formatY){
		var format = new Object();
		if(this.imageItems.length < 1) return format;
	
		if(this.imageItems.length <= formatX * formatY) {
			if(this.imageItems.length <= (formatX - 1) * (formatY - 1)) {
				return this.generateFormat(formatX - 1, formatY - 1);
			} else {
				format.x = formatX;
				format.y = formatY;
				return format;
			}
		} else {
			return this.generateFormat(formatX + 1, formatY + 1);
		}
	}
});

// ImageItem
var ImageItem = new Class({		
		Implements: [Events, Chain],
    initialize: function(element, top, left){
    	this.element = element;
    	this.opacity = 0;
    	this.highlight = true;
    	
    	element.setStyle('opacity', 0);
      
      element.setStyle('position', 'absolute');
      
      element.addEvents({
          'mouseover': function(){
      	  	if(this.highlight) element.tween('opacity', 1);
          }.bind(this),
          
          'mouseout': function(){   	
          	if(this.highlight) element.tween('opacity', this.opacity);
          }.bind(this)
      });
    },
    
    initSize: function(){
    	this.element.getElements('*').each(function(ele){
    		ele.setStyle('max-width', ele.getSize().x);
    	}.bind(this));
    },
    
    setSize: function(size){
    	this.element.setStyle('width', size);
  		this.element.getElements('*').each(function(ele){
  			ele.setStyle('width', size);
  		}.bind(this));
    },
    
    morphSize: function(size, time){
    	var fade = new Fx.Morph(this.element, {link: 'chain', duration: time, transition: Fx.Transitions.Linear});
    	fade.start({ 'width': size }).chain(function(){ this.fireEvent('complete')}.bind(this));
    	
    	this.element.getElements('*').each(function(ele){
    		ele.set({'morph': { duration: time, transition: Fx.Transitions.Linear }}).morph({'width': size});
    	});
    }
});

// start
window.addEvent('domready', function(){
	itemField = new ItemField($('mediacontainer'), 4, 5);
	markedSections = new Array();
	$$('#sections li a').each(function(ele){
		ele.addEvent('click', function(event){
			new Event(event).stop();
			markNavi(ele.get('class').split(' ').getLast());
		});			
	});
});

window.addEvent('load', function(){
	itemField.imageItems.each(function(item){
		item.initSize();
	});

	$(document.window).addEvent('resize', function(){
		itemField.resize(getMediaWidth());
		itemField.work();
	});
	
	itemField.resize(getMediaWidth());
	
	var start = $('start');
	if(start){
		markNavi(start.get('class'));
	} else {
		markNavi('');
	}
});
