/**
 * mahalo3-hp.js
 *
 * Javascript specific to the Mahalo three homepage
 *
 * Copyright (c) 2009 Mahalo.com, Inc
 *
 */

// global questions interval (slideshow) id
var questionsIntervalId = 0;

$(document).ready(function(){
    init_hp_question_controls();
    
    if(!isSheriff) {
         init_hp_question_slideshow();
    }
    $("#hp-header-ask-input textarea").focus();
});

/**
 *  Initializes the controls that toggle homepage questions
 */
function init_hp_question_controls() {
    // click event for controls
    $(".hp-questions-controls li").live("click", function(e){
        var controls = $(".hp-questions-controls li");
        var questions = $(".hp-question");
        var question_index = $(".hp-questions-controls li").index(this);
        
        // not last list element (last is link) or active control
        if(question_index < controls.length - 1 && !$(this).hasClass("active")) {
            e.preventDefault();
            
            // stop the slideshow
            clearInterval(questionsIntervalId);
            
            // make the clicked control "active"
            controls.removeClass("active");
            $(this).addClass("active");
            
            // fade the current question out, and when done, fade in the selected question.
            $(".hp-question:visible").fadeOut(function(){
                // fade in selected question.
                $(questions[question_index]).fadeIn();
            });
        }
    });
}

/**
 *  Initializes the questions slideshow by setting a timer that dictates when 
 *  the next method is called.
 */
function init_hp_question_slideshow() {
    questionsIntervalId = setInterval("question_slideshow_next()", 5000); // 5 sec.
}

/**
 *  Advances the questions slideshow to the next "slide"
 */
function question_slideshow_next() {
    var controls = $(".hp-questions-controls li");
    var questions = $(".hp-question");
    var active_question_index = $(".hp-questions-controls li").index($(".hp-questions-controls li.active"));
    
    // determine next index
    if(active_question_index + 1 <= questions.length - 1) {
        // safe to go to next
        next_question_index = active_question_index + 1;
    }
    else {
        // go back to beginning
        next_question_index = 0;
    }
    
    // fade the current question out, and when done, fade in the next question and update controls.
    $(".hp-question:visible").fadeOut(function(){
        // fade in next question.
        $(questions[next_question_index]).show();
        
        // update controls.
        controls.removeClass("active");
        $(controls[next_question_index]).addClass("active");
    });
}
 
