SurveyManager = function() {
    bindMethods(this);
}

SurveyManager.prototype.initialize = function() {
    /* This gets called before the page is done loading */
    this.survey_num = location.href.replace(/^http:\/\/[\w.]+\/\w+\/(\d+)\D+$/, '$1');
    this.loading_image = '/media/img/loading.gif';
    this.answers = {};
    this.uid = -1;
    this.qcounter = 0;
    this.servicesproxy = new JsonRpcProxy('http://' + location.host + '/services/survey/', 
        ['save_respondent', 'get_questions', 'save_answers' ]);

    var def = this.servicesproxy.get_questions(this.survey_num);
    def.addCallback(this.LoadQuestionSet);
    def.addErrback(this.QuestionLoadFailed);

};

SurveyManager.prototype.QuestionLoadFailed = function(err) {

};

SurveyManager.prototype.OnLoad = function() { 
    connect('register_btn', 'onclick', this, 'SaveRegistration');
};

SurveyManager.prototype.SaveRegistration = function(e) {
    /* If the user sticks in garbage we save it.*/
    if($('id_first_name').value == '') { return this.InsertError('First Name is a required field'); }
    if($('id_last_name').value == '') { return this.InsertError('Last Name is a required field'); }
    if($('id_email').value == '') { return this.InsertError('Email is a required field'); }
    var data = { first_name : $('id_first_name').value, last_name : $('id_last_name').value, 
                email : $('id_email').value, company_name : $('id_company_name').value,
                phone_number : $('id_phone_number').value, salutation : $('id_salutation').value, 
                title : $('id_title').value };
    var def = this.servicesproxy.save_respondent(data);
    def.addCallback(this.SurveyBuild);
};

SurveyManager.prototype.RegisterError = function(e) {
    this.InsertError(e); 
};

SurveyManager.prototype.SurveyBuild = function(sid) {     
    log(sid);
    this.uid = sid;
    this.StartSurvey();   
};

SurveyManager.prototype.InsertError = function(msg) {
    var err_div = DIV({'id':'error', 'class':'error'},P({}, msg));
    if($('error')) {
        swapDOM('error', err_div);
    } else {
        insertSiblingNodesBefore($('survey_box'), err_div);
    }
};

SurveyManager.prototype.StartSurvey = function() {
    log('loading question');
    this.LoadQuestion(this.qids[this.qcounter]);
};

SurveyManager.prototype.LoadQuestionSet = function(qarr) {
    this.questions = {};
    this.qids = [];
    for(var i = 0; i < qarr.data.length; i++) {
        this.questions[qarr.data[i].id] = qarr.data[i];    
        this.qids[i] = qarr.data[i].id;
    }
};

SurveyManager.prototype.LoadQuestion = function(qid) {
    var question = this.questions[qid];
    var template = '';
    var qno = this.qcounter + 1;
    var data = { 'question':question.question, 'qno':qno };
    var pdata = { 'qno':qno, 'prev':false, 'next':false, 'qtotal':this.qids.length };
    if(qno > 1) {
        pdata['prev'] = true;
    }

    if(qno < this.qids.length) {
        pdata['next'] = true;
    }
    log(question.type);
    if( question.type == 'choice' ) {
        template = 'vert_choice_template';
        data['multiple'] = question.data['multiple'];
        data['choices'] = question.data['choices'];
    } else if ( question.type == 'comment' ) {
        template = 'comment_template';
    } else if ( question.type == 'matrix') {
        template = 'matrix_template';
        data['clabels'] = question.data['clabels'];
        data['rlabels'] = question.data['rlabels'];
    }
    
    var page = TrimPath.processDOMTemplate('pagination', pdata);
    var res = TrimPath.processDOMTemplate(template, data);
    $('survey_box').innerHTML = res + page;
    if(pdata['prev']) {
        connect('prev_question', 'onclick', this, 'PrevQuestion');
    }
    if(pdata['next']) {
        connect('next_question', 'onclick', this, 'NextQuestion');
    } else {
        connect('finish', 'onclick', this, 'FinishSurvey');
    }
};

SurveyManager.prototype.PrevQuestion = function(e) {
    log('in prev');
    this.SaveCurrentQuestion();
    if(this.qcounter > 0) {
        this.qcounter -= 1;
    }
    log(this.qcounter);
    this.LoadQuestion(this.qids[this.qcounter]);
};

SurveyManager.prototype.SaveCurrentQuestion = function() {
    var current_type = this.questions[this.qids[this.qcounter]].type; 
    var current_qid = this.qids[this.qcounter];
    if($('prev_question')) {
        disconnectAllTo('prev_question');
    }
    if($('next_question')) {
        disconnectAllTo('next_question');
    }
    this.answers[current_qid] = [];
    if( current_type == 'comment' && $('comment')) {
        this.answers[current_qid] = [ $('comment').value ];   
    } else if ( current_type == 'choice' ) {
        var inputs = getElementsByTagAndClassName('input', null, 'survey_box');
        for( var i = 0; i < inputs.length; i++ ) {
            if(inputs[i].checked) {
                log(inputs[i].value);
                this.answers[current_qid][this.answers[current_qid].length] = inputs[i].value;
            }
        }
        var tareas = getElementsByTagAndClassName('textarea', null, 'survey_box');
        for( var i = 0; i < tareas.length; i++) {
            if(tareas[i].value != '') {
                this.answers[current_qid][this.answers[current_qid].length] = tareas[i].value;
            }
        }
    } else if ( current_type == 'matrix' ) {
        var inputs = getElementsByTagAndClassName('input', null, 'survey_box');
        for( var i = 0; i < inputs.length; i++ ) {
            if(inputs[i].checked) {
                log(inputs[i].value);
                this.answers[current_qid][this.answers[current_qid].length] = inputs[i].value;
            }
        } 
    }
};

SurveyManager.prototype.NextQuestion = function(e) {
    /* First thing is that we save the answer */
    log('Next Question');
    this.SaveCurrentQuestion();
    this.qcounter += 1; 
    this.LoadQuestion(this.qids[this.qcounter]);
};

SurveyManager.prototype.FinishSurvey = function(e) {
    this.SaveCurrentQuestion(); 
    var def = this.servicesproxy.save_answers(this.answers, this.survey_num, this.uid);
    var res = TrimPath.processDOMTemplate('finished', {});
    $('main').innerHTML = res;
};

surveyManager = new SurveyManager();
surveyManager.initialize();
addLoadEvent(surveyManager.OnLoad);
