/**************************************************************

	Script :
		yyacum_bis.js
		Yyacum yet another carousel using mootools.
		Basic sliding carousel. 
		bis adds a few options to make the images themselves clickable.
	
	Version:
		1.2.1
		
	Dependencies :
		Mootools 1.2 trunk - Element.dimensions, Selectors, Domready, Fx.Transitions, Fx Elements, Assets
		
	Author :
		poudro	 
		
	Licence	: 
		Open Source MIT Licence
		
	Class : 
		yyacum
		This class creates from a chosen set of pictures a carousel that is injected to the container of your choice.
		The set may be created from a list of <img> tags with a certain class on your page or from an array input as an option.
		By default, when you click on the container, it will change the speed/direction of the scrolling depending on where you click.
		You can have as many as you want on one page.
				 
	Arguments : 
		container - the DOM element that will contain the scrolling pictures, requires being in position 
					either absolute or relative
		options - the object containing options, if any
		 
	Options :
		(Formatting is: "option: default", if only a limited number of values are available for that option then it 
			appears as "option: (default|value1|value2...)")
		
		speed: 1 - Sets the speed of the scrolling, with a value of 1 it takes 10 seconds for one picture to scroll 
					the full length of the container. A negative value will make the scrolling go the other way.
		
		direction: ('horizontal'|'vertical') - whether the scrolling is horizontal or vertical.
		
		imgClass: 'yyacum' - class of <img> tags to pick up.
		
		dispose: (false|true) - If set to true, will remove from the DOM the img tags with class imgClass after construction of 
									the carousel.

		clickable: (true|false) - Enable mouse interaction. If enabled, a click on the container will change the current speed.
									Close to the center will be slow, close to the edges will be fast, position of the click relative
									to the center will make it go one way or the other.
		
		maxSpeed: 5 - Maximum speed attainable by clicking.
		
	 	inputArray: [] - Array style input if tags are not wanted. the imgAnchors options cannot be used with this option.
	 	 
	 	imgAnchors: (false|true) - If set to true, takes precedence over option 'clickable' and is incompatible with 'inputArray', 
	 								makes images in carousel clickable, the click brings to the href of the Parent anchor.
	 	                            (syntax: <a href="big/img.jpg"><img src="small/img.jpg" alt="text"></a>).
	 	                            
	 	legend: (false|true) - If set to true, requires imgAnchors, adds a legend which is taken from the alt property of the img.
	 	
	 	
		
	Examples: 
		1- In your <head> :			
					window.addEvent('domready',function(){
						var carousel = new yyacum('container',{dispose:true, clickable:false, speed:-1});
					});
		In your <body> :
					<div id="container" style="position:relative;width:80%;height:50px;"></div> 
 					<img src="pic1" class="someclass1 someclass2 yyacum" />
 					<img src="pic2" class="someclass1 someclass2 yyacum" />
 					<img src="pic3" class="someclass3 someclass4 yyacum" />
  					<img src="pic4" class="someclass2 someclass4" />
			
 			-->  pictures pic1, pic2 and pic3 will be injected into the carousel and removed from the DOM but not picture4.

 		2- In your <head> :	
					window.addEvent('domready',function(){
						var carousel = new yyacum('container',{inputArray:['pic1','pic2','pic3'], speed:1, direction:'vertical'});
					});
			In your <body> :
					<div id="container" style="position:relative;width:50px;height:80%;"></div> 
 			
 			-->  pictures pic1, pic2 and pic3 will be injected into the carousel though were never present in the DOM as such.


**************************************************************/

var carousel = new Class ({
	Implements : Options,

	options: {
		speed: -3,
		maxSpeed: 10,
		imgClass: 'carousel',
		direction: 'horizontal',
		clickable: true,
		inputArray: [],
		dispose: false,
		imgAnchors: false,
		legend: false
	},

	initialize: function(contDiv, options) {
		var i;
		this.setOptions(options);

		this.contDiv = $(contDiv);
		this.contDiv.setStyle('overflow','hidden');
		this.contDivWidth = this.contDiv.getCoordinates().width;
		this.contDivHeight = this.contDiv.getCoordinates().height;

		this.cloneDiv = [];
		this.cloneDiv[0] = new Element('div', {'styles':{'display':'block','position':'absolute','left':0,'top':0}}).inject(this.contDiv);

		if(this.options.legend){
			this.legend = new Element('div',{'styles':{'position':'absolute','color':'white','background-color':'black','padding':10,'opacity':0.75}});
			//this.legend = new Element('div');
		}

		switch (this.options.direction) {
			case 'vertical':
				this.divDim1='width';	
				this.divDim2='height';
				this.divPos='top';
				this.contDivRefCoord = this.contDivHeight;
				break;
			default:
				this.divDim1='height';	
				this.divDim2='width';
				this.divPos='left';
				this.contDivRefCoord = this.contDivWidth;
				break;
		}
		this.cloneDiv[0].setStyle(this.divDim1,this.contDivHeight);

		this.ourLeft = 0;
		this.divWidth = 0;

		if (this.options.inputArray.length != 0)
			this.injectImgViaAssets();
		else
			this.injectImgViaTags();
	},
	
	moveOpts: function() {
		if (this.options.speed<0)
			this.sign = -1;
		else
			this.sign = 1;
		this.timeStep=100000*this.divWidth/(Math.abs(this.options.speed)*this.contDivRefCoord);
	},
	
	drawCarousel: function () {
		if ($('spnLoading')){
			$('spnLoading').style.cssText = "display:none;";
		}

		var i,nextPos;
		this.nextMove = {};
		this.numClones = 3+Math.ceil(this.contDivRefCoord/this.divWidth);
		for (i=1; i<this.numClones; ++i) 
			this.cloneDiv[i] = this.cloneDiv[0].clone().setStyle(this.divPos,this.cloneDiv[i-1].getCoordinates(this.contDiv)[this.divPos]+this.divWidth).inject(this.contDiv);

		this.innerImages = $$('#'+ this.contDiv.id + ' img'); 
		this.innerImages.each(function(image){image.set('opacity',1)});
		this.innerImages.set('morph',{link:'cancel'});

		this.moveOpts();
		this.cloneFx = new Fx.Elements(this.cloneDiv,{duration:this.timeStep,transition:'linear',link:'cancel'});
		this.setFxToPos();
		if (this.options.clickable)
			this.onClickDo();
		if (this.options.imgAnchors)
			this.contDiv.addEvents({
				'mousemove': function(ev){
					var IE6 = false /*@cc_on || @_jscript_version <= 5.7 @*/;
					var aryWindowSize = getWindowSize();
					width = aryWindowSize['width'];

					$clear(this.carousel_p);
					var target = $(ev.target);
					var index = this.innerImages.indexOf(target);
					this.innerImages.morph({opacity:0.5});
					$$('.hoverStateOff').each(function(elem){
						elem.removeClass('hoverStateOff');
						//elem.morph('.hoverState');
						elem.addClass('hoverState');
					});/**/

					/***************************************************/
//					if (IE6){
//						this.innerImages.filter = 'alpha(opacity=50)';
//					}
//					this.innerImages.opacity = 0.5;
//					this.innerImages.store('opacity', 0.5);
					/***************************************************/

					$$('#containera img').each(function(el){
						if (!IE6){
							//el.src = el.src.replace("-75-shadow.png","-75.jpg");
							//el.src = el.src.replace("-202-shadow.png","-202.jpg");
						}
					});
					$$('.faderLeft').each(function(elem){
						elem.morph({opacity:1});
					});/**/
					$$('.faderRight').each(function(elem){
						elem.morph({opacity:1});
					});/**/
					//$('.faderLeft').morph({opacity:1});
					if (index != -1) {
						//alert(Browser.Engine.trident);
						this.innerImages[index].morph({opacity:1});

						if (!IE6){
							//this.innerImages[index].src = this.innerImages[index].src.replace("-75.jpg","-75-shadow.png");
							//this.innerImages[index].src = this.innerImages[index].src.replace("-202.jpg","-202-shadow.png");
						}

						if (document.getElementById('detailWrap')){
							var imgindex = (index-2);
							while (imgindex>(tempgallery.length-1)){
								imgindex = (imgindex-tempgallery.length);
							}
							if (tempgallery[imgindex][4]==0){
								$$('.supportingInfo').each(function(elem){
									elem.style.display = "";
								});
								$('ddOriginalPrice').innerHTML=tempgallery[imgindex][1];
								$('ddSalePrice').innerHTML=tempgallery[imgindex][2];
							}
							else{
								$$('.supportingInfo').each(function(elem){
									elem.style.display = "none";
								});
							}
							$('paintingTitle').innerHTML=tempgallery[imgindex][0];
							$('paintingInfo').innerHTML=tempgallery[imgindex][5];
							$('ddPaintingInformation').innerHTML=tempgallery[imgindex][3];
							$$('.hoverState').each(function(elem){
								elem.removeClass('hoverState');
								//elem.morph('.hoverStateOff');
								elem.addClass('hoverStateOff');
							});/**/
						}
					}
					this.cloneFx.pause();
					if (this.options.legend&&(target.match('img'))&&(this.legends.get(target.src)!='')){
						var id = this.legends.get(target.src);
						/*
if (id!=null){
							while (id.indexOf(" ")>0){
								id = id.replace(" ","");
							}
							while (id.indexOf("'")>0){
								id = id.replace("'","");
							}
							//alert('['+ev.page.x+']['+width+']');
							if ((ev.page.x+175)>width){
								//alert(this.legend.style.width)
								//left = ev.page.x+15;
								left = (width-175);
							}
							else{
								left = ev.page.x+15;
							}
							alert(id);
							this.legend.set('html',$(id).innerHTML).setStyles({'top':ev.page.y+15,'left':left}).inject(document.body);
							this.legend.set('id','SweetBerryWine');
						}
*/
					}
					if (this.options.legend&&this.legends.get(target.src)=="")
						this.legend.dispose();
				}.bind(this),
				'mouseleave': function(){
					this.innerImages.morph({opacity:1});
					$$('.hoverStateOff').each(function(elem){
						//elem.morph('.hoverState');
						elem.removeClass('hoverStateOff');
						elem.addClass('hoverState');
					});/**/
					$$('#containera img').each(function(el){
						var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
						if (IE6){
							//el.src = el.src.replace("-75-shadow.png","-75.jpg");
							//el.src = el.src.replace("-202-shadow.png","-202.jpg");
						}
					});
					$$('.hoverStateOff').each(function(elem){
						//elem.morph('.hoverState');
						elem.removeClass('hoverStateOff');
						elem.addClass('hoverState');
					});
					if (this.options.legend)
						this.legend.dispose();
					this.cloneFx.resume().chain(function(){this.moveCarousel()}.bind(this));
				}.bind(this),
				'click': function(ev){
				
				
					var target = $(ev.target);
					if (target.match('img')&&(this.anchors.get(target.src)!=''))
						
					//	alert(this.anchors.get(target.src));
						Mediabox.open(target.src, '', '');
						
//						bgContainer = $('genCnt');
						/*
bgElem.style.display = 'block';
						bgContainer.style.display = 'block';
*/
						//window.location.href = this.anchors.get(target.src);
				}.bind(this)
			});

		if (document.getElementById('detailWrap')){
			var imgindex = 0;
			if (tempgallery[imgindex][4]==0){
				$$('.supportingInfo').each(function(elem){
					elem.style.display = "";
				});
				$('ddOriginalPrice').innerHTML=tempgallery[imgindex][1];
				$('ddSalePrice').innerHTML=tempgallery[imgindex][2];
			}
			else{
				$$('.supportingInfo').each(function(elem){
					//elem.morph({opacity:0});
					elem.style.display = "none";
				});
			}
			$('paintingTitle').innerHTML=tempgallery[imgindex][0];
			$('paintingInfo').innerHTML=tempgallery[imgindex][5];
			$('ddPaintingInformation').innerHTML=tempgallery[imgindex][3];
		}

		if ($('FastForward')){
			$('FastForward').addEvent('mouseover', function(ev) {
				ev = new Event(ev).stop();
				this.options.speed=-20;
				this.changeOpts();
			}.bind(this));
			$('FastForward').addEvent('mouseout', function(ev) {
				ev = new Event(ev).stop();
				this.options.speed=-3;
				this.changeOpts();
			}.bind(this));
		}

		if ($('Reverse')){
			$('Reverse').addEvent('mouseover', function(ev) {
				ev = new Event(ev).stop();
				this.options.speed=(this.options.speed*-1);
				this.changeOpts();
			}.bind(this));
		}

		if ($('FastReverse')){
			$('FastReverse').addEvent('mouseover', function(ev) {
				ev = new Event(ev).stop();
				this.options.speed=20;
				this.changeOpts();
			}.bind(this));
			$('FastReverse').addEvent('mouseout', function(ev) {
				ev = new Event(ev).stop();
				this.options.speed=3;
				this.changeOpts();
			}.bind(this));
		}

		this.moveCarousel();
	},
	
	moveCarousel: function(){
		this.setFxStartPos();
		this.cloneFx.start(this.nextMove);
		this.carousel_p = (function () {
			this.setFxStartPos();
			this.cloneFx.start(this.nextMove);
		}).periodical(this.timeStep, this);
	},

	setFxStartPos: function(){
		for (i=0; i<this.numClones; ++i) 
			this.cloneDiv[i].setStyle(this.divPos,(i-1)*this.divWidth);	
	},
	
	setFxToPos: function(){
		var nextPos;
		for (i=0; i<this.numClones; ++i) {
			nextPos = (i-1+this.sign)*this.divWidth;
			if (this.options.direction=='vertical')
				this.nextMove[i] = {'top': nextPos};
			else
				this.nextMove[i] = {'left': nextPos};
		}
	},
	
	changeOpts: function(){
		if (this.carousel_p)
			this.carousel_p = $clear(this.carousel_p);
		this.cloneFx.cancel();

		var currentLocation = this.cloneDiv[0].getCoordinates(this.divCont)[this.divPos];
		this.moveOpts();
		this.setFxToPos();
		this.cloneFx.options.duration = Math.abs(this.timeStep*(currentLocation-(this.sign-1)*this.divWidth)/(this.sign*this.divWidth));
		this.cloneFx.start(this.nextMove).chain(function(){this.cloneFx.options.duration = this.timeStep; this.moveCarousel();}.bind(this));
	},
	
	injectImgViaTags: function() {
		this.imagesLoaded_p = (function () {
			var i,h,w,toAdd;
			var newImg = Array();

			this.loaded = 0;
			$each(document.images, function(img,ind) {
				if (document.images[ind].complete)
					++this.loaded;
			}, this);

			if (this.loaded==document.images.length) {
				$clear(this.imagesLoaded_p); 
				this.images = $$('img.'+this.options.imgClass);
				this.anchors = new Hash();
				this.legends = new Hash();
				if (this.images.length != 0) {
					for (i=0; i<this.images.length; ++i) {
						var imageCoords = this.getImageCoords(this.images[i],i);
						if (this.options.imgAnchors)
							this.anchors.set(this.images[i].src,this.images[i].getParent());
						if (this.options.legend)
							this.legends.set(this.images[i].src,this.images[i].alt);
						newImg[i] = new Asset.image(this.images[i].src)
							 .inject(this.cloneDiv[0]).setStyles({'float':'left','height':imageCoords.h, 'width':imageCoords.w -3,'padding-left' :'25px','padding-right' :'25px', 'left':0})
							 .setStyle(this.divPos,this.ourLeft);
						this.grow(imageCoords.toAdd);
						this.grow(50);
						if (this.options.dispose)
							this.images[i].destroy();
					}
					//this.grow(-20);
					this.drawCarousel();
				}
			}
		}).periodical(50,this);					
	},
	
	injectImgViaAssets: function () {
		var asset_images = [];
		new Asset.images(this.options.inputArray, {
			onProgress: function (ind) {
				asset_images[ind]=this;				
			},
			
			onComplete: (function () {
				asset_images.each(function(image,ind){
					var imageCoords = this.getImageCoords(image,ind);
					image.inject(this.cloneDiv[0]).setStyles({'position':'absolute', 'height':imageCoords.h, 'width':imageCoords.w, 'left':0}).setStyle(this.divPos,this.ourLeft);
					this.grow(imageCoords.toAdd);
				},this)
				this.drawCarousel();				
			}).bind(this)
		});
	},
					
	getImageCoords: function(image,ind) {				
		var h,w,toAdd;
		if (this.options.direction=='vertical') {
			w=this.contDivWidth;
			h=w*image.height/image.width;	
			toAdd=h;
		} else {
			//h=this.contDivHeight;
			h=image.height;
			w=h*image.width/image.height;	
			toAdd=w;
		}
		return {'w':w, 'h':h, 'toAdd':toAdd};
	},

	grow: function(toAdd) {
		this.cloneDiv[0].setStyle(this.divDim2,this.divWidth+toAdd);
		this.divWidth = this.cloneDiv[0].getCoordinates(this.contDiv)[this.divDim2];
		this.cloneDiv[0].setStyle(this.divPos,-this.divWidth);
		this.ourLeft += toAdd;
	},

	onClickDo: function(){
		this.contDiv.addEvent('click', function(ev) {
			ev = new Event(ev).stop();
			var l,r;
			l=this.contDiv.getCoordinates()[this.divPos];
			r=l+this.contDivRefCoord;
			if (this.options.direction=='vertical')
				this.options.speed=(2*(ev.client.y-l)/(r-l)-1)*this.options.maxSpeed;
			else
				this.options.speed=(2*(ev.client.x-l)/(r-l)-1)*this.options.maxSpeed;
			this.changeOpts();
		}.bind(this));
	}		
});

function getWindowSize() {
	//alert('hit');
	var myWidth = 0, myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	var ary = [];
	ary['width'] = myWidth;
	ary['height'] = myHeight;
	return ary;
}

