/***================================================================================================================================
        O N   D O C U M E N T   R E A D Y
==================================================================================================================================*/

        $(document).ready(function(){
                /***================================================================================================================
                        divers et déclarations
                ==================================================================================================================*/
                var slash = '/';
                var spanTextLength = 50;

                var deviceAgent = navigator.userAgent.toLowerCase();
                var agent = deviceAgent.match(/(iphone|ipod|ipad)/);
                if (agent == 'iphone,iphone'){
                        location = 'http://local.iphone.lewebconcret.ch';
                }else if(agent == 'ipad,ipad'){
                        location = 'http://local.ipad.lewebconcret.ch';
                }

                /***================================================================================================================
                        général
                ==================================================================================================================*/

                String.prototype.short = function (){
                        if (this.length == 0 || this.length<=spanTextLength) return this;
                        return this.substr(0, spanTextLength)+"...";
                };

                String.prototype.stripTags = function() {
                        return this.replace(/<\/?[^>]+>/gi, '');
                };

                String.prototype.escapeHTML = function() {
                        var div = document.createElement('div');
                        var text = document.createTextNode(this);
                        div.appendChild(text);
                        return div.innerHTML;
                };

                String.prototype.unescapeHTML = function() {
                        var div = document.createElement('div');
                        div.innerHTML = this.stripTags();
                        return div.childNodes[0].nodeValue;
                };

                /*------------------------------------------------------------------------------------------------------------------
                        GA
                ------------------------------------------------------------------------------------------------------------------*/
                /*
                var _gaq = _gaq || [];
                _gaq.push(['_setAccount', 'UA-7596484-1']);
                _gaq.push(['_trackPageview']);

                (function() {
                        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
                        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
                        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
                })();
                */
                $.ga.load('UA-7596484-1');

                /*------------------------------------------------------------------------------------------------------------------
                        orbit
                ------------------------------------------------------------------------------------------------------------------*/
                if ($.fn.orbit) $('#myScroll').orbit({
                        animation                       : 'horizontal-slide',       /*fade, horizontal-slide, vertical-slide*/
                        animationSpeed                  : 2000,          /*how fast animations are*/
                        advanceSpeed                    : 4000,         /*if timer advance is enabled, time between transitions*/
                        startClockOnMouseOut            : false,         /*if timer should restart on MouseOut*/
                        startClockOnMouseOutAfter       : 0,         /*how long after mouseout timer should start again*/
                        directionalNav                  : false,        /*manual advancing directional navs*/
                        captions                        : false,         /*if has a title, will be placed at bottom*/
                        captionAnimationSpeed           : 500,          /*how quickly to animate in caption on load and between captioned and uncaptioned photos*/
                        timer                           : true         /*if the circular timer is wanted*/
                });

                /*------------------------------------------------------------------------------------------------------------------
                        ticker
                ------------------------------------------------------------------------------------------------------------------*/
                if ($.fn.getTwitter) $("#twitter").getTwitter({
                        userName: "lewebconcret",
                        numTweets: 5,
                        loaderText: "Chargement des informations...",
                        slideIn: true,
                        showHeading: false,
                        headingText: "Latest Tweets",
                        showProfileLink: false,
                        showTimestamp: false
                });

                $("div.ticker").vTicker({
                        speed: 500,
                        pause: 3000,
                        showItems: 1,
                        animation: 'fade',
                        mousePause: true
                });

                $("#tabs").tabs({ fx: { opacity: 'toggle' } });

                $('#date').datepicker();

                $('table.comparison tbody tr:odd td').addClass('odd');
                $('table.comparison tbody tr:even td').addClass('even');
                $('table.comparison tbody tr.prix td').addClass('prix');

                $("table.comparison tbody tr.group").click(function(){$(this).next(".extendableText").toggle();});
                $("dl.exemples dt").click(function(){$(this).next("dd").slideToggle("slow");});

                $(".link").click(function (){var $dataset = $(this).dataset(); if ($dataset.link != "") location = $dataset.link;});

                /*------------------------------------------------------------------------------------------------------------------
                        rollOver
                ------------------------------------------------------------------------------------------------------------------*/
                $("img").mouseover(function(){
                        var imgOriginSrc;
                        if ($(this).attr("data-hsrc") != undefined){
                                imgOriginSrc = $(this).attr("src");
                                $(this).attr({src:$(this).attr("data-hsrc")});

                                $(this).mouseout(function() {$(this).attr({src:imgOriginSrc})});
                        }
                });

                /*------------------------------------------------------------------------------------------------------------------
                        sliders
                ------------------------------------------------------------------------------------------------------------------*/

                $(".extendArrow").click(function(){$(this).prev(".extendableText").slideToggle("slow");});
                $(".expand").click(function(){$(this).prev(".extendableText").slideToggle("slow");});
                $(".expand").toggle(
                        function () {$(this).addClass("expandActive");},
                        function () {$(this).removeClass("expandActive");}
                );

                $("div.detailed>ul>li>h1").click(function(){
                        var myAncestor = $(this).parent("li").parent("ul").parent("div.detailed");

                        var nbElements = myAncestor.find("h1").length;

                        var divHeight = ((nbElements)*3)-1 + ".2em";

                        myAncestor.find("h1").removeClass("selected");
                        $(this).addClass("selected");
                        myAncestor.find("div").fadeOut("slow");
                        $(this).next("div").fadeIn("fast");
                        $(this).next("div").css("height", divHeight);
                });

                $("div.detailed li:first-child h1").trigger("click");

                /*------------------------------------------------------------------------------------------------------------------
                        selects
                ------------------------------------------------------------------------------------------------------------------*/

                $("select").change(function(){
                        var $dataset = $(this).dataset();
                        if ($dataset.type = 'callpage') return;


                        switch ($dataset.type){
                                case 'calltype' :
                                        window.location = transport.informations["url"];
                                        break;
                                default:
                                        break;
                        }
                });

                /***================================================================================================================
                        spécifique
                ==================================================================================================================*/

                /*------------------------------------------------------------------------------------------------------------------
                        menu
                ------------------------------------------------------------------------------------------------------------------*/
                var timeout    = 500;
                var closetimer = 0;
                var ddmenuitem = 0;

                function menu_close(){ if(ddmenuitem) ddmenuitem.css('visibility', 'hidden'); }
                function menu_canceltimer(){
                        if(closetimer){
                                window.clearTimeout(closetimer);
                                closetimer = null;
                        }
                }

                $('#menu > li').mouseover( function(){
                        menu_canceltimer();
                        menu_close();
                        ddmenuitem = $(this).find('ul').css('visibility', 'visible');
                })

                $('#menu > li').mouseout(function(){closetimer = window.setTimeout(menu_close, timeout);})

                document.onclick = menu_close;

                /*------------------------------------------------------------------------------------------------------------------
                        ettiquette
                ------------------------------------------------------------------------------------------------------------------*/

                $('#etiquetteLWCBottom').click(function(){$("#etiquetteLWCTop").slideToggle("slow");})

                /*------------------------------------------------------------------------------------------------------------------
                        bannerBar
                ------------------------------------------------------------------------------------------------------------------*/
                $('#bannerBar').click(function(){location='';})

                /*------------------------------------------------------------------------------------------------------------------
                        print button
                ------------------------------------------------------------------------------------------------------------------*/
                $('button.print').click(function() {
                        window.print();
                        return false;
                });

        });

/***============================================================================
        D I S P L A Y
==============================================================================*/
        function effectAppear(o){

                if (o.style.display=='none'){
                        Effect.toggle(o.id, 'appear', {duration: 0.6});
                }else{
                        o.style.display='none';
                };
        }

/***============================================================================
        C H A R G E M E N T   D E   L A   P A G E
==============================================================================*/

        function browserNotification(){

                if ( !(document.getElementById && document.createElement)){

                        /*alert("pas ff");*/

                };

        };

/***============================================================================
        B R O W S E R S
==============================================================================*/

        var isIE      = ((navigator.userAgent.indexOf("MSIE")    >= 0) ? 1 : 0);
        var isFirefox = ((navigator.userAgent.indexOf("Firefox") >= 0) ? 1 : 0);
        var isSafari  = ((navigator.userAgent.indexOf("Safari")  >= 0 && navigator.vendor.indexOf("Apple")   >= 0) ? 1 : 0);

/***============================================================================
        D O M
==============================================================================*/


/***============================================================================
        F O N C T I O N S
==============================================================================*/

        function changeInPW(o, originalClassName){
                o.value = '';
                o.type = 'password';
                o.className = originalClassName;
        };



/***============================================================================
        F O N C T I O N N E M E N T   G E N E R A L
==============================================================================*/

        /*----------------------------------------------------------------------
         ne fait rien
        ----------------------------------------------------------------------*/
        function doNothing(){
                return null;
        };

        /*----------------------------------------------------------------------
         formatte un texte
        ----------------------------------------------------------------------*/
        function contentDisplay(content) {

                content.replace( " "   ,"&nbsp;");

                content.replace( "\r\n","<br>");
                content.replace( "\r"  ,"<br>");
                content.replace( "\n"  ,"<br>");

                return content;

        };

        /*----------------------------------------------------------------------
         renvoie le code de la touche appuyee lors d'un evenement clavier
        ----------------------------------------------------------------------*/
        function getKeyCode(evenement){
                for (prop in evenement){
                        if(prop == 'which') return evenement.which;
                }

                return event.keyCode ? event.keyCode : event.charCode;
        };

        /***--------------------------------------------------------------------
                affiche ou cache des objets
        ----------------------------------------------------------------------*/

        function show_hide(obj)  { if (isDisplayed(obj)){hide(obj)         }else{show(obj)        } } ;
        function visibility(obj) { if (isVisible(obj)  ){invisible(obj)    }else{visible(obj)     } } ;
        function fade(obj, step) { if (isVisible(obj)  ){fadeOutObject(obj.id, step);}else{fadeInObject(obj.id, step);} } ;

        function visible(obj)    { obj.style.visibility = 'block';};
        function invisible(obj)  { obj.style.visibility = 'hidden';};
        function isVisible(obj)  { return obj.style.visibility != 'hidden';};

        function show(obj)       { obj.style.display = 'block';};
        function hide(obj)       { obj.style.display = 'none';     };
        function isDisplayed(obj){ return obj.style.display == 'block';     };


        function showTab(li, lis, tab, tabs){
                for (l=0; l < lis.length; l++) lis[l].className = '';
                li.className = 'selected';

                for (t=0; t < tabs.length; t++) hide(tabs[t]);
                show(tab);
        };

        function getParagraphs(a){

                var var2Return = '';

                for (i=0; i < a.length; i++) {
                        var2Return = var2Return + '<p class="error_title">' + a[i].error_number + '</p>' + '<p class="error_text">' + a[i].error_message + '</p>';
                }

                return var2Return;
        };

        function message(msg){
                $('#messageBar').html(msg);
        }

        function twitterCallback2(twitters) {
                var statusHTML = [];
                for (var i=0; i<twitters.length; i++){
                        var username = twitters[i].user.screen_name;
                        var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
                                return '<a href="'+url+'">'+url+'</a>';
                                }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
                                return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
                        });
                        //statusHTML.push('<li><span>'+status+'</span> <a style="font-size:85%" href="http://twitter.com/'+username+'/statuses/'+twitters[i].id_str+'">'+relative_time(twitters[i].created_at)+'</a></li>');
                        statusHTML.push('<li><span>'+status+'</span></li>');
                }
                document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');
                $("#twitter_update_list a").html('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;en savoir plus...');
                $("#twitter_update_list a").css('margin-right','5em');
                $("#twitter_update_list a").css('float','right');
        }


        function relative_time(time_value) {
                var values = time_value.split(" ");
                time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
                var parsed_date = Date.parse(time_value);
                var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
                var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
                delta = delta + (relative_to.getTimezoneOffset() * 60);

                if (delta < 60)                 { return 'less than a minute ago';
                } else if(delta < 120)          { return 'about a minute ago';
                } else if(delta < (60*60))      { return (parseInt(delta / 60)).toString() + ' minutes ago';
                } else if(delta < (120*60))     { return 'about an hour ago';
                } else if(delta < (24*60*60))   { return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
                } else if(delta < (48*60*60))   { return '1 day ago';
                } else                          { return (parseInt(delta / 86400)).toString() + ' days ago';
                }
        }


/***============================================================================
        D Y N A M I C
==============================================================================*/


