/*
 * Dialogue
*/

window.dialogue = {
    init: function () {
        this.makeDialogue();
    },
    
    dialogueTimer: 0,
    dialogueIndex: 1,
    
    makeDialogue: function () {
		var self = this;
		
        $.ajax({
			url: '/wp-content/themes/thesis_18/custom/ajax_handler.php',
			data: 'task=dialogue',
			type: 'post',
			async: true,
			cache: false,
			success: function(html){
				$('#dialogue').html(html);
				
				self.rotateDialogue();
			}
		});
    },
    rotateDialogue: function () {
        var self = this;

        if ($('#line_' + this.dialogueIndex).length == 0) {
            setTimeout(function(){self.stopDialogue()}, self.timeoutSpeed());
        } else {     
            this.dialogueTimer = setTimeout(function () {
                var thisline = {
                    speaker: $('#line_' + self.dialogueIndex).parents('.person').attr('id'),
                    line: 'line_' + self.dialogueIndex
                };
                
                $(":not(#" + thisline.speaker + ") .bubble")
                    .fadeOut(400, function() { $(this).children().hide(); });
                
                $("#" + thisline.line).show().parent().fadeIn(400);
                
                self.dialogueIndex = self.dialogueIndex + 1;
              
                self.rotateDialogue();

            }, self.timeoutSpeed() );
        }
    },
    stopDialogue: function () {
        var self = this;
        clearTimeout(this.dialogueTimer);
        $("#dialogue .bubble").fadeOut(600);
        self.dialogueIndex = 1;
        self.dialogueTimer = 0;
        setTimeout(function() {
            self.makeDialogue();
        }, 1000);
    },
        
    timeoutSpeed: function() {
        var words = 0;
        if(this.dialogueIndex > 1)
            words = $('#line_' + this.dialogueIndex - 1).text().split(' ').length;
			
        return words * 1300 + 400 + 500; // 400 for animation, 1300 per word, 500 buffer
    }
};

