	var wait_save_data = 1;

	var error_code = 1;
	var visaPattern = /^(?:4[0-9]{12}(?:[0-9]{3})?)$/;
	var mastPattern = /^(?:5[1-5][0-9]{14})$/;
	var amexPattern = /^(?:3[47][0-9]{13})$/;
	var discPattern = /^(?:6(?:011|5[0-9][0-9])[0-9]{12})$/;


$('.form-upgrade').validator().on('submit', function (e) {
	$('.info').empty();
	error_code = 1;
  	if (e.isDefaultPrevented()) {
    	// handle the invalid form...
    	console.log('has error');
  	} else {
    	// everything looks good!
    	e.preventDefault();


    	var USER_DATA = {};
    	USER_DATA.projectTypeNumber = $('[name="projectNumber"]').val();
    	USER_DATA.dealerToken = $('[name="dealerToken"]').val();
    	USER_DATA.dealerName = $('[name="dealerName"]').val();
    	USER_DATA.domain = $('[name="domain"]').val();
    	USER_DATA.reportSubject = $('[name="reportSubject"]').val();



		USER_DATA.account 	= $('[name="account"]').val();
		/*USER_DATA.imeiOld 	= $('[name="imeiOld"]').val();*/

		USER_DATA.imei 		= $('[name="imei"]').val();
		USER_DATA.name 		= $('[name="name"]').val();
		USER_DATA.describe1 = $('[name="describe1"]').val();
		USER_DATA.describe2 = $('[name="describe2"]').val();
		USER_DATA.describe3 = $('[name="describe3"]').val();
		USER_DATA.describe4 = $('[name="describe4"]').val();
		USER_DATA.servicePlanCode = $('[name="servicePlan"]').val();
		USER_DATA.servicePlan = $('[name="servicePlan"] option:selected').text();
		USER_DATA.servicePlanType = $('[name="servicePlan"] option:selected').data('plantype');

		USER_DATA.assetType = $('[name="assetType"]').val();
		USER_DATA.instalLocation = $('[name="instalLocation"]').val();
		USER_DATA.notes = $('[name="notes"]').val();
		USER_DATA.isDeviceInstalled = $('[name="isDeviceInstalled"]:checked').val();
		USER_DATA.initialMileage = $('[name="initialMileage"]').val();
		USER_DATA.initialEngineHours = $('[name="initialEngineHours"]').val();


		USER_DATA.paymentTypeCode = $('input[name="paymentType"]:checked').val();
		USER_DATA.paymentType = $('input[name="paymentType"]:checked').siblings('span').text();

		switch (USER_DATA.paymentTypeCode){
			case '1':
				USER_DATA.payment1 = $('[name="ccType"]:checked').val();
				USER_DATA.payment2 = $('[name="ccNumber"]').val();
				USER_DATA.payment3 = $('[name="ccExpiryDate"]').val();
				USER_DATA.payment4 = $('[name="ccNameOnCard"]').val();
				USER_DATA.payment5 = $('[name="ccCVV"]').val();

				error_code = validateCreditCardNumber({'ccNum':USER_DATA.payment2});
				break;
			case '2':
				USER_DATA.payment1 = $('[name="bankAccountName"]').val();
				USER_DATA.payment2 = $('[name="bankName"]').val();
				USER_DATA.payment3 = $('[name="bankBSB"]').val();
				USER_DATA.payment4 = $('[name="bankAccountNumber"]').val();
				break;
			case '4':
				USER_DATA.paymentType = 'voucher';
				USER_DATA.payment1 = $('[name="voucherCode"]').val();
				break;
			default:
				USER_DATA.payment1 = $('[name="invoiceName"]').val();
				USER_DATA.payment2 = $('[name="invoiceNumber"]').val();
				USER_DATA.payment3 = $('[name="invoiceRUT"]').val();
				USER_DATA.payment4 = $('[name="invoiceEmail"]').val();
		}

		if ($('[name="autosuspend"]').prop('checked')) {
			USER_DATA.autosuspend = 1;
		}else{
			USER_DATA.autosuspend = 0;
		}

		USER_DATA.solutionCode = $('[name="solution"]').val();
		USER_DATA.solution = $('[name="solution"] option:selected').text();
		USER_DATA.deviceType = $('[name="deviceType"]').val();
		USER_DATA.domain = $('[name="domain"]').val();

		USER_DATA.fitoptions = $('[name="fitoptions"]').val();
		if (USER_DATA.fitoptions && USER_DATA.fitoptions.length) {
			USER_DATA.fitoptions = USER_DATA.fitoptions.reduce((a, b) => parseInt(a) + parseInt(b), 0);
		}else{
			USER_DATA.fitoptions = 0;
		}

	
		console.log('USER_DATA', USER_DATA);

		console.log(error_code);
		switch (error_code){
			case 1:
				if (wait_save_data == 1) {
					checkDealerImei(USER_DATA);
				}else{
					console.log("Sending previous form data");
				}
				break;

			case 2:
				$('.info').html('<div class="errors">Enter valid payment details, please.</div>');
				break;
		}


  	}

  	return false;
});



function validateCreditCardNumber(data) {
    data.ccNum = data.ccNum.replace(/\s+/g, '');
    var code = 1;

    var isVisa = visaPattern.test( data.ccNum ) === true;
    var isMast = mastPattern.test( data.ccNum ) === true;
    var isAmex = amexPattern.test( data.ccNum ) === true;
    //var isDisc = discPattern.test( ccNum ) === true;

    if( isVisa || isMast || isAmex ) {
        if ( data.ccNum == '5555555555555555' || data.ccNum == '4444444444444444' || data.ccNum == '333333333333333') {
        	code = 2;
        }
    } else {
        //alert("Please enter a valid card number.");
        code = 2;
    }

    return code;
}

function checkDealerImei(params) {

	$.ajax({
		type: "GET",
		url: "https://newapi.quiktrak.co/Common/v1/Activation/GetAssetsInfo",
		dataType: 'json',
		data: {imeis: params.imei, majortoken: params.dealerToken},
		async: true,
		cache: false,
		beforeSend: function(){
			wait_save_data = 0;
			$('.form_submit').toggleClass('disabled');
			$('.form_submit .submit_text, .form_submit .preloader').toggleClass('vis_hidden');
			preloader.on();
		},
		success: function(result){
			wait_save_data = 1;
			$('.form_submit').toggleClass('disabled');
			$('.form_submit .submit_text, .form_submit .preloader').toggleClass('vis_hidden');
			preloader.off();

			console.log(result);
			var MajorCode = result.MajorCode;
			if (MajorCode == '000') {
				sendUserData(params);
			}else{
				$('.info').html('<div class="errors">This IMEI '+params.imei+' not belong to Dealer Account '+$(dealerName).val()+'</div>');
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			console.log(XMLHttpRequest);
			console.log(textStatus);
			console.log(errorThrown);
			wait_save_data = 1;
			$('.form_submit').toggleClass('disabled');
			$('.form_submit .submit_text, .form_submit .preloader').toggleClass('vis_hidden');
			preloader.off();
		}
	});
}

function sendUserData(params){
	$.ajax({
		type: "POST",
		url: "php/save_in_db_u2l.php",
		dataType: 'json',
		data: params,
		async: true,
		cache: false,
		beforeSend: function(){
			wait_save_data = 0;
			$('.form_submit').toggleClass('disabled');
			$('.form_submit .submit_text, .form_submit .preloader').toggleClass('vis_hidden');
			preloader.on();
		},
		success: function(data){
			wait_save_data = 1;
			$('.form_submit').toggleClass('disabled');
			$('.form_submit .submit_text, .form_submit .preloader').toggleClass('vis_hidden');
			preloader.off();

			console.log(data);
			var replyCode = data.replyCode;
			var respondMsg = data.msg;
			switch (replyCode){
				case '9999': case '1005': case '1004': case '1002': case '1000':
					$('.info').html('<div class="errors">'+respondMsg+'</div>');
					break;
				case '000':
					$('.clearAfter').val('');
					/*$('.device_count').empty();*/
					$('.info').html('<div class="success">'+respondMsg+'</div>');
					var letter = data.letter;
					if (letter) {
						window.open(letter,'_blank');

						var letterFrame = '<iframe src="'+letter+'" onload="resizeIframe(this)" style="width: 100%;"></iframe>';
						$('#modalLetter').modal('show');
		            	$('#modalLetter .modal-content').html(letterFrame);
					}
					break;
				default:
				$('.info').html('<div class="errors">Error, please try again later</div>');
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			console.log(XMLHttpRequest);
			console.log(textStatus);
			console.log(errorThrown);
			$('.form_submit').toggleClass('disabled');
			$('.form_submit .submit_text, .form_submit .preloader').toggleClass('vis_hidden');
			$('.info').html('<div class="errors">Error, please try again later</div>');
			wait_save_data = 1;
			preloader.off();
		}
	});
}