﻿/*

SOMMAIRE

- Déclaration / vérification des variables globales
- SqueezeBox : popups inline
- Focus boite de recherche
- Accordéons
- Bulles (tooltip)
- Mise en forme du sitemap
- Liens externes
- Tooltips
- Input Cleaner
- Text area check
- Articles tools box
- Smooth Scroll
- Google Analytics

*/


////////////////////////////////////////////////
/////////////////// DomReady ///////////////////
////////////////////////////////////////////////


window.addEvent('domready', function() {

    /* VARIABLES GLOBALES */
    // URL du site, URL de la page courante

    var cap_siteURL = document.location.protocol + '//' + document.location.hostname;
    var cap_pageURL = document.location;
    if (typeof cap_CMS_SiteName == "undefined") cap_CMS_SiteName = "";
    if (typeof cap_CMS_DocumentName == "undefined") cap_CMS_DocumentName = "";
    if (typeof cap_CMS_Environment == "undefined") cap_CMS_Environment = "";
    if (typeof cap_SiteRootUrl == "undefined") cap_SiteRootUrl = "";
    if (typeof cap_CMS_AliasPath == "undefined") {
        cap_CMS_AliasPath = "";
    } else {
        if (cap_CMS_AliasPath.slice(0, 1) == "/") {
            cap_CMS_AliasPath = cap_CMS_AliasPath.slice(1);
        }
        cap_CMS_AliasPath = cap_CMS_AliasPath.toLowerCase()
    }

    var cap_globalVarAlert = {
        view: function() {
            alert(
                'hostname = ' + document.location.hostname + '\n' +
                'cap_siteURL = ' + cap_siteURL + '\n' +
                'cap_pageURL = ' + cap_pageURL + '\n' +
                'cap_CMS_SiteName = ' + cap_CMS_SiteName + '\n' +
                'cap_CMS_DocumentName = ' + cap_CMS_DocumentName + '\n' +
                'cap_CMS_Environment = ' + cap_CMS_Environment + '\n' +
                'cap_SiteRootUrl = ' + cap_SiteRootUrl + '\n' +
                'cap_CMS_AliasPath = ' + cap_CMS_AliasPath
            );
        }
    }
    //cap_globalVarAlert.view();



    /*  SQUEEZE BOX  */
    // Affichage d'un contenu dans un popup inline (ajax, from elements, iframe content, simgles images, youtube flash...)

    cap_initSqueezeBox = {
        run: function(el) {
            if (el) {
                var parentsTag = el.getParent();
                parentsTag.each(function(item) {
                    item.addClass('boxed');
                });
            }
        }
    };
    cap_initSqueezeBox.run($$('img.boxed'));

    SqueezeBox.assign($$('a.boxed'), {
        size: { x: 750, y: 450 },
        sizeLoading: { x: 700, y: 400 },
        parse: 'rel',
        overlayOpacity: 0.4,
        ajaxOptions: {
            method: 'get' // we use GET for requesting plain HTML
        }
    });



    /* GESTION DU FOCUS DANS LA BOITE DE RECHERCHE */
    // ajoute une indication 'Rechercher' dans la boite de recherche quand celle-çi est vide

    var cap_searchField = { // Mise à jour : 27/05/2009

        init: function(element, cssClassBlur, container, cssClassFocus) {
            if (element && cssClassBlur && container && cssClassFocus) cap_searchField.inprove(element, cssClassBlur, container, cssClassFocus);
        },

        inprove: function(element, cssClassBlur, container, cssClassFocus) {
            // si le champ est vide au chargement de la page, on ajoute l'indication
            element.value = element.value.clean();
            if (!element.value) {
                element.addClass(cssClassBlur);
            }

            // on affiche ou pas l'indication en fonction de l'action de l'utilisateur, et du contenu du champ
            element.addEvents({
                'focus': function() {
                    container.addClass(cssClassFocus);
                    element.removeClass(cssClassBlur);
                },
                'blur': function() {
                    element.value = element.value.clean();
                    container.removeClass(cssClassFocus);
                    if (!element.value) {
                        element.addClass(cssClassBlur);
                    }
                }
            });
        }
    }

    cap_searchField.init($$('#searchBox input')[0], 'inputBlur', $$('#searchBox table')[0], 'inputFocus');



    /* ACCORDÉONS */
    // boite dans la sidebar

    var cap_accordion = {
        launch: function(toggles, content, displayElement) {

            // initialisation de l'accordéon
            if (displayElement) {
                if (toggles && content) {
                    initAccordion(toggles, content, displayElement);
                }
            } else {
                if (toggles && content) {
                    initAccordion(toggles, content);
                }
            }

            function initAccordion(toggles, content, displayElement) {
                if (!displayElement) displayElement = 0;
                var AccordionObject = new Accordion(toggles, content, {
                    display: displayElement,
                    transition: Fx.Transitions.Quart.easeInOut,
                    duration: 400
                });
            }

            // ouverture d'un élément au passage de la souris, avec un délais
            toggles.addEvents({
                'mouseenter': function() {
                    this.setProperty('status', 'wait');
                    function openAccordion() {
                        if (this.getProperty('status') == 'wait') {
                            this.fireEvent('click');
                            this.removeProperty('status');
                        }
                    };
                    openAccordion.bind(this).delay(300);
                },
                'mouseleave': function() {
                    this.removeProperty('status');
                }
            });

        }
    }

    cap_accordion.launch($$('.togglers'), $$('.elements'), -1);


    /* BULLE */

    function cap_bubble(tipItem, tipCssClass) {
        if (tipItem && tipItem != 'undefined' && tipCssClass) {

            if (tipItem.getProperty('title') != '') {
                var tip = new Tips(tipItem, {
                    className: tipCssClass,
                    hideDelay: 0,
                    showDelay: 0,
                    offsets: { 'x': 15, 'y': -90 }
                });
                return tip;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    cap_bubble($$('.bubble h2'), 'sitemap_tip');



    /* MISE EN FORME DU SITEMAP */

    function cap_sitemap() {

        var sitemapSection = $$('.section');
        if (sitemapSection && sitemapSection != 'undefined') {

            sitemapSection.each(function(item) {
                var description = item.getElement('p');
                if (description && description != 'undefined') {
                    var title = description.get('text');

                    item.setProperty('title', title);

                    var overSectionFx = new Fx.Tween(item);

                    cap_bubble(item, 'sitemap_tip').addEvents({
                        'show': function(tip) {
                            if (Browser.Engine.trident) {
                                new Fx.Tween(tip, { duration: 0 }).start('opacity', 1);
                            } else {
                                new Fx.Tween(tip, { duration: 400 }).start('opacity', .8);
                            }
                            overSectionFx.cancel();
                            overSectionFx.start('background-color', '#fff', '#e4f3f6');
                        },
                        'hide': function() {
                            overSectionFx.cancel();
                            overSectionFx.start('background-color', '#e4f3f6', '#fff');
                        }
                    });
                }
            });

        }
    }
    cap_sitemap();


    /* LIENS EXTERNES */
    // améliore l'ergonomie et la visibilité des liens pointant vers l'extérieur du site

    var cap_externalLinks = { // Mise à jour : 15/01/2009

        init: function(container, noInproveCssClass) {
            if (container && noInproveCssClass) cap_externalLinks.improve(container, noInproveCssClass);
        },

        improve: function(container, noInproveCssClass) {

            // on récupere les liens de la page (dans le div #container)
            container.each(function(item, index) {

                // on teste si le domaine du site se trouve pas dans le href, et que l'adresse commence bien par http:// ou https://
                if (!item.href.contains(cap_siteURL) && (item.href.match("^http://") || item.href.match("^https://"))) {

                    // si le lien n'a pas de propriété 'target', on en ajoute un (les liens s'ouvriront dans une nouvelle fenêtre)
                    if (!item.target) {
                        item.setProperty('target', '_blank');
                    }

                    // si le lien n'a pas de propriété 'title', on en ajoute un
                    if (!item.title && !item.hasClass('boxed')) {
                        item.setProperty('title', 'lien vers : ' + item.href);
                    }

                    // si le liens n'est pas sur une image et qu'il na pas de CssClass interdisant le traitement, on ajoute la classe CSS
                    if (!item.getElement("img") && !item.hasClass(noInproveCssClass)) {
                        // on ajoute la classe CSS
                        item.addClass('externalLink');
                        //item.adopt(item, 'top');
                    }
                }
            })
        }
    };

    cap_externalLinks.init($$('#content a'), 'noExternalLink');
    cap_externalLinks.init($$('#sidebar a'), 'noExternalLink');
    cap_externalLinks.init($$('#footer_partners a'), 'noExternalLink');


    /* TIPS */
    /* Meilleur affichage des tooltips */

    var cap_toolTip = {

        start: function(item, showDelay, hideDelay, offsetX, offsetY) {
            if (item) {
                item.each(function(el, i) {
                    var cssclass = el.getProperty('class') + '_tip';
                    el.removeProperty('alt');
                    var tip = new Tips(el, {
                        className: cssclass,
                        hideDelay: hideDelay,
                        showDelay: showDelay,
                        offsets: { 'x': offsetX, 'y': offsetY }
                    });
                });
            }
        }
    }

    cap_toolTip.start($$('.form_alert'), 0, 0, 25, 9);
    cap_toolTip.start($$('.form_valid'), 0, 0, 25, 9);
    cap_toolTip.start($$('.form_info'), 0, 0, 25, 9);
    cap_toolTip.start($$('#searchResults .results li img'), 200, 0, 25, 9);
    cap_toolTip.start($$('#header_logo img'), 200, 0, 18, 22);
    //cap_toolTip.start($$('a.externalLink'), 200, 0, 18, 22);



    /* INPUT CLEANER */
    // nettoyage automatique des champs

    var cap_inputCleaner = {
        // supression des espace blanc avant et après
        trim: function(elements) {
            elements.each(function(item) {
                item.value = item.value.trim();
                item.addEvent('blur', function() { item.value = item.value.trim(); });
            });
        },
        // supression du javascript inséré dans un champ
        stripScripts: function(elements) {
            elements.each(function(item) {
                item.value = item.value.stripScripts();
                item.addEvent('blur', function() { item.value = item.value.stripScripts(); });
            });
        }
    }
    cap_inputCleaner.trim($$('.form input'));
    cap_inputCleaner.stripScripts($$('.form input'));
    cap_inputCleaner.trim($$('.form textarea'));
    cap_inputCleaner.stripScripts($$('.form textarea'));



    /* TEXTAREA CHECK */
    // Contrôle et affichage du nombre de caractères entrés + ajustement automatiquement la hauteur du textaera

    var cap_textareaChech = { // Mise à jour : 27/05/2009

        init: function(inputElement, displayElement, maxLenght, defaultRows, stringSeparator) {
            if (inputElement && displayElement && maxLenght && defaultRows && stringSeparator) {
                cap_textareaChech.check(inputElement, displayElement, maxLenght, defaultRows, stringSeparator);
                inputElement.addEvents({
                    'keydown': function() {
                        cap_textareaChech.check(inputElement, displayElement, maxLenght, defaultRows, stringSeparator);
                    },
                    'change': function() {
                        cap_textareaChech.check(inputElement, displayElement, maxLenght, defaultRows, stringSeparator);
                    },
                    'blur': function() {
                        cap_textareaChech.check(inputElement, displayElement, maxLenght, defaultRows, stringSeparator);
                    }
                });
            }
        },

        resizingTextArea: function(inputElement, defaultRows) {
            var rows = inputElement.rows;
            var newRows = inputElement.value.split('\n').length;
            if (newRows + 2 > rows) {
                inputElement.rows = newRows + 10;
            }
            if (newRows + 10 < rows) {
                inputElement.rows = Math.max(defaultRows, newRows + 2);
            }
        },

        check: function(inputElement, displayElement, maxLenght, defaultRows, stringSeparator) {
            // màj de l'indicateur
            displayElement.set('html', inputElement.value.length + stringSeparator + maxLenght);
            inputElement.value = inputElement.value.slice(0, maxLenght);

            // ajustement auto de la hauteur du textaera
            cap_textareaChech.resizingTextArea(inputElement, defaultRows);
        }

    }

    cap_textareaChech.init($$('.txtCommentaire')[0], $('txtCommentaireLenghtIndicator'), 2000, 12, ' / ');



    /* ARTICLES TOOLS BOX */
    // Attache les fonctionalités correspondantes à la barre d'outils dans un article (imprimer, partager...)

    var cap_attachArticlesTools = {

        print: function(el) {
            if (el && el != '') el.addEvent('click', function() { window.print() });
        },

        addThis: function(el) {
            if (el && el != '') {
                // initialisation des paramètres
                addthis_pub = 'inspq';
                addthis_language = "fr";
                addthis_options = 'email, favorites, digg, delicious, myspace, facebook, linkedin, twitter, buzz, google, live, more';
                addthis_offset_top = 0;
                addthis_offset_left = 0;
                addthis_localize = {
                    email_caption: "Envoyer à un ami",
                    email: "Courriel",
                    favorites: "Favoris",
                    more: "plus..."
                };

                // on attache le lien + la CssClass 'noInproveCssClass' de la fonction 'cap_externalLinks'
                el.setProperty('href', 'http://www.addthis.com/bookmark.php?v=250');
                el.addClass('noExternalLink');

                // on charge le .js requis
                Asset.javascript('http://s7.addthis.com/js/250/addthis_widget.js');

                // on attache les événements
                el.addEvents({
                    'click': function() {
                        return addthis_sendto();
                    },
                    'mouseover': function() {
                        return addthis_open(this, '', '[URL]', '[TITLE]');
                    },
                    'mouseout': function() {
                        addthis_close();
                    }
                });

            }
        }
    }

    cap_attachArticlesTools.print($$('.toolBox .print'))
    cap_attachArticlesTools.addThis($$('.toolBox .share'))



    /* SMOOTH SCROLL */
    // Smooth Scroll sur toutes les ancres
    var cap_smoothScroll = new Fx.SmoothScroll({
        duration: 800,
        transition: Fx.Transitions.Pow.easeOut
    });



    /*  GOOGLE ANALYTICS  */
    // Injection du script Google Analytics

    var cap_googleAnalytics = {

        add: function(firstTracker, secondTracker) {

            var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
            new Asset.javascript(gaJsHost + "google-analytics.com/ga.js", {
                onload: function() {
                    firstTracker = _gat._getTracker("UA-442299-39");
                    firstTracker._initData();
                    firstTracker._trackPageview();
                    secondTracker = _gat._getTracker("UA-10814955-1");
                    secondTracker._initData();
                    secondTracker._trackPageview();

                    // pour tracker tous les liens pointant vers l'extérieur
                    if (firstTracker && secondTracker) {
                        $$('a[href^=http]').each(function(el) {
                            el.addEvent('click', function() {
                                var dd = '/outgoing/' + el.get('href').replace('http://', '');
                                pageTracker._trackPageview(dd);
                            } .bind(this));
                        });
                    }
                }
            });
        }
    };

    //ne pas ajouter google analytics sur les sites s'executant en local ou en stage
    if (cap_CMS_Environment != "stage" && cap_CMS_Environment != "localhost") cap_googleAnalytics.add();

});
