$(document).ready(function () {

		//profileConfirmation();

		if (typeof window.driverRegistrationResumeMedia !== 'undefined' && window.driverRegistrationResumeMedia > 0) {

			mediaForm(window.driverRegistrationResumeMedia);

			return;

		}

        loadGeneralTab();

		//profileConfirmation();

		//mediaForm(7);

		//addDriverDocumentForm();

		//addVehicleForm();

		//addVehicleDocumentForm(11);

            

});



(function () {

	

	var tabRegistration = "#tabRegistration";

	var driverRegSaveOverlaySafetyTimer = null;

	function driverRegEnsureOverlayStyles() {

		if (document.getElementById('driver-reg-save-overlay-styles')) {

			return;

		}

		var s = document.createElement('style');

		s.id = 'driver-reg-save-overlay-styles';

		s.textContent = '#driver-reg-save-overlay{position:fixed;inset:0;z-index:99999;display:none;align-items:center;justify-content:center;background:rgba(255,255,255,.82);backdrop-filter:blur(2px);}' +
			'#driver-reg-save-overlay.is-visible{display:flex;}' +
			'#driver-reg-save-overlay .driver-reg-save-overlay__spinner{width:44px;height:44px;border:4px solid #e8e8ef;border-top-color:#635bff;border-radius:50%;animation:driver-reg-save-spin .75s linear infinite;}' +
			'@keyframes driver-reg-save-spin{to{transform:rotate(360deg);}}';

		document.head.appendChild(s);

	}

	function driverRegSaveOverlayShow() {

		driverRegEnsureOverlayStyles();

		var $o = $('#driver-reg-save-overlay');

		if (!$o.length) {

			$('body').append('<div id="driver-reg-save-overlay" aria-busy="true" role="status"><span class="driver-reg-save-overlay__spinner" aria-hidden="true"></span></div>');

			$o = $('#driver-reg-save-overlay');

		}

		if (driverRegSaveOverlaySafetyTimer) {

			clearTimeout(driverRegSaveOverlaySafetyTimer);

		}

		driverRegSaveOverlaySafetyTimer = setTimeout(function () {

			driverRegSaveOverlayHide();

		}, 180000);

		$o.addClass('is-visible');

	}

	function driverRegSaveOverlayHide() {

		if (driverRegSaveOverlaySafetyTimer) {

			clearTimeout(driverRegSaveOverlaySafetyTimer);

			driverRegSaveOverlaySafetyTimer = null;

		}

		$('#driver-reg-save-overlay').removeClass('is-visible');

	}

	

	loadGeneralTab = function (id) {

        driverForm(id);

    };

	function initDriverDobDatepicker() {

		var $inp = $('#tabRegistration input.driver-dob-field[name="user_dob"], #fromDriver input.driver-dob-field[name="user_dob"]');

		if (!$inp.length) {

			$inp = $('#tabRegistration input[name="user_dob"], #fromDriver input[name="user_dob"]');

		}

		if (!$inp.length || typeof $.fn.datepicker !== 'function') {

			return;

		}

		if ($inp.hasClass('hasDatepicker')) {

			$inp.datepicker('destroy');

		}

		var maxS = $inp.attr('data-dob-max');

		var minS = $inp.attr('data-dob-min');

		var yNow = new Date().getFullYear();

		var maxY = maxS && maxS.length >= 4 ? parseInt(maxS.substring(0, 4), 10) : yNow - 14;

		var minY = minS && minS.length >= 4 ? parseInt(minS.substring(0, 4), 10) : yNow - 90;

		if (isNaN(maxY)) {

			maxY = yNow - 14;

		}

		if (isNaN(minY)) {

			minY = yNow - 90;

		}

		var opts = {

			dateFormat: 'yy-mm-dd',

			changeMonth: true,

			changeYear: true,

			yearRange: minY + ':' + maxY

		};

		if (maxS) {

			opts.maxDate = maxS;

		} else {

			opts.maxDate = '-14y';

		}

		if (minS) {

			opts.minDate = minS;

		} else {

			opts.minDate = '-90y';

		}

		$inp.datepicker(opts);

	}

    driverForm = function (id) {

		var fid = typeof id !== 'undefined' && id !== null ? id : 0;

        fcom.ajax(fcom.makeUrl('DriverRegistration', 'form', [fid]), '', function (t) {

            $(tabRegistration).html(t);

			var sid = $('#driver_reg_state_prefill').val();

			if (typeof sid === 'undefined' || sid === null || sid === '') {

				sid = 0;

			}

			getCountryStates($('#user_country').val(), sid, '#user_state');

			initDriverDobDatepicker();

        });

    };

    setupDriver = function (frm) {

		if (!$(frm).validate())

            return;

		driverRegSaveOverlayShow();

		var url = fcom.makeUrl('DriverRegistration', 'setupDriver');

		var postData = fcom.frmData(frm);

		if (typeof postData === 'string') {

			postData += (postData.length ? '&' : '') + 'fOutMode=json&fIsAjax=1';

		}

		$.ajax({

			type: 'POST',

			url: url,

			data: postData,

			dataType: 'json',

			success: function (ans) {

				if (!ans || ans.status == -1) {

					driverRegSaveOverlayHide();

					if (ans && ans.msg) {

						alert(ans.msg);

					}

					return;

				}

				if (ans.status == 1) {

					if (ans.stripe_response && typeof console !== 'undefined' && console.debug) {

						console.debug('[DriverRegistration] stripe_response', ans.stripe_response);

					}

					var stripeUrl = ans.stripe_onboarding_url || ans.redirectUrl;

					if (stripeUrl) {

						window.location.href = stripeUrl;

						return;

					}

					driverRegSaveOverlayHide();

					if (ans.stripe_message) {

						$.mbsmessage(ans.stripe_message, true, 'alert alert--info');

					}

					if (ans.driverId > 0) {

						mediaForm(ans.driverId);

					}

					return;

				}

				driverRegSaveOverlayHide();

				$.mbsmessage(ans.msg, true, 'alert alert--danger');

			},

			error: function () {

				driverRegSaveOverlayHide();

			}

		});

		return false;

	};





    mediaForm = function (driverId) {

        fcom.ajax(fcom.makeUrl('DriverRegistration', 'mediaForm', [driverId]), '', function (res) {

            $(tabRegistration).html(res);

        });

    };

	

	setupMedia = function () {

        addDriverDocumentForm();

    };



    removeImg = function (driverId) {

        if (!confirm(langLbl.confirmDeleteImage)) {

            return;

        }

        fcom.updateWithAjax(fcom.makeUrl('DriverRegistration', 'removeImage', [driverId]), '', function (t) {

            mediaForm(driverId);

        });

    };





    addDriverDocumentForm = function () {

        fcom.ajax(fcom.makeUrl('DriverRegistration', 'driverDocumentsForm'), '', function (t) { 

            $(tabRegistration).html(t);

        });



    };



    setupDriverDocuments = function (frm) {

        if (!$(frm).validate())

            return;

        var data = fcom.frmData(frm);

		

		fcom.ajax(fcom.makeUrl('DriverRegistration', 'setupDriverDocuments'), fcom.frmData(frm), function(t) {

			var ans = JSON.parse(t);

			

			if(ans.status == 1){

				addVehicleForm();

			}else{

				$.mbsmessage(ans.msg, true, 'alert alert--danger');

			}

		});

		

        /*fcom.updateWithAjax(fcom.makeUrl('DriverRegistration', 'setupDriverDocuments'), data, function (t) {

            addVehicleForm();

        });*/

    };

	

	addVehicleForm = function () {
        fcom.ajax(fcom.makeUrl('DriverRegistration', 'vehicleForm', []), '', function (t) { 
            $(tabRegistration).html(t);
        });
    };

	

	setupVehicle = function (frm) {

		if (!$(frm).validate())

            return;

			fcom.ajax(fcom.makeUrl('DriverRegistration', 'setupVehicle'), fcom.frmData(frm), function(t) {

				var ans = JSON.parse(t);

				if(ans.status == 1){

					if (ans.vehicleId > 0) {

						addVehicleDocumentForm(ans.vehicleId);

                		return false;

            		}

			}else{

				$.mbsmessage(ans.msg, true, 'alert alert--danger');

			}

		});

		return false;

	

	}

	

	

	

	addVehicleDocumentForm = function (id) {

        fcom.ajax(fcom.makeUrl('DriverRegistration', 'vehicleDocumentsForm', [id]), '', function (t) { 

            $(tabRegistration).html(t);

        });

    };



    setupVehicleDocuments = function (frm) {

        if (!$(frm).validate())

            return;

        var data = fcom.frmData(frm);

        fcom.ajax(fcom.makeUrl('DriverRegistration', 'setupVehicleDocuments'), data, function (t) {

			profileConfirmation(t.userId);

        });

    };

	

	profileConfirmation = function (id) {

        fcom.ajax(fcom.makeUrl('DriverRegistration', 'profileConfirmation', [id]), '', function (t) { 

            $(tabRegistration).html(t);

        });

    };





})();



$(document).on('click', '.fileType-Js', function () {

    var node = this;

    $('#form-upload').remove();

    var driverId = document.frmDocuments.driverId.value;

    var documentId = $(node).attr('data-field_id');

    var frm = '<form enctype="multipart/form-data" id="form-upload" style="position:absolute; top:-100px;" >';

    frm = frm.concat('<input type="file" name="file" />');

    frm = frm.concat('<input type="hidden" name="document_id" value="' + documentId + '"></form>');

    $('body').prepend(frm);

    $('#form-upload input[name=\'file\']').trigger('click');

    if (typeof timer != 'undefined') {

        clearInterval(timer);

    }

    timer = setInterval(function () {

        if ($('#form-upload input[name=\'file\']').val() != '') {

            clearInterval(timer);

            $val = $(node).val();

            $.ajax({

                url: fcom.makeUrl('DriverRegistration', 'uploadDriverDocuments', [driverId]),

                type: 'post',

                dataType: 'json',

                data: new FormData($('#form-upload')[0]),

                cache: false,

                contentType: false,

                processData: false,

                beforeSend: function () {

                    $(node).val('Loading..');

					$.mbsmessage('Loading..', true, 'alert alert--process');

                },

                complete: function () {

                    $(node).val($val);

                },

                success: function (ans) {

					

                    if (!ans.status) {

						$.mbsmessage(ans.msg, true, 'alert alert--danger');

                        //fcom.displayErrorMessage(ans.msg);

                        return;

                    }

					$.mbsmessage(ans.msg, true, 'alert alert--success');

                    //fcom.displaySuccessMessage(ans.msg);

                    $('.text-danger').remove();

                    $('#input-formfield' + documentId).html(ans.msg);

                    $('#formfield_' + documentId).val(ans.file);

                    if (ans.status == true) {

                        $('#input-formfield' + documentId).removeClass('text-danger');

                        $('#input-formfield' + documentId).addClass('text-success');

                    } else {

                        $('#input-formfield' + documentId).removeClass('text-success');

                        $('#input-formfield' + documentId).addClass('text-danger');

                    }

                },

                error: function (xhr, ajaxOptions, thrownError) {

                    alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);

                }

            });

        }

    }, 500);

});





$(document).on('click', '.fileType-vehicle-doc-Js', function () {

    var node = this;

    $('#form-upload').remove();

    var vehicleId = document.frmDocuments.vehicleId.value;

    var documentId = $(node).attr('data-field_id');

    var frm = '<form enctype="multipart/form-data" id="form-upload" style="position:absolute; top:-100px;" >';

    frm = frm.concat('<input type="file" name="file" />');

    frm = frm.concat('<input type="hidden" name="document_id" value="' + documentId + '"></form>');

    $('body').prepend(frm);

    $('#form-upload input[name=\'file\']').trigger('click');

    if (typeof timer != 'undefined') {

        clearInterval(timer);

    }

    timer = setInterval(function () {

        if ($('#form-upload input[name=\'file\']').val() != '') {

            clearInterval(timer);

            $val = $(node).val();

            $.ajax({

                url: fcom.makeUrl('DriverRegistration', 'uploadVehicleDocuments', [vehicleId]),

                type: 'post',

                dataType: 'json',

                data: new FormData($('#form-upload')[0]),

                cache: false,

                contentType: false,

                processData: false,

                beforeSend: function () {

                    $(node).val('Loading..');

					$.mbsmessage('Loading..', true, 'alert alert--process');

                },

                complete: function () {

                    $(node).val($val);

                },

                success: function (ans) {



                    if (!ans.status) {

                        //fcom.displayErrorMessage(ans.msg);

						$.mbsmessage(ans.msg, true, 'alert alert--danger');

                        return;

                    }

					$.mbsmessage(ans.msg, true, 'alert alert--success');

                    $('.text-danger').remove();

                    $('#input-formfield' + documentId).html(ans.msg);

                    $('#formfield_' + documentId).val(ans.file);

                    if (ans.status == true) {

                        $('#input-formfield' + documentId).removeClass('text-danger');

                        $('#input-formfield' + documentId).addClass('text-success');

                    } else {

                        $('#input-formfield' + documentId).removeClass('text-success');

                        $('#input-formfield' + documentId).addClass('text-danger');

                    }

                },

                error: function (xhr, ajaxOptions, thrownError) {

                    alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);

                }

            });

        }

    }, 500);

});



$(document).on('click', '.File-Js-Profile', function () {

    var node = this;

    $('#form-upload').remove();

    var driver_id = $(node).attr('data-driver_id');

    var frm = '<form enctype="multipart/form-data" id="form-upload" style="position:absolute; top:-100px;" >';

    frm = frm.concat('<input type="file" name="file" />');

    $('body').prepend(frm);

    $('#form-upload input[name=\'file\']').trigger('click');

    if (typeof timer != 'undefined') {

        clearInterval(timer);

    }

    timer = setInterval(function () {

        if ($('#form-upload input[name=\'file\']').val() != '') {

            clearInterval(timer);

            $val = $(node).val();

            $.ajax({

                url: fcom.makeUrl('DriverRegistration', 'setUpImage', [driver_id]),

                type: 'post',

                dataType: 'json',

                data: new FormData($('#form-upload')[0]),

                cache: false,

                contentType: false,

                processData: false,

                beforeSend: function () {

					$.mbsmessage('Loading..', true, 'alert alert--process');

                },

                complete: function () {

                    $(node).val($val);

                },

                success: function (ans) {

                    if (ans.status == 1) {

                        //fcom.displaySuccessMessage(ans.msg);

                        mediaForm(ans.driver_id);

                    } else {

						$.mbsmessage(ans.msg, true, 'alert--danger alert');

                    }

                    //reloadList();



                    /*

                     alert(ans);	

                     mediaForm(ans.driver_id);		

                     reloadList();						

                     */},

                error: function (xhr, ajaxOptions, thrownError) {

                    alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);

                }

            });

        }

    }, 500);

});