dojo.provide("com.ba.gui.MediaComponent");

dojo.require("com.ba.Util");
dojo.require("dojox.fx.easing");
dojo.require("dojo.fx");

dojo.declare("com.ba.gui.MediaComponent",
	null,
	{
		_currentNode: null,
		_scrollId: null,
		_maxPosition: 0,
		_viewportWidth: 0,
		_publishConnection: null,
		statics: { isBuildClass:"MediaComponentBuild",
					templateString: '<li><img src="{{ previewURL }}" alt="{{ altContent }}"/>{{ interactionContent }}<div class="label"><div class="goLeft"><span></span></div><div class="goRight"><span></span></div><div class="content"><h3><a href="{{ landingURL }}">{{ title }}</a></h3><p>{{ previewBody }}<span>{{ itemDate }}</p></div></div></li>',
					interactionContentString: '<div class="isVideo"></div><span class="movieLinkBg"></span><a href="{{ movieLink }}" class="movieLink"></a>'
				},
				
		constructor: function(node, args){
		
				//alert("sring" + typeof(node));
			if(typeof(node) == "string"){
				node = dojo.byId(node);
			} 
			
			if(node) {
				if(!node.id) {
					node.id = com.ba.Util.GenerateId(); 
				}
			
				this._currentNode = node.id;
			}
			if(!dojo.hasClass(node, this.statics.isBuildClass))
			{
				this._buildElements();
				this._connectInteractions();

				if((dojo.isIE) && (dojo.isIE <= 7) ){
					// Do the resizing etc... with a small delay for little old IE...
					window.setTimeout(dojo.hitch(this, "_setIEHeights"), 100);
				} else {
					dojo.addClass(node, this.statics.isBuildClass);
				}
			} 
		},
		
		_buildElements: function(){
			
			var node = dojo.byId(this._currentNode);
			var ulNode;
			
			dojo.forEach(dojo.query("#" + this._currentNode+" > ul"), function(ulElement){ 
				ulNode = ulElement;
			});

			node.removeChild(ulNode);
			
			var newInnerHTML = "";
			var queryList = dojo.query("li", ulNode);
			
			dojo.forEach(queryList, dojo.hitch(this, function(listElement) { 
				newInnerHTML += this._createIndividualElement(listElement);
			}));
			
			// We assume an element is full width...
			this._viewportWidth = dojo.style(node, "width");
			this._maxPosition = this._viewportWidth * queryList.length;
			
			this._scrollId = com.ba.Util.GenerateId();
			
			node.innerHTML = '<ul id="'+this._scrollId+'">'+newInnerHTML+newInnerHTML+'</ul>'; 
			
			dojo.query(".movieLinkBg").style("opacity", 0.5);
			dojo.query(".movieLink").style("opacity", 0.9);
            
			dojo.style(this._scrollId, "width", (this._maxPosition * 2) + "px");

			// Cleanup...
			queryList = undefined;
			
		},
		
		_setIEHeights: function(scrollId){
			
			dojo.addClass(dojo.byId(this._currentNode), this.statics.isBuildClass);
			dojo.forEach(dojo.query("#"+this._scrollId+" li .label"), function(labelElement){
				var currentHeight;
                
				dojo.forEach(dojo.query(".content", labelElement), function(contentElement){
					currentHeight = dojo.contentBox(labelElement).h
				});

				dojo.forEach(dojo.query(".goLeft, .goRight,.goLeft span, .goRight span", labelElement), function(control){
					dojo.style(control, "height", currentHeight+"px");
				});
			});
		},
		
		_createIndividualElement: function(source)
		{
		
			element = this.statics.templateString;
			var newString = "";
			
			dojo.forEach(dojo.query("img", source), function(element){ 
				newString = element.src;
			});
			
			element = element.replace(/{{ previewURL }}/gi, newString);
			
			newString ="";
			
			dojo.forEach(dojo.query(".description h1", source), function(element){ 
				newString = element.innerHTML;
			});
			
			element = element.replace(/{{ title }}/gi, newString);
			element = element.replace(/{{ altContent }}/gi, newString);
			
			newString ="";
			
			var queryList = dojo.query(".description .date", source);
			dojo.forEach(queryList, function(element){ 
				newString = element.innerHTML;
			});
			queryList.orphan();
			queryList = undefined;
			
			element = element.replace(/{{ itemDate }}/gi, newString);
			
			newString ="";
			
			dojo.forEach(dojo.query(".description p", source), function(element){ 
				newString = element.innerHTML;
			});
			
			element = element.replace(/{{ previewBody }}/gi, newString);
			
			newString = "";
            
			queryList = dojo.query(".readMore", source);
			
			dojo.forEach(queryList, function(element){ 
				newString = element.href;
			});
			
			if(newString){
				newString = newString.replace(/about:blank/gi, "");
				newString = newString.replace(/about:/gi, "");
			}
            
			element = element.replace(/{{ landingURL }}/gi, newString);

			newString ="";
			queryList = dojo.query(".videoLink", source);
			
			dojo.forEach(queryList, function(element){ 
				newString = element.href;
			});
			
			if(newString){
				newString = newString.replace(/about:blank/gi, "");
				newString = newString.replace(/about:/gi, "");
				//~ alert("newString: " + newString);
				newString = this.statics.interactionContentString.replace(/{{ movieLink }}/gi, newString);
			}
			
			if(newString){
				element = element.replace(/<li>/gi, '<li class="videoElement">');
			}
			
			element = element.replace(/{{ interactionContent }}/gi, newString);

			return element;
		}, 
        
		_connectInteractions: function(){
			dojo.query("#"+this._scrollId + " .goRight").onclick(dojo.hitch(this, this.onClickRight));
			dojo.query("#"+this._scrollId + " .goLeft").onclick(dojo.hitch(this, this.onClickLeft));
			dojo.query("#"+this._scrollId + " .movieLink").onclick(dojo.hitch(this, this.onClickVideo));
			this._publishConnection = dojo.subscribe("MediaComponent_VideoInstanciated", this, this._onVideoCreated);
		},
		
		_onVideoCreated: function(id){
			console.debug("_onVideoCreated.. " + id);
			var playerId = "player_for_"+this._scrollId;
			var player = dojo.byId(playerId);
			
			dojo.subscribe("MediaComponent_LOADUPDATE", this, this.onPlayerLoadUpdate);
			dojo.subscribe("MediaComponent_PLAY", this, this.onPlayerPlay);
			dojo.subscribe("MediaComponent_STOP", this, this.onPlayerStop);
			
		},
		
		onPlayerLoadUpdate: function(obj){
            console.debug('nu mag ik pas afspelen');
			//console.debug(obj);
		},
		
		onPlayerPlay: function(obj){
			console.debug("play...");
			
			var labelElement;
			
			dojo.forEach(dojo.query("#"+ this._currentNode + " .videoMode .label"), function(element){
				labelElement = element;
			});
			
			dojo.fadeOut({node: labelElement, onEnd: function(){ dojo.style(labelElement, "display", "none")} }).play();
		},
		
		onPlayerStop: function(obj){
			console.debug("stop...");
			var labelElement;
			
			dojo.forEach(dojo.query("#"+ this._currentNode + " .videoMode .label"), function(element){
				labelElement = element;
			});
			
			dojo.style(labelElement, "display", "block");
			dojo.fadeIn({node: labelElement}).play();
		},
		
		
		onClickVideo: function(e){
			dojo.stopEvent(e);
			
			// get the li item...
			var currentLi = e.currentTarget.parentNode;
			
			if(!dojo.hasClass(currentLi, "videoMode"))
			{
				var currentLabel;
				
				dojo.forEach(dojo.query(".label", currentLi), function(labelElement){
					currentLabel = labelElement;
				});
				
				
				var playerId = "player_for_"+this._scrollId
				var playerTarget = dojo.byId(playerId);
				
				if(!playerTarget){
					playerTarget = dojo.doc.createElement("div");
					playerTarget.id = playerId;
				}
				
				dojo.place(playerTarget, currentLabel, "before");
				dojo.style(playerTarget, "height", dojo.style(this._currentNode, "height"));
				dojo.style(playerTarget, "width", this._viewportWidth);
				dojo.style(playerTarget, "background", "#000");
				dojo.style(playerTarget, "position", "absolute");
				dojo.style(playerTarget, "opacity", "0");
				
				dojo.addClass(currentLi, "videoMode")
				
				// Do play the video....
				var animation = new dojo.fx.chain([
					dojo.fadeOut({node: currentLabel}),
					dojo.fadeIn({node: playerTarget})
				])
				
				dojo.connect(animation, "onEnd", this, this._createVideoPlayer);

				animation.play();
				
				

			}
		},
		
		_createVideoPlayer: function(){
		
			var videoFile;
			
			// find the video location
			dojo.forEach(dojo.query("#" + this._scrollId + ".videoMode .movieLink"), function(videoElement){
				videoFile = dojo.attr(videoElement, "href");
			});
			
			var flashvars = {};
			flashvars.file = videoFile;
			flashvars.autostart = 'true';
			flashvars.bufferlength = 10;
			var params = {};
			params.allowfullscreen = 'true';
			params.allowscriptaccess = 'always';
			params.wmode = 'transparent';
			params.name = "player_for_"+this._scrollId;

			var attributes = {};
			swfobject.embedSWF("sites/Bedrijf/images/player.swf", "player_for_"+this._scrollId, this._viewportWidth, dojo.style(this._currentNode, "height"), "9.0.115", "sites/Bedrijf/scripts/swfObject/expressInstall.swf", flashvars, params, attributes);

			console.debug("currentLi: " + playerReady);
		},
		
		
		onClickRight: function(e){
			if(!dojo.hasClass(this._scrollId, "animating")){
			
				var currentPosition = dojo.style(this._scrollId, "left");
				
				var maxPos = this._maxPosition;
				var scrollId = this._scrollId;
				var videoPlayerId = "player_for_"+this._scrollId;

				dojo.addClass(this._scrollId, "animating");
				

				dojo.animateProperty({ node: this._scrollId,
										duration: 600,
										properties: {
											left: { end: currentPosition-this._viewportWidth, unit:"px" }
										},
										easing: dojox.fx.easing.cubicInOut,
										onEnd: function(){
										
											var pos = dojo.style(scrollId, "left")
											
											if( pos <= -maxPos){
												dojo.style(scrollId, "left", (pos+maxPos)+"px");
											}
											
											var videoPlayer = dojo.byId(videoPlayerId);
											if(videoPlayer)
											{
												videoPlayer.parentNode.removeChild(videoPlayer);
												
												dojo.query("#"+scrollId + " .videoMode").removeClass("videoMode");
											}
											
											dojo.removeClass(scrollId, "animating");

										}
									}).play();

			}
		},
		
		onClickLeft: function(e){
			if(!dojo.hasClass(this._scrollId, "animating")){
				var currentPosition = dojo.style(this._scrollId, "left");
				
				var maxPos = this._maxPosition;
				var scrollId = this._scrollId;

				if(currentPosition >= 0){
					currentPosition -= this._maxPosition;
					dojo.style(scrollId, "left", (currentPosition)+"px");
				}
				
				dojo.addClass(this._scrollId, "animating");
				
				dojo.animateProperty({ node: this._scrollId,
										duration:400,
										properties: {
											left: { end: currentPosition+this._viewportWidth, unit:"px" }
										},
										easing: dojox.fx.easing.cubicInOut,
										onEnd: function(){
											dojo.removeClass(scrollId, "animating");
										}
									}).play();
			}
		}
		
	});
	
dojo.mixin(com.ba.gui.MediaComponent, { 
		VideoPlayerModelUpdate: function(obj){
            //console.dir(obj);
			//com.ba.gui.MediaComponent.onPlayerPlay(obj);
			//console.debug("dit is er al geladen: " + obj['loaded']);
			//console.debug("dit is het totaal: " + obj['total']);
			//console.debug('ik check het ff hoor');
			var player = dojo.byId(obj['id']);
			/*var config = player.getConfig();
			config.bufferlength = (obj['total']/2);
			console.debug('bufferlength'+config.bufferlength);*/
			
			if(obj['loaded'] > (obj['total']/2))
			{
				console.debug('meer dan de helft is geladen');
				player.sendEvent("PLAY");
			}
			
        },
		VideoPlayerStatusUpdate: function(obj){
			
			var player = dojo.byId(obj['id']);
			var config = player.getConfig();
			//console.dir(config);
			switch(config.state){
				 case "LOADED":
                    dojo.publish("MediaComponent_STOP", [obj['id']]);      
                	console.debug('LOADED');
					break;
				case "PLAYING":
					dojo.publish("MediaComponent_PLAY", [obj['id']]);
					console.debug('PLAYING');
					break;
				case "PAUSED":
				case "COMPLETED":
					dojo.publish("MediaComponent_STOP", [obj['id']]);
					console.debug('COMPLETED');
					break;
				case "IDLE":
					console.debug('IDLE');
					dojo.publish("MediaComponent_STOP", [obj['id']]);
					break;
			}
		}
});
	
var playerReady = function (obj) {
	console.debug("playerReady");
	
	var id = obj['id'];
	var version = obj['version'];
	var client = obj['client'];
	
	dojo.publish("MediaComponent_VideoInstanciated", [id]);

	mediaComponent = document.getElementById(id);
	
	mediaComponent.addModelListener("STATE", "com.ba.gui.MediaComponent.VideoPlayerStatusUpdate");
	
	mediaComponent.addControllerListener("ITEM", "com.ba.gui.MediaComponent.VideoPlayerStatusUpdate");
	mediaComponent.addControllerListener("STOP", "com.ba.gui.MediaComponent.VideoPlayerStatusUpdate");
	mediaComponent.addControllerListener("PLAY", "com.ba.gui.MediaComponent.VideoPlayerStatusUpdate");
	mediaComponent.addControllerListener("SEEK", "com.ba.gui.MediaComponent.VideoPlayerStatusUpdate");
	//mediaComponent.addModelListener("LOADED", "com.ba.gui.MediaComponent.VideoPlayerModelUpdate");
	
	//mediaComponent.sendEvent("PLAY",false);
};

