(function(v, $){

    // Extend the VMF URL module for getting parameter values
    var url = $.extend({}, vmf.url, {
        getParam: function(name){
            var url = window.location.toString();
            var start = url.indexOf("?");
            if (start < 0) 
                return null;
            var params = url.substring(start + 1, url.length).split("&");
            for (var i in params) {
                var tuple = params[i].split("=");
                if (tuple[0] == name) 
                    return tuple[1];
            }
            return null;
        }
    });
    
    // Get the Decision Tree DOM element
    var _list = v.get("#dec-tree");
    
    // Get the initial visible element from the HTML code
    var _cElm = v.get("#" + _list.attr("fq"));
    
    // Get the start over action
    var _so = _list.attr("so");
    
    // Check if initial element is defined in the URL
    var _fq = url.getParam("fq");
    var _lq = url.getParam("lq");
    var _tq = _fq || _lq;
    if (_tq) {
        // Override the inital element in the HTML code
        if (_cElm) 
            _cElm.removeClass("visible");
        // Update the first element pointer using the _fq parameter
        _cElm = v.get("#" + _tq);
        _cElm.addClass("visible");
        if (_lq) 
            v.get("#dec-btn").hide();
    }
    
    _cElm.addClass("visible");
    
    // The next question/div to show up.
    var _nElm = null;
    
    // The redirect URL if any.
    var _rdUrl = "";
    
    var _end = false;
    
    var _local = false;
    
    // The history array
    var _ht = [];
    
    // The message div
    var _mdiv = v.get("#dec-msg");
    
    // Utility function for clearing radio button
    var _clearRb = function(){
        this.checked = false;
    }
    
    // Utility function for creating the tracking object
    var _getScObj = function(c){
        var o = $.extend({
            topic: window.location.pathname,
            progress: "",
            eventType: "e"
        }, c);
        var steps = [];
        for (var i = 0; i < _ht.length; i++) {
           steps.push(_ht[i].attr("id"));     
        }
        steps.push(_cElm.attr("id"));
        o.progress = steps.join(",");
        return o;
    }
    
    var _inputs = v.get("#dec-tree input");
    _inputs.each(function(){
       var _this = $(this);
       _this.attr("name", _this.parent().parent().attr("id") + "_ans");
    });
    
    // Add event handler to all the questions
    v.addHandler(_inputs, 'click', function(){

        var _this = $(this);
        var _rd = _this.attr("redirect");
        var _lo = _this.attr("local");
        if (_this.attr("end")) {
            _end = true;
        }else{
            _end = false;
        }
        if(_lo && _lo == "true"){
            _local = true;
        }else{
            _local = false;
        }
        if (_rd) {
            _rdUrl = _rd;
            _nElm = null;
        }
        else {
            _rdUrl = "";
            _nElm = v.get("#" + this.value);
        }
        if (_mdiv.css("display")) 
            _mdiv.slideUp();
    });
    
    var _nextBtn = v.get("#dec-next-btn");
    _nextBtn.attr("href", window.location.href);
    // Add event handler for the next button
    v.addHandler(_nextBtn, 'click', function(){
        // Check if the user has made a selection yet
        if (!_nElm) {
            // Check if this is a redirection
            if (_rdUrl != "") {
                if(_local)
                    window.location.href = _rdUrl;
                else
                    window.open(_rdUrl);
                return false;
            }
            _mdiv.children("span").html("Please answer the question first.").end().slideDown("fast");
            return false;
        }
        /* Error message when there is the next element can't be found.
         * (i.e. no more next step)
         */
        if (_nElm.length == 0) {
            alert("Sorry, there is no next step.");
            return false;
        }
        
        if (_ht.length == 0) {
            v.get("#dec-btn li").show();
        }
        
        if (_end) {
            v.get("#dec-btn li.last").hide();
            v.get("#dec-btn li.last").prev().addClass("no-bg");
        }
        
        // Push the current element to the history
        _ht.push(_cElm);
        
        // Make the current element invisible
        _cElm.removeClass("visible");
        // Clear the radio button
        _cElm.find("input").each(_clearRb);
        // Update the current pointer
        _cElm = _nElm;
        // Make the current element visible
        _nElm.addClass("visible");
        // Update the next pointer
        _nElm = null;
        
        return false;
    });
    var _prevBtn = v.get("#dec-previous-btn");
    _prevBtn.attr("href", window.location.href);
    v.addHandler(_prevBtn, 'click', function(){
        _end = false;
        v.get("#dec-btn li.last").show();
        v.get("#dec-btn li.last").prev().removeClass("no-bg");
        
        _cElm.removeClass("visible");
        _cElm.find("input").each(_clearRb);
        _cElm = _ht.pop();
        if (_ht.length == 0) 
            v.get("#dec-btn li:first").hide();
        
        _cElm.addClass("visible");
        _nElm = null;
        return false;
    });
    var _soBtn = v.get("#dec-restart-btn");
    _soBtn.attr("href",(_so != "") ? _so : window.location.href );
    v.addHandler(_soBtn, 'click', function(){

        if (window.sc_qt != null) {
            var o = _getScObj({eventType:'s'});
            sc_qt(_getScObj({eventType:'s'}));
        }
        
        // Redirect to a different URL if Start-Over-Question is specified.
        // and remove event handler for window unload
        if(_so != ""){
            v.removeHandler(v.get(window), 'unload');
            window.location.href = _so;
        }
        
        if(_ht.length == 0){
            return false;
        }
        
        _end = false;
        v.get("#dec-btn li.last").show();
        v.get("#dec-btn li.last").prev().removeClass("no-bg");
        v.get("#dec-btn li:first").hide();
        _cElm.removeClass("visible");
        _cElm.find("input").each(_clearRb);
        _cElm = _ht[0];
        _cElm.addClass("visible");
        _ht = [];
        _nElm = null;
        return false;
    });
    //
    v.get("#dec-btn li").show();
    v.get("#dec-btn li:first").hide();
    // Adding tracking function to the window unload event
    v.addHandler(v.get(window), 'unload', function(){
        if(window.sc_qt != null)
            sc_qt(_getScObj());
    })
})(vmf.dom, jQuery);
