/*jslint regexp: true, browser: true, sloppy: true, white: true, plusplus: true, maxerr: 50, indent: 4 */
(function () {
	var U = LnkWcb.util,
	/* ********** DEBUT CONFIG ********** */
	 INTE_CFG = {
			lang: 'fr',
			canal: 'NEXITY0004',
			// global selectors
			trigger: '.LnkWcbForm-trigger', // the trigger is the element that activates the container
			container: '.LnkWcbForm-container', // the container that will be activated by the trigger
			closer: '.LnkWcbForm-closer', // the container closer
			formId: 'INTE_FORM_CFG_',
			// relative selectors (relative to form root in 'formId')
			userStatus: '.user-status',
			errorStatus: '.user-errors',
			calleeInput: 'input[name="callee"]'
		},
	/* ********** FIN CONFIG ********** */
		$ = LnkWcb.jQuery;
		
/**
	 * This helper function does the setup of the trigger button (aka "Le Bouton").
	 */
	function setupWcbTrigger() {
		var params = U.urlDecode(window.location.search.substring(1));
		$(INTE_CFG.trigger).click(function () {
			var elem = $(INTE_CFG.container),
				trigger = $(INTE_CFG.trigger),
				b = LnkWcb.inte1.montrerBouton;
			if (!b) {
				trigger.fadeOut();
			} else {
				elem.show();
				trigger.hide();
			}
		});
		
	}

	/**
	 * Setup the open/close animation for CNIL legal notice.
	 * This custom animation is required to allow this inline element to move accordingly.
	 * The jQuery UI/Effects/Slide would not suit this need.
	 * 
	 * @param F {jQuery} a jQuery search result holding the WCB form
	 */
	function setupCnilAnimation(F) {
		var opening = false, open = false, closing = false;
		F.find('.LnkWcbCnil').mouseenter(function (event) {
			var E = $(this).find('.depliant'),
				W = E.parent('.enveloppe'),
				distance;
			if (opening || open) {
				return;
			}
			opening = true;
			E.show();
			W.css('width', 'auto');
			distance = E.width();
			W.css('width', 0);
			E.css({ position: 'relative', left: -distance }).animate({ left: '+=' + distance }, {
				duration: 'slow', queue: false,
				step: function () {
					W.css('width', String(distance + parseInt(E.css('left'), 10))+'px');
				},
				complete: function () {
					E.css({ position: 'static', left: 'auto' }).show();
					W.css('width', 'auto');
					opening = false;
					open = true;
					E.dequeue();
				}
			});
		}).mouseleave(function (event) {
			var E = $(this).find('.depliant'),
				W = E.parent('.enveloppe'),
				distance;
			if (closing || !open) {
				return;
			}
			closing = true;
			E.show();
			W.css('width', 'auto');
			distance = E.width();
			E.css({ position: 'relative', left: 0 }).animate({ left: '-=' + distance }, {
				duration: 'slow', queue: false,
				step: function () {
					W.css('width', String(distance + parseInt(E.css('left'), 10))+'px');
				},
				complete: function () {
					E.css({ position: 'static', left: 'auto' }).hide();
					W.css('width', 'auto');
					closing = false;
					open = false;
					E.dequeue();
				}
			});
		});
	}

	/**
	 * This helper function creates one integration bouton.
	 * 
	 * @param I {Object} the integration namespace
	 * @param cfgBouton {Object} the bouton config
	 * @param cfgCalendar {Object} the date picker config
	 */
	function setupWcbForm(I, cfgBouton, cfgCalendar) {
		var F = $(cfgBouton.formSel),
			oldShowUserErrors, ackEnded;
		I.montrerBouton = false;
		/* ----- Bouton ----- */
		I.bouton = new LnkWcb.BoutonJquery(cfgBouton);
		I.bouton.showUserStatus = function (msg) { // permettre le HTML dans les messages des intermédiaires d'appel
			$(this.cfg.formSel).find(this.cfg.userStatusElemRelSel).html(msg);
		};
		F.find('input[name="callee"]').focus(function () {  // permettre de supprimer le contenus du champs telephone onFocus
                $(this).attr('defaultval', $(this).val());
				$(this).val('');
		});
        F.find('input[name="callee"]').blur(function () {  // permettre de remettre le contenus du champs telephone onBlur si inchangé
				if($(this).val() == ''){
                    $(this).val($(this).attr('defaultval'));
                }
		});
		I.bouton.onChannelState(function (etat, etatOuverture) { // Formulaire : différé en état non ouvert, et désactivé en inactif ou hors-limites
			if (!etat.estActif || !etat.peutRecevoirAppel ||etatOuverture ==="FERME" || etatOuverture ==="FERIE" || etatOuverture ==="SATURE") {
				
				F.find('.champ-wcb').hide(); 
			}else {
				F.find('.champ-wcb').show();
			}
		});
		oldShowUserErrors = I.bouton.showUserErrors;
		I.bouton.showUserErrors = function () {
			var that = this, ret;
			ret = oldShowUserErrors.apply(this, arguments);
			F.find(that.cfg.userErrorsElemRelSel).show();
			setTimeout(function () {
				F.find(that.cfg.userErrorsElemRelSel).has("ul").fadeOut();
			}, 5000);
			return ret;
		};
		
		I.bouton.onSendCall(function (args, attrs) {
			F.find(this.cfg.userStatusElemRelSel).addClass('busy');
			F.find('input').attr("disabled", true); // prevent duplicate submits
			F.find('.champ-wcb').hide();
		});
		ackEnded = function (status, params) {
			F.find(this.cfg.userStatusElemRelSel).removeClass('busy');
			F.find('input').attr("disabled", false); // re-enable form submits
			setTimeout(function () {
				$(INTE_CFG.userStatus).empty();
				F.find('.champ-wcb').show();
			}, 5000);
			
		};
		
		I.bouton.onError(ackEnded);
		I.bouton.onEnded(ackEnded);
		I.bouton.onFallback(ackEnded);
		I.bouton.onFallback(function (status, params) { // activer automatiquement le mode différé
			if (status.debordementCause === 'CAUSE_BLOQUE' || status.debordementCause === 'CAUSE_DEBORDE' || status.debordementCause === 'CAUSE_SATURE'|| status.debordementCause === 'CAUSE_FERME' || status.debordementCause === 'CAUSE_FERIE' || status.debordementCause === 'CAUSE_BLOQUE') {
				F.find('.champ-wcb').hide();
			}
			else {
				F.find('.champ-wcb').show();
			}
		});
		/* ----- Intégration ----- */
		I.afficherDiffere = function (afficher) {
			F.find('.panneau-date-differe').toggleClass('cacher', !afficher);
			if (afficher) {
				I.calendrier.refresh(); // vérif des horaires d'ouverture + démarrage du calendrier (destroy+init+show)
			}
			else {
				I.calendrier.hide();
			}
		};
		/* ----- Intégration Evènements Formulaire ----- */
		$('a[rel="external"]').attr('target', '_blank'); // corriger les liens ayant l'attribut rel="external"
		F.find('a.cnil').attr('href',
			// L'URL email ci-dessous est volontairement découpée en petits morceaux
			// pour emêcher que les spammeurs ne l'obtiennent trop facilement.
			[ 'mail','to',':cnil@','linkeo.','com?','subject=',encodeURIComponent('Accès données personnelles pour ' + cfgBouton.canal) ].join(''));
		setupCnilAnimation(F);
		F.find('.codeCanal').text(cfgBouton.canal);
		F.find('input[name="callee"]').keypress(function (event) { // filtrer les caractères saisis
			var c = String.fromCharCode(event.charCode);
			if (event.charCode && !/^[0-9+]$/.test(c)) { // interdire la saisie des caractères autres que '0' à '9' et '+'
				return false;
			}
		}).keyup(function (event) { // filtrer le contenu du champ pendant la saisie
			var E = $(this), val = E.val(), pos;
			val = val.replace(/[^0-9+]/g, ''); // éliminer les caractères autres que '0' à '9' et '+'
			val = (val.indexOf('+') === 0 ? '+' : '') + val.replace(/\+/g, ''); // supprimer les '+' qui ne sont pas au début
			val = val.replace(/^\+0+/, '+'); // éliminer les '0' qui suivent le '+' initial, s'il y en a un
			val = val.replace(/^000+/, '00'); // interdire plus de deux '0' initiaux
			if (val !== E.val()) {
				if (!E.parent().hasClass('warning')) {
					E.wrap('<span class="warning"/>'); // afficher un avertissement en cas de modification
				}
				E.val(val);
			}
		});
		F.submit(function () {
			var callee;
			callee = F.find(I.bouton.cfg.calleeInputRelSel).val();
			I.bouton.rappeler(callee);
			return false;
		});
		/* ----- Lancement ----- */
		I.bouton.estOuvert(); // vérif de l'état du canal + refresh cal (à faire après le setup du bouton et du calendrier)
	}

	/**
	 * This helper function creates integration namespaces,
	 * and collects config options in order to create all integration boutons.
	 * <p>
	 * Customize here to add new boutons.
	 */
	function setupAllWcbForms() {
		var I, cfgBouton, cfgCalendar,
			params = U.urlDecode(window.location.search.substring(1)),
			formId;
		try {
			/* ----- Inits ----- */
			LnkWcb.intl.setLang(INTE_CFG.lang);
			setupWcbTrigger();
			LnkWcb.intes = LnkWcb.intes || [];
			
			$(INTE_CFG.container).each(function(index) {
				formId = 'INTE_FORM_CFG_' + index;
				$(this).find('form').attr('id', formId);
				// Ajout John pour changement du code canal
                eachCanal = INTE_CFG.canal;
                if($(this).find('form').attr('code_canal') != '' && $(this).find('form').attr('code_canal') != undefined){
                    eachCanal = $(this).find('form').attr('code_canal');
                }
				/* ----- Lancement des enchainements d'initialisations ----- */
				//I = LnkWcb['inte'+index] = LnkWcb['inte'+index] || {}; 
				I = LnkWcb.intes[index] = LnkWcb.intes[index] || {};
				// création du namespace de l'intégration n°1
				cfgBouton = {
					canal: eachCanal,
					grabbedFormId: formId,				// enable the 'grabForm' Trait
					formSel: '#'+formId,				// '#LnkWcbForm' by default
					userStatusElemRelSel: INTE_CFG.userStatus,	// '.user-status' by default
					userErrorsElemRelSel: INTE_CFG.errorStatus,	// '.user-errors' by default
					calleeInputRelSel: INTE_CFG.calleeInput,	// 'input[name="callee"]' by default
					dateInputRelSel: INTE_CFG.dateInput			// '.LnkWcbDateDiff' by default
				};
			
				setupWcbForm(I, cfgBouton);
			});	
				
			
			
			
		}
		catch (exc) {
			LnkLog.log('LnkWcb.inte', exc);
		}
	}

	/**
	 * Create WCB integration when document is ready.
	 */
    //Ajout JOHN pour modif live du canal sur les contact_bar
    $(document).ready(function() {
        $('div.block_contact_large div[class="phone LnkWcbForm-container"], div.block_contact div[class="phone LnkWcbForm-container"]').each(function(index) {
            if($(this).closest('div.linkeo_canal').length == 1){
                new_code_canal = $(this).closest('div.linkeo_canal').attr('linkeo_code_canal');
                if(new_code_canal != undefined && new_code_canal != ''){
                    $(this).find('form').attr('code_canal', new_code_canal);
                }
            }
        });
        
    });
    //Fin Ajout JOHN
    
    //Issam  ajout block newsletter
    
                jQuery(document).ready(function(){
                $('#submit_newsletter').click(function(){

                    if(!check_email_valid($('#email_newsletter').val()))
                    {
                        $('#email_newsletter').css('border','1px solid red')     ; 
                        return false ; 
                    }else
                    {
                          $('#email_newsletter').css('border','none')     ;  
                    }


                    if(!check_form_code_postal($('#code_postal_newsletter').val()))
                    {
                        $('#code_postal_newsletter').css('border','1px solid red')     ; 
                        return false ; 
                    }else
                    {
                          $('#code_postal_newsletter').css('border','none')     ;  
                    }


                    var data ="email="+$('#email_newsletter').val()+"&code_postal="+$('#code_postal_newsletter').val() ; 
                    $.ajax({
                          type: 'POST',
                          url: 'ajax_newsletter.php',
                          data: data,
                          dataType: "json",
                          success : function(data) {
                                var xt_multc = "";
							
								xt_multc += "&x2="+$('#code_postal_newsletter').val()+"&x4=Inscription newsletter&x5=" + $('#email_newsletter').val() ;
								
								xt_med('F','13','FORM_cok_Inscription_Newsletter'+xt_multc);
                                $('#fieldset_newsletter').html('<span>Merci, votre inscription a été enregistrée.</span>') ; 
								
                          }

                         });
                         
                    return false ; 
                })
            }) ; 


            function check_email_valid(email)
            {   
                var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

               if(reg.test(email) == false) {

                  return false;
               }

               return true ; 

            }


            function check_form_code_postal (contenu){

                //window.alert("bob "+champ);
                // Initialisation des variables


                if (contenu.search(/^[0-9-.+ ]*$/) != -1 && contenu != "" && contenu.length == 5){
                    // Formulaire valide
                    return true ;
                } else {
                    return false ;
                }
            }
    
    
    //fin ajout block newsletter
	try {
		$(setupAllWcbForms); // execute when the document is ready
	} catch (ignoredExc) {
		// LnkLog.log('integration', ignoredExc);
	}
}());

