

function ajoutsupqte(obj,id){
	var limite = -1;

	if(isNaN(jQuery(id).val()) == true) jQuery(id).attr("value","0");

	var minvalue = 1;  	// valeur par defaut
	var maxvalue = 100; 	// valeur par defaut
	var value = 1;		// valeur par defaut

	if(!(isNaN(jQuery(id).attr("value")))) {
		value = parseInt(jQuery(id).attr("value"));
	}

	// Lors du rechargement du panier, on interdit la mise à jours des quantités
    if(jQuery(id).hasClass("qty-gray")) {
        return false;
    }

	var valueUpdated = true;
	if( jQuery(obj).attr("name") == "incremente" && value < maxvalue ) {
		value++;
	} else if( jQuery(obj).attr("name") == "decremente" && value > minvalue ) {
		value--;
	}
	else {
		valueUpdated = false;
	}
	jQuery(id).attr("value", value);

    if(valueUpdated) {
        if(jQuery(id).parent().parent().parent().parent().attr('id') == 'shopping-cart-table') {
            lockCart();
            // On programme la mise à jour automatique du panier
            scheduleRefreshCart();
        }
    }

	return false;
}

function lockCart()
{
    // On grise le bouton "Valider mon panier"
    jQuery('.validation_button').attr("disabled", true);
    jQuery('.validation_button').addClass("gray");
}

function scheduleRefreshCart()
{
    // Si un mise à jour du panier est programmée, on la stop
    jQuery('body').stopTime('cart_refresher_timer');

    // On programme la mise à jour du panier pour dans deux secondes
    jQuery('body').oneTime(2000, 'cart_refresher_timer', function() {
        // On grise les quantitées
        jQuery('.qte').addClass("qty-gray");

        // On lock le panier
        refreshAlertAndLockCart();

        // On met à jour le panier
        //jQuery('#refreshButton').click();
        jQuery('#cart-list').submit();
    });
}


function refreshAlertAndLockCart()
{
    shadow = document.createElement('div');
    shadow.style.height       = document.body.offsetHeight + 100 + "px" /* pourquoi FF ne retourne pas la véritable hauteur de la page */;
    $(shadow).addClassName("refresh-cart-shadow");

    message = document.createElement('div');
    $(message).addClassName("refresh-cart-box-parent");

    content = document.createElement('div');
    $(content).addClassName("refresh-cart-box");

    loader = document.createElement('div');
    $(loader).addClassName("refresh-cart-loader");

    content.appendChild(loader);
    content.appendChild(document.createTextNode('Mise à jour du panier'));
    content.appendChild(document.createElement('br'));
    content.appendChild(document.createTextNode('Veuillez patienter'));
    message.appendChild(content);
    $(document.body).appendChild(shadow);
    $(document.body).appendChild(message);
}


function verifForm(cible, texte) {
	if(cible.value == texte) cible.value = "";
}
function setValueIfEmpty(cible, texte) {
	if(cible.value == '') cible.value = texte;
}

/*
 * Gestion de la regeneration du captcha
 */
function renewCaptcha() {

	if ( $('captcha_renew_url') ) {
		var captchaContainerId = 'captcha-container';
		var captchaUrl = $('captcha_renew_url').value;

		var updater = new Ajax.Updater(captchaContainerId, captchaUrl, {
			method: 'get',
			onComplete: function(){},
	    	onFailure: function() {alert('Impossible de regénérer le captcha.');},
	    	onSuccess: function() {$('captcha').value = '';}

		});
	}
}

/*
 * Gestion du comportement Fiche Article et QuickLook
 */
function selectMagentoDropDownItemByValue(lDropDownId, lvalue, isInitialisation, lProductModelId) {

	var options   = jQuery("#"+lDropDownId).children("option");
	var foundItem = false;
	if ( options.length > 0 ) {
		for(var i=0;i<options.length;i++){
			option = options[i];
			if ( jQuery(option).attr("value") == lvalue ) {
				jQuery(option).attr("selected", "selected");
				jQuery("#"+lDropDownId).selectedIndex = i;
				var textAttribute = false;
				if(lDropDownId.substr(lDropDownId.length-3, 3) == '558'){
					textAttribute = jQuery('#color_label_'+lProductModelId);
				}
				else{
					textAttribute = jQuery('#size_label_'+lProductModelId);
				}
				textAttribute.text(option.text);
				foundItem = true;
			}
		}
	}

	spConfig[lProductModelId].configureElement(document.getElementById(lDropDownId), isInitialisation);
	return foundItem;
}

//Selectionne la couleur et taille par defaut lors de l'affichage de la page
function loadDefaultSelectedValues(isInitialisation, isQl) {
	var formClass = ".product_addtocart_form";
	if(isQl)
		formClass = "#quick-look-product .product_addtocart_form";

	jQuery(formClass).each(function(){
		var modelId = this.id.split('_')[3];

		var couleurAttrId	  = jQuery("#couleur-attribute-id").attr("value");

		var couleurDropDownId = "attribute-"+modelId+"-"+couleurAttrId;

		selectMagentoDropDownItemByValue( couleurDropDownId, productDefaultAttributeValues.couleurWeb, isInitialisation, modelId);

		var tailleAttrId	= jQuery("#taille-attribute-id").attr("value");

		var tailleDropDownId = "attribute-"+modelId+"-"+tailleAttrId;

		selectMagentoDropDownItemByValue( tailleDropDownId, productDefaultAttributeValues.tailleWeb, isInitialisation, modelId);

	});

}

/* Gestion des couleurs produit */
function gestionCouleur() {

	jQuery("ul.couleurs-liste li").click(function(){

		var IdSplit = new Array();
		jQuery(this).attr("id").scan(/[\d]+/, function(match) { IdSplit.push(match[0]) });
		var couleurOptionId 	= IdSplit[0];
		var lProductModelId 	= IdSplit[1];
		var lProductArticleId 	= IdSplit[2];
		return changerCouleur(couleurOptionId, lProductModelId, lProductArticleId);
	});
}

function changerCouleur(couleurOptionId, lProductModelId, lProductArticleId){
	var idCouleur = "#puce"+couleurOptionId+"-"+lProductModelId+"-"+lProductArticleId;
	var couleurAttrId		= jQuery("#couleur-attribute-id").attr("value");
	var reg = new RegExp('^<div>(.*)</div>$');
	var respMedia = false;
	var respPrice = false;
	if(productview[lProductModelId]['media'])
	{
		productview[lProductModelId]['media'][couleurOptionId].content.scan(reg,function(match){
			if(match.size() == 2) respMedia = match[1];
		});
	}

	if(respMedia != false)
	{
		var useIE8 = false;
		if($('annitate_on_ie8').innerHTML == 'false') {
			if(navigator.appName == 'Microsoft Internet Explorer') {
				var patern = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
				if (patern.exec(navigator.userAgent) != null) {
					if(parseFloat(RegExp.$1) == 8) {
						useIE8 = true;
					}
				}
			}
		}
		if(!useIE8) {
			$('product-media-container-'+lProductModelId).style.opacity = 0.1;
		}
		$('product-media-container-'+lProductModelId).update(respMedia);
		if(!useIE8) {
			Effect.Fade($('product-media-container-'+lProductModelId), { duration: 0.5, from: 0.1, to: 1 });
		}

	}

	if(productview[lProductArticleId])
	{
		productview[lProductArticleId].price.scan(reg,function(match){
			if(match.size() == 2) respPrice = match[1];
		});
	}

	if(respPrice != false)
	{
		$('simpleconfigurable-block-price-'+lProductModelId).update(respPrice);
	}

	/* Selection de la valeur correspondante dans la liste déroulante des options (cachée) */
	var couleurDropDownId = "attribute-"+lProductModelId+"-"+couleurAttrId;

	var options = jQuery("#"+couleurDropDownId).children("option");

	if ( options.length > 0 ) {
		jQuery(".input-box").removeClass('validation-error');
		jQuery(".input-box").children('.validation-advice').hide();

		selectMagentoDropDownItemByValue( couleurDropDownId,couleurOptionId, false, lProductModelId);
	}

	jQuery("ul#couleurs-"+lProductModelId+" li").removeClass('actived').removeClass('rouge-border').removeAttr('style').ifixpng();
	jQuery(idCouleur).addClass('actived rouge-border').removeAttr('style').ifixpng();
	jQuery('#couleur-name-' + lProductModelId).html(jQuery(idCouleur + ' a').html());

	var cible = jQuery(idCouleur).children('a').attr("href");

	var imgCible = "p.product-image #image-"+lProductModelId;
	if (jQuery(idCouleur).parents("div.coupdoeil-fiche").length > 0) imgCible = "p.product-image #image2";

	if( !jqBrowserIsIe )
	{
	  jQuery(imgCible).fadeOut("fast", function () {
		jQuery(idCouleur).attr("src",cible).fadeIn("fast");
	  });
	}
	handleColorChoosedSelectDefaultSize(lProductModelId);
	/*
	if(typeof(categoryUrl) != 'undefined'){
		jQuery('#quicklook-iframe-container .fiche-detail').click(function(){
			var hrefFicheDetail = jQuery(this).attr('href');
			if(hrefFicheDetail.slice(0,1) == '#'){
				var artParam = '?article=' + jQuery('#product_addtocart_form_'+lProductModelId+' input[name=\'product\']').attr('value');
				jQuery(this).attr('href',(categoryUrl+'/'+hrefFicheDetail.slice(1)+artParam));
			}
		});
	}
	*/
	return false;
}


function handleColorChoosedSelectDefaultSize(lProductModelId) {

	var tailleAttrId	= jQuery("#taille-attribute-id").attr("value");

	/* Selection de la valeur correspondante dans la liste déroulante des options (cachée) */
	var tailleDropDownId = "attribute-"+lProductModelId+"-"+tailleAttrId;

	var options = jQuery("#"+tailleDropDownId).children("option");

	var itemWasFound = selectMagentoDropDownItemByValue( tailleDropDownId, productDefaultAttributeValues.tailleWeb, false, lProductModelId);

	if(!itemWasFound && options.length >= 1)
	{
		selectMagentoDropDownItemByValue(tailleDropDownId,jQuery("#"+tailleDropDownId+" option:first").attr('value'), false, lProductModelId);
	}
}

/* Gestion des multiples images produit
 * @TODO Pourrait n'être appelé que si on est dans une fichie produit avec plusieurs images ...
 */
function gestionImages() {
	jQuery("ul.imagesgalerie li").click(function(e){

		var cible	  = jQuery(this).children('a').attr("href");
		var zoomImage = jQuery(this).children('a').children('input').attr("value");

		//setJqZoomImage(cible,zoomImage,'titre');

		var current = jQuery('#main-image #image').attr("src");
		if (cible == current) {
		  return false;
		}
		else {
			jQuery(".jqZoomWindow").remove();
			jQuery(".jqZoomPup").remove();
			jQuery(".image-zoom").remove();

			jQuery('img.feature').remove();

			jQuery('#product-image').append('<a href="'+zoomImage+'" class="product-image image-zoom" id="main-image" style="margin: 0; padding: 0px;"><img src="'+cible+'" class="feature" id="image" alt="" /></a>');
			if(typeof(zoom.width) != 'undefined' && typeof(zoom.height) != 'undefined'){
				jQuery('#product-image a').jqzoom({
				  zoomType: 'standard',
				  zoomWidth: zoom.width,
				  zoomHeight: zoom.height,
				  xOffset: zoom.xOffset,
				  yOffset: zoom.yOffset,
			      showEffect:'fadein',
			      hideEffect:'fadeout',
			      fadeoutSpeed: '100',
			      fadeinSpeed: '300',
			      lens: true,
			      title :false
			    });
			}
		}

		e.stopPropagation();

		return false;
	});
}

function gestionNewsletter() {

	jQuery('#newslettershowForm').click(function(e) {

		jQuery('#mininewsletterform').show();
		jQuery('#nlsmessage').hide();
		e.stopPropagation();
		return false;
	});
}

var jqBrowserIsIe = false;

jQuery(document).ready(function(){
    //alert(" Debut ready()");

	jQuery.each(jQuery.browser, function(i, val) {

		      //Si gestion transparence tous navigateurs sauf IE, mettre la condition.
			  //Du au probleme sur Firefox 3.5, aucune transparence sur aucun navigateurs.
			  //if(i=="msie" && val==true){
			  if(true)
			  {
			  jqBrowserIsIe =true;
			  }
	});

	 jQuery.fn.extend({
		//Gestion du menu sous catégorie : mettre la class du li à "current" pour activer le menu au chargement
         menu_accordion: function() {

            return this.each(function() {

            	if(jQuery(this).data('accordiated'))
					return false;

				jQuery.each(jQuery(this).find('ul, li>div'), function(){
					jQuery(this).data('accordiated', true);
					jQuery(this).hide();
				});

				jQuery.each(jQuery(this).find('h2:not(.foo)'), function(){
					jQuery(this).click(function(e){
						activate(e.target);
						return void(0);
					});
				});

				jQuery.each(jQuery(this).find('h2:not(.foo) img'), function() {
					jQuery(this).click(function(e) {
						activate(jQuery(e.target).parent());
						return void(0);
					});
				});

				var active = false;

				if(jQuery(this).find('li.current'))	{
					//console.log(jQuery(this).find('li.current'));
					active = jQuery(this).find('li.current a')[0];
				}

				if(active){ // Si une familleweb est sélectionnée
					activate(active, 'toggle', 'parents');
					jQuery(active).parents().parents().show();
				}
				else { // Sinon on regarde si des N+1 doivent être ouvertes
					if(jQuery(this).find('li.activate'))	{
						active = jQuery(this).find('li.activate ul')[0];
					}
					if(active == undefined ){	// on regarde l'ancre pour ouvrir une N+1
						var ancre = getAncre();
						if(ancre){
							if(jQuery(ancre)){
								active = jQuery('#category_'+ancre)[0];
							}
						}
					}
					if(active){
						activate(active, 'toggle', 'parents');
						jQuery(active).show();
					}
				}

				function activate(el, effect, parents){
					if(el.id) {
						// L'el est il la flèche ou l'h2 ?
						if(!$('fleche_' + el.id + '_off')) {
							el = jQuery('#' + el.id).parent().parent();
							el.id = el.attr('id');
						}
						// On ferme toute les fleches
						jQuery('.fleche_on').hide();
						jQuery('.fleche_off').show();

						// On ouvre la bonne fleche
						if(!jQuery('#' + el.id).parent().hasClass('active')) { // Ouverture
							jQuery('#fleche_' + el.id + '_off').hide();
							jQuery('#fleche_' + el.id + '_on').show();
						}
						//else { // Fermeture
						//	jQuery('#fleche_' + el.id + '_off').show();
						//	jQuery('#fleche_' + el.id + '_on').hide();
						//}
					}
					jQuery(el)[(parents || 'parent')]('li').toggleClass('active').siblings().removeClass('active').children('ul, div').slideUp('fast');
					jQuery(el).siblings('ul, div')[(effect || 'slideToggle')]((!effect)?'fast':null);
				}
            });
        }
		// fin gestion menu
    });
    //*/


	function getAncre() {
	    var loc = window.location;
	    if(loc.hash){
	    	$posId = loc.hash.lastIndexOf('_');
	    	return loc.hash.substring($posId+1);
	    }
	    else
	    	return false;
	}

	/* gestion de l'aide de l'info bulle pour la newsletter */
	/*jQuery("#infonewsletter").hide();

	jQuery("#newsletter-validate-detail .info").click(function () {
		jQuery("#infonewsletter:hidden").fadeIn("slow");
	  return false;
    });

	jQuery("#infonewsletter .info-close").click(function () {
      jQuery("#infonewsletter").fadeOut("fast");
	  return false;
    });
	 */

	/* ********************************** */
	/* lancement au chargement de la page */
	/* ********************************** */

	jQuery('#newsletter-validate-detail a.info').cluetip({attribute: 'href', width: 334, positionBy: 'bottomTop', leftOffset: 0,  topOffset: 25});
	jQuery('.moncompte a.info').cluetip({attribute: 'href', width: 334, leftOffset: 0, topOffset: 90});
	jQuery('.account-create a.info').cluetip({attribute: 'href', width: 334, leftOffset: 0, topOffset: 90});
	jQuery('#checkout-step-billing a.info').cluetip({attribute: 'href', width: 334, leftOffset: 23, topOffset: -50,positionBy:'fixed'});

	jQuery('#login-form a.popin-mdp').cluetip({attribute: 'href', width: 334, leftOffset: 10, topOffset: -50,positionBy:'fixed'});
	jQuery('#login-form a.popin-mdp-top').cluetip({attribute: 'href', width: 334, leftOffset: -170, topOffset: -135,positionBy:'auto'});
	jQuery('.tools a.popin-center-ami').cluetip({attribute: 'href', width: 554, positionBy:'center', arrows: false});
	jQuery('.information-produit a.popin-center-ami').fancybox({ 'scrolling' : 'no', 'padding' : 10, 'margin' : 0, 'titleShow' : false, 'autoDimensions' : true, 'overlayOpacity' : 0, 'showCloseButton' : true});

	jQuery('a.popin-fixed-ami').cluetip({attribute: 'href', width: 554, positionBy:'center', referent: 'main', hideReferent: true, arrows: false});


	jQuery('a.popin-right').cluetip({attribute: 'href', width: 350, leftOffset: 0, topOffset: 90});
	jQuery('a.popin-center').cluetip({attribute: 'href', width: 530, positionBy:'center', arrows: false});

	//jQuery('a.popin-lavage').cluetip({attribute: 'href', width: 350, positionBy:'right', leftOffset: 30, topOffset: 5});
	jQuery('a.popin-lavage').fancybox({ 'scrolling' : 'no', width: 35, 'padding' : 10, 'margin' : 0, 'titleShow' : false, 'autoDimensions' : true, 'overlayOpacity' : 0, 'showCloseButton' : true});

	//
	// Initialisation de la fiche produit
	//
	if(typeof(productDefaultAttributeValues) != "undefined" && isEmptyObject(productDefaultAttributeValues) != true  ) {

			loadDefaultSelectedValues(true, false);
			//  selectMagentoDropDownItemByValue() x2
			//	  spConfig.configureElement()
	    	//		    this.reloadOptionLabels(element)
			//          this.fillSelect(element)
			//          this.resetChildren(element)
	    	//          this.reloadPrice()
	    	//            showCustomPriceBlock() => AJAX
			//

			gestionCouleur();
	}
	else if(typeof(smallview) != "undefined")
	{
		gestionCouleurSmallView();
	}

	if(jQuery('#quicklookmode-enabled').html() == "0" )
	{
		initMenuLeft();
		gestionImages();
		gestionNewsletter();
	}
	else
	{
		if( jQuery('#quick-look-main-container').html() != null )	{
			gestionImagesQLook();
			//quickLookSetupWishlist(); // VITHO: Fonctionnalité jamais demandée, jamais servie
		}
	}
});

//
// Gestion de NewsletterInterests
//

function submitInterests() {

	if($('email_address').value == '') return;

	if ( ! interestsForm.validator.validate() ) return;

	Element.show('form-please-wait');

	$('inscription-newsletterinterest').request({
        onFailure: function(resp) {

			errorMsg = '<div id="inscription-form">'
				     + '<span class="error">Un problème est survenu lors de l\'opération.'
				     + '<br/>'
				     + 'Nous vous invitons à rééssayer ultérieurement.</span>'
				     + '</div>';

			$('inscription-form').update(errorMsg); },

        onSuccess: function(resp) {

			$('inscription-form').update(resp.responseJSON.html); }
    });
}

//
// Gestion des blocks Ajax: panier, poll, etc...
//

var BlocksAjaxClass = Class.create({

	  initialize: function() {
	    this.blocks = new Array();
	    this.ajaxUrl = BASE_URL +'ajax/call/index/';
	  },
	  // Methode pour ajouter un block Ajax
	  addBlock: function(name, success_dest, error_dest, oncomplete, param) {
	    if(this.getBlockDetailsByName(name) == null)
	    {
	    	var blockArray = new Array();
		    blockArray['success_dest'] = success_dest;
		    blockArray['error_dest'] = error_dest;
		    blockArray['name'] = name;
		    blockArray['onComplete'] = oncomplete;
		    if(Object.isUndefined(param) == false)
		    	blockArray['param'] = param;
		    else
		    	blockArray['param'] = 0;
		    this.blocks[this.blocks.length] =  blockArray;
	    }
	    //else
	    //	console.log("le block suivant est déjà initialisé : "+ name);
	  },

	  getParameters: function (){
		var params = "no_cache&";
		this.blocks.each(function(item){ params = params + item['name'] +"="+item['param']+ "&";});
		return params;
	  },

	  launchRequest : function(){

		  if(this.blocks.length)
		  {
		    new Ajax.Request(this.ajaxUrl,
			{ method: 'get',
			  parameters :  this.getParameters() ,
			  onSuccess : function(resp)
				{
					var resp = resp.responseJSON;
					for( var blockname in resp)
					{
						var respblock = resp[blockname];
						var blockdetails = BlocksAjax.getBlockDetailsByName(blockname);
						if(blockdetails != null)
						{
							if( Object.isUndefined(respblock.error) == false){
								$(blockdetails['error_dest']).update(respblock.error);
							}

							if( Object.isUndefined(respblock.success) == false) {
								$(blockdetails['success_dest']).update(respblock.success);
							}
						}
					}
				},
				onComplete: function()
				{
					BlocksAjax.blocks.each(
						function(item){
							if(item['onComplete'].empty() == false )
								window[item['onComplete']]();
						});
					BlocksAjax.blocks = new Array();
				},
				onFailure: function() {alert('Erreur lors de l\'appel ajax.');}
			});
		  }
	  },
	  getBlockDetailsByName: function(name){
		  var result = null;
		  this.blocks.each(function(item){
			  	if(item['name'] == name)
			  		result =  item;
			  	});
		  return result;
	  }



	});

function delete_cookie ( cookie_name )
{
  var cookie_date = new Date ( );  // current date & time
  cookie_date.setTime ( cookie_date.getTime() - 1 );
  document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}


// Initialisation de l'objet à utiliser pour initialiser l'url Ajax et ajouter des blocks Ajax
jQuery(document).ready(function() {
//
	BlocksAjax = new BlocksAjaxClass;
//
	if($('connexion')         != undefined) BlocksAjax.addBlock('welcome','connexion','','');
	if($('quick-panier')      != undefined) BlocksAjax.addBlock('smallcart','quick-panier','', $('quickpanier_oncomplete').innerHTML);
	if($('pollBlock')         != undefined) BlocksAjax.addBlock('poll','pollBlock','','');
	var paramProductViewed = 0;
	if($('product_id')!= undefined) {
		paramProductViewed = $('product_id').innerHTML ;
	}
	if($('productviewedajax') != undefined) BlocksAjax.addBlock('productviewed','productviewedajax','','initQuickLook',paramProductViewed );
	if(typeof(todayBlock)     != 'undefined' ){
		todayBlock.each(function(e){
			BlocksAjax.addBlock(e['today_mode'], e['today_id'], '', 'todayInit', e['today_category']);
		});
	}
	BlocksAjax.launchRequest();
});
var isTodayInit = false;
function todayInit(){
	if(isTodayInit == false){
	    jQuery(document).ready(function() {
	        jQuery(".aujourdhuiScroll").each(function(){
		        jQuery(this).scrollable({circular: true}).navigator().autoscroll({ autoplay: true });
	        });
	        jQuery(".aujourdhuiScroll .items a:not(.jyvais)").hover(
	            function() { jQuery(".aujourdhuiScroll .items a.jyvais").addClass("hover"); },
	            function() { jQuery(".aujourdhuiScroll .items a.jyvais").removeClass("hover"); }
	        );
    });
	}
    isTodayInit = true;
}



function isEmptyObject(obj) {
	for(var prop in obj) {
		if(obj.hasOwnProperty(prop))
		return false;
	}
	return true;
}



function setCatContextUrlProductRedirect(obj)
{
	if(typeof(categoryUrl) != 'undefined'){
		var urlproduct = jQuery(obj).attr('href');
		urlproductfinal = urlproduct.slice(urlproduct.lastIndexOf('/'));
		jQuery(obj).attr('href', categoryUrl+ urlproductfinal)
	}
}


/*
 * Recalcule la nouvelle URL lors de la selection d'un filtre & redirige vers cette dernière
 */
function addResultAttrFilter(attrName,attrValue,urlpattern)
{
	window.location.replace(urlpattern.replace( attrName, attrValue ));
}



/*
 * Gestion des messages d'erreur/avertissement dans des popins
 */
/*
 * 	DESACTIVÉ POUR LE MOMENT
 *
jQuery(document).ready(function() {
    if($('use_alert_popin').innerHTML == 'true') {
        $$('ul.messages').each(function(it) {

            jQuery(it).fadeOut(0);
            jQuery(it).fadeIn('slow');

            var li = new Element('li', {'class': 'close'});
            var a = new Element('a', {'href' : '#' }).update("fermer");
            a.onclick = function() {
                jQuery(this.parentNode.parentNode).fadeOut('slow');
            }
            li.appendChild(a);
            it.insertBefore(
                li,
                it.firstChild
            );
        });
    }
});

*/

function showFbLike()
{
	if(window.fbLikeHiddenCount == 1) {
		jQuery('.fb_iframe_widget').css('visibility', 'visible');
	}
	if(window.fbLikeHiddenCount > 0) {
		window.fbLikeHiddenCount--;
	}
}


function hideFbLike()
{
	if(!window.fbLikeHiddenCount) {
		window.fbLikeHiddenCount = 0;
	}
	window.fbLikeHiddenCount++;
	if(window.fbLikeHiddenCount == 1) {
		jQuery('.fb_iframe_widget').css('visibility', 'hidden');
	}
}

var initMenuLeft = function() {
	if(jQuery('#menuleft_method').html() == "accordeon" ) {
		jQuery('.col-left .sous-nav ul').menu_accordion();
	}
	else {
		jQuery('.col-left .sous-nav .head').click(function() {
			/*if(this.id) {
				if(!jQuery('#' + this.id).parent().hasClass('active')) { // Ouverture
					console.log('Ouverture');
					jQuery('#fleche_' + this.id + '_off').hide();
					jQuery('#fleche_' + this.id + '_on').show();
				}
				else { // Fermeture
					console.log('fermeture');
					jQuery('#fleche_' + this.id + '_off').show();
					jQuery('#fleche_' + this.id + '_on').hide();
				}

			}*/
			//console.log(this.id);
			var img = $('fleche_' + this.id);
			jQuery(this).next().animate(
				{
					height: 'toggle'
				},
				'fast',
				function() {
					// Animation complete.
				});
			if(jQuery('#fleche_' + this.id + '_on').css('display') == 'none') { // Ouverture
					jQuery('#fleche_' + this.id + '_off').hide();
					jQuery('#fleche_' + this.id + '_on').show();
			}
			else { // Fermeture
					jQuery('#fleche_' + this.id + '_off').show();
					jQuery('#fleche_' + this.id + '_on').hide();
			}
			return false;
		});
	}
}

/* Compter le nombre de propriétés d'un objet */
var countProperties = function (obj) {
    var count = 0;
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            count = count + 1;
    }
    return count;
}



/* popup des conditions de l'offre */
function openOffres() {
                var hauteur = 500;
                var largeur = 470;
                var top = ((jQuery(window).height() - hauteur) / 2) + jQuery(window).scrollTop();
                var left = ((jQuery(window).width() - largeur) / 2) + jQuery(window).scrollLeft();
                var page = "popup-conditions-des-offres";
                var w = window.open(page,"conditionsoffres","top="+top+",left="+left+",width="+largeur+",height="+hauteur+",menubar=no,scrollbars=yes,statusbar=no,,status=no,location=no,resizable=yes,directories=no");
    w.focus();
}

//
// Liste (variable globale) de champs non obligatoire,
// utilisé à différents endroits du Javascript.
//

var ignoreInputValue = ['Lieu-dit','Résidence, bat, étage...'];

jQuery(document).ready(function($) {
	/* Forumlaire - Valeur par défaut */
	jQuery('form').each(function(){
		jQuery(this).submit(function(){
			if(jQuery(this).find('.validation-failed').size() == 0) {
				jQuery(this).find('.grayed').each(function(){
					if(jQuery.inArray(jQuery(this).val(), ignoreInputValue) !== false)
						jQuery(this).val("");
				});
			}
		});
	});
	
	/* Effet de hover img sur tout les liens avec la class "hover_effect" */
	var replacement = '_hover.';
	jQuery('.hover_effect img').hover(function() {
		jQuery(this).attr("src", jQuery(this).attr("src").replace(/\.([^\.]*)$/,replacement+'$1'));
		jQuery(this).parent().addClass('hover');
	}, function() {
		jQuery(this).attr("src", jQuery(this).attr("src").replace(/_hover([^_hover]*)$/,'$1'));
		jQuery(this).parent().removeClass('hover');
	});
	
});
