var navigation;
var family;
var collection;
var item;

var Navigation = Class.create({

    initialize: function() {
		this._container = $('sub-nav');
		this._current = 0;
		this.populate();
		this.addObservers();
	},

	populate: function () {
		allfamilies.each(function(n) {
			var navId = 'nav' + n.id;
	        var element = Builder.node('a', {href: '#', id: navId}, n.title);
			this._container.down('div').insert({
				before: element
			});
	    }.bind(this));
		this._container.down(0).addClassName('first');
	},

	addObservers: function() {
		this._container.observe('click', this.handleClick.bind(this));
	},

	handleClick: function(e) {
		e.preventDefault();
		var elt = e.element();
        if (elt.tagName == 'DIV')
	        return;
		e.stop();
		this._current = elt.identify().gsub(/nav/, '');
		console.log('selected family: ' + this._current);
		if ($('family').visible()) {
			Effect.Fade($('family'), {
				duration: 0.3,
				afterFinish: function() {
					collection = new Collection('collection', 'collection-wrapper', navigation._current);
				}.bind(this)
			});
		} else if($('collection').visible()) {
			Effect.Fade('collection-left-arrow', {duration: 0.3});
			Effect.Fade('collection-right-arrow', {duration: 0.3});
			Effect.Fade($('collection'), {
				duration: 0.3,
				afterFinish: function() {
					collection._current = this._current;
					collection.rePopulate();
				}.bind(this)
			});
		} else if($('item').visible()) {
			Effect.Fade($('item'), {
				duration: 0.3,
				afterFinish: function() {
					collection._current = this._current;
					collection.rePopulate();
				}.bind(this)
			});
		}
    }

});

var Family = Class.create({

    initialize: function(container) {
		this._container = $(container);
		this._items = $H({});
		this._loaded = false;
		this._current = 0;
		this._clicked = false;
		this.populate();
		this.addObservers();
	},

	populate: function () {
		var count = 1;
		allfamilies.each(function(n) {
			var familyId = 'family' + n.id;
	        var element = Builder.node('img', {src: '/data/family_' + n.id + '.jpg', id: familyId, style: 'display: none;', onload: 'family.setLoaded(this);'}, '');
			this._container.down(0).down('div').insert({
				before: element
			});
			this._items.set(familyId, false);
	    }.bind(this));
		this._container.down(0).down(0).addClassName('first');
		new PeriodicalExecuter(this.checkLoadingProgress.bind(this), 0.1);
	},

	checkLoadingProgress: function(o) {
		if (this._items.keys().length == 0) {
			o.stop();
			this._loaded = true;
			this._container.fire('family:loaded');
		}
	},

	setLoaded: function(elt) {
		this._items.unset(elt.identify());
	},

	fadeIn: function() {
		this._container.show();
		var items = $$('#family .list img');
		Effect.multiple(items, Effect.Appear, {duration: 0.9});
	},

    fadeOut: function() {
		Effect.Fade(this._container, {
			duration: 0.3,
			afterFinish: function() {
				this._container.fire('family:changed');
			}.bind(this)
		});
	},

	addObservers: function() {
		this._container.observe('click', this.handleClick.bind(this));
		this._container.observe('mouseover', this.handleOver.bind(this));
		this._container.observe('mouseout', this.handleOut.bind(this));
	},

	handleClick: function(e) {
		console.log('family selected');
		var elt = e.element();
        if (elt.tagName == 'DIV')
	        return;
		e.stop();
		if (!this._clicked) {
			this._clicked = true;
			this._current = elt.identify().gsub(/family/, '');
			this.fadeOut();
		}
    },

    handleOver: function(e) {
		console.log('family over');
		var elt = e.element();
        if (elt.tagName == 'DIV')
	        return;
		e.stop();
		if (!this._clicked) {
			console.log(elt.identify().gsub(/family/, ''));
			this.showFullTitle(elt);
		}
    },

    handleOut: function(e) {
		console.log('family out');
		var elt = e.element();
	    if (elt.tagName == 'DIV')
	        return;
	    elt = elt.up('div');
	    e.stop();
		$('callout').hide();
    },

    showFullTitle: function(elt) {

		var item = allfamilies.find(function(i) {
            if (i.id == elt.identify().gsub(/family/, '')) return true;
        }.bind(this));

        console.log(item.title.escapeHTML());

		$('callout').update(item.title.escapeHTML());
		$('callout').show();
		$('callout').clonePosition(elt, {
			setHeight: false,
			setWidth: false,
			offsetTop: 160,
			offsetLeft: 10
		});

    }

});

var Collection = Class.create({

    initialize: function(container, wrapper, current) {
		this._container = $(container);
		this._wrapper = $(wrapper);
		this._items = $H({});
		this._loaded = false;
		this._current = current;
		this._clicked = false;
		this._scrolled = 0;
		this.populate();
		this.addObservers();
	},

	populate: function () {
		var items = [];
		allcollections.find(function(i) {
	        if (i.family_id == this._current) items.push(i);
	    }.bind(this));
		items.each(function(n) {
	        var collectionId = 'collection' + n.id;
	        var element = Builder.node('img', {src: '/data/' + n.id + '/list.jpg', id: collectionId, style: 'display: none;', onload: 'collection.setLoaded(this);'}, '');
			this._container.down(0).down('div').insert({
				before: element
			});
			this._items.set(collectionId, false);
	    }.bind(this));
		this._container.down(0).down(0).addClassName('first');
		new PeriodicalExecuter(this.checkLoadingProgress.bind(this), 0.1);
	},

	rePopulate: function () {
		this._clicked = false;
		$$('#collection .list img').each(function(i) {
			i.remove();
		});
		var items = [];
		allcollections.find(function(i) {
	        if (i.family_id == this._current) items.push(i);
	    }.bind(this));
		items.each(function(n) {
	        var collectionId = 'collection' + n.id;
	        var element = Builder.node('img', {src: '/data/' + n.id + '/list.jpg', id: collectionId, style: 'display: none;', onload: 'collection.setLoaded(this);'}, '');
			this._container.down(0).down('div').insert({
				before: element
			});
			this._items.set(collectionId, false);
	    }.bind(this));
		this._container.down(0).down(0).addClassName('first');
		new PeriodicalExecuter(this.checkLoadingProgress.bind(this), 0.1);
	},

	checkLoadingProgress: function(o) {
		if (this._items.keys().length == 0) {
			o.stop();
			this._loaded = true;
			this._container.fire('collection:loaded');
		}
	},

	setLoaded: function(elt) {
		this._items.unset(elt.identify());
	},

	fadeIn: function() {
		this._container.show();
		this._wrapper.show();
		if ($$('#collection .list img').length > 4) {
			Effect.Appear('collection-left-arrow', {duration: 0.3});
			Effect.Appear('collection-right-arrow', {duration: 0.3});
		}
		var items = $$('#collection .list img');
		Effect.multiple(items, Effect.Appear, {duration: 0.9});
	},

    fadeOut: function() {
		Effect.Fade('collection-left-arrow', {duration: 0.3});
		Effect.Fade('collection-right-arrow', {duration: 0.3});
		Effect.Fade(this._container, {
			duration: 0.3,
			afterFinish: function() {
				this._wrapper.hide();
				this._container.fire('collection:changed');
			}.bind(this)
		});
	},

	addObservers: function() {
		this._container.observe('click', this.handleClick.bind(this));
		$('collection-left-arrow').observe('click', this.handleLeftArrowClick.bind(this));
		$('collection-right-arrow').observe('click', this.handleRightArrowClick.bind(this));
	},

	handleClick: function(e) {
		var elt = e.element();
        if (elt.tagName == 'DIV')
	        return;
		e.stop();
		if (!this._clicked) {
			this._clicked = true;
			this._current = elt.identify().gsub(/collection/, '');
			this.fadeOut();
		}
    },

	handleLeftArrowClick: function(e) {
		var elt = e.element();
		e.stop();
		this.scrollContents(1);
    },

	handleRightArrowClick: function(e) {
		var elt = e.element();
		e.stop();
		this.scrollContents(-1);
    },

    scrollContents: function(direction) {
    	if (($$('#collection .list img').length - 4 + direction + this._scrolled) >= 0 && ($$('#collection .list img').length - 4 + direction + this._scrolled) <= $$('#collection .list img').length - 4) {
    		this._scrolled += direction;
    		this._container.setStyle('left: ' + 154 * this._scrolled + 'px;');
    	}
    }

});

var Item = Class.create({

    initialize: function(container, current) {
		this._container = $(container);
		this._controls = $(container).down(0);
		this._items = $H({});
		this._loaded = false;
		this._current = current;
		this.populate();
		this.addObservers();
	},

	populate: function () {
		$('details').hide();
		$('item-list').update('<div class="clearer"><div>');
		var items = [];
		allitems.find(function(i) {
	        if (i.collection_id == this._current) items.push(i);
	    }.bind(this));
		this._current = items[0].id;
		items.each(function(n) {
	        var itemId = 'item' + n.id;
	        var element = Builder.node('img', {src: '/data/' + n.collection_id + '/' + n.id + '/small_image.jpg', id: itemId, style: 'display: none;', onload: 'item.setLoaded(this);'}, '');
			this._container.down(0).down('div').insert({
				before: element
			});
			this._items.set(itemId, false);
	    }.bind(this));
		this._container.down(0).down(0).addClassName('first');
		new PeriodicalExecuter(this.checkLoadingProgress.bind(this), 0.1);
	},

	checkLoadingProgress: function(o) {
		if (this._items.keys().length == 0) {
			o.stop();
			this._loaded = true;
			this._container.fire('item:loaded');
		}
	},

	setLoaded: function(elt) {
		this._items.unset(elt.identify());
	},

	fadeIn: function() {
		this._container.show();
		var items = $$('#item .list img');
		Effect.multiple(items, Effect.Appear, {
			to: 0.5, duration: 0.9, afterFinish: function() {
				$('item' + this._current).setOpacity(1.0);
			}.bind(this)
		});
		this.showDetails();
	},

    fadeOut: function() {
		Effect.Fade(this._container, {
			duration: 0.3,
			afterFinish: function() {
				this._container.fire('collection:changed');
			}.bind(this)
		});
	},

	addObservers: function() {
		this._controls.observe('click', this.handleClick.bind(this));
		this._controls.observe('mouseover', this.handleOver.bind(this));
		this._controls.observe('mouseout', this.handleOut.bind(this));
	},

	handleClick: function(e) {
		var elt = e.element();
        if (elt.tagName == 'DIV')
	        return;
		e.stop();
		$('item' + this._current).setOpacity(0.5);
		this._current = elt.identify().gsub(/item/, '');
		$('item' + this._current).setOpacity(1.0);
		this._container.fire('item:changed');
    },

	showDetails: function() {
		if ($('details').visible()) {
			Effect.Fade($('details'), {
				duration: 0.3,
				afterFinishInternal: Prototype.emptyFunction,
				afterFinish: function() {
					this.updateDetails();
				}.bind(this)
			});
		} else {
			this.updateDetails();
		}
	},

	updateDetails: function() {
		var details = $('details');
		var item = allitems.find(function(i) {
	        if (i.id == this._current) return i;
	    }.bind(this));
		var itemId = 'item' + item.id;
		details.down('h1').innerHTML = item.family;
		details.down('h2').innerHTML = item.title;
		details.down('p').innerHTML = item.description;
		var element = Builder.node('img', {src: '/data/' + item.collection_id + '/' + item.id + '/large_image.gif', id: itemId, onload: 'Effect.Appear($("details"), {duration: 0.3});'}, '');
		this._container.down('span').update(element);
	},

	handleOver: function(e) {
		var elt = e.element();
        if (elt.tagName == 'DIV')
	        return;
		e.stop();
		elt.setOpacity(1.0);
    },

	handleOut: function(e) {
		var elt = e.element();
        if (elt.tagName == 'DIV')
	        return;
		e.stop();
		if (elt.identify() != ('item' + this._current)) {
			elt.setOpacity(0.5);
		}
    }

});

function init() {
	bindUI();
	navigation = new Navigation();
	if (typeof(window['selectedfamily']) != "undefined") {
		collection = new Collection('collection', 'collection-wrapper', selectedfamily);
	} else {
		family = new Family('family');
	}

}

function bindUI() {
	document.observe('family:loaded', function() {
		family.fadeIn();
	});
	document.observe('family:changed', function() {
		collection = new Collection('collection', 'collection-wrapper', family._current);
	});
	document.observe('collection:loaded', function() {
		collection.fadeIn();
	});
	document.observe('collection:changed', function() {
		item = new Item('item', collection._current);
	});
	document.observe('nav:changed', function() {
		if (typeof(window['collection']) != "undefined") {

		} else {
			collection = new Collection('collection', 'collection-wrapper', navigation._current);
		}
	});
	document.observe('item:loaded', function() {
		item.fadeIn();
	});
	document.observe('item:changed', function() {
		item.showDetails();
	});
}

document.observe('dom:loaded', function() {
	init();
})
