$(function() {
	// affichage des cadres a 100% de hauteur
	var max_height = document.documentElement.clientHeight-65;
	$('#contenu-left').css('height', max_height);
	$('#contenu-right').css('height', max_height);
	
	/*$('#contenu-left').resizable({
		maxHeight: max_height,
		minHeight: max_height,
		minWidth:300,
		handles: 'e'
	});
	
	$('#contenu-right').resizable({
		maxHeight: max_height,
		minHeight: max_height,
		minWidth:300,
		handles: 'w'
	});
	*/
	$('#cadre-total').css('height', max_height);

	// mise en place de la scrollbar a l interieur des cadres
	var max_height_overflow = max_height-74;
	$('.overflow').css('height', max_height_overflow);
	
	// detection du milieu du cadre pour le message de selection
	var avg_height= (max_height-parseInt($('.select').css('height')))/2;
	$('.select').css('padding-top', avg_height);
	
	// agrandit les textarea automatiquement
	autoGrow();
	
	// affiche le compteur de caractere pour le textarea
	countChar();
	
	// cache la tooltip de chargement
	$('.loading').hide();
	
	// charge les onglets
	tabs();
	
	// affiche le calendrier
	calendar();
	
	// verifie les formulaires
	valide_form();
	
	// affiche les tooltips
	view_tooltips();
	
	// charge les accordeons
	accordion();
	
	// autocompletion pour la recherche
	$("#search_left").autocomplete({
		source: "top_search.php",
		minLength: 2,
		select: function(event, ui) {
			var redir = ui.item.id.split('|');
			window.location = redir[1]+'.php?id='+redir[0];
		}
	});
	
	// rafraichit les pubs automatiquement
	refresh_pub();
	
	// charge les differents edit
	edit(); edit_textarea(); edit_select();
	
	// charge la possibilite de drag
	sort();
});

// filtre les resultats
function filter(type,get,url)
{
	var form_fields = "";
	var form_ok = true;
	//if(!get.match('form=no')) { form_fields += $('form#'+type+'_form').serialize(); }
	if(get.match('serialize=yes')) { var new_serialize = get.split('&id_form='); var new_serialize2 = new_serialize[1].split('&'); form_fields += '&'+$('form#'+new_serialize2[0]).serialize(); form_ok = $('#'+new_serialize2[0]).validationEngine({returnIsValid:true}); }
	if(get!='') { form_fields += '&'+get; }
	if(type=='locations_add') { type = 'locations'; }

	if(type=='stats' && get.match('graph=1')) { $('#view_graph').hide(); $('#view_datas').show(); if(form_fields.match('stats=1&') || form_fields.match('stats=0&')) { buildGraphTime(); } else { buildGraphChart();  calendar(); } }
	else if(type=='stats' && get.match('csv=1')) { window.location = 'members.php?'+form_fields; }
	else
	{
		if(form_ok)
		{
			$('.tipsy-inner').css('visibility','hidden'); $('.tipsy').css('visibility','hidden');
			if(type!='pub') { $('.loading').show(); }
			$('#'+type+'_view').load(url+'?'+form_fields,function() { 
				$('.loading').hide();
				if(type=='locations') { locations_sortable(); edit(); edit_select(); view_tooltips(); }
				if(type=='locations_details') { tabs(); }
				if(type=='games_in') { time_games(); filter('nb_games','','top_games.php'); filter('nb_inlive','','top_inlive.php'); view_tooltips(); }
				if(type.match('webmail') || type.match('mp')) { sort_mail(); viewTinymce(); valide_form(); view_tooltips(); autocomp(); filter('nb_inbox','','top_inbox.php'); }
				if(type.match('members')) { view_tooltips(); calendar(); valide_form(); autoGrow(); countChar(); }
				if(type.match('stats')) { view_tooltips(); view_tooltips_e(); }
				if(type=='stats') { filter('stats_header',get,'stats_header.php'); $('#view_graph').show(); $('#view_datas').hide(); }
				if(type=='stats_header') { calendar(); }
				if(type.match('faq')) { accordion(); }
				if(type.match('lotofoot')) { tabs(); view_tooltips(); }
				if(type=='login' && url.match('login')) { $('#log').focus(); }
				if(type=='login' && url.match('mdp')) { $('#loginOubli').focus(); }
				if(type=='admin') { valide_form(); viewTinymce(); view_tooltips(); }
				if(type=='admin' && (form_fields.match('id=3') || form_fields.match('id=5') || form_fields.match('id=6'))) { sort(); edit(); edit_textarea(); }
			});
		}
	}
	document.location.hash = get;
	return false;
}

// cree le graph pour les stats sessions
function buildGraphTime()
{
	var data = new google.visualization.DataTable();
	
	// valeur abscisse
	var abscisse_value = $('#value_stats_abs').html();
	var nb_abs = abscisse_value.split(',');
	var months = new Array();
	for(i=0;i<nb_abs.length;i++) { months[i] = nb_abs[i]; }
	
	// construction des abscisses
	data.addColumn('date', 'Date');
	for (var i = 0; i < months.length; ++i) { data.addColumn('number', months[i]); data.addColumn('string', 'title1'); data.addColumn('string', 'text1'); }
	
	// valeur ordonnee
	var ordonnee_value = $('#value_stats_ord').html();
	var nb_ord = ordonnee_value.split('|');
	var raw_data = new Array();
	for(i=0;i<nb_ord.length;i++) 
	{ 
		var nb_ord2 = nb_ord[i].split(',');
		raw_data[i] = new Array(); 
		raw_data[i][0] =  nb_ord2[0];
		for(j=1;j<nb_ord2.length;j++)
		{
			raw_data[i][j] =  nb_ord2[j];
		}
	}
	// construction des ordonnees
	var m = 0;
	data.addRows(raw_data.length);
	for (var i = 0; i < raw_data.length; ++i)
	{
		data.setValue(i, 0, new Date(parseInt(raw_data[i][0]),parseInt(raw_data[i][1]),parseInt(raw_data[i][2])));
		for(var j = 0; j < months.length; ++j) { var k = j+3; if(j==0) { m = 1; } else { m = m+3; } data.setValue(i, m, parseInt(raw_data[i][k])); }
	}

	// affichage du graph	
	var div = $('#stats_view');
	new google.visualization.AnnotatedTimeLine(div.get(0)).draw(data, {
		allValuesSuffix: $('#value_suffix').html(),
		displayAnnotations: false,
		displayExactValues: true,
		//displayRangeSelector : false
	});
	$('.loading').hide();
}

// cree le graph pour les stats banque
function buildGraphChart()
{
	var data = new google.visualization.DataTable();
	// valeur ordonnee
	var ordonnee_value = $('#value_stats_ord').html();
	var nb_ord = ordonnee_value.split('|');
	var raw_data = new Array();
	for(i=0;i<nb_ord.length;i++) 
	{ 
		var nb_ord2 = nb_ord[i].split(',');
		raw_data[i] = new Array(); 
		raw_data[i][0] =  nb_ord2[0];
		for(j=1;j<nb_ord2.length;j++)
		{
			raw_data[i][j] =  nb_ord2[j];
		}
	}
	// valeur abscisse
	var abscisse_value = $('#value_stats_abs').html();
	var nb_abs = abscisse_value.split(',');
	var months = new Array();
	for(i=0;i<nb_abs.length;i++) { months[i] = nb_abs[i]; }

	// construction des axes
	data.addColumn('string', 'Month');
	for (var i = 0; i < raw_data.length; ++i) { data.addColumn('number', raw_data[i][0]); }
	data.addRows(months.length);
	for (var j = 0; j < months.length; ++j) { data.setValue(j, 0, months[j].toString()); }
	for (var i = 0; i < raw_data.length; ++i) { for (var j = 1; j < raw_data[i].length; ++j) { data.setValue(j-1, i+1, parseInt(raw_data[i][j])); } }

	// affichage du graph
	var div = $('#stats_view');
	var chart = new google.visualization.ColumnChart(div.get(0));
	
	chart.draw(data, {
		width: div.width(),
		height: div.height(),
		legend: 'right',
		backgroundColor: '#ffffff',
		fontSize: 11
	});
	$('.loading').hide();
}

// ouvre une fenetre modal
function open_dialog(type,get,height,width)
{
	if(width=='') { width = document.body.clientWidth; width = Math.round(0.9*width,2); }
	if(height=='') { height = document.body.clientHeight; height = Math.round(0.8*height); }
	if(get=='') { get = '?get=0'; }
	get += '&width='+width+'&height='+height;
	$('.loading').show();
	$('#dialog-'+type).load(type+'.php?'+get).dialog({
		bgiframe: true,
		autoOpen: false,
		height: height,
		maxHeight : height,
		width: width,
		modal: false,
		resizable: false,
		open: function(ev, ui) {
			$('.loading').hide();
		}
	});
	$('#dialog-'+type).dialog('open');
}

// affiche l editeur de texte pour la redaction d un message
function viewTinymce()
{
	$('textarea.tinymce').tinymce({
		script_url : 'tinymce/jscripts/tiny_mce/tiny_mce.js',
		language : $('#langue').val(),
		height:'300px',
		plugins : 'safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template',
		theme : 'advanced',
		plugins : 'emotions',
		skin : 'banroa',
		theme_advanced_buttons1 : 'bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,outdent,indent,blockquote,|,link,unlink,|,emotions,|,forecolor,backcolor,code',
		theme_advanced_buttons2 : '',
		theme_advanced_buttons3 : '',
		theme_advanced_toolbar_location : 'top',
		theme_advanced_toolbar_align : 'left',
		theme_advanced_resizing : true,
		force_br_newlines : true,
		force_p_newlines : false,
        forced_root_block : ''
	});
}

// charge les tabulations
function tabs()
{
	$("#tabs").tabs({
		ajaxOptions: {
			error: function(xhr, status, index, anchor) {
				$(anchor.hash).html("<div class='error'>Couldn't load this tab. We'll try to fix this as soon as possible.</div>");
			}
		},
		select: function(event, ui) { /*$('.loading').show();*/ },
		load: function(event, ui) { $('.tipsy-inner').css('visibility','hidden'); $('.tipsy').css('visibility','hidden'); sort(); accordion(); edit(); calendar(); valide_form(); },
		selected: $('.selected_tabs').html()
	});
}

// affiche les tooltips
function view_tooltips() { $('.tooltip').tipsy({gravity: 's',html: true}); }
function view_tooltips_e() { $('.tooltip_e').tipsy({gravity: 'e',html: true}); }

// affiche le calendrier
function calendar() { $.datepicker.setDefaults($.extend({showMonthAfterYear: false}, $.datepicker.regional[$("#langue")])); $(".date").datepicker({changeMonth:true,changeYear: true,showButtonPanel: true}); }

// valide les formulaires
function valide_form() { $(".validate").validationEngine({scroll:false}); }

// agrandit les textarea automatiquement
function autoGrow() { $('textarea.autogrow').autogrow(); }

// affiche le compteur de caractere pour le textarea
function countChar() { $(".counter").charCounter(255,{format: "%1 "+$(".txt_counter").html()}); }

// affiche les accordeons
function accordion() { $(".accordion").accordion({ autoHeight: false,navigation: true}); }

// rafraichit les pubs automatiquement
function refresh_pub()
{
	setInterval(function() {
		filter('pub','','pubs.php');
	}, 60000);
}

// modifie les donnees
function edit()
{
	$('.editable').editable('datas_edit.php', { 
		type : 'text',
		indicator : '<img src="images/Decor/loader_green.gif" height="16" width="16" alt="" />',
		loadtype : 'POST',
		width : '100%',
		cancel : 'annuler',
		submit : 'ok',
		onblur : 'ignore',
		event : 'dblclick',
		tooltip : 'Double cliquez pour modifier...'
	});
}

// modifie les donnees avec textarea
function edit_textarea()
{
	$('.editable_textarea').editable('datas_edit.php', { 
		type : 'textarea',
		indicator : '<img src="images/Decor/loader_green.gif" height="16" width="16" alt="" />',
		loadtype : 'POST',
		cols : 150,
		rows : 3,
		cancel : 'annuler',
		submit : 'ok',
		onblur : 'ignore',
		event : 'dblclick',
		tooltip : 'Double cliquez pour modifier...'
	});
}

// modifie les donnees avec menu deroulant
function edit_select()
{
	$('.editable_select').editable('datas_edit.php', { 
		loadurl : 'datas_edit_select.php',
		type : 'select',
		indicator : '<img src="images/Decor/loader_green.gif" height="16" width="16" alt="" />',
		loadtype : 'POST',
		cancel : 'annuler',
		submit : 'ok',
		onblur : 'ignore',
		event : 'dblclick',
		tooltip : 'Double cliquez pour modifier...'
	});
}

// reordonne
function sort()
{
	$(".sortable").sortable({
		axis: 'y',
		handle: '.dragme',
		cursor : 'move',
		stop : function() {
			serial = $(".sortable").sortable('serialize');
			$.ajax ({ type: "POST",dataType: "html", url: "datas_sortable.php", data: serial});
		}
	});
}
