﻿//Le script démarre une fois la page terminé
var PageLettre = "<h1>Mots commençant par la lettre [LETTRE]</h1><blockquote>Consultez la liste des mots commençant par cette lettre.</blockquote><div class='fleche'></div>";
var stringHash = /#/;
var inline_link_splitter = /\?Element=/;
var enterdisable = false;

// Redirection d'un adresse non-ajax
var splitted_location = new String(document.location).split("/");  
var splitted_param = new String(splitted_location[splitted_location.length -1]).split("?");
if(splitted_param[1]){       
    var params = splitted_param[1].split("&");
    for(p = 0; p < params.length; p++)
    {                  
        cparam = params[p].split("=");
        if(cparam[0].toLowerCase() == "element"){
            element = cparam[1].split("#");             
            window.location = "Default.aspx#" + element[0];
        }            
    }
}


$("document").ready( function(){     
   
    //reconstruction du href des lettres
    $(".patenaude_link a").attr("href", '#auteur');
    $("a.link_footer").each(function(){$(this).attr("href", "#" + $(this).html().toLowerCase());  });  
    
    $("#LettresDiv a").each( function() {       
        $(this).attr("href", "#" + $(this).html()); //Brise la navigation conventionnelle  
        $(this).click(function(){if($('#RechercherTextBox').val() != ""){$('#RechercherTextBox').val("");pageload($(this).html())}});
    });
    //reconstruction du href des éléments
    activate_dyn_ajax_action();  
       
    //Activation de la navigation AJAX
    $.historyInit(pageload);   
    
    //Activation de la navigation keydown
    keyDownNavigation();
    $("#form1").unbind();
    //Activation du livesearch
    livesearch.init();      
    
});

//Le Core central de la navigation AJAX
function pageload(hash) {
	// la variable hash ne contient pas le #

	var hash = new String(hash);
	
	if(hash != '') {
	    		    
	    if(stringHash.test(hash)){
	        var hashs = hash.split("#");
	        hash = hashs[0];
	        $("#" + hashs[1]).focus();
	    }
	    
	    hash = transcodeUTF8SpecialChar(hash);
	    
	    // Lancer la recherche par le hash
	    if(hash.substr(0,2) == "s_"){
	        livesearch.searchFromHash(hash.substr(2));	        
	        return;
	    }
	    
	    
		// Navigation par le Hash
		if(hash == "accueil" || hash == "auteur" || hash == "références" || hash == "liens" || hash == "commentaires"){}else{
		    if(($("div#LettresDiv a.active").html() != hash.substring(0,1).toUpperCase() && $('#RechercherTextBox').val() == "" ) ||  hash.length == 1){
		        
		        getLetter(hash.substring(0,1));	
		        if(hash.length == 1){
		            letterPage(hash.substring(0,1));       
		        }		        
		    }
		}
		if(hash.length > 1){ 
		    getElement(hash);          
		    document.title = hash + " – Lexique de mathématique" ;            
		}
	} else {
		// Load la page d'accueil et la liste A
		getLetter("A");
		window.location = "#accueil";
	}
}
	
		
livesearch = {
  t: 0,
  one_letter : false,
  search: function() {
    var word = $('#RechercherTextBox').val(); 
   
    if(word == "") return false;   
        
    if(word.length == 1){       
        var isLetterExp = /[a-zA-Z]{1}/;
        if(isLetterExp.test(word)){           
            livesearch.one_letter = true;
            var loc = new String(window.location);
            var letter = word.toUpperCase();
            var hash = loc.split("#");hash = hash[1].toUpperCase();
            if(hash == letter){letterPage(hash.substring(0,1));getLetter(letter);}
            window.location = "#" + letter;         
            return false;
        }
    }    
    livesearch.one_letter = false;
    $("div#LettresDiv a.active").removeClass("active");    
    
    livesearch.lunchSearch(word);
  },
  searchFromHash: function(string) {
    var word = string; 
   
    if(word == "") return false;   
        
    if(word.length == 1){       
        var isLetterExp = /[a-zA-Z]{1}/;
        if(isLetterExp.test(word)){           
            livesearch.one_letter = true;
            var loc = new String(window.location);
            var letter = word.toUpperCase();
            var hash = loc.split("#");hash = hash[1].toUpperCase();
            if(hash == letter){letterPage(hash.substring(0,1));getLetter(letter);}
            window.location = "#" + letter;         
            return false;
        }
    }    
    livesearch.one_letter = false;
    $("div#LettresDiv a.active").removeClass("active");    
    
    livesearch.lunchSearch(word);
  },
  lunchSearch: function(word){
    $.get("lexique_query.aspx", {Action: "getResult", Recherche: word},
           function (xml){
             $("ul#SectionDiv").html($("data",xml).text());                           
             activate_dyn_ajax_action();   
            
             var found = false; 
            
             //Terme rechercher
             var currentquery = $("currentQuery", xml).text().toLowerCase();
             //Trim white space au début et à la fin.
             currentquery = currentquery.replace(/^\s+|\s+$/g, '');
             
             for(x=0; x< $("ul#SectionDiv li").length; x++){
                if($("ul#SectionDiv li:eq(" + x + ")").text().toLowerCase() == currentquery){
                    var word = $("ul#SectionDiv li:eq(" + x + ")").text();
                    highLightLetter(word.substring(0,1));
                    getElement(word);  //À trouver l'élément exacte
                    found = true;                   
                }
             }
             if(found == false){
                $("div#ElementDiv").html($("message",xml).text());
             }
           }
     )
  },
  init: function(){
    //Retire la configuration autucomplete sur le champ de recherche
    $('#RechercherTextBox').attr('autocomplete', 'off');
     $('#RechercherTextBox').unbind("keydown");

    
    //Active la recherche lorsqu'on passe sur le champ de recherche
    $('#RechercherTextBox').focus(function(){
      $(this).css("background-color", "#fff");
      $(this).keydown(function(e){      
         if(e.keyCode == 32) return true;     
         if (e.keyCode == 13) {
             clearTimeout(livesearch.t);
             livesearch.search();
             return false;
         }else{
             if (livesearch.t) clearTimeout(livesearch.t);
             livesearch.t = setTimeout("livesearch.search()", 600);
         }
      });
    }, function(){});
    //Désactive la recherche lorsqu'on sort clique ailleur dans la page
    $('#RechercherTextBox').blur(function(){
      $(this).unbind("keydown");
    });
    $('#RechercherButton').click(function(){livesearch.search();return false;});
  }
};

function keyDownNavigation(){
    $(document).keydown(function(e){       
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
		switch(key) {
			case 37: 
			  navElement("previous");
			  break;			
			case 39: 
			  navElement("next");
			  break;			
			case 13: 
			  if(enterdisable == false){
			    navElement("open");
			  }
			  break;
		}
    });    
}

function navElement(action){
    
    var list = $("ul#SectionDiv");
    if(!list.find("li")) return false;
    
    var actif = $("ul#SectionDiv a.actif");
    var keyActif = $("ul#SectionDiv a.keyActif");
    var active = (keyActif.html() != null) ? keyActif : ((actif.html() != null) ? actif : $("ul#SectionDiv li a:first") );
    
   
   
    $(".keyActif").removeClass("keyActif");         
    switch(action){
        case "previous": active.parent().prev("li").find("a").addClass("keyActif");break;
        case "next": active.parent().next("li").find("a").addClass("keyActif");break;
        case "openprevious": 
               prev = actif.parent().prev("li").find("a").html();
               if(prev == null)return;
               window.location = "#" + prev;break;
        case "opennext": 
               next = actif.parent().next("li").find("a").html()
               if(next == null)return;
               
               window.location = "#" + next;break;
        case "open": window.location = "#" + active.html();break;
    }
}


//Recherche d'une lettre sur le serveur
function getLetter(attr_letter){    
    //Règle les problèmes d'accent   
    attr_letter = transcodeLetter(attr_letter);
      
    $.get("lexique_query.aspx", {Action: "getSection", Section: attr_letter},
           function (xml){
            $("ul#SectionDiv").html($("data",xml).text());            
            activate_dyn_ajax_action();                      
           }
     )    
     highLightLetter(attr_letter); 
     if(livesearch.one_letter == false) $('#RechercherTextBox').val('');
}

//Recherche d'un éléement sur le serveur
function getElement(attr_element){    
    $("div#ElementDiv").fadeTo("fast", 0.3);
    $.get("lexique_query.aspx", {Action: "getElement", Element: attr_element},
           function (xml){           
            
            enterdisable = (attr_element == 'commentaires') ? true : false;
            //Send page change to Google Analytics
            if(attr_element != 'accueil'){
             _uacct = "UA-97685-5";
             urchinTracker("/terme/" + attr_element);
            }
           
            $("div#ElementDiv").html($("data",xml).text());
            activate_dyn_interne_ajax_action(attr_element);
            
            
            $("textarea").unbind();
            
             highLightElement(attr_element);
            
            
            $("div#ElementDiv").fadeTo("fast", 1.1);              
              
            if(attr_element == "accueil" || attr_element == "auteur" || attr_element == "références" || attr_element == "liens" || attr_element == "commentaires"){
                place_next_previous_print(attr_element, true);           
            }else{
                highLightLetter(transcodeLetter(attr_element.substring(0,1)));
                place_next_previous_print(attr_element, false);
                window.scrollTo(0,112);
              }    
                
              
             
           }
     )         
} 

//Activation des événements onclick sur tout les liens de recherche
function activate_dyn_ajax_action(content){
    $("#SectionDiv li a").each( function() {
       $(this).attr("alt", $(this).html());
       $(this).attr("href", "#" + $(this).html().toLowerCase()); //Brise la navigation conventionnelle            
    });
}

//Activation des événements onclick sur tout les liens de recherche
function activate_dyn_interne_ajax_action(currentTerme){
     $("div#ElementDiv a").each(function(){dyn_interne_ajax_action($(this), currentTerme)});
     $("div#ElementDiv area").each(function(){dyn_interne_ajax_action($(this), currentTerme)});    
}

function dyn_interne_ajax_action(item, currentTerme){
   if(item.attr("href")){          
       if(inline_link_splitter.test(item.attr("href"))){             
            var split_href = item.attr("href").split(inline_link_splitter);           
            item.attr("href", "#" + split_href[(split_href.length -1)]);               
       }else{
          //Vérifie les liens internes à cette page
         if(stringHash.test(item.attr("href"))){ 
             var split_href = item.attr("href").split(stringHash);
           item.attr("href", "#" + currentTerme + "#" + split_href[(split_href.length -1)]);
         }    
       }          
   }  
}

function highLightLetter(letter){
    $("div#LettresDiv a.active").removeClass("active");    
    $("div#LettresDiv a:contains('" + letter.toUpperCase() + "')").addClass("active"); 
}

function highLightElement(element){
    $(".actif").removeClass("actif");       
    $("a[@alt=" + element + "]").addClass("actif");  
}

function letterPage(letter){
    $("div#ElementDiv").fadeTo("fast", 0.3, function(){$("div#ElementDiv").html(PageLettre.replace("[LETTRE]", letter));$("div#ElementDiv").fadeTo("fast", 1.1);});
}

function place_next_previous_print(element, onlyprinter){
    var app = "<a href='#' class='btn printer'  onClick='window.print();return false;'></a>";
    if(!onlyprinter && $("a[@alt=" + element + "]").parent().next("li").html() != null) app += "<a href='#' class='btn next' onClick='navElement(\"opennext\");return false;'></a>";
    if(!onlyprinter && $("a[@alt=" + element + "]").parent().prev("li").html() != null) app += "<a href='#' class='btn previous' onClick='navElement(\"openprevious\");return false;'></a>";
    $("div#ElementDiv h1:first").append(app);
}


function transcodeLetter(text){
    var from = new Array('à','é','è','ê','ô','û');
    var to   = new Array('a','e','e','e','o','u');     
    text = text.toLowerCase(); 
         
	for(l = 0; l < from.length ; l++){	    
	    strTarget = from[l];
	    strSubString = to[l];
	    var intIndexOfMatch = text.indexOf( strTarget );
	    while (intIndexOfMatch != -1){		         
		    text = text.replace( strTarget, strSubString );		   
		    intIndexOfMatch = text.indexOf( strTarget );
	    }
	}	
	
	return text;
}


function transcodeLetter(text){
    var from = new Array('à','é','è','ê','ô','û');
    var to   = new Array('a','e','e','e','o','u');     
    text = text.toLowerCase(); 
         
	for(l = 0; l < from.length ; l++){	    
	    strTarget = from[l];
	    strSubString = to[l];
	    var intIndexOfMatch = text.indexOf( strTarget );
	    while (intIndexOfMatch != -1){		         
		    text = text.replace( strTarget, strSubString );		   
		    intIndexOfMatch = text.indexOf( strTarget );
	    }
	}	
	
	return text;
}


function transcodeUTF8SpecialChar(text){
    var from = new Array('%C3%A0','%C3%A2','%C3%A9','%C3%A8', '%C3%AA', '%C3%B4','%C3%B6', '%C3%89', '%C3%AF','%20');
    var to   = new Array('à','â','é','è', 'ê','ô','ö',"É",'ï',' ');     
                
	for(l = 0; l < from.length ; l++){	    
	    strTarget = from[l];
	    strSubString = to[l];
	    var intIndexOfMatch = text.indexOf( strTarget );
	    while (intIndexOfMatch != -1){		         
		    text = text.replace( strTarget, strSubString );		   
		    intIndexOfMatch = text.indexOf( strTarget );
	    }
	}	
	return text;
}
