Ticker = {};

Ticker.speed = 100;
Ticker.startdelay = 0;
Ticker.wait = 4000;
Ticker.data = [];
Ticker.newWindow = false;

Ticker.id = "Ticker.main";
Ticker.linkId = "Ticker.link";
Ticker.timer = null;
Ticker.index = -1;
Ticker.position = 0;
Ticker.waitchar = '.';
Ticker.trailchar = '_';
Ticker.addwaitchar = true;


Ticker.stop = function() {
    clearTimeout(Ticker.timer);
}

Ticker.start = function() {
    Ticker.timer = setTimeout(Ticker.next, Ticker.startdelay);
}
Ticker.next = function() {
    clearTimeout(Ticker.timer);
    Ticker.fillinRunning = false;
    var tk = document.getElementById(Ticker.id);
    tk.innerHTML = '&nbsp;';
    Ticker.incIndex();
    var tklink = document.getElementById(Ticker.linkId);
    if (tklink) {
        tklink.onclick = function() {
        };
        if (typeof(Ticker.data[Ticker.index]) == 'object') {
            //might have a link in it
            if (Ticker.data[Ticker.index].link) {
                Ticker.setClick(tklink);
            }
        }
    }
    Ticker.timer = setTimeout(Ticker.outputNextChar, 0);
}

Ticker.setClick = function(elm) {
    elm.href = Ticker.data[Ticker.index].link;
    if(Ticker.newWindow){
        elm.target = "_blank";
    }    
}

Ticker.fillin = function() {
    if (Ticker.fillinRunning) {
        var elm = document.getElementById(Ticker.id);
        elm.innerHTML += Ticker.waitchar;
        Ticker.timer = setTimeout(Ticker.fillin, Ticker.speed * 10);
    }
}

Ticker.outputNextChar = function() {
    if (Ticker.position > (Ticker.getText().length - 1)) {
        //call the wait and then reload	
        if (Ticker.addwaitchar) {
            Ticker.fillinRunning = true;
            Ticker.timer = setTimeout(Ticker.fillin, Ticker.speed * 10);
        }
        setTimeout(Ticker.next, Ticker.wait);
    } else {
        var elm = document.getElementById(Ticker.id);
        if (Ticker.trailchar.length > 0) {
            if (elm.innerHTML.charAt(elm.innerHTML.length) == Ticker.trailchar) {
                //safety - but it will break if the string has the trail char in it!
                Ticker.removeLastChar();
            }
        }
        var ch = Ticker.getText().charAt(Ticker.position++);
        elm.innerHTML += ch;
        if (Ticker.trailchar.length > 0) {
            elm.innerHTML += Ticker.trailchar;
            setTimeout(Ticker.removeLastChar, Ticker.speed / 2);
        }
        Ticker.timer = setTimeout(Ticker.outputNextChar, Ticker.speed);
    }
}

Ticker.removeLastChar = function() {
    var elm = document.getElementById(Ticker.id);
    elm.innerHTML = elm.innerHTML.substr(0, elm.innerHTML.length - 1);
}
Ticker.getText = function() {
    var obj = Ticker.data[Ticker.index];
    if (typeof(obj) == 'object') {
        return obj.text;
    }
    return obj;
}

Ticker.incIndex = function() {
    Ticker.index++;
    if (Ticker.index > (Ticker.data.length - 1)) {
        Ticker.index = 0;
    }
    Ticker.position = 0;
}

