var index;
var maxImages;
var interval;
var timeout;
var timer;


jQuery(function(){

/*  $("li.element_company a")
             .each(function()
                  {
                   var height_li = $('li#company a').text().length;
                   if( height_li > 50 )
                   var text_li = $('li#company1 a').text().substr(0,40)+"...";
                   $('li#company a').text( text_li );
                  }); */


  var height = Math.max( $('div#candidate.bloc_home ul').height(), $('div#recruter.bloc_home ul').height() );
 $('div#candidate.bloc_home ul').height(height);
 $('div#recruter.bloc_home ul').height(height);
 
 var height = Math.max( $('div#candidate.bloc_home').height(), $('div#recruter.bloc_home').height() );
 $('div#candidate.bloc_home').height(height);
 $('div#recruter.bloc_home').height(height); 
 
 $('div#candidate.bloc_home.ads').css("min-height", "273px");
 $('div#recruter.bloc_home.ads').css("min-height", "273px"); 
 
 $("div#sub_container.full").height($("div#center_container").height());
 $("div#sub_container").height($("div#center_container").height());
 
 /** Permet de gérer la taille de la boîte à outils en fonction du contenu et d'aligner les autres blocs */
 var height = Math.max( $('div#tools.block ul').height(), $('div#parteners.block ul').height() );
 $('div#tools.block ul').height();
 $('div#parteners.block ul').height(height); 
 
  var height = Math.max( $('div#tools.block').height(), $('div#parteners.block').height() );
 $('div#tools.block').height(height);
 $('div#parteners.block').height(height);
 
 $('div#candidatePlus.bloc_candidat').height($('.box').outerHeight() + 16);
 $('div#recruterPlus.bloc_recruter').height($('.box').outerHeight() + 16);
 /**/
 
  if( $('div #testimony span p:last').text().length > 170 )
 {
  $('div #testimony span p:last').text( $('div #testimony span p:last').text().substr(0, 170)+ '...' );
 } 
 
 /********banniere de pub*************/
 $('div#sub_container > div.pub.ads').not(':first').fadeTo(0, 0);
 $("div#sub_container > div.pub.ads").not(':first').hide();
 
 index = 1;
 maxImages = $('div#sub_container > div.pub.ads').length;
 setTimer();
 /**********************/
 $( "form#search_home" )
   .submit( function(){
    try
    { 
     if(validSearchForm())
     {
      var url = '/recherche';
      
      var params = new Array();
      var key_locations = "";
      // Localisation
       // Tous les codes postaux
      if( $("input#key_location").val() != '' && $("input#key_location").data('datas').zip == 'Tous les codes postaux' )
      {
       key_locations = no_accent( $("input#key_location").data('datas').no_accent.toLowerCase() );
       url += "/" + key_locations + '-0';
      }
       // region 
      else if( $("input#key_location").val() != '' && $("input#key_location").data('datas').zip == 'vide' )
      {
       key_locations = $("input#key_location").data('datas').no_accent;
       key_locations = no_accent( key_locations.replace( new RegExp("[ ,/]", "gi"),"-").toLowerCase() );
       url += "/" + key_locations;
      }
       // departement ou ville 
      else
      {
       if($("input#key_location").val() != '' )
       {
        key_locations = no_accent( $("input#key_location").data('datas').no_accent.toLowerCase() );
        url += "/" + key_locations + "-" + $("input#key_location").data('datas').zip;
       }
      }
      
      // Keywords
      // url += ( $("input#job_title").val()!='' ) ? "/titre-"     + escape( $("input#job_title").val().replace( new RegExp("[ ,/]", "gi"),"+") ) : '';
      var key_words = $("input#key_words").val();
      
      if ( key_words.length > 3 )
      {
       var reg=new RegExp("(de )?(le )?(la )?(les )?", "gi");
       key_words = ( key_words != '' ) ? key_words.replace(reg, "") : '';
      }
      // key_words = ( key_words != '' ) ? no_accent(trim( key_words )) : '';
      // key_words = ( key_words != '' ) ? escape(trim( key_words )) : '';
      key_words = ( key_words != '' ) ? escape( trim( key_words.replace( new RegExp("[ ,/]", "gi"),"-") ) ) : '';
      
      
      
/*       var deleteStrings = ['le', 'la', 'les', 'de']; 
      key_words = key_words.split(" ");
      for(var i=0; i < deleteStrings.length; i++)
      {
       for(var j=0; j < key_words.length; j++)
       {
        if(key_words[j].toLowerCase() === deleteStrings[i])
        {
            key_words.splice(j, 1);
        }
       }
      }
      key_words = key_words.join("-"); */

      // url += ( key_words != '' ) ? "/" + escape( key_words.replace( new RegExp("[ ,/]", "gi"),"-") ) : '';
      url += ( key_words != '' ) ? "/" + key_words : '';
      
      if( key_words != '' )  window.location= url;
      else window.location= url + '/';
     }
     return false;
    }
    catch(err)
    {
     return false;
    }
   });
    
  $( "div#main div#popupHome #button_close" )
   .click( function(){
    $("div#main div#popupHome").hide(); 
    });
    
  $( "div#main #load_popup" )
   .click( function(){
    $("div#main div#popupHome").show(); 
    });
 
 
 /*************/
 // ANIMATION //
 /*************/
 ByRei_jScroller2.config.refreshtime = 50;
 
 var time=5000;
 slideTimeout =
 function()
 {
  clearTimeout( timeSlide );
  time = 5000;
  first=$("div.slide:first").attr( "id" );
  last=$("div.slide:last").attr( "id" );
  if( first!=last )
  {
   if( $("div.current_slide").attr( "id" ) != last )
   {
    $("div.current_slide").next().css( "left", "600px" );
    displaySlide( $("div.current_slide").next().attr( "id" ) );
   }
   else
   {
    $("div.slide:first").css( "left", "600px" );
    displaySlide( first );
   }
  }
 }

 // EXECUTE ANIMATION WITH TIMER
 timeSlide = setTimeout( "slideTimeout()", time );

 // Button onClick
 $(".slide_button")
   .click ( function()
          {
           clearTimeout( timeSlide );
           time=10000;
           var find=false;
           var button=$(this);
           // REPOS. SLIDES
           $("div.slide")
             .each(function()
                  {
                   $(this).stop( false, true );
                   if ( !$(this).hasClass( "current_slide" ) )
                   {
                    if( $(this).attr( "id" ) == $(button).attr("name") )
                     find=true;
                    else
                    {
                     if( find==true )
                      $(this).css("left","600px");
                     else
                      $(this).css("left","-600px");
                    }
                   }
                  });
           // START ANIMATION
           displaySlide( $(this).attr("name") );
          });

 // Slide Animation
 displaySlide =
 function( id )
 {
  
  //Opacity button change
  $(".slide_button")
    .each(function()
         {
          $(this).removeClass("slide_selected");
         }); 
  $(".slide_button[name=" + id + "]").addClass("slide_selected");

  var divToMove = $("div#" + id);
  
  if( ! $(divToMove).hasClass( "current_slide" ) )
  {
   var sens=1;
   if( $(divToMove).css("left") == "600px" ) sens = -1;
   
   divToMove
     .animate(
             {
             "left": "0px"
             },
             500,
             "linear",
             function(){$(this).addClass( "current_slide" );timeSlide = setTimeout( "slideTimeout()", time );}
            );
   
   $("div.current_slide")
     .animate(
             { "left": (sens*600)+"px" },
             500,
             "linear",
             function(){$(this).removeClass( "current_slide" );}
            );
  }
 }

 // video
 // $('.frame_video').click(function(){
  init_media_content();
 // });
 
 
 });

function selectRegion( id, value )
{
 $("input#zip_city").val( id );
 $("input#key_location").val( value );
 $("input#distance").val( "200" );
 return false;
}


function validSearchForm()
{
 // $('form#search input[type=text]')
   // .each( function()
        // {
         // if( $(this).val()==$(this).attr("alt") ) $(this).val("");
        // }); 
 $('form#search_home input[type=text]').each( function(){
   if( $(this).val()==$(this).attr("alt") ) $(this).val("");
  });
 return true;
}


// FUNCTIONS
// Return text (arg[1])without accents
no_accent =
function ( my_string )
{
 var new_string = "";
 var pattern_accent = new Array("é", "è", "ê", "ë", "ç", "à", "â", "ä", "ï", "î", "û", "ô", "ö", "\xF4", "\xE8", "'");
 var pattern_replace_accent = new Array("e", "e", "e", "e", "c", "a", "a", "a", "i", "i", "u", "o", "o", "o", "o", "");
 if (my_string && my_string!= ""){ new_string = preg_replace (pattern_accent, pattern_replace_accent, my_string); }
 return new_string;
}

function preg_replace (array_pattern, array_pattern_replace, my_string)
{
 var new_string = String (my_string);
 for (i=0; i<array_pattern.length; i++)
 {
  var reg_exp= RegExp(array_pattern[i], "gi");
  var val_to_replace = array_pattern_replace[i];
  new_string = new_string.replace (reg_exp, val_to_replace);
 }
 return new_string;
}

function trim ( my_string )
{
 return my_string.replace(/^\s+/g,'').replace(/\s+$/g,'');
} 

function changeImage()
{
 /* console.log( "index : " + index); */
 var nextIndex = index + 1;
 nextIndex = (nextIndex > maxImages) ? 1 : nextIndex;
 /* console.log( "nextIndex : " + nextIndex ); */
 $('div#sub_container > div.pub.ads').not( $('#ad_column' + nextIndex) ).fadeTo( 500, 0, function() { $(this).hide() } );
 $('#ad_column' + nextIndex).show();
 $('#ad_column' + nextIndex).fadeTo( 500, 1 );
}

function setTimer()
{
 interval = setInterval( function() {
  if( index > maxImages )
   index = 1;
  changeImage();
  index++;
 }, 5000);
}

function init_media_content()
{
 $(".frame_video").each(function(){
  $(this).jmedia(
   {version:"9,0", mode:"replace", elemClass:'jm_videoPlayer'},
   {src:"/system/packages/flash-jw-flv-player/player-viral.swf",
    width: "361px",
    height:"271px",
    quality:"best",
    wmode:"transparent",
    allowfullscreen:"true",
    flashVars: "file=/templates/needprofile/video/bourseoulavie.flv&image=/templates/needprofile/imgs/video/thierry_congard.jpg&controlbar=over&controlbar.idlehide=true"
    }
  );
  
 });
 
}
