/*global window,$,call_process,confirm,createCookie, Array, CompaneoForms, parseInt, setTimeout*/

/* Usage: 

	window.Form1 = CompaneoForms();
			
	Form1.init({
		form					: string	[#id],
		form_post_interval		: integer	[milliseconds],
		mode					: string	[slide, normal],
		submit_type				: string	[ajax, submit],
		save_coupon				: string	[ajax, submit],
		save_questionnaire		: string	[ajax, submit],
		saved_coupon			: string	[ajax, submit],
		custom_events			: {
			slide			: function [callback],
			coupon			: function [callback],
			confirmation	: function [callback],
			lastslide		: function [callback]
		}
	});
 * */


var CompaneoForms = function () {
    "use strict";
	/* Note on the "self" usage.
	 * 
	 * 
	 * use "self" for all declarations
	 * use "self" to access this scope from inner functions and to refer to this class instance
	 * 
	 * use "this" for executions and read queries in the current scope.
	 * 
	 * 
	 * Examples :
	 * 
		var myObject = function () {
		
			var self = {};
			
			self.myVariable = 1;
			
			self.myIncrementMyVariable = function () {
				this.myVariable++;	
			}
			
			self.myOtherMethod = function () {
				this.myIncrementMyVariable(); // myVariable == 2
				
				setTimeout(function () {
					self.myIncrementMyVariable(); // myVariable == 3
				}, 1000);
			} 
			return self;
		 };
	 * */
	var self = {};

	self.num_qst				= 0;
	self.total_qst				= 0;
	self.current_slide			= 1; // default slide
	self.previous_slide			= 1;
	self.is_last_slide			= false;
	self.autosave_id			= null;
	self.refresh_session_id		= null;
	self.last_slide				= 0;
	self.next_slide				= 1;
	self.is_qa					= false;
	self.session_post_interval	= 60 * 1000 * 10;
	self.default_lang_code		= null;
	self.restore_id             = null;
	self.show_callcliquer		= true;
	self.onCoupon				= false;
	self.message_ok				= '<div class=\'ok\'>OK</div>';
	//self.beforeunload			= {'fr_FR': 'Si vous avez besoin d\'aide, nous pouvons vous rappeler GRATUITEMENT !', 'fr_BE': 'Si vous avez besoin d\'aide, nous pouvons vous rappeler GRATUITEMENT !', 'nl_BE': 'Indien u hulp nodig heeft, bellen wij u GRATIS terug!', 'nl_NL': 'Indien u hulp nodig heeft, bellen wij u GRATIS terug!', 'en_GB': 'If you need any assistance, we can call you back FREE!'}
	self.path_to_ajax			= null;
	self.site_front				= null;
	self.default_path			= '/w3s/ajax_front.php?';
	self.default_protocole		= 'http://';
	self.data_type				= 'json';
	self.view_offer				= '';
	self.show_callcliquer		= true;
	self.defaut_confirm_mode	= 'submit';
	self.qid_for_silde			= '';
	self.answered_qid			= [];
	self.reject_particulier		= null;
	self.question_type			= {};
	self.qa_or_mail				= false;
	self.prt_cod				= null;
	self.list_qa				= false;
	self.first_rfq				= true;
	self.auto_save				= true;
	self.first_save				= true;
	self.nb_step				= "";
	self.back_show				= true;
	self.all_sub_qst			= false;
	self.qst_slide              = [];
	self.qst_nbinput			= [];
	self.nb_input_shown			= 0;
	self.q						= {};
	self.last_hash				= 0;
	self.button_controle        = false;
	self.qst_first_slide		= '';
	self.gettext_other			= {
        'fr_FR' : 'Autre',
        'fr_BE' : 'Autre',
        'nl_BE' : 'Andere',
        'nl_Nl' : 'Andere',
        'en_GB' : 'Other',
        'de_DE' : 'Andere'
    };
	self.gettext_continuer		= {
        'fr_FR' : 'COMMENCER VOTRE DEMANDE DE DEVIS',
        'fr_BE' : 'COMMENCER VOTRE DEMANDE DE DEVIS',
        'nl_BE' : 'Begin met uw offerte-aanvraag',
        'nl_Nl' : 'Begin met uw offerte-aanvraag',
        'en_GB' : 'Start here with your request for quotes',
        'de_DE' : 'Starten Sie Ihre anfrage'
    };
	self.gettext_initial		= '';
	self.container_id			= "#container_bdx";
	self.triggerCustomEvent = function (e) {
		if (typeof this.options.custom_events[e] === 'function') {
			this.options.custom_events[e]();
		}
	};

	/* o = jQuery instance */
	self.safeDisplay = function (o, options) {
		var is_visible = (o.is(':visible') || o.children().is(':visible'));
        if ((is_visible && options.action === 'show') || (!is_visible  && options.action === 'hide')) {
			return false;
		}

		self.options.animation.options = $.extend({}, self.options.animation.options, options);
		self.o = o.removeClass('questionError');
		setTimeout(function () {
			/* Nico - Wed Aug  4 11:13:46 CEST 2010
			 * self.onAnimation Boolean added to keep track of the animation 
			 * status of a slide that could be melted in certain situations.
			 * 
			 * For an example, comment out "self.onAnimation = true;" and 
			 * launch the Unit/Functional Test Suite.
			 * 
			 * Headaches ensues.
			 * */
			if (self.onAnimation === true) {	// Unfinished animation caught
				return false;
			}
			self.onAnimation = true;
            if ($.browser.mozilla || $.browser.webkit) {
				self.doAnimate(self.o);
				return false;
			}

			self.c = self.o.show().children().hide();
			self.doAnimate(self.c);
			return false;
		}, 150);
	};
	self.doAnimate = function (el) {
		if (self.options.is_api !== true) {
			$('html,body').scrollTop(0, 1000);
		}
		self.onAnimation = true;
		var customAnimation = false;


		if ($.effects !== undefined) {
			if (self.options.animation.effect !== ''
					&& $.isFunction($.effects[self.options.animation.effect])
					&& !($.browser.msie && parseInt($.browser.version) <= 7)) {
				customAnimation = true;
			}
		}

		if (customAnimation === true) {
			el.show(self.options.animation.effect,function() {
				self.fixAnimationIE(el);
				self.onAnimation = false;	// Releasing animation switch 
											// after the animation ended						
			});
		}
		else {
		el.animate({opacity : 'toggle'}, 150, function () {
			self.fixAnimationIE(el);
			self.onAnimation = false;	// Releasing animation switch 
										// after the animation ended
		});
		}
		return false;
	};
	
	self.fixAnimationIE = function (iel) {	
	
		if (self.onAnimation === true && $.browser.msie) {
			var IEversion = parseInt($.browser.version, 10);
			if (IEversion >= 8) {
				iel.filter('label').css({
					'display': 'inline'
				});
				iel.filter('span').has("input[type='text']").css({
					'display': 'block'
				});
			}
			
			
			if (IEversion == 7) {
				iel.filter('label').css({
					'display': 'block'
					});
				iel.filter('span').has("input[type='text']").css({
					'display': 'block'
				});
			}
		}
		return false;
	};	
	
	self.determineCurrentSlide = function () {	

		if(self.last_hash === 0 ){
			var hash = location.hash.replace('#', '');
			if(hash !== '' && hash <= self.last_slide){
				return hash;
			}
		}
		var 
		current_slide	= this.current_slide,
		selector, scope, total, required, q;
			
		
		if (this.question_shown) {
			this.question_shown = false;
			return this.current_slide;
			
		}
		
		if (this.is_last_slide) {
			return this.current_slide;
		}
		
		while (true) {
	        selector	= 'li.slide' + current_slide;
			scope		= self.options.form;
			q			= $(selector, scope);
            total		= parseInt(q.filter('.companeo_question').length + q.filter('.sub_question').filter('.displayed').length, 10);
				
			required	= q.filter('.displayed').filter('.is_required').length;
			
			if (total > 0) {
				if (required === q.filter('.displayed').filter('.is_required').filter('.is_answered').length  && q.filter('.displayed').length === total) {
					current_slide++;
					continue;
				}
				
				/*Il y a des questions requises non repondues*/
				break;
			} 
			else {
				
				if (q.filter('.to_display').length === 0) {
					if ((current_slide + 1) <= this.last_slide) {
						current_slide++;
						continue;
					}
				}
				
				if (q.filter('.displayed').length === q.length && q.length > 0) {
					current_slide++;
					continue;
				}
				
				/* Il n'y a pas de questions requises mais il y a des questions */
				break;
			}
		}
		
		return (current_slide > this.last_slide) ? this.last_slide  : current_slide;
	};
	
	self.displayPreviousSlide = function (hash) {	

		if (this.current_slide === 1) {
			return false;
		}

		if (this.current_slide <= 2) {
			self.back_show = true;
			$("#progressbar_contener").hide();
			$('.back_slide').css('visibility', 'hidden').hide();
		}	
		this.is_last_slide = false;
		this.current_slide--;
		
		
		var 
		scope	= self.options.form,
		q		= $('li.slide' + this.current_slide, scope),
		a, b;
		
		for (var i = this.current_slide; i <= this.last_slide; i++) {
			$('li.slide' + i).removeClass('displayed');
		}
		self.qid_for_silde ='';
		$('li', scope).not('.slide' + this.current_slide).removeClass('questionError').css('display', 'none').hide();
		
		a = q.filter('.to_display').addClass('displayed');
		b = q.filter('.companeo_question').addClass('displayed');
		
		q.filter('.displayed').each(function(i,qst) {
			var id = $(qst).attr('id').split('_');
			self.qid_for_silde += ','+ id[id.length-1];
		});
		$('#qid').val(self.qid_for_silde);
		this.safeDisplay(q.filter('.displayed'), {action : 'show' , direction: self.options.animation.options.direction_previous, distance:50});

		if (a.length + b.length === 0) {
			this.displayPreviousSlide();
		}
		
		this.progressBar(Math.round(((this.current_slide) / this.last_slide) * 100));
		this.triggerCustomEvent('slide');
		if(self.options.is_api !== true){
			if(hash === undefined){
				self.button_controle = true;
			}
			window.location.hash = this.current_slide;
			self.last_hash		 = this.current_slide;
		}
		

	};
	
	self.displayCurrentSlide = function (next_slide, hash) {	
		
		next_slide = (next_slide == undefined? this.determineCurrentSlide(): parseInt(next_slide));

		var q			= null;
		this.is_last_slide = false;
		if (this.current_slide === next_slide && this.current_slide > 1) {
			return false;
		}
		this.current_slide = next_slide;
		
		if(this.current_slide  > 1 && self.back_show === true){
			$("#progressbar_contener").show();
			self.back_show = false;
			$('.back_slide').css('visibility', 'visible').show();
		}	
		if(this.current_slide > 1) {
			var done = Math.round(((this.current_slide-1) / (this.last_slide-1)) * 100);
			this.progressBar(done);
		}
		$('li', self.options.form).not('.slide' + this.current_slide).removeClass('questionError').filter('.displayed').css('display', 'none').hide();
		$("#divQuestion").show();
		self.q = $('li.slide' + this.current_slide, self.options.form);
		self.qid_for_silde ='';
		self.dispatch_qst(self.q.filter('.to_display, .companeo_question'));
		self.q.filter('.to_display').addClass('displayed');
		self.q.filter('.companeo_question').addClass('displayed');
		self.q = self.q.filter('.displayed');
		if(self.q.length === 0 && (this.current_slide + 1 <  this.last_slide)){
			self.displayCurrentSlide(this.current_slide+1);
			return false;
		}
		self.qst_first_slide = self.q; 
		if(self.options.reduced_template === "1" && this.current_slide === 1 && $(".is_answered").length === 0 ){
			this.safeDisplay(  self.q.first(), {action : 'show' , direction: self.options.animation.options.direction_previous, distance:50});
		}else{
			this.safeDisplay(self.q, {action : 'show', direction: self.options.animation.options.direction_next, distance:50});
		}
		

		self.q.filter('.displayed').each(function(i,qst) {
		
			var id = $(qst).attr('id').split('_');
			if($(qst).hasClass("question_img")){
				self.check_height_label_img(id[2]);
			}

			self.qid_for_silde += ','+ id[id.length-1];
		});
	
		if (this.current_slide === 1) {
			$('#qid').val(self.qid_for_silde);
		}
		
	
		if (self.q.filter('.displayed') === 0) {
			this.displayCurrentSlide();
		}
		
		if(self.options.is_api !== true){
			if(hash === undefined){
				self.button_controle = true;
			}
			if(this.current_slide != '1'){
				window.location.hash = this.current_slide;
			}
			self.last_hash		 = this.current_slide;
		}
		
		this.triggerCustomEvent('slide');
		
		
	};
	self.go_back = function (){	
		
		if(self.options.is_api !== true){
			
			  $(window).hashchange( function(){
				var hash = location.hash.replace('#', '');
				
			    if(hash !== '' && !self.button_controle && hash < self.last_slide){
			    	if(self.last_hash < hash){
			    		self.displayCurrentSlide(hash,true);
                        self.last_hash = hash;
			    		 return false;
			    	}else{
			    		$(".back_slide").trigger('click');
                        self.last_hash = hash;
			    		 return false;
			    	}
			    }
			    self.button_controle = false;
			   
			  });
		}
	};
	
	self.dispatch_qst = function (q){	
		self.nb_input_shown = 0;
		var q1 = q.not("#form_qst_question_additional, #form_qst_mail, #form_qst_zipcode");
		if(q1.length > 0){
			self.q = q = q1;
		}else{
			return q;
		}
		q.each(function(i,qst) {

			if(self.current_slide === self.last_slide && !self.options.is_qa && ($("#form_qst_mail").length === 1)){
					$("#form_qst_question_additional,#form_qst_mail,#form_qst_zipcode").attr('class', 'companeo_question is_required to_display slide'+ (self.current_slide+1) );
					$("#div_sup").append('<div class="progress_step">&nbsp;</div>');
					self.last_slide++;
					$(".progress_step").css("width",Math.round((180 - 2* (self.last_slide-1) )/(self.last_slide-1)) );

			}
			var qst_id = $(qst).attr("id").split('_');
				qst_id =qst_id[2];
			if(self.nb_input_shown + self.all_sub_qst['qst_tail_'+ qst_id] < 13 || i === 0 ){
					self.nb_input_shown += self.all_sub_qst['qst_tail_'+qst_id];
				
			}else{
					var new_class = $(qst).attr('class').replace('slide'+self.current_slide, 'slide'+ (parseInt(self.current_slide,10)+1));
					$(qst).attr('class',new_class ).addClass('to_display');
					self.q = self.q.not(qst);
			}
		
		});
		
	
		
		
	};
	/*self.shouldSlide = function () {
		return (this.determineCurrentSlide() !== this.current_slide);
	};*/
	
	self.requiredQuestionAnswered = function () {	
		return $("[class*=is_answered][class*=is_required]", self.options.form).length;	
	};
	
	self.requiredQuestionLeft = function () {	
		return (this.requiredQuestionCount() - this.requiredQuestionAnswered());
	};
	
	self.requiredQuestionCount = function () {	
		return $("[class*=is_required]", self.options.form).length;
	};
	
	self.optionalQuestionsLeft = function (slide) {	
		return $('li.slide' + slide + '.displayed:not(.is_required):not(.is_answered)', self.options.form).length;
	};
	
	self.questionCount = function () {	
		return $("[class*=companeo_question], [class*=sub_question]", self.options.form).length;
	};
	

	
	self.init = function (options, start) {	
		
		var 
		default_options = {
			form				: '#form1',
			form_post_interval	: 3000,
			submit_type			: 'submit',
			mode				: 'normal', // or 'slide'
			save_coupon			: 'submit',
			is_qa				: false,
			is_api				: false,
			auto_save			: true,
			reduced_template	: false,
			default_path		: self.default_path,
			ID					: (options.ID === 'opportunity_id') ? options.ID : 'rfq_id',
			save_questionnaire	: (options.mode === 'slide') ? 'ajax' : 'submit',
			saved_coupon		: (options.is_api=== true)?'ajax' : 'submit',
			confirm_mode		: (options.confirm_mode !== undefined )?options.confirm_mode:self.defaut_confirm_mode,
			animation			: {effect : 'fade', options : {direction_next:'right', direction_previous:'left'}},
			data_type			: (options.is_api=== true)?'jsonp':self.data_type,
			list_qa				: 'false',
			autoentrepreneur	: false,
			custom_events		: {
				"slide"			: function () {},
				"coupon"		: function () {},
				"confirmation"	: function () {},
				"lastslide"		: function () {}
			}
		};


		/* Saving clients some CPU cycles.
		 * 	*/
 		if (typeof options === 'object') {
			options = $.extend({}, default_options, options);
		} 
		else {
			options = default_options;
		}

 		if (options.is_api === true) {
 			self.path_to_ajax = self.default_protocole + options.site_front + options.default_path;
 			self.site_front	 = self.default_protocole + options.site_front;
 			
 		}
 		else {
 			self.path_to_ajax =  self.default_protocole + location.host + options.default_path;
 			self.site_front	 = 	 self.default_protocole + location.host;
 		}
 		
 	
 		if (options.is_api !== true) {
 			document.onkeypress			= self.onKeyPressHandler;
 			
 		}
 		
 		
		self.options = options;

		
		switch (start) {
		case 'coupon':
			self.list_qa	= (self.options.list_qa !== undefined && self.options.list_qa !== 'false')?self.options.list_qa.split(','):false;
			self.coupon_helper();
			break;
		case 'confirmation':
			self.rfq_confirmation();
			break;
		default:
	
			self.questionnaire_helper();
			break;
		}

		new CompaneoMask(self.options.default_lang_code);
		
		$('.show_step_rfq').css('display', 'block').show();
		
	};
		
	self.questionnaire_helper = function() {

		var first = ($(" .question_element :first li", self.options.form).attr('id') || false);

		$("[id ^='hidden_form_']", self.options.form).css('display', 'none').hide();
		$('#show_next', self.options.form).show();
		this.form					= $(self.options.form);
		this.display_one_question	= (self.options.mode !== 'normal');
		self.all_sub_qst = $('body').data();
		
		if (self.options.mode === 'slide') {
	
			self.format_answer_per_line();
			if(parseInt($('#div_title1').height()) > 50){
				$('.title1').css('font-size','0.7em');
			}
	
			if(parseInt($('#carousel_text >p').height()) > 60){
				$('#carousel_text >p').css('font-size','0.9em');
			}
			if (self.options.is_api !== true) {
				self.go_back();
			}
				
		}
		
		
		self.registerInputs();
		
		if (this.display_one_question === true) {
			this.toc					= [];
			this.total_qst				= this.toc.length;
			this.num_qst				= 1;
			this.sub_question_id		= '';
			this.current_question_id	= this.get_qid_from_str(first);
			
			$(".question_element li", self.options.form).css('display', 'none').hide();
		}

		$("#mode").val(self.options.mode);

		switch (self.options.mode) {
		case 'slide':
			
			$('#process_slide', self.options.form).show();
			$('#process_normal, .back_slide', self.options.form).css('visibility', 'hidden').hide();
			$('.back_slide', self.options.form).unbind().bind('click', function () {
				self.displayPreviousSlide();
			});
		
			$('#about_compa_href').hover(
 					function () {
 						  self.show_about_companeo();
 					},
 					function () {
 						 $("#about_compa").hide();
 						 $("#div_middleside").show();
 					}
 				);	
	
			window._goButtonClick = function() {self.show_question();   };
			if (jQuery.browser.msie && parseInt(jQuery.browser.version)==6) {
			    jQuery('#show_next', self.options.form).attr("href","javascript:_goButtonClick();");
			} else {
				$('#show_next', self.options.form).unbind().bind('click', function () {
					self.show_question();
				});
			}


            //find all class slide and number
            var searchSlideNum = new RegExp(/slide(\d+)/);
            var allslides = [], maxslide = 0;
            $("li[class*=slide]", self.options.form).each(function(){
                var numSlide = parseInt(searchSlideNum.exec($(this).attr('class'))[1],10);
                if($.inArray(numSlide, allslides) == -1){
                    allslides.push(numSlide);
                }
            });
            allslides.sort();
            maxslide = allslides.length;

            if(maxslide > 0){
                //autocorrect slide numbering problems
                for(var i = 0;i<maxslide;i++){
                    //oops no slide for this number ?
                    if ($('li.slide' + (i+1), self.options.form).length === 0) {
                        //decrement slides number
                        var len=allslides.length;
                        for(var j=0; j<len; j++) {
                            $('li.slide'+allslides[j], self.options.form).removeClass('slide'+allslides[j]).addClass('slide'+(allslides[j]-1));
                        }
                    }
                    allslides.shift();
                    self.nb_step +='<div class="progress_step">&nbsp;</div>';
                }

                //second case => li without slide
                var noslideClass = $("li", self.options.form).not('[class*=slide]');
                if(noslideClass.length){
                    maxslide++;
                    noslideClass.addClass('slide'+maxslide);
                    self.nb_step +='<div class="progress_step">&nbsp;</div>';
;                }

                this.last_slide = maxslide;
            }
            else{
                $("li", self.options.form).not('[class*=slide]').each(function () {
                    if ($.inArray($(this).attr('id'), ['form_qst_mail', 'form_qst_question_additional', 'form_qst_zipcode']) !== -1) {
                        self.qa_or_mail		= true;
                        return true;
                    }
                    $(this).addClass('slide' + self.next_slide);
                    self.nb_step +='<div class="progress_step">&nbsp;</div>';
                    self.next_slide++;

                });

                if (!self.qa_or_mail) {
                    this.next_slide--;
                }
                this.last_slide = this.next_slide;

                $('#form_qst_mail, #form_qst_question_additional, #form_qst_zipcode').each(function () {
                    $(this)[0].className = $(this)[0].className.replace(/slide\d+\*?\b/g, '');
                    $(this).addClass('slide' + self.last_slide);
                });
            }

            this.next_slide = 0;

			$("#div_sup").html(self.nb_step);
			
			if(self.last_slide > 1){
				$(".progress_step").css("width",Math.round((180 - 2* (self.last_slide-1) )/(self.last_slide-1)) );
			}
		
			this.displayCurrentSlide();
			if($("#container_bdx_v2").length > 0){
				self.container_id = '#container_bdx_v2';
			}

			if(self.options.reduced_template === "1" && $(".is_answered").length === 0 && (self.options.is_api && cmpoApi.last_catcod === null )) {
				
					self.new_init_vertical_website();
					$('#show_next').unbind().one('click', function() {
						self.new_short_to_vertical(true);
						$(this).click(function() { self.show_next(true, true,true);  });
					});
			}
			if(self.options.is_api && cmpoApi.last_catcod !== null ){
				self.new_short_to_vertical(false);
				
			}
			break;
			
		

		
		case 'normal':
			$("#show_next", self.options.form).bind('click', function () {
				self.show_next(false, true); 
			});
					

			$(".sub_question", self.options.form).css('marginLeft', '40px');
			if(self.options.force_normal_api) {
				$("#divQuestion").show();
				$('#process_slide', self.options.form).show();
				$('#process_normal, .back_slide', self.options.form).css('visibility', 'hidden').hide();
				$('#about_compa_href').hover(
	 					function () {
	 						  self.show_about_companeo();
	 					},
	 					function () {
	 						 $("#about_compa").hide();
	 						 $("#div_middleside").show();
	 					}
	 				);	
			}
			//$("#" + first, self.options.form).css('display', 'block').show();
			break;
		default:
			break;
		}

		
		
		$(".companeo_question", self.options.form).filter('.is_answered').each(function () {
			$('input:checked', $(this)).each(function () {
				
				if ($(this).attr('type') === 'radio') {
					if ($(this).val() !== 0) {
						$(this).trigger('click', true);
					}
				}
 
				if ($(this).attr('type') === 'checkbox') {
					$(this).trigger('click', true).attr('checked', 'checked');
				}

			});
			$('option:selected', $(this)).each(function () {
				if ($(this).val() !== 0) {
					$(this).parent().trigger('change', true);
				}
			});
			
			$('input[type=text]', $(this)).each(function () {
				if ($(this).val() !== '') {
					$(this).trigger('blur', true);
				}
			});
		});

		if (self.autosave_id === null && self.options.reset_interval !== true && self.options.auto_save) {
			this.last_exec = new Date().valueOf();
			self.from_last_serialize = $(self.options.form).serialize();
			self.autosave_id = setInterval(self.test_change, self.options.form_post_interval);

		}

		if (self.refresh_session_id === null && (self.last_exec + 10000)> new Date().valueOf()) {
			this.last_session_exec = new Date().valueOf();
			self.refresh_session_id = setInterval(self.refresh_session, self.session_post_interval);
		}
		self.init_cluetip();
		self.ie_img_checkbox();
		
		
	};
	
	
	self.registerInputs = function () {	
		
		$('li', self.options.form).each(function () {
			
			var parent = $(this);

			$('input, select, textarea', $(this)).not('.answer_per_line').each(function () {
				
				var 
				id		= parent.attr('id'),
				qid		= parseInt(parent.attr('id').replace(/\D*/, ''), 10),
				name	=  $(this).attr('name').split('-'),
				type	= ($.inArray(name[0], ['img_checkbox', 'img_radio']) !== -1) ? name[0] : $(this).attr('type');

				if (isNaN(qid)) {
					switch (id) {
					case 'form_qst_question_additional':
						$(this).bind('click', function () {
							return self.make_answered_qa();
						});
						break;
					case 'form_qst_mail':
						qid = 'mail';
						$(this).bind('blur', function () {
                            var email = $(this).val().toLowerCase();
                            $(this).val(email);
							if (/^[a-zA-Z0-9._\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,4}$/.test(email)) {
								return self.make_answered_text('form_email_field', qid, false);
							}

							return $('#' + id).removeClass('is_answered').addClass('questionError');
						});
						break;
					case 'form_qst_zipcode':
						qid = 'zipcode';
						$(this).bind('blur', function () {
							return self.make_answered_text('form_zipcode_field', qid, false);
						});

						break;

					default:
						break;
					}
				}
				
				/* Prevent double bind on "named" items
				 * */
		
				if ($.inArray(id, ['form_qst_mail', 'form_qst_question_additional', 'form_qst_zipcode']) !== -1 || type === 'hidden') {
					return true;
				}
				
				switch (type) {
				case 'img_checkbox':
				case 'img_radio':
				case 'checkbox':
				case 'radio':
					self.question_type[qid] = type; 

					if ($(this).attr("name").indexOf('redirect') === -1) {
						$(this).bind('click', function (e, dr) {
							return self.sub_qst_binding(qid, $(this).val(), type, $(this).is(':checked'), dr);
						});
					}
					break;
				case 'textarea':
				case 'text':
					self.question_type[qid] = type; 
					$(this).bind('blur', function (e, dr) {
						return self.sub_qst_binding(qid, $(this).val(), type, false, dr);
					});
					break;

				case 'select-one':
				case 'select-multiple':
					$(this).bind('change', function (e, dr) {
						return self.sub_qst_binding(qid, $(this).val(), 'select_' + qid + '_option', false, dr);
					});
					break;
	
				default:
					break;
				}
			});
		});
	};
	
	
	self.get_confirmation = function () {	

		$.ajax({
			type	:  (self.options.is_api === true)?'GET':'POST',
			url		: self.path_to_ajax +'action=get_confirmation' ,
			dataType: self.options.data_type, 
			async	: true,
			success	: function (res) {
				if (res.status === "success") {
					$(self.options.form).html(res.data);
					if(self.options.is_api){
						$("#api_layer_processing").remove();
						$("#api_processing").remove();
					}
					$(".show_step_confirmation").show();
		
					self.bind_trash();
					self.tooltip_bind();
					self.bind_carousel();
					if(self.options.is_api) {
						$('.show_step_rfq,.show_step_coupon, #carousel_logo_fac').hide();
						if (jQuery.browser.msie && parseInt(jQuery.browser.version) ===6) {
							$("#tuteur").css('display', 'none');
						}else{
							$("#tuteur").css('display', 'block');
						}
					}
					return true;
					
				}

			}
		});
	};
	
	self.display_coupon = function () {	
		var is_tags = (window.location.href.indexOf("tag") !== -1);
		if(self.options.is_api !== true){
			window.location.hash = 'coupon';
		}
		$("#container_bdx_v2").css({'height':'auto', 'min-height':'550px'});
		self.onCoupon = true;
				
		$.ajax({
			type	:  (self.options.is_api === true)?'GET':'POST',
			url		: self.path_to_ajax +'action=get_coupon&is_tags=' + is_tags,
			data	: this.serializeAddContext(false),
			dataType: self.options.data_type, 
			context	: this,
			async	: true,
			success	: function (display_coupon_res) {
				self.clear_error_messages();
				self.res_check = true;
				self.reject_particulier = display_coupon_res.reject_particulier;
				
				$('.show_step_rfq').css('display', 'none').hide();
				$('.show_step_coupon').css('display', 'block').show();
				
				$('.question_element', self.options.form).css('display', 'none').hide();
				
				var process_to_hide = ".process_validate";
				
				if (self.display_one_question === true || self.options.force_normal_api ) {
					process_to_hide += "_nav";
				} 
				
				$('#widget_categ').css('display','none');
				$('.testicat,.facoffers').css('display','none');
				$(".tags_coupon").show();
				$('.steps').hide();
				$(".menu_bar").hide();

				//$('div.corpQuestionnaire').coupon_helper();
				if (is_tags) {
					$(".verbatag3, #tags_verbatim, #display_results_tags, #top_tags").remove();
				}
								
				$(process_to_hide, self.options.form).remove();

				$('#partial_coupon', self.options.form).html(display_coupon_res.data).css('display', 'block').show();
				if(self.options.is_api && cmpoApi.options.onfancy !== undefined && cmpoApi.options.onfancy){
					$(".ui-widget-overlay").css('height', window.outerHeight);
				}
				if (display_coupon_res.page_type ==='qa') {
						window.QA = new CompaneoQa();
						QA.init(self.options.default_lang_code, self.options.site_front, self.options.is_api, self.options.confirm_mode);
						return false;
				}
				if (display_coupon_res.page_type ==='confirmation') {
					self.bind_trash();
					self.tooltip_bind();
					self.bind_carousel();

				}
				
				$('#btn_form', self.options.form).unbind().bind('click', function () {
					self.save_coupon(); 
				});

				if (self.options.save_coupon !== 'submit') {
					$("#process_save_coupon", self.options.form).css('display', 'block').show();
				}
				if ($("#great_offers").length > 0) {
					self.bind_carousel();
				}
				$(self.options.form).attr("ACTION", "/dispatcher.php?action=save_coupon");
				new CompaneoMask(self.options.default_lang_code);
				self.coupon_helper();
				return true;
				

			}
		});
		
		this.triggerCustomEvent('coupon');
	};
	
	self.check_coupon = function () {	
		$("#btn_form", self.options.form).focus();

		if ($(".warn:visible").length > 0) {
			var id = $(".warn:visible:first").parents('div.questionRFQ');

			if (id) {
				for (var i = 0; i< 2; i++) {
						$(id).animate({opacity: 0.1}, 250 );
						$(id).animate({opacity: 1}, 250 );
					}

			}
			return false;
		}
		return true;
	};
	
	self.save_coupon = function () {	
	
		clearInterval(self.autosave_id);
		
		if ($("#btn_form_hidden").is(':visible') ||$(".jqicontainer").is(':visible') || self.check_coupon() === false ) {
			return false;
		}		
		self.call_process();
		
		var is_tags = (window.location.href.indexOf("tag") !== -1);
		$.ajax({
			type	:  (self.options.is_api === true)?'GET':'POST',
			url		: self.path_to_ajax +'action=save_coupon&is_tags=' + is_tags,
			data	: this.serializeAddContext(),
			dataType: self.options.data_type,
			context	: this,
			async	: true,
			success	: function (save_coupon_res) {
				
				self.clear_error_messages();
			
				switch (save_coupon_res.status) {
				case 'success':
					if (self.options.is_api === true) {
						self.api_next_form();
						return false;
					}
					if ($("#great_offers").length > 0) {
						self.bind_carousel();
					}
				
					if (self.options.saved_coupon === 'submit') {
						var tmp = (self.list_qa !== false)?3000:50;
						setTimeout(function() { $(self.options.form).submit() },tmp);
						return false;
					}
				
					$('#partial_coupon', self.options.form).html(save_coupon_res.data).css('display', 'block').show();
					$('.process_validate_nav', self.options.form).remove();
					
					if (save_coupon_res.page_type === 'qa') {
							window.QA = new CompaneoQa();
							QA.init(self.options.default_lang_code, self.options.site_front, self.options.is_api, self.options.confirm_mode);
							$(".menu_bar").hide();
						
					}
					if (save_coupon_res.page_type ==='confirmation') {
						
						if(self.options.is_api) {
							$('.show_step_rfq,.show_step_coupon, #carousel_logo_fac').hide();
						}
						self.bind_trash();
						self.tooltip_bind();
						self.bind_carousel();
						return false;
						
					}
					
					
					break;
				case 'error':
                    if(self.options.is_api !==true) {
                        $.prompt.close();
                    }
                    else{
                        $("#one_qa,#multiple_qa,#qa_logo,#api_layer_processing,#layer_processing,#api_processing").hide();
                    }


					if ($('#partial_coupon').length === 0) {
						$('<div id="partial_coupon" class="corpQuestionnaire"></div>').appendTo(self.options.form);
					}
					$('#partial_coupon', self.options.form).html(save_coupon_res.data).css('display', 'block').show();
					$("#process_save_coupon", self.options.form).css('display', 'block').show();
					new CompaneoMask(self.options.default_lang_code);
					self.coupon_helper();
					break;
				}
				
				return true;

			}
		});
	};
	
	self.serializeAddContext = function (serializeForm) {	
		serializeForm = serializeForm || true;
		
		var data = [];

		if (serializeForm === true) {
			data = $(self.options.form).serializeArray();
		}

		if (window.companeoDefaultContext !== undefined) {
			for (var element in window.companeoDefaultContext) {
				if (element !== '') {
					data.push({
						name	: element,
						value	: window.companeoDefaultContext[element]
					});
				}
			}
		}
		return data;

	};

	self.scrollToFirstError = function () {		
		var id = $(".questionError:first").attr('id');
		if (id) {
			$('html,body').scrollTop($("#" + id).offset().top, 1000);
		}
	};
	

	self.show_next = function (update_qid, display_errors, get_next_auto) {	
		if (self.options.mode === 'normal') {
			if (update_qid === true) {
				$('#qid', self.options.form).val(this.current_question_id);
			}
			else {
				$('#qid', self.options.form).val('');
			}
		}
		else if (update_qid !== false &&  display_errors !== false || self.qid_for_silde.indexOf('mail') !==-1) {
			
				$('#qid', self.options.form).val(self.qid_for_silde);
		}
		$("#last_slide").val(self.last_slide === self.current_slide); 
		if (self.options.reduced_template === "1" && $("#container_bdx").length > 0) { 
			$("#container_bdx").unbind();
		}
		
		$.ajax({
			type	:  (self.options.is_api === true)?'GET':'POST',
			data	: this.serializeAddContext(),
			dataType: self.options.data_type, 
			//context	: this,
			url		: self.path_to_ajax +'action=save_questionnaire',
			async	: true,
			success	: function (show_next_res) {
		
				self.first_save = false;
				if (update_qid === false &&  display_errors === false) {
					return false;
				}
			
				if ($('#' + self.options.ID, self.options.form).val() === '' && show_next_res.rfq_id !== undefined) {
					$('#' + self.options.ID, self.options.form).val(show_next_res.rfq_id);
				}
				self.last_exec = new Date().valueOf();
				if (show_next_res.old_rfq_msg !== undefined) {
					if (show_next_res.is_qa === true) {
						$('#form'+ show_next_res.is_qa).html(show_next_res.old_rfq_msg);
					}
					else {
						$.showMessage({
							thisMessage	: [show_next_res.old_rfq_msg],
							className	: 'messageStackError',
							appendto	:  (self.options.is_api === true)?"#"+cmpoApi.options.divId:'body'
						});
					}
				}
				
				if (update_qid === false) {
					self.clear_error_messages();
				}

				if (show_next_res.list_qa !== false && self.options.is_qa !== true) {
					
					if(self.options.is_api){
						cmpoApi.list_qa = show_next_res.list_qa;
					}
					self.list_qa = show_next_res.list_qa;
				}

				if (show_next_res.status === 'success') {
					self.res_check = true;

					if ( self.options.mode === 'normal') {
						
						if (update_qid === false && display_errors !== false ) {
						if (self.options.is_qa === true) {
							self.get_next_qa(show_next_res.cat_cod);
							self.update_status_qa(show_next_res.rfq_id);
							return false;
						}
						clearInterval(self.autosave_id);
						self.get_coupon(show_next_res.coupon_shown);
						return false;
						}
					}
					else {
						if (self.last_slide === self.current_slide && (get_next_auto  || self.check_get_next())) {
							if (self.options.is_qa === true) {
								self.update_status_qa(show_next_res.rfq_id);
								if (self.options.is_api) {
									self.api_next_form();
									return false;
								}
								self.get_next_qa(show_next_res.cat_cod);
								return false;
							}
							clearInterval(self.autosave_id);
							self.get_coupon(show_next_res.coupon_shown);
							return false;
						}

						if (get_next_auto  || self.check_get_next()) {
							self.question_shown = false;
							self.displayCurrentSlide();
						}
						else{
							return false;
						}
					}

				}
				else {
					if (display_errors === false) {
						return false;
					}
					self.res_check = false;
					if (show_next_res.list_error !== undefined && show_next_res.list_error !== false) {
						$.each(show_next_res.list_error, function (qid) {
							if (qid === 'website') {
								$("#website").parent().parent().removeClass('is_answered').addClass('questionError');
							}
							$("#form_qst_" + qid + ", #hidden_form_" + qid, self.options.form).removeClass('is_answered').addClass('questionError');
						});
					}
					
					if (show_next_res.error !== undefined && self.options.mode !== 'slide' && update_qid === false) {
						$("#msg_error").attr('class', 'required_qst').html("<p>" + show_next_res.error + "</p>");
							self.scrollToFirstError();

					}
				}


				return false;	
			}
		});
	};
	self.check_get_next = function () {	

		var qids = self.qid_for_silde.split(',');
		var res = true;
		$.each(qids, function (i,qid) {
			qid = parseInt(qid, 10);
			if (isNaN(qid) === false) {

				var check = $.inArray(self.question_type[qid],Array('checkbox', 'img_checkbox','text', 'textarea'));

				if (check !==-1 ||  $.inArray(qid,self.answered_qid) === -1) {
					res = false;
				}
				
			}
			
		});

		return res;
	};
	self.get_coupon = function (show_coupon) {	
		var temp = 50;
		if ((self.options.save_questionnaire === 'submit' || show_coupon === false) && self.options.is_api !== true ) {
			if (show_coupon === false) {
				$(self.options.form).attr("ACTION", "/dispatcher.php?action=save_coupon");
				self.call_process();
				temp = (self.list_qa !== false || self.list_qa === undefined)?3000:50;
			}
			setTimeout(function() { $(self.options.form).submit() }, temp);
			return false;
		}
		else {
			$('#msg_error').css('display', 'none').hide();
			self.display_coupon();
			return false;

		}
	};
	self.api_next_form = function () {	
		self.list_qa =(self.options.is_api === true)?cmpoApi.list_qa:self.list_qa;

		if ((self.list_qa!== undefined && self.list_qa !== false) && cmpoApi.current_qa < self.list_qa.length && self.options.answer_qa_online === "1" ) {
			cmpoApi.options.cat_cod = self.list_qa[cmpoApi.current_qa];
				if (cmpoApi.current_qa === 0 ) {
					self.call_process();
					$('body').delay(3000).queue(function () {
					
						cmpoApi.current_qa++;
						cmpoApi.ajax_getform(true, true);
					});
				}
				else{
					cmpoApi.current_qa++;
					cmpoApi.ajax_getform(true, true);
				}
				
		}else{

			if(cmpoApi.current_qa === 0){
				self.call_process();
				$('body').delay(3000).queue(function () {
					$.prompt.close();
					self.get_confirmation();
				});
			}else{
				self.get_confirmation();
			}
		}

	};
	
	self.call_process = function () {	

		if(self.options.is_api !== true) {
			$('html,body').scrollTop(0 , 10);
		}

		if ((self.list_qa!== undefined && self.list_qa !== false) && self.list_qa.length > 0 && (self.options.answer_qa_online === undefined || self.options.answer_qa_online === "1") ) {

			$.each(self.list_qa, function (i, qa) {
				$("#qa_infos_" + qa).css('display', 'block').show();
			});
			if (self.list_qa.length === 1) {
				$("#one_qa").show();
			}
			else {
				$("#multiple_qa").show();
			}
			$("#qa_logo").css('width',((self.list_qa.length/3)*100)+'%').show();
		
			if ($("#layer_processing").length > 0) {
				if(self.options.is_api !==true) {
					$.prompt($("#layer_processing_qa").html(),{buttons: {}, top:'5%', prefix:(jQuery.browser.msie && parseInt(jQuery.browser.version)==6)?'jqi_ie6':'jqi'});
					$(".jqifade").css('background-color','#457da9');
				}
				else{
					
					if((jQuery.browser.msie && parseInt($.browser.version) > 7) || !jQuery.browser.msie){
						var pos =  $(self.container_id).position();
						$("#api_layer_processing").css({height : $(self.container_id).height(), top: pos.top, left:pos.left, width:$(self.container_id).width()}).show();
					}
					$("#layer_processing_qa,#api_processing").show();
				}
			}
		}
		else{
			if ($("#layer_processing").length > 0) {
				if(self.options.is_api !==true) {
				$.prompt($("#layer_processing").html(),{buttons: {},  top:'5%',prefix:(jQuery.browser.msie && parseInt(jQuery.browser.version)==6)?'jqi_ie6':'jqi'});
				$(".jqifade").css('background-color','#457da9');
				}
				else{
				
					if((jQuery.browser.msie && parseInt($.browser.version) > 7) || !jQuery.browser.msie){
						var pos =  $(self.container_id).position();
						$("#api_layer_processing").css({height : $(self.container_id).height(), top: pos.top, left:pos.left, width:$(self.container_id).width()}).show();
					}
					$("#layer_processing,#api_processing").show();
				}
			}
		}
	
	};
	
	self.increment_num_qst = function () {	
		if (this.sub_question_id === '' && this.num_qst <= this.total_qst) {
			this.num_qst++;
		}
	};

	self.decrement_num_qst = function () {
		if (this.num_qst > 1) {
			this.num_qst--;
		}
	};


	self.update_num_qst = function (prev_next) {
		self.last_question = false;

		if (prev_next === true) {
			this.increment_num_qst();
		}
		else {

			this.decrement_num_qst();
		}

		if (this.num_qst === (this.total_qst + 1)) {
			self.last_question = true;
		}
	};

	self.get_qid_from_str = function (val) {

		if (val === 'form_qst_question_additional') {
			return 'qst_question_additional';
		}

		if (val === 'form_qst_mail') {
			return 'mail';
		}
		if (val === '' || val === undefined || !val) {
			return false;
		}

		var
			tmp = val.split('_'),
			qid = parseInt(tmp[2], 10);

		return isNaN(qid) ? '' : qid;

	};

	self.clear_error_messages = function (qid) {	
		if (qid !== undefined) {
			$("#hidden_form_" + qid, self.options.form).removeClass('questionError is_answered');
			$("#form_qst_" + qid, self.options.form).removeClass('questionError is_answered');
		}
		else {
			$(".questionError", self.options.form).removeClass('questionError is_answered');
			$(".error_message", self.options.form).remove();
			$("li:visible", self.options.form).css('display', 'block').show();
		}
	};


	self.display_question_form = function () {	
		if (this.list_sub_qst === undefined) {
			return;
		}

		$.each(this.list_sub_qst, function (i, qid) {
			$("#hidden_form_" + qid, self.options.form).css('display', 'block').show();
		});

	};

	self.display_this_question = function (question) {	

		if (question === false) {
			return false;
		}

		this.clear_error_messages();

		this.current_question_id	= this.get_qid_from_str(question);
		$(".question_element li", self.options.form).css('display', 'none').hide();
		$("#" + question, self.options.form).css('display', 'block').show('slow');
	};
	
	self.display_question = function (question) {	

		if (this.display_one_question === true) {
			this.display_this_question(question);
			return false;
		}
		
		this.display_question_form();
	};

	self.check_mandatory = function (question) {	
		return ($('#' + question + ' span.required', self.options.form).length > 0);
	};

	self.check_answered = function (question) {	
		if ($('#' + question + ' input:checked', self.options.form).length > 0) {
			return true;
		}
		else if ($('#' + question + ' input:selected', self.options.form).length > 0) {
			return true;
		}
		else if ($('#' + question).val() !== '') {
			return true;
		}

		return false;
	};
	
	self.show_question = function (qid) {
		if (this.display_one_question === true) {
            self.show_next(true, true, true);
            return false;
		}
		else {
			this.current_question_id = qid;
			self.show_next(true, true);
		}
	};

	self.add_sub_question = function (qid, sub_qst, slidenum) {	

		if (!sub_qst instanceof Array) {
			return false;
		}
	
		if (sub_qst.length > 0) {
			
			
			if (this.display_one_question === true) {
				var 
				tmp_toc				= this.toc, i, n;
				
				this.toc = [];
				
				for (i = 0; i < tmp_toc.length; i++) {
					
					if (tmp_toc[i] === 'form_qst_' + qid) {
						
						this.toc.push(tmp_toc[i]);
						
						for (n = 0; n < sub_qst.length; n++) {
							if ($('#hidden_form_' + sub_qst[n], self.options.form).length > 0) {
								this.toc.push('hidden_form_' + sub_qst[n]);
							}
						}
					}
					else {
						this.toc.push(tmp_toc[i]);
					}
				}
				
				this.total_qst = this.toc.length;
			}
			if(self.qst_slide[slidenum] === undefined){
				self.qst_slide[slidenum] = 0;
			var nb_question =	$('li').filter('.slide'+slidenum).filter('.companeo_question');
				$.each(nb_question, function (i, q) {
					var id = $(q).attr('id').split('_');
					self.qst_slide[slidenum] += self.all_sub_qst['qst_tail_'+id[2]];
				});
			}
			var current_slidenum = Math.max(slidenum, self.current_slide);
			$.each(sub_qst, function (i, q) {
				if (q !== undefined) {
					if (self.options.mode === 'slide') {
						var in_current_slide = self.qst_slide[slidenum] + self.all_sub_qst['qst_tail_'+ q] < 13;
								if (in_current_slide && !self.display_one_question){
									if (self.qid_for_silde.indexOf(q) === -1) {
										self.qid_for_silde +=','+q;
									}
									$('#qid').val(self.qid_for_silde);
									self.qst_slide[slidenum] += self.all_sub_qst['qst_tail_'+q];
									
									if(self.current_slide === current_slidenum){
										$('#hidden_form_' + q, self.options.form).css('display', 'block').show();
									}
									$('#hidden_form_' + q, self.options.form).addClass('to_display displayed');
									$("#hidden_form_"+q).attr('class',$("#hidden_form_"+q).attr('class').replace('slide'+(current_slidenum+1), 'slide'+ current_slidenum));
									self.question_shown = true;
							}else{
									if($("#hidden_form_"+q).hasClass('to_display')===false){
										$("#hidden_form_"+q).attr('class',"sub_question to_display "+'slide'+ (current_slidenum+1));
									}
							}
					}
					else {
						if ($('#hidden_form_' + q, self.options.form).length > 0) {
							$('#hidden_form_' + q, self.options.form).css('display', 'block').show();
						}
						
						
					}
				}	
			});
			
		}
	};

	self.del_sub_question = function (answerid, slidenum) {	

		var 
		list_qst_to_del			= [],
		sub_qst_data			= self.all_sub_qst[answerid+'_sub_qst'], 
		tmp_toc					= this.toc,
		i						= 0,
		n						= 0,
		testdeletion			= false,
		common_sub_question	= [];
		
		answerid				= "#"+answerid;
		
		$('input:checked', $(answerid).closest('li')).each(function () {
			for (var e in sub_qst_data) {
				
				var subqst = self.all_sub_qst[$(this).attr('id')+'_sub_qst'];
				if (e && subqst !== undefined) {
					if ($.inArray(sub_qst_data[e], subqst) !== -1) {
						common_sub_question.push(sub_qst_data[e]);
					}
				}
			}
		});
	
		if (sub_qst_data !== null && sub_qst_data !== undefined && sub_qst_data.length > 0) {
			
			$.each(sub_qst_data, function (i, q) {
					if($.inArray(q,common_sub_question ) === -1){
						var 
						o = $('#hidden_form_' + q, self.options.form).removeClass('displayed'),
						is_on_same_slide = null;
						
						if (self.options.mode === 'slide') {
							var testSlide = new RegExp(/slide(\d)/).exec(o.attr('class'));
							is_on_same_slide = o.removeClass('to_display').hasClass('slide' + self.current_slide) || parseInt(testSlide[1],10) < self.current_slide;
							
							if (is_on_same_slide === true || self.current_slide > slidenum) {
								o.removeClass('displayed').css('display', 'none').hide();
								self.question_shown = false;
								self.qid_for_silde = self.qid_for_silde.replace(q,'');
								$('#qid').val(self.qid_for_silde);
								self.qst_slide[slidenum] -= self.all_sub_qst['qst_tail_'+q];
							}
						}
						else {
							o.css('display', 'none').hide();
						}
		
						list_qst_to_del.push('hidden_form_' + q);
					}
			});

			if (this.display_one_question === true) {

				this.toc = [];
				
				for (i = 0; i < tmp_toc.length; i++) {
					
					testdeletion = false;
					
					for (n = 0; n < list_qst_to_del.length; n++) {
						
						if (tmp_toc[i] === list_qst_to_del[n]) {
							
							testdeletion = true;
							break;
						}
					}
					
					if (testdeletion === false) {
						this.toc.push(tmp_toc[i]);
					}
				}
				this.total_qst = this.toc.length;
			}
		}
	};
	
	self.make_answered = function (qid, type, is_checked, val) {	

		var 
			scope		= self.options.form,
			is_checkbox	= this.checkbox_metatype(type),
			q			= $("#form_qst_" + qid + ", #hidden_form_" + qid, scope),
			checked_val	= ($('#form_qst_' + qid + ' input:checked', scope).length + $('#hidden_form_' + qid + ' input:checked', scope).length);
			
		if (val !== 0 && val!== undefined && val!== '') {
			if ($.inArray(qid, self.answered_qid)) {
				self.answered_qid.push(qid);
			}
			q.removeClass('questionError').addClass('is_answered');
	
		} 
		else {
			self.answered_qid[qid] = undefined;
			q.addClass('questionError').removeClass('is_answered');
		}
		
		if (is_checkbox === true) {
			if (checked_val === 0) {
				q.addClass('questionError').removeClass('is_answered');
			}
		}
		
		if (type.indexOf('select') !== -1 && val === 0) {
			this.clear_error_messages(qid);
		}
	};
	
	self.make_answered_text = function (id, qid) {
		var 
		val	= $.trim($('#' + id).val()),
		q	= $('#form_qst_' + qid + ', #hidden_form_' + qid, self.options.form);
		
		if (val !== null && val !== '' && val.indexOf('_') === -1) {
			self.answered_qid.push(qid);
			q.removeClass('questionError').addClass('is_answered');
		} 
		else {
			if (val !== '') {
				self.answered_qid[qid] = undefined;
				q.removeClass('is_answered').addClass('questionError');
			}
		}
	};
	
	self.make_answered_qa = function () {	
		if ($('#form_qst_question_additional input:checked', self.options.form).length > 0) {
			
			$('#form_qst_question_additional', self.options.form).addClass('is_answered');
		}
		else {
			$('#form_qst_question_additional', self.options.form).removeClass('is_answered');
		}
	};
	
	self.sub_qst_binding = function (qid, val, type, is_checked, dry_run) {	
		
	
		this.current_question_id = qid;
		if (dry_run !== true && self.options.mode === 'slide') {
			self.show_next(true, false);
		}

		var 
			is_checkbox		= this.checkbox_metatype(type),
			last_iid		= self.all_sub_qst['form_qst_' + qid+'_last_iid'],
			max				= 0;
			
		
		dry_run	= !!(dry_run === true);
		
		is_checked = !(is_checked === undefined || is_checked === false);
		
		
		if (qid !== undefined) {
			this.make_answered(qid, type, is_checked, val);
		}
		
		var slidenum = self.all_sub_qst['form_qst_' + qid+'_slidemun'];
		var sub_questions = self.all_sub_qst[type + '_' + val+'_sub_qst'];
		
		if (!is_checkbox) {
			
			if (last_iid === val) {
				return true;
			}
			
			if (last_iid > 0) {
				this.del_sub_question(type + '_' + last_iid, slidenum);
			}
			
			//$('#form_qst_' + qid, self.options.form).data('last_iid', val);
			self.all_sub_qst['form_qst_' + qid+'_last_iid'] = val;
		} 
		else if (is_checked === false) {
			this.del_sub_question(type + '_' + val, slidenum);
		}
		

		if (sub_questions !== undefined && sub_questions !== null ) {
			max = sub_questions.length;
			if (max > 0 && sub_questions instanceof Array && (!is_checkbox || (is_checkbox && is_checked === true))) {
				self.add_sub_question(qid, sub_questions,slidenum);
			}
		}
		
		if (self.options.mode === 'slide') {
			//new_slide = this.determineCurrentSlide();
			/*if (new_slide !== this.current_slide && (!is_checkbox && dry_run === false) && this.optionalQuestionsLeft(this.current_slide) === 0) {
				this.displayCurrentSlide(new_slide);
			}*/
			return true;
		}

		if (!is_checkbox && dry_run === false) {
			self.show_question(qid);
		}

		return dry_run !== true;
		

	};

	self.test_change = function () {	

		var 
		tmp_serialize		= $(self.options.form).serialize(),
		new_date			= new Date().valueOf(),
		interval_last_exec	= new_date - self.last_exec;

		if (self.from_last_serialize !== tmp_serialize && ((interval_last_exec) > self.options.form_post_interval)) {
			self.from_last_serialize = tmp_serialize;
			self.last_exec = new_date;
			self.show_next(false, false);
		}
	};
	
	self.update_status_qa = function (rfq_id) {	
		if (rfq_id != undefined) {
			$.ajax({
				type	:  (self.options.is_api === true)?'GET':'POST',
				url		: self.path_to_ajax +'action=update_status_qa',
				data	: {rfq_id: rfq_id},
				dataType: self.options.data_type, 
				context	: this,
				async	: true
			});
		}
	};
	
	self.refresh_session = function () {	
		var 
		new_date					= new Date().valueOf(),
		interval_last_session_exec	= new_date - self.last_session_exec;

		if (interval_last_session_exec > self.session_post_interval) {

			$.ajax({
				type	:  (self.options.is_api === true)?'GET':'POST',
				url		: self.path_to_ajax +'action=refresh_session',
				dataType: self.options.data_type, 
				context	: this,
				async	: true,
				success : function () {
					self.last_session_exec = new Date().valueOf();
				}
			});
			return false;
		}
	};

	self.progressBar = function (done) {	
		$("#progress_done").css('width', done + "%");
	};
	
	self.delete_offer = function (oid, rfq_id, pos) {	
	
		$("#dialog:ui-dialog").dialog("destroy");
		$("#dialog-confirm").dialog({
			resizable: false,
		    dialogClass : 'delete_offer',
			position    :[pos.left-50,(self.options.is_api === true)?pos.top+170:pos.top+70],
			buttons: {
				"ok": function() {
					$.ajax({
						type	:  (self.options.is_api === true)?'GET':'POST',
						url		: self.path_to_ajax +'action=delete_offer',
						dataType: self.options.data_type, 
						data	: {action: 'delete_offer', oid: oid, rfq_id: rfq_id},
						async	: true,
						success : function (res) {
							$("#dialog-confirm").dialog("close");
							if (res.status === 'success') {
								$("#offer_selected_"+ res.rfq_id).html(res.data);
								$("#offer_selected_"+ res.rfq_id).effect("highlight", {color : "#da6e7d"}, 1000);
								self.bind_trash();
								self.bind_offer_view();
								self.tooltip_bind();
							}
							else {
								
								if (res.old_rfq_msg !== undefined ) {
									$.showMessage({
										thisMessage	: [res.old_rfq_msg],
										className	: 'messageStackError',
										appendto	:  (self.options.is_api === true)?"#"+cmpoApi.options.divId:'body'
									});
									return false;
								}
								$(".messageStackError").text(res.message);
							}
						}
						
					});
				},
				Cancel: function() {
					$(this).dialog( "close" );
				}
			}
		}).width('90%');
		$(".delete_offer").attr('id',"dialog_delete");
	};

	self.checkbox_metatype = function (type) {	
		return type === 'checkbox' || type === 'img_checkbox';

	};
	
	self.onKeyPressHandler = function (e) {	

		e 				= e || window.event;
		var having_focus	= (document.activeElement.id == 'input_search');
		if (e.keyCode === 13 && !having_focus) {
			if (self.onCoupon === true) {
				$('input, select,textarea, radio','.questionRFQ').each(function() {
					$(this).blur();
				});
				$('#btn_form').click();
			}else{
				$('#show_next').click();
			}
			return false;
		}
	};
	
	self.coupon_helper = function() {	

		self.onCoupon = true;
		self.firstTime = true;
		
		var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );
		var is_safari = /safari/.test( navigator.userAgent.toLowerCase() );

		if (is_chrome||is_safari){
			$("#let_message_to_fac :radio").bind('change' ,function (){
				self.focusThis(this);
			});
		}
		
		if ( $('#is_dedicated').val() === 'true') {
			self.message_ok = '<div class=\'ok okpic\'></div>';
			$('.warn').text('').addClass('warnpic');
		
		}

		$('#btn_form', self.options.form).unbind().bind('click', function () {
			self.save_coupon(); 
		});

		
		$('p.quiVous').attr('class','identite');
		
		// The dropdown list "poste" is not displayed on dedicated news.
		if ($('#list_poste').length > 0) {
			
			self.clone_poste = $('#list_poste option').clone();
			
			$('#list_poste').bind('change',function () {
			
				if ($(this).val() == 100) {
					$('#div_poste_other').show();
					$("#div_poste_other > p").removeClass('field_provided');
					$("#div_poste_other > label > input").removeClass('field_provided');
				}
				else{
					$('#div_poste_other').hide();
					$("#div_poste_other > p").addClass('field_provided');
					$("#div_poste_other > label > input").addClass('field_provided');
				}
			}).change();
		}
		
		$('#list_proserv_activity').bind('change',function() {
			if ($(this).val() == 100) {
				
				$('#div_proserv_activity_other').show();
				$("#div_proserv_activity_other > p, #div_proserv_activity_other").removeClass('field_provided');
				$("#div_proserv_activity_other > label > input, #div_proserv_activity_other").removeClass('field_provided');
			
			}
			else{
				$('#div_proserv_activity_other').hide();
				$("#div_proserv_activity_other > p, #div_proserv_activity_other").addClass('field_provided');
				$("#div_proserv_activity_other > label > input, #div_proserv_activity_other").addClass('field_provided');
			}
		}).change();
		
		$('#list_segment').bind('change', function() {
			self.initLayout($(this).val()); 
			if( !self.firstTime ){ self.checkThis($(this)); }
			self.firstTime = false;
			self.warn_company_name($(this).val(), false);
			
		});
		
		$('#date_creation').unbind().bind('change', function () {
			
			var date = $(this).val();
			if(date !== ''){
				$('div.warn', '#div_date_creation').hide();
			}
			if (date === '' || date ==='OLDA') {
				return false;
			}

			// Auto-entrepreneur exists only in France.
			if (self.options.autoentrepreneur === true) {
			
				var year = parseInt(date, 10);
				var auto = $.inArray($("#list_segment").val(), ['1','3']);
				
				if (auto !== -1 && (isNaN(year) || (new Date().getFullYear() < year +3))) {
					$("#div_autoentrepreneur > p, #div_autoentrepreneur").removeClass('field_provided');
					$("input[name='autoentrepreneur']:first").focus();
				} else {
					$("#div_autoentrepreneur > p, #div_autoentrepreneur").addClass('field_provided');
				}
			
			}
			
		});
		
		$('#country').bind('change', function() {
			self.open_outgeo();
			self.disable_form();
		});
		
		if($('#list_cities').length){
			$('#list_cities a').bind('click',function(){
				$('#city').val($(this).text());
				$('#city').blur();
				return false;
			});
			
			$('#city').bind('focus', function(){
				$('#list_cities').show();
			})
			.bind('blur',function(){
				setTimeout("$('#list_cities').hide()",300);				
			});
		}
		
		$('input, select,textarea, radio','#partial_coupon').each(function() {
	
			$(this).bind('focus', function() {self.focusThis(this);})
			    	.bind('blur', function() {self.checkThis(this);});
						
			var thisParent = $(this).parents('div.questionRFQ');
			var thisParentID = $(this).parents('div.questionRFQ').attr('id');
			var thisID = $(this).attr('id');	
			if ( $(this).hasClass('error') ) {
				
				$('div.ok',thisParent).remove();							
				
				if ( thisParentID == 'div_company_name' ) {
					if ( $('select','#div_segment').val() != '' ) {
						$('select','#div_segment').trigger('change');
						$('div.warn', thisParent).hide();
						$('div.warn', thisParent).filter('#notice_cn_' + $('select','#div_segment').val()).show();
					}
				
				}else if (thisParentID != 'div_cli_civilite'  ) {
					$('div.warn', thisParent).show();
				}
				
				
				if ( $('input[type = radio]', '#div_cli_civilite').is(':checked') != true) {
					$('div.warn', '#div_cli_civilite').show(); 
				}
			
			}else if ( thisParentID == 'div_cli_civilite' && $('input[type = radio]', '#div_cli_civilite').is(':checked')
						&&	$('div.ok',thisParent).length == 0 ) {
				$('#div_cli_civilite').append(self.message_ok);  
			}else if (thisID == 'cli_mail') {	
					self.checkEmail(this);
			}else if ($(this).val() != '' && $(this).attr('type') != 'radio'	&& thisID != 'cli_news_partner' && $(this).attr('type')!='checkbox' && $(this).attr('type')!='hidden'  ) {	
					thisParent.append(self.message_ok);
			}
		});		
		
		$('select','#div_segment').trigger('change');
		$(".radio_civ:first").focus();
		//self.estara_bind();		
	};
	
	self.warn_company_name = function(index, show_warn) {	

		$('#date_creation').trigger('change');
	
		if (index !==5 && index !='' ) {
			if (index === '6') {
				$("#div_proserv_activity > p").removeClass('field_provided');
				$("#div_proserv_activity > select" ).removeClass('field_provided');
			}
			
			$("#div_company_name > p, #div_date_creation > p, #div_poste > p").removeClass('field_provided');
			$("#div_company_name > label>input, #div_date_creation > select, #div_poste > select" ).removeClass('field_provided');
			$("#company_name").attr('tabindex', 5).focus();
		}
		else{
			if (index === '6') {
				$("#div_proserv_activity > p").addClass('field_provided');
				$("#div_proserv_activity > select" ).addClass('field_provided');
			}
			$("#div_company_name > p, #div_date_creation > p, #div_poste > p").addClass('field_provided');
			$("#div_company_name > label>input, #div_date_creation > select, #div_poste > select").addClass('field_provided');
		}
		if (index != undefined && $('#company_name').val()  == '' && show_warn === undefined) {
			$('div.ok', '#div_company_name').remove();
			$('.warn', '#div_company_name').hide();
			$('#notice_cn_'+index, '#div_company_name' ).show();
		}
		if (index === "") {
			$( '#div_company_name').hide();
			$( '#div_date_creation').hide();
			$( '#div_poste').hide();
		}
	};
	
	self.focusThis = function(obj) {	
		
		if ( $(obj).attr('type') != 'select-one' ) {

			$(obj).removeClass("idleField").removeClass("activite").removeClass("poste")
			.addClass("focusField");
		}

		if( $(obj).attr('name') === 'let_message_to_fac' ){
			if($(obj).val() === 'true'){
				$("#message_to_fac").show();
				return false;
			}
			$("#message_to_fac").hide();
			return false;
		}
		$('.identite').css({'font-weight':''});
		$(obj).parents('div.questionRFQ').children('p.identite').css({'font-weight':'bold'});

		//$('#div_cli_civilite').children('p.identite').attr({'style':''});

		if ( $('input[type = radio]', '#div_cli_civilite').is(':checked') && $('#div_cli_civilite').children('div.ok').length == 0 ) {
				 		$('#div_cli_civilite').children('div.warn').hide();
						$('#div_cli_civilite').append(self.message_ok);
		}					
	};	
	
	self.checkThis = function(obj) {	
		var thisParent 		= $(obj).parents('div.questionRFQ');
		var thisParentID 	= thisParent.attr('id');
		var value 		  	= $.trim($(obj).val());
		var trash_tel		= Array("","00.00.00.00.00","01.23.45.67.89","000.00.00.000","012.34.56.789");
	

		$('div.ok',thisParent).remove();
		if ( thisParent.children('p').children('span').hasClass('required') ) {

			switch($(obj).attr('type')) {
				case 'radio':
					if ( $('input[type = radio]', '#div_cli_civilite').is(':checked')  ) {
						$('label', '#div_cli_civilite').attr({'style':''});
						$("#cli_prenom").addClass("focusField").focus();
					}else{
						$(this).removeClass("focusField").addClass("idleField");

					}
				break;
				case 'text':
                case 'email':
                case 'tel':
					$(obj).removeClass("focusField").addClass("idleField");
					if ( thisParentID == 'div_company_name' ) { // Si CAS PARTICULIER
						if ( value == '' && $('select','#div_segment').val() != '' ) {
							$('div.warn', thisParent).hide();
							$('#notice_cn_' +$('select','#div_segment').val(), '#div_company_name').show();
						
						}else if ( value == '' && $('select','#div_segment').val() == '' ) {
							$('div.warn', thisParent).hide();
							$('#notice_cn_1', '#div_company_name').show();
						}else{
							$('div.warn', thisParent).hide();
							thisParent.append(self.message_ok);	
						}
					}
					else if (thisParentID == 'div_cli_tel') {
						if ( $.inArray(value, trash_tel) != -1 || isNaN(parseInt(value)) && value.indexOf('00') !== 0) { 
							if ( $('div.warn:visible', thisParent).length == 0 ) {
								$('div.ok',thisParent).remove();
								$('div.warn', thisParent).show();
								self.checkValidPhone(false);
							}
						}
						else{
							self.checkValidPhone(true);
							$('div.warn', thisParent).hide();
							thisParent.append(self.message_ok);
						}
						
					}
					else if (thisParentID == 'cli_mail') { 
						self.checkEmail(obj); 
					}
					else{
						if ( value == '' ) { // Si le champ est vide
							if ( $('div.warn:visible', thisParent).length == 0 ) { // erreur non affich� donc afficher
								$('div.ok',thisParent).remove();
								$('div.warn', thisParent).show();
							}						
						}else{ // Si le champ est remplis 
							if ( $('div.warn:visible', thisParent).length == 1 ) { // Si message d'erreur
								$('div.warn', thisParent).hide();
								$(obj).attr({'style':''});					
							}
							
							
							if ( thisParentID == 'div_cli_prenom' && $('input[type = radio]', '#div_cli_civilite').is(':checked') != true ) {
								$('div.ok',thisParent).remove();
								thisParent.append(self.message_ok);
								$('div.warn', '#div_cli_civilite').show(); 
							}
							
							if ($('div.ok',thisParent).length == 0) {
								thisParent.append(self.message_ok);
							}
						}
					
					}
				break;
				case 'textarea':
				
					$(obj).removeClass("focusField").addClass("idleField");
					
					if ( value == '' && $('div.warn:visible', thisParent).length == 0 ) {
						$('div.ok',thisParent).remove();
						$('div.warn', thisParent).show();
					}else if ( value != '' && $('div.warn:visible', thisParent).length == 1 ) {
						$('div.warn', thisParent).hide();
						$(obj).attr({'style':''});
						thisParent.append(self.message_ok);
					}else if ( value != '' && $('div.warn:visible', thisParent).length == 0 && thisParent.children('div.ok').length == 0 ) {
						thisParent.append(self.message_ok);
					}
					
				break;	
				case 'select-one':
				case 'select-multiple':
				case 'select':
	
					$(obj).removeClass("focusField").addClass("idleField");
					$(obj).attr({'style':''});
					$('div.ok',thisParent).remove();
					
					if ( value == '' && $('div.warn:visible', thisParent).length == 0 ) {
						$('div.ok',thisParent).remove();
						$('div.warn', thisParent).show();							
					}else if ( value != '' && $('div.warn:visible', thisParent).length == 1 ) {
						$('div.warn', thisParent).hide();
						$(obj).attr({'style':''});
						thisParent.append(self.message_ok);
					}else if ( value != '' && $('div.warn:visible', thisParent).length == 0 && thisParent.children('div.ok').length == 0 ) {	
						thisParent.append(self.message_ok);
					}
				break;
			}
		}

		$(obj).parents('div.questionRFQ').children('p.identite').attr('style','');
		
	};
	
	self.checkEmail = function(obj) {
        var email = $('#cli_mail').val().toLowerCase();
        $('#cli_mail').val(email);
		
		var email_regexp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-\.])+\.)+([a-zA-Z0-9]{2,4})+$/;
			var is_valid = email.match(email_regexp);
				
		if (!is_valid ) {
			$('div.ok',$(obj).parents('div.questionRFQ')).remove();
			$('div.warn', $(obj).parents('div.questionRFQ') ).show();
		}
		else if (is_valid && $(obj).parents('div.questionRFQ').children('div.ok').length == 0 ) {
			$('div.warn', $(obj).parents('div.questionRFQ') ).hide();
			$(obj).parents('div.questionRFQ').append(self.message_ok);
			
		}else{
			$('div.warn', thisParent).show();
		}
	};
	
	self.checkValidPhone = function(isValid) {	
		$("#btn_form").attr('onclick','');
		if (!isValid) { 
			$("#btn_form").attr("disabled", true);
			self.animate_field("#cli_tel");
		}
		else{
			$("#btn_form").attr("disabled", false);
		}
	};
	
	self.animate_field = function(field) {	
		for (var i = 0; i<2; i++) {
			$(field).animate({opacity: 0.1}, 250 );
			$(field).animate({opacity: 1}, 250 );
		}
	};
	
	self.initLayout = function(selected) {	
		self.disable_fields(selected);
		if ($('#no_business').is(':selected') && $('#layer_particulier').html() != null) { 
			self.open_layout('layer_particulier'); 
			$('li > a').vAlign();
		}
		self.disable_form();
		
	};
	
	self.disable_fields = function(vous) {	
		
		if (vous === "") {
			return false;
		}

		var vous = parseInt(vous);

		$("#div_company_name").hide();
		$("#div_poste").hide();
		$("#div_poste_other").hide();
		$("#div_date_creation").hide();
		$("#div_activity").hide();
		$("#div_proserv_activity").hide();
		$('#div_proserv_activity_other').hide();

		
		switch(vous) {
			case 1:
				$("#div_company_name").show();
				$("#div_date_creation").show();
				$("#div_poste").show();
				$("#div_activity").show();
				$("#cn_caption").html($("#cn_alt_caption_1").html());
				break;
			case 2:
				$("#div_company_name").show();
				$("#div_activity").show();
				$("#div_poste").show();
				$("#cn_caption").html($("#cn_alt_caption_2").html());	
			break;
			case 3:
				$("#div_company_name").show();
				$("#div_date_creation").show();
				$("#div_activity").show();
				$("#cn_caption").html($("#cn_alt_caption_3").html());	
			break;			
			case 4:
				//$("#div_date_creation").css('display',"none");
				$("#div_company_name").show();
				$("#div_date_creation").show();
				$("#div_poste").show();	
				$("#cn_caption").html($("#cn_alt_caption_4").html());
			break;
			case 5:
				$("#cli_particulier").val('t');
				$("#cli_newsletter").val('f');
				$("#cli_news_partner").val('f');
			break;
			case 6:
				$("#div_date_creation").show();
				$("#div_proserv_activity").show();
				$("#list_proserv_activity").change();
			break;
		}

		
		if ($('#list_poste').length > 0) {
			
			var save_pst = $('#list_poste').val();
			
			$("#list_poste").empty().append(self.clone_poste.filter('.post2seg_' + vous));
			
			if (save_pst == '') {
				$('#list_poste option:first').attr('selected', 'selected').change();
			}
			else {
				$('#list_poste').val(save_pst).change();
			}
		
		}
	};
	
	/**
	 * Open a layout for a given layer_id.
	 */
	self.open_layout = function (layer_id) {	

		if(self.options.is_api !== true){
		 	if ($('#jqi_state_state0').length == 0) {
		 		$.prompt($('#'+layer_id).html());
		 		$('.jqiclose').bind('click',function() {
		 			self.select_segment(this);
		 		});
		 	}
		}
		else{
			
			if((jQuery.browser.msie && parseInt($.browser.version) > 7) || !jQuery.browser.msie){
				var pos =  $(self.container_id).position();
				$("#api_layer_processing").css({height : $(self.container_id).height(), top: pos.top, left:pos.left, width:$(self.container_id).width()}).show();
			}
			$("#api_processing,#layer_particulier").show();
	 		$('.jqiclose').bind('click',function() {
	 			$("#api_processing,#layer_particulier,#api_layer_processing").hide();
	 			self.select_segment(this);
	 		});
		}
	}; 

	/**
	 * Disable or enable submit button. 
	 */
	self.disable_form = function() {	
		
		var disable = false;
		var no_business = $("#layer_particulier").css("display");
		var county_selected = $("#country").val();
		var no_dn_business = $("#5").css("display");
		var button = ($("#layer_btn").html() != null) ? $("#layer_btn").html() : '#btn_form';
		
		
		
		if (
				(no_business != undefined || no_dn_business != undefined) 
			&& 
				(
					($("#no_business").is(':selected'))
				|| 
					($("#list_segment").val() == 5)
					
				)
			) {
			disable = true;
		} else if (		(county_selected != undefined)
						&&	(self.is_forbidden_countries(county_selected))) {
			disable = true;
		}

		var state = 'null';
		if (disable) {
			$(button).hide();
			$(button+"_hidden").show();
			state = 'f';
		} else {
			$(button).show();
			$(button+"_hidden").hide();
		}
			
		self.restore_ie_select();
		self.update_user_status($("#rfq_id_js").val(), state);
	};

	self.restore_ie_select = function () {	
		if ($('#jqi_state_state0').length >0) {
			return false;
		}
		
		if ($.browser.msie && parseInt($.browser.version) == 6) {
			$('select').css({'position':'relative','top':'0','left':'0'});
		}
		clearInterval(self.restore_id);

	};


	self.update_user_status = function(rfq_id, state) {	
		
		if (rfq_id == undefined) {
			return false;
		}
		
		$.ajax({
			type		: "POST",
			url			: "/w3s/w3s_user.php",
			data		: "w3s=update_user_status&rfq_id=" + rfq_id + "&state=" + state,
			dataType 	: "json"
		});
		
	};
	
	self.select_segment = function(el) {	
		if ($(el).attr('rel') === undefined) {
			return false;
		}
		var v = $(el).attr('rel');
		$.prompt.close();
		$('#list_segment').val(v);
		$('#list_segment').trigger('change');
		$("#api_layer_processing").hide();
		if ($.browser.msie && parseInt($.browser.version) == 6) {
			self.restore_id = setInterval(self.restore_ie_select, 30);
		}
	};
	
	/**
	 * Check if country_code is for a forbidden country.
	 * 
	 * @param 	String country_code ex. FR.
	 * @return Bool 
	 */
	self.is_forbidden_countries = function(country_code) {	
		var companeo_countries = [];
		companeo_countries["FR"] = 'france';
		companeo_countries["FX"] = 'france';
		companeo_countries["GP"] = 'france';
		companeo_countries["GF"] = 'france';
		companeo_countries["MQ"] = 'france';
		companeo_countries["MC"] = 'france';
		companeo_countries["RE"] = 'france';
		companeo_countries["PM"] = 'france';
		companeo_countries["NC"] = 'france';
		companeo_countries["BE"] = 'belgium';
		companeo_countries["DE"] = 'germany';
		companeo_countries["GB"] = 'uk';
		companeo_countries["NL"] = 'nl';
		companeo_countries["LU"] = 'luxembourg';
		companeo_countries["DE"] = 'Deutschland';
		return ((companeo_countries[country_code] === undefined));
	};

	/**
	 * Open layer "outgeo" for countries not supported by Companeo.
	 */
	self.open_outgeo = function() {	
		
		var county_selected = $("#country").val();
		if (self.is_forbidden_countries(county_selected)) {
			if ($("#layer_outgeo").html() != null) {
				if(self.options.is_api !== true){
					$.prompt($("#layer_outgeo").html());
				}else{
					if((jQuery.browser.msie && parseInt($.browser.version) > 7) || !jQuery.browser.msie){
						var pos =  $(self.container_id).position();
						$("#api_layer_processing").css({height : $(self.container_id).height(), top: pos.top, left:pos.left, width:$(self.container_id).width()}).show();
					}
					$("#api_processing,#layer_outgeo").show();
			 		$('.jqiclose').bind('click',function() {
			 			$("#api_processing,#layer_outgeo,#api_layer_processing").hide();
			 		});
				}
	 		}
		}

	};
	
	self.init_cluetip = function () {	
		$(".js_hint").cluetip({showTitle: false, splitTitle: '|', cluetipClass: 'default'});
		$(".img_hint").cluetip({showTitle: true, splitTitle: '|', cluetipClass:'image',width:302});
	};
	
	self.ie_img_checkbox = function () {	
		if ($.browser.msie === true) {
			$('.img_hint').bind('click', function() {
			
				var id = $(this).parent().attr('for');
				
				if (id.indexOf('img_checkbox_') != -1) {
					var ilabel = 'img_checkbox_' + $(this).attr('rel');
				
					$('#'+ilabel).trigger('click');
					if(jQuery.browser.msie && parseInt(jQuery.browser.version) < 9){
						$('#'+ilabel).trigger('click');
					}
					
					if ( $('#'+ilabel).attr('checked') != true ) {
		    			$('#'+ilabel).attr('checked', true);
					}else{
						$('#'+ilabel).attr('checked', false);
					}
				}
				else{
					var ilabel = 'img_radio_' + $(this).attr('rel');
					$('#'+ilabel).attr('checked', true);
					$('#'+ilabel).trigger('click');
					
				}
			});

		}
	};
	
	self.get_other_question = function () {	
	
		
		clearInterval(self.autosave_id);
		$.ajax({
			type	:  (self.options.is_api === true)?'GET':'POST',
			url		: self.path_to_ajax +'action=other_question',
			dataType: self.options.data_type, 
			context	: this,
			async	: false,
			success	: function (data) {
				self.current_slide			= 1;
				self.next_slide				= 1;
			
				self.options.get_other_question = false;
				$("#corps_questionnaire").html(data.data);
				self.options.first_registerInputs 	= true;
				self.init(self.options);
				self.options.first_registerInputs 	= false;
				
			}
		});
	}; 
	self.get_next_qa = function (cat_cod) {	
		//var Qa = new CompaneoQa();
		window.QA.skipe_qa("accordion_"+cat_cod);
	};
	self.estara_bind = function () {	
		/*var estara = $("#estara_alert").val();
		 if (estara != false && self.show_callcliquer === true) {
				window.onbeforeunload = function (event) {
							self.show_callcliquer = false
							return	self.beforeunload[self.options.default_lang_code];
				} 
		}*/
		
	}; 
	self.rfq_confirmation = function () {	
		
		
		self.tooltip_bind();
		self.offer_selected_entity();
		if (self.options.is_api !== true) {
			self.bind_carousel();
		}
		self.accord_confirm();
		self.bind_trash();
		self.bind_offer_view();
		
		$('.show_step_rfq').css('display', 'none').hide();
		$('.show_step_coupon').css('display', 'none').hide();
		$('.show_step_confirmation').css('display', 'block').show();
		
		$("#menu_product_positionner").css('display', 'none').hide();
		$("#search_rnat .input_search").attr('value','').show();
		$(document).bind('click', function () {
			$("#menu_product *").removeClass("menu_hover");
		});
		$(".menu_bar").hide();
	};
	
	self.bind_trash = function () {	
	
		if (self.options.is_api && jQuery.browser.msie && parseInt(jQuery.browser.version)==6) {
			window._goButtonClick = function(e) { 
				var oid = $(e).attr('id');
				oid = oid.split('_');
				self.delete_offer(oid[1], oid[2],$(e).position());
			};
		    $(".trash").attr("href","javascript:_goButtonClick(this);");
		} else {
			$('.trash').unbind().bind('click', function () {
				var oid = $(this).attr('id');
				oid = oid.split('_');
				self.delete_offer(oid[1], oid[2], $(this).position());
			});
		}

	};
	self.bind_carousel = function () {	
		$('#great_offers').carousel({
				total       : $("#great_offers>ul>li").length,
				scroll		: 3,
				btnNext		: ".next_great",
				btnPrev		: ".prev_great",
				mouseWheel	: true,
				circular	: true
		});
		
		
	};
	self.tooltip_bind = function () {	
		$('.selected_offer_lib').tooltip({ 
			bodyHandler: function() { 
            var tmp = $(this).parent().attr('id');
            return $('#offer_'+tmp).html();
			} 
		});
		
	};
	
	self.offer_selected_entity = function () {	
			$('.offer_selected_entity').hover(function() {
				$(this).addClass('offer_selected_entity_hover');
			}, function() {
				$(this).removeClass('offer_selected_entity_hover');
			});
	};

	self.accord_confirm = function () {	
			$('.accord_confirm').hover(function() {
				$(this).addClass('accord_confirm_hover');
			}, function() {
				$(this).removeClass('accord_confirm_hover');
			});
	};
	self.format_answer_per_line = function () {	
		$(".answer_per_line").each(function () {
			var per_line = $(this).val();
			var qid = $(this).attr('id');

			if (per_line > 1) {
                var q = $('#answers_' + qid +' >span') ;
                var nb_answer = q.length;
                var increment = Math.ceil(nb_answer/per_line);
                var table ='<table class="answer_per_line_' + per_line +'"><tbody>';

                for(var i=0; i<increment; i++) {
                    table +='<tr>';
                        for(var j=0; j<per_line; j++) {
                            var index_anwser = i+(j*increment);
                            if ($(q[index_anwser]).html()!== null) {
                                table +='<td class="multiple_per_line_' +per_line+'">' + $(q[index_anwser]).html() + '</td>';
                            }
                        }
                    table +='</tr>'
                }


                table +='</tbody></table>';
                $('#answers_' + qid).html(table).show();
			}
		});
	};
	self.check_height_label_img = function (id){
			var maxheight = 0;
			$("#question_image_"+id+ ",#divQuestion").show();
			$("#question_image_"+id +' label').each(function () {
				var h = $(this).height();
				maxheight = (maxheight > h)?maxheight:h;
	
				});

				if(maxheight !== 0){
					$(".labels_"+id).height(maxheight);
				}

	};
	self.bind_offer_view = function () {
		$(".selected_offer_lib").bind('click',function() {
			var id =$(this).attr('id').split('_');
			if (id[2] && id[3] > 0) {

				var url = self.default_protocole + self.options.site_front +'/offer_view.php?otcid='+ id[1]+'&noselect=t';
				if (!self.view_offer.closed && self.view_offer.location) {
					self.view_offer.location.href = url;
				}
				else { 
					self.view_offer=window.open(url,'view_offer','height=550,width=1000,scrollbars=yes,resizable=yes');
					if (!self.view_offer.opener) view_offer.opener = self;
				}
				if (window.focus) {self.view_offer.focus()}
				
			}
			
		});
	};	
	self.show_about_companeo = function () {
		var middl =$("#div_middleside");
		var h =  parseInt( $(middl).height());
		$(middl).hide();
		
		$("#about_compa").css({ 
                              height :h
							}).show();
	

	};
	self.new_init_vertical_website = function () {
		if(self.original_bind === false){
			return true;
		}
		self.original_bind = false;
		self.gettext_initial = $("#show_next").text();
		$("#show_next").text(self.gettext_continuer[self.options.default_lang_code]);
		var first = $('.companeo_forms',"#divQuestion ul li.slide1:first");
		var firstContainer = first.filter(':first').parent();
		var otherContainer = first.not(':first').parent();
		var answer = first.length;
		if(answer > 2){
			otherContainer.hide();
			$('img',firstContainer).hide();
			
			var new_answer = firstContainer.clone();
			
			new_answer.attr('id','other_answer');
			$('label',new_answer).text(self.gettext_other[self.options.default_lang_code]);
			$('input',new_answer).attr('name','input_other').attr('id','input_other');
			firstContainer.after(new_answer);
			$('#other_answer input').bind('click', self.new_short_to_vertical);
		
		}
		

		first.filter(':first').one('click', function() {
			self.new_short_to_vertical(false);
		    $(this).click(function() { self.show_next(true, false);
		    });
		});
		$("#button_controle").addClass('reduced');
		$("#leftslide_title").hide().next().hide();
		$('#middleside #divQuestion').css('float','none');
		$("#container_bdx_v2").css('height','260px');
		$("#form1 #process_slide").css({'height':'55px','z-index':'100'});
		$('#divQuestion').css('height','70px');
		$("#middleside .ui-widget-content").css('margin-bottom','1px');
		$("#form1 #corps_questionnaire, #middleside #divQuestion").css('min-height','100px');
		$("#middleside #tuteur").css('height','5px');
		$(".fac_explorer").css('height','103px');

	};
	
	self.new_short_to_vertical = function (submit) {	
		
		if(self.original_bind){
			if(submit){
				self.show_next(true, true,true);
			}
			else{
				 self.show_next(true, false);
			}
			return false;
		}
		self.original_bind = true;
		if(self.gettext_initial != ''){
			$("#show_next").text(self.gettext_initial);
		}
		
		$('#middleside #divQuestion').css('float','left');
		$("#leftslide_title").show().next().show(1000);
		$('#divQuestion').removeAttr("style");
		$("#middleside .ui-widget-content").css('margin-bottom','17px');
		$("#button_controle").removeClass('reduced');
		$("#form1 #process_slide").css({'height':'76px' ,'z-index':'100'});
		$("#form1 #corps_questionnaire, #middleside #divQuestion").css('min-height','325px');
		$("#middleside #tuteur").css('height','325px');
		$(".fac_explorer").css('height','309px');
		$("#container_bdx_v2").css({'height':'auto', 'min-height':'550px'});
		$('.companeo_forms',"#divQuestion ul li.slide1:first").parent().show();
		$('img',$("#divQuestion ul li.slide1").filter('.companeo_question')).show();
		$("#divQuestion ul li.slide1").filter('.companeo_question').show();
		$('#other_answer').remove();

		//self.qst_first_slide.show(1000);
	
	};
	self.init_vertical_website = function () {	
		$("#leftslide_title").next().hide(1000);
		$("#form1 #process_slide").css('height','40px');
		$("#middleside .ui-widget-content").css('margin-bottom','1px');
		$("#form1 #corps_questionnaire, #middleside #divQuestion").css('min-height','180px');
		$("#middleside #tuteur").css('height','180px');
		$(".fac_explorer").css('height','203px');
		self.qst_first_slide.not(self.qst_first_slide.first()).hide(1000);

	};
	
	self.short_to_vertical = function () {	
		$("#leftslide_title").next().show(1000);
		$("#middleside .ui-widget-content").css('margin-bottom','17px');
		$("#form1 #process_slide").css('height','76px');
		$("#form1 #corps_questionnaire, #middleside #divQuestion").css('min-height','325px');
		$("#middleside #tuteur").css('height','325px');
		$(".fac_explorer").css('height','309px');
		

		$('img',$("#divQuestion ul li.slide1").filter('.companeo_question')).show();
		
		$("#divQuestion ul li.slide1").filter('.companeo_question').show();
		self.qst_first_slide.show(1000);
	
	};
	return self;
};
