	/**
	 * FLASH NAME must be RCISimulator because of the *$!!� makolab financial flash and IE
	 */
	var flashId="RCISimulator";
	
	
	function openPopup(url) {
		window.open(url,"popupMap24","width=570,height=520,menubar=no,location=no,status=no,scrollbars=no,resizable=no,status=no,toolbar=no,location=no")
	}
	
	function resizeFromFlash(height) {
		if(!ajaxNav.flexOpen){
			resizePageBody(height, callResizeAppFromFlash);
		}
		else{
			resizeFlash(height);
		}
	}
	function callResizeAppFromFlash() {
		var object = document.getElementById(flashId);
		object.resizeApp();
	}
	
	function resizeFlash(height) {
		var object = document.getElementById(flashId);
		object.style.height = height + 'px';
		object.height = height;
		object.parentNode.style.height = object.style.height;
	}
	
	function updateMentions(arr) {	
		var mentionsLegalesDiv = document.getElementById('mentionsLegales');
		mentionsLegalesDiv.innerHTML="";
		for (var i=0; i<arr.length; i++) {
			var elm = document.createElement('span');
			elm.innerHTML = '&nbsp;&nbsp;(' + (i+1) + ')' + ' ' + arr[i] + '.';
			mentionsLegalesDiv.appendChild(elm);
		}
	}
	
	function goToHome() {
		var flash = document.getElementById(flashId);
		if (flash) {
			flash.goToHome();
			return false
		} else return true;
	}

	function getViewportDimensions() {
		var d = document.documentElement;
		var object = document.getElementById(flashId);
		var objectPosTop = findPos(object)[1];
		return {
			x : d.scrollLeft,
			y : d.scrollTop,
			height : d.clientHeight,
			width : d.clientWidth,
			yApp : objectPosTop
		};
	}
	
	
	function executeStats(locale, params) {
		var netstat_sitename = "renault-fr";
		var netstat_countername = locale + ".minisite.TopRenault." + params;
		//trace('-&nbsp;'+netstat_countername+'<br/>');
		if (window.sitestat_update) sitestat_update(netstat_sitename, netstat_countername);
	}
	
	function trace() {
		var debug = document.getElementById('debug');
		if (!debug) {
			debug = document.createElement('div');
			debug.id = 'debug';
			debug.style.position = 'fixed';
			debug.style.top = 0;
			debug.style.left = 0;
			debug.style.width = '250px';
			debug.style.height = '500px';
			debug.style.border = '1px solid #000';
			debug.style.background = "#fff";
			debug.style.overflow = 'auto';
			document.body.appendChild(debug);
		}
		debug.scrollTop = debug.scrollHeight;
		debug.innerHTML+= '<br/>' + Array.prototype.slice.apply(arguments).join(', ');
	}

	function bugdetPlannerPopup() {
		window.open('/static/html/popup_budgetPlanner.html', 'budgetPlanner', 'width=520,height=415, scrollbars=no, menu=no, status=no, resizable=no, toolbar=no, location=no');
	}                
	
	function scrollToFlashPosition(flashPosTop) {
		var object = document.getElementById(flashId);
		var objectPosTop = findPos(object)[1];
		document.documentElement.scrollTop = document.body.scrollTop = objectPosTop + flashPosTop;
	}
	
	function findPos(obj) {
		var curleft = curtop = 0;
		if (obj.offsetParent) {
			do {
					curleft += obj.offsetLeft;
					curtop += obj.offsetTop;
				} while (obj = obj.offsetParent);
		}
		return [curleft,curtop];
	}
	
/* PARTIE FINANCEMENT */


	
	// VN data must be by the components to this the page (via the component param)
    var _DisplaySimulatorRenderer_ = {    
        // the finance parameter will be added by the flash callback
        "deposit" : "",
        "duration" : "",
        "insurance" : "",
        "offerType" : ""
    };



     function __Display_Simulator__updateFinValues() {		
		//Retourne les nouvelles valeurs a l'application Flex
		var flash = document.getElementById(flashId);
		if (flash) {
			flash.updateFinanceInfo(_DisplaySimulatorRenderer_);
			return false
		} else return true;		
    }

    // Javascript routine called by the flash when user change slider value
    // code directly taken from example at http.//fin.makolab.pl
    var _DisplaySimulatorRenderer_timeoutId=-1;

    //var InternetExplorer = navigator.appName.indexOf("Microsoft") != -1;
    
    function RCISimulator_DoFSCommand(command, args) {
    	  //var RCISimulatorObj = InternetExplorer ? RCISimulator : document.RCISimulator;
			var RCISimulatorObj = document.getElementById(flashId);
    	//trace(command, args)
        if (command == "SendFinanceDataToRSite"){
            arg = args.split(",")
	        // data given via the flash
	        _DisplaySimulatorRenderer_.carPrice   = arg[0];
	        _DisplaySimulatorRenderer_.deposit    = arg[1];
	        _DisplaySimulatorRenderer_.duration   = arg[2];
	        // insurrance are the concatenation of arg 5 to 7    
	        _DisplaySimulatorRenderer_.insurance  = arg[5] +","+arg[6] +","+ arg[7];
	        
	        _DisplaySimulatorRenderer_.offerType  = arg[11];
	        _DisplaySimulatorRenderer_.genericParam = arg[14];
	
	        // Prevention : Because huges flash simulators call, AJAX calls are delayed
	        clearTimeout(_DisplaySimulatorRenderer_timeoutId);
	        _DisplaySimulatorRenderer_timeoutId = setTimeout(__Display_Simulator__updateFinValues, 300);
     	}     	
    }	
	
	if (navigator.appName &&
        navigator.appName.indexOf("Microsoft") != -1 &&
        navigator.userAgent.indexOf("Windows") != -1 &&
        navigator.userAgent.indexOf("Windows 3.1") == -1)
	    {
	        document.write('<SCRIPT LANGUAGE=VBScript\> \n');
	        document.write('on error resume next \n');
	        document.write(
	                'Sub RCISimulator_FSCommand(ByVal command, ByVal args)\n');
	        document.write(
	               ' call RCISimulator_DoFSCommand(command, args)\n');
	        document.write('end sub\n');
	        document.write('</SCRIPT\> \n');
	    }
   
    
    
	var AjaxNavigation = new Class({
		initialize : function(){
			var _self = this;
			this.oLaunchers = $$('a.ajaxLink');
			//conteneur du futur code HTML & wrapper
			this.oAjaxHtmlContainer = new Element('div');
			this.oAjaxHtmlWrapper = new Element('div')
				.injectBefore($('footer'))
				.setStyles({
					'height' : 0,
					'overflow' : 'hidden'
			});
			this.oAjaxHtmlWrapper.adopt(this.oAjaxHtmlContainer);
			this.flexOpen = true;
			//flash
			this.oFlash = $('TopRenaultFlexFlashDiv');
			//this.oFlash.style.overflow = 'hidden';
			
			this.oLaunchers.each(function(oLink){
				_self.observe(oLink);
			})
			
		},
		observe : function(oLink){
			var _self = this;
			oLink.addEvent('click', function(e){
				new Event(e).stop();
				document.location.hash = '#action=folded';
				_self.remote(oLink);
			})
		},
		remote : function(oLink){
			var _self = this;
			//si déjà une réponse, pas d'appel ajax appel ajax
			if (oLink.hasResponse){
				if (this.flexOpen){
					this.onResponse(oLink.reponse, '', true);
					this.flexOpen = false;
				}else{
					this.onResponse(oLink.reponse);
				}
			}else{
				var url = oLink.href + '?nonav=1';
				var myRemote = new Ajax(url,{
					method: 'get',
					onRequest : function(){
					},
					onSuccess : function(sResponse){
						if (_self.flexOpen){
							_self.onResponse(sResponse, '', true);
							_self.flexOpen = false;
						}else{
							_self.onResponse(sResponse);
						}

					},
					onComplete : function(sResponse){
						//j'ai ma réponse je l'enregistre
						oLink.hasResponse = true;
						oLink.reponse = sResponse;
						
						
					}
				}).request();
			}
		},
		onResponse : function(sResponse, iFlashHeight, flashMode, callback){
			var _self = this;
			if (sResponse){
				sResponse.substring(sResponse.indexOf('<body'),sResponse.lastIndexOf('</body>')).replace(/<body(\s.*)?\>/,'');

				this.oAjaxHtmlContainer.innerHTML = sResponse;
				//on reevalue les scripts de la page introduite
				this.oAjaxHtmlContainer.getElements('script').each(function(script){
					eval(script.innerHTML);
				})
			}
			
			if (flashMode){
				_self.iSize = parseInt(_self.oAjaxHtmlContainer.offsetHeight);
				if (iFlashHeight){
					_self.flexOpen = true;
					var iCtn1Height = iFlashHeight;
					var iCtn2Height = 0;
				} else {
					var iCtn1Height = 24;
					var iCtn2Height = _self.iSize;
				}


				_self.aEffectsElms = [_self.oFlash, _self.oAjaxHtmlWrapper];

				//lancement effet
				_self.effect(iCtn1Height, iCtn2Height, callback);
			}else{
				_self.oAjaxHtmlWrapper.setStyle('height', 'auto');
			}
			
			
			
		},
		effect : function(iCtn1Height, iCtn2Height, callback){
			var _self = this;
			this.myEffect = new Fx.Elements(_self.aEffectsElms,{
				onComplete : function(){
					//resizeFlash(iCtn1Height);
					if (iCtn2Height>0)  //patch pour mettre automatiquement la hauteur de la boite qui est agrandit en height auto (pour gérer les agrandissement des contenus
						_self.oAjaxHtmlWrapper.setStyle('height', 'auto');
					if(callback) callback();
				},
				onMotion : function(){
					resizeFlash(parseInt(this.now[0].height));
				}
				/*,
				onStart : function(){
					_self.oFlash.style.overflow = 'hidden';
				}*/
			});
			this.myEffect.start({
			    '0': {
			        'height': iCtn1Height
			    },
				'1': {
					'height': iCtn2Height
				}
			});
		}
	})
	function toggleMe(id){
		var elm = document.getElementById(id);
		if (elm.className.match(/\mentionsLegalesOpened\b/)){
			elm.className = 'mentionsLegales';
		}else{
			elm.className += ' mentionsLegalesOpened';
		}
	}
	
	function resizePageBody(fHeight, callbackForAnimation){
		var fHeight = fHeight ? fHeight : 700;
		ajaxNav.onResponse(null, fHeight, true, callbackForAnimation);
	}
	
	window.addEvent('domready', function(){		
		ajaxNav = new AjaxNavigation();
	})
	
	
	//custom appli toprenault
	Fx.Base.implement({
		step: function(){
			var time = $time();
			if (time < this.time + this.options.duration){
				this.delta = this.options.transition((time - this.time) / this.options.duration);
				this.setNow();
				this.increase();
				this.fireEvent('onMotion', this.element);
			} else {
				this.stop(true);
				this.set(this.to);
				this.fireEvent('onComplete', this.element, 10);
				this.callChain();
			}
		}
	});
	

	//correction pour IE6, bug a un moment le title est remplace par le hash de l'url
	var lastTitle = document.title;
	if (document.all && window.attachEvent && /MSIE [56]/.test(navigator.userAgent)) {
		setInterval(titleChecker, 100);
	}

	function titleChecker() {
		var newTitle = document.title;
		if (lastTitle != newTitle) {
			if (newTitle.match(/\action=/))
				document.title = lastTitle;
			else 
				lastTitle = newTitle;
		}
	}

String.extend({
    substitute: function(object, regexp){
        return this.replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name){
            if (match.charAt(0) == '\\') return match.slice(1);
            return (object[name] != undefined) ? object[name] : '';
        });
    },
    removeacc: function(){
        // A OPTMISER
        var torem = this;
        torem = torem.split('');
        toremout = new Array();
        toremlen = torem.length;
        var sec = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž';
        var rep = ['A','A','A','A','A','A','a','a','a','a','a','a','O','O','O','O','O','O','O','o','o','o','o','o','o','E','E','E','E','e','e','e','e','e','C','c','D','I','I','I','I','i','i','i','i','U','U','U','U','u','u','u','u','N','n','S','s','Y','y','y','Z','z'];
        for (var y = 0; y < toremlen; y++){
            if (sec.indexOf(torem[y]) != -1){
                toremout[y] = rep[sec.indexOf(torem[y])];
            }else{
                toremout[y] = torem[y];
            }
        }
        toascout = toremout.join('');
        return toascout;
    },
    removeponct : function(){
        // A OPTMISER
        var torem = this;
        torem = torem.split('');
        toremout = new Array();
        toremlen = torem.length;
        var sec = ' .-_²';
        var rep = ['','','','',''];
        for (var y = 0; y < toremlen; y++){
            if (sec.indexOf(torem[y]) != -1){
                toremout[y] = rep[sec.indexOf(torem[y])];
            }else{
                toremout[y] = torem[y];
            }
        }
        toascout = toremout.join('');
        return toascout;
    }
});

function generateOutboundsClick(){
    $(document.body).addEvent("click", function(e){
        var parentone = $(e.target).getParent();
        if(parentone.nodeName != "HTML"){
            var parenttwo = $(e.target).getParent().getParent() || $(document.body);
        }else{
            var parenttwo = parentone;
        }
        if(parenttwo.nodeName != "HTML"){
            var parentthree = $(e.target).getParent().getParent().getParent();
        }else{
            var parentthree = parentone;
        }

        if(e.target.nodeName == "A"){
            outBoundClick(e.target, e);
        }else if(parentone && parentone.nodeName == "A"){
            outBoundClick(parentone, e);
        }else if(parenttwo && parenttwo.nodeName == "A"){
            outBoundClick(parenttwo, e);
        }else if(parentthree && parentthree.nodeName == "A"){
            outBoundClick(parentthree, e);
        }
    });
}

function outBoundClick(elem,e){
    var reg=new RegExp("[/]+", "g");
    var href= elem.href.split(reg);
    var documentLoc = window.location.hostname.split(reg);

    if(href[0] == "http:" && href[1] != documentLoc && href[1] != "www.addthis.com"){
        if(elem.target && elem.target == "_blank"){
            sendTracker("Outbound links","Goto "+elem.href,window.location.href);
        }else{
            new Event(e).stop();
            sendTracker("Outbound links","Goto "+elem.href,window.location.href);
            setTimeout(function(){
                window.location.href=elem.href;
            },300);
        }
    }
}

/* 	Fonction sendTracker pour analytics
*
*	sendTracker(categorie, action, opt_label, opt_value)
*	appelle la fonction gaq_push(['_trackEvent',category, action, opt_label, opt_value)
*	pour les statistiques de visite
*
*	Detail des parametres :
*	category (obligatoire)
*	Cet attribut représente le niveau de regroupement 0 des événements.
*
*	action (obligatoire)
*	Cet attribut est destiné à identifier le type d’action auditée.
*
*	label (optionnel)
*	Cet attribut est destiné à identifier précisément l’action auditée.
*
*	value (optionnel)
*	Cet attribut est destiné à recevoir une valeur à imputer à chaque appel pour les
*	critères précédents.
*
*	Reduit les params en lowercase
*/
    function sendTracker(category, action, label, value){
    // On passe tout en lowercase
    var categorie = ""+category || "";
    var options = ""+action || "";

    var catPush = categorie.removeacc().toLowerCase();
    var actPush = options.removeacc().toLowerCase();

    var optlabPush = "";
    if(label){
        optlabPush = label.removeacc().toLowerCase();
    }

    var optvalPush = null;
    if(value){
        if(typeof(value)!='undefined'){
            optvalPush = value;
        }
    }

    if(optvalPush != null && optvalPush != ""){
        if(typeof(optvalPush)!='undefined'){
            optlabPush += " "+optvalPush;
        }
    }

    _gaq.push(['_trackEvent', catPush, actPush, optlabPush]);
}

window.addEvent('domready', function() {
    generateOutboundsClick();
});
