var Ytemplate = YUI( {
	base:'/scripts/yui/',
	timeout :10000
});

Ytemplate.namespace("dior");
Ytemplate.use("base", "io-base", function(Y) {

	var _this;
	var frameRate=25;
	
	var transactionTemplate = {
		complete : function(id, o) {
		},
		success : function(id, o, args) {
			_this.setTemplateItems(o.responseXML);
		},
		failure : function(id, o) {
			alert(id + ": Transaction Event Failure.  The status text is: "
					+ o.statusText + ".");
		},
		abort : function(id) {
			alert(id + ": Transaction Event Aborted.");
		}
	}

	var cfg = {
		on : {
			complete :transactionTemplate.complete,
			success :transactionTemplate.success,
			failure :transactionTemplate.failure
		},
		context :transactionTemplate
	};

	function TemplateController(url) {
		TemplateController.superclass.constructor.apply(this, arguments);
		_this = this;
		this.set("url", url);
	}

	TemplateController.NAME = "templatecontroller";
	TemplateController.ATTRS = {
		url : {
			value:null
		},
		xmlRoot : {
			value :''
		},
		items : {
			value : []
		},
		currentFrame : {
			value: '0'
		},
		currentInterval:{
			value:null
		},
		currentStep:{
			value:null
		},
		steps : {
			value:[]
		},
		duration:{
			value:'6000'
		},
		init:{
			value:true
		}
	}


	Y.extend(TemplateController, Y.Base, {
		loadData:function(){

			var urlTemplate = (Y.Lang.isUndefined(templateUrl) ? '' : templateUrl) ;
			Y.io(this.get("url") + "template/"+urlTemplate, cfg);
		},
		setTemplateItems:function (xmlTemplate) {
			this.set("xmlRoot", xmlTemplate.documentElement);
			var stepParams = this.get("xmlRoot").getElementsByTagName("steps");
			this.set("duration", stepParams[0].getAttribute("duration"));
			var steps = stepParams[0].getElementsByTagName("step");
			var stepArray = [];
			var delay = 0;
			for(var i=0; i <steps.length; i++){

				stepArray.push({
					'id' : steps[i].getAttribute("id"),
					'start' : steps[i].getAttribute("start"),
					'duration' : steps[i].getAttribute("duration"),
					'delay' : delay
				});
				
				this.on("templatecontroller:timeline"+delay, 
						function(e, args){this.setStep(args)}, this, i);
				
				delay = delay +parseInt(steps[i].getAttribute("duration"));
			}
			this.set("steps", stepArray);
			var startStep = 0//Math.round(Math.random()*(steps.length-1));
			this.set("currentFrame", (this.get("steps")[startStep].delay));
			this.setStep(startStep);
			var map = mapInstance;
			items = this.get("xmlRoot").getElementsByTagName('item');
			var arrayItems=[];
			for ( var i = 0; i < items.length; i++) {
				var itemObj = new Yitem.dior.init();
				var _tmpRoot = items[i];
				if (_tmpRoot.getAttribute("priority") != undefined) {
					itemObj.set("priority", _tmpRoot.getAttribute("priority"));
				}
				if (_tmpRoot.getAttribute("id") != undefined) {
					itemObj.set("xmlId",  _tmpRoot.getAttribute("id"));
				}
				if (_tmpRoot.getAttribute("disable") != undefined && _tmpRoot.getAttribute("disable") == "true") {
					continue;
				}
				var animation = _tmpRoot.getElementsByTagName("animation");
				var animArray = [];
				for(var j=0; j<animation.length; j++){
					
					var from = animation[j].getElementsByTagName("from");
					var fromObj = {};
					if(from.length){
						from = from[0];
						fromObj = { x:from.getAttribute("x") , y:from.getAttribute("y")}
						if(j==0){
							itemObj.set("coordinates", {});
							itemObj.set("coordinates.x",from.getAttribute("x"));
							itemObj.set("coordinates.y",from.getAttribute("y"));
						}
					}
					
					var to = animation[j].getElementsByTagName("to");
					var toObj = {};
					if(to.length){
						to = to[0];
						toObj = { x:to.getAttribute("x") , y:to.getAttribute("y")}
						if(to.getAttribute("opacity") != undefined){
							toObj.opacity = to.getAttribute("opacity");
						}
					}
					
					animArray[animation[j].getAttribute("start")] = {
						start:		this.convertInFrameRate(animation[j].getAttribute("start")),
						duration:	this.convertInFrameRate(animation[j].getAttribute("duration")),
						effect:		animation[j].getAttribute("effect"),
						from:		fromObj,
						to:			toObj
					};
					var event;
					if(animation[j].getAttribute("startstep") == null){
						event = "templatecontroller:timeline"+animation[j].getAttribute("start");
					}else{
						event = "templatecontroller:timelinestart_"+animation[j].getAttribute("step")+"_"+(parseInt(animation[j].getAttribute("start"))+parseInt(this.get("steps")[animation[j].getAttribute("step")].delay));
					}
					//Y.log("Event : "+event, "info", "template");
					this.subscribe(event, 
							function(e, args){this.animStart(args)}, itemObj, 
							animation[j].getAttribute("start"));

					itemObj.subscribe("itemcontroller:stopTimeline", function(e){
						if(this.get("init") != true){
							this.clearTimeline();
						}
						}, this);
					itemObj.subscribe("itemcontroller:startTimeline", function(e){
						if(this.get("init") != true){
							this.get("currentInterval").cancel();
							this.set("currentInterval",Y.later((1000/frameRate), this, "startTimeline", [], true));
						}
						}, this);
				}
				itemObj.set("animations" , animArray);

				var size = _tmpRoot.getElementsByTagName("size");
				if (size.length) {
					itemObj.set("size", {});
					itemObj.set("size.width",Math.round(size[0].getAttribute("w")* map.get("xbox")));
					itemObj.set("size.wsize",size[0].getAttribute("w"));
					itemObj.set("size.height",Math.round(size[0].getAttribute("h")* map.get("ybox")));
					itemObj.set("size.hsize",size[0].getAttribute("h"));
					itemObj.set("size.string",size[0].getAttribute("w")+"x"+size[0].getAttribute("h"));
				}

				 arrayItems.push(itemObj);
			}
			this.set("items",arrayItems);
			this.fire("templatecontroller:loaded");
		},
		convertInFrameRate:function(value){
			return (value/frameRate);
		},
		startTimeline:function(_this){
			var nextFrame = this.get("currentFrame");
			Y.log("Current Frame:"+nextFrame, "info", "framerate")
			if(this.get("init") != true){
				this.fire("templatecontroller:timeline"+nextFrame);
			}else{
				this.fire("templatecontroller:timelinestart_"+this.get("steps")[this.get("currentStep")].id+"_"+nextFrame);
			}
			this.set("currentFrame", (parseInt(nextFrame)+1));	
			if(this.get("currentFrame") > (parseInt(this.get("steps")[this.get("currentStep")].delay)+parseInt(this.get("steps")[this.get("currentStep")].start))){
				this.set("init", false);
			}
			if(this.get("currentFrame") > this.get("duration")){
				this.set("currentFrame", 0);
			}

		},
		setStep:function(number){
			this.set("currentStep", number);
			Y.log("New Step : "+this.get("currentStep") +' at frame '+this.get("currentFrame"), "info", "template");
		},
		clearTimeline:function(){
			this.get("currentInterval").cancel();
		},
		launch:function(){
			Y.log("Launch", "info", "template")
			this.set("currentInterval",Y.later((1000/frameRate), this, "startTimeline", [], true));
		}
	})

	Ytemplate.dior = {
		init :TemplateController
	};

});
var templateUrl="";