var iframeHeightThresold = 284;
$("form").submit(function () {
	Login();
	return false;
});
function Request() {
	var request = {
		url: "",
		parameters: {},
		ddType: "",
		resourceType: ""
	};
	return request;
}
function CallPythonService(request) {
	return new Promise(function (resolve, reject) {
		$.ajax({
			type: "Get",
			url: request.url,
			contentType: 'application/json',
			dataType: 'json',
			headers: { 'Access-Control-Allow-Origin': '*' },
			data: request.parameters,
			success: function (response) {
				resolve(response);
			},
			error: function (ex) {
				if (!isProduction) {
					console.log(ex);
				}
			}
		});
	});
}

$(function () {
	$("#txtPassword").keypress(function (e) {
		if (e.which == 13) {
			//alert('You pressed enter!');
			Login();
		}
	});
});
var user = { "UserName": "", "Userid": 0, "Name": '', "LoginDate": new Date(), 'LastUpdatedDate': new Date() };

function GenerateRandom(length) {
	var text = "";
	var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
	for (var i = 0; i < length; i++) {
		text += possible.charAt(Math.floor(Math.random() * possible.length));
	}
	return text;
}
function BindResponseData(Type, response) {
	if (Type == 'ValidateUser') {
		if (response.status == 'success') {
		user.SUID = GenerateRandom(8);
			user.UserName = response.userName;
			user.Name = response.FirstName;
			user.Userid = response.id;
			user.LoginDate = Date.parse(new Date());
			user.LastUpdatedDate = Date.parse(new Date());
			sessionStorage.setItem("sessionData", JSON.stringify(user));
			sessionStorage.setItem("configData", JSON.stringify(response.clientConfiguration));
			document.cookie="NASYAUserName="+response.userName+"";
			location.href = response.clientConfiguration+'/index.html'; //GetUrlParam('returnUrl','index.html');
		} else {
			//alert(response.description);
			if (response.isUserBlocked) {
				swal("User Locked", response.description, "error");
				var courntDown = setInterval(function () {
					$('.text-muted').html("Please try after " + response.timeLeft + " seconds");
					if (response.timeLeft != 0)
						response.timeLeft = response.timeLeft - 1;
					else {
						clearInterval(courntDown);
						swal("User Unlocked", "Please login now", "success");
					}
				}, 1000);
			}
			else {
				clearInterval(courntDown);
				swal("Warning", response.description, "warning");
			}
		}
	}
}
function Login() {
	var userName = $('#txtUserName').val();
	var password = $('#txtPassword').val();
	// for device name
	var deviceName = $("#device-name").val();
	if(deviceName === "80"){
		swal("Warning", "Device not Selected", "warning");
		return
	}
	var request = new Request();
	request.url = 'cgi/cgi_ValidateUser.py';
	request.parameters = { 'userName': btoa(userName), 'password': btoa(password) };
	request.Type = 'ValidateUser';
	CallPythonService(request).then(function (response) {
		if (response.status == 'success') {
			if(response.default_password){
				changePasswordPopUp();
			}
			else{
				user.SUID = GenerateRandom(8);
				user.UserName = response.userName;
				user.Name = response.FirstName;
				user.Userid = response.id;
				user.LoginDate = Date.parse(new Date());
				user.LastUpdatedDate = Date.parse(new Date());
				sessionStorage.setItem("sessionData", JSON.stringify(user));
				// sessionStorage.setItem("configData", response.clientConfiguration);
				sessionStorage.setItem("configData", 'system');
	
				// location.href = response.clientConfiguration+'/index.html'; //GetUrlParam('returnUrl','index.html');
				location.href = 'system/index.html'; //GetUrlParam('returnUrl','index.html');
			}
		} else {
			//alert(response.description);
			if (response.isUserBlocked) {
				swal("User Locked", response.description, "error");
				var courntDown = setInterval(function () {
					$('.text-muted').html("Please try after " + response.timeLeft + " seconds");
					if (response.timeLeft != 0)
						response.timeLeft = response.timeLeft - 1;
					else {
						clearInterval(courntDown);
						swal("User Unlocked", "Please login now", "success");
					}
				}, 1000);
			}
			else {
				clearInterval(courntDown);
				swal("Warning", response.description, "warning");
			}
		}
	});
}

function changePasswordPopUp() {
  
	swal({
		title: "EULA",
		html: true,
		text: `<iframe id="eula" src="Global_Sanuyi_EULA.htm" width="650px" height="284px" frameborder="0"></iframe>`,
		showCancelButton: true,
		confirmButtonText: "Agree",
		  cancelButtonText: "Disagree",  
		closeOnConfirm: false,
		closeOnCancel: true,
		customClass:"swal-wide",
		width: 700,
		animation: "slide-from-top"
	},
		function(isConfirm) {
			if (isConfirm) {
				swal({
					title: "You are required to change the default password!",
					html: true,
					text: `<input type='password' class='form-control' id='new-password' placeholder='New password' autocomplete="off" readonly onfocus="this.removeAttribute('readonly');">
							<input type="checkbox" style="margin:5px;" onclick="showPassword(this)">Show Password<br>
							<error-output id="error" style="color: red; font-size: 12px; margin-top: 5px;"></error-output>`,
					showCancelButton: true,
					closeOnConfirm: false,
					closeOnCancel: false,
					// width: 250,
					animation: "slide-from-top"
				},
					function(isConfirm) {
						if (isConfirm) {
							var userName=$('#txtUserName').val();
							var password=$('#new-password').val();
							var old_password=$('#txtPassword').val();
							try {
								if(checkpassword(password)) {
									$('#error').html("");
									var request = new Request();
									request.url = 'cgi/cgi_ValidateUser.py';
									request.parameters = { requestType:'ChangePassword','userName':btoa(userName), 'password': btoa(password), 'old_password':btoa(old_password)};
									request.Type = 'ChangePassword';
									CallPythonService(request).then((response) => {
										if (response.status == 'success') {
											if(response.default_password){
												changePasswordPopUp();
											}
											else{
												user.SUID = GenerateRandom(8);
												user.UserName = response.userName;
												user.Name = response.FirstName;
												user.Userid = response.id;
												user.LoginDate = Date.parse(new Date());
												user.LastUpdatedDate = Date.parse(new Date());
												sessionStorage.setItem("sessionData", JSON.stringify(user));
												// sessionStorage.setItem("configData", response.clientConfiguration);
												sessionStorage.setItem("configData", 'system');
									
												// location.href = response.clientConfiguration+'/index.html'; //GetUrlParam('returnUrl','index.html');
												location.href = 'system/index.html'; //GetUrlParam('returnUrl','index.html');
											}
										} else {
											//alert(response.description);
											if (response.isUserBlocked) {
												swal("User Locked", response.description, "error");
												var courntDown = setInterval(function () {
													$('.text-muted').html("Please try after " + response.timeLeft + " seconds");
													if (response.timeLeft != 0)
														response.timeLeft = response.timeLeft - 1;
													else {
														clearInterval(courntDown);
														swal("User Unlocked", "Please login now", "success");
													}
												}, 1000);
											}
											else {
												clearInterval(courntDown);
												swal("Warning", response.description, "warning");
											}
										}
									})
								}
							}
							catch(e) {
								$('#error').html(e)
							}	
						} else {
							parent.swal("Cancelled", "", "error");
						}
				});
			}
			else {
				parent.swal("Cancelled", "", "error");
			}
		});
}

function showPassword(obj) {
	var type = $(obj).siblings('input').attr('type');
	if (type === "password") {
	  $(obj).siblings('input').attr('type',"text");
	} else {
	  $(obj).siblings('input').attr('type',"password");
	}
  }

function checkpassword(password) {
	let flag = true;
	let error_str = '';
	if(password.length < 8) {
		flag = false;
		error_str+="Error: Password must contain at least eight characters! <br>";
	}
	re = /[0-9]/;
	if(!re.test(password)){
		flag = false;
		error_str+="Error: password must contain at least one number (0-9)! <br>";
	}
	re = /[a-z]/;
	if(!re.test(password)) {
		flag = false;
		error_str+="Error: password must contain at least one lowercase letter (a-z)! <br>";
	}
	re = /[A-Z]/;
	if(!re.test(password)) {
		flag = false;
		error_str+="Error: password must contain at least one uppercase letter (A-Z)! <br>";
	}
	re =/\W|_/g;
	if(!re.test(password)) {
		flag = false;
		error_str+="Error: password must contain at least one special character! <br>";
	}
	if(!flag) throw error_str;
	return true;
}

function GetUrlParam(parameter, defaultvalue) {

	var urlparameter = defaultvalue;
	if (window.location.href.indexOf(parameter) > -1) {
		urlparameter = getUrlVars()[parameter];
	}
	return urlparameter;
}

function getUrlVars() {
	var vars = {};
	var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
		vars[key] = value;
	});
	return vars;
}
if (typeof (Storage) == "undefined") {
	alert("Browser Not support");
}

function eulaScrollFunction() {

	$('.confirm.btn.btn-lg.btn-primary').attr("disabled", true);
    var $contents = $('#eula').contents();
	$('#eula').contents().on( 'scroll', function(){
		if($('#eula').contents().scrollTop() >= $('#eula').contents().height() - iframeHeightThresold ) {
			$('.confirm.btn.btn-lg.btn-primary').attr("disabled", false);
		}
		else {
			$('.confirm.btn.btn-lg.btn-primary').attr("disabled", true);
		}
	});
}