Drupal.locale = { 'pluralFormula': function ($n) { return Number(($n!=1)); }, 'strings': {"":{"An AJAX HTTP error occurred.":"Une erreur HTTP AJAX s'est produite.","HTTP Result Code: !status":"Code de statut HTTP : !status","An AJAX HTTP request terminated abnormally.":"Une requ\u00eate HTTP AJAX s'est termin\u00e9e anormalement.","Debugging information follows.":"Informations de d\u00e9bogage ci-dessous.","Path: !uri":"Chemin: !uri","StatusText: !statusText":"StatutTexte: !statusText","ResponseText: !responseText":"ReponseTexte: !responseText","ReadyState: !readyState":"ReadyState: !readyState","Disabled":"D\u00e9sactiv\u00e9","Enabled":"Activ\u00e9","Edit":"Modifier","None":"Aucun(e)","Upload":"Transfert de fichiers","Configure":"Configurer","Done":"Termin\u00e9","Show":"Afficher","Select all rows in this table":"S\u00e9lectionner toutes les lignes du tableau","Deselect all rows in this table":"D\u00e9s\u00e9lectionner toutes les lignes du tableau","Not published":"Non publi\u00e9","Please wait...":"Veuillez patienter...","Hide":"Masquer","Loading":"En cours de chargement","Only files with the following extensions are allowed: %files-allowed.":"Seuls les fichiers se terminant par les extensions suivantes sont autoris\u00e9s\u0026nbsp;: %files-allowed.","By @name on @date":"Par @name le @date","By @name":"Par @name","Not in menu":"Pas dans le menu","Alias: @alias":"Alias : @alias","No alias":"Aucun alias","New revision":"Nouvelle r\u00e9vision","Drag to re-order":"Cliquer-d\u00e9poser pour r\u00e9-organiser","Changes made in this table will not be saved until the form is submitted.":"Les changements effectu\u00e9s dans ce tableau ne seront pris en compte que lorsque la configuration aura \u00e9t\u00e9 enregistr\u00e9e.","The changes to these blocks will not be saved until the \u003cem\u003eSave blocks\u003c\/em\u003e button is clicked.":"N'oubliez pas de cliquer sur \u003cem\u003eEnregistrer les blocs\u003c\/em\u003e pour confirmer les modifications apport\u00e9es ici.","Show shortcuts":"Afficher les raccourcis","This permission is inherited from the authenticated user role.":"Ce droit est h\u00e9rit\u00e9e du r\u00f4le de l'utilisateur authentifi\u00e9.","No revision":"Aucune r\u00e9vision","@number comments per page":"@number commentaires par page","Requires a title":"Titre obligatoire","Not restricted":"Non restreint","(active tab)":"(onglet actif)","Not customizable":"Non personnalisable","Restricted to certain pages":"R\u00e9serv\u00e9 \u00e0 certaines pages","The block cannot be placed in this region.":"Le bloc ne peut pas \u00eatre plac\u00e9 dans cette r\u00e9gion.","Customize dashboard":"Personnaliser le tableau de bord","Hide summary":"Masquer le r\u00e9sum\u00e9","Edit summary":"Modifier le r\u00e9sum\u00e9","Don't display post information":"Ne pas afficher les information de la contribution","@title dialog":"dialogue de @title","The selected file %filename cannot be uploaded. Only files with the following extensions are allowed: %extensions.":"Le fichier s\u00e9lectionn\u00e9 %filename ne peut pas \u00eatre transf\u00e9r\u00e9. Seulement les fichiers avec les extensions suivantes sont permis : %extensions.","Re-order rows by numerical weight instead of dragging.":"R\u00e9-ordonner les lignes avec des poids num\u00e9riques plut\u00f4t qu'en les d\u00e9placant.","Show row weights":"Afficher les poids des lignes","Hide row weights":"Cacher le poids des lignes","Autocomplete popup":"Popup d'auto-compl\u00e9tion","Searching for matches...":"Recherche de correspondances...","Hide shortcuts":"Cacher les raccourcis"}} };;
function PulldownMenu( args ) {

  var $ = jQuery;
  var menu = this;
  
  /*
   * Defaults
   */
  menu.timerID = undefined;
  menu.timerTimeout = 200;
  menu.pulldownAutoCenter = true;
  menu.pulldownAutoCenterType = 'page'; // centre sur la 'page' ou l'item de 'menu'
  menu.pulldownAutoPosition = true;
  menu.pulldownTopPositionAdjustment = 0;
  menu.pulldownLeftPositionAdjustment = 0;
  menu.pulldownElement = undefined;
  menu.pulldownCursorElement = undefined;
  menu.pulldownCursorAutoCenterElement = '';
  menu.pulldownCursorLeftAdjustment = 0;
  menu.menuElement = undefined;
  menu.visibilityClass = '.casper-ifjs';
  menu.pulldownLayerOrder = 1000;
  menu.openCallback = undefined;

  if( args !== undefined ) {
    
    if( args.pulldownElement  !== undefined ) {
      menu.pulldownElement = args.pulldownElement;
    }
    else {
      return {error: 1, msg:'pulldown element not specified'} // Should use js Error object
    }
    
    if( args.menuElement  !== undefined ) {
      menu.menuElement = args.menuElement;
    }
    else {
      return {error: 2, msg:'menu element not specified'}  // Should use js Error object
    }
    
    if( args.pulldownCursorElement  !== undefined ) {
      menu.pulldownCursorElement = args.pulldownCursorElement;
    }
    if( args.pulldownCursorAutoCenterElement  !== undefined ) {
      menu.pulldownCursorAutoCenterElement = args.pulldownCursorAutoCenterElement;
    }
    if( args.pulldownCursorLeftAdjustment  !== undefined ) {
      menu.pulldownCursorLeftAdjustment = args.pulldownCursorLeftAdjustment;
    }
    if( args.timerTimeout  !== undefined ) {
      menu.timerTimeout = args.timerTimeout;
    }
    if( args.pulldownAutoCenter  !== undefined ) {
      menu.pulldownAutoCenter = args.pulldownAutoCenter;
    }
    if( args.pulldownAutoCenterType  !== undefined ) {
      menu.pulldownAutoCenterType = args.pulldownAutoCenterType;
    }
    if( args.pulldownAutoPosition  !== undefined ) {
      menu.pulldownAutoPosition = args.pulldownAutoPosition;
    }
    if( args.pulldownTopPositionAdjustment  !== undefined ) {
      menu.pulldownTopPositionAdjustment = args.pulldownTopPositionAdjustment;
    }
    if( args.pulldownLeftPositionAdjustment  !== undefined ) {
      menu.pulldownLeftPositionAdjustment = args.pulldownLeftPositionAdjustment;
    }
    if( args.visibilityClass  !== undefined ) {
      menu.visibilityClass = args.visibilityClass;
    }
    if( args.pulldownLayerOrder  !== undefined ) {
      menu.pulldownLayerOrder = args.pulldownLayerOrder;
    }
    if( args.openCallback  !== undefined ) {
      menu.openCallback = args.openCallback;
    }
  }
  
  // take control of the pulldown visibility
  menu.pulldownElement.removeClass( this.visibilityClass ).show().css({
    visibility: 'hidden',
    zIndex: menu.pulldownLayerOrder - 10
  });
  
  menu.menuElement.bind('mouseenter', $.proxy( menu.showPulldown, menu ) );
  menu.menuElement.bind('mouseleave', $.proxy( menu._internalTimer, menu ) );
  menu.pulldownElement.bind('mouseenter', $.proxy( menu.clearTimer, menu ) );
  menu.pulldownElement.bind('mouseleave', $.proxy( menu._internalTimer, menu ) );
  
  menu.setPosition();
  
}

PulldownMenu.method( 'setPosition', function() {

  var $ = jQuery;
  var menu = this;
  var topPosition = 0;
  var leftPosition = 0;
  var menuWidth = 0;
  var pulldownWidth = 0;

  if( menu.pulldownAutoPosition ) {
    topPosition = menu.menuElement.offset().top + menu.menuElement.height() + menu.pulldownTopPositionAdjustment;
    menu.pulldownElement.css({
      top: topPosition
    });
  }
  if( menu.pulldownAutoCenter ) {
    if( menu.pulldownAutoCenterType === 'menu' ) {
      menuWidth = menu.menuElement.width();
      pulldownWidth = menu.pulldownElement.width();
      leftPosition = menu.menuElement.offset().left + ((menuWidth - pulldownWidth ) / 2);
      
      menu.pulldownElement.css({
        left: leftPosition
      });
    }
    else if( menu.pulldownAutoCenterType === 'page' ) {
      leftPosition = (-1 * (menu.pulldownElement.width() / 2) ) + menu.pulldownLeftPositionAdjustment;
      menu.pulldownElement.css({
        left: '50%',
        marginLeft: leftPosition
      });
    }

  }
  else if( menu.pulldownAutoPosition ) {
    leftPosition = menu.menuElement.offset().left + menu.pulldownLeftPositionAdjustment ;
    menu.pulldownElement.css({
      left: leftPosition
    });
  }
  
  if( menu.pulldownCursorElement !== undefined ) {
    if( menu.pulldownCursorAutoCenterElement === '' ) {
      menu.pulldownCursorAutoCenterElement = menu.menuElement;
    }
    leftPosition = menu.menuElement.position().left + (menu.pulldownCursorAutoCenterElement.width()/2) + menu.pulldownCursorLeftAdjustment;
    menu.pulldownCursorElement.css({
      left: leftPosition
    });
  }

});

PulldownMenu.method( 'showPulldown', function( event ) {
  
  var $ = jQuery;
  var menu = this;
  var target = $(event.currentTarget);
  menu.clearTimer();
  menu.setActiveStatus();
  menu.setPosition();
  menu.pulldownElement.stop(true,true).css({
    visibility: 'visible',
    zIndex: menu.pulldownLayerOrder
  });
  
  //Callback on first open
  if( menu.openCallback  !== undefined ) {
     menu.openCallback();
     menu.openCallback = undefined; //Call only once
  }
  
  menu.pulldownElement.find('.boutons').removeClass('.boutons'); 
  menu.pulldownElement.find('.image').removeClass('.image');
  
});

PulldownMenu.method( 'hidePulldown', function( ) {

  var $ = jQuery;
  var menu = this;
  if( menu.pulldownElement != undefined ) {
    if( $.browser.msie && (parseInt($.browser.version) < 9) ){
      menu.pulldownElement.css({
        visibility: 'hidden'
      });
    }
    else {
      menu.pulldownElement.animate({
        opacity: 0
      }, 300, function(){ menu.pulldownElement.css({
          visibility: 'hidden',
          opacity: 1,
          display: 'block'
        });
      });
    }
  }
  menu.clearActiveStatus();
    
});

PulldownMenu.method( 'setActiveStatus', function() {
  
  var menu = this;
  menu.menuElement.addClass('active-pulldown');

});

PulldownMenu.method( 'clearActiveStatus', function( ) {

  var menu = this;
  menu.menuElement.removeClass('active-pulldown');
  
});

PulldownMenu.method( 'clearTimer', function() {

  var menu = this;
  menu._internalTimer( 'clear' );

});

PulldownMenu.method( '_internalTimer', function( event ) {

  var $ = jQuery;
  var menu = this;
  if( menu.timerID != undefined || event === 'clear' ) {
    clearTimeout( menu.timerID );
  }
  if( menu.timerTimeout != undefined && event !== 'clear' ) {
    menu.pulldownElement.css({
      zIndex: menu.pulldownLayerOrder - 10
    });
    menu.timerID = setTimeout(  $.proxy( menu.hidePulldown , menu ) , menu.timerTimeout );
  }
  
});;
function ImageLoader( args ) {

  var $ = jQuery,
         loader = this;
  
  loader.target = '.lazy-load';
  loader.url = new Array();
  loader.urlAttribute = 'data-tva-image';
  loader.replaceChildren = false;
  loader.clearClasses = false;
  loader.injectClasses = '';
  loader.images = {};
  loader.idGenerator = loader.uid();
  
  if( args !== undefined ) {
    if( args.target  !== undefined ) {
      loader.target = args.target;
    }
    if( args.url  !== undefined ) {
      loader.url = args.url;
    }
    if( loader.url === '' ) {
      if( args.urlAttribute  !== undefined ) {
        loader.urlAttribute = args.urlAttribute;
      }
    }
    if( args.clearClasses  !== undefined ) {
      loader.clearClasses = args.clearClasses;
    }
    if( args.replaceChildren  !== undefined ) {
      loader.replaceChildren  = args.replaceChildren ;
    }
    if( args.injectClasses  !== undefined ) {
      loader.injectClasses = args.injectClasses;
    }
  }
  
  $( loader.target ).each( function( index ) {
    
    var element = {},
        uid = loader.idGenerator(),
        url = '';
        
        element.target = $(this);
    
    if( loader.url.length === 0 ) {
      url = element.target.attr( loader.urlAttribute );
      if( url === undefined ) {
        return { 'error': 'url non défini.' };
      }
    }
    else {
      url = loader.url[index];
    }
    
    element.clearClasses = loader.clearClasses;
    element.replaceChildren = loader.replaceChildren;
    
    if( loader.injectClasses !== '' ){
      element.injectClasses = loader.injectClasses;
    }

    // Load image if not already loaded
    if( loader.images[ url+uid ] === undefined ) {
      loader.images[ url+uid ] = document.createElement('img');
      $( loader.images[ url+uid ] ).bind('load', $.proxy( loader.replaceElement, element ) );
      loader.images[ url+uid ].src = url;
    }
     
  });
  
}
ImageLoader.method( 'uid' , function(){
  var id = 0;
  return function() {
    return ( id += 1 );
  }
});
ImageLoader.method( 'replaceElement', function( event ) {
  
  var $ = jQuery,
         element = this,
         image = $( event.currentTarget );
         
  if( element.clearClasses ){
    element.target.attr('class','');
  }
  
  if( element.injectClasses !== '' ){
    image.attr('class', element.injectClasses );
  }
  
  if( !element.replaceChildren ) {
    element.target.html('<img src="'+image.attr('src')+'" alt="'+image.attr('alt')+'" class="'+image.attr('class')+'">');
  } else {
    element.target.replaceWith('<img src="'+image.attr('src')+'" alt="'+image.attr('alt')+'" class="'+image.attr('class')+'">');
  }
  
});;
/**
* Condense 0.1 - Condense and expand text heavy elements
*
* (c) 2008 Joseph Sillitoe
* Dual licensed under the MIT License (MIT-LICENSE) and GPL License,version 2 (GPL-LICENSE). 
*/
 
/*
* jQuery plugin
*
* usage:
*  
*   $(document).ready(function(){     
*     $('#example1').condense();
*   });
*
* Options:
*  condensedLength: Target length of condensed element. Default: 200  
*  minTrail: Minimun length of the trailing text. Default: 20
*  delim: Delimiter used for finding the break point. Default: " " - {space}
*  moreText: Text used for the more control. Default: [more]  
*  lessText: Text used for the less control. Default: [less]  
*  ellipsis: Text added to condensed element. Default:  ( ... )  
*  moreSpeed: Animation Speed for expanding. Default: "normal"  
*  lessSpeed: Animation Speed for condensing. Default: "normal"
*  easing: Easing algorith. Default: "linear"
*/

(function($) {

  // plugin definition
  $.fn.condense = function(options) {
    
    //$.metadata ? debug('metadata plugin detected') : debug('metadata plugin not present');//detect the metadata plugin?

    var opts = $.extend({}, $.fn.condense.defaults, options); // build main options before element iteration

    // iterate each matched element
    return this.each(function() {
	    $this = $(this);

      // support metadata plugin (v2.0)
	    var o = $.metadata ? $.extend({}, opts, $this.metadata()) : opts; // build element specific options
     
      //debug('Condensing ['+$this.text().length+']: '+$this.text());
      
      var clone = cloneCondensed($this,o);

      if (clone){ 
        // id attribute switch.  make sure that the visible elem keeps the original id (if set).
        $this.attr('id') ? $this.attr('id','condensed_'+$this.attr('id')) : false;

        var controlMore = " <span class='condense_control condense_control_more' style='cursor:pointer;'>"+o.moreText+"</span>";
        var controlLess = " <span class='condense_control condense_control_less' style='cursor:pointer;'>"+o.lessText+"</span>";
        clone.append(o.ellipsis + controlMore);
        $this.after(clone).hide().append(controlLess);

        $('.condense_control_more',clone).click(function(){
          //debug('moreControl clicked.');
          triggerExpand($(this),o)
        });

        $('.condense_control_less',$this).click(function(){
          //debug('lessControl clicked.');
          triggerCondense($(this),o)
        });
      }

	  });
  };

  function cloneCondensed(elem, opts){
    // Try to clone and condense the element.  if not possible because of the length/minTrail options, return false.
    // also, dont count tag declarations as part of the text length.
    // check the length of the text first, return false if too short.
    if ($.trim(elem.text()).length <= opts.condensedLength + opts.minTrail){
      //debug('element too short: skipping.');
      return false;
    } 

    var fullbody = $.trim(elem.html());
    var fulltext = $.trim(elem.text());
    var delim = opts.delim; 
    var clone = elem.clone();
    var delta = 0;

    do {
      // find the location of the next potential break-point.
      var loc = findDelimiterLocation(fullbody, opts.delim, (opts.condensedLength + delta));
      //set the html of the clone to the substring html of the original
      clone.html($.trim(fullbody.substring(0,(loc+1))));
      var cloneTextLength = clone.text().length;
      var cloneHtmlLength = clone.html().length;
      delta = clone.html().length - cloneTextLength; 
      //debug ("condensing... [html-length:"+cloneHtmlLength+" text-length:"+cloneTextLength+" delta: "+delta+" break-point: "+loc+"]");
    //is the length of the clone text long enough?
    }while(clone.text().length < opts.condensedLength )

    //  after skipping ahead to the delimiter, do we still have enough trailing text?
    if ((fulltext.length - cloneTextLength) < opts.minTrail){
      //debug('not enough trailing text: skipping.');
      return false;
    }

    //debug('clone condensed. [text-length:'+cloneTextLength+']');
    return clone;
  }


  function findDelimiterLocation(html, delim, startpos){
    // find the location inside the html of the delimiter, starting at the specified length.
    var foundDelim = false;
    var loc = startpos;    
    do {
      var loc = html.indexOf(delim, loc);
      if (loc < 0){
        //debug ("No delimiter found.");
        return html.length;
      } // if there is no delimiter found, just return the length of the entire html string.
      foundDelim = true;
      while (isInsideTag(html, loc)) {
        // if we are inside a tag, this delim doesn't count.  keep looking...      
        loc++;
        foundDelim = false;
      }
    }while(!foundDelim)
    //debug ("Delimiter found in html at: "+loc);
    return loc;
  }


  function isInsideTag(html, loc){
    return (html.indexOf('>',loc) < html.indexOf('<',loc));
  }


  function triggerCondense(control, opts){
    //debug('Condense Trigger: '+control.html());  
    var orig = control.parent(); // The original element will be the control's immediate parent.
    var condensed = orig.next(); // The condensed element will be the original immediate next sibling.    
    condensed.show();    
    var con_w  = condensed.width();
    var con_h = condensed.height();
    condensed.hide(); //briefly flashed the condensed element so we can get the target width/height
    var orig_w  = orig.width();
    var orig_h = orig.height();
    orig.animate({height:con_h, width:con_w, opacity: 1}, opts.lessSpeed, opts.easing,
      function(){
        orig.height(orig_h).width(orig_w).hide();
        condensed.show(); 
      });
  }


  function triggerExpand(control, opts){
    //debug('Expand Trigger: '+control.html());    
    var condensed = control.parent(); // The condensed element will be the control's immediate parent.
    var orig = condensed.prev(); // The original element will be the condensed immediate previous sibling.
    orig.show();
    var orig_w  = orig.width();
    var orig_h = orig.height();
    orig.width(condensed.width()+"px").height(condensed.height()+"px"); 
    condensed.hide();
    orig.animate({height:orig_h, width:orig_w, opacity: 1}, opts.moreSpeed, opts.easing);
    if(condensed.attr('id')){
      var idAttr = condensed.attr('id');
      condensed.attr('id','condensed_'+idAttr);
      orig.attr('id',idAttr);
    } 
  }


  /**
   * private function for debugging
   */
  function debug($obj) {if (window.console && window.console.log){window.console.log($obj);}};


  // plugin defaults
  $.fn.condense.defaults = {
    condensedLength: 200,  
    minTrail: 20,
    delim: " ",
    moreText: "[more]",  
    lessText: "[less]",  
    ellipsis: " ( ... )",  
    moreSpeed: "normal",  
    lessSpeed: "normal",
    easing: "linear"
  };

})(jQuery);
;
(function($){$.fn.jCarouselLite=function(o){o=$.extend({btnPrev:null,btnNext:null,btnGo:null,mouseWheel:false,auto:null,speed:200,easing:null,vertical:false,circular:true,visible:3,start:0,scroll:1,beforeStart:null,afterEnd:null},o||{});return this.each(function(){var b=false,animCss=o.vertical?"top":"left",sizeCss=o.vertical?"height":"width";var c=$(this),ul=$("ul",c),tLi=$("li",ul),tl=tLi.size(),v=o.visible;if(o.circular){ul.prepend(tLi.slice(tl-v-1+1).clone()).append(tLi.slice(0,v).clone());o.start+=v}var f=$("li",ul),itemLength=f.size(),curr=o.start;c.css("visibility","visible");f.css({overflow:"hidden",float:o.vertical?"none":"left"});ul.css({margin:"0",padding:"0",position:"relative","list-style-type":"none","z-index":"1"});c.css({overflow:"hidden",position:"relative","z-index":"2",left:"0px"});var g=o.vertical?height(f):width(f);var h=g*itemLength;var j=g*v;f.css({width:f.width(),height:f.height()});ul.css(sizeCss,h+"px").css(animCss,-(curr*g));c.css(sizeCss,j+"px");if(o.btnPrev)$(o.btnPrev).click(function(){return go(curr-o.scroll)});if(o.btnNext)$(o.btnNext).click(function(){return go(curr+o.scroll)});if(o.btnGo)$.each(o.btnGo,function(i,a){$(a).click(function(){return go(o.circular?o.visible+i:i)})});if(o.mouseWheel&&c.mousewheel)c.mousewheel(function(e,d){return d>0?go(curr-o.scroll):go(curr+o.scroll)});if(o.auto)setInterval(function(){go(curr+o.scroll)},o.auto+o.speed);function vis(){return f.slice(curr).slice(0,v)};function go(a){if(!b){if(o.beforeStart)o.beforeStart.call(this,vis());if(o.circular){if(a<=o.start-v-1){ul.css(animCss,-((itemLength-(v*2))*g)+"px");curr=a==o.start-v-1?itemLength-(v*2)-1:itemLength-(v*2)-o.scroll}else if(a>=itemLength-v+1){ul.css(animCss,-((v)*g)+"px");curr=a==itemLength-v+1?v+1:v+o.scroll}else curr=a}else{if(a<0||a>itemLength-v)return;else curr=a}b=true;ul.animate(animCss=="left"?{left:-(curr*g)}:{top:-(curr*g)},o.speed,o.easing,function(){if(o.afterEnd)o.afterEnd.call(this,vis());b=false});if(!o.circular){$(o.btnPrev+","+o.btnNext).removeClass("disabled");$((curr-o.scroll<0&&o.btnPrev)||(curr+o.scroll>itemLength-v&&o.btnNext)||[]).addClass("disabled")}}return false}})};function css(a,b){return parseInt($.css(a[0],b))||0};function width(a){return a[0].offsetWidth+css(a,'marginLeft')+css(a,'marginRight')};function height(a){return a[0].offsetHeight+css(a,'marginTop')+css(a,'marginBottom')}})(jQuery);;
// Chosen, a Select Box Enhancer for jQuery and Protoype
// by Patrick Filler for Harvest, http://getharvest.com
// 
// Version 0.9.4
// Full source at https://github.com/harvesthq/chosen
// Copyright (c) 2011 Harvest http://getharvest.com

// MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md
// This file is generated by `cake build`, do not edit it by hand.
(function() {
  /*
  Chosen source: generate output using 'cake build'
  Copyright (c) 2011 by Harvest
  */  var $, Chosen, get_side_border_padding, root;
  var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  root = this;
  $ = jQuery;
  $.fn.extend({
    chosen: function(options) {
      if ($.browser === "msie" && ($.browser.version === "6.0" || $.browser.version === "7.0")) {
        return this;
      }
      return $(this).each(function(input_field) {
        if (!($(this)).hasClass("chzn-done")) {
          return new Chosen(this, options);
        }
      });
    }
  });
  Chosen = (function() {
    function Chosen(form_field, options) {
      this.form_field = form_field;
      this.options = options != null ? options : {};
      this.set_default_values();
      this.form_field_jq = $(this.form_field);
      this.is_multiple = this.form_field.multiple;
      this.is_rtl = this.form_field_jq.hasClass("chzn-rtl");
      this.default_text_default = this.form_field.multiple ? "Select Some Options" : "Select an Option";
      this.set_up_html();
      this.register_observers();
      this.form_field_jq.addClass("chzn-done");
    }
    Chosen.prototype.set_default_values = function() {
      this.click_test_action = __bind(function(evt) {
        return this.test_active_click(evt);
      }, this);
      this.activate_action = __bind(function(evt) {
        return this.activate_field(evt);
      }, this);
      this.active_field = false;
      this.mouse_on_container = false;
      this.results_showing = false;
      this.result_highlighted = null;
      this.result_single_selected = null;
      this.allow_single_deselect = (this.options.allow_single_deselect != null) && this.form_field.options[0].text === "" ? this.options.allow_single_deselect : false;
      this.choices = 0;
      return this.results_none_found = this.options.no_results_text || "No results match";
    };
    Chosen.prototype.set_up_html = function() {
      var container_div, dd_top, dd_width, sf_width;
      this.container_id = this.form_field.id.length ? this.form_field.id.replace(/(:|\.)/g, '_') : this.generate_field_id();
      this.container_id += "_chzn";
      this.f_width = this.form_field_jq.outerWidth();
      this.default_text = this.form_field_jq.data('placeholder') ? this.form_field_jq.data('placeholder') : this.default_text_default;
      container_div = $("<div />", {
        id: this.container_id,
        "class": "chzn-container" + (this.is_rtl ? ' chzn-rtl' : ''),
        style: 'width: ' + this.f_width + 'px;'
      });
      if (this.is_multiple) {
        container_div.html('<ul class="chzn-choices"><li class="search-field"><input type="text" value="' + this.default_text + '" class="default" autocomplete="off" style="width:25px;" /></li></ul><div class="chzn-drop" style="left:-9000px;"><ul class="chzn-results"></ul></div>');
      } else {
        container_div.html('<a href="javascript:void(0)" class="chzn-single"><span>' + this.default_text + '</span><div><b></b></div></a><div class="chzn-drop" style="left:-9000px;"><div class="chzn-search"><input type="text" autocomplete="off" /></div><ul class="chzn-results"></ul></div>');
      }
      this.form_field_jq.hide().after(container_div);
      this.container = $('#' + this.container_id);
      this.container.addClass("chzn-container-" + (this.is_multiple ? "multi" : "single"));
      this.dropdown = this.container.find('div.chzn-drop').first();
      dd_top = this.container.height();
      dd_width = this.f_width - get_side_border_padding(this.dropdown);
      this.dropdown.css({
        "width": dd_width + "px",
        "top": dd_top + "px"
      });
      this.search_field = this.container.find('input').first();
      this.search_results = this.container.find('ul.chzn-results').first();
      this.search_field_scale();
      this.search_no_results = this.container.find('li.no-results').first();
      if (this.is_multiple) {
        this.search_choices = this.container.find('ul.chzn-choices').first();
        this.search_container = this.container.find('li.search-field').first();
      } else {
        this.search_container = this.container.find('div.chzn-search').first();
        this.selected_item = this.container.find('.chzn-single').first();
        sf_width = dd_width - get_side_border_padding(this.search_container) - get_side_border_padding(this.search_field);
        this.search_field.css({
          "width": sf_width + "px"
        });
      }
      this.results_build();
      return this.set_tab_index();
    };
    Chosen.prototype.register_observers = function() {
      this.container.mousedown(__bind(function(evt) {
        return this.container_mousedown(evt);
      }, this));
      this.container.mouseup(__bind(function(evt) {
        return this.container_mouseup(evt);
      }, this));
      this.container.mouseenter(__bind(function(evt) {
        return this.mouse_enter(evt);
      }, this));
      this.container.mouseleave(__bind(function(evt) {
        return this.mouse_leave(evt);
      }, this));
      this.search_results.mouseup(__bind(function(evt) {
        return this.search_results_mouseup(evt);
      }, this));
      this.search_results.mouseover(__bind(function(evt) {
        return this.search_results_mouseover(evt);
      }, this));
      this.search_results.mouseout(__bind(function(evt) {
        return this.search_results_mouseout(evt);
      }, this));
      this.form_field_jq.bind("liszt:updated", __bind(function(evt) {
        return this.results_update_field(evt);
      }, this));
      this.search_field.blur(__bind(function(evt) {
        return this.input_blur(evt);
      }, this));
      this.search_field.keyup(__bind(function(evt) {
        return this.keyup_checker(evt);
      }, this));
      this.search_field.keydown(__bind(function(evt) {
        return this.keydown_checker(evt);
      }, this));
      if (this.is_multiple) {
        this.search_choices.click(__bind(function(evt) {
          return this.choices_click(evt);
        }, this));
        return this.search_field.focus(__bind(function(evt) {
          return this.input_focus(evt);
        }, this));
      }
    };
    Chosen.prototype.search_field_disabled = function() {
      this.is_disabled = this.form_field_jq.attr('disabled');
      if (this.is_disabled) {
        this.container.addClass('chzn-disabled');
        this.search_field.attr('disabled', true);
        if (!this.is_multiple) {
          this.selected_item.unbind("focus", this.activate_action);
        }
        return this.close_field();
      } else {
        this.container.removeClass('chzn-disabled');
        this.search_field.attr('disabled', false);
        if (!this.is_multiple) {
          return this.selected_item.bind("focus", this.activate_action);
        }
      }
    };
    Chosen.prototype.container_mousedown = function(evt) {
      var target_node;
      if (!this.is_disabled) {
        target_node = evt != null ? evt.target.nodeName : null;
        if (evt && evt.type === "mousedown") {
          evt.stopPropagation();
        }
        if (!this.pending_destroy_click && target_node !== "ABBR") {
          if (!this.active_field) {
            if (this.is_multiple) {
              this.search_field.val("");
            }
            $(document).click(this.click_test_action);
            this.results_show();
          } else if (!this.is_multiple && evt && ($(evt.target) === this.selected_item || $(evt.target).parents("a.chzn-single").length)) {
            evt.preventDefault();
            this.results_toggle();
          }
          return this.activate_field();
        } else {
          return this.pending_destroy_click = false;
        }
      }
    };
    Chosen.prototype.container_mouseup = function(evt) {
      if (evt.target.nodeName === "ABBR") {
        return this.results_reset(evt);
      }
    };
    Chosen.prototype.mouse_enter = function() {
      return this.mouse_on_container = true;
    };
    Chosen.prototype.mouse_leave = function() {
      return this.mouse_on_container = false;
    };
    Chosen.prototype.input_focus = function(evt) {
      if (!this.active_field) {
        return setTimeout((__bind(function() {
          return this.container_mousedown();
        }, this)), 50);
      }
    };
    Chosen.prototype.input_blur = function(evt) {
      if (!this.mouse_on_container) {
        this.active_field = false;
        return setTimeout((__bind(function() {
          return this.blur_test();
        }, this)), 100);
      }
    };
    Chosen.prototype.blur_test = function(evt) {
      if (!this.active_field && this.container.hasClass("chzn-container-active")) {
        return this.close_field();
      }
    };
    Chosen.prototype.close_field = function() {
      $(document).unbind("click", this.click_test_action);
      if (!this.is_multiple) {
        this.selected_item.attr("tabindex", this.search_field.attr("tabindex"));
        this.search_field.attr("tabindex", -1);
      }
      this.active_field = false;
      this.results_hide();
      this.container.removeClass("chzn-container-active");
      this.winnow_results_clear();
      this.clear_backstroke();
      this.show_search_field_default();
      return this.search_field_scale();
    };
    Chosen.prototype.activate_field = function() {
      if (!this.is_multiple && !this.active_field) {
        this.search_field.attr("tabindex", this.selected_item.attr("tabindex"));
        this.selected_item.attr("tabindex", -1);
      }
      this.container.addClass("chzn-container-active");
      this.active_field = true;
      this.search_field.val(this.search_field.val());
      return this.search_field.focus();
    };
    Chosen.prototype.test_active_click = function(evt) {
      if ($(evt.target).parents('#' + this.container_id).length) {
        return this.active_field = true;
      } else {
        return this.close_field();
      }
    };
    Chosen.prototype.results_build = function() {
      var content, data, startTime, _i, _len, _ref;
      startTime = new Date();
      this.parsing = true;
      this.results_data = root.SelectParser.select_to_array(this.form_field);
      if (this.is_multiple && this.choices > 0) {
        this.search_choices.find("li.search-choice").remove();
        this.choices = 0;
      } else if (!this.is_multiple) {
        this.selected_item.find("span").text(this.default_text);
      }
      content = '';
      _ref = this.results_data;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        data = _ref[_i];
        if (data.group) {
          content += this.result_add_group(data);
        } else if (!data.empty) {
          content += this.result_add_option(data);
          if (data.selected && this.is_multiple) {
            this.choice_build(data);
          } else if (data.selected && !this.is_multiple) {
            this.selected_item.find("span").text(data.text);
            if (this.allow_single_deselect) {
              this.selected_item.find("span").first().after("<abbr></abbr>");
            }
          }
        }
      }
      this.search_field_disabled();
      this.show_search_field_default();
      this.search_field_scale();
      this.search_results.html(content);
      return this.parsing = false;
    };
    Chosen.prototype.result_add_group = function(group) {
      if (!group.disabled) {
        group.dom_id = this.container_id + "_g_" + group.array_index;
        return '<li id="' + group.dom_id + '" class="group-result">' + $("<div />").text(group.label).html() + '</li>';
      } else {
        return "";
      }
    };
    Chosen.prototype.result_add_option = function(option) {
      var classes;
      if (!option.disabled) {
        option.dom_id = this.container_id + "_o_" + option.array_index;
        classes = option.selected && this.is_multiple ? [] : ["active-result"];
        if (option.selected) {
          classes.push("result-selected");
        }
        if (option.group_array_index != null) {
          classes.push("group-option");
        }
        return '<li id="' + option.dom_id + '" class="' + classes.join(' ') + '">' + option.html + '</li>';
      } else {
        return "";
      }
    };
    Chosen.prototype.results_update_field = function() {
      this.result_clear_highlight();
      this.result_single_selected = null;
      return this.results_build();
    };
    Chosen.prototype.result_do_highlight = function(el) {
      var high_bottom, high_top, maxHeight, visible_bottom, visible_top;
      if (el.length) {
        this.result_clear_highlight();
        this.result_highlight = el;
        this.result_highlight.addClass("highlighted");
        maxHeight = parseInt(this.search_results.css("maxHeight"), 10);
        visible_top = this.search_results.scrollTop();
        visible_bottom = maxHeight + visible_top;
        high_top = this.result_highlight.position().top + this.search_results.scrollTop();
        high_bottom = high_top + this.result_highlight.outerHeight();
        if (high_bottom >= visible_bottom) {
          return this.search_results.scrollTop((high_bottom - maxHeight) > 0 ? high_bottom - maxHeight : 0);
        } else if (high_top < visible_top) {
          return this.search_results.scrollTop(high_top);
        }
      }
    };
    Chosen.prototype.result_clear_highlight = function() {
      if (this.result_highlight) {
        this.result_highlight.removeClass("highlighted");
      }
      return this.result_highlight = null;
    };
    Chosen.prototype.results_toggle = function() {
      if (this.results_showing) {
        return this.results_hide();
      } else {
        return this.results_show();
      }
    };
    Chosen.prototype.results_show = function() {
      var dd_top;
      if (!this.is_multiple) {
        this.selected_item.addClass("chzn-single-with-drop");
        if (this.result_single_selected) {
          this.result_do_highlight(this.result_single_selected);
        }
      }
      dd_top = this.is_multiple ? this.container.height() : this.container.height() - 1;
      this.dropdown.css({
        "top": dd_top + "px",
        "left": 0
      });
      this.results_showing = true;
      this.search_field.focus();
      this.search_field.val(this.search_field.val());
      return this.winnow_results();
    };
    Chosen.prototype.results_hide = function() {
      if (!this.is_multiple) {
        this.selected_item.removeClass("chzn-single-with-drop");
      }
      this.result_clear_highlight();
      this.dropdown.css({
        "left": "-9000px"
      });
      return this.results_showing = false;
    };
    Chosen.prototype.set_tab_index = function(el) {
      var ti;
      if (this.form_field_jq.attr("tabindex")) {
        ti = this.form_field_jq.attr("tabindex");
        this.form_field_jq.attr("tabindex", -1);
        if (this.is_multiple) {
          return this.search_field.attr("tabindex", ti);
        } else {
          this.selected_item.attr("tabindex", ti);
          return this.search_field.attr("tabindex", -1);
        }
      }
    };
    Chosen.prototype.show_search_field_default = function() {
      if (this.is_multiple && this.choices < 1 && !this.active_field) {
        this.search_field.val(this.default_text);
        return this.search_field.addClass("default");
      } else {
        this.search_field.val("");
        return this.search_field.removeClass("default");
      }
    };
    Chosen.prototype.search_results_mouseup = function(evt) {
      var target;
      target = $(evt.target).hasClass("active-result") ? $(evt.target) : $(evt.target).parents(".active-result").first();
      if (target.length) {
        this.result_highlight = target;
        return this.result_select(evt);
      }
    };
    Chosen.prototype.search_results_mouseover = function(evt) {
      var target;
      target = $(evt.target).hasClass("active-result") ? $(evt.target) : $(evt.target).parents(".active-result").first();
      if (target) {
        return this.result_do_highlight(target);
      }
    };
    Chosen.prototype.search_results_mouseout = function(evt) {
      if ($(evt.target).hasClass("active-result" || $(evt.target).parents('.active-result').first())) {
        return this.result_clear_highlight();
      }
    };
    Chosen.prototype.choices_click = function(evt) {
      evt.preventDefault();
      if (this.active_field && !($(evt.target).hasClass("search-choice" || $(evt.target).parents('.search-choice').first)) && !this.results_showing) {
        return this.results_show();
      }
    };
    Chosen.prototype.choice_build = function(item) {
      var choice_id, link;
      choice_id = this.container_id + "_c_" + item.array_index;
      this.choices += 1;
      this.search_container.before('<li class="search-choice" id="' + choice_id + '"><span>' + item.html + '</span><a href="javascript:void(0)" class="search-choice-close" rel="' + item.array_index + '"></a></li>');
      link = $('#' + choice_id).find("a").first();
      return link.click(__bind(function(evt) {
        return this.choice_destroy_link_click(evt);
      }, this));
    };
    Chosen.prototype.choice_destroy_link_click = function(evt) {
      evt.preventDefault();
      if (!this.is_disabled) {
        this.pending_destroy_click = true;
        return this.choice_destroy($(evt.target));
      } else {
        return evt.stopPropagation;
      }
    };
    Chosen.prototype.choice_destroy = function(link) {
      this.choices -= 1;
      this.show_search_field_default();
      if (this.is_multiple && this.choices > 0 && this.search_field.val().length < 1) {
        this.results_hide();
      }
      this.result_deselect(link.attr("rel"));
      return link.parents('li').first().remove();
    };
    Chosen.prototype.results_reset = function(evt) {
      this.form_field.options[0].selected = true;
      this.selected_item.find("span").text(this.default_text);
      this.show_search_field_default();
      $(evt.target).remove();
      this.form_field_jq.trigger("change");
      if (this.active_field) {
        return this.results_hide();
      }
    };
    Chosen.prototype.result_select = function(evt) {
      var high, high_id, item, position;
      if (this.result_highlight) {
        high = this.result_highlight;
        high_id = high.attr("id");
        this.result_clear_highlight();
        if (this.is_multiple) {
          this.result_deactivate(high);
        } else {
          this.search_results.find(".result-selected").removeClass("result-selected");
          this.result_single_selected = high;
        }
        high.addClass("result-selected");
        position = high_id.substr(high_id.lastIndexOf("_") + 1);
        item = this.results_data[position];
        item.selected = true;
        this.form_field.options[item.options_index].selected = true;
        if (this.is_multiple) {
          this.choice_build(item);
        } else {
          this.selected_item.find("span").first().text(item.text);
          if (this.allow_single_deselect) {
            this.selected_item.find("span").first().after("<abbr></abbr>");
          }
        }
        if (!(evt.metaKey && this.is_multiple)) {
          this.results_hide();
        }
        this.search_field.val("");
        this.form_field_jq.trigger("change");
        return this.search_field_scale();
      }
    };
    Chosen.prototype.result_activate = function(el) {
      return el.addClass("active-result");
    };
    Chosen.prototype.result_deactivate = function(el) {
      return el.removeClass("active-result");
    };
    Chosen.prototype.result_deselect = function(pos) {
      var result, result_data;
      result_data = this.results_data[pos];
      result_data.selected = false;
      this.form_field.options[result_data.options_index].selected = false;
      result = $("#" + this.container_id + "_o_" + pos);
      result.removeClass("result-selected").addClass("active-result").show();
      this.result_clear_highlight();
      this.winnow_results();
      this.form_field_jq.trigger("change");
      return this.search_field_scale();
    };
    Chosen.prototype.results_search = function(evt) {
      if (this.results_showing) {
        return this.winnow_results();
      } else {
        return this.results_show();
      }
    };
    Chosen.prototype.winnow_results = function() {
      var found, option, part, parts, regex, result_id, results, searchText, startTime, startpos, text, zregex, _i, _j, _len, _len2, _ref;
      startTime = new Date();
      this.no_results_clear();
      results = 0;
      searchText = this.search_field.val() === this.default_text ? "" : $('<div/>').text($.trim(this.search_field.val())).html();
      regex = new RegExp('^' + searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'i');
      zregex = new RegExp(searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'i');
      _ref = this.results_data;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        option = _ref[_i];
        if (!option.disabled && !option.empty) {
          if (option.group) {
            $('#' + option.dom_id).hide();
          } else if (!(this.is_multiple && option.selected)) {
            found = false;
            result_id = option.dom_id;
            if (regex.test(option.html)) {
              found = true;
              results += 1;
            } else if (option.html.indexOf(" ") >= 0 || option.html.indexOf("[") === 0) {
              parts = option.html.replace(/\[|\]/g, "").split(" ");
              if (parts.length) {
                for (_j = 0, _len2 = parts.length; _j < _len2; _j++) {
                  part = parts[_j];
                  if (regex.test(part)) {
                    found = true;
                    results += 1;
                  }
                }
              }
            }
            if (found) {
              if (searchText.length) {
                startpos = option.html.search(zregex);
                text = option.html.substr(0, startpos + searchText.length) + '</em>' + option.html.substr(startpos + searchText.length);
                text = text.substr(0, startpos) + '<em>' + text.substr(startpos);
              } else {
                text = option.html;
              }
              if ($("#" + result_id).html !== text) {
                $("#" + result_id).html(text);
              }
              this.result_activate($("#" + result_id));
              if (option.group_array_index != null) {
                $("#" + this.results_data[option.group_array_index].dom_id).show();
              }
            } else {
              if (this.result_highlight && result_id === this.result_highlight.attr('id')) {
                this.result_clear_highlight();
              }
              this.result_deactivate($("#" + result_id));
            }
          }
        }
      }
      if (results < 1 && searchText.length) {
        return this.no_results(searchText);
      } else {
        return this.winnow_results_set_highlight();
      }
    };
    Chosen.prototype.winnow_results_clear = function() {
      var li, lis, _i, _len, _results;
      this.search_field.val("");
      lis = this.search_results.find("li");
      _results = [];
      for (_i = 0, _len = lis.length; _i < _len; _i++) {
        li = lis[_i];
        li = $(li);
        _results.push(li.hasClass("group-result") ? li.show() : !this.is_multiple || !li.hasClass("result-selected") ? this.result_activate(li) : void 0);
      }
      return _results;
    };
    Chosen.prototype.winnow_results_set_highlight = function() {
      var do_high, selected_results;
      if (!this.result_highlight) {
        selected_results = !this.is_multiple ? this.search_results.find(".result-selected.active-result") : [];
        do_high = selected_results.length ? selected_results.first() : this.search_results.find(".active-result").first();
        if (do_high != null) {
          return this.result_do_highlight(do_high);
        }
      }
    };
    Chosen.prototype.no_results = function(terms) {
      var no_results_html;
      no_results_html = $('<li class="no-results">' + this.results_none_found + ' "<span></span>"</li>');
      no_results_html.find("span").first().html(terms);
      return this.search_results.append(no_results_html);
    };
    Chosen.prototype.no_results_clear = function() {
      return this.search_results.find(".no-results").remove();
    };
    Chosen.prototype.keydown_arrow = function() {
      var first_active, next_sib;
      if (!this.result_highlight) {
        first_active = this.search_results.find("li.active-result").first();
        if (first_active) {
          this.result_do_highlight($(first_active));
        }
      } else if (this.results_showing) {
        next_sib = this.result_highlight.nextAll("li.active-result").first();
        if (next_sib) {
          this.result_do_highlight(next_sib);
        }
      }
      if (!this.results_showing) {
        return this.results_show();
      }
    };
    Chosen.prototype.keyup_arrow = function() {
      var prev_sibs;
      if (!this.results_showing && !this.is_multiple) {
        return this.results_show();
      } else if (this.result_highlight) {
        prev_sibs = this.result_highlight.prevAll("li.active-result");
        if (prev_sibs.length) {
          return this.result_do_highlight(prev_sibs.first());
        } else {
          if (this.choices > 0) {
            this.results_hide();
          }
          return this.result_clear_highlight();
        }
      }
    };
    Chosen.prototype.keydown_backstroke = function() {
      if (this.pending_backstroke) {
        this.choice_destroy(this.pending_backstroke.find("a").first());
        return this.clear_backstroke();
      } else {
        this.pending_backstroke = this.search_container.siblings("li.search-choice").last();
        return this.pending_backstroke.addClass("search-choice-focus");
      }
    };
    Chosen.prototype.clear_backstroke = function() {
      if (this.pending_backstroke) {
        this.pending_backstroke.removeClass("search-choice-focus");
      }
      return this.pending_backstroke = null;
    };
    Chosen.prototype.keyup_checker = function(evt) {
      var stroke, _ref;
      stroke = (_ref = evt.which) != null ? _ref : evt.keyCode;
      this.search_field_scale();
      switch (stroke) {
        case 8:
          if (this.is_multiple && this.backstroke_length < 1 && this.choices > 0) {
            return this.keydown_backstroke();
          } else if (!this.pending_backstroke) {
            this.result_clear_highlight();
            return this.results_search();
          }
          break;
        case 13:
          evt.preventDefault();
          if (this.results_showing) {
            return this.result_select(evt);
          }
          break;
        case 27:
          if (this.results_showing) {
            return this.results_hide();
          }
          break;
        case 9:
        case 38:
        case 40:
        case 16:
        case 91:
        case 17:
          break;
        default:
          return this.results_search();
      }
    };
    Chosen.prototype.keydown_checker = function(evt) {
      var stroke, _ref;
      stroke = (_ref = evt.which) != null ? _ref : evt.keyCode;
      this.search_field_scale();
      if (stroke !== 8 && this.pending_backstroke) {
        this.clear_backstroke();
      }
      switch (stroke) {
        case 8:
          this.backstroke_length = this.search_field.val().length;
          break;
        case 9:
          this.mouse_on_container = false;
          break;
        case 13:
          evt.preventDefault();
          break;
        case 38:
          evt.preventDefault();
          this.keyup_arrow();
          break;
        case 40:
          this.keydown_arrow();
          break;
      }
    };
    Chosen.prototype.search_field_scale = function() {
      var dd_top, div, h, style, style_block, styles, w, _i, _len;
      if (this.is_multiple) {
        h = 0;
        w = 0;
        style_block = "position:absolute; left: -1000px; top: -1000px; display:none;";
        styles = ['font-size', 'font-style', 'font-weight', 'font-family', 'line-height', 'text-transform', 'letter-spacing'];
        for (_i = 0, _len = styles.length; _i < _len; _i++) {
          style = styles[_i];
          style_block += style + ":" + this.search_field.css(style) + ";";
        }
        div = $('<div />', {
          'style': style_block
        });
        div.text(this.search_field.val());
        $('body').append(div);
        w = div.width() + 25;
        div.remove();
        if (w > this.f_width - 10) {
          w = this.f_width - 10;
        }
        this.search_field.css({
          'width': w + 'px'
        });
        dd_top = this.container.height();
        return this.dropdown.css({
          "top": dd_top + "px"
        });
      }
    };
    Chosen.prototype.generate_field_id = function() {
      var new_id;
      new_id = this.generate_random_id();
      this.form_field.id = new_id;
      return new_id;
    };
    Chosen.prototype.generate_random_id = function() {
      var string;
      string = "sel" + this.generate_random_char() + this.generate_random_char() + this.generate_random_char();
      while ($("#" + string).length > 0) {
        string += this.generate_random_char();
      }
      return string;
    };
    Chosen.prototype.generate_random_char = function() {
      var chars, newchar, rand;
      chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
      rand = Math.floor(Math.random() * chars.length);
      return newchar = chars.substring(rand, rand + 1);
    };
    return Chosen;
  })();
  get_side_border_padding = function(elmt) {
    var side_border_padding;
    return side_border_padding = elmt.outerWidth() - elmt.width();
  };
  root.get_side_border_padding = get_side_border_padding;
}).call(this);
(function() {
  var SelectParser;
  SelectParser = (function() {
    function SelectParser() {
      this.options_index = 0;
      this.parsed = [];
    }
    SelectParser.prototype.add_node = function(child) {
      if (child.nodeName === "OPTGROUP") {
        return this.add_group(child);
      } else {
        return this.add_option(child);
      }
    };
    SelectParser.prototype.add_group = function(group) {
      var group_position, option, _i, _len, _ref, _results;
      group_position = this.parsed.length;
      this.parsed.push({
        array_index: group_position,
        group: true,
        label: group.label,
        children: 0,
        disabled: group.disabled
      });
      _ref = group.childNodes;
      _results = [];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        option = _ref[_i];
        _results.push(this.add_option(option, group_position, group.disabled));
      }
      return _results;
    };
    SelectParser.prototype.add_option = function(option, group_position, group_disabled) {
      if (option.nodeName === "OPTION") {
        if (option.text !== "") {
          if (group_position != null) {
            this.parsed[group_position].children += 1;
          }
          this.parsed.push({
            array_index: this.parsed.length,
            options_index: this.options_index,
            value: option.value,
            text: option.text,
            html: option.innerHTML,
            selected: option.selected,
            disabled: group_disabled === true ? group_disabled : option.disabled,
            group_array_index: group_position
          });
        } else {
          this.parsed.push({
            array_index: this.parsed.length,
            options_index: this.options_index,
            empty: true
          });
        }
        return this.options_index += 1;
      }
    };
    return SelectParser;
  })();
  SelectParser.select_to_array = function(select) {
    var child, parser, _i, _len, _ref;
    parser = new SelectParser();
    _ref = select.childNodes;
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      child = _ref[_i];
      parser.add_node(child);
    }
    return parser.parsed;
  };
  this.SelectParser = SelectParser;
}).call(this);;

// usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console) {
      arguments.callee = arguments.callee.caller;
      console.log( Array.prototype.slice.call(arguments) );
  }
};
// make it safe to use console.log always
(function(b){function c(){}for(var d="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","),a;a=d.pop();)b[a]=b[a]||c})(window.console=window.console||{});


// place any jQuery/helper plugins in here, instead of separate, slower script files.

(function($){
	$.fn.inlineHelp = function(){
		
		return this.each(function(){
			
			var $this = $(this);

			$this.parents('form').submit(function(){
				if ($this.val() == $this.attr("title")) {
					$this.val("");
				}
			});
			
			$(window).load(function () {	
				if($this.val() == $this.attr("title")){
					$this.addClass("inline-help");								
				}
			});

			$this.focus(function(){
				if($this.val() == $this.attr("title")){
					$this.val("");
					$this.removeClass("inline-help");
				}
			});

			$this.blur(function(){
				if($.trim($this.val()) == ""){
					$this.val($this.attr("title"));
					$this.addClass("inline-help");
				}
			});
			
			$this.trigger('blur');
			
		});
		
	}

	$(function(){
		$("input.inlinehelp-enabled").inlineHelp();
	});
	
})(jQuery);
;
/*
 * jQuery Easing v1.1 - http://gsgd.co.uk/sandbox/jquery.easing.php
 *
 * Uses the built in easing capabilities added in jQuery 1.1
 * to offer multiple easing options
 *
 * Copyright (c) 2007 George Smith
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */

jQuery.easing = {
	easein: function(x, t, b, c, d) {
		return c*(t/=d)*t + b; // in
	},
	easeinout: function(x, t, b, c, d) {
		if (t < d/2) return 2*c*t*t/(d*d) + b;
		var ts = t - d/2;
		return -2*c*ts*ts/(d*d) + 2*c*ts/d + c/2 + b;		
	},
	easeout: function(x, t, b, c, d) {
		return -c*t*t/(d*d) + 2*c*t/d + b;
	},
	expoin: function(x, t, b, c, d) {
		var flip = 1;
		if (c < 0) {
			flip *= -1;
			c *= -1;
		}
		return flip * (Math.exp(Math.log(c)/d * t)) + b;		
	},
	expoout: function(x, t, b, c, d) {
		var flip = 1;
		if (c < 0) {
			flip *= -1;
			c *= -1;
		}
		return flip * (-Math.exp(-Math.log(c)/d * (t-d)) + c + 1) + b;
	},
	expoinout: function(x, t, b, c, d) {
		var flip = 1;
		if (c < 0) {
			flip *= -1;
			c *= -1;
		}
		if (t < d/2) return flip * (Math.exp(Math.log(c/2)/(d/2) * t)) + b;
		return flip * (-Math.exp(-2*Math.log(c/2)/d * (t-d)) + c + 1) + b;
	},
	bouncein: function(x, t, b, c, d) {
		return c - jQuery.easing['bounceout'](x, d-t, 0, c, d) + b;
	},
	bounceout: function(x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	bounceinout: function(x, t, b, c, d) {
		if (t < d/2) return jQuery.easing['bouncein'] (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing['bounceout'] (x, t*2-d,0, c, d) * .5 + c*.5 + b;
	},
	elasin: function(x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	elasout: function(x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	elasinout: function(x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	backin: function(x, t, b, c, d) {
		var s=1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	backout: function(x, t, b, c, d) {
		var s=1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	backinout: function(x, t, b, c, d) {
		var s=1.70158;
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	linear: function(x, t, b, c, d) {
		return c*t/d + b; //linear
	}
};;
/**
 * LavaLamp - A menu plugin for jQuery with cool hover effects.
 * @requires jQuery v1.1.3.1 or above
 *
 * http://gmarwaha.com/blog/?p=7
 *
 * Copyright (c) 2007 Ganeshji Marwaha (gmarwaha.com)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * Version: 0.2.0
 * Requires Jquery 1.2.1 from version 0.2.0 onwards. 
 * For jquery 1.1.x, use version 0.1.0 of lavalamp
 */

/**
 * Creates a menu with an unordered list of menu-items. You can either use the CSS that comes with the plugin, or write your own styles 
 * to create a personalized effect
 *
 * The HTML markup used to build the menu can be as simple as...
 *
 *       <ul class="lavaLamp">
 *           <li><a href="#">Home</a></li>
 *           <li><a href="#">Plant a tree</a></li>
 *           <li><a href="#">Travel</a></li>
 *           <li><a href="#">Ride an elephant</a></li>
 *       </ul>
 *
 * Once you have included the style sheet that comes with the plugin, you will have to include 
 * a reference to jquery library, easing plugin(optional) and the LavaLamp(this) plugin.
 *
 * Use the following snippet to initialize the menu.
 *   $(function() { $(".lavaLamp").lavaLamp({ fx: "backout", speed: 700}) });
 *
 * Thats it. Now you should have a working lavalamp menu. 
 *
 * @param an options object - You can specify all the options shown below as an options object param.
 *
 * @option fx - default is "linear"
 * @example
 * $(".lavaLamp").lavaLamp({ fx: "backout" });
 * @desc Creates a menu with "backout" easing effect. You need to include the easing plugin for this to work.
 *
 * @option speed - default is 500 ms
 * @example
 * $(".lavaLamp").lavaLamp({ speed: 500 });
 * @desc Creates a menu with an animation speed of 500 ms.
 *
 * @option click - no defaults
 * @example
 * $(".lavaLamp").lavaLamp({ click: function(event, menuItem) { return false; } });
 * @desc You can supply a callback to be executed when the menu item is clicked. 
 * The event object and the menu-item that was clicked will be passed in as arguments.
 */
(function($) {
$.fn.lavaLamp = function(o) {
    o = $.extend({ fx: "linear", speed: 500, click: function(){} }, o || {});

    return this.each(function() {
        var me = $(this), noop = function(){},
            $back = $('<li class="back"><div class="left"></div></li>').appendTo(me),
            $li = $("li", this), curr = $("li.current", this)[0] || $($li[0]).addClass("current")[0];

        $li.not(".back").hover(function() {
            move(this);
        }, noop);

        $(this).hover(noop, function() {
            move(curr);
        });

        $li.click(function(e) {
            setCurr(this);
            return o.click.apply(this, [e, this]);
        });

        setCurr(curr);

        function setCurr(el) {
            $back.css({ "left": el.offsetLeft+"px", "width": el.offsetWidth+"px" });
            curr = el;
        };

        function move(el) {
            $back.each(function() {
                $(this).dequeue(); }
            ).animate({
                width: el.offsetWidth,
                left: el.offsetLeft
            }, o.speed, o.fx);
        };

    });
};
})(jQuery);
;
/* Reprend control des element caché avec javascript */(function ($) {

  $(document).ready(function() {
    $('.hidden-ifjs, .casper-ifjs').removeClass('hidden-ifjs casper-ifjs').hide();
  });
  
}(jQuery));

/* Main Menu pulldowns */(function ($) {

  $(document).ready(function() {
    
    if( $('.activate-pulldown-emissions a').length > 0 ) {
      if( window.PulldownMenu ){
        new PulldownMenu({
          menuElement: $('.activate-pulldown-emissions a'),
          pulldownElement: $('.pulldown-emissions'),
          pulldownCursorElement: $('.pulldown-emissions .triangle'),
          pulldownCursorLeftAdjustment: -17,
          pulldownTopPositionAdjustment: 2,
          openCallback: function() {
            new ImageLoader({
              target: '.pulldown-emissions .emission-en-vedette .image',
              urlAttribute: 'data-tva-image',
              injectClasses: 'image',
              clearClasses: true
            });
          },
          timeout: 200
        });
      }
    }
    
    if( $('.activate-pulldown-cinema a').length > 0 ) {
      if( window.PulldownMenu ){
        new PulldownMenu({
          menuElement: $('.activate-pulldown-cinema a'),
          pulldownCursorElement: $('.pulldown-cinema .triangle'),
          pulldownCursorLeftAdjustment: -17,
          pulldownElement: $('.pulldown-cinema'),
          pulldownTopPositionAdjustment: 2,
          openCallback: function() {
            new ImageLoader({
              target: '.pulldown-cinema .emission-en-vedette .image',
              urlAttribute: 'data-tva-image',
              injectClasses: 'image',
              clearClasses: true
            });
          },
          timeout: 200
        });
      }
    }
  
  });
  
}(jQuery));

/* Injecte des elements uniquement pour le visuel */(function ($) {

  $(document).ready(function() {
    /* Relief pour le footer */
    $('.main .alignement').before('<div class="ir relief">&nbsp;</div>');
  });
  
}(jQuery));


/* Bouton Connexion dans la barre TVA */(function ($) {

  $(document).ready(function() {

    if( Drupal.settings.login !== undefined ){
      
      if(Drupal.settings.login.userLoginUrl !== undefined){
        
        $.ajax({
          url: Drupal.settings.login.userLoginUrl,
          error:function(msg){
             //log( "Error !: " + msg );
           },
          success:function(request){
            //affiche le contenu du fichier dans le conteneur dédié
            var connexion = {};
            connexion.status = $(request).data('tva-is-user-logged-in');
            connexion.userName = $(request).data('tva-username');
            //log(connexion);
            //log(connexion.userName);
            
            $('#barre_tva').addClass('interne');
            $('#barre_tva dd.sans-connexion').remove();
            
            if(connexion.status === 'logged in'){ 
              $('#barre_tva dd.last').after('<dd class="connexion logged"><a class="item" href="/utilisateur/'+connexion.userName+'">mon profil</a></dd>');
              $('#barre_tva dd.connexion a.item').after('<div class="dropdown">'+
                '<ul>'+
                '<li class="first"><a class="sub-item" href="/utilisateur/'+connexion.userName+'/modifier">Modifier mon profil</a></li>'+
                '<li><a class="sub-item" href="/utilisateur/deconnexion">Déconnecter</a></li>'+
                '</ul>'+
                '</div>');
                $('#block-boxes-box-entrez-communaute').css({visibility: 'hidden', height: '0'});
            }else{
              $('#barre_tva dd.last').after('<dd class="connexion"><a class="item" href="/utilisateur/connexion">Connexion</a></dd>');
              $('#block-boxes-box-entrez-communaute').css({visibility: 'visible', height: 'auto'});
            }

          }
        });
        
      }
    }

    /* Dropdown de la barre TVA */
    
    $('#barre_tva dd').live("mouseover", function(){
      $(this).addClass('hover');
      $(this).children('.dropdown').show();
    });
    
    $('#barre_tva dd').live("mouseout", function(){
      $(this).removeClass('hover');
      $(this).children('.dropdown').hide();
    });
  

  });
  
}(jQuery));



;
// Li les variable dans HEADER puis retourne le tout dans un tableau respectif
(function ($) {
$(document).ready(function() {
   $.extend({
    getUrlVars: function(){
      var vars = [], hash;
      var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
      for(var i = 0; i < hashes.length; i++)
      {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
      }
      return vars;
    },
    getUrlVar: function(name){
      return $.getUrlVars()[name];
    }
  });
  
  
});
}(jQuery));

/* Pour les liens externes - rel="external" */(function ($) {
  $(document).ready(function() {
   $("a[href][rel='external']").click(function(){
      window.open(this.href);
      return false;
    });
  });
}(jQuery));

/* Fontion pour vérifier si un élément existe dans le dom */(function ($) {

  $(document).ready(function() {
    jQuery.fn.exists = function(){return this.length>0;}
  });

}(jQuery));


/* Functionalite "Lire plus" */(function ($) {

  $(document).ready(function() {
    if( $('.lire-plus').length > 0 ) {
      $('.lire-plus').show().condense({
        condensedLength: 400,  
        minTrail: 100,
        delim: " ",
        moreText: '<span style="color:#1D80C3;">Lire plus</span>',  
        lessText: '<span style="color:#1D80C3;">Réduire</span>',  
        ellipsis: "…",  
        moreSpeed: "fast",  
        lessSpeed: "fast",
        easing: "linear"
      });
    }    
  });
  
}(jQuery));

/* Check Safari */(function ($) {

  $(document).ready(function() {
    
    var ua = $.browser;
    if ( ua.safari) {
      $('section.communaute h1.titre').addClass('font-petite');
    }
  });
  
}(jQuery));

/* En Ondes */(function ($) {
  
  var positionInitiale = 0;
  var deplacementPossible = 0;
  var direction = undefined;
    
  positionneListeEnOnde = function() {
    var listeEnOnde = $('#enOnde #menuEnOnde .liste');
    var positionActuelle = listeEnOnde.position();
    var limiteDroite = positionInitiale - deplacementPossible;
    
    if( direction == 'suivant' ){
      var newPosition = parseInt(positionActuelle.left) - 5;
      if( newPosition > limiteDroite ) {
        listeEnOnde.css({left: newPosition});
      }
      else{
        listeEnOnde.css({left: limiteDroite});
      }
    }
    if( direction == 'precedent' ){
      var newPosition = parseInt(positionActuelle.left) + 5;
      if( newPosition < positionInitiale ){
        listeEnOnde.css({left: newPosition});
      }
      else{
        listeEnOnde.css({left: positionInitiale});
      }
    }
  }
  
  $(document).ready(function() {
    /* Les incontournables */
    if( $('.tva-pas-incontournable').length > 0 ) {
          $('#incontournables').hide();
    }
  });

  $(document).ready(function() {
    var largeurVisible = $('#menuEnOnde').width();
    var listeEnOnde = $('#enOnde #menuEnOnde .liste');
    var navBouton = $('#enOnde .navBouton');
    var intervalListeEnOnde = undefined;
    var longueurListeEnOnde = 0;
    var contrainteEnLargeur = 0;
    
    /*
     * Calcule la longueur totale réelle de la navigation une fois toutes les émissions générées
     */
    $('#enOnde #menuEnOnde .liste .uneEmission').each( function() {
      var uneEmission = $(this);
      longueurListeEnOnde += uneEmission.width() + 9 /*border*/ ;
    });

    /* 
     * Créé l'élément qui servira de contrainte au 'Drag and drop' et redimensionne la liste `la bonne taille;
     */
    longueurListeEnOnde += parseInt( listeEnOnde.css('paddingRight') );
    longueurListeEnOnde += parseInt( listeEnOnde.css('paddingLeft') );
    
    deplacementPossible = longueurListeEnOnde - largeurVisible;
    contrainteEnLargeur = (deplacementPossible * 2) + largeurVisible + parseInt( listeEnOnde.css('paddingLeft') ) + parseInt( listeEnOnde.css('paddingRight') );
    positionInitiale = deplacementPossible;
    listeEnOnde.css({
      width: longueurListeEnOnde,
      left: positionInitiale
    });
    
    listeEnOnde.wrap('<div id="boiteDeDrag" />');
    $('#boiteDeDrag').css({
      position: 'relative',
      width: contrainteEnLargeur,
      height: 44,
      top: 0,
      left: -deplacementPossible
    });
    
    navBouton.click( function(){
      return false;
    });
    
    navBouton.mousedown( function(){
      navigation = $(this).attr('id');
      
      if( navigation == 'navSuivant' ) {
        direction ='suivant';
        clearInterval( intervalListeEnOnde );
        positionneListeEnOnde();
        intervalListeEnOnde = setInterval( 'positionneListeEnOnde()', 10 );
      }
      else if( navigation == 'navPrecedent' ) {
        direction ='precedent';
        clearInterval( intervalListeEnOnde );
        positionneListeEnOnde();
        intervalListeEnOnde = setInterval( 'positionneListeEnOnde()', 10 );
      }
      return false;
    });
  
    navBouton.mouseup( function(){
      if( intervalListeEnOnde != undefined ){
        clearInterval( intervalListeEnOnde );
        intervalListeEnOnde = undefined;
        direction = undefined;
      }
      return false;
    });
    
    navBouton.mouseleave( function (){
      navBouton.mouseup();
      return false;
    });
    
    navBouton.mouseout( function (){
      navBouton.mouseup();
      return false;
    });
    
    if( $('#enOnde #menuEnOnde').length > 0 ) {
      $('#enOnde #menuEnOnde .liste').draggable( {
        axis: 'x',
        containment: '#boiteDeDrag'
      });
    }

    
  });
}(jQuery));

/* Overlay pour les vidéos */(function ($) {
  $(document).ready(function() {
    
    /*Accueil*/
    $('.uneEmission .imageVideo').after('<span class="ir imageVideoOverlay">Vidéo</span>');
    /* Carousels de vidéos*/
    $('#emissionVideos  .imageVideo').after('<span class="ir imageVideoOverlay">Vidéo</span>');
    /* Thumbs des web séries*/
    $('.web-series-fiche .listeThumb .image').after('<span class="ir imageVideoOverlay">Vidéo</span>');
    $('.web-series article .capsule .image').after('<span class="ir imageVideoOverlay">Vidéo</span>');
    
  });
}(jQuery));

/* Onglets et Carouselles */(function ($) {
  // garde une liste des carousel activés sur la page
  var startedCarousel = new Array();

  $(document).ready( function() {
    
    $('#enVedette .onglets .menuLiens').click( function(){
      var lien = $(this);
      
      $('#enVedette .onglets .active').removeClass('active');
      $('#enVedette .article').hide();
      lien.parent().addClass('active');
      $( lien.attr('href') ).show();
      
      // Est-ce que le carousel est déjà activé?
      // Les carousels caché dans les onglets doivent être activé lors de leur premier affichage
      // jCarousel ne pouvant pas déterminer la dimension du carousel si les élément sont cachés.
      if( startedCarousel[lien.attr('href')] == undefined ) {
        if( $(lien.attr('href')+" .carousel li").length > 0 ) {
          startedCarousel[lien.attr('href')] = $(lien.attr('href')+" .carousel").jCarouselLite({
            btnNext: lien.attr('href')+" .itemSuivant a",
            btnPrev: lien.attr('href')+" .itemPrecedent a"
          }); 
        }
      }
      return false;
    });
    
  });

  $(document).ready(function() {
    $('#enVedette .carousel , #emissionVideos .carousel, #emissionPhotos .carousel, #cinemaAVoir .carousel, #carouselAcc .carousel, #carouselConcours .carousel, #carouselSection .carousel').each( function(){
      $(this).after('<span class="itemNavigationCarousel itemPrecedent"><a class="ir" href="#">Precedent</a></span><span class="itemNavigationCarousel itemSuivant"><a class="ir" href="#">Suivant</a></span>');
    });
    
    /**** Carousel Les plus populaires ****/
    $('#lesPlusPopulaires').show();
    if( $('#lesPlusPopulaires .carousel li').length > 1 ) {
      startedCarousel['#lesPlusPopulaires'] = $('#lesPlusPopulaires .carousel').jCarouselLite({
        btnNext: "#lesPlusPopulaires .itemSuivant a",
        btnPrev: "#lesPlusPopulaires .itemPrecedent a"
      });
    }
    
    
    
    
    /**** Carousel Videos - Émission ****/

   
    if( Drupal.settings.carouselVideos !== undefined && Drupal.settings.carouselVideos.carouselPictureNumber !== undefined ){
      qtThumbs = 3;
      carouselPictureNumber = Drupal.settings.carouselVideos.carouselPictureNumber;
      if(carouselPictureNumber < 3){
        qtThumbs = carouselPictureNumber;
      }
      $('#emissionVideos').show();
    if( qtThumbs >= 0 ) {
      startedCarousel['#emissionVideos'] = $("#emissionVideos .carousel").jCarouselLite({
        btnNext: "#emissionVideos .itemSuivant",
        btnPrev: "#emissionVideos .itemPrecedent",
        visible: qtThumbs
      });
    }
    if( carouselPictureNumber <= 3 ) {
      $("#emissionVideos .itemSuivant").hide();
      $("#emissionVideos .itemPrecedent").hide();
    } else {
      $('#emissionVideos .itemSuivant').bind('click', function() {
        tracking_galleryVideo('Next');
      });    
      $('#emissionVideos .itemPrecedent').bind('click', function() {
        tracking_galleryVideo('Previous');
      });          
    }
    }else {
      $('#emissionVideos').hide();
    }    
    
    
    
    /**** Carousel Photos - Émission ****/
    
    if( Drupal.settings.carouselPhotos !== undefined && Drupal.settings.carouselPhotos.carouselPictureNumber !== undefined ){
      qtThumbs = 3;
      carouselPictureNumber = Drupal.settings.carouselPhotos.carouselPictureNumber;
      if(carouselPictureNumber < 3){
        qtThumbs = carouselPictureNumber;
      }
      $('#emissionPhotos').show();
    if( qtThumbs >= 0 ) {
      startedCarousel['#emissionPhotos'] = $("#emissionPhotos .carousel").jCarouselLite({
        btnNext: "#emissionPhotos .itemSuivant",
        btnPrev: "#emissionPhotos .itemPrecedent",
        visible: qtThumbs
      });
    }
    if( carouselPictureNumber <= 3 ) {
      $("#emissionPhotos .itemSuivant").hide();
      $("#emissionPhotos .itemPrecedent").hide();
    } else {
      $('#emissionPhotos .itemSuivant').bind('click', function() {
        tracking_galleryPhoto('Next');
      });    
      $('#emissionPhotos .itemPrecedent').bind('click', function() {
        tracking_galleryPhoto('Previous');
      });          
    }
    }else {
      $('#emissionPhotos').hide();
    }
    

    
   /**** Carousel Vidéos dans l'Onglet Vidéos - Émission ****/
    
    if( Drupal.settings.carouselAVoir !== undefined && Drupal.settings.carouselAVoir.carouselPictureNumber !== undefined ){
      qtThumbs = 3;
      carouselPictureNumber = Drupal.settings.carouselAVoir.carouselPictureNumber;
      if(carouselPictureNumber < 3){
        qtThumbs = carouselPictureNumber;
      }
      $('#cinemaAVoir').show();
    if( qtThumbs >= 0 ) {
      startedCarousel['#cinemaAVoir'] = $("#emissionVideos .carousel").jCarouselLite({
        btnNext: "#cinemaAVoir .itemSuivant",
        btnPrev: "#cinemaAVoir .itemPrecedent",
        visible: qtThumbs
      });
    }
    if( carouselPictureNumber <= 3 ) {
      $("#cinemaAVoir .itemSuivant").hide();
      $("#cinemaAVoir .itemPrecedent").hide();
    } else {
      $('#cinemaAVoir .itemSuivant').bind('click', function() {
        tracking_galleryVideo('Next');
      });    
      $('#cinemaAVoir .itemPrecedent').bind('click', function() {
        tracking_galleryVideo('Previous');
      });          
    }
    }else {
      $('#cinemaAVoir').hide();
    }    
        
    
    /*** Ajout de la navigation dans les caroussels les section d'accueil ***/
    $('div.boxDegrade article ul').each(function(){
      var qtLis = $(this).data("qt-li") - 1;
      var lis = ''; 
      for (i=1; i<=qtLis; i++){
        lis = lis + '<li><a href="#" class="points">&nbsp;</a></li>';  
      }
      $(this).parent().parent().next().append('<ul>'+
        '<li class="previous" onClick="javascript:tracking_carousselAccueil(\''+ $(this).data('tva-tracking') + '\',\'previous\',\'flecheGauche\');\"><a>&nbsp;</a></li>'+
        '<li><a href="#" class="points actif">&nbsp;</a></li>'+
        lis+
        '<li class="next" onClick="javascript:tracking_carousselAccueil(\''+ $(this).data('tva-tracking') + '\',\'next\',\'flecheDroite\');\"><a>&nbsp;</a></li>'+
        '</ul>');
    });
      
    
    /*** Le controle des boutons dans les carousels les section d'accueil et galerie photo des App Mobiles ***/
    function checkButton(button){
      if (button.hasClass('points')){
       button.parent('li').parent('ul').find('.points').removeClass('actif');
       button.addClass('actif'); 
      }
    }
    
    /*** Le controle des flèches dans les carousels les section d'accueil et galerie photo des App Mobiles ***/
    function checkDirection(button){

      var CarouselContainer = button.parent('li').parent('ul').parent('nav').parent('section');
      var findNav = CarouselContainer.find('nav');
      var indice = findNav.data("indice-nav");
      var carouselNumberItems = CarouselContainer.find('.points').length;
      
      if (button.parent().hasClass('next')){
        if(indice == carouselNumberItems){
          indice = 1;
          CarouselContainer.find('.points').removeClass('actif');
          findNav.data("indice-nav", 1);
          CarouselContainer.find('.points:eq(0)').addClass('actif');
        }else{
          indice++;
          CarouselContainer.find('.points').removeClass('actif');
          var newActif = indice-1;
          findNav.data("indice-nav", indice);
          CarouselContainer.find('.points:eq('+newActif+')').addClass('actif');
        }
      }else if(button.parent().hasClass('previous')){
        if(indice == 1){
          var newActif = carouselNumberItems - 1;
          findNav.data("indice-nav", carouselNumberItems);
          CarouselContainer.find('.points').removeClass('actif');
          CarouselContainer.find('.points:eq('+newActif+')').addClass('actif');
        }else{
          indice--;
          CarouselContainer.find('.points').removeClass('actif');
          var newActif = indice-1;
          findNav.data("indice-nav", indice);
          CarouselContainer.find('.points:eq('+newActif+')').addClass('actif');
        } 
      }
    }
    
    /*** Ajout de la navegation dans les carousels les section d'accueil ***/
    /*
    $('#en_vedette .en-vedette-content').each(function(){
      var qtLis = $(this).find('ul').data("qt-li") - 1;
      var lis = '';
      for (i=1; i<=qtLis; i++){
        lis = lis + '<li><a href="#" class="points">&nbsp;</a></li>';  
      }
      $('#en_vedette nav').append('<ul>'+
        '<li class="previous"><a>&nbsp;</a></li>'+
        '<li><a href="#" class="points actif">&nbsp;</a></li>'+
        lis+
        '<li class="next"><a href="#">&nbsp;</a></li>'+
        '</ul>');
    });
    */
    
    /**** Carousel - En vedette ****/

    if( $('#en_vedette').exists() && !($('#en_vedette ul').data("qt-li")-1) == 0) {
      var qtLis = $('#en_vedette ul').data("qt-li")-1;
      var lis = 0;
      function fadeOut() {
         $('#en_vedette ul li.current').fadeOut('slow', function() {
           if(lis != qtLis){
             lis++;
           } else {
             lis = 0;
           }
            $(this).removeClass('current');
           fadeIn();    
        });
      };
      function fadeIn() {
         $('#en_vedette ul li').eq(lis).fadeIn('slow', function() {
          $(this).addClass('current');
          $(this).parent().siblings('p.liens').children('a.gris').attr('href',$(this).children('a').attr('href'));
          setTimeout( function(){
            fadeOut();
          }, 5000);  
        });
      };      
      setTimeout( function(){
        fadeOut();
      }, 5000);   
    }

   
    /**** Caroussel Nos Artistes ****/
    if( $('#nosArtistes .carousel li').length > 0 ) {
      startedCarousel['#nosArtistes'] = $("#nosArtistes .carousel").jCarouselLite({
        btnNext: "#nosArtistes .next",
        btnPrev: "#nosArtistes .previous",
        visible: 1,
        btnGo:
          ["#nosArtistes nav ul a.points:eq(0)", "#nosArtistes nav ul a.points:eq(1)",
          "#nosArtistes nav ul a.points:eq(2)", "#nosArtistes nav ul a.points:eq(3)"]
      });
    }
    
    $("#nosArtistes nav ul a").click(function() {
      checkButton($(this));  
      checkDirection($(this));
    });
    
    /**** Carousel Vous l'avez manqué? ****/
    if( $('#avezManquez .carousel li').length > 0 ) {
      startedCarousel['#avezManquez'] = $("#avezManquez .carousel").jCarouselLite({
        btnNext: "#avezManquez .next",
        btnPrev: "#avezManquez .previous",
        visible: 1,
        start: 0,
        btnGo:
          ["#avezManquez nav ul a.points:eq(0)", "#avezManquez nav ul a.points:eq(1)",
          "#avezManquez nav ul a.points:eq(2)", "#avezManquez nav ul a.points:eq(3)"]
      });
    }
    
    $("#avezManquez nav ul a").click(function() {
      checkButton($(this));  
      checkDirection($(this));
    });
    
    /**** Caroussel Les actualités du groupe TVA ****/
    if( $('#actualites .carousel li').length > 0 ) {
      startedCarousel['#actualites'] = $("#actualites .carousel").jCarouselLite({
        btnNext: "#actualites .next",
        btnPrev: "#actualites .previous",
        visible: 1,
        btnGo:
          ["#actualites nav ul a.points:eq(0)", "#actualites nav ul a.points:eq(1)",
          "#actualites nav ul a.points:eq(2)", "#actualites nav ul a.points:eq(3)"]
      });
    }
    
    
    $("#actualites nav ul a").click(function() {
      checkButton($(this));  
      checkDirection($(this));
    });


    /*** mainCarousel (carousel d'images et de thumbs) ***/
     var carouselTimer = 5000; //5s
     var carousel = new Array();
    
    /*** prend les carousels avec la classe mainCaroussel et définis les valeurs nécessaire à l'exécution du carousel ***/
    $(".mainCarousel").each(function (i) {
      var id = $(this).attr('id');
      carousel[id] = new Array();
      
      carousel[id]['position'] = 0; // position de départ
      carousel[id]['trigger'] = $('#'+id+' span.itemNavigationCarousel'); // items de navigation (flèches)
      carousel[id]['timer'] = setInterval("jQuery('#"+id+" .itemSuivant').click();", carouselTimer); // interval pour le carousel
      carousel[id]['slider'] = $('#'+id).parents('section.mainSlider').attr('id'); // contener des photos
      carousel[id]['positionMax'] = ($('#'+carousel[id]['slider']+' article.slide').length-1); // nombre de slides
      
      var qtThumbs = 5;
      
      if( Drupal.settings.carouselEnVedette !== undefined && Drupal.settings.carouselEnVedette.carouselPictureNumber !== undefined ){
        var carouselPictureNumber = Drupal.settings.carouselEnVedette.carouselPictureNumber;
        if(carouselPictureNumber < 5){
          qtThumbs = carouselPictureNumber;
        }
      }
      startedCarousel[id] = $("#"+id+" .carousel").jCarouselLite({
          btnNext: "#"+id+" .itemSuivant",
          btnPrev: "#"+id+" .itemPrecedent",
          visible: qtThumbs,
          speed: 500
      });
     });    
     
    /*** remplace la fonction d'autoroll de jcarousellite par une fonction custom ***/ 
    $(".mainCarousel .itemSuivant, .mainCarousel .itemPrecedent, .mainCarousel a[rel]").click(function() {
        animCarousel($(this));
        clearInterval(carousel[id]['timer']);
        carousel[id]['timer'] = setInterval("jQuery('#"+id+" .itemSuivant').click();", carouselTimer);
    });    
    
    /*** action sur le click suivant ***/
    $('.mainCarousel .itemSuivant').bind('click', function() {  
       animCarousel($(this));
       if (carousel[id]['position'] < carousel[id]['positionMax']) {
          carousel[id]['position']++;
       } else {
          carousel[id]['position'] = 0;
       };          
       mainSlider(carousel[id]['position'], id);     
    });
    
    /*** action sur le click précédant ***/
    $('.mainCarousel .itemPrecedent').bind('click', function() {
       animCarousel($(this));
       if (carousel[id]['position'] > 0) {
          carousel[id]['position']--;
        } else {
          carousel[id]['position'] = carousel[id]['positionMax'];
        };        
        mainSlider(carousel[id]['position'], id);      
    });
    
    /*** click sur les thumbnails ***/
    $(".mainCarousel a[rel]").click(function () {
      animCarousel($(this));
      carousel[id]['position'] = $(this).attr('rel');
      mainSlider(carousel[id]['position'], id);
    });
    
    /*** enlève l'option de doubleclick et défini le carousel qui est en action ***/
    function animCarousel(data) {
       id = data.parents('section').attr('id');
       carousel[id]['trigger'].css({visibility: 'hidden'});
       return id;
    };
    
    /*** vérifie ie or not, animation ***/
    var msie = $.browser.msie;
    var msieVersion = $.browser.version;
    function mainSlider(data, id) {     
      $('#'+id+' img').removeClass('active');
      $('#'+id+' a[rel="'+data+'"] img').addClass('active');
     
        $('#'+carousel[id]['slider']+' article.slide').stop(true, true).fadeOut(500);
        $('#'+carousel[id]['slider']+' article.slide').eq(data).stop(true, true).fadeIn(1000, function() {
          carousel[id]['trigger'].css({visibility: 'visible'});
        });       
      
    };
    
  });      
}(jQuery));

/* Ajustement fine des espace dans la navigation principale *//*(function ($) {
    
  $(document).ready(function() {
    var espaceTotale = 958;
    var espaceTexte = 0;
    var marge = 0;
    var liens = $('#menuPrincipal .interne');
    var readyID = undefined;
    
    var calculeMarges = function( liens, espaceTotale, espaceTexte ) {
      // Calcule espace prise par le texte
      liens.each( function() {
        espaceTexte += parseInt( $(this).width() );
      });
      
      marge = Math.floor( (espaceTotale - espaceTexte) / (liens.length - 1) );
      $('#menuPrincipal .interne:not(#menuPrincipal .interne:last)').css('paddingRight', marge );
    }

    var checkReadyState = function() {
      if( document.readyState === 'complete' ) {
        clearTimeout( readyID );
        calculeMarges(liens, espaceTotale, espaceTexte );
      } 
    }
    
    //readyID = setInterval( checkReadyState , 10 ); 

  });
  
}(jQuery));*/

/* boite de navigation */(function ($) {
  $(document).ready(function() {
    
    $('.llCd a').bind('click', function() {
      var data = $(this).parents('div.wrapperllCd').attr('id');
      $('#'+data+' .llCd a').removeClass('actif');
      $(this).addClass('actif');
      $('#'+data+' div.llContainer').hide();
      $('#'+data+' .'+$(this).attr('rel')).show();
    });
    
    $('.llCd a').bind('mouseenter mouseleave', function(e) {
      if ($(this).attr('class') != 'actif') {
         var data = $(this).parents('ul').children('li').children('.actif');
         if (e.type == "mouseenter") {
          data.addClass('grey');
         } else {
          data.removeClass('grey');
         };         
      };
    });
    
    jQuery(function() {jQuery(".llCd, .filtreAlpha").lavaLamp({fx: "backout", speed: 700})});
    
  });
}(jQuery));

/* Start Chosen on certain form elements */(function ($) {

  $(document).ready(function() {
    
    $(".chzn-select").chosen({no_results_text: "Aucun résultat pour"}); 
    $(".chzn-container .chzn-single").addClass('boiteOmbre');
    
    var j = 100;
    $(".chzn-select").each(function() {
      $(this).parent().css({'position':'relative','z-index':j});
      j = j-1;
    });
  }); 
}(jQuery));

/* Cache et gère la visibilité des champs émissions et chaînes spécialisées dans contactez-nous*/(function ($) {

  $(document).ready(function() {
    
    var sujetDuMessage = $('#edit-submitted-sujet-du-message').val();
    
    $('#webform-component-emissions label, #webform-component-chaines-specialisees label').hide();
    
    if( sujetDuMessage !== 'emissions' ) {
      $('#webform-component-emissions').hide();
    }
    
    if( sujetDuMessage !== 'chaines' ) {
      $('#webform-component-chaines-specialisees').hide();
    }

    $('#webform-component-sujet-du-message select').change( function() {
      var selected = $(this).val();
      
      // Cache tout et montre un si nécessaire
      $('#webform-component-emissions, #webform-component-chaines-specialisees').hide();
      if( selected === 'emissions' ) {
        $('#webform-component-emissions').show();
      }
      if( selected === 'chaines' ) {
        $('#webform-component-chaines-specialisees').show();
      }
    });
  }); 
}(jQuery));

/* InfoBulle */(function ($) {

  $(document).ready(function() {
 
    $('.legende li').hover(function() {  
     
      var cetElement = $(this).find('.icone');
      var bulle = $(this).children('.infobulle');

          cetElement.after('<span class="rc infobulle">'+ cetElement.text() + '<span class="pointe">&nbsp;</span></span>');
          if (cetElement.hasClass('single')) {
             $(this).children('.infobulle').addClass('single');
            
          }

     },
      function() {
        $(this).children('span.infobulle').remove();
      }
    );
  });
  
  
}(jQuery));

/* InfoBulle - Accueil pour les icones de partage */(function ($) {
  $(document).ready(function() {
 
// 
//    $('#enVedette .icone').hover(function() {      
//      var cetElement = $(this);
//      var bulle = $(this).children('.infobulle');
//      var wrap = $(this).parent('.wrap-infobulle');
//      var text = cetElement.data("text-infobulle");
//      cetElement.wrap('<div class="wrap-infobulle"></div>');
//      cetElement.after('<span class="rc infobulle"><span class="chiffre">'+ cetElement.text() +'</span><span class="text">'+ text +'</span><span class="pointe">&nbsp;</span></span>');
//     },
//      function() {
//        $('span.infobulle').remove();
//        $(this).unwrap('<div class="wrap-infobulle"></div>');
//      }
//    );
//  
  
  });
}(jQuery));


/* Changer le texte de Twitter */(function ($) {

  $(document).ready(function() {
 
     $('.lienllCd').click( function() {
          $('.twtr-join-conv').text('Participer à la conversation');
    });
    
  });
  
}(jQuery));


/*** affichage des filtes
(function ($) {

  $(document).ready(function() {
  
      $('ul.filtreChoix a').click(function() { 
        $('ul.filtreChoix a').removeClass('active');
        $('ul.filtreChoix a').each(function (i) {
           $('section.'+ $(this).attr('class')).css("display","none");
        });
        filtre = $(this).attr('class');
        $('ul.filtreChoix a.'+ filtre).addClass('active');
        $('section.'+ filtre).css("display","block");
       });
       
    });
  
}(jQuery));
 ***/
 
 /* Afficher le bloc de pub sur les thumbnails de jeux seulement s'il y a une pub de loader  */
 (function ($) {

  $(document).ready(function() {
    
    /*if ($('#special3-1 img').attr("src") != 'http://s0.2mdn.net/viewad/817-grey.gif') {
      $('#special3-1').show();
    } 
    
    if ($('#special3-2 img').attr("src") != 'http://s0.2mdn.net/viewad/817-grey.gif') {
      $('#special3-2').show();
    } 
    
    if ($('#special3-3 img').attr("src") != 'http://s0.2mdn.net/viewad/817-grey.gif') {
      $('#special3-3').show();
    } 
    
    if ($('#special3-4 img').attr("src") != 'http://s0.2mdn.net/viewad/817-grey.gif') {
      $('#special3-4').show();
    }*/
    
    if ($('#boutonCinema img').attr("src") == 'http://s0.2mdn.net/viewad/817-grey.gif') {
      $('#special6Cinema img').hide();
    }; 
    
    /*** special 6 boites dans la colonne de droite ***/
    $("#pubSpecial6 .pubList").each(function (i) {  
      if ($("#pubSpecial6 .pubList:eq("+i+") img").attr("src") != 'http://s0.2mdn.net/viewad/817-grey.gif') {
        $("#pubSpecial6 .pubList:eq("+i+")").css('display', 'block');
        $("#pubSpecial6").css('display', 'block');
       }      
    });  
    
  });
  
}(jQuery));


/*Bouton - Redirectionner vers les commentaires  */
 (function ($) {

  $(document).ready(function() {
    
    $('a.commentez').click(function() {
      var elementClicked = $(this).attr("href");
      var destination = $(elementClicked).offset().top;
      $("html:not(:animated),body:not(:animated)").animate({scrollTop: destination-40}, 500 );
      return false;
    });

    
  });
  
}(jQuery));



/****** Functions pour le champ de recherche ******/

function rechercheTVA() {

	url = "http://tva.canoe.ca/recherche/?sen=site&ie=UTF-8&q=";
	recherche = encodeURI(document.frmRechercheTVA.recherche.value);
	window.location = url+recherche;

}

function viderechercheTVA() {

	document.frmRechercheTVA.recherche.value = "";

}


/* Bloc Trouve tout - Vidéotron  */
 (function ($) {
  $(document).ready(function() {
    
    $('input.quoi, input.ou').each(function(){
        $(this).data('val', $(this).val());
    });

    $('input.quoi, input.ou').focus(function(){
      if($(this).val() == $(this).data('val')){
        $(this).val("");
      }
    });

    $("input.quoi, input.ou").focusout(function() {
      if($(this).val() == ""){
        $(this).val($(this).data('val'));
      }
    });
    
    $('#bloc-trouve-tout a.btn-recherche').click(function(event){  
        event.preventDefault();

        if( $('input.quoi').val() != $('input.quoi').data('val') || $('input.ou').val() != $('input.ou').data('val') ){
          
          if( $('input.quoi').val() != $('input.quoi').data('val') ){
            var quoiValue = $('input.quoi').val();
          }else{
            var quoiValue = '';
          }
          
          if ($('input.ou').val() != $('input.ou').data('val')){
            var ouValue = $('input.ou').val();
          }else{
            var ouValue = '';
          }

          var adresse = 'http://ad.doubleclick.net/clk;250960495;20681658;p?http://videotron.trouvetout.ca/fr/trouve?what=' + quoiValue + '&where=' + ouValue;
          window.open(adresse, '_blank');
        }else{
          window.open('http://ad.doubleclick.net/clk;250960495;20681658;p?http://videotron.trouvetout.ca', '_blank');
        }

    });
    
  });
}(jQuery));;

