var survey = {
    questions: {
        template: null,
        add: function() {
            var n = survey.questions.template.clone();
            n.insertAfter($('#survey-form fieldset.q:last'));
            n.show();
            $('#survey-form fieldset:last input[type=text]:first').focus();
            n.find('.action-remove').click(survey.questions.remove);
            n.find('.action-up').click(survey.questions.up);
            n.find('.action-down').click(survey.questions.down);
            n.find('.qtype').val('').change(survey.questions.updateQuestionElements).trigger('change');
            survey.prepareCheckboxBehavior(n);
            n.find('.qa li').hover(survey.questions.hvron, survey.questions.hvroff);
            survey.questions.hideShowOrderActions();
            return false;
        },
        remove: function(){
            if ($('#survey-form fieldset.q').length > 1) {
                $(this).parents('fieldset.q').remove();
                survey.questions.hideShowOrderActions();
            }
        },
        up: function() {
            var p = $(this).parents('fieldset.q');
            p.insertBefore(p.prev('fieldset.q'));
            survey.questions.hvroff.call(this);
        },
        down: function() {
            var p = $(this).parents('fieldset.q');
            p.insertAfter(p.next('fieldset.q'));
            survey.questions.hvroff.call(this);
        },
        updateQuestionElements: function() {
            var q = $(this).parents('fieldset.q');
            var displayAnswers = this.value == 'MULTIPLE_CHOICE' || this.value == 'SCALE_MATRIX';
            q.find('div.answers').css('display', displayAnswers ? 'block' : 'none');
            q.find('div.items').css('display', this.value == 'SCALE_MATRIX' ? 'block' : 'none');
            q.find('div.normal').css('display', this.value == 'SCALE_MATRIX' ? 'none' : 'block');
            q.find('div.matrix').css('display', this.value == 'SCALE_MATRIX' ? 'block' : 'none');
        },
        disableMultipleCheckboxIfNecessary: function() {

        },
        hvron: function() {
            $(this).addClass('hvr');
        },
        hvroff: function() {
            $(this).removeClass('hvr');
        },
        hideShowOrderActions: function() {
            if ($('fieldset.q').length > 1) $('ul.qa').show();
            else $('ul.qa').hide();
        }
    },
    process: function(){
        // hide any error messages before proceeding
        $('div.portalWarningMessage').hide();
        
        var sfs = $('#s');
        var sn = $('input', sfs).val() || $('fieldset.q:first input[type=text]').val();
        var s = {
            key: sfs.attr('key') || null,
            name:sn,
            questions:[]};
        $('fieldset.q').each(function(i){
            var cbAma = $('input[type=checkbox].ama', this);
            var cbFr = $('input[type=checkbox].fr', this);
            var cbReq = $('input[type=checkbox].req', this);
            var ques = {
                id: $(this).attr('qid') || null,
                type: $('select', this).val() || null,
                text: $('div.question textarea', this).val() || null,
                answers:[],
                allowMultipleAnswers: (cbAma && cbAma[0].checked) || false,
                forcedRanking: (cbFr && cbFr[0].checked) || false,
                required: (cbReq && cbReq[0].checked) || false,
                items:[] // for scale matrix questions
            };

            // validate maximum question length
            if (ques.text == null) {
                $('div.question div.portalWarningMessage', this).text('Question text is required').show();
            }
            if (ques.text && ques.text.length > 2000) {
                $('div.question div.portalWarningMessage', this).text('maximum 2000 characters').show();
            }

            var a = $.trim($('div.answers textarea', this).val());
            if (a) {
                var re = a.match(/\n/) ? /\s*\n\s*/ : /\s*,\s*/;
                $.each(a.split(re), function(i, e){
                    ques.answers.push({text:e});
                });
            }

            var it = $.trim($('div.items textarea', this).val());
            if (it) {
                var re = it.match(/\n/) ? /\s*\n\s*/ : /\s*,\s*/;
                $.each(it.split(re), function(i, e){
                    ques.items.push({text:e});
                });
            }

            s.questions.push(ques);
        });

        // see if any error message divs have text in them
        var hasErrors = $('div.portalWarningMessage:visible').length > 0;
        if (hasErrors) {
            $('#hasErrors').show();
        }

        if (!hasErrors && typeof pfn == 'function') pfn(s);
    },
    prepareCheckboxBehavior: function(scope) {
        $('div.answers', scope).each(function(){
            var cbAma = $('input[type=checkbox].ama', this);
            var cbFr = $('input[type=checkbox].fr', this);
            cbFr.click(function(){
                if (this.checked) {
                    cbAma[0].checked = false;
                    cbAma[0].disabled = true;
                } else {
                    cbAma[0].disabled = false;
                }
            });
        });
    }
};
$(function(){
//    $('#survey-form fieldset.q:first input[type=text]:first').focus();
    $('#s_title').focus();
    $('#add-question-link').click(survey.questions.add);
    $('.qtype').change(survey.questions.updateQuestionElements);
    survey.prepareCheckboxBehavior(document);
    $('.action-remove').click(survey.questions.remove);
    $('.action-up').click(survey.questions.up);
    $('.action-down').click(survey.questions.down);
    var st = $('#st');
    $('#s_title').blur(function(){
        st.text(this.value);
    });
    $('.qa li').hover(survey.questions.hvron, survey.questions.hvroff);
    $('.ab').click(survey.process);

    // create template from first fieldset and reset the values
    survey.questions.template = $('#survey-form fieldset.q:first').remove();
    survey.questions.template.attr('qid','');
    survey.questions.template.find('input').val('');
    survey.questions.template.find('textarea').empty();
    survey.questions.template.hide();
});
