var asynchronousQuery = 0;

function hideNshow(selecteur, speed)
{
	var div; // Pour retro-compatibilité

	if(div = document.getElementById(selecteur))
		selecteur = "#" + selecteur;

	if($(selecteur).is(':visible'))
		$(selecteur).hide(speed);
	else
		$(selecteur).show(speed);
}


function q(file, d, block, merge)
{	
	// Barre de chargement
	// Compteur de requêtes
	if(asynchronousQuery < 0)
		asynchronousQuery = 0;
	asynchronousQuery = asynchronousQuery + 1;
	// Affichage
	/*$("#asynchronousLoaderText").html("Traitement de données");*/
	if($("#asynchronousLoader").css('display') == 'none')
		$("#asynchronousLoader").fadeIn('fast');
	
	if(document.getElementById(block)) {
		block = '#' + block;
	}

	// Exécution requete asynchrone
	$.post
	(
		file, {ajax: [d]},
		function success(data) 
		{
			updateBlock(block, data, merge);
		},
		"html"
	);
}

function ajaxFileUpload(fileId)
{
	$("#cache")
	.ajaxStart(function() {
		// L'objet cach est défini dans le main .tpl
		cach.visibility = "visible";
	})
	.ajaxComplete(function() {
		cach.visibility = "hidden";
	});

	$.ajaxFileUpload
	(
		{
			url:'index.php?ajax=func:uploadFile',
			secureuri:false,
			fileElementId: fileId,
			dataType: 'xml',
			success: function (data, status)
			{
				q('index.php', 'page:filemanager/medias,type:pictures', 'divImages', 0);
				q('index.php', 'page:filemanager/medias,type:medias', 'divMédias', 0);
				q('index.php', 'page:filemanager/shortcut', 'files_container', 0);
				hideNshow('files_container');
			},
			error: function (data, status, e)
			{
				alert(e);
			}
		}
	)
	return false;
}

function resetBlock(block)
{
	if(document.getElementById(block)) {
		block = '#' + block;
	}
	
	$(block).html('');
}


function updateBlock(block, data, merge)
{
	if(data != str_replace('<div id="AsynchronousErrors">', '', data))
	{
		/*$("#MessageContent").css("display", "none");*/
		$("#MessageContent").html(data);
		$("#MessageScreen").slideDown("slow");
		return false;
	}

	switch(merge)
	{
		case "-1" : 
			$(data).prependTo(block);
			break;
		case "1" :
			$(data).appendTo(block);
			break;
		default :
			$(block).html(data);
	}

	// Décrémentation du compteur de requête
	asynchronousQuery = asynchronousQuery - 1;
	if(asynchronousQuery == 0)
		$("#asynchronousLoader").fadeOut("slow");
}


function ValideCGV(text)
{
	if($('#CGValidation').is(':checked') == false)
    {
		updateBlock('#CGVError', text, 0);
		$("#CGVError").slideDown("slow");
        return false;
    }
    
	return true;
}

function addFileInput(block, name, extra)
{
	updateBlock(block, '<br /><input type="file" name="' + name + '" id="' + name + '" '+ extra +'/>', "1");
}

function checkedAll(checkboxName) {
	with (document.formulaire)
	{
		Box = document.getElementsByName(checkboxName+'[]');
		for (i = 0; i < Box.length; i++) {
			if(document.getElementById('checkedAllCheckbox').checked == false)
				Box[i].checked = false;
			else
				Box[i].checked = true;
		}
	}
}

//transforme champ cliqué en input
//supprime l'effet du double click
//et ajoute l'effet onblur sur l'input
function change_name(id, path, ext, page, block, folder){
	d = document.getElementById(id+ext+"_file");
	d.innerHTML = "<input id=\"input_"+id+ext+"_file\" type=\"text\" value=\""+id+"\" onblur=\"validate_name('"+id+"','"+path+"','"+ext+"','"+page+"','"+block+"', '"+folder+"');\"/>";
	//d.removeAttribute("ondblclick");
}

//recupere le nouveau nom transmi par la fonction change_name
//reactive l'effet du double click
//et rafraichi le block
function validate_name(id, path, ext, page, block, folder){
	var newname;
	d = document.getElementById(id+ext+"_file");
	newname = document.getElementById("input_"+id+ext+"_file").value;
	d.innerHTML = newname;
	q('index.php', 'page:'+page+',func:renameFile,block:'+block+',folder:'+folder+',path:'+path+',ext:'+ext+',newname:'+newname+',oldname:'+path+id+ext, block, '0');
}


function str_replace(search, replace, subject) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'
 
    var s = subject;
    var ra = r instanceof Array, sa = s instanceof Array;
    var f = [].concat(search);
    var r = [].concat(replace);
    var i = (s = [].concat(s)).length;
    var j = 0;
    
    while (j = 0, i--) {
        if (s[i]) {
            while (s[i] = (s[i]+'').split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
        }
    }
 
    return sa ? s : s[0];
}

function strtr (str, from, to) {
    // http://kevin.vanzonneveld.net
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // +      input by: uestla
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: $trans = {"hello" : "hi", "hi" : "hello"};
    // *     example 1: strtr("hi all, I said hello", $trans)
    // *     returns 1: 'hello all, I said hi'
    // *     example 2: strtr('äaabaåccasdeöoo', 'äåö','aao');
    // *     returns 2: 'aaabaaccasdeooo'
    // *     example 3: strtr('ääääääää', 'ä','a');
    // *     returns 3: 'aaaaaaaa'
 
    var fr = '', i = 0, lgth = 0;
 
    if (typeof from === 'object') {
        for (fr in from) {
            str = str.replace(fr, from[fr]);
        }
        return str;
    }
    
    lgth = to.length;
    if (from.length < to.length) {
        lgth = from.length;
    }
    for (i = 0; i < lgth; i++) {
        str = str.replace(from[i], to[i], 'g');
    }
    
    return str;
}

function str_ireplace (search, replace, subject ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Martijn Wieringa
    // +      input by: penutbutterjelly
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Jack
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: str_ireplace('l', 'l', 'HeLLo');
    // *     returns 1: 'Hello'
 
    var i, k = '';
    var searchl = 0;
    var reg;
 
    search += '';
    searchl = search.length;
    if (!(replace instanceof Array)) {
        replace = new Array(replace);
        if (search instanceof Array) {
            // If search is an array and replace is a string,
            // then this replacement string is used for every value of search
            while (searchl > replace.length) {
                replace[replace.length] = replace[0];
            }
        }
    }
 
    if (!(search instanceof Array)) {
        search = new Array(search);
    }
    while (search.length>replace.length) {
        // If replace has fewer values than search,
        // then an empty string is used for the rest of replacement values
        replace[replace.length] = '';
    }
 
    if (subject instanceof Array) {
        // If subject is an array, then the search and replace is performed
        // with every entry of subject , and the return value is an array as well.
        for (k in subject) {
            subject[k] = str_ireplace(search, replace, subject[k]);
        }
        return subject;
    }
 
    for (i = 0; i < search.length; i++) {
		alert(search[i]);
		reg = new RegExp(search[i], 'gi');
        subject = subject.replace(reg, replace[i]);
    }
 
    return subject;
}

function trim (str, charlist) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: mdsjack (http://www.mdsjack.bo.it)
    // +   improved by: Alexander Ermolaev (http://snippets.dzone.com/user/AlexanderErmolaev)
    // +      input by: Erkekjetter
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: DxGx
    // +   improved by: Steven Levithan (http://blog.stevenlevithan.com)
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // *     example 1: trim('    Kevin van Zonneveld    ');
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: trim('Hello World', 'Hdle');
    // *     returns 2: 'o Wor'
    // *     example 3: trim(16, 1);
    // *     returns 3: 6
 
    var whitespace, l = 0, i = 0;
    str += '';
    
    if (!charlist) {
        // default list
        whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
    } else {
        // preg_quote custom list
        charlist += '';
        whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\$1');
    }
    
    l = str.length;
    for (i = 0; i < l; i++) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(i);
            break;
        }
    }
    
    l = str.length;
    for (i = l - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    
    return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

function stripslashes (str) {
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +      fixed by: Mick@el
    // +   improved by: marrtins
    // +   bugfixed by: Onno Marsman
    // +   improved by: rezna
    // +   input by: Rick Waldron
    // +   reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +   input by: Brant Messenger (http://www.brantmessenger.com/)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: stripslashes('Kevin\'s code');
    // *     returns 1: "Kevin's code"
    // *     example 2: stripslashes('Kevin\\\'s code');
    // *     returns 2: "Kevin\'s code"
    return (str+'').replace(/\\(.?)/g, function (s, n1) {
        switch (n1) {
            case '\\':
                return '\\';
            case '0':
                return '\u0000';
            case '':
                return '';
            default:
                return n1;
        }
    });
}