var Slideshow = Class.extend({
	init: function(target, reference, stopped, options) {
		var _this = this;
		this.element = $(target);
		this.rotate_manually = this.getIndexByHash() > 0;
		this.stopped = stopped;
		this.reference = $(reference);
		this.slides = this.element.find('img');
		this.contents = this.reference.find('#slides-contents');
		this.controls = this.element.parent().find('.previous-button, .next-button');
		this.currentSlide = 0;
		this.freezed = false;
		this.playing = false;
		
		this.element.find('img').css('display', 'none');
		
		this.detector = new iDetector();
		
		var settings = {
			minWidth: 900,
			minHeight: 430,
			horizontal_center: true,
			vertical_center: true,
			fit_landscape: false,
			fit_portrait: false
		};
		
		this.options = $.extend(settings, options);
		
		if (_this.stopped || _this.rotate_manually) {
			_this.element.find('img').show();
		}
		
		$(document).ready(function() {
			_this.resizeHeader();
			_this.resize();
		});
		
		if (!this.stopped) {
			$(window).bind('hashchange', function() {
				var selectedIndex = _this.getIndexByHash();
				if (selectedIndex >= 0) {
					_this.goTo(selectedIndex, true);
				}
			});
		}
		
		$(window).load(function() {
			_this.resizeHeader();
			if (!_this.stopped || !_this.rotate_manually) {
				_this.bindEvents();
				_this.setupGallery();
			}
			_this.resize();
		});
		
		$(window).resize(function() {
			_this.resizeHeader();
			_this.resize();
		});
	},
	
	bindEvents: function() {
		var _this = this;
		
		$('body').delegate('.previous-button', 'click', function() {
			_this.previous();
		});
		
		$('body').delegate('.next-button', 'click', function() {
			_this.next();
		});
		
//		if (!this.detector.detectAgent()) {
//			$('#header').bind('mouseenter', function() {
//				_this.showControls();
//			});
//			
//			$('#header').bind('mouseleave', function() {
//				_this.hideControls();
//			});
//		} else {
//			this.timerTouchHeader;
//			$('#header').bind('touchstart', function(ev) {
//					clearTimeout(_this.timerTouchHeader);
//					_this.showControls();
//			});
//			
//			$('#header').bind('touchend', function(ev) {
//				_this.timerTouchHeader = setTimeout(function() {
//					if (_this.controlsVisible) {
//						_this.hideControls();
//					}
//				}, 2500)
//			});
//		}
	},
	
	setupGallery: function() {
		var _this = this;
		var indexSelector = this.getIndexByHash();

		if (indexSelector >= 0) {
			this.currentSlide = indexSelector;
			this.element.find('img:eq('+indexSelector+')').show();
			this.getContent();
		} else {
			this.element.find('img').each(function(index) {
				var li = $(this);
				
				if (index != _this.currentSlide) {
					li.css('display', 'none');
				}
				else {
					li.show();
					_this.getContent();
				}
			});
		}

		if (!_this.rotate_manually) {
			this.setupSwicth();
		}
	},
	
	getIndexByHash: function() {
		var selector = window.location.hash ? window.location.hash.replace('#!/', '') : false;
		return selector ? this.element.find('#' + selector).index() : -1;
	},
	
	resize: function() {
		var _this = this;
		this.element.find('img').each(function() {
			_this.slide = $(this);

			_this.headerWidth = _this.reference.width();
			_this.headerHeight = _this.reference.height();
			
			_this.ratio = (_this.slide.height() / _this.slide.width()).toFixed(2);
			
			if ((_this.headerHeight <= _this.options.minHeight) && (_this.headerWidth <= _this.options.minWidth)){
				
				if ((_this.headerHeight/_this.headerWidth) > _this.ratio) {
					_this.options.fit_landscape && _this.ratio <= 1 ? _this.resizeWidth(true) : _this.resizeHeight(true);
				} else {
					_this.options.fit_portrait && _this.ratio > 1 ? _this.resizeHeight(true) : _this.resizeWidth(true);
				}
			
			} else if (_this.headerWidth <= _this.options.minWidth) {
			
				if ((_this.headerHeight/_this.headerWidth) > _this.ratio) {
					_this.options.fit_landscape && _this.ratio <= 1 ? _this.resizeWidth(true) : _this.resizeHeight();
				} else {
					_this.options.fit_portrait && _this.ratio > 1 ? _this.resizeHeight() : _this.resizeWidth(true);
				}
				
			} else if (_this.headerHeight <= _this.options.minHeight) {
			
				if ((_this.headerHeight/_this.headerWidth) > _this.ratio) {
					_this.options.fit_landscape && _this.ratio <= 1 ? _this.resizeWidth() : _this.resizeHeight(true);
				} else {
					_this.options.fit_portrait && _this.ratio > 1 ? _this.resizeHeight(true) : _this.resizeWidth();
				}
			
			} else {
			
				if ((_this.headerHeight/_this.headerWidth) > _this.ratio){
					_this.options.fit_landscape && _this.ratio <= 1 ? _this.resizeWidth() : _this.resizeHeight();
				} else {
					_this.options.fit_portrait && _this.ratio > 1 ? _this.resizeHeight() : _this.resizeWidth();
				}
				
			}
			
			if (_this.options.horizontal_center){
				var left = (_this.headerWidth - _this.slide.width()) / 2;
				if (left <= 0) {
					_this.slide.css('left', left);
				}
			}
			
			if (_this.options.vertical_center){
				var top = (_this.headerHeight - _this.slide.height()) / 2;
				
				if (top <= 0) {
					_this.slide.css('top', top);
				}
			}
			
			$(_this.getFlashObj()).attr('width', Math.max($(window).width(), 1024));
			$(_this.getFlashObj()).attr('height',parseInt($('#header').css('height')));
		});
		
	},
	
	resizeWidth: function(minimum) {
		
		if (minimum){
			if (this.slide.width() < this.headerHeight || this.slide.width() < this.options.minWidth ) {
				if (this.slide.width() * this.ratio >= this.options.minHeight) {
					this.slide.width(this.options.minWidth);
		    		this.slide.height(this.slide.width() * this.ratio);
		    	}else {
		    		this.resizeHeight();
		    	}
		    }
		} else {
			if (this.options.minHeight >= this.headerHeight && !this.options.fit_landscape) {
				if (this.headerWidth * this.ratio >= this.options.minHeight || (this.headerWidth * this.ratio >= this.options.minHeight && this.ratio <= 1)) {
					this.slide.width(this.headerWidth);
					this.slide.height(this.headerWidth * this.ratio);
				} else if (this.ratio > 1) {
					this.slide.height(this.options.minHeight);
					this.slide.width(this.slide.height() / this.ratio);
				} else if (this.slide.width() < this.headerWidth) {
					this.slide.width(this.headerWidth);
		    		this.slide.height(this.slide.width() * this.ratio);
				}
			} else {
				this.slide.width(this.headerWidth);
				this.slide.height(this.headerWidth * this.ratio);
			}
		}
	},
	
	resizeHeight: function(minimum) {
		if (minimum) {
			if (this.slide.height() < this.headerHeight){
				if (this.slide.height() / this.ratio >= this.options.minWidth) {
					this.slide.height(this.options.minHeight);
					this.slide.width(this.slide.height() / this.ratio);
				} else {
					this.resizeWidth(true);
				}
			}
		} else {
			if (this.options.minWidth >= this.headerWidth) {
				if (this.headerHeight / this.ratio >= this.options.minWidth || this.ratio > 1) {
					this.slide.height(this.headerHeight);
					this.slide.width(this.headerHeight / this.ratio);
				} else if (this.ratio <= 1) {
					this.slide.width(this.options.minWidth);
		    		this.slide.height(this.slide.width() * this.ratio);
				}
			} else {
				this.slide.height(this.headerHeight);
				this.slide.width(this.headerHeight / this.ratio);
			}
		}
	},
	
	resizeHeader: function() {
		var browserwidth = $(window).width();
		var browserheight = $(window).height();
		var header = $('#header');
		
		if (this.flashVideoOpened) {
			this.increase();
		}
		
		if (navigator.userAgent.search('iPad') != -1) {
			header.height(551);
		}
		else if (browserwidth < 1024 && !this.flashVideoOpened) {
			header.height(434);
		}
		else if (!this.flashVideoOpened) {
			var calc;
			calc = Math.round(((browserwidth * 434) / 1024).toFixed(2));
			
			header.height(calc);
		}
		
		if (browserwidth <= 900) {
			header.width(900);
		}
		else {
			header.width('auto');
		}
		
		$('#flashcontent').height(header.height());
	},
	
	previous: function() {
		var index;
		
		if (this.currentSlide == 0) {
			index = (this.slides.length - 1);
		} else {
			index = this.currentSlide - 1;
		}
		
		this.goTo(index);
	},
	
	next: function() {
		var index;
		
		if (this.currentSlide == (this.slides.length - 1)) {
			index = 0;
		} else {
			index = this.currentSlide + 1;
		}
		this.goTo(index);
	},
	
	goTo: function(index, hashChange) {
		if (!this.animating) {
			if (this.freezed && !this.rotate_manually) {
				this.setupSwicth();
			}
			
			this.animating = true;
			
			var _this = this;
			
			$(this.slides.get(this.currentSlide)).fadeOut(
				function() {
					_this.currentSlide = index;
					// hide and show top contents
					_this.hideContents();
					_this.showContent();
					
					// hide and show main contents
					_this.hideInfos();
					_this.showInfo();
					
					$(_this.slides.get(_this.currentSlide)).fadeIn(
						function() {
							_this.animating = false;
						}
					);
				}
			);
		}
	},
	
	getContent: function() {
		this.showInfo();
		this.showContent();
	},
	
	showInfo: function() {
		var slide = this.slides.get(this.currentSlide);
		var info = slide.id + '-info';
		$('#' + info).fadeIn();
	},
	
	hideInfos: function() {
		$('.references-list').children().hide();
		if (this.stopped) {
			$('.logo').hide();
		}
		//$('#content-header').hide();
	},
	
	showContent: function() {
		$('.logo').show();
		$('#content-header').show();
		var slide = this.slides.get(this.currentSlide);
		var content = slide.id + '-content';
		$('#' + content).fadeIn();
	},
	
	hideContents: function() {
		var _this = this;
		this.contents.children().each(function() {
			//var info = $('#' + this.id.replace('content', 'info'));
			//info.hide();
			
			var content = $(this);
			content.hide();
			
			var video = content.find('video');
			if (video.length > 0) {
				video.get(0).pause();
				video.get(0).src = "";
				video.get(0).load();
			}
			
			content.find('video, .html-player-video-controls').remove();
			var flashPlayer = _this.getFlashObj();
			if (flashPlayer !== undefined) {
				$(flashPlayer).remove();
			}
			content.find('.description').show();
		});
		
		if (this.playing) _this.toggleNavigationLink();
		
		this.freezed = false;
		this.playing = false;
	},
	
	showControls: function() {
		if(this.contents.children().length > 1) {
			this.controls.each(function() {
				var control = $(this);
				if (control.attr('class').search('previous') >= 0) {				
					control.stop().animate({left: 0});
				}
				else {
					control.stop().animate({right: 0});
				}
			});
			
			this.controlsVisible = true;
			
			if (!this.freezed || !this.rotate_manually) {
				this.stopSlideSwitch();
			}
		}
	},
	
	hideControls: function() {
		this.controls.each(function() {
			var control = $(this);
			if (control.attr('class').search('previous') >= 0) {				
				control.stop().animate({left: - control.width()});
			}
			else {
				control.stop().animate({right: - control.width()});
			}
		});
		
		this.controlsVisible = false;
		
		if (this.freezed && !this.playing && !this.rotate_manually) {
			this.setupSwicth();
		}
	},
	
	setupSwicth: function() {
		if(this.contents.children().length > 1) {
			var _this = this;
			this.freezed = false;
			//this.switchSlidesTimer = setInterval(function() { _this.switchSlide(); }, 10000);
		}
	},
	
	switchSlide: function() {
		var index;
		
		if (this.currentSlide == (this.slides.length - 1)) {
			index = 0;
		} else {
			index = this.currentSlide + 1;
		}
		
		this.goTo(index);
	},
	
	stopSlideSwitch: function() {
		clearInterval(this.switchSlidesTimer);
		this.freezed = true;
	},
	
	getVideoContent: function(target, wmode) {
		this.hideInfos();
		this.showInfo();
		if (!this.stopped) return; // this line its a workaround to disable the video player, need to be removed when the videos are done.
		
		var obj = $(target);
		if (obj.attr('rel')) {
			var contentHeader = $('#content-header');
			var header = $('#header');
			
			var width = contentHeader.width();
			var height = contentHeader.height();
			
			if (this.detector.detectAgent()) {
				var videoSource = $.browser.webkit ? obj.attr('rel') : obj.attr('rel').replace('mp4', 'ogg');
				
				if (this.detector.getDeviceName() == 'iphone') {
					videoSource = videoSource.replace('.mp4', '.m4v');
				}
				
				var html = $('<video src="'+videoSource+'"></video>');
				obj.parent().parent().after(html);
				obj.parent().parent().hide();
				
				this.resizeVideo(html, header.width(), header.height(), false);
				
				var about = $('#' + obj.parent().parent().parent().attr('id').replace('content', 'info')).find('.reference-about').fadeIn();
				var images = $('#' + obj.parent().parent().parent().attr('id').replace('content', 'info')).find('.references-images-list').fadeIn();
				this.toggleNavigationLink();
				
				// stop slide switch
				this.stopSlideSwitch();
				this.playing = true;
				
				html.htmlPlayer({
					alternativeVersions: false,
					autoPlay: true,
					controls: ['play', 'progress'],
					onPlay: function() {
						var controls = obj.parent().parent().parent().find('.html-player-video-controls');
						var diff = (width - controls.width()) / 2;
						controls.css('margin-left', diff);
						controls.fadeIn();
					}
				});
			} else {
				var videoSource = obj.attr('rel').replace('mp4', 'flv');
				var id = "flashVideo";
				obj.parents("#content-header").after('<div id="' + id + '"></div>');
				obj.parent().parent().hide();
				var params = {
					wmode: (wmode || "transparent")
				};
				var flashvars = {
					video: '../' + videoSource,
					blackBars: true,
					uiHeight: -30,
					windowHeight: jQuery(window).height(),
					windowScroll: jQuery(window).scrollTop()
				};
				var attributes = {
					id: "flashcontent",
					name: "flashcontent"
				};
				swfobject.embedSWF("flash_bin/CCVideoPlayer.swf", id, $(window).width(), height, "9.0.124", "flash_bin/expressInstall.swf", flashvars, params, attributes);
				
				// stop slide switch
				this.stopSlideSwitch();
				this.playing = true;
				
				//callback
				jQuery(window).resize(function() {
					jQuery('#' + attributes.id)[0].updateHeight(jQuery(window).height());
				});
				jQuery(document).scroll(function() {
					jQuery('#' + attributes.id)[0].updateScroll(jQuery(window).scrollTop());
				});
			}
		}
	},
	
	resizeVideo: function(element, width, height, fixedTop) {
		if (element.is(':visible')) {
			element.css({
				'width': 'auto',
				'height': 'auto'
			});
			
			
			if (element.width() > element.height()) {
				element.css('height', '100%');
			}
			else {
				element.css('width', '100%');
			}
			
			if (element.width() > width) {
				element.css('margin-left', -(element.width() / 2) + 'px');
				element.css('left', '50%');
			}
			else {
				element.css({
					height: 'auto',
					width: '100%',
					marginLeft: 0,
					left: 0
				});
			}
			
			
			if (element.height() > height && !fixedTop) {
				element.css('margin-top', -(element.height() / 2) + 'px');
				element.css('top', '50%');
			}
			else if (element.height() > height && fixedTop) {
				element.css({
					marginTop: 0,
					top: 0
				});
			}
			else if (element.height() == height) {
				element.css({
					height: '100%',
					width: 'auto',
					marginTop: 0,
					top: 0
				});
			}
			else {
				element.css({
					height: '100%',
					width: 'auto',
					marginTop: 0,
					top: 0
				});
				
				var dif = width - element.width();
				if (dif < 0) {
					element.css('left', dif +'px');
				}
			}
		}
	},
	
	toggleNavigationLink: function() {
		$('.to-top').toggle();
	},
	
	getFlashObj: function(){
		var movie = 'flashcontent';
		if (window.document[movie]) {
			return window.document[movie];
		}
		if (navigator.appName.indexOf("Microsoft Internet")==-1) {
			if (document.embeds && document.embeds[movie]) {
				return document.embeds[movie]; 
			}
		} else {
			return document.getElementById(movie);
		}
	},
	
	increase: function() {
		var header = $('#header');
		if (header.width() > 900) {
			var height = Math.round((header.width()/16)*9);
			this.flashVideoOpened = true;
			$('#header, #flashcontent').height(height);
		}
		this.flashVideoOpened = true;
	},
	
	decrease: function() {
		this.flashVideoOpened = false;
		this.resizeHeader();
		$('#flashcontent').remove();
		$('#slides-contents li:visible').find('.description').show();
		$('.logo').show();
	},
	
	toMenu: function() {
		var header = $('#header');
		var menu = $('.menu');
		var general = $('#general');
		var w = $(window);
		
		var diff = (header.height() - w.height()) + (general.outerHeight(true) - general.innerHeight()) + 10;
		
		if (w.height() < header.height() || (header.height() + diff) > w.height()) {
			$(document).scrollTop(diff + menu.outerHeight(true));
		}
	}
});
