var uuid='';
var clientConfig = []
$(function () {	
	//SetupclientConfig();
    ValidateSession(true);
	loadjscssfile('../devScripts/constants.js','js');
	loadjscssfile('../Plugins/JAlerts/jTimeout.js','js');
	loadjscssfile('../Plugins/JAlerts/jAlert.min.js','js');
	loadjscssfile('../Plugins/JAlerts/jAlert.css','css');
	
	$(document).ajaxStart(function(request){
        ValidateSession(false);
    });
	$(document).ajaxSuccess(function(response,x,s){
        if(response.status == 'NoAccess')
			window.location.href = "unAutherizedAccess.html"; 
    });

    /*document.addEventListener("contextmenu",function(e){
	    e.preventDefault();
	},false);*/
});

var scriptPath = "devScripts/"

function Request() {
    var request = {
        url: "",
        parameters: {},
        Type: ""
    };
    return request;
}

function CreateProfile(sessionData)
{
		if($('.adminDropdown')[0] == undefined)
			return false;
		
		// $('.userProfile')[0].innerHTML='<i><img src="images/icon-men.png" alt=""></i><b>'+sessionData.Name+'</b><span>My account</span>';
		// $('.profile-details')[0].innerHTML='<a href="about-us.html">About Us</a><a href="javascript:void(0);">Settings</a><a href="userprofile.html">Profile</a><a href="javascript:void(0);">Notification</a><span class="divider"></span>	<a href="javascript:void(0);" onclick="Logout()">Logout</a>'
		

		var htmlMyAccount = `<a class="dropdown-item" href="profile.html"><i class="dropdown-icon zmdi zmdi-account"></i><span>Profile</span></a>
						<a class="dropdown-item" href="#"><i class="dropdown-icon zmdi zmdi-card"></i><span>My balance</span></a>
						<a class="dropdown-item" href="inbox.html"><i class="dropdown-icon zmdi zmdi-email"></i><span>Inbox</span></a>
						<a class="dropdown-item" href="#"><i class="dropdown-icon zmdi zmdi-settings"></i><span>Settings</span></a>
						<div class="dropdown-divider"></div>
						<div class="sub-dropdown-menu show-on-hover">
							<a href="#" class="dropdown-toggle dropdown-item no-caret"><i class="zmdi zmdi-check text-success"></i>Online</a>
							<div class="dropdown-menu open-left-side">
								<a class="dropdown-item" href="#"><i class="dropdown-icon zmdi zmdi-check text-success"></i><span>Online</span></a>
								<a class="dropdown-item" href="#"><i class="dropdown-icon zmdi zmdi-circle-o text-warning"></i><span>Busy</span></a>
								<a class="dropdown-item" href="#"><i class="dropdown-icon zmdi zmdi-minus-circle-outline text-danger"></i><span>Offline</span></a>
							</div>
						</div>
						<div class="dropdown-divider"></div>
						<a class="dropdown-item" href="javascript:void(0);" onclick="Logout()"><i class="dropdown-icon zmdi zmdi-power"></i><span>Log out</span></a>`;
		
		var htmlProfile = `<button class="dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
							<img src="../images/svg/097-user.svg" class="iconHead"/><span>`+sessionData.UserName+`</span>
							</button>
							<div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuButton">
							<a class="dropdown-item" href="userProfile.html";" title="Profile">Profile</a>
								<a class="dropdown-item" href="javascript:void(0);" onclick="Logout()">Logout</a>
								</div>`
								// <a class="dropdown-item" href="javascript:void(0);" title="Device Name">`+GetDeviceID()+`</a>
		
		$('.adminDropdown ')[0].innerHTML = htmlProfile ;//= `<span>`+sessionData.Name+`<i class="zmdi zmdi-chevron-down"></i></span>`
		sessionData.LastUpdatedDate = Date.parse(new Date());
		sessionStorage.setItem("sessionData", JSON.stringify(sessionData));
		
}
function ValidateSession(isCreateProfile)
{	
	var sessionData =JSON.parse(sessionStorage.getItem("sessionData"));	
	var sessionTimeOut = sessionTimeOut == undefined  ? parent.sessionTimeOut:sessionTimeOut;
	if (typeof(Storage) !== "undefined" && sessionData != null) {
		$('.main-container').show();
		uuid = sessionData.SUID;		
		if(isCreateProfile)
			CreateProfile(sessionData)
		else
			window.localStorage.timeoutCountdown = sessionTimeOut;
	} else {
		console.log('logout'+ new Date());
		location.href="../login.html";
		return false;
	}
}
function SetupclientConfig()
{
	var configData =sessionStorage.getItem("configData");
	if (typeof(Storage) !== "undefined" && configData != null) {
		clientConfig = configData.menuIcons;
	}
	for(var i=0;i<clientConfig.length;i++)
	{
		if(clientConfig[i].value){
			if(clientConfig[i].id !='')
				$('#'+clientConfig[i].id).show();
			else
				$('.'+clientConfig[i].class).show();
		}
		else{
			if(clientConfig[i].id !='')
				$('#'+clientConfig[i].id).hide();
			else 
				$('.'+clientConfig[i].class).hide();
		}
	}
}
function GetLoginUserDetails()
{
	var sessionData =JSON.parse(sessionStorage.getItem("sessionData"));	
	if (typeof(Storage) !== "undefined" && sessionData != null) {
			return sessionData;
		}
		else {
			console.log('logout1'+ new Date());
			location.href="login.html";
			return false;
	}
	return sessionData;
}
function showAlertMessage(headerText,message,type)
{
	if(type == 'success')
		type='Success';
	else
		type='failure';
	
	$.Notify({
	text : message,
	headerText:headerText,
	type:type,
	position:'bottom-right'
  });
}
function ShowNotif(headerText, ntype) {
	var showNotif = true;
	var autoHide = true;
	if (ntype == 'success')
		ntype = 'success';
	else if (ntype == 'fail')
		ntype = 'error';
	else {
		showNotif = false;
		var autoHide = true;
	}
	$.iaoAlert({
		msg: headerText,
		position: 'bottom-right',
		type: ntype,
		mode: "dark",
		closeButton: true,
		closeOnClick: false,
		fadeOnHover: false,
		autoHide: autoHide,
		alertTime: "5000",
		zIndex: '999',
		alertClass: 'h2'
	});
}
function Logout(redirectToLogin)
{
	sessionStorage.clear();
	if(redirectToLogin == undefined || redirectToLogin)
	{		
		var currentPage =window.location.href;
		console.log('logout'+ new Date());
		location.href="../login.html";
		//.href="login.html"+'?returnUrl='+currentPage;
	}
	
}
function loadjscssfile(filePath, filetype){	
    if (filetype=="js"){ //if filename is a external JavaScript file
        var fileref=document.createElement('script')
        fileref.setAttribute("type","text/javascript")
        fileref.setAttribute("src", filePath)
    }
    else if (filetype=="css"){ //if filename is an external CSS file
        var fileref=document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filePath)
    }
    if (typeof fileref!="undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref)
}

function GetTableConfig(tableKey)
{
	var tableConfig = {};
	var configData =sessionStorage.getItem("configData");	
	if (typeof(Storage) !== "undefined" && configData != null) {
		var results = jQuery.grep(configData.dataTables, function( n, i ) {
		  return ( n.key === tableKey);
		});
		if(results !=null && results.length > 0)
		{
			tableConfig = results[0].config;
		}
		else{
			var results = jQuery.grep(configData.dataTables, function( n, i ) {
			  return ( n.key == 'default');
			});
			tableConfig = results[0].config;
		}
			
	}
	else {
		console.log('logout1'+ new Date());
		location.href="login.html";			
	}
	return tableConfig;
}
function notify(headerText,message,type)
{
	if(type == 'success')
		type='Success';
	else
		type='failure';
	
	$.Notify({
	text : message,
	headerText:headerText,
	type:type,
	position:'bottom-right'
  });
}

function Request() {
    var request = {
        url: "",
        parameters: {}
    };	
    return request;
}
function InvokePythonService(request,dataType) {
	return new Promise(function(resolve, reject) {
		request.parameters.uuid=uuid;
		$.ajax({
			type: "Get",
			url: request.url,
			contentType: 'application/json',
			dataType: dataType == undefined ? 'json':dataType,
			headers: { 'Access-Control-Allow-Origin': '*' },
			data: request.parameters,
			success: function (response) {
				resolve(response);
			},
			error: function (ex) {
				reject(ex); // Reject the promise and go to catch()
				if(!isProduction){
					console.log(ex);
				}
			}
		});
	});
}
function GetDeviceID(){
	var deviceKey = "";
	var configData =sessionStorage.getItem("configData");	
	if (typeof(Storage) !== "undefined" && configData != null) {
		deviceKey = sessionStorage.getItem("configData");
	}
	deviceKey = "LYRA-TERA-2000"
	return deviceKey;
}

