jQuery.fn.goCollapse = function(zone, visible) {
    if(visible) {
        $(this).prepend('<span class="collapse_moins">');
    }
    else {
        $(this).prepend('<span class="collapse_plus">');
        zone.hide();
    }
    
    $(this)
        .find('span')
            .click(function() {
                $(this).toggleClass('collapse_moins').toggleClass('collapse_plus');
                zone.toggle();
            });
};

jQuery.fn.goEditable = function(settings) {
    settings = jQuery.extend({
        text: 'Cliquez ici pour ajouter du contenu'
    }, settings);
    
    if($(this).val() != '') {
        var val = $(this).val();
        $(this)
            .css('border', '1px solid white')
            .mouseover(function() { $(this).css({ border: '1px solid silver', background: '#edfebe' }); })
            .mouseout(function() { $(this).css({ border: '1px solid white', background: 'white' }); })
            .click(function() { $(this).css({ border: '1px solid silver', background: 'white' }).unbind(); });
    }
    else {
        var html = $(this).parent().html();
        $(this).parent().html('<a href="#">'+settings.text+'</a>').find('a').click(function() { $(this).parent().html(html); });
    }
};

String.prototype.trim = function() {
a = this.replace(/^\s+/, '');
return a.replace(/\s+$/, '');
};

function isNumeric(sText) {
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;
 
   for (var i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
 }  
function checkOblig(){	
	var nb_error = 0;
	$('.oblig')
		.each(function() {
          	var data = $(this).val();
              if(data.trim() == '') { // champ vide
              
                  $(this)
                      .addClass('error')
                      .focus(function() { $(this).removeClass('error'); });   
                  nb_error++;                  
              }
          });
    if(nb_error != 0) {
              alert('Merci de bien vouloir renseigner tous les éléments de votre adresse de livraison');
              scrollTo(0,0);
              return false;
          }
   return true;
}
$(document).ready(function() {	
	jQuery.each($('.mr_sp_img > img'), function(i, val) {
      img_width = $(this).attr('width');
      img_height = $(this).attr('height');
      midle_frame_width = img_width - 10;
      midle_frame_height = img_height - 10;
      $('>.rounded',this.parentNode).css('width',midle_frame_width+32+'px');
      $('>.rounded > .tm',this.parentNode).css('width',midle_frame_width+'px');
      $('>.rounded > .bm',this.parentNode).css('width',midle_frame_width+'px');
      
      $('>.rounded > .ml',this.parentNode).css('height',midle_frame_height+'px');
      $('>.rounded > .mr',this.parentNode).css('height',midle_frame_height+'px');
      
      $('>.rounded >.mm',this.parentNode).css({'width':midle_frame_width+'px','height':midle_frame_height+'px'});
      //centering .rounded   
      rounded_left = ($(this.parentNode).width()/2)-($('>.rounded',this.parentNode).width()/2);
      $('>.rounded',this.parentNode).css({'left':rounded_left});      
      img_left = ($(this.parentNode).width()/2)-(img_width/2);
      $(this).css({'left':img_left});
      //middle .rounded & img
      //alert(($(this.parentNode).height()/2)+'-'+($('>.rounded',this.parentNode).height()/2));
      rounded_top = ($(this.parentNode).height()/2)-($('>.rounded',this.parentNode).height()/2);
      $('>.rounded',this.parentNode).css({'top':rounded_top});
      img_top = ($(this.parentNode).height()/2)-(img_height/2);
      $(this).css({'top':img_top});
       $('>.rounded',this.parentNode).show();
    });
    $(this)
        .find('form')
            .submit(function() { // validation des champs obligatoires
                var nb_error = 0;
                $(this)
                    .find('.oblig')
                        .each(function() {
                        	var data = $(this).val();
                            if(data.trim() == '') { // champ vide
                                $(this)
                                    .addClass('error')
                                    .focus(function() { $(this).removeClass('error'); });   
                                nb_error++;
                            }
                        })
                    .end();
                if(nb_error != 0) {
                    alert('Merci de bien vouloir renseigner tous les éléments encadrés en rouge');
                    
                    scrollTo(0,0);
                    return false;
                }
                
                return true;
            })
        .end();
		
    /***************************************************************************
     * To check  letter and more than 10 products 
     **************************************************************************/
    $('form#form-shoping-cart').submit(function() { 
    	
                var nb_error = 0;
                var nb_empty_cart = 0;
                var nb_empty =0;
                $(this)
                    .find('.num_product')
                        .each(function() {
                        	var num = $(this).val(); 
							  // alert(num);                    	
                        	if(num == 'cart_empty'){
                        		$(this)
                                    .addClass('error')
                                    .focus(function() {  $(this).removeClass('error'); }); 
								nb_empty_cart++;	
							}
							if(isNumeric(num)== false || num==0 || num==''  ){
								$(this)
                                    .addClass('error')
                                    .focus(function() { $(this).val(''); $(this).removeClass('error');});  
                                    
								nb_empty++;
							}
                            if( num> 10 || num <0  ) { // champ vide
                                $(this)
                                    .addClass('error')
                                    .focus(function() { $(this).val(''); $(this).removeClass('error'); }); 
                                nb_error++;
                            }
                        })
                    .end();
                if(nb_empty_cart != 0){ 
                    alert('Votre panier est vide.');  					 
                    scrollTo(0,0);
                    return false;
                }    
                if(nb_empty != 0) {  
                	alert('Veuillez saisir une quantite.');                
                    scrollTo(0,0);
                    return false;
                }    
                
                if(nb_error != 0) {
                    alert('Vous ne pouvez commander que 10 éléments maximum.\nEn cas de demande supérieure, contacter le service client.');
                    scrollTo(0,0);
                    return false;
                }
        return true;
    });
    
    
    $('#menu-left-ul > li a').mouseover(function(){
    	img = "<img src='/_design/home/menu-left-li-roll-over.png' id='menu-left-li-roll-over'/>";
    	$(this).after(img);
    }).mouseout(function(){ $('#menu-left-li-roll-over').remove();});
     //set width for .flexible_list_title
    var flexible_list_title_width = 0;    
    $.each($('.flexible_list_title'), function() {
    	if($(this).width()>flexible_list_title_width)
    		flexible_list_title_width = $(this).width();
    });
    $('.flexible_list_title').width(flexible_list_title_width);
    //set class pair or impair to table or li list
	autoPairClass();
	//button play
	$('.mh_jouer').mouseover(function(){
		$('#mh_jouer').hide();
		$('#mh_jouer_over').css('visibility','visible');
	}).mouseout(function(){
		$('#mh_jouer').show();
		$('#mh_jouer_over').css('visibility','hidden');
	});
	//special content col1
	$.each($('.cp_bg > div:first-child'), function(i, val) {
		$.each($('> .cp_title:first-child',this), function(i, val) {
			if(($(this.parentNode).html().substr(0,22)).match('cp\_title')){
					$(this).children(":first").removeClass("cp_bg_top");
					$(this).children(":first").addClass("cp_bg_top_abs");
			}
		});
		$.each($('> .cp_title',this), function(i, val) {
			image_class = $(this.parentNode).children(":first").attr('class');
			if(image_class=='img_bottom_left'||image_class=='img_bottom_right'||image_class=='img_top_left'||image_class=='img_top_right'){
				back_up_div = $(this.parentNode).children(":first");
				$(this.parentNode).children(":first").remove();
				if(($(this.parentNode).html().substr(0,22)).match('cp\_title')){
						$(this).children(":first").removeClass("cp_bg_top");
						$(this).children(":first").addClass("cp_bg_top_abs");
				}
				$(this.parentNode).prepend(back_up_div);
			}
		});
    });

	//special content col2
	
	$.each($('.cp_wrapper1'), function(i, val) {
		$.each($('> div',this), function(i, val) {
			$.each($('> .cp_title:first-child',this), function(i, val) {
				if(($(this.parentNode).html().substr(0,22)).match('cp\_title')){
						$(this).children(":first").removeClass("cp_bg_top");
						$(this).children(":first").addClass("cp_bg_top_abs");
				}
			});
		});
	});
	//special content col3
	
	$.each($('.cp_wrapper2'), function(i, val) {
		$.each($('> div',this), function(i, val) {
			$.each($('> .cp_title:first-child',this), function(i, val) {
				if(($(this.parentNode).html().substr(0,22)).match('cp\_title')){
						$(this).children(":first").removeClass("cp_bg_top");
						$(this).children(":first").addClass("cp_bg_top_abs");
				}
			});
		});
	});
    //cal height of cp_home_bg
    var height = 0;
    var clone_height = 0;
    var obj_height = 0;
    var one_line_height = 14;
    var img_height = $('#height_img').val()-48;
    var obj_height_default = 30;
    var margin_top = -5;
    var margin_bottom = 0;//13+27=40
    var one_line_length = 25;//'This is a first course in'.length;
    var one_line_length_obj = 14;//'Help & support'.length;
	$.each($('.cp_home_wrapper'), function(i, val) {
		if(this.clientHeight> clone_height){
			clone_height = this.clientHeight;
			obj_height = ((TrimString($('> h1',this).text()).length)/one_line_length_obj)*obj_height_default;
			height = $('> .content_text',this).height()+margin_top+img_height+obj_height+margin_bottom;
		}
    });
	$('.cp_home_bg').css('height',height+'px');

	$('.ml-li3').mouseover(function(){
		if(($(this.parentNode.parentNode).attr('class')).match('ml-li2-selected')){
			$(this.parentNode.parentNode).css({'background':'transparent url(/_design/home/li_bg.jpg) no-repeat scroll left top'})
			$('> a.class_menu_level2',this.parentNode).css({'color':'#009900'});
		}
	});
});
function autoPairClass(){//parent_class_name,tag_child
	parent_class_name = arguments[1]?arguments[1]:'auto_pair';
	tag_child = arguments[2]?arguments[2]:'tr';
	jQuery.each($("."+parent_class_name+" > "+tag_child), function(i, val) {
		$(this).attr('class',(i%2?'impair':'pair'));
    });
}
function TrimString(stringToTrim){
 return stringToTrim.replace(/^\s+|\s+$/g,"");
}

/**********************************************************************************
 * To remove all accent characters, replace space by hiphen and return small letter  
 **********************************************************************************/
function removeAccents(str) {
	
	str = str.toLowerCase();

	str = str.replace(/[\u00E0\u00E1\u00E2\u00E3\u00E4\u00E5]/g,'a');
	str = str.replace(/[\u00E7]/g,'c');
	str = str.replace(/[\u00E8\u00E9\u00EA\u00EB]/g,'e');
	str = str.replace(/[\u00EC\u00ED\u00EE\u00EF]/g,'i');
	str = str.replace(/[\u00F2\u00F3\u00F4\u00F5\u00F6\u00F8]/g,'o');
	str = str.replace(/[\u00F9\u00FA\u00FB\u00FC]/g,'u');
	str = str.replace(/[\u00FD\u00FF]/g,'y');
	str = str.replace(/[\u00F1]/g,'n');
	str = str.replace(/[\u0153]/g,'oe');
	str = str.replace(/[\u00E6]/g,'ae');
	str = str.replace(/[\u00DF]/g,'ss');

	str = str.replace(/[^a-z0-9_\s\'\:\/\[\]-]/g,'');
	str = str.replace(/[\s\'\:\/\[\]-]+/g,' ');
	str = str.replace(/[ ]/g,'-');

	return str;
	
}

function minString(obj,val){
	//obj.length;	
	if($(obj).val().length < val) {
		return $(obj).attr('alt')+' require at least '+(val)+' characters';
	}else{return true;}
	
}

pngfix_=function(els){
	if($.browser.msie && $.browser.version>6 || !$.browser.msie)return;
	var ip=/\.png/i;
	var i=$(els).size();
	while(i-- >0){
		var el=$(els).size()>1?els[i]:els;
		var es=el.style;		
		if(el.src&&el.src.match(ip)&&!es.filter){
			es.height=el.height;
			es.width=el.width;
			es.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+el.src+"',sizingMethod='crop')";
			el.src=clear;
		}else{
			var elb=el.currentStyle.backgroundImage;
			if(elb.match(ip)){
				var path=elb.split('"');
				var rep=(el.currentStyle.backgroundRepeat=='no-repeat')?'crop':'scale';
				es.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+path[1]+"',sizingMethod='"+rep+"')";
				//alert(el.clientHeight+"=="+$(el).height()+'cssheight:'+$(el).css('height'));
				es.height=$(el).height();
				es.backgroundImage='none';
				//$('#mh_jouer').text('=>'+es.ClassName+'<=');	
				/*
				var elkids=el.getElementsByTagName('*');
				if (elkids){
					var j=elkids.length;
					if(el.currentStyle.position!="absolute" && el.currentStyle.position!="relative")es.position='static';
					while (j-- >0)
						if(!elkids[j].style.position)
							elkids[j].style.position="relative";
				}*/
			}
		}
	}
}

function v_align(obj){
	var plus_h = arguments[1]?arguments[1]:0;
	jQuery.each($(obj), function(i, val) {
		if($(this).html().trim()!=""){
	      //var item_height = $(this).attr('height')>0?$(this).height():33;
	      var item_height = $(this).height()>0?$(this).height():33;
	      var item_top = ($(this.parentNode).height()/2)-(item_height/2);
	      //alert($(this).text()+'=>item_height='+item_height+' $(this.parentNode).height()='+$(this.parentNode).height());
	      if(item_top<=0){item_top=0;}
	      $(this).css({'top':item_top+plus_h});
    	}
     
    });
}
function IsNumeric(inputVal) {
     if (isNaN(parseFloat(inputVal))) {
          return false;
     }
     return true
}
/*function Preload() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=Preload.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}*/
function doPreload(){
	Preload('/_design/home/jouter_over.png','/_design/home/inscription_btn.png');
}
function Preload() { //v3.0
  var d=document; 
  if(d.images){ 
  	if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=Preload.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){
    	//d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];
    	$('body').append('<img src="'+a[i]+'" class="preload" />');
    }
   }
}

function submitFrm(idfrm){
  /*
  alert(idfrm);
  $('#'+idfrm).trigger("submit");*/
   //$('#'+idfrm).submit();
   document.forms[idfrm].submit();
   
}
/*	arguments[1]: get obj to toggle Active class
	arguments[2]: get text to toggle text
*/
function showHideDiv(id_lastname){
	
	if(arguments[1]){
		var obj = arguments[1];
		$(obj).toggleClass("active");
	}
	if(arguments[2]){
		var obj = arguments[1];
		var new_text = arguments[2];
		//append input tag for storing val
		if($.trim($('#origin_'+id_lastname).html())==''){
			$('body').append('<div class="hided" id="origin_'+id_lastname+'">'+$(obj).html()+'</div>');
		}
		if($.trim($('#new_'+id_lastname).html())==''){
			$('body').append('<div class="hided" id="new_'+id_lastname+'"><span></span>'+new_text+'</div>');
		}
		//toggle text
		($(obj).attr('class')).match('active')?$(obj).html($('#new_'+id_lastname).html()):$(obj).html($('#origin_'+id_lastname).html());
		
	}
	if(($(obj).attr('class')).match('active')){
		$('#div_msg_'+id_lastname).hide();
		$('#div_msg_'+id_lastname+'_error').hide();
	}
	$('#block_modify_'+id_lastname).slideToggle('fast');	
	$('#div_modify_'+id_lastname).slideToggle('fast');
	
	//$('#button_'+id_lastname+'_after_click').toggle();
	//$('#button_'+id_lastname).toggle();
	
	reEmbedButton();
}
function ajaxPost(idfrm,id_lastname,url_page){
	validation_ok = true;
	$.each($(".error",$('#'+idfrm)), function(i, val) {
		if($(this).css('display')=='block') validation_ok = false;
	});
	if(validation_ok){
		var timeout = null;
		var delay_sms_show = 2000;
		$.ajax({
		   type: "POST",
		   url: url_page,
		   data: $('#'+idfrm).formSerialize(),
		   beforeSend: function(data){
				$('#div_msg_'+id_lastname+'_error').hide();
		   },
		   error: function(data){
		   },
		   success: function(data){
		   	data = eval(data);
		   	status = $(data).attr('status');
		   	if(status==1){
		   		//$('#div_modify_'+id_lastname).hide('fast');
		   		$('#div_msg_'+id_lastname).text($(data).attr('msg'));
		   		$('#div_msg_'+id_lastname).css({'color':'green'});
		   		$('#div_msg_'+id_lastname).slideDown('fast');
		   		//$('#button_'+id_lastname+'_after_click').toggle();
				//$('#button_'+id_lastname).toggle();			
				if (timeout) clearTimeout(timeout);	
				setTimeout(function(){
					if($(data).attr('id_replace_text')!=""){
						$('#'+$(data).attr('id_replace_text')).html($(data).attr('val_replace_text'));
					}
		   			//$('#div_modify_'+id_lastname).show('fast');
		   			//$('#div_msg_'+id_lastname).hide('fast');
		   			//$('#th_bt_'+id_lastname).click();
			    }, delay_sms_show);
			    
		   	}else{
		   		$('#div_msg_'+id_lastname+'_error').text($(data).attr('msg'));
		   		$('#div_msg_'+id_lastname+'_error').css({'color':'red','margin':'0 0 10px'});
		   		$('#div_msg_'+id_lastname+'_error').slideDown('fast');
		   	}
		   		   	
		   },
			async: false
		 });
	 }
}
function reEmbedButton(){
	sIFR.replace(VAGRundschriftD, {
	  	selector: '.btn_check',
		css: ['.sIFR-root { font-size: 11px; color: #9c7865; width: 50px; height: 24px; text-align: center; text-transform: uppercase; cursor: pointer;  background-color: #3D2F28;}',
			'a { color: #9c7865; text-decoration: none;}',
	        'a:link { color: #9c7865; }',
			'a:hover { color: #1edad5; }'
		],
			  wmode: 'window',
			  tuneHeight: '-5',
			  selectable: false,
			forceSingleLine: true
	});
}