var im_win;
var prefix = "/gwt-chat/Messenger.html?session=";
var timerID = null;
var attemptCount = 0;

function startLiveChat(hasUsername, showHistory, sessionId) {
    startLiveChatDomain(hasUsername, showHistory, sessionId, null);
}

function startLiveChatDomain(hasUsername, showHistory, sessionId, domain) {
    startLiveChatDomain(hasUsername, showHistory, sessionId, domain, null);
}

function startLiveChatDomain(hasUsername, showHistory, sessionId, domain, locale) {

    var imurl = prefix + sessionId;
    if (domain != null && domain != '') {
        imurl += "&domain=" + domain;
    }

    if (locale != null && locale != '') {
        imurl += "&locale=" + locale;
    }

    if (im_win == null || !im_win.open || im_win.closed) {
        im_win = window.open(imurl, 'newim', 'width=900, height=600, scrollbars=yes, resizable=yes');
    }

    if (hasUsername != null && hasUsername != 'null') {
        attemptCount = 0;
        openPrivateTab(hasUsername, showHistory);
    }

    try {
        im_win.focusChat();
    } catch (e) {
        im_win.focus();
    }

}

function openPrivateTab(hasUsername, showHistory) {
    if (attemptCount < 10) {
        try {
            im_win.openPrivateTab(hasUsername, showHistory);
            clearTimeout(timerID);
        } catch (e) {
            attemptCount++;
            timerID = self.setTimeout("openPrivateTab('" + hasUsername + "','" + showHistory + "')", 500);
        }
    } else {
        attemptCount = 0;
        clearTimeout(timerID);
    }
}

