﻿var PlayerDim = { Width: 480, Height: 270 };
CurrentChannel = 73;
var SpecialChannel = 83;
if(!self.AJAX_WebBaseURL)self.AJAX_WebBaseURL="";
onLoadObj.push(initializeCmd);
traceable = false;
function rptReady(objr, ctx) {
    if(!$get(ctx.container)) alert("NOT EXISTS : " + ctx.container);
    $get(ctx.container).innerHTML = RenderRepeater(ctx.name, objr);
    ExecuteNextSteps(ctx);
}
var DefaultList="Latest";
function LoadInitialVideo(){
    if(FirstLoadVideo){
        ShowVideo(FirstLoadVideo);
    } else if (VideoLists[DefaultList].collection.length != 0) {
        ShowVideo(VideoLists[DefaultList].collection[0]);
    }
}
var selectedTab="Tab1";
function ChangeTab(tab){
    if(selectedTab == tab) return;
    $get("Tab" + selectedTab).className="inactive";
    $get("Tab" + tab).className = "active";
    $get(selectedTab + "Div").style.display = "none";
    $get(tab + "Div").style.display = "block";
    selectedTab = tab;
}
function VideoRated(html){
    $get("videoRate").innerHTML=html;
}
function RefreshRate(video) {
}
function RateIsRefreshed(obj,ctx){
    if(obj && ctx.obj){
        for(var key in obj)
            ctx.obj[key]=obj[key];
        $get("videoRate").innerHTML = obj["AvgRatableImg"];
        ctx.obj.nextRefreshDate=new Date();
        ctx.obj.nextRefreshDate.setSeconds(ctx.obj.nextRefreshDate.getSeconds() + 10);
    }
}

function searchTag(tag) {
    Search("TAG::" + tag);
}

function Search(searchStr){
    if (PageManager.Mediathek.NeedRedirect)
        PageManager.Mediathek.Redirect({ search: searchStr });
      else
        VideoLists["searchList"].Search(searchStr);
}

function ShowVideo(video,autoplay){
    if(!video) return;
    if(!video.nextRefreshDate || video.nextRefreshDate<new Date())
        RefreshRate(video);
    autoplay = autoplay || video.autoplay;
    currentVideo=video;
    ShowRelatedList(video);
    video.CategoryIds.sort(CategorySort);    
    rptReady([video], { name: "player", container: "videoDiv", ToDo: "Increment();" });
    RenderVideoProperties(video);
    PageManager.GoToTop();
    WritePlayerContent(video, autoplay);
    if (PageManager.Category.NeedRedirect)
        PageManager.AddToHistory({ plid: CurrentPlayList, videoid: video.Id });
    else
        PageManager.AddToHistory({ category: CurrentCategory, videoid: video.Id });
}

function SendLog(vobj, typ) {
    if (!typ) {
        if (vobj.currentTime == 0) return;
        var typ = Math.round(100 * vobj.currentTime / vobj.duration);
        if (typ % 10 <= 8) return;
        typ = 200 + (Math.ceil(typ / 10) * 10);
    }
    if (vobj.tracked && vobj.tracked["L" + typ]) return;
    PrepareLog(vobj);
    var src = "http://b2b.splaytv.de/Comp/DH4qFqpY14QINa3nVb4PFW/PlayerComm.ashx?InfoType=" + typ + "&Info=" + vobj.currentTime;
    for (var key in vobj.logParams)
        src += "&" + key + "=" + vobj.logParams[key];
    LogFrame.src = src;
    vobj.tracked["L" + typ] = true;
   
}
var LogFrame = null;
function PrepareLog(vid) {
    if (LogFrame && vid.prms) return;
    vid.logParams = { Psession: GetSession(), ClientId: "", Action: "L", Type: "10", VideoId: currentVideo.Id };
    vid.tracked = {};
    if (LogFrame) return;
    LogFrame = document.createElement("IFRAME");
    LogFrame.style.position = "absolute";
    LogFrame.style.visibility = "hidden";
    document.body.appendChild(LogFrame);
}
function GetSession() {
    var result, i;
    result = '';
    var guid = new Date().getTime().toString(16).toUpperCase();
    for (var j = 0; j < 32; j++) {
        if (j == 8 || j == 12 || j == 16 || j == 20)
            result = result + '-';
        if (j < guid.length) i = guid.charAt(j);
        else i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
        result = result + i;
    }
    return result;
}
if ((navigator.userAgent.toLowerCase().indexOf("iphone") == -1 && navigator.userAgent.toLowerCase().indexOf("ipad") == -1) || !document.createElement('video').canPlayType)
    WritePlayerContent = function (video, autoplay, container, wmode) {
        var interfaceId = video.InterfaceId;
        var id = video.Id;
        var interfaceInfo = video.InterfaceInfo;
        if (!interfaceId) {
            var so = new SWFObject("player/vPlayer.swf", "", PlayerDim.Width, PlayerDim.Height, "9.0.124", "#000000");
            so.addParam("quality", "high");
            so.addParam("wmode", wmode || "transparent");
            so.addParam("allowScriptAccess", "sameDomain");
            so.addParam("allowFullScreen", "true");
            so.addVariable("clipID", id);
            if (self.playerConfig) so.addVariable("config", playerConfig);
            if (autoplay) so.addVariable("autostart", true);
            so.useExpressInstall(AJAX_WebBaseURL + 'player/expressinstall.swf');
            so.write(container || "flash-content");
        } else {
            var playername = container ? container + "uplayer" : "uplayer";
            var so = new SWFObject("http://www.youtube.com/v/" + interfaceInfo + "?hl=de&enablejsapi=1&playerapiid=" + playername, playername, PlayerDim.Width, PlayerDim.Height, "9.0.124", "#000000");
            so.addParam("quality", "high");
            so.addParam("wmode", "transparent");
            so.addParam("allowScriptAccess", "always");
            so.addParam("allowFullScreen", "true");
            so.useExpressInstall(AJAX_WebBaseURL + 'player/expressinstall.swf');
            so.write(container || "flash-content");
        }
    };
else
    WritePlayerContent = function (video, autoplay, container) {
        $get(container || "flash-content").innerHTML = '<video src="' + GetURL(video, '.DBig.mp4') + '" style="background-color:#000000" autobuffer="true" onplay="SendLog(this,1);" ontimeupdate="SendLog(this);" controls="true" width="' + PlayerDim.Width + '" height="' + PlayerDim.Height + '" poster="' + GetURL(video, '.b.jpg') + '" />';
    };


function onYouTubePlayerReady(playerId) {
    if (playerId != "uplayer") return;
    var ytplayer = document.getElementById("uplayer");
    ytplayer.addEventListener("onStateChange", "onPlayerStateChange");
}

// This function is called when the player changes state
function onPlayerStateChange(newState) {
    if (!document.getElementById("uplayer").incremented && newState == 1) {
        document.getElementById("uplayer").incremented = true;
        JS.Objects.IncrementView(null, null, currentVideo.Id, true);
    }
}

function ShowSpecialVideoContainer() {
    $get("video-sp-bg-container").style.visibility = "visible";
    $get("video-sp-container").style.visibility = "visible";
}
function HideSpecialVideoContainer() {
    $get("video-sp-bg-container").style.visibility = "hidden";
    $get("video-sp-container").style.visibility = "hidden";
    $get("video-sp-player").innerHTML = "<div id='flash-content-sp'></div>";
}

function ShowSpecialVideo(id, interfaceId, interfaceInfo) {
    if ($get("flash-content")) {
        $get("flash-content").innerHTML = '<img src="' + GetURL(currentVideo,'.b.jpg') + '">';
        window.setTimeout('WritePlayerContent(currentVideo);', 3000);
    }
    ShowSpecialVideoContainer();
    WritePlayerContent(VideoLists["Specials"].Index[id], true, "flash-content-sp", "window");
}
var SpecialVideoInd = 0;
function IndexSpecial() {
    var index = VideoLists["Specials"].Index = {};
    var list = VideoLists["Specials"].collection;   
    for (var i = 0; i < list.length; i++)
        index[list[i].Id] = list[i];
}
function RenderSpecialVideo(fetchFirst,initialize) {
    if(fetchFirst==true){
        window.setTimeout('VideoLists["Specials"].Fetch(1, "IndexSpecial();RenderSpecialVideo(false,true)")', 10);
        return;
    }

    var list = VideoLists["Specials"].collection;
    if(list.length>1){
        if (initialize)
            SpecialVideoInd = Math.round(Math.random() * (list.length - 1));
        else if ((++SpecialVideoInd) >= list.length)
            SpecialVideoInd = 0;
        window.setTimeout("RenderSpecialVideo()",10000);
    }
    if (list.length == 0) return;
    rptReady([list[SpecialVideoInd]], { name: "player-sp", container: "video-spDiv" });        
}

function ShowRelatedList() {

}
var LinkBUTemplate = "Buchung.html?ss=";
function RenderVideoProperties(video){
    var tipList=[];
    var lnkList=[];
    var renderLinks=!!$get("LinksContainer");
    for(var i=1;i<4;i++){
        if(video.Properties["Tip" + i + "T"] && video.Properties["Tip" + i + "U"])
            tipList.push({Title:video.Properties["Tip" + i + "T"],URL:video.Properties["Tip" + i + "U"]});
        if(renderLinks && video.Properties["Link" + i + "T"] && video.Properties["Link" + i + "U"])
            lnkList.push({Title:video.Properties["Link" + i + "T"],URL:video.Properties["Link" + i + "U"]});
    }
    rptReady(tipList,{name:"Tips",container:"TipsContainer"});
    if(renderLinks) rptReady(lnkList,{name:"Links",container:"LinksContainer"});
    if($get("LinkBUContainer")){
        if (video.Properties["LinkBU"] && video.Properties["LinkBT"]) {
            $get("LinkBUContainer").style.display = "block";
            var link = video.Properties["LinkBU"];
            var httpLink = link.indexOf("http") == 0;
            if (!httpLink)
                link = LinkBUTemplate + link;
            $get("LinkBU").target = httpLink ? "_blank" : "_self";
            $get("LinkBU").href = link;
            $get("LinkBU").innerHTML = video.Properties["LinkBT"];
        }
        else
            $get("LinkBUContainer").style.display="none";
    }

    if (video.Properties["Quelle"] && $get("Quelle")) {
        var html = (video.Properties['QuelleU'] ? '<a href="' + video.Properties["QuelleU"] + '" target="_blank">' : '') + video.Properties['Quelle'] + (video.Properties['QuelleU'] ? '</a>' : '');
        if (video.Properties["Quelle2"])
            html += (video.Properties['Quelle2U'] ? '<a href="' + video.Properties["Quelle2U"] + '" target="_blank">, ' : ', ') + video.Properties['Quelle2'] + (video.Properties['Quelle2U'] ? '</a>' : '');
        $get("Quelle").innerHTML = html;
    }
    
}

function ShowVideoAndList(listId, currentVideo, repeater, container) {
    VideoLists[listId].Fetch(1, "ShowVideoAndListCB('" + listId + "'," + (currentVideo?"currentVideo":"null") + ",'" + repeater + "','" + container + "')");
}

function ShowVideoAndListCB(listId, video, repeater, container) {
    var list = VideoLists[listId];
    if (list.collection.length == 0) {
        list.Render(null);
        return;
    }
    if (!video) {
        video = list.collection.splice(0, 1)[0];
        rptReady([video], { name: repeater, container: container });
        RenderVideoProperties(video);
        currentVideo=video;
    }
    else {
        var found = false;
        for (var i = 0; i < list.collection.length; i++) {
            if (list.collection[i].Id == video.Id) {
                list.collection.splice(i, 1);
                found = true;
                break;
            }
        }
        if (!found) list.collection.length = list.collection.length - 1;
    }
    list.Render(null);
}

function changeCategory(catid, vList, ind, video, autoplay) {
    if (vList) {
        FirstLoadVideo = VideoLists[vList].collection[ind];
    }
    else if (video)
        FirstLoadVideo = video;
    else
        FirstLoadVideo = null;
    if (FirstLoadVideo)
        FirstLoadVideo.autoplay = autoplay;         
    if (SetCategory(CurrentCategory, catid))
        InitializeLists();
    else if (!PageManager.Category.NeedRedirect && FirstLoadVideo)
        ShowVideo(FirstLoadVideo, FirstLoadVideo.autoplay);
}

function SetCategory(oldCategory, catid) {
    if (oldCategory == catid) return false;
    if (PageManager.Category.NeedRedirect) {
        var params = {};
        if (catid)
            params.category = catid;
        else if (CurrentCategory > 0)
            params.category = CurrentCategory;
        if (FirstLoadVideo) {
            params.videoid = FirstLoadVideo.Id;
            if (FirstLoadVideo.autoplay)
                params.autoplay = 1;
        }
        PageManager.Category.Redirect(params);
        return false;
    }
    if ((!catid || catid==-1) && FirstLoadVideo && FirstLoadVideo.CategoryIds.length > 0) {
        if (FirstLoadVideo.CategoryIds.length > 1) FirstLoadVideo.CategoryIds.sort(CategorySort);
        catid = FirstLoadVideo.CategoryIds[0];
    }
    if (catid != -1 && !Categories["i" + catid]) {
        changeCategory(-1);
        return false;
    }
    var oldCat = $get("CAT" + oldCategory);

    if(oldCat)
        oldCat.className = "inactive";
    CurrentCategory = catid;
    if(catid>0){
        $get("CAT" + catid).className = "active";
    	if(!oldCat || (oldCat.BL!=Categories["i" + catid].BL))
		ChangeCatTab(Categories["i" + catid].BL);
    }
    ChangeTab("videos");

    return true;
}

function changePlayList(PLId) {
    if(PLId==CurrentPlayList) return;
    if (PageManager.PlayList.NeedRedirect) {
        
        PageManager.PlayList.Redirect({plid: PLId});
        return;
    }

    if (PLId != -1 && !PlayLists["i" + PLId]) {
        changePlayList(-1);
        return;
    }
    var oldPL=$get("PL" + CurrentPlayList);

    if(oldPL)
        oldPL.className = "inactive";
    CurrentPlayList = PLId;
    if (PLId > 0) {
        $get("PL" + PLId).className = "active";
        if ($get("PLTitle")) $get("PLTitle").innerHTML = PlayLists["i" + PLId].Description;
        if(CurrentPlayList>0)
            InitializeLists();
    }
}
CurrenCatTab="CAT";
function ChangeCatTab(BL){
	var nextTab=BL?"BL":"CAT";
	if(nextTab==CurrenCatTab) return;
	$get(CurrenCatTab + "Tab").className="inactive";
	$get(nextTab + "Tab").className="active";
	$get(CurrenCatTab + "Div").style.display="none";
	$get(nextTab + "Div").style.display = "block";
	CurrenCatTab = nextTab;
}



function InitializeWithParameters(){
    return false;
}
var searchDefaultValue;
function Initialize() {
    if($get("search"))searchDefaultValue = $get("search").value;
    if (!InitializeWithParameters()) {
       JS.Objects.GetCategories(PrepareCategories);
       
   }
}
var Categories=[];
function PrepareCategories(list) {
	Categories = list;
	var BLList=[];
	var CatList=[];
	for (var i = 0; i < list.length; i++){
		Categories["i" + Categories[i].CatId]=Categories[i];
		Categories[i].index=i;
		Categories[i].BL = Categories[i].CatName.substring(0,2)=="BL";
		Categories[i].CatName = Categories[i].CatName.substring(3);
		if(Categories[i].BL)
			BLList.push(Categories[i]);
		else
			CatList.push(Categories[i]);
    }
    PrepareBLContainer();
	rptReady(BLList,{container:"BLDiv",name:"categories"});
	PrepareCATContainer();
	rptReady(CatList, { container: "CATDiv", name: "categories" });
	if (CurrentCategory == -1 && FirstLoadVideo && FirstLoadVideo.CategoryIds.length>0) {
	    if (FirstLoadVideo.CategoryIds.length > 1) FirstLoadVideo.CategoryIds.sort(CategorySort);
	    CurrentCategory = FirstLoadVideo.CategoryIds[0];
	}
	GetPlayLists();
}
function PrepareBLContainer() { }
function PrepareCATContainer() { }

var PlayLists = [];
function GetPlayLists() {
    JS.Objects.GetPlayLists(PreparePlayLists);
    RenderSpecialVideo(true);

}
function PreparePlayLists(list) {
    PlayLists = list;
    for (var i = 0; i < list.length; i++) {
        PlayLists["i" + list[i].PlayListId] = list[i];
    }
    rptReady(PlayLists, { container: "PLDiv", name: "playList" });
    InitializeLists(true);
}

function CategorySort(val1,val2){
     return Categories["i" + val1].index - Categories["i" + val2].index;
}
function PrepareRepeaters() {
    //ShowSpecialVideo
    RepeaterTemplates.Add('player-sp',null,
'<div class="ad">Werbung</div>' +
'<h3>Sehnsucht Deutschland Partner stellen sich vor</h3>' +
'<div class="special-vid">' +
'  <a href="#" onclick="ModalPlayer[\'video-sp\'].Play(\'[{this.CurrentItem.Id}]\',[{this.CurrentItem.InterfaceId}],\'[{this.CurrentItem.InterfaceInfo}]\');return false"><img src="[{GetURL(this.CurrentItem,\'.s.jpg\')}]" width="235" height="132" alt="[{this.CurrentItem.Title}]" /><div class="bt-smallplay"></div></a>' +
'</div>' +
'<div class="special-teaser-title">' +
'    <h2>[{this.CurrentItem.Title}]</h2>' +
'    <span class="teaser-link"><a href="#" onclick="ModalPlayer[\'video-sp\'].Play(\'[{this.CurrentItem.Id}]\',[{this.CurrentItem.InterfaceId}],\'[{this.CurrentItem.InterfaceInfo}]\');return false">Jetzt anschauen</a></span>' +
'</div> '); 

    RepeaterTemplates.Add('TAGS', null,
'<a href="#" onclick="searchTag(\'[{this.CurrentItem}]\');return false;"><span>[{this.CurrentItem}]</span></a>',
null, ' ',null);
    RepeaterTemplates.Add('Tips', null,
'<li><a href="[{this.CurrentItem.URL}]" target="_blank">[{this.CurrentItem.Title}]</a></li>',
null, null, null);
    RepeaterTemplates.Add('Links', null,
'<a href="[{this.CurrentItem.URL}]" target="_blank">[{this.CurrentItem.Title}]</a>',
null, null, null);
    RepeaterTemplates.Add('CatList', null,
'<a href="[{PageManager.Category.Page}]?category=[{this.CurrentItem}]" onclick="changeCategory([{this.CurrentItem}]);return false;">[{Categories["i" + this.CurrentItem].CatName}]</a>',
null, ", ", null);
    PrepareNavigationTemplates();
    PreparePageRepeaters();
}
function PrepareNavigationTemplates() {

    RepeaterTemplates.Add('categories', null, '<li><a href="[{PageManager.Category.Page}]#c=[{this.CurrentItem.CatId}]" id="CAT[{this.CurrentItem.CatId}]" onclick="changeCategory([{this.CurrentItem.CatId}]);return false;" class="inactive">[{this.CurrentItem.CatName}]</a></li>');
    RepeaterTemplates.Add('playList', null, '<li><a href="[{PageManager.PlayList.Page}]#p=[{this.CurrentItem.PlayListId}]" id="PL[{this.CurrentItem.PlayListId}]" onclick="changePlayList([{this.CurrentItem.PlayListId}]);return false;" class="inactive">[{this.CurrentItem.Name}]</a></li>');
}
new VideoList(null, null, "Specials", OrderType.Date, 5, PagingType.None, -1, null, -1, false, SpecialChannel, true, -1, true);

function ModalPlayer(name, defaultHTML, animate){
    this.Name = name;
    this.DefaultHTML = defaultHTML || ('<center><div style="margin-top:10%;margin-bottom:5px;width:480px;height:10px;text-align:right;"><a class="bt-close"><img src="../player/assets/bt_close.gif" width="17" height="14" alt="Schliessen" title="Schliessen" style="border:none;" /></a></div><div id="' + name + '-player" style="width:480px;height:10px;overflow:visible" onmousedown="event.cancelBubble=true;"><div id="flash-content-sp"></div></div></center>');
    this.NeedAnimate = !!animate;
    ModalPlayer[name] = this;
}
ModalPlayer.prototype = {
    BGContainer: null,
    FrontContainer: null,
    Show: function () {
        if (!this.BGContainer) {
            this.BGContainer = $get(this.Name + "-bg-container");
            if (!this.BGContainer)
                this.BGContainer = CreateElementWithStyle("DIV", "width:100%;height:100%;position:fixed;top:0px;left:0px;visibility:hidden;zIndex:20000001;filter:alpha(opacity=80);opacity:0.8;backgroundColor:#0E0E0E;", true);
        }
        var name = this.Name;
        if (!this.FrontContainer) {
            this.FrontContainer = $get(this.Name + "-container");
            if (!this.FrontContainer) {
                this.FrontContainer = CreateElementWithStyle("DIV", "width:100%;height:100%;position:fixed;top:0px;left:0px;visibility:hidden;zIndex:20000002;", true);
                this.FrontContainer.innerHTML = this.DefaultHTML;
            } else
                this.DefaultHTML = this.FrontContainer.innerHTML;
            this.FrontContainer.onmousedown = function (event) { ModalPlayer[name].Hide(event); };
        }
        document.onkeydown = function (event) { event = window.event || event; if ((event.keyCode || event.which) == 27) ModalPlayer[name].Hide(event); else alert((event.keyCode || event.which)); };
        if (this.NeedAnimate) this.Animate(true);
        else
            this.BGContainer.style.visibility = this.FrontContainer.style.visibility = "visible";
    },
    Hide: function (event) {
        if (this.AnimationTimer) {
            window.clearTimeout(this.AnimationTimer);
        }
        document.onkeydown = null;
        this.BGContainer.style.visibility = this.FrontContainer.style.visibility = "hidden";
        this.FrontContainer.innerHTML = this.DefaultHTML;
    },
    AnimationTimer: null,
    Animate: function (initialize) {
        if (initialize) {
            this.BGContainer.style.height = this.BGContainer.style.width = "10%";
            this.BGContainer.style.border = "2px solid #ffffff";
        } else {
            this.BGContainer.style.visibility = "visible";
            val = this.BGContainer.style.width;
            val = new Number(val.substring(0, val.length - 1)) + 10;
            this.BGContainer.style.height = this.BGContainer.style.width = val + "%";
            this.BGContainer.style.top = this.BGContainer.style.left = ((100 - val) / 2) + "%";
            if (val == 100) {
                this.AnimationTimer = null;
                this.BGContainer.style.border = "none";
                this.BGContainer.style.top = this.BGContainer.style.left = 0 + "px";
                this.FrontContainer.style.visibility = "visible";
                WritePlayerContent(this.saveCtx.video, true, "flash-content-sp", "window");
                return;
            }
        }
        this.AnimationTimer = window.setTimeout("ModalPlayer['" + this.Name + "'].Animate()", 50);

    },
    Play: function (id, interfaceId, interfaceInfo) {
        if (currentVideo && $get("flash-content")) {
            $get("flash-content").innerHTML = '<img src="' + GetURL(currentVideo, '.b.jpg') + '">';
            window.setTimeout('WritePlayerContent(currentVideo);', this.NeedAnimate ? 3000 : 2000);
        }
        this.Show();
        var video = VideoLists["Specials"].Index[id];
        if (!this.NeedAnimate) WritePlayerContent(video, true, "flash-content-sp", "window"); //"window"
        else
            this.saveCtx = { video: video };
    }
}
new ModalPlayer("video-sp",null,true);
function CreateElementWithStyle(tag, style, appendBody) {
    var obj = document.createElement(tag);
    document.body.appendChild(obj);
    if(!style) return obj;
    var styleElms = style.split(";");
    for (var i = 0; i < styleElms.length; i++) {
        if (styleElms[i].length > 0) {
            var styleElm = styleElms[i].split(":");
            obj.style[styleElm[0]] = styleElm[1];
        }
    }
    return obj;
}

