/**
 * Fichier devant contenir tous les outils Javascript succeptibles d'être
 * appelés depuis toutes les pages du site.
 *
 * @package		zCorrecteurs
 * @subpackage	js
 * @author		dworkin, vincent1870
 */

/**
 * Initialisation des effets du site.
 */
function initTopLink()
{
	topLink = $('toplink');
	if (!topLink)
		return;
	var fxTopLink = new Fx.Morph(topLink, {duration:150, transition: Fx.Transitions.Back.easeInOut});
	topLink.addEvent('click', function(event){
		event.stop();
		new Fx.Scroll(window, {duration:1000, transition: Fx.Transitions.Quart.easeOut}).toTop();
	});
}

var sideBarLeft;
var sideBarRight;

function initSideTips()
{
	var tipper = new Tips('div.sidebarleft a', {
		showDelay: 1000,
		fixed: true,
		offset : {'x': 160, 'y': -10},
		onShow: function(tip) {
			tip.fade('in');
		},
		onHide: function(tip) {
			tip.fade('out');
		}
	});

	tipper.container.style.zIndex = 100;
	tipper.container.set('tween', {duration: 100});
}

/**
 * Gestion des clics sur les liens publicitaires. Le comptage des clics
 * se fait en Ajax. La redirection est faite une fois le clic enregistré.
 */
function initPublicite()
{
	$$('.bloc_partenaires a').each(function(elem, i) {
		if (elem.href != '/contact/' && elem.id.replace('pub-', '').trim() != '')
		{
			elem.addEvent('click', function(e) {
				zMessage.info('Chargement...', {duration: -1});

				xhr = new Request({
					method: 'post',
					url: '/publicite/ajax-pub-clic.html',
					onComplete: function(text) {
						zMessage.cacher();
						window.location = elem.href;
					}
				});

				xhr.send('id='+elem.id.replace('pub-', '')+'&cat='+_ajax_data['categorie_courante']);
				e.stop();
			});
		}
	});
 }

/**
* Gestion des blocs déroulants.
*/
function initBlocsDeroulants()
{
	var blocs_titre = $$('.UI_rollbox .title');
	var blocs_deroulant = $$('.UI_rollbox .hidden');
	var time = 400;
	var blocs_sliders = [];

	/* Création des sliders */
	blocs_deroulant.each(function(elem, i) {
		blocs_sliders.push(new Fx.Slide(elem, {duration: 200, transition: Fx.Transitions.ExpoEaseIn}));
		blocs_sliders[i].hide();
	});

	blocs_titre.each(function(elem, i) {
		elem.addEvent('click', function(e){
			e.stop();
			blocs_sliders[i].toggle();
		});
	});

	// Menu "Détente"
	//new MenuMatic();
}

/**
 * Initialisation des actions Ajax.
 */
function initAjax()
{
	//Initialisation des liens ajax
	$$('a.ajax').each(function(elem, i){
		elem.addEvent('click', function(e){
			e.stop();
			xhr = new Request({method: 'get', url: elem.href,
				onSuccess: function(text, xml){
					json = JSON.decode(text);
					zMessage.display(json.msg, json.type);
					if ($type(json.data) == 'string' && $type(json.exec) == 'string') {
						data = JSON.decode(json.data);
						$exec(json.exec);
					}
				}});
			xhr.send('ajax=1');
		});
	});

	//Initilisations des formulaires ajax
	$$('form.ajax').each(function(elem, i){
		elem.addEvent('submit', function(e){
			e.stop();
			action = elem.action;
			if(action.trim() == '') action = _ajax_data['page_courante'];
			xhr = new Request({method: elem.method, url: action,
				onSuccess: function(text, xml){
					json = JSON.decode(text);
					zMessage.display(json.msg, json.type);
					if ($type(json.data) == 'string' && $type(json.exec) == 'string') {
						data = JSON.decode(json.data);
						$exec(json.exec);
					}
				}
			});
			xhr.send(elem.toQueryString()+'&ajax=1');
		});
	});
}

/**
 * Post-chargement des publicités Adsense.
 */
/*function initAdsense()
{
	var pub = $('adsense_postchargement');
	if(!pub) return;
	pub.inject($('adsense'));
	pub.setStyle('display', 'block');
}*/

/**
 * Initialise le blocage des éléments du formulaire lors
 * de sa soumission, pour éviter des doubles insertions.
 */
function initAntiSubmitSpam()
{
	function returnFalse() { return false; }
	$$('form').each(function(form) {
		form.addEvent('submit', function() {
			if(this.sumbitted)
				return false;
			this.sumbitted = true;
			this.getElements('input, select, checkbox, textarea')
			.each(function(el) {
				el.setStyle('opacity', '0.3');
				el._onclick = el.onclick; el.onclick = returnFalse;
				el._onkeypress = el.onkeypress; el.onkeypress = returnFalse;
			});

			setTimeout(function() {
				this.getElements('input, select, checkbox, textarea')
				.each(function(el) {
					el.setStyle('opacity', '1');
					el.onclick = el._onclick;
					el.onkeypress = el._onkeypress;
				});
				this.sumbitted = false;
			}.bind(this), 5000);
		});
	});
}

/**
 * Initialise les sous-menus
 */
function initSousMenu()
{
    var sp = $('speedbarre');
    if (!sp) return;

	sp.getElements('ul li ul').each(function(el) {
		el.fade('hide');
		el.getParent('li').addEvents({
			'mouseenter': function() {
				el.fade('in');
			},
			'mouseleave': function() {
				el.fade('out');
			}
		});
	});
}

function fermerAnnonce(a)
{
    xhr = new Request({method: 'get', url: a.href,
		onSuccess: function(text, xml){
			masquerAnnonce($('annonce_postchargement'));
		}
	});
	xhr.send('ajax=1');
}

function masquerAnnonce(annonce)
{
	annonce.slide('out');
}

window.addEvent('load', function() {
	initSousMenu();
	initTopLink();
	initSideTips();
	initBlocsDeroulants();
	initAjax();
	initPublicite();
	initAntiSubmitSpam();
	//initAdsense();


	(function() { // Tri des tableaux zCode
	var sortImg = {
		'up':   '/css/img/generator/arrow-up.gif',
		'down': '/css/img/generator/arrow-down.gif',
		'none': '/css/img/generator/arrow-updown.gif'
	};

	var accents = [
		'ß','à','á','â','ã','ä','å','æ','ç',
		'è','é','ê','ë','ì','í','î','ï','ð',
		'ñ', 'ò','ó','ô','õ','ö','ø',
		'ù','ú','û','ü','ý','ý','þ','ÿ'
	];
	var replaceWith = [
		's', 'a','a','a','a','a','a','a','c',
		'e','e','e','e','i','i','i','i','d',
		'n', 'o','o','o','o','o','o',
		'u','u','u','u','y','y','b','y'
	];

	var removeAccents = function(str) {
		for (var i = 0; i < accents.length; i++)
			while (str.indexOf(accents[i]) >= 0)
				str = str.replace(accents[i], replaceWith[i]);
		return str;
	}

	var sortTable = function(table, index, dir) {
		var dom_lignes = table.getElementsByTagName('tr');
		var lignes = [];

		for (var i = 0; i < dom_lignes.length; i++)
			lignes[lignes.length] = dom_lignes[i];

		var order = [];
		for (var i = 0; i < lignes.length; i++) {
			if (lignes[i].getElementsByTagName('th').length)
				continue;

			var cell = lignes[i].getElementsByTagName('td');
			if (index >= cell.length)
				continue;
			cell = cell[index];

			order.push([i, removeAccents(cell.get('text').toLowerCase())]);
		}
		order.sort(function(a, b) {
			return (a[1] < b[1] ? -1 : (a[1] == b[1] ? 0 : 1))
				* (dir == 'up' ? 1 : -1);
		});

		for (var i = 0; i < order.length; i++)
			table.appendChild(lignes[order[i][0]]);

	}


	$$('table.tab_user').each(function(tableau) {
		tableau.sorted = null;

		tableau.getElements('th').each(function(header) {
			var img = new Element('img', {
				'src':   sortImg['none'],
				'class': 'tabsort',
				'style': 'padding-right: 5px; opacity: 0.3'
			}).inject(header, 'top');

			header.addEvent('mouseenter', function() {
				img.setStyle('opacity', '1');
			});
			header.addEvent('mouseleave', function() {
				if (!tableau.sorted || tableau.sorted[0] !== header)
					img.setStyle('opacity', '0.3');
			});
			header.setStyle('cursor', 'pointer');

			header.addEvent('click', function() {
				var headers = header.parentNode.getElementsByTagName('th');
				var index = 0;
				for (; index < headers.length && headers[index] !== header; index++);

				if (tableau.sorted) {
					if (tableau.sorted[0] == header) {
						var dir = tableau.sorted[1] == 'up' ? 'down' : 'up';
						tableau.sorted[1] = dir;
						tableau.sorted[0].getElement('img.tabsort').set('src', sortImg[dir]);
						sortTable(tableau, index, dir);
						return;
					}
					else {
						tableau.sorted[0].getElements('img.tabsort')
							.set('src', sortImg['none'])
							.setStyle('opacity', '0.3');
						tableau.sorted = null;
					}
				}

				tableau.sorted = [header, 'up'];
				sortTable(tableau, index, 'up');
				tableau.sorted[0].getElement('img.tabsort').set('src', sortImg['up']);
			});
		});
	});
	})();


	// Poisson d'avril :)

	/*var dt = new Date();
	if(dt.getMonth() != 3 || dt.getDate() != 1)
		return;

	function createCookie(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	}

	function readCookie(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}

	function eraseCookie(name) {
		createCookie(name,"",-1);
	}

	// 10 secondes de fun toutes les 4 pages env
	if((parseInt(Math.random() * 10) % 4) == 0) {
		var rumbaTimer = null;
		var cible = 'input, a';

		//Seulement 5 fois au maximum.
		var times = readCookie('poisson');
		if (!times)
		{
			times = 0;
		}
		createCookie('poisson', parseInt(times) + 1, 1);
		if (parseInt(times) >= 5)
		{
			return;
		}

		function rumba(ev) {
			var el = this;
			if(!rumbaTimer)
				rumbaTimer = window.setTimeout(function() {
					function remettreLiens() {
						$$(cible).each(function(el) {
							el.removeEvent('mouseover', rumba);
							if(!el.oldCoordinates)
								return;
							var move = new Fx.Move(el, {
								'offset': {
									'x': el.oldCoordinates.x,
									'y': el.oldCoordinates.y
								},
								'position': 'upperLeft',
								'edge': 'upperLeft',
								'transition': Fx.Transitions.Elastic.easeIn,
								'duration': 1000
							}).chain(function() {
								el.setStyle('position', 'relative');
								el.setPosition({x: 0, y: 0});
							});
							move.start();
						});
					}
					var vibrations = 0;
					function vibrer() {
						window.resizeTo(screen.width - 20, screen.height);
						if(vibrations > 50) {
							window.resizeTo(screen.width, screen.height);
							return remettreLiens();
						}
						var x, y;
						if(vibrations % 2) {
							x = Math.round(Math.random() * 100) - 30;
							y = Math.round(Math.random() * 100) - 30;
							window.moveBy(x, y);
						}
						else
							window.moveBy(-x, -y);
						vibrations++;
						setTimeout(vibrer, 10);
					}
					vibrer();
				}, 1000 * 10);
			var a = ((parseInt(Math.random() * 100) % (60 - 10 + 1)) + 10)
				* (parseInt(Math.random() * 10) % 2 ? -1 : 1);
			var b = ((parseInt(Math.random() * 100) % (60 - 10 + 1)) + 10)
				* (parseInt(Math.random() * 10) % 2 ? -1 : 1);

			if(!el.oldCoordinates)
				el.oldCoordinates = {
					x: el.getPosition().x,
					y: el.getPosition().y
				};

			a += el.getPosition().x;
			b += el.getPosition().y;

			el.setStyle('position', 'absolute');

			var move = new Fx.Move(el, {
				'offset': {
					'x': a,
					'y': b
				},
				'position': 'upperLeft',
				'edge': 'upperLeft',
				'transition': Fx.Transitions.Bounce.easeOut,
				'duration': 400
			});
			move.start();
		}

		$$(cible).each(function(el) {
			el.addEvent('mouseover', rumba);
		});
	}*/
});

/**
 * Gestion des spoilers (nécessaires pour le zCode).
 */
function switch_spoiler(a)
{
	if(a.nodeName == 'DIV' && a.className == 'spoiler2')
	{
		var b = a.getElementsByTagName('div')[0];

		if (b.style.visibility == 'visible')
			b.style.visibility = 'hidden';
		else
			b.style.visibility = 'visible';
		return false;
	}
	switch_spoiler(a.parentNode.nextSibling);
	return false;
}

function switch_spoiler_hidden(a)
{
	var b = a.parentNode.nextSibling.getElementsByTagName('div');
	b = b[0];
	if (b.style.display == 'block')
		b.style.display = 'none';
	else
		b.style.display = 'block';
	return false;
}

/**
 * Permet de demander la page à afficher.
 * @author karamilo
 */
function gotopage(url, nb_item, nbbp, a)
{
	if (!a) a = '';

	if(nbbp > 0 && nb_item > 0)
	{
		var n = Math.ceil(nb_item / nbbp);
		var msg = 'Veuillez saisir un numéro de page entre 1 et ' + n + ' :';
	}
	else
	{
		var n = 0;
		var msg = 'Veuillez saisir un numéro de page';
	}
	var p = prompt(msg, 0);

	if(p > 0)
	{
		if(p < 1)
			p = 1;
		else if(p > n && n > 0)
			p = n;
		document.location = url + p + a;
	}
}

/**
 * Gestion de l'affectation d'une note au site sur le livre d'or.
 * @author dworkin
 */
function changerNote(note)
{
	$('current-rating').setStyle('width', note*30);
	$('note').value = note;
	$('message').focus();

	return false;
}

/**
 * Affiche une boite de dialogue de confirmation.
 * @author vincent1870
 */
function show_confirm_msg(title, content, callback)
{
	dialog = new Jx.Dialog({
		label: title,
		content: content +
			'<div style="text-align: right;">' +
				'<input type="button" value="Oui" onclick="xhr=new Request({method: \'post\', url=\''+callback+'\'}); xhr.send(\'confirmer=on\');" /> ' +
				'<input type="button" value="Non" onclick="$(\'dialog_confirm\').hide();" /> ' +
			'</div>',
		id: 'dialog_confirm',
		modal: true,
		width: 500,
		height: 200,
		resize: false
	});
	dialog.show();
}

/**
 * Définition de quelques fonctions utiles.
 * @link http://www.talus-works.net/wall.html?type=txt&file=includes/js/common.js
 */
function htmlspecialchars(str){
	str = str.replace('&', '&amp;');
	str = str.replace('<', '&lt;');
	str = str.replace('>', '&gt;');

	return str;
}

function htmlspecialchars_decode(str){
	str = str.replace('&lt;', '<');
	str = str.replace('&gt;', '>');
	str = str.replace('&amp;', '&');

	return str;
}

function number_format (number, decimals, dec_point, thousands_sep) {
    // Formats a number with grouped thousands
    // version: 906.1806
    // discuss at: http://phpjs.org/functions/number_format
    var n = number, prec = decimals;

    var toFixedFix = function (n,prec) {
        var k = Math.pow(10,prec);
        return (Math.round(n*k)/k).toString();
    };

    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;

    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

    var abs = toFixedFix(Math.abs(n), prec);
    var _, i;

    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;

        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }

    var decPos = s.indexOf(dec);
    if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
        s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
    }
    else if (prec >= 1 && decPos === -1) {
        s += dec+new Array(prec).join(0)+'0';
    }
    return s;
}

