/*----------------------------------------------------------------------
*  Le Phare JavaScript library - (c) 2010
*
* Nécessite :
*    - jQuery
*    - jQuery.validate
---------------------------------------------------------------------- */

(function ($) {
   $(document).ready(function () {
      var id = $('body').attr('id'),
          lg = $('html').attr('lang').replace(/^([a-z]{2}).*$/i, '$1').toLowerCase();

      // Test la présence d'un id sur le body
      !id && alert("ATTENTION\n la balise body n'a pas d'id !");

      // Traitements des spécifiques
      switch (id) {
         case 'pageContact' : 
            // Traitement lié a la page
            break;
            case 'pageRecherche':
               searchEngine();
            break;
            case 'pageContactConfBrochure':
               url = '../s04_contact/_ajax_brochure.php';
               $.download( url,'prod='+$('#jsProduit').val());           
            break;
            case 'pageAccueil':
                $('#vignetteHome').animateNews();
            break;
         default:
      }

      // Traitements des génériques
      $('.fade').delay(8000).fadeOut(1500);
      $('form').validate();
      fancybox();
   });
})(jQuery)

jQuery.download = function(url, data, method){
	//url and data options required
	if( url && data ){ 
		//data can be string of parameters or array/object
		data = typeof data == 'string' ? data : jQuery.param(data);
		//split params into form inputs
		var inputs = '';
		jQuery.each(data.split('&'), function(){ 
			var pair = this.split('=');
			inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'" />'; 
		});
		//send request
		jQuery('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>')
		.appendTo('body').submit().remove();
	};
};
// On ajoute le corps de la methode
(function($) {
   $.extend($.fn, {
      replay : function(timeout, callback) {
         /* On itère tous les éléments de la collection en
         cours et pour chacun d'eux on retourne this */
         return this.each(function() {
            // On garde une reference sur l'objet courant
            var obj = $(this),
                fnc = function () {
                   callback.call(obj);
                   setTimeout(fnc, timeout);
                };
                // On execute la premiere itération
                fnc();
            return this;
         });
      }
   });
})(jQuery);

(function($) {
   $.fn.extend({
      animateNews : function(opts) { 
         var options = $.extend({
           duration   : 'slow',
           timer      : 5,
           fleche     :'fleche',
           left       : 146,
           leftDepart: 70,
           newsMax    : 'jsOneActuMax',
           imageMax   : 'jsNewsImage'
         }, opts);
                
        return this.each(function(){
            var obj = $(this),
                cur    = 0,
                news = obj.find('li'),
                move = function(idx){
                   $('.'+options.imageMax).eq(cur).css({'z-index' : 1});
                   $('.'+options.newsMax).eq(cur).css({'z-index' : 1});
                   $('.'+options.newsMax).fadeOut('slow');
                   //$('.'+options.imageMax).fadeOut('slow');
                  
                   MonLeft = idx==0? options.leftDepart: options.leftDepart + (idx*options.left);  
                  
                   $('#'+options.fleche).animate({left: MonLeft},{duration:1000});
           
                    $('.'+options.newsMax).eq(idx).css({'z-index' : 2}).fadeIn('slow');
                    $('.'+options.imageMax).eq(idx).css({'z-index' : 2}).fadeIn('slow',function(){
                    $('.'+options.imageMax).eq(cur).fadeOut();
                    cur = idx;
                    });
                },
                animated = function(){
                  var idx = cur + 1;
                     if (idx >= news.length) idx = 0;
                     move(idx);
                   }
                  ;
   
            $('.'+options.newsMax+':first').show();
            $('.'+options.imageMax+':first').show();
            
            $(news).each(function(){
               myLink = $(this).find('a');
               myLink.each(function(){
                  $(this).click(function(){
                     var idx = $(this).attr('href').replace('#news-','');
                     if(idx!=cur)      
                        move(idx);
//                      if (options.timer) {
//                         clearInterval(interval);
//                         interval = setInterval(animated, options.timer * 1000);
//                      }
                     clearInterval(interval);
                     return false;                     
                  });
               });
            })
            if (options.timer) {
               interval = setInterval(animated, options.timer * 1000);
            }
                
        });
   }
   });
   })(jQuery);

var v_arob="@";

// permet d'afficher une adresse email et d'y mettre un line mailto: associé.
// av : partie gauche de l'Adresse (avant @)
// ap : partie droite de l'Adresse (apres @)
// cl : class (style) à appliquer au lien (paramètre optionnel)
function write_link_email(av,ap,cl)
{
  // gestion du style si passé en paramètre
  if(cl!="") src_style="class='"+cl+"'";
  else  src_style="";
  src="<a href=\"javascript:link_email('"+av+"','"+ap+"')\""+src_style+"><"+"script"+">write_email('"+av+"','"+ap+"');</"+"script"+"></a>";
  document.write(src);
}

// permet d'afficher une adresse email
// av : partie gauche de l'Adresse (avant @)
// ap : partie droite de l'Adresse (apres @)
function write_email(av,ap)
{
	document.write(av+v_arob+ap);
}

// permet de générer un lien de type mailto vers une adresse email
// av : partie gauche de l'Adresse (avant @)
// ap : partie droite de l'Adresse (apres @)
function link_email(av,ap)
{
	document.location="mailto:"+av+v_arob+ap;
	return void(0);
}

/********************************************************************/
/* moteur de recherche */
/********************************************************************/

function searchEngine()
{  searchAjax();
   $('#colOrigine input[type="checkbox"]').click(searchAjax)

   $('#jsAll').click(function(){   
         $('#colOrigine input[type="checkbox"]:not(#jsAll)').each(function(){ this.checked = $('#jsAll').attr('checked');});
         searchAjax();
   });
   activCosmClic();

}
function searchAjax()
{
   var   ZoneOrigine = $('#jsOrigine').serialize(), 
         url         = '';
   if(ZoneOrigine!='')
   {
      if($('#jsOrigine input[name="data[origine][]"]:checked').length==0)       ZoneOrigine += '&data[origine]=-1';
      if($('#jsOrigine input[name="data[solubilite][]"]:checked').length==0)    ZoneOrigine += '&data[solubilite]=-1';
      if($('#jsOrigine input[name="data[certification][]"]:checked').length==0) ZoneOrigine += '&data[certification]=-1';
      
   }      
   url         = '../s06_catalogue/_ajax_actifcosm.php?' + (ZoneOrigine!='' ? ZoneOrigine:'reset=1');
   $('#jsLoad').show();   
   $.getJSON(url, function(data) { 
         // retire l'ul quand il est là
         $('#colActivite ul').remove();
         // ajoute les checkbox dans le choix des activités cosmétiques
         $('#jsZoneActivite').html(data.content);
         // retire le contenu de resultat dans le cas ou on aurait plus le texte 
         $('#blocResultat').empty();
         if($('#jsZoneActivite').serialize()!='') ajax_actCosm();
         else   $('#blocResultat').html(data.products);
         // on tourne sur tous les checkbox de colActivité pour 
         activCosmClic();

         $('#jsLoad').hide();
   });         
}
function activCosmClic()
{
   $('#colActivite input[type="checkbox"]').click(ajax_actCosm);
}
function strrpos (haystack, needle, offset) {
    // Finds position of last occurrence of a string within another string  
    // 
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/strrpos    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   input by: saulius
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: strrpos('Kevin van Zonneveld', 'e');    // *     returns 1: 16
    // *     example 2: strrpos('somepage.com', '.', false);
    // *     returns 2: 8
    // *     example 3: strrpos('baa', 'a', 3);
    // *     returns 3: false    // *     example 4: strrpos('baa', 'a', 2);
    // *     returns 4: 2
    var i = -1;
    if (offset) {
        i = (haystack + '').slice(offset).lastIndexOf(needle); // strrpos' offset indicates starting point of range till end,        // while lastIndexOf's optional 2nd argument indicates ending point of range from the beginning
        if (i !== -1) {
            i += offset;
        }
    } else {        i = (haystack + '').lastIndexOf(needle);
    }
    return i >= 0 ? i : false;
}
function ajax_actCosm()
{
   var   ZoneActi = $('#jsZoneActivite').serialize(),
         ZoneOrigine = $('#jsOrigine').serialize(),         
         url= '';      
   
   if(ZoneOrigine!='')
   {
      if($('#jsOrigine input[name="data[origine][]"]:checked').lenght==0)       ZoneOrigine += '&data[origine][]=-1';
      if($('#jsOrigine input[name="data[solubilite][]"]:checked').lenght==0)    ZoneOrigine += '&data[solubilite][]=-1';
      if($('#jsOrigine input[name="data[certification][]"]:checked').lenght==0) ZoneOrigine += '&data[certification][]=-1';
      
   }
   
   url      = '../s06_catalogue/_ajax_actif.php?'+ (ZoneActi!='' ? ZoneActi : 'reset=1') + '&' + (ZoneOrigine!='' ? ZoneOrigine:'resetOr=1');
         
   $('#jsLoad').show();
   $.getJSON(url, function(data) { 
         $('#blocResultat').empty();
         $('#blocResultat').append(data.products);
         $('#jsLoad').hide();
   });
  
}

function fancybox(){
	/* Apply fancybox to multiple items */
	$("#pdf").fancybox({
		'transitionIn'	:	'elastic',
		'transitionOut'	:	'elastic',
		'speedIn'		:	600, 
		'speedOut'		:	200, 
		'overlayShow'	:	false,
		'type'         :  'iframe',
      'height'       :  400 
	});
	$('.btnNewsletter,#jsNewsLetter').fancybox({		
      'transitionIn'	:	'elastic',
		'transitionOut'	:	'elastic',
		'speedIn'		:	600, 
		'speedOut'		:	200, 		
   	'overlayShow'	:	false,
	   'type'         :  'iframe',
	   'width'        :  530 ,
      'height'       :  380 
   });
   $('#Map area').fancybox({		
      'transitionIn'	:	'elastic',
		'transitionOut'	:	'elastic',
		'speedIn'		:	600, 
		'speedOut'		:	200, 		
   	'overlayShow'	:	true,
	   'type'         :  'iframe',
	   'width'        :  940,
	   'height'        :  580
   });

}



