var series = null, seriesLow = [], images = null, downloaded = 0, totalSize = 0;
var blocList = [], picArray = [], blocHTML = "", serialize = '';

var effets = 1, numCol = 2, maxBlocHeight = 392;
var closeimgMetallic = '<img src="data/images/exitm.gif" onmouseover="this.src=\'data/images/exitb.gif\'" onmouseout="this.src=\'data/images/exitm.gif\'" />';

var suggestionPos = 0, oldsuggestionPos = 0, Match = 0, stickyDate = false;
var maxSuggestion = -1;
var menuActif = false;

pic1 = new Image(); 
pic1.src = 'theme/images/ui-bg_gloss-wave_55_5c9ccc_500x100.png';
pic2 = new Image(); 
pic2.src = 'theme/images/ui-bg_highlight-soft_100_eeeeee_1x100.png';
pic3 = new Image(); 
pic3.src = 'theme/images/ui-bg_highlight-soft_25_5A9D1A_1x100.png';
pic4 = new Image(); 
pic4.src = 'theme/images/theme/images/ui-icons_808080_256x240.png';
pic5 = new Image(); 
pic5.src = 'theme/images/theme/images/ui-icons_ffffff_256x240.png';

var isIE7 = ( jQuery.browser.msie && jQuery.browser.version < 8.0 );
var chatLoaded = false;

/*===================================
|| Initialise l'interface d'Arcadya ||
====================================*/

$(document).ready(function ()
{
	if( jQuery.browser.msie && jQuery.browser.version < 7.0 )
		alert( 'Internet Explorer 6 n\'est pas compatible avec Arcadya.\nMerci de mettre à jour votre navigateur.' );
		
	var height = ( window.ActiveXObject ? document.documentElement.clientHeight : window.innerHeight );
	$('#infoProgress').css('top', Math.floor( height / 2 ) - 40 ).show();
	$('#progressbar').css('top', Math.floor( height / 2 ) - 20);
	$("#progressbar").progressbar( ).children().css('background','#5c9ccc url(theme/images/ui-bg_gloss-wave_55_5c9ccc_500x100.png) 50% 50% repeat-x').css('border-color','#4297d7');

	$.ajax( { async: false, dataType: 'json', global: false, url: 'init.php',
		success: function(data)
		{
			blocHTML = data.bloc;
			alias=data.alias;
			images=data.images;
			series=data.noms;
			for( var i=0; i < series.length; ++i )
				seriesLow[i] = series[i].toLowerCase();

			$('#seriesDiv').next().html(data.series).find( 'li li').bind( 'click', function(){ add( $(this).text() ); } );
			$('#series_endedDiv').next().html(data.seriesEnd).find( 'li li').bind( 'click', function(){ add( $(this).text() ); } );
		} } );
	
	for( x in images ){ totalSize += images[x][1]; } //dans une boucle à part sinon bug IE
	
	
	if( location.search == '?preload=false' )
		endInit();
	else
	{
		for( x in images )
		{
			var pic = new Image();
			
			if( !isIE7 )
			{
				pic.onload = checkPreloading;
				pic.onerror = checkPreloading;
			}
			pic.nom = images[x][0];
			pic.taille = images[x][1];
			
			pic.src = 'data/images/' + images[x][0];
		}
		
		if( isIE7 ) //le préchargement ne marche pas correctement sous IE7
			endInit();
	}
});



/*======================================
|| Vérifie le préchargement des images ||
=======================================*/

function checkPreloading()
{
	downloaded += this.taille;
	
	$("#progressbar").progressbar( 'value', Math.floor(downloaded  * 100 / totalSize) );
	$("#fichier").html( this.nom );
	
	if( downloaded == totalSize )
		endInit();
}


/*=================================
|| Termine l'initialisation de l'interface d'Arcadya ||
==================================*/
var tempWrap = null, posTop = 'false';
function endInit()
{
	if( isIE7 )
		$('.colonne').bind( 'mousedown', function(e){ return false; } ).sortable( {items: '.bloc' , placeholder: 'sortHelper', forcePlaceholderSize: true, connectWith: ['.colonne'], cursor:'move', handle:'.handle', distance:'6', tolerance: 'pointer' } );
	else
		$('.colonne').bind( 'mousedown', function(e){ return false; } ).sortable( {items: '.bloc' , placeholder: 'sortHelper', forcePlaceholderSize: true, connectWith: ['.colonne'], cursor:'move', opacity:0.6, handle:'.handle', distance:'6', tolerance: 'pointer' } );

	$('.highlightL').bind('click', function(){ return afficher(this.getAttribute('page')); } );
	$(document).bind('click', function()
							{
								clearSuggestion();
								if(stickyDate)
								{
									stickyDate = false;
									cClick();
								}
								
								if( menuActif == true )
								{
									clearMenu();
									menuActif = false;
								}
							} );
	$('#go').bind( 'click', function(){ add( $('#saisie').val() ); } );
	$('#suggestion').bind( 'mouseover', function()
							{
								$('#suggestion > li').eq(oldsuggestionPos).removeClass('suggestHover').addClass('suggest');
								$('#suggestion > li').eq(suggestionPos).removeClass('suggest').addClass('suggestHover');
							} );
				
	setOnlineStatus();				
	arcadyaLogin(true);
	$('body').children().slice(0,3).remove();
	$('body div').show();
	$('#saisie').focus().css('font-style','italic').val("Veuillez lire l'aide attentivement").one('click',function(){ if($('#saisie').css('font-style') == 'italic') $('#saisie').val('').css('font-style','');})
			.one('keydown',function(){ if($('#saisie').css('font-style') == 'italic') $('#saisie').val('').css('font-style','');}).bind( 'keydown', function(event){return handleKeys(event);} )
			.bind( 'keyup', function(event){autocompletion(event);} );
}


/*=======================================================================
|| Ouvre un nouveau bloc/rafraichit un existant/affiche l'icone d'erreur ||
=========================================================================*/

function handleResult(xhr,status)
{
	$('#loading').css('visibility','hidden');
	var response = xhr.responseText.split('@');
	if( status == 'success' && response[1] && response[2] )
	{
		if( !xhr.onLoad )
			$('#saisie').val('');
	
		$('#status').attr('src','data/images/success.png');
		var heightCol1 = 0, heightCol2 = 0, heightCol3 = (numCol == 3 ? 0 : 9999 );
		$('.colonne:eq(0) > div:visible').each( function(){ heightCol1 += $(this).height(); } );
		$('.colonne:eq(1) > div:visible').each( function(){ heightCol2 += $(this).height(); } );
		if( numCol == 3 ) $('.colonne:eq(2) > div:visible').each( function(){ heightCol3 += $(this).height(); } );

		var minHeight = Math.min( heightCol1, heightCol2 );
		minHeight = Math.min( minHeight, heightCol3 );

		var colonne;
		if( minHeight == heightCol1 )
			colonne = $('.colonne:eq(0)');
		else if( minHeight == heightCol2 )
			colonne = $('.colonne:eq(1)');
		else
			colonne = $('.colonne:eq(2)');
		
		if( document.getElementById( 'bloc'+xhr.id ) )
		{
			if( response[1] == 'Calendrier' )
			{
				$('#bloc'+xhr.id ).addClass('bloc').datepicker({onChangeMonthYear: function(year,month)
																				{
																					var cal = $(this);
																					getDates(month,year,cal);
																				} } ).children(':first').addClass('datepicker').children(':first').children(':last').addClass('handle');
			}
			else
			{
				$('#bloc'+xhr.id ).find('.blocTitle').html( response[1] );
				$('#bloc'+xhr.id ).find('.contentM').html( response[2] );
				$('#bloc'+xhr.id+' .accordion').accordion({ header: "h3", autoHeight: false, alwaysOpen: false, active: xhr.active }).find('h3').bind('click',function(){ $(this).parent().find('.ui-accordion-content:hidden').prev().removeClass('ui-state-focus') } );
			
				if( $('#bloc'+xhr.id ).css('display') == 'none' )
					showBlock( 'bloc'+xhr.id, xhr.onLoad );
			}
		}
		else
		{
			if( response[1] == 'Calendrier' )
			{
				colonne.prepend( response[2] );
				colonne.find('.calendar:first').attr('id','bloc'+xhr.id).hide().addClass('bloc').datepicker( {onChangeMonthYear: function(year,month)
																				{
																					var cal = $(this);
																					getDates(month,year,cal);
																				} } ).children(':first').addClass('datepicker').children(':first').children(':last').addClass('handle');
				
				if( effets == 1 )
					$('#bloc'+xhr.id).fadeIn('slow');
				else
					$('#bloc'+xhr.id).show();
			}
			else
			{
				var part6, part7;
				if( response[0] == '1' ) //minimized
				{
					part7 = blocHTML.part7min;
					part8 = blocHTML.part8min;
				}
				else
				{
					part7 = blocHTML.part7;
					part8 = blocHTML.part8;
				}
				
				colonne.prepend( blocHTML.part1 + xhr.id + blocHTML.part2 + xhr.id + blocHTML.part3 + xhr.id + blocHTML.part4 + xhr.id + blocHTML.part5 + response[1] + blocHTML.part6 + xhr.id + part7 + xhr.id + part8 + maxBlocHeight + blocHTML.part9 + response[2] + blocHTML.part10 );
				$('#bloc'+xhr.id+' .accordion').accordion({ header: "h3", autoHeight: false, alwaysOpen: false, active: xhr.active }).find('h3').bind('click',function(){ $(this).parent().find('.ui-accordion-content:hidden').prev().removeClass('ui-state-focus') } );
				showBlock( 'bloc'+xhr.id, xhr.onLoad );
			}
			
			$('#saisie').focus();
		}
	}
	else
		$('#status').attr('src','data/images/error.png');

	setTimeout( "$('#status').css('visibility','visible')", 50 );
}


/*=====================================
|| Gère l'affichage des icones de la barre des tâches ||
======================================*/
			
function afficher(page)
{
	switch( page )
	{
		case 'forum':
			return window.open( 'http://www.arcadya.net/forum/' ); break;

		case 'agt':
			return window.open( 'http://agt.arcadya.net/' ); break;
			
		case 'chat':
			add('chat'); break;
			//return window.open( 'http://www.arcadya.net/forum/chat/' ); break;
			
		case 'aide':
			$.get( 'aide.php', function (data, textStatus){ popupData( 'Aide', data ) }, 'html' ); break;
			
		case 'login':
		{
			$.get( 'login.txt?v=2', function (data, textStatus){ popupData( 'Connexion', data ) }, 'html' );
			setTimeout( function(){ $('#userInput').focus() }, 500 ); break;
		}
		
		case 'logout':
		{
			$.get( 'logout.php', function()
								{
									if(readCookie('arcId'))
										eraseCookie( 'arcId' ); //IE8 fix
									
									if(readCookie('arcPw'))
										eraseCookie( 'arcPw' ); //IE8 fix
										
									if(readCookie('arcCl'))
										eraseCookie( 'arcCl' ); //IE8 fix
									
									$('#logout').css('visibility','hidden').attr('src', 'data/images/login.png').attr('id', 'login').attr('title','Connexion').css('visibility','visible')
									.unbind().bind('click', function(){ afficher('login'); return false; } ); 
									
									$('.split2,.split3,.notice-wrap').remove();
									$('#staticContent').after('<div class="split2"><div class="colonne"></div></div><div class="split2"><div class="colonne"></div></div>');
									
									if( isIE7 )
										$('.colonne').bind( 'mousedown', function(e){ return false; } ).sortable( {items: '.bloc' , placeholder: 'sortHelper', forcePlaceholderSize: true, connectWith: ['.colonne'], cursor:'move', handle:'.handle', distance:'6', tolerance: 'pointer' } );
									else
										$('.colonne').bind( 'mousedown', function(e){ return false; } ).sortable( {items: '.bloc' , placeholder: 'sortHelper', forcePlaceholderSize: true, connectWith: ['.colonne'], cursor:'move', opacity:0.6, handle:'.handle', distance:'6', tolerance: 'pointer' } );
								});
			$('[page="notes"]').remove(); 
			
			break;
		}
	
		case 'options':
		{
			if( readCookie('arcId') )
			{
				$.post( 'options.php', {Action: '_display'}, function (data)
				{
					var result = data.split('|');
					if( result[0] == 'success' )
					{
						popupData( 'Préférences utilisateurs', result[1] );  
						if( screen.width > 1400 )
							document.getElementById('opt_col3').disabled = false;
							
						if( jQuery.browser.opera )
							$('.oltxt :checkbox').css('top','-1px');
					}
					else
						popupData( 'Préférences utilisateurs', 'Erreur lors de la tentative d\'accès à la base de données.' );  
					
				}, 'html' ); 
			}
			else
				popupData( 'Préférences utilisateurs', 'Vous devez d\'abord vous connecter.' );
				
			break;
		}
			
		case 'seriesFav':
		{
			if( readCookie('arcId') )
				showMenu( '#favoritesDiv' );
			else
				popupData( 'Séries favorites', 'Vous devez d\'abord vous connecter.' );
			break;
		}
		
		case 'seriesEnCour':
			showMenu( '#seriesDiv' ); break;
			
		case 'seriesTermine':
			showMenu( '#series_endedDiv' ); break;
			
		case 'rss':
		{
			if( readCookie('arcId') )
			{
				$('#rssMenu').html('<li onclick="location.href=\'rss.php?u='+readCookie('arcId')+'&type=VF\'"><div>Srt VF</div></li><li onclick="location.href=\'rss.php?u='+readCookie('arcId')+'&type=VO\'"><div>Srt VO</div></li><li onclick="location.href=\'rss.php?u='+readCookie('arcId')+'&type=SRT\'"><div>Srt VF/VO</div></li><li onclick="location.href=\'rss.php?u='+readCookie('arcId')+'&type=EP\'"><div>Episodes</div></li>');
				showMenu( '#rssDiv' );
			}
			else
				popupData( 'Flux RSS', 'Vous devez vous connecter la première fois pour avoir accès aux flux RSS.' );
			break;
		}
		
		case 'notes':
		{
			$.get( 'notes.php', function (data, textStatus)
							{
								if( data.length != 5 )
								{
									popupData( 'Ajouter une note', data );
									setTimeout( function(){ $('#Titre').focus(); }, 500 );
									$('#overDiv button').eq(0).bind( 'click', function(){ jQuery.noticeAdd({ effects: effets, username: $('#usr').val(), title: $('#Titre').val(), text: $('#Message').val().replace( /\n|\r|\r\n/gi, '<br>') }); $(this).next().attr('disabled',''); } );
									$('#overDiv button').eq(1).bind( 'click', function(){ $.post( 'notes.php', { Titre: $('#Titre').val(), Message: $('#Message').val(), Duree: $('#Duree :selected').text() }, function(){ cClick(); } ); } );
								}
							}, 'html' ); break;
		}
	
		case 'upload':
		{
			if( readCookie('arcId') )
			{
				$.get( 'upload.php', function(data, textStatus)
								{
									if( data.length != 5 )
									{
										popupData( 'Partage de fichiers', data );
										if( jQuery.browser.opera )
										{
											$('#overDiv input:eq(0)').attr('size','72');
											$('#filesList').css('width','502px');
										}
									}
								}, 'html' ); 
			}
			else			
				popupData( 'Partage de fichiers', 'Vous devez être connecté pour pouvoir uploader des fichiers.' );
				
			break;
		}
		
		case 'snapshot':
		{
			if( !readCookie('arcId') )
			{
				popupData( 'Sauvegarde de l\'arrangement des blocs', 'Vous devez être connecté pour sauvegarder la position des blocs.' );
				break;
			}
			
			var emptyCol = true;
			serialize = '';
			$('.colonne').each( function()
						{
								var emptyCol = true;
								$(this).find('.bloc:visible').each( function()
																	{
																		emptyCol = false;
																		if( $(this).hasClass( 'calendar' ) )
																			serialize += 'cal';
																		else
																		{
																			if( $(this).find('.contentL').css('display') == 'none' )
																				serialize += '#';
															
																			var cmdTemp = blocList[this.id.substr(4)];
																			var tmp;
																			if( cmdTemp.substr(0,3) == '%23' )
																				tmp = cmdTemp.substr(3);
																			else 
																				tmp =  cmdTemp;

																			if( tmp.substr( tmp.length - 4, 3) == '%3B' )
																				serialize +=  tmp.substr(0, tmp.length - 4);
																			else
																				serialize +=  tmp;
																			
																			$(this).find('[role="tabpanel"]').each( function(i){ if( $(this).css('display') == 'block' ) serialize += ';' + i; } );
																		}
																		
																		serialize += '|';
																	} );
								
								if( !emptyCol )
									serialize = serialize.substr( 0, serialize.length - 1);
									
								serialize += '&';
						} );
			$.post( 'options.php', { Action: '_load', onLoad: serialize.substr( 0, serialize.length - 1) }, function(data)
									{
										if( data == 'success' )
											popupData( "Sauvegarde des blocs", "Sauvegarde effectuée avec succès.", 800 );
										else
											popupData( "Sauvegarde des blocs", "Une erreur s'est produite. Merci de bien vouloir réessayer.", 1400 );	
										
									}, 'html' ); break;
		}
	}

	return false;
}


/*====================
|| Gère l'affichage des popup ||
=====================*/

function popupData( title, content, timeout )
{
	var isDiv = content.substr(1,3) == 'div';
	content = '<span>'+content+'</span>';
	
	stickyDate = false;
	if( typeof(timeout) == 'number')
		overlib( content, CAPTION, title, CAPTIONPADDING, 4, TEXTPADDING, 8, CGCLASS,'olraisedMetallic', CLOSETEXT, closeimgMetallic, CLOSECLICK, CAPTIONFONTCLASS, 'olcapMetallic', FGCOLOR, '#eeeeee',TEXTFONTCLASS,'oltxt', MIDX,0, MIDY,0, WRAP, BGCOLOR,'#666666', NOCLOSE, TIMEOUT, 1100  );
	else				
		overlib( content, STICKY, CAPTION, title, CAPTIONPADDING, 4, TEXTPADDING, 8, CGCLASS,'olraisedMetallic', CLOSETEXT, closeimgMetallic, CLOSECLICK, CAPTIONFONTCLASS, 'olcapMetallic', FGCOLOR, '#eeeeee',TEXTFONTCLASS,'oltxt', MIDX,0, MIDY,0, WRAP, BGCOLOR,'#666666', MODAL, CLOSETITLE, 'Fermer', STATUS, 'Cliquez sur la croix en haut à droite pour revenir au site' );

	if( content.substr(1,3) == 'div' )
		var width = $('.oltxt > span:first').width();
	else
		var width = $('.oltxt > span:first').width() + 20;
	
	var pos = ( ( ( window.ActiveXObject ? document.documentElement.clientWidth : window.innerWidth ) - width ) / 2 ) - 10;
	$('#overDiv > table:first').attr('width','').css('width',width+'px').css('max-width',width+'px').parent().css('left',pos+'px');

}


/*=============================
|| Prend en charge la connection à la BD ||
==============================*/

function register()
{
	user = $('#userInput').val();
	pass = $('#pwdInput').val();
	$.post( 'register.php', { username: user,  password: pass } , function(data)
						{
							var result = data.split('|');
							if( result[0] == 'success' )
							{
								$('#loginError').css('color','green').html('Vous êtes maintenant enregistré et connecté au site. Bon surf.<br />');
								setTimeout( "cClick()", 2500 );
								$('#login').css('visibility','hidden').attr('src', 'data/images/logout.png').attr('id', 'logout').css('visibility','visible').unbind().bind('click', function(){ afficher('logout'); return false; } );
							}
							else
							{
								$('#loginError').html(result[1]);
								$('#Connection').focus();
							}
						}, 'html' );
}

var maxFav = 0;	
var favChanged = false, updateFav = false;

function arcadyaLogin(onInit)
{					
	var user = '', pass = '';
	if( !onInit )
	{
		user = $('#userInput').val();
		pass = $('#pwdInput').val();
	}

	$.post( 'login.php', { username: user, password: pass } , function(data)
			    					{
									if( data.success )
									{
										cClick();
										effets = data.effets;
										maxBlocHeight = data.maxBlocHeight;
										
										$('.split2,.split3,.notice-wrap').remove();
									
										numCol = data.numCol;
										if( data.numCol == 2)
											$('#staticContent').after('<div class="split2"><div class="colonne"></div></div><div class="split2"><div class="colonne"></div></div>');
										else
											$('#staticContent').after('<div class="split3"><div class="colonne"></div></div><div class="split3"><div class="colonne"></div></div><div class="split3"><div class="colonne"></div></div>');
				
										if( isIE7 )
											$('.colonne').bind( 'mousedown', function(e){ return false; } ).sortable( {items: '.bloc' , placeholder: 'sortHelper', forcePlaceholderSize: true, connectWith: ['.colonne'], cursor:'move', handle:'.handle', distance:'6', tolerance: 'pointer' } );
										else
											$('.colonne').bind( 'mousedown', function(e){ return false; } ).sortable( {items: '.bloc' , placeholder: 'sortHelper', forcePlaceholderSize: true, connectWith: ['.colonne'], cursor:'move', opacity:0.6, handle:'.handle', distance:'6', tolerance: 'pointer' } );

										if( data.favoris.length > 1 )
										{
											maxFav = 0;
											var favSeries = '', favSize = 0;
											var favoris = data.favoris.replace(/^\|/,'').replace(/\|$/,'').split('|');
											for( var i = 0; i < favoris.length; ++i )
											{
												if( favoris[i] )
												{
													$('<span style="display:none">'+favoris[i]+'</span>').appendTo('body').each( function(){ favSize = $(this).width(); } ).remove();
													if( favSize > maxFav )
														maxFav = favSize;
														
													favSeries += '<li><div onmousedown="return false" onselectstart="return false"><span>' + favoris[i] + '</span><span class="txtDelete" favid="'+i+'" onclick="deleteFavorite(this,event)">X</span></div></li>';
												}
											}
								
											$('#favoritesMenu').width((maxFav+60)+'px').html(favSeries).find('div').bind( 'click', function()
																													{
																														if( favChanged )
																															favChanged = false;
																														else
																															add( $(this).find('> span:first').html() ); 
																													} );													
											
											$('#favoritesMenu').sortable( {axis: 'y', cancel: '.txtDelete', containment: 'parent', distance: 12, items: 'li', stop: function(){favChanged = true;}, update: function(){ favChanged = true; updateFav = true; }, tolerance: 'pointer' } );
										}
										else
											$('#favoritesMenu').width('auto').html( '<li style="padding:2px 10px 0 10px" id="aucunFav">Aucun favoris</li>' );
											
										if( data.showNotes )
											$('[page="aide"]').after('<div class="highlightL" style="float:right;width:34px" page="notes" onclick="afficher(\'notes\')"><div class="highlightR"><div class="highlightM"><img src="data/images/notes.png" id="notes" title="Notes" alt="" /></div></div></div>');
										
										var colonnes = data.onLoad.split('&');
										for( var col = 0; col < colonnes.length; ++col )
										{
											var cmds = colonnes[col].split('|'); 
											for( var i = 0; i < cmds.length; ++i )
											{
												if( cmds[i] != '' )
												{
													add(cmds[i], $('.colonne').eq(col) );
													if( cmds[i] == 'chat' || cmds[i] == '#chat' )
														chatLoaded = true;
												}
											}
										}
										
										//if( !chatLoaded )
										//	setTimeout( function(){add( 'chat' );}, 2000 );

										$('#login').css('visibility','hidden').attr('src', 'data/images/logout.png').attr('id', 'logout').attr('title','Déconnexion').css('visibility','visible').unbind().bind('click', function(){ afficher('logout'); return false; } );
										for( var i = 0; i < data.number; ++i )
											jQuery.noticeAdd({ effects: effets, username: data.notes[i].username, title: data.notes[i].title, text: data.notes[i].text });
											
										$.get( 'cron/online.php', {action: 'changeuser'}, null, 'html' );
									}
									else
									{
										if( !onInit )
										{
											$('#loginError').html('Identifiants incorrect. Veuillez réessayer.<br />');
											$('#pwdInput').val('').focus();
										}
									}

									if( !readCookie( 'arcId' ) && onInit )
									{
									}		
									//jQuery.noticeAdd({ stay:true, effects: false, username: 'Seth', title: 'Dons', text: "Comme vous le savez probablement déjà tous, le serveur dédié d'Arcadya est entièrement financé par les dons, avec des paiements tous les 6 mois. C'est donc avant la fin de ce mois que la location doit être renouvelée.<br><br>Pour ceux qui ne le savent pas encore, le serveur coûte 250,61 euros. Le délai officiel accordé est de 3 jours pour payer la somme avant coupure du serveur.<br><br>Nous faisons donc appel à votre générosité pour pouvoir continuer l'aventure. Il n'y a pas de limite minimale, tous les dons comptent.<br><br>Merci à tous ceux qui nous soutiendront.<center><a href=\"paypal.html\" target=\"_blank\"><span style=\"color:#22B14C;font-size:150%\">Lien paypal</span></a></center>"});
								
									
							
										
								}, 'json' );
								
}

function setOnlineStatus()
{	
	if( !readCookie( 'arcOl' ) )
		$.get( 'cron/online.php', {action: 'connected'}, null, 'html' );
	else
		$.get( 'cron/online.php', {action: 'refresh'}, null, 'html' );
	
	setTimeout( setOnlineStatus, 120000 ); //120000 ms = 2 minutes
}


/*================================================
|| Prend en charge la sauvegarde des préférences ||
=================================================*/

function setOptions()
{
	var _effets = document.getElementById("effets").checked;
	var agt = !(document.getElementById("agt").checked);
	var col = document.getElementById("numCol").value;
	var _maxBlocHeight = parseInt( document.getElementById("maxBlocHeight").value );
	
	if( isNaN(_maxBlocHeight) )
		_maxBlocHeight = 392;
	else if( _maxBlocHeight < 200 )
		_maxBlocHeight = 200;
	
	var _calOpts = 0;
	
	if( document.getElementById("calFilter").checked )
		_calOpts += 1;
		
	if( document.getElementById("calPast").checked )
		_calOpts += 2;
		
	var _newPwd = '';
	if( document.getElementById("newPassword").value != '' )
		_newPwd = document.getElementById("newPassword").value;
	
	$.post( 'options.php', { Action: '_global', Effets: _effets, AGT: agt, NumCol: col, MaxBlocHeight: _maxBlocHeight, CalOpts: _calOpts, newPwd: _newPwd }, function(data)
																			{
																				var result = data.split('|');
																				if(result[0] == 'success')
																				{
																					effets = _effets;
																					
																					if( maxBlocHeight != _maxBlocHeight )
																					{
																						maxBlocHeight = _maxBlocHeight;
																						$('.contentM').css('max-height',maxBlocHeight+'px');
																					}
																					
																					if( result[1] == 1 )
																					{
																						$('.calendar').each( function()
																											{
																												var month = $(this).find('.ui-datepicker-title > span:first').html();
																												var year = $(this).find('.ui-datepicker-title > span:last').html();
																											
																												switch( month )
																												{
																													case 'Janvier': month = 1; break;
																													case 'Février': month = 2; break;
																													case 'Mars': month = 3; break;
																													case 'Avril': month = 4; break;
																													case 'Mai': month = 5; break;
																													case 'Juin': month = 6; break;
																													case 'Juillet': month = 7; break;
																													case 'Août': month = 8; break;
																													case 'Septembre': month = 9; break;
																													case 'Octobre': month = 10; break;
																													case 'Novembre': month = 11; break;
																													case 'Décembre': month = 12; break;
																												}
																												
																												getDates(month,year,$(this));
																											} );
																					}
																				
																					$('#optMsg').css('color','green').html('Sauvegarde effectuée');
																						
																					if( col != numCol )
																					{
																						if( numCol == 2 )
																						{
																							$('.split2').removeClass('split2').addClass('split3');
																							$('.split3:last').after('<div class="split3"><div class="colonne"></div></div>');
																							$('.colonne:last').bind( 'mousedown', function(e){ return false; } ).sortable( {items: '.bloc' , placeholder: 'sortHelper', forcePlaceholderSize: true, connectWith: ['.colonne'], cursor:'move', opacity:0.6, handle:'.handle', distance:'6', tolerance: 'pointer' } );	
																						}
																						else
																						{
																							$('.colonne:eq(2) > div:visible').each( function()
																											{
																												var heightCol1 = 0, heightCol2 = 0;
																												$('.colonne:eq(0) > div:visible').each( function(){ heightCol1 += $(this).height(); } );
																												$('.colonne:eq(1) > div:visible').each( function(){ heightCol2 += $(this).height(); } );

																												var colonne;
																												var minHeight = Math.min( heightCol1, heightCol2 );

																												if( minHeight == heightCol1 )
																													colonne = '.colonne:eq(0)';
																												else
																													colonne = '.colonne:eq(1)';
																													
																												$(this).prependTo( colonne );
																											} );
																							
																							$('.split3:last').remove();
																							$('.split3').removeClass('split3').addClass('split2');
																						}
																							
																						numCol = col;
																					}
																					
																					
																					setTimeout( 'cClick()', 1000 );
																				}
																				else
																					$('#optMsg').css('color','red').html('Erreur lors de la sauvegarde');
																			}, 'html');
}


/*=========================================================
|| Affiche un menu et applique le highlight sur les icones ||
===========================================================*/

function showMenu(id)
{
	clearMenu();
	menuActif = true;

	$(id).addClass('highlightL-hover').children().addClass('highlightR-hover').children().addClass('highlightM-hover');

	if( effets == 1 )
		$(id).next().slideDown( 'fast' );
	else
		$(id).next().show();
}


/*=========================================================
|| Cache les menus et retirer le highlight sur les icones ||
==========================================================*/

function clearMenu()
{
	if( effets == 1 )
	{
		$('#menuHeader > li > ul:visible').slideUp('fast');
		$('#rssMenu').slideUp('fast');
	}
	else
	{
		$('#menuHeader > li > ul:visible').hide();
		$('#rssMenu').hide();
	}

	$('#menuHeader > li > div').removeClass('highlightL-hover').children().removeClass('highlightR-hover').children().removeClass('highlightM-hover');
	$('#rssDiv').removeClass('highlightL-hover').children().removeClass('highlightR-hover').children().removeClass('highlightM-hover');
	
	if( updateFav )
	{
		updateFavorite();
		updateFav = false;
	}
}


/*=====================================
||Prend en charge le multi-file upload||
=======================================*/

function multiFile(obj)
{
	if($('input.upload').size() > 10)
	{
		alert('La limite de 10 fichiers est atteinte.');
		return false;
	}

	var v = obj.value;
	var ext = v.substring(v.lastIndexOf(".")+1, v.length).toLowerCase();

	if ( !v || ( ext != "srt" && ext != "torrent" && ext != "zip" ) )
	{
		alert('Seul les fichiers ".torrent", ".srt" et ".zip" sont autorisés.');
		return false;
	}
		
	$(obj).hide().parent().prepend('<input type="file" class="upload" size="' + ( jQuery.browser.opera ? 72 : 80 ) + '" name="fileX[]" onchange="multiFile(this)" />');
	$("div#filesList").append('<div>'+v+'<img src="data/images/delete.png" style="cursor:pointer;position:relative;left:25px;top:4px" /></div>').find("img").click(function()
			{
				$(this).parent().remove();
				$(obj).remove();
				return true; 
			} );
}


/*===============================================================
||Prend en charge l'affichage de l'echec/réussite de l'opération||
=================================================================*/

function fileResult()
{
	$('#overDiv input.upload:gt(0)').remove();
	$('#filesList div').remove();
	var result = document.getElementById('hiddenFrame').contentWindow.document.body.innerHTML.split('|');
	document.getElementById('hiddenFrame').contentWindow.document.body.innerHTML = '';
	if( result[0] == 'success' )
	{
		$('#uploadError').css('color','green').html('L\'opération s\'est déroulé avec succès.<br /><br />');
		setTimeout( "cClick()", 1500 );
	}
	else if( result[0] == 'error' )
		$('#uploadError').css('color','red').html(result[1]);
	else
		$('#uploadError').html('');
}


/*==========================================
||Gère les votes pour la commande "partage"||
============================================*/

function rate( obj, id, val )
{
	if( readCookie('arcId') )
	{
		if( Math.abs(val) == 5 )
		{
			$.post( 'rate.php', { id: id, val: val }, function(data)
										{
											var result = data.split('|');
											if(result[0] == 'success')
											{
												var img, span;
												if( val < 0 )
												{
													img = $(obj).next();
													span = $(obj).next().next().next();
												}
												else
												{
													img = $(obj).prev();
													span = $(obj).next();
												}

												img.attr('src', 'data/images/'+result[1] );
												span.html( '('+result[2]+')' );
											}
											else
											{
												if( result[1] )
													popupData( 'Vote', result[1] );
												else
													popupData( 'Vote', 'Une erreur s\'est produite. Merci de bien vouloir réessayer.' );
											}
										}, 'html' );
		}
	}
	else
		popupData( 'Vote', 'Vous devez vous connecter pour pouvoir voter.' );
}


/*=================
||Gère des choses ||
===================*/

function deleteShared(id,obj)
{
	$.post( 'deleteShared.php', { id: id }, function(data)
								{ 
									if( data == 'success' )
									{
										$(obj).parent().parent().remove();
									}
									else
										popupData( 'Suppression de fichier', 'Une erreur s\'est produite. Le fichier n\'a pas été effacé.' );
								}, 'html' );
}



function getDates(month,year,cal)
{
	$.post( 'calendar.php', { month: month, year: year }, function(data, textStatus)
														{
															if( data.success )
															{
																cal.find('td').each( function(){ this.onclick = function(){ return false; }; } ).find('a').unbind('mouseover').unbind('mouseout').css('cursor','default').removeClass('ui-state-hover');
																for( var i = 0; i <= 31; ++i )
																{
																	if( data.dates[''+i] )
																	{
																		cal.find(".ui-state-default:contains('"+i+"')").eq(0).addClass('ui-state-hover').css('cursor','pointer').bind('mouseover',{val: data.dates[''+i]},
																		function(event)
																		{
																			if(!stickyDate)
																				overlib( '<ul class="popupDate">'+event.data.val+'</ul>', FULLHTML );	 
																		} ).bind('mouseout',function(){ return nd(); } ).bind('click',{val: data.dates[''+i]}, function(event)
																		{
																			stickyDate = true;
																			overlib( '<ul class="popupDate">'+event.data.val+'</ul>', FULLHTML, STICKY );
																			return false;
																		} );
																	}
																}
															}
															else
																popupData( "Calendrier", "Une erreur s'est produite. Les dates ne sont pas disponibles." )
														}, 'json' )	;
}


function addFavorite(id)
{
	if( !readCookie('arcId') )
	{
		popupData( 'Ajout de favoris', 'Vous devez être connecté pour ajouter des séries/commandes à vos favoris.' );
		return;
	}
	
	var cmd = blocList[id], cmdStripped = '';
	if( cmd.substr( cmd.length - 4, 3 ) == '%3B' )
		cmdStripped = cmd.substr( 0, cmd.length - 4 );
	else
		cmdStripped = cmd;
		
	$.post( 'options.php', { Action: '_addFav', favCmd: cmdStripped }, function(data)
							{
								var result = data.split('|');
								if( result[0] == 'success' )
								{
									popupData( "Favoris", "Favori ajouté avec succès", 1100 );
									$('#aucunFav').remove();
									var lastFavId = $('#favoritesMenu div:last').find('> span:last').attr('favid');
									lastFavId = lastFavId ? parseInt(lastFavId) : -1;
									$('#favoritesMenu').append('<li><div onmousedown="return false"><span>' + result[1] + '</span><span class="txtDelete" favid="'+ (lastFavId+1) +'" onclick="deleteFavorite(this,event)">X</span></div></li>').find('div:last').bind( 'click', function()
																													{
																														if( favChanged )
																															favChanged = false;
																														else
																															add( $(this).find('> span:first').html() ); 
																													} );
																													
									var favSize = 0;										
									$('<span style="display:none">'+result[1]+'</span>').appendTo('body').each( function(){ favSize = $(this).width(); } ).remove();
									if( favSize > maxFav )
									{
										maxFav = favSize;
										$('#favoritesMenu').width((maxFav+60)+'px');
									}
								}
								else
								{
									var errorMsg = ( result[1] ? result[1] : "Une erreur s'est produite. Merci de bien vouloir réessayer." );
									popupData( "Ajout de favoris", errorMsg, 1100 );		
								}
							}, 'html' );		
}


function updateFavorite()
{
	var newFav = '|';
	$('#favoritesMenu div').each( function(){ newFav += $(this).find('> span:first').html().replace(/^( +)/,'').replace(/( +)$/,'') + '|'; } );
	
	$.post( 'options.php', { Action: '_updateFav', NewFav: newFav }, function(data)
							{
								if( data == 'success' )
									$('#favoritesMenu div').each( function(i){ $(this).find('> span:last').attr('favid',i); } );
								else
									popupData( 'Favoris', "Erreur lors de la mise à jour de l'ordre des favoris.", 1100 );
									
							}, 'html' );
}


function deleteFavorite(obj,event)
{
	if( window.event )
		 window.event.cancelBubble = true;
	else
		event.stopPropagation();
		
	var favId = $(obj).attr('favid');							
	$.post( 'options.php', { Action: '_deleteFav', FavId: favId }, function(data)
							{
								var result = data.split('|');
								if( result[0] == 'success' )
								{
									var speed = ( effets == 1 ? 'slow' : 0 );
									$('#favoritesMenu div > span[favid='+favId+']').parent().parent().fadeOut( speed, function()
										{
											$(this).remove();
											maxFav = 0;
											
											if( $('#favoritesMenu div').length == 0 )
												$('#favoritesMenu').width('auto').html( '<li style="padding:2px 10px 0 10px" id="aucunFav">Aucun favoris</li>' );
											else
											{
												var favSize = 0;
												$('#favoritesMenu div').each( function(i)
																			{			
																				$(this).find('> span:last').attr('favid',i);
																				
																				$('<span style="display:none">'+$(this).find('> span:first').html()+'</span>').appendTo('body').each( function(){ favSize = $(this).width(); } ).remove();
																				if( favSize > maxFav )
																					maxFav = favSize;
																			} );
																						
												$('#favoritesMenu').width((maxFav+60)+'px');
											}
										} );
								}
								else
									popupData( "Suppression de favoris", "Une erreur s'est produite. Merci de bien vouloir réessayer.", 1100 );	
							}, 'html' );
}


var timeoutId = -999;
//remettre var showInfo car bug sous IE
function showInfos(serie,srtInfoExists)
{
	if( timeoutId != -999 )
		clearTimeout( timeoutId );
	
	if( typeof(serie) == 'number' )
	{
		if( srtInfoExists == true )
		{
			timeoutId = setTimeout( function()
				{	
						$('body').css('cursor','wait');
						$.post( 'infos.php', { srtId: serie }, function(data)
											{
												if( data.success )
												{
													var popup = '<div class="popupInfoEpisode" style="min-width:250px"><ul>';
													popup += '<li class="popupTitleEpisode">'+data.episode+'</li>';
													popup += '<li style="padding-top:6px"><b>Date de parution:</b> '+data.Time+'</li>';
													popup += '<li><b>Tags:</b> '+data.Tags+'</li><hr>';
													popup += '<li style="padding-top:6px"><b>SeriesSub:</b> <span style="color:green">'+data.Seriessub+'</span></li>';
													popup += '<li><b>TV Subtitles:</b> <span style="color:green">'+data.TVSubtitles+'</span></li>';
													popup += '<li><b>U-Sub:</b> <span style="color:green">'+data.Usub+'</span></li>';
													popup += '<li><b>Sub-way:</b> <span style="color:green">'+data.Subway+'</span></li>';
													
													overlib( popup, FULLHTML );
												}
												else
													overlib( '<div class="popupInfoEpisode">Aucune information disponible</div>', FULLHTML );
													
												$('body').css('cursor','default');
													
											}, 'json' ); 
				}, 400 );
		}
		else if( srtInfoExists == false )
		{
			timeoutId = setTimeout( function()
				{	
						$('body').css('cursor','wait');
						$.post( 'infos.php', { Episode: serie }, function(data)
											{
												if( data.success )
												{
													var popup = '<div class="popupInfoEpisode" style="min-width:250px"><ul>';
													popup += '<li class="popupTitleEpisode">'+data.episode+'</li>';
													popup += '<li style="padding-top:6px"><b>Date de parution:</b> '+data.Time+'</li>';
													popup += '<li><b>Tags:</b> '+data.Tags+'</li><hr>';
													popup += '<li style="padding-top:6px"><b>SeriesSub:</b> <span style="color:green">'+data.Seriessub+'</span></li>';
													popup += '<li><b>TV Subtitles:</b> <span style="color:green">'+data.TVSubtitles+'</span></li>';
													popup += '<li><b>U-Sub:</b> <span style="color:green">'+data.Usub+'</span></li>';
													popup += '<li><b>Sub-way:</b> <span style="color:green">'+data.Subway+'</span></li>';
													
													overlib( popup, FULLHTML );
												}
												else
													overlib( '<div class="popupInfoEpisode">Aucune information disponible</div>', FULLHTML );
													
												$('body').css('cursor','default');
													
											}, 'json' ); 
				}, 400 );
		}
		else
		{
			timeoutId = setTimeout( function()
				{	
						$('body').css('cursor','wait');
						$.post( 'infos.php', { Id: serie }, function(data)
											{
												if( data.success )
												{
													var popup = '<div class="popupInfoEpisode"><ul>';
													popup += '<li class="popupTitleEpisode">'+data.episode+'</li>';
													popup += '<li style="padding-top:6px"><b>Titre:</b> '+data.title+'</li>';
													popup += '<li><b>Date de diffusion:</b> '+data.time+'</li>';
													//popup += '<li><b>Nombre de téléchargements:</b> '+data.download+'</li>';
													popup += '<li style="min-width:240px;max-width:400px"><b>Information:</b> '+(data.comments?data.comments:'Aucune')+'</li>';
													
													if( data.trailer )
														popup += '<li style="padding-top:10px"></li></ul></div>';
													else
														popup += '<li><b>Trailer:</b> '+(data.trailer?data.trailer:'Aucun')+'</li></ul></div>';
													
													overlib( popup, FULLHTML );
												}
												else
													overlib( '<div class="popupInfoEpisode">Aucune information disponible</div>', FULLHTML );
													
												$('body').css('cursor','default');
													
											}, 'json' ); 
				}, 700 );
		}
	}
	else
	{
		timeoutId = setTimeout( function()
				{
						$('body').css('cursor','wait');
						$.post( 'infos.php', { Serie: serie }, function(data)
											{
												if( data.success )
												{
													var popup = '<div class="popupInfoSerie"><div style="width:50%;padding-bottom:20px"><ul><li><b>Première diffusion:</b> '+data.first+'</li><li><b>Sous-titres:</b> '+( data.srt ? data.srt : (!isIE7?'<i>':'')+'Inconnu'+(!isIE7?'</i>':''))+'</li><li><b>Chaîne:</b> '+data.chaine+'</li><li><b>Format:</b> '+data.format+' min</li><li><b>Genre:</b> '+data.genre+'</li><li><b>Pays d\'origine:</b> '+data.origine+'</li>';

													popup += '<li><b>Titre français:</b> '+( data.nomFr ? data.nomFr : (!isIE7?'<i>':'')+'Inconnu'+(!isIE7?'</i>':''))+'</li>';
													popup += '<li><b>Alias:</b> '+( data.alias ? data.alias : (!isIE7?'<i>':'')+'Aucun'+(!isIE7?'</i>':''))+'</li>';
													popup += '<li><b>Saisons diffusées:</b> '+data.saison+'</li>';

													if( data.ended )
													{
														popup += '<li><b>Épisodes diffusés:</b> '+data.episode+'</li>';
														popup += '<li><b>Statut:</b> <span style="color:red">Arrêtée en '+data.ended+'</span></li></ul>';
													}
													else
													{
														popup += '<li><b>Dernier épisode diffusé:</b> '+data.episode+'</li>';
														popup += '<li><b>Statut:</b> <span style="color:green">Diffusion en cours</span></li></ul>';
													}
													
													popup += '</div><img src="data/images_ie/series/'+data.image+'.jpg" alt="" onerror="$(this).replaceWith(\'<span style=&quot;position:absolute;top:100px;right:100px;color:blue&quot;><b><i>Pas dimage actuellement</i></b></span>\')" style="position:absolute;top:8px;right:8px;width:320px;height:180px" >';
													popup += '<i>'+data.synopsis+'</i></div>';
													overlib( popup, FULLHTML );
												}
												
												$('body').css('cursor','default');
											}, 'json' ); 
				}, 500 );
	}
}