﻿var interval_dj_home=null;
var interval_sondage=null;
var interval_bouncy=null;
var interval_pulsate=null;
var _tweets = null;
var _curtweet = 0;
var _hovers = new Array();

$(document).ready(function(){
  //popin login
  $('#trigger_login').click(function(){
    $('#login_top').toggle(500);
  });
  
  
  
  //Init tweets cycle
  if($('.tweeter_to_replace').length>0){
    populateTweet();
    setInterval('changeTweets()',10000);
  }
  
 
  
  //bounce sondage
  bounceSondage(true);
  $(".question").hover(function(){clearTimeout(interval_sondage)}, function(){});
  
  //bouncy links
  bouncy(true);
  $('.bouncy').hover(function(){
    $(this).stop(true,true).fadeTo(1,1);
    clearTimeout(interval_bouncy);
  },function(){bouncy(false);});
  
  //center pagination
  center_pagination();
  
  //Aperçu des descriptions résultats de recherche
  limitDescriptions();
  
  populate_faq();
  
  //Calendars  
  $('.calendar').datepicker({
    dateFormat: 'dd/mm/yy',
    monthNames: ["Janvier","Février","Mars","Avril","Mai","Juin","Juillet","Août","Septembre","Octobre","Novembre","Decembre"],
    prevText:"Précédent",
    nextText:"Suivant",
    dayNamesMin:["D","L","Ma","Me","J","V","S"],
    minDate: 0,
    firstDay: 1
  });
  
 // Ajax top Djs pour footer 
 $.ajax({
    url: rootabs+'xslt.aspx?typerubrique=1&rubriqueid=131&elementid='+villeId,
    success: function(html){
      $('.ajaxLoad').fadeOut('slow', function() {});
      $('#top5_content').html(html);
      $('#top5_content').fadeIn('slow', function() {});
      //resize photos top -> width
      $("#footer .home_top_5 a img").each(function(){
        if($(this).width()<201){
          $(this).css('width','202px');
          $(this).css('height','auto');
        }
      });
      //hover top 5 : affiche le nom
      $("#footer .home_top_5 a").hover(function(){$(this).find('.name').stop(true,true).fadeIn(300)}, function(){$(this).find('.name').stop(true,true).fadeOut(300)});
    }
  });

  $('.conteneurDepot, .conteneurCarte').mouseover(function(){
    $(this).addClass('borderForModalSearch');
  });
  
  $('.conteneurDepot, .conteneurCarte').mouseout(function(){
    $(this).removeClass('borderForModalSearch');
  });
  
  $('.conteneurDepot').click(function(){
    go('1','21','','','10','2');
    $("#recherche_dj").dialog("destroy");
  });
  
  // Ajax top pour la home
  
  if($('.home_dj_mav')){
    $.ajax({
    url: rootabs+'xslt.aspx?typerubrique=1&rubriqueid=130&elementid='+villeId,
    success: function(html){
      $('.home_dj_mav').html(html);
      //top 5 home slider
      $('.home_dj_mav .info .info_back').fadeTo(0,0.47); //opacity
      $('.home_dj_mav .info').first().addClass('active').animate({left:76},800, 'swing');  //montre le premier
      $('.home_dj_mav .info').hover(function(){clearInterval(interval_dj_home)},function(){switchTop5Home()} ); //stoppe-relance l'anim sur hover
      switchTop5Home(); //Lance le slider
    }
  });
  }
  
  $('.nbEvalAttente').html(nbEvalAttente);
  
  //shake effect
  pulsateEffect(true);
  $('.pulsateEffect').hover(function(){
    $(this).stop(true,true).fadeTo(1,1);
    clearTimeout(interval_pulsate);
  },function(){pulsateEffect(false);});
  
  $('.fancybox').fancybox({
    'openEffect' : 'elastic',
    'closeEffect' : 'elastic',
    'openSpeed' : 600,
    'closeSpeed' : 200
  }); 
  
});

function switchTop5Home(){
  if($('.home_dj_mav .active').length>0){
    interval_dj_home = setInterval(function(){
      if($('.home_dj_mav .active').next('.info').length>0){
        $('.home_dj_mav .active').removeClass('active').stop(true,true).animate({top:300},500, 'swing').next('.info').addClass('active').css({top:204,left:520}).stop(true,true).animate({left:76},800, 'swing');
      }
      else{
        $('.home_dj_mav .active').removeClass('active').stop(true,true).animate({top:300},500, 'swing').siblings('.info').first().addClass('active').css({top:204,left:520}).stop(true,true).animate({left:76},800, 'swing');
      }
    },6000);
  }
}

function bounceSondage(direct){  
  if(direct){$(".question").stop(true,true).css('top',0).effect("bounce", { times:3 }, 250);}
  interval_sondage = setTimeout(function(){
    bounceSondage(true);
  },18000);
}

function bouncy(direct){  
  if(direct){$(".bouncy").stop(true,true).effect("pulsate", { times:1 }, 500);}
  interval_bouncy = setTimeout(function(){
    bouncy(true);
  },6000);
}

function pulsateEffect(direct){  
  if(direct){$('.pulsateEffect').stop(true,true).effect("pulsate", { times:4 }, 500);}
  interval_pulsate = setTimeout(function(){
    pulsateEffect(true);
  },6000);
}


function changeTweets(){  

  if(_curtweet>=(_tweets.length-1)){
    _curtweet=0;
  }

  var text = _tweets[_curtweet].text;
  var date =  parseDate(_tweets[_curtweet].created_at);
  try{
    var reg=new RegExp("((http|ftp):\/\/\\S*)",'gi') ;
    text = text.replace(reg,'<br/><a href="$1">$1</a>');
  }
  catch(e){}


  $('.tweeter_to_replace').each(function(){

    $(this).fadeOut(500,function(){
      $(this).html(text+'&#160;-&#160;<span class="date_twit">Twitté le '+date+'</span>');
      $(this).fadeIn(500);
    })
  });
  
  _curtweet++;
}

function populateTweet(){
  $.get(
    rootabs+'/tweets.aspx',
    {},
    function (data) {
      _tweets = data;
      changeTweets();
    },
    "json"
  );
}

function parseDate(str) {
  var v=str.split(' ');
  return new Date(Date.parse(v[1]+" "+v[2]+", "+v[5]+" "+v[3]+" UTC"));
} 

function voteSondage(id){
  
  if($('input:radio[name=res_vote]:checked').length==0){return;} // Pas de résultat coché
  
  var toreplace = $('.partenaires_suivi_question .to_replace');
  var old_height = $(toreplace).parent().height()
  $(toreplace).parent().css('height',old_height); //Save hauteur
  
  $(toreplace).fadeOut(200,function(){
    $(toreplace).load(rootabs+'xslt.aspx?typerubrique=1&rubriqueid=120&elementid='+id+'&enregistrementid=120&firstenr=2&nbenr=20&enr2='+id+'&enr3='+$('input:radio[name=res_vote]:checked').val(), function(){
      $(toreplace).fadeIn(200, function(){
        $(toreplace).find('.res').animate({left:0}, 800, function(){        
          $('.question .chiffre').fadeTo(700,0.8);
        });
      });
      $(toreplace).parent().animate({height:$(toreplace).height()}); //Animate nouvelle hauteur
      clearTimeout(interval_sondage);// Tue le bounce
    });
  });   
}


function seeWithoutVote(id){
  var toreplace = $('.partenaires_suivi_question .to_replace');
  var old_height = $(toreplace).parent().height()
  $(toreplace).parent().css('height',old_height); //Save hauteur
  
  $(toreplace).fadeOut(200,function(){
    $(toreplace).load(rootabs+'xslt.aspx?typerubrique=1&rubriqueid=120&elementid='+id, function(){
      $(toreplace).fadeIn(200, function(){
        $(toreplace).find('.res').animate({left:0}, 800, function(){        
          $('.question .chiffre').fadeTo(700,0.8);
        });
      });
      $(toreplace).parent().animate({height:$(toreplace).height()}); //Animate nouvelle hauteur
      clearTimeout(interval_sondage);// Tue le bounce
    });
  });   
}

function center_pagination(){
  var finalwidth=0;
  var count_obj = $('.pagination_container .pagination').first().children('').length;

  $('.pagination_container .pagination').first().children('').each(function(){
    finalwidth = finalwidth + $(this).outerWidth();
  });
  $('.pagination_container .pagination').css('width', finalwidth+(count_obj*5)+'px');
}

function limitDescriptions(){
  $('.unResultat .desc').each(function(){
    
    //Retire les desc inutiles & continue
    if($(this).html()=='<br>'){$(this).remove();return true;}
    
    //Retire le br en début de texte
    reg =  new RegExp("^(<br>)+","gi");
    $(this).html($(this).html().replace(reg,""));
    
    //Système de hover pour cacher/montrer les textes
    if($(this).height()>20){
      var tmp_height = $(this).height();      
      $(this).css('height','16px');
      $(this).parent().append('<div class="to_be_continued">[...]</div>')
      $(this).parent().parent().hover(function(){
        var caller = this;
        var time = setTimeout(function(){         
          $(caller).find('.desc').stop().animate({height:tmp_height});
        },800, [caller, tmp_height])
        _hovers.push([caller,time]);
        
      }, function(){
        var caller = this;
        removeFromHovers(caller)        
        $(caller).find('.desc').stop().animate({height:16});
      });
    }
    
    
  });
}

function populate_faq(){
  var content = "<p class=\"mav\">Question : </p><br/>";
  $(".pour_ancre").each(function(i,elm){
    elm.id = "faq_"+i;
    content += ">> <a href=\"#faq_"+i+"\">"+elm.textContent+"</a> <br/><br/>";
  }); 
  $("#faq #smallLeft").html(content);
}


//Retrouve si un timer est set pour le div passé en param
function removeFromHovers(obj){
  for(var i=0;i<_hovers.length;i++){
    if(_hovers[i][0]==obj){
      //Clear le timer
      clearTimeout(_hovers[i][1]);
      //Nettoie le tableau
      _hovers.remove(i);
      //Quitte la boucle
      break;
    }
  }
}


function track(fieldname,value){
  $.ajax({
    url: rootabs+'xslt.aspx?typerubrique=1&rubriqueid=140&enregistrementid=140&firstenr=2&nbenr=10&enr2='+fieldname+'&enr3='+value,
    success: function(html){
    }
  });
}

function checkSiret(caller){
  
  if(!isSiretValide(caller.value.killspaces())){
    $('.siretAjax').html("Ce SIRET n'est pas valide. Un SIRET est composé de 14 chiffres.");
    return;
  }
  
  $.ajax({
    url: rootabs+'siret.aspx?valeur='+caller.value.killspaces(),
    success: function(html){
      if($(html).hasClass('siret_error')){
        $('.siretAjax').html($(html).text()).effect("highlight");
        $('#siretAjaxOK').val('0');
        if(relaunchVerif){verifstandard();}
        return;
      }
      
      if($(html).hasClass('siret_wait')){
        $('.siretAjax').html($(html).text()).effect("highlight");
        $('#siretAjaxOK').val('1');
        if(relaunchVerif){verifstandard();}
        return;
      }
      
      
      $('.siretAjax').html("Ce numéro est enregistré au registre du commerce sous l'identité "+$(html).find('.name').text()).effect("highlight");
      $('#siretAjaxOK').val('1');
      if(relaunchVerif){verifstandard();}
      
      
    }
  });
}

function verifForm(paramToSplit, nameInput, valeur, idInput){
  if($('#'+idInput).nextAll('.errorForm').length > 0){
    $('#'+idInput).nextAll('.errorForm').first().slideUp(function(){
      $(this).remove();
       $.ajax({
        url: rootabs+'verifForm.aspx?paramToSplit='+paramToSplit+'&nameInput='+nameInput+'&valeur='+valeur+'&idInput='+idInput,
        success: function(response){
          if(response["ERROR"] == 1){
            var html = '<div class="errorForm">';
            for(i=0; i<response["MESSAGES"].length; i++){
              html += ""+response["MESSAGES"][i]+"<br/>";
            }
            html += "</div>";
            $('#'+response["IDINPUT"]).parents('.choixValue').append(html);
            $('.errorForm').slideDown();
            $('#'+response["IDINPUT"]).addClass('errorFormFocus');
          }
          else{
            $('#'+response["IDINPUT"]).removeClass('errorFormFocus');
          }
        }
      });
    });
  }else{
    $.ajax({
      url: rootabs+'verifForm.aspx?paramToSplit='+paramToSplit+'&nameInput='+nameInput+'&valeur='+valeur+'&idInput='+idInput,
      success: function(response){
        if(response["ERROR"] == 1){
          var html = '<div class="errorForm">';
          for(i=0; i<response["MESSAGES"].length; i++){
            html += ""+response["MESSAGES"][i]+"<br/>";
          }
          html += "</div>";
          $('#'+response["IDINPUT"]).parents('.choixValue').append(html);
          $('.errorForm').slideDown();
          $('#'+response["IDINPUT"]).addClass('errorFormFocus');
          
        }
        else{
          $('#'+response["IDINPUT"]).removeClass('errorFormFocus');
        }
      }
    });
  }
}


