/**
* 
*/

require(["solutions/qtAuthor/js/jquery-1.9.1.js", "dojo/domReady!"], function () { });
require(["solutions/qtAuthor/js/jquery-ui-1.10.3.custom.js", "dojo/domReady!"], function () { });
require(["solutions/qtAuthor/js/jquery.countdown.js", "dojo/domReady!"], function () { });
require(["solutions/qtAuthor/js/jquery.countdown-ru.js", "dojo/domReady!"], function () { });
require(["solutions/qtAuthor/js/jquery.ui.touch-punch.min.js", "dojo/domReady!"], function () { });
require(["solutions/authoring/js/MapArea/common.js", "dojo/domReady!"], function () { });
//require(["solutions/qtAuthor/js/jquery.iframe-post-form.js", "dojo/domReady!"], function () { });


var _currentAnswer = undefined;

function goToLink(mainContext, addContext, filterContext) { 
      window.open(window.location.toString()+addContext, "_blank"); 
  } 

function goToTest(mainContext, addContext, filterContext) { 
  var host = window.location.host;
  var pathname = window.location.pathname;
  var protocol = window.location.protocol;
  window.open(protocol + "//" + host + pathname +"?userdata=qtAuthor"+addContext,'_blank');
  }   
  
function prepareClassifDnD() {

    // получаем ответы из модели
    var model = document.getElementById("4_mainModel");
    var instance = model.getInstanceDocument("4_mainInstance");
    var answers = instance.getElementsByTagName("answer");
    for (var i = 0; i < answers.length; ++i) {
        var answer = answers[i];  // Calling myNodeList.item(i) isn't necessary in JavaScript
        $('div.answers').append("<div id='d" + answer.attributes.getNamedItem("DestructorID").value + "' class='answer'>" + (answer.text == undefined ? answer.textContent : answer.text) + '</div>'); // Content
    }

    var destructors = instance.getElementsByTagName("option");
  
  var showCorrect = instance.getElementsByTagName("showCorrect")[0];

    for (var j = 0; j < destructors.length; ++j) {
        var destructor = destructors[j];
        var answ = destructor.getElementsByTagName("answ")[0];
        var opt = destructor.getElementsByTagName("opt")[0];
        var answText = answ.textContent != undefined ? answ.textContent : answ.text;
        var answDestructorID = answ.attributes.getNamedItem("DestructorID").value;
        var optText = opt.textContent != undefined ? opt.textContent : opt.text;
        $("#tblQuestion").append('<tr id="vd' + destructor.attributes.getNamedItem("id").value + '" class="destructor"><td style="padding: 10px; border: 1px solid #DDDDDD"><div class="values" style="width: 15px;">' + destructor.attributes.getNamedItem("letter").value + '</div></td><td style="width: 20%; padding: 10px; border: 1px solid #DDDDDD">              <div class="values" style="float: left; white-space: normal !important">' + optText + '</div></td><td class="acceptAnswers" style="border: 1px solid #DDDDDD; margin:10px;">' + (answText != '' ? '<div id="d' + answDestructorID + '" class="answer">' + answText + '</div>' : '') + '</td></tr>');
    if (showCorrect.textContent == 'true' || showCorrect.text == 'true'){
      var correctAnsw = destructor.getElementsByTagName("correctAnsw")[0]
      var correctAnswText = correctAnsw.textContent != undefined ? correctAnsw.textContent : correctAnsw.text;
      var correctAnswDestructorID = correctAnsw.attributes.getNamedItem("DestructorID").value;
      $("#tblCorrectQuestion").append('<tr id="vc' + destructor.attributes.getNamedItem("id").value + '" class="destructor"><td style="padding: 10px; border: 1px solid #DDDDDD"><div class="values" style="width: 15px;">' + destructor.attributes.getNamedItem("letter").value + '</div></td><td style="width: 20%; padding: 10px; border: 1px solid #DDDDDD">              <div class="values" style="float: left; white-space: normal !important">' + optText + '</div></td><td class="acceptAnswers" style="border: 1px solid #DDDDDD; margin:10px;">' + (correctAnswText != '' ? '<div id="c' + correctAnswDestructorID + '" class="answer">' + correctAnswText + '</div>' : '') + '</td></tr>');
    }    
  
  }

    var status = instance.getElementsByTagName("testingStatus")[0];
    if (status.textContent == '0' || status.text == '0') {


        $('div.answer').on('click', function (arg) {
            onDivAnswerClick(arg);
        });

        $('div.answers').on('click', function (arg) {
            if (_currentAnswer != undefined && _currentAnswer != null && _currentAnswer.parentElement.className != "answers ui-droppable") {
                _currentAnswer.remove();
                _currentAnswer = undefined;
            }
        });

        $('td.acceptAnswers').on('click', function (arg) {
            if (_currentAnswer != undefined && _currentAnswer != null) {
                $(this).empty();
                $(this).append($(_currentAnswer).clone().on('click', function (arg) {
                    onDivAnswerClick(arg);
                }).draggable({
                    helper: 'clone',
                    opacity: 0.5
                }));
                $(_currentAnswer).css('border', '');
                _currentAnswer = undefined;
            }
        });


        $('div.answer').draggable({
            helper: 'clone',
            opacity: 0.5
        });

        $('td.acceptAnswers').droppable({
            tolerance: 'pointer',
            accept: 'div.answer',
            drop: function (event, ui) {
                // $('div.answers').append($(this).children().clone());
        $(this).empty();
                $(this).append($(ui.draggable).clone().on('click', function (arg) {
                    onDivAnswerClick(arg);
                }).draggable({
                    helper: 'clone',
                    opacity: 0.5
                }));
            }
        });

        $('div.answers').droppable({
            tolerance: 'pointer',
            accept: 'div.answer',
            drop: function (event, ui) {
                // $(this).append(ui.draggable.clone());
                if (ui.draggable.parent()[0] != $('div.answers')[0]) {
                    ui.draggable.remove();
                }
            }
        });
    }
}

function saveClassifAnswerToModel() {

    var model = document.getElementById("4_mainModel");
    var instance = model.getInstanceDocument("4_mainInstance");
    var nodeAnswers = instance.getElementsByTagName("result")[0];
  nodeAnswers.textContent = '';
    $("tr.destructor").each(function (index, tr) {
        var variantDestructorID = tr.id.substring(2);
    var startId = tr.id.substring(0,2);
    if (startId == 'vd')
    {
      if ($(tr).find('div.answer')[0] != undefined) {
        var destructorID = $(tr).find('div.answer')[0].id.substring(1);
        var nodeAnswer = nodeAnswers.appendChild(nodeAnswers.ownerDocument.createElement('option2'))
        nodeAnswer.setAttribute("VariantDestructorID", variantDestructorID);
        nodeAnswer.setAttribute("DestructorID", destructorID);
      }
    }
    });
    model.rebuild();
    model.recalculate();
    model.refresh();
}

function onDivAnswerClick(arg) {
    $('div.answer').css('border', '');
    if (_currentAnswer != arg.currentTarget) {
        $(arg.currentTarget).css('border', '4px solid #00FF00');
        _currentAnswer = arg.currentTarget;
        arg.stopPropagation();
    }
}

function OnPartSelected(partName) {
    alert(partName);
    _currentPartName = partName;
}

function prepareDnD() {

    // получаем ответы из модели
    var model = document.getElementById("4_mainModel");
    var instance = model.getInstanceDocument("4_mainInstance");
    var answers = instance.getElementsByTagName("answer");
    for (var i = 0; i < answers.length; ++i) {
        var answer = answers[i];  // Calling myNodeList.item(i) isn't necessary in JavaScript
        $('div.answers').append("<div id='d" + answer.attributes.getNamedItem("DestructorID").value + "' class='answer'>" + (answer.text == undefined ? answer.textContent : answer.text) + '</div>'); // Content
    }

    var destructors = instance.getElementsByTagName("option");

  var showCorrect = instance.getElementsByTagName("showCorrect")[0];
  
  
    for (var j = 0; j < destructors.length; ++j) {
        var destructor = destructors[j];
        var answ = destructor.getElementsByTagName("answ")[0];
        var opt = destructor.getElementsByTagName("opt")[0];
    
        var answText = answ.textContent != undefined ? answ.textContent : answ.text;
        var answDestructorID = answ.attributes.getNamedItem("DestructorID").value;
        var optText = opt.textContent != undefined ? opt.textContent : opt.text;
        $("#tblQuestion").append('<tr id="vd' + destructor.attributes.getNamedItem("id").value + '" class="destructor"><td style="padding: 10px; border: 1px solid #DDDDDD"><div class="values" style="width: 15px;">' + destructor.attributes.getNamedItem("letter").value + '</div></td><td style="width: 20%; padding: 10px; border: 1px solid #DDDDDD">              <div class="values" style="float: left; white-space: normal !important">' + optText + '</div></td><td class="acceptAnswers" style="border: 1px solid #DDDDDD; margin:10px;">' + (answText != '' ? '<div id="d' + answDestructorID + '" class="answer">' + answText + '</div>' : '') + '</td></tr>');
    
    if (showCorrect.textContent == 'true' || showCorrect.text == 'true'){
      var correctAnsw = destructor.getElementsByTagName("correctAnsw")[0]
      var correctAnswText = correctAnsw.textContent != undefined ? correctAnsw.textContent : correctAnsw.text;
      var correctAnswDestructorID = correctAnsw.attributes.getNamedItem("DestructorID").value;
      $("#tblCorrectQuestion").append('<tr id="vc' + destructor.attributes.getNamedItem("id").value + '" class="destructor"><td style="padding: 10px; border: 1px solid #DDDDDD"><div class="values" style="width: 15px;">' + destructor.attributes.getNamedItem("letter").value + '</div></td><td style="width: 20%; padding: 10px; border: 1px solid #DDDDDD">              <div class="values" style="float: left; white-space: normal !important">' + optText + '</div></td><td class="acceptAnswers" style="border: 1px solid #DDDDDD; margin:10px;">' + (correctAnswText != '' ? '<div id="c' + correctAnswDestructorID + '" class="answer">' + correctAnswText + '</div>' : '') + '</td></tr>');
    }
  }

    var status = instance.getElementsByTagName("testingStatus")[0];
    if (status.textContent == '0' || status.text == '0') {


        $('div.answer').on('click', function (arg) {
            $('div.answer').css('border', '');
            if (_currentAnswer != arg.currentTarget) {
                $(arg.currentTarget).css('border', '4px solid #00FF00');
                _currentAnswer = arg.currentTarget;
                arg.stopPropagation();
            }
        });

        $('div.answers').on('click', function (arg) {
            if (_currentAnswer != undefined) {
                $(this).append(_currentAnswer);
                $(_currentAnswer).css('border', '');
                _currentAnswer = undefined;
             }
        });

        $('td.acceptAnswers').on('click', function (arg) {
            $('div.answers').append($(this).children());
            if (_currentAnswer != undefined) {
                $(this).append(_currentAnswer);
                $(_currentAnswer).css('border', '');
                _currentAnswer = undefined;
            }
        });


        $('div.answer').draggable({
            helper: 'clone',
            opacity: 0.5
        });

        $('td.acceptAnswers').droppable({
            tolerance: 'pointer',
            accept: 'div.answer',
            drop: function (event, ui) {
                $('div.answers').append($(this).children());
                $(this).append(ui.draggable);
            }
        });

        $('div.answers').droppable({
            tolerance: 'pointer',
            accept: 'div.answer',
            drop: function (event, ui) {
                $(this).append(ui.draggable);
            }
        });
    }
}


function prepareSort() {

    // получаем ответы из модели
    var answer2destructor = {};
  var correctAnswerToDestructor = {};
    var model = document.getElementById("4_mainModel");
    var instance = model.getInstanceDocument("4_mainInstance");
    var destructors = instance.getElementsByTagName("option");
  var showCorrect = instance.getElementsByTagName("showCorrect")[0];
    for (var i = 0; i < destructors.length; ++i) {
        var destructor = destructors[i];  // Calling myNodeList.item(i) isn't necessary in 
        var answ = destructor.getElementsByTagName("answ")[0];
        var opt = destructor.getElementsByTagName("opt")[0];
    
        var answText = answ.textContent != undefined ? answ.textContent : answ.text;
        var optText = opt.textContent != undefined ? opt.textContent : opt.text;
    

        if (answText == '') {
            $('div.answers').append('<div id="' + destructor.attributes.getNamedItem("id").value + '" class="answer">' + optText + '</div>');
        } else {
            answer2destructor[answText] = destructor;
        }
    if (showCorrect.textContent == 'true' || showCorrect.text == 'true'){
      var correctAnswer = destructor.getElementsByTagName("correctAnsw")[0];
      var correctText = correctAnswer.textContent != undefined ? correctAnswer.textContent : correctAnswer.text;
      correctAnswerToDestructor[correctText] = destructor
    }
    }

    var answers = instance.getElementsByTagName("answer");
  

    for (var j = 0; j < answers.length; ++j) {
        var answer = answers[j];
        // найти дестрактор с заданным ответом
        var answerText = (j + 1).toString();
        destructor = answer2destructor[answerText];
    
        $("#tblQuestion").append('<tr id="v'+answerText+'" class="destructor"><td style="width: 10px; padding: 10px; border: 1px solid #DDDDDD"><div class="values" style="font-weight: bold; float: left; white-space: normal !important"><b>' + answerText + '</b></div></td><td class="acceptAnswers" style="border: 1px solid #DDDDDD; margin:10px;">' + (destructor ? '<div id="' + destructor.attributes.getNamedItem("id").value + '" class="answer">' + getTextContent(destructor.getElementsByTagName("opt")[0]) + '</div>' : '') + '</td></tr>');
    if (showCorrect.textContent == 'true' || showCorrect.text == 'true'){
      correctDestructor = correctAnswerToDestructor[answerText];
      $("#tblCorrectQuestion").append('<tr id="c'+answerText+'" class="destructor"><td style="width: 10px; padding: 10px; border: 1px solid #DDDDDD"><div class="values" style="font-weight: bold; float: left; white-space: normal !important"><b>' + answerText + '</b></div></td><td class="acceptAnswers" style="border: 1px solid #DDDDDD; margin:10px;">' + (correctDestructor ? '<div id="' + correctDestructor.attributes.getNamedItem("id").value + '" class="answer">' + getTextContent(correctDestructor.getElementsByTagName("opt")[0]) + '</div>' : '') + '</td></tr>');

    }    
  
  }

    var status = instance.getElementsByTagName("testingStatus")[0];
    if (status.textContent == '0' || status.text == '0') {

        $('div.answer').on('click', function (arg) {
            $('div.answer').css('border', '');
            if (_currentAnswer != arg.currentTarget) {
                $(arg.currentTarget).css('border', '4px solid #00FF00');
                _currentAnswer = arg.currentTarget;
                arg.stopPropagation();
            }
        });

        $('div.answers').on('click', function (arg) {
            if (_currentAnswer != undefined) {
                $(this).append(_currentAnswer);
                $(_currentAnswer).css('border', '');
                _currentAnswer = undefined;
            }
        });

        $('td.acceptAnswers').on('click', function (arg) {
            $('div.answers').append($(this).children());
            if (_currentAnswer != undefined) {
                $(this).append(_currentAnswer);
                $(_currentAnswer).css('border', '');
                _currentAnswer = undefined;
            }
        });

        $('div.answer').draggable({
            helper: 'clone',
            opacity: 0.5
        });

        $('td.acceptAnswers').droppable({
            tolerance: 'pointer',
            accept: 'div.answer',
            drop: function (event, ui) {
                $('div.answers').append($(this).children());
                $(this).append(ui.draggable);
            }
        });

        $('div.answers').droppable({
            tolerance: 'pointer',
            accept: 'div.answer',
            drop: function (event, ui) {
                $(this).append(ui.draggable);
            }
        });
    }
}

function getTextContent(obj) {
    return obj.textContent != undefined ? obj.textContent : obj.text;
}

// сохранение данных html-формы в xml-объект модели XForm
function saveAnswerToModel() {

    var model = document.getElementById("4_mainModel");
    var instance = model.getInstanceDocument("4_mainInstance");
    var nodeAnswers = instance.getElementsByTagName("result")[0];
  nodeAnswers.textContent = '';
    $("tr.destructor").each(function (index, tr) {
        var variantDestructorID = tr.id.substring(2);
    var startId = tr.id.substring(0,2);
    if (startId == 'vd')
    {
      if ($(tr).find('div.answer')[0] != undefined) {
        var destructorID = $(tr).find('div.answer')[0].id.substring(1);
        var nodeAnswer = nodeAnswers.appendChild(nodeAnswers.ownerDocument.createElement('option2'))
        nodeAnswer.setAttribute("VariantDestructorID", variantDestructorID);
        nodeAnswer.setAttribute("DestructorID", destructorID);
      }
    }
    });
    model.rebuild();
    model.recalculate();
    model.refresh();
}


// сохранение данных html-формы в xml-объект модели XForm
function saveSortAnswerToModel() {

    var model = document.getElementById("4_mainModel");
    var instance = model.getInstanceDocument("4_mainInstance");
    var nodeAnswers = instance.getElementsByTagName("result")[0];
  nodeAnswers.textContent = '';
    $("tr.destructor").each(function (index, tr) {
    var startId = tr.id.substring(0,1);
    if (startId == 'v')
    {
      if ($(tr).find('div.answer')[0] != undefined) {
        var id = $(tr).find('div.answer')[0].id;
        var answer = $(tr).find('div.values')[0].innerText;
        var nodeAnswer = nodeAnswers.appendChild(nodeAnswers.ownerDocument.createElement('option2'))
        nodeAnswer.setAttribute("id", id);

        if (nodeAnswer.textContent != null)
          nodeAnswer.textContent = answer;
        else
          nodeAnswer.text = answer;
      }
    }
    });
    model.rebuild();
    model.recalculate();
    model.refresh();
}


function injectCounter(toDate, fromDate) {
    if (fromDate && fromDate != undefined) {
        $('#timerDiv').countdown({ until: toDate, from: fromDate, format: 'MS' });
    } else {
        $('#timerDiv').countdown({ until: toDate, format: 'MS' });
    }

    var model = document.getElementById("4_mainModel");
    var instance = model.getInstanceDocument("4_mainInstance");
    var nodeAlgo = instance.getElementsByTagName("testingAlgorithm")[0];

  if (nodeAlgo.textContent == 'Тестирование для самоконтроля' || nodeAlgo.text == 'Тестирование для самоконтроля') {
    $('#showcaseHeaderContainer').css('background', 'white')
    $('body').css('background', 'white');
    $('.xforms-value').css('background', 'white')
  }

}

function clearWordStyles() {
    $('.MsoNormal').removeAttr('style');
    $('.MsoNormal > *').css('font-size', '12pt');
}

function showcaseShowMessage(mainContext, addContext, filterContext) {
    window.alert('Выделена строка: ' + addContext);
}

function showcaseShowAddContext(mainContext, addContext, filterContext) {
    window.alert('add_context = ' + addContext);
}

function showcaseShowFilterContext(mainContext, addContext, filterContext) {
    window.alert('filter_context = ' + filterContext);
}

function showcaseShowMainContext(mainContext, addContext, filterContext) {
    window.alert('main_context = ' + mainContext);
}

function showcaseShowAllContexts(mainContext, addContext, filterContext) {
    window.alert('main_context = ' + mainContext + '\n' + 'add_context = ' +
      addContext + '\n' + 'filter_context = ' + filterContext);
}

function imageFilePicker(callback, value, meta) {               
    tinymce.activeEditor.windowManager.open({
        title: 'Image Picker',
        url: 'fc0001/pictures',
        width: 650,
        height: 550,
        buttons: [{
            text: 'Insert',
            onclick: function () {
                tinymce.activeEditor.windowManager.close();
            }
        }, {
            text: 'Close',
            onclick: 'close'
        }],
    }, {
        oninsert: function (url) {
            callback(url);
            console.log('done');
        },
    });
}

/* ******* Map Area Draw   ******* */
/* ******* @ Serhio Magpie ******* */

/* serdidg@gmail.com      */
/* http://screensider.com */

var Painter = new function(){
  var that = this,
    isCanvas = false,
    nodes,
    context,
    points = [],
    areas = [],
    answers,
    answer,
    model,
    instance;
  var colors = [
    {'r':'0', 'g':'172', 'b':'239'},
    {'r':'255', 'g':'0', 'b':'0'},
    {'r':'255', 'g':'255', 'b':'0'},
    {'r':'0', 'g':'255', 'b':'0'},
    {'r':'0', 'g':'0', 'b':'255'},
    {'r':'251', 'g':'140', 'b':'0'},
    {'r':'0', 'g':'137', 'b':'123'},  
    {'r':'245', 'g':'0', 'b':'100'},
    {'r':'142', 'g':'36', 'b':'170'},
    {'r':'109', 'g':'76', 'b':'65'},
    {'r':'96', 'g':'125', 'b':'139'},
    {'r':'0', 'g':'172', 'b':'193'},
    {'r':'233', 'g':'30', 'b':'99'},    
    {'r':'67', 'g':'160', 'b':'71'}
  ];
  
  that.getHexColor = function(index){
    return '#'+colors[index]['r'].toString(16)+colors[index]['g'].toString(16)+colors[index]['b'].toString(16);
  }
    
  var checkCanvas = function(){
    if(nodes['canvas'].getContext){
      isCanvas = true;
      nodes['canvas'].width = nodes['draw'].offsetWidth;
      nodes['canvas'].height = nodes['draw'].offsetHeight;
      context = nodes['canvas'].getContext('2d');
    }else{
      _.remove(nodes['canvas']);
    }
  };
  
  var clearAllBtn = function(){
    nodes['clear_all'] = nodes['buttons'].appendChild(_.node('input', {'type':'button', 'value':'Очистить всё'}));
    nodes['clear_all'].onclick = clearAll;
  };
    
  var addBtn = function(){
    nodes['add'] = nodes['buttons'].appendChild(_.node('input', {'type':'button', 'value':'Добавить область'}));
    nodes['add'].onclick = add;
  };
  
  var saveBtn = function(){
    nodes['save'] = nodes['buttons'].appendChild(_.node('input', {'type':'button', 'value':'Сохранить область'}));
    nodes['save'].onclick = save;
  };
  
  var clearAll = function(){
    clear();
    _.clearNode(nodes['info']);
    points = [];
    areas = [];
    // Clear preview from points or canvas
    if(isCanvas){
      clearCanvas();
    }else{
      clearPoints();
    }
  };
    
  var add = function(){
    _.remove(nodes['add']);
    _.addClass(nodes['preview'], 'draw');
    _.addEvent(nodes['draw'], 'mousedown', addPoint);
    // Render buttons
    saveBtn();
  };
  
  var save = function(){
    clear();
    areas.push(_.clone(points));
    renderAnswer(points);
    points = [];
//    renderInfo();
  };
  
  var clear = function(){
    _.remove(nodes['add']);
    _.remove(nodes['save']);
    _.removeClass(nodes['preview'], 'draw');
    _.removeEvent(nodes['draw'], 'mousedown', addPoint);
    addBtn();
  }
  
  var clearCanvas = function(){
    context.clearRect(0, 0, nodes['canvas'].width, nodes['canvas'].height);
  };
  
  var clearPoints = function(){
    _.clearNode(nodes['points']);
  };
  
  var addPoint = function(e){
    var e = _.getEvent(e),
      offset = _.getOffset(nodes['draw']),
      x = e.clientX + _.getDocScrollLeft() - offset[0],
      y = e.clientY + _.getDocScrollTop() - offset[1];
    // Push point to area array
    points.push({'x' : x, 'y' : y});
    // Draw point
    if(isCanvas){
      drawCanvasAll();
    }else{
      drawHtmlPoint(x,y);
    }
    // Prevent drag event
    e.preventDefault && e.preventDefault();
    return false;
  };
  
  var drawHtmlPoint = function(x, y){
    var node = nodes['points'].appendChild(_.node('div', {'class':'point'}));
    node.style.top = y-1+'px';
    node.style.left = x-1+'px';
  };
  
  var drawCanvasPoints = function(o, areaColorIndex){
    // Draw lines
    var rgb = ''+colors[areaColorIndex]['r']+','+colors[areaColorIndex]['g']+','+colors[areaColorIndex]['b'];
    context.fillStyle = 'rgba('+rgb+',0.2)';
//    context.fillStyle = 'rgba(0,172,239,0.2)';
    context.lineWidth = 1;
    context.strokeStyle = 'rgba('+rgb+',0.8)';
//    context.strokeStyle = 'rgba(0,172,239,0.8)';
    context.beginPath();
    for(var i = 0, l = o.length; i < l; i++){
      if(i == 0){
        context.moveTo(o[i]['x'], o[i]['y']);
      }else{
        context.lineTo(o[i]['x'], o[i]['y']);
      }
    }
    context.closePath();
    context.fill();
    context.stroke();
    // Draw points
    context.fillStyle = 'rgba('+rgb+',0.8)';
//    context.fillStyle = 'rgba(0,139,191,0.8)';
    for(var i = 0, l = o.length; i < l; i++){
      context.fillRect(o[i]['x']- 2, o[i]['y']- 2, 4, 4);
    }
  };
  
  var drawCanvasAll = function(){
    clearCanvas();
    // Draw saved areas
    var i = -1;
    for(i = 0, l = areas.length; i < l; i++){
      drawCanvasPoints(areas[i], i);
    }
    // Draw current area
    if (i==-1) {++i};
    drawCanvasPoints(points, i);
  };
  
  that.drawAnswerPointsAll = function(){
    areas = [];
    points = [];
    var items = answers.getElementsByTagName('answer');
    var item, i=0, j=0, len=0, coords='', coordsText='', a=[], answerColor='';
    for (i = 0; i < items.length; ++i) {
      item = items[i];
      coords = item.getElementsByTagName('destructor')[0];
      coordsText = coords.textContent != undefined ? coords.textContent : coords.text;
      a = coordsText.split(',');
//      console.log(a);
      for (j = 0, len = a.length; j < len; j = j+2) {
        points.push({'x' : +a[j], 'y' : +a[j+1]});
      }     
      areas.push(_.clone(points));
//      console.log(areas.length);
      points = [];
      answerColor = item.getElementsByTagName('color')[0];
      setValue(answerColor, ''+colors[i]['r']+','+colors[i]['g']+','+colors[i]['b']);
//      setValue(answerColor, that.getHexColor(i));
    }
    if (areas.length > 0) {
      drawCanvasAll();
      refreshXForm();
    }
  }
  
  var renderInfo = function(){
    var text;
    
    _.clearNode(nodes['info']);
    
    nodes['info'].appendChild(_.node('span', '<map>'));
    nodes['info'].appendChild(_.node('br'));
    
    for(var i = 0, l = areas.length; i < l; i++){
      if(areas[i].length > 0){
        text = '<area shape="poly" coords="';
        for(var i2 = 0, l2 = areas[i].length; i2 < l2; i2++){
          if(i2 > 0){
            text += ',';
          }
          text += areas[i][i2]['x'] + ',' + areas[i][i2]['y'];
        }
        text += '">';
        nodes['info'].appendChild(_.node('span', text));
        nodes['info'].appendChild(_.node('br'));
      }
    }    
    nodes['info'].appendChild(_.node('span', '</map>'));
  };
  
  var renderAnswer = function(areaPoints){
    var coords='';
    if (areaPoints.length > 0){
      for(var i2 = 0, l2 = areaPoints.length; i2 < l2; i2++){
        if(i2 > 0){
          coords += ',';
        }
        coords += areaPoints[i2]['x'] + ',' + areaPoints[i2]['y'];
      }
    }
//    console.log(coords);
    if (coords != '') {
      var answerItem = answers.appendChild(answer.cloneNode(true));
      var coordsItem = answerItem.getElementsByTagName("destructor")[0];
      setValue(coordsItem, coords);
      var answerColor = answerItem.getElementsByTagName('color')[0];
      var i = areas.length-1;
      setValue(answerColor, ''+colors[i]['r']+','+colors[i]['g']+','+colors[i]['b']);
      refreshXForm();
    }
  };
  
  var refreshXForm = function(){
    xforms.ready = false;
    model.rebuild();
    model.recalculate();
    xforms.refresh();
    xforms.ready = true;
  }
  
  that.init = function(){
    model = document.getElementById('btzAnswersCard_mainModel');
    instance = model.getInstanceDocument('btzAnswersCard_mainInstance');
    answer = model.getInstanceDocument('btzAnswersCard_answerInstance').getElementsByTagName('answer')[0];
    answers = instance.getElementsByTagName('data')[0].getElementsByTagName('answers')[0];
    nodes = {
      'preview' : _.getEl('preview'),
      'draw' : _.getEl('draw'),
      'canvas' : _.getEl('canvas'),
      'points' : _.getEl('points'),
      'buttons' : _.getEl('bar'),
      'info' : _.getEl('info')
    }
    // Init Canvas
    checkCanvas();
    that.drawAnswerPointsAll();
    // Render buttons
    // clearAllBtn();
    addBtn();
  };
}