
var iBoxWidth = iBoxHeight = 0 ;
var iBoxWidthSubstract = 230 ;
var iBoxHeightSubstract = 15 ;

//window.setTimeout(function () { if (!xajaxLoaded) { alert('Error: the xajax Javascript file could not be included. Perhaps the URL is incorrect?\nURL: typo3conf/ext/xajax/xajax_js/xajax.js'); } }, 6000);

jQuery(document).ready(function($) {
    
    // Ajout target=blank pour les liens externe
    var currentHost = window.location.host ;
    var currentHostLength = currentHost.length ;

    $('a').each(function() {

        // verification si le lien commence par http
        if ( this.href.substring(0, 4) =='http') {
            // aucun traitement 
            if( (this.href.substring(7, (currentHostLength+7))==currentHost || this.href.substring(8,(currentHostLength+8))==currentHost ) ) {
                // Do nothing
            }
            else {
                // Ajout de l'attribut
                $(this).click(function(event) {
                    $(this).attr('target', '_blank') ;
               });
            }
        }
    });

	/* $('.detail_mois').toggle(); */
	$(".month_label").click(function () {
		$(this).next(".detail_mois").toggle();
    });


/*
Recherche progressive ______________ */

    $( "#q" ).autocomplete({
    	source: "/index.php?eID=live_search&type=encyclopedie",
    	minLength: 3,
    	select: function( event, ui ) {logAutocomplete( ui.item ? ui.item.id :this.value );}
    });
    
    //function logAutocomplete(message) { $("#q_url").val(message);}
    function logAutocomplete(message) {document.location.href=message;}

	$( "#btn_search" ).click(function(event){
		if ( $("#q_url").val()!='') {
			if(typeof $("#q_url").val() != 'undefined') {
				document.location.href=$("#q_url").val();
				return false;
			}
			if ( $( "#contenu #q" ).val()!='' ) {
			}
		}
		else {
			$("#q_url").remove();
		}
    });    
	
	
/*
Facebox ______________ */
    // 
    $('a[rel*=facebox]').facebox() ;
    

/*
Atlas : ouverture de la popup ______________ */
/*
    $('a[rel*=atlas]').popupWindow({ 
        height:840,
        width:1024,
        centerScreen:1,
        windowName:'atlas'
    });
*/


/*
Load external link to new page ______________ */
    $('a[rel=external]').click(function(e){ 
        open(this.href); 
        e.preventDefault(); 
    });  

/*
    $("#frm_login_entete #f_login").focus(function(e) {
        if ( $(this).val() == 'Votre identifiant' )
            $(this).val('') ; // Update value
            $(this).css('color', '#252525');  // Change color
    });
    $("#frm_login_entete #f_password").focus(function(e) {
        if ( $(this).val() == 'pass' ) {
            $(this).css('color', '#252525');  // Change color
            $(this).val('') ; // Update value
            //$(this).attr('type', 'password') ; // ne fonctionne pas :(
        }
    });
*/

/*
Traitement du hash ______________ */
    if (location.hash.substring(1)!='') {
        var sMyHash = location.hash.substring(1) ;
        if (sMyHash.substring(0, 2)=="i_") {
            if ($('[name=' + location.hash.substring(1) +']').length > 0) {
                $('[name=' + location.hash.substring(1) +']').parent('p').addClass("highlight") ;
            }
            /*
            else {
                $('#article').prepend("<p>Le contenu de l'article que vous souhaitez consulter est disponible en version abonné<br/>Ouvrir une <a href=\"/essai7jours.php\">période d'essai gratuite</a></p>");
            }
            */
        }
    }
    
/*
Smooth scroll ______________ */
    $('a[href*=#]').click(function() {
        if ($(this.href)=='#') {
            //alert('Do nothing') ;
            return false;
        }
        else {
            //alert(document.hash) ;
            if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
                && location.hostname == this.hostname) {
                var $target = $(this.hash);

                $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
                if ($target.length) {
                    var targetOffset = $target.offset().top;
                    $('html,body').animate({scrollTop: targetOffset}, 1000);
                    return false;
                }
            }
        }
    });

    // Se connecter 
    $('#seconnecter').click(function(){
        $("#frm_login_entete").toggle() ;
        return false;
    });
    
    // Link to display dictionary on full page
    $('.mydico').click(function(){

        // Call facebox with url
        jQuery.facebox(function($) {
            jQuery.facebox({ ajax: '/dictionnaire/div/?no_cache=1' })
        }) ;

        $("#facebox .body").css('width', '580px') ;

        return false ;
    });
    
    // Link to display entreeIndex under FullText search
    $('.entreeindex a').click(function(){
        
        if ( $(this).attr("rel").length>0 ) {
            
            // Display result
            $(this).next(".entreeindex_result").toggle();

            // Test if there is an ul html tag inside .entreeindex_result
            // This is to prevent to call many time the xajax... Save time
            if ($(this).next(".entreeindex_result").find('ul').length == 0) {
                // Call ajax method
                tx_eu_getRelatedIndexEntries('napp', $(this).attr("rel") ) ;
            }
        }
        return false ;
    });

    /*
    FUNCTIONS FOR MEDIA DIALOG BOX ___________________ */
    $('.dialog_link').click(function(){
        if ( $(this).attr("rel").length>0 ) {
            if ( $(this).attr("rel")!= 'facebox' ) {
                eventDialogLink(this) ;
            }
        }
        return false;
    });
    
    

    setDialogDimensions() ;
    
    // Dialog
    $('#dialog').dialog({
        autoOpen: false,
        modal: true,
        closeOnEscape: true,
        width: parseInt(iBoxWidth),
        minWidth:  700,
        height:  parseInt(iBoxHeight),
        minHeight:  515,
        resizeStop: doresize,
        close: doclose,
        buttons: {"Fermer": function() {$(this).dialog("close");}},
        overlay: {opacity: 0.7,background: "black"}
    });

    $(".ui-widget-overlay").live("click", function() {  $("#dialog").dialog("close"); } );

    // function when popup is closed
    function doclose() {
        $('#dialog').html('<div class="center"><p><img src="/commun/images/facebox/loading.gif" alt="chargement du média" /></p></div>') ;
        $('#dialog').css('display:none;') ;
    }

    
    function doresize() {
        // retrieve current dimensions
        iBoxWidth = $('#dialog').width();
        iBoxHeight = $('#dialog').height();
        
        // Assign current dimensions to cookie
        createCookie('media_width', ''+iBoxWidth, 365) ;
        createCookie('media_height', ''+iBoxHeight, 365) ;

        // create variables
        iObjectWidth = (iBoxWidth - iBoxWidthSubstract)+'px' ;
        iObjectHeight = (iBoxHeight - iBoxHeightSubstract)+'px' ;

        // create css object
        var cssObj = {
            'width' : ''+iObjectWidth+'',
            'height' : ''+iObjectHeight+''
        }
        
        // Set dimension to css
        $("#dialog_player").css( cssObj ) ;
        $("#dialog_player embed").css( cssObj ) ;
        $("#dialog_player object").css( cssObj ) ;
    }


/*
SEARCH FORM FUNCTIONS ______________ */

    $("#recherche").submit(function (){
        var sKeyword = $("#q").val() ;
        sKeyword.replace(/^\s+/g,'').replace(/\s+$/g,'') ;

        if (sKeyword!='') {
            return true;
        }
        alert("Veuillez saisir un mot clé");
        return false ;
    });

}) 


/*
DIALOG FUNCTIONS ______________ */

function setDialogDimensions() {
    // Prepare cookie
    if (readCookie('media_width')=="" || readCookie('media_width')=="null" || readCookie('media_width')==null || readCookie('media_width')==0 ) {
        iBoxWidth = 700 ;
        createCookie('media_width', ''+iBoxWidth, 365) ;
    }
    else {
        iBoxWidth = readCookie('media_width') ;
    }

    if (readCookie('media_height')=="" || readCookie('media_height')=="null" || readCookie('media_height')==null || readCookie('media_height')==0) {
        iBoxHeight = 550 ;
        createCookie('media_height', ''+iBoxHeight, 365) ;
    }
    else {
        iBoxHeight = readCookie('media_height') ;
    }
}

function eventDialogLink(po_this) {

    // prepare media dimension and cookie
    setDialogDimensions() ;

    // check if ID exits 
    if ( $(po_this).attr("rel").length>0 ) {

        var sTitle = $(po_this).attr("title") ;

        // Call xajax loader
        tx_eu_sendMyMedia('m', $(po_this).attr('rel')) ;

        // Assign title & call popup
        $('#dialog').dialog( 'option', 'title', sTitle );
        $('#dialog').dialog( 'open' );
    }
    else {
        alert('Le média sélectionné n\'est pas valide') ;
    }
    return false;
}

// Dialog Link popup
function doDialogLink() {
    $('.dialog_link').click(function(){
        if ( $(this).attr("rel").length>0 ) {
            if ( $(this).attr("rel")!= 'facebox' ) {
                eventDialogLink(this) ;
            }
        }
        return false;
    });
}
function doProcessPopupMedia() {

    if ( $("#dialog_player").length != 0 ) {
        iBoxWidth = $('#dialog').width();
        iBoxHeight = $('#dialog').height();

        iObjectWidth = (iBoxWidth - iBoxWidthSubstract)+'px' ;
        iObjectHeight = (iBoxHeight - iBoxHeightSubstract)+'px' ;

        var cssObj = {
            'width' : ''+iObjectWidth+'',
            'height' : ''+iObjectHeight+''
        }

        $("#dialog_player").css( cssObj ) ;
        $("#dialog_player embed").css( cssObj ) ;
        $("#dialog_player object").css( cssObj ) ;
    }
}


/*
DICTIONARY FUNCTIONS ___________________ */

/*
preLoadedDico() called on dictionnaire.xsl to run Jquery preCall
*/
function preLoadedDico() {
    
    // Attach event on btn form
    $("#frm_dic #btn_search").click(function(){
        
        // display a waiting message
        $("#dicoResult").html('<p class="center">Recherche en cours...<br/><img src="/commun/images/facebox/loading.gif" alt="" /></p>') ;
                
        // Call Ajax Dico
        doDico();
        
        return false;
    });
    return false;
}


function doDicoPre() {
    // display a waiting message
    $("#dicoResult").html('<p class="center">Recherche en cours...<br/><img src="/commun/images/facebox/loading.gif" alt="" /></p>') ;

    // Call Ajax Dico
    doDico();
}

// execute an ajax request
function doDico() {

    //var sSearchTerm = $("#dic_body #q2").attr('value');
    var sSearchTerm = $("#frm_dic #q2").attr('value');

    //tx_eu_getDicoContent( '<xjxquery><q>&tx_eu[search]='+sSearchTerm+'</q></xjxquery>' ) ;
    tx_eu_getDicoContent('q', sSearchTerm ) ;

    return false;
}

/*
XAJAX CLIENT USER FUNCTION LAYER ___________________ */

var xajaxRequestUri="/xajax-ctrl";
var xajaxDebug=false;
var xajaxStatusMessages=true;
var xajaxWaitCursor=false;
var xajaxDefinedGet=0;
var xajaxDefinedPost=1;
var xajaxRewritedGet=2;
var xajaxLoaded=false;

function tx_eu_sendMyMedia(){return xajax.call("_sendMyMedia", arguments, 2);}
function tx_eu_getExtraContent(){return xajax.call("_getExtraContent", arguments, 2);}
function tx_eu_getDicoContent(){return xajax.call("_getDicoContent", arguments, 2);}
function tx_eu_getRelatedIndexEntries(){return xajax.call("_getRelatedIndexEntries", arguments, 2);}


function mfplayer_DoFSCommand(command) {/* alert("2"+command); */}
function media_player_DoFSCommand(command) {/* alert("2"+command); */}


/*
cookie functions ___________________ */
function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    
    //alert(name+"="+value+expires+"; path=/") ;
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

/* function used on flash */
function ChildMovieIsLoaded() {} 

