$(function() {
    $('.autogrow').elastic();
    $('.addanswer').click(function() { return addAnswer($(this).closest('.answerwrapper').find('table.data')); });
    $('.addquestion').click(addQuestion);
    $('.removeanswer').click(removeAnswer);
    $('.removequestion').click(removeQuestion);

    $('body').append('<div id="minimalmarkhint" class="popupwrapper"><div class="popup"></div></div>');
    $('.popup', $("#minimalmarkhint")).append($.trim($("#minimalmarkhinttext").val())).css("z-index", "25");
    $('body').append('<div id="emailshint" class="popupwrapper"><div class="popup"></div></div>');
    $('.popup', $("#emailshint")).append($.trim($("#emailshinttext").val())).css("z-index", "25");

    var minimalmarklinkoffset = $('#minimalmarkhintlink').offset();
    var emailshintoffset = $('#emailshintlink').offset();
    //костыли для IE
    if (minimalmarklinkoffset) $("#minimalmarkhint").css('top', minimalmarklinkoffset.top + 15).css('left', minimalmarklinkoffset.left - 20).css('width', '350px');
    if (emailshintoffset) $("#emailshint").css('top', emailshintoffset.top + 15).css('left', emailshintoffset.left - 20).css('width', '350px');




    function addAnswer($answerTable, first, questionId) {
        if (first && first == true) {
            var encodedName = new Array();
            encodedName.push(questionId);
            encodedName.push(0);
        }
        else {
            var encodedName = $answerTable.find('tr:last > td:last > input').attr('name').replace('mq', '').replace('a', '').split('_');
        }
        questionId = encodedName[0];
        var answerId = parseInt(encodedName[1]) + 1;

        var $tr = $('<tr/>').addClass('answerholder');

        var $delTd = $('<a/>').addClass('removeanswer').attr('href', '#');
        $delTd.append($('<img/>').attr('src', (first && first == true) ? 'img/trash_gray.gif' : 'img/trash.gif'));

        var $defaultTd = $('<input/>').attr('type', 'radio').attr('id', 'dq' + questionId + '_' + answerId).val(answerId).attr('name', 'dq' + questionId);

        var $answerTd = $('<textarea/>').addClass('autogrow required').attr('rows', 2).attr('name', 'aq' + questionId + '_a' + answerId);

        var $markTd = $('<input/>').addClass('px50 digits required').attr('type', 'text').attr('name', 'mq' + questionId + '_a' + answerId);

        if (first && first == true) {
            $delTd.addClass('disbled');
            $defaultTd.attr('checked', true);
        }

        $tr.append($('<td>').append($delTd)).append($('<td/>').append($defaultTd)).append($('<td/>').append($answerTd)).append($('<td/>').append($markTd));
        $answerTable.append($tr);
        
            $answerTd.elastic();
        
        if ($answerTable.find('tr').length > 2) {
            var $a = $answerTable.find('tr.answerholder:first > td > a.removeanswer');
            $a.removeClass('disabled');
            $a.find('img').attr('src', 'img/trash.gif');
        }
        $('.removeanswer').click(removeAnswer);

        return false;
    }

    function removeAnswer() {
        if (!$(this).hasClass('disabled')) {
            var $tr = $(this).closest('tr');
            var $answerTable = $tr.closest('table.data');
            $tr.remove();
            if ($answerTable.find('tr').length <= 2) {
                var $a = $answerTable.find('tr.answerholder:first > td > a.removeanswer');
                $a.addClass('disabled');
                $a.find('img').attr('src', 'img/trash_gray.gif');
            }
            var $radio = $answerTable.find('input[type="radio"]');
            if (!$radio.find(':checked').length) {
                $answerTable.find('input[type="radio"]:first').attr('checked', true);
            }
        }
        return false;
    }

    function addQuestion() {
        $lastQuestion = $('.questionanswerwrapper:last');
        var questionId = parseInt($lastQuestion.find('.questionholder > textarea').attr('name').replace('q', '')) + 1;

        var $questionWrapper = $('<div/>').addClass('questionwrapper field');
        var $questionAnswerWrapper = $('<div/>').addClass('questionanswerwrapper');

        var $aRemoveQuestion = $('<a/>').addClass('removequestion').attr('href', '#');
        $aRemoveQuestion.append($('<img/>').attr('src', 'img/trash.gif'));
        $aRemoveQuestion.click(removeQuestion);
        var $questionHolder = $('<div/>').addClass('questionholder');
        var $question = $('<textarea/>').attr('rows', 2).attr('name', 'q' + questionId).addClass('autogrow required');
        $questionHolder.append($('<label/>').attr('for', 'q' + questionId).text(QuestionnaireResources.Question)).append($question);

        var $answerWrapper = $('<div/>').addClass('answerwrapper');
        var $table = $('<table/>').addClass('data');
        var $tr = $('<tr/>');
        $tr.append(addTh(1, '')).append(addTh(10, QuestionnaireResources.Default)).append(addTh(80, QuestionnaireResources.Answer)).append(addTh(9, QuestionnaireResources.Mark));
        $table.append($tr);
        $answerWrapper.append($table);

        $questionWrapper.append($aRemoveQuestion).append($questionHolder);

        $questionAnswerWrapper.append($questionWrapper).append($answerWrapper);
        $answerTable = $answerWrapper.find('table.data');
        addAnswer($answerWrapper.find('table.data'), true, questionId);


        var $addAnswer = $('<a/>').addClass('noul addanswer').attr('href', '#');
        $addAnswer.append($('<img/>').attr('src', 'img/add.gif')).append(QuestionnaireResources.AddAnswer);

        $answerWrapper.append($('<div/>').addClass('linkholder').append($addAnswer));

        $addAnswer.click(function() { return addAnswer($(this).closest('.answerwrapper').find('table.data')); });

        $lastQuestion.after($questionAnswerWrapper);
         $answerTd = $answerTable.find('.answerholder').find('textarea.autogrow');
        $question.elastic();
        $answerTd.elastic();
        var $a = $('.questionanswerwrapper').find(':first .removequestion');
        $a.removeClass('disabled');
        $a.find('img').attr('src', 'img/trash.gif');
        return false;
    }

    function addTh(width, text) {
        return $('<th/>').attr('width', width + '%').text(text);
    }

    function removeQuestion() {
        if (!$(this).hasClass('disabled')) {
            var $qWrapper = $('.questionanswerwrapper');

            $(this).closest('.questionanswerwrapper').remove();

            if ($qWrapper.length <= 2) {
                var $a = $qWrapper.find(':first .removequestion');
                $a.addClass('disabled');
                $a.find('img').attr('src', 'img/trash_gray.gif');
            }
        }
        return false;
    }
});

function showminimalmarkhint() {
    $("#minimalmarkhint").show();
    return false;
}

function hideminimalmarkhint() {
    $("#minimalmarkhint").hide();
    return false;
}

function showemailshint() {
    $("#emailshint").show();
    return false;
}

function hideemailshint() {
    $("#emailshint").hide();
    return false;
}

function selectQuestionLanguage(qid) {
    var url = 'fieldlanguage.ivp/load?required=true&textarea=true&table=QuestionnaireQuestions&field=QuestionXml&QuestionnaireId=' + $('#id').val() + '&id=' + qid;
    openDialog(url, 'selectlanguage', { width: 900, height: 650 });
    return false;
}

function selectQuestionnaireLanguage() {
    var url = 'fieldlanguage.ivp/load?required=true&table=Questionnaires&field=NameXml&id=' + $('#id').val();
    openDialog(url, 'selectlanguage', { width: 900, height: 650 });
    return false;
}

function selectAnswerLanguage(aid, qid) {
    var url = 'fieldlanguage.ivp/load?required=true&textarea=true&table=QuestionnaireAnswers&field=AnswerXml&QuestionId=' + qid + '&id=' + aid;
    openDialog(url, 'selectlanguage', { width: 900, height: 650 });
    return false;
}