/******************************************************************/
/*ARD Blankplayer Version 1.19.7							*/
/******************************************************************/
/* (C)  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 currentclipplaying = false;
var currentclipplayinginit = false;
var current_Player = false;
var current_PlayerDomId = false;
var fullscreenactive = false;
var startat = 0;

var ec_pId = false;
var ec_current = false;
var dmcPlayerCount=0;
var dmcPlayerArray=new Array();

function loading(jqtarget){ // loading animation	
    jqtarget.empty();
    jqtarget.show();
    var rand = Math.random()+"";
    rand = rand.substring(2, rand.length);
    jqtarget.append('<div id="loading'+rand+'" class="loading"></div>');
    if (2==SWFOBJECTVERSION) {
        flashvars 	= {};
        params = {
            wmode:"transparent",
            bgcolor:FLASHBGCOLOR
        };
        attributes 	= {
            style:";"
        };
        swfobject.embedSWF(FLASHLOADINGANIOMATION, "swf"+rand, FLASHLOADINGANIOMATION_W, FLASHLOADINGANIOMATION_H,"6", flashvars, params,attributes);
    } else {
        var so = new SWFObject(FLASHLOADINGANIOMATION, "swf"+rand, FLASHLOADINGANIOMATION_W, FLASHLOADINGANIOMATION_H, "6", FLASHBGCOLOR);
        so.addParam("wmode", "transparent");
        so.setAttribute("style", ";");
        so.write("loading"+rand);
    }
}

function UrlEncoding(input) {
    var encodedInputString=escape(input);
    encodedInputString=encodedInputString.replace("%3A", ":");
    return encodedInputString;
}

/*DASERSTE
Baiscly ued 4 Daserste -used 4  Compatibility 
*/

if (typeof closeHelpInfoObj != 'function') {
    function closeHelpInfoObj() {}
}
if (typeof setScrollPanes != 'function') {
    function setScrollPanes() {}
}
/*DASERSTE*/

function service(playerId) {
// see rewritten AJAX snippets in AX_schnipsel
}


function dmcplayer() { //(avaible_url,furls,p_type,v_format) {
    // SWR +++
    dmcPlayerCount++;
    dmcPlayerArray[dmcPlayerCount] = this;
    this.playerId = dmcPlayerCount;// synthetic numerical id, starting with 1
    // please use swrSetSize to
    this.A_WIDTH=256;
    this.A_HEIGHT=29;
    this.S_WIDTH=256;
    this.S_HEIGHT=144;
    this.E_WIDTH=512;
    this.E_HEIGHT=288;
    this.H_WIDTH=960;
    this.H_HEIGHT=544;
    // SWR ---
    //
    this.debug = function (str) { // debuglayer is deativated @ moment
        dbg("dmcplayer: "+str);
    };
    /*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;
    /*URLS*/
	
    /* Player configs */
    this.starttime = 0;
    this.download_url = false;
    this.rss_url = false;
    this.home_enlarge_url = false;
    this.home_show_fs = false;
    this.enlarge_url = false;
    this.showcarrier = false;
    this.ivw_tag = false;
    this.enable_ivw_tag = false;
    this.debug_ivw_tag = false;
    this.previewimage = false;
    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.hidelayersonhq = new Array('page'); // ID of DOM Object
    this.layerec_id = "extended_controls"; // ID of DOM Object
    this.livestream = false;
    this.mp3stream = false;
    this.autostart = false; // 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":9,
        "microsoftmedia":10,
        "realmedia":6,
        "quicktime":7
    };
    this.minimal_version_fallback = {
        "flashmedia":new Array("quicktime",3)
    };
    this.defaultconn = 2; // 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.revokedplugins = 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*/
    this.hidePageDivs = function () {
        for (var div in this.hidelayersonhq) {
            $j('#'+this.hidelayersonhq[div]).hide();
        }
    };
	
    this.showPageDivs = function () {
        for (var div in this.hidelayersonhq) {
            $j('#'+this.hidelayersonhq[div]).show();
        }

    };
    // 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.ivwcount_url) {
            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;display:none;" 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.customerror = function (e) {
        obj = $j('#'+this.layer_id);
        obj.empty();
        obj.load(ERRORPATH+this.errorAjax[e]+APPHTMLEXTENSION);
        $j.getScript(ERRORPATH+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];
                }
            }
        }
    };
	
    this.getposition = function() {
        var obj = this.players[this.currentplayer];
        return obj.getposition();
    };
	
    this.getstate = function() {
        var obj = this.players[this.currentplayer];
        return obj.getstate();
    };


    /* SWR Erweiterungen/Anpassungen */

    this.buildOptions = function() {
        var html='';
        html+='<div id="options">';
        html+=' <div class="options">';
        html+='		<div class="line">';
        html+='			<a id="b_setting'+this.playerId+'" class="option" href="#">';
        html+='				<span class="text">Einstellungen</span>';
        html+='				<span class="arrow"></span>';
        html+='			</a>';
        html+='         <div class="option optIcons">';
        html+='             <div class="icons">';
        //        html+='                 <a id="ic_carryopen'+this.playerId+'" class="carry_open" href="#" title="Mitnehmen"><span>Mitnehmen</span></a>';
        //        html+='                 <a id="ic_popup'+this.playerId+'" class="popup" href="#" title="Vollbild"><span>Vollbild</span></a>';
        //        html+='                 <a id="ic_hq'+this.playerId+'" class="hq" href="#" title="HighQuality"><span>HighQuality</span></a>';
        //        html+='                 <a id="ic_rss'+this.playerId+'" class="podcast" href="#" title="Podcast"><span>Podcast</span></a>';
        html+='                 <a id="ic_dl'+this.playerId+'" class="download" href="#" title="Download"><span>Download</span></a>';
        html+='             </div>';
        html+='         </div>';
        //        html+='			<a id="b_vote'+this.playerId+'" class="option optRating" href="#">';
        //        html+='				<span class="text">Bewertung</span>';
        //        html+='				<span class="rating rate_4"></span>';
        //        html+='				<span class="arrow"></span>';
        //        html+='			</a>';
        html+='		</div>';
        html+='	</div>';
        //        html+='	<div class="options">';
        //        html+='		<div class="line">';
        //        html+='			<a id="b_info'+this.playerId+'" class="option" href="#">';
        //        html+='				<span class="text">Information</span>';
        //        html+='				<span class="arrow"></span>';
        //        html+='			</a>';
        //        html+='			<a id="b_links'+this.playerId+'" class="option" href="#">';
        //        html+='				<span class="text">Links</span>';
        //        html+='				<span class="arrow"></span>';
        //        html+='			</a>';
        //        html+='			<a id="b_comment'+this.playerId+'" class="option" href="#">';
        //        html+='				<span class="text">Kommentare</span>';
        //        html+='				<span class="arrow"></span>';
        //        html+='			</a>';
        //        html+='			<a id="b_recommend'+this.playerId+'" class="option" href="#">';
        //        html+='				<span class="text">Weiterempfehlen</span>';
        //        html+='				<span class="arrow"></span>';
        //        html+='			</a>';
        //        html+='		</div>';
        //        html+='	</div>';
        //        html+='	<div class="options">';
        //        html+='     <div class="option optIcons">';
        //        html+='			<div class="icons">';
        //        html+='				<a id="ic_carryopen'+this.playerId+'" class="carry_open" href="#" title="Mitnehmen"><span>Mitnehmen</span></a>';
        //        html+='				<a id="ic_popup'+this.playerId+'" class="popup" href="#" title="Vollbild"><span>Vollbild</span></a>';
        //        html+='				<a id="ic_hq'+this.playerId+'" class="hq" href="#" title="HighQuality"><span>HighQuality</span></a>';
        //        html+='				<a id="ic_rss'+this.playerId+'" class="podcast" href="#" title="Podcast"><span>Podcast</span></a>';
        //        html+='				<a id="ic_dl'+this.playerId+'" class="download" href="#" title="Download"><span>Download</span></a>';
        //        html+='			</div>';
        //        html+='		</div>';
        //        html+=' </div>';
        html+='</div>';
        html+='<div id="optionBoxContainer'+this.playerId+'" class="swrOptionBoxContainer"></div>';

        $j('#'+this.layer_id).after(html);

        html='<a name="playeranchor'+this.playerId+'"></a>';
        $j('#'+this.layer_id).before(html);
    }

    this.swrSetSize = function(w,h) {
        // every player should zoom the video to this size
        // patch 16/9 sizes for WMA
        this.vsizes16_9['1'] = { 'w':w, 'h':h };
        this.vsizes16_9['2'] = { 'w':w, 'h':h };
        // patch 4/3 size defs//
        this.vsizes4_3['1'] = { 'w':w, 'h':(w*3)/4 };
        this.vsizes4_3['2'] = { 'w':w, 'h':(w*3)/4 };
        // Audio Size
        this.vsizesaudio['1'] = { 'w':w, 'h':h };
        this.vsizesaudio['2'] = { 'w':w, 'h':h };
        // brutal hack, please see dmcplayerinit for SWR++
        if(this.player_type == "extended") {
            // extended video player has 29 Pixels controll bar
            h+=28;
        }
        this.WIDTH=w;
        this.HEIGHT=h;
    }

    /* swrInit is an attempt to work around limitations of the init.js file and it's problems. */
    this.swrInit = function() {
        // other inti stuff later
        dbg('!!!!!!!!!!!!!!!!!!!!!!!!!!<br>');
        dbg('!! swrInit() !!!!!!!!!!!!!<br>');
        dbg('!!!!!!!!!!!!!!!!!!!!!!!!!!<br>');
		
        // this initialises the player debugging if needed
        $j("#infopane").hide(); // make sure info layer is unvisible(bottom infoplayer for heklp and infobutton)
        if (typeof pdebug!="undefined" && pdebug==false) {
            $j("#videodebugclear").hide(); // Hide debugging clearbutton layer
            $j("#videodebug").hide(); // Hide debugging layer
        }
        // this initialises the player object on the page.
        // this generate some UI things and the player embed object code


        if (typeof showplayer!="undefined" && showplayer!=false) {
            // Show player is true - Home edition
            if (this.player_type=="extended") {
                // prepare options
                this.buildOptions();

                // Show player is true - Extended edition
                // startscreen settings... currently the Infopane is opened.
                this.start(); // after player preps start it.

                // ---------------------------------------------------------------------
                // DANGER: one option box for all players? where to display?
                // to prevent confusion, do it only for the first player at the moment
                // ---------------------------------------------------------------------
                if(this.playerId==1) {
                    var tab = INITIALTAB;
                    // SWR, added as hack, otherwise uninitialized errors follow
                    ec_current = tab; // set current layer... later used to deativate Buttons--
                    if (this.function_urls[tab]!=false && SHOWINITIALTAB==true) {
                        dbg('------------------------');
                        dbg('-- init options once! ['+tab+'] --');
                        dbg('------------------------');

                        // tab content container
                        var cobj = $j('#optionBoxContainer'+this.playerId);
                        var obj = $j('#b_'+tab+this.playerId); // the infobutton
                        // Some URL defined in the baseHTML code
                        var url = this.function_urls[tab];

                        cobj.empty(); // first empty the content container
                        loading($j('#optionBoxContainer'+this.playerId)); // loading animation
                        //cobj.load(url+".html",null,setScrollPanes()); // load the url
                        cobj.load(url+APPHTMLEXTENSION,null);
                        cobj.attr('url',url); // set an attr (used by button funcitons

                        // create dynamic function object to encapsulate player specific
                        // post load call to the service(playerId) function in the script
                        // loaded by getScript (bullshit bingo rulez!)
                        // Mind the gap: sc'+pId+' at the end returns the function object!
                        // function needs to to have individual name for each player to
                        // prevent race conditions! You have been warned!
                        var dynFunSrc='function sc'+playerId+'(data, textStatus) { service('+playerId+') }; sc'+pId+' ';
                        var dynFun=eval(dynFunSrc);

                        // Some Tabvs need some aditional JS code... but infopane doesnt!
                        $j.getScript(url+APPJSEXTENSION, dynFun);

                        dbg('LOADED: loading: '+url+APPJSEXTENSION);
							
                        obj.addClass("optActive"); // Add correct klass to Button obj.
                        ec_current = tab; // set current layer... later used to deativate Buttons--
                    }
                }
            }
        }
        //FIX IE6 FLICKER BUG!
        try {
            document.execCommand("BackgroundImageCache", false, true);
        } catch(err) {}


        if (typeof window.closeHelpInfoObj != 'function') {
            dbg('empty helper closeHelpInfoObj created');
            // function closeHelpInfoObj() {}
            window.closeHelpInfoObj=function() {};
        }
        if (typeof window.setScrollPanes != 'function') {
            dbg('empty helper setScrollPanes created');
            // function setScrollPanes() {}
            window.setScrollPanes=function() {};
        }
    }


    /* 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;
        this.HEIGHT=(this.WIDTH*3)/4;
        if(this.player_type == "extended") {
            // extended video player has 29 Pixels controll bar
            this.HEIGHT+=28;
        }
    }
    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();
        plength=0;
        for (attr in loaded_Players) {
            this.debug("registered Player"+loaded_Players[attr]+" - "+attr);
            plength++;
        }
		
        if (this.autostart==true) {
            currentclipplaying = this.globid;
        }
        if (plength>1 && currentclipplayinginit==false) {
            currentclipplayinginit = true;
            window.setTimeout("controlplayers()", 5000);
        }
    } 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, {
                expires: COOKIEEXPIREINDAYS
            });
            $j.cookie('connspeed',c, {
                expires: COOKIEEXPIREINDAYS
            });
        } 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" && c!="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 if (c!="false" && p!=null) {
        this.debug("found cookie settings c:"+c);
        this.settings['player'] = this.defaultplayer;
        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('');
    if (this.usedplayers.length>0) {
        controls.append('<p class="homesettings_p1"><a id="home_set" class="homesetting" href="#" title="Einstellungen"><span>Einstellungen</span></a></p>');
        $j('#home_set').bind('click', function () { // Bind Click
            $j('.homesettings_p1').hide();
            $j('.home_sel').show();
            return false;
        }); // Bind Click
    } else {
        controls.append('<p class="homesettings_p1"></p>');
    }
	
    if (this.home_enlarge_url != false) {
        controls.append('<p class="homesettings_p1 home_fs_inplugin"><a id="home_fs" class="popup" href="#" title="vergr&ouml;&szlig;ern"><span>vergr&ouml;&szlig;ern</span><span class="enlarge"></span></a></p>');
        $j('#home_fs').bind('click', function () { // Bind Click
            // +++ SWR: multiplayer hack
            location.href=dmcPlayerArray[1].home_enlarge_url;
            return false;
        }); // Bind Click
    }
    if (this.home_show_fs == true) {
        controls.append('<p class="homesettings_p1 home_fs_inplugin"><a id="home_fs" class="popup" href="#" title="Vollbild"><span>Fullscreen</span><span class="fs"></span></a></p>');
        $j('#home_fs').bind('click', function () { // Bind Click
            // +++ SWR: multiplayer hack
            dmcPlayerArray[1].fullscreen();
            return false;
        }); // Bind Click
        if (this.currentplayer == 'flashmedia') {
            $j('.home_fs_inplugin').hide();
        }
    }
    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 class="home_sel"><span><input id="'+domid+'" type="radio" name="pformat" value="'+obj.typ+'" '+checked+'  /><label id="label'+domid+'"  value="'+obj.typ+'" for="'+domid+'">'+obj.shortname+'</label></span></p>');
            $j('#'+domid).bind('click', function () { // Bind Click
                // +++ SWR: multiplayer hack
                if (dmcPlayerArray[1].currentplayer!=$j(this).attr('value')) { // only switch if Playervalue will change
                    $j.cookie('homeplayertype',$j(this).attr('value'), {
                        expires: COOKIEEXPIREINDAYS
                    });
                    // +++ SWR: multiplayer hack
                    dmcPlayerArray[1].switchPlayer($j(this).attr('value')); // jsut switch the player
                    p = player;
                    if (p.currentplayer == 'flashmedia') {
                        $j('.home_fs_inplugin').hide();
                    } else {
                        $j('.home_fs_inplugin').show();
                    }
                    $j('.homesettings_p1').show();
                    $j('.home_sel').hide();
                }
            }); // Bind Click
        }
        catch(err) {
            this.debug("adding home radio button for "+this.usedplayers[p]+" failed");
        }
    }
    if (this.usedplayers.length>0) {
        controls.append('<p class="home_sel home_selbackmargin"><a id="home_back" class="home_selback" href="#" title="Zur&uuml;ck"><span>Zur&uuml;ck</span></a></p>');
        $j('#home_back').bind('click', function () { // Bind Click
            $j('.homesettings_p1').show();
            $j('.home_sel').hide();
            p = player;
            if (p.currentplayer == 'flashmedia') {
                $j('.home_fs_inplugin').hide();
            } else {
                $j('.home_fs_inplugin').show();
            }
            return false;
        }); // Bind Click
    }
    $j('.home_sel').hide();
//controls.append('');?? not needed??
};

// Extended Player needs many Buttons..
function initExtendedButtons() {
    var rssobj = $j("#ic_rss"+this.playerId); // 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','#');
        rssobj.bind("click", function(){
            location.href=$j(this).attr('rssurl');
            return false;
        });
    } else {
        rssobj.hide();
    }
    var dlobj = $j("#ic_dl"+this.playerId); // generate URL, JS; for Downloads (generated by getCurrentUrl)
    if (this.download_url!=false) {
        dlobj.show();
        dlobj.attr('dlurl',this.download_url);
        dlobj.attr('href','#');
        dlobj.bind("click", function(){
            location.href=$j(this).attr('dlurl');
            return false;
        });
    } 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+this.playerId);	 // the button object
        if ($j.browser.msie && $j.browser.version ==6) {} else {
            bobj.attr('href','#'); // rewrtite href to JS
        }
        bobj.attr("url",this.function_urls[button]); // save URL
        bobj.attr("button",button); // tell the button is name
        bobj.attr("playerId",this.playerId); // tell the button it's playerId

        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
            var pId = obj.attr("playerId"); // get my playerId
            obj.attr("current",true); // current obj
            // +++ SWR: multiplayer hack
            dbg(b + "_url:"+url);

            // erase every optionBoxContainer
            $j(".swrOptionBoxContainer").empty(); // The Container for the contents of the Tab

            var cobj = $j("#optionBoxContainer"+pId); // The Container for the contents of the Tab
            //				alert(ec_current);
            $j("#b_"+ec_current+pId).removeClass("optActive"); // remove Class from old current
            cobj.empty(); // empty tab Container

            if (ec_current!=b || ec_pId!=pId) { // if this button not selected fill it
                obj.addClass("optActive"); // active current
                cobj.empty(); // 1. remove all children
                //loading($j('#optionBoxContainer'+pId)); // set loading anim
                //cobj.load(url+".html",null,setScrollPanes()); // load the URL into optionBoxContainer

                if (url!="") {
                    dbg('WARNING: loading: '+url+APPJSEXTENSION);
                    cobj.load(url+APPHTMLEXTENSION,null); // load the URL into optionBoxContainer
                    cobj.attr("url",url); // save url to optionBoxContainer
                    //dbg('WARNING: loading: '+url+APPJSEXTENSION);

                    // create dynamic function object to encapsulate player specific
                    // post load call to the service(playerId) function in the script
                    // loaded by getScript (bullshit bingo rulez!)
                    // Mind the gap: sc'+pId+' at the end returns the function object!
                    // function needs to to have individual name for each player to
                    // prevent race conditions! You have been warned!
                    var dynFunSrc='function sc'+pId+'(data, textStatus) { service('+pId+') }; sc'+pId+' ';
                    var dynFun=eval(dynFunSrc);

                    $j.getScript(url+APPJSEXTENSION, dynFun); // load JS file (some tabs need JS code)

                    dbg('LOADED: loading: '+url+APPJSEXTENSION);
                }
                ec_pId = pId;
                ec_current = b; // set marker 4 current state
            } else {
                ec_pId = false;
                ec_current = false; // if button is selected we deselect it / set ec_current=false.. class was removed before.
            }
            return false;
        });// 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"+this.playerId);
    if (this.showcarrier==true) {
        coobj.show();
        coobj.attr('href','#');
        coobj.unbind();
        // +++ SWR: multiplayer hack, transport playerId into onClick handler
        coobj.attr('playerId',''+this.playerId);
        coobj.bind("click", function(){
            // +++ SWR: multiplayer hack, retrieve playerId from calling element
            var playerId = 1 * $j(this).attr('playerId');
            dbg("CarryOpen Button Click for "+playerId);
            dmcPlayerArray[playerId].loadCarrier(1); // method for Carrier popup
            return false;
        });
    } else {
        coobj.hide();
    }
};

function setHQB() {
    var hqobj = $j("#ic_hq"+this.playerId); // 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','#');
        hqobj.attr('hqurl',avaible);
        hqobj.unbind();
        // +++ SWR: multiplayer hack, transport playerId into onClick handler
        hqobj.attr('playerId',''+this.playerId);
        hqobj.bind("click", function(){
            // +++ SWR: multiplayer hack, retrieve playerId from calling element
            var playerId = 1 * $j(this).attr('playerId');
            dbg("HQ Button Click for "+playerId);
            dmcPlayerArray[playerId].loadHqPlayer(1); // method for HQ switch
            return false;
        });
    } else {
        hqobj.hide(); // no HQ  - hide the button
    }
};

function setPopupB() {
    var popupobj = $j("#ic_popup"+this.playerId);
    if (typeof this.players[this.currentplayer]!="undefined" && this.currentplayer != 'flashmedia' && this.players[this.currentplayer].testscriptconn()==true  && this.mp3stream==false) {//&& (this.currentplayer == 'microsoftmedia' && $j.browser.msie==true)
        dbg("Fullscreen Button SHow");
        popupobj.show(); // show button an rewrite code
        popupobj.attr('href','#');
        //popupobj.attr('hqurl',avaible);
        popupobj.unbind();
        // +++ SWR: multiplayer hack, transport playerId into onClick handler
        popupobj.attr('playerId',''+this.playerId);
        popupobj.bind("click", function(){
            // +++ SWR: multiplayer hack, retrieve playerId from calling element
            var playerId = 1 * $j(this).attr('playerId');
            dbg("Fullscreen Button Click for "+playerId);
            dmcPlayerArray[playerId].loadPopup(); // method for POPUP switch
            return false;
        });
    } else {
        popupobj.hide(); // no HQ  - hide the button
    }
};

function setPopupBHighQuality() {
    var popupobj = $j("#"+this.layerhq_id+'fs');
    if (typeof this.players[this.currentplayer]!="undefined" && this.currentplayer != 'flashmedia' && this.players[this.currentplayer].testscriptconn()==true  && this.mp3stream==false) {
        popupobj.show(); // show button an rewrite code
        popupobj.attr('href','#');
        popupobj.unbind();
        // +++ SWR: multiplayer hack, transport playerId into onClick handler
        popupobj.attr('playerId',''+this.playerId);
        popupobj.bind("click", function(){
            // +++ SWR: multiplayer hack, retrieve playerId from calling element
            var playerId = 1 * $j(this).attr('playerId');
            dbg("HQ Fullscreen Button Click for "+playerId);
            dmcPlayerArray[playerId].loadPopup(); // method for POPUP switch
            dmcPlayerArray[playerId].initHqInterface();
            return false;
        });
    } 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");

        // SWR: protection vs Prototype
        if((typeof this.avaibleplayers[p])=='function') { 
            continue;
        }

        ids[this.avaibleplayers[p]]=p;
    }
    for(var p in this.avaible_url) { // URLS in config
        
        // SWR: protection vs Prototype
        if((typeof this.avaible_url[p])=='function') { 
            continue;
        }

        this.debug("init Player XXX "+(typeof this.avaible_url[p]));
        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+"','"+this.video_format+"')"); // load the playerobject (witch eval && new)
            // SWR++ please use swrSetSize(w,h) !!!!
            // Dynamische Größen auf einer Seite, überschreibt Initialisierung
            // aus globalen Variablen, was keine soooo gute Idee ist ...
            if(typeof this.WIDTH!='undefined') {
                // alert(this.WIDTH);
                playerobj.FLASHEMBEDAUDIOW=this.WIDTH;
                playerobj.FLASHEMBEDAUDIOH=this.HEIGHT;
                playerobj.FLASHEMBEDSIMPLEW=this.WIDTH;
                playerobj.FLASHEMBEDSIMPLEH=this.HEIGHT;
                playerobj.FLASHEMBEDW=this.WIDTH;
                playerobj.FLASHEMBEDH=this.HEIGHT;
            //playerobj.FLASHEMBEDHQW=this.H_WIDTH;
            //playerobj.FLASHEMBEDHQH=this.H_HEIGHT;
            }
            // SWR--
            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.starttime, this.player_type,this.minimal_version[p],this.livestream,this.mp3stream,this.flashstreamingserver,this.enablebuffering,this.player_world);
            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

                // SWR: protection vs Prototype
                if((typeof this.avaible_url[ids[p]][url])=='function') { 
                    continue;
                }

                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");
            this.revokedplugins.push(p);
        }
    }

    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);
    this.rememberdavaible=false;
    for(p in this.usedplayers) { // for each enabled player
        
        // SWR: protection vs Prototype
        if((typeof this.usedplayers[p])=='function') { 
            continue;
        }

        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;
            this.defaultavaibleid=p;
            this.debug("check defaultplayer avaible --- "+this.defaultavaibleid);
        }
        var rememberedsetting = this.settings['player'];
        if (this.player_type!='extended') {
            rememberedsetting = $j.cookie('homeplayertype',$j(this).attr('value'), {
                expires: COOKIEEXPIREINDAYS
            });
        }
        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.defaultavaible=true;
        this.defaultavaibleid = 0;
    //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.settings['player'] = this.defaultplayer;
        this.settings['conn'] 	= this.settings['conn'];
    //this.rememberSetting(this.usedplayers[this.rememberdavaibleid],this.settings['conn']);// anbd remember it...
    }
    this.debug("defaultavaible == "+this.defaultavaible+" rememberdavaible == "+this.rememberdavaible);
    if (this.defaultavaible==true && this.rememberdavaible==false){
        this.debug("default avaible ! remembered player (="+this.settings['conn']+") not found");
        this.debug("default avaible ! remembered size "+this.settings['conn']);
        var connections = this.players[this.usedplayers[0]].getconn();
        this.debug("default avaible ! defaultavaibleid "+this.defaultavaibleid);
        this.debug("default avaible ! defaultavaibleid "+this.usedplayers[this.defaultavaibleid]);
        this.defaultplayer = this.usedplayers[this.defaultavaibleid];
        //this.debug(connections);
        //this.debug("to 1"+ typeof connections[1]);
        //this.debug("to 2"+ typeof connections[2]);
        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.debug('??: '+this.defaultplayer+" "+this.settings['conn']);
        this.settings['player'] = this.defaultplayer;
        this.settings['conn'] 	= this.settings['conn'];
    //this.rememberSetting(this.defaultplayer,this.settings['conn']);
    //alert(this.usedplayers);
    }
    // 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);
            if (this.player_type=='extended') {
                this.customerror("otherplayer");
            } else {
                this.debug("otherplayer not extended");
            //this.currentplayer =
            }
        //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') {
                if (SCRIPTCONN) window.clearInterval(SCRIPTCONN);
                // +++ SWR: multiplayer hack, delayed call with playerId
                var cmd='testfullscreenbuttonavaibility('+this.playerId+')';
                dbg(cmd);
                SCRIPTCONN = setInterval(cmd, 2500);
                this.setCOB();
                this.setHQB();
                this.setPopupB();
            }
            this.writevideo(obj,this.layer_id); // Finally write oput the�video with the urrent player plugin
            if (this.player_type=='extended' && this.autostart==true) {
                // +++ SWR: multiplayer hack, delayed call with playerId
                var cmd='dmcPlayerArray['+this.playerId+'].play();';
                dbg(cmd);
                window.setTimeout(cmd, 100);
            }
//            $j('#'+this.layer_id).append('<div id="play" playerId="'+this.playerId+'">[play]</div>');
//            $j('#'+this.layer_id+' #play').click(function() {
//                var pId = $j(this).attr("playerId"); // get my playerId
//                var cmd='dmcPlayerArray['+pId+'].play();';
//                alert("Play! "+cmd);
//                dbg(cmd);
//                window.setTimeout(cmd, 100);
//            });
        } 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']);
    // XXX
    // obj.FLASHEMBEDW = 300;
    // obj.FLASHEMBEDH = 225;
    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(obj);
        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'], {
        expires: COOKIEEXPIREINDAYS
    }); // save small player settings
    var obj = this.players[this.currentplayer]; // playerobj
    if (this.autostart==false && startat>0) {
        obj.autostart = 1;
        obj.enablebuffering= 1;
    }
    this.rememberSetting(this.currentplayer,this.highQ); // remember  Highquality movie
    if (obj.enabled) { // if playerobject
        obj.prepareHqMode();
        $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
        this.hidePageDivs();//$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 {
                    // +++ SWR: multiplayer hack, delayed call with playerId
                    var cmd='dmcPlayerArray['+this.playerId+'].closeHqPlayer()';
                    dbg(cmd);
                    window.setTimeout(cmd, 100);
                }
            }
        });
        this.initHqInterface();
        // +++ SWR: multiplayer hack, delayed call with playerId
        var cmd='dmcPlayerArray['+this.playerId+'].play()';
        dbg(cmd);
        window.setTimeout(cmd, 100);
    } 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="#"></a></div>'); //append fullscreen button
    $j('#'+this.layerhq_id).append('<div id="'+closerid+'"><a href="#">Schlie&szlig;en</a></div>'); //and append close button
    var hqvideoclose = $j('#'+closerid); // get the Closebutton object
    hqvideoclose.unbind();
    // +++ SWR: multiplayer hack, transport playerId into onClick handler
    hqvideoclose.attr('playerId',''+this.playerId);
    hqvideoclose.bind("click", function(){ // bind the click
        // +++ SWR: multiplayer hack, retrieve playerId from calling element
        var playerId = 1 * $j(this).attr('playerId');
        dmcPlayerArray[playerId].closeHqPlayer(); // Call function... ... reason Flash also di this...
        return false;
    });
    $j('#'+fsid).hide();
    if (SCRIPTCONN) window.clearInterval(SCRIPTCONN);
    // +++ SWR: multiplayer hack, delayed call with playerId
    var cmd='testfullscreenbuttonavaibility('+this.playerId+')';
    dbg(cmd);
    SCRIPTCONN = window.setInterval(cmd, 2500);
};

// Closing the HQ player
function closeHq() {
    $j(document).unbind('keydown');
    var obj = this.players[this.currentplayer];
    if (obj.enabled) {
        this.starttime = obj.prepareCloseHqMode();
        obj.starttime = this.starttime;
    }
    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();
    this.showPageDivs();//$j('#page').show(); // show the page
    if ($j.cookie('smallplayer')==null) {
        var cs = this.defaultconn;
    } else {
        var cs = $j.cookie('smallplayer');
    }
    // remember old player settings
    // +++ SWR: multiplayer hack, improve later
    dmcPlayerArray[this.playerId].rememberSetting(dmcPlayerArray[this.playerId].currentplayer,cs);

    dbg("Close HQ Player: Settings remembered: currenplayer:"+dmcPlayerArray[this.playerId].currentplayer+" cs:"+cs);
    $j('#playermodule').show(); // show the playermodule
    $j.cookie('smallplayer', null, {
        expires: COOKIEEXPIREINDAYS
    }); // reset smallplayer cookie
    dbg("Close HQ Player: Final Switch HQ Player");
    // show the "small" current player
    // +++ SWR: multiplayer hack, improve later
    dmcPlayerArray[this.playerId].switchPlayer(dmcPlayerArray[this.playerId].currentplayer);
    if (SCRIPTCONN) window.clearInterval(SCRIPTCONN);

    // +++ SWR: multiplayer hack, delayed call with playerId
    var cmd='testfullscreenbuttonavaibility('+this.playerId+')';
    dbg(cmd);
    SCRIPTCONN = window.setInterval(cmd, 2500);
    dbg("Close HQ Player______________");

    // +++ SWR: multiplayer hack, delayed call with playerId
    var cmd='dmcPlayerArray['+this.playerId+'].play()';
    dbg(cmd);
    window.setTimeout(cmd, 100);
//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();

    // +++ SWR: multiplayer hack, improve later
    dmcPlayerArray[this.playerId].switchPlayer(dmcPlayerArray[this.playerId].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(SPEEDTEST_URL,                        // Image filename
        SPEEDTEST_SIZE,                                  // 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 + '" startTime="'+start+'" fileSize="'+fileSize+'">'); // special case.. IE needed attr direct in IMG
    $j('#speedtest').load(function(){
        dbg("SPEEDTEST: Finished");
        start = $j(this).attr("startTime");
        fileSize = $j(this).attr("fileSize");
        connectionSpeed=computeConnectionSpeed(start,fileSize);
        dbg("SPEEDTEST: result"+connectionSpeed+" "+connectionType(connectionSpeed));
        connectionSpeedTestfinished=true;
        // +++ SWR: multiplayer hack, improve later (this. ...?)
        dmcPlayerArray[this.playerId].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 = SPEEDTEST_LIMITS.SLOW_MODEM;
    FAST_MODEM = SPEEDTEST_LIMITS.FAST_MODEM;
    ISDN_MODEM = SPEEDTEST_LIMITS.ISDN_MODEM;
    // These are constants which define the base speeds
    // for a number of different connections.  They are
    // measured in units of kbps.
	
    if (speed) {
        // +++ SWR: multiplayer hack, you know the drill
        if (speed < SLOW_MODEM) {
            return dmcPlayerArray[this.playerId].lowQ;
        } else if (speed < FAST_MODEM) {
            return dmcPlayerArray[this.playerId].lowQ;
        } else if (speed < ISDN_MODEM) {
            return dmcPlayerArray[this.playerId].midQ;
        } else {
            return dmcPlayerArray[this.playerId].midQ;
        }
    } else {
        return dmcPlayerArray[this.playerId].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(playerId) {
    // +++ SWR: multiplayer hack, mind the gap, new parameter!!!
    if (dmcPlayerArray[playerId].players[dmcPlayerArray[playerId].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 (dmcPlayerArray[playerId].player_type=='extended') {
        dmcPlayerArray[playerId].setHQB();
        dmcPlayerArray[playerId].setPopupB();
        dmcPlayerArray[playerId].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+" "+newsurl+" "+format+" "+layerid+" "+layerhq);
        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;
    player.defaultplayer = "microsoftmedia";
    /*Video urls*/
    player.avaible_url = newsurl;
    player.start();
};



function controlplayers() {
    for (attr in loaded_Players) {
        loaded_Players[attr].getposition();
        loaded_Players[attr].getstate();
        if (loaded_Players[attr].getstate() == 3 && currentclipplaying!=attr) {
            loaded_Players[currentclipplaying].pause();
            currentclipplaying = attr;
        //alert(currentclipplaying+" "+attr);
        } else {
    //alert(currentclipplaying+" "+attr);
    }
    }
    window.setTimeout("controlplayers()", 2500);
}

function avoidClickFunction()
{
// code here...
}
