/* File Created: July 10, 2014 */

var startTime;

$(document).ready(function() {
	startTime = new Date().getTime();
});


jQuery.ajaxSetup({ global: true,
	statusCode: {
		401: function () { // if ajax authentication fails then reload to get redirected to login page
			location.reload(true);
			location.href = location.href;
			return false;
		}
	}
});

var blurred = false;


$(window).on('focus', function () {		// AX-24898.24919.2 .focus(function () {

	checkTimeOnFocus();

});

function checkTimeOnFocus() {
	var now = new Date().getTime();

	var diff = now - startTime;
	if (diff > 60 * 1000) {
		checkIfLoggedIn();
	}
}

function checkIfLoggedIn() {
		startTime = new Date().getTime();
	var result;
	$.ajax({
	    url: '/Home/IsLoggedIn',
	    type: 'POST',
	    async: false,
	    dataType: 'json',
	    success: function (data) {

	        result = data;
	        if (result == false) {
	            // AX-1336.2308 Clear URL for CTE page after autologout
	            if (location.pathname.toLowerCase().indexOf("ClinicTimeException".toLowerCase()) >= 0) {
	                location.reload(true);
	                var controller = location.pathname.toLowerCase().indexOf("Home".toLowerCase()) >= 0 ? "/Home/" : "/Mobile/";
	                var goUrl = controller + "Scheduler";
	                history.pushState("", "", goUrl);   // Force to set history with new url. This fix issue with IE10, so now we can use location.reload() also in IE10
	                location.href = goUrl;
	            } else {
	                location.reload(true);
	                location.href = location.href.split("#")[0];
	            }
	        }
	    }

	});

	

}


function keepAlive() {
	
	var now = new Date().getTime();

	var diff = now - startTime;
	if (diff > 60 * 1000) { // AX-505 do this at most once per minute
		startTime = new Date().getTime();
		var result;
		$.ajax({
			url: '/Home/KeepAlive',
			type: 'POST',
			async: false,
			dataType: 'json',
			success: function(data) {

				result = data;
			}
		});
	}

}

setInterval(function() {
	 checkTimeOnFocus();
}, 3000); 

/*
setInterval(function () {
	checkIfLoggedIn();
}, 60000);
*/
