
$(document).ready(function(){
	// step 1: fill in the form, click the button
	$(".getlicensebutton").on("click", function(e) {
		e.preventDefault();

		// validate the form
		$(".getlicense .form-group").removeClass("has-error");

		if (!ValidateEmail( $(".getlicense input[name='e']").val() )) {
			$(".getlicense input[name='e']").parents(".form-group").first().addClass("has-error");
			return;
		}
		
		//submit the form
		var fd = new FormData(document.getElementById("getlicenseform"));
		$.ajax({
			url: "//software.logaholic.com/install/makelicensev6.php",
			type: "POST",
			processData: false,
	        contentType: false,
	        data: fd,
	        success: function(result) {
	        	res = ui.ParseJSON(result);
	        	if (res.Status=="Success") {
	        		$(".getlicense .box-body").html(res.Message); 
	        		$(".response .callout").hide();           		
	        	} else {
	        		ui.Callout(res);
	        		return;
			    }


	        	// step 2: choose the order for this license
	        	//$(".getlicense .box-body").html(result);
	        	
				$(".getlicense .box-body .licenselink").on("click", function(){
					oid = $(this).attr("data-orderid");
					fd.append('forceorderid', oid);
					$.ajax({
						url: "//software.logaholic.com/install/makelicensev6.php",
						type: "POST",
						processData: false,
			            contentType: false,
			            data: fd,
			            success: function(result) {

			            	// step 3: receive and save the license
			            	res = ui.ParseJSON(result);

			            	if (res.Status=="Success") {
			            		$(".getlicense .box-body").html(res.Message + "<hr>");
			            		SaveLicense(res.license);
			            	} else {
			            		$(".getlicense .box-body").html(result);
			            	}
			            } 

					});

				});
	        } 

		});


	});

	function SaveLicense(license) {
		$.ajax({
			url: "app/model/GetLicense.php",
			data: "license="+license,
			type: "POST",
			success: function(result) {
				$(".getlicense .box-body").append(result);
				$(".licenseinfo .box-body").hide();
				$(".licenseinfo .box-body").load("app/model/GetLicense.php");
				$(".licenseinfo .box-body").fadeIn();
			}
		});

	}
});