
Element.Events.mouseInside = {
};

Element.Events.playerResize = {
};

Element.Events.slideOut = {
    
};

Element.Events.slideOutReady = {
    
};


var ShowIt = new Class(
	{	
		serverdomain: "",
		bandwidthPath: "",
		baseUrl:"",
		specialParams : "?r=r",
		skinName : 'ondemand',
		applicationId: '396689409',
		swfBase: "",
		id:null,
		width:0,
		height:0,
		x:0,
		y:0,
		targetName:null,
		player:null,
		wmode:"window",
		slideEnabled:false,
		autostart:true,
		launcher:null,
		debug:false,
		allowedWmodes:["window", "opaque", "transparent"],
		initialized:false,
		config:null,
		slideDuration:-1,
		parentElement:null,
		embedMode:null,
		version:"AS3",
		mouseOverState : "",
		slideButton:null,
		embedMode:null,
		slideState:"",
		forcedWidth:-1,
		forcedHeight:-1,
		keepVideoAspectRatio:null,
		autoplay:null,
		playlistTemplate:null,
		tokens:null,
		customParams:null,
		category:null,
		zIndex:100,
		elementsToHide:null,
		
		initialize: function(playerId, x, y, width, height, autostart, launchButtonId, version){
			if($defined($(playerId))){
				alert("ERROR: element " + playerId + " already exists");
				return;
			}
			if(!autostart && !$defined($(launchButtonId))){
				alert("ERROR: launch button is not defined");
				return;
			}
			
			this.serverdomain = "http://" + getDomainFromUrl('http://iptv.cdn.tv1.de/iptv/player/macros/_v_f_500_de/_s_ondemand/_x_s-396689409/');
			var baseLink = '/iptv/player/macros/_v_f_500_de/_s_ondemand/_x_s-396689409/'
			var first = baseLink.indexOf("/_");
			this.baseUrl = this.serverdomain + baseLink.substring(0, first);
			this.bandwidthPath = this.serverdomain + '/iptv/img/test.txt';
			this.swfBase = this.serverdomain +  '/iptv/swf/xflv/';
			if($defined(version)){
				this.version = version;
			}
			
			this.id = playerId;
			this.x = x;
			this.y = y;
			this.width = width;
			this.height = height;
			this.autostart = autostart;
			if(! autostart){
				this.launcher = $(launchButtonId);
				if(Browser.Engine.trident){
					this.launcher.setStyle("cursor", "hand");
				}
				else{
					this.launcher.setStyle("cursor", "pointer");
				}
			}
	    },
	    
	    setWmode: function(wmode){
	    	if(this.initialized){
	    		alert("ERROR: cannot set wmode after initialization");
	    		return;
	    	}
	    	if(this.allowedWmodes.indexOf(wmode) < 0){
	    		alert("ERROR: invalid wmode");
	    		return;
	    	}
	    	this.wmode = wmode;
	    },
	    
	    overrideAutoPlay:function(b){
	    	this.autoplay = b;
	    },
	    
	    setCategory:function(n){
	    	this.category = n;
	    },
	    
	    setContent:function(id, singleton){
	    	if(singleton == undefined){
	   	 		this.specialParams += '$singleton=true';
	   		}
	   		else{
	   			this.specialParams += '$singleton=' + singleton;
	   		}
	    	this.specialParams = this.specialParams + '$contentId=' + id;
	    },
	    
	    setPlaylistTemplate:function(s){
	    	this.playlistTemplate = s;
	    },
	    
	    setParams:function (){
	    	var urlPath = document.location.href;
	    	var idx = urlPath.indexOf("?");
	    	if(idx > 0){
			 	urlPath = urlPath.substring(idx + 1, urlPath.length);
			 	var params = urlPath.split("&");
			 	for(var  i = 0; i < params.length; i++){
			 		var param = params[i];
			 		if(param != ""){
			 			var paramProperties = param.split("=");
			 			switch(paramProperties[0]){
			 				case 'category':
			 					this.category = paramProperties[1];
								//this.specialParams += '$category=' + paramProperties[1];
								break;
							case 'singleton':
								this.specialParams += '$singleton=' + paramProperties[1];
								break;
							case 'content':
								this.specialParams += '$contentId=' + paramProperties[1];
								break;
							case 'startPosition':
								this.specialParams += '$startPosition=' + paramProperties[1];
								break;
							case 'idx':
								this.specialParams += '$idx=' + paramProperties[1];
								break;
				 		}
			 		}
			 	}
			 	
			}
			if(this.forcedWidth > 0 && this.forcedHeight > 0){
				this.specialParams += '$forcedWidth=' + this.forcedWidth;
				this.specialParams += '$forcedHeight=' + this.forcedHeight;
				this.specialParams += '$keepVideoAspectRatio=' + this.keepVideoAspectRatio;
			}
			if(this.category != null){
				this.specialParams += '$category=' + this.category;
		 	}
		},
		
		insertIntoElement: function(elementId, videoWidth, videoHeight, keepVideoAspectRatio){
	    	if(! $defined(elementId) || ! $defined( $(elementId) ) ){
	    		alert("ERROR: target element not defined");
	    		return;
	    	}
	    	if($defined(videoWidth) && $defined(videoHeight)){
	    		this.forcedWidth = videoWidth;
	    		this.forcedHeight = videoHeight;
	    		if($defined(keepVideoAspectRatio)){
	    			this.keepVideoAspectRatio = keepVideoAspectRatio;
	    		}
	    	}
	    	this.setParams();
	    	this.embedMode = "embedded";
	    	this.parentElement = $(elementId);
	    	if(this.autostart){
	    		autoInit(this);
	    	}
	    	else{
	    		autoInit(this, this.launcher);
	    	}
	    	addMouseInsideEventListener(this);
			addResizeEventListener(this);
	    },
	    
	    buildOverlayPlayer: function(elementId, buttonId, slideDuration){
	    	if($defined($(elementId))){
	    		alert("ERROR: target element already exists");
	    		return;
	    	}
	    	if(!$defined(buttonId) || !$defined($(buttonId))){
	    		alert("ERROR: button element not defined");
	    		return;
	    	}
	    	this.embedMode = "overlay";
	    	$(buttonId).setStyle("visibility", "hidden");
	    	this.slideDuration = slideDuration;
	    	this.slideEnabled = true;
	    	this.parentElement = new Element("div",
	    	{
	    		'id': elementId
	    	});
	    	
	    	
	    	this.setParams();
	    	this.slideButton = $(buttonId);
	    	if(this.autostart){
	    		autoInit(this);
	    	}
	    	else{
	    		autoInit(this, this.launcher);
	    	}
	    	addMouseInsideEventListener(this);
			addResizeEventListener(this);
			addSlideOutEventListener(this);
			addSlideInEventListener(this, this.slideButton);
			addSlideOutReadyEventListener(this);
	    },
	    
	    handleMouseEvent: function(e){
	    	var flashMovie = getFlashMovieObject("showIt");
			var isAllowed = false;
			isAllowed = $defined(flashMovie.onMouseMovedOutside);
			if(isAllowed){
				var mX = e.page.x;
				var mY = e.page.y;
				var playerRect = getBounds(this.player);
				var newState = (containsCoordinates(playerRect, mX, mY))?"in" : "out";
				if(this.mouseOverState != newState){
					this.mouseOverState = newState;
					if(this.mouseOverState == "out"){
					    try{
							flashMovie.onMouseMovedOutside();
						}
						catch(e){
							debug("could not call flash function");
							//should not happen on a server
						}
					}
				}
			}
		},
		
		optimizePosition:function() {
			if(this.slideState == "out"){
				return;
			}
			var optimizedPos = this.getOptimizedPosition();
			this.parentElement.setStyle("left", optimizedPos);
			hideOverlappingElements(this.player, this.elementsToHide);
		},
		
		getOptimizedPosition:function(){
			var optimizedPos = null;
			var containerWidth = this.player.getStyle('width').toInt();
			var availWidth = (window.innerWidth) ? window.innerWidth : (window.document.body.offsetWidth) ? window.document.body.offsetWidth : containerWidth;
			availWidth = Math.max(availWidth, containerWidth);
			optimizedPos = (availWidth - containerWidth) /2;
			return optimizedPos;
		},
		
		onResized:function(width, height, callback){
			this.player.setStyle("width", width);
			this.player.setStyle("height", height);
			if(Browser.Engine.trident){
				$("showIt").width = "" + width;
				$("showIt").height = "" + height;
			}
			else{
				$('showIt').setStyle("width", width);
				$('showIt').setStyle("height", height);
			}
			if(callback){
				if(getFlashMovieObject("showIt").onResized){
					getFlashMovieObject("showIt").onResized();
				}
			}
			if(this.x == 'center'){
				this.optimizePosition();
			}
		},
		
		slideOut:function(e){
			if(this.slideEnabled){
				var target = -1 * this.width;
				setTimeout("slidedOut()", this.slideDuration);
				var myFx = new Fx.Tween(this.parentElement, {duration:this.slideDuration, transition: Fx.Transitions.Elastic.easeOut});
				myFx.start('left', target);
				this.slideState = "out";
			}
		},
		
		slideIn:function(e){
			if(this.slideEnabled){
				//a special for Opera
				if(Browser.Engine.presto){
					this.parentElement.setStyle('visibility', 'visible');
				}
				var target = 0;
				if(this.x == "center"){
					target = this.getOptimizedPosition();
				}
				else{
					target = this.x;
				}
				this.slideButton.setStyle('visibility', 'hidden');
				var myFx = new Fx.Tween(this.parentElement, {duration:this.slideDuration, transition: Fx.Transitions.Elastic.easeOut});
				myFx.start('left', target);
				this.slideState = "in";
			}
		},
		
		onSlideoutReady:function(e){
			this.slideButton.setStyle('visibility', 'visible');
			showHiddenElements(this.player, this.elementsToHide);
			//a special for Opera (does not like sliding with negative values)
			if(Browser.Engine.presto){
				this.parentElement.setStyle('visibility', 'hidden');
			}
		}
	}
);

function initialize(showIt){
	theShowIt = showIt;
}

function unload(showIt){
	if(showIt.parentElement != null){
		showIt.parentElement.getParent().removeChild(showIt.parentElement);
	}
}

function embedAS2Version(showIt){
	var so = new SWFObject(showIt.serverdomain + "/iptv/swf/xflv/showIt.swf", "showIt", showIt.width, showIt.height,"9.0.115");
	try {
		so.useExpressInstall(showIt.serverdomain + '/iptv/swf/expressinstall.swf');
	}
	catch(e){}
	var configPath = showIt.serverdomain +'/iptv/player/macros/_v_f_500_de/_s_ondemand/_x_s-396689409/xflv/config.xml' + showIt.specialParams;
	so.addParam("menu","false");
	so.addParam("wmode",showIt.wmode); // transparent, opaque <- nicht bei allowFullScreen=true
	so.addParam("quality","high");
	so.addParam("swLiveConnect","true");		
	so.addParam("allowFullScreen", "true");
	so.addParam("scaleMode", "showall");
	so.addParam("allowScriptAccess","always");
	so.addVariable("plugin_version", "9.0.115");
	so.addVariable("baseUrl", showIt.baseUrl);
	so.addVariable("configXml", configPath);
	if($defined(showIt.bandwidthPath)){
		so.addVariable("bandwidthPath",showIt.bandwidthPath);
	}
	so.addVariable("homePage", window.location.href);
	so.addVariable("domain", document.domain);
	so.addVariable("debug", "true");
	so.addVariable("swfBase", showIt.swfBase);
	so.setAttribute("style"," ");
	so.write(showIt.id);
}

function embedAS3Flash10Version(showIt){
	var so = new SWFObject(showIt.serverdomain + "/iptv/swf/xflv/showIt3.1.swf", "showIt", showIt.width, showIt.height,"10.0");
	try {
		so.useExpressInstall(showIt.serverdomain + '/iptv/swf/expressinstall.swf');
	}
	catch(e){}
	so.addParam("menu","false");
	so.addParam("wmode",showIt.wmode);
	so.addParam("quality","high");
	so.addParam("swLiveConnect","true");		
	so.addParam("allowFullScreen", "true");
	so.addParam("scaleMode", "showall");
	so.addParam("allowScriptAccess","always");
	so.addVariable("plugin_version", "10.0");
	if(showIt.bandwidth > 0){
		so.addVariable("bandwidth", showIt.bandwidth);
	}
	else if($defined(showIt.bandwidthPath)){
		so.addVariable("bandwidthPath",showIt.bandwidthPath);
	}
	so.addVariable("skin", showIt.skinName);
	so.addVariable("application", showIt.applicationId);
	if($defined(showIt.webcastId)){
		so.addVariable("webcastId", showIt.webcastId);
	}
	so.addVariable("baseUrl", showIt.baseUrl);
	so.addVariable("params", showIt.specialParams);
	so.addVariable("language", 'de');
	so.addVariable("homePage", window.location.href);
	//TODO check debug param
	so.addVariable("debug", "true");
	so.addVariable("jsEnabled", "true");
	so.addVariable("domain", document.domain);
	if(showIt.autoPlay != null){
		so.addVariable("autoPlay", showIt.autoplay);
	}
	if(showIt.playlistTemplate != null){
		so.addVariable("xasxTemplate", showIt.playlistTemplate);
	}
	if(showIt.enhancedStreaming == true){
		so.addVariable("fmsConnectionMode", "enhanced");
		if(showIt.tokens != null && showIt.tokens > 0){
			so.addVariable("urlTokens", showIt.tokens);
		}
	}
	if(showIt.customParams != null){
		for(var i = 0; i < showIt.customParams.length; i++){
			var paramParts = showIt.customParams[i].split("=");
			if(paramParts.length != 2){
				continue;
			}
			so.addVariable(paramParts[0], paramParts[1]);
		}
	}
	so.setAttribute("style"," ");
	so.write(showIt.id);
}

function embedAS3Version(showIt){
	var so = new SWFObject(showIt.serverdomain + "/iptv/swf/xflv/showIt3.swf", "showIt", showIt.width, showIt.height,"9.0.115");
	try {
		so.useExpressInstall(showIt.serverdomain + '/iptv/swf/expressinstall.swf');
	}
	catch(e){}
	so.addParam("menu","false");
	so.addParam("wmode",showIt.wmode);
	so.addParam("quality","high");
	so.addParam("swLiveConnect","true");		
	so.addParam("allowFullScreen", "true");
	so.addParam("scaleMode", "showall");
	so.addParam("allowScriptAccess","always");
	so.addVariable("plugin_version", "9.0.115");
	if(showIt.bandwidth > 0){
		so.addVariable("bandwidth", showIt.bandwidth);
	}
	else if($defined(showIt.bandwidthPath)){
		so.addVariable("bandwidthPath",showIt.bandwidthPath);
	}
	so.addVariable("skin", showIt.skinName);
	so.addVariable("application", showIt.applicationId);
	if($defined(showIt.webcastId)){
		so.addVariable("webcastId", showIt.webcastId);
	}
	so.addVariable("baseUrl", showIt.baseUrl);
	so.addVariable("params", showIt.specialParams);
	so.addVariable("language", 'de');
	so.addVariable("homePage", window.location.href);
	//TODO check debug param
	so.addVariable("debug", "true");
	so.addVariable("jsEnabled", "true");
	so.addVariable("domain", document.domain);
	if(showIt.autoplay != null){
		so.addVariable("autoPlay", showIt.autoplay);
	}
	if(showIt.playlistTemplate != null){
		so.addVariable("xasxTemplate", showIt.playlistTemplate);
	}
	if(showIt.enhancedStreaming == true){
		so.addVariable("fmsConnectionMode", "enhanced");
		if(showIt.tokens != null && showIt.tokens > 0){
			so.addVariable("urlTokens", showIt.tokens);
		}
	}
	if(showIt.customParams != null){
		for(var i = 0; i < showIt.customParams.length; i++){
			var paramParts = showIt.customParams[i].split("=");
			if(paramParts.length != 2){
				continue;
			}
			so.addVariable(paramParts[0], paramParts[1]);
		}
	}
	so.setAttribute("style"," ");
	so.write(showIt.id);
}

function load(showIt){
	if(showIt.launcher != null){
		showIt.launcher.removeEvents();
		showIt.launcher.setStyle('cursor', 'default');
		showIt.launcher.setStyle('visibility', 'hidden');
	}
	
	var holder = showIt.parentElement;
	if(showIt.embedMode == "overlay"){
		$$("body")[0].appendChild(holder);
	}
	var elementsToHide = new Array();
	if(Browser.Engine.trident  && !$defined(Browser.Engine.trident5)){
		elementsToHide = $$("select", "embed", "object");
	}
	else{
		elementsToHide = $$("embed", "object");
	}
	showIt.elementsToHide = elementsToHide;
	if(showIt.embedMode == "overlay"){
		holder.setStyles({
			position:"absolute",
			zIndex:showIt.zIndex,
			display:"block",
			top: showIt.y
		});
		if(typeof showIt.x == 'number'){
			holder.setStyle("left", showIt.x);
		}
		setupButton(showIt);
		var player = new Element("div", {
			"id":showIt.id,
			'styles': {
		        'position':'relative',
				'padding':0,
				'margin':0,
				'border':'none',
				'width': showIt.width,
				'height':showIt.height,
				'zIndex':showIt.zIndex,
				'display':'block'
		    }
		});
		showIt.player = player;
		showIt.parentElement.appendChild(player);
		if(showIt.version == "AS3"){
			embedAS3Version(showIt);
		}
		else if(showIt.version == "AS3_10"){
			embedAS3Flash10Version(showIt);
		}
		else{
			embedAS2Version(showIt);
		}
		if(showIt.x =="center"){
			showIt.optimizePosition();
			window.addEvent('resize', function(e){
				showIt.optimizePosition();
			});
		}
		//if (!window.ie && ! window.gecko) document.captureEvents(Event.MOUSEMOVE);
		addMouseListener(showIt);
	}
	else{
		var player = new Element("div", {
			"id":showIt.id,
			'styles': {
		        'position':'relative',
				'padding':0,
				'margin':0,
				'border':'none',
				'width': showIt.width,
				'height':showIt.height,
				'zIndex':showIt.zIndex,
				'display':'block'
		    }
		});
		showIt.player = player;
		showIt.parentElement.appendChild(player);
		if(showIt.version == "AS3"){
			embedAS3Version(showIt);
		}
		else if(showIt.version == "AS3_10"){
			embedAS3Flash10Version(showIt);
		}
		else{
			embedAS2Version(showIt);
		}
	}
}

function onMouseMovedInside(){
	//called from flash player
	if($defined(window.fireEvent)){
		window.fireEvent('mouseInside');
	}
}



function setupButton(showIt){
	if(!$defined(showIt.slideButton)){
		return;
	}
	if(Browser.Engine.trident){
		showIt.slideButton.setStyle("cursor", "hand");
	}
	else{
		showIt.slideButton.setStyle("cursor", "pointer");
	}
	
	showIt.slideButton.setStyle("visibility", "hidden");
}

function resizePlayer(width, height, callback){
	if($defined(window.fireEvent)){
		window.fireEvent('playerResize', [width, height, callback]);
	}
}

/**
 event listener delegates
*/
function addMouseListener(showIt){
	var listenerElement = window;
	if(Browser.Engine.trident){
		listenerElement = document;
	}
	listenerElement.addEvent('mousemove', function(event){
		showIt.handleMouseEvent(event);
	});
}

function addResizeEventListener(showIt){
	window.addEvent('playerResize', function(width, height, callback){
		showIt.onResized(width, height, callback);
	});
}

function addMouseInsideEventListener(showIt){
	window.addEvent('mouseInside', function(e){
		showIt.mouseOverState = "in";
	});
}

function addSlideOutEventListener(showIt){
	window.addEvent('slideOut', function(e){
		showIt.slideOut(e);
	});
}

function addSlideInEventListener(showIt, button){
	button.addEvent('click', function(e){
		showIt.slideIn(e);
	});
}

function addSlideOutReadyEventListener(showIt){
	window.addEvent('slideOutReady', function(e){
		showIt.onSlideoutReady(e);
	});
}

/**
end event listener delegates
*/

function autoInit(showIt, ctrl){
	if(ctrl != null){
		ctrl.addEvent('click', function(){
			load(showIt);
		});
	}
	else{
		window.addEvent('domready', function(){
			load(showIt);
		});
	}
	if(Browser.Engine.trident){
		window.addEvent('unload', function(){
			unload(showIt);
		});
	}
}

function slideOut(e){
	//called from flash player
	if($defined(window.fireEvent)){
		window.fireEvent('slideOut');
	}
}

function slidedOut(){
	if($defined(window.fireEvent)){
		window.fireEvent('slideOutReady');
	}
}

