/*
	Video.js

        Version: 0.2

	This file handles the javscript API for JW player.

	It also handles the ajasx submision and otehr details for star rating system

*/
//initiate global vars
var thePlayer = '';

var apiReady = false;

var currentChannel = '';

var defaultChannel = 'TK1400';

var author = '';

var title = '';

var thisIdx = '';

var videoConfig = {DOMitem:'ul.list', 'thumbWidth': 100};


/*
 *Query string parser
 *to remove dependencies on other scripts
 */
function getQuerystring(key, default_) {
  if (default_==null) default_="";
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}


/*
* This function is called by JW Player whwen it is ready
*/
function playerReady(obj) {
	//alert('the videoplayer '+obj['id']+' has been instantiated');
	thePlayer = document.getElementById(obj['id']);

	apiReady = true;

	addListeners();

        initChannel();


}


function starRating (Rating) {

	var read_only = (Rating) ? true : false;


	//alert(read_only);

        $('#star_rating:hidden').fadeIn('fast');

	if ($('.starRating').is('*')) {

		if (read_only) {

			//gray out the label text
			$('#videorate').text('Your Rating ').css('color', 'gray');

		}else{

			$('#videorate').text('Rate this Video ').css('color', 'white');

		}

		if (Rating) {

			$('.starRating[value='+Rating+']').attr('checked', 'checked');

		} else {

			$('.starRating').removeAttr('checked');
		}

		//clean up the bs
		$('.star-rating-control').remove();


		$('.starRating').removeClass('star-rating-applied').attr('autocomplete', 'off').rating({

		  readOnly: read_only,

		  callback: function(value, link){


		  	if (currentChannel !== '') {

		  			$.post( '_rate.php', 'star2='+value+'&channel='+currentChannel, function() {

						$.cookie(currentChannel, value, { expires: 1 });

						starRating(value);

					});


		  	}


		  }

		});

	}

}

function updateStatus() {


		author = thePlayer.getPlaylist()[thisIdx].author;

		title = thePlayer.getPlaylist()[thisIdx].title;

		var tags = thePlayer.getPlaylist()[thisIdx].tags;

		if (tags != null) {

			currentChannel = tags;

		}


		//update metadata so facebook connect works correct
		$('meta[name=title]').attr('content', author);

		$('meta[name=description]').attr('content', title);

		$('link[rel=image_src]').attr('href', 'https://vrptv.com/my/chanx/image.php?channel='+currentChannel);

		//update channel reference on mailto link in social media
		$('a#email').attr('href', $('a#email').attr('href').replace($('a#email').attr('href').substring($('a#email').attr('href').lastIndexOf('=') + 1), currentChannel));

		//update the "Now Playing"  marquee
		$('#midDescription div.pad').html('<div class="bold heading">'+author+'</div>'+title);

		var theCookie = $.cookie(currentChannel);

		if (theCookie !== null) {

			var channelRating = theCookie;

		} else {

			var channelRating = false;

		}

		starRating(channelRating);

}

function stateMonitor(obj) {
	currentState = obj['newstate'];
	if(currentState == 'PLAYING') {
		updateStatus();
	}
	if(currentState == 'IDLE') {//teh player has finished playing
	//alert ('the videoplayer '+obj['id']+' has stoped playing now!');
	}
}

function handleError(message) {

		alert('an error has occured');

}

function addListeners() {
        try
        {
          playlist = thePlayer.getPlaylist();
        }
        catch(e)
        {
          setTimeout("addListeners();", 100);
        }
        //...whatever you want to do here, such as:
        thePlayer.addModelListener('STATE', 'stateMonitor');
        thePlayer.addControllerListener('ERROR', 'handleError');

}


/*
* bind the video list widget to the player an dupdate the "Now Playing" area
*/
function bindList(channel) {
	//video list widget
		//set start state
                
         _hookLists();
                
		$('.list li:not(".pdf")').each(function() {

			$(this).find('a')

			.bind('click', function() {

				if (apiReady) {
					//api is ready to roll

					thisIdx = parseFloat(this.id.replace('idx_', ''));

					//track this video play
					$.get('_ajaxStats.php?channel='+currentChannel+'&useragent='+document.referrer);

					//thePlayer.sendEvent('LOAD', playList);

					thePlayer.sendEvent('ITEM', thisIdx);

					return false;

				}
			});

		});

                $('.list li.pdf').each(function(){

                    $(this).find('a').attr('target', '_BLANK');


                });

}

/*
 * Build a playlist
 *
 */
function buildList(channel) {


	if (channel.nullChannel == 1) {

		 thePlayer.sendEvent('LOAD', channel.baseurl+'playlist.php?var_single_item&channel='+channel.placeholder_channel);

		 theHTML = '<li>';

		 theHTML += '<div class="left">';

		 theHTML += '<div class="icon">';

		 theHTML += '<a id="idx_0" href="?channel='+channel.placeholder_channel+'" >';

		 theHTML += '<img alt="'+channel.title+'" src="'+channel.baseurl+'/image.php?channel='+channel.placeholder_channel+'&var_width='+videoConfig.thumbWidth+'" border="0" />';

		 theHTML += '</a>';

		 theHTML += '</div>';

		 theHTML += '<a href="?channel='+channel.placeholder_channel+'" >'+channel.title+'</a>';

		 theHTML += '</div>';

		 theHTML += '</li>';

	}else{

	   var playlist = thePlayer.getPlaylist();

	   var today = new Date();

	   var theHTML = '';//container for list items

	   var x;

	   for (x in playlist) {

		   var theDate = new Date(playlist[x].date);

                   var age = Math.round((today - theDate)/1000/60/60/24);

    		   theHTML += (playlist[x].file.search(/.pdf/i) > 0) ? '<li class="pdf">' : '<li>';

		   theHTML += '<div class="left">';

		   theHTML += '<div class="icon">';

		   theHTML += (playlist[x].file.search(/.pdf/i) > 0) ? '<a href="'+playlist[x].file+'">' : '<a id="idx_'+x+'" href="?channel='+playlist[x].tags+'" >';

		   theHTML += '<img alt="'+playlist[x].author+'" src="'+channel.baseurl+'/image.php?channel='+playlist[x].tags+'&var_width='+videoConfig.thumbWidth+'" border="0" />';

		   theHTML += '</a>';

		   theHTML += '</div>';

		   theHTML += (playlist[x].file.search(/.pdf/i) > 0) ? '<a href="'+playlist[x].file+'">' : '<a id="idx_'+x+'" href="?channel='+playlist[x].tags+'" >';

                   theHTML += playlist[x].author+'</a>';

		   theHTML += '<em>updated '+age+' days ago.</em>';

		   theHTML += '</div>';

		   theHTML += '</li>';

	   }

    }



   $(videoConfig.DOMitem).append(theHTML);

   /*
    * check if a skin function exists and run it if it does
    */
   if (typeof(applySkin) == 'function') {

       applySkin();

   }


   bindList(channel);

}

/*
 * Inititilize a channel
 *
 * get the data object for channel passed in query string
 *
 *
 *
 *
 */
function initChannel(){

	//get channel from the uri string if can
	var channelID = getQuerystring('channel', false);

	if (!channelID) channelID = defaultChannel;

	$.getJSON('_proxy.php', {uri: 'http://vrptv.com/my/chanx/?channel='+channelID}, function (channel) {

            currentChannel = channel.channel_ref;

            author = channel.title;

            title = channel.intro;

            thisIdx = channel.idx;

            /*
             * check if the the video list widget ul has been populated by php
             * if it has - just bind it, if not first build the list and THEN bind it
             *
             */
            if (!$(videoConfig.DOMitem+'>li').is('*')) {

                buildList(channel);

            }else{

                bindList(channel);

            }


	});



}

