/**
 * Fichier devant contenir tous les outils Javascript succeptibles d'être
 * appelés depuis toutes les pages du site.
 *
 * @copyright	Copyright (c) www.zcorrecteurs.fr 2009
 * @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.tip.style.zIndex = 100;
	tipper.tip.set('tween', {duration: 100});
}

/**
 * Gestion des clics sur les liens publicitaires.
 */
function initPublicite()
{
	$$('.bloc.partenaires ul li a, #footer .links a').each(function(elem, i) {
		//if(elem.href.substring(elem.href.length - 1) != '/')
		//	elem.href += '/';
		//href = elem.href.split('/');
		//href = href[href.length - 1];
		if(elem.href != '/contact/' && elem.href != '/publicite/acheter.html')
		{
			elem.addEvent('click', function(e) {
				zMessage.info('Chargement...', {duration: -1});
				//Envoi de la requête en base de données
				xhr = new Request({
					method: 'post',
					url: '/publicite/ajax-pub-clic.html',
					onComplete: function() {
						zMessage.cacher();
						window.location = elem.href;
					}
				});
				xhr.send('url='+elem.href+'&cat='+_ajax_data['categorie_courante']);
				e.stop();
			});
		}
	});
 }

/**
* Gestion des blocs déroulants.
*/
function initBlocsDeroulants() {
	var blocs_titre = $$('.bloc_deroulant .titre');
	var blocs_deroulant = $$('.bloc_deroulant .deroulant');
	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();
			/* On affiche */
			blocs_sliders[i].toggle();
		});
	});
}

/**
 * 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');
		});
	});
}

window.addEvent('load', function() {
	initTopLink();
	initSideTips();
	initBlocsDeroulants();
	initAjax();
	initPublicite();
});

/**
 * Gestion des spoilers (nécessaires pour le zCode).
 * @author karamilo
 */
function switch_spoiler(a)
{
	var b = a.getElementsByTagName('div');
	b = b[0];
	if (b.style.visibility == 'visible')
		b.style.visibility = 'hidden';
	else
		b.style.visibility = 'visible';
	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();
}

/**
 * Affiche la boite de dialogue pour la protection admin.
 * @author vincent1870
 */
function show_admin_wall()
{
	dialog = new Jx.Dialog({
		label: title,
		content: '<form method="post" action="/informations/mur-admin.html">' +
			'<label for="mdp_admin">Entrez le mot de passe admin : </label><br />' +
			'<input type="password" name="mdp_admin" id="mdp_admin" /> ' +
			'<input type="submit" value="Continuer" /></form>',
		id: 'dialog_confirm',
		modal: true,
		width: 500,
		height: 200,
		resize: false
	});
	dialog.show();
}

function str_replace(search, replace, subject, count) {
	var	f = [].concat(search),
		r = [].concat(replace),
		s = subject,
		ra = r instanceof Array,
		sa = s instanceof Array;
	var s = [].concat(s);
	if(count)
		this.window[count] = 0;
	for(i=0, sl=s.length; i < sl; i++) {
		if (s[i] === '')
			continue;
		for(j=0, fl=f.length; j < fl; j++) {
			temp = s[i]+'';
			repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
			s[i] = (temp).split(f[j]).join(repl);
			if (count && s[i] !== temp)
				this.window[count] += (temp.length-s[i].length)/f[j].length;
		}
	}
	return sa ? s : s[0];
}

/**
 * Définition de quelques fonctions utiles.
 * @link http://www.talus-works.net/wall.html?type=txt&file=includes/js/common.js
 */
/**
 * Simule htmlspecialchars de base de PHP.
 * @author Talus
 * @param string str Chaine à encoder
 * @return string
 */
function htmlspecialchars(str){
	str = str_replace('&', '&amp;', str);
	str = str_replace('<', '&lt;', str);
	str = str_replace('>', '&gt;', str);

	return str;
}

/**
 * Simule l'inverse de htmlspecialchars de base de PHP.
 * @author Talus
 * @param string str chaine à décoder
 * @return string
 */
function htmlspecialchars_decode(str){
	str = str_replace('&lt;', '<', str);
	str = str_replace('&gt;', '>', str);
	str = str_replace('&amp;', '&', str);

	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;
}
