﻿/* - Typerwriter class - */
/* - Should protect setLetter and finnish but unfortunately i can't get protected methods to work with delays - */

var Typewriter = new Class({

    //implements
    Implements: [Options],

    //options
    options: {
        container: $$('body')[0],
        message: '',
        delay: 150,
        cursor: 0,
        items: 0,
        selected: 0
    },

    //initialization
    initialize: function(options) {
        //set options
        this.setOptions(options);
    },

    //start the typewriter
    start: function() {
        this.displayNextItem();
        this.updateCursor.periodical(8000, this);
       
    },

    //displayNextItem
    displayNextItem: function() {
        this.options.container[this.options.selected].getParent("li").setStyle("display", "block");

        //for every letter
        for (x = 0; x < this.options.message[this.options.selected].innerHTML.length; x++) {
            //spit out the letter
            var id = this.setLetter.delay(this.options.delay * x, this);
        }
    },

    //place the newest letter in the container
    setLetter: function() {

        if (!Browser.Engine.trident)
            this.options.container[this.options.selected].set('html', this.options.container[this.options.selected].get('html').replace(" _", "") + '' + this.options.message[this.options.selected].innerHTML.charAt(this.options.cursor) + " _");
        else
            this.options.container[this.options.selected].set('html', this.options.container[this.options.selected].get('html').replace("&nbsp;_", "") + '' + this.options.message[this.options.selected].innerHTML.charAt(this.options.cursor) + "&nbsp;_");

        //increment cursor
        this.options.cursor++;

        //Oncomplete go to next item//
        if (this.options.message[this.options.selected].innerHTML.length == this.options.cursor) {
            //this.updateCursor();
        }
    },

    //updateCursor
    updateCursor: function() {
        this.options.container[this.options.selected].set("html", "");
        this.options.container.each(
			function(item, index) {
			    item.getParent("li").setStyle("display", "none");
			});
        this.options.cursor = 0;
        this.options.selected++;
        if (this.options.selected == this.options.items)
            this.options.selected = 0;

        this.displayNextItem();
    }

});
 
