// afficher masquer contenu input value formulaires
(function($) {
	$.fn.clearOnFocus = function() {
		function clearOnFocusFocus(event)
		{
			if($(this).val() == $(this).data('clearOnFocus'))
			{
				$(this).val('');
			}
			
			if($(this).attr('on_focus_enable') != '')
      {
        $("#"+$(this).attr('on_focus_enable')).attr('disabled', false)
      }
		}
		function clearOnFocusBlur(event)
		{
			if($.trim($(this).val()) == '')
			{
				$(this).val($(this).data('clearOnFocus'));
				if($(this).attr('on_focus_enable') != '')
        {
          $("#"+$(this).attr('on_focus_enable')).attr('disabled', true)
        }
			}
		}
		return this.each(function()
			{
				if($(this).val() == '')
				{
					$(this).val($(this).attr('default_value'));
				}
				$(this).data('clearOnFocus', $(this).attr('default_value'));
				
				
				//	unbind any previous listeners
				$(this).unbind('focus', clearOnFocusFocus);
				$(this).unbind('blur', clearOnFocusBlur);
				
				//	bind listeners to the functions
				$(this).bind('focus', clearOnFocusFocus);
				$(this).bind('blur', clearOnFocusBlur);
			}
		);
	};
})(jQuery);

$(document).ready(function ()
{
	$('.clearOnFocus').clearOnFocus();
});

// Affichage acces rapide
$(document).ready(function() {
	function megaHoverOver(){
		$(this).find(".sub").stop().fadeTo('fast', 1).show();
			
		//Calculate width of all ul's
		(function($) { 
			jQuery.fn.calcSubWidth = function() {
				rowWidth = 0;
				//Calculate row
				$(this).find("ul").each(function() {					
					rowWidth += $(this).width(); 
				});	
			};
		})(jQuery); 
		
		if ( $(this).find(".row").length > 0 ) { //If row exists...
			var biggestRow = 0;	
			//Calculate each row
			$(this).find(".row").each(function() {							   
				$(this).calcSubWidth();
				//Find biggest row
				if(rowWidth > biggestRow) {
					biggestRow = rowWidth;
				}
			});
			//Set width
			$(this).find(".sub").css({'width' :biggestRow});
			$(this).find(".row:last").css({'margin':'0'});
			
		} else { //If row does not exist...
			
			$(this).calcSubWidth();
			//Set Width
			$(this).find(".sub").css({'width' : rowWidth});
		}
	}
	function megaHoverOut(){ 
	  $(this).find(".sub").stop().fadeTo('fast', 0, function() {
		  $(this).hide(); 
	  });
	}
	var config = {    
		 sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
		 interval: 100, // number = milliseconds for onMouseOver polling interval    
		 over: megaHoverOver, // function = onMouseOver callback (REQUIRED)    
		 timeout: 5, // number = milliseconds delay before onMouseOut    
		 out: megaHoverOut // function = onMouseOut callback (REQUIRED)    
	};
	$("ul#mainNav li .sub").css({'opacity':'0'});
	$("ul#mainNav li").hoverIntent(config);
});

// Tabs 
$(function() {
	$("#tabs").tabs( {fx: { opacity: 'toggle', duration:'normal' }}).tabs("rotate", 2000).addClass('ui-tabs-vertical ui-helper-clearfix');
	$("#tabs li").removeClass('ui-corner-top').addClass('ui-corner-left');
	
	$('#tabs').hover(function(){
    $(this).tabs('rotate', 0, false);
  },function(){
    $(this).tabs({fx: { opacity: 'toggle', duration:'normal' }}).tabs('rotate', 2000);
  });
});

$("#tabs").tabs()

// TOGGLE
$(document).ready(function(){

	//Hide (Collapse) the toggle containers on load
	$(".toggle_container.hidefirst").hide(); 

	//Switch the "Open" and "Close" state per click then slide up/down (depending on open/close state)
	$("h2.trigger").click(function(){
		$(this).toggleClass("active").next().slideToggle("fast");
		return false; //Prevent the browser jump to the link anchor
	});
	$("a.trigger").click(function(){
		if($(this).next().hasClass("active"))
		{
		  $(this).toggleClass("active").next().toggleClass("active").slideToggle("fast");
		}
		else{
  		//ferme les conteneur déjà ouvert
  		$('.toggle_container.active').toggleClass("active").slideToggle("fast");
  		$('.trigger.active').toggleClass("active");
  		$(this).toggleClass("active").next().toggleClass("active").slideToggle("fast");
		}
		return false; //Prevent the browser jump to the link anchor
	});

});

// SCROLLABLE
$(document).ready(function() {
 
//$("#chained").scrollable({circular: true, mousewheel: true}).navigator().autoscroll({
//	interval: 3000		
//});	
});

/**
 *
 * @param {jqObject} the field where the validation applies
 * @param {Array[String]} validation rules for this field
 * @param {int} rule index
 * @param {Map} form options
 * @return an error string if validation failed
 */
function checkQty(field, rules, i, options){
    if (field.val() % field.attr('condit') != 0) {
        // this allows to use i18 for the error msgs
        return "Ce produit ne peut être commandé que par multiple de "+field.attr('condit');
    }
}

//AJAX
function triggerConfirmCart(){
  $("a.confirm_cart_trigger").bind('click', function(){
    qty_field = '#qty' + $(this).attr('sku_article_id');
    if($(qty_field).length > 0)
    {
      if(false === $('#table_references_form').validationEngine('validateField', qty_field))
      {
        $('#modal-window').jqm({ajax:$(this).attr('href')+'?qty='+$(qty_field).val()});
        $('#modal-window').jqmShow();
      }
    }
    else
    {
      $('#modal-window').jqm({ajax:$(this).attr('href')});
      $('#modal-window').jqmShow();
    }
    
    return false;
  });
}

$(document).ready(function() {
	$(".ajax_skus").click(function(){
		ajax_update = '#'+($(this).attr('update'));
		base_url = ($(this).attr('href'));
		ajax_url = base_url+'?template=skus';
		if($.browser.msie == true && $.browser.version == '7.0')
    {
      window.location.href = base_url;
      return false;
    }
	  $.ajax({
      url: ajax_url,
      success: function(data) {
        $(ajax_update).html(data);
        triggerConfirmCart();
      }
    });
  });
});

//oredering modal box
$(document).ready(function() {
  triggerConfirmCart();
});


//table ref width
$(document).ready(function() {
if ( $(".wrap_table_references_fiche_produit").width() > 522 )
  {$(".table_references").width(936);} else {$(".table_references").width(520);}
});

$(document).ready(function() {
  $('.buy_multi').bind('click', function(el){
    $("#"+$(this).attr('open')).click();
    return false;
  })
});


function ajaxToDiv(class_name)
{
	if ( class_name === undefined ) {
		class_name = '.ajax_to_div';
	}
	$(class_name).bind('click', function(){
    ajax_update = '#'+($(this).attr('to_div'));
    ajax_url = ($(this).attr('href'));
    $.ajax({
      url: ajax_url,
      success: function(data) {
        $(ajax_update).html(data);
      }
    });
    return false;
  });
}

$().ready(function() {
  ajaxToDiv('.ajax_to_div');
});


//floating table header
function UpdateTableHeaders() {
  $("div.divTableWithFloatingHeader").each(function() {
      var originalHeaderRow = $(".tableFloatingHeaderOriginal", this);
      var floatingHeaderRow = $(".tableFloatingHeader", this);
      var offset = $(this).offset();
      var scrollTop = $(window).scrollTop();
      if ((scrollTop > offset.top) && (scrollTop < offset.top + $(this).height())) {
          floatingHeaderRow.css("visibility", "visible");
          floatingHeaderRow.css("top", Math.min(scrollTop - offset.top, $(this).height() - floatingHeaderRow.height()) + "px");

          // Copy cell widths from original header
          $("th", floatingHeaderRow).each(function(index) {
              var cellWidth = $("th", originalHeaderRow).eq(index).css('width');
              $(this).css('width', cellWidth);
          });

          // Copy row width from whole table
          floatingHeaderRow.css("width", $(this).css("width"));
      }
      else {
          floatingHeaderRow.css("visibility", "hidden");
          floatingHeaderRow.css("top", "0px");
        }
    });
}

$(document).ready(function() {
    $("table.tableWithFloatingHeader").each(function() {
      $(this).wrap("<div class=\"divTableWithFloatingHeader\" style=\"position:relative\"></div>");

      var originalHeaderRow = $("tr:first", this)
      originalHeaderRow.before(originalHeaderRow.clone());
      var clonedHeaderRow = $("tr:first", this)

      clonedHeaderRow.addClass("tableFloatingHeader");
      clonedHeaderRow.css("position", "absolute");
      clonedHeaderRow.css("top", "0px");
      clonedHeaderRow.css("left", $(this).css("margin-left"));
      clonedHeaderRow.css("visibility", "hidden");

      originalHeaderRow.addClass("tableFloatingHeaderOriginal");
    });
    UpdateTableHeaders();
    $(window).scroll(UpdateTableHeaders);
    $(window).resize(UpdateTableHeaders);
});


// "carousel" de valeurs exemple dans le champs recherche du header
$(document).ready(function() {
	if($("#text_recherche_header").val() == $("#text_recherche_header").attr('default_value'))
	{
  	var i = 0;
  	var mytimer = window.setInterval(function(){
        var exemples = new Array("Recherche: lavabo","Recherche: baignoire 1M70","Recherche: 43130509","Recherche: CH88","Recherche: tube cuivre","Recherche: porcher","Recherche: de dietrich","Recherche: tubage","Recherche: radiateurs","");
        $("#text_recherche_header").val(exemples[i++]);
        if(i==9) i=0;
        }
        ,1500);
    $("#text_recherche_header").click(function() {
      window.clearInterval(mytimer);
      if (this.value=="Recherche: lavabo") this.value = ""; 
      if (this.value=="Recherche: baignoire 1M70") this.value = ""; 
      if (this.value=="Recherche: 43130509") this.value = ""; 
      if (this.value=="Recherche: CH88") this.value = ""; 
      if (this.value=="Recherche: tube cuivre") this.value = "";
      if (this.value=="Recherche: porcher") this.value = ""; 
      if (this.value=="Recherche: de dietrich") this.value = ""; 
      if (this.value=="Recherche: tubage") this.value = ""; 
      if (this.value=="Recherche: radiateurs") this.value = ""; 
      if (this.value=="Recherche") this.value="";
      });
	}
});
  
$(document).ready(function() {
	$('#modal-window').jqm({ajax:'@href', trigger: 'a.modal_trigger'});
	$('#modal-popup-window').jqm();
});

