dojo.provide("Z2h.Notification");

dojo.require("dojo.fx");
dojo.require("dojo.fx.easing");
dojo.require("dijit._Widget");
dojo.require("dijit._Templated");

dojo.declare("Z2h.Notification", [dijit._Widget, dijit._Templated], {
	templateString: null,
	templatePath: dojo.moduleUrl("Z2h","templates/Notification.html"),
	templateCssString: null,
	templateCssPath: dojo.moduleUrl("Z2h","templates/Notification.css"),
	widgetsInTemplate : true,
	
	_bounce_point_animation: null,
	_pullback_animation: null,
	
	_attachNode: null,
	
	pointTo: "",
	
	postCreate: function(){
		dojo.place(this.containerNode,dojo.body(),'last');
		
		var checkFor = this.containerNode.id;
		
		dojo.query(".notification_container").forEach( function(node,index,list){
			if ( node.id != checkFor ){
				dojo.destroy(node.id);
			}
		});
		
		this.inherited("postCreate",arguments);
		
		if ( this.pointTo != "" ) {
			this._attachNode = dojo.byId(this.pointTo);
			
			var attachCoords = dojo.position(this._attachNode);
			var thisCoords = dojo.position(this.containerNode);
			
			var newX = attachCoords.x - thisCoords.w;
			var newY = attachCoords.h/2;
			
			dojo.style(this.containerNode,"top",newY+"px");
			dojo.style(this.containerNode,"left",newX+"px");
		}
		
		dojo.fadeIn({ 
			node: this.arrowNode,
			_this: this,
			duration: 100,
			onEnd: function(){
				this._this.playBouncePoint();
			}
		}).play();
	},
	
	playBouncePoint: function(){
		if ( this._bounce_point_animation == null ){
			this.setupBouncePoint();
		}
		this._bounce_point_animation.play();
	},
	
	setupBouncePoint: function(){
		var container = dojo.contentBox(this.containerNode);
		var arrow = dojo.contentBox(this.arrowNode);
		
		this._bounce_point_animation = dojo.animateProperty({
			_this: this,
			node: this.arrowNode,
			properties: {
				marginLeft: {
					start: 0,
					end: container.w - arrow.w,
					units: 'px'
				}
			},
			easing: dojo.fx.easing.bounceOut,
			duration: 1000,
			onEnd: function(){
				this._this.bouncePointEnd();
			}
		});
	},
	
	bouncePointEnd: function(){
		this.playPullback();
	},
	
	playPullback: function(){
		if ( this._pullback_animation == null ){
			this.setupPullback();
		}
		
		this._pullback_animation.play();
	},
	
	setupPullback: function(){
		this._pullback_animation = dojo.animateProperty({
			_this: this,
			node: this.arrowNode,
			properties: {
				marginLeft: {
					end: 0,
					units: 'px'
				}
			},
			onEnd: function(){
				this._this.pullbackEnd();
			},
			duration: 2000
		});
	},
	
	pullbackEnd: function(){
		this.playBouncePoint();
	},
	
	clickArrow: function(evt){
		evt.preventDefault();
	},
	
	destroy: function(){
		dojo.destroy(this.containerNode);
	}
	
});

