/**
 *
 */

require(["solutions/qtAuthor/js/jquery-1.11.0.min.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/qtAuthor/js/jquery.imagemapster.min.js", "dojo/domReady!"], function () {});
require(["solutions/qtAuthor/js/lightbox.min.js", "dojo/domReady!"], function () {});

var _currentAnswer = undefined;

function goToLink(mainContext, addContext, filterContext) {
  window.open(window.location.toString() + 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='mdl-cell mdl-cell--12-col-desktop mdl-cell--8-col-tablet mdl-cell--8-col-phone 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 class="td-letter"><div class="mdl-cell">' + destructor.attributes.getNamedItem("letter").value + '</div></td><td class="td-option"><div class="mdl-cell">' + optText + '</div></td><td class="acceptAnswers td-class-value">' + (answText != '' ? '<div id="d' + answDestructorID + '" class="mdl-cell 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();
        var _answerClone = $(_currentAnswer).clone().on('click', function (arg) {
            onDivAnswerClick(arg);
          }).draggable({
            helper : 'clone',
            opacity : 0.5
          });
        $(this).append(_answerClone);
        $(_answerClone).removeClass("mdl-shadow--4dp");
        _answerClone = undefined;
        $(_currentAnswer).removeClass("mdl-shadow--4dp");
        _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();
//  }
  $('div.answer').removeClass("mdl-shadow--4dp");
  if (_currentAnswer != arg.currentTarget) {
    $(arg.currentTarget).addClass("mdl-shadow--4dp");
    _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='mdl-cell mdl-cell--12-col-desktop mdl-cell--8-col-tablet mdl-cell--8-col-phone 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 class="td-letter"><div class="mdl-cell">' + destructor.attributes.getNamedItem("letter").value + '</div></td><td class="td-option"><div class="mdl-cell">' + optText + '</div></td><td class="acceptAnswers td-class-value">' + (answText != '' ? '<div id="d' + answDestructorID + '" class="answer mdl-cell">' + 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) {
        $(this).append(_currentAnswer);
       // $(_currentAnswer).css('border', '');
        $(_currentAnswer).removeClass("mdl-shadow--4dp");
        _currentAnswer = undefined;
      }
    });

    $('td.acceptAnswers').on('click', function (arg) {
      $('div.answers').append($(this).children());
      if (_currentAnswer != undefined) {
        $(this).append(_currentAnswer);
        $(_currentAnswer).removeClass("mdl-shadow--4dp");
        _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="mdl-cell mdl-cell--12-col-desktop mdl-cell--8-col-tablet mdl-cell--8-col-phone 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 class="td-letter"><div class="mdl-cell"><b>' + answerText + '</b></div></td><td class="acceptAnswers td-sort-value">' + (destructor ? '<div id="' + destructor.attributes.getNamedItem("id").value + '" class="answer mdl-cell">' + 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) {
      onDivAnswerClick(arg);
    });

    $('div.answers').on('click', function (arg) {
      if (_currentAnswer != undefined) {
        $(this).append(_currentAnswer);
        $(_currentAnswer).removeClass("mdl-shadow--4dp");
        _currentAnswer = undefined;
      }
    });

    $('td.acceptAnswers').on('click', function (arg) {
      $('div.answers').append($(this).children());
      if (_currentAnswer != undefined) {
        $(this).append(_currentAnswer);
        $(_currentAnswer).removeClass("mdl-shadow--4dp");
        _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);
    var answer = tr.id.substring(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);
        nodeAnswer.setAttribute("text", answer);
        //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 injectImageMapster() {
  var xref = {};
  var areasDict = [];
  var model = document.getElementById('4_mainModel');
  var instance = model.getInstanceDocument('4_mainInstance');
  var destructors = instance.getElementsByTagName('options')[0].getElementsByTagName('option');
  for (var i = 0; i < destructors.length; ++i) {
    var destructor = destructors[i];
    var letter = destructor.getElementsByTagName('letter')[0];
    var name = destructor.getElementsByTagName('destructorHTML')[0];
    var coords = destructor.getElementsByTagName('answerText')[0]; 
    var letterText = letter.textContent != undefined ? letter.textContent : letter.text;
    var nameText = name.textContent != undefined ? name.textContent : name.text;
    var coordsText = coords.textContent != undefined ? coords.textContent : coords.text; 
    $('#image_map').append('<area name="'+letterText+'" shape="poly" coords="'+coordsText+'" href="#"></area>');
    areasDict.push({key: letterText, toolTip: nameText});
    xref[letterText] = nameText;
  }
  var mapImg = $('#mapImg');
//  mapImg.attr('usemap', '#imageMap');
//  $('img').mapster('unbind');
  mapImg.mapster({
    fillOpacity : 0.4,
    fillColor : 'd42e16',
    strokeColor : '3320FF',
    strokeOpacity : 0.8,
    strokeWidth : 4,
    stroke : true,
    isSelectable : true,
    singleSelect : true,
    mapKey : 'name',
    listKey : 'name',
    areas : areasDict,
    showToolTip : true,
    toolTipClose : ['area-mouseout'],
    onClick : function (e) {
      var currentKey = e.key;
      if (e.selected === true) {
        var options = instance.getElementsByTagName('result')[0].getElementsByTagName('option');
        for (var i = 0; i < options.length; ++i) {
          var option = options[i];
          var checked = option.getElementsByTagName('checked')[0];
          var letter = option.getElementsByTagName('letter')[0];
          if (letter.textContent == currentKey || letter.text == currentKey) {
            setValue(checked, '0_1');
          } else {
            setValue(checked, '0_0');
          }
        }
        $('#selections').html(xref[e.key]);
      } else {
        var selectedOption = instance.getElementById('variant'+currentKey).getElementsByTagName('checked')[0];
        setValue(selectedOption, '0_0');
        $('#selections').html('');
      }
      xforms.ready = false;
      xforms.refresh();
      xforms.ready = true;
    },
    onConfigured : function (success) {
      if (success) {
        for (var i = 0; i < destructors.length; ++i) {
          var destructor = destructors[i];
          var isTrue = destructor.getElementsByTagName('isTrue')[0];
          if (isTrue.textContent == 'true' || isTrue.text == 'true') {
            var letter = destructor.getElementsByTagName('letter')[0];
            var letterText = letter.textContent != undefined ? letter.textContent : letter.text;
            this.mapster('set_options', { 
              areas: [{
                  key: letterText,
                  fillColor: '00ff00'
                }]
            })
          }
        }
      
        var options = instance.getElementsByTagName('result')[0].getElementsByTagName('option');
        for (var i = 0; i < options.length; ++i) {
          var option = options[i];
          var checked = option.getElementsByTagName('checked')[0];
          if (checked.textContent == '0_1' || checked.text == '0_1') {
            var letter = option.getElementsByTagName('letter')[0];
            var letterText = letter.textContent != undefined ? letter.textContent : letter.text;
            this.mapster('set', true, letterText);
            $('#selections').html(xref[letterText]);
          }
        }
      }
    }
  });
  console.log('injectImageMapster READY!');
}
