/*!
 * D4Y JavaScript Library (Nécessite jquery)
 * http://www.D4Y.be
 *
 * Copyright 2011, Damien Dupuis
 *
 */

var wampFolder = "";
var absoluteURL = (getAbsolutePath()!= "http://localhost/")? getAbsolutePath(): getAbsolutePath()+wampFolder;
 
function ajustDimension(from,to){
	$(''+to+'').width($(''+from+'').width());
	$(''+to+'').height($(''+from+'').height());
	}
	
	
function hrefLocation(url){
	window.location.href = url;
}

/*Traitement de chaine*/
function no_accent (my_string) {
		var new_string = "";
		var pattern_accent = new Array("é", "è", "ê", "ë", "ç", "à", "â", "ä", "î", "ï", "ù", "ô", "ó", "ö");
		var pattern_replace_accent = new Array("e", "e", "e", "e", "c", "a", "a", "a", "i", "i", "u", "o", "o", "o");
		if (my_string && my_string!= "") {
			new_string = preg_replace (pattern_accent, pattern_replace_accent, my_string);
		}
		return new_string;
	}
	
function preg_replace (array_pattern, array_pattern_replace, my_string)  {
	var new_string = String (my_string);
		for (i=0; i<array_pattern.length; i++) {
			var reg_exp= RegExp(array_pattern[i], "gi");
			var val_to_replace = array_pattern_replace[i];
			new_string = new_string.replace (reg_exp, val_to_replace);
		}
		return new_string;
	}
	
/*Imposer l'introduction d'un chiffre*/

function numericOnly(id){
	var field = document.getElementById(id);
    field.value=field.value.replace(/[^0-9]/g,"");	
}

function prixOnly(id){
	var field = document.getElementById(id);
    field.value=field.value.replace(/[^0-9.]/g,"");	
}

/*Imposer l'introduction de caractère alphanumérique - et blank space uniquement*/

function alphaOnly(id){
	var field = document.getElementById(id);
    field.value=field.value.replace(/[^a-zA-Z àäâéèëêïîùûüç-]/gi,"");	
}

function cityOnly(id){
	var field = document.getElementById(id);
    field.value=field.value.replace(/[^a-zA-Z àäâéèëêïîùûüç'-]/gi,"");	
}

function alphaNumericOnly(id){
	var field = document.getElementById(id);
    field.value=field.value.replace(/[^0-9a-zA-Z àäâéèëêïîùûüç.-]/gi,"");	
}

function entreeLibre(id){
	var field = document.getElementById(id);
    field.value=field.value.replace(/[^0-9a-zA-Z àäâéèëêïîùûüç-]/gi,"");	
	field.value=no_accent(field.value);
	
}


function phoneOnly(id){
	var field = document.getElementById(id);
    field.value=field.value.replace(/[^0-9.+)(/]/gi,"");	
}

function emailOnly(id){
	var field = document.getElementById(id);
    field.value=field.value.replace(/[^0-9a-zA-Z@{1,1}._-]/gi,"");	
}

function Uppercase(id) {
	var field = document.getElementById(id);
	field.value = field.value.toUpperCase();
}

function ucfirst(id){
	var field = document.getElementById(id);
	var str = field.value;
    str += '';
    var f = str.charAt(0).toUpperCase();
    field.value = f + str.substr(1);
}

function limitString(id,limit,id_dis){
	var str = $('#'+id).val();
	if(str.length > limit){
		$('#'+id).val(str.substr(0, limit));
	}
	//Afficher les caractères restant
	restant = ((limit - str.length) >= 0)? (limit - str.length) : 0;
	$('#'+id_dis).html(restant);
}

function limitValue(id,s,limit){
	var field = document.getElementById(id);
	var str = field.value;
	if(s == 'max')
		{
		var valeur =  (parseFloat(str) > limit)? limit : str;
		}
	else{
		var valeur = (parseFloat(str) < limit)? limit : str;
		}
	field.value = valeur;
}

function moreOrLess(action,id,minimum,maximum){
	var edit = (action == "more")? "+1" : "-1";
	var dest = document.getElementById(id);
	valeur = dest.value;
	if(action == "more")
		{
		if(eval(valeur) < eval(maximum))
			{
			dest.value = eval(valeur+edit);
			}
		}
	else{
		if(eval(valeur) > eval(minimum))
			{
			dest.value = eval(valeur+edit);
			}
		}
}

function checkMax(id,valeur){
	var field = document.getElementById(id);
	if(field.value.length > valeur)
		{
		field.value = field.value.substr(0,valeur);
		}
}

$.fn.clearForm = function() {
  return this.each(function() {
	var type = this.type, tag = this.tagName.toLowerCase();
	if (tag == 'form')
	  return $(':input',this).clearForm();
	if (type == 'text' || type == 'password' || tag == 'textarea' || type == 'hidden' )
	  this.value = '';
	else if (type == 'checkbox' || type == 'radio')
	  this.checked = false;
	else if (tag == 'select')
	  this.selectedIndex = 0;
  });
};


function LocalisationCountry(action,inputString,from){	
if(action == 'look'){
		if(inputString.length == 0) {
			// Hide the suggestion box.
			$('#suggestions'+from).hide();
		} else {
			$.post("localisation.php", {action:"country",field:from,queryString: ""+inputString+""}, function(data){
				if(data.length >0) {
					$('#suggestions'+from).show();
					$('#autoSuggestionsList'+from).html(data);

				}
			});
		}
		}
	else if(action == 'fill')
		{
		if($('#'+inputString)){
		$('#pays').val($('#'+inputString).attr('pays'));
		}
		setTimeout("$('#suggestions"+from+"').hide();", 200);
		}
}
	
	
function LocalisationAutocomplete(action,from,inputString){
	if(action == 'look'){
		if(inputString.length == 0) {
			// Hide the suggestion box.
			$('#suggestions'+from).hide();
		} else {
			//Vérifier si le pays déjà complété
			var pays = $("#pays").val();
			$.post("localisation.php", {action:"autocomplete",field:from,country:pays,queryString: ""+inputString+""}, function(data){
				if(data.length >0) {
					$('#suggestions'+from).show();
					$('#autoSuggestionsList'+from).html(data);

				}
			});
		}
		}
	else if(action == 'fill')
		{
		$('#cp').val($('#'+inputString).attr('cp'));
		$('#ville').val($('#'+inputString).attr('ville'));
		$('#pays').val($('#'+inputString).attr('pays'));
		$('#localisation_id').val($('#'+inputString).attr('id'));
		setTimeout("$('#suggestions"+from+"').hide();", 200);
		}
	}


function isInt(x) {
   var y=parseInt(x);
   if (isNaN(y)) return false;
   return x==y && x.toString()==y.toString();
 }
 
 function getAbsolutePath() {
	 
   return window.location.protocol+"//"+window.location.host+"/";
}

function clearReponse(){
	 $('div#reponse').fadeOut();
	 $('div#reponse').html('');
}

function change_captcha()
	 {
	 	$('img#captcha').attr("src",absoluteURL+"/lib/get_captcha.php?rnd=" + Math.random());
	 }
	 
function rewrite(source){
	$('#'+source).val(str2url($('#'+source).val().replace(/^[0-9]+\./, ''), 'UTF-8'));
}
	 
function str2url(str,encoding,ucfirst)
{
	str = str.toUpperCase();
	str = str.toLowerCase();

	str = str.replace(/[\u0105\u0104\u00E0\u00E1\u00E2\u00E3\u00E4\u00E5]/g,'a');
	str = str.replace(/[\u00E7\u010D\u0107\u0106]/g,'c');
	str = str.replace(/[\u010F]/g,'d');
	str = str.replace(/[\u00E8\u00E9\u00EA\u00EB\u011B\u0119\u0118]/g,'e');
	str = str.replace(/[\u00EC\u00ED\u00EE\u00EF]/g,'i');
	str = str.replace(/[\u0142\u0141]/g,'l');
	str = str.replace(/[\u00F1\u0148]/g,'n');
	str = str.replace(/[\u00F2\u00F3\u00F4\u00F5\u00F6\u00F8\u00D3]/g,'o');
	str = str.replace(/[\u0159]/g,'r');
	str = str.replace(/[\u015B\u015A\u0161]/g,'s');
	str = str.replace(/[\u00DF]/g,'ss');
	str = str.replace(/[\u0165]/g,'t');
	str = str.replace(/[\u00F9\u00FA\u00FB\u00FC\u016F]/g,'u');
	str = str.replace(/[\u00FD\u00FF]/g,'y');
	str = str.replace(/[\u017C\u017A\u017B\u0179\u017E]/g,'z');
	str = str.replace(/[\u00E6]/g,'ae');
	str = str.replace(/[\u0153]/g,'oe');
	str = str.replace(/[\u013E\u013A]/g,'l');
	str = str.replace(/[\u0155]/g,'r');

	str = str.replace(/[^a-z0-9\s\'\:\/\[\]-]/g,'');
	str = str.replace(/[\s\'\:\/\[\]-]+/g,' ');
	str = str.replace(/[ ]/g,'-');
	str = str.replace(/[\/]/g,'-');

	if (ucfirst == 1) {
		c = str.charAt(0);
		str = c.toUpperCase()+str.slice(1);
	}

	return str;
}

function checkAllInit(id,classe){
	
	$('#'+id).click(function(){
				if ($(this).is(':checked')){$('.checklist'+classe).attr('checked', true);}
				else{$('.checklist'+classe).attr('checked', false);}});
			
			
			
			$('input').each(function(index){
				if($('input:eq('+index+')').is('.checklist'+classe))
					{
					$('input:eq('+index+')').click(function(){
						checkAllVerification(id,'.checklist'+classe);
						});
					}
				});
			
}

function checkAllVerification(checker,checked){
				var count = 0;
				var check_count = 0;
				$('input').each(function(index){
				if($('input:eq('+index+')').is(checked))
					{
					if($('input:eq('+index+')').is(':checked'))
						{
						check_count++;	
						}
					count++;
					}
				
				});
				if(check_count < count){
					$('#'+checker).attr('checked',false)
				}else{$('#'+checker).attr('checked',true)}
			}
			
function passGen(length, special) {
  var iteration = 0;
  var password = "";
  var randomNumber;
  if(special == undefined){
      var special = false;
  }
  while(iteration < length){
    randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33;
    if(!special){
      if ((randomNumber >=33) && (randomNumber <=47)) { continue; }
      if ((randomNumber >=58) && (randomNumber <=64)) { continue; }
      if ((randomNumber >=91) && (randomNumber <=96)) { continue; }
      if ((randomNumber >=123) && (randomNumber <=126)) { continue; }
    }
    iteration++;
    password += String.fromCharCode(randomNumber);
  }
  return password;
}

function autoPassword(){
	var password = passGen('8',false);
	
	$("#mdp").val(password);
	if($("#mdp_confirm")){
		$("#mdp_confirm").val(password);
		}
		
	if($("#notifier")){
		$("#notifier").attr('checked','checked')
	}
}

function fakeReload(){
	window.location.href = location.href;
}

function clearForm(id){
	$('#'+id+' input').each(function(index, element) {
		if($(this).attr('type') == "text" || $(this).attr('type') == "checkbox"){
        $(this).val('');
		}
    });
	
	$('#'+id+' select').each(function(index, element) {
        $(this).val('');
    });
	
	$('#'+id).submit();
}

function controlForm(id){
	//Format
	$("#"+id+" input , #"+id+" textarea").each(function(index, element){
		var rel = $(this).attr('rel');
		if(rel){
		frel = rel.split(' ');
		var fonction = "";
		for(var i= 0; i < frel.length; i++)
			{
			var eid = $(this).attr('id');
			if(frel[i] == "ucfirst"){
				fonction = fonction+"ucfirst('"+eid+"'); ";
				}
			else if(frel[i] == "Uppercase"){
				fonction = fonction+"Uppercase('"+eid+"'); ";
			}
			else if(frel[i] == "email"){
				fonction = fonction+" emailOnly('"+eid+"'); ";
			}
			else if(frel[i] == "phone"){
				fonction = fonction+" phoneOnly('"+eid+"'); ";
			}
			else if(frel[i].substr(0,11) == "limitString"){
				var stl = (frel[i].length - 11);
				var limit = frel[i].substr(11,stl);
				fonction = fonction+"limitString('"+eid+"','"+limit+"','limitString"+eid+"'); ";
			}
				
			$(this).keyup(function(){
				eval(fonction)
				})
				
			$(this).blur(function(){
				eval(fonction)
				})
			}
		}
		
	})
}

function diaporamaInit(id,photos,interval){
		var image = photos.split('|');
		$('div#diaporama').css('backgroundImage','url('+absoluteURL+'"diaporama/'+id+'/'+image[0]+'")');
		$('div#diaporama_preload').attr('src',''+absoluteURL+'diaporama/'+id+'/'+image[1]+'');
		interval = (interval*1000);
		setTimeout("diaporamaRun('"+id+"','"+photos+"',"+interval+",1)",interval);
		
}

function diaporamaRun(id,photos,interval,i){
	var image = photos.split('|');
	var count = (i < image.length)? i : 0;
	var count_preload = count + 1 ;
	
	$('div#diaporama').fadeOut('slow', function() {
		$('div#diaporama').css('backgroundImage','url("'+absoluteURL+'diaporama/'+id+'/'+image[count]+'")');
		$('div#diaporama_preload').css('backgroundImage','url("'+absoluteURL+'diaporama/'+id+'/'+image[count_preload]+'")');
		});
	
	$('div#diaporama').fadeIn('slow', function() {});
	setTimeout("diaporamaRun('"+id+"','"+photos+"',"+interval+","+count_preload+")",interval);
}

