

/* SIG kept in memory */
var SIG;

/* For the fadeout */
var lastRun;

/* Defaulting this var */
var hasVoted = 0;

/* Is vote in progress or not */
var isVoting = false;

/* Fullscreen popup */
var full_popup;

/* Type of errors to display (alert/div) */
var error_type = 'div';

/* For the rating */
var is_note = false;

/* Avoids having many redirects */
var being_redirected = false;


/* Items content in the current channel */
var channel_items = null;

/* This function adds a bookmark */
function addBookmarks(sig)
{
	if(sig)
	{
		SIG = sig;
		parameters = new Object();
		parameters['sig'] = sig
		parseResponseFunction = returnedaddBookmarks
		runAJAX('api_server/', 'addbookmark', parameters, 'get');
	}
}

function returnedaddBookmarks(response)
{
	if(response == 1)
	{
		document.getElementById('remove_bookmark').style.display = 'block';
		document.getElementById('add_bookmark').style.display = 'none';
		displayMessage(JST_ADDED_IN_FAVORITES)
	}
	else
	{
		displayError(JST_COULDNT_ADD_FAVORITES)
	}
}

/* Removes a bookmark */
function removeBookmarks(sig)
{
	if(sig)
	{
		SIG = sig;
		parameters = new Object();
		parameters['sig'] = sig;
		parseResponseFunction = returnedremoveBookmarks
		runAJAX('api_server/', 'removebookmark', parameters, 'get');
	}
}

function returnedremoveBookmarks(response)
{
	if(response == 1)
	{
		document.getElementById('add_bookmark').style.display = 'block'
		document.getElementById('remove_bookmark').style.display = 'none'
		displayMessage(JST_REMOVED_FROM_FAVORITES);
	}
	else
		displayError(JST_COULDNT_REMOVE_FAVORITES)
}

var add_channel_open = false;
function startAddChannel()
{
	add_channel_open = true;
	document.getElementById('add_to_channel').style.visibility = 'visible'
}

function closeAddChannel()
{
	if(add_channel_open == true)
		setUpFade('add_to_channel');
	add_channel_open = false;
}

function closeWriteToAuthor()
{
	setUpFade('write_to_author');
}

function closeAddComment()
{
	setUpFade('new_comment', 'FadeComment');
}

function FadeComment()
{
	$('#add_comment_form').css('display', 'block');
	$('#new_comment').css('display', 'none');
	$('#new_comment').css('visiblity', 'visible');
}

function closeAddChannelAuth()
{
	setUpFade('add_into_new');
}

function addIntoNewChannel(sig)
{
	var newchannel = document.getElementById('new_channel').value;

	parameters = new Object();
	parameters['channel_name'] = encodeURIComponent(newchannel);
	parameters['sig'] = sig;
	parseResponseFunction = returnedaddChannel;
	runAJAX('api_server/', 'add_into_new', parameters, 'get');

}

var add_rating_open = false;
function startAddRating()
{
	add_rating_open = true;
	document.getElementById('video_rate').style.visibility = 'visible'
}

function closeAddRating()
{
	for (i=1; i <= 10; i=i+1)
	{
		var obj = 'star_'+i;
		document.getElementById(obj).src = "/img/default/notext/note-star-grey.gif";
	}
	document.getElementById('video_rating_waiting').style.visibility = 'hidden';
	setUpFade('video_rate');
	hasVoted = 0;
}

function setRating()
{
	document.getElementById('rating').value = hasVoted;
}

function startAddBookmark()
{
	add_bookmark_open = true;
	document.getElementById('addbookmark').style.visibility = 'visible'
}

function closeAddBookmark()
{
	setUpFade('addbookmark');
}

function returnedaddChannel(response)
{
	if(response <= 0)
	{
		if (response == -7006)
		{
			displayError(JST_PLAYER_ERROR_CHANNEL_CHECK_NAME);
		}
		else if (response == -7002)
		{
			displayError(JST_CHANNEL_EXISTS)
		}
		else if(response == -7000)
		{
			alert(JST_PLAYER_ERROR_CHANNEL_CHECK_NAME);
		}
		else
		{
			var suffix = '';
			if (isNaN(response) == false)
			{
				suffix = response;
			}
			displayError(JST_COULDNT_ADD_CHANNEL+' ['+response+']')
		}
	}
	else if (isNaN(response) == true)
	{
		displayError(JST_COULDNT_ADD_CHANNEL)
	}
	else
	{
		var o=new Option(document.getElementById('new_channel').value, response);
		document.getElementById('existing_channel').options[document.getElementById('existing_channel').options.length]=o;
		document.getElementById('new_channel').value = '';
		document.getElementById('existing_channel').disabled = false;
		document.getElementById('existing_channel_bttn').disabled = false;
		setUpFade('add_to_channel');
	}
}

function addIntoExistingChannel(sig)
{
	channelSIG = document.getElementById('existing_channel').value;
	parameters = new Object();
	parameters['channel_SIG'] = channelSIG;
	parameters['sig'] = sig;
	parseResponseFunction = returnedexistingChannel;
	runAJAX('api_server/', 'add_into_existing', parameters, 'get');

}

function returnedexistingChannel(response)
{
	if(response == 1)
	{
		displayMessage('ok');
		setUpFade('add_to_channel')
	}

	else
	{
		if(response == -1503)
		{
			displayError(JST_ALREADY_IN_CHANNEL)
		}
		else
			displayError(JST_COULDNT_INSERT_CHANNEL);
	}
}

var tempImage;

function overStar(v)
{
	/* Preloading image */
	if(!tempImage)
	{
		tempImage = new Image;
		tempImage.src = "/img/default/notext/note-star-yellow.gif"
	}

	new_image = "/img/default/notext/note-star-yellow.gif"
	for(i=1; i<=10; i=i+1)
	{
		if(i<=v)
			document.getElementById('star_'+i).src = new_image;
		else
			document.getElementById('star_'+i).src = "/img/default/notext/note-star-grey.gif";
	}
}


function outStar()
{
	for(i=10; i > 0; i=i-1)
	{
		if(i<=hasVoted)
			document.getElementById('star_'+i).src = "/img/default/notext/note-star-yellow.gif";
		else
			document.getElementById('star_'+i).src = "/img/default/notext/note-star-grey.gif";
	}
}



function videoRate(params)
{
	// Patch, hidden by other layer
	//document.getElementById('video_rating_stars').style.display = 'none';
	document.getElementById('video_rating_waiting').style.visibility = 'visible';

	exploded = params.split(',');
	sig = exploded[0];
	note = exploded[1];

	hasVoted = note;

	parameters = new Object();
	parameters['rating'] = note;
	parameters['sig'] = sig;
	parseResponseFunction = returnedVideoRate;
	runAJAX('api_server/', 'video_rate', parameters, 'get');
}

function returnedVideoRate(response)
{
	if(response <= 0)
	{
		if(window.document.flvplayer)
		{
			try {
				window.document.flvplayer.SetVariable("is_note", "false");
			}
			catch(err) {

			}
		}

		displayError(JST_COULDNT_SAVE_VOTE)
		timeout(setUpFade, 'video_rating_waiting', 900);
		hasVoted = 0;
	}
	else
	{
		if(window.document.flvplayer)
		{
			try {
				window.document.flvplayer.SetVariable("is_note", "true");
			}
			catch(err) {

			}
		}

		exploded = response.split('|')
		if(exploded.length != 2)
		{
			returnedVideoRate(-1)
			return
		}

		/* Shows the rate results if invisible */
		document.getElementById('li_vote').style.display = 'block';

		document.getElementById('video_rating_span').innerHTML = exploded[0];
		document.getElementById('video_rating_count_span').innerHTML = exploded[1];

		document.getElementById('video_rating_stars').style.display = 'block';
//		document.getElementById('video_rating_waiting').style.visibility = 'hidden';
		overStar(hasVoted)
		//document.getElementById('video_rating_waiting').innerHTML = JST_PLAYER_VOTE_OK
		displayMessage(JST_PLAYER_VOTE_OK);
		timeout(setUpFade, 'video_rating_waiting', 900);
	}
}


function displayError(message)
{
	alert(message)
}

function displayError2(message)
{
	if(error_type == 'alert')
	{
		alert(message)
	}
	else
	{
		lastRun = false

		document.getElementById('errorbar').style.visibility = 'visible';
		document.getElementById('errorbar').innerHTML = message;
		fader('errorbar',4000,50,1500)
	}
}

function displayMessage(message)
{

}

var messagebar = 0;
function displayMessage2(message)
{
	lastRun = false

	/*document.getElementById('successbar').style.visibility = 'visible';*/
	/*document.getElementById('successbar').innerHTML = message;*/

	if(document.getElementById('messagebar_'+messagebar))
	{
		document.getElementById('messagebar_'+messagebar).innerHTML = message
		document.getElementById('messagebar_'+messagebar).style.visibility = 'visible'
	}
	else
	{
		mess=document.getElementById("messagebar");
		newP=document.createElement('p');
		newP.id = 'messagebar_'+messagebar;
		newP.innerHTML=message
		newP.style.bottom = (28*messagebar)+'px';
		mess.appendChild(newP);
	}

	fader('messagebar_'+messagebar,4000,50,1500)

	messagebar ++;

}


function setUpFade(ename, callback) {
	lastRun = false
	fader(ename,2,50,300, callback);
}

// Fades an element
// elName - id of the element
// start - time in ms when the fading should start
// steps - number of fading steps
// time - the length of the fade in ms
var timer
function fader(elName,start,steps,time, callback) {
  setOpacity(elName,100); // To prevent flicker in Firefox
                          // The first time the opacity is set
                          // the element flickers in Firefox
  fadeStep = 100/steps;
  timeStep = time/steps;
  opacity = 100;
  time = start + 100;
  while (opacity >=0) {
   	window.setTimeout("setOpacity('"+elName+"',"+opacity+","+callback+")",time);
    opacity -= fadeStep;
    time += timeStep;
  }
}


function setOpacity(elName,opacity, callback) {
  opacity = (opacity == 100)?99:opacity;
  el = document.getElementById(elName);
  // IE
  el.style.filter = "alpha(opacity:"+opacity+")";
  // Safari < 1.2, Konqueror
  el.style.KHTMLOpacity = opacity/100;
  // Old Mozilla
  el.style.MozOpacity = opacity/100;
  // Safari >= 1.2, Firefox and Mozilla, CSS3
  el.style.opacity = opacity/100


  if(opacity <= 0)
  {

  	reg = new RegExp('^messagebar');
  	if(reg.test(elName) == true)
  	{
		messagebar--;
  	}

  	if (callback)
  	{
  		callback();
  	}

  	lastRun = true;
	document.getElementById(elName).style.visibility = 'hidden'
/*	document.getElementById(elName).style.display = 'none';*/
	setOpacity(elName, 100);
  }
}

/* Opens a fullscreen window */
/* pSeek is the position in the video when opening fullscreen */
/* is_note is a boolean: has the user already voted */
function fullscreen(seekNum, is_note)
{
	popup_url = '/player/?player_mode=fullscreen';
	if(channel_sig)
		popup_url += '&csig='+channel_sig
	popup_url += '&sig='+video_sig+'&seekNum='+seekNum+'&is_note='+is_note;

	full_popup = window.open(popup_url, '', 'width=' + screen.availWidth  + ',height=' + screen.availHeight + ',status=no,resizable=yes,scrollbars=no');

	if(!full_popup)
		window.alert(JST_COULDNT_OPEN_FULLSCREEN)
}

var share_friend_open = false;
function startShareFriends()
{
	share_friend_open = true;
	document.getElementById('share_friends_player').style.visibility = 'visible';
}

function closeShareFriends()
{
	if(share_friend_open == true)
		setUpFade('share_friends_player')
	share_friend_open = false;
}

/* Export Video */
format = 'html';

function makeHTML(type)
{
	switch(type)
	{
	    case 'forum':
			out = '<a href="' + export_obj.url.page + '" title="' + export_obj.video.title + '"><img src="' + export_obj.url.thumbnail + '" alt="' + export_obj.video.title + '"/></a><br /><a href="' + export_obj.url.page + '">' + export_obj.video.title+'</a>';
	        break;
        case 'mail':
            out = '<a href="' + export_obj.url.page + '">' + export_obj.video.title + '</a>';
	        break;
	}
	return out;
}

function makeBBCODE(type)
{
	switch(type)
	{
	    case 'forum':
			out = '[url=' + export_obj.url.page + '][img]' + export_obj.url.thumbnail + '[/img][/url]\n[url=' + export_obj.url.page + ']' + export_obj.video.title + '[/url]';
	        break;
        case 'mail':
            out = '[url=' + export_obj.url.page + ']' + export_obj.video.title + '[/url]';
	        break;
	}
	return out;
}

function makeWIKI(type)
{
	switch(type)
	{
	    case 'forum':
			out = '[((' + export_obj.url.thumbnail + '|' + export_obj.video.title + '))|' + export_obj.url.page + ']\n[' + export_obj.video.title + '|' + export_obj.url.page + ']';
			break;
        case 'mail':
            out = '[' + export_obj.video.title + '|' + export_obj.url.page + ']';
	        break;
	}
	return out;
}

function openCopyVideo()
{
    $('#export_video_player').css('visibility', 'visible');
}

function closeCopyVideo()
{
    if($('#export_video_player').css('visibility') == 'visible')
	{
		setUpFade('export_video_player');
	}
}

function changeSyntax(syntax, elt)
{
	format = syntax;
	updateCode(elt);
	return false;
}

function updateCode(elt)
{
	if(elt.match(/(forum|mail)/g))
	{
	    export_dest = elt.replace(/^export_/, "");
	    element = elt+'_code';
	    $('#'+element).val(eval('make'+format.toUpperCase()+'("'+export_dest+'")'));
	    //eval('$("#'+element+'").value = make'+format.toUpperCase()+'("'+export_dest+'");');
	}
}

function switchElt(elt)
{
	$('.code').each(function() {
	    if($(this).attr('id') != elt) {
	        $(this).hide();
	    } else {
	        updateCode(elt);
			$(this).toggle();
	    }
	});
}

function closePreviewExport()
{
	if($('#export_video_player_preview').css('visibility') == 'visible')
	{
	    $('#export_video_player_preview').fadeOut('slow');
	}
}

function export_preview(element)
{
	switch(element)
	{
	    case 'export_website_code':
	        $('#export_video_player_preview').css('width', '400px');
	        $('#export_video_player_preview').css('height', 'auto');
	        $('#preview_content').css('paddingTop', '0px');
	        $('#preview_content').css('textAlign', 'left');
	        element = 'export_website_code_preview';
	        break;
        case 'export_forum_code':
            $('#export_video_player_preview').css('width', '247px');
	        $('#export_video_player_preview').css('height', '300px');
	        $('#preview_content').css('paddingTop', '25%');
	        $('#preview_content').css('textAlign', 'center');
	        break;
	}

	//$('#preview_content').html(HtmlDecode(document.getElementById(element).innerHTML));
	$('#preview_content').html($('#' + element).val());
	
	$('#export_video_player_preview').css('zIndex', '9999');
    $('#export_video_player_preview').css('visibility', 'visible');
    $('#export_video_player_preview').css('display', 'block');
}

function selectCode(elt)
{
    elt.focus();
    elt.select();
	if(document.all)
	{
		therange=elt.createTextRange()
		therange.execCommand("Copy")
	}
}


function sentToFriend(sig)
{
	i = 1;
	errors = 0;
	success = 0;
	paramschar = '';


	regexp = new RegExp('^[A-Za-z0-9._-]{2,}@[A-Za-z0-9.-]{2,}[.][A-Za-z]{2,4}$');

	// Checks the validity of the recipients
	while(document.getElementById('s2f_to_email_'+i))
	{
		value = document.getElementById('s2f_to_email_'+i).value;
		value = trimAll(value);
		document.getElementById('s2f_to_email_'+i).value = value;

		if(value.length == 0)
		{
			document.getElementById('s2f_to_email_'+i).style.backgroundColor= '#FFF';
			document.getElementById('s2f_to_email_'+i).style.color= '#000';
			i = i + 1;
			continue;
		}

		if(regexp.test(value) == false)
		{
			document.getElementById('s2f_to_email_'+i).style.backgroundColor= 'red';
			document.getElementById('s2f_to_email_'+i).style.color= '#FFF';
			errors ++;
		}
		else
		{
			document.getElementById('s2f_to_email_'+i).style.backgroundColor= '#FFF';
			document.getElementById('s2f_to_email_'+i).style.color= '#000';

			paramschar = paramschar+'&s2f_to_emails[]='+value
			success ++;
		}
		i = i + 1;
	}

	// Checks the validity of the sender_email
	if(document.getElementById('sender_email_hidden'))
	{
		senderemail = trimAll(document.getElementById('sender_email_hidden').value);
		if(regexp.test(senderemail) == false)
		{
			return false;
		}
	}
	else
	{
		senderemail = trimAll(document.getElementById('sender_email').value);
		if(regexp.test(senderemail) == false)
		{
			document.getElementById('sender_email').style.backgroundColor= 'red';
			document.getElementById('sender_email').style.color= '#FFF';
			return false;
		}
		else
		{
			document.getElementById('sender_email').style.backgroundColor= '#FFF';
			document.getElementById('sender_email').style.color= '#000';
		}
	}

	if(errors == 0 && success >= 1)
	{
	  saveContact();
		document.getElementById('send_btn_div').style.display = "none";
		document.getElementById('wait_message_div').style.display = "block";

		document.getElementById('share_friends_btn').disabled = true;
		parameters = new Object();
		parameters['s2f_sig'] = sig;
		parameters['s2f_from_email'] = senderemail;
		parameters['s2f_to_emails[]'] = paramschar;
		parameters['s2f_copy_me'] = 1;
		parameters['s2f_extra_message'] = document.getElementById('share_message').value;

		parseResponseFunction = returnedSendFriends;
		runAJAX('tools/s2f/index.php', 'ajax_send_mails', parameters, 'post');
	}

	// always returning false
	return false;
}

// Save s2f contacts
function saveContact(){
      var w = $("input[@class='input_friends']").size();
      var i = 0;
      var fields = new Array();
        $('body').find('.input_friends').each(function() {
        fields[i] = $(this).val();
        i++;
        });
        var liste_mails = fields.join('|');
        if(w%2==1){
        liste_mails = liste_mails + "|" + i;
        } else if(w%2==0){
        liste_mails = " |" + liste_mails + "|" + i;
          }
      var exdate=new Date();
      exdate.setDate(exdate.getDate()+ 30);
      SetCookie('__s2fc', liste_mails, exdate);
}

function initContact() {
    var data = GetCookie('__s2fc');
    var k = 0;
      if (data!=null && data!=""){
      var liste_mails = data.split('|');
      var u = liste_mails.pop();
      var z = $("input[@class='input_friends']").size();
        if(z==4){ var v = liste_mails.shift();}
      for(i=1;i<=Math.ceil((u-5)/2);i++){moreEmails();}
      $("input[@class='input_friends']").each(function() {
      $(this).val(liste_mails[k]);
      k++;
      });
      }
}

$(document).ready(initContact);

function returnedSendFriends(response)
{
	document.getElementById('share_friends_btn').disabled = false;
	if(response == 1)
	{
		displayMessage(JST_PLAYER_MAIL_OK);
		setUpFade('share_friends_player')
	}
	else
	{
		displayError(JST_PLAYER_MAIL_FAILED)
	}
	document.getElementById('send_btn_div').style.display = "block";
	document.getElementById('wait_message_div').style.display = "none";
}



// For Video Views / Description
function showDescription(idLayer, actionLayer)
{
	if(actionLayer=='on'){
		document.getElementById(idLayer+'_off').style.display='none';
		document.getElementById(idLayer+'_on').style.display='block';
	}else{
		document.getElementById(idLayer+'_off').style.display='block';
		document.getElementById(idLayer+'_on').style.display='none';
	}
}

// For the player page
function addComment()
{
	document.getElementById('addcomment').style.display='block';
	document.getElementById('add_comment_link').style.display = 'none';
	document.getElementById('add_comment_link_top').style.display = 'none';
	//document.getElementById('comment_title').focus();
}

function write_to_author(sig)
{
	if ($('#islogged').val() == 'no')
	{
		$('#write_to_author').css('visibility', 'visible');
	}
	else
	{
		window.location = '/videos/?action=write_message&sig='+sig;
	}
	return false;
}

function addCommentCheck()
{
	var errors = 0
	var title = document.form_comment.comment_title.value
    var description = document.forms['form_comment'].comment_description.value
	if(title.length < 4 || title.length > 255)
	{
		document.getElementById('error_title_comment').style.visibility = 'visible'
		errors = errors + 1
	}
	else
		document.getElementById('error_title_comment').style.visibility = 'hidden'


	if(description.length < 4 || description.length > 255)
	{
		document.getElementById('error_description_comment').style.visibility = 'visible'
		errors = errors + 1
	}
	else
		document.getElementById('error_description_comment').style.visibility = 'hidden'

	if (document.getElementById('islogged').value == "no" && errors == 0)
	{
		$('#add_comment_form').css('display', 'none');
		$('#new_comment').css('display', 'block');
		$('#new_comment').css('visibility', 'visible');
		document.form_comment_auth.comment_title.value = document.form_comment.comment_title.value;
		document.form_register_comment.comment_title.value = document.form_comment.comment_title.value;
		document.form_comment_auth.comment_description.value = document.form_comment.comment_description.value;
		document.form_register_comment.comment_title.value = document.form_comment.comment_title.value;
		document.form_register_comment.comment_description.value = document.form_comment.comment_description.value;
		return false;
	}

	if(errors > 0)
		return false
	else
	{
		return true
	}
}



// Counter (2 lines by default)
nbfields = 4


// Adds 3 email fields in <li> tags
function moreEmails()
{
	// If there are less than 10 lines, adds lines
	if(nbfields < 30)
	{
		liste=document.getElementById("emailsfields");

		nouveauli=document.createElement('li');
		nouveauli.innerHTML='<input type="text" name="friends_emails[]" class="input_friends" id="s2f_to_email_'+(nbfields+2)+'" flexy:ignore /><input type="text" name="friends_emails[]" class="input_friends" id="s2f_to_email_'+(nbfields+1)+'" flexy:ignore />'

		liste.appendChild(nouveauli);
		nbfields = nbfields + 2;
	}

	// If 10 lines or more, hides the moreemails link
	if(nbfields >= 30)
		document.getElementById('moreemailslink').style.visibility='hidden'
}

// Check if the current item is the last element in playlist
function video_is_last()
{
	var last = false;

	$('#playlist_scroll .playlist_roll div').each(function()
	{
		if ($(this).attr('id') == 'playlist_detail_on')
		{
			last = true;
		}
		else
		{
		    last = false;
		}
	});

	return last;
}

/* Goes to the previous video (playlist mode) */
function goto_previous_video()
{
	if (may_I_reload() == true && being_redirected == false && ((video_is_first == true && GetCookie('playlist_loop') == 1) || video_is_first != true))
	{
		being_redirected = true;

		window.location.href = '/video/' + channel_items[getPreviousItemInList(channel_items, video_sig)] + '.html#' + channel_sig;
	}
}

/* Goes to the next video (playlist mode) */
function goto_next_video()
{
	if(may_I_reload() == true && being_redirected == false && ((video_is_last() == true && GetCookie('playlist_loop') == 1) || video_is_last() != true))
	{
		being_redirected = true;

		var next_sig = false;

		if (typeof(channel_items) == 'object' && channel_items != null)
		{
			// channel_items is populated by ajax query (dynamic channel)
		    next_sig = channel_items[getNextItemInList(channel_items, video_sig)];
		}
		else
		{
			// channel_items is populated by the main entry point of the channel (/channel/)
			var second_item_href = $('.playlist_roll div:nth-child(2) a').attr('href');
			if (!!second_item_href)
			{
                var regexp = new RegExp('(.*)/video/(.*)\.html#(.*)', 'gi');
				regexp = regexp.exec(second_item_href);

				if (regexp != null && typeof(regexp[2]) != 'undefined')
				{
	    			next_sig = regexp[2];
				}
			}
		}

		if (next_sig !== false)
		{
			window.location.href = '/video/' + next_sig + '.html#' + channel_sig;
		}
		else
		{
			window.location.reload();
		}
	}
}

function may_I_reload()
{
	if (document.forms['form_comment'])
	{
		if(
			document.getElementById('add_to_channel').style.visibility == 'visible' ||
			document.getElementById('share_friends_player').style.visibility == 'visible' ||
			document.forms['form_comment'].comment_title.value != '' ||
			document.forms['form_comment'].comment_description.value != '')
		{
			if(window.confirm(JST_MAY_NO_RELOAD))
				return true;
			else
				return false;
		}
	}
	return true;
}


function videosTab()
{
	if((document.getElementById('tab_li_channels'))||(document.getElementById('tab_li_plustab')))
	{
		document.getElementById('tab_li_videos').className = 'here';
		document.getElementById('tab_div_videos').style.display = 'block';

		if(document.getElementById('tab_li_channels'))
		{
			document.getElementById('tab_li_channels').className = '';
			document.getElementById('tab_div_channels').style.display = 'none';
	
		}
	
		if(document.getElementById('tab_li_plustab'))
		{
			document.getElementById('tab_li_plustab').className = '';
			document.getElementById('tab_div_plus').style.display = 'none';
		}
	}

}

function channelsTab()
{
	if((document.getElementById('tab_li_videos'))||(document.getElementById('tab_li_plustab')))
	{
		document.getElementById('tab_li_channels').className = 'here';
		document.getElementById('tab_div_channels').style.display = 'block';
		if(document.getElementById('tab_li_videos'))
		{
			document.getElementById('tab_li_videos').className = '';
			document.getElementById('tab_div_videos').style.display = 'none';
		}

		if(document.getElementById('tab_li_plustab'))
		{
			document.getElementById('tab_li_plustab').className = '';
			document.getElementById('tab_div_plus').style.display = 'none';
		}
	}
}

function plusTab()
{
	if((document.getElementById('tab_li_videos'))||(document.getElementById('tab_li_channels')))
	{
		document.getElementById('tab_li_plustab').className = 'here';
		document.getElementById('tab_div_plus').style.display = 'block';
		if(document.getElementById('tab_li_channels'))
		{
			document.getElementById('tab_li_channels').className = '';
			document.getElementById('tab_div_channels').style.display = 'none';
		}
	
		if(document.getElementById('tab_li_videos'))
		{
			document.getElementById('tab_li_videos').className = '';
			document.getElementById('tab_div_videos').style.display = 'none';
		}
	
	}
}

/* State can be:
	- on
	- off */
function setPlayerMute(state)
{
	SetCookie('player_mute', state);
}

function setPlayerVolume(volume)
{
	SetCookie('player_volume', volume);
}

function getPlayerVolumeMute()
{
	volume = GetCookie('player_volume');
	mute = GetCookie('player_mute')

	if(volume && volume != null)
		flash_parameters["player_volume"] = volume;
	if(mute && mute != null)
		flash_parameters["player_mute"] = mute;
}



function loopMode(state)
{
	if(state == 1)
	{
		document.getElementById('loopOn').className = 'loop_active';
		document.getElementById('loopOff').className = 'loop_inactive';
	}
	else
	{
		document.getElementById('loopOn').className = 'loop_inactive';
		document.getElementById('loopOff').className = 'loop_active';
	}

	SetCookie('playlist_loop', state);
}


/* Temp function */
/* Patch for flash player */
function isLoggedIn(next_func, params)
{
		var func = function()
		{
			next_func(params);
		}
		func()
}


	// Counts the number of description
	function countComment(maxlength)
	{
		// Gets the field's value
//		texti = document.getElementById('comment_description').value
		texti = document.form_comment.comment_description.value
		// Counts the length
		nb_chars = texti.length

		// If limit reached
		if(nb_chars > maxlength)
		{
			// Cuts the text
			texti = texti.substring(0, maxlength)
			// Changes the field value
//			document.getElementById('comment_description').value = texti
			document.form_comment.comment_description.value = texti
		}

		//alert(document.getElementById('video_description').scrollHeight)
//		document.getElementById('comment_description').scrollTop = document.getElementById('comment_description').scrollHeight
		document.form_comment.comment_description.scrollTop = document.form_comment.comment_description.scrollHeight
	}

function setRegisterComment()
{
	document.form_register_comment.comment_title.value = document.form_comment.comment_title.value;
	document.form_register_comment.comment_description.value = document.form_comment.comment_description.value;
	return true;
}

function setRegisterCommentConnect()
{
	if (document.form_comment_auth.login_email.value == "" || document.form_comment_auth.login_password.value == "")
	{
		return false;
	}
	else
	{
		return true;
	}
}

function setRegisterVideoRate()
{
	document.form_register_video_rate.rating.value = hasVoted;
	return true;
}

function setRegisterVideoRateConnect()
{
	document.form_register_video_rate_connect.rating.value = hasVoted;
	if (document.form_register_video_rate_connect.login_email.value == "" || document.form_register_video_rate_connect.login_password.value == "")
	{
		return false;
	}
	else
	{
		return true;
	}
}

function  setRegisterBookmarkConnect()
{
	if (document.BookmarkConnectForm.login_email.value == "" || document.BookmarkConnectForm.login_password.value == "")
	{
		return false;
	}
	else
	{
		return true;
	}
}

function setRegisterChannel()
{
	document.form_register_channel.channel_name.value = document.getElementById('new_channel').value;
	return true;
}

function setRegisterChannelConnect()
{
	document.form_register_channel_connect.channel_name.value = document.getElementById('new_channel').value;
	if (document.form_register_channel_connect.login_email.value == "" || document.form_register_channel_connect.login_password.value == "")
	{
		return false;
	}
	else
	{
		return true;
	}
}

function returnedRateSession(response)
{

}

function BanComment(id, sig)
{
	if(window.confirm(JST_PLAYER_CONFIRM_BAN_COMMENT))
	{
		$.ajax({
			type: "GET",
			url: "/api_server/",
			data: 'action=ban_comment&id='+ id + '&sig=' + sig,
			success: function(){
				$('#article'+id).fadeOut(800);
				return false;
			}
		});
	}
}


function lodgeAbuse(sig)
{
	if (sig)
	{
		window.location.href = '/tools/abuse/?sig='+sig;
	}
}

/* Generic SSO JS's */

function saveCommentSession(callback)
{
    parameters = new Object();
	parameters['sig'] = document.getElementById('sig').value;
	parameters['comment_title'] = document.forms['form_comment'].elements['comment_title'].value;
	parameters['comment_description'] = document.forms['form_comment'].elements['comment_description'].value;
	parseResponseFunction = callback;
	runAJAX('api_server/', 'video_comment_session', parameters, 'get');
}

function moduleLoginPlayerCompletation()
{
	return  (($('#form_comment_auth input[@class*=sso_mlp_login]').val() &&
			 $('#form_comment_auth input[@class*=sso_mlp_password]').val()) ||
			 ($('#form_comment_auth TABLE').css('display') == 'none'));
}

// Clic in the "register" button
function setRegisterComment_SSO()
{
    saveCommentSession(returnedCommentRegister_SSO);

    return false;
}

// Clic in the "login" button
function setRegisterCommentConnect_SSO()
{
	if (!moduleLoginPlayerCompletation())
	{
	}
	else
	{
		saveCommentSession(returnedCommentConnect_SSO);
	}
	return false;
}

function returnedCommentRegister_SSO(response)
{
	if(response == 1)
	{
	}
	else
	{
	}

	document.getElementById('form_register_comment').submit();
}

function returnedCommentConnect_SSO(response)
{
	if(response == 1)
	{
	}
	else
	{
	}

	document.getElementById('form_comment_auth').submit();
}

// Get the index of next entry in item_list by the current_item
// If the current_item is the latest item, this function return the first item
function getNextItemInList(item_list, current_item)
{
	var find = false;

	for (var i in item_list)
	{
	    if (find)
		{
			return i;
		}
		if (item_list[i] == current_item)
		{
			find = true;
		}
	}

	// Item at end of the item_list
	for (var i in item_list)
	{
	    return i;
	}
}

// Get previous item in item_list by current_item
// If the current_item is the first item, this function return the lastest item in item_list
function getPreviousItemInList(item_list, current_item)
{
	// First position in item_list
	for (var i in item_list)
	{
		if (item_list[i] == current_item)
		{
		    var last_index = 0;
			for (var i in item_list)
			{
				last_index = i;
			}
			return last_index;
		}
		else
		{
			break;
		}
	}

	var last_index = 0;

	for (var i in item_list)
	{
	    if (item_list[i] == current_item)
		{
		    return last_index;
		}

		last_index = i;
	}
}

function validSIGExpr()
{
	return '([a-z0-9\-_]){12}';
}

// Get channel SIG from the current URL
function getChannelSIG()
{
	var url = document.location.href;

	var regexp = new RegExp('(.*)#(' + validSIGExpr() + ')(.*)', 'gi');
	regexp = regexp.exec(url);

	if (regexp != null && typeof(regexp[2]) != 'undefined' && regexp[2].indexOf('iLy') != -1)
	{
	    return regexp[2];
	}

	return false;
}

function populateChannelBlock(csig)
{
	var container = $('#playlist_bar');
    var current_item_in_playerlist = false;
    var items_count = 0;
	channel_items = {};

    $.ajax({
			type: 'GET',
			url: '/api_server/',
			data: 'action=get_channel_informations&csig=' + csig,
			dataType: 'json',
   			success: function(channel)
			{
			    // Test success
				if (typeof(channel['channel_infos']) != 'undefined' && typeof(channel['channel_items']) != 'undefined')
				{
				    // Populate channel infos
				    $('.playlist_mast', container).attr({'title': $('.playlist_mast', container).attr('title') + channel['channel_infos']['channel_creation_date']});
					$('.channel_name', container).html($('<div/>').text(channel['channel_infos']['channel_name']).html());
					$('.channel_counter', container).html(channel['channel_infos']['channel_counter']);
					$('.channel_userlink', container).html(channel['channel_infos']['owner_link'] + channel['channel_infos']['owner_username'] + '</a>');

					// Populate channel items
					for (var i in channel['channel_items'])
					{
						if (typeof(channel['channel_items'][i]['title_short']) != 'undefined')
						{
						    channel_items[i] = {};
						    channel_items[i] = channel['channel_items'][i]['sig'];

						    if ((video_sig == channel['channel_items'][i]['sig']))
						    {
						    	current_item_in_playerlist = items_count;
							}

							var video = $(	((video_sig == channel['channel_items'][i]['sig']) ?
													'<div id="playlist_detail_on">' :
													'<div class="playlist_detail">'
											) +
				    							'<a href="/video/' + channel['channel_items'][i]['sig'] + '.html#' + csig + '" title="' + htmlentities(channel['channel_items'][i]['title']) + '">' +
													'<img src="' + channel['channel_items'][i]['img'] + '" width="74" height="54" alt="' + htmlentities(channel['channel_items'][i]['title']) + '" class="playlist_detail_img" />' +
													'<br />' +
													$('<div/>').text(channel['channel_items'][i]['title_short']).html() +
												'</a>' +
											'</div>');

							$('.playlist_roll', container).append(video);

							items_count++;
						}
					}

					// Display the channel box only if the current item is present
					if (current_item_in_playerlist !== false)
					{
					    // Set channel tab width
						$('#playlist_scroll .playlist_roll').css({'width': (items_count * 140)});

						// Show the channel tab
						$(container).show('slow').slideDown('slow');

						// Scroll to the channel box
						var targetOffset = $(container).offset().top;
						$('html,body').animate({scrollTop: targetOffset}, 100);

					    // Set the cursor at the current item
					 	scroll_channel_tab(current_item_in_playerlist);

						// Insert RSS feed
						var rss_feed = $('<link rel="alternate" type="application/rss+xml" href="/channel/' + csig + '.html?format=rss" id="channelrss" title="' + htmlentities(channel['channel_infos']['channel_name']) + '" />');
						$('head').append(rss_feed);
					}
				}
			}
	});
}

/**
* Event dispatche par le composant de double click
*/
function syncRoadBlock(adTag){
	a = adTag.split(';');
	if (a.length>0)
	{
		for (x=0; x<=a.length-1; x++)
		{
			if (a[x].indexOf('sz=') == 0)
			{
				size = a[x].substring(3);
				dims = size.split('x');
				width = dims[0];
				height = dims[1];
				loadRBs(width, height, adTag);
			}
		}
	}
}
function loadRBs(w, h, adTag){
	var bannerHTML = '<iframe src="' + adTag + '" id="ifr_companion" width="'+w+'" height="'+h+'" marginwidth=0 marginheight=0 hspace=0 vspace=0 frameborder=0 scrolling=no>' + '</iframe>';
	$('div #same_topic .ad_rectangle').html(bannerHTML);
}

/**
* Event dispatche par le composant de lightningCast
*/
function loadBanner(banner,href){
	var bannerIMG = banner;
	var clickThruHref = href

	var bannerLower = bannerIMG.toLowerCase();
	var bannerHTML = bannerIMG;

	if ("" == clickThruHref || "DHTML" == clickThruHref || "null" == clickThruHref || 0 < bannerLower.indexOf(".swf")) {
		bannerHTML = '<HTML><IFRAME src="' + bannerIMG + '" frameborder="0" scrolling="no" width="300" height="250" marginwidth="0" marginheight="0"/></HTML>';
	}
	else if (0 == bannerHTML.indexOf("http")) {
		bannerHTML = '<HTML><CENTER><A HREF="' + clickThruHref + '" target="_blank"><IMG SRC="' + bannerIMG + '" border="0"></A></CENTER></HTML>';
	}
	else {
		bannerHTML = '<HTML>' + bannerIMG + '</HTML>';
	}

	$('div #same_topic .ad_rectangle').html(bannerHTML);
}


// Scroll into the channel tab to the current item
function scroll_channel_tab(to_highlight)
{
	document.getElementById('playlist_scroll').scrollLeft = ((to_highlight * 130) - 10);
}

$(document).ready(function(){
	var channel_sig_from_url = getChannelSIG();
	if (!!channel_sig_from_url)
	{
	    channel_sig = channel_sig_from_url;
	    // If have channel sig, display the channel tab
   		populateChannelBlock(channel_sig_from_url);

		/* Loop of the playlist */
		playlist_loop = GetCookie('playlist_loop');
		playlist_loop = (playlist_loop && playlist_loop != null && playlist_loop >= 0) ? playlist_loop : 1;
 		loopMode(playlist_loop)
	}

	/*$('#abuse_link').click(function(){
        window.location.href = '/tools/abuse/?sig=' + $(this).attr('class');
        return false;
	});*/

});


