// JavaScript Document

var settings = {
	slideshow: true,
	fade: true,
	loop: true,
	zoom: true
}

var Flickr = new Class({

	initialize: function(key) {
		this.base = 'http://api.flickr.com/services/rest/'
//		this.key = key || 'f18494061e5117b577caf0ad27b19d9c'
		this.key = key || '5b82e96a73edb257e7ecfeef1523775f'
	},

	request: function(method, arguments) {
		var url = this.base + '?method=' + method + '&api_key=' + this.key + '&format=json'
		arguments.each(function(argument, index) {
			url += '&' + argument.name + '=' + argument.value
		})
		return url;
	}

});

var slideshow = false
var lastCategory = false

var photo = false
var flickr = new Flickr()


var sets = {
	home: '72157603769201839',
	new_items: '72157603551434070',
	scarves: '72157603556179773',
	mohair_scarves: '72157603665292549',
	chenille_scarves: '72157603660792608',
	garments: '72157603665248049',
	jackets: '72157603555954525',
	pins: '72157603637534717',
	necklaces: '72157603660672338',
	fancy_hats: '72157603677182988',
	cottage: '72157603792223541',
	archive: '72157623114636947'
}

var links = {}

function initSlideshow(categories) {

	/* Fix IE6 CSS bug */

	if (window.ie6) {$('content').setStyle('overflow', 'hidden')}

	/* Because the Flickr API does not allow JavaScript callbacks with brackets (in this case,
	to call a method of an object in an array, i.e. collection[2].evaluate()), the only dynamic
	option was to use the eval() function to dynamically create global variables names
	'collection0', 'collection1', 'collection2', etc. */

	var loopCode = "lastCategory = 'collection" + (categories.length-1) + "';"

	categories.each(function(category, index){
		loopCode += "collection" + index + " = new Collection(categories["+index+"].set, 'collection"+index+"', categories["+index+"].show);collection"+index+".retrieve();"
	})

	eval(loopCode)
}


var Collection = new Class({

	initialize: function(set, name, show) {

		this.set = set
		this.name = name
		this.index = 0
		this.show = show
		this.response = false
		this.info = false

	},

	retrieve: function() {

		var photosURL = flickr.request('flickr.photosets.getPhotos', [{name: 'photoset_id', value: this.set}, {name: 'per_page', value: '18'}, {name: 'extras', value: 'original_format'}, {name: 'jsoncallback', value: this.name+'.evaluate'}])
		var infoURL = flickr.request('flickr.photosets.getInfo', [{name: 'photoset_id', value: this.set}, {name: 'jsoncallback', value: this.name+'.evaluateInfo'}])

		if (!this.response) {
			new Asset.javascript(photosURL)
			new Asset.javascript(infoURL)
		}
	},

	evaluate: function(response) {
		this.response = response
		this.inject()
	},

	evaluateInfo: function(response) {
		this.description = response
		this.injectInfo()
	},

	injectInfo: function() {
		var response = this.description
		var description = new Element('div', {'class': 'description'})
		var title = new Element('h4')
		var content = new Element('p')

		title.appendText(response.photoset.title._content.capitalize())
		content.appendText(response.photoset.description._content)

		description.adopt(title).adopt(content)

		if ($(this.name) && !($('sidebar').getElement('.static'))) {
			description.inject($(this.name).getParent())
		}
	},

	inject: function() {

		var container = new Element('div', {'class': 'thumbs', 'id': this.name})
		var list = new Element('ul')
		var static = $('sidebar').getElement('.static')

		var response = this.response.photos || this.response.photoset

		for (index=0; index<response.photo.length; index++) {
			var photo = response.photo[index]

//			var thumb = 'http://farm' + photo.farm + '.static.flickr.com/'  + photo.server + '/' + photo.id + '_' + photo.secret + '_m.jpg'
			var thumb = 'http://farm' + photo.farm + '.static.flickr.com/'  + photo.server + '/' + photo.id + '_' + photo.secret + '_t.jpg'

			var title = (photo.title.length <= 20) ? photo.title.capitalize() : (photo.title.substr(0, 20) + '...').capitalize()

/* For some reason, IE6 has a problem with the <span> inside the <a> */

			var item = new Element('li').adopt(new Element('a', {href: '#', title: photo.title.capitalize(), 'events' : {'mousedown' : this.display.bind(photo)}}))

			if (!window.ie6) {
				item.getElement('a').adopt(new Element('span').appendText(title))
			}

			item.setStyle('background-image', 'url(' + thumb + ')')
			if (index >= this.show) {item.addClass('hidden')}
			item.inject(list)
		}


		list.inject(container)



		if (static) {
			container.inject(static, 'before')
		}
		else {
			container.inject($('sidebar'))
		}

		list.setStyles({
			'height' : list.getSize().size.y + 'px',
			'overflow' : 'hidden'
		})

		var hidden = list.getElements('li.hidden')
		for (i=0; i<hidden.length; i++) {
			hidden[i].removeClass('hidden')
		}


		if (response.photo.length > this.show) {
			new Element('p').adopt(new Element('a', {href: '#', 'class' : 'sideButton', 'events' : {'mousedown' : this.expand.bindWithEvent(this)}}).appendText('Click here for more images...')).inject(list, 'after')
		}

		if (this.description && !static) {
			this.injectInfo()
		}

		if (this.name == lastCategory) {
			slideshow = new Slideshow(this, {})
			if (settings.slideshow) {
				slideshow.start()
			}
		}

	},

	test: function(event) {
		alert(event.target)
	},

	expand: function(event) {
		var thumbs = $(this.name).getElement('ul')

		if (thumbs) {

			thumbs.setStyles({
				'height' : 'auto',
				'overflow' : 'auto'
			})

			event.target.getParent().remove()

		}
	},

	display: function(event) {

		if (photo.photo != this) {

			if (event) {
				slideshow.stop()
			}

			if ($('zoom')) {
				$('content').getElement('.slide').remove()
				$('zoom').effect('opacity', {duration: 1000, transition: Fx.Transitions.linear, onComplete: function(){if($('zoom')){$('zoom').remove()}}}).start(1,0);
				//$('zoom').remove()
			}

			photo = new Photo(this)
			photo.getInfo()
		}


	},

	fade: function(event) {
//		photo = new Photo(this)
//		photo.fade()
	}


});


var Slideshow = new Class({

	options: {
		loop: settings.loop,
		interval: 3000
	},

	initialize: function(collection, options) {
		this.setOptions(options);
		this.index = 0
		this.playing = false
	},

	start: function() {
		this.index = 0
		this.playing = true
		this.show()
	},

	next: function() {

		var thumbs = $('sidebar').getElements('div.thumbs li a')

		if (this.index+1 >= thumbs.length) {
			if (this.options.loop) {
				this.index = 0
				this.show()
			}
			else {
				this.stop()
			}
		}
		else {
			this.index++
			this.show()
		}
	},

	stop: function() {

		if (crossfade) {
			crossfade.stop()
		}
		if (photo.loading) {
			photo.stop()

			if ($('content').getElement('p.loading')) {
				$('content').getElement('p.loading').remove()
			}
		}

		this.playing = false;
	},

	show: function() {
		if (this.playing) {
			var thumbs = $('sidebar').getElements('div.thumbs li a')
			thumbs[this.index].fireEvent('mousedown')
		}
	}

});

var crossfade = false;


Slideshow.implement(new Options);

var Photo = new Class({

	initialize: function(photoObj) {
		this.photo = photoObj
		this.src = this.getSource()

		this.loading = true
		this.stopped = false
		this.load()
		this.info = false

		this.size = {
			original: {x: false, y: false},
			small: {x: false, y: false}
		}

		crossfade = false
	},

	getSource: function() {
//		var src = 'http://farm' + this.photo.farm + '.static.flickr.com/'  + this.photo.server + '/' + this.photo.id + '_' + this.photo.secret + '.jpg'
//		var src = 'http://farm' + this.photo.farm + '.static.flickr.com/'  + this.photo.server + '/' + this.photo.id + '_' + this.photo.secret + '_b.jpg'
		var src = 'http://farm' + this.photo.farm + '.static.flickr.com/'  + this.photo.server + '/' + this.photo.id + '_' + this.photo.originalsecret + '_o.' + this.photo.originalformat

		return src;
	},

	load: function() {
		if ($('content').getElement('.slide .dropshadow')) {
			var loading = new Element('p', {'class' : 'loading'}).appendText('Loading ' + this.photo.title.capitalize() + '...').inject($('content').getElement('.slide .dropshadow'), 'after')
		}

		var thisPhoto = this

		var img = new Asset.image(this.src, {onload: function(){thisPhoto.display(this)}});

	},

	stop: function() {
		this.stopped = true
	},

	display: function(img) {

		if (!crossfade && !this.stopped) {
			img = this.resize(img, 540)
			this.fade(this.makeSlide(img))
		}

	},

	resize: function(img, maxWidth) {

		img.addClass('offScreen').inject(document.body)
		this.size.original = {x: img.getSize().size.x, y: img.getSize().size.y}

		if (this.size.original.x > maxWidth) {
			this.size.small = {x: maxWidth, y: maxWidth * (this.size.original.y/this.size.original.x)}
			img.setStyles({
				width: this.size.small.x,
				height: this.size.small.y
			})
		}
		else {
			this.size.small = this.size.original
		}

		return img;
	},

	makeSlide: function(img) {

		var slide = new Element('div', {'class' : 'slide'})
		img.setProperty('title', 'Click to Zoom')

		var thisPhoto = this

		if (settings.zoom) {
			img.addEvent('mousedown', this.zoomIn.bindWithEvent(this))
		}
		slide.adopt(new Element('div', {'class' : 'dropshadow'}).adopt(img)).adopt(new Element('h4')).adopt(new Element('p'))

		img.removeClass('offScreen')

		return slide;

	},

	fade: function(slide) {

		if ($('content').getElement('p.loading')) {
			$('content').getElement('p.loading').remove()
		}

		var duration = 1000
		var old = $('content').getElements('.slide')

if (settings.fade) {
		if (old.length == 1) {
			slide.setOpacity(0).addClass('absolute').inject(old[0], 'after')
	
			crossfade = new Fx.Elements($$('div.slide'), {
				duration: duration,
				transition: Fx.Transitions.linear,
				onComplete: this.endFade,
				onCancel: this.cancelFade
			});
	
			crossfade.start({
				//'0': {'opacity': [1, 0]},
				'1': {'opacity': [0, 1]}
			});

		}
		else {
			if (old.length > 1) {
				for (i=0; i<old.length; i++) {
					old[i].remove()
				}
			}

			slide.setOpacity(0).inject($('content'), 'top')

			crossfade = new Fx.Style(slide, 'opacity', {
				duration: duration, 
				transition: Fx.Transitions.linear,
				onComplete: this.endMultiFade
			});
	
			crossfade.start(0, 1);

		}
}
else {
			$('content').empty()
			slide.inject($('content'), 'top')
			if (slideshow.playing) {slideshow.next.delay(slideshow.options.interval, slideshow)}
}

		if (this.info) {
			this.injectInfo(slide)
		}
		this.loading = false

	},


	endFade: function() {

		$('content').getElements('div.slide')[1].removeClass('absolute')
		$('content').getElement('div.slide').destroy();

		crossfade = false

		if (slideshow.playing) {slideshow.next.delay(slideshow.options.interval, slideshow)}
	},

	cancelFade: function() {
		$('content').getElement('div.slide').destroy();
		$('content').getElement('div.slide').removeClass('absolute').setOpacity(1)
		crossfade = false
	},

	endMultiFade: function() {
		if (slideshow.playing) {slideshow.next.delay(slideshow.options.interval, slideshow)}
	},

	getInfo: function(name) {
		url = flickr.request('flickr.photos.getInfo', [{name: 'photo_id', value: this.photo.id}, {name: 'secret', value: this.photo.secret}])
		url += '&jsoncallback=photo.evaluate'
		new Asset.javascript(url)
	},

	evaluate: function(response) {
		this.info = response.photo

		if (!this.loading) {
			var img = $('content').getElement('img[src='+this.src+']')

			if (img) {
				this.injectInfo(img.getParent().getParent())
			}
		}

	},

	injectInfo: function(slide) {
		if (!this.stopped) {
			slide.getElement('h4').empty().appendText((this.info.title._content).capitalize())
			slide.getElement('p').empty().appendText(this.info.description._content)
		}
	},

	zoomIn: function(event) {

		slideshow.stop()

		if (this.size.original.x > 540) {
			var click = {x: event.page.x - event.target.getLeft(), y: event.page.y - event.target.getTop()}

			var zoomImg = event.target.clone()
			zoomImg.setStyle('position', 'absolute')

			var zoomWindow = new Element('div', {id: 'zoom'}).setStyles({
				width: this.size.small.x,
				height: this.size.small.y,
				overflow: 'hidden',
				position: 'absolute',
				top: event.target.getTop(),
				left: event.target.getLeft(),
				backgroundColor: '#666'
			}).adopt(zoomImg)

			zoomWindow.addEvent('mousedown', this.zoomOut.bindWithEvent(this)).inject(document.body)

			this.zoom = new Fx.Styles(zoomImg, {duration: 500})
			this.zoom.start({
				'height': [this.size.small.y, this.size.original.y],
				'width': [this.size.small.x, this.size.original.x],
				'left' : [0, (-((click.x/this.size.small.x) * this.size.original.x) + this.size.small.x/2).toInt()],
				'top' : [0, (-((click.y/this.size.small.y) * this.size.original.y) + this.size.small.y/2).toInt()]
			});
		}

	},

	zoomOut: function() {

		this.zoom.start({
			'height': this.size.small.y,
			'width': this.size.small.x,
			'left' : 0,
			'top' : 0
		});
		(function(){$('zoom').remove()}).delay(this.zoom.options.duration)
	}


});
