
/**
 *  Javascript General
 *  
 *  Contents
 *      1. Menus
 *          1.1 Menu Principal
 *          1.2 Menu Stats
 *      2. Traitements spécifiques
 *          2.1 Agenda
 *          2.2 La Une
 *          2.2 Recherche
 *      3. Outils
 *          3.1 Font Resizer
 *          3.2 Impression
 *          3.3 Mail (todo ?)
 *          3.4 Social Bookmarking
 *          3.5 spip_out et pdfs
 *      4. Détection par classe CSS Navigateur + OS
 *      n. Helpers & Utils
 *  
 *  @author     Alexandre, Paul
 *  @version    spip.2.0.10
 */

$(function()
{
    //========================================================================================================================
    //      1. Menus
    //========================================================================================================================
	
    
    //------------------------------------------------------------------------------------------------------------------------
    //      1.1 Menu principal

	$(".menu-secondaire").css( "display", "none" );
	$(".on").parent("li").addClass("on-pas-focus");
	$("#menu li a").hover(function(){
		 $(".on-pas-focus").children("a").removeClass("on");
	},
	function(){
		$("#menu li a.on").next("ul").css('display','block');
		$(".on-pas-focus").children("a").addClass("on");
	});
	$("#menu1 ul ul,#menu2 ul ul").hover(function(){},
    function(){
		$("#menu li a.on").next("ul").css('display','block');
	});
    $("#menu1 li").hover(function()
    {
        $(this).parent().find("ul").css("display","none");
        $(this).children("ul").css('display','block');
        $("#menu2 li a, #menu2 li a.on").next("ul").css('display','none');
        $(".on-pas-focus").children("a").removeClass("on");
    },
    function(){
    	$(".on-pas-focus").children("a").addClass("on");
    });
	$("#menu2 li").hover(function()
	{
        $(this).parent().find("ul").css("display","none");
        $(this).children("ul").css('display','block');
        $("#menu1 li a, #menu1 li a.on").next("ul").css('display','none');
        
    },
    function(){});
	$(".menu-secondaire").hover(function(){
		$(this).prev("a").addClass("focus");
	},
	function(){
		$(this).prev("a").removeClass("focus");
		$("#menu li a.on").next("ul").css('display','block');
	});
	
	$(function(){
    	$("#menu li a.on").next("ul").css('display','block');
    });
	
    
    //------------------------------------------------------------------------------------------------------------------------
    //      1.2 Menu stats
	
	$(".sous-menu-stats").css( "display", "none" );
    $("#top14 li a").hover(function()
    {
        $(this).parent().parent().find("ul").css("display","none");
        $(this).next("ul").fadeIn();
        $("#prod2 li a").next("ul").css('display','none');
    },
    function(){});
	$("#prod2 li a").hover(function()
	{
        $(this).parent().parent().find("ul").css("display","none");
        $(this).next("ul").fadeIn();
        $("#top14 li a").next("ul").css('display','none');
    },
    function(){});
    

    //========================================================================================================================
    //      2. Traitements spécifiques
    //========================================================================================================================
	
    
    //------------------------------------------------------------------------------------------------------------------------
    //      2.1 Agenda

    $(".semaine").each(function(){
        $(this).find(".agenda-programme-jour").css("height",$(this).height()-90);
    });
	
    
    //------------------------------------------------------------------------------------------------------------------------
    //      2.2 La Une
    
   $(".container-une").css("height",$(".une-wrapper").height());
	
    
    //------------------------------------------------------------------------------------------------------------------------
    //      2.3 Recherche

    $('#formulaire_recherche input.text').val( 'Rechercher...' ).addClass( 'default-val-switcher' );
    
    //      validation
    //$('#formulaire_recherche form').submit( function()
    $('#formulaire_recherche form .submit').click( function()
    {
        var vstate = true;
        //var input_val = $(this).find('#recherche').val();
        var input_val = $('#formulaire_recherche form #recherche').val();
        
        if ( input_val == "Rechercher..." ) {
            vstate = false;
        }
        else
        {
            if ( empty( input_val )) {
                alert( "La recherche ne peut pas être vide." );
                vstate = false;
            }
            if ( strlen( input_val ) < 3 ) {
                alert( "Le terme recherché doit comporter au moins 3 caractères." );
                vstate = false;
            }
        }
        return vstate;
    });
    
    //      valeur par défaut (réutilisable)
    $('.default-val-switcher').each(function()
    {
        var default_val = $(this).val();
        $(this).click( function() { if ( $(this).val() == default_val ) $(this).val( '' ); });
        $(this).focus( function() { if ( $(this).val() == default_val ) $(this).val( '' ); });
        $(this).blur( function() { if ( $(this).val() == '' ) $(this).val( default_val ); });
    });
    
    
    
    //========================================================================================================================
    //      3. Outils
	//        
    //========================================================================================================================
	
    
    //------------------------------------------------------------------------------------------------------------------------
    //      3.1 Font Resizer
    
    //      Reset Font Size
    var originalFontSize = $('.lire-article').css('font-size');
    $(".resetFont").click(function() {
        $('.lire-article').css('font-size', originalFontSize);
    });
    //      Increase Font Size
    $(".increaseFont").click(function()
    {
        var currentFontSize = $('.lire-article').css('font-size');
        var currentFontSizeNum = parseFloat(currentFontSize, 10);
        var newFontSize = currentFontSizeNum*1.2;
        $('.lire-article').css('font-size', newFontSize);
        return false;
    });
    //      Decrease Font Size
    $(".decreaseFont").click(function()
    {
        var currentFontSize = $('.lire-article').css('font-size');
        var currentFontSizeNum = parseFloat(currentFontSize, 10);
        var newFontSize = currentFontSizeNum*0.8;
        $('.lire-article').css('font-size', newFontSize);
        return false;
    });
	
    
    //------------------------------------------------------------------------------------------------------------------------
    //      3.2 Impression
    
    $('#toolbox li.tool3').click(function()
    {
        window.print();
        return false;
    });
	
    
    //------------------------------------------------------------------------------------------------------------------------
    //      3.4 Social Bookmarking
	
    $(".socialtags").css("display","none");
    $('#toolbox li.tool5 span').click(function()
    { 
        if ($(this).hasClass("actif"))
        {
            $(".socialtags").hide("slow");
            $("#toolbox").animate({ height:"14px" });
            $(this).removeClass('actif');
        }
        else
        {
            $("#toolbox").animate({ height:"32px" });
            $(".socialtags").show("slow");
            $(this).addClass('actif');
        }
    });
    
    
    //------------------------------------------------------------------------------------------------------------------------
    //      3.5 spip out et pdf
    
    $(".pdf").attr( "target", "_blank" );
	
	$("a.spip_out[attr*='http://']").attr( "target", "_blank" ).css("background","url('../_imgs/external.gif') no-repeat scroll right center #FFFFFF");
    $("a.spip_out[attr!*='http://']").addClass("spip_in").removeClass("spip_out");
    
    
    //========================================================================================================================
    //      4. Détection par classe CSS Navigateur + OS
    //========================================================================================================================
    
    var ua = navigator.userAgent.toLowerCase();
    var myBrowsers = {
        //      Déjà détectés en natif par jQuery 
        mozilla: $.browser.mozilla,
        safari:  $.browser.safari,
        opera:   $.browser.opera,
        ie:      $.browser.msie,
        //      Quelques améliorations et ajouts
        ie6:     $.browser.msie && ($.browser.version < 7),
        ie7:     $.browser.msie && ($.browser.version == 8),
        ie8:     $.browser.msie && ($.browser.version > 7),
		
		firefox_lt_191:     $.browser.mozilla && ($.browser.version < '1.9.1'),
		
        iphone:  /iphone/.test(ua),
        chrome:  /chrome/.test(ua),
        firefox: /firefox/.test(ua),
        webkit:  /webkit/.test(ua),
        //      Détection de plateformes
        osx:     /mac os x/.test(ua),
        win:     /win/.test(ua),
        linux:   /linux/.test(ua)
    };
    $.each(myBrowsers, function(a, b) {
        if ( b ) $( 'html' ).addClass( a );
    });
	
});

//========================================================================================================================
//      n. Helpers & Utils
//========================================================================================================================


/**
 *  Simple Ajax Helper
 *
 *  @example
 *      simple_ajax_helper({
 *          fond: "club",
 *          data: 'id_club=36',
 *          zone: '#zone-update'
 *      });
 *
 *  @param  Object vars = {
 *      fond:       String: chemin du fond (spip) qui renvoie les données,
 *      //url:        String: chemin du fichier (http url) qui renvoie les données,
 *      data:       String: paramètres du type "var1=test&var2=retest",
 *      zone:       String: selecteur jQuery,
 *      append:     Boolean: si on rajoute ou remplace la zone cible,
 *      callback:   Function: appelée au chargement
 *  }
 *  @return XmlHttpRequest Object (utile pour arreter le chargement manuellement)
 */
function simple_ajax_helper( vars )
{
    //      TODO: securiser les appels
    if ( vars.fond ) var real_url = "spip.php?page=" + vars.fond;
    //else var real_url = vars.url;
    if ( vars.zone ) $(vars.zone).prepend('<div class="skin-loading" id="icon-ajax-loader"></div>');
    return $.ajax(
    {
        type:"POST",
        url:real_url,
        data:vars.data,
        success:function( incoming )
        {
            if ( vars.zone )
            {
                $('#icon-ajax-loader').remove();
                if ( vars.append ) $( vars.zone ).append( incoming );
                else $( vars.zone ).html( incoming );
                //      debug
                //if ( incoming == '' ) $( vars.zone ).append( 'vide. vars.data = ' + vars.data );
            }
            if ( vars.callback ) eval( vars.callback );
        },
        error:function()
        {
            //      TODO: simple ajax error handling
            alert( "Erreur de chargement sur " + real_url );
        }
    });
}


/**
 *  Util: empty
 *  @see    http://phpjs.org/functions/empty:392
 */
function empty( mixed_var )
{
    var key;
    if (mixed_var === "" ||
        mixed_var === 0 ||
        mixed_var === "0" ||
        mixed_var === null ||
        mixed_var === false ||
        typeof mixed_var === 'undefined'
    ){
        return true;
    }
    if (typeof mixed_var == 'object') {
        for (key in mixed_var) {
            return false;
        }
        return true;
    }
    return false;
}


/**
 *  Util: strlen
 *  @see    http://phpjs.org/functions/strlen
 */
function strlen( string )
{
    var str = string+'';
    var i = 0, chr = '', lgth = 0;
    if (!this.php_js || !this.php_js.ini || !this.php_js.ini['unicode.semantics'] ||
            this.php_js.ini['unicode.semantics'].local_value.toLowerCase() !== 'on') {
        return string.length;
    }
    var getWholeChar = function (str, i) {
        var code = str.charCodeAt(i);
        var next = '', prev = '';
        if (0xD800 <= code && code <= 0xDBFF) { // High surrogate (could change last hex to 0xDB7F to treat high private surrogates as single characters)
            if (str.length <= (i+1))  {
                throw 'High surrogate without following low surrogate';
            }
            next = str.charCodeAt(i+1);
            if (0xDC00 > next || next > 0xDFFF) {
                throw 'High surrogate without following low surrogate';
            }
            return str.charAt(i)+str.charAt(i+1);
        } else if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate
            if (i === 0) {
                throw 'Low surrogate without preceding high surrogate';
            }
            prev = str.charCodeAt(i-1);
            if (0xD800 > prev || prev > 0xDBFF) { //(could change last hex to 0xDB7F to treat high private surrogates as single characters)
                throw 'Low surrogate without preceding high surrogate';
            }
            return false; // We can pass over low surrogates now as the second component in a pair which we have already processed
        }
        return str.charAt(i);
    };
    for (i=0, lgth=0; i < str.length; i++) {
        if ((chr = getWholeChar(str, i)) === false) {
            continue;
        } // Adapt this line at the top of any loop, passing in the whole string and the current iteration and returning a variable to represent the individual character; purpose is to treat the first part of a surrogate pair as the whole character and then ignore the second part
        lgth++;
    }
    return lgth;
}


/*
 * fancybox
 */
$(function()
{
	$("a.iframe-fancy").fancybox({
		'transitionIn'	: 'none',
		'transitionOut'	: 'none',
		'width'			: 800,
		'height'		: 600,
		'overlayOpacity': 0.6,
		'overlayColor'	: '#316072',
		'padding'		: 2,
		'margin'		: 100
	});

	$("a.fancy-match-feuille").fancybox({
		'transitionIn'	: 'none',
		'transitionOut'	: 'none',
		'autoDimensions': true,
		'overlayOpacity': 0.6,
		'overlayColor'	: '#316072',
		'padding'		: 0,
		'scrolling'		: 'no',
		'titleShow'		: false,
		'margin'		: 100
		
	});
	$("a.video-fancy").fancybox({
		'type'			:'iframe',
		'transitionIn'	: 'none',
		'transitionOut'	: 'none',
		'overlayOpacity': 0.95,
		'overlayColor'	: '#111',
		'width'			: 660,
		'height'		: 610,
		'padding'		: 0,
		'scrolling'		: 'no',
		'titleShow'		: false,
		'autoDimensions': false,
		'autoScale'		: false
		
	});
	

/* highlight_club par franck */

$("#highlight_club .h_club").click( function(){
	$(".day .teaming span").removeClass("highlight");
	$(".day .teaming span").parent().parent().removeClass("highlight");
	$(".day .teaming span." + $(this).attr('data-club-class') ).parent().parent().addClass("highlight");
	$(".day .teaming span." + $(this).attr('data-club-class') ).addClass("highlight");
});
							


});
