/*******************************************
 *
 * Secure Live Chat API - by Naughty America
 * Dependencies: jQuery
 *
 *******************************************/

// Every function (and feed) uses these common parameters
var player_dir = "http://content.naughtyamerica.com/naughty/public/live_chat/swf";
var flashvars = {};
flashvars.type = "http";
flashvars.bufferlength = "0";
flashvars.controlbar = "none";
flashvars.autostart = "1";
flashvars.stretching = "exactfit";
flashvars.mute = false;
flashvars.width = "450";
flashvars.height = "300";
flashvars.author = "Naughty America";
flashvars.title = "Naughty America Live Chat";
flashvars.description = "Live Chat is brought to you by Naughty America!";

var params = { allowfullscreen: "false", allowScriptAccess:"always", wmode:"transparent" };
var attributes 	= { id:"live_player", name:"live_player" };
var reserved_screen_names = ['admin', 'administrator', 'na live'];
var interval_ids = { get_preview: null, check_preview: null, stop_preview: null };

/******* QVC *********/
var free_qvc_shows = ['live_with_lauren', 'live_naughty_girl_talk', 'naughty_americans'];

/* Name to room conversions */
var nameToRoom = [];
nameToRoom['lonely_student'] = 12;
nameToRoom['live_naughty_student'] = 12;
nameToRoom['naughty_after_class'] = 13;
nameToRoom['live_naughty_teacher'] = 13;
nameToRoom['gym_cam'] = 14;
nameToRoom['live_gym_cam'] = 14;
nameToRoom['gmna'] = 15;
nameToRoom['gmna_live'] = 15;
nameToRoom['live_with_lauren'] = 15;
nameToRoom['live_naughty_secretary'] = 16;
nameToRoom['live_naughty_milf'] = 17;
nameToRoom['office_girl'] = 18;
nameToRoom['office_girl_1'] = 18;
nameToRoom['office_girl_2'] = 18;
nameToRoom['office_girl_3'] = 18;
nameToRoom['live_party_girls'] = 19;
nameToRoom['live_naughty_nurse'] = 20;
nameToRoom['live_naughty_mystery'] = 21;
nameToRoom['tester'] = 22;
nameToRoom['live_naughty_president'] = 23;

var roomName = 'gmna';
var player = null;

// For limiting trailers on article pages
var on_preview_page = false;
var eligible_preview_page = false;
var join_link = '';


// If Firebug isn't on, then just throw away the debug messages
if(window.console == undefined) {
    console = new Object;
    console.log = function(message) {  }
}

// This function is called when the post roll event is triggered
function show_post_roll() {
	$('.post-roll-container').removeAttr("style");
    console.log('Post roll event triggered!');	
}

// Error reporting function for the NA Player
function logIt(string){
     console.log('logIt: ' + string);
     
     // TODO: Make this into an event/call directly from the player instead of a string parse.
     if(string == 'Showing the image/video') {
    	 	show_post_roll();
     }
}

/*
 * When a player is ready, it calls this function
 */
function playerReady(thePlayer) {
    player = window.document[thePlayer.id];
    /*
    player.addModelListener('ERROR','playerError');
    player.addModelListener('STATE','playerState');
    player.addModelListener('LOAD','playerState');
    player.addEventListener('jwplayerPlayerState','playerState');
    
    player.addModelListener('LOAD','playerState');
    player.addEventListener('jwplayerPlayerState','playerState');
    player.addEventListener('jwplayerMediaError','playerError');
    */
}

function playerError(obj) {
    $('#debug_message_error').text('Error: ' + obj.message);
    console.log('Error: ' + obj.message);
}


var first_load = false;
function playerState(obj) {
    $('#debug_message_state').text('Changed: ' + obj.oldstate + ' => ' + obj.newstate);
    /*
     if(player.getConfig().stretching != 'exactfit') {
        debug_print('Incorrect stretching: ' + player.getConfig().stretching);
    }


    if(obj == 'IDLE') {
        player.sendEvent('PLAY', 'true')
    }*/
}

function in_array(needle, haystack) {
    var found = false, key;
     for (key in haystack) {
        if (haystack[key] == needle) {
            found = true;
            break;
        }
    }

    return found;
}

// Place the HTML5 player code into the div element specified in the options
function embed_html5_player(video_src, options) {
    console.log('Embedding HTML5 player into: ' + options.div_element);
    $('#' + options.div_element).html('<video src="' + video_src + '" width="' + options.width + '" height="' + options.height + '" autoplay="autoplay" controls="controls" poster="' + options.image + '" prelead="meta"></video>');
}

function embed_preview_player(options) {

    var player_dir = "http://content.naughtyamerica.com/naughty/public/live_chat/preview_player/";
    // var player_swf = 'player-starttime.swf'; // Old player for use on BitGravity
    
    // Limelight handles MP4s and FLVs differently, so different starttime variables must be used
    var player_swf = 'player-limelight.swf';
    if(options.extension) {
    		player_swf = (options.extension == 'flv') ? 'player-limelight-flv.swf' : 'player-limelight.swf';
    }
    
    var attributes = { 'id': 'playerID', 'name': 'playerID' };
    var params = { wmode: 'transparent', 'allowscriptaccess': 'always' };


	attributes.id = options.div_element;
	attributes.name = options.div_element;

    if(options.allowfullscreen) {
        params.allowfullscreen = "true";
    }

    // Newest player for live archives "10.1.53"
    if(!options.flash_version) {
        options.flash_version = "10.0.0";
    }

    // URL Encode first!
    options.file = options.file.replace('&', '%26');
    options.file = options.file.replace('?', '%3F');
    options.file = options.file.replace('=', '%3D');

    video_flashvars = { id: 'playerID'};
    video_flashvars.file = options.file;

    // Set a default title and description
    video_flashvars.title = (!options.title) ? 'Naughty America' : options.title;
    video_flashvars.description = (!options.description) ? 'Naughty America - Nobody Does It Better!' : options.description;

    // Set the streamer to either the file itself (when calling without a playlist) or the stream designated.
    if(options.playlist) {
        video_flashvars.playlistfile = options.file;
        video_flashvars.streamer = options.stream;
    }
    else {
        video_flashvars.streamer = options.file;
    }

    	// Google Analytics plugin: DISABLED by DS2 on 10-18-10
    video_flashvars.plugins = '';
    
    // This is the plugin that loads the 2 buttons: << >> for skipping around
    if(!options.disable_skipping) {
        video_flashvars.plugins += player_dir + 'ForwardBack.swf';
    }

    // This is the plugin that has a sliding window with a picture and text when the 'i' is pressed
    if(options.description_window) {
       video_flashvars.plugins += ',' + player_dir + 'DescriptionWindow.swf';
    }



    // This is the embed plugin, denoted by the <>
    if(options.embed_window) {
       video_flashvars.plugins += ',' + player_dir + 'EmbedWindow.swf';
    }

    // This is the plugin that loads the small preview images
    if(options.screenshots_available) {
        video_flashvars.plugins += ',' + player_dir + 'Preview.swf';
    }

    // This is the variable that controls whether the Description Window pops up when loaded
    if(options['DescriptionWindow.auto']) {
       video_flashvars['DescriptionWindow.auto'] = options['DescriptionWindow.auto'];
    }

    // The post-roll plugin
    if(options.postroll) {
        video_flashvars.plugins += ',' + player_dir + 'PostRoll.swf';
    }

    // These 2 lines are for handling video scrubbing
    video_flashvars.provider = "http";
    video_flashvars.type = "bitgravity";


    video_flashvars.dock = "false";
    video_flashvars.bufferlength = (!options.bufferlength) ? "5" : options.bufferlength;
    video_flashvars.http = { startparam: "starttime" };
    console.log('Player buffer lenth: ' + video_flashvars.bufferlength);

    // There's a bug with IE6 that causes the video not to play if we use autostart. So, if the user has IE6, don't autostart.
    if(!isIE6) {
    		video_flashvars.autostart = options.autostart;
    		console.log("Autostarting the video!");
    }
    else {
    		video_flashvars.autostart = false;
    		console.log("Using IE6, so we can't autostart.");
    }
    
    video_flashvars.stretching = "exactfit";
    video_flashvars.controlbar = options.controlbar;
    if(options.mute == true || options.mute == 'true') {
        video_flashvars.volume = 0;
    }
    video_flashvars.width = options.width;
    video_flashvars.height = options.height;
    video_flashvars.image = (options.image && options.image != '') ? options.image : 'http://content.naughtyamerica.com/naughty/public/live_chat/live_load.jpg';

    //console.log("Plugins: " + video_flashvars.plugins + "\nPlayer: " + player_dir + player_swf);
	swfobject.embedSWF(player_dir + player_swf, options.div_element, video_flashvars.width, video_flashvars.height, options.flash_version, "http://bitcast-b.bitgravity.com/player/expressInstall.swf", video_flashvars, params, attributes);
}

function embed_advection_player(options) {
    var player_dir = "http://wcs.mp.advection.net/advection/_dld/player/";
    var attributes = {};
    var params = { wmode: 'transparent'};
	attributes.id = options.div_element;
	attributes.name = options.div_element;

    if(options.allowfullscreen) {
        params.allowfullscreen = "true";
    }

    // URL Encode first!
    options.file = options.file.replace('&', '%26');
    options.file = options.file.replace('?', '%3F');
    options.file = options.file.replace('=', '%3D');
    
    video_flashvars = {};
    video_flashvars.file = options.file;
    
    // Set the streamer to either the file itself (when calling without a playlist) or the stream designated.
    if(options.playlist) {
        video_flashvars.playlistfile = options.file;
        video_flashvars.streamer = options.stream;
    }
    else {
        video_flashvars.streamer = options.streamer;
    }   
    
//  video_flashvars.provider = "http";
    video_flashvars.type = "rtmp";
    video_flashvars.dock = "false";
    video_flashvars.bufferlength = "5";
//  video_flashvars.http = { startparam: "starttime" };
    video_flashvars.autostart = options.autostart;
    video_flashvars.stretching = "exactfit";
    video_flashvars.controlbar = options.controlbar;
    if(options.mute == true || options.mute == 'true') {
        video_flashvars.volume = 0;
    }
    video_flashvars.width = options.width;
    video_flashvars.height = options.height;
    //video_flashvars.image = (options.image != '') ? options.image : 'http://content.naughtyamerica.com/naughty/public/live_chat/live_load.jpg';
    video_flashvars.image = 'http://content.naughtyamerica.com/naughty/public/live_chat/live_load.jpg';

    
	swfobject.embedSWF(player_dir + 'player_4_7.swf', options.div_element, video_flashvars.width, video_flashvars.height, "10.0.0", "http://bitcast-b.bitgravity.com/player/expressInstall.swf", video_flashvars, params, attributes);
}




/* Naming Pattern: gmna_update_{day of the week}_flash_1k.flv
 * {day of the week} = { monday - friday, weekend }
 */
function get_daily_gmna_video_name() {

    // Since we have a new commercial, ALWAYS show it
    //return 'Commercial 4-3.flv';
    return 'Commercial 16-9_flash_1k.flv';

    var d = NADate();
    var weekday = new Array(7);
    weekday[0] = "weekend";
    weekday[1] = "monday";
    weekday[2] = "tuesday";
    weekday[3] = "wednesday";
    weekday[4] = "thursday";
    weekday[5] = "friday";
    weekday[6] = "weekend";
    return 'gmna_update_' + weekday[d.getUTCDay()] +  '_flash_1k.flv';
}

function loadVideo(video, viewsLeft) {
    current_video = video;

    $('#top_cam').html('<a href="#"><img src="/images/trailer_limiter/' + viewsLeft + '_left.jpg" width="604" height="455" /></a>');
    //player.sendEvent('LOAD', video);
}

function scrollSchedule(direction) {

    if(direction == 'right') {
        $('#live_schedule').animate({scrollLeft: '+=221px'}, 1000, 'swing');
    }
    else {
        $('#live_schedule').animate({scrollLeft: '-=221px'}, 1000, 'swing');
    }
}

// Usage: scrollArea('#members_favorites','right', 125);
function scrollArea(id, direction, amount) {

    if(direction == 'right') {
        $(id).animate({scrollLeft: '+=' + amount + 'px'}, 1000, 'swing');
    }
    else {
        $(id).animate({scrollLeft: '-=' + amount + 'px'}, 1000, 'swing');
    }
}

// Insert a custom card in case the show is not live
function insertCard() {

	var card = "http://content.naughtyamerica.com/naughty/public/live_chat/live_gmna.jpg";
	document.getElementById('top_cam').innerHTML('<img title="Naughty America Live" src="' + card + '">');
}

/********************************
 *
 * Preview Timeout Functions
 *
 ********************************/

// Make sure preview_cookie and join_link are set globally in the page, the functions below require them
// preview_cookie = the template name e.g. 'chat_gym_cam'
// join_link = the cms generated join link


function getPreviewData(the_cam_function, id_or_class, force_timeout) {

  // Set default identifier
  if ( id_or_class == null || id_or_class == "" )
    id_or_class = '#top_cam';

  // Reset all intervals!
  clear_all_timers();

  // Make ajax request for data
  $.get("/index.php", { m: "chat", s: "preview_ajax", name: preview_cookie }, function(data) {

    if ( data.match(/ERROR/) ) {
      if ( typeof the_cam_function == "function" )
        the_cam_function();
        // Call for a cease & desist order after the appropriate amount of time
        if(!interval_ids.stop_preview) {
            interval_ids.stop_preview = setInterval(function() { stopLivePreview(id_or_class, null, 'Error!'); }, 60000);
        }
    } else {
      var return_data =  new Array();
      var temp = data.split("|");
      var x;
      for ( x in temp ) {
        //alert(temp[x]);
        var temp2 = temp[x].split("=");
        return_data[temp2[0]] = temp2[1];
        //alert(return_data[temp2[0]]);
      }
      checkPreview(return_data, the_cam_function, id_or_class, force_timeout);
    }
  } );
}



function checkPreview(data_array, the_cam_function, id_or_class, force_timeout) {

  clearInterval(interval_ids.check_preview);
  interval_ids.check_preview = null;

  // Set default identifier
  if ( id_or_class == null || id_or_class == "" )
    id_or_class = '#top_cam';



  var preview_length = data_array['timeout']*1000;

  // Force a timeout if desired
  if(force_timeout) {
      preview_length = force_timeout;
  }


  if ( preview_length == null || preview_length == '0' || preview_length == 0 )
  	preview_length = 60000; // Backup timeout

  //alert("Preview Length: "+preview_length);
  one_day = 60*60*24*1000;

  // Check to see if the current feed is "live"
  var live = ( data_array['status'] == "on" ) ? true : false;

  if ( !live && !force_timeout ) { // Let the stream load but check again in 60 seconds
    //debug_print("Not live!");
    if ( typeof the_cam_function == "function" )
      the_cam_function();

    if(!interval_ids.get_preview) {
        interval_ids.get_preview = setInterval(function() { getPreviewData('', id_or_class); }, 60000);
    }
    return;
  }

  //debug_print('We are live!');

  // If so check/set cookie and timeout
  var regex = new RegExp(preview_cookie+'=([^;]+)');
  var match = regex.exec(document.cookie);
  //alert(match);
  var mytime = new Date;
  var unixtime = mytime.getTime();

  //alert("unixtime: "+unixtime);
  if ( match != null && match[1] != null ) { // Cookie is set
    var thentime = parseInt(match[1]);
    //alert("thentime: "+thentime);
    /*
    var then_date = new Date();
    then_date.setTime(thentime);
    var now_date = new Date();
    alert("Then: "+then_date.toGMTString()+" Now: "+now_date.toGMTString());
    */

    if ( thentime > unixtime ) { // Cookie is not 24 hrs old, reject
      //alert('thentime: '+thentime+' > unixtime: '+unixtime);
      stopLivePreview(id_or_class, data_array['image_url'], 'Old cookie - ' + data_array['name']);
    } else { // Reset cookie and allow
        //
      //alert('thentime: '+thentime+' < unixtime: '+unixtime);
      if ( typeof the_cam_function == "function" ) {
        the_cam_function();
      }

      // Call for a cease & desist order after the appropriate amount of time
      if(!interval_ids.stop_preview) {
        interval_ids.stop_preview = setInterval(function() { stopLivePreview(id_or_class, data_array['image_url'], 'Reset cookie' + current_channel); }, preview_length);
      }
      //setTimeout("stopLivePreview('" + id_or_class + "', '"+data_array['image_url']+"')", preview_length);
      setPreviewCookie(preview_cookie, unixtime);
    }

  } else { // Cookie not set, allow
    //alert('Initial Cookie Set');
    if ( typeof the_cam_function == "function" )
      the_cam_function();

    // Call for a cease & desist order after the appropriate amount of time
    if(!interval_ids.stop_preview) {

        interval_ids.stop_preview = setInterval(function() { stopLivePreview(id_or_class, data_array['image_url'], 'New cookie: ' + data_array['name']); }, preview_length);

    }
    //setTimeout("stopLivePreview('" + id_or_class + "', '"+data_array['image_url']+"')", preview_length);
    setPreviewCookie(preview_cookie, unixtime);
  }
}

function setPreviewCookie(name, now) {
  var mydate = new Date;
  mydate.setTime(now+one_day+one_day);
  cookie_val = name+'='+(now+one_day)+'; expires='+mydate.toGMTString()+'; path=/';
  //alert('Set Cookie: '+cookie_val);
  document.cookie = cookie_val;
}

function clear_all_timers() {
  clearInterval(interval_ids.check_preview);
  clearInterval(interval_ids.get_preview);
  clearInterval(interval_ids.stop_preview);
  interval_ids.get_preview = null;
  interval_ids.check_preview = null;
  interval_ids.stop_preview = null;
}

function stopLivePreview(the_div,the_img, message) {
  clear_all_timers();
  player = null;

  if(!message) { message = '-'; }
  debug_print('Stopped: ' + message);

  // Stop checking if the channel is live or not
  clearInterval(interval_id);

  //alert("stopLivePreview called");
  if ( the_img == null || the_img == "" )
    the_img = "http://content.naughtyamerica.com/naughty/public/live_chat/live_timeout_default_card.jpg";
  $(the_div).html("<div id='top_stream'><a href='"+join_link+"' title='Join Naughty America Live'><img src='"+the_img+"' alt='Live Video Shows at Naughty America Live Join Here!' /></a></div>");

  // Don't forget the bottom cam!
  if($('#bottom_stream') != null) {
     $('#bottom_stream').html("<div id='bottom_stream'><a href='"+join_link+"' title='Join Naughty America Live'><img src='"+the_img+"' alt='Live Video Shows at Naughty America Live Join Here!' /></a></div>");
  }
}

function inform_via_button(button_id, message, color, boldness, disabled) {

	if(disabled == null) {
		disabled = "";
	}

	$("#" + button_id).val(message);
	$("#" + button_id).css("color", color);
	$("#" + button_id).css("font-weight", boldness);
	$("#" + button_id).attr("disabled",disabled);
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

/**************** Screen name management via jQuery ****************/
function sleep(delay)
{
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}

jQuery(document).ready(function($) {

    $("#send_email").click(function() {

        // The email is trimmed of whitespace, converted to lowercase, then validated as a correctly formatted email address
        var email = $("#email").val().trim().toLowerCase().match(/[a-z0-9\!\#\$\%\&\'\*\+\-\/\=\?\^\_\`\{\|\}\~]+@[a-z0-9\-\.]+\.[a-z]{2,4}/i);
        if(email != null) {
            $("#send_email").attr("disabled","disabled");
            $("#send_email").val("Sending...");
            $.get('http://tour.naughtyamerica.com/?m=live&email=' + email, {}, function(data) {
                    $("#send_email").val('Thank you!');
            });
        }
        else {
            alert('Please type a proper email address before hitting "Send Now".');
        }

    });

    set_live_rollovers();
});

function set_live_rollovers() {
    // TEMP: Until the ffmpeg bug can be straightened out
    return;

    jQuery(".live_show").hover(
      function () {
        var channel = $(this).attr('id');
        $("#top_cam").append("<div class='floating_box'><img class='live_screen_grab' src='http://bitcast-a.v1.sjc1.bitgravity.com/naughty/public/live_chat/images/" + channel + ".jpg'></div>");
      },
      function () {
        $("#top_cam").find(".floating_box").remove();
      }
    );
}

/*******************************************
 *
 * NA TV API - by Naughty America
 * Dependencies: jQuery
 *
 *******************************************/
var channel_check_id = null;

function show_bottom_feed(show) {
    if(show) {
        $('#bottom_cam').slideDown('fast');
    }
    else {
        $('#bottom_cam').slideUp('fast');
    }
}

function show_bottom_section(show) {
    if(show) {
        $('#past_live').slideDown('fast');
    }
    else {
        $('#past_live').slideUp('fast');
    }
}

function update_channels() {

    //console.log("Update Channels called from " + arguments.callee.caller.toString() + ' called from: ' + location.href);
    var url = location.href;
    var show_type;
    if(url.search(/debug_shows/) != -1 && 0) {
        show_type = 'all';
    }
    else {
        show_type = 'active';
    }
    naughty_rpc('Live.get_channel_info', { status: show_type }, function(channels) {

        // Stop all other instances
        if(channel_check_id != null) {
            clearTimeout(channel_check_id);
            channel_check_id = null;
        }

        // Remove all 'live_show' classes from the channel buttons and apply the new ones (if any)
        $('.live_show').removeClass('live_show');
        if(channels) {
            for (var i in channels) {
                if(channels[i]['type'] == 'stream') {
                    debug_print(channels[i]['title'] + ' is LIVE!')
                    //$('#' + channels[i]['name']).addClass('live_show');
                    $('#live_content_available').addClass('live_red');
                    break;
                }
            }
        }
        else {
            $('#live_content_available').removeClass('live_red');
            debug_print('No live shows available.');
        }

        // Disabled since the channel selector is gone
        //set_live_rollovers();
        
        /* Auto-refresh: engaged
        if(channel_check_id == null) {
            channel_check_id = setTimeout(function() { update_channels(); }, 5000);
        }*/
    });

}

// This function will turn the "Live" navigation menu button red if there is a show that is currently live
function update_live_button() {

    var url = location.href;
    var show_type;
    if(url.search(/debug_shows/) != -1 && 0) {
        show_type = 'all';
    }
    else {
        show_type = 'active';
    }
    naughty_rpc('Live.get_channel_info', { status: show_type }, function(channels) {

        // Stop all other instances
        if(channel_check_id != null) {
            clearTimeout(channel_check_id);
            channel_check_id = null;
        }

        // Remove all 'live_show' classes from the channel buttons and apply the new ones (if any)
        if(channels && channels.length > 0) {
            debug_print(channels[0]['title'] + ' is LIVE!')
            $('#live_content_available').addClass('live_red');
        }
        else {
            $('#live_content_available').removeClass('live_red');
            debug_print('No live shows available.');
        }

        // Auto-refresh: engaged
        if(channel_check_id == null) {
            channel_check_id = setTimeout(function() { update_channels(); }, 10000);
        }
    });

}


/**
 * Load the channel, the chatbox, who's on iframe & archived videos
 */
function switch_channel(current_channel, channel_title, screen_name, options, chat_options) {  

    clear_all_timers();

    // Show/Hide the section & bottom feed
    show_bottom_section(live_channels[current_channel].archived == 1);
    show_bottom_feed(false);

    /* Embed preview video if:
     * 1) Preview mode is explicitly asked for
     * 2) An expired member is looking at non-QVC show
     */
    if(options.preview || (options.is_expired && !in_array(current_channel, free_qvc_shows))) {
        preview_cookie = "chat_" + current_channel;
        console.log('Preview mode: enabled');
        getPreviewData( function() { embed_channel(current_channel, options); });

    }
    else {
        console.log('Unlimited viewing: enabled');
        embed_channel(current_channel, options);
    }

    // Embed the chat window
    if(chat_options.preview) {
        if(!options.chat_window_div) {
            options.chat_window_div = 'chat_window_new';
        }

        //$('#chat_window_area').load("/index.php?m=chat&site=" + current_channel + "&mode=solo&nats=" + options.nats + "&template=chat_window");
        console.log("Loaded chat template");
        embed_tour_chat_iframe(options.chat_window_div, screen_name, chat_options);
        //embed_chat_iframe(options.chat_window_div, screen_name, chat_options);
    }
    else {
        embed_member_chat_iframe('chat_window_new', screen_name, chat_options);
    }

    // Highlight the proper channel
    $('.active_show').removeClass('active_show');
    $('#' + current_channel).addClass('active_show');

    // Load Who's On Live iframe & change the label
    $('.show_title').text(channel_title);
    $('#whos_on_live').attr('src', 'http://api.naughtyamerica.com/labs/index.php?m=api&s=online&chat=' + current_channel + '&custom_template=whos_on_live&tracking=members');

    // Change the archived video list
    $('#highlight_vids_area').html('<p class="loading-message"><b>Loading...</b><img align="absmiddle" src="http://content.naughtyamerica.com/naughty/public/live_chat/images/spinner.gif"></p>');
    $('#highlight_vids_area').load('/index.php?m=chat&site=' + current_channel + '&template=scenes_live_archive&mode=solo');
}

/**
 * Embed the chat iframe in the element specified
 * Note: Preview chat boxes are 56 pixels shorter in height than asked for due to the deletion of the typing area.
 */
function embed_tour_chat_iframe(element_id, screen_name, options) {

    var iframe_code = '';
    var chat_window = 'tour_guest';

    if(!options) {
        options = default_chat_window_options;
    }

    if(!options.current_channel) {
        options.current_channel = current_channel;
    }
    
	// Set the brand based on the domain we're being called from
    options.brand = (document.domain.search('tour.suite703.com') != -1) ? 'suite703' : 'naughtyamerica'; 
    
    // Randomize chat name and show no link to change it for Free Live Trial
    if ( screen_name == null || screen_name == '' ) {
        screen_name = 'Tour_' + Math.floor(Math.random()*1000);
    }

    naughty_rpc('Live.get_channel_info', { channel_name: options.current_channel }, function(channel) {
        
        if(channel) {			
			
		    iframe_code = '<iframe style="z-index: 1" id="chatFrame" src="http://tour.' + options.brand + '.com/client/' + chat_window + '.php?room_id=' + channel.chat_room_id + '&screen_name=' + screen_name + '&width=' + options.width + '&height=' + options.height + '&no_header" width="' + options.width + '" height="' + (options.height - 59) + '" frameborder="0" scrolling="no"></iframe>';
		    console.log('Iframe code for ' + document.domain + ': ' + iframe_code);
		    $('#' + element_id).html(iframe_code);
		    //console.log('Embedded tour chat into: ' + element_id + ' = ' + $('#' + element_id).html());
        }
    });
}

// Embed the chat iframe in the element specified
function embed_member_chat_iframe(element_id, screen_name, options) {

    var iframe_code = '';
    var chat_window = 'chat_guest';

    if(!options) {
        options = default_chat_window_options;
    }

    if(!options.current_channel) {
        options.current_channel = current_channel;
    }

    // Dimentions and options for preview chat
    if(options.preview) {
        chat_window = 'tour_guest';
        $("#new_chat_window").css('height', '258px');
        options.height = 258;
        screen_name = 'Tour_' + Math.floor(Math.random()*1000);
    }

    // Randomize chat name and show no link to change it for Free Live Trial
    if ( window.location.hostname.search(/free/) != -1 || screen_name == null || screen_name == '' ) {
            //screen_name = 'Guest_' + Math.floor(Math.random()*1000);
            //iframe_code = '<iframe id="chatFrame" src="/client/' + chat_window + '.php?room=' + current_channel + '&screen_name=' + screen_name + '&width=' + options.width + '&height=' + options.height + '" width="' + options.width + '" height="' + options.height + '" frameborder="0" scrolling="no"></iframe>';

    }
    else {
        iframe_code = '<iframe id="chatFrame" src="/client/' + chat_window + '.php?room=' + options.current_channel + '&screen_name=' + screen_name + '&width=' + options.width + '&height=' + options.height + '" width="' + options.width + '" height="' + options.height + '" frameborder="0" scrolling="no"></iframe>';
    }

    if(!options.preview) {
      iframe_code += '<br/><span class="message"><a title="Live Chat Screen Name Changer" href="/index.php?&m=account&s=settings">Click here</a> to change your chat screen name!</span>';
    }

    if ( screen_name == null || screen_name == '' ) {

        //overlay_popup('bedroom_login');
        console.log("Redirecting to Account settings page");
        top.location.href = '/index.php?&m=account&s=settings';
    }
    else {
        console.log("Embedding iframe code: %s", iframe_code);
        $('#' + element_id).html(iframe_code);
        console.log("Done embedding iframe code.");
    }
}


/*******************************************
 *
 * Live Naughty TV - by Naughty America
 * Dependencies: jQuery
 *
 *******************************************/

// Every function (and feed) uses these common parameters
var polling_interval = 15000;
var interval_id = null;
var player_dir = "http://content.naughtyamerica.com/naughty/public/live_chat/swf";
var params = { allowfullscreen: "false", allowScriptAccess:"always", wmode:"transparent" };
var attributes 	= { id:"live_video_player", name:"live_video_player" };
var reserved_screen_names = new Array('admin', 'administrator', 'na live');
var default_channel_data = { type: "trailer", file: "http://content.naughtyamerica.com/naughty/public/sizzler/vids/livesizzler_flash_1k.flv" };
var video_defaults = { width: "615", height:"410", mute: "false", autostart: "1", image: "http://content.naughtyamerica.com/naughty/public/live_chat/live_load.jpg", controlbar: "none" }
var default_chat_window_options = { width: "450", height:"400", preview: "false" }
var video_flashvars = {};

var current_channel = 'naughty_americans';

video_flashvars.title = "Naughty America Live Video";
video_flashvars.description = "Live Chat is brought to you by Naughty America!";
video_flashvars.author = "Naughty America";

var current_segment = { name: '', file: '', type: '', top_stream: '', bottom_stream: ''};

// Embed the chat iframe in the element specified
function embed_chat_iframe(element_id, screen_name, options) {

    var iframe_code = '';
    var chat_window = 'chat_guest';

    if(!options) {
        options = default_chat_window_options;
    }

    // Dimentions and options for preview chat
    if(options.preview) {
        chat_window = 'tour_guest';
        $("#new_chat_window").css('height', '258px');
        options.height = 258;
        screen_name = 'Tour_' + Math.floor(Math.random()*1000);
    }

    // Randomize chat name and show no link to change it for Free Live Trial
    if ( window.location.hostname.search(/free/) != -1 || screen_name == null || screen_name == '' ) {
            screen_name = 'Guest_' + Math.floor(Math.random()*1000);
            iframe_code = '<iframe id="chatFrame" src="/client/' + chat_window + '.php?room=' + current_channel + '&screen_name=' + screen_name + '&width=' + options.width + '&height=' + options.height + '" width="' + options.width + '" height="' + options.height + '" frameborder="0" scrolling="no"></iframe>';
    }
    else {
        iframe_code = '<iframe id="chatFrame" src="/client/' + chat_window + '.php?room=' + current_channel + '&screen_name=' + screen_name + '&width=' + options.width + '&height=' + options.height + '" width="' + options.width + '" height="' + options.height + '" frameborder="0" scrolling="no"></iframe>';
    }

    if(!options.preview) {
      iframe_code += '<br/><span class="message"><a title="Live Chat Screen Name Changer" href="/index.php?&m=account&s=settings">Click here</a> to change your chat screen name!</span>';
    }

    $('#' + element_id).html(iframe_code);
    console.log('%% Embedded chat into (' + element_id + '): ' + $('#' + element_id).html());
}

function embed_stream(div_element, stream, options) {

    var player_swf = '/player-5.0-streamer.swf',
        streamer = stream,
        file_stream = stream;

	attributes.name = attributes.id = div_element;
    options = check_video_defaults(options);

    if(options.allowfullscreen) {
        params.allowfullscreen = "true";
    }

    // RTMP Streams with Advection must be handled in a special way
    if(stream.search(/rtmp:/) != -1) {
        player_swf = '/player-advection.swf';
        streamer = stream.substring(0, stream.lastIndexOf("/")),
        file_stream = stream.substring(stream.lastIndexOf("/") + 1);
        video_flashvars.provider = "";
    }
    // BitGravity streams
    else {
        video_flashvars.provider = "http";
        //video_flashvars.type = "bitgravity"; /* This type is required for players older than 5.0 */
        video_flashvars.bufferlength = "0";
        video_flashvars.http = { startparam: "starttime" };
    }
    
    // URL Encode
    streamer = streamer.replace('&', '%26');
    streamer = streamer.replace('?', '%3F');
    streamer = streamer.replace('=', '%3D');


    video_flashvars.file = file_stream;
    video_flashvars.streamer = streamer;
    video_flashvars.controlbar = options.controlbar;
    video_flashvars.autostart = "1";
    video_flashvars.stretching = "exactfit";
    if(options.mute == true || options.mute == 'true') {
        video_flashvars.volume = 0;
    }
    video_flashvars.width = options.width;
    video_flashvars.height = options.height;
    video_flashvars.image = options.image;
    console.log('STREAM: ' + video_flashvars.streamer + ' FILE: ' + video_flashvars.file + ' PLAYER: ' + player_dir + player_swf);
    swfobject.embedSWF(player_dir + player_swf, div_element, video_flashvars.width, video_flashvars.height, "10.0.0", "http://bitcast-b.bitgravity.com/player/expressInstall.swf", video_flashvars, params, attributes);
}

function check_video_defaults(options) {
    if(!options) {
        return video_defaults;
    }

    if(!options.width) options.width = video_defaults.width;
    if(!options.height) options.height = video_defaults.height;
    if(!options.mute) options.mute = video_defaults.mute;
    if(!options.autostart) options.autostart = video_defaults.autostart;
    if(!options.image) options.image = video_defaults.image;
    if(!options.controlbar) options.controlbar = video_defaults.controlbar;
    if(!options.link) options.link = '';
    if(!options.linktarget) options.linktarget = '_self';
    if(!options.displayclick) options.displayclick = 'play';


    return options;

}

function embed_trailer(div_element, video_file, options) {

	attributes.id = div_element;
	attributes.name = div_element;

    if(!options.controlbar) {
        options.controlbar = 'over';
    }
    options = check_video_defaults(options);

    if(options.allowfullscreen) {
        params.allowfullscreen = "true";
    }  

    // URL Encode first!
    if(video_file && video_file != '') {
	    video_file = video_file.replace('&', '%26');
	    video_file = video_file.replace('?', '%3F');
	    video_file = video_file.replace('=', '%3D');
    }
    video_flashvars.file = video_file;
    video_flashvars.streamer = video_file;

    // These 2 lines are for handling video scrubbing & YouTube embeds
    video_flashvars.provider = (options.youtube) ? "youtube" : "http";

    if(!options.youtube) {
        video_flashvars.type = "bitgravity";
    }
    
    // If they passed in a playlist, be sure to play it
    if(options.playlistfile) {
    		video_flashvars.playlistfile = options.playlistfile;
    }

    if(options.repeat) {
    		video_flashvars.repeat = options.repeat;
    }
    
    //video_flashvars.provider = "bitgravity";
    //video_flashvars.type = "bitgravity";
    video_flashvars.bufferlength = "5";
    video_flashvars.controlbar = options.controlbar;
    video_flashvars.http = { startparam: "starttime" };
    video_flashvars.autostart = options.autostart;
    video_flashvars.stretching = "exactfit";
    if(options.mute == true || options.mute == 'true') {
        video_flashvars.volume = 0;
    }
    video_flashvars.width = options.width;
    video_flashvars.height = options.height;
    video_flashvars.image = options.image;

    // If this trailer is being inserted onto a page that is for preview only, check to see if that page is eligible for showing trailers
    if(on_preview_page) {
        console.log("Article page eligibility: " + eligible_preview_page);
        if(!eligible_preview_page) {
            var image_tag = '<img width="' + options.width + '" height="' + options.height + '" alt="Click here to download!" title="Click here to download!" src="' + options.image + '">';
            var play_button = '<img id="download_button" src="http://content.naughtyamerica.com/naughty/public/live_chat/images/btn_sqr_full_video.png">';
            var final_tag = '<div style="position: relative"><a href="'+ join_link +'">' + play_button + image_tag + '</a></div>';
            $('#' + div_element).html(final_tag);
            return;
        }
    }

    swfobject.embedSWF(player_dir + '/player-5.0-licensed.swf', div_element, video_flashvars.width, video_flashvars.height, "10.0.0", "http://bitcast-b.bitgravity.com/player/expressInstall.swf", video_flashvars, params, attributes);
	
}

/**
 * Embed the channel that is currently live (if there is one), else embed Live With Lauren.
 * param array options - options to be passed to embed_channel
 */
function embed_whats_live_now(options) {

    if(!options) {
      options = video_defaults;
    }

    var channel_name = 'naughty_americans';
    
    naughty_rpc('Live.get_channel_info', { status: 'live_now', limit: 4 }, function(data) {

        // For now, we only care about the 1st live show returned
        for (var channel in data) {
            channel_name = channel;
            break;
        }
        embed_channel(channel_name, options);
    });
}

/* Usage:
 * watch_whats_live_now('%append%');
 */
function watch_whats_live_now(nats_code, target, tracking_method, new_window) {

  if(!nats_code) {
    nats_code = '';
  }

  if(!target) {
      target = (target_domain != undefined) ? target_domain : 'http://members.naughtyamerica.com';
  }
  
  if(target[target.length-1] != '/') {
	  target += '/';
  }
  

  if(!tracking_method) {
      tracking_method = 'nats';
  }

  naughty_rpc('Live.get_whats_live_now', { status: 'active' }, function(data) {

    var final_url;

    // Default to the schedule is something goes wrong (or there is nothing live)
    var channel_slug = 'schedule';
    if(data) {
        channel_slug = data;
    }

    // Nats
    if(nats_code != '' && tracking_method != 'affid') {
        final_url = target + 'live_chat/' + channel_slug + '/?' + nats_code;
    }
    // Affiliate ID (CMS Galleries)
    else if(tracking_method == 'affid') {
       final_url = target + 'index.php/live_chat/' + channel_slug + '/AFFID' + nats_code + '/TRACKA/';
    }
    // Members/Bedrooms/No Tracking
    else {
        final_url = target + 'live_chat/' + channel_slug + '/';
    }

    if(!new_window) {
        top.location.href = final_url;
    }
    else {
        window.open(final_url, "NA Live!");
    }
  });
}

function embed_channel(channel_name, options) {

  // Change the current channel & reset any past re-checks
  if(current_channel != channel_name) {
      debug_print('Switching: ' + current_channel + ' => ' + channel_name);
      current_channel = channel_name;
      clearInterval(interval_id);
      interval_id = null;
  }

  var channel_data = default_channel_data;
  var player_options = {};

  if(!options) {
      options = video_defaults;
  }

  if(options.force_embed == undefined)
  {
      options.force_embed = false;
  }

  naughty_rpc('Live.get_channel_info', { channel_name: channel_name, secure: true }, function(data) {

    if(data) {
      channel_data = data;
      debug_print('Got info for: ' + channel_data['name']);
      //debug_print("Stream: " + channel_data['top_stream'])
    }

    // If we're switching from live to a trailer (or vice versa) the player must be stopped
    if(channel_data['type'] != current_segment['type']) {
    		debug_print('Mode switch: ' + current_segment['type'] + ' => ' + channel_data['type']);
        current_segment['type'] = channel_data['type'];
    }

    switch(channel_data['type']) {
      case 'video':
      case 'trailer':
        // Embed new trailers only if they've changed
        if((channel_data['file'] != current_segment['file']) || options.force_embed) {

          // Only force an embed once!
          options.force_embed = false;

          // With the 5.0 beta player, the API has changed, so the player must be re-embedded...for now
          if(0 && player) {
            player_options.type = "video";
            player_options.provider = "http";
            player_options.mute = false;
            player_options.autostart = true;
            player_options.stretching = 'exactfit';
            player_options.file = channel_data['file'];
            debug_print('Load video:' + channel_data['name']);
            player.sendEvent('LOAD', player_options);
          }
          else {
            $("#top_cam").html('<div id="top_stream"></div>');
            debug_print('Embedding Trailer:' + channel_data['name']);
            
            // If there's an alternate trailer, choose it sometimes
            var trailer_file = channel_data['file'];
            if(channel_data['file2'] != '' && (Math.floor( Math.random() * 2 ) == 1) ) {
            		trailer_file = channel_data['file2'];
            }
            embed_trailer('top_stream',trailer_file, options);
          }
          current_segment['file'] = channel_data['file'];
          current_segment['name'] = channel_data['name'];
        }
        break;
        case 'stream':

            if(channel_data['cameras'] != 2) {
                show_bottom_feed(false);
            }

            // Embed new streams only if they've changed
            if(channel_data['name'] != current_segment['name']) {

                // With the 5.0 beta player, the API has changed, so the player must be re-embedded...for now
                if(0 && player) {
                    // This is a special type for the CDN!
                    player_options.type = "bitgravity";
                    player_options.provider = "http";
                    player_options.mute = false;
                    player_options.stretching = 'exactfit';
                    player_options.streamer = player_options.file = channel_data['top_stream'];
                    debug_print('Load event:' + channel_data['top_stream']);
                    player.sendEvent('LOAD', player_options);
                }
                else {
                    $("#top_cam").html('<div class="live-overlay"></div><div id="top_stream"></div>');
                    debug_print('Embedding Stream:' + channel_data['top_stream']);
                    embed_stream('top_stream', channel_data['top_stream'], options);
                }
                current_segment['top_stream'] = channel_data['top_stream'];
                current_segment['name'] = channel_data['name'];

                // Don't bother with the bottom cam if there isn't one
                if(channel_data['cameras'] == 2) {
                    console.log(current_segment['name'] + " is a 2 cam show: Showing bottom camera.");
                    show_bottom_feed(true);

                    $("#bottom_cam").html('<div id="bottom_stream"></div>');

                    // 11-17-09: No need to mute the bottom feed because they don't broadcast the audio!
                    options.mute = false;
                    embed_stream('bottom_stream', channel_data['bottom_stream'], options);
                    current_segment['bottom_stream'] = channel_data['bottom_stream'];
                }
                else {
                    console.log(current_segment['name'] + " is a 1 cam show: Hiding bottom camera.");
                    show_bottom_feed(false);
                }
        }

        
        break;
    }

    if(interval_id == null) {
        //interval_id = setInterval(function() { embed_channel(channel_data['name'], options); }, polling_interval);
    }
  });
}


// This is to see if API needs "labs" as a sub directory in the path
function get_preview_data(the_cam_function, id_or_class, path) {
    // Set default identifier
    if ( id_or_class == null || id_or_class == "" ) {
        id_or_class = '#top_cam';
    }

    if(path == null) {
        path = '';
    }

  // Make ajax request for data
  $.get("/labs/index.php?m=chat&s=preview_ajax&name=" + preview_cookie, function(data) {
    if ( data.match(/ERROR/) ) {
      if ( typeof the_cam_function == "function" )
        the_cam_function();
      setTimeout("stopLivePreview('" + id_or_class + "')", 60000);
    } else {
      var return_data =  new Array();
      var temp = data.split("|");
      var x;
      for ( x in temp ) {
        var temp2 = temp[x].split("=");
        return_data[temp2[0]] = temp2[1];
      }
      checkPreview(return_data, the_cam_function, id_or_class);
    }
  } );
}


/******** QVC AREA **********/
function load_qvc(options) {

    // Allow for testing on localhost
    var index_file = 'index3.php';
    var this_domain = (document.domain.search(/localhost/) != -1) ? 'http://' + document.domain.replace(/\\/g,'/').replace(/\/[^\/]*\/?$/, '') : '';

    // Setup defaults
    if(!options) {
        options = { width: 960, height: 585, site: 'live_naughty_girl_talk'};
    }
    console.log('Showing QVC popup.');

    // Add the background graphic
    $('body').append('<div id="overlay_mask"></div>');

    // Add the overlay element
    //$(options.element).add('<div id="overlay_popup"></div>');
    $('body').append('<div id="overlay_popup_container"><div id="overlay_popup"></div></div>');

    if(this_domain.search("www.naughtyamerica.com") != -1 || this_domain.search("www.suite703.com") != -1) {
        index_file = 'index3.php';
    }

    var url = this_domain + '/' + index_file + '?m=misc&s=loader&template=live_popup&site=' + options.site;
    $('#overlay_popup').hide()
                       .css('height', options.height)
                       .css('width', options.width)
                       .load(url, {}, function(data) {
                            $('#overlay_mask').animate({ opacity: .7 }, 'slow');
                            $(this).slideDown('slow');
                        });
}

function embed_qvc(options) {

    // Find out which QVC show is live or on deck
    var qvc_show = 'live_naughty_girl_talk';
    naughty_rpc('Live.get_channel_info', { status: 'live_now', limit: 4 }, function(data) {
        for (var channel in data) {
            if(in_array(channel, free_qvc_shows)) {
                qvc_show = channel;
                
                // Change the label in the pop-up to the show's title
                $("#show-name").text(data[channel]['title']);
                break;
            }
        }

        // Embed the currently live QVC show (or NGT if nothing is on)
        embed_channel(qvc_show, options);

        // Fetch the actors and display them in the QVC sidebar
        naughty_rpc('Live.get_upcoming_actors_html',
            {site: qvc_show, limit: 4, debug: true },
            function(data) {
                if(data) {
                    $(options.actor_container).hide().html(data).fadeIn('slow');
                }
            });
    });


}

// Destroy the overlayed popup
// @param boolean no_reload Whether or not to refresh the page
// Usage: destroy_popup(true);  // This will destroy the popup without reloading the page
function close_qvc() {

    $('#overlay_popup').slideUp('slow', function() {
        $(this).remove();
        $('#overlay_popup_container').remove();
        $('#overlay_mask').animate({ opacity: 0 }, 'fast', function() { $(this).remove() });
    })
}


/**************** 
 * APE Functions 
 *****************/
var live_pipe = null;
function init_live_ape_admin() {

	APE.Config.scripts = ['http://tour.naughtyamerica.com/js/apeCoreSession.js'];
    //Instantiate APE Client
    var client = new APE.Client();

    //Load APE Core
    client.load({'identifier': 'NA_NOTIFICATIONS', 'channel': 'na_live'});

    //Intercept 'load' event. This event is fired when the Core is loaded and ready to connect to APE Server
    client.addEvent('load', function() {
        //Call the core start function to connect to APE Server if a session cannot be restored
        if (0 && client.core.options.restore) {
            // Calling start(); without arguments will ask the APE Server for a user session
            console.log('Restoring APE session');
            client.core.start();
        } else {    
            var display_name = 'NAAdmin' + Math.round(Math.random() * 100000);
            client.core.start({"name":display_name});
            console.log('Logging in as: ' + display_name);
            // Tell the admin page that we're connected
			$('#live-connection-status').removeClass('red').addClass('orange').html('CONNECTING...');
        }
    });

    // Once connected, you can receive notifications of change in Live status!
    client.addEvent('ready', function() {
        var options = { 'height': 400, 'width': 600 }
        client.onRaw('changeLiveStatus', function(raw, pipe) {
            console.log('Live Status Notification: ' + unescape(raw.data.status) + ' = ' + unescape(raw.data.info.title));
        });
    });

    // Once you join the channel, bind the buttons to do the actions.
    client.addEvent('multiPipeCreate', function(pipe, options) {
		// Set the pipe
		live_pipe = pipe;
		console.log('Live APE Admin connected successfully (' + pipe.name + ')');
		
		// Tell the admin page that we're connected
		$('#live-connection-status').removeClass('orange').addClass('green').html('CONNECTED');
    });
}

function init_live_ape_client() {
	  //Use APE JSF build with sessions
	  //APE.Config.scripts = [APE.Config.baseUrl + '/Build/uncompressed/apeCoreSession.js'];
	
	  // Try to load it off of the load-balanced tour
	  //console.log("Loading: " + window.target_domain + '/js/apeCoreSession.js');
	  APE.Config.scripts = [window.target_domain + '/js/apeCoreSession.js'];
	           	  
	  //Instantiate APE Client
	  var client = new APE.Client();
	 
	  //Load APE Core
	  //client.load({'identifier': 'NA_NOTIFICATIONS', 'channel': 'na_live'});
	  client.load();
	 
	  //Intercept 'load' event. This event is fired when the Core is loaded and ready to connect to APE Server
	  client.addEvent('load', function() {
	  //Call the core start function to connect to APE Server if a session cannot be restored
	  if (client.core.options.restore) {
		  // Calling start(); without arguments will ask the APE Server for a user session
	      console.log('Restoring APE session');
	      client.core.start();
	  } else {    

	     // Log them in as their display name or a semi-random name
		 if(window.display_name == undefined || window.display_name == '') {
			  window.display_name = 'NAUser' + Math.round(Math.random() * 1000000);
		 }                   
	                    
	     client.core.start({"name": window.display_name});
	     console.log('Live APE Client Loaded. Logging in as: ' + window.display_name);
	   }
	  });
	 
		// Once connected, you can receive notifications of change in Live status!
		client.addEvent('ready', function() {
		            
			client.core.join(['na_live', 'na_messages']);
			//client.core.join('na_messages');
		    
			client.onRaw('newMessage', function(raw, pipe) {
				var message_data = raw.data.data;
			    console.log('New ' + unescape(raw.data.type) + ' message from: ' + unescape(raw.data.data.display_name));
			    // Fill in the values
			    $('#latest-message-template .author_name').html(message_data.display_name);
			    $('#latest-message-template .wallMessageText').html(message_data.message_text);

			    // Insert HTML
			    $('#message_board').prepend($('#latest-message-template').clone().html()).slideDown('slow');
			    console.log('Message added!');
			});
			
			// If the live status changes, the LIVE button should be updated
			client.onRaw('changeLiveStatus', function(raw, pipe) {
				console.log('Live Status Notification: ' + unescape(raw.data.status) + ' = ' + unescape(raw.data.info.title));

				/* When a show goes on-air: 
				 * 1) change the LIVE button to it's highlighted color
				 * 2) TODO: re-embed the Live Now area with the new show
				 */
				if(unescape(raw.data.status) == 'on-air') {
				    $('#live_content_available').addClass('live_red');
				}
				/* When a show goes off-air: 
	             * 1) change the LIVE button to it's normal color
	             * 2) TODO: re-embed the Live Now area with the trailer for the show
	             */
				else {
					$('#live_content_available').removeClass('live_red');
				}
			});
		});
	    
		// Once you join the channel, bind the buttons to do the actions.
		client.addEvent('multiPipeCreate', function(pipe, options) {
				// Set the pipe
				live_pipe = pipe;
				console.log('Live APE client connected successfully to channel: ' + pipe.name);
				
				/*** For debugging only 
				if(pipe.name == 'na_messages') {
				    var data = { display_name: 'Lance Hardwood', message_text: "Yowza!" }
				    console.log( 'Posting a wall message!');
				    live_pipe.request.send('sendMessage', {'type': 'wall', 'data': data});
				}
				***/

		});
}

function send_wall_message(data) {

    console.log( 'Posting a wall message!');
    live_pipe.request.send('sendMessage', {'type': 'wall', 'data': data});
}


//This is for use by the NA TV Admin page. When a show is made live, a notification is sent out to all connected clients.
function send_live_notification(form) {
	if(live_pipe) {
		var waiting = true;
		var form_id = $(form).attr('id');
		var status = ($(form.type).val() == 'trailer') ? 'off-air' : 'on-air';
		var info = { name: $(form.name).val(), title: $(form.title).val() };
		// Alert the admin that the message is being broadcast, then send.
		$('#message').html('Sending the instant notification to all people watching...');
		console.log( form_id + ': Changing ' + $(form.title).val() + ' to ' + status );
		live_pipe.request.send('newLiveStatus', {'status': status, 'info': info });
		setTimeout("$('#" + form_id + "').submit();", 1000);
		return false;
	}
	else {
		alert('Please wait for the page to finish loading. It is still trying to connect to the Live "Instant Notification" Sever.');
	}
	return true;
}

