import mx.data.encoders.Num;
import templateBook.mvctemplate.*
import templateBook.mvc.*
import templateBook.I.*
import flash.display.BitmapData
import templateBook.util.Observable
import templateBook.Configuration
import mx.transitions.Tween
import mx.transitions.easing.*
import flash.geom.*;
import flash.display.*;
import NetConnection
import NetStream


class templateBook.mvctemplate.BackgroundView extends AbstractView {
			
/////////////////////////////////////////////////////////////////////////////////////////
var preloader:MovieClip
var __urlFlv:String
var __proportionFlv:String
var inter_stream:Number
var __arrayContainer:Array
var __container:MovieClip
var __containerCurrent:MovieClip
var __bitmap:BitmapData
var __tweenAlpha:Tween
private var __gradient:MovieClip
/////////////////////////////////////////////////////////////////////////////////////////
var __url:String
var __inter:Number
var __target:MovieClip
var __bmp:BitmapData
var __inter_start:Number
var _timeTweenIntro:Number=1.5
var __loader:MovieClipLoader
var defaultBcg:String
var tweenPreloader:Tween
var _time:Number=0

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

public function defaultController (model:Observable):Controller {
  return new BackgroundController(model)
 }
 
/////////////////////////////////////////////////////////////////////////////////////////

function BackgroundView() {
	preloader._visible=false
	__loader=new MovieClipLoader()
		__arrayContainer=[]
		this.__container=this.createEmptyMovieClip("mcContainer",1)
}
 
/////////////////////////////////////////////////////////////////////////////////////////

function onLoad() {
	var m:BookModel=BookModel(this.getModel())
    __loader.addListener(this)
	__gradient.swapDepths(101)
	__gradient._visible=false
	onResizeAlpha()
}

////////////////////events model ///////////////////////////////////////////////////////////

function onChangeBackground() {
	
var m:BookModel = BookModel(this.getModel())	
this.__tweenAlpha.stop()
__tweenAlpha.stop()

var bcg:String = m.getBackground() /////get background url from model
defaultBcg=bcg
start_change_background(bcg)   ///////change background
 
}

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

private function start_change_background(url_) {
	clearInterval(__inter_start)
	
	clearInterval(this.__inter)
	var m:BookModel=BookModel(this.getModel())
	
	var new_url=url_
	
	__containerCurrent.stream.pause()
	
	if(new_url.length==0||new_url==undefined||typeof(new_url)!="string"){
	 this.__inter=setInterval(this,'changeBackground',100,defaultBcg) 
	}else{
	this.__inter=setInterval(this,'changeBackground',100,new_url)
	}
}

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

function changeBackground(url_:String){
	clearInterval(this.__inter)
	var new_url=url_
		
	if(new_url==this.__url){  /////old background and new background - tozsamosc
	 this.fadeInEnd()	
	}else{
	   setBackground(new_url)
	}
}

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

function setBackground(url_:String){
	__url = (url_)

	if(__url=="transparent"){
		 this.removeAll()
	     this.fadeInEnd()
	}else{
	
	if(__url.indexOf("x")>=0){
	this.changeColorBackground(__url)  //////////////change Color Background (not loaded)
	}else if (__url.indexOf(".flv") >= 0) { ////it is flv
		__urlFlv = __url.split(",")[0]
		__proportionFlv = __url.split(",")[1]
		trace("__urlFlv = "+__urlFlv)
		
		play_move()
	}else{
	this.loadBackground(__url)    //////////////////////load file Background
	}
	
	}
}

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

function play_move() {
	
	var th=this

	var dep:Number=this.__container.getNextHighestDepth()
	this.__containerCurrent = this.__container.createEmptyMovieClip("mcContainer" + dep, dep)
	__containerCurrent._alpha=0
	this.__arrayContainer.push(this.__containerCurrent)
	var video:MovieClip = __containerCurrent.attachMovie("video_container","video_container",4897489489486465464).main_video
	

	/////proportion flv
	var pW:Number = __proportionFlv.split(":")[0]
	var pH:Number = __proportionFlv.split(":")[1]
	
	var w:Number = 400
	var h:Number = (w * pH) / pW
	
	video._width = w
	video._height = h
			
	
video.smoothing=true	
var connection_nc:NetConnection = new NetConnection();
connection_nc.connect(null);
var stream_ns:NetStream = new NetStream(connection_nc);
stream_ns.setBufferTime(5)
__containerCurrent.stream = stream_ns
video.attachVideo(stream_ns);
stream_ns.onStatus = function(infoObject:Object) {
    switch (infoObject.code) {
       
        case 'NetStream.Play.Stop' :
          stream_ns.play(th.__urlFlv)
          break;
    }
}

/////play delay stream
clearInterval(inter_stream)
inter_stream = setInterval(function() {
stream_ns.play(th.__urlFlv);
clearInterval(th.inter_stream);
},200)


onResize()

this.__tweenAlpha=new Tween(__containerCurrent,"_alpha", mx.transitions.easing.Strong.easeIn,0,100,_timeTweenIntro,true);
this.__tweenAlpha.onMotionFinished = Delegate2.create(this, this.fadeInEnd)

	
}

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

private function mask(){
	var m:BookModel=BookModel(this.getModel())
	var mask:MovieClip=this.createEmptyMovieClip("mcMask",125532452)
	Drawing.rectangle(mask,0,0,m.__width,m.__height,["0xFF0000",100])
	this.setMask(mask)	
}

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

function onResizeAlpha() {
	var m:BookModel=BookModel(this.getModel())
	
	__gradient._width = m.__width
	__gradient._height = m.getAreaHeight()
	
}

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

function onResize() {
	var m:BookModel=BookModel(this.getModel())
	onResizeAlpha()
	var scale=Configuration.BACKGROUND_SCALE ////optional noResize
	if (__url.indexOf("network") >= 0&&__url.indexOf("network")!=undefined) { ///////network image
	create_network(__bitmap)
	}else if(scale=="true"){
	var resize:Resize=new Resize(m.__width,m.__height,__containerCurrent._width,__containerCurrent._height)
	var new_size:Object=resize.max()
	this.__containerCurrent._width=new_size.w
	this.__containerCurrent._height = new_size.h
	}
	this.mask()
	this.reset()
}

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

private function changeColorBackground(url){
	this.create_next_movieclip()
	Drawing.rectangle(this.__containerCurrent,0,0,Stage.width,Stage.height,[url,100])
	this.reset()
	this.__containerCurrent._alpha = 0
	__tweenAlpha.stop()
	this.__tweenAlpha=new Tween(__containerCurrent,"_alpha", mx.transitions.easing.Strong.easeIn,0,100,_timeTweenIntro,true);
	this.__tweenAlpha.onMotionFinished = Delegate2.create(this, this.fadeInEnd)
	
	visible_unvisible_gradient()
}

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

private function loadBackground(url_) {
	var m:BookModel=BookModel(this.getModel())
	var dep:Number=this.__container.getNextHighestDepth()
	this.__containerCurrent=this.__container.createEmptyMovieClip("mcContainer"+dep,dep)
	this.__arrayContainer.push(this.__containerCurrent)
	if(url_.indexOf("network")>=0){ ///////network image
	__loader.loadClip(url_.split(",")[0],this.__containerCurrent.createEmptyMovieClip("container",1))	
	}else{   ///not network image
	__loader.loadClip(url_,this.__containerCurrent.createEmptyMovieClip("container",1))
	}
}

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

private function create_next_movieclip(){
	var dep:Number=this.__container.getNextHighestDepth()
	this.__containerCurrent=this.__container.createEmptyMovieClip("mcContainer"+dep,dep)
	this.__arrayContainer.push(this.__containerCurrent)	
}

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

private function create_network(bmp_) {
	var m:BookModel=BookModel(this.getModel())
	var linkage = "background_rectangle";
	create_next_movieclip()
	/////create network
	var w:Number = m.__width
	var h:Number = m.__height
	var matrix = new Matrix(); 
    matrix.rotate(Math.PI/2);
	this.__containerCurrent.clear();
	this.__containerCurrent.beginBitmapFill(bmp_,matrix);
	this.__containerCurrent.lineTo(w, 0);
	this.__containerCurrent.lineTo(w,h);
	this.__containerCurrent.lineTo(0,h);
	this.__containerCurrent.lineTo(0, 0);
	this.__containerCurrent.endFill();
		
	/////////////////////////////////////////////
	/*
	  var filter:GlowFilter = new GlowFilter();
	  filter.color = 0x000000
	  filter.alpha = 200
	  filter.blurX = 700
	  filter.blurY = 700
	  filter.strength = 1.3
	  filter.quality = 3
	  filter.inner = true
	  filter.knockout = false
	  var filterArray:Array = new Array();
      filterArray.push(filter);
      __containerCurrent.filters = filterArray;
	 /*/
	
	
	/*  old version
	var w = __target._width//102;
	var h = __target._height//102;
	var spaceX:Number = 0
	var spaceY:Number = 0
	var lengthX:Number = Math.ceil(Stage.width/(w+spaceX));
	var lengthY:Number = Math.ceil(Stage.height/(h+spaceY))
	var dep:Number = 0;
	for (var x = 0; x<lengthX; x++) {
		for (var y = 0; y<lengthY; y++) {
			var row:MovieClip = this.__containerCurrent.createEmptyMovieClip(linkage+x,dep++);
			row.attachBitmap(bmp_,1)
			row._x = (w+spaceX)*x;
			row._y = (h+spaceY)*y;
		}
	}
	/*/
}

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

function onLoadComplete(target:MovieClip) {
__target._parent=target
target._parent._alpha = 0
preloader._visible = false
delete preloader.circle.onEnterFrame
//tweenPreloader.stop()
//tweenPreloader=new Tween(preloader, '_width', Strong.easeOut, preloader._width, 0, .5, true)
}

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

function onLoadStart() {
	///preloader._visible=true	
	_time = getTimer()
	preloader.circle.onEnterFrame=function(){
	this._rotation += 18	
    }
}

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

function onLoadProgress(target:MovieClip, bytesLoaded:Number, bytesTotal:Number) {
var m:BookModel = BookModel(this.getModel())
if(  (getTimer()-_time )>1 ){
preloader._visible = true
}
var proc:Number = (bytesLoaded/bytesTotal)*m.__width
preloader._x = m.getAreaWidth()/2
preloader._y=m.getAreaHeight()/2
/*
preloader.rectangle._width = proc
preloader.field.autoSize=true
preloader.field.text=int((bytesLoaded/bytesTotal)*100)+"%"
preloader.field._x=preloader.rectangle._width-preloader.field._width
/*/
}

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

function onLoadInit(target:MovieClip) {
	this.reset()
	if (__url.indexOf("network") >= 0) {  /////jesli bedziemy tworzyc siatke
	//__bitmap.dispose()
	    __bitmap = new BitmapData(target._width, target._height, false)
		target.bmp=__bitmap
		__bitmap.draw(target)
		target._visible=false
		this.create_network(__bitmap)	
		var delay=0
	}else {
		
		if (Configuration.BACKGROUND_SMOOTHING == "true") { /////smotthing true
	//__bmp.dispose()	
	target.bmp = new BitmapData(target._width, target._height, true, 0xFF0000)
	///__bmp=target.bmp
	target.bmp.draw(target)
	target._parent.attachBitmap(target.bmp, 2, "auto", true)
	target.removeMovieClip()
	}
		
		onResize()	
		var delay=1
	}
	this.__containerCurrent._alpha = 0
	__tweenAlpha.stop()
	this.__tweenAlpha=new Tween(__containerCurrent,"_alpha", mx.transitions.easing.Strong.easeIn,0,100,_timeTweenIntro,true);
	this.__tweenAlpha.onMotionFinished = Delegate2.create(this, this.fadeInEnd)
	
	visible_unvisible_gradient()
}

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

function visible_unvisible_gradient() {
	var gradient = "true"
	var gradient_color="0xFF0000"
	if (__gradient._visible == false&&gradient=="true") {
		__gradient._alpha = 0
		if(gradient_color.length){
		NewColor.setColor(__gradient,gradient_color)
		}
		__gradient._visible = true
		new Tween(__gradient,"_alpha", mx.transitions.easing.Strong.easeIn,0,100,_timeTweenIntro,true);
		
	}
}

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

function reset(){
	var len:Number=this.__arrayContainer.length-2
	for(var i=0;i<len;i++){
		var mc:MovieClip = MovieClip(this.__arrayContainer.shift())
		mc.bmp.clear()
		mc.bmp.dispose()
		mc.removeMovieClip()
		
	}
	for(var i in this.__arrayContainer){
		var mc:MovieClip=MovieClip(this.__arrayContainer[i])
		mc.stopTween()
	}
}

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

function removeAll(){
	for(var i in this.__arrayContainer){
		var mc:MovieClip=MovieClip(this.__arrayContainer[i])
		mc.stopTween()
		mc.removeMovieClip()
}
}

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

function fadeInEnd(){
	var m:BookModel=BookModel(this.getModel())
	m.dispatchEvent({target:this,type:"onLoadBackground"})
	
}

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



}

