/**
 * @author Sergey Chikuyonok (gonarch@design.ru)
 * @copyright Art.Lebedev Studio (http://www.artlebedev.ru)
 */

function Panorama(elem, switcher){
	this.ptr = $(elem);
	this.switcher = $(switcher);
	var images = this.ptr.find('img');
	this._drag = false;
	
	
	//find image for current time
	var dt = new Date();
	var time = parseInt(dt.getHours()+''+(dt.getMinutes() < 10 ? '0' : '' ) + dt.getMinutes());
	var img, re = /from(\d+)\s+to(\d+)/;
	
	images.each(function(){
		var cl = this.className;
		var m = re.exec(cl);
		if(m && parseInt(m[1], 10) <= time && parseInt(m[2], 10) >= time){
			img = $(this);
			return;
		}
	});
	
	if(!img)
		img = images.eq(0);
			
	img.removeClass('hidden');
	
	this.can_we_switch = true;
	
	this.autostart = true;
	
	this.auto_tw = null;
	this.auto_timer = null;

	this.fade_duration = 10;

	this.image = {
		ptr: img,
		width: img.attr('width'),
		height: img.attr('height')
	};
	
	if($.browser.msie){
		this.ptr.css("opacity",0).show();
		this.image.width = img.width();
		this.image.height = img.height();
		this.ptr.hide().css("opacity",1);
	}
	
	this.attachEvents();
	this.onResize();
};

Panorama.prototype = {
	/**
	 * Attach draging events
	 */
	attachEvents: function(){
		var me = this;
		var f = function(evt){
			return me.dispatchEvent(evt);
		};

		var f2 = function(){
			return !me._drag;
		};

		this.image.ptr.mousedown(f).bind('load', f);
		$(document).mousemove(f).mouseup(f).bind('dragstart', f2).bind('drag', f2).bind('select', f2);
		$(window).bind('resize', f);

		this.switcher.find('.show').click(function(){ me.show(); }).end().find('.hide').click(function(){ me.hide(); }).css('opacity', 0);
	},

	/**
	 * Event dispatcher
	 * @param {Event} evt
	 */
	dispatchEvent: function(evt){
		switch(evt.type){
			case 'load':
				this.onLoad(evt);
				break;
			case 'mousedown':
				this.onMouseDown(evt);
				break;
			case 'mouseup':
				this.onMouseUp(evt);
				break;
			case 'mousemove':
				this.onMouseMove(evt);
				break;
			case 'resize':
				this.onResize(evt);
				break;
		}
	},

	/**
	 * Get/set panorama image state (if it was loaded or not)
	 * @param {Boolean} state
	 * @return {Boolean}
	 */
	imageLoaded: function(state){
		if(typeof(state) != 'undefined'){
			this._loaded = state;
		}

		return this._loaded;
	},

	/**
	 * Method invoked when panorama image was loaded
	 * @param {Event} evt
	 */
	onLoad: function(evt){
		this.imageLoaded(true);
	},

	/**
	 * Method invoked when user pressed mouse button on panorama image
	 * @param {Event} evt
	 */
	onMouseDown: function(evt){
		//get canvas size
		this._canvas_width = this.ptr.width();

		//update images size
		this.image.width = this.image.ptr.width();

		//set image coordinates to pixels
		this._img_pos = this.image.ptr[0].offsetLeft;
		this.image.ptr.css({left: this._img_pos, right: 'auto'});

		//remember cursor position
		this._drag_start = evt.pageX;

		this.stopAutoRotate();

		this._drag = true;
		evt.preventDefault();
		return false;
	},

	/**
	 * Method invoked when user moves mouse on document
	 * @param {Event} evt
	 */
	onMouseMove: function(evt){
		if(this._drag){
			this.moveTo(evt.pageX - this._drag_start + this._img_pos);
		}
	},

	/**
	 * Method invoked when user releases mouse button
	 * @param {Event} evt
	 */
	onMouseUp: function(evt){
		if(this._drag){
			//make image position in percents
			var pos = this.image.ptr[0].offsetLeft;
			var ex = Math.abs(this._canvas_width - this.image.width);
			if( ex/2 > Math.abs(pos) ){
				//use 'left' property
				this.image.ptr.css({left: (pos / this._canvas_width * 100)+'%', right: 'auto'});
			}
			else{
				//use 'right' property
				this.image.ptr.css({right: (-(pos / this._canvas_width * 100) )+'%', left: 'auto'});
			}
			this._drag = false;
			this.autostart = false;
		}
	},

	onResize: function(evt){
		this._canvas_width = this.ptr.width();
	},

	/**
	 * Move panorama image to specific coordinate
	 */
	moveTo: function(x){
		//удостоверимся, что панорама будет в границах холста
		//$("#header").html("789---" + my.image.width);
		x = Math.min(0, Math.max(this._canvas_width - this.image.width, x));
		this.image.ptr.css("left", x);
	},

	/**
	 * Show panorama image
	 */
	show: function(){
		if(this.can_we_switch){
			var me = this;
			this.can_we_switch = false;
			this.moveTo((this._canvas_width - this.image.width) / 2);
			this.ptr.css({opacity: 0, display: 'block'});
			new Tween(this.ptr, 'opacity', EEQ.linear, 0, 1, this.fade_duration);
			(new Tween(this.switcher.find('.show'), 'opacity', EEQ.linear, 1, 0, this.fade_duration)).onMotionFinished=function(obj){
				$(obj).css({display: 'none'});
				me.can_we_switch = true;
			};
			(new Tween(this.switcher.find('.hide').css('display', 'block'), 'opacity', EEQ.linear, 0, 1, this.fade_duration)).onMotionFinished=function(obj){
				$(obj).css("filter","");
			};
	
			if(this.autostart){
				var me = this;
				this.auto_timer = setTimeout(function(){ me.autoRotate(); }, 3000);
			}
		}
	},

	/**
	 * Hide panorama image
	 */
	hide: function(){
		if(this.can_we_switch){
			var me = this;
			this.can_we_switch = false;
			(new Tween(this.ptr, 'opacity', EEQ.linear, 1, 0, this.fade_duration)).onMotionFinished = function(obj){
				$(obj).css('display', 'none');
				me.can_we_switch = true;
			};
			(new Tween(this.switcher.find('.hide'), 'opacity', EEQ.linear, 1, 0, this.fade_duration)).onMotionFinished=function(obj){
				$(obj).css({display: 'none'});
			};
			new Tween(this.switcher.find('.show').css('display', 'block'), 'opacity', EEQ.linear, 0, 1, this.fade_duration);
	
			this.autostart = false;
			this.stopAutoRotate();
		}
	},

	/**
	 * Automatic panorama rotation
	 * @param {Number} dir Rotation direction (0 - to right, 1 - to left)
	 */
	autoRotate: function(dir){
		dir = dir || 0;

		//считаю расстояние, на которое нужно прокрутить панораму
		this._canvas_width = this.ptr.width();
		var left = this.image.ptr[0].offsetLeft;
		var len = Math.abs((dir) ? left : this.image.width - this._canvas_width + left);

		//длительность анимации считаю в зависимости от расстояния
		var duration = Math.round(len/3);

		var me = this;
		this.auto_tw = new Tween(this.image.ptr, '', EEQ.linear, 0, 1, duration);
		this.auto_tw.onMotionChanged = function(){
			//это нужно для того, чтобы анимация нормально работала при ресайзе окна
			if(dir){
				me.moveTo(left * (1 - this.position));
			}
			else{
				me.moveTo(left - (me.image.width - me._canvas_width + left) * this.position);
			}
		};

		this.auto_tw.onMotionFinished = function(){
			me.autoRotate(!dir);
		}
	},

	stopAutoRotate: function(){
		//stop automatic rotation
		if(this.auto_timer){
			clearInterval(this.auto_timer);
		}
		if(this.auto_tw){
			this.auto_tw.stop();
		}
	}
};

$(function(){
	new Panorama('#panorama', '#panorama-switch');
	$('#tower-sections').find('a').mouseover(function(){$(this).addClass('active')}).mouseout(function(){$(this).removeClass('active')});
});
