// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/indexOf
if (!Array.prototype.indexOf) {
	Array.prototype.indexOf = function(elt /*, from*/) {
		var len = this.length >>> 0;
		var from = Number(arguments[1]) || 0;
		from = (from < 0) ? Math.ceil(from) : Math.floor(from);

		if (from < 0) {
			from += len;
		}

		for (;from < len;from++) {
			if (from in this && this[from] === elt) {
				return from;
			}
		}
		return -1;
	};
}

if (!Array.prototype.in_array) {
	Array.prototype.in_array = function(val) {
		if (!val) {
			return;
		}
		for (var i= 0, ei = this.length;i < ei;i++) {
			if (this[i].toUpperCase() == val.toUpperCase()) {
				return i;
			}
		}
		return -1;
	};
}

(function($) {
	$.fn.parentHasClass = function(cls, end) {
		if (typeof $(this) != 'object') {
			return (false);
		}
		var ptr = $(this);
		end = end ? end.toUpperCase() : 'BODY';
		while (ptr.get(0).nodeName != end) {
			ptr = ptr.parent();
		}
		if (ptr.hasClass(cls)) {
			return ptr;
		}
		return (false);
	}
	
	$.fn.parentHasId = function(id, end) {
		if (typeof $(this) != 'object') {
			return (false);
		}
		var ptr = $(this);
		end = end ? end.toUpperCase() : 'BODY';
		while (ptr.get(0).nodeName != end && ptr.get(0).nodeName != 'BODY') {
			ptr = ptr.parent();
		}
		if (ptr.attr('id') == id) {
			return ptr;
		}
		return (false);
	}
	
	$.fn.resetInput = function() {
		$(this).find('input:text').purge();
		$(this).find('input:checkbox').attr('checked', '');
		$(this).find('input:radio').attr('checked', '');
		$(this).find('input:select').attr('selected', '');
		$(this).find('li.valid').removeClass('valid');

		return $(this);	
	}
	
	$.fn.purge = function() {
		$(this).val('');
		$(this).removeAttr('disabled');
		return $(this);
	}
	
	$.fn.to_array = function() {
		var arrData = new Array($(this).length);
		var it = 0;

		$(this).each(function() {
			arrData[it] = $(this).text();
			it++;
		});
		return arrData;
	}
	
	$.fn.concrete = function(action, _val, target) {
		var ptr = $(target);
		
		$(this).bind(action, function() {
			if ($(this).val() != '') {
				ptr.val(value);
				ptr.attr('disabled', 'disabled');
			} else {
				ptr.removeAttr('disabled');
			}
			return $(this);
		});
		return $(this);
	};
	
	$.fn.turnOn = function() {
		$(this).removeClass('off').addClass('on');
		return $(this);
	};

	$.fn.turnOff = function() {
		$(this).removeClass('on').addClass('off');
		return $(this);
	};

})(jQuery)

var setMasse = function() {
	var big_daddy = '';
	var target = '';
	var embBox = ['#ct_det_envoi_postExport', '#ct_det_envoi_colissimoEmballageIntl', '#ct_det_envoi_colissimoEmballage', '#ct_det_envoi_chronopostPaE', '#ct_det_envoi_chronopostPaEIntl'];
	var last_id = '';
	var returnForm = false;
	
	function set_masse() {
		//var returnForm = true;
		big_daddy.find(':radio').click(function() {
			var elmt = $(this);
			var options = elmt.parent().find('select:first');
			var typologieVal = $('#ct_typologie').find(':radio[name=type]:checked').val();
			
			if( typologieVal != 'colis' && typologieVal != 'courrier') {
			//if (!returnForm)
				options.find('option:first').attr('selected', 'selected');
			}
			
			big_daddy.find(':radio').not(this).parents('.valid').removeClass('valid');

			var new_id = '#'+ elmt.attr('id');

			if (embBox.in_array(new_id) != -1) {
				if (new_id != last_id) {
					target.purge();
				}

				last_id = new_id;

				if( typologieVal != 'colis' && typologieVal != 'courrier') {
					// if (!returnForm)
					options.find('option:first').attr('selected', 'selected');
				}

				options.change(function() {
					var elmt = $(this);
					var isEmb = embBox.in_array(elmt.attr('id').substr(0, -5));
					elmt.data(last_id+ '_change', true);
					if ($(new_id).attr('checked') == true) {
						if (elmt.find('option:selected').attr('rel') != '') {
							target.val(elmt.find('option:selected').attr('rel'));
							target.attr('disabled', 'disabled')
						} else if (!returnForm) {
							//if( $('#ct_typologie').find(':radio[name=type]:checked').val() != 'colis' && $('#ct_typologie').find(':radio[name=type]:checked').val() != 'courrier'){
								target.purge();
							//}
						}
					}
				}).change();
			} else {
				//if( $('#ct_typologie').find(':radio[name=type]:checked').val() != 'colis' && $('#ct_typologie').find(':radio[name=type]:checked').val() != 'courrier'){
					options.change(function() {return (false);});
					//target.purge();
					$('#ct_det_poids').removeAttr('disabled');
				//}
			}
		});		
	}
	
	function set_daddy(daddy) {big_daddy = $(daddy);}
	
	function set_target(_target) {target = $(_target);}
	
	function set_returnForm(_returnForm) {returnForm = _returnForm;}
	
	function init(daddy, _target, _returnForm) {
		set_returnForm(_returnForm)
		set_daddy(daddy);
		set_target(_target);
		//var selected = $('#nature_postExport').val() ? $('#nature_postExport').val() : '';
		/*$.post('/laposteforms/export_emballage', {Expediteur: ($('body').hasClass('entreprise') ? 'entreprise' : 'particulier'), Selected: selected}, function(data){
			$('#ct_det_envoi_postExportListe').append(data);
			if (selected)
				$('#ct_det_envoi_postExportListe').change();
		});*/
	}
	return {init: init, set_masse: set_masse, set_daddy: set_daddy, set_returnForm: set_returnForm};
}();

/*
var gereSelectIe = function()
{
	var original_size = 0;
	function getMaxSize(ptr)
	{
		var mSize = 0;
		ptr.each(function(){
			mSize = $(this).width() > mSize ? $(this).width() : mSize;
		});
		return mSize;
	}
	
	function init(cls)
	{
		$(cls).find('select').focus(function(){
			original_size = $(this).width();
			$(this).width(getMaxSize($(this).find('option')));
		});
		$(cls).find('select').blur(function(){
			$(this).width(original_size);
		});
	}
	return {init: init, getMaxSize: getMaxSize};
}();
*/

var handleDetails = function() {
	var natureChecked = false;
	var typologie = $('#ct_typologie');
	var destination = $('#ct_destination');
	var details = $('#ct_details');
	var exception = '';
	
	function setException(e) {exception = e;}
	
	function getException() {return exception;}
	
	function setNatureStep(step) {natureChecked = step;}
	
	function getNatureStep() {return natureChecked;}
	
	function handle() {
		var typologie = $('#ct_typologie');
		var destination = $('#ct_destination');
		var details = $('#ct_details');

		var isColis = typologie.find(':radio:checked').is('.colis');
		var isInternational = destination.find(':radio:checked').is('.international');
		details.turnOn();
		natureChecked = true;
		if (isColis && isInternational) {
			details.find('.courrier').turnOff();
			details.find('.national').turnOff();
			details.find('.colis').filter('.international').show();
			
			// cacher les options de recommandation qui ne servent pas aux colis internationaux
			$('#ct_det_reco_export3j, #ct_det_reco_exportSuivi, #ct_det_reco_securexport, #ct_det_reco_r1, #ct_det_reco_r2, #ct_det_reco_ar_int').parents('li').hide();
			$('#ct_det_recoInt').hide();
			if ($('#ct_typologie').find(':radio[name=type]:checked').val() == 'colis' && $('#ct_destination').find(':radio:checked').is('.international') == true && $('#ct_det_envoi_colissimoIntl:checked') == '[object Object]'  && $('#ct_det_envoi_colissimoEmballageIntl:checked') == '[object Object]' && $('#ct_det_envoi_chronopostIntl:checked') == '[object Object]' && $('#ct_det_envoi_chronopostPaEIntl:checked') == '[object Object]') {
				$('#ct_det_reco').hide();
				$('#ct_det_coliInt').hide();
			}			
		} else if (isColis && !isInternational) { 
			details.find('.courrier').turnOff();
			details.find('.international').hide();
			details.find('.colis').filter('.national').show();
			$('#ct_det_reco').turnOff().css('display', '');
		} else if (!isColis && isInternational) {
			details.find('.colis').hide();
			details.find('.national').turnOff();
			details.find('.courrier').filter('.international').each(function(){
				if (exception != $(this).attr('id')) {
					$(this).show();
				}
			});
			$('#ct_det_recoInt').hide();
		} else {
			// (!isColis && !isInternational) 
			details.find('.colis').turnOff();
			details.find('.international').hide();
			details.find('.courrier').filter('.national').turnOn();
			$('#ct_det_reco').turnOff();
		}
		$('#ct_det_poids_wrapper').turnOn();
	}
	
	function init() {
		var destination = $('#ct_destination');

		if (destination.find(':radio:checked').hasClass('.national')) {
			handle();
		} else {
			if (natureChecked == true) {
				handle();
			}
		}
		natureChecked = true;
	}

	return {init: init, handle: handle, setNatureStep: setNatureStep, getNatureStep: getNatureStep, setException: setException, getException: getException};
}();

var pageType = function() { 
	function init() {
		$('form').append('<input type="hidden" name="expediteur" value="'+ ($('body').hasClass('entreprise') ? 'entreprise' : 'particulier') +'" />');
	}
	return {init: init};
}();


$(function() {
	var isIe = $.browser.msie;
	var typologie, origine, destination, destinationFrance, destinationDOM, destinationDOMListe, destinationMonde, destinationMondeListe, details, nature, recommandation, poids, actions;
	var etape; // position dans les étapes du formulaire (courrier/colis, origine/destination...) pour gestion bouton retour.
	var defaultValCountry = '';
	var exceptionIdApplied = new Array();
	var exceptionLevel;
	var det_envoi = $('#ct_det_envoi');
	var natureChecked = false;
	var postExportList = $('#ct_det_envoi_postExportListe');
	var savePostExportList = '';
	var rebuild_reco;	

	var returnForm = $('#returnForm')[0] ? true : false;
	returnForm = true;

	var resultForm = $("input[name='isResult']")[0] ? true : false;

	var e3j = $('#ct_det_reco_export3j_wrap');
	var exportSuivi = $('#ct_det_reco_exportSuivi_wrap');
	var securExportWrapper = $('#ct_det_reco_securexport_container');
	
	var allowedPays = ['57', '23', '59', '67', '69', '76', '103', '133', '164', '180', '77', '192', '43']; //Allemagne, Belgique, Danemark, Espagne, Finlande, Grande-Bretagne, Irlande, Luxembourg, Pays-Bas, Portugal, Royaume-uni, Suède, Suisse. Pour sécurExport et PostExportSecur
	var pays = $('select#destination_pays');
	var typologie = $('#ct_typologie');
	var destination = $('#ct_destination');
	var details = $('#ct_details');

	handleDetails.setNatureStep(false);		
	setMasse.init('#ct_nature_envoie', '#ct_det_poids', returnForm);
	setMasse.set_masse();
	init();

	$("#actions2").css("display", "none");

	if (!returnForm) {
		resetReco();
	}

	etapeTypologie();
	etapeDestination();
	etapeDetails();
	etapeNature();
	if (!resultForm) {
		boutonRetour();
		nouvelleRecherche();
	}
	//adjustheight($('#resumerRecherche .radio_back'), 2);
	export3J();
	funcExportSuivi();
	securexport();
	gestionPostExportList();
	
	gestionOptionsColisIntl();
	
	infosPopIn();
	//pageType.init();
	returnForm = false;
	setMasse.set_returnForm(false);
//	if (isIe)
//		gereSelectIe.init('.select_container');
	/**** Functions ****/
	function reset() {
		$('input:text').purge();
		$('input:checkbox').attr('checked', '');
		$('input:radio').attr('checked', '');
		$('input:select').attr('selected', '');
	}
	
	function init() {
		typologie = $('#ct_typologie');
		destination = $('#ct_destination').hide(); // A faire en CSS av-ec .jsActif #...
		details = $('#ct_details').turnOff(); // A faire en CSS avec .jsActif #...
		actions = $('#actions')
		if (!resultForm) {
			actions.hide(); // A faire en CSS avec .jsActif #...
		}
		destinationDOMListe = $('#ct_dest_ff_liste_dom');
		destinationMondeListe = $('#ct_dest_ff_liste_pays');
		nature = $('#ct_nature_envoie');
		$('#destination_pays').find('option[value=""]').text('');
		$('#country_choice').focus(function() {
			if (defaultValCountry == '') {
				defaultValCountry = $(this).val();
				$(this).val('')
			}
		});
		exceptionIdApplied =  new Array();
		exceptionLevel = -1;
		
		$('.destination_pays_colis').find('option[value=""]').text('');
		
		$('#calcTarif').submit(function() {return calculer_tarif_verifForm()});
		handleDetails.setNatureStep(false);
	}
	
	function resetReco() {
		$('#ct_bloc_recommandation_options, #ct_det_reco_oui_choix').find('input:radio').click(function(e) {
			if ($(this).parentHasClass('valid', 'li')) {
				e.stopImmediatePropagation();
				$(this).removeAttr('checked');
				setParentElements($(this), 'li', 'valid', 'ul', 1);
				if (typologie.find(':radio:checked').is('.colis') == false) {
					$('#ct_det_reco_ar_int, #ct_det_reco_ar').attr('disabled', 'disabled');
					$('#ct_det_reco_ar_int, #ct_det_reco_ar').removeAttr('checked');
					setParentElements(($(this).parentHasId('ct_det_reco_oui_choix', 'ul') ? $('#ct_det_reco_ar') : $('#ct_det_reco_ar_int')), 'li', 'valid', 'ul', 1);
				}
			} else {
				$('#ct_det_reco_ar_int, #ct_det_reco_ar').removeAttr('disabled');
			}
		});
	}
	
	function resizeAndFill(actualArray, size) {
		var i,j=1;
		var newArray = new Array(size);
		newArray[0]=actualArray[0];
		for(i=1;i<actualArray.length;i++){
			if(actualArray[i] != "" && actualArray[i] != null){
				newArray[j]=actualArray[i];
				j++;
			}
		}
		return newArray;
	}

	function completion(_blocToComplete, _toArray) {
		var arrData = new Array(_toArray.length);
		var arrVal = new Array(_toArray.length);
		var it = 0;
		var _val = '';
		var texte_pays = '';
		_toArray.each(function() {
			arrData[it] = $(this).text();
			arrVal[it] = $(this).val();
			it++;
		});

		if(it != _toArray.length) {
			arrData = resizeAndFill(arrData, it);
			arrVal = resizeAndFill(arrVal, it);
		}

		_blocToComplete.autocomplete({
			minChars : 1,
			delay : 400,
			matchContains : false,
		  	url : null,
		  	data: arrData
		});

		$('#country_submit').filter(function(){return !$(this).data('country_submit_click')}).click(function() {
			var elmt = $(this);		
			elmt.data('country_submit_click', true);

			if($('#country_choice').val()=="Enter the destination country of your postal item") {
				texte_pays = $('#ct_dest_ff_liste_pays select option:selected').text();
			} else {
				texte_pays = _blocToComplete.val();
			}

			if (arrData.in_array(texte_pays) != -1) {
				_toArray.parent().val(arrVal[arrData.in_array(texte_pays)]);
				elmt.parent().turnOff().parent().find('p.result').addClass('valid').turnOn().find('.radio_back').html(texte_pays);
				_toArray.parent().change();
				handleDetails.init();
				
				/* AJOUT POUR LA LETTRE VERTE */
				var destinationPaysId = $('.destination_pays').find('option:selected').attr('value');
				if ( (destinationPaysId && destinationPaysId != 2 && destinationPaysId != 74) || typo_envoi=="colis") {
					$("#ct_det_envoi_lverte_inter").parents(".radio").hide();
				} else {
					$("#ct_det_envoi_lverte_inter").parents(".radio").show();
				}
				/* FIN AJOUT POUR LA LETTRE VERTE */

/*				if (allowedPays.indexOf(pays.val()) == -1) postExportList.find('#ct_det_envoi_postExportListe_P05 ,#ct_det_envoi_postExportListe_P06, #ct_det_envoi_postExportListe_E05 ,#ct_det_envoi_postExportListe_E06').turnOff();
				else postExportList.find('#ct_det_envoi_postExportListe_P05 ,#ct_det_envoi_postExportListe_P06, #ct_det_envoi_postExportListe_E05 ,#ct_det_envoi_postExportListe_E06').turnOn();
  */                              
                                if (allowedPays.in_array(pays.val()) != -1 ) {
                                    $("#ct_det_envoi_postExportListe option[value='P05'], #ct_det_envoi_postExportListe option[value='P06'], #ct_det_envoi_postExportListe option[value='E05'], #ct_det_envoi_postExportListe option[value='E06']").show();
                                } else {
                                    $("#ct_det_envoi_postExportListe option[value='P05'], #ct_det_envoi_postExportListe option[value='P06'], #ct_det_envoi_postExportListe option[value='E05'], #ct_det_envoi_postExportListe option[value='E06']").hide();
                                }
			} else {
				alert ("Nous n'avons pas trouvé le nom du pays saisi. Merci de vérifier l'orthographe du pays de destination.");
				$('#country_choice').focus();
			}
		});
	}
	
	function setParentElements(ptr, elm, cls, end, unset) {
		if (typeof ptr != 'object' || !elm || !ptr || !ptr.get(0)) {
			return ptr;
		}
		elm = elm.toUpperCase();
		end = end ? end.toUpperCase() : 'BODY';
		while (ptr.get(0).nodeName != end) {
			if (ptr.get(0).nodeName == elm) {
				if (!unset) {
					ptr.addClass(cls);
				} else {
					ptr.removeClass(cls);
				}
			}
			ptr = ptr.parent();
		}
		return ptr;
	}

	function selectionOption(ptr, rad, toSwitch) {
		if (!rad) {
			ptr.addClass('off');
		}
		if (toSwitch) {
			toSwitch.parent().find('label:eq(0)').turnOff();
			toSwitch.turnOn();
		}
		ptr = setParentElements(ptr, 'li', 'valid', 'ul');
		ptr.find('li:not(.valid, li ul#ct_det_reco_oui_choix li)').turnOff();
	}

	function etapeTypologie() {
		typologie.find(':radio').click(function() {
			//$(".warningsColisTarifs").show();
			$("#actions2").css("display", "block");
			selectionOption($(this));
			if($('#ct_typo_courrier').attr('class')=="radio off") {
				typo_envoi="colis";
				completion($('#country_choice'), $('.destination_pays_colis option'));
			} else if($('#ct_typo_colis').attr('class')=="radio off") {
				typo_envoi="courrier";
				completion($('#country_choice'), $('.destination_pays option'));
			}
			actions.show();
			destination.show().find(':checked').attr('checked','checked');
			if (!returnForm) {
			//	if( $('#ct_typologie').find(':radio[name=type]:checked').val() != 'colis' && $('#ct_typologie').find(':radio[name=type]:checked').val() != 'courrier'){
					destination.find(':selected').attr('selected', '');
			//	}
			}
			destinationDOMListe.hide();
			destinationMondeListe.turnOff();
			details.turnOff();
			if ($(this).val() == "courrier" /*&& !$('#ct_dest_ff_monde:selected')*/)
			{
				$('#ct_det_reco_ar_int, #ct_det_reco_ar').attr('disabled', 'disabled');
			} else {
				$('#ct_det_reco_ar_int, #ct_det_reco_ar').removeAttr('disabled');
			}
		}).filter(':checked').click();
	}

	function etapeDestination() {
		destinationFrance = $('#ct_dest_ff_france');
		destinationDOM = $('#ct_dest_ff_dom');
		destinationMonde = $('#ct_dest_ff_monde');
		destinationDOMListe.hide();
		destinationMondeListe.turnOff();
		
		destinationFrance.click(function() {
			selectionOption($(this), null, $(this).parent().find('label:eq(1)'));
			$('#ct_from_france').addClass('off');
			handleDetails.init();
			destinationDOMListe.hide();
			destinationMondeListe.turnOff();
			if (typologie.find(':radio:checked').is('.colis')) {
				$('#ct_det_envoi_colissimoEmballage_choix, #ct_det_envoi_chronopostPaE_choix').find('option.national').turnOn();
			}
			//	$('#ct_det_envoi_colissimoEmballageIntl_choix2').hide();
			//	$('#ct_det_envoi_chronopostPaEIntl_choix2').hide();
				
		
				$("#ct_det_envoi_colissimoEmballage_choix option[value='1B']").show();
				$("#ct_det_envoi_colissimoEmballage_choix option[value='L']").show();
				$("#ct_det_envoi_colissimoEmballage_choix option[value='XL']").show();	
				
				$("#ct_det_envoi_colissimoEmballage_choix option[value='2B']").show();	
				$("#ct_det_envoi_colissimoEmballage_choix option[value='3B']").show();	
				$("#ct_det_envoi_colissimoEmballage_choix option[value='CD']").show();	
				$("#ct_det_envoi_colissimoEmballage_choix option[value='M']").show();	
				$("#ct_det_envoi_colissimoEmballage_choix option[value='P']").show();	
				$("#ct_det_envoi_colissimoEmballage_choix option[value='SPL']").show();	
		
				$("#ct_det_envoi_chronopostPaE_choix option[value='B6']").show();	
				$("#ct_det_envoi_chronopostPaE_choix option[value='E05']").show();	
				$("#ct_det_envoi_chronopostPaE_choix option[value='P2']").show();	

				$("#ct_det_envoi_chronopostPaE_choix option[value='B3']").show();	
				$("#ct_det_envoi_chronopostPaE_choix option[value='E1']").show();	
				$("#ct_det_envoi_chronopostPaE_choix option[value='P1']").show();
			}).filter(':checked').click();

		destinationDOM.click(function() {
			selectionOption($(this), null, $(this).parent().find('label:eq(1)'));
			$('#ct_from_france').turnOff();
			handleDetails.init();
			details.turnOff();
			destinationDOMListe.show();
			destinationMondeListe.turnOff();
			if (typologie.find(':radio:checked').is('.colis')) {
				$('#ct_det_envoi_colissimoEmballage_choix, #ct_det_envoi_chronopostPaE_choix').find('option.national').turnOff();
			}

			//	$('#ct_det_envoi_colissimoEmballageIntl_choix2').turnOn();
			//	$('#ct_det_envoi_colissimoEmballage_choix').turnOff();
				
			//	$('#ct_det_envoi_chronopostPaE_choix').turnOff();
			//	$('#ct_det_envoi_chronopostPaEIntl_choix2').turnOn();
								

				$("#ct_det_envoi_colissimoEmballage_choix option[value='1B']").show();
				$("#ct_det_envoi_colissimoEmballage_choix option[value='L']").show();
				$("#ct_det_envoi_colissimoEmballage_choix option[value='XL']").show();	
				
				$("#ct_det_envoi_colissimoEmballage_choix option[value='2B']").hide();	
				$("#ct_det_envoi_colissimoEmballage_choix option[value='3B']").hide();	
				$("#ct_det_envoi_colissimoEmballage_choix option[value='CD']").hide();	
				$("#ct_det_envoi_colissimoEmballage_choix option[value='M']").hide();	
				$("#ct_det_envoi_colissimoEmballage_choix option[value='P']").hide();	
				$("#ct_det_envoi_colissimoEmballage_choix option[value='SPL']").hide();	
		
				$("#ct_det_envoi_chronopostPaE_choix option[value='B6']").show();	
				$("#ct_det_envoi_chronopostPaE_choix option[value='E05']").show();	
				$("#ct_det_envoi_chronopostPaE_choix option[value='P2']").show();	

				$("#ct_det_envoi_chronopostPaE_choix option[value='B3']").hide();	
				$("#ct_det_envoi_chronopostPaE_choix option[value='E1']").hide();	
				$("#ct_det_envoi_chronopostPaE_choix option[value='P1']").hide();										
								
		//	$('#ct_dest_ff_liste_dom select[name=dom_tom] option:first').attr('selected', 'selected');
		}).filter(':checked').click();
		destinationMonde.click(function() {
			selectionOption($(this), null, $(this).parent().find('label:eq(1)'));
			$('#ct_from_france').turnOff();
			handleDetails.init();
			details.turnOff();
			destinationDOMListe.hide();
			destinationMondeListe.turnOn();

			if (returnForm && $('#country_choice').val() != '') {
				$('#country_submit').click();
			}

				$('#ct_det_envoi_colissimoEmballage_choix2').hide();
				$('#ct_det_envoi_colissimoEmballage_choix').hide();
				
		}).filter(':checked').click();
		
		destinationDOMListe.find('select').add(destinationMondeListe.find('select')).change(function() {
			if ($(":selected:not([value=''])", this).length) {
				preHandledetails();
			} else if (!$('#ct_dest_ff_dom:checked') && !$('#ct_dest_ff_monde:checked')) {
				details.turnOff();
			}
		}).find('option').filter(':selected').parent().change();
	}

		function preHandledetails() {
			if (destination.find(':radio:checked').hasClass('.national')) {
				handledetails();
			} else {
				if (natureChecked == true) {
					handledetails();
				}
			}
			natureChecked = true;

			if ($('#ct_typologie').find(':radio[name=type]:checked').val() == 'colis' && $('#ct_destination').find(':radio:checked').is('.international') == true && $('#ct_det_envoi_colissimoIntl:checked') == '[object Object]'  && $('#ct_det_envoi_colissimoEmballageIntl:checked') == '[object Object]' && $('#ct_det_envoi_chronopostIntl:checked') == '[object Object]' && $('#ct_det_envoi_chronopostPaEIntl:checked') == '[object Object]'){
				$('#ct_det_reco').hide();
				$('#ct_det_coliInt').hide();
			}
		}

		function handledetails() {
			var isColis = typologie.find(':radio:checked').is('.colis');
			var isInternational = destination.find(':radio:checked').is('.international');
		//	if ($('#ct_typologie').find(':radio[name=type]:checked').val() == 'colis' && $('#ct_destination').find(':radio:checked').is('.international') == true && $('#ct_det_envoi_colissimoIntl:checked') == ''  && $('#ct_det_envoi_colissimoEmballageIntl:checked') == '' && $('#ct_det_envoi_chronopostIntl:checked') == '' && $('#ct_det_envoi_chronopostPaEIntl:checked') == ''){
			//	$('#ct_det_reco').hide();
			//	$('#ct_det_coliInt').hide();
			
		//	}
			details.turnOn();
			natureChecked = true;
			if (isColis && isInternational) {
				details.find('.courrier').turnOff();
				details.find('.national').turnOff();
				details.find('.colis').filter('.international').show();
				
				// cacher les options de recommandation qui ne servent pas aux colis internationaux
				$('#ct_det_reco_export3j, #ct_det_reco_exportSuivi, #ct_det_reco_securexport, #ct_det_reco_r1, #ct_det_reco_r2, #ct_det_reco_ar_int').parents('li').hide();
				$('#ct_det_recoInt').hide();
			} else if (isColis && !isInternational) {
				details.find('.courrier').turnOff();
				details.find('.international').hide();
				details.find('.colis').filter('.national').show();
				$('#ct_det_reco').turnOff().css('display', '');
			} else if (!isColis && isInternational) {
				details.find('.colis').hide();
				details.find('.national').turnOff();
				details.find('.courrier').filter('.international').each(function(){
					if (exceptionIdApplied[0] != $(this).attr('id')) {
						$(this).show();
					}
				});
				$('#ct_det_recoInt').hide();
			} else { 
				// (!isColis && !isInternational)
				details.find('.colis').turnOff();
				details.find('.international').hide();
				details.find('.courrier').filter('.national').turnOn();
				$('#ct_det_reco').turnOff();
			}
			$('#ct_det_poids_wrapper').turnOn();
			//	$('#ct_det_reco').hide();
			//	$('#ct_det_coliInt').hide();
		}
	
	function etapeDetails() {
		var detailsRecommande = $('#ct_det_reco, #ct_det_recoInt, #ct_det_reco_oui,#ct_det_reco_non');
		var choixRecommande = $('#ct_det_reco_oui_choix').hide();

		if ($('#ct_det_reco_r1').attr('checked') ) {
			$('#ct_det_reco_r1').parents('li:first').addClass('valid');
			$('#ct_det_reco_ar_int, #ct_det_reco_ar').removeAttr('disabled');
			$('#ct_det_poids').removeAttr('disabled');
		}
		if ($('#ct_det_reco_r2').attr('checked') ) {
			$('#ct_det_reco_r2').parents('li:first').addClass('valid');
			$('#ct_det_reco_ar_int, #ct_det_reco_ar').removeAttr('disabled');
			$('#ct_det_poids').removeAttr('disabled');
		}
		if ($('#ct_det_envoi_lverte_nat').attr('checked') ) {
			$('#ct_det_poids').removeAttr('disabled');
		}
		if ($('#ct_det_envoi_lverte_inter').attr('checked') ) {
			$('#ct_det_poids').removeAttr('disabled');
		}
		if ($('#ct_det_reco_securexport').attr('checked') ) {
			$('#ct_det_poids').removeAttr('disabled');
		}
		if ($('#ct_det_envoi_colissimoIntl').attr('checked') ) {
			$('#ct_det_poids').removeAttr('disabled');
		}
		if ($('#ct_det_envoi_chronopostIntl').attr('checked') ) {
			$('#ct_det_poids').removeAttr('disabled');
		}
		if ($('#ct_det_envoi_colissimo').attr('checked') ) {
			$('#ct_det_poids').removeAttr('disabled');
		}
		if ($('#ct_det_envoi_chronopost').attr('checked') ) {
			$('#ct_det_poids').removeAttr('disabled');
		}
		if ($('#ct_det_reco_ar_int').attr('checked') ) {
			$('#ct_det_reco_ar_int').parents('li:first').addClass('valid');
			$('#ct_det_reco_ar_int').removeAttr('disabled');
			$('#ct_det_poids').removeAttr('disabled');
		}
		if ($('#ct_det_reco_ar').attr('checked') ) {
			$('#ct_det_reco_ar').parents('li:first').addClass('valid');
			$('#ct_det_reco_ar').removeAttr('disabled');
			$('#ct_det_poids').removeAttr('disabled');
		}
		if ($('#ct_det_reco_oui').attr('checked') ) {
			$('#ct_det_reco_oui').parents('li:first').addClass('valid');
			$('#ct_det_reco_oui_choix li:eq(3), #ct_det_reco_oui_choix li:eq(4)').addClass('off');
			detailsRecommande.find(':radio[name=recoON]').parents('.valid:first').removeClass('valid');
			$('#ct_det_reco_oui').parents('li:first').addClass('valid');
			if($('#ct_det_reco_oui').is('[value=oui]')) {
				choixRecommande.show();
			} else {
				choixRecommande.hide();
			}
			if ($('#ct_det_reco_oui_r1').attr('checked') ) {
				$('#ct_det_reco_oui_r1').parents('li:first').addClass('valid');
				$('#ct_det_reco_ar_int, #ct_det_reco_ar').removeAttr('disabled');
			}
			if ($('#ct_det_reco_oui_r2').attr('checked') ) {
				$('#ct_det_reco_oui_r2').parents('li:first').addClass('valid');
				$('#ct_det_reco_ar_int, #ct_det_reco_ar').removeAttr('disabled');
			}
			if ($('#ct_det_reco_oui_r3').attr('checked') ) {
				$('#ct_det_reco_oui_r3').parents('li:first').addClass('valid');
				$('#ct_det_reco_ar_int, #ct_det_reco_ar').removeAttr('disabled');
			}
			if ($('#ct_det_reco_oui_r4').attr('checked') ) {
				$('#ct_det_reco_oui_r4').parents('li:first').addClass('valid');
			}
			if ($('#ct_det_reco_oui_r5').attr('checked') ) {
				$('#ct_det_reco_oui_r5').parents('li:first').addClass('valid');
			}
			if ($('#ct_det_reco_ar').attr('checked') ) {
				$('#ct_det_reco_ar').parents('li:first').addClass('valid');
			}
		} else if ($('#ct_det_reco_non').attr('checked')) {
			$('#ct_det_reco_non').parents('li:first').addClass('valid');
		}

		detailsRecommande.find(':radio[name=recoON]').click(function() {
			if ($('#ct_det_envoi_lp').attr('checked') && ($('#ct_dest_ff_france').attr('checked') || $('#ct_dest_ff_dom').attr('checked'))) {
				$('#ct_det_reco_oui_choix li:eq(3), #ct_det_reco_oui_choix li:eq(4)').addClass('off');
				if (!returnForm) {
				//	if( $('#ct_typologie').find(':radio[name=type]:checked').val() != 'colis' && $('#ct_typologie').find(':radio[name=type]:checked').val() != 'courrier'){
						$('#ct_det_reco_oui_r1, #ct_det_reco_oui_r2, #ct_det_reco_oui_r3, #ct_det_reco_oui_r4, #ct_det_reco_oui_r5, #ct_det_reco_ar').each(function() {
							setParentElements($(this), 'li', 'valid', 'ul', 1);
							$(this).removeAttr('checked');
						});
				//	}
				}
			}
			detailsRecommande.find(':radio[name=recoON]').parents('.valid:first').removeClass('valid');
			$(this).parents('li:first').addClass('valid');

			if($(this).is('[value=oui]')) {
				choixRecommande.show();
			} else {
				choixRecommande.hide();
			}
		});

		detailsRecommande.find(':checkbox').click(function() {
			$('#ct_det_poids_wrapper').turnOn();
			setParentElements($(this), 'li', 'valid', 'ul', ($(this).attr('checked') ? 0 : 1));
		});
		detailsRecommande.find(':radio[name=reco]').click(function() {
		$('#ct_det_reco_ar_int, #ct_det_reco_ar').removeAttr('disabled');
			$('#ct_det_poids_wrapper').turnOn();
			detailsRecommande.find(':radio[name=reco]').parent('.radio_back').parent('.bloc_link').parent('.valid').removeClass('valid');
			setParentElements($(this), 'li', 'valid', 'ul');
		});
	};

	function etapeNature() {
		/* Ces 2 tableaux sont utilisés pour le système de règles d'affichage des blocs en fonction des options choisies */
		/* Le 1er tableau contient les id des input qui doivent cacher un bloc dont l'id est contenu dans le 2eme tableau */
		/* Ils sont liés par leur clé */
		/* le second tableau peut contenir un id, un tableau d'id ou faire appel à une fonction -- sans paramêtres */
		var exceptionClick = [	'ct_det_envoi_eco',					'ct_det_envoi_docEco',				'ct_det_envoi_marchEco',
								'ct_det_envoi_docPrio', 			'ct_det_envoi_colissimoEmballage',	'ct_det_envoi_chronopost',
								'ct_det_envoi_chronopostPaEIntl', 	'ct_det_envoi_chronopostPaE',		'ct_det_envoi_postExport',
								'ct_det_envoi_colissimoEmballageIntl', 'ct_det_envoi_colissimoIntl',
								'ct_det_envoi_lverte_nat',	    'ct_det_envoi_lverte_inter'];

		var exceptionTarget = [	['ct_det_reco', 'ct_det_coliInt'],	['ct_det_recoInt', 'ct_det_coliInt'],	['ct_det_recoInt', 'ct_det_coliInt'],
								['ct_det_reco_securexport_container', 'ct_det_coliInt'],	['ct_det_reco', 'ct_det_coliInt'],	['ct_det_reco', 'ct_det_coliInt'],
								['ct_det_recoInt', 'ct_det_reco', 'ct_det_coliInt'],	['ct_det_reco', 'ct_det_coliInt'],	['ct_det_recoInt', 'ct_det_coliInt'],
								['ct_det_recoInt', 'ct_det_coliInt'], 	['ct_det_reco', 'ct_det_coliInt'],
								'ct_det_reco', 'ct_det_recoInt'];
		var level = 0;

		nature.find('input').click(function() {
			var typologieVal = $('#ct_typologie').find(':radio[name=type]:checked').val(); 
			if (!returnForm) {
				if( typologieVal != 'colis' && typologieVal != 'courrier') {
					$('#ct_bloc_recommandation_options, #ct_bloc_recommandation').find('li').each(function() {
						var elmt = $(this);
						elmt.removeClass('on')
							.removeClass('off')
							.removeClass('valid');
						
						elmt.css('display', '').find('input:checked, input:selected').attr({checked: '', selected: ''});
					});
				}
			}
		
			if (destination.find(':radio:checked').is('.international')) {
				$('#ct_det_coliInt').hide();
				$('#ct_det_recoInt').show();
			} else {
				$('#ct_det_reco').turnOn();
			}

			dim = exceptionClick.in_array($(this).attr('id'));
			if ($('#'+exceptionIdApplied[level]).hasClass('off')) {
				$('#'+exceptionIdApplied[level]).turnOn();
			}
			if ($('#'+exceptionIdApplied[level]).css('display') != 'show') {
				$('#'+exceptionIdApplied[level]).show();
			}
			if (dim != -1) {
				exceptionIdApplied[level] = exceptionTarget[dim];
				treateElement(exceptionTarget[dim]);
			} else {
				exceptionIdApplied[level] = -1;
			}

			handleDetails.setException(exceptionIdApplied[level]);

			if (!returnForm) {
				if( typologieVal != 'colis' && typologieVal != 'courrier'){
					if ($(this).parentHasClass('valid', 'li') == false) {
						$('#ct_bloc_recommandation, #ct_bloc_recommandation_options').resetInput();
					}
					nature.find('.valid').removeClass('valid');
				}
			}

			setParentElements($(this), 'li', 'valid', 'ul');

			function treateElement(input) {
				if (typeof input == 'function') {
					input();
				} else if (typeof input == 'object' && input.length) {
					for (var i=0;i < input.length;i++) treateElement(input[i]);
				} else {
					$('#'+input).hide();
				}
			};
		}).filter(':checked').click();
	}
	
	function nouvelleRecherche() {
		$('#new_search').click(function(e){
			/*
			$("#actions2").css("display", "none");
			e.preventDefault();
			returnForm = false;
			setMasse.set_returnForm(false);
			exceptionIdApplied[0] = '';
			typologie.add(destination).add(details).find(':radio:checked, option:selected').attr('checked', '').attr('selected', '');
			details.find(':text').val('');
			actions = $('#actions').hide();
			$('.off:not(.result)').removeClass('off');
			$('.on').turnOff();
			$('.valid').removeClass('valid');
			$("input[type='radio']:checked").attr('checked', false);
			$('#destination_pays').val('');
			$('#country_choice').val(defaultValCountry);
			defaultValCountry = '';
			for (;exceptionLevel >= 0;exceptionLevel--)
				$('#'+exceptionIdApplied[exceptionLevel]).show();
			$('#ct_det_reco_oui_choix').hide();
			$('#ct_det_poids').purge();
			$('#ct_det_recoInt').hide();
			$('#ct_bloc_recommandation, #ct_bloc_recommandation_options').find('li').show();
			$('#ct_nature_envoie li').css('display', '');
			init();
			*/
			window.location=window.location;
		});
	}

	function boutonRetour() {
		$('#retour').click(function(e) {
			e.preventDefault();
			returnForm = false;
			setMasse.set_returnForm(false);
			exceptionIdApplied[0] = false;
			$('#ct_det_poids').purge()
			$('#ct_det_poids_wrapper').turnOff();
			$('#ct_det_recoInt').hide();
			handleDetails.setNatureStep(false);		
			$('#ct_bloc_recommandation, #ct_bloc_recommandation_options').find('li').show();
			$('#country_choice').autocomplete({data:[""]});
			destination.find(':radio[name=destination]').removeAttr('checked');
			if(details.is(':visible')) {
				details.turnOff();
				details.find('.valid').removeClass('valid');
				details.find('li').css('display', '');
				$('#ct_det_reco .off').removeClass('off');
				destination.find('.off:not(.result, #ct_dest_ff_liste_pays)').removeClass('off');
				destination.find('.on').turnOff();
				destination.find('.valid').removeClass('valid');
				$('.destination_pays').val('');
				$('.destination_pays_colis').val('');
				$('#ct_det_reco_oui_choix').hide();
				$('#ct_dest_ff_liste_dom').hide();
				$('#ct_det_reco').turnOff().css('display', '');
			} else if (destination.is(':visible')) {
				/*
				$('#ct_destination .off:not(.result, #ct_dest_ff_liste_pays), #ct_typologie .off').removeClass('off');
				destination.find('.on').turnOff();
				details.find('.on').turnOff();
				details.find('li').css('display', '');
				$('.valid').removeClass('valid');
				$('#ct_dest_ff_liste_dom').hide();
				destination.hide();
				actions.hide();
				$('#destination_pays').val('');
				*/
				window.location=window.location;
			}
		})
	};

	function export3J() {
		e3j.hide();
		var natureEnvoi = $('#ct_nature_envoie :radio[name=nature]');
		var e3jCheckbox = $('#ct_det_reco_export3j');

		natureEnvoi.click(function() {
			var elmt = $(this);
			if (allowedPays.in_array(pays.val()) != -1 ) {
				$("#ct_det_envoi_postExportListe option[value='P05']").show();
				$("#ct_det_envoi_postExportListe option[value='P06']").show();
			} else {
				$("#ct_det_envoi_postExportListe option[value='P05']").hide();
				$("#ct_det_envoi_postExportListe option[value='P06']").hide();		
			}		

			if ((elmt.is('#ct_det_envoi_docPrio') || elmt.is('#ct_det_envoi_marchPrio') || (elmt.is('#ct_det_envoi_postExport') )&& allowedPays.in_array(pays.val()) != -1 && ($('#ct_det_envoi_postExportListe').val() != "P05" &&  $('#ct_det_envoi_postExportListe').val() != "P06" ) )){
				e3j.show();

				if (allowedPays.in_array(pays.val()) != -1 ) {
					$("#ct_det_envoi_postExportListe option[value='P05']").show();
					$("#ct_det_envoi_postExportListe option[value='P06']").show();
				} else {
					$("#ct_det_envoi_postExportListe option[value='P05']").hide();
					$("#ct_det_envoi_postExportListe option[value='P06']").hide();
				}

				if (allowedPays.in_array(pays.val()) == -1 && (elmt.is('#ct_det_envoi_docPrio') || elmt.is('#ct_det_envoi_marchPrio'))) {
					$('#ct_det_reco_export3j_wrap').hide();
				}
			} else {
				e3j.hide();
			}
		});

		e3jCheckbox.filter(function(){return !$(this).data('exported')}).click(function() {
			var elmt = $(this);
			elmt.data('exported', true);
			if (elmt.is(':checked')) {
				elmt.parents('li').siblings().turnOff().css('display', '');
				$('#ct_det_reco_r1, #ct_det_reco_r2, #ct_det_reco_ar_int').each(function() {
					if ($(this).parentHasClass('valid', 'li')) {
						if (!returnForm) {
							//if( $('#ct_typologie').find(':radio[name=type]:checked').val() != 'colis' && $('#ct_typologie').find(':radio[name=type]:checked').val() != 'courrier'){
								$(this).removeAttr('checked');
							//}
						}
					}
					if ($(this).attr('id') == 'ct_det_reco_ar_int' /*&& !$('#ct_dest_ff_monde:selected') && !typologie.find(':radio').hasClass('courrier') à réutiliser */) {
						$(this).attr('disabled','disabled').attr('selected', '');
					}
				});
			} else {
				nature.find('input:checked').each(function() {
					if ($(this).attr('id') == 'ct_det_envoi_postExport') {
						elmt.parents('li').siblings().turnOn();
						postExportList.change();
					} else {
						$(this).click();			
					}
				});
			}
		});
	}

	function funcExportSuivi() {		
		exportSuivi.hide();
		var natureEnvoi = $('#ct_nature_envoie :radio[name=nature]');
		var exportSuiviCheckbox = $('#ct_det_reco_exportSuivi');

		natureEnvoi.click(function() {
			var elmt = $(this);
			
			if (allowedPays.in_array(pays.val()) != -1) {
				$("#ct_det_envoi_postExportListe option[value='P05']").show();
				$("#ct_det_envoi_postExportListe option[value='P06']").show();
			} else {
				$("#ct_det_envoi_postExportListe option[value='P05']").hide();
				$("#ct_det_envoi_postExportListe option[value='P06']").hide();		
			}		

			if ((elmt.is('#ct_det_envoi_docPrio') || elmt.is('#ct_det_envoi_marchPrio') || (elmt.is('#ct_det_envoi_postExport') )&& /*allowedPays.in_array(pays.val()) != -1 && */($('#ct_det_envoi_postExportListe').val() != "P05" &&  $('#ct_det_envoi_postExportListe').val() != "P06" ) )) {
				exportSuivi.show();

				if (allowedPays.in_array(pays.val()) != -1) {
					$("#ct_det_envoi_postExportListe option[value='P05']").show();
					$("#ct_det_envoi_postExportListe option[value='P06']").show();
				} else {
					$("#ct_det_envoi_postExportListe option[value='P05']").hide();
					$("#ct_det_envoi_postExportListe option[value='P06']").hide();		
				}
				
//				if (allowedPays.in_array(pays.val()) == -1 && (elmt.is('#ct_det_envoi_docPrio') || elmt.is('#ct_det_envoi_marchPrio'))){
//					$('#ct_det_reco_exportSuivi_wrap').hide();				
//				}
			} else {
				exportSuivi.hide();
			}
		});

		exportSuiviCheckbox.filter(function(){return !$(this).data('exported')}).click(function() {
			var elmt = $(this);
			elmt.data('exported', true);
			if (elmt.is(':checked')) {
				elmt.parents('li').siblings().turnOff().css('display', '');
				$('#ct_det_reco_r1, #ct_det_reco_r2, #ct_det_reco_ar_int').each(function() {
					if ($(this).parentHasClass('valid', 'li')) {
						if (!returnForm) {
							//if( $('#ct_typologie').find(':radio[name=type]:checked').val() != 'colis' && $('#ct_typologie').find(':radio[name=type]:checked').val() != 'courrier'){
								$(this).removeAttr('checked');
							//}
						}
					}
					if ($(this).attr('id') == 'ct_det_reco_ar_int' /*&& !$('#ct_dest_ff_monde:selected') && !typologie.find(':radio').hasClass('courrier') à réutiliser */) {
						$(this).attr('disabled','disabled').attr('selected', '');
					}
				});
			} else {
				nature.find('input:checked').each(function(){
					if ($(this).attr('id') == 'ct_det_envoi_postExport') {
						elmt.parents('li').siblings().turnOn();
						postExportList.change();
					} else {
						$(this).click();
					}
				});
			}
		});
	}

	function securexport() {
		$('#ct_det_envoi_docPrio, #ct_det_envoi_docEco, #ct_det_envoi_marchEco').click(function() {securExportWrapper.hide();}).filter(':checked').click();
		$('#ct_det_envoi_marchPrio, #ct_det_envoi_postExport').click(function() {securExportWrapper.show();}).filter(':checked').click();
		
		$('#ct_det_reco_securexport').filter(function(){return !$(this).data('secured')}).click(function() {
			var elmt = $(this);
			elmt.data('secured', true);
			if (elmt.is(':checked')) {
				elmt.parents('li').siblings().turnOff().css('display', '');
				$('#ct_det_reco_r1, #ct_det_reco_r2, #ct_det_reco_ar_int').each(function() {
					if ($(this).parentHasClass('valid', 'li')) {
						$(this).removeAttr('checked');
						setParentElements($(this), 'li', 'valid', 'ul', 1);
					}
					if ($(this).attr('id') == 'ct_det_reco_ar_int') {
						$(this).attr('disabled','disabled');
					}
				});
			} else {
				nature.find('input:checked').each(function() {
					if ($(this).attr('id') == 'ct_det_envoi_postExport') {
						elmt.parents('li').siblings().turnOn();
						postExportList.change();
					} else {
						$(this).click();
					}
				});
			}
		}).filter(':checked').click();
	}
	
	function gestionPostExportList() {
		var e3js = ['ct_det_envoi_postExportListe_P01', 'ct_det_envoi_postExportListe_P02', 'ct_det_envoi_postExportListe_P03', 'ct_det_envoi_postExportListe_P04', 'ct_det_envoi_postExportListe_P05', 'ct_det_envoi_postExportListe_P06', 'ct_det_envoi_postExportListe_P08', 'ct_det_envoi_postExportListe_P09', 'ct_det_envoi_postExportListe_P10', 'ct_det_envoi_postExportListe_E01', 'ct_det_envoi_postExportListe_E02', 'ct_det_envoi_postExportListe_E03', 'ct_det_envoi_postExportListe_E04', 'ct_det_envoi_postExportListe_E05', 'ct_det_envoi_postExportListe_E06', 'ct_det_envoi_postExportListe_P07', 'ct_det_envoi_postExportListe_E07', 'ct_det_envoi_postExportListe_E08', 'ct_det_envoi_postExportListe_E09', 'ct_det_envoi_postExportListe_E10'];
		var exportSuivis = ['ct_det_envoi_postExportListe_P01', 'ct_det_envoi_postExportListe_P02', 'ct_det_envoi_postExportListe_P03', 'ct_det_envoi_postExportListe_P04', 'ct_det_envoi_postExportListe_P05', 'ct_det_envoi_postExportListe_P06', 'ct_det_envoi_postExportListe_P08', 'ct_det_envoi_postExportListe_P09', 'ct_det_envoi_postExportListe_P10', 'ct_det_envoi_postExportListe_E01', 'ct_det_envoi_postExportListe_E02', 'ct_det_envoi_postExportListe_E03', 'ct_det_envoi_postExportListe_E04', 'ct_det_envoi_postExportListe_E05', 'ct_det_envoi_postExportListe_E06', 'ct_det_envoi_postExportListe_P07', 'ct_det_envoi_postExportListe_E07', 'ct_det_envoi_postExportListe_E08', 'ct_det_envoi_postExportListe_E09', 'ct_det_envoi_postExportListe_E10'];
		var secuExports = ['ct_det_envoi_postExportListe_P07', 'ct_det_envoi_postExportListe_P08', 'ct_det_envoi_postExportListe_P09', 'ct_det_envoi_postExportListe_P10', 'ct_det_envoi_postExportListe_E07', 'ct_det_envoi_postExportListe_E08', 'ct_det_envoi_postExportListe_E09', 'ct_det_envoi_postExportListe_E10' ];

		postExportList.change(function() {
			if ($('#ct_det_envoi_postExport').attr('checked') == true) {
				handlePostExportListChange($(this));
				if( ($('#ct_det_envoi_postExportListe').val() == "P07" ||  $('#ct_det_envoi_postExportListe').val() == "P08"  ||  $('#ct_det_envoi_postExportListe').val() == "P09"  ||  $('#ct_det_envoi_postExportListe').val() == "P10") ) {
					$('#ct_det_reco_securexport_container').show();
				}
				$('#ct_det_reco_exportSuivi_wrap').show();

				if (allowedPays.in_array(pays.val()) != -1 ) {
					$('#ct_det_reco_export3j_wrap').show();
					$("#ct_det_envoi_postExportListe option[value='P05']").show();
					$("#ct_det_envoi_postExportListe option[value='P06']").show();
				} else {
					$("#ct_det_envoi_postExportListe option[value='P05']").hide();
					$("#ct_det_envoi_postExportListe option[value='P06']").hide();
				}
				if ( ($('#ct_det_envoi_postExportListe').val() == "P05" ||  $('#ct_det_envoi_postExportListe').val() == "P06" ) ) {
					$('#ct_det_recoInt').hide()
				}
			}
		}).blur(function() {
			if ($('#ct_det_envoi_postExport').attr('checked') == true) {
				handlePostExportListChange($(this));
				if( ($('#ct_det_envoi_postExportListe').val() == "P07" || $('#ct_det_envoi_postExportListe').val() == "P08"  || $('#ct_det_envoi_postExportListe').val() == "P09" ||  $('#ct_det_envoi_postExportListe').val() == "P10") ) {
					$('#ct_det_reco_securexport_container').show();
				}
				$('#ct_det_reco_exportSuivi_wrap').show();
				if (allowedPays.in_array(pays.val()) != -1) {
					$('#ct_det_reco_export3j_wrap').show();
					$("#ct_det_envoi_postExportListe option[value='P05']").show();
					$("#ct_det_envoi_postExportListe option[value='P06']").show();
				} else {
					$("#ct_det_envoi_postExportListe option[value='P05']").hide();
					$("#ct_det_envoi_postExportListe option[value='P06']").hide();
				}
				if ( ($('#ct_det_envoi_postExportListe').val() == "P05" || $('#ct_det_envoi_postExportListe').val() == "P06" ) ) {
					$('#ct_det_recoInt').hide();
				}					
			}
		}).find('option').filter(':selected').parent().change();

		function handlePostExportListChange(elmt) { 
			securExportWrapper.hide();
			var ids = elmt.find('option:selected').attr('id');
			e3j.hide();
			exportSuivi.hide();
			if (ids == 'ct_det_envoi_postExportListe_P05' || ids == 'ct_det_envoi_postExportListe_P06' || ids == 'ct_det_envoi_postExportListe_E05' || ids == 'ct_det_envoi_postExportListe_E06') {
				$('#ct_det_recoInt').hide();
			} else {
				if ($('#ct_det_recoInt').css('display') == 'none') {
					$('#ct_det_recoInt').show();
				}
				if (e3js.indexOf(ids) != -1 && allowedPays.in_array(pays.val()) != -1) {
					e3j.show();
				}
				if (exportSuivis.indexOf(ids) != -1 /*&& allowedPays.in_array(pays.val()) != -1*/) {
					exportSuivi.show();
				}
				if (secuExports.indexOf(ids) != -1) {
					securExportWrapper.show();
				}
			}
			//	$('#ct_det_reco_export3j_wrap').show();
		}
	}
	
	function gestionOptionsColisIntl() {
		var ColissimoIntl = $('#ct_det_envoi_colissimoIntl');
		var autresTypes = $('#ct_det_envoi_colissimoEmballageIntl, #ct_det_envoi_chronopostIntl, #ct_det_envoi_chronopostPaEIntl');
		
		var ar = $('#ct_det_reco_ar_int');
		var autresOptions = $('#ct_det_reco_export3j, #ct_det_reco_exportSuivi, #ct_det_reco_securexport, #ct_det_reco_r1, #ct_det_reco_r2');
		var blocReco = $('#ct_det_recoInt');
		
		ColissimoIntl.click(function() {
			blocReco.show();
			if ($('#ct_typologie').find(':radio[name=type]:checked').val() == 'colis' && $('#ct_destination').find(':radio:checked').is('.international') == true && $('#ct_det_envoi_colissimoIntl:checked') != '') {
				blocReco.hide();
				$('#ct_det_coliInt').show();
			} else {
				$('#ct_det_coliInt').hide();
			}
			ar.parents('li').show();
			autresOptions.parents('li').hide();
		});
		
		autresTypes.click(function() {
			blocReco.hide();
		});
	};
	
	function infosPopIn() {
		var popIns = $('.infosPopIn').hide();
		var links = $('.linkPopIn').click(function (e) {
			e.preventDefault();
			var elmt = $(this);
			$(elmt.attr('href')).show();
		});
		var off = $('.linkPopInOff').click(function (e) { 
			e.preventDefault();
			var elmt = $(this);
			elmt.parent().hide();
		});
	}
	
	function calculer_tarif_verifForm() {	
		var natureEnvoi = $('#ct_typologie').find(':radio[name=type]:checked').val();
		var poids = parseInt($('#ct_det_poids').val());
		var destination_pays = $('#destination_pays').val();
		var contenu_intl = $('#ct_nature_envoie :radio:checked').val();
		var securExport = $('#ct_det_reco_securexport:checked').val();
		var origineDomTom = $('#destination_ff_dom_tom').val();
		var destinationPaysId = $('#destination_pays').find('option:selected').attr('value');
	
		var traduction_fr={
			postage:	'Votre envoi dépasse les 3.000 grammes, contactez votre interlocuteur commercial',
			postageIntl:'Votre envoi dépasse les 2.000 grammes, contactez votre interlocuteur commercial',
			colis:		'Votre envoi dépasse les 30.000 grammes, contactez votre interlocuteur commercial',
			ecopacket:	'Le tarif Ecopli ne s\'applique pas au delà de 250gr',
			economie:	'Le tarif économique est un tarif unique de 0 à 100 grammes. Nous vous conseillons de choisir le tarif prioritaire pour vos envois de 0 à 50 g pour bénéficier d\'un tarif plus avantageux et d\'un délai de distribution plus rapide. Cela vous évitera de payer le tarif d\'une tranche de poids plus élevée.',
			overseas:	'Veuillez sélectionner une Zone d\'Outre-Mer dans la liste',
			country:	'Veuillez sélectionner un pays dans la liste',
			emballage:	'Veuillez sélectionner un emballage dans la liste',
			securexportPoids:	'Le poids pour l\'option secur\'Export est limité à 2.000 grammes.',
			weight:		'Veuillez saisir un poids en grammes'
		}
		var traduction_en={
			postage: 'Your postage is more than 3,000 grams, please contact your commercial advisor',
			colis: 'Your package weighs more than 30 kg, please contact your local branch.',
			ecopacket: 'The Ecopacket rate only applies to post up to 250g.',
			economie: 'The economy rate only applies to mail between 0 and 100g. We recommend the priority rate for mail between 0 and 50g so you can take advantage of a better price and shorter delivery time. This way, you avoid paying for the higher weight band.',
			overseas:'Please select an Overseas Territory in the list',
			country:'Please select a country in the list',
			emballage:'Please choose your packaging from the list',
			weight:'Please fill a weight in grams'
		}
		var traduction_es={
			postage: 'Tu envio supera los 3.000 g. Ponte en contacto con tu asesor comercial.',
			colis: 'Tu envio excede los 30 kg; contacta con tu agente comercial.',
			ecopacket: 'La tarifa Ecopacket solo se aplica a los envios con un peso de hasta 250 g.',
			economie: 'La tarifa economica solo se aplica a los envios comprendidos entre 0 y 100 g. Para envios de 0 a 50 g recomendamos la tarifa prioritaria, que te ofrece un precio mejor y un plazo de entrega mas corto. Así evitaras pagar por el tramo de peso superior.',
			overseas: 'Selecciona un Territorio de ultramar',
			country: 'Selecciona un pais',
			emballage: 'Selecciona un tipo de paquete',
			weight: 'Rellene un peso en gramos'
		}

		if ($('input[name=lang]').val() == 'es') {
			var traduction = traduction_es;
		} else if ($('input[name=lang]').val() == 'en') {
			var traduction = traduction_en;
		} else {
			var traduction = traduction_fr;
		}
		
		// Si pas emballage et un poid de format 'incorrect'
		if (!$('#ct_det_envoi_chronopostPaE').is(":checked") && !$('#ct_det_envoi_colissimoEmballage').is(":checked") && !$('#ct_det_envoi_chronopostPaEIntl').is(":checked") && !$('#ct_det_envoi_colissimoEmballageIntl').is(':checked') && (poids=="" || poids=="0" || (!IsNumeric(poids)) )) {
			alert((traduction.weight));
			return (false);
		}

		//si emabalage mais pas d emballage selectionné
		if ($('#ct_det_envoi_colissimoEmballage').is(":checked") || $('#ct_det_envoi_colissimoEmballageIntl').is(':checked')) {
			if ($('.emballage:enabled:visible option:selected').val() =="") {
				alert((traduction.emballage));
				return (false);
			}
		}

		//poid max colis en France
		if (poids > 30000 && natureEnvoi!="courrier" && !destination_pays) {
			alert((traduction.colis));
			return (false);
		}
		
		// poid max courrier en France
		if (poids > 3000 && natureEnvoi=="courrier" && !destination_pays) {
			alert((traduction.postage));
			return (false);
		}
		
		//poid max courrier international from outremer sauf lettre verte
		if (poids > 2000 && natureEnvoi=="courrier" && origineDomTom && destination.find(':radio:checked').is('.international') && !$('#ct_det_envoi_lverte_inter').is(':checked')) {
			alert((traduction.postageIntl));
			return (false);
		}

		//poid max lettre verte internationale from outremer
		if (poids > 3000 && natureEnvoi=="courrier" && origineDomTom && destination.find(':radio:checked').is('.international') && $('#ct_det_envoi_lverte_inter').is(':checked')) {
			alert(traduction.postage);
			return (false);
		}

		//poid max ecopli 250gr en France
		if (poids > 250 && $('#ct_det_envoi_eco').is(':checked') && !destination_pays) {
			alert((traduction.ecopacket));
			return (false);
		}
		
		// On averti l'utilisateur si l'envoi est a destination de l'etranger, en economique et pese moins de 51 grammes.
		if (poids < 51 && $('#ct_det_envoi_docEco').is(':checked')) {
			alert ((traduction.economie));
			$('#ct_det_envoi_docPrio').click();
			return (false);
		}
		
		/*Si l'internaute sélectionne les critères suivants :
		-	Pays de destination : l'un des dix-huit pays suivants : Bénin, Burkina Faso, Cameroun, Centrafrique, Comores, Congo (République du), Côte d'Ivoire, Djibouti, Gabon, Guinée (République de), Madagascar, Mali, Mauritanie, Niger, Sénégal, Tchad, Togo, Tunisie ;
		-	Contenu : "Document" ou "Marchandise",
		Une tranche de poids 2 001-3 000 g est ajoutée à la liste des tranches de poids.
		La tranche de poids 2 001-3 000 g est réservée à ces 18 pays africains : elle n'est affichée à l'écran et n'est utilisée pour les calculs tarifaires que si le client a sélectionné l'un des 18 pays ci-dessus.
		*/
/*		if (destination_pays && natureEnvoi=="courrier") {
			if ((destination_pays == 28 || destination_pays == 24 || destination_pays == 47 || destination_pays == 41 || destination_pays == 118 || destination_pays == 40 || destination_pays == 44 || destination_pays == 58 || destination_pays == 75 || destination_pays == 85 || destination_pays == 139 || destination_pays == 143 || destination_pays == 149 || destination_pays == 160 || destination_pays == 198 || destination_pays == 206 || destination_pays == 207 || destination_pays == 212 ) && (contenu_intl == 'docPrio' || contenu_intl == 'marchPrio' || contenu_intl == 'docEco' || contenu_intl == 'marchEco' )) {
				if (poids > 3000) {
					alert(traduction.postage);
					return (false);
				}
			} else if (poids > 2000) {
				alert(traduction.postageIntl);
				return (false);
			}
		}
*/

		if (destination_pays && natureEnvoi=="courrier" && !origineDomTom) {
			if (contenu_intl == "lettreVerte_inter") {
				if( (destinationPaysId==2 || destinationPaysId == 74) && (poids > 3000) ) {
					alert(traduction.postage);
					return (false);
				}
			} else {
				if ((destination_pays == 28 || destination_pays == 24 || destination_pays == 47 || destination_pays == 41 || destination_pays == 118 || destination_pays == 40 || destination_pays == 44 || destination_pays == 58 || destination_pays == 75 || destination_pays == 85 || destination_pays == 139 || destination_pays == 143 || destination_pays == 149 || destination_pays == 160 || destination_pays == 198 || destination_pays == 206 || destination_pays == 207 || destination_pays == 212 ) && (contenu_intl == 'docPrio' || contenu_intl == 'marchPrio' || contenu_intl == 'docEco' || contenu_intl == 'marchEco' )) {
					if (poids > 3000) {
						alert(traduction.postage);
						return (false);
					}
				} else if (poids > 2000) {
					alert(traduction.postageIntl);
					return (false);
				}
			}
		}

		/* Si la tranche de poids sélectionnée est supérieure à 2000g, l'option Secur'Export n'est plus disponible. */
		if (poids > 2000 && securExport) {
			alert(traduction.securexportPoids);
			return (false);
		}
		
		if (!$('#ct_det_poids').is(':disabled') && !poids) {
			alert(traduction.weight);
			return (false);
		}
		
		// réactiver le poids s'il a été désactivé et rempli automatiquement.
		$('#ct_det_poids').removeAttr('disabled');
		
		return true;
		
		function IsNumeric(sText) {
			var ValidChars = "0123456789";
			var IsNumber=true;
			var Char;
			for (i = 0; i < sText.length && IsNumber == true; i++) {
				Char = sText.charAt(i);
				if (ValidChars.indexOf(Char) == -1) IsNumber = false;
			}
			return IsNumber;
		}
	}
});
