if (typeof redcats === 'undefined') {
    var redcats = {};
}
var ie6 = false;

/*
var consoleLog = function(myvar) {
    if (typeof(console) != 'undefined') {
        console.log(myvar);
    }
};
*/

(function($) {
    /**
     * @section     popins, sections & urls management
     */
    var W = window, D = W.document, DE = D.documentElement;
    
    function getMaskConfig(id, htmlId, opacity) {
        return {
            id: id,
            html: '<div id="' + htmlId + '"></div>',
            insertStyles: {opacity: 0,left: 'viewport:middle'},
            insertAnimStyles: {opacity: opacity},
            insertAnimDuration: 200,
            removeAnimStyles: {opacity: 0},
            removeAnimDuration: 150
        };
    }
    
    function getLoaderConfig(id, htmlId) {
        return {
            id: id,
            html: '<div id="' + htmlId + '"><p><img src="' + l10n.url.loading + '" alt="" /><br /><br />' + l10n.loading + '</p></div>',
            insertStyles: {opacity: 0,left: 'viewport:middle'},
            insertAnimStyles: {opacity: 0.9},
            insertAnimDuration: 10,
            removeAnimStyles: {opacity: 0},
            removeAnimDuration: 10
        };
    }
    
    function getPopinConfig(id, mask, loader, clsOpen, clsClose) {
        return {
            id: id,
            loader: loader,
            mask: mask,
            preloadTimeout: 15000,
            insertStyles: {top: 'viewport:before',left: 'viewport:middle','min-left': 0},
            insertAnimStyles: {top: 'viewport:middle','min-top': 0},
            insertAnimDuration: 600,
            removeAnimStyles: {top: 'viewport:before'},
            removeAnimDuration: 500,
            openClassName: clsOpen,
            closeClassName: clsClose
        };
    };
    
    box.ui('mask').create(getMaskConfig('popinMask', 'popinMask', 0.3));
    box.ui('mask').create(getMaskConfig('sectionMask', 'sectionMask', 0.5));
    box.ui('loader').create(getLoaderConfig('sectionLoader', 'sectionLoader'));
    
    //box.ui('popin').create(getPopinConfig('generic', 'popinMask', 'popinLoader', 'popinOpen', 'popinClose'));
    
    box.ui('popin').create({
        id: 'section',
        loader: 'sectionLoader',
        mask: 'sectionMask',
        preloadTimeout: 15000,
        insertStyles: {left: 'viewport:before'},
        insertAnimStyles: {left: 'viewport:middle'},
        insertAnimDuration: 600,
        removeAnimStyles: {left: 'viewport:before'},
        removeAnimDuration: 500,
        openClassName: 'SectionOpen',
        closeClassName: 'sectionClose',
        insertTarget: '#discover'
    });
    /*
    var nocache = function(url) {
        if (url.indexOf('?') > 0) {
            url = url + '&' +  (new Date()).getTime();
        } else {
            url = url + '?' +  (new Date()).getTime();
        }
        return url;
    }
    */
    redcats.manageAddress = function(e) {
        var url = e.value;
        if (url === ('/' + l10n.home)) {
            if (typeof(box.ui('popin.section')) !== 'undefined' && box.ui('popin.section').opened) {
                /* if home requested, close any opened popin */
                box.ui('popin.section').close();
                box.ui('popin.section').enable(true);
            }
            $.address.title(l10n.title);
            $.address.value(l10n.home);
        } else if ((url === '/' && W.location.pathname !== l10n.url.home) ) { //|| url === W.location.pathname
            $.address.value(W.location.pathname);
            return false;
        } else {
            if (url === '/') {
                if (W.location.pathname === l10n.url.home) {
                    $.address.value(l10n.home);
                    return false;
                } else {
                    url = W.location.pathname;
                }
            }
            var dataParam = '';
            if (url.indexOf(l10n.url.search) > -1) {
                dataParam = 'SearchText=' + $('#searchQuery').val();
            }
            
            $.ajax({
                type: 'POST',
                url: url,
                cache:false,
                dataType: 'html',
                data: dataParam,
                error: function(xhr) {
                    box.fire({type: 'requesterror',component: 'rPopin',status: xhr.status});
                },
                success: function(response) {
                    /* if by any means, ajax request returns a complete html, loads the url */
                    if (response.indexOf('<!DOCTYPE') > -1) {
                        W.location.href = url;
                    } else {
                        var pageDatas = redcats.getPageDatas(response);
                        if (pageDatas.id === 'top' || pageDatas.id === 'right' || pageDatas.id === 'bottom' || pageDatas.id === 'left') {
                            /* checks if popin exists && with the right id && is opened */
                            if (((typeof(box.ui('popin.section').datas) !== 'undefined') && (box.ui('popin.section').datas.id === pageDatas.id)) && box.ui('popin.section').opened) {
                                /* true : update section */
                                box.fire({type: 'requestsuccess',component: 'sectionUpdate',id: pageDatas.template,response: pageDatas.response, pageDatas: pageDatas});
                            } else {
                                /* false : open popin */
                                box.fire({type: 'requestsuccess',component: 'rPopin',response: pageDatas.response, pageDatas: pageDatas});
                            }
                        }
                    }
                }
            });
        }
    }
    
    redcats.getPageDatas = function(response) {
        var pageDatas = $(response).find('#pageDatas'),
            section = pageDatas.find('.id').text(),
            pageTitle = pageDatas.find('.title').text(),
            pageTemplate = pageDatas.find('.template').text(),
            url = pageDatas.find('.url').text().replace('/eng/eng/', '/eng/').replace('/fre/fre/', '/fre/');
        return {
            id: section,
            title: pageTitle,
            template: pageTemplate,
            url: url,
            response: response
        };
    }
    
    /**
     * popin content request
     */
    redcats.popin = function(e) {
        box.fire({type: 'requeststart',component: 'rPopin'});
        var url = e.currentTarget.href;
        if (url.indexOf(W.location.host) > -1) {
            url = url.split(W.location.host)[1];
        }

        if ($("#header .international li:first-child a").attr('href').indexOf(l10n.url.eng) > -1) {
            $("#header .international li:first-child a").attr('href', l10n.url.eng + url.replace('/fre/','/').replace('/eng/','/'));
        }
        if ($("#header .international li:first-child a").attr('href').indexOf(l10n.url.fra) > -1) {
            $("#header .international li:first-child a").attr('href', l10n.url.fra + url.replace('/fre/','/').replace('/eng/','/'));
        }


        $.ajax({
            url: url,
            cache:false,
            dataType: 'html',
            data: url.split('?')[1],
            error: function(xhr) {
                box.fire({type: 'requesterror',component: 'rPopin',response: xhr.responseText});
            },
            success: function(response) {
                /* if by any means, ajax request returns a complete html, loads the url */
                if (response.indexOf('<!DOCTYPE') > -1) {
                    W.location.href = url;
                } else {
                    var pageDatas = redcats.getPageDatas(response);
                    if (pageDatas.url === "") {
                        pageDatas.url = url;
                    }
                    box.fire({type: 'requestsuccess',component: 'rPopin',response: response, pageDatas: pageDatas});
                }
            }
        });
    };
    
    /**
     * update sub sections
     */
    redcats.sectionUpdate = function(e) {
        
        box.fire({type: 'requeststart',component: 'sectionUpdate',target: e});
        var url = e.currentTarget.href;
        if (url.indexOf(W.location.host) > -1) {
            var url = url.split(W.location.host)[1];
        }
        if ($("#header .international li:first-child a").attr('href').indexOf(l10n.url.eng) > -1) {
            $("#header .international li:first-child a").attr('href', l10n.url.eng + url.replace('/fre/','/').replace('/eng/','/'));
        }
        if ($("#header .international li:first-child a").attr('href').indexOf(l10n.url.fra) > -1) {
            $("#header .international li:first-child a").attr('href', l10n.url.fra + url.replace('/fre/','/').replace('/eng/','/'));
        }
        var dataRev = '';
        if (typeof($(e.currentTarget).attr('rev')) != 'undefined') {
            dataRev += 'rev=' + $(e.currentTarget).attr('rev');
        }

        $.ajax({
            type: 'POST',
            url: url,
            cache:false,
            dataType: 'html',
            data: dataRev,
            error: function(xhr) {
                box.fire({type: 'requesterror',component: 'sectionUpdate',status: xhr.status, response: xhr.responseText});
            },
            success: function(response) {
                /* if by any means, ajax request returns a complete html, loads the url */
                if (response.indexOf('<!DOCTYPE') > -1) {
                    W.location.href = url;
                } else {
                    var pageDatas = redcats.getPageDatas(response);
                    box.fire({type: 'requestsuccess',component: 'sectionUpdate',id: pageDatas.template,response: response, pageDatas: pageDatas});
                }
            }
        });
    };
    
    box.dom(document).ready(function() {
    
        box.bind({
            'requesterror.popin.section': function(e) {
                box.ui('popin.section').open({
                    id: 'top',
                    html: e.response
                });
            },
            'beforeopen.popin.section': function(e) {
                /* switches popin config depending on which section to open */
                if (e.namespace === 'right') {
                    var windowWidth = $('#page').getWidth();
                    var sectionWidth = 920 + ((windowWidth - 920) / 2);
                    e.source.dom.insertTarget = '#betweenUs';
                    e.source.dom.insertStyles = {width: 0};
                    e.source.dom.insertAnimStyles = {width: sectionWidth};
                    e.source.dom.removeAnimStyles = {width: 0};
                }
                if (e.namespace === 'left') {
                    e.source.dom.insertTarget = '#discover';
                    e.source.dom.insertStyles = {left: 'viewport:before'};
                    e.source.dom.insertAnimStyles = {left: 'viewport:middle'};
                    e.source.dom.removeAnimStyles = {left: 'viewport:before'};
                }
                if (e.namespace === 'bottom') {
                    e.source.dom.insertTarget = '#bottomPage';
                    e.source.dom.insertStyles = {};
                    e.source.dom.insertAnimStyles = {top: -525};
                    e.source.dom.removeAnimStyles = {top: 0};
                }
                if (e.namespace === 'top') {
                    e.source.dom.insertTarget = '#page';
                    e.source.dom.insertStyles = {top: 'viewport:before',left: 'viewport:middle','min-left': 0};
                    e.source.dom.insertAnimStyles = {top: 50};
                    e.source.dom.removeAnimStyles = {top: 'viewport:before'};
                }
                if ($('#divToolTip').length) {
                    $('#divToolTip').remove();
                    box.ui('scroll').destroy('tooltipScrollable');
                }
            },
            'addtodom.popin.section': function(oEvt) {
                redcats.init();
            },
            /* chrome bug */
            'addtodom.popin.section.right': function() {
                
                var windowWidth = $('#page').getWidth();
                var maxWidth = windowWidth - 55; /* 55px => closed left section width */
                $('#betweenUs').css('width', maxWidth);
            },
            'close.popin.section.right': function() {
                $('#betweenUs').css('width', '56px');
            },
            /* /chrome bug */
            'open.popin.section': function(oEvt) {
                /* Focus inside the popin on the close button */
                oEvt.source.mask.dom.update(oEvt.source.mask.element);
                $(oEvt.source.element).find('.sectionCore').find('.sectionClose').eq(0).attr('tabIndex', '-1').focus();
            },
            'close.popin.section': function(oEvt) {
                if(oEvt.namespace != "right") {
                    $('#betweenUs').css('width', '56px');
                }
//                $.address.title(l10n.title);
//                $.address.value(l10n.home);
            },
            'close.popin.section': function() {
                $('#divToolTip').remove();
            },  
            /**
             * @section     specific popins
             */
            'requeststart.rPopin': function(oEvt) {
                box.ui('mask.sectionMask').show();
                $('a.sectionUpdate').unbind();
            },
            'requesterror.rPopin': function(oEvt) {
                box.ui('popin.section').open({
                    id: 'top',
                    html: oEvt.response
                });
            },
            'requestsuccess.rPopin': function(oEvt) {
                var pageDatas = oEvt.pageDatas;
                $.address.value(pageDatas.url);
                $.address.title(pageDatas.title);
                var datas = {
                    id: pageDatas.id,
                    html: oEvt.response
                };
                box.ui('popin.section').open(datas);
                
            },
            
            /**
             * @section     popin content update
             */
            'requeststart.sectionUpdate': function(oEvt) {
                box.ui('loader.sectionLoader').show();
                if ($("#contact").length < 1){
                    redcats.scroll.remove();
                }
                $('a.sectionUpdate').unbind();
            },
            'requesterror.sectionUpdate': function(oEvt) {
                $('.sectionWrapper').empty().append($(oEvt.response).children());
            },
            'requestsuccess.sectionUpdate': function(oEvt) {
//                $('.sectionWrapper').empty().append($(oEvt.response).children());
//                box.fire({type: 'updatesuccess',component: 'sectionUpdate',id: oEvt.id});
                var pageDatas = redcats.getPageDatas(oEvt.response);
                if ((box.ui('popin.section').datas.id !== pageDatas.id) && box.ui('popin.section').opened) {
                    box.fire({type: 'requestsuccess',component: 'rPopin',response: oEvt.response, pageDatas : pageDatas});
                } else {
                    $('.sectionWrapper').empty().append($(oEvt.response).children());
                    box.fire({type: 'updatesuccess',component: 'sectionUpdate',id: oEvt.id, pageDatas : pageDatas});
                }
                if ($('#divToolTip').length) {
                    $('#divToolTip').remove();
                    box.ui('scroll').destroy('tooltipScrollable');
                }
            },
            'updatesuccess.sectionUpdate': function(oEvt) {
                var pageDatas = oEvt.pageDatas;
                redcats.init();
                /*
                if (D.getElementById('contact')) {
                    // in case of a return of the form with an error not seen in js 
                    redcats.validFormContact();    
                } else {

                }
                */
                $.address.value(pageDatas.url);
                $.address.title(pageDatas.title);
            },
            'updatesuccess.sectionUpdate.contactPress': function(oEvt) {
                //redcats.validFormContact();
            },
            'updatesuccess.sectionUpdate.contactOthers': function(oEvt) {
                //redcats.validFormContact();
            },
            'updatesuccess.sectionUpdate.brandFittingRoom': function(oEvt) {
                if (D.getElementById('contentFlow')) {
                    setTimeout(function(){redcats.initContentFlow();}, 500);
                }
            },
            'requeststart.quizz': function() {
                $('#question .actions').replaceWith('<p>' + l10n.loading + '</p>');
                box.ui('form').destroy('question');
            },
            'requestsuccess.quizz': function(oEvt) {
                $('.sectionWrapper').empty().append($(oEvt.response).children());
                redcats.init();
                if ($('#question').length) {
                    redcats.quizz();
                }
            }
        });
        
        /* detect which popin to open based on content location in the html tree */
        var section, id, htmlId, temp;
        if (!!$('#discover').find('.sectionCore').length) {
            id = 'left';
            htmlId = '#sectionDiscover';
        }
        if (!!$('#betweenUs').find('.sectionCore').length) {
            id = 'right';
            htmlId = '#sectionBetweenUs';
        }
        if (!!$('#bottomPage').find('.sectionCore').length) {
            id = 'bottom';
            htmlId = '#sectionBrand';
        }
        if (!!$('#sectionContact').length) {
            id = 'top';
            htmlId = '#sectionContact';
        }
        if (!!$('#pageError').length) {
            id = 'top';
            htmlId = '#pageError';
        }
        /* landing with a clean url (http://whatever) opens the location.pathname requested page */
        if (!!htmlId) {
            temp = $(htmlId);
            temp.remove();
            var langUrl = W.location.pathname.replace('/fre/','/').replace('/eng/','/');
            if ($("#header .international li:first-child a").attr('href').indexOf(l10n.url.eng) > -1) {
                $("#header .international li:first-child a").attr('href', l10n.url.eng + langUrl);
            }
            if ($("#header .international li:first-child a").attr('href').indexOf(l10n.url.fra) > -1) {
                $("#header .international li:first-child a").attr('href', l10n.url.fra + langUrl);
            }
            
            if (($.address.value() === ('/') || $.address.value() === W.location.pathname)) {
                if ($(htmlId).length < 1) {
                    box.ui('popin.section').open({
                        id: id,
                        html: temp
                    });
                }
                var pageDatas = redcats.getPageDatas(temp);
                //$.address.title(pageDatas.title);
            } else if ($.address.value() === ('/' + l10n.home)) {
                $.address.title(l10n.home);
                return false;
            }    
        }
        
    });
    
})(jQuery);

(function($) {
    /**
     * @section     fancy stuffs
     */
    var W = window, D = W.document, DE = D.documentElement;
    
    // configure scrollbar HTML
    // take notice of class="{$barCls}", because the class name is also configurable
    box.ui('scroll').configure({
        bar: '<a href="#" class="{$barCls}"></a>'
    });
    
    redcats.accordions = function() {
        
        redcats.scroll.compute();
        $('#page').find('.accordion').find('.content:not(.on)').slideUp(0, function() {
            redcats.scroll.compute();
        });
        $('#page').find('.accordion').find('h2').click(function(e) {
            e.preventDefault();
            var toggler = $(this);
            var content = $(this).next();
            if (content.hasClass('on')) {
                content.slideUp('400', function() {
                    toggler.removeClass('on');
                    content.removeClass('on');
                    redcats.scroll.compute();
                    if($('.notScrolled').height() > 420) {
                        redcats.scroll.compute();
                    }
                });
            } else {
                toggler.addClass('on');
                content.addClass('on').slideDown('400', function() {
                    redcats.scroll.compute();
                    if($('.notScrolled').height() > 420) {
                        redcats.scroll.compute();
                    }
                });
            }
        });
        if($('.notScrolled').height() > 420) {
            redcats.scroll.compute();
        }
    };
    
    redcats.subNavigation = function() {
        var toggler = $('.subNavigation > a');
        var subNav = toggler.parent();
        
        toggler.click(function(e) {
            e.preventDefault();
            if (subNav.hasClass('on')) {
                subNav.removeClass('on');
            } else {
                subNav.addClass('on');
                subNav.find('ul').hide().slideDown();
            }
        });
    };
    
    /**
     * @section     scrollbars
     */
    redcats.scroll = {
        add: function() {
            // Ipad Iphone
            box.ui('scroll').create({
                element: '#scrollable',
                buttons: false
            });
            if (redcats.detectDevice()) {
                $('#scrollable').jScrollTouch();
            }
        },
        remove: function() {
            box.ui('scroll').destroy('scrollable');
        },
        compute: function() {
            /*
            console.log(typeof(box.ui('scroll.scrollable')));
            if (typeof(box.ui('scroll.scrollable')) === 'undefined' ) {
                console.log("add");
                redcats.scroll.add();
            }*/
            //box.ui('scroll.scrollable').compute();
            setTimeout(function() {box.ui('scroll.scrollable').compute()}, 400);
        }
    };
    
    redcats.processCarousel = function() {
        if (box.ui('carousel.brands')) {
            box.ui('carousel').destroy('brands');
        }
        box.ui('carousel').create({
            element: '#brands',
            horizontal: true,
            display: 3,
            duration: 200,
            circular:true
        });
    };
    
    /**
     * @section     contentFlow
     */
    redcats.initContentFlow = function() {
        redcats.cf = new ContentFlow('contentFlow', {
            conf: {
                showControlls: true,
                duration: 2000,
                startOnLoad: false
            },
            reflectionHeight: 0,
            maxItemHeight: 330,
            flowSpeedFactor: 0.5,
            relativeItemPosition: 'top/above',
            calcCoordinates: function(item) {
                var h = item.size.height;
                var rP = item.relativePosition;
                var x = rP * 0.25;
                var y = h;
                return {
                    x: x,
                    y: y
                };
            },
            calcSize: function(item) {
                var rP = item.relativePosition;
                var h = 1 - (Math.abs(rP) * 0.1);
                var w = h;
                return {
                    width: w,
                    height: h
                };
            },
            fixItemSize: true
        });
        redcats.cf.init();
        
        var pre = document.createElement('div');
        $CF(pre).addClassName('button');
        pre.addClassName('preButton');
        pre.setAttribute('title', l10n.prev);
        
        var next = document.createElement('div');
        $CF(next).addClassName('button');
        next.addClassName('nextButton');
        next.setAttribute('title', l10n.next);
        
        redcats.cf.Container.appendChild(pre);
        redcats.cf.Container.appendChild(next);
        
        jQuery('.preButton').click(function() {
            redcats.cf.moveTo('left');
        });
        jQuery('.nextButton').click(function() {
            redcats.cf.moveTo('right');
        });

    };
    
})(jQuery);

(function($) {
    /**
     * @section     videos management
     */
    var W = window, D = W.document, DE = D.documentElement;
    
    redcats.player = {
        deploy: function(dim) {
            $('#dPlayer a').click(function(e) {
                e.preventDefault();
                $(this).css('outline', 0);
                $('#dPlayer').animate({width: 500,height: 280,top: -30,left: 0}, 600, function() {
                    redcats.videos.load(e);
                    box.fire({type: 'open',component: 'player'});
                });
            });
        },
        close: function(dim) {
            $('#dPlayer').animate({width: 160,height: 200,top: 0,left: 50}, 400);
        }
    };
    
    redcats.detectDevice = function() {
        /* handle terminal
         @todo better <video> support detection */
        var isIPad = function() {
            return navigator.userAgent.indexOf('iPad') !== -1;
        };
        var isIPhone = function() {
            return navigator.userAgent.indexOf('iPhone') !== -1;
        };
        var isIPod = function() {
            return navigator.userAgent.indexOf('iPod') !== -1;
        };
        return (isIPad() || isIPhone() || isIPod());
    };
    
    redcats.videos = {
        load: function(e) {
            var videoUrl = e.currentTarget.href;
            var subUrl = videoUrl.replace('/video/mp4/','/xml/').replace('.mp4', '.srt');
            var playerWrapper = $('#dPlayer');
            if (redcats.detectDevice()) {
                playerWrapper.addClass('on')
                             .prepend('<a class="closeVideo" href="#">fermer</a>')
                             .append('<video id="videoPlayer" src="' + videoUrl + '" type="video/mp4" width="' + playerWrapper.width() + '" height="' + playerWrapper.height() + '" preload="auto" autoplay="true" controls="controls"></video>' + 
                                     '<div class="srt" data-video="videoPlayer" data-srt="' + subUrl + '"></div>');
                redcats.srt();
            } else {
                redcats.videos.flashPlayer({
                    wrapper: playerWrapper,
                    url: videoUrl,
                    height: playerWrapper.height(),
                    width: playerWrapper.width()
                });
            }
        },
        flashPlayer: function(video) {
            if (!redcats.detectDevice()) {
                /* adobe flash player if not an iPhone/Pod/Pad */
                var xmlSubtitlesFile = null;
                if ($('#xmlContainer').length) {
                    if (!($('#xmlContainer').html().lastIndexOf('/') == $('#xmlContainer').html().length-1)) {
                        xmlSubtitlesFile = $('#xmlContainer').html(); 
                    }
                } else {
                    var xmlSubtitlesFileTmp = null;
                    if (video.url.indexOf('xml=') > -1) {
                        xmlSubtitlesFileTmp = video.url.split('xml=')[1];
                        if (xmlSubtitlesFileTmp.indexOf('&') > -1) {
                            xmlSubtitlesFileTmp = xmlSubtitlesFileTmp.split('&')[0]
                        }
                    }
                    if (!((video.url.lastIndexOf('/') == video.url.length-1) || xmlSubtitlesFileTmp === '')) {
                        xmlSubtitlesFile = xmlSubtitlesFileTmp;
                    }
                }
                video.wrapper.addClass('on').append('<div id="videoPlayer"></div>');
                var flashvars = {flvPath: video.url,showClose:true,playOk: true, subsFile: xmlSubtitlesFile};
                var params = {
                    allowScriptAccess: "always",
                    wmode: "transparent",
                    allowFullScreen: "true"
                };
                var attributes = {
                    id: "videoPlayer",
                    name: "videoPlayer"
                };
                $('#dPlayer .corner').css('display','none');
                swfobject.embedSWF("/extension/redcats/design/web/swf/player.swf", "videoPlayer", video.width, video.height, "9.0.0", "expressInstall.swf", flashvars, params, attributes);
            }
        },
        close: function() {
            $('#dPlayer .corner').css('display','block');
            $('#videoPlayer').remove();
            $('#dPlayer').find('a.closeVideo').remove();
            $('#dPlayer').removeClass('on');
        }
    };
    
    redcats.ajaxVideo = {
        init: function(listener) {
            var listener = $(listener);
            $(listener).click(function(e) {
                e.preventDefault();
                box.fire({type: 'open',component: 'ajaxVideo',source: e});
            });
            if (listener.closest('div').attr('id') === 'managersVideos') {
                box.ui('mask').create({
                    id: 'maskVideo',
                    html: '<div id="maskVideo"></div>',
                    insertTarget: '#managersVideos',
                    insertStyles: {opacity: '0'},
                    insertAnimStyles: {opacity: '0.9'},
                    insertAnimDuration: '200',
                    removeAnimStyles: {opacity: '0'},
                    removeAnimDuration: '150'
                });
                $('#managersVideos').append('<div id="player"></div>');
            } else if (listener.parent().attr('class') === 'btn video') {
                box.ui('mask').create({
                    id: 'maskVideoHome',
                    html: '<div id="maskVideoHome"></div>',
                    insertTarget: '#homeCarousel',
                    insertStyles: {opacity: '0'},
                    insertAnimStyles: {opacity: '0.9'},
                    insertAnimDuration: '200',
                    removeAnimStyles: {opacity: '0'},
                    removeAnimDuration: '150'
                });
                $('#homeCarousel').append('<div id="playerHome"></div>');
            } else if (listener.closest('div').attr('id') === 'moreVideo') {
                box.ui('mask').destroy('maskMoreVideo');
                box.ui('mask').create({
                    id: 'maskMoreVideo',
                    html: '<div id="maskMoreVideo"></div>',
                    insertTarget: '#moreVideo',
                    insertStyles: {opacity: '0'},
                    insertAnimStyles: {opacity: '0.9'},
                    insertAnimDuration: '200',
                    removeAnimStyles: {opacity: '0'},
                    removeAnimDuration: '150'
                });
                $('#moreVideo').append('<div id="player"></div>');
            }
        },
        load: function(e) {
            box.fire({type: 'requeststart',component: 'ajaxVideo',source: e.source});
            $.ajax({
                type: 'POST',
                url: $(e.source.currentTarget).attr('href'),
                dataType: 'html',
                error: function(xhr) {
                    box.fire({type: 'requesterror',component: 'ajaxVideo',status: xhr.status,source: e.source});
                },
                success: function(response) {
                    box.fire({type: 'requestsuccess',component: 'ajaxVideo',response: response,source: e.source});
                }
            });
        },
        flashPlayer: function(e) {
            if (!redcats.detectDevice()) {
                var video = $('#videoContainer'), videoSrc = $('#videoContainer').html(), videoHeight = $("#videoContainer").height(), videoWidth = $("#videoContainer").width();
                var xmlSubtitlesFile = $('#xmlContainer').html();
                /* adobe flash player if not an iPhone/Pod/Pad */
                var flashvars = {flvPath: videoSrc,showClose:true,playOk: true};
                if ($(e.source.currentTarget).parent().attr('class') === 'btn video') {
                    var flashvars = {
                        flvPath: videoSrc,
                        sizeMax: 1,
            			showClose: true,
            			playOk: true,
            			subsFile: xmlSubtitlesFile
                    };
                }
                var params = {
                    allowScriptAccess: "always",
                    wmode: "transparent",
                    allowFullScreen: "true"
                };
                var attributes = {
                    id: "flashPlayer",
                    name: "flashPlayer"
                };
                swfobject.embedSWF("/extension/redcats/design/web/swf/player.swf", "videoContainer", videoWidth, videoHeight, "9.0.0", "expressInstall.swf", flashvars, params, attributes);
            } else {
                
                var videoContainer = $('#videoContainer').parent();
                var url = $('#videoContainer').html();
                var subUrl = url.replace('/video/mp4/','/xml/').replace('.mp4', '.srt');
                var h = $('#videoContainer').height();
                var w = $('#videoContainer').width();
                $('#videoContainer').remove();
                $('#xmlContainer').remove();
                
                videoContainer.html('<video id="videoPlayer" src="'+url+'" type="video/mp4" width="'+w+'" height="'+h+'" preload="auto" autoplay="true" controls="controls">' +
                                    '   <a href="/extension/redcats/design/web/video/mp4/'+url+'.mp4">Download the video</a>' +
                                    '</video>' +
                                    '<div class="srt" data-video="videoPlayer" data-srt="'+subUrl+'"></div>');
                $('#videoPlayer').parent().addClass('on').prepend('<a class="closeVideo" href="#">fermer</a>');
                
                redcats.srt();
                
                $('.closeVideo').click(function(e) {
                    e.preventDefault();
                    box.fire({type: 'close',component: 'ajaxVideo'});
                });
                
            }
        }
    };
    
    box.dom(document).ready(function() {
        box.bind({
            /**
             * @section     video
             */
            'open.player': function(oEvt) {
                $('#dPlayer').find('a.closeVideo').click(function(e) {
                    e.preventDefault();
                    box.fire({type: 'close',component: 'player'});
                });
            },
            'close.player': function(oEvt) {
                redcats.videos.close();
                redcats.player.close();
            },
            /**
             * @section     video managers
             */
            'open.ajaxVideo': function(oEvt) {
                if (D.getElementById('moreVideo')) {
                    redcats.videos.close();
                    redcats.player.close();
                }
                redcats.ajaxVideo.load(oEvt);
            },
            'requeststart.ajaxVideo': function(oEvt) {
                if ($(oEvt.source.currentTarget).closest('div').attr('id') === 'managersVideos') {
                    box.ui('mask.maskVideo').show();
                } else if ($(oEvt.source.currentTarget).closest('div').attr('id') === 'moreVideo') {
                    box.ui('mask.maskMoreVideo').show();
                } else if ($(oEvt.source.currentTarget).parent().attr('class') === 'btn video') {
                    box.ui('mask.maskVideoHome').show();
                }
            },
            'requestsuccess.ajaxVideo': function(oEvt) {
                if ($(oEvt.source.currentTarget).closest('div').attr('id') === 'managersVideos') {
                    $('#player').append($(oEvt.response).find('#videoContainer')).append($(oEvt.response).find('#xmlContainer'));
                } else if ($(oEvt.source.currentTarget).closest('div').attr('id') === 'moreVideo') {
                    $('#player').append($(oEvt.response).find('#videoContainer')).append($(oEvt.response).find('#xmlContainer'));
                } else if ($(oEvt.source.currentTarget).parent().attr('class') === 'btn video') {
                    $('#playerHome').append($(oEvt.response).find('#videoContainer')).append($(oEvt.response).find('#xmlContainer'));
                }
                redcats.ajaxVideo.flashPlayer(oEvt);
            },
            'close.ajaxVideo': function(oEvt) {
                if (D.getElementById('moreVideo')) {
                    $('#player').remove();
                    box.ui('mask.maskMoreVideo').hide();
                    $('#moreVideo').append('<div id="player"></div>');
                }
                if (D.getElementById('managersVideos')) {
                    $('#player').remove();
                    box.ui('mask.maskVideo').hide();
                    $('#managersVideos').append('<div id="player"></div>');
                }
                if (D.getElementById('playerHome')) {
                    $('#playerHome').remove();
                    box.ui('mask.maskVideoHome').hide();
                    $('#homeCarousel').append('<div id="playerHome"></div>');
                }
            }
        });
    });
    
})(jQuery);

(function($) {
    /**
     * @section     forms
     */
    var W = window, D = W.document, DE = D.documentElement;
    
    box.ui('form').addPatterns({
        password: /^.{4,}$/,
        name: /^[azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBN0123456789\u00E0\u00E2\u00E7\u00E8\u00E9\u00EA\u00EB\u00EF\u00F4\u00F9\u00FC\u0153\u00a0\u0020\u0027\u2019\u00C0\u00C1\u00C2\u00C3\u00C4\u00C7\u00C8\u00C9\u00CA\u00CB\u00CC\u00CD\u00CE\u00CF\u00D1\u00D2\u00D3\u00D4\u00D5\u00D6\u00D9\u00DA\u00DB\u00DC\u00DD\s\.'-]*[^0-9]$/,
        telephone: /^\+?[0-9\s\.\(\)]*$/, /* /^[\d\s\.\(\)\+-]{10}$/, */
        zipcode: /^[0-9]{5}$/,
        twoNumbers: /^[0-9]{2}$/,
        fiveNumbers: /^[0-9]{5}$/,
        number: /^[0-9]+$/
    });
    var errorCls = 'error';
    
    var getErrorTarget = function(field) {
        var c, t;
        if ('radio' === field.type) {
            c = field.getElements().parent().parent().prev();
            if (c.length && c.hasClass('legend')) {
                return c;
            } else {
                c = field.getElements().parent().parent().parent().prev();
                if ((c.length && c[0].nodeName.toLowerCase() === 'legend') || (c.length && c[0].className.indexOf('legend' > -1))) {
                    return c;
                }
            }
        } else {
            return field.getLabel();
        }
    };
    
    redcats.addFormError = function(e) {
        box.dom('#' + e.source.id + 'Error').html(e.source.msg);
    };
    
    redcats.addFieldError = function(e) {
        var error = box.dom('#' + e.source.name + 'Error');
        if (error.length) {
            error.html(e.msg);
        } else {
            $(e.source.name + 'Error').remove();
            getErrorTarget(e.source).append('<em id="' + e.source.name + 'Error" class="error">' + e.msg + '</em>');
        }
        error = null;
    };
    
    redcats.removeFieldError = function(e) {
        box.dom('#' + e.source.name + 'Error').remove();
    };
    
    redcats.quizz = function() {
        if (box.ui('form.question') !== 'undefined') {
            box.ui('form').destroy('question');
        }
        var radioName = $('#question').find('input:radio').attr('name');
        box.ui('form').create({
            element: '#question'
        }).mustValidate(function(form) {
            form.field(radioName).mustValidate(function(field) {
                if (!field.isChecked()) {
                    return l10n.errors.title;
                }
            });
            return l10n.errors.quizz;
        });
    };
    
    redcats.validFormContact = function() {
        var civilityFieldName = $("#contact .radios.civility li:first-child input").attr("name");
        if (box.ui('form.contact')) {
            box.ui('form').destroy('contact');
        }
        box.ui('form').create({
            element: '#contact'
        }).mustValidate(function(form) {
            form.field(civilityFieldName).mustValidate(function(field) {
                if (!field.isChecked()) {
                    return l10n.errors.mandatory;
                }
            });
            form.field('lastName').mustValidate(function(field) {
                if (field.isEmpty()) {
                    return l10n.errors.mandatory;
                }
            });
            form.field('firstName').mustValidate(function(field) {
                if (field.isEmpty()) {
                    return l10n.errors.mandatory;
                }
            });
            form.field('phone').mustValidate(function(field) {
                if (field.isEmpty()) {
                    return l10n.errors.mandatory;
                } else if (!field.isMatching('telephone')) {
                    return l10n.errors.invalidInput;
                }
            });
            form.field('email').mustValidate(function(field) {
                if (field.isEmpty()) {
                    return l10n.errors.mandatory;
                } else if (!field.isMatching('email')) {
                    return l10n.errors.unvalidFormat;
                }
            });
            form.field('demand').mustValidate(function(field) {
                if (field.isEmpty()) {
                    return l10n.errors.mandatory;
                }
            });
            
            return l10n.errors.forms;
        });
    };
    
    box.dom(document).ready(function() {
        box.ui('form').create({
            element: '#search'
        });

        box.bind({
            'error.field': redcats.addFieldError,
            'valid.field': redcats.removeFieldError,
            'submit.form': function(e, domEvt) {
                if (e.valid === false) {
                    redcats.addFormError(e);
                }
                if (typeof(redcats.processForm[e.id]) != 'undefined' && typeof(domEvt) !== 'undefined') {
                   redcats.processForm[e.id](e, domEvt);
                }
            }
        });
    
    });
    redcats.processForm = {
        contact : function(e, domEvt) {
            var contactForm = $('#contact');
            var submitName = contactForm.find('input:submit').attr('name');
            var submitVal = contactForm.find('input:submit').val();
            if (e.valid && typeof(domEvt) !== 'undefined') {
                domEvt.preventDefault();
                box.fire({type: 'requeststart',component: 'sectionUpdate'});
                $.ajax({
                    type: 'POST',
                    cache: false,
                    url: $('#contact').attr('action'),
                    data: $('#contact').serialize() + '&' + submitName + '=' + submitVal,
                    dataType: "html",
                    error: function(xhr) {
                        box.fire({type: 'requesterror',component: 'sectionUpdate',status: xhr.status, response: xhr.responseText});
                    },
                    success: function(response) {
                        var pageDatas = redcats.getPageDatas(response);
                        box.fire({type: 'requestsuccess',component: 'sectionUpdate',response: response, pageDatas:pageDatas});
                    }
                });
            }
        },
        question : function(e, domEvt) {
            if (e.valid && typeof(domEvt) !== 'undefined') {
                domEvt.preventDefault();
                var questionForm = $('#question');
                var submitName = questionForm.find('input:submit').attr('name');
                var submitVal = questionForm.find('input:submit').val();
                box.fire({type: 'requeststart',component: 'quizz'});
                $.ajax({
                    type: 'POST',
                    data: questionForm.serialize() + '&' + submitName + '=' + submitVal,
                    url: questionForm.attr('action'),
                    error: function() {
                        questionForm.html('<p class="error ajaxMsg">' + l10n.errors.title + '</p>');
                    },
                    success: function(response) {
                        var pageDatas = redcats.getPageDatas(response);
                        box.fire({type: 'requestsuccess',component: 'quizz',response: response, pageDatas:pageDatas});
                    }
                });
            }
        },
        search : function(e, domEvt) {
            domEvt.preventDefault();
            box.fire({type: 'requeststart', component:'rPopin'});
            var searchForm = $('#search');
            var submitName = searchForm.find('input:image').attr('name');
            var submitVal = searchForm.find('input:image').val();
            $.ajax({
               type: 'GET',
               url: $('#search').attr('action'),
               data: $('#search').serialize() + '&' + submitName + '=' + submitVal,
               error: function(xhr) {
                   box.fire({type: 'requesterror',component: 'sectionUpdate',status: xhr.status, response: xhr.responseText});
               },
               success: function(response) {
                   //$.address.value(searchForm.attr('action'));
                   var pageDatas = redcats.getPageDatas(response);
                   box.fire({type: 'requestsuccess',component: 'rPopin',response: response, pageDatas:pageDatas});
               }
           })
       }
   };
    
})(jQuery);

(function($) {
    /**
     * @section     inits
     */
    var W = window, D = W.document, DE = D.documentElement;
    
    box.dom(document).ready(function() {
    
        box.ui('carousel').create({
            element: '#homeCarousel',
            horizontal: true,
            display: 1,
            duration: 1200,
            circular: false,
            paginate: true
        });
        
        /* binds history & browser buttons events */
        $.address.externalChange(function(e) {
            redcats.manageAddress(e);
        });
        
        
        $.address.internalChange(function(e) {
            var test = e;
        });

        $('#page').delegate('.sectionOpen', 'click', function(e) {
            e.preventDefault();
            box.fire({type: 'close',component: 'ajaxVideo'});
            redcats.popin(e);
        });

        $('#page').delegate('a.sectionClose', 'click', function(e) {
            $.address.value(l10n.home);
            $.address.title(l10n.title);
            if ($("#header .international li:first-child a").attr('href').indexOf(l10n.url.eng) > -1) {
                $("#header .international li:first-child a").attr('href', l10n.url.eng);
            }
            if ($("#header .international li:first-child a").attr('href').indexOf(l10n.url.fra) > -1) {
                $("#header .international li:first-child a").attr('href', l10n.url.fra);
            }
        });
        
        redcats.ajaxVideo.init('#homeCarouselInner .video a');
    });
    
    redcats.init = function() {
        redcats.subNavigation();
        redcats.player.deploy();
        $('#page').find('a.sectionUpdate').bind('click', function(e) {
            e.preventDefault();
            redcats.sectionUpdate(e);
        });
        if ($('#scrollable').length) {
            redcats.scroll.remove();
            setTimeout(function() {redcats.scroll.add()}, 400);
        }
        if (D.getElementById('quizz') && D.getElementById('question')) {
            redcats.quizz();
        }
        if ($('#page').find('.accordion').length) {
            redcats.accordions();
        }
        if (D.getElementById('moreVideo')) {
            redcats.ajaxVideo.init('#moreVideo a');
        }
        if (D.getElementById('manager')) {
            redcats.ajaxVideo.init('#managersVideos a');
        }
        if (D.getElementById('officesMap')) {
            box.ui('plugin.tooltip').create({
                element: '.tooltip'
            });
        }
        if ($('.carousel').length) {
            redcats.processCarousel();
        }
        if ($('#contact').length) {
            redcats.validFormContact();
        }
        if ($('#contentFlow').length) {
            setTimeout(function(){redcats.initContentFlow();}, 500);
        }
        if (typeof(ie7) !== 'undefined') {
            if (D.getElementById('brandsInner')) {
                $('#brandsInner a.logo img').each(function() {
                    var image = $(this);
                    var height = image.height();
                    image.css('margin-top', - height/2);
                });
            }
            if ($('.numbers').length) {
                $('.numbers').each(function() {
                    var span = $(this).find('a').find('span');
                    var height = span.height();
                    span.css('margin-top', - height/2);
                })
            }
        }
    };
})(jQuery);

(function($) {
/*
 * jQuery srt
 *
 * version 0.1 (November 28, 2008)
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
/*
  usage:
    <video src="example.ogg" id="examplevideo" />
    <div class="srt" data-video="examplevideo" data-srt="example.srt"></div>

  jquery.srt.js will try to load subtitles in all elements with 'srt' class.
  'data-video' atribute is used to link to the related video,
  if no data-srt is provided, the contents of the div is parsed as srt.
*/

redcats.srt = function() {
  function toSeconds(t) {
    var s = 0.0
    if(t) {
      var p = t.split(':');
      for(i=0;i<p.length;i++)
        s = s * 60 + parseFloat(p[i].replace(',', '.'))
    }
    return s;
  }
  function strip(s) {
    return s.replace(/^\s+|\s+$/g,"");
  }
  function playSubtitles(subtitleElement) {
    var videoId = subtitleElement.attr('data-video');
    var srt = subtitleElement.text();
    subtitleElement.text('');
    srt = srt.replace(/\r\n|\r|\n/g, '\n')
    
    var subtitles = {};
    srt = strip(srt);
    var srt_ = srt.split('\n\n');
    for(s in srt_) {
        st = srt_[s].split('\n');
        if(st.length >=2) {
          n = st[0];
          i = strip(st[1].split(' --> ')[0]);
          o = strip(st[1].split(' --> ')[1]);
          t = st[2];
          if(st.length > 2) {
            for(j=3; j<st.length;j++)
              t += '\n'+st[j];
          }
          is = toSeconds(i);
          os = toSeconds(o);
          subtitles[is] = {i:i, o: o, t: t};
        }
    }
    var currentSubtitle = -1;
    var ival = setInterval(function() {
      var currentTime = document.getElementById(videoId).currentTime;
      var subtitle = -1;
      for(s in subtitles) {
        if(s > currentTime)
          break
        subtitle = s;
      }
      if(subtitle > 0) {
        if(subtitle != currentSubtitle) {
          subtitleElement.html(subtitles[subtitle].t);
          currentSubtitle=subtitle;
        } else if(subtitles[subtitle].o < currentTime) {
          subtitleElement.html('');
        }
      }
    }, 100);
  }
  $('.srt').each(function() {
    var subtitleElement = $(this);
    var videoId = subtitleElement.attr('data-video');
    if(!videoId) return;
    var srtUrl = subtitleElement.attr('data-srt');
    if(srtUrl) {
      $(this).load(srtUrl, function (responseText, textStatus, req) { playSubtitles(subtitleElement)})
    } else {
      playSubtitles(subtitleElement);
    }
  });

}
})(jQuery);

/*
 * jQuery jScrollTouch plugin 1.1
 *
 * Copyright (c) 2010 Damien Rottemberg damien@dealinium.com
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 *
 */
(function($) {
    $.fn.jScrollTouch = function() {
        if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {
            var isTouchScreen = 1;
        } else {
            var isTouchScreen = 0;
        }
        $(this).css({
            'overflow-y': 'auto',
            'position': 'relative'
        });
        return this.each(function() {
            var cont = $(this);
            
            var height = 0;
            var cpos = cont.scrollTop()
            cont.scrollTop(100000);
            height = cont.scrollTop();
            cont.scrollTop(cpos);
            var fullheight = height + cont.outerHeight();
            var scrollbarV_length = cont.innerHeight() * (cont.innerHeight() / fullheight) + 2;
            
            var width = 0;
            var lpos = cont.scrollLeft();
            cont.scrollLeft(100000);
            width = cont.scrollLeft();
            cont.scrollLeft(lpos);
            var fullwidth = width + cont.outerWidth();
            
            cont.bind('mousedown touchstart', function(e) {
                cpos = cont.scrollTop();
                draggable = $('.draggable');
                if (isTouchScreen) {
                    e = e.originalEvent.touches[0];
                }
                
                var sY = e.pageY;
                var sX = e.pageX;
                
                cont.bind('mousemove touchmove ', function(ev) {
                    if (isTouchScreen) {
                        ev.preventDefault();
                        ev = ev.originalEvent.touches[0];
                    }
                    
                    var top = cpos - (ev.pageY - sY);
                    var left = lpos - (ev.pageX - sX);
                    
                    cont.scrollTop(top);
                    cpos = cont.scrollTop();
                    sY = ev.pageY;
                    
                    if (isTouchScreen) {
                        draggable.css('top', Math.min(cpos + cpos * cont.innerHeight() / fullheight, fullheight - scrollbarV_length) + 'px');
                    }
                });
                cont.bind('mouseup touchend', function(ev) {
                    cont.unbind('mousemove touchmove mouseup touchend');
                });
            });
        });
    }
})(jQuery);
function closeFlash() {
    box.fire({
        type: 'close',
        component: 'player'
    });
    box.fire({
        type: 'close',
        component: 'ajaxVideo'
    });
};

function getTagPlayVid(videoName){
	_gaq.push(['_trackEvent', 'Videos', 'Play', videoName]);
};

