/* File Created: May 15, 2014 */
// asynchronous refreshes of the unread message indicator


var tidUnread; // = setTimeout(asyncUserAgent, 2000);
var tiUnreadMsg;            // 70054890 Time Interval for Unread Messages
function asyncUnreadMsg() {
	$.ajax({
		url: '/Home/UnreadMessageCount',
		type: 'POST',
		dataType: 'json',
		cache: false,
		success: ShowHideUnreadMsg
	});
    clearTimeout(tidUnread);
    tidUnread = setTimeout(function() { asyncUnreadMsg(); }, tiUnreadMsg);
}

// 70054890 Async function to be called only once (not setTimeOut)
function asyncUnreadMsgOnlyOnce() {
    $.ajax({
        url: '/Home/UnreadMessageCount',
        type: 'POST',
        dataType: 'json',
        success: ShowHideUnreadMsg
    });
}

// 70054890 Function called in _Laout.cshtml. Use this function instead of direct use of asyncUnreadMsg() because paramenter timeInterval is lost after setTimeout() is trigger
function setAsyncUnreadMsg(timeInterval) {
    if (timeInterval > 0) {
        tiUnreadMsg = (timeInterval * 60000) + 3000;                            // 70054890 Set Time interval in Milliseconds from Minutes, AX-506 Add 3 seconds to avoid be the same as AutoLogout
        asyncUnreadMsg();                                                       // 70054890 Call async message count every time interval
    } else {
        asyncUnreadMsgOnlyOnce();                                               // 70054890 Just get UnreadMessage once.
    }
}

function ShowHideUnreadMsg(result) {
	if (result.Count == 0) {
		$("#newMailContainer").hide();
		$("#newMailCount").hide();
	} else {
		$("#newMailContainer").show();
		$("#newMailCount").show();
		$("#newMailCount").text(result.Count);
	}
	$("#newMailCount2").text(result .Count);
	
	$("#refreshTime").text(result.DateTime);

}

// 70054890 Only update Last Update Date and Time
function asyncLastUpdate() {
    $.ajax({
        url: '/Home/LastUpdatedDateTime',
        type: 'POST',
        dataType: 'json',
        cache: false,
        success: LastUpdateRefresh
    });
    clearTimeout(tidUnread);
    tidUnread = setTimeout(function() { asyncLastUpdate(); }, tiUnreadMsg);
}

// 70054890 Async function to be called only once (not setTimeOut)
function asyncLastUpdateOnlyOnce() {
    $.ajax({
        url: '/Home/LastUpdatedDateTime',
        type: 'POST',
        dataType: 'json',
        success: LastUpdateRefresh
    });
}

// 70054890 Set Async Last Update Time only once of with time interval
function setAsyncLastUpdate(timeInterval) {
    if (timeInterval > 0) {
        tiUnreadMsg = (timeInterval * 60000) + 3000;        // AX-506 Add 3 seconds to avoid be the same as AutoLogout
        asyncLastUpdate();
    } else {
        asyncLastUpdateOnlyOnce();
    }
}

// 70054890 Update Last Update Date and Time only
function LastUpdateRefresh(result) {
    $("#refreshTime").text(result.DateTime);    
}
//$(document).ready(asyncUnreadMsg);        // 70054890 Set in _Layout.cshtml file
