// Webcarnews.com - Scripts communs
// (k) Radis au Curry 2009

// Pour Google Analytics
var tmp = document.domain.split('.');
if (tmp.length >= 3) {
  document.domain = tmp[tmp.length - 2] + '.' + tmp[tmp.length - 1];
}

// Pour le moteur de recherche: ID de visiteur
if (!String.random) String.random = function() {
  var length = arguments[0] || 6;
  var result = '';
  for (var i = 0; i < length; i++) {
    result += String.fromCharCode(97 + Math.floor((Math.random()*24)));
  }
  return result;
};
function loadUserID() {
  var name = 'wwwwebcarnewscom_pJ7EdfX84';
  var value = Cookie.read(name);
  if (!value) {
    value = String.random(30);
    Cookie.write(name, value);
  }
  return value;
}
// Recherche
window.onload = function () {
  if (document.getElementById) {
    var search = document.getElementById('search_input');
    if (search) search.onclick = function() {
       search.value = '';
    };
  }
}

// Pour la séléction du nombre d'articles par page
String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/, '');
};

// DetectVersion => Flash
// http://www.howtocreate.co.uk/wrongWithIE/?chapter=navigator.plugins
// http://web.archive.org/web/20070825204102/http://www.quirksmode.org/js/flash.html
// Tant pis pour la détection, de toute façon on s'en fout
DetectVersion = {
  FlashVersion: 100,
  putFlash: function (swf, width, height) {
    // object@id="test" => viré, était utile ?
    var h =
      '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://active.macromedia.com/flash2/cabs/swflash.cab#version=4,0,0,0" width="'+width+'" height="'+height+'">'+
      '<param name="movie" value="'+swf+'">'+
      '<param name="loop" value="true">'+
      '<param name="quality" value="high">'+
      '<param name="scale" value="showall">'+
      '<embed src="'+swf+'" scale="showall" loop="true" quality="high" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" width="'+width+'" height="'+height+'">'+
      '</object>';
    document.write(h);
  }
};

// Pubs SmartAdServer
sas_tmstp = Math.round(Math.random()*10000000000); sas_masterflag=1;
function SmartAdServer(sas_pageid,sas_formatid,sas_target) {
  if (sas_masterflag==1) {sas_masterflag=0;sas_master='M';} else {sas_master='S';}
  document.write('<scr'+'ipt src="http://www.smartadserver.com/call/pubj/' +
    sas_pageid + '/' + sas_formatid + '/'+sas_master + '/' + sas_tmstp + '/' +
    escape(sas_target) + '?"></scr'+'ipt>');
}

// 27/01/2009: Menu déroulant
function scrollableMenu(menu) {
  function choucroute(e) {
    var scrollerHeight = 18;

    if (!this._originalHeight) {
      this._originalHeight = this._subMenu.getSize().y;
      this._subMenu.setStyle('height', (this._originalHeight+2*scrollerHeight)+'px');
    }

    var menuList = this._subMenu;
    var menuPos = this.getPosition();
    menuPos.y += this.getSize().y;
    var menuSize = menuList.getSize();
    var menuBottom = menuSize.y + menuPos.y;
    var windowBottom = document.getSize().y + document.getScroll().y;
    var newMenuHeight = windowBottom - menuPos.y - 4;
    var menuScroll = menuList.getScroll().y;
    var overflow = true;

    if (newMenuHeight > this._originalHeight) {
      newMenuHeight = this._originalHeight;
      overflow = false;
    }

    this._height = newMenuHeight;

    menuList.setStyle('height', (newMenuHeight-1)+'px');

    if (!this._bottomScroller) {
      var scrollerWidth = menuList.getSize().x-2;
      var topScroller;
      var startScrolling = function(x) {
        if (this._timer) $clear(this._timer);
        this._scroll = this._subMenu.getScroll().y;
        this._scrollMax = this._subMenu.getScrollSize().y;
        this._timer = (function(x) {
          var y = this._scroll+x;
          if (y >= 0 && y <= this._scrollMax) {
            this._subMenu.scrollTo(0, y);
            this._scroll = y;
            this._timer = arguments.callee.pass(x, this).delay(15);
          }
        }).run(x*3, this);
      };
      var stopScrolling = function() {
        $clear(this._timer);
      };

      this._topScroller = new Element('div', {
        'class': 'menuHandleMoreTop',
        'styles': {
          'height': scrollerHeight+'px',
          'width': scrollerWidth+'px',
          'margin-left': '1px'
        },
        'events': {
          'mouseover': startScrolling.pass(-1, this),
          'mouseleave': stopScrolling.bind(this)
        }
      });
      this._bottomScroller = new Element('div', {
        'class': 'menuHandleMoreBottom',
        'styles': {
          'height': scrollerHeight+'px',
          'width': scrollerWidth+'px',
          'margin-left': '1px'
        },
        'events': {
          'mouseover': startScrolling.pass(1, this),
          'mouseleave': stopScrolling.bind(this)
        }
      });
      this._bottomScroller.inject(menuList, 'after');
      this._topScroller.inject(menuList, 'after');
    }

    if (overflow) {
      this._bottomScroller.setStyle('top', (newMenuHeight+menuPos.y-scrollerHeight-1)+'px');
      this._bottomScroller.setStyle('display', 'block');
      this._topScroller.setStyle('display', 'block');
      menuList.getFirst().getFirst().setStyle('padding-top', scrollerHeight+'px');
      menuList.getLast().getFirst().setStyle('padding-bottom', scrollerHeight+'px');
    } else {
      menuList.scrollTo(0, 0);
      this._bottomScroller.setStyle('display', 'none');
      this._topScroller.setStyle('display', 'none');
      menuList.getFirst().getFirst().setStyle('padding-top', '0');
      menuList.getLast().getFirst().setStyle('padding-bottom', '0');
    }
  }
  menu.addEvent('mouseover', choucroute.bind(menu));
}

window.addEvent('domready', function() {
  var menuItems = $$('ul#menu > li');
  var i, j;

  for (i = 0; i < menuItems.length-1; i++) {
    var o = menuItems[i];
    o._subMenu = $(o.getFirst('ul')); // $() for ie
    if (o._subMenu) {
      var handle = o.getFirst('a');
      var minWidth = o.getFirst().getSize().x;

      o._subMenu.setStyle('min-width', minWidth+'px');
      // === ONMOUSEOVER ===
      handle.addEvent('mouseenter', function() {
        this.addClass('over');
        // <workaround>
        if (Browser.Engine.trident && !this._alreadyShowed) {
          this._alreadyShowed = true;
          var o = this;
          var minWidth = o.getFirst().getSize().x;
          var li = o._subMenu.getFirst('li')
          if (li) {
            var requiredSize = li.getSize().x;
            var actualSize = li.getFirst().getSize().x;
            //alert('BOUH: '+actualSize+','+requiredSize+','+minWidth);
            var items = o._subMenu.getElementsByTagName('a');
            for (var j = 0; j < items.length; j++) {
              var item = $(items[j]);
              var pad =
                item.getStyle('padding-left').toInt()+
                item.getStyle('padding-right').toInt()+
                item.getStyle('border-left-width').toInt()+
                item.getStyle('border-right-width').toInt();
              var w = requiredSize-pad;
              var w2 = minWidth-pad;
              item.setStyle('width', (w > w2 ? w : w2)+'px');
            }
            // Pour IE7 sinon donne une mauvaise taille au 1er affichage
            if (o._subMenu.getSize().x < requiredSize) {
              o._subMenu.setStyle('width', requiredSize+'px');
            }
          }
        }
        // </workaround>
      }.bind(o));
      // === ONMOUSELEAVE ===
      o.addEvent('mouseleave', function() {
        window._lastOut = this;
        this._outTimer = (function () { 
          this.removeClass('over');
        }).bind(this).delay(600);
      }.bind(o));
      o.addEvent('mouseenter', function() {
        if (window._lastOut && window._lastOut!=this) _lastOut.removeClass('over');
        if (this._outTimer) $clear(this._outTimer);
      }.bind(o));
      // === SCROLL ===
      scrollableMenu(o);
    }
  }
});
