window.addEvent( 'domready', function() {
    init();
    initPopUp();
    menu_deroulant() ;
    hideSitemap();
    lien_blank();
    infobulle_accessible();
    //AJOUT POUR NOUVEAU SITEMAP
        if( $$(".sitemap").length>0 ){
        sitemap();
    }
    //FIN AJOUT POUR NOUVEUA SITEMAP
} );

function hideSitemap(){
 uls2 = $$('.accordion_2');
 uls = $$('.accordion_1');
 
 if(uls.length > 1){
	for(i=0; i < (uls2.length- 1); i++){
 		uls2[i].style.display = 'none';
	}

	for(i=0; i < (uls.length-1); i++){
 		uls[i].style.display = 'none';
	}
	
	
 }
 
 $$('.click').each( function( obj ) {
		 
	 if( obj.getElements( 'li' ).length != 0 )
	 {
		 
		 var plus_img = new Element( 'img', {
				 'src': img_deplie,
				 'alt': 'Déplier'
		 } );

		 ret = plus_img.inject( obj.getElement('span') );
		 obj.set('styles', {'background':'none',
				 'padding':'0'});		 
				 
		 
	 }else{
		 //obj.getElement('a').set('styles', {'margin-left':'17px'});
	 }
 } );
}

function init( ) {
    if( $('sommaireAuto') ) {
	    sommaireAutoInit();
		changeDisplaySommaire();
	}
    
    new SmoothScroll({  duration:700  }, window);
    
    /*initExternalLinks();*/
    /*var myTips = new Tips( '.tips' );*/
}

/*function initExternalLinks()
{
    $$( 'a[rel=external]' ).each( function( item ) {
        item.target = '_blank';
    } );
}*/

function initPopUp()
{
    $$('a.popup').each( function(item) {
        item.addEvent( 'click', function() {
            url = item.href;
            url = url.replace( 'http://' + location.host, '' );
            url = ezpopup + url;
            return open_popup( url );
        } );
    } );
}

function open_popup( url )
{
    window.open( url );
    return false;
}

function closeNAVc(){
	var ultoclose;
	var temp;
	
	ultoclose = document.getElementById('sitemap').getElementsByTagName('ul');
	for(var i=0; i<ultoclose.length; i++){
		temp = ultoclose[i].getElementsByTagName('ul');
		for(var y=0; y<temp.length; y++){
			temp[y].style.display = "none";
		}
	}
}

function showPrintLink()
{
	document.write('<span class="lien_imprimer"><a href="javascript:print();" title="' + print_title + '">' + print_label + '</a></span>');
}

function showSitemap(_o, _libel){
	var srub;
	
//	srub = _o.getElementsByTagName("ul");
	srub = document.getElementById("accordion_"+_libel);
	img = _o.getElementsByTagName("img");

	if( srub.style.display == "none" ){
		srub.style.display = "block";		
		img[0].title = "Cliquez pour replier le menu "; 
		img[0].src = "/extension/ird/design/ird/images/picto/picto_replie.png";
	}else if( srub.style.display =="block"  || srub.style.display ==""){
		srub.style.display = "none";		
		img[0].title = "Cliquez pour déplier le menu ";
		img[0].src = "/extension/ird/design/ird/images/picto/picto_deplie.png";
	}
}

function checkDaBox(_form, _param){

	var checkBox;
	var temp;	
	
	temp = document.getElementById(_form).getElementsByTagName('input');
	
	if(_param == 'off'){
		for( i = 0; i<temp.length; i++){
			if(temp[i].type == "checkbox"){
				temp[i].checked = false;
			}
		}
	}else{
		for( i = 0; i<temp.length; i++){
			if(temp[i].type == "checkbox"){
				temp[i].checked = true;
			}
		}
	}
	
	return false;
}

function GMapWritePoint( lat, lng , div )
{
    var myicon = new GIcon();
    myicon.image = picto_url;
    myicon.shadow = shadow_url;
    myicon.iconSize = new GSize( 42, 27 );
    myicon.shadowSize = new GSize( 42, 27 );
    myicon.iconAnchor = new GPoint( 11, 23 )
    

    var mark = new GMarker( new GLatLng( lat, lng ), myicon );
    GEvent.addListener( mark, 'click', function() {
        mark.openInfoWindowHtml( document.getElementById( div ).innerHTML );
    } );
    return mark;
}


/* __________________________________ Sommaire automatique */

// permet de mettre tous les div en display none sauf celui que l'on vient de cliquer
function initDisplayNone(position,nb) {
	
	for (var i = 0; i < nb; i++) {
		if ( i != position) {
			var DivElt = $('chapitre'+i);
			var titre = $('titre'+i);
			DivElt.set('class', 'chapitre_display_no');
			titre.set('class', '');
		}
	}
}

function sommaireAutoInit() {
         
	// Generation somaire : MENU
	var ctn_sommaire = new Element('div', {
		 'class': 'ctn_sommaire',
		 'id':'sommaire',
		 'text':''
	});	
	// on place le nouveau div avant le div "editorial"
	var editorial = $('content').getElement('.editorial');
	ctn_sommaire.inject(editorial, 'before');
	
	var ctn_sommaire = $('content').getElement('.ctn_sommaire');
	var editorial = $('content').getElement('.editorial');
	
	// on construit nos element pour le sommaire
	var hc = new Element('div', { 'class': 'hc', 'text':'' });	
	hc.inject(ctn_sommaire, 'bottom');

	var h3 = new Element('h3')	
	h3.inject(hc, 'bottom');
	var span = new Element('span', {'text':'Sommaire' });	
	span.inject(h3, 'bottom');
	var content = new Element('div', { 'class': 'content', 'text':'' });	
	content.inject(hc, 'bottom');
	var ul = new Element('ul');	
	ul.inject(content, 'bottom');
	
	// autre méthode plus rapide mais moins propre
	/*ctn_sommaire.set('html', 
		'<div class="hb"></div>', 
		'<div class="hc"><h3><span>Sommaire</span></h3>
		<div class="content"><ul></ul></div></div>', 
		'<div class="ha"></div>');
	*/
	
	// on recupere le ul
	var ul = ctn_sommaire.getElement('.content ul');
	var content_sommaire =  $('content').getElement('.ctn_sommaire');
	
	var myarray = $('sommaireAuto').getElements('h3');
	var tabli = '';
	var tabValue = [];
	// on forme notre liste li
	myarray.each(function(item,i) {
                if(item.getParent().className != 'vue view')
                {
                    tabValue[i] =item.textContent;
                    tabli = tabli + '<li id="titre'+i+'"><a href="#chapitre'+[i]+'">'+item.getText()+'</a></li>';
                }
	});
	ul.set('html', tabli);
	
	
	// CONTENT
	var myarray2 = $('sommaireAuto').getChildren('*');
	var tabElt = [];
	var tabSection = [];
	var cpt = 0;
	var new_div = false;
                
	myarray2.each(function(item,i) {
			if (item.tagName != 'H3') {
				if( $chk( new_div ) ) 	{
					item.inject( new_div );
				}
				
			} else {

					
				new_div = new Element('div', {
				'class': 'chapitre_display_no ancre',
				'id': 'chapitre'+cpt
                });
                
				new_div.inject( item, 'after' );
				item.inject( new_div );
					
				cpt++;
			}
	});
	
	// lien retour au sommaire
    retour_sommaire = new Element('p', {
    'class': 'top'
    });
    lien_sommaire = new Element('a', {
    'href': '#sommaire',
    'text':'Retour au sommaire'
    });

    lien_sommaire.inject( retour_sommaire);
    retour_sommaire.inject( 'sommaireAuto');
	
    if( $('chapitre0') == null )
    {
        $$('.ctn_sommaire').each( function(	item ) {
            item.setStyle( 'display', 'none' );
        } );
    }
    else
    {
        // on affiche seulement la premier section
    	$('chapitre0').set('class', 'chapitre_display_yes');
	    // on met en gras seulement le premier titre
    	$('titre0').set('class', 'selected');
    }

}


function changeDisplaySommaire() {
	//compte le nombre d element h3
	var nbH2 = $$('#sommaireAuto h3');
        var foo = 0;
        nbH2.each( function(h3, j){ 
                    if(h3.getParent().className != 'vue view')
                    {
                        foo++;
                    }
        });
        
	var nb = foo;
	var ctn_sommaire = $('content').getElement('.ctn_sommaire');
	var tabHref = ctn_sommaire.getElements('.content a');
	tabHref.each(function (item,i) {
			item.addEvent('click', function() {
				//Recupere le div qui correspond et on modifie sa classe
				var DivElt = $('chapitre'+i);
				var titre = $('titre'+i);
				DivElt.set('class', 'chapitre_display_yes');
				titre.set('class', 'selected');
                                initDisplayNone(i,nb);
			});
	});	
}

function complete( searchControl, searcher )
{
    var nb_par_page = 8;
    
    $$( '.gs-result' ).each( function( gs_result, i) {
        var href =  gs_result.getElement( '.gs-title a' ).get( 'href' );
        var siteurl = gs_result.getElement( '.gs-visibleUrl-long' ).get( 'text' );
        var link = '<p class="lien_supp"><a href="' + href + '" rel="external" target="_blank">'+ siteurl +'</a></p>';
        gs_result.getElement( '.gs-visibleUrl-short' ).set( 'html', link );
    });

    $$('.gsc-cursor-box').each( function( item ) { item.dispose(); });
    
    if (searcher.cursor && searcher.cursor.pages.length > 1) 
    { 
        var ctnPaginationNode = new Element( 'div', {'class' : 'ctn_pagination',
                                            'html' : '<div class="hb"/>'});
        var hc = new Element( 'div', {'class' : 'hc',
                                    'html': '<h3><span>Navigation par page</span></h3>'}).inject( ctnPaginationNode, 'bottom' );
        new Element( 'div', {'class' : 'ha'}).inject( hc, 'after' );
        var paginationContentNode = new Element( 'div', {'class' : 'content'} ).inject( hc, 'bottom' );
        new Element( 'div', {'class' : 'break'} ).inject( paginationContentNode, 'after' );
        var paginationParagraph = new Element( 'p' ).inject( paginationContentNode, 'top' );
        var ctnPaginationNodeFooter = ctnPaginationNode.clone();
        var paginationParagraphFooter = ctnPaginationNodeFooter.getElement( 'p' );

        if ( searcher.cursor.currentPageIndex > 0 )
        {
            
            var pageNodeFirst = new Element( 'span', {'class': "goto_first"} ).inject( paginationParagraph, 'top' );
            var pageNodeFirstFooter = pageNodeFirst.clone();
            var pageNodeFirstLink = new Element( 'a', {'href': '#',
                                                    'events': {'click': function(){searcher.gotoPage( 0 );  return false; } }
                                                } ).inject( pageNodeFirst, 'top' );
            new Element( 'img', {'src' : '/extension/ird/design/ird/images//picto/picto_goto_first.gif',
                        'alt' : 'Premier'}).inject( pageNodeFirstLink );
            pageNodeFirstLink.clone().cloneEvents( pageNodeFirstLink ).inject( pageNodeFirstFooter );
            pageNodeFirstFooter.inject(  paginationParagraphFooter, 'top' );
            
            var pageNodePrev = new Element( 'span', {'class': "goto_preview"} ).inject( paginationParagraph, 'bottom' );
            var pageNodePrevFooter = pageNodePrev.clone();
            var pageNodePrevLink = new Element( 'a', {'href': '#',
                                                    'events': {'click': function(){searcher.gotoPage( searcher.cursor.currentPageIndex - 1 );  return false; } }
                                                } ).inject( pageNodePrev );
            new Element( 'img', {'src' : '/extension/ird/design/ird/images//picto/picto_goto_prev.gif',
                        'alt' : 'Précédent'}).inject( pageNodePrevLink );
            pageNodePrevLink.clone().cloneEvents( pageNodePrevLink ).inject( pageNodePrevFooter );
            pageNodePrevFooter.inject(  paginationParagraphFooter, 'bottom' );
            
        }
        
        var pagesNodes = new Element( 'span', {'class': 'pages'} ).inject( paginationParagraph, 'bottom' );
        var pagesNodesFooter = pagesNodes.clone().inject( paginationParagraphFooter, 'bottom' );
        
        for ( var i=0; i < searcher.cursor.pages.length; i++ ) 
        {
            if ( i == searcher.cursor.currentPageIndex )
            {
                var pageSpan = new Element( 'span', {'class': "current", 'html' : ' - ' + searcher.cursor.pages[i].label} ).inject( pagesNodes, 'bottom' );
                if (i == 0 )
                {
                    pageSpan.set( 'html', searcher.cursor.pages[i].label );
                }
                var pageSpanFooter = pageSpan.clone().inject( pagesNodesFooter, 'bottom' );
            }
            else
            {
                var pageSpan = new Element( 'span', {'class': "other"}).inject( pagesNodes, 'bottom' );
                if (i > 0 )
                {
                    pageSpan.set( 'html', ' - ' );
                }
                var pageSpanFooter = pageSpan.clone().inject( pagesNodesFooter, 'bottom' );
                var pageSpanLink = new Element( 'a', {'href': '#',
                                                    'html': searcher.cursor.pages[i].label,
                                                    'events': {'click': function(){
                                                        var page = this.get( 'text' );
                                                        page -- ;
                                                        searcher.gotoPage( page );
                                                        return false;
                                                        } }
                                                } ).inject( pageSpan, 'bottom' );
                pageSpanLink.clone().cloneEvents( pageSpanLink ).inject( pageSpanFooter );
            }
        }

        if ( searcher.cursor.currentPageIndex < 7 )
        {

            var pageNodeNext = new Element( 'span', {'class': "goto_preview"} ).inject( paginationParagraph, 'bottom' );
            var pageNodeNextFooter = pageNodeNext.clone();
            var pageNodeNextLink = new Element( 'a', {'href': '#',
                                                    'events': {'click': function(){searcher.gotoPage( searcher.cursor.currentPageIndex + 1 );  return false;} }
                                                } ).inject( pageNodeNext );
            new Element( 'img', {'src' : '/extension/ird/design/ird/images//picto/picto_goto_next.gif',
                        'alt' : 'Suivant'}).inject( pageNodeNextLink );
            pageNodeNextLink.clone().cloneEvents( pageNodeNextLink ).inject( pageNodeNextFooter );
            pageNodeNextFooter.inject(  paginationParagraphFooter, 'bottom' );

            var pageNodeLast = new Element( 'span', {'class': "goto_first"} ).inject( paginationParagraph, 'bottom' );
            var pageNodeLastFooter = pageNodeLast.clone();
            var pageNodeLastLink = new Element( 'a', {'href': '#',
                                                    'events': {'click': function(){searcher.gotoPage( 7 ); return false; } }
                                                } ).inject( pageNodeLast, 'bottom' );
            new Element( 'img', {'src' : '/extension/ird/design/ird/images//picto/picto_goto_last.gif',
                        'alt' : 'Dernier'}).inject( pageNodeLastLink );
            pageNodeLastLink.clone().cloneEvents( pageNodeLastLink ).inject( pageNodeLastFooter );
            pageNodeLastFooter.inject(  paginationParagraphFooter, 'bottom' );
        }
        else
        {
            $('googleMoreResults').removeClass( 'hidden' );
        }
        
        ctnPaginationNode.inject( $('googleSearchControl').getElement('.gsc-results'), 'top' );
        ctnPaginationNodeFooter.inject( $('googleSearchControl').getElement('.gsc-results'), 'bottom' );
        
        var infosPage = new Element( 'p', {'class' : 'infos_page'} ).inject( ctnPaginationNode, 'after' );
        var infosPagesSpan = new Element('span').inject( infosPage );
        var currentPage = searcher.cursor.currentPageIndex + 1 ;
        var firstIndex = ( searcher.cursor.currentPageIndex * nb_par_page ) + 1;
        var lastIndex = currentPage * nb_par_page ;
        infosPagesSpan.set( 'text', 'Page ' + currentPage + ' : Résultats ' + firstIndex + ' à ' + lastIndex );

        
    }

}


/* __________________________________ menu principal déroulant accessible */
function menu_deroulant() {
		
    /* si l'effet de masquage est gênant, commenter cette ligne et mettre à jour la fauille de style */
	//$$(".main_nav li ul").addClass("js_ok");
    
	$$(".main_nav li .a_deplie").each(function(item, index){
		var menu_ok = "menu_"+index;
		var ssmenu = "#"+menu_ok+" ul";
        
	    item.addEvent('focus', function(){
            $$(".main_nav li ul").set('styles',{'display':'none'});
            $$(ssmenu).set('styles',{'display':'block'});
	    });
        
        $$('a').addEvent('focus', function(){
                if(this.getParents('.main_nav')==''){
                    $$(".main_nav li ul").set('styles',{'display':'none'});
                }                                                             
        });
        
	});
    
    $$(".main_nav .li_deplie").each(function(item, index){
		var menu_ok = "menu_"+index;
		var ssmenu = "#"+menu_ok+" ul";
		
	    item.addEvent('mouseover', function(){
                $$(".main_nav li ul").set('styles',{'display':'none'});
                $$(ssmenu).set('styles',{'display':'block'});
	    });
        item.addEvent('mouseout', function(){
                $$(ssmenu).set('styles',{'display':'none'});
	    });
	});
}

/* __________________________________ infobulles accessibles à partir du title des liens avec la class='infobulle'  */
function infobulle_accessible() {
    
    var a_infobulle = $$('a[class=infobulle]');
    
    /* actions sur les liens */
    a_infobulle.each(function(a_infobulle) {
        var infobulle_txt = a_infobulle.get("title");
        if (infobulle_txt) {
            a_infobulle.addEvents({
                'mouseover': function(){
                    show_infobulle(a_infobulle, infobulle_txt);
                },
                'focus': function(){
                    show_infobulle(a_infobulle, infobulle_txt);
                },
                'mouseout': function(){
                    hide_infobulle(a_infobulle, infobulle_txt);
                },
                'keydown': function(){
                    hide_infobulle(a_infobulle, infobulle_txt);
                }
            });
        }
    });
    
    /* afficher l'infobulle */
    function show_infobulle(a_infobulle, infobulle_txt) {
        
        /* si l'infobulle est prévue pour afficher des infos complémentaires, celles-ci doivent être précédées de ':' */
        if(infobulle_txt.test(":")){
            var infobulle_utile = infobulle_txt.split(":");
            infobulle_utile = infobulle_utile[1];
        }else{
            var infobulle_utile = infobulle_txt;
        }
           
        var infobulle = new Element('span').set('text', infobulle_utile);
        infobulle.inject(a_infobulle);
        a_infobulle.removeProperty('title');
    }
    
    /* masquer l'infobulle */
    function hide_infobulle(a_infobulle, infobulle_txt) {
        a_infobulle.getChildren('span').destroy();
        a_infobulle.set('title', infobulle_txt);
    }
        
}

/* __________________________________ ouverture accessible des liens externes (http + https) dans une nouvelle fenêtre */
function lien_blank() {
    
    var liens = $$("a");
    liens.each(function(lien) {
		    	
       var href = lien.get("href");
   
       	/** Derniere condition ajoute pour permettre l ouverture des  sites de langues dans la meme fenetre */
       if(null != href &&( ((href.contains('http://')||href.contains('https://')))&&lien.parentNode.parentNode.getAttribute('class') != "langue" )) {
           
           /** Condition tres special pour empecher le bug sur les ancre du sommaire auto**/
           
           if (lien.getParent().getParent().getParent().getParent().getParent().getProperty('class').contains('sommaire')) {

           }else{
           
               lien.addEvent("click", function() {window.open(href);return false;});
               var titre_lien = lien.get('title');
               if(titre_lien){
                   lien.set("title", titre_lien+" (nouvelle fenêtre)");
               }else{
                   var intitule_lien = lien.innerText||"";
                   if( intitule_lien == ''){ 
                       for(var i = 0; i <lien.childNodes.length; i++){
                           if(lien.childNodes[i].nodeName == 'IMG' )
                           {
                           intitule_lien += lien.childNodes[i].attributes['alt'].nodeValue.trim() + " ";
                           }
                           else if ( lien.childNodes[i].textContent ) 
                           {
                           intitule_lien += lien.childNodes[i].textContent.trim() + " ";
                           }
                       }
                   }
                   else {
                       intitule_lien = intitule_lien + " ";
                   }
                   lien.set("title", intitule_lien+"(nouvelle fenêtre)");
               }
       
           }
       }
	       
	});
}



//----------------------------------------------------------------------------------------------
// ***** AJOUT POUR NOUVELLE VERSION SITEMAP *******************
//*******************************************************************

/* function showSitemap(_o, _libel){
	var srub;
	
//	srub = _o.getElementsByTagName("ul");
	srub = document.getElementById("accordion_"+_libel);
	img = _o.getElementsByTagName("img");
	
	if( srub.style.display == "none" ){
		srub.style.display = "block";		
		//img[0].title = "Replier le menu : "+ srub.getPrevious().text; 
		img[0].src = "/extension/ird_site_de_representation/design/ird_representation/images/puces/puce_replie.png";
	}else if( srub.style.display =="block"  || srub.style.display ==""){
		srub.style.display = "none";		
		//img[0].title = "Déplier le menu : "+ srub.getPrevious().text;
		img[0].src = "/extension/ird_site_de_representation/design/ird_representation/images/puces/puce_deplie.png";
	}
}
 */
 
 
// Plan du site 
function sitemap(){
    
    var ss_menu = $$('.deplie').getFirst('ul');
    ss_menu.set('styles',{'display':'none'});

    var event_replie_sitemap = function(){
        var parent = this.getParent();
        var menu_deplie = parent.getFirst('ul');
        menu_deplie.set('styles',{'display':'block'});
        parent.removeClass('deplie');
        parent.addClass('replie');
        var image = this.getChildren();
        image.set('src', img_replie);
        var altTexte = 'Replier le menu '+parent.getFirst('a').getNext('a').get('html');
        image.set('alt', altTexte);
        deplie_sitemap( this );
    };

    var event_deplie_sitemap = function(){
        var parent = this.getParent();
        var menu_deplie = parent.getFirst('ul');
        menu_deplie.set('styles',{'display':'none'});
        parent.removeClass('replie');
        parent.addClass('deplie');
        var image = this.getChildren();
        image.set('src', img_deplie);
        
        var altTexte = 'déplier le menu '+parent.getFirst('a').getNext('a').get('html');
        image.set('alt', altTexte);
        
        replie_sitemap(this);
    };
    
     function replie_sitemap( lien ){
        lien.removeEvent('click', event_deplie_sitemap);
        lien.addEvent('click', event_replie_sitemap);
    }
    
    function deplie_sitemap( lien ){
        lien.removeEvent('click', event_replie_sitemap);
        lien.addEvent('click', event_deplie_sitemap);
    }
        
    $$('.deplie').each(function(el){
            var lien = new Element('a', {'class':'picto','href':'#'});                
            
       
        lien.inject(el, 'top');
        lien.set('href','javascript:void(0)');
        
        var altTexte = 'déplier le menu '+lien.getNext('a').get('text');
         var image = new Element('img', {'src':img_deplie, 'alt':altTexte});
        image.inject(lien);
        replie_sitemap(lien); 
    }); 
    
}

//*******************************************************************
// *****       Fin de lajout pour nouveau sitemap      *******************
//----------------------------------------------------------------------------------------------

