$(function(){

  /**
   * Menu
   */
  $("#menu a").hover(function(){
    $('#menu-'+selectedMenu).css('background-position', '0px 0px');
    $(this).css('background-position', '0px -58px');
  },
  function(){
    $(this).css('background-position', '0px 0px');
    $('#menu-'+selectedMenu).css('background-position', '0px -58px');
  });
  $('#menu-'+selectedMenu).addClass('selected').css('background-position', '0px -58px');

  $(".detail-btn").hover(function(){
    $(this).css('background-position', '0px -28px');
  },
  function(){
    $(this).css('background-position', '0px 0px');
  });

  /**
   * Page accueil bloc promos
   */  
//  $("#promotions").html('');
  $("#promotions").jcarousel(
   {
     buttonNextHTML: null,
     buttonPrevHTML: null,
     scroll:1,
     visible: 3,
     auto: 4,
     animation: "slow",
     wrap: 'circular',
     itemVisibleInCallback: {onBeforeAnimation: mycarousel_itemVisibleInCallback},
     initCallback: mycarousel_initCallback
   }
  );

  /**
   * Moteur
   */
  $("#moteurMarque").change(function(){
    if($(this).val() != ''){
      $.post(
        '/ajax/annonces/get_modeles',
        {marque: $(this).val()},
        function(data){
          $("#moteurModele").replaceWith(data);
        }
      );
    }
  });
  $(".accueil-moteur [id*=AnnoncePrix]").each(function(){
    if($(this).val() == ''){
      $(this).val('\u20ac');
    }
  }).blur(function(){
    if($(this).val() == ''){
      $(this).val('\u20ac');
    }
  }).focus(function(){
    if($(this).val() == '\u20ac'){
      $(this).val('');
    }
  });
  $(".accueil-moteur [id*=AnnonceKm]").each(function(){
    if($(this).val() == ''){
      $(this).val('KM');
    }
  }).blur(function(){
    if($(this).val() == ''){
      $(this).val('KM');
    }
  }).focus(function(){
    if($(this).val() == 'KM'){
      $(this).val('');
    }
  });
  $('#moteur-prix').slider({
    range: true,
    step: 1000,
    min: 0,
    max: 50000,
    values: [0,50000],
    slide: function(event, ui){updateSlider(event, ui, 'prix');},
    change: function(event, ui){updateSlider(event, ui, 'prix');}
  });
  $('#moteur-km').slider({
    range: true,
    step: 5000,
    min: 0,
    max: 100000,
    values: [0,100000],
    slide: function(event, ui){updateSlider(event, ui, 'km');},
    change: function(event, ui){updateSlider(event, ui, 'km');}
  });
  $('#moteur-annee').slider({
    range: true,
    step: 1,
    min: 1985,
    max: new Date().getFullYear(),
    values: [1985,new Date().getFullYear()],
    slide: function(event, ui){updateSlider(event, ui, 'annee');},
    change: function(event, ui){updateSlider(event, ui, 'annee');}
  });

  /**
   * Alerte email
   */
  $("#alerteMarque").change(function(){
    if($(this).val() != ''){
      $.post(
        '/ajax/alertes_emails/get_modeles',
        {marque: $(this).val()},
        function(data){
          $("#alerteModele").replaceWith(data);
        }
      );
    }
  });

  /**
   * Détail d'annonce Horinaja
   */
  $('#equip-horinaja').Horinaja({
    capture: 'equip-horinaja',
    delai: 0.3,
    duree: 3,
    pagination: true
  });

  /**
   * Lightbox détail annonce
   */
  $("a[rel='photos-annonce']").colorbox({slideshow:true, transition:"fade", slideshowSpeed:4000});


  /**
   * Gestion des PNG sous IE6
   */
  try{
    DD_belatedPNG.fix('*');
  }catch(err){
    //on est pas sous ie6
  }

  /**
   * Share This
   */
  stLight.options({publisher:'8de64d37-bbeb-45b4-a057-7cc678611dfa'});

});

function mycarousel_itemVisibleInCallback(carousel, item, i, state, evt){

  var idx = carousel.index(i, mycarousel_itemList.length);
  mycarousel_getItemHTML(mycarousel_itemList[idx - 2]);

  $("#promotions li").each(function(){if(!$(this).children('.promos-foreground').length)$(this).prepend('<div class="promos-foreground"><!-- --></div>')});
  idx = i-1;
  $(".jcarousel-item-"+idx).children('.promos-foreground').remove();
}
function mycarousel_getItemHTML(item){
  if(item){
    $('.promos .marque').html(item.marque+' '+item.modele);
    $('.promos .prix').html(item.prix+' \u20ac');
    $('.promos .detail a').attr('href', item.url);
  }
}
function mycarousel_initCallback(carousel){
  $(".promos .prec img").click(function(){
    carousel.prev();
  });
  $(".promos .next img").click(function(){
    carousel.next();
  });
}

function detailSendMail(send, id){
  if(!send || typeof(send) == 'object'){
    if(send == undefined){
      send = {};
    }
    var form = '<label for="nom" class="colorbox-label">Votre nom : </label><input type="text" id="nom" value="'+(send.nom!=undefined?send.nom:'')+'" /><br /><br />\n\
    <label for="prenom" class="colorbox-label">Votre prénom : </label><input type="text" id="prenom" value="'+(send.prenom!=undefined?send.prenom:'')+'" /><br /><br />\n\
    <label for="from" class="colorbox-label">Votre adresse email : </label><input type="text" id="from" /><br /><br />\n\
    <label for="to" class="colorbox-label">L\'adresse email de votre ami : </label><input type="text" id="to" value="'+(send.to!=undefined?send.to:'')+'" /><br /><br />\n\
    <a href="#" onclick="return detailSendMail(true, \''+id+'\');">Envoyer l\'email</a>';
    $.colorbox({html:form});
  }else{
    var errors = [], text = 'Les erreurs suivantes ont été rencontrées : <br /><ul>', nom, prenom, to, from, coords;
    if((nom = $("#nom").val()) == ''){
      errors.push('Vous devez indiquer votre nom.');
    }
    if((prenom = $("#prenom").val()) == ''){
      errors.push('Vous devez indiquer votre prénom.');
    }
    if((to = $("#to").val()) == ''){
      errors.push('Vous devez indiquer l\'adresse email de votre ami.');
    }else if(!/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(to)){
      errors.push('L\'adresse email de votre ami est invalide.')
    }
    if(errors.length != 0){
      for(i in errors){
        text += '<li>'+errors[i]+'</li>\n';
      }
      text += '</ul>';
      $.colorbox({
        html: text,
        onClosed: function(){
            detailSendMail({
              nom: nom,
              prenom: prenom,
              to: to
            }, id);
          }
      });
    }else{
      if((from = $("#from").val()) == '' || !/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(from)){
        from = prenom+' '+nom+'<contact@reflexautomobile.com>';
      }else{
        from = prenom+' '+nom+'<'+from+'>';
      }
      coords = {nom: nom, prenom: prenom, from: from, to: to};
      $.post(
        '/annonces/detailSendMail/'+id,
        coords,
        function(data){
          $.colorbox({html: '<p>'+data+'</p>'});
          setTimeout($.colorbox.close, 3000);
        }
      )
    }
  }
  return false;
}

function updateSlider(event, ui, type){
  var values = $('#moteur-'+type).slider('option', 'values');
  if(type != 'annee')
    $('#moteur-'+type+'-txt').text($('#moteur-'+type+'-txt').text().replace(/(d|D)e [0-9 ]+ à [0-9 ]+( (€|Kms))?/, '$1e '+number_format(values[0], 0, '', ' ')+' à '+number_format(values[1], 0, '', ' ')+' $2'));
  else
    $('#moteur-'+type+'-txt').text($('#moteur-'+type+'-txt').text().replace(/(d|D)e [0-9 ]+ à [0-9 ]+( (€|Kms))?/, '$1e '+values[0]+' à '+values[1]+' $2'));
  $('#Annonce'+type.charAt(0).toUpperCase()+type.substr(1)+'Min').val(values[0]);
  $('#Annonce'+type.charAt(0).toUpperCase()+type.substr(1)+'Max').val(values[1]);
  $('#AlerteEmail'+type.charAt(0).toUpperCase()+type.substr(1)+'Min').val(values[0]);
  $('#AlerteEmail'+type.charAt(0).toUpperCase()+type.substr(1)+'Max').val(values[1]);
}

function number_format(number, decimals, dec_point, thousands_sep) {
    number = (number+'').replace(',', '').replace(' ', '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}
