// JavaScript Document

/*AJAX*/


function protoAjax(page,metod,dest,formulaire,loading,callback){
	
	if(formulaire && formulaire != "")
		{
		var variable = "Form.serialize('"+formulaire+"')" ;
		}
	else{
		var variable = "";
		}
	var ajax = new Ajax.Updater(dest,page,
			{
			method: metod,
			parameters: eval(variable),
			onCreate: function(){
				if(document.getElementById(loading))
				document.getElementById(dest).innerHTML = document.getElementById(loading).innerHTML;
				},
			onComplete: function (){
				eval(callback);
			}
			}
		);
	return ajax;
}

function lightAjax(page,titre,metod,formulaire,closebtn,callback)
	{
	if(formulaire && formulaire != "")
		{
		var variable = "Form.serialize('"+formulaire+"')" ;
		}
	else{
		var variable = "";
		}
	Lightview.show({
	  href: page,
	  rel: 'ajax',
	  title: titre,
	  options: {
		autosize: true,
		topclose: closebtn,
		closeButton:false,
		overlayClose:false,
		keyboard:false,
		ajax: {
		  method: metod,
		  parameters: eval(variable),
		  onComplete: function (){
				eval(callback);
			}
		}
	  }
	});
	}

/*///VERIFICATION DE LA PRESSION DE LA TOUCHE "ENTER"///*/

function checkEnter(e,funct){ //e is event object passed from function invocation
	var characterCode ;//literal character code will be stored in this variable
	if(e && e.which){ //if which property of event object is supported (NN4)
		e = e
		characterCode = e.which //character code is contained in NN4's which property
	}
	else{
		e = event
		characterCode = e.keyCode //character code is contained in IE's keyCode property
	}

	if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
		setTimeout(funct,1);
		return false;
	}
	else{
		return true;
	}
}

/*///GESTION DE CLASS CSS///*/
function changeClass(class_id,id)
	{
	var div = document.getElementById(id);
	if(div)
		{
		div.className = class_id ;
		}
	}
	

/*///EXECUTER UNE FONCTION func1 SI OK ET func2 SI NO///*/

function okOrNo(func1,func2,timing)
	{
	var ok = document.getElementById('ok');
	var no = document.getElementById('no');
	if(ok || no)
		{
		if(ok)
			{
			setTimeout(func1,timing);
			}
		else if(no)
			{
			setTimeout(func2,timing);
			}
		}
	else{
		setTimeout('okOrNo("'+func1+'","'+func2+'","'+timing+'")',100);
		}
	}
	
/*///REDIRIGER VERS UNE URL///*/

function hrefLocation(url)
	{
	window.location.href = url;
	}
	
	
/*///EXECUTER LA FONCTION QUAND LE DIV id EST DISPONIBLE///*/

function wDivLdA(id,fonction,delai)
	{
	var div = document.getElementById(id);
	var delai = (!delai)? 100 : delai;
	if(div)
		{
		setTimeout(fonction,delai);
		}
	else{
		setTimeout('wDivLdA("'+id+'","'+fonction+'")',delai);
		}
	}

//Afficher ou caché un element au moyen de son ID
function viewOrHiddenDiv(id,action)
	{
	var div = document.getElementById(id);
	
	if(action == "hidden")
		{
		div.style.visibility = "hidden";
		div.style.display = "none";
		}
	else if(action = "view")
		{
		div.style.visibility = "visible";
		div.style.display = "block";
		}
	}
	
function viewHiddenDiv(id)
	{
	var div = document.getElementById(id);
	if(div.style.visibility == "visible" && div.style.display == "block")
		{
		div.style.visibility = "hidden";
		div.style.display = "none";
		}
	else if(div.style.visibility == "hidden" && div.style.display == "none")
		{
		div.style.visibility = "visible";
		div.style.display = "block";
		}
	else{
		div.style.visibility = "visible";
		div.style.display = "block";
		}
	}
	
	
	
function viewIfChecked(id,input)
	{
	var input = document.getElementById(input);
	if(input.checked == true)
		{
		viewOrHiddenDiv(id,'view')
		}
	else{
		viewOrHiddenDiv(id,'hidden')
		}
	}
	
/*///FONCTION DE TEXTE///*/

/*Vérifier une adresse email*/

function checkMail(email)
	{
	var place = email.indexOf("@",1);
	var point = email.indexOf(".",place+1);
	var domain = email.charAt(point+1);
	domain = email.substring(point+1,email.length);
	heberg = email.substring(place+1,point);

	if((place > -1)&&(email.length >2)&&(point > 1) && (domain!="" && domain.length > 1) && (heberg.length > 1))
		{
		return true;
		}
	else{
		return false;
		}
	}
	
/*Vérifier une URL*/
	
function checkUrl(url)
	{
	var exp = new RegExp("^((http|https|ftp)://|www).{2,}[.].{2,}$","g");
	return exp.test(url);
	}

/*Vérifier que la valeur est un chiffre*/

function is_chiffre(valeur)
	{
	var exp = new RegExp("^[0-9]*$","g");
	return exp.test(valeur);
	}
	
/*Vérifier que la valeur est un prix*/

function is_money(valeur)
	{
	var exp = new RegExp("^€?[0-9]*[.,]{0,1}[0-9]{0,2}$","g");
	return exp.test(valeur);
	}
	
/*Vérifier que la valeur est une couleur valide*/

function is_color(entry)
	{
	var validChar='0123456789ABCDEF';
	entry=entry.toUpperCase();   // lowercase characters?
	var strlen = entry.length;
	if(strlen == 6)
		{
		var error =0;
		// Now scan string for illegal characters
		for (i=0;i<strlen;i++)
			{
			if(validChar.indexOf(entry.charAt(i))<0)
				{
				error++;
				} // end scanning loop
			}
		if(error == 0)
			{
			return true;
			}
		else{
			return false;
			}
		}
	else{
		return false;
		}
	}
	
/*Vérifier une date*/

function is_Date(d) {
// Cette fonction permet de vérifier la validité d'une date au format jj-mm-aaaa
if (d == "") // si la variable est vide on retourne faux
return false;

e = new RegExp("^[0-9]{1,2}-[0-9]{1,2}-([0-9]{4})$");

if (!e.test(d)) // On teste l'expression régulière pour valider la forme de la date

return false; // Si pas bon, retourne faux
// On sépare la date en 3 variables pour vérification, parseInt() converti du texte en entier
j = parseInt(d.split("-")[0], 10); // jour
m = parseInt(d.split("-")[1], 10); // mois
a = parseInt(d.split("-")[2], 10); // année


// Définition du dernier jour de février
// Année bissextile si annnée divisible par 4 et que ce n'est pas un siècle, ou bien si divisible par 400
if (a%4 == 0 && a%100 !=0 || a%400 == 0) fev = 29;
else fev = 28;

// Nombre de jours pour chaque mois
nbJours = new Array(31,fev,31,30,31,30,31,31,30,31,30,31);

// Enfin, retourne vrai si le jour est bien entre 1 et le bon nombre de jours, idem pour les mois, sinon retourn faux
return ( m >= 1 && m <=12 && j >= 1 && j <= nbJours[m-1] );
}
//--> 

/*///INITIALISATION DU DRAG AND DROP///*/

function dragOk(fct)
	{
	//Les div à trouver
	var ok = document.getElementById('dragOk');
	if(ok)
		{
		setTimeout(""+fct+"",100);
		}
	else{
		setTimeout("dragOk('"+fct+"')",200);
		}
	}
	
/*///CREATION DE LA LISTE 2 COLONNE POUR LE DRAG AND DROP///*/
function createSortable(id_1,id_2)
	{
	Sortable.create(id_2,{containment:[id_1,id_2],dropOnEmpty:true});
	Sortable.create(id_1,{containment:[id_1,id_2],dropOnEmpty:true});
	}
	

/*/ORDONNER UNE LISTE DRAG AND DROP AVEC BUTTON/*/

function moveUp(list, row) {
moveRow(list, row, 1);
}

function moveDown(list, row) {
moveRow(list, row, -1);
}

function moveRow(list, row, dir) {
var sequence=Sortable.sequence(list);
for (var j=0; j<sequence.length; j++) {
var i = j - dir;
if (sequence[j]==row && i >= 0 && i <= sequence.length) {
var temp=sequence[i];
sequence[i]=row;
sequence[j]=temp;
break;
}
}

Sortable.setSequence(list, sequence);
}


	
/*///Remplacer des caractères dans une chaine///*/

function Remplace(expr,a,b)
	{
      var i=0
      while (i!=-1) {
         i=expr.indexOf(a,i);
         if (i>=0) {
            expr=expr.substring(0,i)+b+expr.substring(i+a.length);
            i+=b.length;
         }
      }
      return expr
   }
   

/*///ALLEZ SUR LE ANCHOR///*/
	
function goAnchor(id)
	{
	window.location.href= '#anchor_'+id;
	}
	
/*/// CHECKBOX ACTION ///*/

function checkAll(from,what)
	{
	var nb_check = document.getElementsByName(what).length;
	var statut = (document.getElementById(from).checked == true)? true : false;
	for(var i = 0 ; i < (nb_check + 1) ; i++)
		{
		var id = what+'_'+i;
		if(document.getElementById(id))
		document.getElementById(id).checked = statut ;
		}
	}
	
	
function checkBoxAction(what,action)
	{
	var nb_check = document.getElementsByName(what).length;
	for(var i = 0 ; i < nb_check ; i++)
		{
		if(action == true)
			{
			document.getElementById(what+i).checked = "checked" ;
			}
		else if(action == false)
			{
			document.getElementById(what+i).checked = "" ;
			}
		}
	}

function BoxCmder(id,what)
	{
	var nb_check = document.getElementsByName(what).length;
	var statut = 0;
	for(var i = 0 ; i < nb_check ; i++)
		{
		if(document.getElementById(what+i).checked == true)
			{
			statut++;
			}
		}
	if(statut == nb_check)
		{
		document.getElementById(id).checked = "checked";
		}
	else{
		document.getElementById(id).checked = "";
		}
	}
	
function executeCopy(from,pour)
	{
	var checkbox = document.getElementById(from);
	var action = (checkbox.checked == true)? "copy" : "remove" ;
	
	if(pour == "fact_livr_address")
		{
		copyData(pour,action);
		}
	}
	

//function de transfert de donnée vers un div

function transData(value , dest , hiddendiv)
	{
	document.getElementById(dest).value = value;
	if(hiddendiv)
		{
		viewHiddenDiv(hiddendiv);
		}
	}
	
	
	
function checkCaptcha(valeur,dest)
	{
	var ajax = new Ajax.Updater(dest,'captcha_check.php',{method: 'POST',parameters: 'valeur='+valeur});
	return ajax;
	}
	
function refreshCaptcha(captcha)
	{
	document.getElementById(captcha).src = "captcha/CaptchaSecurityImages.php?width=100&height=50&characters=5&date="+escape(new Date());
	}
	
function ajustDimension(to,from,offset_w,offset_h,color){
	if(color){document.getElementById(to).style.backgroundColor = color;}
	document.getElementById(to).style.width = ($(from).getWidth() - offset_w)+"px";
	document.getElementById(to).style.height = ($(from).getHeight() - offset_h)+"px";
}

function setDimension(id,hdim,vdim){
	document.getElementById(id).style.width = vdim+"px";
	document.getElementById(id).style.height = hdim+"px";
}

function completeTxt(name,sens,base,dest){
	var base = document.getElementById(base).value;
	var name = document.getElementById(name).value;
	//Sens = s ou e (start ou end)
	if(sens == "s")
		{
		document.getElementById(dest).value = name+' '+base;
		}
	else if(sens == "e")
		{
		document.getElementById(dest).value = base+' '+name;
		}
}

function favoris(bookmarkurl,bookmarktitle) {
if ( navigator.appName != 'Microsoft Internet Explorer' ){
window.sidebar.addPanel(bookmarktitle,bookmarkurl,"");
}
else {
window.external.AddFavorite(bookmarkurl,bookmarktitle);
}
} 


function formatTextarea(text,sens){
	if(sens == 'html')
		{
		var a = '\n';
		var b = '<br/>';
		}
	else{
		var b = '\n';
		var a = '<br/>';
		}
	var text_formated = Remplace(text,a,b);
	return text_formated;
}


function soundSession(state)
	{
	var zoneaction = document.getElementById('action_execute');
	zoneaction.value = "sessionSound";
	var zoneid = document.getElementById('id_execute');
	zoneid.value = state;
	protoAjax('sound.php','POST','action_ajax','execute','loading');
	}
	
function removeValueInArray(Arr,p_val) {
    var toRemove = null;
    for(var i = 0, l = Arr.length; i < l; i++) {
        if(Arr[i] == p_val) { toRemove = { id: i, value: Arr[i] }; }
    }
 
    if (toRemove != null) {
        for (var i = toRemove.id; i < Arr.length; i++) {
            Arr[i] = Arr[i+1];
        }
        Arr.pop();
        return toRemove.value;
    }
 
    return null;
}

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


function checkOther(from,id){
if(document.getElementById(from).checked == true)
	{
	document.getElementById(id).checked = true;
	}
}

function locationInfo(action,from){
	if(action == "autocomplete")
		{
		new Ajax.Autocompleter(from, from+"_autocompleter", "localisation.php",{indicator:'loading_'+from,
  minChars: 2,parameters: 'action='+action, afterUpdateElement :setLocationValues},{})
		}
}

function setValue(element,attr) {
	var e = document.getElementById(element);
	if (e==null){return;}
	if (attr == -1) {e.value = '';} 
	else if (attr != null && attr != ' ' && attr != '') {e.value = attr;}
}

function setLocationValues(text, li)
{
	if(document.getElementById('localisation_id'))
	setValue('localisation_id',li.getAttribute('localisation_id'));
	if(document.getElementById('cp'))
	setValue('cp',li.getAttribute('localisation_cp'));
	if(document.getElementById('city'))
	setValue('city',li.getAttribute('localisation_city'));
	if(document.getElementById('country'))
	setValue('country',li.getAttribute('localisation_country'));
}

function clientInfo(action,type,from){
	if(action == "autocomplete")
		{
		new Ajax.Autocompleter(from, from+"_autocompleter", "client.php",{indicator:'loading_'+from,
  minChars: 2,parameters: 'action='+action+'&type='+type, afterUpdateElement :setClientValues},{})
		}
}

function setClientValues(text, li)
{
	if(document.getElementById('client_id'))
	setValue('client_id',li.getAttribute('client_id'));	
	var clientdata = li.getAttribute('client_prenom')+' '+li.getAttribute('client_nom')+' ('+li.getAttribute('client_localisation')+')';
	if(document.getElementById('client'))
	setValue('client',clientdata);
}

function articleInfo(action,from){
	if(action == "autocomplete")
		{
		new Ajax.Autocompleter(from, from+"_autocompleter", "article.php",{indicator:'loading_'+from,
  minChars: 2,parameters: 'action='+action, afterUpdateElement :setArticleValues},{})
		}
}

function setArticleValues(text, li)
{
	if(document.getElementById('article'))
	setValue('article',li.getAttribute('article'));	
	if(document.getElementById('description'))
	tinyMCE.get('description').setContent(li.getAttribute('description'));	
	if(document.getElementById('url'))
	setValue('url',li.getAttribute('url'));	
}

function lightviewPicture(url){
	Lightview.show({
  href: url,
  rel: 'image'
});
}

function sleep(time, func) {
    setTimeout(func,time);
}



/*LISTE CADEAU*/

var Reseller = Class.create();

Reseller.prototype = {
  initialize: function() {
  },
  
  login: function(){
	Lightview.show({href: 'shop.php',rel: 'ajax',title: 'Login Reseller',
	  options: {autosize: true,topclose: false,closeButton:false,ajax: {method: 'POST',
		  parameters: 'action=loginreseller',
		  onComplete: function (){}
			}
		  }
		}); 
 },
  
 login_exec: function(){
	 lightAjax('shop.php','','POST','login_reseller',false,'okOrNo("window.location.reload(true)","",2000)');
 },
 
 logout: function(){
	 Lightview.show({href: 'shop.php',rel: 'ajax',title: 'Logout Reseller',
	  options: {autosize: true,topclose: false,closeButton:false,ajax: {method: 'POST',
		  parameters: 'action=logout',
		  onComplete: function (){okOrNo("window.location.reload(true)","",2000)}
			}
		  }
		}); 
 }
}


var Reseller = new Reseller();

