jQuery.cookie = function (key, value, options) {

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

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

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

        value = String(value);

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

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

/* ==========================================================
 * bootstrap-twipsy.js v1.3.0
 * http://twitter.github.com/bootstrap/javascript.html#twipsy
 * Adapted from the original jQuery.tipsy by Jason Frame
 * ==========================================================
 * Copyright 2011 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================== */


!function( $ ) {

 /* CSS TRANSITION SUPPORT (https://gist.github.com/373874)
  * ======================================================= */

  var transitionEnd

  $(document).ready(function () {

    $.support.transition = (function () {
      var thisBody = document.body || document.documentElement
        , thisStyle = thisBody.style
        , support = thisStyle.transition !== undefined || thisStyle.WebkitTransition !== undefined || thisStyle.MozTransition !== undefined || thisStyle.MsTransition !== undefined || thisStyle.OTransition !== undefined
      return support
    })()

    // set CSS transition event type
    if ( $.support.transition ) {
      transitionEnd = "TransitionEnd"
      if ( $.browser.webkit ) {
        transitionEnd = "webkitTransitionEnd"
      } else if ( $.browser.mozilla ) {
        transitionEnd = "transitionend"
      } else if ( $.browser.opera ) {
        transitionEnd = "oTransitionEnd"
      }
    }

  })


 /* TWIPSY PUBLIC CLASS DEFINITION
  * ============================== */

  var Twipsy = function ( element, options ) {
    this.$element = $(element)
    this.options = options
    this.enabled = true
    this.fixTitle()
  }

  Twipsy.prototype = {

    show: function() {
      var pos
        , actualWidth
        , actualHeight
        , placement
        , $tip
        , tp

      if (this.getTitle() && this.enabled) {
        $tip = this.tip()
        this.setContent()

        if (this.options.animate) {
          $tip.addClass('fade')
        }

        $tip
          .remove()
          .css({ top: 0, left: 0, display: 'block' })
          .prependTo(document.body)

        pos = $.extend({}, this.$element.offset(), {
          width: this.$element[0].offsetWidth
        , height: this.$element[0].offsetHeight
        })

        actualWidth = $tip[0].offsetWidth
        actualHeight = $tip[0].offsetHeight

        placement = maybeCall(this.options.placement, this, [ $tip[0], this.$element[0] ])

        switch (placement) {
          case 'below':
            tp = {top: pos.top + pos.height + this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2}
            break
          case 'above':
            tp = {top: pos.top - actualHeight - this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2}
            break
          case 'left':
            tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth - this.options.offset}
            break
          case 'right':
            tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width + this.options.offset}
            break
        }

        $tip
          .css(tp)
          .addClass(placement)
          .addClass('in')
      }
    }

  , setContent: function () {
      var $tip = this.tip()
      $tip.find('.twipsy-inner')[this.options.html ? 'html' : 'text'](this.getTitle())
      $tip[0].className = 'twipsy'
    }

  , hide: function() {
      var that = this
        , $tip = this.tip()

      $tip.removeClass('in')

      function removeElement () {
        $tip.remove()
      }

      $.support.transition && this.$tip.hasClass('fade') ?
        $tip.bind(transitionEnd, removeElement) :
        removeElement()
    }

  , fixTitle: function() {
      var $e = this.$element
      if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') {
        $e.attr('data-original-title', $e.attr('title') || '').removeAttr('title')
      }
    }

  , getTitle: function() {
      var title
        , $e = this.$element
        , o = this.options

        this.fixTitle()

        if (typeof o.title == 'string') {
          title = $e.attr(o.title == 'title' ? 'data-original-title' : o.title)
        } else if (typeof o.title == 'function') {
          title = o.title.call($e[0])
        }

        title = ('' + title).replace(/(^\s*|\s*$)/, "")

        return title || o.fallback
    }

  , tip: function() {
      if (!this.$tip) {
        this.$tip = $('<div class="twipsy" />').html('<div class="twipsy-arrow"></div><div class="twipsy-inner"></div>')
      }
      return this.$tip
    }

  , validate: function() {
      if (!this.$element[0].parentNode) {
        this.hide()
        this.$element = null
        this.options = null
      }
    }

  , enable: function() {
      this.enabled = true
    }

  , disable: function() {
      this.enabled = false
    }

  , toggleEnabled: function() {
      this.enabled = !this.enabled
    }

  }


 /* TWIPSY PRIVATE METHODS
  * ====================== */

   function maybeCall ( thing, ctx, args ) {
     return typeof thing == 'function' ? thing.apply(ctx, args) : thing
   }

 /* TWIPSY PLUGIN DEFINITION
  * ======================== */

  $.fn.twipsy = function (options) {
    $.fn.twipsy.initWith.call(this, options, Twipsy, 'twipsy')
    return this
  }

  $.fn.twipsy.initWith = function (options, Constructor, name) {
    var twipsy
      , binder
      , eventIn
      , eventOut

    if (options === true) {
      return this.data(name)
    } else if (typeof options == 'string') {
      twipsy = this.data(name)
      if (twipsy) {
        twipsy[options]()
      }
      return this
    }

    options = $.extend({}, $.fn[name].defaults, options)

    function get(ele) {
      var twipsy = $.data(ele, name)

      if (!twipsy) {
        twipsy = new Constructor(ele, $.fn.twipsy.elementOptions(ele, options))
        $.data(ele, name, twipsy)
      }

      return twipsy
    }

    function enter() {
      var twipsy = get(this)
      twipsy.hoverState = 'in'

      if (options.delayIn == 0) {
        twipsy.show()
      } else {
        twipsy.fixTitle()
        setTimeout(function() {
          if (twipsy.hoverState == 'in') {
            twipsy.show()
          }
        }, options.delayIn)
      }
    }

    function leave() {
      var twipsy = get(this)
      twipsy.hoverState = 'out'
      if (options.delayOut == 0) {
        twipsy.hide()
      } else {
        setTimeout(function() {
          if (twipsy.hoverState == 'out') {
            twipsy.hide()
          }
        }, options.delayOut)
      }
    }

    if (!options.live) {
      this.each(function() {
        get(this)
      })
    }

    if (options.trigger != 'manual') {
      binder   = options.live ? 'live' : 'bind'
      eventIn  = options.trigger == 'hover' ? 'mouseenter' : 'focus'
      eventOut = options.trigger == 'hover' ? 'mouseleave' : 'blur'
      this[binder](eventIn, enter)[binder](eventOut, leave)
    }

    return this
  }

  $.fn.twipsy.Twipsy = Twipsy

  $.fn.twipsy.defaults = {
    animate: true
  , delayIn: 0
  , delayOut: 0
  , fallback: ''
  , placement: 'above'
  , html: false
  , live: false
  , offset: 0
  , title: 'title'
  , trigger: 'hover'
  }

  $.fn.twipsy.elementOptions = function(ele, options) {
    return $.metadata ? $.extend({}, options, $(ele).metadata()) : options
  }

}( window.jQuery || window.ender );

/* ===========================================================
 * bootstrap-popover.js v1.3.0
 * http://twitter.github.com/bootstrap/javascript.html#popover
 * ===========================================================
 * Copyright 2011 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =========================================================== */


!function( $ ) {

  var Popover = function ( element, options ) {
    this.$element = $(element)
    this.options = options
    this.enabled = true
    this.fixTitle()
  }

  /* NOTE: POPOVER EXTENDS BOOTSTRAP-TWIPSY.js
     ========================================= */

  Popover.prototype = $.extend({}, $.fn.twipsy.Twipsy.prototype, {

    setContent: function () {
      var $tip = this.tip()
      $tip.find('.title')[this.options.html ? 'html' : 'text'](this.getTitle())
      $tip.find('.content p')[this.options.html ? 'html' : 'text'](this.getContent())
      $tip[0].className = 'popover'
    }

  , getContent: function () {
      var content
       , $e = this.$element
       , o = this.options

      if (typeof this.options.content == 'string') {
        content = $e.attr(o.content)
      } else if (typeof this.options.content == 'function') {
        content = this.options.content.call(this.$element[0])
      }
      return content
    }

  , tip: function() {
      if (!this.$tip) {
        this.$tip = $('<div class="popover" />')
          .html('<div class="arrow"></div><div class="inner"><h3 class="title"></h3><div class="content"><p></p></div></div>')
      }
      return this.$tip
    }

  })


 /* POPOVER PLUGIN DEFINITION
  * ======================= */

  $.fn.popover = function (options) {
    if (typeof options == 'object') options = $.extend({}, $.fn.popover.defaults, options)
    $.fn.twipsy.initWith.call(this, options, Popover, 'popover')
    return this
  }

  $.fn.popover.defaults = $.extend({} , $.fn.twipsy.defaults, { content: 'data-content', placement: 'right'})

}( window.jQuery || window.ender );

$(function() {
    // init namespace
    var App = App || {};

    // init nested namespaces
    App.model = App.model || {};
    App.collection = App.collection || {};
    App.router = App.router || {};
    App.view = App.view || {};


    // global var
    App.context = {
        open_pane: false,
        scrollpane_api: null,
        scrollpane_lot_api: null
    };

    // init model
    App.model.LotLight = Backbone.Model.extend({
        toJson: function() {
            var item = _.clone(this.attributes);
            return item;
        }
    });

    // init collection
    App.collection.LotLigth = Backbone.Collection.extend({
        model: App.model.LotLight,

        comparator: function(lot) {
           return 99999999 - parseInt(lot.get('id'));
        }
    });

    // route
    App.router.Workspace = Backbone.Router.extend({
        routes: {
            'prive/lots/': 'initLotLigthView',
            'prive/lots/*filters': 'refreshLotLightView',
            'prive/lots/:page': 'refreshLotLightView',
            'lots/:id': 'showLot'
        },

        initialize: function(options) {
            if (!_.isUndefined(options) && !_.isUndefined(options.collection)) {
                this.collection = options.collection;
            } else {
                this.collection = new App.collection.LotLigth();
            }

            this.collectionView = new App.view.LotLigthCollectionView({ router: this });

            this.routePrefix = '/';
            if (/pro_dev.php\/.*/.test(window.location.pathname)) {
               this.routePrefix = '/pro_dev.php/';
            }

            _.bindAll(this, 'initLotLigthView', 'refreshLotLightView', 'showLot', 'getUrlSegments');
        },
        
        initLotLigthView: function() {
            
            var that = this;
            $(that.collectionView.el).html('');
            var segments = this.getUrlSegments(1);
            this.generateCookie(segments);
           
            $.getJSON(this.routePrefix+'prive/lots/', function(data) {
                _.each(data.collection, function(lotData) {
                    var lot = new App.model.LotLight(lotData);
                    that.collection.add(lot);
                    that.collectionView.addLotLigthView(lot);
                });
                that.collectionView.refreshPager(that.routePrefix+'prive/lots/', data.page);
                var scrollpane = $('.scroll-pane').jScrollPane();
                that.collectionView.refreshNumPager(data.page);
                App.context.scrollpane_api = scrollpane.data('jsp');
                $('#container #lots .jspPane').css({ left: '0px' });
            });
        },

        refreshLotLightView: function(page) {
            var that = this;
            var options = {};

            if (this.collection.length == 0) {
                options = { force: true };
            }
            
            var segments = this.getUrlSegments(page);
            this.generateCookie(segments);

            if (_.isNull(App.context.scrollpane_api)) {
                var scrollpane = $('.scroll-pane').jScrollPane({ verticalDragMaxHeight: 260 });
                App.context.scrollpane_api = scrollpane.data('jsp');
            }

            if (_.isNaN(parseInt(segments.page))) {
                segments.page = 1;

                if (!_.isNull(App.context.scrollpane_api)) {
                    App.context.scrollpane_api.getContentPane().html('');
                } else {
                    $(that.collectionView.el).html('');
                    var scrollpane = $('.scroll-pane').jScrollPane({ verticalDragMaxHeight: 260 });
                    App.context.scrollpane_api = scrollpane.data('jsp');
                }

                if (segments.search != '') {
                    that.collection.reset({silent: true});
                }
            }

            $.getJSON(this.routePrefix+'prive/lots/'+segments.page+segments.search, options, function(data) {
                if (data.collection.length > 0) {

                    _.each(data.collection, function(lotData) {
                        var lot = new App.model.LotLight(lotData);
                        that.collection.add(lot);
                        that.collectionView.addLotLigthView(lot);
                    });
                    
                    that.collectionView.refreshNumPager(segments.page);
                    that.collectionView.refreshPager(that.routePrefix+'prive/lots/', data.page, segments.search);

                    if (!_.isUndefined(data.title)) {
                      $('#container #lots h4').html(data.title);
                    }

                    if (!_.isUndefined(options.force) && options.force == true && segments.page > 1) {
                        var anchor = parseInt(page - 1) * 10;

                        if (!_.isNull(App.context.scrollpane_api)) {
                            App.context.scrollpane_api.scrollToBottom();
                        } else {
                            $.scrollTo('.lot_light:eq('+anchor+')');
                        }
                    }
                }
                else {
                    that.collectionView.removePager();
                    that.collectionView.displayNoResult();
                }
            });
        },

        getUrlSegments: function(page) {
            var search = window.location.search;

            if (!Modernizr.history) {
                // parse hash to extract window.location.search
                var hash = window.location.hash;
                var pattern = /(.*)\?(.*)/;
                if (pattern.test(hash)) {
                    var parse = pattern.exec(hash);
                    search = '?'+parse[2];
                }
            }

            var pattern = /(\d)+\?(.*)/;
            if (pattern.test(page)) {
                var parse = pattern.exec(page);
                var page = parseInt(parse[1]);
            }

            return {
                url: this.routePrefix+'prive/lots/',
                page: page,
                search: search   
            };
        },

        showLot: function(id) {
            var that = this;
            
            $.get(this.routePrefix+'lots/'+id, function(data) {
                if (data != '') {
                    var lotView = new App.view.LotView({ router: that, html: data });
                    var el = lotView.render().el;

                    //$('a.itineraire').fancybox({ 'overlayShow': true, 'frameWidth': 800, 'frameHeight': 600 });
                    el.find('abbr.timeago').timeago();
                    $('#container #lot_pane .jspPane').css({ left: '4px' });

                    $('a.popover-lnk').popover({
                       offset: 10,
                       trigger: 'manual',
                       html: true
                    });

                    $('a.popover-lnk').click(function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        $(this).popover('show');
                    });

                    $('body').click(function(e) {
                        $('a.popover-lnk').popover('hide');
                        $('.popover').remove();
                    });
                }
            }, 'html');
        },

        generateCookie: function(segments) {
            $.cookie('referer', segments.url+segments.page+segments.search);
        }
    });


    // views
    App.view.LotLigthView = Backbone.View.extend({
        tagName: 'div',

        template: $('#lot_light_tpml'),

        events: {
            "click .lot_light": "showLot"    
        },

        initialize: function(options) {
            this.router = options.router;    
        },

        render: function() {
            $(this.el).html(this.template.tmpl(this.model.toJSON()));
            return this;
        },

        showLot: function(e) {
            e.preventDefault();
            var el = $(e.currentTarget);
            el.addClass('visited');
            $('.jspPane div.active').removeClass('active');
            el.addClass('active');
            $.cookie('lot_referer', null);

            this.router.navigate('lots/'+el.attr('data-lot-id'), true);
        }
    });

    App.view.LotLigthCollectionView = Backbone.View.extend({
        el: $('#lots_collection_pager'),
        
        events: {
            "click #js_pager": "refreshView" ,
            "click #num-pager a": "scrollTo"
        },

        initialize: function(options) {
            this.router = options.router;
            if (!_.isNull(App.context.scrollpane_api)) {
                App.context.scrollpane_api.getContentPane().html('');
            } else {
                $(this.el).html('');
            }
            _.bindAll(this, 'refreshView', 'scrollTo');
        },

        addLotLigthView: function(model) {
            var modelView = new App.view.LotLigthView({ model: model, router: this.router });

            if (!_.isNull(App.context.scrollpane_api)) {
                App.context.scrollpane_api.getContentPane().append(modelView.render().el);
                App.context.scrollpane_api.reinitialise();
            } else {
                $(this.el).append(modelView.render().el);
            }
            
            $("abbr.timeago").timeago();
        },

        refreshPager: function(url, page, params) {
            $('#js_pager').remove();
            
            if (!_.isNull(page)) {
                var pager = $('#lot_pager').tmpl({url: url, page: page, params: params});

                if (!_.isNull(App.context.scrollpane_api)) {
                    App.context.scrollpane_api.getContentPane().append(pager);
                    App.context.scrollpane_api.reinitialise();
                } else {
                    $(this.el).append(pager);
                }  
            }
        },

        removePager: function() {
            $('#js_pager').remove();
        },
        
        refreshNumPager: function(page) {
            if(_.isNull(page))
                page = 1;
                
            if(page > 1 && !$('#page1').length)
                page = 1;
            
            var titlePage = '<div id="page'+(page)+'" class="sep-pages">Page n°'+(page)+'</div>';
            if(page > 1)
                $('#js_pager').before(titlePage);
            else
                $('.jspPane div').first().before(titlePage);

            var contentNumPager = '<li class="title">Pages:</li>';
            for(i=1;i<=page;i++)
                contentNumPager += '<li><a href="#lots_collection_pager" rel="#page'+i+'" class="navigation-scrollpane">'+i+'</span></li>';

            if($('#num-pager').length)
                $('#num-pager').remove();
        
            $('.jspContainer').after('<ul id="num-pager">'+contentNumPager+'</ul>');
            App.context.scrollpane_api.reinitialise();
        },

        refreshView: function(e) {
            e.preventDefault();
            $('#container #lots .jspPane').css({ left: '0px' });
            this.router.navigate($(e.currentTarget).find('a').attr('href'), true);
        },
        
        scrollTo: function(e) {
            var el = $(e.currentTarget);
            App.context.scrollpane_api.scrollToElement(el.attr('rel'), true);
        },

        displayNoResult: function() {
            if (!_.isNull(App.context.scrollpane_api)) {
                App.context.scrollpane_api.getContentPane().html('<div class="notice">Aucun résultat pour votre recherche</div>');
            } else {
                $(that.collectionView.el).html('<div class="notice">Aucun résultat pour votre recherche</div>');
            }
        }
    });

    App.view.LotView = Backbone.View.extend({
        el: $('#lot_pane'),

        events: {
            "click a.history_back": 'closePane',
            "click div.lot_retour": 'showLotRetour',
            "click a.track": 'trackExport'    
        },

        initialize: function(options) {
            this.router = options.router;
            this.html = options.html;

            if (!App.context.open_pane) {
                // open pane with jquery animate
                // init scrollbar and height
                this.openPane();
            }

            _.bindAll(this, 'openPane', 'closePane', 'render', 'showLotRetour', 'trackExport');
        },

        openPane: function() {            
            App.context.open_pane = true;
            $(this.el).show();
        },

        closePane: function(e) {
            e.preventDefault();
            $('.jspPane div.active').removeClass('active');
            
            if (!_.isNull($.cookie('lot_referer'))) {
                var lot_referer = $.cookie('lot_referer');
                $.cookie('lot_referer', null);
                this.router.navigate(lot_referer, true);

            } else {
                if (App.context.open_pane == true) {
                    App.context.open_pane = false;
                    $(this.el).hide();

                    var referer = $.cookie('referer');
                    if (_.isUndefined(referer)) {
                        referer = 'prive/lots/';
                    }

                    this.router.navigate(referer, false);
                }
            }
        },

        showLotRetour: function(e) {
            e.preventDefault();
            var el = $(e.currentTarget);
            $.cookie('lot_referer', 'lots/'+el.attr('data-parent-id'));

            this.router.navigate('lots/'+el.attr('data-lot-id'), true);
        },

        trackExport: function(e) {
            var el = $(e.currentTarget);
            var prefix = this.router.routePrefix;

            $.ajax({
              url: prefix+'lot_private/trackExport',
              data: {
                id: el.attr('data-lot-id'),
                tracking_code: el.attr('data-export-type')
              },
              dataType: 'json',
              type: 'POST'
            });
        },

        render: function() { 
            if (_.isNull(App.context.scrollpane_lot_api)) {
                $(this.el).html(this.html);
                var scrollpanelot = $('.scroll-pane-lot').bind('jsp-scroll-y', function(event, scrollPositionY, isAtTop, isAtBottom) {
                    $('#container #lot_pane .jspPane').css({ left: '4px' });
                }).bind('jsp-initialised', function(event, isScrollable) {
                    $('#container #lot_pane .jspPane').css({ left: '4px' });
                }).jScrollPane({ verticalDragMaxHeight: 260, hijackInternalLinks: true });
                if ($('.scroll-pane-lot').length > 0) {
                  App.context.scrollpane_lot_api = scrollpanelot.data('jsp');
                }

            } else {
                App.context.scrollpane_lot_api.getContentPane().html(this.html);
                App.context.scrollpane_lot_api.reinitialise();
                App.context.scrollpane_lot_api.scrollToElement('#show', true);
            }
            return this;
        }
    });

    // viewport
    App.view.Viewport = Backbone.View.extend({
        el: $('body'),
        
        events: {
            "submit #container form.lot_search": "submitSearch"    
        },

        initialize: function(options) {
            this._initHistory(options.collection);
            this._initUI();

            var search = window.location.search;
            if (/\?display_lot=(\d+)/.test(search)) {
              var lot_infos = /\?display_lot=(\d+)/.exec(search);
              var lot_id = lot_infos[1];
              this.router.navigate('lots/'+lot_id, true);
            } 
        },

        submitSearch: function(e) {
            e.preventDefault();

            if (!_.isNull(App.context.scrollpane_api)) {
                App.context.scrollpane_api.scrollTo(0, 0);
            }

            var el = $(e.currentTarget);
            if (el.find('#filters_uuid').val() == 'Rechercher une référence') {
              el.find('#filters_uuid').val(null);
            }

            if (el.find('#filters_departements').val() == 'Départements de chargement') {
              el.find('#filters_departements').val(null);
            }

            this.router.navigate('prive/lots/?'+$(e.currentTarget).serialize(), true);
        },

        _initHistory: function(collection) {
            this.router = new App.router.Workspace({collection: collection});

            if (!_.isUndefined(Backbone.history)) {
                this.pushState = Modernizr.history ? true : false;

                this.routePrefix = '/';
                if (/pro_dev.php\/.*/.test(window.location.pathname)) {
                   this.routePrefix = '/pro_dev.php/';
                }

                if (!this.pushState) {
                    window.location.hash = '#'+window.location.pathname+window.location.search;
                }

                Backbone.history.start({pushState: this.pushState, silent: false, root: this.routePrefix });
            }
        },

        _initUI: function() {
            if ($('#lot_pane').length == 1) {
                if (App.context.open_pane == true) {
                    $('#lot_pane').hide();
                }
            }

            $( ".datepicker" ).datepicker({
                showOn: "button",
                buttonImage: "/css/images/calendar.png",
                buttonImageOnly: true,
                changeMonth: true,
                changeYear: true
            });

            $("abbr.timeago").timeago();

            this.el.ajaxStart(function() {
                $('#spinner').css({
                   'top': ($(document).height() - $(window).height()) + (( $(window).height() - 200) /2),
                   'left': ($(window).width() - 200) /2
                });
                $('#spinner').show();
            });

            this.el.ajaxStop(function() {
                $('#spinner').hide();
            });
        }
    });


    var mm = new App.view.Viewport({collection: new App.collection.LotLigth() });
    
    var opts = {
      lines: 12, // The number of lines to draw
      length: 7, // The length of each line
      width: 4, // The line thickness
      radius: 10, // The radius of the inner circle
      color: '#fff', // #rgb or #rrggbb
      speed: 1, // Rounds per second
      trail: 60, // Afterglow percentage
      shadow: false // Whether to render a shadow
    };
    var target = document.getElementById('spinner');
    var spinner = new Spinner(opts).spin(target);
    $('#spinner').hide();

    var interval = window.setInterval(function() {
        $("abbr.timeago").timeago();
    }, 60000);

    /* gestion des onglets */
    $('.liste').hide();
    $('div#page_1').show();
    $('#onglet_1').parent('li').addClass('selected');
    $('#tabs a.onglet').click( function() {
        $('#tabs ul li').removeClass('selected');   
        $(this).parent('li').addClass('selected');  
        var onglet = $(this).attr('href');
        $('.liste').hide();         
        $(onglet).show();
    });

    //$("a.fancybox, a.itineraire").fancybox({ 'overlayShow': true, 'frameWidth': 800, 'frameHeight': 600 });     
});
