/*************** Début specif international****************************/

/*spécifité ie : surcharge de la fonction getElementsByClassName*/
if (!document.getElementsByClassName){
  document.getElementsByClassName = function(nameOfClass,nameOfTag){
		var i = 0;
		var j = 0;
		var rep = new Array();
          var div = document.getElementsByTagName(nameOfTag);
          
          while (element = div[i++]) {
                 if (element.className == nameOfClass) {
                        rep[j] = element;
                        j++;
                 }
          }
          return rep;
  }
}


/*Récupération de la langue courante en utilisant le breadcrumb; retourne null si le site n'a pas de 1er niveau*/
function currentLanguage(){
	var breadcrumbs = document.getElementsByClassName("breadcrumb_navigation","span");
	if (breadcrumbs.length > 0) {
		var breadcrumb = breadcrumbs[0].getElementsByTagName("a");
		if(breadcrumb.length>1){
			currentLang = breadcrumb[1].getAttribute("href");
		} else {
			currentLang = null;
		}
		return currentLang;
	}
	return null;
}

/*Contextualisation sur le body : ajoute la langue comme class sur la balise body*/
/*Précondition : il faut que la premier niveau de l'arborescence soit la langue*/
function context(){
	var bodyElt = document.getElementsByTagName('body');
	currentLang = currentLanguage();
	
	if(currentLang != null) {
		/*parse la chaîne de langue
		spécifité ie6 et 7 : currentLang = http://nomdusite/langue/
		autres navigateurs : currentLang = /langue/
		*/
		var lastSlash = currentLang.lastIndexOf("/",currentLang.length);
		currentLang = currentLang.substring(0,lastSlash);
		var firstSlash = currentLang.lastIndexOf("/",currentLang.length);
		currentLang = currentLang.substring(firstSlash+1,currentLang.length);
		bodyElt[0].className = currentLang;
	}
}


/*Supprime les actualités n'étant pas dans la langue courante dans la boite actualité en mode statique*/
/*Précondition : il faut ajouter l'appel du script dans le template last_elements.html et encapsuler les news dans un div*/
function staticNewsInt(){
	currentLang = currentLanguage();
	if(currentLang != null) {
		var boxLastElements = document.getElementsByClassName("staticsnews","div");
		//alert(boxLastElements);
		var nbCarLanguage = currentLang.length;
		var divDelete = new Array();
		var k = 0;
		
	
		for (var i = 0; i < boxLastElements.length; i++) { 
			var lien = boxLastElements[i].getElementsByTagName("a");
			for (var j = 0; j < lien.length; j++) { 
				var status = lien[j].getAttributeNode("href").value; 	
		    	if(status.substring(0,nbCarLanguage) != currentLang){
		    		divDelete[k] = lien[j].parentNode;
		    		k++;
		    	}	
			}
		}
		
		/*On enlève les Div sélectionnés précédement*/
		if(boxLastElements.length > 0){
			this.div = boxLastElements[0].parentNode;
			for(var l = 0; l <divDelete.length; l++){
				    this.div.removeChild(divDelete[l]);
			}
		}
	}
}
/*************** FIN specif international****************************/




function scrollerInt(name, divid, delay, incr, pause){



	this.name = name;
	this.div = document.getElementById(divid);
	
	
	
	/*************** Début specif international****************************/
	/****Supprime les actualités n'étant pas dans la langue courante*******/
	
	/*Récupère la langue courante*/
	currentLang = currentLanguage();
	
	if(currentLang != null) {
	
		/*Liste des div qui ont un lien vers une rubrique qui ne fait pas partie de la langue courante*/
		var lien = this.div.getElementsByTagName("a");
		var nbCarLanguage = currentLang.length;
		var divDelete = new Array();
		var k = 0;
		for (var j = 0; j < lien.length; j++) { 
	    	var status = lien[j].getAttributeNode("href").value; 	
	    	if(status.substring(0,nbCarLanguage) != currentLang){
	    		//cells[j].parentNode.style.display="none";
	    		divDelete[k] = lien[j].parentNode;
	    		k++;
	    		}		
		}
		
		/*On enlève les Div sélectionnés précédement*/
		for(var l = 0; l <divDelete.length; l++){
			    this.div.removeChild(divDelete[l]);
		}
		
    /*Nettoyage des div suppression ou ajout d'actualités à la fin du bloc*/
		lien = this.div.getElementsByTagName("a");
		if(lien.length>1){
//alert(lien[0].getAttributeNode("href").value);
		  /*Cas ou il y a plusieurs actualités, Ajoute le div de fin en début si ce n'est pas le cas */
			if(lien[0].getAttributeNode("href").value != lien[lien.length-1].getAttributeNode("href").value){
					
				cloneLast = lien[lien.length-1].parentNode.cloneNode(true);
				this.div.insertBefore(cloneLast,lien[0].parentNode);
			} else {
			     /*Cas où il n'y a que 2 actualités identiques => supression de la dernière pour éviter l'affichage dynamique*/
			     if(lien.length==2){
			       this.div.removeChild(lien[lien.length-1].parentNode);
           }
      }
		}

	}
	/*************** Fin specif international****************************/
	

	
	

	
	
	this.size = Math.abs(parseInt(this.div.style.height));
	this.pos = 0;
	this.nextPos = 0;
	this.delay = delay;
	this.pause = pause;
	this.incr = incr;
	this.timer = 0;
	this.pauseTimer = 0;
	this.wait = true;
	this.relativeY = false;
	this.mouseIsDown = false;
	this.fixedMode = false;
	this.cursor = "move";
	
	


	
		
	this.run = function(){
		if (this.pos <= this.nextPos) {
			var incr;
			/* amortissement */
			if (this.nextPos - this.pos <= this.incr) {
				incr = Math.ceil((this.nextPos - this.pos)/2);
				if (incr > this.incr){
					incr = this.incr;
				} else if (incr == 0) {
					incr = 1;
				}
			} else {
				incr = this.incr;
			}
			this.pos += incr;
			this.div.scrollTop = this.pos;
			if (this.div.scrollTop != this.pos) {
				window.clearInterval(this.timer);
				window.clearInterval(this.pauseTimer);
				this.start();
			}
		} else {
			window.clearInterval(this.timer);
			window.clearInterval(this.pauseTimer);
			this.wait = true;
			this.pauseTimer = window.setTimeout(this.name+'.next()', this.pause);
		}
	}
	
	this.start = function(){
		this.pos = 0;
		this.nextPos = 0;
		window.clearInterval(this.timer);
		window.clearInterval(this.pauseTimer);
		this.pauseTimer = window.setTimeout(this.name+'.next()', this.pause);
	}
	
	this.next = function(){
		this.wait = false;
		this.pos = this.nextPos;
		this.nextPos += this.size;
		window.clearInterval(this.timer);
		window.clearInterval(this.pauseTimer);
		this.timer = window.setInterval(this.name+'.run()', this.delay);
	}
	
	this.stop = function(){
		window.clearInterval(this.timer);
		window.clearInterval(this.pauseTimer);
	}
	
	this.restart = function(){
		this.pos = Math.abs(this.div.scrollTop);
		this.nextPos = 0;
		while(this.nextPos < this.pos) {
			this.nextPos += this.size;
		}
		this.wait = false;
		window.clearInterval(this.timer);
		window.clearInterval(this.pauseTimer);
		this.timer = window.setInterval(this.name+'.run()', this.delay);
	}
	
	this.mouseover = function(e){
		if (!this.fixedMode){
			var relatedElmt;
			if (!e) {
				relatedElmt = window.event.fromElement;
			} else {
				relatedElmt = e.relatedTarget;
			}
			if (!this.relatedIsIn(relatedElmt)) {
				this.div.style.cursor = this.cursor;
				this.stop();
			}
		}
	}
	
	this.mouseout = function(e){
		if (!this.fixedMode){
			var relatedElmt;
			if (!e) {
				relatedElmt = window.event.toElement;
			} else {
				relatedElmt = e.relatedTarget;
			}
			if (!this.relatedIsIn(relatedElmt)) {
				this.div.style.cursor = "default";
				this.restart();
			}
		}
	}
	
	this.mousedown = function(e){
		if (!e) var e = window.event;
		this.relativeY = e.clientY;
		this.mouseIsDown = true;
		return false;
	}
	
	this.mouseup = function(e){
		this.relativeY = false;
		this.mouseIsDown = false;
		return false;
	}
	
	this.mousemove = function(e){
		if (this.mouseIsDown && !this.fixedMode) {
			if (!e) var e = window.event;
			this.scroll(this.relativeY - e.clientY);
			this.relativeY = e.clientY;
		}
	}
	
	this.mouseWheel = function(e, ref){
		if (e) {
			this.scroll(10*e.detail);
			e.preventDefault();
		} else {
			if (ref == this.div) {
				this.scroll(-window.event.wheelDelta);
			}
			return false;
		}
	}
	
	this.scroll = function(l){
		var newPos = this.div.scrollTop + l;
		this.div.scrollTop += l;
		if (newPos > this.div.scrollTop) {
			this.div.scrollTop = newPos - this.div.scrollTop;
		} else if (newPos < this.div.scrollTop) {
			this.div.scrollTop = this.div.scrollHeight - (this.div.scrollTop - newPos);
		}
	}
	
	this.dblclick = function(e){
		if (this.fixedMode) {
			this.cursor = "move";
			this.fixedMode = false;
			this.div.style.MozUserSelect = "none";
			this.div.onselectstart = function(){return false;};
			this.restart();
		} else {
			this.cursor = "text";
			this.fixedMode = true;
			this.div.style.MozUserSelect = "";
			this.div.onselectstart = function(){return true;};
			this.stop();
		}
		this.div.style.cursor = this.cursor;
	}
	
	/* Cherche si l'objet relatif à l'évènement est un sous-élement */
	this.relatedIsIn = function(reltg){
		while (reltg && reltg != this.div && reltg.nodeName != 'BODY')
			reltg= reltg.parentNode;
		if (reltg && reltg == this.div)
			return true;
		return false;
	}
	
	/* Désactive la sélection */
	this.div.style.MozUserSelect = "none";
	this.div.onselectstart = function(){return false;};
	
	if (document.addEventListener) eval("this.div.addEventListener('DOMMouseScroll', function(e){"+this.name+".mouseWheel(e);}, false)");
	else eval("this.div.onmousewheel = function(){return "+this.name+".mouseWheel(0, this);};");
	
	var events = ['mouseover', 'mouseout', 'mousedown', 'mouseup', 'mousemove', 'dblclick'];
	for(ev in events) {
		try{eval("this.div.on"+events[ev]+" = function(e){"+this.name+"."+events[ev]+"(e);}");}
		catch(e){}
	}
	
	this.start();
}

/*************** Début specif international****************************/

/***************Gestion des rubriques lors du changement anglais/français****************************/

/*Donne seulement les enfants de premier niveau de eltNode qui ont pour classe className*/
function getChildsByClassName(eltNode,className){
  var children = eltNode.childNodes;
  var listChild = new Array();
  var j=0;
  for(var i=0;i<children.length;i++){
    if(children[i].className==className){
      listChild[j]=children[i];
      j++;
    }
  }
  return listChild;
}

/*Donne le lien "href" à la posiition indiqué*/
function getCategoryAtPosition(secondLevelNode,position){
  var list = secondLevelNode.getElementsByClassName("second_level","span");
  var tmp = list[0].childNodes;
  var cat;

  for(var i=0;i<tmp.length;i++){
    if(i==position){
      var tmp2 = tmp[i].getElementsByTagName("a");
      cat = tmp2[0].getAttribute("href");
    } 
  }
  return cat;
}

/*Change le lien du menu indiquant la langue pour que celui pointe vers la même rubrique dans l'autre langue
Exemple: arborscence :  - fr -> Accueil/Actualités/Contact
                        - en -> Home/News/Contact
Nous sommes dans "Actualités" et nous voulons changer de langues, sans ce script on se retrouve dans la 1ere 
rubrique contenur dans la rubrique en soit Home. Avec le script, on se retrouve dans la rubrique News.
Précondition: avoir le même nombre de rubriques dans les différentes langues
*/
function switchLanguage(){

  var firstLevelNodes = document.getElementsByClassName("first_level","span");
  var secondLevelNodes;
  var active;
  var menuActive;
  var newLink;
  var counter = 0;
  var cat;

  /*Calcul de la position de la rubrique courante*/
  if(firstLevelNodes.length==1){
    active = getChildsByClassName(firstLevelNodes[0],"active");
    if(active.length==1){
      secondLevelNodes = active[0].getElementsByClassName("second_level","span");
      for(var i=0;i<secondLevelNodes[0].childNodes.length;i++){
        if(secondLevelNodes[0].childNodes[i].className=="active")counter=i;
      }
    }
    
    /*Changement du lien pour chaques langues*/
    defaultmenuNodes = getChildsByClassName(firstLevelNodes[0],"defaultmenu");
    for(var j=0;j<defaultmenuNodes.length;j++){
      /*récupère le nouveau lien*/
      cat = getCategoryAtPosition(defaultmenuNodes[j],counter);
      /*changement du lien*/
      defaultmenuNodes[j].childNodes[1].getAttributeNode("href").value = cat;
    }
  }
}
/***************Gestion des rubriques lors du changement anglais/français****************************/

$(document).ready(context);
$(document).ready(switchLanguage);
/*************** FIN specif international****************************/



