// JavaScript Document
/*	FILE:	/assets/js/channel_page.js
	DESC:	This page contains scripts required by all channel pages
			
	REV:	$Rev: 17056 $
			
	MAKE NO EDITS ABOVE THIS LINE
	
	MORE:	
	
	LAST MODIFIED:	8/16/2010 by Nikhil Mohan
*/

function minf(min_data)
{
    if(min_data < 10)
          return "0"+min_data;
    else
          return min_data;
}

function formaDate(xml_time){
	var vid_start_time  = str2date(xml_time);
		var Y = vid_start_time.getFullYear();
		var m = vid_start_time.getMonth();
		var d = vid_start_time.getDate();
		var H = vid_start_time.getHours();
		var i = vid_start_time.getMinutes()
	var vid_local_date = new Date(Date.UTC(Y,m,d,H,i,0,0));
		var lY = vid_local_date.getFullYear();
		var lm = vid_local_date.getMonth();
		var ld = vid_local_date.getDate();
		var lH = vid_local_date.getHours();
		var li = vid_local_date.getMinutes();
	var current_date = new Date();
	if(current_date.toDateString() == vid_local_date.toDateString()){
		var vid_nice_time = "";
	}
	else
	{
		var vid_nice_time = (vid_local_date.getMonth()+1) + "/" +(vid_local_date.getMonth()+1) + " at ";
	}
	if(vid_local_date.getHours() == 0)
	{
		vid_nice_time += "12:" + minf(vid_local_date.getMinutes()) + " am";
	}
	else
	{
		if(vid_local_date.getHours() < 12)
		{
			vid_nice_time +=  vid_local_date.getHours() + ":" + minf(vid_local_date.getMinutes()) + " am";
		}
		else
		{
			if(vid_local_date.getHours()-12 == 0)
			{
				vid_nice_time +=  "12:" + minf(vid_local_date.getMinutes()) + " pm";
			}
			else
			{
				vid_nice_time +=  (vid_local_date.getHours()-12) + ":" + minf(vid_local_date.getMinutes()) + " pm";
			}
		}
	}
	return vid_nice_time;
}

if (RESIZE_PLAYER == null) {
  var RESIZE_PLAYER = true;
}

if (Dyyno == null) {
    var Dyyno = null;
}

var wowza_session_ended_count = 2;
var PlaylistArray = []; var resw_array = []; var resh_array = [];
var curr_pl_vid_id, curr_res_w, curr_res_h;


// FIX BROKEN JS & PROVIDE MISSING FUNCTIONALITY
if (!Array.indexOf) {
  Array.prototype.indexOf = function (obj, start) {
    for (var i = (start || 0); i < this.length; i++) {
      if (this[i] == obj) {
        return i;
      }
    }
    return -1;
  }
};

String.prototype.capitalize = function(){
   return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
};

function isset () {
    // discuss at: http://phpjs.org/functions/isset    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    var a=arguments, l=a.length, i=0;
        if (l===0) {
        throw new Error('Empty isset'); 
    }
    while (i!==l) {        if (typeof(a[i])=='undefined' || a[i]===null) { 
            return false; 
        } else { 
            i++; 
        }    }
    return true;
}

function addslashes(str) {
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\0/g,'\\0');
	return str;
};

function stripslashes(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\0/g,'\0');
	str=str.replace(/\\\\/g,'\\');
	return str;
};

// SET UP THE FUNCTIONS
function startCountup(){
    var cd_id = this.getAttibute("id");
    document.getElementById(cd_id).innerHTML = "";
    $('#'+cd_id).countdown({since:vid_start_time,compact:true,layout:'Started {dn} {dl} {hnn}{sep}{mnn}{sep}{snn} ago.'});
}

function dyyno_openChatWindow() {
	var chat_url = REG_URL + '/auth/mychannel/chat.php?sid=' + HASH_VARS['sid'];
	var win_name = 'dyynoChatWindow_' + HASH_VARS['sid'];
	var features = 'width=440,height=440';
	window.open(chat_url,win_name,features);
};

function dyyno_openVideoWindow(vid_type,vid_id) {
	if(HASH_VARS['sid']){
		var vid_type = 'sid';
		var vid_id = HASH_VARS['sid'];
	}else{
		var vid_type = 'vod';
		var vid_id = HASH_VARS['vod'];
	}
	var vid_url = REQ_PROT + '://' + REQ_HOST + '/player/?channel=' + THIS_CHANNEL_NAME + '&' + vid_type + '=' + vid_id + '&popout=1';
	var win_name = 'dyynoVideoWindow' + vid_id;
	var player_height = document.getElementById('dyynoplayerdiv').style.height;
	var player_width = document.getElementById('dyynoplayerdiv').style.width;
	var features = 'resizable=yes,width='+player_width+',height='+player_height;
	window.open(vid_url,win_name,features);
};

function dyynoPopoutOpened() {
	if (HASH_VARS['sid']) {
		dyynoStartPlayer2('live', HASH_VARS['sid'], '100%', '100%', false);
	} else {
		var player_height = document.getElementById('dyynoplayerdiv').style.height;
		var player_width = document.getElementById('dyynoplayerdiv').style.width;
		dyynoStartPlayer2('vod', HASH_VARS['vod'], player_height, player_width, false);
	}
}

function str2date(timestamp){    
    var parts = timestamp.split(' ');
    var day = parts[0].split('-');
    var time = parts[1].split(':');
    var myDate = new Date(day[0],(day[1]-1),day[2],time[0],time[1],time[2]);
    return myDate;
};

function showElement(elem_id){
    document.getElementById(elem_id).style.display="block";
};

function hideElement(elem_id){
    document.getElementById(elem_id).style.display="none";
};

function removeElement(elem_id){
    var parent_element = document.getElementById(elem_id).parentNode;
    var target_element = document.getElementById(elem_id);
    parent_element.removeChild(target_element);
};

function dyynoStartPlayer2(type, id, width, height, autostart)
{
	if(typeof(DISPLAY_CHAT_WIDGET) != "undefined")
	{	
		if(DISPLAY_CHAT_WIDGET)
		{
			loadChatWindow();
		}
	}

	if (document.getElementById('statusdiv').innerHTML)
		document.getElementById('statusdiv').innerHTML = '';
	document.getElementById('dyynoVideoPlayer').style.backgroundImage = 'none';
	window.scrollTo(0,0);
	terminateDyyno();
	active_session_id = null;
	
	var player = document.getElementById('dyynoplayerdiv');
	if(type == 'live' || type == 'sr')
	{
		player.style.width = '640px';
		player.style.height = '480px';
		if(typeof(DISPLAY_CHAT_LINK) == "undefined" || !DISPLAY_CHAT_LINK) {}
		else showElement('chatLink');
		showElement('floatLink');
		hashInject('vod', false);
		hashInject('sid', id);
		var image = RSS_URL + '/sessionimages/' + id + '.jpg';
	}
	else if(type == 'vod')
	{
		if(!RESIZE_PLAYER)
		{
			player.style.width = "640px";
			player.style.height = "480px";
		}
		else
		{
			player.style.width = ""+width+"px";
			player.style.height = ""+height+"px";
		}

		hideElement('chatLink');
		hideElement('floatLink');
		hashInject('sid', false);
		hashInject('vod', id);
		var image = 'http://' + REQ_HOST + '/assets/image_display.php?id=' + id;
	}
	
	if(dyyno_is_compatible)
	{
		var player_path = "http://" + REQ_HOST + "/assets/players/dyynoplayer-"+DYYNOPLAYER_VERSION+".swf";
		if(!RESIZE_PLAYER)
		{
			var so = new SWFObject(player_path, 'dyynoFlashPlayer', 640, 480, '9');
		}
		else 
		{
			var so = new SWFObject(player_path, 'dyynoFlashPlayer', width, height, '9');
		}
		so.addParam('allowfullscreen', 'true');
		so.addParam('allowscriptaccess', 'always');
		so.addParam('bgcolor', '#000000');
		so.addParam('wmode','opaque');
		if (autostart !== false) 
		{
			so.addVariable('autostart', 'true');
		} 
		else 
		{
			so.addVariable('autostart', 'false');
			so.addVariable('image', image);
			so.addVariable('file', 'dyyno/Dyyno_preroll_generic.flv');
		}
		if (HASH_VARS['bufferlength'])
			so.addVariable('bufferlength', HASH_VARS['bufferlength']);
		else
			so.addVariable('bufferlength', 2);
		so.addVariable('channel', THIS_CHANNEL_NAME);
		so.addVariable('controlbar', 'over');
		so.addVariable('debugPlayer', HASH_VARS['debug']);
		so.addVariable('playerready', 'dyynoPlayerReady');
		if (autostart === false) 
		{
			so.addVariable('adzone', 'Personal_Pre_roll');
		} 
		else if (typeof(window.DEFAULT_ADZONE) === 'undefined')
		{
			so.addVariable('adzone', '');
		} 
		else 
		{
			so.addVariable('adzone', window.DEFAULT_ADZONE);
		}
        if (typeof(window.AD_NETWORK) !== 'undefined') {
            so.addVariable('ads.network', window.AD_NETWORK);
            if (window.AD_NETWORK == 'yume') {
                so.addVariable('ads.yume_domain', '413HVKesLgW');
                so.addVariable('ads.yume_server', 'plg1.yumenetworks.com');
            }
        }
        if (typeof(window.AD_ZONE) !== 'undefined') {
            so.addVariable('ads.zone', window.AD_ZONE);
        }
        if (typeof(window.yume_flash_callback) !== 'undefined') {
            so.addVariable('ads.banner', 'medrect');
        }
		if(type == 'live' || type == 'sr')
			so.addVariable('sid', id);
		else if(type == 'vod')
			so.addVariable('vod', id);
        if (typeof(PLAYER_PARAMS) == 'object') {
            for (param in PLAYER_PARAMS) {
                so.addVariable(param, PLAYER_PARAMS[param]);
            }
        }
		so.write('dyynoplayerdiv');
	}
	else
	{
		alert("Unable to play videos, until the compatibility issues are addressed.");
	}
}

function dyynoPlayerReady(obj){
	var player = document.getElementById('dyynoFlashPlayer');
	player.addEventListener('dyynoPlayerError', 'dyynoPlayerError');
	player.addEventListener('dyynoVideoResize', 'dyynoPlayerResize');
	player.addModelListener('STATE','dyynoLoadNextVideo');
}

function dyynoPlayerError(error_desc){
	var errorHTML = '<p class="error">' + error_desc + '</p>';
	document.getElementById('dyynoplayerdiv').innerHTML = errorHTML;
}

function dyynoPlayerResize(obj){
	var player = document.getElementById('dyynoplayerdiv');

	if(!RESIZE_PLAYER)
	{
		player.style.width = "640px";
		player.style.height = "480px";
	}
	else
	{
		player.style.width = "" + obj.width + "px";
		player.style.height = "" + obj.height + "px";
	}
	
}

var curr_index = 0;

//Dyyno Playlist Event Handler
function dyynoLoadNextVideo(obj)
{
	if(obj.newstate == "COMPLETED")
	{
		//alert("Array = "+PlaylistArray+"; Prev Index = "+curr_index+" AND total indexes = "+length);
		if(PlaylistArray.length == 0 || curr_index == (PlaylistArray.length-1))
		{
			//Last video reached, do nothing
		}
		else
		{			
			curr_pl_vid_id = PlaylistArray[curr_index+1];
			//alert(curr_pl_vid_id+" array = "+PlaylistArray);
			//curr_res_w = resw_array[curr_index+1];
			//curr_res_h = resh_array[curr_index+1];
			dyynoStartPlayer2('vod',curr_pl_vid_id,640,480);
			window.frames['dyynoPLMembers'].setCurrentVideo(curr_index+1);
			curr_index++;
		}
	}
}

///////////////////////////////////////////////
// START OF PLAYLIST FUNCTIONS
///////////////////////////////////////////////

//Functions added to display video list at bottom of player for playlist view

$(window).load( function(){	$("#dyynoPLViewer").hide();}  );

$(document).ready(function()
{
	$(document).bind('click', function(e) 
	{
        var $clicked = $(e.target);
    });
});

function showPLmemDiv(val)
{		
	if(val == 1)
		$("#dyynoPLViewer").show();
	else
		$("#dyynoPLViewer").hide();
}

function set_current_vid_id(video_id, res_w, res_h, curr_sel)
{
	curr_index = parseInt(curr_sel);
	curr_pl_vid_id = video_id;
	curr_res_w = res_w;
	curr_res_h = res_h;
}

function populatePLArray(data_array, w_data_array, h_data_array)
{
	PlaylistArray = []; resw_array = []; resh_array=[];

	for(var i=0; i<data_array.length; i++)
	{
		PlaylistArray[i] = data_array[i];
		resw_array[i] = w_data_array[i];
		resh_array[i] = h_data_array[i];
	}
}

function loadPlaylistPanel(pl_id, video_id, res_w, res_h, channel_name, pl_name)
{
	curr_pl_vid_id = video_id;		
	showPLmemDiv(1);
	document.getElementById('dyynoPLViewer').innerHTML = '';
	document.getElementById('dyynoPLViewer').innerHTML = '<iframe id="dyynoPLMembers" name="dyynoPLMembers" src="/_channel/vidsinpl.php?pl_id='+pl_id+'&user='+channel_name+'&pltitle='+pl_name+'" width="960" height="200" frameborder="0" scrolling="no"></iframe>';
	dyynoStartPlayer2('vod',video_id,res_w,res_h);
}

///////////////////////////////////////////////
// END OF PLAYLIST FUNCTIONS
///////////////////////////////////////////////


function dyynoDoVideo(host,c_port,sid,wowza_url,adzone){
    if(document.getElementById('statusdiv').innerHTML)
      document.getElementById('statusdiv').innerHTML = '';
    //window.parent.scrollTo=(0,0);
    window.scrollTo(0,0);
        if(dyyno_is_compatible){
        document.getElementById("dyynoVideoPlayer").style.backgroundImage = "none";
        var z = "";
        var w = 0;
        var h = 0;
		/*if(BROADCASTER == 1){
			adzone = "Personal_Pre_roll";
		}*/
        active_session_id = sid;
		if(typeof(DISPLAY_CHAT_LINK) == "undefined" || !DISPLAY_CHAT_LINK) {}
		else showElement('chatLink');
		showElement('floatLink');
		hashInject('vod',false);
		hashInject('sid',sid);
		//launch_dyyno_player(host,c_port,sid,wowza_url,adzone,z,z,w,h,z,HASH_VARS['debug'],null,null);
        launch_dyyno_player(host,c_port,sid,wowza_url,adzone,z,z,w,h,z,HASH_VARS['debug'],null,null,BROADCASTER);
    }else{
        alert("Unable to play videos, until the compatibility issues are addressed.");
    }
};

function dyynoDoVOD(vod_filename,vod_width,vod_height,vod_idn,channel)
{
	if(typeof channel === 'undefined')
	{
		channel = THIS_CHANNEL_NAME;
	}
	if (document.getElementById('statusdiv').innerHTML)
      document.getElementById('statusdiv').innerHTML = '';
    //window.parent.scrollTo=(0,0);
    window.scrollTo(0,0);
    terminateDyyno();
    active_session_id = null;
    
    video_params["host"] = "vod.dyyno.com";
    video_params["seek"] = "fastplay";
    video_params["locate"] = channel;
    video_params["content"] = "mp4:"+vod_filename;
    video_params["video_filename"] = vod_filename;
    if (!RESIZE_PLAYER) {
      video_params["vod_width"] = '640';
      video_params["vod_height"] = '480';
    } else {
      video_params["vod_width"] = vod_width;
      video_params["vod_height"] = vod_height;
    }
    hideElement('chatLink');
	hideElement('floatLink');
	hashInject('sid',false);
	hashInject('vod',vod_idn);
    //document.getElementById("dyynoVideoPlayer").style.backgroundImage = VIDEO_PLAYER_BG;
    //setTimeout("dyynoStartVODPlayer()",1000);
	setTimeout("dyynoStartPlayer()",1000);
};

function dyynoStartPlayer(){
	if(typeof(DISPLAY_CHAT_WIDGET) != "undefined")
	{	
		if(DISPLAY_CHAT_WIDGET)
		{
			loadChatWindow();
		}
	}

    document.getElementById("dyynoVideoPlayer").style.backgroundImage = "none";
    var the_div = document.getElementById("dyynoplayerdiv");
	the_div.style.width = ""+ video_params["vod_width"] +"px";
	the_div.style.height = ""+ video_params["vod_height"] +"px";
	
	if(dyyno_is_compatible){
	var player_path = "http://" + REQ_HOST + "/assets/players/jwplayer.swf";
	var so = new SWFObject(player_path, 'mpl', video_params['vod_width'], video_params['vod_height'], '9');
	so.addParam('allowfullscreen', 'true');
	so.addParam('allowscriptaccess', 'always');
	so.addParam('wmode','opaque');
	so.addVariable('file', video_params['locate'] + '/' + video_params['content']);
	so.addVariable('bufferlength', '0');
	so.addVariable('streamer', 'rtmp://' + video_params['host'] + '/' + video_params['seek']);
	so.addVariable('autostart', 'true');
	so.write('dyynoplayerdiv');
    }else{
        // dyyno_is_compatible == false ... what happened here?
		alert("Unable to play videos, until the compatibility issues are addressed.");
    }
};

function dyynoInit(){ //UPDATED (MINIMALIST) COMPATIBILITY TEST
	hashParse(); // loads the variables from the URL fragment into HASH_VARS
	var passed = true;
	
	// 1. JAVASCRIPT MUST BE ENABLED
	hideElement("dyynoCompatFailed");
	document.getElementById("compat_js").className="pass"; //JS is enabled.
	
	// 2. MUST HAVE FLASH VERSION 10.0.0 OR BETTER
	if(DetectFlashVer(10, 0, 0) >= 0){
		document.getElementById("compat_flash").className="pass";
	}else{
		document.getElementById("compat_flash").className="fail";
		passed = false;
	}
	
	// 3. COOKIES MUST BE ENABLED  (only needed for chat, really)
	var are_cookies_enabled = (navigator.cookieEnabled) ? true : false;
	if(typeof navigator.cookieEnabled == "undefined" && !are_cookies_enabled){
		// fallback for gimpy browsers...
		document.cookie = "testcookie";
		are_cookies_enabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
	}
	if(are_cookies_enabled){
			document.getElementById("compat_cookies").className="pass";
	}else{
		document.getElementById("compat_cookies").className="fail";
		passed = false;
	}
	
	// ALL REQUIREMENTS MET?
	if(passed){
		document.getElementById('dyynoplayerdiv').innerHTML = vid_message;
		dyyno_is_compatible = true;
	}else{
		dyyno_is_compatible = false;
		showElement("dyynoCompatFailed");
	}
	
	// get the video list and make thumbnails
	dyynoGetVideos();
};

function getConnectionType(){
    /*  IE doesn't use the same XMLHTTP object as other browsers,
        we have to identify which XMLHTTP object is valid for this 
        browser before we start using it 
    */
    var my_connection;
    try{
        //Firefox, Opera, Safari
        my_connection = new XMLHttpRequest();
    }
    catch(e){
        //MSIE
        try{
              my_connection = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e){
              try{
                my_connection = new ActiveXObject("Microsoft.XMLHTTP");
             }
              catch(e){
                alert("No AJAX Support")
                return false;
              }
        }
    }
    return my_connection;
};

function dyynoGetVideos(){
    /* this sets up the connection */
    var my_connection = getConnectionType();
    my_connection.onreadystatechange = function(){
        var found_active_session = false;
		var real_use_dyyno_player = ((USE_DYYNO_PLAYER && HASH_VARS['dyynoplayer'] != '0') || HASH_VARS['dyynoplayer'] == '1');
        if(my_connection.readyState == 4){ 
            //dump the XML to the handler function
            var the_videos;
            the_videos = my_connection.responseXML.documentElement;
            
            //handle the live videos
            var current_live_videos = [];
            var the_live_videos = the_videos.getElementsByTagName("live_video");
            for(i=0; i < the_live_videos.length; i++){
                var this_video = the_live_videos[i];
                if(!this_video.tagName){continue;} //whitespace check
                //var vid_wowza         = this_video.getAttribute('wowza_url');
                var vid_host        = this_video.getAttribute('host');
                var vid_cport        = this_video.getAttribute('cport');
                var vid_desc        = this_video.getAttribute('desc');
                var vid_sid            = this_video.getAttribute('sid');
                var vid_wowza_url = this_video.getAttribute('wowza_url');
                var vid_s_time        = this_video.getAttribute('s_time');
                var vid_duration    = this_video.getAttribute('duration');
                var vid_pub_date    = this_video.getAttribute('pub_date');
                var vid_thumb        = this_video.getAttribute('thumb');
                var vid_idn            = this_video.getAttribute('idn');
                var vid_title        = this_video.getAttribute('title');
                if(typeof(window.DEFAULT_ADZONE) === undefined){
					var vid_adzone         = "";
				}else{
					var vid_adzone         = window.DEFAULT_ADZONE;
				}
                var vid_id            = 'dyynoLiveVideo_'+vid_sid;
                if (vid_sid == active_session_id)
                  found_active_session = true;
                if(navigator.userAgent.toLowerCase().indexOf('iphone') != -1)
					var vid_onclick = (vid_wowza_url) ? 'document.location=\'http'+vid_wowza_url.substr(4)+'/playlist.m3u8\'' : '';
				else if(real_use_dyyno_player)
					var vid_onclick = 'dyynoStartPlayer2(\'live\', \''+vid_sid+'\',\'100%\',\'100%\')';
                else
                  var vid_onclick = 'dyynoDoVideo(\''+vid_host+'\',\''+vid_cport+'\',\''+vid_sid+'\',\''+vid_wowza_url+'\',\''+vid_adzone+'\')';
                if(vid_sid > ""){ //Firefox counts the space between nodes as nodes
                    //check if this video is in the videos_live array and add it if it to the page and the array if it isn't
                    current_live_videos.push(vid_id);
                    var video_exists = videos_live.indexOf(vid_id);
                    if(video_exists == -1){  //this video is not in the array
                        //add the video to the videos_live array
                        videos_live.push(vid_id);
                        //add the video to the page
                        var live_item  = '<div id="'+vid_id+'" class="dyynoVideoThumbnail_up" onmouseover="this.className=\'dyynoVideoThumbnail_over\'" onmouseout="this.className=\'dyynoVideoThumbnail_up\'" onclick="' + vid_onclick + ';showPLmemDiv(0)">';
                            live_item += '  <img src="'+vid_thumb+'" class="thumbImg"/>';
                            live_item += '  <div class="vidInfo"><h4 style="margin:0px;padding:0px;font-size:11px;">'+unescape(vid_title)+'</h4>';
                            live_item += '    <p>Started: '+formaDate(vid_s_time)+'</p>';
                            live_item += '  </div>';
                            live_item += '  <div class="clearFloats"></div>';
                            live_item += '</div>';
                        document.getElementById("dyynoLiveVideos").innerHTML += live_item;
                    }
                }
				if(initial_req_checked == false){
					if(vid_sid == HASH_VARS['sid']){
						//play this one
						if (real_use_dyyno_player)
							dyynoStartPlayer2('live', vid_sid, '100%', '100%');
						else
							dyynoDoVideo(vid_host,vid_cport,vid_sid,vid_wowza_url,vid_adzone);
						initial_req_checked = true;
					}
				}
            }
            
            //cleanup stale LIVE videos
            var live_div = document.getElementById("dyynoLiveVideos");
            var page_live_videos = [];
            //var vid_cnt = 0;
            for(var i=0; i < live_div.childNodes.length; i++){
                var this_node = live_div.childNodes[i];
                if(!this_node.tagName){continue;} //whitespace
                if(this_node.tagName.toLowerCase().match('div')){
                    var div_id = this_node.getAttribute('id');
                    var is_current = current_live_videos.indexOf(div_id);
                    if(is_current == -1){
                        //this video needs to go
                        removeElement(div_id); //removes the div from the page
                        videos_live.splice(videos_live.indexOf(div_id),1); //removes the div_id from the reference array
                    }
                }
            }
            if(current_live_videos.length > 0){
                live_div.style.display = 'block';
                document.getElementById('dyyno_noLiveVideos').style.display = 'none';
            }else{
                live_div.style.display = 'none';
                document.getElementById('dyyno_noLiveVideos').style.display = 'block';
            }
            
            //handle the SR videos
            var current_scheduled_videos = [];
            var the_scheduled_videos = the_videos.getElementsByTagName("sr_video");
            for(i=0; i < the_scheduled_videos.length; i++){
                var this_video = the_scheduled_videos[i];
                
                if(!this_video.tagName){continue;} //whitespace check
                //var vid_wowza         = this_video.getAttribute('wowza_url');
                var vid_host        = this_video.getAttribute('host');
                var vid_cport        = this_video.getAttribute('cport');
                var vid_title        = this_video.getAttribute('title');
                var vid_desc        = this_video.getAttribute('desc');
                var vid_sid            = this_video.getAttribute('sid');
                var vid_wowza_url = this_video.getAttribute('wowza_url');
                var vid_s_time        = this_video.getAttribute('s_time');
                var vid_duration    = this_video.getAttribute('duration');
                var vid_pub_date    = this_video.getAttribute('pub_date');
                var vid_thumb        = this_video.getAttribute('thumb');
                var vid_idn            = this_video.getAttribute('idn');
				var vid_type            = this_video.getAttribute('type');
                if(typeof(window.DEFAULT_ADZONE) === undefined){
					var vid_adzone         = "";
				}else{
					var vid_adzone         = window.DEFAULT_ADZONE;
				}
                var vid_thumbnail     = REG_URL + "/auth/dpc/image_display.php?id="+vid_idn;
                var vid_id            = 'dyynoScheduledVideo_'+vid_sid;
                var cd_id            = 'cd_'+vid_sid;
                
                if (vid_sid == active_session_id)
                  found_active_session = true;
                if (navigator.userAgent.toLowerCase().indexOf('iphone') != -1)
                  var vid_onclick = (vid_wowza_url) ? 'document.location=\'http'+vid_wowza_url.substr(4)+'/playlist.m3u8\'' : '';
				else if(real_use_dyyno_player)
					var vid_onclick = 'dyynoStartPlayer2(\'sr\', \''+vid_sid+'\',\'100%\',\'100%\')';
                else
                  var vid_onclick = 'dyynoDoVideo(\''+vid_host+'\',\''+vid_cport+'\',\''+vid_sid+'\',\''+vid_wowza_url+'\',\''+vid_adzone+'\')';

                if(vid_sid > ""){ //Firefox counts the space between nodes as nodes
                    //check if this video is in the videos_live array and add it if it to the page and the array if it isn't
                    current_scheduled_videos.push(vid_id);
                    var video_exists = videos_scheduled.indexOf(vid_id);
                    if(video_exists == -1){ 
                        //this video is not in the array
                        //add the video to the videos_live array
                        videos_scheduled.push(vid_id);
                        //add the video to the page
                        var scheduled_item  = '<div id="'+vid_id+'" class="dyynoVideoThumbnail_up" onmouseover="this.className=\'dyynoVideoThumbnail_over\'" onmouseout="this.className=\'dyynoVideoThumbnail_up\'" onclick="' + vid_onclick + ';showPLmemDiv(0)">';
                            scheduled_item += '  <img src="'+vid_thumbnail+'" class="thumbImg"/>';
                            scheduled_item += '  <div class="vidInfo"><h4 style="margin:0px;padding:0px;font-size:11px;">'+unescape(vid_title)+'</h4>';
                            scheduled_item += '    <div>Type: '+unescape(vid_type)+'</div>';
                            scheduled_item += '    <div id="'+cd_id+'" >Started: '+formaDate(vid_s_time)+'</div>';
                            scheduled_item += '  </div>';
                            scheduled_item += '  <div class="clearFloats"></div>';
                            scheduled_item += '</div>';
                        document.getElementById("dyynoScheduledVideos").innerHTML += scheduled_item;
                        /*if(vid_start_time > time_now){
                            $('#'+cd_id).countdown({until:vid_start_time,compact:true,layout:'Starting in: {dn} {dl} {hnn}{sep}{mnn}{sep}{snn}',alwaysExpire:true,onExpiry:startCountup});
                        }else{
                            $('#'+cd_id).countdown({since:vid_start_time,compact:true,layout:'Started {dn} {dl} {hnn}{sep}{mnn}{sep}{snn} ago.'});
                        }*/
                    }
					if(initial_req_checked == false){
						if(vid_sid == HASH_VARS['sid']){
							//play this one
							if (real_use_dyyno_player)
								dyynoStartPlayer2('sr', vid_sid, '100%', '100%');
							else
								dyynoDoVideo(vid_host,vid_cport,vid_sid,vid_wowza_url,vid_adzone);
							initial_req_checked = true;
						}
					}
                }
            }
            
            //cleanup stale SR videos
            var sr_div = document.getElementById("dyynoScheduledVideos");
            var page_sr_videos = [];
            //var vid_cnt = 0;
            for(var i=0; i < sr_div.childNodes.length; i++){
                var this_node = sr_div.childNodes[i];
                if(!this_node.tagName){continue;} //whitespace
                if(this_node.tagName.toLowerCase().match('div')){
                    var div_id = this_node.getAttribute('id');
                    var is_current = current_scheduled_videos.indexOf(div_id);
                    if(is_current == -1){
                        //this video needs to go
                        removeElement(div_id); //removes the div from the page
                        videos_scheduled.splice(videos_scheduled.indexOf(div_id),1); //removes the div_id from the reference array
                    }
                }
            }
            if(current_scheduled_videos.length > 0){
                sr_div.style.display = 'block';
                document.getElementById('dyyno_noScheduledVideos').style.display = 'none';
            }else{
                sr_div.style.display = 'none';
                document.getElementById('dyyno_noScheduledVideos').style.display = 'block';
            }
            
            //handle the VOD videos
            var current_vod_videos = [];
            var the_vod_videos = the_videos.getElementsByTagName("vod_video");
            var vod_div = document.getElementById("dyynoVideosOnDemand");
            
            if (Dyyno == null) {
                for(i=0; i < the_vod_videos.length; i++){
                    var this_video = the_vod_videos[i];
                    /*
                        THE ATTRIBUTES OF A VOD VIDEO:
                        title            user editable data
                        file            unique filename
                        res_x            height
                        rex_y            width
                    */
                    if(!this_video.tagName){continue;} //whitespace check
                    var vid_title         = this_video.getAttribute('title');
                    var vid_file         = this_video.getAttribute('file');
                    var vid_res_x         = this_video.getAttribute('res_x');
                    var vid_res_y         = this_video.getAttribute('res_y');
                    var vid_idn         = this_video.getAttribute('idn');
                    var thumb_filename_arr = vid_file.split('.');
					var thumb_filename = thumb_filename_arr[0] + '.jpg';
					//var vid_thumbnail     = THUMBNAIL_SERVER.replace(/%1\$s/, vid_idn).replace(/%2\$s/, THIS_CHANNEL_NAME).replace(/%3\$s/, vid_file.replace(/\.mp4$/, '.jpg'));
					var vid_thumbnail     = THUMBNAIL_SERVER.replace(/%1\$s/, vid_idn).replace(/%2\$s/, THIS_CHANNEL_NAME).replace(/%3\$s/, thumb_filename);
                    
					var vid_id            = 'dyynoVideoOnDemand_' + vid_idn;
                    var vid_view_count    = this_video.getAttribute('view_count');
                    var vid_pub			  = this_video.getAttribute('pub');
                    var vid_category      = this_video.getAttribute('category');
                    
                    if(real_use_dyyno_player)
                        var vid_onclick = 'dyynoStartPlayer2(\'vod\', \''+vid_idn+'\','+vid_res_x+','+vid_res_y+');showPLmemDiv(0);';
                    else
                        var vid_onclick = 'dyynoDoVOD(\''+vid_file+'\',\''+vid_res_x+'\',\''+vid_res_y+'\',\''+vid_idn+'\');showPLmemDiv(0);';
                    
                    if(vid_idn > "" && vid_pub=='1'){ //Firefox counts the space between nodes as nodes
                        //check if this video is in the videos_live array and add it if it to the page and the array if it isn't
                        current_vod_videos.push(vid_id);
                        var video_exists = videos_vod.indexOf(vid_id);
                        if(video_exists == -1){ //this video is not in the array
                            //add the video to the videos_live array
                            videos_vod.push(vid_id);
                            //add the video to the page
                            var vod_item  = '<div id="'+vid_id+'" class="dyynoVideoThumbnail_up"  onmouseover="this.className=\'dyynoVideoThumbnail_over\'" onmouseout="this.className=\'dyynoVideoThumbnail_up\'" onclick="'+vid_onclick+'">';
                                vod_item += '  <img src="'+vid_thumbnail+'" class="thumbImg" />';
                                vod_item += '  <div class="vidInfo"><h4 style="margin:0px;padding:0px;font-size:11px;">'+unescape(vid_title)+'</h4>';
                                //vod_item += '    <p><span>Category:</span>'+vid_category+'</p>';
                                if (vid_res_x != vid_res_y != 0) {
                                     vod_item += '    <p><span>Size:</span>'+vid_res_x+' x '+vid_res_y+'</p>';
                                }
                                if(vid_view_count > 0){
                                vod_item += '    <p><span>Views:</span>'+vid_view_count+'</p>';
                                }
                                vod_item += '  </div>';
                                vod_item += '  <div class="clearFloats"></div>';
                                vod_item += '</div>';
                            document.getElementById("dyynoVideosOnDemand").innerHTML += vod_item;
                        }
                        if (initial_req_checked == false){
                            if(vid_idn == HASH_VARS['vod']){
                                // this is the one to play
                                if (real_use_dyyno_player)
                                    dyynoStartPlayer2('vod', vid_idn, vid_res_x, vid_res_y);
                                else
                                    dyynoDoVOD(vid_file,vid_res_x,vid_res_y,vid_idn);
                                initial_req_checked = true;
                            }
                        }
                    }
                }
                
                //cleanup stale VOD videos
                var page_vod_videos = [];
                //var vid_cnt = 0;
                for(var i=0; i < vod_div.childNodes.length; i++){
                    var this_node = vod_div.childNodes[i];
                    if(!this_node.tagName){continue;} //whitespace
                    if(this_node.tagName.toLowerCase().match('div')){
                        var div_id = this_node.getAttribute('id');
                        var is_current = current_vod_videos.indexOf(div_id);
                        if(is_current == -1){
                            //this video needs to go
                            removeElement(div_id); //removes the div from the page
                            videos_vod.splice(videos_vod.indexOf(div_id),1); //removes the div_id from the reference array
                        }
                    }
                }
            }
            
            // Change headers
            if(the_vod_videos.length > 0){
                vod_div.style.display = 'block';
                document.getElementById('dyyno_noVideosOnDemand').style.display = 'none';
            }else{
                vod_div.style.display = 'none';
                document.getElementById('dyyno_noVideosOnDemand').style.display = 'block';
            }
            
            //kill player if session is no longer valid
            if (active_session_id != null && !found_active_session) {
                --wowza_session_ended_count;
                if (wowza_session_ended_count == 0) {
                    active_session_id = null;
                    document.getElementById("dyynoFlashPlayer").sessionStopped();
                }
            } else {
                wowza_session_ended_count = 2;
            }
			
			// If it hasn't been found by now, don't try again
			initial_req_checked = true;
            
            // Trigger the new Dyyno API
            if (Dyyno) {
                Dyyno.processVideos(my_connection.responseXML);
                Dyyno.init_done();
            }
        }
    }
    my_connection.open("GET", CHANNEL_FEED_URL, true); 
    my_connection.send(null);
	if((!isset(HASH_VARS['vod'])) && (!isset(HASH_VARS['sid']))){
		initial_req_checked = true;
	}
    //do this again in a few seconds
    //setTimeout("dyynoGetVideos()",15000);
};

function tweetThis() {
	var tweet_text = "Watching " + THIS_CHANNEL_NAME.capitalize() + " on Dyyno: " + window.location.href;
	window.open('http://twitter.com/home?status='+encodeURIComponent(tweet_text),'tweeter','toolbar=0,status=0,width=626,height=436');
};

function shareOnMyspace(){
	window.open('http://www.myspace.com/Modules/PostTo/Pages/?u='+encodeURIComponent(document.location.toString()),'ptm','height=450,width=440').focus();
};

function emailThis(){
	var href = "mailto:?subject=Watching " + CHANNEL_TITLE + " on Dyyno&body=I thought you might want to see this: " + escape(window.location.href);
	window.open(href,'emailer','toolbar=0,status=0,width=626,height=436');
};

function fbs_click() {
		u=location.href;
		t="Watching Video on Dyyno.com";
		window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
		return false;
	}

//Load the Chat Widget next to the player
function loadChatWindow()
{
	channel_name = THIS_CHANNEL_NAME;
	if($('#chat_frame').length == 0)
	{
		$('#video_chat_row').append('<td id="chat_frame" width="320" height="480" align="center"><iframe src="/chat/fb_twitter_chat/?channel='+channel_name+'&width=320&height=480" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:320px; height:480px;" allowTransparency="true">No Iframe support in your browser</iframe></td>');
	}					
}



