var ajaxRequest;
var loop = '';
var currstreamname = ' ';
var stateSettings = 'hidden';
var stateSidebar = 'show';

var curPageTV = 1;    //sidebar pagenumber for scrolling livetv
var numOfPagesTV = 1
var curPageREC = 1;    //sidebar pagenumber for scrolling liveRecords
var numOfPagesREC = 1

var curEpgInfoId = 0;
var curCategory;

function init() {
    curCategory = defaultcategory;
    switchSidebarContent(sidebarType);
}

function sidebarHover(id, type) {
    $('#epgdetail').children().hide();
    $('#recdetail').children().hide();
    if (type == 'tv') {
        $('#epgdetail_content_tv_'+id).show();
        $('#sidebar_content_tv_channelid_'+id).addClass('highlight');
    }else{
        $('#epgdetail_content_rec_'+id).show();
        $('#sidebar_content_rec_assetid_'+id).addClass('highlight');
    }
}

function sidebarHoverOut(id, type) {
    $('#epgdetail_content_tv_'+id).hide();
    $('#epgdetail_content_rec_'+id).hide();

    if (curChannel > 0) {
        $('#epgdetail_content_tv_'+curChannel).show();
    }else if (curRecord > 0) {
        $('#epgdetail_content_rec_'+curRecord).show();
    }
    if (type == 'tv') {
        if (id != curChannel) {
            $('#sidebar_content_tv_channelid_'+id).removeClass('highlight');
        }
    }else {
        if (id != curRecord) {
            $('#sidebar_content_rec_assetid_'+id).removeClass('highlight');
        }
    }

}

function arrowHover(dir) {
    document.getElementById('arrow_'+dir).src='img/arrow_'+ dir + '_hover.gif';
}
function arrowHoverOut(dir) {
    document.getElementById('arrow_'+dir).src='img/arrow_'+ dir + '.gif';
}

function slide(dir) {
    if (sidebarType == 'livetv') {
        if (numOfPagesTV > 1) {
            if (dir == "up") {
                if (curPageTV > 1) {
                    nextPage = curPageTV-1;
                }else{
                    nextPage = curPageTV;
                }
            } else {
                if (curPageTV < numOfPagesTV) {
                    nextPage = curPageTV+1;
                }else{
                    nextPage = curPageTV;
                }
            }
            document.getElementById('sidebar_content_tv_'+curPageTV).style.display='none';
            document.getElementById('sidebar_content_tv_'+nextPage).style.display='block';
            curPageTV = nextPage;
        }
    }else if (sidebarType == 'records') {
        if (numOfPagesREC > 1) {
            if (dir == "up") {
                if (curPageREC > 1) {
                    nextPage = curPageREC-1;
                }else{
                    nextPage = curPageREC;
                }
            } else {
                if (curPageREC < numOfPagesREC) {
                    nextPage = curPageREC+1;
                }else{
                    nextPage = curPageREC;
                }
            }
            document.getElementById('sidebar_content_rec_'+curPageREC).style.display='none';
            document.getElementById('sidebar_content_rec_'+nextPage).style.display='block';
            curPageREC = nextPage;
        }
    }
    return false;
}

function switchSidebarContent(type) {
    if (type == 'livetv') {
    	getStations(defaultcategory);
        $("#records").hide();
        $("#channels").show();
        $("#sidebarHeaderList").show();
        $("#sidebarHeaderListRecord").hide();
        sidebarType = 'livetv';
        $('.menu_left').addClass('active');
        $('.menu_right').removeClass('active');
    }
    if (type == 'records') {
    	getRecords();
        $("#records").show();
        $("#channels").hide();
        $("#sidebarHeaderList").hide();
        $("#sidebarHeaderListRecord").show();
        sidebarType = 'records';
        $('.menu_left').removeClass('active');
        $('.menu_right').addClass('active');
    }
    if (type == 'catchup') {
    	getCatchup();
    	$("#sidebarHeaderListRecord").hide();
    	$("#sidebarHeaderList").hide();
	}
}

function getLiveChannelData(cid, cid2) {

    //thisMovie("nelloplayer").setPVRStream('','','','','');
    //thisMovie("nelloplayer").setLIVEStream('','','','','','','','','');

    $('#sidebar_content_tv_channelid_'+curChannel).removeClass('highlight');
    $('#sidebar_content_rec_assetid_'+curRecord).removeClass('highlight');

    curChannel = cid;
    curRecord = 0;

    if (ajaxRequest != undefined) {
        ajaxRequest.abort();
    }
    ajaxRequest = $.post(absolute_path + 'ajax.php' + get_params,
    {
        cmd: 'getLiveChannelParams',
        cid: cid,
        cid2: cid2
    },
        function(data)
        {
        	// we use params[0] for additional ad-targeting data
            params = data.split('|');
            checkvar = params[11] || false;

            if (params[3] > 0) {
	            var additionalData = params[0].split(';');
                var adVariablesExtended = '';

	            for (var i = 0; i < additionalData.length; i++) {
                    adVariablesExtended = additionalData[i].replace('=', '_') + (adVariablesExtended ? '+' : '') + adVariablesExtended + ';kv' + additionalData[i];
	            }
	            thisMovie("nelloplayer").setAdVariables(adVariablesExtended);

	            if (checkvar == false) {
					showChannel(params[3], params[4], params[5], params[6], params[7], params[1], params[10], params[8], params[2], params[9]);
	            }else{ // Dualchannel
					showChannel(params[3], params[4], params[5], params[6], params[7], params[1], params[10], params[8], params[2], params[9],params[13],params[14],params[15],params[16],params[17],params[11],params[20],params[18],params[12],params[19]);
	            }

			}

        }
     );
}

function showChannel(cid,pid,tstamp,lifetime,hash,streamname,app,uid,mcast,version) {

	//alert(cid + ', ' + pid+ ', ' +tstamp+ ', ' +lifetime+ ', ' +hash+ ', ' +streamname+ ', ' +app+ ', ' +uid+ ', ' +mcast+ ', ' +version);

	//thisMovie("nelloplayer").setAdVariables(adVariables + '+station_' + streamname);

	checkvar = arguments[10] || false;

	if (checkvar == false)
    {
		thisMovie("nelloplayer").setLIVEStream(cid,pid,tstamp,lifetime,hash,streamname,app,uid,mcast,version);
	}
	else // Dualchannel
	{
	    thisMovie("nelloplayer").setLIVEStream(cid,pid,tstamp,lifetime,hash,streamname,app,uid,mcast,version,arguments[10],arguments[11],arguments[12],arguments[13],arguments[14],arguments[15],arguments[16],arguments[17],arguments[18],arguments[19]);
	}

	// Social-TV: Senderwechsel mitteilen (Sprenger, 2011-07-20)
	if (typeof socialBar != 'undefined' && channel2station[cid] != 0) { socialBar.changeStation(channel2station[cid]); }

	currstreamname = streamname + " mit Teleboy";

	document.title = currstreamname;
}

function getPvrData(aid) {

    //thisMovie("nelloplayer").setPVRStream('','','','','');
    //thisMovie("nelloplayer").setLIVEStream('','','','','','','','','');

    $('#sidebar_content_tv_channelid_'+curChannel).removeClass('highlight');
    $('#sidebar_content_rec_assetid_'+curRecord).removeClass('highlight');

    curChannel = 0;
    curRecord = aid;

	if (ajaxRequest != undefined) {
    	ajaxRequest.abort();
    }
    ajaxRequest = $.post(absolute_path + 'ajax.php' + get_params,
    {
        cmd: 'getPvrParams',
        aid: aid
    },
        function(data)
        {
        	params = data.split('|');
			if (params[2] > 0) {
            	showPvr(params[1], params[2], params[3], params[4], params[0], params[5], params[6]);
			}
        }
     );
}

function showPvr(movie,user,tstamp,hash,title,version,app) {

	//alert(movie + ',' + user + ',' + tstamp + ',' + hash + ',' + title + ',' + version + ',' + app);

	thisMovie("nelloplayer").setPVRStream(movie,user,tstamp,hash,title,version,app);

	currstreamname = title + " mit Teleboy";
    document.title = currstreamname;

}

function getCatchupData(constid) {

    curChannel = 0;
    curRecord = 0;
    curCatchup = constid;

	if (ajaxRequest != undefined) {
    	ajaxRequest.abort();
    }
    ajaxRequest = $.post(absolute_path + 'ajax.php' + get_params,
    {
        cmd: 'getCatchupParams',
        constid: constid
    },
        function(data)
        {
        	params = data.split('|');
			if (params[2] > 0) {
            	showCatchup(params[1], params[2], params[3], params[4], params[0], params[5], params[6]);
			}
        }
     );
}

function showCatchup(movie,user,tstamp,hash,title,version,app) {

	thisMovie("nelloplayer").setPVRStream(movie,user,tstamp,hash,title,version,app);

	currstreamname = title + " mit Teleboy";
    document.title = currstreamname;

}

function getStations(category) {

    $("#sidebarHeaderList").find('a').removeClass('selected');
    $('#category_'+category).addClass('selected');

    if (category != curCategory) {
        $('#sidebar_content_tv').children().removeClass('highlight');
        $('#sidebar_content_rec').children().removeClass('highlight');

        curCategory = category;
        curPageTV = 1;
    }

    //loader
    if (arguments[1] === true)
    {
       $("#channels").html("<div class=\"loader\"><img id='loaderimg' src='" + absolute_path+ "../img/ajax-loader.gif" + "' width='16' height='16' alt='loader' /></div>");
    }

    $.post(absolute_path + 'ajax.php' + get_params,
    {
        cmd: 'getStations',
        category: category
    },
        function(data)
        {
            parts = data.split('*-///-*');
            $("#channels").html(parts[0]);
            $("#epgdetail").html(parts[1]);

            reloadcounter++;
            loop = window.setTimeout("getStations('"+category+"')", c_flashplayer_renewinterval);

            numOfPagesTV = $("#channels").children().length;  // number of pages for  TV sidebar scrolling

            $('#sidebar_content_tv_1').hide();
            $('#sidebar_content_tv_'+curPageTV).show();
            $('#sidebar_content_tv_channelid_'+curChannel).addClass('highlight');

            if (curChannel > 0) {
                $('#epgdetail_content_tv_'+curChannel).show();
                if (autostart == true) {
                    getLiveChannelData(curChannel, curDualChannel);
                    autostart = false;
                }
            }

            $(".ceebox").ceebox({ borderWidth:'1', titles:false }); /* Wusch re-initialisierung */
            $("tr.ceebox_buy_channel").click(function() {
                $.fn.ceebox.popup('<a href="/layer/rectv/buy_channel.inc.php?lang='+lang+'" rel="iframe modal:true">link</a>', { htmlWidth:500, htmlHeight:300, titles:false });
            });
            $("tr.ceebox_wrong_country").click(function() {
                $.fn.ceebox.popup('<a href="/layer/rectv/wrong_country.inc.php?lang='+lang+'" rel="iframe modal:true">link</a>', { htmlWidth:500, htmlHeight:300, titles:false });
            });
            $("tr.ceebox_technical_error").click(function() {
                $.fn.ceebox.popup('<a href="/layer/rectv/tech_error.inc.php?lang='+lang+'" rel="iframe modal:true">link</a>', { htmlWidth:500, htmlHeight:300, titles:false });
            });

        }
     );

    if ( ! currstreamname.value == null )
    {
        document.title = currstreamname;
    }

    //getRecords();
}

function getRecords() {

    //loader icon
    if (arguments[1] === true)
    {
       $("#channels").html("<div class=\"loader\"><img id='loaderimg' src='" + absolute_path+ "img/ajax-loader.gif" + "' width='16' height='16' alt='loader' /></div>");
    }

    $.post(absolute_path + 'ajax.php' + get_params,
        {
            cmd: 'getRecords'
        },
        function(data)
        {
            parts = data.split('*-///-*');
            $("#records").html(parts[0]);
            $("#recdetail").html(parts[1]);

            numOfPagesREC = $("#records").children().length;  // number of pages for sidebar scrolling
            if (numOfPagesREC < curPageREC) {
                curPageREC = 1;
            }

            $('#sidebar_content_rec_1').hide();
            $('#sidebar_content_rec_'+curPageREC).show();
            $('#sidebar_content_rec_assetid_'+curRecord).addClass('highlight');

            if (curRecord > 0) {
                $('#epgdetail_content_rec_'+curRecord).show();
                if (autostart == true) {
                    getPvrData(curRecord);
                    autostart = false;
                }
            }
        }
     );

}

function getCatchup() {

	//getPvrData(curCatchup);
	if (curCatchup > 0) {
		//$('#epgdetail_content_rec_'+curRecord).show();
        if (autostart == true) {
            getCatchupData(curCatchup);
            autostart = false;
        }
    }

}

function switchSmoothing(value) {

    $.post(absolute_path + 'ajax.php' + get_params,
        {
            cmd: 'switchSmoothing',
            smoothing: value
        },
        function(data)
        {
            window.location.reload();
        }
     );

}

function switchProtocol(value) {

    $.post(absolute_path + 'ajax.php' + get_params,
        {
            cmd: 'switchProtocol',
            protocol: value
        },
        function(data)
        {
            window.location.reload();
        }
     );

}

function thisMovie(movieName) {

    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName]
    }
    else {
        return document[movieName]
    }

}

function miniPlayer(cid,pid,tstamp,lifetime,hash,streamname,mcast,version) {
	//popup = window.open("/tv/player/miniplayer.php?cid="+cid+"&pid="+pid+"&tstamp="+tstamp+"&lifetime="+lifetime+"&hash="+hash+"&streamname="+streamname+"&mcast="+mcast+"&version="+version,"miniplayer","width=340,height=245,scrollbars=no,resizable=yes");
	popup = window.open("/tv/player/miniplayer.php?cid="+cid,"miniplayer","width=341,height=247,scrollbars=no,resizable=yes,toolbar=no,directories=no,menubar=no,status=no,location=no");
}

function showSettings() {

	if (stateSettings == "hidden") {
		document.getElementById('settings').style.display='';
		stateSettings = "show";
	} else {
		document.getElementById('settings').style.display='none';
		stateSettings = "hidden";
	}
    return false;

}

function showSidebar() {

	if (stateSidebar == "hidden") {

		$("div#sidebar").show();
		$("div#kinomode").hide();
		$("div#epginfo").show();
        $("div#epgdetail").show();
		document.getElementById('nelloplayer').width = 768;
  		document.getElementById('nelloplayer').height = 432;
		stateSidebar = "show";
	} else {
		$("div#sidebar").hide();
		$("div#kinomode").show();

		document.getElementById('nelloplayer').width = 1024;
  		document.getElementById('nelloplayer').height = 576;

        $("div#settingsctrl").hide();
  		$("div#epgdetail").hide();
		stateSidebar = "hidden";
	}
    return false;

}

function hideContent() {
    $("#notavailable").hide();
    $("#buychannel").hide();
    $("#nowmvstream").hide();
}

function toggleDesc(cat, size, time, cid) {

    if (size == 'short') {
        $('#info_'+size+'_'+cat+'_'+time+'_'+cid).hide();
        $('#info_long_'+cat+'_'+time+'_'+cid).show();
    }else{
        $('#info_'+size+'_'+cat+'_'+time+'_'+cid).hide();
        $('#info_short_'+cat+'_'+time+'_'+cid).show();
    }
    return false;

}

function resizeVideo() {

  var myWidth = 0, myHeight = 0;
  if ( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if ( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if ( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  // size 1  based on width
  var hvideoWidth = myWidth;
  var hvideoHeight = Math.round(hvideoWidth / 768 * 462);
  var pHeight = Math.round(myWidth / 462 * 768);

  // size 2 based on height
  var vvideoHeight = myHeight - 33;
  var vvideoWidth = Math.round(vvideoHeight / 462 * 768);
  var pWidth = Math.round(myHeight / 462 * 768);

 // alert("pWidth: "+pWidth);

  if (hvideoWidth > vvideoWidth) {
  	var videoWidth = vvideoWidth;
	var videoHeight = vvideoHeight;

	var resizeWidth = myWidth;
	var resizeHeight = pHeight;

  } else {
  	var videoWidth = hvideoWidth;
	var videoHeight = hvideoHeight;

	var resizeWidth = pWidth;
	var resizeHeight = myHeight;
  }

  // window.alert( 'Width = ' + myWidth );
  // window.alert( 'Height = ' + myHeight );

  // document.getElementById('vsize').innerHTML = "V: " +vvideoHeight + " x "+ vvideoWidth + " H: " + hvideoHeight + " x " + hvideoWidth;
  document.getElementById('nelloplayer').width = videoWidth;
  document.getElementById('nelloplayer').height = videoHeight;
  //var pagewidth = videoWidth + 210;
  //document.getElementById('page').style.width = pagewidth + "px";

}

function resizedStream() {

	resizeVideo();
	window.onresize = resizeVideo;

}

function sendLog() {

	thisMovie("nelloplayer").sendLog();

}

