closedquestion-8.x-3.x-dev/assets/js/xmlQuestionConvert.js

assets/js/xmlQuestionConvert.js
/**
 * @file
 * ClosedQuestion specific functions for the xmlEditor.
 */

/**
 * Make sure we remember when user edits the question using the textarea.
 *
 * @param {object} bodyField
 *  De bodyField textarea DOM object
 */
function CQ_InitBody(bodyField) {
  var events = 'keyup.cq paste.cq';
  jQuery(bodyField).unbind(events);
  /* we should remember when user edits the question using the textarea */
  jQuery(bodyField).bind(events, function () {
    jQuery(this).data('cq_isdirty', true);
  });
}

/**
 * Select the tab that should be initially selected.
 * This is called by Drupal.behaviours.
 */
function CQ_InitialView(context) {
  var bodyField = jQuery('#edit-field-question-xml-0-value', context);
  CQ_InitBody(bodyField);

  if (bodyField.length > 0) {
    if (bodyField[0].value.length > 0) {
      CQ_ShowTree();
    }
    else {
      CQ_ShowTemplates()
    }
  }

  /* make sure the field has the correct text format */
  /* @TODO: implement better solution, http://drupal.stackexchange.com/questions/16036/how-do-you-set-a-default-input-text-format-per-content-type */
  var $select = jQuery('#body_field_wrapper .filter-list.form-select');

  if ($select.children('[value=closedquestion]').length === 1) {
    $select.val('closedquestion').attr('data-val-set-by-xmleditor', 'true');
    $select.trigger('change');
    $select.closest('.fieldset-wrapper').hide();
  }


  /* listen to editor updates */
  jQuery('#xmlJsonEditor_tree_container').xmlTreeEditor('bind', 'change', function () {
    jQuery(bodyField).data('cq_isdirty', false);
  });
}

/**
 * Find the body field.
 *
 * @param lang
 *   The suggested language to use to search for the body field. If no body
 *   field with this language is found, "und" is used. If that also results in
 *   no match, the first textarea with a name that starts with 'body' is used.
 */
function CQ_FindBodyField(lang) {
  var bodyFieldSelector = '#edit-field-question-xml-0-value';
  var bodyField = jQuery(bodyFieldSelector)[0];
  if (bodyField == undefined) {
    bodyField = jQuery('textarea[name^="field_question_xml"]')[0];
  }
  return bodyField;
}

/**
 * Called before form submit
 * @returns
 */
function CQ_beforesubmit() {
  var bodyField = CQ_FindBodyField(drupalSettings.closedquestion.language);
  if (jQuery(bodyField).data('cq_isdirty') === false || jQuery(bodyField).data('cq_isdirty') === undefined) {
    /* user has not modified the xml using the bodyField: get latest version of xml from tree editor */
    bodyField.value = jQuery('#xmlJsonEditor_tree_container').xmlTreeEditor('read');
  }
  return false;
}

function CQ_AddHelpAndCSS(questionType) {
  /* add attribute to container to later style it with CSS */
  var container = jQuery('#xmlJsonEditor_container');
  container.attr('data-question-type', questionType);

}
/**
 * Shows the editor tab, loads the current XML into the editor and hides the
 * XML and templates tabs.
 */
function CQ_ShowTree(forceInit) {
  var lang = drupalSettings.closedquestion.language;
  var bodyField = CQ_FindBodyField(lang);
  var initEditor = (forceInit || (
    bodyField.value.trim().length > 0
    && (jQuery('#xmlJsonEditor_tree_container').attr('data-xmleditor-is-init') !== 'true'
      || jQuery(bodyField).data('cq_isdirty') === true)
    ));

  jQuery('#xmlJsonEditor_tree').addClass('xmlJsonEditor_activeTab');
  jQuery('#xmlJsonEditor_tree').removeClass('xmlJsonEditor_inactiveTab');
  jQuery('#xmlJsonEditor_xml').addClass('xmlJsonEditor_inactiveTab');
  jQuery('#xmlJsonEditor_xml').removeClass('xmlJsonEditor_activeTab');
  jQuery('#xmlJsonEditor_templates').addClass('xmlJsonEditor_inactiveTab');
  jQuery('#xmlJsonEditor_templates').removeClass('xmlJsonEditor_activeTab');

  jQuery('#edit-field-question-xml-wrapper').css('display', 'none');
  jQuery('#xmlJsonEditor_container').css('display', 'block');
  jQuery('#xmlJsonEditor_template_container').css('display', 'none');
  jQuery('#xmlJsonEditor_tree_container').closest('form');

  if (!initEditor) {
    return;
  }
  jQuery('#xmlJsonEditor_tree_container').xmlTreeEditor('init', '#xmlJsonEditor_editor', bodyField.value, drupalSettings.closedquestion.xmlConfig);

  /**
   * Add links to tutorials etc based on question type
   */
  jQuery('#xmlJsonEditor_tree_container').xmlTreeEditor('bind', 'change', function (data) {
    if (data.type === "question" && data.what === "attribute" && data.which === "type") {
      CQ_AddHelpAndCSS(data.value);
    }
  });
  var questionTags = jQuery('#xmlJsonEditor_tree_container').xmlTreeEditor('search', 'question');
  if (questionTags && questionTags[0] && questionTags[0].data) {
    if (questionTags[0].data().jstree_cq && questionTags[0].data().jstree_cq.attributes) {
      CQ_AddHelpAndCSS(questionTags[0].data().jstree_cq.attributes.type);
    }
  }

  /**
   * plugin matchImg editor
   */


  /* bind to before load attribute editor */
  jQuery('#xmlJsonEditor_tree_container').xmlTreeEditor('bind', 'onLoadEditor', function (data) {
    var miEditorConfig = {};
    var re;
    var matchImage, matchImageData, imageSrc, hotspotIdInput;

    jQuery('.matchImgEditor').remove();

    var parent = jQuery('#xmlJsonEditor_tree_container').xmlTreeEditor('closest', data.treeNode, 'question');
    var questionType = parent.data('jstree_cq').attributes.type;

    if (['arrow', 'dragdrop', 'hotspot'].indexOf(questionType) === -1) {
      return;
    }

    if (data.type === "hotspot") {
      /* Create hotspot editor. */

      // Get ourselves an image.
      matchImage = jQuery('#xmlJsonEditor_tree_container').xmlTreeEditor('search', 'matchimg');
      if (matchImage[0] !== undefined) {
        matchImageData = matchImage[0].data();
        imageSrc = matchImageData.jstree_cq.attributes.src;
        if (imageSrc && imageSrc.indexOf('[attachurl') === 0) {
          // Try to get image url.
          var imageUrl = '';
          re = new RegExp('\attachurl:([^\[]*)\]', 'ig');
          var imageSrcResult = re.exec(matchImageData.jstree_cq.attributes.src)[1];
          var $fa_imagecontainer = jQuery(".media-item[title='" + imageSrcResult + "']");
          if ($fa_imagecontainer.length > 0) {
            var fid = $fa_imagecontainer.attr('data-fid');
            imageUrl = drupalSettings.basePath + 'closedquestion/getmedia/' + fid;
          }
        }
        else if (imageSrc && imageSrc.indexOf('[[{') === 0) {
          // Assume Media tag: get fid.
          re = new RegExp('"fid":([^,]*),');
          var fid = re.exec(matchImageData.jstree_cq.attributes.src)[1];
          imageUrl = drupalSettings.basePath + 'closedquestion/getmedia/' + fid;
        }

        miEditorConfig.imageURL = imageUrl;
      }

      // Config editor.
      var shapeSelect = jQuery(data.editorElements.forElement.attributeEditorElements).find("#xmlEditor_shape")[0];
      var coordsFormElement = jQuery(data.editorElements.forElement.attributeEditorElements).find("#xmlEditor_coords")[0];
      var $coordsFeedback = jQuery('<li class="miEditorFeedback xmlJsonEditor_feedback_description"></li>');
      jQuery(coordsFormElement).parent().find('.xmlEditorAttributeFeedback ul').append($coordsFeedback);

      var shape = jQuery(shapeSelect).val();
      var coords = jQuery(coordsFormElement).val();

      miEditorConfig.imageFormElements = data.editorElements.forElement.attributeEditorElements;
      miEditorConfig.shapeSelect = shapeSelect;
      miEditorConfig.mode = 'edit hotspot';
      miEditorConfig.insertBeforeElement = jQuery('#xmlEditor_coords');
      miEditorConfig.imageWidth = matchImageData.jstree_cq.attributes.width;
      miEditorConfig.imageHeight = matchImageData.jstree_cq.attributes.height;
      /* create matchImgEditor */
      var miEditor = new matchImgEditor(jQuery('#editor_values'), miEditorConfig);
      if (miEditor.config.imageURL === undefined) {
        return true;
      }

      /* bind to ondrawshape event to detect changes */
      miEditor.bind('onDrawShape', function (hotspotData) {
        var dataAsString = '';
        var dataAsArray = [];
        var imageDimensions;
        var lx, ly, hx, hy;
        switch (hotspotData.shape) {
          case 'circle':
            dataAsString = parseInt(hotspotData.coords.x) + ',' + parseInt(hotspotData.coords.y) + ',' + hotspotData.radius;
            imageDimensions = hotspotData.radius * 2 + 'x' + hotspotData.radius * 2;
            break;

          default:
            jQuery(hotspotData.coords).each(function () {
              dataAsArray.push(parseInt(this.x) + ',' + parseInt(this.y));
              lx = (lx === undefined || this.x < lx) ? this.x : lx;
              ly = (ly === undefined || this.y < ly) ? this.y : ly;
              hx = (hx === undefined || this.x > hx) ? this.x : hx;
              hy = (hy === undefined || this.y > hy) ? this.y : hy;
            });
            dataAsString = dataAsArray.join(',');
            imageDimensions = (hx - lx) + 'x' + (hy - ly);
            break;
        }

        jQuery(coordsFormElement).val(dataAsString).trigger('change');
        $coordsFeedback.html('Hotspot dimensions: ' + imageDimensions + ' pixels');
      });

      //set the selected shape
      jQuery(shapeSelect).change(function () {
        miEditor.clearCanvas();
        miEditor.setCurrentShape(jQuery(this).val());
      })
      miEditor.clearCanvas();
      miEditor.setCurrentShape(shape);

      //draw the shape
      if (coords !== '') {
        miEditor.loadShape({
          "shape": shape,
          "coords": coords
        });
      }
      return false;
    }
    else if (data.type === "match" || data.type === "startstate") {
      miEditorConfig = {};

      matchImage = jQuery('#xmlJsonEditor_tree_container').xmlTreeEditor('search', 'matchimg', {"parent": parent});
      if (matchImage[0] !== undefined) {
        matchImageData = matchImage[0].data();
        imageSrc = matchImageData.jstree_cq.attributes.src;
        if (imageSrc && imageSrc.indexOf('[attachurl') === 0) {
          // Try to get image url.
          var imageUrl = '';
          re = new RegExp('\attachurl:([^\[]*)\]', 'ig');
          var imageSrcResult = re.exec(matchImageData.jstree_cq.attributes.src)[1];
          var $fa_imagecontainer = jQuery(".media-item[title='" + imageSrcResult + "']");
          if ($fa_imagecontainer.length > 0) {
            var fid = $fa_imagecontainer.attr('data-fid');
            imageUrl = drupalSettings.basePath + 'closedquestion/getmedia/' + fid;
          }
        }
        else if (imageSrc && imageSrc.indexOf('[[{') === 0) {
          // Assume Media tag: get fid.
          re = new RegExp('"fid":([^,]*),');
          var fid = re.exec(matchImageData.jstree_cq.attributes.src)[1];
          imageUrl = drupalSettings.basePath + 'closedquestion/getmedia/' + parseInt(fid, 10);
        }

        miEditorConfig.imageURL = imageUrl;
      }

      miEditorConfig.imageFormElements = data.editorElements.forElement.attributeEditorElements;
      miEditorConfig.shapeSelect = shapeSelect;
      miEditorConfig.mode = 'view hotspots';
      if (data.type === 'match') {
        miEditorConfig.insertBeforeElement = jQuery('#xmlEditor_draggable');
      }else{
        miEditorConfig.insertBeforeElement = jQuery('#xmlEditor_value');
      }
      miEditorConfig.imageWidth = matchImageData.jstree_cq.attributes.width;
      miEditorConfig.imageHeight = matchImageData.jstree_cq.attributes.height;

      /* create matchImgEditor */
      miEditor = new matchImgEditor(jQuery('#editor_values'), miEditorConfig);
      if (miEditor.config.imageURL === undefined) {
        return true;
      }

      /* get hotspots, and draw them on the image */
      var hotspots = jQuery('#xmlJsonEditor_tree_container').xmlTreeEditor('search', 'hotspot');
      var hotspotTitleIds = [];
      // Time is used to create unique id's
      var time = new Date().getTime();
      jQuery(hotspots).each(function () {
        /* get data */
        var hotspotsData = this.data().jstree_cq.attributes;

        //keep track of titles, so we can update them when matched
        var hotspotTitleId = 'xmlEditor_' + time + '_' + hotspotsData.id;
        hotspotTitleIds.push(hotspotTitleId);

        /* add to editor */
        miEditor.loadShape({
          "shape": hotspotsData.shape,
          "coords": hotspotsData.coords,
          "title": '<span id="' + hotspotTitleId + '">' + hotspotsData.id + '</span>'
        }, true);
      });

      if (data.type === "match") {
        /* let the hotspot id input tell us when its contents change, and update
         * the corresponding shapes in the editor
         * TODO: fix selector by giving input fields proper id's
         */
        hotspotIdInput = miEditorConfig.imageFormElements.find("#xmlEditor_hotspot");
        hotspotIdInput.keyup(function () {
          var input = jQuery(this);
          var inputValue = input.val();
          jQuery(hotspotTitleIds).each(function () {
            var span = jQuery('#' + this);
            var spanText = span.html();
            try {
              var inputValueRegExp = new RegExp(inputValue);
              if (spanText.match(inputValueRegExp)) {
                span.parent().addClass('xmlJsonEditor_matched');
              }
              else {
                span.parent().removeClass('xmlJsonEditor_matched');
              }
              input.css('background-color', '');
              input.attr('title', '');
            } catch (e) {
              /* the regular expression provided is not ok */
              span.parent().removeClass('xmlJsonEditor_matched');
              input.css('background-color', '#fcc');
              input.attr('title', 'This is not a correct regular expression');
            }
          });
        });
        hotspotIdInput.keyup(); // run it for the first time.
      }

      /* Start state editor */
      if (data.type === "startstate") {
        var question = jQuery('#xmlJsonEditor_tree_container').xmlTreeEditor('search', 'question')[0];
        var questionAtts = question.data().jstree_cq.attributes;
        if (question.data().jstree_cq.attributes) {
          jQuery('#editor_values').removeAttr('class').attr('class', questionAtts.cssclass); // Transparent draggables class
        }

        var treeDraggables = jQuery('#xmlJsonEditor_tree_container').xmlTreeEditor('search', 'draggable');
        var $container = jQuery('<div id="cq_editoranswerContainer" />');
        var $sourceElement = jQuery("#xmlEditor_value");
        var currentValue = $sourceElement.val();
        var ddDraggableStartPos = [];
        var currentY = 0;

        jQuery('.matchImgEditorImage').wrap($container);

        jQuery(treeDraggables).each(function () {
          var matches, inlineTag, imgHTML, i;
          /* get data */
          var data = this.data().jstree_cq;
          var id = data.attributes.id;
          var html = data.content;

          // Replace Media tags with HTML tags.
          if (CQ_MediaModule2IsEnabled() === true) {
            matches = html.match(/\[\[.*?\]\]/g);
            if (matches) {
              inlineTag = "";
              for (i = 0; i < matches.length; i++) {
                inlineTag = matches[i];
                imgHTML = CQ_ImgHtmlFromMediatag(inlineTag);
                html = html.replace(inlineTag, imgHTML);
              }
            }
          }

          var $draggable = jQuery('<div cqvalue="' + id + '" class="cqDdDraggable">' + html + '</div>');
          jQuery('#cq_editoranswerContainer').append($draggable);
        });

        /* Handle the case in which there is no value set. */
        if (!currentValue || currentValue.length === 0) {
          currentValue = '';
        }

        // Check if all draggables defined in the value are still present.
        var draggablePosArray = currentValue.split(';');
        var draggablePosObject = {};
        jQuery.each(draggablePosArray, function (i, posAsString) {
          var posAsArray = posAsString.split(',');
          if (posAsArray.length === 3 && jQuery('#cq_editoranswerContainer .cqDdDraggable[cqvalue="' + posAsArray[0] + '"]').length > 0) {
            draggablePosObject[posAsArray[0]] = {
              "cqvalue": posAsArray[0],
              "x": parseInt(posAsArray[1], 10),
              "y": parseInt(posAsArray[2], 10)
            };
          }
        });

        // Position draggables, taking into account new draggables.
        jQuery(treeDraggables).each(function (i, treeDraggable) {
          var data = treeDraggable.data().jstree_cq;
          var id = data.attributes.id;
          var $draggableGUI = jQuery('#cq_editoranswerContainer .cqDdDraggable[cqvalue="' + id + '"]');

          if (!draggablePosObject[id]) {
            var draggableGUIWidth = $draggableGUI.width();
            var draggableGUIHeight = $draggableGUI.height();

            currentY = currentY === 0 ? draggableGUIHeight / 2 : currentY;

            // Add settings to answer string.
            currentValue += id + ',' + (draggableGUIWidth / 2) + ',' + (currentY) + ';';

            draggablePosObject[id] = {
              "cqvalue": id,
              "x": parseInt(draggableGUIWidth / 2, 10),
              "y": parseInt(currentY, 10)
            };

            currentY += draggableGUIHeight + 2;
          }
        });

        //Get new value for for element.
        currentValue = '';
        jQuery.each(draggablePosObject, function (id, posAsObject) {
          ddDraggableStartPos.push(posAsObject);
          currentValue += posAsObject.cqvalue + ',' + posAsObject.x + ',' + posAsObject.y + ';';
        });

        // Init question.
        cqInitDDQuestion({
          "ddImage": miEditorConfig.imageURL,
          "questionid": 'cq_editor',
          "ddDraggableStartPos": ddDraggableStartPos,
          "formElement": $sourceElement
        });

        // Finaly, update form element.
        $sourceElement.val(currentValue);
        window.setTimeout(function () {
          $sourceElement.trigger('change'); // For some reason this doesn't work directly @todo fix.
        }, 300);
      }

      return false;
    }
    else {
      /* destroy matchImgEditors */
      jQuery('.matchImgEditor').remove();
      return true;
    }


  });

  /* Init SO editor */
  jQuery('#xmlJsonEditor_tree_container').xmlTreeEditor('bind', 'onLoadEditor', function (data) {
    var question = jQuery('#xmlJsonEditor_tree_container').xmlTreeEditor('closest', data.treeNode, 'question');
    var questionConfig = question.data('jstree_cq');
    var questionType = questionConfig.attributes.type;
    var question_options = [];
    var $wrapper;
    if (['selectorder'].indexOf(questionType) === -1) {
      return;
    }

    if (data.type === "match" || data.type === "startstate") {
      jQuery('#soEditor').remove();
      var $editorContainer = jQuery('<div id="soEditor"></div>');
      var sourceElement;
      var options = jQuery('#xmlJsonEditor_tree_container').xmlTreeEditor('search', 'option');
      jQuery.each(options, function () {
        var option_data = jQuery(this).data('jstree_cq');
        var text_el = jQuery('#xmlJsonEditor_tree_container').xmlTreeEditor('search', 'choice', {"parent": this})[0];
        var text_data = jQuery(text_el).data('jstree_cq');

        question_options.push({
          "id": option_data.attributes.id,
          "label": text_data.content
        });
      });

      if (data.type === "match") {
        sourceElement = jQuery("#xmlEditor_pattern");
      }
      else {
        sourceElement = jQuery("#xmlEditor_value");
      }

      $wrapper = sourceElement.closest('.xmlJsonEditor_attribute_container_wrap');

      $wrapper.prepend($editorContainer);
      $editorContainer.soEditor({
        "input": sourceElement,
        "question_options": question_options,
        "allowDuplicates": questionConfig.attributes.duplicates === "1",
        "horizontalAlignment": questionConfig.attributes.alignment === "horizontal",
        "onlyOrder": questionConfig.attributes.onlyorder,
        "allowSpecialElements": (data.type === "match") ? true : false
      });
    }
  });

  jQuery('#xmlJsonEditor_tree_container').xmlTreeEditor('bind', 'onLoadEditor', function (data) {
    var question = jQuery('#xmlJsonEditor_tree_container').xmlTreeEditor('closest', data.treeNode, 'question');
    var questionConfig = question.data('jstree_cq');
    var questionType = questionConfig.attributes.type;
    var question_options = [];

    var $wrapper;
    if (['check'].indexOf(questionType.toLowerCase()) === -1) {
      return;
    }

    if (data.type === "match") {
      jQuery('#maEditor').remove();
      var $editorContainer = jQuery('<div id="maEditor"></div>');
      var sourceElement;
      var options = jQuery('#xmlJsonEditor_tree_container').xmlTreeEditor('search', 'option');
      jQuery.each(options, function () {
        var option_data = jQuery(this).data('jstree_cq');
        var text_el = jQuery('#xmlJsonEditor_tree_container').xmlTreeEditor('search', 'choice', {"parent": this})[0];
        var text_data = jQuery(text_el).data('jstree_cq');

        question_options.push({
          "id": option_data.attributes.id,
          "label": text_data.content
        });
      });


      sourceElement = jQuery("#xmlEditor_pattern");

      $wrapper = sourceElement.closest('.xmlJsonEditor_attribute_container_wrap');

      $wrapper.prepend($editorContainer);
      $editorContainer.maEditor({
        "input": sourceElement,
        "question_options": question_options
      });
    }
  });

  /* Click first item (@todo: fix the need for this ugly timeout) */
  window.setTimeout(function () {
    jQuery('#xmlEditor_1 a').first().click();
  }, 50);

  return true;
}

/**
 * Shows the XML tab and hides the editor and templates tabs.
 */
function CQ_ShowXML() {
  var bodyField = CQ_FindBodyField(drupalSettings.closedquestion.language);
  try {
    bodyField.value = jQuery('#xmlJsonEditor_tree_container').xmlTreeEditor('read');
    jQuery(bodyField).data('cq_isdirty', false);
  } catch (e) {
    console.error(e);
  }

  jQuery('#xmlJsonEditor_tree').addClass('xmlJsonEditor_inactiveTab');
  jQuery('#xmlJsonEditor_tree').removeClass('xmlJsonEditor_activeTab');
  jQuery('#xmlJsonEditor_xml').addClass('xmlJsonEditor_activeTab');
  jQuery('#xmlJsonEditor_xml').removeClass('xmlJsonEditor_inactiveTab');
  jQuery('#xmlJsonEditor_templates').addClass('xmlJsonEditor_inactiveTab');
  jQuery('#xmlJsonEditor_templates').removeClass('xmlJsonEditor_activeTab');

  jQuery('#xmlJsonEditor_container').css('display', 'none');
  jQuery('#edit-field-question-xml-wrapper').css('display', 'block');
  jQuery('#xmlJsonEditor_template_container').css('display', 'none');
}

/**
 * Shows the templates tab and hides the editor and XML tabs.
 */
function CQ_ShowTemplates() {
  jQuery('#xmlJsonEditor_tree').addClass('xmlJsonEditor_inactiveTab');
  jQuery('#xmlJsonEditor_tree').removeClass('xmlJsonEditor_activeTab');
  jQuery('#xmlJsonEditor_xml').addClass('xmlJsonEditor_inactiveTab');
  jQuery('#xmlJsonEditor_xml').removeClass('xmlJsonEditor_activeTab');
  jQuery('#xmlJsonEditor_templates').addClass('xmlJsonEditor_activeTab');
  jQuery('#xmlJsonEditor_templates').removeClass('xmlJsonEditor_inactiveTab');

  jQuery('#xmlJsonEditor_container').css('display', 'none');
  jQuery('#edit-field-question-xml-wrapper').css('display', 'none');
  jQuery('#xmlJsonEditor_template_container').css('display', 'block');
}

/**
 * Loads a template into the editor. Gives a warning if the editor is not empty.
 *
 * @param template
 *   The XML string to load.
 */
function CQ_LoadTemplate(template) {
  var lang = drupalSettings.closedquestion.language;
  var bodyField = CQ_FindBodyField(lang);
  var confirmed = true;
  if (jQuery(bodyField)[0].value.length > 0) {
    confirmed = confirm("Loading this template will overwrite your current question. Are you sure?");
  }
  if (confirmed) {
    jQuery(bodyField)[0].value = template;
    CQ_ShowTree(true);
  }
}


/**
 * Helper, converts Media module tag to <img>
 * @param {string} mediaTag
 * @returns {string}
 */
function CQ_ImgHtmlFromMediatag(mediaTag) {
  var mediaTagCopy = mediaTag;
  var mediaObj, $img;

  /* Try to parse media tag. */
  mediaTag = mediaTag.replace('[[', '').replace(']]', '');
  try {
    mediaObj = JSON.parse(mediaTag);
  } catch (err) {
    mediaObj = false;
  }

  if (mediaObj !== false) {
    /* Obtain html to return. */
    $img = jQuery('<img />');

    if (mediaObj.attributes && mediaObj.attributes['data-src']) {
      $img.attr('src', mediaObj.attributes['data-src']);
    }
    else {
      $img.attr('src', drupalSettings.basePath + 'closedquestion/getmedia/' + mediaObj.fid);
    }

    $img.attr('data-fid', mediaObj.fid);
    $img.attr('data-view-mode', mediaObj.view_mode);

    if (mediaObj.attributes) {
      $img.attr(mediaObj.attributes);
    }

    $img.addClass('media-image');

    return $img[0].outerHTML;
  }

  /* Return original tag. */
  return mediaTagCopy;
}


/**
 * Helper, returns Media tag for image element.
 * @param {object} $image
 *   A jQuery <img> element.
 * @returns {String}
 *   The media tag.
 */
function CQ_MediatagFromImg($image) {
  var attributes = {};
  var styleAttrValues = [];
  if ($image.width() > 0) {
    styleAttrValues.push('width:' + $image.width() + 'px');
    attributes['width'] = $image.width();
  }

  if ($image.height() > 0) {
    styleAttrValues.push('height:' + $image.height() + 'px');
    attributes['height'] = $image.height();
  }

  attributes['typeof'] = "foaf:Image";
  attributes['class'] = $image.attr('class');
  attributes['style'] = styleAttrValues.join(';');
  attributes['data-src'] = $image.attr('src');
  attributes['title'] = $image.attr('title');
  attributes['alt'] = $image.attr('alt');

  var tagContent = {
    "fid": $image.attr('data-fid'),
    "type": 'media',
    "view_mode": $image.attr('data-view-mode')
  };

  tagContent['attributes'] = attributes;

  return '[[' + JSON.stringify(tagContent) + ']]';
}


/**
 * Helper function. Detects whether Media Module 2.x is enabled.
 * @returns {Boolean}
 */
function CQ_MediaModule2IsEnabled() {
  return (typeof Drupal.media !== 'undefined' && typeof Drupal.media.popups !== 'undefined' && typeof Drupal.media.popups.mediaBrowser !== 'undefined');
}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc