/* Main Portfolio Class */
var Portfolio = {
	
	dataURL: 'proxy/proxy.php?yws_path=' + encodeURIComponent('services/rest/?method=flickr.photosets.getPhotos&api_key=72a5b081f359ffb09ebedd2f4dd2205b&format=json&photoset_id=72157594293629858&privacy_filter=1'), 
	photos: [],
	
	initialize: function(){
		this.rootEl = $('photos-list');
		
		this.loaderFx = new Fx.Morph('loader', {
			duration: 'normal', 
			transition: Fx.Transitions.easeOut
		});
		
		this.loadCollection(this.dataURL);
		this.registerEvents();
	},
	
	loadCollection: function(url){
		new Request({
			url: url, 
			method: 'get', 
			onSuccess: function(transport){
				this.build(JSON.decode(transport.replace('jsonFlickrApi(','').replace('})', '}')));
			}.bind(this)
		}).send();
	},
	
	build: function(data){
		var layout = (Browser.Engine.webkit) ? $$('html, body') : $$('body');
		$('container').setStyle('width', data.photoset.total * 150 + document.getSize().x);
		layout.setStyle('width', data.photoset.total * 150 + document.getSize().x + $('container').getPosition().x);
		data.photoset.photo.each(function(photo, idx){
			this.photos[idx] = new Photo(photo, idx);
			this.photos[idx].build().inject(this.rootEl);
			this.photos[idx].loadThumb();
		}.bind(this));
		
		/* Checking for all thumbs are already loaded to start showing them */
		this.fn = function() {
			if(!this.checkAllThumbsLoaded())
				this.checkAllThumbsLoaded();
			else {
				$clear(this.checker);
				this.rootEl.fireEvent('thumbs:loaded');
				this.thumbsLoaded = true;
				window.scrollTo(0,0);
			}
		};
		this.checker = this.fn.periodical(100, this);
	},
	
	checkAllThumbsLoaded: function(){
		return this.photos.every(function(photo){
			return photo.thumbLoaded;
		});
	},
	
	closeAllOpened: function(){
		if(this.currentPhoto && this.currentPhoto.opened)
			this.currentPhoto.close();
	},
	
	registerEvents: function(){
		
		$('link-to-home').addEvents({
			'click': function(event) {
				event.stop();
				this.blur();
				Portfolio.closeAllOpened();
				$clear(Portfolio.slideshow);
				new Fx.Scroll(window, {
					wheelStops: false
				}).toLeft();
			},
			'mouseover': function(event) {
				this.getElement('em').set('text', '<');
			},
			'mouseout': function(event) {
				this.getElement('em').set('text', '>');
			}
		});
		
		document.addEvent('mousewheel', function(event){
			$clear(Portfolio.slideshow);
		});
	
		document.addEvent('keydown', function(event){
			if (event.key == "right") {
				event.stop();
				this.stopSlideshow();
				this.move(1);
			} else if(event.key == "left") {
				event.stop();
				this.stopSlideshow();
				this.move(-1);
			} else if(event.key == "space") {
				event.stop();
				if(!this.slideshowRunning){
				  this.slideshowForceStop = false;
				  this.startSlideshow();
				} else
					this.stopSlideshow();
			} else if(event.key == "esc") {
				event.stop();
				if(this.currentPhoto) {
					this.currentPhoto.close();
					if(this.slideshowRunning) this.stopSlideshow();
				}
			}
		}.bindWithEvent(this));
		
		this.rootEl.addEvent('thumbs:loaded', function(event){
			this.animate();
		}.bindWithEvent(this));
	},
	
	move: function(dir){
		var index = ((this.currentPhoto) ? this.currentPhoto.index : -1) + dir;
		
		if(index < 0 && dir < 0)
			index = this.photos.length - 1;
		else if(index > (this.photos.length - 1) && dir > 0)
			index = 0;
			
		this.closeAllOpened();
		this.photos[index].open();
	},
	
	animate: function(){

		this.loaderFx.start({opacity: 0}).chain(function(){
			this.photos.each(function(photo, i){
				photo.link.removeClass('hidden');
			});
			
			$('photos-list').set('style', {'display': 'block'});
			
			var mySlide = new Fx.Slide('photos-list', {
				mode: 'horizontal',
				wrapper: $('container'),
				duration: 1500, 
				transition: Fx.Transitions.Bounce.easeOut
			}).hide().slideIn().chain(function(){
				$('photos-list').getParent().setStyles({
					'overflow':'visible',
					'width':'auto'
				});
			});
			
		}.bind(this));
		this.startSlideshow();
	},
	
	startSlideshow: function(){
		// Starting a slideshow by default. Direction - right.
		this.slideshow = this.move.periodical(5000, this, 1);
		this.slideshowRunning = true;
	},
	
	stopSlideshow: function(){
		$clear(this.slideshow);
		this.slideshowRunning = false;
	}
};

var Photo = new Class({
	
	initialize: function(data, idx){
		this.data = data;
		this.index = idx;
		//return this.build(data);
	},
	
	build: function(){
		this.image = new Element('img', {
			src: 'images/blank.gif',
			alt: this.data.title
		});
		this.link = new Element('a', {
			href: '#',
			title: this.data.title,
			'class': 'hidden',
			styles: {
				opacity: 0.5
			},
			events: {
				'click': this.toggle.bindWithEvent(this),
				'mouseover': function(e){
					this.set('morph', {duration: 'short', transition: Fx.Transition.easeIn });
					this.morph({ opacity: 1 });
				},
				'mouseout': function(e){
					if(!this.hasClass('_extended')) {
						this.set('morph', {duration: 'long', transition: Fx.Transition.easeOut });
						this.morph({ opacity: 0.35 });
					}
				}
			}
		});
		this.title = new Element('span', {
			'class': 'title',
			'text': this.data.title
		});
		this.li = new Element('li', {
			'class': 'photo'
		});
		
		this.toggleEffect = new Fx.Morph(this.link, {duration: 500, transition: Fx.Transitions.Sine.easeOut});
		
		return this.li.adopt(this.link.adopt([this.image, this.title]));
	},
	
	toggle: function(event){
		event.stop();
		this.link.blur();
				
		// Closing opened image
		Portfolio.closeAllOpened();
		
		// Stopping slideshow
		Portfolio.stopSlideshow();
		Portfolio.slideshowForceStop = true;
		
		// Toggle clicked photo
		if(this.link.hasClass('_extended')) 
			this.close();
		else
			this.open();
	},
	
	open: function(){
		if(Portfolio.slideshowRunning) {
			Portfolio.stopSlideshow();
			var slideshow = true;
		}
			
		Portfolio.loaderFx.start({opacity: 0.5});
		
		var oldimg = this.image;
		this.image = this.load(this.data, '', function(image){
			Portfolio.loaderFx.cancel().start({opacity: 0});
			if(slideshow && !Portfolio.slideshowForceStop) Portfolio.startSlideshow();
			
			this.image = image.replaces(oldimg);
							
			Portfolio.currentPhoto = this;
			this.link.addClass('_extended');
			this.opened = true;
			
			this.toggleEffect.set({
				background: 'white'
			}).start({
				'width': image.getSize().x,
				'height': image.getSize().y,
				'margin-top': -(image.getSize().y / 2 - 50),
				'padding-bottom': '28px',
				'border-width': '12px',
				'opacity': 1,
				'z-index': 100
			}).chain(function(){
				this.scrollFx = new Fx.Scroll(window, {
					wheelStops: false,
					offset: { x: - ((document.getSize().x - this.image.getSize().x) / 2) }
				}).toElement(this.link);
			}.bind(this));
		}.bind(this));
	},
	
	close: function(){
		this.toggleEffect.cancel().start({
			'width': 140,
			'height': 100,
			'margin-top': 0,
			'padding-bottom': 0,
			'border-width': 0,
			'opacity': 0.35,
			'z-index': 1
		}).chain(function(){
			var oldimg = this.image;
			this.image = this.load(this.data, '_m', function(image){
				this.image = image.replaces(oldimg);
				this.link.removeClass('_extended');
				this.opened = false;
			}.bind(this));
		}.bind(this));
	},
	
	loadThumb: function(data){
		var oldimg = this.image;
		this.image = this.load(data, '_m', function(image){
			this.thumbLoaded = true;
			this.image.replaces(oldimg).getParent().fireEvent('image:loaded');
		}.bind(this));
	},
	
	load: function(data, type, callback){
		return new Asset.image(this.getPhotoURL(this.data, type), { 
			alt: this.data.title,
			onload: callback || $empty
		});
	},
	
	getPhotoURL: function(photoObj){
		var type = arguments[1] || '';
		// type: one of the supported by Flickr image types {smtb}
		// Sample format: http://farm4.static.flickr.com/3102/2799404715_19a4502692_o.jpg
		return 'http://farm' + photoObj.farm + '.static.flickr.com/' + photoObj.server + "/" + photoObj.id + "_" + photoObj.secret + type + '.jpg';
	}
});