$(document).ready(function(){

	/** Show error message */
	function show_error(message){

		console.error(message);

		if(PNotify){
			 $(function(){
				new PNotify({
					title: 'Error',
					text: message,
					type: 'error',
					desktop: {
						desktop: true
					}
				});
			 });
		}
	}

	/* Payment */
	$(".pay_button").click(function(event){

		$(".pay_button").attr("disabled", true);
		$(".pay_button").addClass("disabled");


		var $this = $(this);
		var url = vpos_constants["SET_PAYMENT_ATTRIBUTES_URL"];
		var $form = $(this).parents("form");
		var post = {
			payment_code: vpos_constants["PAYMENT_CODE"],
			url_ok: vpos_constants["URL_OK"],
			url_nok: vpos_constants["URL_NOK"],
			vpos_id: $(this).data("id")
		};

        // Reference number
		if($this.data("reference_number")){
		    post["reference_number"] = $this.data("reference_number");
		}

		// Evitar que se pueda pulsar más de una vez sobre el botón
		if(this.clicked){
			event.preventDefault();
			return;
		}
		else{
				this.clicked = true;
		}

		$this.addClass("waiting");

		$.post(url, post, function(data){
			var $input;

			if("status" in data && data["status"]=="error"){
				show_error("Unable to create an operation number");
				return false;
			}

			var formdata = data['data'];

			// Assignment of each attribute generated by server
			$form.attr({
				"action": data['action'],
				"method": data['method']
			});

			if(data['enctype']){
				$form.attr("enctype", data['enctype']);
			}

			for (name in formdata) {
				$input = $('<input type="hidden" />');
				$input.attr("name", name).val(formdata[name]);
				$form.append($input);
			}

			$form.submit();

			return false;
		});
		return false;
	});

});
