import flash.display.BitmapData;
import mx.transitions.easing.Back;
import mx.transitions.easing.Bounce;
import mx.transitions.easing.Strong;
import mx.transitions.Tween;
import mx.events.EventDispatcher
import templateBook.ToolTip
	  
class modCarousel.Carousel extends MovieClip {
	
var array:Array                                                         //array with date from xml
var container:MovieClip		                                            //container thumbs
var thumbLength:Number                                                  //length thumb
var radiusX:Number                                                      //radius X carousel
var radiusY:Number                                                      //radius Y carousel
var thumbWidth:Number                                                   //thumb Width 
var thumbHeight:Number                                                  //thumb Height
var corner_image:Number                                                 //corner image
var corner_bcg:Number                                                   //corner background
private var speedRotation:Number=0                                      //spped rotation carousel
var tweenSpeedRot:Tween                                                 //tween end rotation (in mouse out)
var blockade:Boolean = false                                            //blockade ( function onMouseMove )
var spaceBcg:Number                                                     //space background
var spaceReflection:Number = 0                                          //space reflection-image
var colorBackground:String                                              //color background
var thumbs:Array                                                        //array with thumbs
var inter_load:Number                                                   //inter load next image
var dispatchEvent:Function                                              //for dispatcher
var nameThumbAttrib:String                                              //nam attributes from load images
var shovReflection:Boolean                                              //shov reflection image ( true / false )
var effectMouseOver:Boolean                                             //effect mouse over ( true / false )
var speedRotateMouseOut:Number                                          //speed rotate carousel if mouse out
var speedRotateMouseOver:Number                                         //speed rotate carousel if mouse over
private var dirRotate:Number = 1                                        //direction rotate
private var deltaX:Number = 0                                           //delta rotation (-1...1)
var spaceVerticalMouseOver:Number                                       //space mouse over - vertical
var spaceHorizontalMouseOver:Number                                     //space  mouse over - horizontal
var containerToolTip:MovieClip                                          //container for toolTip
var toolTip:ToolTip                                                     //instance ToolTip
var colorBackgroundToolTip                                              //color background ToolTip
var widthTooltip:Number                                                 //withToolTip ( optional )
var preloaderColor                                                      //preloader color
var preloaderColorSelect                                                //preloader color if select
var preloaderW:Number=23                                                //preloader width
var preloaderH:Number=23                                                //preloader height
var __stageWidth                                                        //stage width
var __stageHeight                                                       //stage height
var mcArea:MovieClip                                                    //area
var active_title:String                                                 //active title
var color_active                                                        //color for active
		
////////////////////////////////////////////////////////////////////////////////////////////////
		
public function Carousel() 	{   
			EventDispatcher.initialize(this)
			array = []
			thumbs = []
			container = this.createEmptyMovieClip("mcContainer", 1)
			containerToolTip = this.createEmptyMovieClip("toolTipContainer", 2)
}

////////////////////////////////////////////////////////////////////////////////////////////////

function set stageWidth(width_) {
	__stageWidth=width_
	
}

////////////////////////////////////////////////////////////////////////////////////////////////

function get stageWidth():Number {
	if (__stageWidth == "100%") {
		return Stage.width
	}else{
	return __stageWidth
	}
}

////////////////////////////////////////////////////////////////////////////////////////////////

function set stageHeight(height_:Number) {
		__stageHeight = height_
}

////////////////////////////////////////////////////////////////////////////////////////////////

function get stageHeight():Number {
	if (__stageHeight == "100%") {
		return Stage.height
	}else{
	return __stageHeight
	}
}

		
///////////set array date and start//////////////////////////////////////////////////////////////////////////////////

function setDate(array_:Array) {
	array = array_.slice()
	thumbLength = array.length
	speedRotation=speedRotateMouseOut
	createThumb()	
	this.onMouseMove = mouse_move
}
			
/////////////set xml date///////////////////////////////////////////////////////////////////////////////////

function setXml(xml_:XML) {
	var array:Array = getArrayObject(xml_)
	setDate(array)
}

/////////////change xml file to array object/////////////////////////////////////////////////////////////////////////////////

function getArrayObject(date_,node_name) {
	var node_name;
	delete counter
	var counter =new Array();
	var array = new Array();
	var il = date_.childNodes.length;
	for (var i = 0; i<il; i++) {
		var row = date_.childNodes[i];
		if (node_name == row.nodeName || node_name == undefined||node_name==0) {
			var g =counter.push(1)-1
			array[g] = new Object();
			for (var b in row.attributes) {
				var tt = row.attributes[b];
				array[g][b] = tt;
			}
		array[g].child = row;
	}}
	return array;
};

////////////////////////////////////////////////////////////////////////////////////////////////
       
       function onLoad() {
			
	   }
	   
////////////////////////////////////////////////////////////////////////////////////////////////


function mouse_move() {
	          ///////////////////deltaX value [0-1]
			 deltaX += (  (_xmouse / radiusX)   -  deltaX  )
			 
			 if (deltaX > 1) { deltaX = 1}
			 if(deltaX<-1){deltaX=-1}
						 
			 if (_xmouse > 0) {
				 dirRotate=1
			 }else {
				 dirRotate=-1
			 }
			 
			 /////margin rotation
			 var marginX:Number =  spaceHorizontalMouseOver
			 var marginY:Number =  spaceVerticalMouseOver
			
			///////current Radius Mouse 
			var radiusMouse:Number = Math.sqrt (  Math.pow(_xmouse ,2)+Math.pow(_ymouse ,2) )
			 
			 /////////////areaX and areaY
			 var areaX:Boolean =    _xmouse <= (radiusX+thumbWidth/2 + marginX)   &&    _xmouse >= (-radiusX - marginX-thumbWidth/2) 
			 if (radiusY >= 0) {
			 var areaY:Boolean =   ( _ymouse <=(radiusY + marginY+thumbHeight/2) && _ymouse >=( -radiusY -marginY-thumbHeight/2) ) 	 
			 }else{
			 var areaY:Boolean =  ( _ymouse >=-thumbHeight-marginY && _ymouse<-radiusY+marginY+thumbHeight/2 ) 
			 }
			 
		
			 if (areaX&&areaY) {
				  tweenSpeedRot.stop()
			     speedRotation = deltaX * speedRotateMouseOver
			      blockade = false
				 
			}else if (blockade == false) {
				 blockade = true
				 tweenSpeedRot.stop()
				 tweenSpeedRot= new Tween(this,'speedRotation',Strong.easeOut,speedRotation,speedRotateMouseOut*dirRotate,1,true)
			 }
}
	   

//////////////create background//////////////////////////////////////////////////////////////////////////////////

function createBackground(mc_:MovieClip) {
	/*
	var mc:MovieClip=mc_.createEmptyMovieClip("background",-1)
	var w = thumbWidth+spaceBcg*2
	var h = thumbHeight + spaceBcg * 2
	var color = colorBackground.split(",")[0]
	var alpha=colorBackground.split(",")[1]
	mc.beginFill(color,alpha)
	mc.moveTo(0,0)
	mc.lineTo(w,0)
	mc.lineTo(w,h)
	mc.lineTo(0,h)
	mc.lineTo(0, 0)
	/*/
	
	var item = mc_._parent._parent
	var node:XMLNode = item.node
	var title:String=node.attributes.title
	
	var w = thumbWidth+spaceBcg*2
	var h = thumbHeight + spaceBcg * 2
	var color = colorBackground.split(",")[0]
	var alpha = colorBackground.split(",")[1]
	
		Drawing.curve(mc_, w, h, corner_bcg, color, 100);	
		
		
	if (title == active_title) {
		
	 var mc:MovieClip = mc_.createEmptyMovieClip("active", 144);
	 mc._x = 0
	 mc._y = 0
	 Drawing.curve(mc,w, h,corner_bcg,color_active,100,4);
	}
}


////////////create mask for reflection///////////////////////////////////////////////////////////////////////////////////////////////////

function createMaskReflection(item_:MovieClip) {
	    var fillType:String = "linear";
		var colors:Array = [0xFFFFFF, 0xFFFFFF];
		var alphas:Array = [70, 0];
		var ratios:Array = [0, 125];
		var matrix = {matrixType:"box", x:0, y:0, w:thumbWidth, h:thumbHeight, r:(90/180)*Math.PI};
		var _maskReflect:MovieClip = item_.images.containerReflect.createEmptyMovieClip("maskReflection",3)
		_maskReflect.beginGradientFill(fillType, colors, alphas, ratios, matrix, "pad");
		_maskReflect.moveTo(0, 0);
		_maskReflect.lineTo(0, thumbHeight);
		_maskReflect.lineTo(thumbWidth+spaceBcg*2, thumbHeight);
		_maskReflect.lineTo(thumbWidth+spaceBcg*2, 0);
		_maskReflect.lineTo(0, 0);
		_maskReflect.endFill();
		_maskReflect._y = thumbHeight + spaceBcg*2-2
		_maskReflect.cacheAsBitmap = true
		item_.images.containerReflect.image.cacheAsBitmap = true
		item_.images.containerReflect.image.setMask(_maskReflect)
}
	 
/////////////load init thumb///////////////////////////////////////////////////////////////////////////////////

function onLoadInit(target:MovieClip) {
	    target._alpha=0
	    var item:MovieClip = target._parent
		var carousel:Carousel=this
				
		//////select 
		//trace(item.__bcg)
		///NewColor.setColor(item.__bcg, "0xFF0000");
				
		////create mask
		var mask_image:MovieClip = target.createEmptyMovieClip("mc_mask", 2);
		Drawing.curve(mask_image, target._width, target._height,corner_image, 0xFF0000, 60);
		target.setMask(mask_image);
		
		
		/////////remove preloader
		delete item.preloader.onEnterFrame
		item.preloader.removeMovieClip()
		
		/////create bitmap Data for thumb
		var bmp:BitmapData = new BitmapData(thumbWidth, thumbHeight, true,0xFF0000)
		bmp.draw(target)
				
		///// all container( container image and reflect and background)
		var images:MovieClip = item.images
			
		/////////////////container Image
		var containerImage:MovieClip=images.containerImage
		var image:MovieClip = containerImage.createEmptyMovieClip("image", 1)
		item.__image=image
		image.attachBitmap(bmp, 1, "auto", true)
		image._x = spaceBcg
		image._y = spaceBcg
	   
	
					
		if(shovReflection==true){
		///////reflection
		var reflect:MovieClip = images.createEmptyMovieClip("containerReflect", 2).createEmptyMovieClip("image", 1)
		
		
		if ( Number(colorBackground.split(",")[1])==0) {
		 reflect.attachBitmap(bmp, 1, "auto", true)
		}else{
		  var bmpRef:BitmapData = new BitmapData(image._width+spaceBcg*2, image._height+spaceBcg*2, true,0xFF0000)
		  bmpRef.draw(images)
		  reflect.attachBitmap(bmpRef, 1, "auto", true)
		}
		
		reflect._yscale=-100
		reflect._y = thumbHeight * 2 +spaceBcg * 4 + spaceReflection
		
				
		////////////mask reflection	
		createMaskReflection(item)
		}
		
		containerImage._xscale = 101
		containerImage._yscale = 101
		
		if (item.node.attributes.title == active_title) {
			//image.enabled=false
		}
					
		///remove
		target.removeMovieClip()
						
		//////add events mouse
		 image.onRollOver = function() {
			
			 if(carousel.effectMouseOver==true){
		       new Tween(images.containerReflect, '_y', Strong.easeOut, images.containerReflect._y,10, .5, true)
			   new Tween(images.containerImage, '_y', Strong.easeOut, images.containerImage._y, -10, .5, true)
			 }
			  
			 var desc:String = item.node.attributes.tool_tip//item.node.firstChild.nodeValue
			 if (desc.length) {
			 ToolTip.path= carousel.containerToolTip
	         carousel.toolTip= ToolTip.create();
	         carousel.toolTip.orient = "TC";
	         carousel.toolTip.show = desc
			}
			 
			 
			 
			    /////////toolTip 
				/*
				var desc:String=item.node.attributes.tool_tip//item.node.firstChild.nodeValue
				if (desc.length) {
				ToolTip.__target=carousel.containerToolTip
			    carousel.toolTip = ToolTip.create();
				carousel.toolTip.colorBcg=carousel.colorBackgroundToolTip
	            carousel.toolTip.label = desc
	            carousel.toolTip.margin = 10
             	carousel.toolTip.maxWidth = carousel.widthTooltip
                carousel.toolTip.align = "TR"
	            carousel.toolTip.shov();
				}
				/*/
				
				
			 			 
			 carousel.dispatchEvent({target:item,type:"onRollOverThumb",selectedItem:item.attrib})
 
		 }
		
		image.onReleaseOutside = function() {
			carousel.toolTip.hide()			
			carousel.dispatchEvent({target:item,type:"onRollOutThumb",selectedItem:item.attrib})
		}
		 
		 
		image.onRollOut = function() {
			if(carousel.effectMouseOver==true){
		       new Tween(images.containerReflect, '_y', Strong.easeOut, images.containerReflect._y, 0, .5, true)
			   new Tween(images.containerImage, '_y', Strong.easeOut, images.containerImage._y, 0, .5, true)
			}
			
			carousel.toolTip.hide()
			carousel.dispatchEvent({target:item,type:"onRollOutThumb",selectedItem:item.attrib})
		}
		image.onRelease = function() {
			
			   ///////redirect			   
			   var urlAll:String = item.node.attributes.redirect
			   var url:String = urlAll.split(",")[0]
			   var window:String = urlAll.split(",")[1]
			   if(urlAll!=undefined){
			   getURL(url, window)
			   }
			
			   carousel.dispatchEvent({target:item,type:"onPressThumb",selectedItem:item.attrib})			   
		}
					
		//////fadeIn
		images.tween = new Tween(containerImage.image, '_alpha', Strong.easeInOut, 0, 100,1, true)
		images.tween2=new Tween(images.containerReflect,'_alpha',Strong.easeInOut,0,100,1,true)
		
		
		/////load image
		clearInterval(inter_load)
		inter_load=setInterval(this,'loadImage',250)
}

///////////////load complete thumb///////////////////////////////////////////////////////////////////////////////////

function onLoadComplete(target:MovieClip) {
	target._alpha=0
		
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function onLoadStart(target:MovieClip) {
	 
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function addPreloader(mc_:MovieClip) {
	var item:MovieClip=mc_
	item.preloader = item.attachMovie("_preloader_carousel", "_preloader_", 100)
	var preloader=item.preloader
	
	////color down
	var colorDown = preloaderColor.split(",")[0]
	var alphaDown = preloaderColor.split(",")[1]
	preloader.down._alpha = alphaDown
	var k:Color = new Color(preloader.down);k.setRGB(colorDown)
	
	/////color up
	var colorUp = preloaderColorSelect.split(",")[0]
	var alphaUp = preloaderColorSelect.split(",")[1]
	preloader.up._alpha = alphaUp
	var k:Color = new Color(preloader.up);k.setRGB(colorUp)
	
	////position preloader
	preloader._x = spaceBcg-preloaderW / 2
	preloader._y = spaceBcg-preloaderH / 2
}


/////////////load Image////////////////////////////////////////////////////////////////////////////////////////////////

function loadImage() {
	clearInterval(inter_load)
	var item:MovieClip = MovieClip(thumbs.shift())
	var image:String=item.attrib[nameThumbAttrib]
	var loader:MovieClipLoader = new MovieClipLoader()
	loader.addListener(this)
	var container:MovieClip = item.createEmptyMovieClip("image_", 5)
	loader.loadClip(image,container)
}

////////////////create thumb//////////////////////////////////////////////////////////////////////////////////

  function createThumb() {
	  var car:Carousel=this
	  var angleStep:Number= ( (Math.PI*2)/thumbLength )
	  var angle:Number = (thumbLength%2==0) ? 1 : 0
	  
	  /////create loader
	  var loader:MovieClipLoader = new MovieClipLoader()
	  loader.addListener(this)
	  	  
	  for (var i = 0; i < this.thumbLength; i++) {
		   
		   var dep:Number=1+i///container.getNextHighestDepth()
		   var item:MovieClip = container.createEmptyMovieClip("mcItem" +dep,dep)//container.attachMovie("a","a"+i,i)//
		   
		   item._alpha=0
		 	   
		   /////add Preloader	
		   addPreloader(item)			
		   item.node=array[i].child	
		   item.attrib=array[i]
		   item.carousel = this
		   
		   ////add thumb for array
		   thumbs.push(item)
		   		   		  		   
		   //////////angle
		   item.angle = angle
		   angle+=angleStep
		   		   
		   //////////////////background	   
		   var images:MovieClip = item.createEmptyMovieClip("images", 1)
		   images._x = -int(thumbWidth / 2)
		   images._y = -int(thumbHeight / 2)
		   var containerImage=images.createEmptyMovieClip("containerImage",1)
		   createBackground(containerImage)
		   
		   ///ref bcg
		   item.__bcg = containerImage
		   
		   
				   
		   item.onEnterFrame = function() {
			   var deltaX:Number = Math.cos(this.angle) ///[-1...1]
			   var deltaY:Number = Math.sin(this.angle) ///[-1...1]
			   
			   var _imgReflect =  this.images.containerReflect.image
			   var _maskReflect = this.images.containerReflect.maskReflection
			   var _img=this.images.containerImage.image
			   
			   ////////change alpha
			   this._alpha=100+(deltaY*50)
			 
			   /////change scale
			   this._xscale =100+(deltaY*50)
			   this._yscale = 100 + (deltaY * 50)
			   if (this._xscale > 100) {
				   this._xscale=100
			   }
			   if (this._yscale > 100) {
				   this._yscale=100
			   }
			   		   
			   
			   //////change x and y thumb
			   this.__x =(  deltaX * this.carousel.radiusX)
			   this.__y = (  deltaY * this.carousel.radiusY)
			   
			   this._x = this.__x
			   this._y = this.__y
			   
			  
			    //////////scale image reflect
			    _imgReflect._y= this.images.containerImage._height+ _imgReflect._height+car.spaceReflection
			    _imgReflect._xscale = 101
			    _imgReflect._yscale = -101
						
				//////////scale mask reflect
			    _maskReflect._xscale = 101
			    _maskReflect._yscale = 101
				
					
			   //////change angle
			   this.angle += this.carousel.speedRotation
			   	  	 			 			   
			   ////chnage depths
			   var newDep:Number = Math.round( deltaY*10000)
			   this.swapDepths(newDep)
							
		   }
    }
	   
	loadImage()
  }

////////////////////////////////////////////////////////////////////////////////////////////////
	
}
	
