// -*- coding: utf-8 -*-
var RollDown = function () {
  var active = false;
  var appearStep = 1000;

  function toggle(myDivId)
  {
    if ($("f_" + myDivId)) {
      FunkyRolldown.toggle("f_" + myDivId);
      return;
    }

    var el = $(myDivId);
    if (active) return;
    active = true;
    var shouldShow = (el.__rdVisible = !el.__rdVisible);
    var items = $$("#" + el.id + " > div");
    if (!shouldShow) items = items.reverse();
    var effect = shouldShow ? Effect.Appear : Effect.Fade;

    function step () {
      var next = items.shift();
      if (next) {
        new effect(next);
        setTimeout(step, appearStep);
      } else
        active = false;
    }

    step();
  }

  return {
    toggle: toggle
  };
}();

var FunkyRolldown = function () {
  var appearStart = 1200.0;
  var appearStep = 1000.0;
  var hideAfter = 1200;
  var currentId = 1;
  var activity = {};

  function show(el) {
    el = $(el);
    for (; el && el != document.body && !el.hasClassName("funky-rolldown"); el = $(el.parentNode));

    if (!el) alert("Invalid FunkyRolldown");
    el = $(el.getElementsByTagName("ul")[0]);
    if (!el) alert("Invalid FunkyRolldown");

    if (!el.id) { el.id = "rdid__" + currentId++; }
    else if (activity[el.id]) return;

    activity[el.id] = true;
    if (el.visible()) {
      //el.style.height = "";
      new Effect.BlindUp(el);
      setTimeout(function () { /*el.hide();*/ activity[el.id] = false; }, hideAfter);
      return;
    }

    var items = $$("#" + el.id + " > li");

    function showNext () {
      var next = items.shift();
      if (next) {
        new Effect.Appear(next, { from: 0 });
        setTimeout(showNext, appearStep);
      } else {
        activity[el.id] = false;
        el.style.height = "";
      }
    }

    items.each(function (item) {
      item.style.visibility = 'hidden';
    });
    new Effect.BlindDown(el);
    setTimeout(function () {
      items.each(function (item) {
        el.style.height = el.offsetHeight + "px";
        item.style.display = 'none';
        item.style.visibility = 'visible';
      });
      showNext();
    }, appearStart);
  }

  return {
    toggle: show
  };
}();

var PopupTag = function () {
  var currentId = 1;
  var popups = {};

  function doGetContentDiv(el) {
    el = $(el);
    while (el && !/popup-tag-body/.test(el.className))
      el = el.nextSibling;

    return el;
  }

  function getContentDiv(el) {
    if (!el || el == document.body) return false;
    return doGetContentDiv(el) || getContentDiv($(el).parentNode);
  }

  function show (el, width, bottomThreshold) {
    el = $(el);
    var id = el.id;
    if (!el.id) id = el.id = "__pt_" + currentId++;

    popupWin = popups[id];
    if (!popupWin)
      popupWin = popups[id] = new PopupWin(
        {
          contentFunc: function (wrapper, cont) {
            $(wrapper).addClassName("popup-tag-content");
            wrapper.innerHTML = getContentDiv(id).innerHTML;
            cont();
          },
          width: width || 300,
          bottomThreshold: bottomThreshold
        });

    popupWin.show(el);
  }

  return {
    show: show
  }
}();

SelfCheckTag = function () {
  function preprocessText(str) {
    return str.strip().toLowerCase().replace(/\s+/g, " ");
  }

  function init(el, useTextField, rightTextAnswer, correctAnswers) {
    el = $(el);
    var button = el.getElementsByClassName("sc-answer-button")[0];
    var comment = el.getElementsByClassName("sc-answer-comment")[0];
    var resultArea = el.getElementsByClassName("sc-result")[0];
    var choices = $A(el.getElementsByClassName("sc-choice"));
    var text = el.getElementsByClassName("sc-text")[0];

    function answered (isCorrect) {
      choices.each(
        function (choice) {
          var isChoiceCorrect = correctAnswers.indexOf(choice.id) >= 0;
          if (choice.checked && (isCorrect || !isChoiceCorrect))
            choice.parentNode.addClassName("sc-mark");
          else
            choice.parentNode.removeClassName("sc-mark");
        });
      el.removeClassName("sc-correct");
      el.removeClassName("sc-incorrect");
      if (isCorrect) {
        el.addClassName("sc-correct");
        resultArea.innerHTML = "Ответ верен."
      } else {
        el.addClassName("sc-incorrect");
        if (correctAnswers.length == 1 || rightTextAnswer)
          resultArea.innerHTML = "Ответ неверен. Правильный ответ:<ul class='sc-right-answer-list'><li>" +
            (useTextField ? rightTextAnswer : $(correctAnswers[0]).nextSibling.innerHTML) + "</li></ul>";
        else
          resultArea.innerHTML = "Ответ неверен. Правильные ответы:<ul class='sc-right-answer-list'>" +
            correctAnswers.collect(function(id) {
              return "<li>" + $(id).nextSibling.innerHTML + "</li>";
            }).join("") + "</ul>";
      }
      resultArea.show();
      if (comment) comment.show();
    }

    function checkChoice() {
      return !choices.find(
            function (input) {
              var isCorrect = correctAnswers.indexOf(input.id) >= 0;
              if (isCorrect != !!input.checked)
                return true;
        });
    }

    function setupStudentMode() {
      var handleClick;
      if (useTextField) {
        handleClick = function (e) {
          Event.stop(e);
          answered(preprocessText(text.value) == preprocessText(rightTextAnswer));
        }.bindAsEventListener();
      } else {
        handleClick = function (e) {
          Event.stop(e);
          answered(checkChoice());
        }.bindAsEventListener();
      }
      button.observe("click", handleClick);
    }

    function setupMethodologistMode() {
      button.disabled = true;
      choices.each(function (choice) {
        if (correctAnswers.indexOf(choice.id) >= 0)
          choice.checked = true;
        choice.disabled = true;
      });
      if (useTextField) {
        text.disabled = true;
        text.value = rightTextAnswer;
      }
    }

    if (window.__studyId || /enable_tests=[^0]/.test(location.href))
      setupStudentMode();
    else
      setupMethodologistMode();
  }
  return {
    init: init
  };
}();

var Xobj = function () {
   var dimMap = {
     pizza: [ 490, 550 ],
     piechart: [ 490, 490 ],
     gallery: [ 490, 550 ],
     "default": [ 490, 550 ]
   };

  function show (id, type, width, height) {
    var textarea = $(id);
    var xml = textarea.value;
    var div = document.createElement("div");
    var dims = dimMap[type] || dimMap["default"];
    swfobject.embedSWF(
      "/images/flash/" + type + ".swf",
      id, width || dims[0], height || dims[1],
      "8", false, { xml: encodeURIComponent(xml), id: encodeURIComponent(id) });
  }

  function resize(id, width, height) {
    xobj = $(id);
    if (!xobj)
      throw new Error("xobj flash not found -- " + id);
    setTimeout(function () {
      if (width) xobj.style.width = width + "px";
      if (height) xobj.style.height = height + "px";
    }, 10);
  }

  return {
    show: show,
    resize: resize
  };
}();
