////////////////////////////////////////////////////////////////////////
// maxVideo v1.0.0
// 2007-03-14 14:33:16
// SiC
////////////////////////////////////////////////////////////////////////
var maxVideo = {};

maxVideo.playList = {}; // data cache


//**********************************************************
// General Functions
//**********************************************************

//----------------------------------------------------------
// Before Initialization
//----------------------------------------------------------
maxVideo.pre_init = function(){

	$langNamespace = maxVideo.lang;

}


//----------------------------------------------------------
// Initialization
//----------------------------------------------------------
maxVideo.init = function(){

	// xhtml fix
	maxVideo.ui.adjustHeight();
	$event("+", "resize", window, maxVideo.ui.adjustHeight);

	maxVideo.ui.buildLinks();
	maxVideo.ui.buildTabs();
	maxVideo.ui.activateTab();

}


//**********************************************************
// UI Functions
//**********************************************************
maxVideo.ui = {}

//----------------------------------------------------------
// Toggle play list panel
//----------------------------------------------------------
maxVideo.ui.adjustHeight = function(){

	if(!$id("contentBox")) return;

	var targetHeight = document.documentElement.clientHeight -  $id("contentBox").offsetTop;

	$id("contentBox").style.height = (targetHeight - 130) + 'px';
	$id("playList").style.height = (targetHeight - 100) + 'px';

}


//----------------------------------------------------------
// Toggle play list panel
//----------------------------------------------------------
maxVideo.ui.togglePanel = function(bShow){

	var obj = $id("playListTD");
	var objSep = $id("separator");
	
	if(bShow == undefined){
		if(obj.style.display != 'none'){
			bShow = false;
		}else{
			bShow = true;
		}
	}

	if(bShow){
		obj.style.display = 'block';
		objSep.innerHTML = "&laquo;";
	}else{
		obj.style.display = 'none';
		objSep.innerHTML = "&raquo;";
	}

}


//----------------------------------------------------------
// Toggle category list
//----------------------------------------------------------
maxVideo.ui.toggleCategory = function(type, category){

	var obj = $id("cat_" + type + "_" + category);
	var objTitle = $id("cat_title_" + type + "_" + category);

	if(obj){
		if(obj.style.display != 'none'){
			obj.style.display = 'none';
			objTitle.innerHTML = '<code>+</code> ' + unescape(category).$encodeHTML();
		}else{
			obj.style.display = 'block';
			objTitle.innerHTML = '<code>-</code> ' + unescape(category).$encodeHTML();
		}
	}

}


//----------------------------------------------------------
// Build links
//----------------------------------------------------------
maxVideo.ui.buildLinks = function(){

	var output = '';

  for(var i=0;i<maxVideo.config.links.length;i++){

		var item = maxVideo.config.links[i];

		if(item.length==3){
			output += '&nbsp;&nbsp;<a href="' + item[1] + '" title="' + item[0] +'" target="_blank">'+
				'<img src="' + item[2] + '" alt="' + item[0] + '" />'+
				'</a>\n';
		}
  }

	$write(output, "links");

}


//----------------------------------------------------------
// Build tabs
//----------------------------------------------------------
maxVideo.ui.buildTabs = function(){

	var output = '';
	var outputWrapper = ''

	maxVideo.defaultTab = maxVideo.config.defaultTab;

	for(var item in maxVideo.config.channels){

		// some variables
		if(!maxVideo.defaultTab) maxVideo.defaultTab = item;
		if(!maxVideo.config.defaultTab){
			maxVideo.defaultTab = Math.random()<0.5 ? maxVideo.defaultTab : item;
		}

		if(!maxVideo.currentTab) maxVideo.currentTab = item;
		if(!maxVideo.playList[item]) maxVideo.playList[item] = {};

		output += '<a id="tab_' + item + '" href="javascript:maxVideo.ui.activateTab(\'' + item + '\')" onclick="this.blur();">' +
			(maxVideo.config.channels[item].icon ? '&nbsp;<img src="' + maxVideo.config.channels[item].icon + '" width="16" height="16" align="absmiddle"/>' : '' ) +
			'&nbsp;' + maxVideo.config.channels[item].title.$encodeHTML() + '&nbsp;' +
			'</a>';

		outputWrapper += '<div id="wrapper_' + item + '">';
		outputWrapper += '</div>';

	}

	$write(output, "tabs");
	$write(outputWrapper, "playList");

}


//----------------------------------------------------------
// Activate Tab
//----------------------------------------------------------
maxVideo.ui.activateTab = function(label){

	if(label == undefined) label = maxVideo.defaultTab;

	var item = maxVideo.config.channels[label];

	$id("tab_" + maxVideo.currentTab).className = "";
	$id("tab_" + label).className = "active";
	
	if(item.showPanel == undefined) item.showPanel = true;

	maxVideo.ui.togglePanel(item.showPanel);

	$id("wrapper_" + maxVideo.currentTab).style.display = "none";
	$id("wrapper_" + label).style.display = "block";

	maxVideo.currentTab = label;

	if(item.player == "__iframe"){
		maxVideo.ui.buildHTMLList();
	}else{
		maxVideo.data.loadPlayLists();
	}

}


//----------------------------------------------------------
// Build HTML Lists
//----------------------------------------------------------
maxVideo.ui.buildHTMLList = function(){

	var label = maxVideo.currentTab;
	var item = maxVideo.config.channels[label];

	if(!item.built){

		var output = '';

		if(!item.currentList) item.currentList = 0;

		for(var i=0; i<item.lists.length;i++){
			
			if(item.lists[i].cat){

				// category list
				output += '<div class="catPanel" id="cat_title_' + i + '"' +
					' onclick="maxVideo.ui.toggleHTMLCategory(' + i + ',\'' + escape(item.lists[i].title) +'\')">' +
					'<code>' + (item.lists[i].open ? '-' : '+') +'</code> ' + item.lists[i].title.$encodeHTML() +
					'</div>';

				output += '<div id="cat_' + i + '" class="itemList" style="' + (item.lists[i].open ? "display: block;" : "display: none;")+ '">';

				for(var j=0;j<item.lists[i].items.length; j++){
					output += '<a href="javascript:maxVideo.ui.activateHTMLItem(\'' + label + '\', ' + i + ',' + j + ')" onclick="this.blur()">' +
						item.lists[i].items[j].title.$encodeHTML() +
						'</a>';
				}

				output += '</div>';
		
			}else{

				// no category
				output += '<div class="catPanel" id="cat_title_' + label + '_' + i + '"' +
					' onclick="maxVideo.ui.activateHTMLItem(\''+label+'\',\'' + i + '\')">' +
					'<code>&middot;</code> ' + item.lists[i].title +
					'</div>';
			}

		}

		$write(output, 'wrapper_' + label);

		item.built = true;

	}
	
	if(item.lists[0].cat){
		maxVideo.ui.activateHTMLItem(label, 0, 0);
	}else{
		maxVideo.ui.activateHTMLItem(label, 0);
	}

}


//----------------------------------------------------------
// Toggle HTML List Category
//----------------------------------------------------------
maxVideo.ui.toggleHTMLCategory = function(index, title){
	
	var obj = $id("cat_" + index);
	var objTitle = $id("cat_title_" + index);

	if(obj){
		if(obj.style.display != 'none'){
			obj.style.display = 'none';
			objTitle.innerHTML = '<code>+</code> ' + unescape(title).$encodeHTML();
		}else{
			obj.style.display = 'block';
			objTitle.innerHTML = '<code>-</code> ' + unescape(title).$encodeHTML();
		}
	}

}


//----------------------------------------------------------
// Toggle HTML List Item
//----------------------------------------------------------
maxVideo.ui.activateHTMLItem = function(label, index, subIndex){

	var channel = maxVideo.config.channels[label];
	
	if(subIndex == undefined){

		var obj = $id('cat_title_' + label + '_' + channel.currentList);
		obj.className = "catPanel";
		obj.innerHTML = '<code>&middot;</code> ' + channel.lists[channel.currentList].title;

		var obj = $id('cat_title_' + label + '_' + index);
		$id('cat_title_' + label + '_' + index).className = "catPanel-active";
		obj.innerHTML = '<strong><code>&raquo;</code> ' + channel.lists[index].title + '</strong>';

		channel.currentList = index;

	}

	var item = subIndex == undefined ? channel.lists[index] : channel.lists[index].items[subIndex];

	// show some info text
	maxVideo.ui.setInfoBarText(
		'<strong>' + $lang("current_playing") + ':</strong> &nbsp; ' +
		channel.title.$encodeHTML() + ' &raquo; ' +
		channel.lists[index].title.$encodeHTML() +
		(subIndex == undefined ? '' : ' &raquo; ' + channel.lists[index].items[subIndex].title.$encodeHTML())
	);
	
	if(item.outside){
		window.open(item.url);
		$id("playerBox").innerHTML = '<p>' + $lang("outside_not_open") + '</p><p><a href="'+item.url.$sanitizeURL()+'" target="_blank">' + item.url.$encodeHTML() + '</a></p>';
	}else{
		maxVideo.ui.bindIframe(label, index, subIndex);
		maxVideo.ui.adjustIframe();
		$event("+", "resize", window, maxVideo.ui.adjustIframe);
	}


}


//----------------------------------------------------------
// Bind IFrame into player area
//----------------------------------------------------------
maxVideo.ui.bindIframe = function(label, index, subIndex){

	maxVideo.action.setPlayer(label);

	var item = maxVideo.config.channels[label].lists[index];
	if(subIndex != undefined){
		item = item.items[subIndex];
	}

	$id(maxVideo.config.playerID).src = item.url;

}


//----------------------------------------------------------
// Bind IFrame into player area
//----------------------------------------------------------
maxVideo.ui.adjustIframe = function(){

	if(maxVideo.currentPlayer != "__iframe") return;

	if(!$id("contentBox")) return;

	var targetHeight = $id("contentBox").style.height;

	$id(maxVideo.config.playerID).style.height = targetHeight;

}


//----------------------------------------------------------
// Build list wrappers
//----------------------------------------------------------
maxVideo.ui.buildListWrapper = function(label, index){

	var uid = label + "__" + index;
	var obj = $id(uid);

	if(!obj){
		$write(
			'<div id="list_' + uid +'">&nbsp;</div>',
			'wrapper_' + label,
			true
		);
	}

}


//----------------------------------------------------------
// Build list wrappers
//----------------------------------------------------------
maxVideo.ui.buildPlayList = function(label, index){

	var list = maxVideo.playList[label]["list_" + index];
	var output = '';
	var count = 0;

	for(var category in list){

		output += '<div class="catPanel" id="cat_title_' + label + '_' + category + '"' +
			' onclick="maxVideo.ui.toggleCategory(\''+label+'\',\'' + category + '\')">' +
			'<code>+</code> ' + unescape(category).$encodeHTML() +
			'</div>';

		output += '<div id="cat_' + label + '_' + category + '" class="itemList" style="display: none;">';

		for(var i=0;i<list[category].length; i++){
			output += '<a href="javascript:maxVideo.action.playItem(\'' + label + '\', ' + index + ',\'' + category + '\', ' + i + ')" onclick="this.blur()">' +
				list[category][i].title.$encodeHTML() +
				'</a>';
			count++;
		}

		output += '</div>';

	}

	if(count == 0) output = '<div class="status">' + $lang("no_content") + '</div>';

	$write(output, 'list_' + label + '__' + index);

}


//----------------------------------------------------------
// set infomation bar text
//----------------------------------------------------------
maxVideo.ui.setInfoBarText = function(html){

	$write(html, 'infobar');

}


//**********************************************************
// Data Access
//**********************************************************
maxVideo.data = {};

//----------------------------------------------------------
// Load in play list - pre-check
//----------------------------------------------------------
maxVideo.data.loadPlayLists = function(label){

	if(!label) label = maxVideo.currentTab;

	if(!maxVideo.playList[label]){
		alert("maxVideo.data.loadPlayLists :: invalid label");
		return;
	}

	// if index list is present
	if(!maxVideo.config.channels[label].lists){
		maxVideo.data.loadIndexList(label);
		return;
	}

	// got lists
	for(var i=0;i<maxVideo.config.channels[label].lists.length;i++){

		if(!maxVideo.playList[label]["list_"+i]){
			setTimeout("maxVideo.data.loadList('" + label + "'," + i + ")", 500 * i);
		}

	}

}


//----------------------------------------------------------
// Load in index list
//----------------------------------------------------------
maxVideo.data.loadIndexList = function(label){

	var item = maxVideo.config.channels[label];

	$write(
		'<div class="status">' + item.title.$encodeHTML() + ' ' + $lang("loading_index") +'</div>',
		'wrapper_' + label
	);

	if(!maxAjaxManager.get(label, item.indexList, maxVideo.data.parseIndexList)){
		$write(
			'<div class="status">' +
			$lang("load_error") + ': ' + maxAjaxManager.error[label].text + ' (' + maxAjaxManager.error[label].code + ')' +
			'</div>',
			'wrapper_' + label
		);
	}

}


//----------------------------------------------------------
// Parse index list
//----------------------------------------------------------
maxVideo.data.parseIndexList = function(id, result, errorCode, errorText){

	var item = maxVideo.config.channels[id];

	// failed
	if(!result){
		$write(
			output = '<div class="status">' + item.title.$encodeHTML() + ' ' + $lang("load_error") +'</div>',
			'wrapper_' + id
		);
		return;
	}

	// ok
	var lists;

	switch(id){
//		case "yoqoo":
//			lists = maxVideo.data.parseYoqooIndex(maxAjaxManager.result[id]);
//			break;
	}

	// output
	if(lists){
		$write('', 'wrapper_' + id);
		maxVideo.config.channels[id].lists = lists;
		maxVideo.data.loadPlayLists(id);
	}else{
		$write('<div class="status">'+ $lang("no_content") +'</div>', 'wrapper_' + id);
	}


}


//----------------------------------------------------------
// Parse Yoqoo index list
//----------------------------------------------------------
//maxVideo.data.parseYoqooIndex = function(xml){
//
//	// Parse the File
//	var	xpathArray = {
//		"namespace": '',
//		"validate": '/rss',
//		"items": '//item',
//		"attributes" : {
//			"title" : 'title/text()',
//			"url" : 'link/text()'
//		}
//	}
//
//	var arrItems = maxXmlListParser.parse(xml, xpathArray);
//
//	return arrItems;
//
//}


//----------------------------------------------------------
// Load in play list
//----------------------------------------------------------
maxVideo.data.loadList = function(label, index){

	var item = maxVideo.config.channels[label].lists[index];
	var uid = label + "__" + index;

	maxVideo.ui.buildListWrapper(label, index);

	$write(
		'<div class="status">' + item.title.$encodeHTML() + ' ' + $lang("loading") +'</div>',
		'list_' + uid
	);

	if(!maxAjaxManager.get(uid, item.url, maxVideo.data.parseList)){
		$write(
			'<div class="status">' +
			$lang("load_error") + ': ' + maxAjaxManager.error[uid].text + ' (' + maxAjaxManager.error[uid].code + ')' +
			'</div>',
			'list_' + uid
		);
	}

}


//----------------------------------------------------------
// Parse play list
//----------------------------------------------------------
maxVideo.data.parseList = function(id, result, errorCode, errorText){

	// lists
	var arrID = id.split("__");
	var label = arrID[0];
	var index = parseInt(arrID[1],10);

	var item = maxVideo.config.channels[label].lists[index];

	// failed
	if(!result){
		$write(
			output = '<div class="status">' + item.title.$encodeHTML() + ' ' + $lang("load_error") +'</div>',
			'list_' + id
		);
		return;
	}

	// ok
	var playList;

	switch(label){
		case "pplive":
			playList = maxVideo.data.parsePPLive(maxAjaxManager.result[id]);
			break;
		case "yoqoo":
//			playList = maxVideo.data.parseYoqoo(maxAjaxManager.result[id], item.title);
//			break;
//		case "pcast":
//			playList = maxVideo.data.parsePCast(maxAjaxManager.result[id]);
//			break;
	}

	playList = maxVideo.data.sortByCategory(playList);

	// cache result
	maxVideo.playList[label]["list_"+index] = playList;

	// output
	maxVideo.ui.buildPlayList(label, index);

}


//----------------------------------------------------------
// Parse PPLive play list
//----------------------------------------------------------
maxVideo.data.parsePPLive = function(xml){

	// Parse the File
	var	xpathArray = {
		"namespace": '',
		"validate": '/root/channel',
		"items": '//channel',
		"attributes" : {
			"title" : 'ChannelName/text()',
			"url" : 'PlayLink/text()',
			"category" : 'Catalog/text()'
		}
	}

	var arrItems = maxXmlListParser.parse(xml, xpathArray);

	return arrItems;

}


//----------------------------------------------------------
// Parse Yoqoo play list
//----------------------------------------------------------
//maxVideo.data.parseYoqoo = function(xml, category){
//
//	// Parse the File
//	var	xpathArray = {
//		"namespace": '',
//		"validate": '/rss',
//		"itemTemplate": {
//			'category': category
//		},
//		"items": '//item',
//		"attributes" : {
//			"title" : 'title/text()',
//			"url" : 'enclosure/@url'
//		}
//	}
//
//	var arrItems = maxXmlListParser.parse(xml, xpathArray);
//
//	return arrItems;
//
//}


//----------------------------------------------------------
// Parse PCast play list
//----------------------------------------------------------
//maxVideo.data.parsePCast = function(xml){
//
//	// Parse the File
//	var	xpathArray = {
//		"namespace": '',
//		"validate": '/rss',
//		"items": '//item',
//		"attributes" : {
//			"title" : 'title/text()',
//			"url" : 'enclosure/@url',
//			"category" : 'type/text()'
//		}
//	}
//
//	var arrItems = maxXmlListParser.parse(xml, xpathArray);
//
//	return arrItems;
//
//}


//----------------------------------------------------------
// Sort list by Category
//----------------------------------------------------------
maxVideo.data.sortByCategory = function(arrItems){

	var arrList = {};

	for(var i=0;i<arrItems.length;i++){

		var cat = arrItems[i].category ?  arrItems[i].category.$trim() : maxVideo.config.defaultCategory;
		cat = escape(cat);

		if(arrList[cat] == undefined){
			arrList[cat] = [];
		}

		arrList[cat].push(arrItems[i]);

	}

	return arrList;

}


//**********************************************************
// Actions
//**********************************************************
maxVideo.action = {};


//----------------------------------------------------------
// Play item
//----------------------------------------------------------
maxVideo.action.playItem = function(label, index, category, itemIndex){

	var item = maxVideo.playList[label]["list_" + index][category][itemIndex];

	$id("notebar").style.display = "none";

	// change player
	maxVideo.action.setPlayer(label);

	var player = $id(maxVideo.config.playerID);

	try{
		switch(label){
			case "pplive":
				player.Stop();
				player.URL = item.url;
				break;
//			case "yoqoo":
//				player.movie = item.url;
//				$id("embed_" + maxVideo.config.playerID).src =  item.url;
//				break;
//			case "pcast":
//				player.stop();
//				player.Channel = item.url;
//				break;
//			case "ppstream":
//				player.pause();
//				player.src = item.url;
//				player.play();
//				break;
		}
	}catch(e){
		maxVideo.action.showError(label);
	}

	// show some info text
	maxVideo.ui.setInfoBarText(
		'<strong>' + $lang("current_playing") + ':</strong> &nbsp; ' +
		maxVideo.config.channels[label].title.$encodeHTML() + ' &raquo; ' +
		unescape(category).$encodeHTML() + ' &raquo; ' +
		item.title.$encodeHTML()
	);

}


//----------------------------------------------------------
// Show Error Message when player init failed
//----------------------------------------------------------
maxVideo.action.showError = function(label){

	var output = $lang("install_player") +
		' <a href="' + maxVideo.config.installers[label] + '" target="_blank">' + $lang("manual_install") + '</a>';

	$write(output, "notebar");

	$id("notebar").style.display = "block";

}


//----------------------------------------------------------
// Set Player
//----------------------------------------------------------
maxVideo.action.setPlayer = function(label){

	if(maxVideo.currentPlayer == label) return;

	// remove old player
	var player = $id(maxVideo.config.playerID);

	try{

		switch(maxVideo.currentPlayer){
			case "pplive":
				player.Stop();
				player.URL = "";
				player.Destroy();
				break;
			case "pcast":
				player.stop();
				player.Channel = "";
				break;
			case "ppstream":
				player.stop();
				player.src = "";
				break;
		}

	}catch(e){}

	// attach new player
	var player = maxVideo.config.channels[label].player ? maxVideo.config.channels[label].player : label;
	$id("playerBox").innerHTML = maxVideo.config.players[player];
	maxVideo.currentPlayer = player;

}
