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) {
    startLiveChatDomainInWindow('newim', hasUsername, showHistory, sessionId, domain, locale);
}

function startLiveChatInWindow(windowName, hasUsername, showHistory, sessionId) {
    startLiveChatDomainInWindow(windowName, hasUsername, showHistory, sessionId, null);
}

function startLiveChatDomainInWindow(windowName, hasUsername, showHistory, sessionId, domain) {
    startLiveChatDomainInWindow(windowName, hasUsername, showHistory, sessionId, domain, null);
}

function startLiveChatDomainInWindow(windowName, hasUsername, showHistory, sessionId, domain, locale) {
    var imurl = prefix + sessionId;

    showHistory = "" + showHistory;

    if (domain != null && domain != '') {
        imurl += "&domain=" + domain;
    }

    if (locale != null && locale != '') {
        imurl += "&locale=" + locale;
    }

    if (hasUsername != null && hasUsername != '') {
        imurl += "&privateUsername=" + hasUsername;
    }

    if (showHistory != null && showHistory != '' && (showHistory.indexOf("true") != -1)) {
        imurl += "&showHistory=" + showHistory;
    }

    if (im_win == null || !im_win.open || im_win.closed) {
        im_win = window.open(imurl, windowName, 'width=900, height=600, scrollbars=yes, resizable=yes');
    } else {
        // fix for Chrome, Safari browser, make following focus work.
        im_win.blur();
    }

    if (hasUsername != null && hasUsername != 'null') {
        openPrivateTab(hasUsername, showHistory);
    }

    try {
        im_win.focusChat();
    } catch(e) {
        im_win.focus();
    }

    setOnlineIfNeed();

}

function setOnlineIfNeed() {
    if (attemptCount < 10) {
        try {
            im_win.setOnlineIfNeed();
            clearTimer();
        } catch (e) {
            attemptCount++;
            timerID = self.setTimeout("setOnlineIfNeed()", 500);
        }
    } else {
        clearTimer();
    }
}

function openPrivateTab(hasUsername, showHistory) {
    if (attemptCount < 10) {
        try {
            im_win.openPrivateTab(hasUsername, showHistory);
            clearTimer();
        } catch (e) {
            attemptCount++;
            timerID = self.setTimeout("openPrivateTab('" + hasUsername + "','" + showHistory + "')", 500);
        }
    } else {
        clearTimer();
    }
}

function clearTimer() {
    attemptCount = 0;
    clearTimeout(timerID);
}

