/*
vrak.webtele.js
© 2009 vrak.tv
Minify with jsmin at http://jscompress.com/
*/

var webtelePath = "webtele";



// ## DHTML works - START ##

// Open list content
function openList(listId) {
		// Opens the list of videos and replaces the "+" button and javascript links
		// $("#listContent" + listId).css("display", "block");
		$("#listContent" + listId).removeClass("invisible");
		$("#listButton" + listId).attr("src", "/" + webtelePath + "/_img/icone_moins.gif");
		$("#listLink" + listId).attr("href", "javascript:closeList(" + listId + ");removeFromOpenedLists(" + listId + ");");
}

// Close list content
function closeList(listId) {
		// Closes the list of videos and replaces the "-" button and javascript links
		//$("#listContent" + listId).css("display", "none");
		$("#listContent" + listId).addClass("invisible");
		$("#listButton" + listId).attr("src", "/" + webtelePath + "/_img/icone_plus.gif");
		$("#listLink" + listId).attr("href", "javascript:openList(" + listId + ");addToOpenedLists(" + listId + ");");
}

function addToOpenedLists(listId) {
	var identifier = "-" + listId + "-";
	var openedListsCookie = $.cookie("webteleOpenedLists");
	var previousCookieValue = "";
	if (openedListsCookie) previousCookieValue = openedListsCookie;
	if (previousCookieValue.indexOf(identifier) == -1) {
		$.cookie("webteleOpenedLists", previousCookieValue + identifier, {path: '/', expires: 1});
	}
}

function removeFromOpenedLists(listId) {
	var identifier = "-" + listId + "-";
	var openedListsCookie = $.cookie("webteleOpenedLists");
	var previousCookieValue = "";
	if (openedListsCookie) previousCookieValue = openedListsCookie;
	if (previousCookieValue.indexOf(identifier) > -1) {
		$.cookie("webteleOpenedLists", previousCookieValue.replace(identifier, ""), {path: '/', expires: 1});
	}
}

// Get list of playlists to add video to
function getPlaylistsToAdd(videoId) {
	hideAllBoxes();
	var playlistsToAddHtml = "<option value=\"\">Choisis une liste</option>\n";
	checkLogin();
	if (memberLogged) {
		if (playlistArray.length > 0) {
			var availableListCount = 0;
			for (i=0; i<playlistArray.length; i++) {
				var listId = playlistArray[i][0];
				var listName = playlistArray[i][1];
				var videoIdsInPlaylist = playlistArray[i][2];
				if (videoIdsInPlaylist.indexOf("-" + videoId + "-") == -1) {
					playlistsToAddHtml += "<option value=\"" + listId + "\">" + listName + "</option>\n";
					availableListCount++;
				}
			}
			if (availableListCount != 0) {
				$("#select_playlistsToAdd" + videoId).html(playlistsToAddHtml);
				$("#btn_liste_ajouter" + videoId + "_content").removeClass("invisible");
				$("#btn_liste_ajouter" + videoId + "_saved").addClass("invisible");
				$("#btn_liste_ajouter" + videoId + "_erreur1").addClass("invisible");
				$("#btn_liste_ajouter" + videoId + "_erreur2").addClass("invisible");
				$("#btn_liste_ajouter" + videoId + "_erreur3").addClass("invisible");
				$("#btn_liste_ajouter" + videoId).removeClass("invisible");
			} else {
				$("#btn_liste_ajouter" + videoId + "_content").addClass("invisible");
				$("#btn_liste_ajouter" + videoId + "_saved").addClass("invisible");
				$("#btn_liste_ajouter" + videoId + "_erreur1").removeClass("invisible");
				$("#btn_liste_ajouter" + videoId + "_erreur2").addClass("invisible");
				$("#btn_liste_ajouter" + videoId + "_erreur3").addClass("invisible");
				$("#btn_liste_ajouter" + videoId).removeClass("invisible");
			}
		} else {
			$("#btn_liste_ajouter" + videoId + "_content").addClass("invisible");
			$("#btn_liste_ajouter" + videoId + "_saved").addClass("invisible");
			$("#btn_liste_ajouter" + videoId + "_erreur1").addClass("invisible");
			$("#btn_liste_ajouter" + videoId + "_erreur2").removeClass("invisible");
			$("#btn_liste_ajouter" + videoId + "_erreur3").addClass("invisible");
			$("#btn_liste_ajouter" + videoId).removeClass("invisible");
		}
	} else {
		$("#btn_liste_ajouter" + videoId + "_content").addClass("invisible");
		$("#btn_liste_ajouter" + videoId + "_saved").addClass("invisible");
		$("#btn_liste_ajouter" + videoId + "_erreur1").addClass("invisible");
		$("#btn_liste_ajouter" + videoId + "_erreur2").addClass("invisible");
		$("#btn_liste_ajouter" + videoId + "_erreur3").removeClass("invisible");
		$("#btn_liste_ajouter" + videoId).removeClass("invisible");
	}
}

// Add video to list
function addVideoToList(listId, videoId) {
	// Ajax video and list id
	var ieRant = Math.floor(Math.random()*1000001); // Generate random so that this f***ing IE browser does not cache xml response
	$.ajax({
		type: "POST",
		url: "/" + webtelePath + "/_dyn/addVideoToList.jsp",
		data: "listId=" + listId + "&videoId=" + videoId + "&ieRant=" + ieRant,
		dataType: "xml",
		success: function(xml) {
			$("#btn_liste_ajouter" + videoId + "_content").addClass("invisible");
			$("#btn_liste_ajouter" + videoId + "_saved").removeClass("invisible");
			addToOpenedLists(listId);
			getMemberPlaylists();
		}
	});
}

function checkOpenedLists() {
	var openedListsCookie = $.cookie("webteleOpenedLists");
	if (openedListsCookie) {
		var listIds = openedListsCookie.split("-");
		for (i=0; i<listIds.length; i++) openList(listIds[i]);
	}
	$("#listBox1").removeClass("invisible");
	$("#listBox2").removeClass("invisible");
}

function showInfo(divId) {
	hideAllBoxes();
	$("#" + divId).removeClass("invisible");
}

function hideAllInfoBoxes() {
	var temp = videoIds.split(",");
	for (i=0; i<temp.length; i++) {
		$("#info_" + temp[i]).addClass("invisible");
	}
}

function toggleFaveType(listType) {
	if (listType == "enVedette") {
		$("#enVedette").css("display", "block");
		$("#listeLecture").css("display", "none");
	} else {
		$("#enVedette").css("display", "none");
		$("#listeLecture").css("display", "block");
	}
}

function toggleVideoType(listType) {
	if (listType == "plusAimees") {
		$("#plusAimees").css("display", "block");
		$("#plusCommentees").css("display", "none");
	} else {
		$("#plusAimees").css("display", "none");
		$("#plusCommentees").css("display", "block");
	}
}

// ## DHTML works - END ##



// ## Member functions - START ##

// Get votes
function getVotes() {
	var ieRant = Math.floor(Math.random()*1000001); // Generate random so that this f***ing IE browser does not cache xml response
	$.ajax({
		type: "GET",
		url: "/" + webtelePath + "/_dyn/getVoteCountForVideo.jsp",
		data: "videoId=" + videoId + "&ieRant=" + ieRant,
		dataType: "xml",
		success: function(xml) {
			var points = $(xml).find("points").text();
			$("#voteCount").html(points);
		}
	});
}

// Check if already voted
function checkIfVoted() {
	var voteCookie = "";
	var alreadyVoted = false;
	if ($.cookie("webteleVote") != null) {
		voteCookie = $.cookie("webteleVote");
		alreadyVoted = voteCookie.indexOf("-" + videoId + "-") > -1;
	}
	if (alreadyVoted) {
		$("#voteLoading").removeClass();
		$("#voteLoading").addClass("invisible");
		$("#voteOff").removeClass();		
	} else {
		$("#voteLoading").removeClass();
		$("#voteLoading").addClass("invisible");
		$("#voteOn").removeClass();		
	}
}

// Add vote
function addVote() {
	var ieRant = Math.floor(Math.random()*1000001); // Generate random so that this f***ing IE browser does not cache xml response
	$.ajax({
		type: "POST",
		url: "/" + webtelePath + "/_dyn/addVoteForVideo.jsp",
		data: "videoId=" + videoId + "&ieRant=" + ieRant,
		dataType: "xml",
		success: function(xml) {
			$("#voteOn").removeClass();
			$("#voteOn").addClass("invisible");
			$("#voteDone").removeClass();			
			getVotes();
		}
	});
}

// Save comment
/*
function saveComment(commentTitle, commentText) {

	var commentError = "";
	if ($.trim(commentTitle) == "" || $.trim(commentTitle) == "Inscris un titre...") {
		commentError += "<div class=\"bold rouge\">Tu dois entrer un titre.</div>";
	}
	if ($.trim(commentText) == "") {
		commentError += "<div class=\"bold rouge\">Tu dois entrer un texte.</div>";
	} else if (commentText.length > 990) {
		commentError += "<div class=\"bold rouge\">Ton texte doit faire 1000 caractères maximum.</div>";
	}

	if (commentError == "") {

		// Temporary spinning loader
		$("#commentBox").removeClass("block");
		$("#commentBox").addClass("invisible");
		$("#commentBoxLoading").removeClass("invisible");
		$("#commentBoxLoading").addClass("block");

		// Ajax the comment if form OK
		var ieRant = Math.floor(Math.random()*1000001); // Generate random so that this f***ing IE browser does not cache xml response
		$.ajax({
			type: "POST",
			url: "/" + webtelePath + "/_dyn/saveCommentForVideo.jsp",
			data: "videoId=" + videoId + "&commentTitle=" + commentTitle + "&commentText=" + commentText + "&ieRant=" + ieRant,
			dataType: "xml",
			error: function() {
				$("#commentBox").html("Une erreur c'est produite en soumettant le commentaire, envoie une message au webmestre avec le plus de détails possible. Merci!");
				$("#commentBox").removeClass("invisible");
				$("#commentBox").addClass("block");
				$("#commentBoxLoading").removeClass("block");
				$("#commentBoxLoading").addClass("invisible");
			},
			success: function(xml) {
				var ajaxError = $(xml).find("error").text();
				if (ajaxError == '') {
					$("#commentBoxDone").removeClass("invisible");
					$("#commentBoxDone").addClass("block")
					$("#commentBoxLoading").removeClass("block");
					$("#commentBoxLoading").addClass("invisible");
				} else {
					$("#commentBox").html("Erreur : " + ajaxError);
					$("#commentBox").removeClass("invisible");
					$("#commentBox").addClass("block");
					$("#commentBoxLoading").removeClass("block");
					$("#commentBoxLoading").addClass("invisible");
				}
			}
		});
	} else {
		// Display error : missing stuff
		$("#commentError").html(commentError);
		$("#commentError").css("display", "block");
	}
	return false;
}
*/

// Flag as offensive
function flagAsInappropriate(commentId) {

	// Temporary spinning loader
	$("#bouton_achtung_" + commentId).html("<img src='/_img/loading_orange.gif' width='16' height='16' alt='Loading...' />");

	var ieRant = Math.floor(Math.random()*1000001); // Generate random so that this f***ing IE browser does not cache xml response
	$.ajax({
		type: "POST",
		url: "/" + webtelePath + "/_dyn/flagCommentAsInappropriate.jsp",
		data: "commentId=" + commentId + "&ieRant=" + ieRant,
		dataType: "xml",
		error: function() {
			$("#message_achtung_" + commentId).html("Doh! Some kind of error occured on the server side!");
		},
		success: function(xml) {
			var ajaxError = $(xml).find("error").text();
			if (ajaxError == '') {
				$("#message_achtung_" + commentId).removeClass("invisible");
				$("#message_achtung_" + commentId).addClass("block");
				$("#bouton_achtung_" + commentId).removeClass("block");
				$("#bouton_achtung_" + commentId).addClass("invisible");
				$("#commentText_" + comment.id).addClass("invisible");
			} else {
				$("#message_achtung_" + commentId).html("Erreur : " + ajaxError);
			}
		}
	});

}

// Check login
var memberLogged = false;
var memberId = 0;
var memberUsername = "";
function checkLoginForComments() {
	var ieRant = Math.floor(Math.random()*1000001); // Generate random so that this f***ing IE browser does not cache xml response
	$.ajax({
		type: "GET",
		url: "/" + webtelePath + "/_dyn/checkLogin.jsp",
		data: "ieRant=" + ieRant,
		dataType: "xml",
		success: function(xml) {
			memberLogged = ($(xml).find("logged").text() == "true");
			if (memberLogged) {
				memberId = Number($(xml).find("id").text());
				memberUsername = $(xml).find("username").text();
				$("#loginOrCommentLoader").removeClass("block");
				$("#loginOrCommentLoader").addClass("invisible");
				$("#commentBox").removeClass("invisible");
				$("#commentBox").addClass("block");
			} else {
				$("#loginOrCommentLoader").removeClass("block");
				$("#loginOrCommentLoader").addClass("invisible");
				$("#commentLoginBox").removeClass("invisible");
				$("#commentLoginBox").addClass("block");
			}
		}
	});
}
function checkLogin() {
	var ieRant = Math.floor(Math.random()*1000001); // Generate random so that this f***ing IE browser does not cache xml response
	$.ajax({
		type: "GET",
		url: "/" + webtelePath + "/_dyn/checkLogin.jsp",
		data: "ieRant=" + ieRant,
		dataType: "xml",
		success: function(xml) {
			memberLogged = ($(xml).find("logged").text() == "true");
			if (memberLogged) {
				memberId = Number($(xml).find("id").text());
				memberUsername = $(xml).find("username").text();
			}
		}
	});
}

// ## Member functions - END ##



// ## Misc. AJAX calls - START ##

function loadEpisodeSelect(programId, episodeId) {
	var maxChar=25;
	//if (programId > 0) {
		$.ajax({
			type: "GET",
			url: "/_dyn/getEpisodesXml.jsp",
			data: "programId=" + programId + "&episodeId=" + episodeId,
			dataType: "xml",
			success: function(xml) {
				var _select = document.getElementById('episodeId');
				// Clear the list
				for (var i=_select.length-1; i>-1; i--) _select.options[i] = null;
				$(xml).find('episode').each(function(){
					// Get values from XML
					var _id = $(this).attr('id');
					var _selected = $(this).attr('selected');
					var _name = $(this).text();
					if(_name.length>maxChar){
						_name=_name.substring(0,maxChar)+'...';
					}
					// Build new option list
					var _option;
					if (_selected == '1') _option = new Option(_name, _id, false, true);
					else _option = new Option(_name, _id, false, false);
					_select.options[_select.length] = _option;
				});
			}
		});
	/*} else {
		$("#episodeId").removeOption(/./);
		$("#episodeId").addOption("0", "Choisis une émission avant");
	}*/
}

// ## Misc. AJAX calls - END ##

// ## Thickbox mini call, exists for search engines - START ## //

function goThickBox(title, url) {
	$(document).ready(function(){
		tb_show(title, url, null);
	});
}

// ## Thickbox mini call, exists for search engines - END ## //




// On print le bandeau compteur
function printBandeauCompteur(div, totalVideos) {
	// Print flash video count
	$(div).flash(	{
		src: '/flashs/BandeauCompteur/BandeauCompteur.swf', width: 458, height: 101, bgcolor: '#ffffff', quality: 'high', menu: false, wmode: 'transparent', swliveconnect: 'true', allowScriptAccess: 'always', allowFullScreen: true, flashvars: {
			videoCount: totalVideos
		}
	},
	{ version: '9.0.115' }
	);
}



// ## Fonctions reliées au player - START ##

function printPlayer(divId, flashSource, width, height, playerParameters)
{
	// On definit les paramètres du flash
	var flashParams = {
		bgColor: "#000000",
		quality: "high",
		wmode: "transparent",
		swliveconnect: "true",
		allowScriptAccess: "always",
		allowFullScreen: true
	};

	// On definit les attributs de l'objet html du flash
	var flashHtmlAttributes = {
		id: "playerVrak"
	};

	swfobject.embedSWF(flashSource, divId, width, height, "9.0.115", "/_img/expressInstall.swf", playerParameters, flashParams, flashHtmlAttributes);
}

function showPreRoll() {
	var preRollInterval = 2;
	if ((parseInt(getPreRollCookieValue())%preRollInterval) == 0) {
		incPreRollCookieValue();
		return true;
	} else {
		incPreRollCookieValue();
		return false;
	}
}

function getPreRollCookieValue() {
	var value = 0;
	var preRollCookie = $.cookie("preRollCookie");
	if (preRollCookie) value = parseInt(preRollCookie);
	return value;
}

function incPreRollCookieValue() {
	var previousValue = 0;
	var preRollCookie = $.cookie("preRollCookie");
	if (preRollCookie) {
		previousValue = parseInt(preRollCookie);
	} else {
		previousValue = 0;
	}
	var newValue = previousValue + 1;

	var date = new Date();
	date.setTime(date.getTime() + (1 * 24 * 60 * 60 * 1000));
	date.setHours(0);
	date.setMinutes(0);
	date.setSeconds(0);
	$.cookie("preRollCookie", newValue, {path: '/', expires: date});
}

// Fonction qui sert à obtenir le timeZone de l'usager
function getUserTimeZone() {
	var timeZone = new Date().getTimezoneOffset()/60*-1;
	return (timeZone);
}

// DART ads - START
function multiTagSyncRoadBlock(div, 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');
				height = dims[0];
				width = dims[1];
				loadRBs(div,height,width,adTag);
			}
		}
	}
}

function syncRoadBlock(adTag) {
	multiTagSyncRoadBlock('myAd1', adTag);
}

function loadRBs(s,w,h,adTag) {
	document.getElementById(s).innerHTML = '<iframe src="' + adTag + '" id="ifr_companion" width="'+w+'" height="'+h+'" marginwidth=0 marginheight=0 hspace=0 vspace=0 frameborder=0 scrolling=no>' + '</iframe>';
}
// DART ads - END

// ## Fonctions reliées au player - END ##

