function init_components_payment(input){
	input.each(function(i,input){
		input = $(input);
		if(!input.is(":visible")) return;
		var action = input.attr('data-action');
		if(!action) {
			console.log('PAYMENT COMPONENT: Need "data-action" to get process payment');
			return;
		}

		$.action({
			action: 'stripe_init_component',
			process: action
		}, function(r){
			if(!r.content) return;
			//On utilise un wrapper pour gérer les overflows "out of the box"
			input.addClass('row card-container');
			var content = $(r.content);
			input.append(content);
			init_creditcard_component();
		});
	});
}

//CHARGEMENT DE LA PAGE
function init_plugin_stripe(){
	switch($.urlParam('page')){
		default:

		break;
	}
}

//Init page settings
function init_setting_global_stripe(parameter){
	switch(parameter.section){
		case 'global.stripe':
			$.each($('code'), function(idx, val){
				hljs.highlightBlock($(val).get(0));
			});
		break;
	}
}

function stripe_setting_save(){
	$.action({ 
		action : 'stripe_setting_save', 
		fields :  $('#stripe-setting-form').toJson() 
	},function(){
		$.message('success','Configuration enregistrée');
	});
}

function stripe_card_execute(options,complete){
	var activeBtn = $('#shop-stripe-button > span.button-active'),
		loadingBtn = $('#shop-stripe-button > span.button-loading');

	var o = $.extend({
		card: '4242424242424242',
		cvv: '123',
		month:8,
		year: 2019,
		owner: ''
	},options);
	try{
		Stripe.setPublishableKey(o.key);
		Stripe.card.createToken({
			number: o.card,
			cvc: o.cvv,
			exp_month:o.month,
			exp_year: o.year,
			name: o.owner
		}, function (status, response) {
			activeBtn.removeClass('hidden');
			loadingBtn.addClass('hidden');
			complete(response);
		});
	} catch(e){
	 	activeBtn.removeClass('hidden');
		loadingBtn.addClass('hidden');
		complete({error:e});
	}
}

function stripe_card(options,complete){
	var stripeLib = 'https://js.stripe.com/v2/';
	if($('script[src="'+stripeLib+'"]',document).length == 0){
		var s = document.createElement( 'script' );
		s.type = 'text/javascript';
		s.setAttribute( 'src', stripeLib );
		s.onload = function(){ stripe_card_execute(options,complete)};
		document.body.appendChild(s);
	}else{
		stripe_card_execute(options,complete);
	}
}


//Fonction pour lancer l'initialisation
//du paiement par Stripe (récup des données)
function stripe_process_payment(public_key, processAction=null){
	try{
		if(!processAction) throw 'Erreur sur l\'action pour procéder au paiement';
		var activeBtn = $('#shop-stripe-button > span.button-active'),
			loadingBtn = $('#shop-stripe-button .button-loading');
		loadingBtn.removeClass('hidden');
		activeBtn.addClass('hidden');

		var cardNumber = $('#stripe-card-number'),
			cardCvv = $('#stripe-card-cvv'),
			cardExpire = $('#stripe-card-expire'),
			cardOwner = $('#stripe-card-owner');

		var expParts = cardExpire.val().split(' / ');
		var month = expParts[0],
			year = expParts[1];

		if(cardNumber.val() == '') throw 'Numéro de carte invalide';
		if(cardCvv.val() == '')  throw 'Numéro CVV invalide';
		if(month == '')  throw 'Mois d\'expiration invalide';
		if(year == '')  throw 'Année d\'expiration invalide';

		stripe_card({
			key : public_key,
	        card: cardNumber.val().replace(/ /g,''),
	        cvv: cardCvv.val(),
	        month: month,
	        year: year,
	        owner: cardOwner.val()
	    },function(response){
		    if(response.error) return $.message('error',response.error.code+' : '+response.error.message);

		    $.action({
		    	action : processAction,
		    	token : response.id
		    },function(r){
		    	reset_inputs('.card-container');
				loadingBtn.addClass('hidden');
		    	activeBtn.removeClass('hidden');
		    	$.message('success','Paiement effectué');
		    });
		});
	} catch(e){
		$.message('error',e);
		loadingBtn.addClass('hidden');
		activeBtn.removeClass('hidden');
	}
}



// 4: VISA, 51 -> 55: MasterCard, 36-38-39: DinersClub, 34-37: American Express, 65: Discover
function init_creditcard_component(){
	var cards = [{
		name: "mastercard",
		color: "#0061A8",
		logo: "fab fa-cc-mastercard"
	}, {
		name: "visa",
		color: "#daa520",
		logo: "fab fa-cc-visa"
	}, {
		name: "dinersclub",
		color: "#888",
		logo: "fab fa-cc-diners-club"
	}, {
		name: "americanExpress",
		color: "#108168",
		logo: "fab fa-cc-amex"
	}, {
		name: "discover",
		color: "#7ea8bb",
		logo: "fab fa-cc-discover"
	}];

	var html = document.getElementsByTagName('html')[0];
	var number = "";
	var cardNumber = $(".card_number");

	//Gestion de l'UI (surbrillance des éléments)
	$(document).click(function(e){
		if(!$(e.target).is(".cvv") || !$(e.target).closest(".cvv").length){
			$(".card").css("transform", "rotatey(0deg)");
			$(".seccode").css("color", "var(--text-color)");
		}
		if(!$(e.target).is(".expire") || !$(e.target).closest(".expire").length)
			$(".date_value").css("color", "var(--text-color)");
		if(!$(e.target).is(".number") || !$(e.target).closest(".number").length)
			cardNumber.css("color", "var(--text-color)");
		if(!$(e.target).is(".inputname") || !$(e.target).closest(".inputname").length)
			$(".fullname").css("color", "var(--text-color)");
	});

	//Gestion du champ N° Carte
	var selected_card = -1;
	$(".number").keyup(function(event){
		cardNumber.text($(this).val());
		number = $(this).val();

		if(parseInt(number.substring(0, 2)) > 50 && parseInt(number.substring(0, 2)) < 56){
			selected_card = 0;
		} else if(parseInt(number.substring(0, 1)) == 4){
			selected_card = 1;  
		} else if(parseInt(number.substring(0, 2)) == 36 || parseInt(number.substring(0, 2)) == 38 || parseInt(number.substring(0, 2)) == 39){
			selected_card = 2;     
		} else if(parseInt(number.substring(0, 2)) == 34 || parseInt(number.substring(0, 2)) == 37){
			selected_card = 3; 
		} else if(parseInt(number.substring(0, 2)) == 65){
			selected_card = 4; 
		} else if(parseInt(number.substring(0, 4)) == 5019){
			selected_card = 5; 
		} else {
			selected_card = -1; 
		}

		if(selected_card != -1){
			html.setAttribute("style", "--card-color: " + cards[selected_card].color);  
			$(".bankid").attr("class", "bankid").addClass(cards[selected_card].logo).removeClass('hidden');
		} else {
			html.setAttribute("style", "--card-color: #cecece");
			$(".bankid").attr("class", "bankid").addClass('hidden');
		}

		if(cardNumber.text().length === 0)
			cardNumber.html("&#x25CF;&#x25CF;&#x25CF;&#x25CF; &#x25CF;&#x25CF;&#x25CF;&#x25CF; &#x25CF;&#x25CF;&#x25CF;&#x25CF; &#x25CF;&#x25CF;&#x25CF;&#x25CF;");
	}).focus(function(){
		cardNumber.css("color", "white");
	}).on("keydown input", function(){
		cardNumber.text($(this).val());

		if(event.key >= 0 && event.key <= 9)
			if($(this).val().length === 4 || $(this).val().length === 9 || $(this).val().length === 14)
				$(this).val($(this).val() +  " ");
	})

	//Gestion du champ Nom
	$(".inputname").keyup(function(){  
		$(".fullname").text($(this).val());  
		if($(".inputname").val().length === 0) $(".fullname").text("NOM");
		return event.charCode;
	}).focus(function(){
		$(".fullname").css("color", "white");
	});

	//Gestion du champ CVV
	$(".cvv").focus(function(){
		$(".card").css("transform", "rotatey(180deg)");
		$(".seccode").css("color", "white");
	}).keyup(function(){
		$(".seccode").text($(this).val());
		if($(this).val().length === 0) $(".seccode").html("&#x25CF;&#x25CF;&#x25CF;");
	}).focusout(function() {
		$(".card").css("transform", "rotatey(0deg)");
		$(".seccode").css("color", "var(--text-color)");
	});


	//Gestion champ Date d'expiration
	var month = 0;
	$(".expire").keypress(function(event){
		if(event.charCode >= 48 && event.charCode <= 57){
			if($(this).val().length === 1){
				if(($(this).val()==1 && event.key<=2) || $(this).val()==0)
					$(this).val($(this).val() + event.key + " / ");
			} else if($(this).val().length === 0){
				if(event.key == 1 || event.key == 0){
					month = event.key;
					return event.charCode;
				} else {
					$(this).val(0 + event.key + " / ");
				}
			} else if($(this).val().length > 2 && $(this).val().length < 9){
				return event.charCode;
			}
		}
		return false;
	}).keyup(function(event){
		$(".date_value").html($(this).val());
		if(event.keyCode == 8 && $(".expire").val().length == 4) $(this).val(month);
		if($(this).val().length === 0) $(".date_value").text("MM / YYYY");
	}).keydown(function(){
		$(".date_value").html($(this).val());
	}).focus(function(){
		$(".date_value").css("color", "white");
	});
}