window.titles = new Array();
window.firstTitle;
window.secondTitle;
if (typeof renderTwitters != 'function')(function () {
    var browser = (function () {
        var b = navigator.userAgent.toLowerCase();
        return {
            webkit: /(webkit|khtml)/.test(b),
            opera: /opera/.test(b),
            msie: /msie/.test(b) && !(/opera/).test(b),
            mozilla: /mozilla/.test(b) && !(/(compatible|webkit)/).test(b)
        }
    })();
    var readyList = [];
    var isReady = false;
    var monthDict = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    window.ify = function () {
        var entities = {
            '"': '&quot;',
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;'
        };
        return {
            "link": function (t) {
                return t.replace(/[a-z]+:\/\/[a-z0-9-_]+\.[a-z0-9-_:~%&\?\/.=]+[^:\.,\)\s*$]/ig, function (m) {
                    return '<a href="' + m + '">' + ((m.length > 25) ? m.substr(0, 24) + '...' : m) + '</a>'
                })
            },
            "at": function (t) {
                return t.replace(/(^|[^\w]+)\@([a-zA-Z0-9_]{1,15})/g, function (m, m1, m2) {
                    return m1 + '@<a href="http://twitter.com/' + m2 + '">' + m2 + '</a>'
                })
            },
            "hash": function (t) {
                return t.replace(/(^|[^\w'"]+)\#([a-zA-Z0-9_]+)/g, function (m, m1, m2) {
                    return m1 + '#<a href="http://search.twitter.com/search?q=%23' + m2 + '">' + m2 + '</a>'
                })
            },
            "clean": function (tweet) {
                return this.hash(this.at(this.link(tweet)))
            }
        }
    }();
    window.renderTwitters = function (obj, options) {
        var classes = {
            V: "green",
            J: "yellow",
            R: "red"
        };

        function node(e) {
            return document.createElement(e)
        }
        function text(t) {
            return document.createTextNode(t)
        }
        function log(text) {
            target.innerHTML += text + "<br>"
        }
        var targetContainer = document.getElementById(window.stmParams.containerDiv);
        var targetContent = document.getElementById(window.stmParams.contentDiv);
        var targetCircle = document.getElementById(window.stmParams.circleDiv);
        var data = null;
        var ul = node('ul'),
            li, statusSpan, timeSpan, i, max = obj.length > options.count ? options.count : obj.length;
        window.titles = new Array();
        for (i = 0; i < max && obj[i]; i++) {
            data = obj[i];
            window.titles.push(data.text)
        }
        window.newMessage = true;
        var secondTitle;
        var firstTitle;
        for (var i = 0; i < window.titles.length; i++) {
            var title = window.titles[i];
            var langTest = new RegExp(options.lang + " ");
            var fractionTest = new RegExp("^([1-2])\/([1-2]): ");
            var codeExtractor = new RegExp(" ([A-Z])$");
            var hashTest = new RegExp(options.hashTag + " [RJV][EF] [ABCDEFGHIJKLMNOPQRSTUVWXYZ]");
            if (title.match(hashTest) && title.match(langTest)) {
                if (title.match(fractionTest)) {
                    for (var u = i + 1; u < window.titles.length; i++) {
                        var tmpTitle = window.titles[u];
                        if (tmpTitle.match(langTest) && tmpTitle.match(hashTest) && tmpTitle.match(fractionTest)) {
                            secondTitle = title;
                            firstTitle = tmpTitle;
                            break
                        }
                    }
                } else {
                    firstTitle = title
                }
                break
            }
        }
        if (firstTitle == undefined && secondTitle == undefined) {
            secondCallTimeOut();
            return
        }
        if (firstTitle == window.firstTitle) {
            return
        }
        clearTimeout(window.msgTimeOutId);
        if (window.msgShown) {
            try {
                $(window.stmParams.btnId).className = "btInfo off"
            } catch (e) {};
            $(window.stmParams.msgDiv).style.display = "none";
            window.messageShown = false
        }
        window.firstTitle = firstTitle;
        targetContainer.style.display = "none";
        targetContent.style.display = "none";
        if (options.clearContents) {
            try {
                while (targetContent.firstChild) {
                    targetContent.removeChild(targetContent.firstChild)
                }
            } catch (e) {}
        }
        if (secondTitle != undefined) {
            secondTitle = secondTitle.replace(options.hashTag + " ", "");
            secondTitle = secondTitle.replace(langTest, "");
            secondTitle = secondTitle.replace(codeExtractor, "");
            secondTitle = secondTitle.replace(fractionTest, "");
            firstTitle = firstTitle.replace(fractionTest, "")
        }
        firstTitle = firstTitle.substring(0,firstTitle.length-2);
        firstTitle = firstTitle.replace(options.hashTag + " ", "");
        firstTitle = firstTitle.substring(0,firstTitle.length-1);
        try {
            var m = codeExtractor.exec(firstTitle);
            var code = m[1]
        } catch (e) {};
        targetCircle.className = classes[code];
        firstTitle = firstTitle.replace(codeExtractor, "");
        window.msgArray = new Array();
        if (secondTitle != undefined) {
            window.msgArray.push(firstTitle + " <span>(1/2)</span>");
            window.msgArray.push(secondTitle + " <span>(2/2)</span>");
            window.newMsg = true;
            alternateMessages()
        } else {
            window.msgArray.push(firstTitle);
            targetContent.innerHTML += firstTitle;
            new Effect.Appear(stmParams.contentDiv, {
                from: 0,
                to: 1,
                duration: 0.5
            });
            new Effect.Appear(stmParams.containerDiv, {
                from: 0,
                to: 1,
                duration: 0.5
            })
        }
        if (typeof options.callback == 'function') {
            options.callback()
        }
    };
    window.getTwitters = function (target, id, count, options) {
        if (typeof id == 'object') {
            options = id;
            id = options.id;
            count = options.count
        }
        if (!count) count = 1;
        if (options) {
            options.count = count
        } else {
            options = {}
        }
        if (!options.timeout && typeof options.onTimeout == 'function') {
            options.timeout = 10
        }
        if (typeof options.clearContents == 'undefined') {
            options.clearContents = true
        }
        if (typeof options.hashTag == "undefined") {
            options.hashTag = "#XYZ"
        }
        if (typeof options.lang == "undefined") {
            options.lang = "F"
        }
        if (options.withFriends) options.withFriends = false;
        options['twitterTarget'] = target;
        if (typeof options.enableLinks == 'undefined') options.enableLinks = true;
        window['twitterCallback'] = function (obj) {
            if (options.timeout) {
                clearTimeout(window['twitterTimeout']);
                clearTimeout(window.errorTimeout)
            }
            renderTwitters(obj, options)
        };
        ready((function (options) {
            return function () {
                if (!document.getElementById(options.twitterTarget)) {
                    return
                }
                var url = 'http://www.twitter.com/statuses/' + (options.withFriends ? 'friends_timeline' : 'user_timeline') + '/' + id + '.json?callback=twitterCallback&count=20&cb=' + Math.random();
                if (options.timeout) {
                    window['twitterTimeout'] = setTimeout(function () {
                        if (options.onTimeoutCancel) window['twitterCallback'] = function () {};
                        options.onTimeout.call(document.getElementById(options.twitterTarget))
                    }, options.timeout * 1000)
                }
                var script = document.createElement('script');
                script.setAttribute('src', url);
                document.getElementsByTagName('head')[0].appendChild(script)
            }
        })(options))
    };
    DOMReady();

    function getTwitterData(orig) {
        var data = orig,
            i;
        for (i in orig.user) {
            data['user_' + i] = orig.user[i]
        }
        data.time = relative_time(orig.created_at);
        return data
    }
    function ready(callback) {
        if (!isReady) {
            readyList.push(callback)
        } else {
            callback.call()
        }
    }
    function fireReady() {
        isReady = true;
        var fn;
        while (fn = readyList.shift()) {
            fn.call()
        }
    }
    function DOMReady() {
        if (document.addEventListener && !browser.webkit) {
            document.addEventListener("DOMContentLoaded", fireReady, false)
        } else if (browser.msie) {
            document.write("<scr" + "ipt id=__ie_init defer=true src=//:><\/script>");
            var script = document.getElementById("__ie_init");
            if (script) {
                script.onreadystatechange = function () {
                    if (this.readyState != "complete") return;
                    this.parentNode.removeChild(this);
                    fireReady.call()
                }
            }
            script = null
        } else if (browser.webkit) {
            var safariTimer = setInterval(function () {
                if (document.readyState == "loaded" || document.readyState == "complete") {
                    clearInterval(safariTimer);
                    safariTimer = null;
                    fireReady.call()
                }
            }, 10)
        }
    }
    function relative_time(time_value) {
        var values = time_value.split(" "),
            parsed_date = Date.parse(values[1] + " " + values[2] + ", " + values[5] + " " + values[3]),
            date = new Date(parsed_date),
            relative_to = (arguments.length > 1) ? arguments[1] : new Date(),
            delta = parseInt((relative_to.getTime() - parsed_date) / 1000),
            r = '';

        function formatTime(date) {
            var hour = date.getHours(),
                min = date.getMinutes() + "",
                ampm = 'AM';
            if (hour == 0) {
                hour = 12
            } else if (hour == 12) {
                ampm = 'PM'
            } else if (hour > 12) {
                hour -= 12;
                ampm = 'PM'
            }
            if (min.length == 1) {
                min = '0' + min
            }
            return hour + ':' + min + ' ' + ampm
        }
        function formatDate(date) {
            var ds = date.toDateString().split(/ /),
                mon = monthDict[date.getMonth()],
                day = date.getDate() + '',
                dayi = parseInt(day),
                year = date.getFullYear(),
                thisyear = (new Date()).getFullYear(),
                th = 'th';
            if ((dayi % 10) == 1 && day.substr(0, 1) != '1') {
                th = 'st'
            } else if ((dayi % 10) == 2 && day.substr(0, 1) != '1') {
                th = 'nd'
            } else if ((dayi % 10) == 3 && day.substr(0, 1) != '1') {
                th = 'rd'
            }
            if (day.substr(0, 1) == '0') {
                day = day.substr(1)
            }
            return mon + ' ' + day + th + (thisyear != year ? ', ' + year : '')
        }
        delta = delta + (relative_to.getTimezoneOffset() * 60);
        if (delta < 5) {
            r = 'less than 5 seconds ago'
        } else if (delta < 30) {
            r = 'half a minute ago'
        } else if (delta < 60) {
            r = 'less than a minute ago'
        } else if (delta < 120) {
            r = '1 minute ago'
        } else if (delta < (45 * 60)) {
            r = (parseInt(delta / 60)).toString() + ' minutes ago'
        } else if (delta < (2 * 90 * 60)) {
            r = 'about 1 hour ago'
        } else if (delta < (24 * 60 * 60)) {
            r = 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago'
        } else {
            if (delta < (48 * 60 * 60)) {
                r = formatTime(date) + ' yesterday'
            } else {
                r = formatTime(date) + ' ' + formatDate(date)
            }
        }
        return r
    }
})();

function stmUpdate(twitterUserId, containerDiv, circleDiv, contentDiv, msgDiv, btnId, fetchInterval, lang, hashTag, multipleMessageDelay, alternateUrl) {
    if (isNaN(fetchInterval)) fetchInterval = 15000;
    if (typeof twitterUserId == "undefined") twitterUserId = "tp1test";
    if (typeof lang == "undefined") lang = "E";
    if (typeof hashTag == "undefined") hashTag = "#XYZ";
    if (typeof multipleMessageDelay == "undefined") multipleMessageDelay = 3000;
    window.stmParams = {
        id: twitterUserId,
        containerDiv: containerDiv,
        contentDiv: contentDiv,
        circleDiv: circleDiv,
        lang: lang,
        hashTag: hashTag,
        msgDelay: multipleMessageDelay,
        btnId: btnId,
        msgDiv: msgDiv,
        alternateUrl: alternateUrl
    };
    setInterval("runUpdate()", fetchInterval);
    runUpdate()
}
function runUpdate() {
    params = window.stmParams;
    getTwitters(params.containerDiv, {
        id: params.id,
        clearContents: true,
        count: 10,
        withFriends: false,
        ignoreReplies: false,
        newwindow: true,
        lang: params.lang,
        hashTag: params.hashTag,
        prefix: "",
        containerDiv: params.containerDiv,
        contentDiv: params.contentDiv,
        circleDiv: params.circleDiv,
        btnId: params.btnId,
        onTimeout: twitterCallTimeOut,
        timeout: 5
    })
}
window.messageShown = false;
window.msgTimeOutId = NaN;
window.msgStep = 0;
window.msgArray = new Array();
window.newMsg = false;
window.errorTimeout = NaN;

function toggleMessage(msgDiv, updateDiv, btnId) {
    if (window.messageShown) {
        try {
            $(btnId).className = "btInfo off"
        } catch (e) {};
        new Effect.Fade(msgDiv, {
            from: 1,
            to: 0,
            duration: 0.5
        });
        var timeoutCall = "resumeMessages('" + updateDiv + "')";
        window.msgTimeOutId = setTimeout(timeoutCall, 500);
        window.messageShown = false
    } else {
        try {
            $(btnId).className = "btInfo on"
        } catch (e) {};
        pauseMessages(updateDiv);
        new Effect.Appear(msgDiv, {
            from: 0,
            to: 1,
            duration: 0.5,
            delay: 0.5
        });
        window.messageShown = true
    }
}
function pauseMessages(updateDiv) {
    if (window.msgArray.length > 1) clearTimeout(window.msgTimeOutId);
    new Effect.Fade(stmParams.containerDiv, {
        from: 1,
        to: 0,
        duration: 0.5
    })
}
function resumeMessages(updateDiv) {
    if (window.msgArray.length > 1) {
        alternateMessages();
        window.newMsg = true
    } else new Effect.Appear(stmParams.containerDiv, {
        from: 0,
        to: 1,
        duration: 0.5
    })
}
function alternateMessages() {
    var target = $(window.stmParams.contentDiv);
    var title = "";
    if (window.newMsg) {
        new Effect.Appear(window.stmParams.containerDiv, {
            from: 0,
            to: 1,
            duration: 0.5
        });
        window.newMsg = false
    }
    if (window.msgStep == 0) {
        title = window.msgArray[0];
        target.innerHTML = title;
        target.style.display = "none";
        new Effect.Appear(window.stmParams.contentDiv, {
            from: 0,
            to: 1,
            duration: 0.5
        });
        window.msgTimeOutId = setTimeout("alternateMessages()", window.stmParams.msgDelay)
    } else if (window.msgStep == 1 || window.msgStep == 3) {
        new Effect.Fade(window.stmParams.contentDiv, {
            from: 1,
            to: 0,
            duration: 0.5
        });
        window.msgTimeOutId = setTimeout("alternateMessages()", 500)
    } else if (window.msgStep == 2) {
        title = window.msgArray[1];
        target.innerHTML = title;
        target.style.display = "none";
        new Effect.Appear(window.stmParams.contentDiv, {
            from: 0,
            to: 1,
            duration: 0.5
        });
        window.msgTimeOutId = setTimeout("alternateMessages()", window.stmParams.msgDelay)
    }
    window.msgStep++;
    if (window.msgStep == 4) window.msgStep = 0
}
function twitterCallTimeOut(target) {
    var url = window.stmParams.alternateUrl + "?cb=" + Math.random();
    var script = document.createElement('script');
    script.setAttribute('src', url);
    document.getElementsByTagName('head')[0].appendChild(script);
    window.errorTimeout = setTimeout("secondCallTimeOut()", 10000)
}
function secondCallTimeOut() {
    var msg = {
        E: "M&eacute;tro alerts are not available. You can refer to the <a href='http://twitter.com/stminfo'>STM's Twitter account</a> to get the status of m&eacute;tro service.",
        F: "Les alertes m&eacute;tro ne sont pas disponibles. Vous pouvez vous r&eacute;f&eacute;rer au <a href='http://twitter.com/stminfo'>compte Twitter de la STM</a> pour obtenir l'&eacute;tat du service."
    };
    var targetContainer = document.getElementById(window.stmParams.containerDiv);
    var targetContent = document.getElementById(window.stmParams.contentDiv);
    var targetCircle = document.getElementById(window.stmParams.circleDiv);
    targetCircle.className = "red";
    if (targetContent.innerHTML != msg[window.stmParams.lang]) {
        targetContent.innerHTML = msg[window.stmParams.lang]
    }
}
