document.write('<script type="text/javascript" src="/js/myrenault/BlockMessagerie.js"></script>');
document.write('<script type="text/javascript" src="/js/myrenault/BlockCarouselDiapo.js"></script>');
document.write('<script type="text/javascript" src="/js/myrenault/BlockGauge.js"></script>');
document.write('<script type="text/javascript" src="/js/myrenault/BlockDeleteAccount.js"></script>');

var browserIsIE = false;
timeoutClone = false;

if(navigator.appName == "Microsoft Internet Explorer"){
    browserIsIE = true;
}

window.addEvent('domready', function(){
	Cufon.replace($$('.cufoned'));
    addFF2Class();
	
	
	
	var viewEditSwitcher = $$(".viewEditSwitch");
	if(viewEditSwitcher.length != 0){
		viewEditSwitcher.each(function(element, index){
			new ViewEditSwitch(element);
		});
	}
	
	var labelBlocksHover = $$(".labelHoverLine");
	if(labelBlocksHover.length != 0){
		labelBlocksHover.each(function(elem){
			var myLabelHover = new LabelHover(elem, labelBlocksHover);
		});
	}

    var options = {};

    if($('j_password'))
    {
        options = {forcedHiddenField:$('j_password')};
    }

	var autoLabelBlocks = $$("input.autoLabel");
    if (autoLabelBlocks.length > 0) {
		autoLabelBlocks.each(function(elem) {
			new AutoLabel(elem, autoLabelBlocks, options);
		});
		autoLabelBlocks.fireEvent('blur');
    }
	
	/* gestion loader */
	monloader = new Loader({
		fog : true,
		container : 'mainInside'
	});
	
	/* gestion loader profile edit */
	editProfileLoader = new Loader({
		fog : true,
		container : 'profileEditInside'
	});
	
	/* kilometrage */
	var kilomBlocks = $$(".kilom");
	if(kilomBlocks.length != 0){
		kilomBlocks.each(function(elem){
			new SplitKilometrage(elem);
		});
	}
	
	var blockMyMultimedias = $$(".blockMyMultimedia");
	if(blockMyMultimedias.length != 0){
		blockMyMultimedias.each(function(elem){
			new BlockMyMultimedia(elem);
		});
	}
	
	// Classe openInPopup pour ouvrir le lien en popup
	var opentoPopup = $$(".openInPopup");
	if(opentoPopup.length != 0){
		opentoPopup.each(function(elem){
			var myOpenPopup = new OpenInPopup(elem);
		});
	}
	
	var inputsPrefix = $$(".prefixInput");
	if(inputsPrefix.length != 0){
		inputsPrefix.each(function(elem){
			var myInputPrefix = new InputPrefix(elem);
		});
	}
	

	
	var popinsConsecutive = $$(".popinsConsecutive");
	if(popinsConsecutive.length != 0){
		popinsConsecutive.each(function(elem){
			var myPopinConsecutive = new PopinConsecutive(elem);
		});
	}


	var checkNotif = $$(".checkNotifInput");
	if(checkNotif.length > 0){
		/**
		 * checkNotif
		 * Find '.checkNotif' and execute checkNotifHandler
		 */

		checkNotif.each(function(el){
			checkNotifHandler(el);
		});
	}

    
    function getImgRatioSize(viewPort,ratio)
    {   
        var size = {};
        size.ratio = viewPort.width/viewPort.height;

        if(size.ratio>ratio){
            size.width=viewPort.width;
            size.height=viewPort.width/ratio;
            size.left=0;
            size.top=-(size.height-viewPort.height)/2;
        }
        else{
            size.width=viewPort.height*ratio;
            size.height=viewPort.height;
            size.left=-(size.width-viewPort.width)/2;
            size.top=0;
          }
        return size;
    }

    function setImgRatioSize($img,viewPort) {
        $img.each(function(elm){
            var img_size = elm.getSize();
            var ratio = img_size.size.x/img_size.size.y;
            var size = getImgRatioSize(viewPort,ratio);
            var new_w=size.width;
            var new_h=size.height;
            elm.setStyles({width:new_w,height:new_h,left:size.left,top:size.top});
         });
    }


    
    
    var $img = $$('.visualWithText .visuals .blockVisual img');
    var viewPort = {
        width: 212,
        height: 150
    };
    if($img.length)
    {
        setImgRatioSize($img,viewPort);
    }
    
    var $img = $$('.visualWithText .nav ul li a img');
    var viewPort = {
        width: 95,
        height: 65
    };
    if($img.length)
    {
        setImgRatioSize($img,viewPort);
    }

    
    var $img = $$('.blockCarouselDiapos .nav ul li a img');
    var viewPort = {
        width: 95,
        height: 65
    };
    if($img.length)
    {
        setImgRatioSize($img,viewPort);
    }
    
    
    var $img = $$('.blockVirtualParc .blockCarouselDiapos .visuals .blockVisual img');
    var viewPort = {
        width: 120,
        height: 80
    };
    if($img.length)
    {
        setImgRatioSize($img,viewPort);
    }
    


});


/**
 * @function checkNotfiHandler
 * @param el {element}
 * @description if input is check so change label wording
 */
function checkNotifHandler(el){
	var inpt = $(el).getElement('.js-checkNotifInput');

	if (inpt.checked) el.addClass('activeNotif');
	$(inpt).addEvent('click', function(){
		if(this.checked){
			$(el).addClass('activeNotif');
		} else{
			$(el).removeClass('activeNotif');
		}
	});
}

function setCarouselPortlet(){
	var blockTabCarousel = $$(".blockTabsCarousel");
	if(blockTabCarousel.length != 0){
		blockTabCarousel.each(function(elem){
			//console.log(elem)
			
			var myCarouselTab = new BlockTabCarousel(elem);
		});
	}
}

var SplitKilometrage = new Class({
	Implements: [Options, Events],
	options : {
		template : '<span>???value???</span>',
		templateReplace : '???value???',
		templateZero : '<span class="zero">0</span>',
		nbrChars : 6
	},
	initialize : function(block,options){
		this.setOptions(options);
		var valueKilom = $(block).getText();
		
		var newVal = "";
		
		for(var pre = 0; pre < this.options.nbrChars - valueKilom.length; pre++){
			newVal += this.options.templateZero;
		}
		
		for(var i =0; i<valueKilom.length; i++){
			var myString = this.options.template.replace(this.options.templateReplace, valueKilom.charAt(i));
			newVal += myString;
		}
		$(block).innerHTML = newVal;
	}
});
SplitKilometrage.implement(new Options);

var BlockTabCarousel = new Class({
	options : {},
	initialize : function(block,options){
		this.block = $(block);
		this.container = this.block.getElement(".blockCarousel");
		this.nav = this.block.getElement(".navCarousel");
		this.navElems = this.block.getElements(".navCarousel .nav li");
		this.elems = this.block.getElements(".elemCarousel");
		this.next = this.block.getElement(".nextBtn");
		this.prev = this.block.getElement(".prevBtn");
		
		this.actual = 0;
		
		this.setStableHeight();
		if(this.elems.length > 1){
			$(this.nav).removeClass("hidden");
			$(this.next).removeClass("hidden");
			$(this.prev).removeClass("hidden");
			$(this.next).addEvent("click",function(e){
				var e = new Event(e).stop();
				this.goToNext();
			}.bind(this));
			
			$(this.prev).addEvent("click",function(e){
				var e = new Event(e).stop();
				this.goToPrev();
			}.bind(this));
			
			var _this = this;
			
			this.navElems.each(function(elem, index){
				var link = $(elem).getElement("a");
				$(link).addEvent("click", function(e){
					var e = new Event(e).stop();
					
					_this.goToElem(index);
				});
			});
			
		}
	},
	setStableHeight: function(){
		var maxHeight = 0;
		for(var i = 0; i < this.elems.length; i++){
			var elem = $(this.elems[i]);
			if(elem.offsetHeight > maxHeight)
				maxHeight = elem.offsetHeight
		}
		$(this.container).setStyle("height",maxHeight);
	},
	goToNext: function(){
		var newActual = (this.actual + 1)%(this.elems.length);
		this.setVisible(newActual);
	},
	goToPrev: function(){
		var newActual = (this.actual - 1)%(this.elems.length);
		if(newActual < 0)
			newActual = this.elems.length+newActual;
		
		this.setVisible(newActual);
	},
	goToElem: function(index){
		this.setVisible(index);
	},
	setVisible: function(newActual){
		$(this.elems[this.actual]).removeClass("current");
		$(this.elems[newActual]).addClass("current");
		
		
		$(this.navElems[this.actual]).removeClass("currentNav");
		$(this.navElems[newActual]).addClass("currentNav");
		
		//console.log(this.navElems, this.actual, newActual);
		this.actual = newActual;
	}
});

var LabelHover = new Class({
	options : {},
	initialize : function(block, blocks, options){
		this.blocks = blocks;
		this.label = $(block).getElement("label.labelHover");
		
		this.input = $(block).getElement("input.text");
		
		$(this.input).addEvent("focus",function(){
			//console.log("focus ", this.input.name);
			$(this.label).addClass("hidden");
		}.bind(this))
		
		$(this.input).addEvent("change",function(){
			//console.log("change ", this.input.name);
			this.checkFields();
		}.bind(this));
		
		$(this.input).addEvent("blur",function(){
			//console.log("blur ", this.input.name);
			this.checkFields();
		}.bind(this))
	},
	checkFields : function(){
		this.blocks.each(function(elem, index){
			this.checkField(elem);
		}.bind(this));
	},
	checkField : function(elem){
		var labelelem = $(elem).getElement("label.labelHover");
		var inputelem = $(elem).getElement("input.text");
		
		if(inputelem.value != ""){
			$(labelelem).addClass("hidden");
		}else{
			$(labelelem).removeClass("hidden");
		}
	}
});

var AutoLabel = new Class({
    options : {},
    initialize : function(block, blocks, options) {
        this.block = block;
        this.blocks = blocks;
        new Element('label', {'class': 'autoLabelHover', 'for': block.getAttribute('name')}).setHTML(block.getAttribute('data-label')).inject(block, 'before');
        block.addEvents({
            focus: function() {
				var elem = this.block;
				elem.getPrevious().addClass('hidden');
                if(options.forcedHiddenField)
                {
                    options.forcedHiddenField.getPrevious().addClass('hidden');
                }
            }.bind(this),
            change: function() {
				this.checkFields();
            }.bind(this),
            blur: function() {
				this.checkFields();
            }.bind(this)
        });
    },
    checkFields: function() {
		this.blocks.each(function(elem, index){
			if (elem.value == '') {
				elem.getPrevious().removeClass('hidden');
			} else {
				elem.getPrevious().addClass('hidden');
			}
		}.bind(this));
    }
});

var BlockMyMultimedia = new Class({
	Implements: [Options, Events],
	options : {},
	initialize : function(block,options){
		this.setOptions(options);
		this.block = $(block);
		
		this.checkTabs();
	},
	checkTabs: function(){
		var self = this;
		var tabs= this.block.getElements(".tabs li a");
		if(tabs.length!= 0){
			tabs.addEvent("click", function(){
				self.stopAllvideos();
			})
		}
	},
	stopAllvideos: function(){
		var elements = this.block.getElements("object");
		var theMovie;
		for(var i=0; i<elements.length; i++)
        {
             elements[i].sendEvent("STOP");
		}
	}
});
BlockMyMultimedia.implement(new Options);

var resizeFlash = function(hToUse){
	$('flashnavgv').style.height = hToUse + "px";
}

function tipBox3(elm, size, iLeft, iTop,cssClass,cssId){
	if(!cssClass) {
        cssClass = '';
    }
    //referer
    //referer = $$('.jaugeWrapper')[0];
     
	if(!$(elm).hasClass("showingTooltip")){
	
		$(elm).addClass("showingTooltip");
		
		var layer = getNextSibling($(elm), {nodeName:"div", className:"tipBoxLayer"});
		if(!layer){
			var layer = getNextSibling($(elm).getParent(), {nodeName:"div", className:"tipBoxLayer"});
		}
		var bloc = getParent($(elm), {nodeName:"div"}),
		clone = $(layer).clone();
		clone.injectInside($('page'));
		clone.addClass('clonedTipBoxLayer '+cssClass+'');
		if(size){
			clone.setStyle('width', size);
		}
		clone.setStyles({
			opacity:0,
			display:'block'
		});
        
        if(cssClass == 'tooltipImpToRight')
        {
           clone.setStyle('top', $(elm).getCoordinates().top - 20);
        }   
        else 
        {
            clone.setStyle('top', ($(elm).getCoordinates().top - clone.offsetHeight + iTop));
        }
            
		if (clone.getCoordinates().bottom >= document.documentElement.clientHeight){
			//console.info($(elm).getCoordinates().bottom, clone.offsetHeight, iTop);
			//clone.setStyle('top', $(elm).getCoordinates().bottom - clone.offsetHeight + iTop);
		}

		if($(bloc).getLeft() < clone.offsetWidth){
			clone.setStyle('left', $(elm).getCoordinates().right - $('page').getLeft() + iLeft)
		}else{
			clone.setStyle('left', $(elm).getCoordinates().left - clone.offsetWidth - $('page').getLeft() + iLeft)
		}
        
        if( cssClass == 'tooltipImpToRight'){
            clone.setStyle('left',  iLeft);
        }

		var opac = new Fx.Styles(clone, {duration: 200, transition: Fx.Transitions.linear});
		opac.start({
			'opacity': [0, 1]
		});
				
		clone.addEvent("mouseover",function(){
			if(timeoutClone){
				clearTimeout(timeoutClone);
			}
			//console.log("reset timeout")
		});


		/*
		$(elm).getChildren().addEvent('mouseout', function() {
			if(timeoutClone){
				clearTimeout(timeoutClone);
			}
			timeoutClone = setTimeout(function(){
				if($(elm).hasClass("showingTooltip")){
					if($(document.body).getElement(".clonedTipBoxLayer")){
						clone= $(document.body).getElement(".clonedTipBoxLayer");
						new Fx.Styles(clone, {duration: 200, transition: Fx.Transitions.linear}).start({
							'opacity': [1,0]
						});
						setTimeout(function(){
							$(elm).removeEvents('mouseout');
							$(elm).removeClass("showingTooltip")
							clone.remove();
						},250);
					}
				}
			}, 500);
			
		});
        */

        $(elm).addEvent('mouseleave', function() {
			if(timeoutClone){
				clearTimeout(timeoutClone);
			}
			timeoutClone = setTimeout(function(){
				if($(elm).hasClass("showingTooltip")){
					if($(document.body).getElement(".clonedTipBoxLayer")){
						clone= $(document.body).getElement(".clonedTipBoxLayer");
						new Fx.Styles(clone, {duration: 200, transition: Fx.Transitions.linear}).start({
							'opacity': [1,0]
						});
						setTimeout(function(){
							$(elm).removeEvents('mouseout');
							$(elm).removeClass("showingTooltip")
							clone.remove();
						},250);
					}
				}
			}, 500);

		});
		
		$(clone).addEvent("mouseout",function(){

			if(timeoutClone){
				clearTimeout(timeoutClone);
			}
			timeoutClone = setTimeout(function(){
				if($(elm).hasClass("showingTooltip")){
					if($(document.body).getElement(".clonedTipBoxLayer")){
						clone= $(document.body).getElement(".clonedTipBoxLayer");

						new Fx.Styles(clone, {duration: 200, transition: Fx.Transitions.linear}).start({
							'opacity': [1,0]
						});
						setTimeout(function(){
							$(elm).removeEvents('mouseout');
							$(elm).removeClass("showingTooltip");
							clone.remove();
						},250);
					}
				}
			}, 500);
		});

	}
};

function tipBox4(elm, size, iLeft, iTop, hideToggle){
	//console.info(elm);
	var hideToggle = hideToggle || false;
	
	var layer = getNextSibling(elm, {nodeName:"div", className:"tipBoxLayer"}),
		 bloc = getParent(elm, {nodeName:"div", className:"block"}),
		 clone = $(layer).clone();
	
	if(hideToggle)
	if(!$(bloc).hasClass("toggleClosed")){
		//clone.remove();
		return;
	}
	
	clone.injectInside($('page'));
	clone.addClass('clonedTipBoxLayer');
	if(size){
		clone.setStyle('width', size);
	}
	clone.setStyles({
		opacity:0,
		display:'block'
	});
	//console.info(clone.offsetHeight, ($(elm).getCoordinates().top + iTop), $(elm).getCoordinates().top, iTop);
	clone.setStyle('top', ($(elm).getCoordinates().top - clone.offsetHeight + iTop));
	if (clone.getCoordinates().bottom >= document.documentElement.clientHeight){
		//console.info($(elm).getCoordinates().bottom, clone.offsetHeight, iTop);
		//clone.setStyle('top', $(elm).getCoordinates().bottom - clone.offsetHeight + iTop);
	}
	
	if($(bloc).getLeft() < clone.offsetWidth){
		clone.setStyle('left', $(elm).getCoordinates().right - $('page').getLeft() + iLeft)
	}else{
		clone.setStyle('left', $(elm).getCoordinates().left - $('page').getLeft() + iLeft)
	}
	
	var opac = new Fx.Styles(clone, {duration: 200, transition: Fx.Transitions.linear});
	opac.start({
	    'opacity': [0, 1]	
	});
	
	elm.addEvent('mouseout', function() {
		clone.remove();
		elm.removeEvents('mouseout');
   });
};


var PopIn = new Class({
    options : {
       width : 450
	},
    initialize : function(layerId, options){
		
        this.setOptions(options);
        this.page = $E('body');
        this.layer = $(layerId || 'layer');

        this.createElms();

        //gestion echap kbd
        this.escapeLayer();

        //gestion Envoyer a un ami
        //this.sendTo();

        //check url pour ouvrir le layer eventuellement parametre
        this.doUrl();
    },
    doUrl : function(){
        var qString = document.location.search;
        var toUse = qString.substr(1,qString.length);
        var duos = toUse.split('&');
        var number = 0;
        var param = false;
        var sendToAlreadyOpened = false;

        duos.each(function(duo){
            var array = duo.split('=');
            if (array[0]=='id'){
                param = true;
                identifiant = array[1];
            }
            if (array[0]=='sendToOpen'){
                sendToAlreadyOpened = array[1];
            }
        });
        //ouverture layer identifie dans url
        var identifiant = $(identifiant);
        if (!identifiant) return;
        this.show(identifiant, sendToAlreadyOpened);
    },
    createElms : function(){
        //on met le layer dans body
        this.page.adopt(this.layer);

        this.mask = new Element('div',{
            'class':'popMask'
        }).setOpacity(0);
        this.page.adopt(this.mask);
        if(IS_IE){
            this.mask.iframe = new Element('iframe')
            //this.mask.iframe.src = 'javascript:void(0)';
            this.mask.iframe.src = 'javascript:;';
            this.mask.adopt(this.mask.iframe);
        }
    },
    setMaskDimensions : function(){
        var coord = {};
        coord.width = window.getScrollWidth();
        coord.height = window.getScrollHeight();
        this.mask.setStyles(coord);
        if (IS_IE){
            this.mask.iframe.setStyles(coord)
        }
    },
    updateLayerPosition : function(options){
        this.posX = window.getScrollLeft()+window.getWidth()/2 - this.options.width/2;
        this.posY = window.getScrollTop()+window.getHeight()/2 - this.layer.getSize().size.y/2;
		//alert(this.posX + ' ' + this.posY + ' ' + this.options.width);
        this.layer.setStyles({
            'left':this.posX,
            'top':this.posY,
            'width':this.options.width
        });
    //this.layer.effect('top',{duration:100}).start(this.posY);
    //this.layer.setStyles({'left':this.posX,'width':this.options.width});
    },
	populate : function(ref){
		this.layer.innerHTML = '';
		var MTref = $(ref).clone();
		this.layer.adopt(MTref);
        try {
		    Cufon.replace(this.layer.getElement('.afterCufoned'));
        } catch (e) { }
        
        if(MTref.getElements('form input[type=text]').length > 0) {
			MTref.getElements('form input[type=text]').each(function(item) {
				var startVal = item.value;
				
				item.addEvent('focus', function(e) {
					var t = e.target || item;
					t.value = '';
				});
				
				item.addEvent('blur', function(e) {
					var t = e.target || item;
					
					if(t.value === '') {
						t.value = startVal;
					}
				});
			});
		}
	},
    show : function(ref, bool) {
		this.populate(ref);
        this.updateLayerPosition();
        this.setMaskDimensions();
        if (bool == 'true') this.switchSendTo();
        this.layer.effect('opacity').start(1);
        this.mask.effect('opacity').start(0.8);
        //check scroll position to update popin position
        //init transition
        //if(!window.ie6)
        this.fxLayerFollowing = new Fx.Style(this.layer, 'top', {
            duration:400,
            wait:false
        });
        window.addEvent('scroll',function(e){
            //if(!window.ie6)
            this.fxLayerFollowing.start(window.getScrollTop()+window.getHeight()/2 - this.layer.getSize().size.y/2);
        }.bind(this));
		this.fxLayerFollowing.start(window.getScrollTop()+window.getHeight()/2 - this.layer.getSize().size.y/2);
		

    },
    escapeLayer : function(){
        document.addEvent('keydown', function(e){
            if (e.keyCode.toInt() == 27) this.hide();
        }.bind(this))
    },
    hide : function() {
        this.mask.effect('opacity',{
            duration:200,
            onStart : function(){
            //if (this.switchSendTo.open == true) this.switchSendTo();
            }.bind(this),
            onComplete : function(ref){
                this.layer.effect('opacity').start(0);
				//this.unPopulate();
            }.bind(this)
        }).start(0);
		
    }
});
PopIn.implement(new Options)

function checkForm(form){
	$(form).fireEvent("formSubmited");
}

var ViewEditSwitch = new Class({
	options : {},
    initialize : function(block, options){
		this.block = $(block);
		var _this = this;
		this.form = this.block.getElement("form");
		this.linkSwitch = this.block.getElements(".switchBtn");
		this.linkSwitch.addEvent("click", function(e){
			var e = new Event(e).stop()
			this.switchView();
		}.bind(this));
		
		this.form.addEvent("formSubmited", function(){
			
			if(formval.check(this)){
				_this.sendDatas(this);
			}
		});
	},
	switchView : function(){
		this.block.toggleClass("visuMode");
		this.block.toggleClass("editMode");
	},
	sendDatas : function(form){
		editProfileLoader.show();
		var _this = this;
		
		var mySendForm = new XHR({method: form.method});
		mySendForm.addEvent('onSuccess', function(response){
			editProfileLoader.hide();
			var responseJson = eval(response);
			_this.setValues(responseJson);
		})
		mySendForm.send(form.action, form.toQueryString());
	},
	setValues : function(datas) {
		for(var i = 0; i < this.form.elements.length; i++){
			var elem = this.form.elements[i];
			$(elem).removeClass("errorForm");
			var errorElem = $(elem.parentNode.parentNode).getPrevious();
			if(elem.name == 'myProfile.preferredCom'){
				errorElem = $(elem.parentNode.parentNode.parentNode).getPrevious();
			} else if(elem.name == 'myProfile.optin'){
                errorElem = $(elem.parentNode).getPrevious();
            }
			if (errorElem && errorElem.hasClass("error")) {
				errorElem.addClass('hidden');
			}
		}
		if(datas.status == "ok") {
            if (typeof updateGauge == 'function') {
				updateGauge();
            }
            if(redirectUrl != undefined && redirectUrl != "") {
                window.location.replace(redirectUrl);
            }
			for(var i = 0; i < this.form.elements.length; i++) {
				var elem = this.form.elements[i];
				if(elem.name in datas.values) {
                    var idField;
                    var elParent = $(elem).getParent();
                    while(elParent) {
                        if(elParent.hasClass("edittxt")) {
                            idField = elParent.id.replace("edittxt","viewtxt");
                            break;
                        }
                        elParent = elParent.getParent();
                    }
                    var viewElement = this.block.getElement("."+idField);
                    var elementValue = datas.values[this.form.elements[i].name];
					if (viewElement) {
						if (elem.type == "text" || elem.type == "hidden") {
							viewElement.innerHTML = (elementValue == "" && emptyText) ? emptyText : elementValue;
						} else if(elem.type == "select-one") {
							viewElement.innerHTML = elem.options[elem.selectedIndex].text;
						} else if(elem.type == "checkbox") {
                            if(this.form.elements[i].name == 'myProfile.hobbies' || this.form.elements[i].name == 'myProfile.preferredCom') {
                                viewElement.innerHTML = elementValue;
                            }else{
							    viewElement.innerHTML = (elementValue=="true") ? labelYes : labelNo;
                            }
                        }
					}
				}
			}
			this.switchView();
		} else if (datas.status == "validation") {
			for(var i = 0; i < this.form.elements.length; i++){
				var elementform = this.form.elements[i];
				if(datas.errors[elementform.name]){
					 if(elementform.name == 'myProfile.preferredCom'){ 
						$(elementform).addClass("errorForm")
                        var errorElem = $(elementform.parentNode.parentNode.parentNode).getPrevious();
                        if (errorElem && errorElem.hasClass('error')) {
                            errorElem.removeClass('hidden');
                        }
					}else if(elementform.name == 'myProfile.optin'){ 
                        $(elementform).addClass("errorForm")
                        var errorElem = $(elementform.parentNode).getPrevious();
                        if (errorElem && errorElem.hasClass('error')) {
                            errorElem.removeClass('hidden');
                        }
                    } else {
						$(elementform).addClass("errorForm")
						var errorElem = $(elementform.parentNode.parentNode).getPrevious();
						if (errorElem && errorElem.hasClass('error')) {
							errorElem.removeClass('hidden');
						}
					}
				}
			}
		} else if (datas.status == "disabled") {
			sendGen({'GA':['_trackPageview', getSiteStructure() + '/GDC-Technical error popin']});  
			popup = new PopIn('errorLayer');
			popup.show("error");
			this.switchView();
		} else if (datas.status == "timeout") {
			sendGen({'GA':['_trackPageview', getSiteStructure() + '/GDC-Technical error popin']});  
			popup = new PopIn('errorLayer');
			popup.show("error");
			this.switchView();
		} else if (datas.status == "error") {
			sendGen({'GA':['_trackPageview', getSiteStructure() + '/GDC-Technical error popin']});  
			popup = new PopIn('errorLayer');
			popup.show("error");
			this.switchView();
		}
	}
});

function addFF2Class(){
    if(window.navigator.userAgent.match('Firefox/2')) {
        $('page').addClass('IS_FF2');
    }
}


Layer = new Class({
	options : {
		showCloseCross : true
	},
	initialize : function(over,content,options) {
		this.over = over;
		this.content = content;
        var closeLabel = options ? (options.closeLabel || "") : "";
		this.closer = new Element('div');
		this.closer.addClass("closer");
		this.closer.setText(closeLabel)
		this.closer.addEvent('click',function() {
			this.hide()
		}.bind(this));

		this.container = new Element('div', {'class':'layerPopin'})
		this.container.setStyles({
			'opacity':'0',
			'position':'absolute',
			'background':'#fff',
			'z-index':'10001',
			'padding':'15px',
			'top':'0',
			'overflow':'hidden'
		})
		.injectInside(document.body);

		this.background = this.container.clone().setStyles({
			'background':'#ddd',
			'z-index':'10000',
			'padding':0
		})
		.injectInside(document.body);

		this.container.adopt($$(this.closer,content));
		this.setOptions(options);

		if(this.options.showCloseCross) {
			this.closer.setStyle('display','block')
		} else {
			this.closer.setStyle('display','none')
		}

		window.addEvent('resize',this.updatePosition.bind(this));
	},
	updatePosition : function() {
		var coordinates = this.getBackgroundSize();

		$$(this.content).filterByTag('iframe').setStyle('display','block');

		this.posX = window.getScrollLeft()+window.getWidth()/2 - this.container.getSize().size.x/2;
		this.posY = window.getScrollTop()+window.getHeight()/2 - this.container.getSize().size.y/2;

		this.posY = this.controlMinYPosition(this.posY);

		this.background.setStyles(coordinates);
		this.container.setStyles({'left':this.posX,'top':this.posY});
	},

	controlMinYPosition : function(position) {
		if(position < 0) {
			return 0;
		} else {
			return position;
		}
	},

	show : function() {
		this.updatePosition();

		this.background.effect('opacity').start(0.7);
		this.container.effect('opacity').start(1);
	},
	hide : function() {
		this.background.effect('opacity').start(0);
		this.container.effect('opacity').start(0);
		//this.fireEvent('onHide');
	},
	getTopOffset : function() {
		return (this.over == window) ? getScrollTop() : 0;
	},
	getBackgroundSize : function() {
		var coordinates = {};
		if(this.over == window) {
			coordinates.width = window.getScrollWidth();
			coordinates.height = window.getScrollHeight();
			coordinates.top = 0;
			coordinates.left = 0;
		} else {
			coordinates = this.over.getCoordinates();
		}
		return coordinates;
	}
});
Layer.implement(new Options,new Events);

var showLoaderLayer = function() {
	monloader.show();
}

var hideLoaderLayer = function() {
    monloader.hide();
}

function performAjaxLogin(form) {
    try {
        showLoaderLayer();
        var queryString = $(form).toQueryString() + "&ajaxLogin=ajaxLogin";
        new Ajax(form.action, {
                method:'post',
                data : queryString,
                onSuccess : function(response) {
                    var json = eval("("+response+")");
                    if (json.authenticated) {
                        sendGen({'GA':['_trackEvent', 'myRenault', 'Home-Login to account']});
                    }
                    setTimeout(function() {
                        window.location = json.url;
                    }, 100);
                }.bind(this),
                onFailure: function() {
					window.location = window.location;
                }
            }).request();
        return false;
    } catch(e) {
        return true;
    }
}

function performAjaxSubmit(form) {
    showLoaderLayer();
    new Ajax(form.action, {
        method:'post',
        data : form,
        onSuccess : function(raw) {
            var response = eval("("+raw+")");
            if(response.hasErrors) {
                $$(".errorContainer").addClass("hidden");
                for(var field in response.fieldErrors) {
                    var value = response.fieldErrors[field];
                    $$(".errorContainer[field="+ field +"]").removeClass("hidden");
                    $$(".errorContainer[field="+ field +"]").setText(value);
                }
                hideLoaderLayer();
            } else {
                var someMore = '';
                if(response.pdErrorCode && response.pdErrorCode != '') {
                    someMore += '&pdErrorCode=' + response.pdErrorCode;
                }
                if(response.eticomErrorCode && response.eticomErrorCode != '') {
                    someMore += '&eticomErrorCode=' + response.eticomErrorCode;
                }
                if (typeof SEND_GEN_AFTER_SUBMIT == 'object') {
					sendGen(SEND_GEN_AFTER_SUBMIT); 
                }
				setTimeout(function() {
					window.location = (response.url + someMore).replace('.action&', '.action?list=&').replace('.jsp&', '.jsp?');
				}, 100);
            }
        }.bind(this)
    }).request();
    return false;
}

var ajaxTimer = null;
function performAjaxAddressLookup(form) {
	if (!$(postcodeField).value.match(/[0-9]{4}\s?[a-zA-z]{2}/) || !$(houseNumberField).value.match(/[0-9]+/)) {
		$(cityField).value = "";
		$(streetField).value = "";
		return;
	}
	if (lookingUp) {
		return;
	}
	if (ajaxTimer != null) {
		window.clearTimeout(ajaxTimer);
	}
	
	ajaxTimer = window.setTimeout(function() {
		ajaxTimer = null;
		lookingUp = true;
		
		new Ajax(ajaxAddressUrl, {
			method : 'post',
			data : {
				postcode: $(postcodeField).value,
				houseNumber: $(houseNumberField).value
			},
			onSuccess : function(raw) {
				lookingUp = false;
				var response = eval(raw);
				if(response.status == 'ok') {
					$(cityField).value = response.values.city;
					$(streetField).value = response.values.street;
				} else {
					$(cityField).value = "";
					$(streetField).value = "";
				}
			}.bind(this),
			onError: function() {
				lookingUp = false;
			}
		}).request();
		
	}, "250");
	
	return false;
}

function layerPopinOnComplete(popin){
	var labelBlocksHover = $(popin).getElements(".labelHoverLine");
	if(labelBlocksHover.length != 0){
		labelBlocksHover.each(function(elem){
			var myLabelHover = new LabelHover(elem, labelBlocksHover);
		});
	}
	
	var opentoPopup = $(popin).getElements(".openInPopup");
	if(opentoPopup.length != 0){
		opentoPopup.each(function(elem){
			var myOpenPopup = new OpenInPopup(elem);
		});
	}
	
	var inputsPrefix = $(popin).getElements(".prefixInput");
	if(inputsPrefix.length != 0){
		inputsPrefix.each(function(elem){
			var myInputPrefix = new InputPrefix(elem);
		});
	}
	
	
}

var OpenInPopup = new Class({
	options : {},
	initialize : function(element,options) {
		this.setOptions(options);
		
		this.height = 200;
		this.width = 500;
		this.titlePopup = "popupAuto";
		
		this.elem = $(element);
		
		if(this.elem.getTag() == "form"){
			this.event = "submit";
			this.urltarget = "action";
		}else{
			this.event = "click";
			this.urltarget = "href";
		}

		if(this.elem.getCssParam("height")){
			this.height = this.elem.getCssParam("height");
		}
		if(this.elem.getCssParam("width")){
			this.width = this.elem.getCssParam("width");
		}
		
		this.setEvent();
	},
	setEvent: function(){
		var _this = this;
		this.elem.addEvent(this.event, function(e){
			var e = new Event(e).stop();
			
			var target = $(this).getAttribute(_this.urltarget) ? $(this).getAttribute(_this.urltarget)  : $(this).getProperty(_this.urltarget);

			if(_this.urltarget == "action"){
				window.open("",_this.titlePopup,"scrollbars=yes,resizable=yes,toolbar=0,menubar=0,directories=0,width="+_this.width+",height="+_this.height+"");
				_this.elem.setProperty("target",_this.titlePopup).submit();
			}else{
				window.open(target,_this.titlePopup,"scrollbars=yes,resizable=yes,toolbar=0,menubar=0,directories=0,width="+_this.width+",height="+_this.height+"");
			}
		})
	}
});
OpenInPopup.implement(new Options,new Events);

var InputPrefix = new Class({
	options : {},
	initialize : function(element,options) {
		this.setOptions(options);
		
		this.elem = $(element);
		this.prefix = "";
		var attributePrefix = this.elem.getAttribute("prefix") ? this.elem.getAttribute("prefix") : (this.elem.getProperty("prefix") ? this.elem.getProperty("prefix") : "");
		
		
		if(attributePrefix != ""){
			this.prefix = attributePrefix;
			this.setEvent();
		}
	},
	setEvent: function(){
		var _this = this;
		this.elem.addEvent("focus", function(){
			if(this.value == ""){
				this.value = _this.prefix;
			}
		});
		this.elem.addEvent("blur", function(){
			if(this.value == "" || this.value == _this.prefix){
				this.value = "";
			}
		})
	}
});
InputPrefix.implement(new Options,new Events);



var PopinConsecutive = new Class({
	options : {},
	initialize : function(element,options) {
		this.setOptions(options);
		window.$tmp = {};
		this.elem = $(element);
		this.toPopin = 0;
		this.elementsPopin = this.elem.getElements(".popinLayer");
		this.openPopin();
	},
	openPopin : function(){
		var self = this;
		var elementToPopin = $(this.elementsPopin[this.toPopin]);
		var objParams = {content: elementToPopin}		
		var widthElem = elementToPopin.getCssParam("width") ? elementToPopin.getCssParam("width") : 200;
		
		
		var objParams = {
			content: elementToPopin,
			classPopin: this.elem.getCssParam("classPopin"),
			onCompleteClose:function(){
				setTimeout(function(){self.openNextPopin();},300);
			}
		}
		
		//console.log(objParams)
		window.$tmp.popId = new LayerPopIn(objParams);
	},
	openNextPopin : function(){
		var selfPopin = this
		this.toPopin += 1;
		if($(this.elementsPopin[this.toPopin])){
			this.openPopin();
		}
	}
});
PopinConsecutive.implement(new Options,new Events);




