/******************************************************************/
/* © DMC 01 Consulting & Development GmbH - gerald.urbas@dmc01.at */
/******************************************************************/
/* ARD Player                                                     */
/******************************************************************/
/* Defining Sizes, Connections and also Interfaces                */
/* to unified player interface. Providing funtionality to create  */
/* DOM Objects for Player (home / extended) 4 the ARD Video portal*/
/* Player configuration items located in player.html (urls, ids   */
/******************************************************************/
var loaded_Players = {}
var current_Player = false;
var current_PlayerDomId = false;
var fullscreenactive = false;


function dmcplayer() { //(avaible_url,furls,p_type,v_format) {
	/*URLS*/
	this.avaible_url = new Array();
	this.avaible_url['flashmedia'] = Array();
	this.avaible_url['microsoftmedia'] = Array(); 
	this.avaible_url['realmedia'] = Array();
	this.avaible_url['quicktime'] = Array();	
	
	this.dl_url = new Array();
	this.dl_url['flashmedia'] = Array();
	this.dl_url['microsoftmedia'] = Array();
	this.dl_url['realmedia'] = Array(); 
	this.dl_url['quicktime'] = Array();

	this.function_urls = new Array();
	this.function_urls['setting'] = false;
	this.function_urls['vote'] = false;
	this.function_urls['info'] = false;
	this.function_urls['links'] = false;
	this.function_urls['comment'] = false;
	this.function_urls['recommend'] = false;
	
	this.download_url = false
	this.rss_url = false;
	this.carrier_url = false;
	this.ivw_tag = false;
	this.enable_ivw_tag = false;
	this.debug_ivw_tag = false;
	this.previewimage = false;
	/*URLS*/
	/* Player configs */
	this.player_world = false;
	this.player_type = "extended"; // or home or simple
	this.video_format = "16_9"; // or 4_3 or audio
	this.layer_id = "video"; // ID of DOM Object
	this.layerhq_id = "hqvideo"; // ID of DOM Object
	this.layerec_id = "extended_controls"; // ID of DOM Object
	this.livestream = false;
	this.mp3stream = false;
	this.autostart = true; // false
	this.enablebuffering = true; // false
	/* Player configs */
	// init vars
	this.detected_plugins = new Array();
	this.avaibleplayers = new Array("flashmedia","microsoftmedia","realmedia","quicktime"); // Player chain
	this.defaultplayer = "flashmedia"; // default player
	this.minimal_version = {"flashmedia":7,"microsoftmedia":10,"realmedia":6,"quicktime":7};
	this.minimal_version_fallback = {"flashmedia":new Array("quicktime",3)};
	this.defaultconn = 1; // default Connection speed	
	this.lowQ = 1;
	this.midQ = 2;
	this.highQ = 3;
	this.errorAjax = {noplayer:'error/noplayer',otherplayer:'error/otherplayer',noplugin:'error/noplugin'}
	this.avaibleconns = {'1':"Modem/ISDN",2:"DSL",3:"VDSL"}; // avaible sizes
	// 16/9 size defs//
	this.vsizes16_9={'1':Array(),2:Array(),3:Array()};
	this.vsizes16_9['1'] = {'w':256,'h':144};
	this.vsizes16_9['2'] = {'w':512,'h':288};
	this.vsizes16_9['3'] = {'w':960,'h':544};
	// 4/3 size defs//
	this.vsizes4_3={'1':Array(),2:Array(),3:Array()};
	this.vsizes4_3['1'] = {'w':192,'h':144};
	this.vsizes4_3['2'] = {'w':384,'h':288};
	this.vsizes4_3['3'] = {'w':720,'h':544};
	// Audio Size
	this.vsizesaudio={'1':Array(),2:Array(),3:Array()};
	this.vsizesaudio['1'] = {'w':256,'h':29};
	this.vsizesaudio['2'] = {'w':573,'h':29};
	this.vsizesaudio['3'] = {'w':960,'h':29};
	this.globid = Math.round(Math.random()*10000);
	this.flashstreamingserver = "";
	this.savecookies = true;
	this.saveAbleCookies = true;
	this.testspeed=false;
	this.currentplayer = false;
	this.settings = false;
	this.usedplayers = new Array();
	this.defaultavaible = false;
	this.rememberdavaible=false;
	this.vsizes = this.vsizes16_9;
	this.players = new Array(this.vsizes);
	this.ivwcount_url = false;
	this.ivwcount_url_added = false;
	// init var
	/* public methods*/
	this.start = dmcplayerstart; // start determinies which player should be generated and call main functions
	this.play = playPlayer; // API to current Plugin Object play method
	this.pause = pausePlayer; // API to current Plugin Object pause method
	this.stop = stopPlayer; // API to current Plugin Object stop method
	this.fastf = fastForwPlayer; // API to current Plugin Object Fast forward method
	this.fastr = fastRewPlayer; // API to current Plugin Object Fast rewind method
	this.setPosition = setPositionPlayer; // API to current Plugin Object set Movie Position (timeline) method
	this.fullscreen = fullscreenPlayer; // API to current Plugin Object Fullscreen mode method
	this.carrier = carrierPlayer; // API to current Plugin Object carrier method
	this.volume = setVolumePlayer; // API to current Plugin Object Volume method
	this.mute = setMutePlayer // API to current Plugin Object Shutdown method
	/* public methods*/
	/* only internal methods*/
	/*VIP Methods*/
	this.init = dmcplayerinit; // init the player final creation
	this.cookietest = cookietest; // helper for testing
	this.writevideo = writevideo; // API to current Plugin Object - write method
	this.wrongversion = writeminmalversioninfo // API to current Plugin Object - Versioninfo method
	this.switchPlayer = switchPlayer; // remove old current player / generate new code
	this.setPlayer = setPlayer; // set the playertype
	this.shutdown = shutdownPlayer // API to current Plugin Object Shutdown method
	// Cookie settings related
	this.rememberSetting = rememberSetting; // Cookie remembering
	this.readSetting = readSetting; // Cookie settigns retrieving
	this.homeSetting = homeSetting; // setting 4 homemode
	this.simpleSetting = simpleSetting; // setting 4 simplemode
	// initiate Buttons
	this.initHomeButtons = initHomeButtons; // Homebuttons
	this.initExtendedButtons = initExtendedButtons; // Buttons for the extended playermode
	this.setCOB = setCarryOpenB; // gen. Popupbutton 4 Extended Audioplayer 
	this.setHQB = setHQB; // gen. HQbutton 4 Extended Videoplayer
	this.setPopupB_HQ = setPopupBHighQuality; // gen. Popupbutton 4 HQ Mode in Extended Audioplayer 
	this.setPopupB = setPopupB; // gen. Popupbutton in Extended Audioplayer 
	// HQ / Popup/ Carriar calls
	this.loadHqPlayer = loadHq; // call HQ mode
	this.initHqInterface = genHQInterface
	this.closeHqPlayer = closeHq; // close HQ mode
	this.loadPopup = loadPopup; // Open Popup
	this.closePopup = closePopup; // Called while closing the popup
	this.loadCarrier = loadCarrier; // call Audio popup (player carrier)
	//Speedtest
	this.startbyspeedtest = startbyspeedtest; // if enabled start the connection speed test
	this.testSpeed = testSpeed; // function 4 speedtest Picture generation
	/* only internal methods*/
	
	/* anon methods*/
	// IVW Zählung
	this.countIVW = function () {
		if (this.ivwcount_url_added==true) {
			if (this.debug_ivw_tag==true) {
				alert("IWV Tag already added!");
			}
			this.debug("IWV Tag already added!");
			return;
		}
		if (!this.ivw_tag) {
			if (this.debug_ivw_tag==true) {
				alert("no IWV Tag defined!");
			}
			this.debug("no IWV Tag!");
		} else {
			if (this.debug_ivw_tag==true) {
				alert("Count TVW tag: "+this.ivw_tag+" "+this.ivwcount_url);
			}
			$j('#'+this.layer_id).append('<img style="border:0px solid red;" src="'+this.ivwcount_url+'" width="1" height="1" alt="szmtag">');
			this.debug("Count TVW tag: "+this.ivw_tag+" "+this.ivwcount_url);
			this.ivwcount_url_added=true;
		}
	}
	
	this.initIVW = function () {
		var currentivw_TYPE = IVW_TYPE;
		if (this.ivw_tag) {
			currentivw_TYPE = this.ivw_tag
		}
		var IVW="http://"+IVW_ANGEBOTSKENNUNG+IVW_BASEURL+currentivw_TYPE+"/"+IVW_CODE+";"+IVW_COMMENT+"";
		this.ivwcount_url = IVW+"?r="+escape(document.referrer)+"&d="+(Math.random()*100000);
		this.debug("init IVM with: "+this.ivwcount_url);
		if (this.debug_ivw_tag==true) {
			alert("IVMTag: "+this.ivwcount_url +" "+this.ivw_tag);
		}
		if (this.autostart==true) {
			this.countIVW();
		}
	}
	
	this.dlurls = function() {
		for(i in this.dl_url){
			if (this.dl_url[i].length==0) {
				this.dl_url[i] = this.avaible_url[i];
			}
		}
	}
	
	// function for retrieving High Qhality URL
	this.getHqAvaible = function() {
		if (typeof this.avaible_url[this.settings['player']][this.highQ]!="undefined") {
			url = this.avaible_url[this.settings['player']][this.highQ];
			return url;
		}
		return false;
	}

	// returns the video URL based on cookie saved settings
	this.getCurrentUrl = function() {
		return this.avaible_url[this.settings['player']][this.settings['conn']];
	}
	
	this.generateplayermatrix = function(arr)  {
		this.debug("new Playermatrix requested");
		this.avaibleplayers = arr;
		this.avaible_url = new Array();
		this.dl_url = new Array();
		for(var i=0;i<arr.length;i++) {
			this.avaible_url[arr[i]] = new Array();
			this.dl_url[arr[i]] = new Array();
			this.debug("added "+arr[i]+" to playermatrix");
		}
	}
	
	this.debug = function (str) { // debuglayer is deativated @ moment
		dbg("dmcplayer: "+str);
	};
	
	this.customerror = function (e) {
			obj = $j('#'+this.layer_id)
			obj.empty();
			obj.load(this.errorAjax[e]+APPHTMLEXTENSION)
			$j.getScript(this.errorAjax[e]+APPJSEXTENSION);
	}
	
	this.isDomId = function(qid) {
		//alert(this.players[this.currentplayer].objid+" "+qid)
		obj = this.players[this.currentplayer]
		if (typeof obj!="undefined" && obj.objid == qid) {
			return true;
		} else {
			return false
		}
	}
	
	this.cleanUrlArray = function() {
		//alert(this.avaible_url);
		for(var p in this.avaible_url) { // URLS in config
			for(var c in this.avaible_url[p]) { // URLS in config
				if (this.avaible_url[p][c]=='') {
					delete this.avaible_url[p][c];
				}
			}
		}
	}
	/* anon methods*/
	/* init DMC player object*/
	this.debug("Player Object created");
}

function dmcplayerstart() {
	this.cleanUrlArray();
	if (this.video_format=="4_3") {
		this.vsizes = this.vsizes4_3;
	}
	if (this.video_format=='audio') {
		this.vsizes = this.vsizesaudio;
	}
	this.dlurls();
	if (this.player_type=='extended') { // Simple Player has beneath no Options
		if (this.testspeed==true) {
			this.testspeed=false;
			this.debug("Speed test requested");
			this.testSpeed();
			this.debug("Speed test running 1 "+connectionSpeedTestfinished +" Stop Player start");
			return;
		}
		if (connectionSpeedTestfinished==true) {
			this.debug("Player Object started "+this.player_type);
			this.readSetting();
			this.init();
			this.initExtendedButtons();
		}
	} else if (this.player_type=='simple') { // Simple Player has beneath no Options
		this.debug("Player Object started "+this.player_type);
		this.simpleSetting();
		this.savecookies = false;
		this.init();
		for (attr in loaded_Players)
			this.debug("registered Player"+loaded_Players[attr]+" - "+attr)
		
	} else if (this.player_type=='home') { // Homepage player has different behaviour
		this.debug("Player Object started "+this.player_type);
		this.homeSetting();
		this.init();
		this.initHomeButtons();
	} else { // Extended player provides full interface
	}
	if (this.enable_ivw_tag) {
		this.initIVW();
	}
	this.debug("Player useable");
	//if (this.autostart==true) {
		//this.play();
	//}
	return true;
}

function cookietest() {
	$j.cookie('TC',true);
	if ($j.cookie('TC')==null) {
		this.saveAbleCookies = false;
	}
	this.debug("Test Cookie function: "+this.saveAbleCookies);
}

// Save setting to the Cookie and to the current player vars
function rememberSetting(p,c) {
	this.debug("saved cookie settings p:"+p+ " c:"+c);
	if (this.savecookies==true) {
		if (this.player_type!='home') {
			$j.cookie('playertype',p);
			$j.cookie('connspeed',c);
		} else {
			this.debug("in Home player we do not remember settings permanent");
		}
	} else {
			this.debug("cookie saving is disabled");
	}
	this.settings['player'] = p;
	this.settings['conn'] = c;

}

// retrieve setting from the cookie, or set defaults (see this.defaultplayer and this.defaultconn)
function readSetting() {
	this.debug("read Cookie settings");
	this.cookietest();
//	if (this.savecookies==true) {
		this.debug("readSetting  - save Cookie settings");
		var p = $j.cookie('playertype');
		var c = $j.cookie('connspeed');	
		this.settings = new Array();
		if (p!="false" && p!=null && c!=null) { // if cookies avaible set them
			this.debug("found cookie settings p:"+p+ " c:"+c);
			if (c==this.highQ) {c=this.midQ}; // never save Highquality movies
			this.settings['player'] = p;
			this.settings['conn'] = c;
		} else {
			this.debug("no cookies!");
			this.rememberSetting(this.defaultplayer,this.defaultconn)
		}
//	} else {
//		#this.debug("readSetting  - save Cookie settings disabled - use defaults");
		//this.rememberSetting(this.defaultplayer,this.defaultconn)
//	}
	return this.settings;
	//alert($j.cookie('connspeed'));
}

// initialize Home player settings. should alwas be small video with default Player or if avaible choosen playertype
function homeSetting() {
	this.debug("set Home settings");
	this.settings = new Array();
	var p = $j.cookie('playertype');
	var homep = $j.cookie('homeplayertype');
	if (p!="false" && p!=null) {
		this.settings['player'] = p;
	}else if (homep!="false" && homep!=null) {
		this.settings['player'] = homep;
	} else {
		this.settings['player'] = this.defaultplayer;
	}
	this.settings['conn'] = this.lowQ;
	return this.settings;
}

// initialize Simple player settings. should alwas be small video with a defined playertype
function simpleSetting() {
	this.debug("set Simple settings");
	this.settings = new Array();
	this.settings['player'] = this.defaultplayer;
	this.settings['conn'] = this.lowQ;
	return this.settings;
}

// generate the radiobuttons for the Homeplayer. 
function initHomeButtons() {
	this.debug("create Homebuttons");
	var controls = $j("#"+this.layerec_id);
	controls.append('');
	for(var p in this.usedplayers) { // iterate over enabled players
		try {	// shouldnt fail, but possible in case of malformed configuration
			var obj = this.players[this.usedplayers[p]];
			this.debug(p);
			var checked='';
			this.debug("? checked player: "+this.settings['player']+" == "+obj.typ);
			if (this.settings['player'] == obj.typ) { // Check the avaible player
				var checked=' checked="true" ';
			}
			var domid= 'r_'+obj.typ; // generate an id for label / input combination
			controls.append('<p><input id="'+domid+'" type="radio" name="pformat" value="'+obj.typ+'" '+checked+'  /><label id="label'+domid+'"  value="'+obj.typ+'" for="'+domid+'">'+obj.name+'</label></p>');
			$j('#'+domid).bind('click', function () { // Bind Click
					if (player.currentplayer!=$j(this).attr('value')) { // only switch if Playervalue will change
						$j.cookie('homeplayertype',$j(this).attr('value'));
						player.switchPlayer($j(this).attr('value')); // jsut switch the player
					}
			}); // Bind Click
		}
		catch(err) {
			this.debug("adding home radio button for "+this.usedplayers[p]+" failed")
		}
	}
	//controls.append('');?? not needed??
}

// Extended Player needs many Buttons..
function initExtendedButtons() {
	var rssobj = $j("#ic_rss"); // generate URL, JS; for RSS feeds (defined in var rss_url in player config)
	if (this.rss_url!=false) {
		rssobj.show();
		rssobj.attr('rssurl',this.rss_url);
		rssobj.attr('href','javascript:;');
		rssobj.bind("click", function(){
		location.href=$j(this).attr('rssurl');
		});
	} else {
		rssobj.hide();
	}
	var dlobj = $j("#ic_dl"); // generate URL, JS; for Downloads (generated by getCurrentUrl)
	if (this.download_url!=false) {
		dlobj.show();
		dlobj.attr('dlurl',this.download_url);
		dlobj.attr('href','javascript:;');
		dlobj.bind("click", function(){
		location.href=$j(this).attr('dlurl');
	});
	} else {
		dlobj.hide();
	}
	// functionurls defines setting,vote,info,links,comment,recommend
	// each of this URLS must be specific for the choosen Movie, so its gets defined in player configuration
	// Buttons hav ID presantations in Template file.. and get enhanced by this lines of code.
	for (var button in this.function_urls) { // for
		//alert(button);
		this.debug(button);
		var bobj = $j("#b_"+button);	 // the button object
		bobj.attr('href','javascript:;'); // rewrtite href to JS
		bobj.attr("url",this.function_urls[button]); // save URL 
		bobj.attr("button",button) // tell the button is name
		bobj.bind("click", function(){ // Clickfunciton
				closeHelpInfoObj()
				var obj = $j(this); // this
				var b = obj.attr("button"); // get buttonname
				var url = obj.attr("url"); // get URL
				obj.attr("current",true); // current obj 
				player.debug(b + "_url:"+url); 
				var cobj = $j("#optionBoxContainer"); // The Container for the contents of the Tab
//				alert(ec_current);
				$j("#b_"+ec_current).removeClass("optActive"); // remove Class from old current 
				cobj.empty(); // empty tab Container
				if (ec_current!=b) { // if this button not selected fill it
					obj.addClass("optActive"); // active current 
					cobj.empty(); // 1. remove all children
					loading($j('#optionBoxContainer')); // set loading anim 
					//cobj.load(url+".html",null,setScrollPanes()); // load the URL into optionBoxContainer
					cobj.load(url+APPHTMLEXTENSION,null); // load the URL into optionBoxContainer
					cobj.attr("url",url); // save url to optionBoxContainer
					$j.getScript(url+APPJSEXTENSION); // load JS file (some tabs need JS code)					
					ec_current = b; // set marker 4 current state
				} else {
					ec_current = false; // if button is selected we deselect it / set ec_current=false.. class was removed before.
				}
		});// Clickfunciton
		if (this.function_urls[button]==false) {
			bobj.hide();
		} else {
			bobj.show();
		}
	} // for
	// set HQ and Fullscreen (popup) functions
	if (this.currentplayer) {
		this.setCOB();
		this.setHQB();
		this.setPopupB();
	}
}

function setCarryOpenB() {
	var coobj = $j("#ic_carryopen"); 
	if (this.mp3stream==true) {
		coobj.show();
		coobj.attr('href','javascript:;');
		coobj.unbind();
		coobj.bind("click", function(){
			dbg("CarryOpen Button Click");		
			player.loadCarrier(1); // method for Carrier popup
		});
	} else {
		coobj.hide();
	}
}

function setHQB() {
	var hqobj = $j("#ic_hq"); // generate HQ buttons if avaible, (--> getHqAvaible)
	var avaible = this.getHqAvaible();
	if (avaible && this.mp3stream==false) { // HQ is avaible
		hqobj.show(); // show button an rewrite code
		hqobj.attr('href','javascript:;');
		hqobj.attr('hqurl',avaible);
		hqobj.unbind();
		hqobj.bind("click", function(){
			dbg("HQ Button Click");		
			player.loadHqPlayer(1); // method for HQ switch
		});
	} else {
		hqobj.hide(); // no HQ  - hide the button
	}
}

function setPopupB() {
	var popupobj = $j("#ic_popup");
	if (typeof this.players[this.currentplayer]!="undefined" && this.players[this.currentplayer].testscriptconn()  && this.mp3stream==false) {
		popupobj.show(); // show button an rewrite code
		popupobj.attr('href','javascript:;');
		//popupobj.attr('hqurl',avaible);
		popupobj.unbind();
		popupobj.bind("click", function(){
					dbg("Fullscreen Button Click");		
					player.loadPopup(); // method for POPUP switch
		});
	} else {
		popupobj.hide(); // no HQ  - hide the button
	}
}

function setPopupBHighQuality() {
	var popupobj = $j("#"+this.layerhq_id+'fs');
	if (this.players[this.currentplayer].testscriptconn()  && this.mp3stream==false) {
		popupobj.show(); // show button an rewrite code
		popupobj.attr('href','javascript:;');
		popupobj.unbind();
		popupobj.bind("click", function(){
					dbg("HQ Fullscreen Button Click");
					player.loadPopup(); // method for POPUP switch
					player.initHqInterface();
		});
	} else {
		popupobj.hide(); // no HQ  - hide the button
	}
}

// this is the main function. It checks which playerurls, plugins and resulting Options avaible for the player. 
function dmcplayerinit() {
	this.debug("get Player type Mode:"+this.player_type);
	//alert(this.playertype)
	var ids = new Array(); // tmeo array
	for(var p in this.avaibleplayers) { // avaible players means which plugins defined in dmcplayer
		//this.debug("show avaible codes: "+this.avaibleplayers[p]+"_Playercode");
		ids[this.avaibleplayers[p]]=p;
	}
	for(var p in this.avaible_url) { // URLS in config
		this.debug("init Player code for avaible player"+p);
		this.debug("check avaible URLS"+this.avaible_url[p]);
		this.debug(p+" Plugin avaible in browser "+this.detected_plugins[p]);
		var versionOK = true;
		if (typeof detected_plugin_versions[p]!="undefined" && this.minimal_version[p]>detected_plugin_versions[p]) {
			this.debug("Version Check: KO - Found minimalversion "+this.minimal_version[p]);
			versionOK = false;
		} else {
			this.debug("Version Check:OK");
		}
		if (typeof detected_plugin_versions[p]=="undefined" && this.detected_plugins[p]==true) { 
			versionOK = true;
		}
		//alert(p+" "+this.detected_plugins[p]+" "+this.avaible_url[p].length+" "+versionOK)
		if (this.detected_plugins[p]==true && this.avaible_url[p].length > 1 && versionOK==true) {
			var playerobj = eval("new "+this.avaibleplayers[ids[p]]+"_Playercode('"+this.player_type+"')"); // load the playerobject (witch eval && new)
			this.debug("check Plugin for "+p+" pstring"+playerobj.detectionplugin+" typ"+playerobj.typ);
			playerobj.setglobid(this.globid);
			playerobj.setconn(this.avaible_url[this.avaibleplayers[ids[p]]]); // set conns ...
			playerobj.setPreviewimage(this.previewimage);
			playerobj.setsizes(this.vsizes); // and sizes to the player object
			playerobj.setplayertype(this.player_type,this.minimal_version[p],this.livestream,this.mp3stream,this.flashstreamingserver,this.enablebuffering);
			playerobj.setautostart(this.autostart);
			//alert(this.playertype)
			//alert(playerobj.playertype)
			this.usedplayers.push(p); // usedplayers holds finally avaible Players.
			this.debug("found Plugin for "+p+" pstring"+playerobj.detectionplugin);
			this.players[this.avaibleplayers[ids[p]]] = playerobj; // save the Player plugin 
			for(url in this.avaible_url[ids[p]]) { // debug checking for avaible URLS
				this.debug("URL("+ids[p]+":"+url+")"+this.avaible_url[ids[p]][url]+"");
				//this.players[this.avaibleplayers[p]].pconn[url] = this.avaible_url[p][url];
			}
			
		} else {
			this.debug("PLUGIN ("+p+") FOR INSTANCE ("+this.globid+") IS NOT AVAIBLE");
		}
	}
	
	if (this.usedplayers.length==0) {
		this.customerror("noplugin");
		return;
	}
	//if (this.playertype!='home') {
	// Now we need to test little more options....
	this.debug("Check defaults usedplayers:"+this.usedplayers.length);		
	for(p in this.usedplayers) { // for each enabled player
		this.debug("check default avaible --- "+this.usedplayers[p]+ "=="+this.defaultplayer);
		if (this.usedplayers[p]==this.defaultplayer) { // this is the default player... fine
			this.defaultavaible=true;
		}
		var rememberedsetting = this.settings['player'];
		if (this.player_type!='extended') {
				rememberedsetting = $j.cookie('homeplayertype',$j(this).attr('value'));
		}
		this.debug("check remembered avaible --- "+this.usedplayers[p]+ "=="+this.settings['player']);
		if (this.usedplayers[p]==rememberedsetting) { // the used player is remembered in Settings also fine
			this.rememberdavaible=true;
			this.rememberdavaibleid=p;
			var connections = this.players[this.usedplayers[p]].getconn();
			this.debug("check remembered stream avaible --- "+this.settings['conn']+ " == "+connections);
			if (typeof connections[this.settings['conn']]=="undefined" ) {
				if (typeof connections[1]!="undefined" ) {
					this.settings['conn'] = 1;
				}	
				if (typeof connections[2]!="undefined" ) {
					this.settings['conn'] = 2;
				}
			}
		}
	}
	// above we fuond out that default is avaible or not... if not we need some other player
	if (this.defaultavaible==false) {
		this.debug("default avaible == false"+" "+this.defaultplayer+" "+this.usedplayers[0]);
		var connections = this.players[this.usedplayers[0]].getconn();
		if (typeof connections[this.settings['conn']]=="undefined" ) {
				if (typeof connections[1]!="undefined" ) {
					this.settings['conn'] = 1;
				}
				if (typeof connections[2]!="undefined" ) {
					this.settings['conn'] = 2;
				}
		}
		this.defaultplayer = this.usedplayers[0]; // so i use the First usedplayer...
		this.rememberSetting(this.usedplayers[0],this.settings['conn']); // anbd remember it...
	}
	// above we found out that user remembered something - so set this remembered player 
	if (this.rememberdavaible==true) {
		this.debug("remembered avaible == true"+" "+this.defaultplayer+" "+this.usedplayers[0]);
		this.defaultplayer = this.usedplayers[this.rememberdavaibleid]; // setted a few lines above
		this.rememberSetting(this.usedplayers[this.rememberdavaibleid],this.settings['conn']);// anbd remember it...
	}
	// Debug check
	if (this.defaultavaible==false && this.rememberdavaible==false){
		this.debug("no default or remembered player found");
		//alert(this.usedplayers);
	}
	
	/*if (this.savecookies==false) {
		this.debug("Savecookies is off...");
		if (this.usedplayers[0]!="undefined") {
			this.debug("Savecookies is off... P avaible:"+this.usedplayers[0]);
			//this.defaultplayer = this.usedplayers[0];
			this.currentplayer = this.usedplayers[0];
			var conns_avaible = this.players[this.currentplayer].getconn();
			for(c in conns_avaible) { // for each enabled conn
				this.debug("Savecookies is off... C avaible:"+conns_avaible[c]);
				this.defaultconn = conns_avaible[c];
			}
			this.debug("Savecookies is off... remember - P:"+this.currentplayer+" C:"+this.defaultconn);
			//this.rememberSetting(this.currentplayer,this.defaultconn);
			this.settings['player'] = this.currentplayer;
			this.settings['conn'] = this.defaultconn;
			//alert(1+" "+this.usedplayers[0]+" "+this.settings+" "+this.players[this.usedplayers[0]].getconn())
		}
	}*/
	
	this.currentplayer = this.settings['player']; // set our current player
	this.currenturl = this.settings['conn']; // set the current URL
	
	loaded_Players[this.globid] = this;
	this.switchPlayer(this.currentplayer); // and switch the player... waht means we generate it here initially-
}

// switching player is more complex
function switchPlayer(ptype) {
	if (ptype==false) { // we want to switch to an unavaible player... not possible
		this.debug("switch Player with"+ptype+" is not supported");
		return;
	} else { // player is possible
		this.debug("switch Player "+ptype);
		if (this.usedplayers.length==0 && typeof this.players[this.currentplayer]=="undefined") { // Player is undefined... Player is not ready.. so stop
			this.debug("switch Player error - No not avaible! "+this.currentplayer)
			this.customerror("noplugin");
			return;
		}
		if (this.players.length==0 && typeof this.players[this.currentplayer]=="undefined") { // Player is undefined... Player is not ready.. so stop
			this.debug("switch Player error - previous player not avaible! "+this.currentplayer)
			this.customerror("noplayer");
			return;
		}
		try {
			this.shutdown()
//			this.players[this.currentplayer].shutdown();
		}catch(e) {
			dbg("shutdown of "+this.currentplayer+ "  failed")
		}
		this.setPlayer(ptype); // set playertype
		if (this.players.length>0 && typeof this.players[this.currentplayer]=="undefined") { // Player is undefined... Player is not ready.. so stop
			this.debug("switch Player error - previous player not avaible! "+this.currentplayer)
			this.debug("switch Player error - alternativeplayers count! "+this.players.length)
			this.customerror("otherplayer");
			return;
		}
		if (typeof this.players[this.currentplayer]=="undefined") { // Player is undefined... Player is not ready.. so stop
			this.debug("switch Player error - player not ready "+this.currentplayer)
			return;
		}
		this.debug("obj creator"+this.currentplayer+" "+this.players[this.currentplayer]);
		var obj = this.players[this.currentplayer]; // get obj
		if (obj.enabled) {
			if (this.player_type == 'extended') {
				SCRIPTCONN = setInterval("testfullscreenbuttonavaibility()", 2500);
				this.setCOB();
				this.setHQB();
				this.setPopupB();
			}
			this.writevideo(obj,this.layer_id); // Finally write oput the´video with the urrent player plugin
		} else {
			this.debug("Player:"+ptype+" is unavaible ("+this.players[this.currentplayer].enabled+")");	
		}
	}
}

// call the subfunction write of the player objects. by using settings array.
function writevideo(obj,div) {
	this.debug("Select player code based on recogization div:"+div+" conn:"+this.settings['conn']);
	//alert(div+" "+this.settings['conn']);
	obj.write(div,this.settings['conn']);
}

function writeminmalversioninfo() {
		$j('#'+this.layer_id).empty();
		$j('#'+this.layer_id).append("Die Version Ihres Plugins ist nicht ausreichend")
}

// each Playerplugin hase its own play/pause options.. this is somee abstract function for that. (wanna say player.play()..)
function playPlayer() {
	var obj = this.players[this.currentplayer];
	if (typeof obj!="undefined") {
		for (p in loaded_Players) {
			if (loaded_Players[p]!=this) {
				loaded_Players[p].pause();
			}
		}
		obj.play();
		current_Player = this;
		this.debug("play ID:"+this.globid);
	} else {
		this.debug("Play: No Plugin ID:"+this.globid);
	}
}

function shutdownPlayer() {
	var obj = this.players[this.currentplayer]
	if (typeof obj!="undefined") {
		obj.shutdown();
		this.debug("shutdown ID:"+this.globid);
	} else {
		this.debug("shutdown: No Plugin ID:"+this.globid);
	}
}


// each Playerplugin hase its own play/pause options.. this is somee abstract function for that. (wanna say player.play()..) 
function pausePlayer() {
	var obj = this.players[this.currentplayer]
	if (typeof obj!="undefined") {
		obj.pause();
		this.debug("pause ID:"+this.globid);
	} else {
		this.debug("Pause: No Plugin ID:"+this.globid);
	}
}

// each Playerplugin hase its own play/pause options.. this is somee abstract function for that. (wanna say player.play()..) 
function stopPlayer() {
	var obj = this.players[this.currentplayer]
	if (typeof obj!="undefined") {
		obj.stop();
		this.debug("Stop ID:"+this.globid);
	} else {
		this.debug("Stop: No Plugin ID:"+this.globid);
	}
}

// each Playerplugin hase its own play/pause options.. this is somee abstract function for that. (wanna say player.play()..) 
function fastForwPlayer() {
	var obj = this.players[this.currentplayer]
	if (typeof obj!="undefined") {
		obj.fastf();
		this.debug("Fastforw ID:"+this.globid);
	} else {
		this.debug("Fastforw: No Plugin ID:"+this.globid);
	}
}

// each Playerplugin hase its own play/pause options.. this is somee abstract function for that. (wanna say player.play()..) 
function fastRewPlayer() {
	var obj = this.players[this.currentplayer]
	if (typeof obj!="undefined") {
		obj.fastr();
		this.debug("FastRev ID:"+this.globid);
	} else {
		this.debug("FastRev: No Plugin ID:"+this.globid);
	}
}

function fullscreenPlayer() {
	var obj = this.players[this.currentplayer]
	if (typeof obj!="undefined") {
		obj.fullscreen(this.settings['conn']);
		this.debug("fullscrenn ID:"+this.globid);
	} else {
		this.debug("fullscrenn: No Plugin ID:"+this.globid);
	}
}

function setPositionPlayer(pos) {
	var obj = this.players[this.currentplayer]
	if (typeof obj!="undefined") {
		obj.position(pos);
		this.debug("position ID:"+this.globid);
	} else {
		this.debug("position: No Plugin ID:"+this.globid);
	}
}

function setVolumePlayer(pos) {
	var obj = this.players[this.currentplayer]
	if (typeof obj!="undefined") {
		obj.volume(pos);
		this.debug("position ID:"+this.globid);
	} else {
		this.debug("position: No Plugin ID:"+this.globid);
	}
}

function setMutePlayer(mute) {
	var obj = this.players[this.currentplayer]
	if (typeof obj!="undefined") {
		return obj.mute(mute);
		this.debug("position ID:"+this.globid);
	} else {
		this.debug("position: No Plugin ID:"+this.globid);
	}
}


function carrierPlayer() {
	var obj = this.players[this.currentplayer]
	if (typeof obj!="undefined") {
		obj.carrier();
		this.debug("carrier ID:"+this.globid);
	} else {
		this.debug("carrier: No Plugin ID:"+this.globid);
	}
}

// set playertype
function setPlayer(ptype) {
	this.debug("set Player "+ptype);
	this.currentplayer = ptype;
}

// Load HQ Movie needs some layer hiding cleaning..
function loadHq() {
	this.debug("Load HQ Player"+arguments[0]);
	$j('#playermodule').hide(); // hide the player module
	var page=$j("#page"); //get teh pag obj
	this.debug("save Cookie"+this.settings['conn']);
	$j.cookie('smallplayer',this.settings['conn']); // save small player settings
	var obj = this.players[this.currentplayer]; // playerobj
	this.rememberSetting(this.currentplayer,this.highQ); // remember  Highquality movie
	if (obj.enabled) { // if playerobject
		$j('#'+this.layerhq_id).empty(); // empty HQ Div
		$j('#'+this.layerhq_id).show(); // show it
		$j('#'+this.layer_id).empty(); // empty video layer... double plugin usage isnt good
		$j('#page').hide(); // hide the complete page
		this.writevideo(obj,this.layerhq_id); // write the current (HQ) video to the hqvideo Div
		//alert(this.currentplayer);
		$j(document).keydown( function(e) {
				var evtobj=window.event? event : e //distinguish between IE's explicit event object (window.event) and Firefox's implicit.
				var unicode=evtobj.charCode? evtobj.charCode : evtobj.keyCode
				var actualkey=String.fromCharCode(unicode)
				if (unicode==27) {
					dbg("ESC Key Pressed")
					if (fullscreenactive==true) {
						dbg("ESC Key Pressed but do nothing - fullscreenopened!");
						fullscreenactive=false;
					} else {
						window.setTimeout("player.closeHqPlayer()", 100);
					}
				}
		});
		this.initHqInterface();
	} else {
		this.debug("Player:"+ptype+" is unavaible ("+this.players[this.currentplayer].enabled+")");
		$j('#'+this.layerhq_id).append('<span class="error">laden des Highqualityplayers fehlgeschlagen</span>');	
	}
}

function genHQInterface() {
			var closerid=this.layerhq_id+'close';
			var fsid=this.layerhq_id+'fs';
			$j('#'+closerid).remove();
			$j('#'+fsid).remove();
			$j('#'+this.layerhq_id).append('<div id="'+fsid+'"><a class="fullscreen" href="javascript:;"></a></div>'); //append fullscreen button
			$j('#'+this.layerhq_id).append('<div id="'+closerid+'"><a href="javascript:;">Schlie&szlig;en</a></div>'); //and append close button
			var hqvideoclose = $j('#'+closerid); // get the Closebutton object
				hqvideoclose.unbind();
				hqvideoclose.bind("click", function(){ // bind the click
					player.closeHqPlayer(); // Call function... ... reason Flash also di this...
				});
			$j('#'+fsid).hide();
			SCRIPTCONN = window.setInterval("testfullscreenbuttonavaibility()", 2500);
			$j('#hqvideo').show();

}

// Closing the HQ player
function closeHq() {
			$j(document).unbind('keydown');
			dbg("Close HQ Player______________")
			$j('#'+this.layerhq_id).empty(); // empty ..
			$j('#'+this.layerhq_id).hide(); // and hide HQ layer
			var closeerid=this.layerhq_id+'close';
			$j('#'+closeerid).empty(); // empty ..
			$j('#'+closeerid).hide(); // and hide HQ layer
			this.players[this.currentplayer].shutdown();
			$j('#page').show(); // show the page
			if ($j.cookie('smallplayer')==null) {
				var cs = this.defaultconn;
			} else {
				var cs = $j.cookie('smallplayer');
			}
			player.rememberSetting(player.currentplayer,cs); // remember old player settings
			dbg("Close HQ Player: Settings remembered: currenplayer:"+player.currentplayer+" cs:"+cs)
			$j('#playermodule').show(); // show the playermodule
			$j.cookie('smallplayer', null); // reset smallplayer cookie
			dbg("Close HQ Player: Final Switch HQ Player")
			player.switchPlayer(player.currentplayer); // show the "small" current player
			SCRIPTCONN = window.setInterval("testfullscreenbuttonavaibility()", 2500);
			dbg("Close HQ Player______________")
			//location.href = location.href; // reload the page...
}

function loadPopup() {
	this.debug("Load POPUP Player");
	try {
		this.fullscreen();
	} catch(e) {
		this.debug("Load POPUP Player failed");
	}
}

function closePopup() {
	this.debug("Close POPUP Player");
	this.players[this.currentplayer].close_popup();
	player.switchPlayer(player.currentplayer);
}

function loadCarrier() {
	this.debug("Load Carrier Player");
	try {
		this.stop();
	} catch(e) {
		this.debug("Load Carrier Stopping the current Player failed");
	}
	try {
		this.carrier();
	} catch(e) {
		this.debug("Load Carrier Player failed");
	}
}

function closeCarrier() {
	
}

// Helper function for Info and Help button (bottom) for closing Player tabs if necessary
function closeAllTabs() {
			var cobj = $j("#optionBoxContainer"); // The Container for the contents of the Tab
			$j("#b_"+ec_current).removeClass("optActive"); // remove Class from old current
			cobj.empty(); // 1. remove all children 
			ec_current = false;
}


// a Speed test Library found @ http://www.taylor.org/~patrick/javascript/lib/
// Usage: 
var connectionSpeed = 0;
var connectionSpeedTestfinished=true
// The variable where connection speed information
// will be stored when it is available.

function startbyspeedtest () {
	this.debug("Player Object started "+this.player_type+" by Speedtest");
	this.defaultconn = connectionType(connectionSpeed);
	this.debug("Changed default Conn to "+connectionType(connectionSpeed));
	this.testspeed=false
	this.start();
}


function testSpeed() {
	this.debug("SPEEDTEST: Create Speed test Picture");
	connectionSpeedTestfinished = false;
	jqueryCSImageTag('img/speedtest.jpg',                        // Image filename
                8955,                                  // Image size
                'border=0 height=0 alt="Conn Speed"',this.layer_id);
}

function jqueryCSImageTag( fileLocation, fileSize, imgTagProperties, layerid ) {
	dbg("SPEEDTEST: Create Speed picture");
	// This function draws the image tag required to run this process.
	// It needs to be passed:
	//     1.  (String)   The location of the file to be loaded
	//     2.  (Integer)  The size of the image file in bytes
	//     3.  (String)   The tag properties to be included in the <img> tag
	// Place a call to this function inside the <body> of your file
	// in place of a static <img> tag.
	
	start = (new Date()).getTime();
		// Record Start time of <img> load.
		
	loc = fileLocation + '?t=' + escape(start);
		// Append the Start time to the image url
		// to ensure the image is not in disk cache.
	$j('#'+layerid).append('<img id="speedtest" style="filter:alpha(opacity=0); opacity:0.; -moz-opacity:0.;" src="' + loc + '" start="'+start+'" fileSize="'+fileSize+'">'); // special case.. IE needed attr direct in IMG
	$j('#speedtest').load(function(){
		dbg("SPEEDTEST: Finished");
		start = $j(this).attr("start");
		fileSize = $j(this).attr("fileSize");
		connectionSpeed=computeConnectionSpeed(start,fileSize);
		dbg("SPEEDTEST: result"+connectionSpeed+" "+connectionType(connectionSpeed));
		connectionSpeedTestfinished=true;
		player.startbyspeedtest();
	}); 
	
	return;
}

function connectionType(speed) {
	// This function returns a string describing the connection type
	// being used by the user-agent hitting the page.
	
	SLOW_MODEM = 15;
	FAST_MODEM = 57;
	ISDN_MODEM = 120;
		// These are constants which define the base speeds
		// for a number of different connections.  They are
		// measured in units of kbps.
	
	if (speed) {
		if (speed < SLOW_MODEM) {
			return player.lowQ;
		} else if (speed < FAST_MODEM) {
			return player.lowQ;
		} else if (speed < ISDN_MODEM) {
			return player.midQ;
		} else {
			return player.midQ;
		}
	} else {
		return player.lowQ;
	}
}

function computeConnectionSpeed( start, fileSize ) {
	// This function returns the speed in kbps of the user's connection,
	// based upon the loading of a single image.  It is called via onload 
	// by the image drawn by drawCSImageTag() and is not meant to be called
	// in any other way.  You shouldn't ever need to call it explicitly.
	end = (new Date()).getTime();
	connectSpeed = (Math.floor((((fileSize * 8) / ((end - start) / 1000)) / 1024) * 10) / 10);
	return connectSpeed;
}
var SCRIPTCONN = null;
var SCRIPTCONN_Count = null;
function testfullscreenbuttonavaibility() {
	if (player.players[player.currentplayer].testscriptconn()) {
		dbg("testfullscreenbuttonavaibility -"+SCRIPTCONN_Count+"-  cleared Intervall - Connection is ready");
		window.clearInterval(SCRIPTCONN);
	}
	if (SCRIPTCONN_Count>6) {
		dbg("testfullscreenbuttonavaibility -"+SCRIPTCONN_Count+"- cleared Intervall after 5 tries - Connection is not ready");
		clearInterval(SCRIPTCONN);
	}
	if (player.player_type=='extended') {
		player.setHQB();
		player.setPopupB();
		player.setPopupB_HQ();
	}
	SCRIPTCONN_Count++;
}

// Intervalspace
var NEWSTRIGGER = false;
var OFFLINETRIGGER = false;
// Init the triggers
var onair=false;
var offline = false;

// this function should be called regularly..
function onlineTrigger(onlineurl,offlineurl,format,layerid,layerhq) {
	dbg("NEWSTRIGGER");
	var url = false; // Info from triggering
	dbg(onlineurl+APPJSEXTENSION+" "+offlineurl+APPJSEXTENSION+" "+format+" "+layerid+" "+layerhq+" ONAIR:"+onair);
	$j.getScript(onlineurl+APPJSEXTENSION);
	if (onair==true) {
		dbg("Now On Air:"+onair);
		showhomeplayer(newsurl,format,layerid,layerhq);
		clearInterval(NEWSTRIGGER);
		OFFLINETRIGGER = setInterval("offlineTrigger('"+offlineurl+"')", 5000)
	}
}

// this function is called for resetting the page..
function offlineTrigger(url) {
	dbg("Offline Check running "+url+" OFFLINE"+offline+" ONAIR"+onair)
	$j.getScript(url+APPJSEXTENSION);
	if (onair==true && offline==true) {
		onair=false;
		offline==false;
		clearInterval(OFFLINETRIGGER);
		location.reload();
	}
}

function showhomeplayer(newsurl,format,layerid,layerhq){ // Load Homeplayer
			showplayer=true;
			player = new dmcplayer(); // generate the player..
			player.detected_plugins = detection; // feed Plugindetection result into the player
			player.player_type = "home";
			player.video_format = format; // oder 4_3
			player.layer_id = layerid;
			player.layerhq_id = layerhq;
			player.livestream = true;
			/*Video urls*/
			player.avaible_url = newsurl;
			player.start();
};