/**
 * Javascripts Ackwa chargés au DOMReady en header
 *
 * @version  0.4 - 15/11/11
 *
 * @copy     Ackwa.fr 2010-2011
 * @see      http://www.ackwa.fr
 * @see      http://getfirebug.com/logging
 */
$().ready(function() {
    /*
     * Définition d'un hauteur minimum pour les pages intérieures
     */
    checkHeight(true); 

    /*
     * Capture des actions sur les liens externes
     *
     * @info  En mode live pour les pages affichées via le sitemap
     *        ou la recherche
     */
    $('a').live('click', function() {
        var sURL  = $(this).url(true); 
        var sHost = sURL.attr('host')

        if (!sHost || ('www.touraine-reperage.fr' == sHost) || ('touraine-reperage.fr' == sHost)) {
        }
        else {
            if (('www.mdph37.fr' == sHost) || ('mdph37.fr' == sHost)) _gaq.push(['_trackEvent', 'Services', 'MDPH' , $(this).attr('href')]);
            $(this).attr({target:'_blank'});
            _gaq.push(['_trackEvent', 'Link', 'Open' , $(this).attr('href')]);
        }
    });
    $('a.pdf').live('click', function() {
        $(this).attr({target:'_blank'});
        _gaq.push(['_trackEvent', 'PDF', 'Download', $(this).attr('title')]);
    });
    $('a.wopen').live('click', function() {
        $(this).attr({target:'_blank'});
        _gaq.push(['_trackEvent', 'PDF', 'Download', $(this).attr('title')]);
    });

    /*
     * Evénements Analytics par Catégorie
     */
    _gaq.push(['_trackEvent', 'Services', 'Rubrique', trim($('#catTitle').text())]);
    _gaq.push(['_trackEvent', 'Services', 'Rubrique', $('#catTitle').attr('ref')]);

    /*
     * Initialisation du Zoom
     */
    zoom($.cookie('zoom'));

    /*
     * Handler du zoom
     */
    $('#zoom span').live('click', function() {
        zoom($(this).attr('id'));
    });

    /*
     * Handler pour l'impression
     */
    $('#print').attr('title', 'Imprimer...');
    $('#print').live('click', function() {
        _gaq.push(['_trackEvent', 'Services', 'Print', jQuery(this).attr('title')]);
        window.print();
    });

    /*
     * Handler pour "Envoyer à un ami"
     */
    $('#mail').attr('title', 'Envoyer à...');
    $('#mail').live('click', function() {
        _gaq.push(['_trackEvent', 'Services', 'Mail', jQuery(this).attr('title')]);
        window.location.href = 'mailto:?subject=A consulter - '+ $(document).attr('title') +'&body=' + window.location.toString();
    });

    /*
     * Activation du champ au clic sur le fieldset correspondant
     *
     * @ack   ATTENTION, si l'un met un "return false;" ici, le formulaire
     *        de recherche ne recoit plus le submit ?
     */
    $('fieldset').live('click', function() {
        $(this).find('textarea').focus();
        $(this).find('input[type=text]').focus();
    });
});
function zoom (z) {
    if (z) {
        $('div#contenu').removeClass('x1 x2 x3 x4').addClass(z);
        $('div#texte li').removeClass('x1 x2 x3 x4').addClass(z);
        $('div#navInt' ).removeClass('x1 x2 x3 x4').addClass(z);
        checkHeight(false);
        $.cookie('zoom', z);
        _gaq.push(['_trackEvent', 'Services', 'Zoom', z]);
    }
}
function trim (sData) {
    return sData.replace(/^\s+/g,'').replace(/\s+$/g,'');
}

/**
 * Contrôle de la taille de la colonne de gauche vs celle de droite
 */
function checkHeight (bDelta) {
    /*
     * hauteur minimum du contenu
     */
    var iDeltaHeight = 10;

    /*
     * Contrôle de la présence du plugin Flash
     *
     * @ack   $('#cantons').is(':visible')
     */
    if (bDelta) iDeltaHeight += 316;

    /*
     * Définition d'un hauteur minimum pour les pages intérieures
     */
    if ($('#texte').length && ($('#content').height() < ($('#navInt').height() + iDeltaHeight))) $('#content').height($('#navInt').height() + iDeltaHeight);
}

/**
 * Debug
 */
function _x(sMsg) {
    if (window.console && window.console.firebug) console.log(sMsg);
}

/**
 * A really simple slider
 *
 * @see http://jqueryglobe.com/article/slide-thumbs
 */
$.fn.ACKSlider = function(settings) {
	/*
	 * The Settings
	 */
	settings = $.extend({
		thumbs:   '#thumbs > span',
		inner:    '#preview_inner',
		slides:   'div',
		width:    600,
		over:     false,
		click:    false,
		opacity:  false,
		onchange: function() {}
	}, settings);
	
	return this.each(function (keep) {
        /*
         * Initialize objects & size
         */
        var outer   = $(this);
        var inner   = $(settings.inner);
        var slides  = $(settings.inner+' > '+settings.slides);
        var thumbs  = $(settings.thumbs);
        var current = 0;

        /*
         * Initialize events
         */
        if (settings.over)  thumbs.mouseenter(function(){doSlide(this);});
        if (settings.click) thumbs.click(function(){doSlide(this);return false;});

        /*
         * Initialize Slides
         */
        outer.animate({'scrollLeft': 0}, 0);
        inner.css('width', (slides.length + 1) * settings.width);
        thumbs.eq(0).toggleClass('selected');

        /*
         * Compute translation
         */
        function doSlide (oo) {
            /*
             * Invocation de la fonction "au changement" et traitements
             * si le slide est différent du précédent
             */
            settings.onchange();
            if (current != thumbs.index(oo)) {
                var pos = slides.eq(thumbs.index(oo)).position();

                /*
                 * Animation des miniatures si souhaitée
                 */
                if (settings.opacity) {
                    thumbs.animate ({'opacity': 1.0},   1);
                    $(oo).animate({'opacity': 0.5}, 250);
                }

                /*
                 * Attribution d'un état "Sélectionné/Actif"
                 */
                thumbs.removeClass('selected');
                $(oo).addClass('selected');

                /*
                 * Défilement...
                 */
                outer.stop().animate({'scrollLeft':pos.left}, 400);
                current = thumbs.index(oo);
            }
        }
	});
};

/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
