var KotoscrollerConfig = {};
function KotoscrollerConfigure(config) {
	KotoscrollerConfig = Object.extend(KotoscrollerConfig,config);
}

var Kotoscroller = Class.create({
	
	workingTime:  0.6,
	
	scroller: null,
	lb: null,
	rb: null,
	
	/**
	 * Ratios of dimensions of images
	 * @type 
	 */
	ratios: [33.2,66.6],
	
	/**
	 * Images list
	 * @type 
	 */
	images: [],
	
	/**
	 * Start poins (this image will show in center)
	 * @type Number
	 */
	startPoint: 2,
	
	zIndexes: [5,6,10,6,5],
	
	lefts: [10.5,25,50,75.5,89.5],
	
	baseWidth: 0, baseHeight: 0, mooving: 0,
	
	/**
	 * Initialize scroller
	 * @param {} scroller
	 */
	initialize: function(scroller) {
		this.scroller = scroller;
		
		this.lb = $$("*[rel='kotoleft']")[0];
		this.rb = $$("*[rel='kotoright']")[0];
		this.initImages();
		this.layout();
		this.activateControls();
	},
	
	/**
	 * Find all images in images div (id=kotoimages), append it to images list 
	 * and fix layout of this images
	 */
	initImages: function() {
		
		bd = this.addImageToList.bind(this);
		$A($('kotoimages').childNodes).each(function(el){
			bd(el);
		});
		this.layoutImages();
	},
	
	/**
	 * Make layout of images
	 */
	layoutImages: function() {
		//получаем размеры скроллера
		scrollerWidth = this.scroller.getWidth();
		scrollerHeight = this.scroller.getHeight();
		
		//устанавливаем свойство самого скроллера
		this.scroller.setStyle({overflow:'hidden'});
		$('kotoimages').setStyle({width:'100%',height:scrollerHeight+'px',position:'relative'});
		
		//TODO: временно скрываем все изображения
		$A(this.images).each(function(im){
			$(im).hide()}
		);
		
		
		//устанаваливаем каждое изображение в нужную точку
		var pm = this.positionImage.bind(this);
		var gim = this.getImageWhithOffset.bind(this);
		
		[-2,-1,0,1,2].each(function(offset){
			pm(gim(offset),offset);
		});
		
		
	},
	
	/**
	 * Set image position to its default
	 */
	positionImage: function(image,offset) {
		
		ratio = ((offset==1 || offset==-1)? this.ratios[1] : (offset==0)? 100 : this.ratios[0])/100;

		newWidth = parseInt(this.baseWidth*ratio);
		newHeight = parseInt(this.baseHeight*ratio);
		
		$(image).setStyle({
			zIndex:this.zIndexes[offset+2],
			position:'absolute',
			top: '50%',
			marginTop: '-'+newHeight/2+'px',
			width: newWidth+'px',
			height: newHeight+'px',
			left: this.lefts[offset+2]+"%",
			marginLeft:'-'+(newWidth/2)+'px'
		});
		
		$(image).show();
		
	},
	
	/**
	 * Get omage whith offset from startPoint
	 * @param {int} offset
	 */
	getImageWhithOffset: function(offset) {
		offset = this.startPoint+offset;
		il = this.images.length;
		if (offset<0) {
			offset = ((nof=(offset%(-1*il)))==0)? 0 : nof+il;
		} else if (offset >= il) {
			offset = offset%il;
		}
		return $(this.images[offset]);
	},
	
	getPositionOf: function(offset) {
		
		positions = {};
		
		kotowidth = $("kotoimages").getWidth();
		kotoheight = $("kotoimages").getHeight();
		
		willImage = this.getImageWhithOffset(-1);
		willWidth = willImage.getWidth();
		willHeight = willImage.getHeight();
		
		leftPos = ((this.lefts[offset]/100)*kotowidth) - (willWidth/2);
		topPos =  (0.5*kotoheight) - (willHeight/2);
			
		positions['left'] = leftPos;
		positions['top'] = topPos;
		
		return positions;
		
	},	
	
	makePositioned: function(image) {
		//сначала что у нас там слева
		ml = parseInt(image.getStyle('marginLeft'));
		setLeft = (parseInt(image.getStyle("left"))/100)*$('kotoimages').getWidth() + ml;
		
		//теперь сверху
		mt = parseInt(image.getStyle('marginTop'));
		setTop = (parseInt(image.getStyle("top"))/100)*$('kotoimages').getHeight() + mt;
		
		image.setStyle({
			marginLeft:0,
			left: setLeft+'px',
			marginTop: 0,
			top: setTop+'px'
		});
		
		return image;
	},
	
	getStylesFor: function(offset) {
		
		ratio = this.getRatio(offset);
		
		if (ratio==0) {
			if (offset<0) {
				return {
					left: $('kotoimages').getWidth()*0.05+'px',
					top: $('kotoimages').getHeight()*0.5+'px',
					width: '1px',
					height: '1px'
				}
			} else {
				return {
					left: $('kotoimages').getWidth()*0.95+'px',
					top: $('kotoimages').getHeight()*0.5+'px',
					width: '1px',
					height: '1px'
				}
			}
			
			
		}
		
		setLeft = parseInt((this.lefts[offset+2]/100)*$('kotoimages').getWidth()-(0.5*this.baseWidth*ratio));
		setTop = parseInt(0.5*$('kotoimages').getHeight()-(0.5*this.baseHeight*ratio));
		
		style = {
			left: setLeft+'px',
			top: setTop+'px',
			width: this.baseWidth*ratio+'px',
			height: this.baseHeight*ratio+'px'
		};
		
		return style;
	},
	
	getRatio: function(offset) {
		
		if (offset > 2 || offset < -2) {
			return 0;
		}
		
		return ((offset==1 || offset==-1)? this.ratios[1] : (offset==0)? 100 : this.ratios[0])/100;
	},
	
	/**
	 * Фиксирует элемент в нужной позиции
	 * @param {} element
	 * @param {} offset
	 */
	stabBack: function(element,offset) {
		if (offset<-2 || offset > 2) {
			element.hide();
		}
		ratio = this.getRatio(offset);
		
		$(element).setStyle({
			top: '50%',
			marginTop: (-1)*(this.baseHeight*ratio/2)+'px',
			left: ((this.lefts[offset+2]==undefined)? 0 : this.lefts[offset+2]) +"%",
			marginLeft: (-1)*(this.baseWidth*ratio/2)+'px',
			zIndex: ((this.zIndexes[offset+2]==undefined)? 0 : this.zIndexes[offset+2])
		});
		this.mooving--;
	},
	
	
	moveImages: function(offset) {
		
		if (this.mooving>0) {
			return false;
		}
		
		//сдвигаем элементы
		if (offset>0) { //сдвигаем влево
			for (e=-2;e<4;e++) {
				this.mooving++;
				
				if (e==3) {
					//последний элемент должен появится
					el = this.getImageWhithOffset(e);
					el.setStyle({
						left: $('kotoimages').getWidth()*0.92+'px',
						top: $('kotoimages').getHeight()*0.5+'px',
						width: '1px',
						height: '1px',
						position: 'absolute',
						marginTop: 0,
						marginLeft: 0
					});
					el.show();
				//	el=null;
				} else{
					el = this.makePositioned(this.getImageWhithOffset(e));
				}
				styles = this.getStylesFor(e-offset);
				
				new Effect.Morph(el,{
					style: styles,
					duration: this.workingTime,
					afterFinish: this.stabBack.bind(this,el,e-offset),
					beforeUpdate: this.needToBeZIndex.bind(this,e-offset)
				});
				
				
			}
		} else { //сдвигаем вправо
			for (e=2;e>-4;e--) {
				this.mooving++;
				if (e==-3) {
					//первый элемент должен появится
					el = this.getImageWhithOffset(e);
					
					el.setStyle({
						left: $('kotoimages').getWidth()*0.08+'px',
						top: $('kotoimages').getHeight()*0.5+'px',
						width: '1px',
						height: '1px',
						position: 'absolute',
						marginTop: 0,
						marginLeft: 0
					});
					el.show();
				} else {
					el = this.makePositioned(this.getImageWhithOffset(e));
				}
				 
				styles = this.getStylesFor(e-offset);
				
				new Effect.Morph(el,{
					style: styles,
					afterFinish: this.stabBack.bind(this,el,e-offset),
					duration: this.workingTime,
					beforeUpdate: this.needToBeZIndex.bind(this,e-offset)
				}); 
			}
		}
		
		this.startPoint+=offset;
	},
	
	/**
	 * Меняет z-index где-то на половине движения
	 */
	needToBeZIndex: function(off,ev) {
		if (ev.currentFrame > ev.totalFrames/2) {
			
			if (off+2<0 || off+2 > 4) {
				$(ev.element).setStyle({
					zIndex: 0
				});
			}
			
			if (this.zIndexes[off+2]!=undefined)  {
				$(ev.element).setStyle({
					zIndex: this.zIndexes[off+2]
				});
			}
		}
	},
	
	moveLeft: function(event) {
		this.moveImages(1);
	},
	
	moveRight: function(event) {
		this.moveImages(-1);
	},
	
	activateControls: function() {
		this.lb.observe("click",this.moveLeft.bindAsEventListener(this));
		this.rb.observe("click",this.moveRight.bindAsEventListener(this));
		
		/*
		if (window.addEventListener) {
		 	window.addEventListener('DOMMouseScroll', this.wheel.bindAsEventListener(this), false);
		}
		window.onmousewheel = document.onmousewheel = this.wheel.bindAsEventListener(this);
		*/
	},
	
	wheel: function(event) {
		/**Is this happen on scroller*/
		event = Event.extend(event);
		if (Event.findElement(event,"#kotoimages")==undefined) {
			return;
		}
		
		if (event.wheelDelta) {
			delta = (window.opera)? event.wheelDelta/-120 : event.wheelDelta/120;
		} else {
			 delta = -event.detail/3;
		}
		
		if (delta!=0) {
			this.accuratyScroll(delta);
			if (event.preventDefault) {
				event.preventDefault();
			} else {
				event.returnValue = false;
			}
        }
	},
	
	
	accuratyScroll: function(delta) {
		this.moveImages(delta);
	},
	
	
	addImageToList: function(element) {
		if (this.baseHeight==0) {
			this.baseHeight=$(element).getHeight();
		}
		if (this.baseWidth==0) {
			this.baseWidth=$(element).getWidth();
		}
		this.images[this.images.length]=element;
	},
	
	layout: function() {
		this.lb.show();
		this.rb.show();
		
		//TODO: это как бы свойства проекта
		$('kotowrapper').setStyle({marginLeft: '54px',marginRight:'54px',overflow:'hidden'});
		
	}
	
	
});

function addHandler(object, event, handler, useCapture) {
 if (object.addEventListener) {
 object.addEventListener(event, handler, useCapture ? useCapture : false);
 } else if (object.attachEvent) {
 object.attachEvent('on' + event, handler);
 } else alert("Add handler is not supported");
} 

function debug(vr) {
	console.log(vr);
}

function initKotoscroller() {
	
	ksc = $$("*[rel='kotoscroller']")[0];
	if (ksc!=undefined) {
		var cat = new Kotoscroller($$("*[rel='kotoscroller']")[0]);
	}
}

document.observe("dom:loaded", function() {
  // initially hide all containers for tab content
  initKotoscroller();
});

//Event.observe(window,'"load"',initKotoscroller);
