// Patch IE9
jQuery.support.noCloneEvent = !!window.addEventListener;


/* variables de touch */
var startX,
startY;
Reflow.renault = {
    //translation settings
    lang: (typeof currentLanguage == "undefined") ? "en": currentLanguage,
    formCheck: (typeof formCheckUrl == "undefined" || formCheckUrl == null) ? "": formCheckUrl,
    isTouched: (function() {
	var el = document.createElement('div');
	el.setAttribute('ongesturestart', 'return;');
	if (typeof el.ongesturestart == "function") {
	    return true;
	} else {
	    return false;
	}
    })(),
    slideShowActivated: false,
    refreshBreadCrump : function refreshBreadCrump(link) {
	var getText = function(a) {
	    var labelText = "";
	    var cufontexts = a.find("cufontext");
	    if(cufontexts.length) {
		cufontexts.each(function(i){
		    labelText += jQuery(this).text();
		});
	    }
	    else {
		labelText = a.text();
	    }
	       	
	    return labelText;
	};
	if (link.parents("#electric-project").length || link.parents("#zedriver").length || link.parents("#rdvEventList").length) {
	    if(link.parents(".main-ajax-place-holder").length ) {
				
		if (jQuery("#breadcrump li").size() <= 3) {
		    jQuery("#breadcrump li.last").removeClass("last");
		    jQuery("#breadcrump ul").append('<li class="last"><a></a></li>');
		}
	    }
	    else {
		if (jQuery("#breadcrump li").size() <= 2) {
		    jQuery("#breadcrump li.last").removeClass("last");
		    jQuery("#breadcrump ul").append('<li class="last"><a></a></li>');
		}
		else if (jQuery("#breadcrump li").size() > 3) {
		    jQuery("#breadcrump li:last").remove();
		    jQuery("#breadcrump li:last").addClass("last");
		}
	    }
			
	    var label = getText(link);
	    jQuery("#breadcrump .last a").html(label).attr("href", link.attr("href"));
	}
	else {
	    var label = getText(link);

	    jQuery("#breadcrump .last a").html(label).attr("href", link.attr("href"));
	}
			
    },
    intercept: function intercept(tabs, destinationId, interceptionsLinks) {
	jQuery(tabs).live("click",
	    function(e) {
		if(!(jQuery.browser.msie && jQuery.browser.version < 8)){ 
		    e.preventDefault();
		    var clickedLink = jQuery(this);
		    var sHref = jQuery(this).attr("href"); 
		    (sHref.indexOf("?") != -1 || sHref.indexOf(".html") != -1) ? sHref += "&ajax=1": sHref += "?ajax=1";
		    if (destinationId === ".sub-ajax-place-holder") {
			(sHref.indexOf("?") != -1 || sHref.indexOf(".html") != -1) ? sHref += "&ajaxtab=1": sHref += "?ajaxtab=1";
		    }
		    //tabs
		    jQuery(tabs).closest(".on").removeClass("on");
		    jQuery(this).parent("li").addClass("on");
		    //fadeout
		    jQuery(destinationId).fadeOut("slow",function() {
			//requete ajax
			jQuery.ajax({
			    url: sHref,
			    success: function(data, response, xhr) {
	                	
				jQuery(destinationId).empty();
				if (response == "error") {
				    if(jQuery(destinationId).find('.ajax-error').length) {
					jQuery(destinationId).find('.ajax-error:eq(0)').append("<br />"+Reflow.widgets.rsm.getText("slideshow.ajax.error"));
				    }
				    else {
					jQuery(destinationId).html("<div class='ajax-error'>" + Reflow.widgets.rsm.getText("slideshow.ajax.error") + "</div>").fadeIn();
				    }
				}
						 
				if(jQuery(destinationId,data).html()==null){					 	
				    jQuery(destinationId).append(Reflow.renault.innerShiv(data,false)).fadeIn();
				}else{
				    jQuery(destinationId).append(Reflow.renault.innerShiv(jQuery(destinationId, data).html(),false)).fadeIn();
				}
                        
				//sliders
				Reflow.renault.zeProject.init();

				//cufon refresh
				if (typeof initFonts === "function") {
				    initFonts();
				}
				
				// Refresh breadcrump 
				Reflow.renault.refreshBreadCrump(clickedLink);
                    	
				// Video
				Reflow.renault.videoManager.init();
                    	
				// Google Map
				Reflow.renault.gmapManager.init();
                    	
				// Facebook, Twitter
				Reflow.renault.setShareUrl(clickedLink);
			    },
			    error: function() {

				if(jQuery(destinationId).find('.ajax-error').length) {
				    jQuery(destinationId).find('.ajax-error:eq(0)').append("<br />"+Reflow.widgets.rsm.getText("slideshow.ajax.error"));
				}
				else {
				    jQuery(destinationId).html("<div class='ajax-error'>" + Reflow.widgets.rsm.getText("slideshow.ajax.error") + "</div>").fadeIn();
				}
			    }
			});
		    });
		}
	    });
	jQuery(interceptionsLinks).live("click",
	    function(e) {
		if(!(jQuery.browser.msie && jQuery.browser.version < 8)){ 
		    e.preventDefault();
		    var clickedLink = jQuery(this);
		    var sHref = jQuery(this).attr("href"); 
		    (sHref.indexOf("?") != -1 || sHref.indexOf(".html") != -1) ? sHref += "&ajax=1": sHref += "?ajax=1";
		    jQuery(destinationId).fadeOut("slow",
			function() {
			    jQuery.ajax({
				url: sHref,
				success: function(data, response, xhr) {
				    jQuery(destinationId).empty();
				    if (response == "error") {
					if(jQuery(destinationId).find('.ajax-error').length) {
					    jQuery(destinationId).find('.ajax-error:eq(0)').append("<br />"+Reflow.widgets.rsm.getText("slideshow.ajax.error"));
					}
					else {
					    jQuery(destinationId).html("<div class='ajax-error'>" + Reflow.widgets.rsm.getText("slideshow.ajax.error") + "</div>").fadeIn();
					}
				    }
				    if(jQuery(destinationId,data).html()==null){					 	
					jQuery(destinationId).append(Reflow.renault.innerShiv(data,false)).fadeIn();
						
				    }else{
					jQuery(destinationId).append(Reflow.renault.innerShiv(jQuery(destinationId, data).html(),false)).fadeIn();
				    } 
				    //sliders
				    Reflow.renault.zeProject.init();
				    
				    //cufon refresh
				    if (typeof initFonts === "function") {
				    	initFonts();
				    }
                        
				    // Refresh breadcrump 
				    Reflow.renault.refreshBreadCrump(clickedLink);

				    // Video
				    Reflow.renault.videoManager.init();

				    // Google Map
				    Reflow.renault.gmapManager.init();

				    // Facebook, Twitter
				    Reflow.renault.setShareUrl(clickedLink);
				},
				error: function() {
				    if(jQuery(destinationId).find('.ajax-error').length) {
					jQuery(destinationId).find('.ajax-error:eq(0)').append("<br />"+Reflow.widgets.rsm.getText("slideshow.ajax.error"));
				    }
				    else {
					jQuery(destinationId).html("<div class='ajax-error'>" + Reflow.widgets.rsm.getText("slideshow.ajax.error") + "</div>").fadeIn();
				    }
				}
			    });
			});
		}
	    });
        
    },
    twizyCompetition: function twizyCompetition() {
	var oRdv = jQuery("#rdv .rdv-cover");
	var oSlide = $('#rdv .slideshow');
	var oTwizy = jQuery("#gallery-twizy");
	oRdv.find("a.link-vote").bind("click",function(e) {
	    e.preventDefault();
	    oRdv.fadeOut("slow", function() {
		$('#gallery-twizy').fadeIn("slow");
	    });
	});
	oTwizy.find("ul.contest-gallery li a").each(function(i) { 
	    (function(elm, index) {
		elm.bind("click",function(e) {
		    e.preventDefault();
		    oTwizy.fadeOut("slow", function() {
			oSlide.fadeIn("slow", function() {
			    if(!Reflow.browser.iTruc){
				Reflow.renault.slideShow();
				oSlide.anythingSlider(parseInt(parseInt(index) + 1)); 
			    }else{
				Reflow.renault.slideShow(function(){
				    oSlide.anythingSlider("setPage"+parseInt(parseInt(index) + 1));
				    oSlide.anythingSlider(1,function(){
					var sHashSlide =jQuery(elm).attr("href");     
					sHashSlide = sHashSlide.split("#")[1];
					sHashSlide = "#"+sHashSlide;                                               
					slideScroll.scrollToElement(sHashSlide,965);
				    });
				});                           
			    }
			});
		    });
		});
	    })(jQuery(this), i);
	});
	oSlide.find("a.link-back").live("click",
	    function(e) {
		e.preventDefault();
		oSlide.fadeOut("slow",
		    function() {
			oSlide.anythingSlider("destroy");
			oTwizy.fadeIn("slow");
		    });
	    });

	var oSignIn = jQuery(".sign-in-wrapper");
	var oRegister = jQuery(".register-wrapper");
	var oInscriptionWrapper = oSignIn.parent();

	if (oSignIn.length > 0 && oRegister.length > 0) {

	    oSignIn.find(".sign-in>.sign-in-content>a.link4").bind("click",
		function(e) {
		    e.preventDefault();
		    oInscriptionWrapper.addClass("open-inscription");
		});

	}

    },
/*
    manageHash: function manageHash() {
	//at load, create an iframe to manage history back and next buttons (will only be used by IE < 8)    
	if (typeof window.ActiveXObject != "undefined" && (typeof documentMode == "undefined" || documentMode < 8)) {
	    var o = document.createElement("IFRAME");
	    o.setAttribute("className", "hidden");
	    o.width = "0";
	    o.height = "0";
	    o.id = "hashiframe";
	    document.body.appendChild(o);
	}

	//init the hash history handler
	Reflow.core.Hash.init(Reflow.core.hashHandler, document.getElementById('hashiframe'));
	Reflow.core.Hash.add2Queue(Reflow,
	    function(newHash, initial) {
		var indexTwizy = 0;
		var sTwizId = newHash;
		if (newHash.indexOf("twizy-g") != -1) {
		    indexTwizy = newHash.split("twizy-g")[1];
		    indexTwizy = parseInt(indexTwizy) - 1;
		    newHash = "twizy";
		}
			

		switch (newHash) {
		    case "login-form":
			jQuery(".bt-expand").trigger("click");
			break;

		    case "subscribe-form":
			jQuery(".sign-in>.sign-in-content>a.link4").trigger("click");
			break;
		    case "contest-home":
			Reflow.renault.closeVideo("videoRDV", {
			    params: {
				"ToClose": "#rdv section:eq(0)",
				"ToOpen": "#contest-home",
				"effect": ["hide", "show"],
				"speed": 0
			    }
			});
		    break;
		case "gallery-twizy":
		    Reflow.renault.closeVideo("videoRDV", {
			params: {
			    "ToClose": "#rdv section:eq(0), #contest-home",
			    "ToOpen": "#gallery-twizy",
			    "effect": ["hide", "show"],
			    "speed": 0
			}
		    });
		break;
	    case "twizy":
		arg = {
		    params: {
			"ToClose": "#rdv section:eq(0), #contest-home, #gallery-twizy",
			"ToOpen": ".slideshow",
			"effect": ["hide", "show"],
			"speed": 0
		    }
		};
		Reflow.renault.closeVideo("videoRDV", arg, function() {
		    jQuery(arg.params.ToClose).each(function(idx, itm){
			jQuery(this)[arg.params.effect[0]](arg.params.speed,
			    function() {
				if(!Reflow.renault.iTruc){
				    jQuery(arg.params.ToOpen)[arg.params.effect[1]](arg.params.speed,
					function() {
					    if (idx == 0) {
						var oTwizy = jQuery("#gallery-twizy").find("ul.contest-gallery");
						oTwizy.find("li:eq(" + indexTwizy + ") a").trigger("click");
					    }
					});   
				}else{								
				    jQuery('.slide-content li.slide-item:not(".cloned"):eq(0) .command li.back').remove();
				    jQuery('.slide-content li.slide-item:not(".cloned"):last .command li.forward').remove();
				    var iSlideWidth = (jQuery('.slide-content li.slide-item').length)*965; 			                               
				    jQuery('.slide-content').css({
					"width":iSlideWidth+"px"
					});
				    slideScroll = new iScroll(document.querySelector('.slide-content'), {
					snap:true,
					momentum:false,
					hScrollbar:false,
					vScrollbar:false,
					desktopCompatibility:true
				    });
			       
				    jQuery(arg.params.ToOpen)[arg.params.effect[1]](arg.params.speed,
					function() {
					    slideScroll.scrollToElement(sTwizId, 0); 
					});   
				}	
			    });
		    });
		});
		break;
	    default:

		break;

	}
    });
},*/
slideShow: function slideShow(callback){
    var oSlide = jQuery('.slideshow:eq(0)');
    function initSlide(slider) {
	jQuery(".slide-item", oSlide).each(function(index, slideEl) {             
	    if (jQuery(this).find(".info-cover").hasClass("dark")) {
		jQuery('.command', this).addClass("dark");
	    } else {
		jQuery('.command', this).removeClass("dark");
	    }
	// jQuery('.command ul li:eq(1)', this).before(jQuery('<li class="slide-pager">' + index + '/' + oSlide.find(".slide-item").not('.cloned').length + '</li>'));
               
	});
	/*if (Reflow.browser.iTruc) {
	    jQuery('.slide-item .command .forward').each(function(i){
		jQuery(this).bind("click", function(e){
		    e.preventDefault();			
		    if(jQuery(this).parents("li.slide-item").next(".slide-item").attr("id")=="")jQuery(this).parents("li.slide-item").next(".slide-item").attr("id","slide-"+parseInt(Math.random()*200000))			
		    slideScroll.scrollToElement("#" + jQuery(this).parents("li.slide-item").next(".slide-item").attr("id"), 0);
		});
	    });
	    jQuery('.slide-item .command .back').each(function(i){
		jQuery(this).bind("click", function(e){
		    e.preventDefault();				
		    if(jQuery(this).parents("li.slide-item").prev(".slide-item").attr("id")=="")jQuery(this).parents("li.slide-item").prev(".slide-item").attr("id","slide-"+parseInt(Math.random()*200000))			
						
		    slideScroll.scrollToElement("#" + jQuery(this).parents("li.slide-item").prev(".slide-item").attr("id"), 0);
		});
	    });
	}*/

    }
        
    var slideHandler = null;
     if (!Reflow.browser.iTruc && jQuery(".slideshow .slide-item").length > 1) {
	oSlide.each(function(i) {

	    if (jQuery("object", this).length > 0 && swfobject.getFlashPlayerVersion().major >= "10") {
		return;
	    } else {
		var carNav;
		(jQuery("#home-slideshow").length) ? carNav = true : carNav = false;
		if (jQuery(".slideshow .slide-item:not('.cloned')").length > 1) {
		    if (Reflow.renault.slideShowActivated == false) {
			if (jQuery(this).parents("#rdv").length == 0) {
			    jQuery(this).anythingSlider({
					autoPlay: true,
					pauseOnHover: true,
					buildNavigation: carNav, 
					getInstance: function (objSlider) {
						slideHandler = objSlider;
					}
			    });

			} else {
			    jQuery(this).anythingSlider({
				autoPlay: false,
				getInstance: function (objSlider) {
				    slideHandler = objSlider;
				}
			    });                     
			}
			initSlide();
			//Reflow.renault.slideShowActivated == true;

		    } else {
			initSlide();
		    }
		}
	    }
	});	
     }
     
    /* 
        touches devices behaviors
      */
    if (Reflow.browser.iTruc && jQuery(".slideshow .slide-item").length > 1) {
	/*jQuery('.slide-content li.slide-item:not(".cloned"):eq(0) .command li.back').remove();
	jQuery('.slide-content li.slide-item:not(".cloned"):last .command li.forward').remove();*/
	var iSlideWidth = (jQuery('.slideshow li.slide-item').length)*965; 			                               
	jQuery('.slide-content').css({
	    "width":iSlideWidth+"px"
	    });
	slideScroll = new iScroll(document.querySelector('.slide-content'), {
	   
	    snap:true,
	    momentum:false,
	    hScrollbar:false,
	    vScrollbar:false,
	    desktopCompatibility:false
	});
           
	if(typeof callback!="undefined")callback();  
    }
},
autoSlide: function autoSlide(countdown, container) {
    var oSlideIt = jQuery(container);

    if (oSlideIt.length > 0) {
	oSlideIt.find("li").not(":eq(0)").hide();
	var slideCount = window.setInterval(function() {

	    if (oSlideIt.find("li:visible").next("li").length == 1) {
		oSlideIt.find("li:visible").fadeOut().next("li").fadeIn();
	    } else {
		oSlideIt.find("li:visible").fadeOut();
		oSlideIt.find("li:eq(0)").fadeIn();
	    }

	},
	countdown);
    }
},
videoStartCallback: function videoStartCallback(idFlash) {
    	
    var oViewportControl = jQuery(".viewport-controller");
    var sClass = "hide-viewport-controller";
    var oElm = jQuery("#videoContainer, .answer-video, #hub-gamme");
    var flashEnabled = true;
    var hasSocial = false;
        
    if (swfobject.getFlashPlayerVersion().major == "0") {
	var oVideo = oElm.find("video");
	var oJs = Reflow.renault.getVideoID(oVideo); //.attr("data-javascript");
	idFlash = oJs.id;
	hasSocial = oJs.social;
	flashEnabled = false;
    }
    switch (idFlash) {
	case "VideoPlayerZE":
	
	    if (!oViewportControl.hasClass(sClass)) oViewportControl.addClass(sClass);
	            
	    if (flashEnabled) {
	    } else if (hasSocial) {
		oElm.find(".dynamic-wrapper").fadeIn("slow", function() {
	            		
		    });
	    }
	    break;
	case "videoRDV":
	    break;
	case "videoPopin":
	    break;
	case "PopinVideoPlayerZE":
		if (jQuery("#" + idFlash ).closest("#autoLoadPopin").length) {
			Reflow.widgets.popinManager.popin("autoLoadPopin").centerPopin();
		}
	    break;
	case "WallVideoPlayer":
	    if (!flashEnabled && hasSocial) {
		oElm.find(".dynamic-wrapper, :not(.dynamic-wrapper)>video").fadeIn("slow", function() {});
	    }
	    break;
	case "VideoHubGamme":
	    break;
	case "VideoHubPdt":
	    break;
	case "360":
	    if (!oViewportControl.hasClass(sClass)) oViewportControl.addClass(sClass);
	    break;
	default:
	    break;

    }

},
videoEndCallback: function videoEndCallback(idFlash, arg, callback) {
    	
    var oViewportControl = jQuery(".viewport-controller");
    var sClass = "hide-viewport-controller";
    var oElm = jQuery("#videoContainer, .answer-video, #hub-gamme, #hub-pdt");
        
    var flashEnabled = true;
    var hasSocial = false;
        
    if (swfobject.getFlashPlayerVersion().major == 0) {
	var oVideo = oElm.find("video");
	var oJs = Reflow.renault.getVideoID(oVideo);
	idFlash = oJs.id;
	hasSocial = oJs.social;
	flashEnabled = false;
    }
    switch (idFlash) {
	case "VideoPlayerZE":
	    if (oViewportControl.hasClass(sClass)) oViewportControl.removeClass(sClass);
	            
	    if (flashEnabled) {
	    //oViewportControl.find("> li:first > a").trigger("click");
	    } else if (hasSocial) {
		oElm.find(".dynamic-wrapper").fadeOut("slow", function() {
		    jQuery(this).hide();
		});
	    }
	    break;
	case "videoRDV":
	    if (swfobject.getFlashPlayerVersion().major == 0) {
		var oVideo = oElm.find("video");
		if(oVideo.length)
		    oVideo[0].pause();
	    }
	    else {
		if(jQuery("#"+idFlash).length)
		    jQuery("#"+idFlash)[0].stopVideoJS();
	    }
	    if (typeof arg == "undefined") {
		arg = {
		    params: {
			"ToClose": "#rdv section:eq(0)",
			"ToOpen": "#rdv .rdv-cover",
			"effect": ["fadeOut", "fadeIn"],
			"speed": "slow"
		    }
		}
	    }
	            
	    jQuery(arg.params.ToClose)[arg.params.effect[0]](arg.params.speed,function(){
		jQuery(arg.params.ToOpen)[arg.params.effect[1]](arg.params.speed,function(){
		    if (typeof callback != "undefined") {
			callback();
		    }
		});
	    });
	    break;
	case "PopinVideoPlayerZE":
		if (jQuery("#" + idFlash ).closest("#autoLoadPopin").length) {
			Reflow.widgets.popinManager.popin("autoLoadPopin").close({
				bgOpen: false
			});
		}
	    break;
	case "WallVideoPlayer":
	    if (!flashEnabled && hasSocial) {
		oElm.find(".dynamic-wrapper, :not(.dynamic-wrapper)>video").fadeOut("slow", function() {
		    jQuery(this).hide();
		});
	    }
	    break;
	case "360":
	    if (oViewportControl.hasClass(sClass)) oViewportControl.removeClass(sClass);
	    break;
	case "VideoHubGamme":
	    oElm.find("#video-hub-gamme-wrapper").fadeOut("slow", function() {
		jQuery(this).hide();
	    });
	case "VideoHubPdt":
	    oElm.find("#video-hub-pdt").fadeOut("slow", function() {
		jQuery(this).hide();
		var linkToGo = oElm.find('.viewport-controller .on').next('li').find('a').attr('href');
		window.location.href = linkToGo;
	    });
            	
	    break;
	default:
	    break;
    }
},
closeVideo: function closeVideo (id, arg, callback) {
    this.videoEndCallback(id, arg, callback);
},
preloadingImages: function preloadIt(attrName, context) {
    if (typeof context == "undefined") {
	context = document;
    }
    Reflow.elmts.imagesPreload = new Array();
    jQuery("img[" + attrName + "]", context).each(function(i) {
	//save original SRC
	jQuery(this).attr("original", jQuery(this).attr("src"));
	//load the placeholder
	jQuery(this).attr("src", jQuery(this).attr(attrName));
	//preload original
	Reflow.elmts.imagesPreload[i] = new Image();
	Reflow.elmts.imagesPreload[i].src = jQuery(this).attr("original");
	//when ready, put the preloaded image
	Reflow.elmts.imagesPreload[i].onLoad = (function(elm, url) {
	    (jQuery(".no-canvas").length == 0) ? jQuery(elm).hide().attr("src", url).fadeIn('slow') : jQuery(elm).hide().attr("src", url).show();
	})(jQuery(this), Reflow.elmts.imagesPreload[i].src)
    });
},
shareURL: "",
setShareUrl: function(link) {
    Reflow.renault.shareURL = link[0].href;
},
getShareUrl: function(link) {
    return (Reflow.renault.shareURL !== "" ? Reflow.renault.shareURL : document.location.href);
},
twitter: function twitter() {
    window.open("http://twitter.com/home?status=Currently+reading+" + Reflow.renault.getShareUrl());
},
facebook: function facebook() {
    window.open("http://www.facebook.com/sharer.php?u=" + Reflow.renault.getShareUrl() + "&t=Share+on+Facebook");
},
initSocial: function initSocial() {
    jQuery(".bt-twitter").live("click", function(e){
	Reflow.renault.twitter();
    });
    jQuery(".bt-facebook").live("click", function(e){
	if(jQuery(this).closest(".answer-video").length == 0) {
	    Reflow.renault.facebook();
	}
    });
},
bookmark: function bookmark(title, url) {
    if (window.sidebar) { // firefox
	window.sidebar.addPanel(title, url, "");
    } else if (window.opera && window.print) { // opera
	var elem = document.createElement('a');
	elem.setAttribute('href', url);
	elem.setAttribute('title', title);
	elem.setAttribute('rel', 'sidebar');
	elem.click();
    } else if (document.all) { // ie
	window.external.AddFavorite(url, title);
    }
},
creativeUtility: function creativeUtility() {
    var elm = jQuery(".bt-creative-utility:eq(0)");
    var tabs = jQuery("#showroom .viewport-controller");
    if (elm.length > 0 && tabs.length > 0) {
	elm.live("click",
	    function(e) {
		e.preventDefault();
		var sIndex = jQuery(this).attr("data-tab");
		var sSelector = "#showroom .viewport-controller:eq(0) li:eq(" + sIndex + ") a";
		jQuery(sSelector).trigger("click");
	    });
    }
},
videoPopinManager: function videoPopinManager() {
    var videoPopinId = "videoPopin";

    if (typeof Reflow.widgets.popinManager != "undefined" && jQuery(".open-video-popin").length) {
        	

	Reflow.widgets.popinManager.create({
	    id: videoPopinId, 
	    popinTemplate: "video"
	});	 
        	
	Reflow.widgets.popinManager.popin(videoPopinId).addCallback({
	    'beforeClose': function(args) {
		if (swfobject.getFlashPlayerVersion().major >= 10) {
		    var currentVideo = args.popin.find("object")[0];
		    if (currentVideo) {
			try {
			    currentVideo.stopVideoJS();
			} catch(e) {
			}
		    }
		} else {
		    var currentVideo = args.popin.find("video")[0];
                		
		    if (currentVideo) {
			try {
			    currentVideo.pause();
			} catch(e) {
			}
		    }
		}
	    }
	});
	jQuery(".open-video-popin").each(function(){
	    if(!jQuery.browser.msie){
		Reflow.widgets.popinManager.popin(videoPopinId).addOpenLink(this);
	    }
	});
    }
},
zeProject: {
    init: function init() {
	//slide-it with countdown
	Reflow.renault.autoSlide(5000, ".fade-slider");
    }
},
carousel: function carousel(nItem,el) {
    var oCarousel = jQuery(el);
    if (typeof jQuery.jCarouselLite == "undefined") {
	Reflow.core.jsLoader(Reflow.settings.jsPluginPath + "jcarousellite_1.1.js",
	    function() {
		loadCarousel(nItem);
	    },
	    "jcarousellite");
    } else {
	loadCarousel(nItem);
    }
    function loadCarousel(nbItem,el) {
	if(!nItem)nbItem = 6;
	oCarousel.each(function() {
	    if (oCarousel.find("li").size() > nbItem) {
		var btPrev = jQuery(this).siblings(".bt-prev"),
		btNext = jQuery(this).siblings(".bt-next");
		jQuery(this).jCarouselLite({
		    btnNext: btNext,
		    btnPrev: btPrev,
		    visible: nbItem,
		    circular: false
		});
	    }
	    else {
		oCarousel.siblings(".bt-next").addClass("disabled");
		oCarousel.siblings(".bt-prev").addClass("disabled");
	    }
	});
            
	/* 
          	touches devices behaviors
             */
	if (Reflow.renault.isTouched) {
	    var sliderContain = jQuery(el);
	    if(sliderContain.length){
		function touchMove2(event) {
		    if (event.targetTouches[0].target.nodeName.toLowerCase() == "img") {
		    //event.preventDefault();
		    } else {
			return;
		    }
		    if (event.targetTouches[0].pageX < (parseInt(startX) - 100)) {
			jQuery(sliderContain).siblings(".bt-next").trigger("click");
		    } else if (event.targetTouches[0].pageX > parseInt((startX) + 100)) {
			jQuery(sliderContain).siblings(".bg-prev").trigger("click");
		    }
		}

		sliderContain.addEventListener("touchmove", touchMove2, false);
		sliderContain.addEventListener("touchstart",
		    function(event) {
			startX = event.touches[0].pageX;
			startY = event.touches[0].pageY;
		    },
		    false);
	    }
                
	}
    }
},
zeDriver: {
    inscription: function inscription() {
	var oInscription = jQuery("#inscription");
	if (oInscription.length) {
	    var oLnk = oInscription.find("a.bt-expand");
	    var oImg = oLnk.find("img");
	    if (!oInscription.hasClass("close") && oImg.length) oImg.attr("src", oImg.attr("src").replace("-off", "-on"));
	    oLnk.bind("click",
		function(e) {
		    e.preventDefault();
		    oInscription.toggleClass("close").toggleClass("open");
		    if (oInscription.hasClass("close")) {
			oImg.attr("src", oImg.attr("src").replace("-on", "-off"));
		    } else {
			oImg.attr("src", oImg.attr("src").replace("-off", "-on"));
		    }
		})
	}
    },
    init: function init() {
	this.inscription();
	Reflow.renault.carousel(6,".mobile-app-carousel-container");
    }
},
validateRegister: function validateRegister(options) {
    	
    if(typeof options === "string") {
	options = {
	    id: options,
	    callback: null
	}
    }
    /** check form **/
    // validateur
    jQuery(options.id).validator({
	lang: Reflow.renault.lang,
	// do not validate inputs when they are edited
	errorInputEvent: null,
	effect: 'oneach',
	onBeforeValidate: function(e, els) {
	    jQuery.each(els,
		function() {
		    jQuery(this).closest("div").find("p.error").remove();
		    jQuery(this).closest("div").removeClass("error-field");
		});
	}
    }).submit(function(e) {
	var form = jQuery(this);
            
            
	// client-side validation OK.
	var formCheck = Reflow.renault.formCheck;
	if(form.attr("id")=="contact-callback-form"){
	    formCheck = jQuery("#save_url").val();
	}
	if(this.submitedOneTime == true) {
	    e.preventDefault();
	}
              
	if (!e.isDefaultPrevented()) {
                  
	    if(options.callback) {
		e.preventDefault();
		options.callback({
		    form: form
		});
		return;
	    }
	    else {
		this.submitedOneTime = true;
                  
		if(formCheck != "") {
		    // submit with AJAX
		    $.ajax({
			// url de validation pour les champs
			url:formCheck + "?" + form.serialize() + "&rdm=" + Math.random() + ((formCheck.indexOf("?") != -1 || formCheck.indexOf(".html") != -1) ? "&ajax=1": "?ajax=1"),
			dataType: "json",
			async: false,
			success: function(json) {
			    // everything is ok. (server returned true)
			    if (json === true) {
				//let action of the form to be submitted "normally"  
				this.submitedOneTime = true;       
			    } else {
				// server-side validation failed. use invalidate() to show errors
				form.data("validator").invalidate(json);
				// prevent default form submission logic
				e.preventDefault();
			    }
			}
		    });
		}
	    }
	}
              
    });
},
disableFieldset: function disableFieldset(n) {
    jQuery("fieldset[name='" + n + "']").attr("disabled", "disabled").hide();
    jQuery("fieldset[name='" + n + "'] input").each(function(i) {
	jQuery(this).removeAttr("required");
	if (jQuery(this).attr("id") == "siret") {
	    jQuery(this)[0].tagPattern = jQuery(this).attr("pattern");
	    jQuery(this).removeAttr("pattern");
	}
	jQuery(this).val("");
    });
},
enableFieldset: function enableFieldset(n) {
    if (jQuery(this).is(":checked")) {
	jQuery("fieldset[name='" + n + "']").attr("disabled", false).show();
	jQuery("fieldset[name='" + n + "'] input").each(function(i) {
	    if (jQuery(this).attr("id") == "siret" && typeof jQuery(this)[0].tagPattern !== "undefined") {
		jQuery(this).attr("pattern", jQuery(this)[0].tagPattern);
	    }
	    jQuery(this).attr("required", "required");
	});
    }
},
initRegisterFormRules: function initRegisterFormRules(id) {
    var oPersonnal = jQuery("#personnal");
    var oCompany = jQuery("#company");
    var oFlyingContainer = jQuery("#flyingblueChoice");
    var oFlyingId = jQuery("#flyingblueId");
    var oFlying = jQuery(".flying");
    if (oPersonnal.length > 0) {
	oPersonnal.live("click",
	    function(e) {
		if (jQuery(this).is(":checked")) {
		    Reflow.renault.disableFieldset.call(jQuery(this), "entrepriseData");
		}
	    });
	oCompany.live("click",
	    function(e) {
		if (jQuery(this).is(":checked")) {
		    Reflow.renault.enableFieldset.call(jQuery(this), "entrepriseData");
		}
	    });
	if (oPersonnal.is(":checked")) oPersonnal.trigger('click');
	if (oCompany.is(":checked")) oCompany.trigger('click');
	if (!oPersonnal.is(":checked") && !oCompany.is(":checked")) Reflow.renault.disableFieldset.call(oPersonnal, "entrepriseData")

	if (oFlyingContainer.length > 0) {
	    var toggleFlyingBlueWrapper = function toggleFlyingBlueWrapper (e) {
		if (jQuery(this).is(":checked")) {
		    oFlyingId.attr("required", "required").attr("minlength", "10").attr("maxlength", "10");
		    oFlying.show();
		} else {
		    oFlyingId.removeAttr("required").removeAttr("minlength").removeAttr("maxlength");
		    oFlying.hide();
		}
	    };
	    //oFlying.hide();
	    oFlyingContainer.bind("click",toggleFlyingBlueWrapper);
	    toggleFlyingBlueWrapper();
	}
    }
},

initNewsletterForm: function initNewsletterForm(id) {
    var oBrands = jQuery("#marques");
    var oModels = jQuery("#models");
    if (oBrands.length > 0 && oModels.length > 0 && typeof carsXML != "undefined" && typeof Reflow.renault.carsXML == "undefined") {
	jQuery.ajax({
	    url: carsXML,
	    success: function(data) {
		Reflow.renault.carsXML = data;
		jQuery(data).find("marques>marque").each(function(i) {
		    oBrands.append("<option value='" + jQuery(this).attr("value") + "'>" + jQuery(this).text() + "</option>");
		});
		jQuery(oBrands).bind("change",
		    function(e) {
			jQuery(oModels).find("option").each(function() {
			    jQuery(this).remove();
			});
			jQuery(Reflow.renault.carsXML).find("models>models-list[id='" + jQuery(this).val() + "']>model").each(function() {

			    jQuery(oModels).append("<option value='" + jQuery(this).attr("value") + "'>" + jQuery(this).text() + "</option>");
			})
		    })
	    }
	})
    }
    var oFlyingContainer = jQuery("#flyingblueChoice");
    var oFlyingId = jQuery("#flyingblueId");
    var oFlying = jQuery(".flying");
    if (oFlyingContainer.length > 0) { 
        	
	var toggleFlyingBlueWrapper = function toggleFlyingBlueWrapper (e) {
	    if (jQuery(this).is(":checked")) {
		oFlying.find("input[data-required],select[data-required]").each(function() {
		    jQuery(this).attr("required", "required");
		});
		oFlyingId.attr("minlength", "10").attr("maxlength", "10");
		oFlying.show();
	    } else {
		oFlying.find("input[data-required],select[data-required]").each(function() {
		    jQuery(this).removeAttr("required");
		});
		oFlyingId.removeAttr("minlength").removeAttr("maxlength");
		oFlying.hide();
	    }
	};
        	
	oFlyingContainer.bind("click", toggleFlyingBlueWrapper);
            
	toggleFlyingBlueWrapper();
    }
},
initEVCenterForm: function initEVCenterForm() {
    var form = jQuery("#ev-center-form");
    if(form.length) {
	var salesPerson = form.find("#evc-salesperson"),
	radioVisited = form.find("[data-show-vendor]"),
	radioName = radioVisited.attr("name"),
	radio = form.find("input[name="+radioName+"]");
    		
	var toggleSalesPerson = function (rd) {
	    if(rd.data("show-vendor") && rd[0].checked) {
		salesPerson.show();
		salesPerson.find('input[type="text"]').attr("required", "required");
	    }
	    else {
		salesPerson.hide();
		salesPerson.find('input[type="text"]').removeAttr("required");
	    }
	};
    		
	radio.bind("click", function() {
	    toggleSalesPerson(jQuery(this));
	});
    		
	toggleSalesPerson(radioVisited);
    }
},
initForms: function initForms(id) {
    var oLoginForm = jQuery("#login-form");
    if (oLoginForm.length) {
	oLoginForm.find(".buttons a.link4").bind("click",
	    function(e) {
		e.preventDefault();                
		oLoginForm.find("#password").attr("required","required");
		oLoginForm.find("#action").val('login');
		oLoginForm.trigger("submit");
	    });
	oLoginForm.find(".buttons a#forgot-pass").bind("click",
	    function(e){
		e.preventDefault();
		oLoginForm.find("#password").removeAttr("required");
		oLoginForm.find("#action").val('forgotpass');
		oLoginForm.trigger("submit");
	    });
             
    }
       
    var oClickToCall = jQuery("#contact-clicktocall");
        
    if(oClickToCall.length){
           
    }

    var api = $(id).data("validator");
    //validator settings
    jQuery.tools.validator.fn("[data-equals]", "Value not equal with the \"<strong>$1</strong>\" field",
	function(input) {
	    var name = input.attr("data-equals"),
	    field = this.getInputs().filter("[name=" + name + "]");
	    return input.val() == field.val() ? true: [field.siblings("label").html()];
	});
    // Radio validation
    jQuery.tools.validator.fn(".radio-required",
	function(input) {
	    var name = input.attr("name");
	    var group_members = jQuery('input[name=' + name + ']');
	    var checked_count = jQuery('input[name=' + name + ']:checked').length;
	    if ((checked_count == 0) && (group_members.first().attr('id') == input.attr('id'))) {
		jQuery('input[name=' + name + ']').click(function() {
		    $(id).data("validator").reset(jQuery('input[name=' + name + ']'));
		});
		$(id).data("validator").invalidate(jQuery(group_members.last()));
		return false;
	    } else {
		return true;
	    }
	});
    // minlength attribute management
    $.tools.validator.fn("[minlength]", "This field must be at least $1 characters long",
	function(input, value) {
	    var min = input.attr("minlength");
	    return value.length >= min ? true: [min];
	});
    // maxlength attribute management
    $.tools.validator.fn("[maxlength]", "This field can't be more than $1 characters long",
	function(input, value) {
	    var max = input.attr("maxlength");
	    return value.length <= max ? true: [max];
	});
    //specific error rendering
    jQuery.tools.validator.addEffect("oneach",
	function(errors, event) {
	    jQuery.each(errors,
		function(index, error) {
		    if (error.input.closest("#ev-center-form").length && !error.input.closest("#evc-salesperson").length) {
			error.input.closest("form").find("p.error").remove();
			error.input.closest("form").find(".std").addClass("error-field");
			error.input.closest("form").find(".std:last").append("<p class='error'>" + error.messages[0].replace('$1', error.input.siblings("label").html()) + "</p>");
		    }
		    else {
			error.input.closest("div").find("p.error").remove();
			error.input.closest("div").removeClass("error-field");
			error.input.closest("div").addClass("error-field");
			error.input.closest("div").append("<p class='error'>" + error.messages[0].replace('$1', error.input.siblings("label").html()) + "</p>");
		    }
		});

	// the effect only remove errors when all inputs are valid  
	},
	function(inputs) {
	    jQuery.each(inputs,
		function() {
		    jQuery(this).closest("div").find("p.error").remove();
		    jQuery(this).closest("div").removeClass("error-field");
		})
	});
        
    jQuery("[data-no-paste]").bind("paste", function (e){
	e.preventDefault();
    });
    jQuery.tools.validator.localize(Reflow.renault.lang, formTranslation);
    // specific rules
    Reflow.renault.initRegisterFormRules(id);
    // specific rules for newsletter
    Reflow.renault.initNewsletterForm(id);
    // specific rules for EV Center
    Reflow.renault.initEVCenterForm(id);
    //launch validation
    Reflow.renault.validateRegister(id);

},
initMyAccountNav: function initMyAccountNav() {
    var oAccount = jQuery(".account-menu");
    if (oAccount.find("p").length > 0) {
	oAccount.find("ul").hide();
	oAccount.find("p").bind("click",
	    function(e) {
		e.preventDefault();
		(jQuery(this).siblings("ul").is(":visible")) ? jQuery(this).siblings("ul").fadeOut() : jQuery(this).siblings("ul").fadeIn();
	    });
    }
},
    
photoGalleryManager: function photoGalleryManager() {  

    if(jQuery(".view-selector-wrapper").length) {
	if(jQuery(".view-selector li").size() > 12) {
	    jQuery(".view-selector-wrapper").addClass("view-selector-carousel-active");
	    Reflow.renault.carousel(12,".view-selector");
	}
	        
	var viewSelectorWrapper = jQuery(".view-selector-wrapper");
	var viewSelector = jQuery(".view-selector");
	        
	if(jQuery.browser.msie && jQuery.browser.version < 9) {
	    //viewSelectorWrapper.append('<div class="view-selector-wrapper-fix"></div>');
	    viewSelectorWrapper.hover(function(e){
		viewSelectorWrapper.stop().animate({
		    opacity: 1
		}, 300);
	    },
	    function(e){
		viewSelectorWrapper.stop().animate({
		    opacity: 0
		}, 300);
	    });
	}
	else {
	    viewSelectorWrapper.hover(function(e){
		viewSelectorWrapper.stop().animate({
		    opacity: 1, 
		    bottom: '0px'
		}, 300);
	    },
	    function(e){
		viewSelectorWrapper.stop().animate({
		    opacity: 0, 
		    bottom: '-20px'
		}, 300);
	    });
	}
	        
	/** thumbnails support **/
	jQuery(".view-selector a").unbind("click").die("click").live("click",
	    function(e) {
		e.preventDefault();
		var sImgUrl = jQuery(this).attr("href");
		var sBigImg = jQuery(".gallery-picture-wrapper .picture");
		sBigImg.attr("src", sImgUrl);
		sBigImg.attr("alt", jQuery(this).find("img:eq(0)").attr("alt"));
		jQuery(this).closest("ul").find("li.on").removeClass("on");
		jQuery(this).parent("li").addClass("on");
	    });
    }
        
},
    
accessibleLinks: function () {
    if (jQuery('ul.accessible-links').size() > 0) {
	jQuery('ul.accessible-links a').addClass ('hidden').bind ('focus', function(e){
    			
	    if (jQuery('ul.accessible-links').hasClass('hidden-accessible-links')) {
		jQuery('ul.accessible-links').removeClass('hidden-accessible-links');
	    }
	    if (jQuery(this).hasClass('hidden')) {
		jQuery(this).removeClass('hidden');
	    }
	});
    }
},

gmapManager: {
    gmapData: [],
    setGmapData: function (d) {
	Reflow.renault.gmapManager.gmapData = d;
    },
    createPartnerMap: function () {
	if (Reflow.renault.gmapManager.gmapData.length == 0 && typeof partnersArray != "undefined") {
	    Reflow.renault.gmapManager.gmapData = partnersArray;
	}
	var map;
	var startPoint = null;
	for (var j=0; j<Reflow.renault.gmapManager.gmapData.length; j++){
	    var partner = Reflow.renault.gmapManager.gmapData[j];
	    if (typeof (partner.centerOnMe) !== "undefined") {
		startPoint = new google.maps.LatLng(partner.coords.x, partner.coords.y);
		break;
	    }
	}
	if(startPoint == null) {
	    startPoint = new google.maps.LatLng(48.831296, 2.227968);
	}
	var mapOptions = {
	    zoom: 1,
	    center: startPoint,
	    mapTypeId: google.maps.MapTypeId.ROADMAP
	};
    	    
	map = new google.maps.Map(document.getElementById("partners-map"), mapOptions); 
	        
	        
	for (var i=0; i<Reflow.renault.gmapManager.gmapData.length; i++){
	    var partner = Reflow.renault.gmapManager.gmapData[i];
	    var infowindow = new google.maps.InfoWindow({
		content: partner.content
	    });
		     
	    var marker = new google.maps.Marker({
		position:  new google.maps.LatLng(partner.coords.x, partner.coords.y),
		map: map,
		title: partner.title
	    });
	    google.maps.event.addListener(marker, 'click', (function(a,b,c) {
		return function () {
		    c.open(a,b)
		};
	    })(map,marker,infowindow));
	}
    },
    	
    init: function () {
	if (typeof (google) !== "undefined" && typeof(google.maps) !== "undefined") {
	    if(document.getElementById("partners-map")) {
		Reflow.renault.gmapManager.createPartnerMap();
	    }
	// Init des autres gmap ici
	/*if(document.getElementById("other-map")) {
					Reflow.renault.gmapManager.otherMap();
				}*/
	}
	    	
    },
    	
    destroy : function (mapObject) {
	if (typeof (google) !== "undefined" && typeof(google.maps) !== "undefined" && mapObject) {
	    // Detruire Google map ici mapObject
	    google.maps.event.clearInstanceListeners(mapObject)
	}
    }
    	
},

company: {
    comparator: function () {

	if(jQuery("#form-company-calc").length) {
	    // get handle to the scrollable DIV
	
	    jQuery("input:range").each(function(){
		var range = jQuery(this), 
		wrapper = range.closest(".range-wrapper"),
		dragValue = range.siblings(".dragValue"),
		handle = null;
	        		
		var setLabel = function (value) {
		    var dragPos = parseInt(handle.css("left")) - dragValue.width() / 2 + handle.width() / 2;
						
		    dragValue.html(value+" "+range.data("unit"));
		    dragValue.animate({
			left: dragPos
		    }, "fast");
		    dragValue.siblings(".label").find("mark").html(value);
		};
	        		
		// initialize rangeinput
		jQuery(this).rangeinput({
		    // display progressbar
		    progress: true,
		    // disable drag handle animation when when slider is clicked
		    speed: 0,
		    precision:1,
		    // this is called when the slider is clicked. we animate the DIV
		    change: function(e, i) {
			setLabel (i);
		    }
		});
	        		
		handle = wrapper.find(".handle");
	
		setLabel (range.val());
	        		
	        		
	    });
	    		
	    Reflow.renault.validateRegister({
		id: "#form-company-calc", 
		callback: function(args){
	
		    var form = args.form
		    url = form.attr("action"),
		    wrapper = jQuery("#company-calc"),
		    ajaxLoader = null;
	            	
		    jQuery.ajax({
			url: url + ((url.indexOf("?") != -1 || url.indexOf(".html") != -1) ? "&ajax=1" : "?ajax=1"),
			type: form.attr("method"),
			data: form.serialize(),
			dataType: "json",
			async: true,
			cache: true,
			beforeSend: function (XMLHttpRequest, settings) {
			    if (jQuery.browser.msie && jQuery.browser.version < 7) {
				wrapper.find("select").css({
				    visibility: "hidden"
				});
			    }
			    wrapper.append('<div class="ajax-loader"></div>');
			    ajaxLoader = wrapper.find(".ajax-loader");
			    ajaxLoader.height(wrapper.height());
	    					
			},
			success: function(data, textStatus, XMLHttpRequest) {
	            			
			    if (data.error || typeof data.c02 !== "number" || typeof data.conso !== "number" || typeof data.maintenance !== "number") {
				var message = data.message ? data.message : Reflow.widgets.rsm.getText("popin.ajax.error");
				ajaxLoader.append('<p class="error" data-error="Bad value">' + message + '</p>');
				ajaxLoader.bind("click", function(e){
				    jQuery(this).fadeOut(300, function(){
					jQuery(this).remove();
				    })
				});
			    }
			    else {
				var co2 = jQuery("#company-calc .co2 .result div:not(.unit)"),
				conso = jQuery("#company-calc .eco .result div:not(.unit)"),
				maint = jQuery("#company-calc .maintenance .result div:not(.unit)");
	    						
				var setValue = function(el, value) {
				    value = parseInt(value);
				    var strValue = "" + value;
	    							
				    while (strValue.length < el.length) {
					strValue = "0" + strValue;
				    }
	    							
				    el.each(function(idx, el){
					jQuery(el).removeAttr("class").addClass("c"+strValue.charAt(idx));
				    });
				};
	    						
				setValue(co2, data.c02);
				setValue(conso, data.conso);
				setValue(maint, data.maintenance);
	    						
				ajaxLoader.fadeOut(300, function(){
				    if (jQuery.browser.msie && jQuery.browser.version < 7) {
					wrapper.find("select").css({
					    visibility: "visible"
					});
				    }
				    jQuery(this).remove();
				});
			    }
	    					
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
			    errorThrown = errorThrown.replace(/['"\n\r]/gi, '');
			    wrapper.find(".ajax-loader").append('<p class="error" data-error="'+errorThrown+'">' + Reflow.widgets.rsm.getText("popin.ajax.error") + '</p>');
			    wrapper.find(".ajax-loader").bind("click", function(e){
				jQuery(this).fadeOut(300, function(){
				    if (jQuery.browser.msie && jQuery.browser.version < 7) {
					wrapper.find("select").css({
					    visibility: "visible"
					});
				    }
				    jQuery(this).remove();
				})
			    });
			}
		    });
	            	
		}
	    });
    }
},
init: function() {
    Reflow.renault.carousel(1,".company-carousel");
    		
    Reflow.renault.company.comparator();
    		
}
},
    
getVideoID: function (oVideo) {
    var data = oVideo.attr("data-javascript");
    	
    if(typeof (data) !== "undefined") {
	data = (new Function("return " + data.replace(/[’]/g,"'")))();
	if (data) {
	    return data;
	}
    }
    return {};
},

printPage: {
    print: function print () {
	window.print();
    },
    init: function init() {
	jQuery(".bt-print").bind("click", function(e){
	    Reflow.renault.printPage.print();
	});
    }
},
    
clickMeOnlyOneTime: { 
    click : function (e) {
	if (typeof this.clickedOneTime === "undefined") {
	    this.clickedOneTime = true;
	}
	else {
	    e.preventDefault();
	}
    },
    init: function (e) {
	jQuery(".one-time-click").live("click", Reflow.renault.clickMeOnlyOneTime.click);
    }
},
    
setCarInfo: function (color, id) {
    if (id && carData && carData[id]) {
	jQuery("a[data-bt-reservation]").each(function(idx,el){
	    jQuery(this).attr("href", carData.url.replace("{0}", carData[id].modele).replace("{1}", carData[id].version).replace("{2}", carData[id].color));
	});
	jQuery("[data-price]").each(function(idx,el){
	    jQuery(this).html(carData[id].price);
	});
    }
},
    
videoManager: {
    	
    init: function(wrapper) {
	if (wrapper == null) {
	    wrapper = jQuery("body");
	}
    		
	if (typeof Reflow.widgets.ReflowVideo !== "undefined" && swfobject.getFlashPlayerVersion().major == 0) {
	    Reflow.elmts["ReflowVideo"] = new Reflow.widgets.ReflowVideo({
		customControls: !(/iPhone|iPad|iPod|Android|blackberry|palm/gi.test(navigator.userAgent)),
		autoplay: true,
		cssSelectors: {
		    closeButton: 'close-video'
		},
		showButtons: {
		    stop: false,
		    progressBar: true,
		    fullBrowser: true,
		    closeButtonInFullBrowser: true,
		    closeButtonInNormalMode: true,
		    volumeBar: true,
		    volumeValue: false,
		    mute: true
		},
		extraSettings: {
		    volumePointerAnimationStyle: 'position',
		    defaultVolumeLevel: 80,
		    volumeVertical: true,
		    remainingTime: false
		},
		callbacks: {
		    onVideoPlaying: function(arg) {
			Reflow.renault.videoStartCallback(Reflow.renault.getVideoID(jQuery(arg.video)).id);
		    },
		    onVideoEnding: function(arg) {		    
			Reflow.renault.videoEndCallback(Reflow.renault.getVideoID(jQuery(arg.video)).id);
		    },
		    videoEndingArgs: {
			"ToClose": "#rdv section:eq(0)",
			"ToOpen": ".rdv-cover"
		    }
		}
	    },
	    Reflow);
	
	    Reflow.elmts["ReflowVideo"].init(Reflow.elmts["ReflowVideo"]);
	            
	            
	    wrapper.find(".close-video").live("click", function(e) {
		e.preventDefault();
		var id = Reflow.renault.getVideoID(jQuery(this).siblings("video:eq(0)")).id;
		if (id != "") {
		    Reflow.renault.videoEndCallback (id);
		}
	    });
	            
	    wrapper.find(".bt-see-again").live("click", function(e) {
		e.preventDefault();
		var videoId = jQuery(this).attr("href");
		if (videoId != "") {
		    jQuery(videoId)[0].play();
		    var id = Reflow.renault.getVideoID(jQuery(videoId)).id;
		    Reflow.renault.videoStartCallback (id);
		}
	    });
	}
	else if (swfobject.getFlashPlayerVersion().major > 0) {
	    wrapper.find("object video source").remove();
	}
    }
},
 

videoLive : {
	
	player: null,
	timeout: null,
	refreshOnLoad: function (link, wrapper, data) {
		
		if ((!link || typeof link.data("mosaic-gallery") == "undefined") && jQuery(".mosaic-control .carousel").length) {
			jQuery(".mosaic-control .carousel").each(function () {
				
				var btPrev = jQuery(this).siblings(".bt-prev"),
				btNext = jQuery(this).siblings(".bt-next");
				
				jQuery(this).jCarouselLite({
					btnNext: btNext,
				    btnPrev: btPrev,
					visible: 7,
					scroll: 1
				});
			});
		}
		
		jQuery(".mosaic-video .cam-display").css("z-index", "6");
		
		if (jQuery("#player").length || jQuery("#player-object").length) {
			
			// declare object for video
			Reflow.renault.videoLive.player = new MediaElementPlayer('#player', {
			    // the order of controls you want on the control bar (and other plugins below)
			    features: ['playpause','current','progress','duration','volume','fullscreen'],
	            // path to Flash and Silverlight plugins
	            pluginPath: 'media/mediaelement/'
			});
			
			Reflow.renault.videoLive.timeout = setTimeout(function () {

				jQuery(".mosaic-poster").fadeOut( "slow", function () {
					
					jQuery(".mosaic-video .cam-display").css({
						zIndex: "3"
					});
					jQuery("body").addClass("cinema");
					Reflow.renault.videoLive.player.play();	
				});
				
			}, 2000);
			
		}
		else{			
			Reflow.renault.videoLive.timeout = setTimeout(function () {

				jQuery(".mosaic-picture .info-picture").fadeOut( "slow", function () {
					jQuery("body").addClass("cinema");
				});
				
				jQuery(".mosaic-picture").hover(function () {
					jQuery(".mosaic-picture .info-picture").stop(false, true).fadeIn();
				}, function () {
					jQuery(".mosaic-picture .info-picture").stop(false, true).fadeOut("slow");
				});
				
			}, 2000);
			
			
		}
		
	
	},
	
	load: function (e) {
		
		e.preventDefault();
	    var link = jQuery(this);
	    var url = this.href;
	    var wrapper = jQuery("#"+jQuery(this).data("load-mosaic-in"));	    
	    
	    var parmAjax = "ajax=1";
	    if (typeof link.data("mosaic-gallery") !== "undefined") {
	    	
	    	parmAjax = "ajax=1&ajaxVideo=1";
	    	
	    }
	    
	    if(typeof url === "string") {
	    	url += ((url.indexOf("?") != -1 || url.indexOf(".html") != -1) ? "&" + parmAjax : "?" + parmAjax);
			jQuery.ajax({
			    url:url,
			    dataType: "html",
			    beforeSend: function (XMLHttpRequest, settings) {
				
					clearTimeout(Reflow.renault.videoLive.timeout);
					
					if (Reflow.renault.videoLive.player !== null) {
						
						Reflow.renault.videoLive.player.pause();
						swfobject.removeSWF("player-object");
						Reflow.renault.videoLive.player = null;
					}
				
					if(wrapper.find(".ajax-loader").length == 0) {
						
					    if(jQuery.browser.msie && jQuery.browser.version < 9) {
					    	wrapper.append(jQuery('<div class="ajax-loader"></div>').height(wrapper.height()).fadeTo(300, 0.7));
					    }
					    else {
					    	wrapper.append(jQuery('<div class="ajax-loader"></div>').height(wrapper.height()).fadeIn(300));
					    }
					}
		    					
			    },
			    success: function(data, textStatus, XMLHttpRequest) {
		            
			    	if (typeof link.data("mosaic-gallery") !== "undefined") {
			    		jQuery(link).parent().addClass("current").siblings(".current").removeClass("current");
			    	}
			    	
					if(jQuery.browser.msie && jQuery.browser.version < 9) {
			
					    data = Reflow.renault.innerShiv(data);
					    wrapper.empty().append(data).css("height", ""); // Surtout pas height: auto
					    Reflow.renault.videoLive.refreshOnLoad(link, wrapper, data);
			                    		
					}
					else {
						
						Reflow.renault.videoLive.refreshOnLoad(link, wrapper, data);
						
						
							wrapper.height(wrapper.height()).fadeTo(300, 0.01, function() {
					    	
					    	wrapper.empty().append(data).css({
					    		height: "",
					    		opacity: "1"
					    	});
					    	Reflow.renault.videoLive.refreshOnLoad(link, wrapper, data);
					    	
					    });
					}
			    },
			    error: function(XMLHttpRequest, textStatus, errorThrown){
			    	wrapper.find(".ajax-loader").append('<div class="error">'+Reflow.widgets.rsm.getText("slideshow.ajax.error")+'</div>');
			    	wrapper.find(".ajax-loader").bind("click", function () {
			    		jQuery(this).remove();
			    	});
			    }
			});
	    }
		
	
	},
	
	init:  function () {
		
		if (jQuery("#player-content").length) {
			Reflow.renault.videoLive.refreshOnLoad(false);
		}
		jQuery("[data-load-mosaic-in]").live("click", Reflow.renault.videoLive.load);
		
		jQuery(".home-mosaic ul").hover(function () {
			jQuery(this).siblings("ul").addClass("passive");
		}, function () {
			jQuery(this).siblings("ul").removeClass("passive");
		});
			
		
		if(jQuery.browser.msie && jQuery.browser.version < 7) {
			jQuery(".mosaic .cam-item").hover(function () {
				jQuery(this).find(".info").css("top", "0")
			}, function () {
				jQuery(this).find(".info").css("top", "136px")
			});
		}
		
	}
	
},

contentLoader: {
    	
    refreshOnLoad: function (link, wrapper, data) {

	//reload fonts
	if (typeof initFonts === "function") {
	    initFonts();
	}
	
	// Refresh breadcrump 
	if (link != null) {
	    Reflow.renault.refreshBreadCrump(link);
	}
	
	// Video
	Reflow.renault.videoManager.init(wrapper);
	        
	// Google Map
	Reflow.renault.gmapManager.init();
	    	
	// Calculatrice
	Reflow.renault.company.comparator();
	
	// Facebook, Twitter
	if (link != null) {
	    Reflow.renault.setShareUrl(link);
	}

	/* Gallery management */
	Reflow.renault.photoGalleryManager();
	    	
	if(jQuery.browser.msie && jQuery.browser.version < 7) {
	    wrapper.find('img[src$=".png"]').each(function(n, e){
		DD_belatedPNG.fixPng( e );
	    });
	}
			
	if(wrapper.find(".wall").length) {
	    wrapper.find(".wall").each(function(e){
		Reflow.renault.wall.initWall(jQuery(this));
	    });
	}
			
			
	if(wrapper.find(".slide-wrapper .slide-content > li").length > 1) {
	    if(!wrapper.hasClass("slideshow") && wrapper.closest("slideshow").length == 0) {
		wrapper.addClass("slideshow");
	    }
	    Reflow.renault.slideShow();
	}
			
	wrapper.find(".fb-like").each(function(idx, el){
	    if (typeof FB  != "undefined"){
		FB.XFBML.parse(el);
	    }
	});
			
    },
    initWrapper: function (wrapper) {
	wrapper.removeClass("slideshow").anythingSlider("destroy");
    },
    load: function (e) {
	    e.preventDefault();
	    var link = jQuery(this);
	    var url = this.href;
	    var wrapper = jQuery("#"+jQuery(this).data("load-in"));
	    		
	    if(typeof url === "string") {
		url += ((url.indexOf("?") != -1 || url.indexOf(".html") != -1) ? "&ajax=1": "?ajax=1");
		jQuery.ajax({
		    url:url,
		    dataType: "html",
		    beforeSend: function (XMLHttpRequest, settings) {
			if(wrapper.find(".ajax-loader").length == 0) {
			    if(jQuery.browser.msie && jQuery.browser.version < 9) {
				wrapper.append(jQuery('<div class="ajax-loader"></div>').height(wrapper.height()).fadeTo(300, 0.7));
			    }
			    else {
				wrapper.append(jQuery('<div class="ajax-loader"></div>').height(wrapper.height()).fadeIn(300));
			    }
			}
	    					
		    },
		    success: function(data, textStatus, XMLHttpRequest) {
	                    	
	                    	
			if(jQuery.browser.msie && jQuery.browser.version < 9) {
	
			    //Reflow.renault.contentLoader.initWrapper(wrapper);
			    data = Reflow.renault.innerShiv(data);
			    wrapper.empty().append(data).css("height", ""); // Surtout pas height: auto
	                    		
			    Reflow.renault.contentLoader.refreshOnLoad(link, wrapper, data);
	                    		
			}
			else {
			    wrapper.height(wrapper.height()).fadeTo(300, 0.01, function() {
				Reflow.renault.contentLoader.initWrapper(wrapper);
				wrapper.empty().append(data).css("height", "").fadeTo(300, 1, function(){ // Surtout pas height: auto
				    Reflow.renault.contentLoader.refreshOnLoad(link, wrapper, data);
				});
			    });
			}
		    },
		    error: function(XMLHttpRequest, textStatus, errorThrown){
			wrapper.find(".ajax-loader").append('<div class="error">'+Reflow.widgets.rsm.getText("slideshow.ajax.error")+'</div>');
			wrapper.find(".ajax-loader").bind("click", function () {
			    jQuery(this).remove();
			});
		    }
		});
	    }
    },
    	
    viewportController : function (e) {
	jQuery(this).parent().addClass("on").siblings().removeClass("on");
    },
    	
    init: function () {
	
		if(!(jQuery.browser.msie && jQuery.browser.version < 8)) { // Pas d'ajax sur IE 6/7
		    jQuery("[data-load-in]").live("click", Reflow.renault.contentLoader.load);
		    jQuery(".viewport-controller a").live("click", Reflow.renault.contentLoader.viewportController);
		    jQuery(".tabs-controller-wrapper-2 a").live("click", Reflow.renault.contentLoader.viewportController);
		}
		else {
		    jQuery(".twizy-lab-controller [data-load-in]").live("click", Reflow.renault.contentLoader.load);
		}
    }
},
twizyLab : {
    voteClickHandler: function(e) {
	e.preventDefault();
			
	if (typeof FB !== undefined) {
	    var a = jQuery(this),
	    shareObj = null;
	    		
	    jQuery(".twizy-lab-zoom .cover .info-cover .error, .twizy-lab-zoom .cover .info-cover .vote-ok").remove();
	    		
	    if (a.closest(".gallery-twizy-list").length) {
		var link = a.closest("li").find("a[data-img-alt]");
		shareObj = {
		    picture : link.data("img-alt"),
		    link : link.attr("href")
		};
		/*if(link.data("swf")) {
		    shareObj.source = link.data("swf");
		    shareObj.media = {};
		    shareObj.media.expanded_width = 398;
		    shareObj.media.expanded_height = 460;
		}*/
	    }
	    else if (a.closest(".info-cover").length) {
		var pctUrl = a.data("img-url");
		if (!pctUrl) {
		    pctUrl = jQuery("#visualisation-twizy-alt").attr("src");
		}
		shareObj = {
		    picture : pctUrl,
		    link : a.attr("href")
		};
		/*if(a.data("swf")) {
		    shareObj.source = a.data("swf");
		    shareObj.media = {};
		    shareObj.media.expanded_width = 398;
		    shareObj.media.expanded_height = 460;
		}*/
	    }
	    			    		
	    if (shareObj != null) {
		shareObj.actions = { 
		    name : Reflow.widgets.rsm.getText("facebook.twizy.action-title"), 
		    link : Reflow.widgets.rsm.getUrl("facebook.twizy.home-contest")
		};
		shareObj.method= 'stream.publish';
		shareObj.name= Reflow.widgets.rsm.getText("facebook.twizy.title1");
		shareObj.caption= Reflow.widgets.rsm.getText("facebook.twizy.title2");
		shareObj.description= Reflow.widgets.rsm.getText("facebook.twizy.description");
					
		Reflow.renault.twizyLab.FBvote(shareObj);
	    }
	}
    },
    FBvote: function FBvote(shareObj){
	var showError = function(message, response) {

	    var fbMessage = response && response.error ? ' data-error="'+response.error.message+'"' : '';
	    fbMessage.replace(/"/gi, "'");
				
	    jQuery(".twizy-lab-zoom .cover .info-cover .error").remove();
	    jQuery(".twizy-lab-zoom .cover .info-cover").append('<p class="error"' + fbMessage + '>'+Reflow.widgets.rsm.getText("facebook.twizy.error-vote")+'</p>');
   
	};
	var feed = function () {
	    FB.api('/me/feed', 'post', shareObj, function(response) {
		if (!response || response.error) {
		    showError(Reflow.widgets.rsm.getText("facebook.twizy.error-vote"), response);
		} 
		else {

		    var btVote = jQuery(".twizy-lab-zoom .cover .bt-vote");
		    var idNum = btVote.data("num");

		    var url = btVote.attr("href");
		    url += ((url.indexOf("?") != -1 || url.indexOf(".html") != -1) ? "&": "?")+ "mode=vote&idItem="+idNum;

		    jQuery.ajax({
			url:  url,
			dataType: "json",
			success: function(data, textStatus, XMLHttpRequest) {
			    if(data.error) {
				var message = data.message ? data.message : Reflow.widgets.rsm.getText("facebook.twizy.error-vote");
				showError(message);
			    }
			    else {
				var voteNum =jQuery(".twizy-lab-zoom .cover .vote-number");
				var nbVote = parseInt(voteNum.find("mark cufontext").html()) + 1;
				if (nbVote <= 1) {
				    voteNum.html(Reflow.widgets.rsm.getText("facebook.twizy.vote").replace("{0}", nbVote));
				}
				else {
				    voteNum.html(Reflow.widgets.rsm.getText("facebook.twizy.votes").replace("{0}", nbVote));
				}
				if (typeof Cufon !== "undefined") {
					Cufon.replace(voteNum[0]);
				}
				jQuery(".gallery-twizy-list a[data-num="+idNum+"]").closest("li").find(".bt-vote mark").html(nbVote);
									
				jQuery(".twizy-lab-zoom .cover .info-cover").append('<p class="vote-ok">'+Reflow.widgets.rsm.getText("facebook.twizy.vote-ok")+'</p>');
			    }
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
			    showError(Reflow.widgets.rsm.getText("facebook.twizy.error-vote"));
			}
		    });
		}
	    });
	};
	FB.init({
	    appId: Reflow.widgets.rsm.getText("facebook.twizy.app-id"), 
	    status: true, 
	    cookie: true, 
	    xfbml: true
	});
	FB.getLoginStatus(function(response) {
	    if (response.session) {
		feed();
	    } else {
		FB.login(function(response) {		
		    if (response.session) {
			if (response.perms) {
			    feed();
			} 
			else {
			    showError(Reflow.widgets.rsm.getText("facebook.twizy.error-authorization"));
			}
		    }
		    else {
			showError(Reflow.widgets.rsm.getText("facebook.twizy.error-authentication"));
		    }
						
		}, 
		{
		    perms: 'publish_stream'
		});
	    }
	});
    },
    zoom: function () {
	jQuery(".gallery-twizy-list.enable-zoom li > a, .gallery-twizy-list.enable-zoom .bt-vote").live("click", function(e){
	    e.preventDefault();
	    var a = jQuery(this);
	    if (a.hasClass("bt-vote")) {
		a = a.closest("li").find(" > a");
	    }
	   // var fbShare = "http://www.facebook.com/sharer.php?u={0}&t={1}",
	    var fbShare = "http://www.facebook.com/sharer.php?u={0}",
	    twShare = "http://twitter.com/home?status={0}",
	    fbLike = '<fb:like href="{0}" layout="button_count" action="like" show_faces="false" font="arial" colorscheme="light" width="160" height="25"></fb:like>',
	    cUrlPage = escape(a.attr("href")),
	    info = a.siblings(".info"),
	    voteLocked = a.attr("data-vote-locked") ? true : false,
	    cDate = a.data("date"),
	    cSkin = a.data("skin"),
	    cNum = a.data("num"),
	    cSwf = a.data("swf"),
	    cOwner = a.data("owner"),
	    cImgAlt = a.data("img-alt"),
	    cTitle = info.find(".title").text(),
	    cAuthor = info.find(".author mark").text(),
	    cVote = info.find(".bt-vote mark").text(),
	    cUrlVote = info.find(".bt-vote").attr("href"),
	    cover = jQuery(".twizy-lab-zoom .cover"),
	    infoCover = jQuery(".twizy-lab-zoom .info-cover"),
	    shareLinks = jQuery(".twizy-lab-zoom .share-links"),
	    command = jQuery(".twizy-lab-zoom .command");
    			
	    var setInfoContent = function () {

		command.find(".slide-pager mark").text(cNum);
		cover.find(".error, .vote-ok").remove();
		cover.find(".date").text(cDate);
		cover.find(".sub-title").text(cTitle);
		cover.find(".copyright mark").text(cAuthor);
		//cover.find(".vote-number mark").text(cVote);
		if (cVote <= 1) {
		    cover.find(".vote-number").html(Reflow.widgets.rsm.getText("facebook.twizy.vote").replace("{0}", cVote));
		}
		else {
		    cover.find(".vote-number").html(Reflow.widgets.rsm.getText("facebook.twizy.votes").replace("{0}", cVote));
		}
		var btVote  = cover.find(".bt-vote");
		btVote.attr("href", cUrlVote).data("img-url", cImgAlt).data("num", cNum).data("swf", cSwf);
		if (voteLocked) {
		    btVote.hide();
		}
		else {
		    btVote.show();
		}
		if (typeof Cufon !== "undefined") {
			Cufon.refresh();
		}
    		//shareLinks.find(".facebookLink").attr("href", fbShare.replace("{0}",cUrlPage).replace("{1}", escape((cOwner == true ? Reflow.widgets.rsm.getText("facebook.twizy.share-own") : Reflow.widgets.rsm.getText("facebook.twizy.share-other")))));
		shareLinks.find(".facebookLink").attr("href", fbShare.replace("{0}",cUrlPage));
		//shareLinks.find(".twitterLink").attr("href", twShare.replace("{0}", Reflow.widgets.rsm.getText("twitter.twizy.share")).replace("{1}",escape(cUrlPage)));
		shareLinks.find(".twitterLink").attr("href", twShare.replace("{0}",encodeURI(Reflow.widgets.rsm.getText("twitter.twizy.url").replace("{0}", cNum))));
		//shareLinks.find(".twitterLink").attr("href", twShare.replace("{0}", Reflow.widgets.rsm.getText("twitter.twizy.share")).replace("{1}",escape(cUrlPage)));
		shareLinks.find(".fb-like").html(fbLike.replace("{0}",cUrlPage));
	    };
    			
	    if(jQuery.browser.msie && jQuery.browser.version) {
		command.hide();
		infoCover.hide();
		shareLinks.hide();
    				
		setInfoContent();
    				
		command.show();
		infoCover.show();
    				
		if (typeof FB  != "undefined"){
		    FB.XFBML.parse(shareLinks.find(".fb-like")[0], function (){
			shareLinks.show();
		    });
		}
		else {
		    shareLinks.show();
		}
	    }
	    else {
		command.fadeOut(300);
		infoCover.fadeOut(300);
		shareLinks.fadeOut(340, function(){
		    setInfoContent();
		    infoCover.fadeIn();
		    command.fadeIn();
		    if (typeof FB  != "undefined"){
			FB.XFBML.parse(shareLinks.find(".fb-like")[0], function (){
			    shareLinks.fadeIn();
			});
		    }
		    else {
			shareLinks.fadeIn();
		    }
	        			
		});
	    }
    			
	    jQuery("img#visualisation-twizy-alt").attr("src", cImgAlt);
    			
	    if(jQuery("#visualisation-twizy").length > 0 && swfobject.getFlashPlayerVersion().major >= "10"){
		var s = jQuery("#visualisation-twizy")[0];
		s.setTexture( cSkin );
	    }
	});
    },
    init: function (){
	/*jQuery(".twizy-lab-controller .sort a").live("click", function(e){
	    e.preventDefault();
	    jQuery(this).addClass("on").parent().siblings().find("a").removeClass("on");
	});*/
    		
	// .gallery-twizy-list .bt-vote <= boutons vote dans la galerie
	jQuery(".twizy-lab-zoom .bt-vote").live("click", Reflow.renault.twizyLab.voteClickHandler)
    		
	Reflow.renault.twizyLab.zoom();
    }
},
    
wall: {
    initGraph: function() {
	var iniH = -85,
	barHeightMax = 150,
	barTop = 0,
	barBot = 50,
	barHeight = barHeightMax - barTop - barBot;
	    	
	    	
	    	
	var moveTogether = function(e){
	    e.preventDefault();
	    		
	    var link = jQuery(this),
	    data = link.data("info"),
	    navigation = link.closest(".graph-navigation"),
	    max = navigation.data("max"),
	    unit = navigation.data("unit"),
	    wrapper = navigation.siblings(".graph-wrapper");
	    		
	    if (data && max && unit) {
		data = data.split("|");
		max = max.split("|");
		unit = unit.split("|");
	    			
		for(var i=0;i<data.length;i++){
		    var calcul = Math.ceil(Math.abs(barHeight - data[i]*barHeight/max[i]));
		    var rect = "rect("+calcul+"px 38px 150px 0)";
		    			
		    wrapper.find(".graph-bar:eq("+i+") .top").animate({
			top:calcul-1
			},700, 'easeInOutCubic');
		    wrapper.find(".graph-bar:eq("+i+") .bot img").animate({
			'clip':rect
		    },700, 'easeInOutCubic');
		    wrapper.find(".graph-bar:eq("+i+") .top span").html('<mark>' + data[i] + '</mark>' + unit[i]);
		}
	    }
	    			
	}
	jQuery(function(){
	    jQuery(".graph-navigation a").unbind().bind("click",moveTogether);
	    jQuery(".graph-navigation a:eq(5)").trigger("click");
	});
    },
    open :function(e){
	e.preventDefault();
	var link = jQuery(this),
	li = link.closest("li");
    		
	li.siblings().find("object").each(function(idx, el){
	    if (typeof el.id !== "undefined") {
		if (typeof el.stopVideoJS === "function") {
		    el.stopVideoJS();
		}
		swfobject.removeSWF(el.id);
	    }
	});
			
			
	setTimeout ((function(l){
	    return function() {
			l.addClass("open").siblings().removeClass("open").removeClass("loaded");
			l.siblings().find(".answer-wrapper").remove(); // Evite d'avoir plusieurs fois le même id dans la page
			/*if (jQuery.browser.msie && jQuery.browser.version < 9) {
			    Reflow.renault.wall.load(l);
			}*/
		    jQuery(window).trigger("smartresize.masonry");
		
	    };
	})(li), 150); // On attend d'être sûr que les flash soit bien supprimé... Merci IE
    		
    		
    },
    load: function(that) {
	var currentObject = that ? that : this;
	var isAutonomie = (jQuery("#wall-question-form").length != 0) ;
	var li = jQuery(currentObject).filter(".open"),
	a = li.find(".question"),
	url = a.attr("href"),
	answer = li.find(".answer-wrapper");
    		    		
	if(li.hasClass("open") && !li.hasClass("loaded") && a.length) {
	    li.addClass("loaded");
	    if (!answer.length) {
		answer = jQuery('<div class="answer-wrapper ajax-loader"></div>');
		li.append(answer);
	    }
	    jQuery.ajax({
		url: url +  ((url.indexOf("?") != -1 || url.indexOf(".html") != -1) ? "&ajax=1" : "?ajax=1") + "&rdm=" + Math.random(),
		dataType: "html",
		async: true,
		cache: false,
		success: function(data) {
		    
		    answer.removeClass("ajax-loader");
    					    					
		    data = Reflow.renault.innerShiv(data);
    					
		    answer.html(data);
    			    			
		    // Video
		    if(answer.find(".answer-video").length != 0) {
			if((jQuery.browser.msie && jQuery.browser.version < 9)) {
			    // Tricks obligeant IE à recharger les flash et évite le cache
			    /*var newFixUrl = answer.find('object param[name="movie"]').attr("value" )+"?rnd="+Math.random();			    
			    answer.find('object param[name="movie"]').attr("value", newFixUrl);
			    answer.find('object').attr("data", newFixUrl);*/
			    
			}
			Reflow.renault.videoManager.init(answer);
		    }
		    
		    //reload fonts
		    if (typeof initFonts === "function") {
		    	initFonts();
		    }
    					
		    if(answer.find(".answer-graph").length == 0 && jQuery.browser.msie && jQuery.browser.version < 7) {
			answer.find('img[src$=".png"]').each(function(n, e){
			    DD_belatedPNG.fixPng( e );
			});
		    }
    					
		    if(answer.find(".answer-graph").length != 0) {
			Reflow.renault.wall.initGraph();
		    }
    					
		    answer.find(".fb-share a, .answer-video .bt-facebook").bind("click", function(e) {
			e.preventDefault();
    						
			var shareObj, 
			description = "",
			wrapper = jQuery(this).closest('.wall-item'),
			question = wrapper.find(".question .question-title");
    						
			if (question.find("cufontext").length) {
			    question.find("cufontext").each(function(idx, el){
				description += jQuery(this).text() + " ";
				description = description.replace(/[ ]{2,}/gi, " ");
			    });
			}
			else {
			    description = question.text();
			}
    			
			shareObj = {
			    picture : Reflow.widgets.rsm.getUrl("facebook.wall.picture"),
			    link : (isAutonomie ? Reflow.widgets.rsm.getUrl("facebook.wall.link") : Reflow.widgets.rsm.getUrl("facebook.faq.link")),
			    method: 'stream.publish',
			    name: (isAutonomie ? Reflow.widgets.rsm.getText("facebook.wall.title1") : Reflow.widgets.rsm.getText("facebook.faq.title1")),
			    caption: (isAutonomie ? Reflow.widgets.rsm.getText("facebook.wall.caption") : Reflow.widgets.rsm.getText("facebook.faq.caption")),
			    description: description
			};	
    						
			var showError = function(message, fbMessage){
			    fbMessage = fbMessage || "";
			    wrapper.append('<div class="layer-error"><p class="error" ' + fbMessage + '>'+message+'</p></div>');
			    wrapper.find(".layer-error").bind("click", function () {
				jQuery(this).remove();
			    });
			};
    						
			var showConfirm = function(message){
			    wrapper.append('<div class="layer-error"><p class="valid">'+message+'</p></div>');
			    wrapper.find(".layer-error").bind("click", function () {
				jQuery(this).remove();
			    });
			};

    						
			var feed = function() {
			    FB.api('/me/feed', 'post', shareObj, function(response) {
				if (!response || response.error) {
				    var fbMessage = response && response.error ? ' data-error="'+response.error.message+'"' : '';
				    fbMessage.replace(/"/gi, "'");
				    //showError((response && response.error ? response.error.message : "Erreur"));
				    showError(Reflow.widgets.rsm.getText("facebook.wall.error"), fbMessage);
				//console.log(response.error);
				} 
				else {
				    showConfirm((isAutonomie ? Reflow.widgets.rsm.getText("facebook.wall.shared") : Reflow.widgets.rsm.getText("facebook.faq.shared")));
				//console.log("Published");
				//console.log(shareObj);
				}
			    });
			};
    						
			FB.init({
			    appId: (isAutonomie ? Reflow.widgets.rsm.getText("facebook.wall.app-id") : Reflow.widgets.rsm.getText("facebook.faq.app-id")), 
			    status: true, 
			    cookie: true, 
			    xfbml: true
			});
			FB.getLoginStatus(function(response) {
			    if (response.session) {
				feed();
			    } else {
				FB.login(function(response) {
				    if (response.session) {
					if (response.perms) {
					    feed();
					}
					else {
					    showError(Reflow.widgets.rsm.getText("facebook.wall.error-authorization"));
					}
				    }
				    else {
					showError(Reflow.widgets.rsm.getText("facebook.wall.error-authentication"));
				    }
				}, 
				{
				    perms: 'publish_stream'
				});
			    }
			});
    						
		    });
    			
    					
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
                    	
		}
	    });
	}
    },

    initFilters: function () {
	var doFilters = function (e) {

	    var form = null;
    			
	    if (e.type == "submit") {
		e.preventDefault();
		form = jQuery(this);
	    }
	    else {
		form = jQuery(this).closest("form");
	    }
    			
	    var url = form.attr("action"),
	    section = form.closest(".wall-section"),
	    wrapper = section.find(".wall-wrapper");
    			
	    jQuery.ajax({
		url: form.attr("action") +  ((url.indexOf("?") != -1 || url.indexOf(".html") != -1) ? "&ajax=1" : "?ajax=1"),
		type: form.attr("method"),
		data: form.serialize(),
		dataType: "html",
		async: true,
		cache: true,
		beforeSend: function (XMLHttpRequest, settings) {
		    section.append('<div class="ajax-loader"></div>');
		},
		success: function(data) {
		    
    					
		    wrapper.find('.wall').masonry("destroy");
		    wrapper.find(".question").unbind();
    					    					
		    data = Reflow.renault.innerShiv(data);
    					
		    wrapper.empty().html(data);
    					
		    Reflow.renault.wall.initWall(wrapper.find(".wall"));

		    section.find(".ajax-loader").fadeOut(300, function(){
			jQuery(this).remove();
		    });
    					
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
		    section.find(".ajax-loader").append('<p class="error">' + Reflow.widgets.rsm.getText("popin.ajax.error") + '</p>');
		    section.find(".ajax-loader").bind("click", function(e){
			jQuery(this).fadeOut(300, function(){
			    jQuery(this).remove();
			})
		    });
		}
	    });
    			
	};
    		
    		
	jQuery("form[data-filter-wall]").unbind().bind("submit", doFilters);
	jQuery("form[data-filter-wall] input[type=radio]").unbind().bind("click", doFilters);
    		
    },
    initWall: function(wall) {
	wall.css({
	    visibility: 'hidden'
	});
	
	if(jQuery(".csstransitions, .csstransforms3d").length) {
	    wall.masonry({
		itemSelector: ".wall-item",
		columnWidth: 121,
		animate: false,
		resizeable: true,
		colCount: 8
	    },
	    function () {
		setTimeout((function(a){
		    return function () {
			Reflow.renault.wall.load(a);
		    };
		})(this), 500);
	    });
	}
	else {
	    wall.masonry({
		itemSelector: ".wall-item",
		columnWidth: 121,
		animate: true, // !(jQuery.browser.msie && jQuery.browser.version < 9),
		resizeable: true,
		colCount: 8,
		animationOptions: {
		    duration: 800,
		    queue: false,
		    complete: Reflow.renault.wall.load
		}
	    });
	}
    		
	wall.find(".question").bind("click", Reflow.renault.wall.open);
	    
	wall.find(".question").each(function(idx, el){
	    
	    var link = jQuery(this),
	    li = link.closest("li");
	    
	    var fontSizeOrg = parseFloat(link.css("font-size")),
	    fontSize = fontSizeOrg;
	    
	    
	    while (link[0].scrollHeight > li[0].scrollHeight || link[0].scrollWidth > li[0].scrollWidth) {
		fontSize -= 1;
		link.css({
		    "font-size": fontSize+"px"
		    });
		if(fontSize < 9) {
		    break;
		}
	    }
	    		
	    // Evite d'être trop prêt des bords
	    link.css({
		"font-size": (fontSize-1)+"px"
	});
    			
	    if (typeof Cufon !== "undefined" && link.find(".question-title").length) {
		
			if (jQuery.browser.msie && jQuery.browser.version < 9) {
			    setTimeout((function(l){
				return function () {
				    Cufon.replace(l.find(".question-num")[0]);
				    Cufon.replace(l.find(".question-title")[0]);
				}
			    })(link),500);
			  /*  Reflow.events.addDOMLoadEvent(function(){
				Cufon.replace(link.find(".question-num")[0]);
				Cufon.replace(link.find(".question-title")[0]);
			    });*/
			}
			else {
			    Cufon.replace(link.find(".question-num")[0], {'z-index': 999});
			    Cufon.replace(link.find(".question-title")[0]);
			}
	    }
	});

	wall.css({
	    visibility: 'visible'
	});
	
	
    },
    initQuestion: function () {
	var sendQuestion = function(args) {
    			    			
	    var form = args.form,
	    url = (args.forcedUrl ? args.forcedUrl : form.attr("action")),
	    data = (args.forcedUrl ? '' : form.serialize()),
	    method = (args.forcedUrl ? 'get' :  form.attr("method")),
	    section = form.closest(".wall-section"),
	    connected = form.data("connected"),
	    ajaxLoader = null;
    			
	    if (connected === false) {
		form[0].submit();
	    }
	    else {
		jQuery.ajax({
		    url: url + ((url.indexOf("?") != -1 || url.indexOf(".html") != -1) ? "&ajax=1" : "?ajax=1"),
		    type: method,
		    data: data,
		    dataType: "html",
		    async: true,
		    cache: true,
		    beforeSend: function (XMLHttpRequest, settings) {
			section.append('<div class="ajax-loader"></div>');
			ajaxLoader = section.find(".ajax-loader");
			ajaxLoader.height(section.height());
		    },
		    success: function(data) {
	    					
			section.append('<div class="wall-popin-question"></div>');
			var popin = section.find(".wall-popin-question");
	    					
			data = Reflow.renault.innerShiv(data);
	
			popin.empty().hide().html(data);
	    					
			Reflow.renault.contentLoader.refreshOnLoad(null, popin, data);
	    					
			var top = section.height() / 2 - popin.height() / 2;
			popin.css({
			    top: top+"px"
			    });
	    					
			if(jQuery.browser.msie && jQuery.browser.version < 9) {
			    section.find(".ajax-loader, .bt-close-sending-question").bind("click", function(e){
				e.preventDefault();
				popin.hide().remove();
				ajaxLoader.hide().remove();
			    });
			    popin.show();
			}
			else {
			    section.find(".ajax-loader, .bt-close-sending-question").bind("click", function(e){
				e.preventDefault();
				popin.fadeOut(300, function(){
				    section.find(".ajax-loader").fadeOut(300, function(){
					jQuery(this).remove();
				    });
				    jQuery(this).remove();
				});
			    });
		    					
			    popin.fadeIn(300);
			}
	    					
			jQuery("#other-question").val("").trigger("blur");
		    },
		    error: function(XMLHttpRequest, textStatus, errorThrown){
			section.find(".ajax-loader").append('<p class="error">' + Reflow.widgets.rsm.getText("popin.ajax.error") + '</p>');
			section.find(".ajax-loader").bind("click", function(e){
			    jQuery(this).fadeOut(300, function(){
				jQuery(this).remove();
			    })
			});
		    }
		});
	    }
	};
	Reflow.renault.validateRegister({
	    id: "#wall-question-form", 
	    callback: sendQuestion
	});
            
	jQuery(".wall-question a.bt-send-question").bind("click", function(e){
	    e.preventDefault();
	    jQuery("#wall-question-form").trigger("submit");
	});
	
	if (jQuery("#wall-question-form").data("popin-url")) {
	     sendQuestion({form: jQuery("#wall-question-form"), forcedUrl: jQuery("#wall-question-form").data("popin-url")});
	}
    },
    init: function () {
	    	
	jQuery(".wall").each(function(e){
	    Reflow.renault.wall.initWall(jQuery(this));
	});
    			    	
	Reflow.renault.wall.initGraph();
	Reflow.renault.wall.initFilters();
	Reflow.renault.wall.initQuestion();
    }
},
    
hubGamme: {
    	
    showSlide: function (e) {
	e.preventDefault();
	var link = jQuery(this),
	slideId = link.attr("href"),
	startPage = link.data("slider");
    		
	if(typeof slideId !== "undefined") {
	    startPage = startPage || 0;
    			
	    slide = jQuery(slideId);

	    if (!Reflow.browser.iTruc) {
		var anySlide = slide.data("AnythingSlider");
	
		if (jQuery.browser.msie && jQuery.browser.version < 9) {
		    jQuery(slideId).css({
			display: "block"
		    });
		    anySlide.setCurrentPage(startPage + 1, true);
		}
		else {
		    slide.css({
			display: "block", 
			opacity: 0
		    });
		    anySlide.setCurrentPage(startPage + 1, true);
		    slide.animate({
			opacity: 1
		    });
		}
	    }
	    else {
		slide.css({
		    display: "block", 
		    opacity: 0
		});
		slide.find(".slide-content")[0].slideScroll.refresh();
		slide.find(".slide-content")[0].slideScroll.scrollToElement(slide.find(".slide-content > li:eq("+startPage+")")[0], 0);
		slide.animate({opacity: 1});
	    }
	}
    },
    	
    hideSlide: function (e) {
	e.preventDefault();
	var link = jQuery(this),
	slideId = link.attr("href");
    		
	if (jQuery.browser.msie && jQuery.browser.version < 9) {
	    jQuery(slideId).css({
		display: "none"
	    });
	}
	else {
	    jQuery(slideId).animate({
		opacity: 0
	    }, function(){
		jQuery(slideId).css({
		    display: "none"
		});
	    });
	}
    },
    	
    initSlide: function (slide) {    		
	var slideHandler = null;
			
	if (!Reflow.browser.iTruc) {
	    jQuery(slide).anythingSlider({
		autoPlay: false,
		pauseOnHover: false,
		buildNextBackButtons: false,
		getInstance: function (objSlider) {
		    slideHandler = objSlider;
		}
	    });
	    jQuery(slide).find(".bt-prev").bind("click", function (e) {
		e.preventDefault();
		slideHandler.goBack();
	    });
	    jQuery(slide).find(".bt-next").bind("click", function (e) {
		e.preventDefault();
		slideHandler.goForward();
	    });
	   // Reflow.renault.slideShowActivated = true;
	}
	else {
	    jQuery(slide).find(".bt-prev, .bt-next").hide();
	  
	    
	    var iSlideWidth = (jQuery(slide).find('li.slide-item').length)*965;
	   jQuery(slide).find('.slide-content').css({
		"width":iSlideWidth+"px"
	    });
    
	    var slideScroll = new iScroll(jQuery(slide).find(".slide-content")[0], { 
		snap:true,
		momentum:false,
		hScrollbar: false,
		vScrollbar: false,
		desktopCompatibility:true 
	    });
	    jQuery(slide).find(".slide-content")[0].slideScroll = slideScroll;
	}
    },
    	
    videoEnd: function() {
	Reflow.renault.videoEndCallback("VideoHubGamme");
    },
    
	videoEndPdt: function() {
	Reflow.renault.videoEndCallback("VideoHubPdt");
    },
    	
    init: function () {
	if (jQuery("#hub-gamme").length) {
	    jQuery("#hub-gamme .slide-hub-gamme").each(function (idx, el) {
		Reflow.renault.hubGamme.initSlide(this);
	    });
    			
	    jQuery("#hub-gamme .cars-list a[data-slider]").bind("click", Reflow.renault.hubGamme.showSlide);
	    jQuery("#hub-gamme .slide-hub-gamme .bt-close").bind("click", Reflow.renault.hubGamme.hideSlide);
	}
    }
},
	
hubAutonomie : {
		
    answersForm: {
	"twizy":{
	    "active": "activeweek, shoppingweek"
	},
	"fluence":{
	    "active": "activeweek, familyweekend, business"
	},
	"zoe":{
	    "active": "activeweek, shoppingweek, familyweekend"
	},
	"kangoo":{
	    "active": "pro, work"
	},
	"user":{}
    },
		
    setCarHandler: function(e){
	var radio = jQuery(this);
			
	Reflow.renault.hubAutonomie.setCar(radio);
    },
		
    setCar: function(radio){
	if(radio && radio.length) {
	    var radioId = radio[0].id;
				
	    jQuery('#type-of-day input[type="radio"]').each(function(idx, el){
		if(Reflow.renault.hubAutonomie.answersForm[radioId].active.indexOf(el.id) == -1) {
		    el.checked = false;
		    el.disabled = true;
		}
		else {
		    el.disabled = false;
		}
	    });
				
	    /*if (!jQuery("#type-of-day .form-content").is(":visible")) {
					jQuery("#type-of-day").addClass("active-line").find(".form-content").slideDown();
					Cufon.replace('#type-of-day .tab-title-1');
				}*/
	    Reflow.renault.hubAutonomie.refresh();
	}
			
    },
		
    setDayType: function (e) {

	if (!jQuery("#type-of-weather .form-content").is(":visible")) {
	    jQuery("#type-of-weather").addClass("active-line").find(".form-content").slideDown();
	    if (typeof Cufon !== "undefined") {
			Cufon.replace('#type-of-weather .tab-title-1');
	    }
	}
	Reflow.renault.hubAutonomie.refresh();
    },
		
    setWeatherType: function (e) {

	if (!jQuery("#type-of-customization .form-content").is(":visible")) {
	    jQuery("#type-of-customization").addClass("active-line").find(".form-content").slideDown();
	    if (typeof Cufon !== "undefined") {
			Cufon.replace('#type-of-customization .tab-title-1');
	    }
	}
	Reflow.renault.hubAutonomie.refresh();
    },
		
    setLoginHandler: function (e) {
	var radio = jQuery(this);
			
	Reflow.renault.hubAutonomie.setLogin(radio);
    },
    setLogin: function (radio) {
	if(radio && radio.length) {
	    var radioId = radio[0].id,
	    wrapper = jQuery("#type-of-customization");
				
	    if (radioId == "yes") {
		//console.log(radio);
		jQuery("input#fb-connected").attr("required", "required");
		wrapper.find('.no .radio').removeClass("radio-required");
		wrapper.find('.no').slideUp();
		wrapper.find('.yes').slideDown();
	    }
	    else if (radioId == "no") {
		jQuery("input#fb-connected").removeAttr("required", "required");
		wrapper.find('.no .radio').addClass("radio-required");
		wrapper.find('.yes').slideUp();
		wrapper.find('.no').slideDown();
	    }
	}
    },
		
    fbConnect: function (e) {
	e.preventDefault();
			
	var link = jQuery(this),
	wrapper = link.parent();
			
	wrapper.find(".error").remove();
			
	var setConnected = function () {
	    jQuery("#fb-connected").val("1");
	    wrapper.append('<p class="ok">' + Reflow.widgets.rsm.getText("facebook.autonomie.connected") + '</p>');
	    wrapper.closest('form').find('input[type="submit"]').trigger("click");
	};
			
	var showError = function (message, fbMessage) {
	    jQuery("#fb-connected").val("");
	    wrapper.append('<p class="error" data-error="' + fbMessage + '">' + message + '</p>');
	};
			
	FB.init({
	    appId: Reflow.widgets.rsm.getText("facebook.autonomie.app-id"), 
	    status: true, 
	    cookie: true, 
	    xfbml: true
	});
	FB.getLoginStatus(function(response) {
	    if (response.session) {
		setConnected();
	    } else {
		FB.login(function(response) {		
		    if (response.session) {
			if (response.perms) {
			    setConnected();
			}
			else {
			    var fbMessage = response && response.error ? response.error.message : "";
			    showError(Reflow.widgets.rsm.getText("facebook.autonomie.error-authorization"), fbMessage);
			}
		    }
		    else {
			var fbMessage = response && response.error ? response.error.message : "";
			showError(Reflow.widgets.rsm.getText("facebook.autonomie.error-authentication"), fbMessage);
		    }
		}, 
		{
		    perms: 'friends_photos,friends_about_me,offline_access,user_birthday,user_education_history,user_hometown,user_interests,status_update,user_relationships,user_work_history,user_relationship_details,user_religion_politics,publish_stream,user_status,user_photos,user_videos'
		});
	    }
	});
    },
		
    refresh: function() {
	/* if(jQuery('#type-of-car input:checked').length == 0) {
		    jQuery('#type-of-day, #type-of-weather, #type-of-customization').removeClass("active-line").find(".form-content").slideUp();
		    Cufon.replace('#type-of-day .tab-title-1, #type-of-weather .tab-title-1, #type-of-customization .tab-title-1');

		    jQuery('#type-of-day input:checked, #type-of-weather input:checked, #type-of-customization input:checked').attr('checked','');
	    }
	    else */ if(jQuery('#type-of-day input:checked').length == 0 || jQuery('#type-of-car input:checked').length == 0) {
	    jQuery('#type-of-weather, #type-of-customization').removeClass("active-line").find(".form-content").slideUp();
	    if (typeof Cufon !== "undefined") {
			Cufon.replace('#type-of-weather .tab-title-1, #type-of-customization .tab-title-1');
	    }
	    jQuery('#type-of-weather input:checked, #type-of-customization input:checked').attr('checked','');
	    if(jQuery('#type-of-car input:checked').length == 0) {
		jQuery('#type-of-day input[type=radio]').attr("disabled", "disabled");
	    }
	}
	else if(jQuery('#type-of-weather input:checked').length == 0) {
	    jQuery('#type-of-customization').removeClass("active-line").find(".form-content").slideUp();
	    if (typeof Cufon !== "undefined") {
			Cufon.replace('#type-of-customization .tab-title-1');
	    }
	    jQuery('#type-of-customization input:checked').attr('checked','');
	}
    },
		
    cancel: function (e) {
	e.preventDefault();
	jQuery('#autonomy-hub input[type=radio]:checked').attr('checked','');
	Reflow.renault.hubAutonomie.refresh();
    },
		
    init: function(){
	if (jQuery('#autonomy-hub').length) {				
				
	    Reflow.renault.hubAutonomie.refresh();
				

	    jQuery('#type-of-car input').live('change', Reflow.renault.hubAutonomie.setCarHandler);
	    Reflow.renault.hubAutonomie.setCar(jQuery('#type-of-car input:checked'));
				
	    jQuery('#type-of-day input').live('change', Reflow.renault.hubAutonomie.setDayType);
	    jQuery('#type-of-weather input').live('change', Reflow.renault.hubAutonomie.setWeatherType);
				

	    jQuery('#type-of-customization input[name="facebook"]').live('change', Reflow.renault.hubAutonomie.setLoginHandler);
	    Reflow.renault.hubAutonomie.setLogin(jQuery('#type-of-customization input[name="facebook"]:checked'));
				
	    jQuery("a[data-fb-connect]").live("click", Reflow.renault.hubAutonomie.fbConnect);
	    jQuery("#reset-form").live("click", Reflow.renault.hubAutonomie.cancel);
	}
    }
},
    
placeHolderFix: function () {
    if(typeof Modernizr !== "undefined" && !Modernizr.input.placeholder){
	jQuery("input").each( function(){
	    if(jQuery(this).val()=="" && typeof jQuery(this).attr("placeholder")!="undefined"  && jQuery(this).attr("placeholder")!=""){
		var input = jQuery(this),
		inputPos = input.position();
		input.after('<label for="' + input.attr("id") + '" class="input-placeholder">' + input.attr("placeholder") + '</label>');
		var ph = input.siblings(".input-placeholder");
					
		var css = {
		    "top": inputPos.top,
		    "left": inputPos.left,
		    "font-size": input.css("font-size"),
		    "font-weight": input.css("font-weight"),
		    "color": input.css("color"),
		    "padding-top": input.css("padding-top"),
		    "padding-bottom": input.css("padding-bottom"),
		    "padding-left": input.css("padding-left"),
		    "padding-right": input.css("padding-right"),
		    "width": input.css("width"),
		    "height": input.css("height")
		};
					
		ph.css(css);

		input.focus(function(){
		    ph.hide();
		});
		input.blur(function(){
		    if(jQuery(this).val()=="") ph.show();
		});
	    }
	});
    }
},
    
precom: {
    	
    init: function() {
	/** car color selection **/
	if (jQuery("#color-choice").length > 0 && jQuery("input[name='idColor']").length > 0) {
	    jQuery("input[name='idColor']").bind("click",
		function(e) {
		    if (jQuery(this).data("picture") != "") {
			jQuery(".color-preview").css("backgroundImage", "url(" + jQuery(this).data("picture") + ")");
		    }
		});
	    if(jQuery("input[name='idColor']:checked").length) {
		jQuery("input[name='idColor']:checked").trigger("click");
	    }
	    else {
		jQuery(".color-preview").css("backgroundImage", "url(" + jQuery(".color-preview").data("picture-start") + ")");
	    }
	}
    }
    	
},

popinOnLoad: {
	init: function () {
		if (jQuery("body[data-popin]").length > 0) {
			if(jQuery.cookie){
				if (jQuery.cookie("Renault-ZE-autoLoadPopin") == null) {
					
					jQuery.cookie("Renault-ZE-autoLoadPopin", jQuery("body[data-popin]"));
					
					var popinId = "autoLoadPopin";
					
					Reflow.widgets.popinManager.create({
						id: popinId,
						popinTemplate: "video"
					});	 
					
					var url = jQuery("body[data-popin]").data("popin");
					url = (url.indexOf("?") != -1 || url.indexOf(".html") != -1) ? url += "&ajax=1": url += "?ajax=1";
					
					Reflow.widgets.popinManager.popin(popinId).load(url);
					Reflow.widgets.popinManager.popin(popinId).open();
					
						
					Reflow.widgets.popinManager.popin(popinId).addCallback({
						'beforeClose': function(args) {
							if (swfobject.getFlashPlayerVersion().major >= 10) {
								var currentVideo = args.popin.find("object")[0];
								if (currentVideo) {
								try {
									currentVideo.stopVideoJS();
								} catch(e) {
								}
								}
							} else {
								var currentVideo = args.popin.find("video")[0];
											
								if (currentVideo) {
								try {
									currentVideo.pause();
								} catch(e) {
								}
								}
							}
						}
					});
				}
			}
		}
	}
},

boxAccordion: {
    switchUs: function () {
		var transEndEventNames = {
			'WebkitTransition' : 'webkitTransitionEnd',
			'MozTransition'    : 'transitionend',
			'OTransition'      : 'oTransitionEnd',
			'msTransition'     : 'msTransitionEnd', // maybe?
			'transition'       : 'transitionEnd'
		},
		transEndEventName = transEndEventNames[ Modernizr.prefixed('transition') ];
		jQuery('#ze-box-accordion>ul>li:not(.open)').live('click',function(){
			var currentItem = jQuery(this);
		//1. close previous opened
			if(transEndEventName)	currentItem.siblings('.open').addClass('closing');
		//2. detect end of closing
			jQuery('#ze-box-accordion>ul>li.closing').live(transEndEventName,function(event){
				event.stopPropagation();
			//3. add class reverse on tiles if necessary
				jQuery('#ze-box-accordion>ul>li.reverse').removeClass('reverse');
				for(var i=0;i<=currentItem.nextAll().length;i++){
					if(i/2 == Math.round(i/2)) {
						currentItem.nextAll(':eq('+parseInt(i-1)+')').addClass('reverse');
					}
				}
				for(var i=0;i<=currentItem.prevAll().length;i++){
					if(i/2 == Math.round(i/2)) {
						currentItem.prevAll(':eq('+parseInt(i)+')').addClass('reverse');
					}
				}
			//4. remove transition + open styles
				jQuery(this).removeClass('closing');
				jQuery('#ze-box-accordion>ul>li.open').removeClass('open');
			//5. add open styles 
				currentItem.addClass('open').addClass('opening');
				jQuery('#ze-box-accordion>ul>li.opening').live(transEndEventName,function(event){
					jQuery(this).removeClass('closing');
				})
			})
			
			 if (jQuery.browser.msie || jQuery('.no-cssanimations').length) {	
				var thisLi = jQuery(this);
				thisLi.siblings('li.open').css('width','672px').removeClass('open').css({
					'width':'81px'
				});
				thisLi.addClass('open').css('width','81px').css({
						'width':'672px'
				})
				//3. add class reverse on tiles if necessary
				jQuery('#ze-box-accordion>ul>li.reverse').removeClass('reverse');
				for(var i=0;i<=currentItem.nextAll().length;i++){
					if(i/2 == Math.round(i/2)) {
						currentItem.nextAll(':eq('+parseInt(i-1)+')').addClass('reverse');
					}
				}
				for(var i=0;i<=currentItem.prevAll().length;i++){
					if(i/2 == Math.round(i/2)) {
						currentItem.prevAll(':eq('+parseInt(i)+')').addClass('reverse');
					}
				}
				jQuery(this).next().removeClass('reverse');
			}
			
		})
		jQuery('#ze-box-accordion>ul>li:not(.open) a').live('click',function(e){
			e.preventDefault();
		})
		jQuery('#ze-box-accordion>ul>li:first').addClass('open').removeClass('reverse');
    },
    init: function () {
		if(jQuery('#ze-box-accordion').length){
			jQuery('#ze-box-accordion>ul>li.open').removeClass('open');
			Reflow.renault.boxAccordion.switchUs();
			(jQuery(document.location.hash).length) ? jQuery(document.location.hash).trigger('click') : jQuery('#ze-box-accordion>ul>li:first').trigger('click');
		}
	}
	    	
},


dispatchMap: {
	data:{
		thisPlace:'',
		timeToGo:'',
		thisMap:'',
		continents:[],
		countries:[],
		eventTypeEnter:'mouseenter',
		eventTypeLeave:'mouseleave'
	},
    mapHighlights: function () {
		// 1. hide country layers
		jQuery('.dispatch-page .country-layer, .dispatch-page .no-lg').addClass('js-move');
		//2. mouse over behaviours
		jQuery('.dispatch-page #world-map-zone area, .dispatch-page #europe-map area').bind(Reflow.renault.dispatchMap.data.eventTypeEnter,function(){
			Reflow.renault.dispatchMap.data.thisMap = jQuery(this).closest('[id*=map-zone]');
			// a. hide previous open layers
			clearTimeout(Reflow.renault.dispatchMap.data.timeToGo);
			jQuery('.display-layer').removeClass('display-layer').addClass('js-move');
			//b. uncolor previous active zone
			for(var i=0;i<Reflow.renault.dispatchMap.data.continents.length;i++){
				Reflow.renault.dispatchMap.data.thisMap.removeClass(Reflow.renault.dispatchMap.data.continents[i]);
			}
			for(var i=0;i<Reflow.renault.dispatchMap.data.countries.length;i++){
				Reflow.renault.dispatchMap.data.thisMap.removeClass(Reflow.renault.dispatchMap.data.countries[i]);
			}
			//c. color zone
			Reflow.renault.dispatchMap.data.thisPlace = jQuery(this).data('zone');
			Reflow.renault.dispatchMap.data.thisMap.addClass('hovered').addClass(Reflow.renault.dispatchMap.data.thisPlace);
			//d. show associated layer
			jQuery('[data-target='+Reflow.renault.dispatchMap.data.thisPlace+']').removeClass('js-move').addClass('display-layer');
		});
		jQuery('.dispatch-page #world-map-zone area, .dispatch-page #europe-map area').bind(Reflow.renault.dispatchMap.data.eventTypeLeave,function(){
		//3. mouse leave behaviours
			var thisItem = jQuery(this),
				thisRelatedLayer = jQuery('.country-layer[data-target='+thisItem.data('zone')+']');
			//A. if associated layer but no timeout (countries)
			if(thisRelatedLayer.length && thisRelatedLayer.parent().attr('id') == 'europe-map-zone'){
				thisRelatedLayer.bind('mouseleave',function(){
				Reflow.renault.dispatchMap.mapLayers(thisItem)
				})
			}
			//B. if associated layer
			else if(thisRelatedLayer.length){
				//a. let users time to reach layer
				Reflow.renault.dispatchMap.data.timeToGo = setTimeout(function(){Reflow.renault.dispatchMap.mapLayers(thisItem)},600);
				//b. clear timer if mouse over layer
				thisRelatedLayer.bind('mouseenter',function(){
					clearTimeout(Reflow.renault.dispatchMap.data.timeToGo)
				});
				jQuery('.display-layer').bind('mouseleave',function(){
					clearTimeout(Reflow.renault.dispatchMap.data.timeToGo);
					Reflow.renault.dispatchMap.mapLayers(thisItem);
				});
			}
			//C. No associated layer
			else{
				Reflow.renault.dispatchMap.mapLayers(thisItem);
			}
		})
    },
	mapLayers: function(target){
		if (jQuery('[data-target='+target.data('zone')+']').length) jQuery('[data-target='+target.data('zone')+']').removeClass('display-layer').delay(300).addClass('js-move');
		Reflow.renault.dispatchMap.data.thisMap.removeClass('hovered');
		Reflow.renault.dispatchMap.data.thisMap.removeClass(target.data('zone'));
	},
	mapLg: function(){
		jQuery('.dispatch-page .no-lg').each(function(){
			var thisItem = jQuery(this),
				arr= [],
				evenArr = [],
				oddArr = [],
				splitted = jQuery('area[data-zone='+thisItem.data('target')+']').attr('coords').split(','),
				i=0,
				j=0,
				arrLentgh,
				aLentgh;
			for(arrLentgh=splitted.length; i<arrLentgh;i++){
				splitted[i] =  parseInt(splitted[i])
			}
			for(aLength=splitted.length;j<aLength;j++){
				if(j/2 == Math.round(j/2)){
					//left
					oddArr.push(splitted[j]);
				}
				else{
					//top
					evenArr.push(splitted[j]);
				}
			}
			function sortNumber(a,b){
				return a - b;
			}
			var coordsX = oddArr.sort(sortNumber)
			var coordsY = evenArr.sort(sortNumber)
			jQuery(this).css({
				'left':coordsX[0]-20+"px",
				'top':coordsY[0]-40+"px"
			})
		})
	},
	mapZoom: function(){
		jQuery('.dispatch-page #world-map-zone area[data-zoom]').bind('click',function(event){
			event.preventDefault();
			jQuery('#europe-map-zone').addClass('undressMe');
			jQuery('#world-map-zone').addClass('coverMe');
		})
		jQuery('.dispatch-page #europe-map-zone a[data-unzoom]').bind('click',function(event){
			event.preventDefault();
			jQuery('#europe-map-zone').removeClass('undressMe');
			jQuery('#world-map-zone').removeClass('coverMe');
		})
	},
	
	apiHelper: function(){
		
		
		
		
	},
	
	
    init: function () {
		if(jQuery('.dispatch-page #world-map-zone').length){
			jQuery('#world-map-zone area').each(function(){				
				Reflow.renault.dispatchMap.data.continents.push(jQuery(this).data('zone'));
			})
			jQuery('.dispatch-page #europe-map-zone area').each(function(){				
				Reflow.renault.dispatchMap.data.countries.push(jQuery(this).data('zone'));
			})
			Reflow.renault.dispatchMap.mapHighlights();
			if(jQuery('.dispatch-page #world-map-zone area[data-zoom]').length){
				Reflow.renault.dispatchMap.mapZoom();
			}
			if(/iPhone|iPad|iPod|Android|blackberry|palm/gi.test(navigator.userAgent)){
				Reflow.renault.dispatchMap.data.eventTypeEnter = 'click';
				Reflow.renault.dispatchMap.data.eventTypeLeave = 'click';
			}
			if(jQuery('.dispatch-page .no-lg').length){
				Reflow.renault.dispatchMap.mapLg();
			}
		}
	}
	    	
},

help24 : function () {
	
	if(jQuery("#vee24LiveHelpTab").length > 0) {
		
		vee24.api.helpMe();
	}
	else {
		window.setTimeout(function () {
			Reflow.renault.help24();
		}, 2000);
	}
	
},

init: function init() {
	
	/* API HELPER */
	jQuery('.help-button a, .product-page-button a').click(function(){  
		vee24.api.helpMe();	
		return false;	
	});
	
	if (typeof jQuery("[data-trigger-help]") !== "undefined" && jQuery("[data-trigger-help]").data("trigger-help") == true ) {
		Reflow.renault.help24();
	}
	
		
	/* Accessibility */
    Reflow.renault.accessibleLinks();
        
    /* Impression */
    Reflow.renault.printPage.init();
        
    // Google Map
    Reflow.renault.gmapManager.init();
    	
    // Company carousel
    Reflow.renault.company.init();

    // Social networks
    Reflow.renault.initSocial();

    // Twizy Lab Design
    Reflow.renault.twizyLab.init();
    
    // Ajax video Loader
    Reflow.renault.videoLive.init();
    
    // Ajax Content Loader
    Reflow.renault.contentLoader.init();
    
    // Wall
    Reflow.renault.wall.init();
    	    	
    /* Slideshow */
    if (jQuery('.slideshow:visible').length) {
	Reflow.renault.slideShow();
    }
        
    /* Hub gamme */
    Reflow.renault.hubGamme.init();

    /** slide init for project ze **/
    Reflow.renault.zeProject.init();

    Reflow.renault.creativeUtility();    

    /* Gallery management */
    Reflow.renault.photoGalleryManager();
	
    /* ZE box Accordion */
    Reflow.renault.boxAccordion.init();
	
    /* Dispatch page */
    Reflow.renault.dispatchMap.init();
        
    Reflow.renault.placeHolderFix();

        
    /** ajax link interception **/
    Reflow.renault.intercept(".tabs-controller-wrapper .tabs li a", ".tabs-wrapper", ".pager a");
    Reflow.renault.intercept(".main-ajax-place-holder .tabs li a", ".sub-ajax-place-holder", ".pager a"); // => Project ZE
    Reflow.renault.intercept(".context-nav li a", ".main-ajax-place-holder", ""); // => ZE Driver

    /** forms management **/
    if (typeof formTranslation == "undefined") formTranslation = {};
        
    if (typeof jQuery.tools != "undefined") {
		jQuery("form").attr("novalidate","novalidate");
		//treat all forms and find required="required" fields or ".radio-required" classes fields to check
		Reflow.renault.initForms("form:not(#wall-question-form, #form-company-calc)");
    }
        
    /* Précommande */
    Reflow.renault.precom.init();

    /* Videos */
    Reflow.renault.videoManager.init();

    /*
	    * Twizy contest
	    */
    Reflow.renault.twizyCompetition();

    /*
	    * ZE Driver pages
	    */
    Reflow.renault.zeDriver.init();

    /* ie global for clickable images into labels */
    if (jQuery.browser.msie) {
	jQuery("label img").bind("click",
	    function(e) {
		jQuery(this).parent("label").siblings("input[type='radio']").trigger("click").trigger("change");
	    });
    }
    /* nav my account*/
    Reflow.renault.initMyAccountNav();
        
    /* hash management */        
    //Reflow.renault.manageHash();
		
		
    /* Hub autonomie */
    Reflow.renault.hubAutonomie.init();
        
}
};

    /**
   * Fix HTML5 Tag when downloaded with AJAX on IE
   */
    // http://jdbartlett.github.com/innershiv
Reflow.renault.innerShiv = (function(){var d,r;return function(h,u){if(!d){d=document.createElement('div');r=document.createDocumentFragment();/*@cc_on d.style.display = 'none'@*/}var e=d.cloneNode(true);/*@cc_on document.body.appendChild(e);@*/e.innerHTML=h.replace(/^\s\s*/, '').replace(/\s\s*$/, '');/*@cc_on document.body.removeChild(e);@*/if(u===false)return e.childNodes;var f=r.cloneNode(true),i=e.childNodes.length;while(i--)f.appendChild(e.firstChild);return f}}());

Reflow.events.addDOMLoadEvent(function(){
    /** video management **/
    Reflow.renault.videoPopinManager();


    /* Ouverture de popin au chargement de la page */
    Reflow.renault.popinOnLoad.init();
});
jQuery(document).ready(function() {
    //preload images
    Reflow.renault.preloadingImages("data-url");
    Reflow.renault.init();
});

