<commit_before>var AIRTIME = (function(AIRTIME){
	var mod;

	if (AIRTIME.library === undefined) {
		AIRTIME.library = {};
	}

	mod = AIRTIME.library;

	mod.checkAddButton = function() {
		var selected = mod.getChosenItemsLength(),
    		$cursor = $('tr.cursor-selected-row'),
    		check = false;

    	//make sure library items are selected and a cursor is selected.
    	if (selected !== 0 && $cursor.length !== 0) {
    		check = true;
    	}

    	if (check === true) {
	    	AIRTIME.button.enableButton("lib-button-add");
	    }
	    else {
	    	AIRTIME.button.disableButton("lib-button-add");
	    }
    };

	mod.fnRowCallback = function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
		var $nRow = $(nRow);

		if (aData.ftype === "audioclip") {
			$nRow.addClass("lib-audio");
		} else if (aData.ftype === "stream"){
            $nRow.addClass("lib-stream");
        } else {
			$nRow.addClass("lib-pl");
		}

		$nRow.attr("id", aData["tr_id"])
	    	.data("aData", aData)
	    	.data("screen", "timeline");
	};

	mod.fnDrawCallback = function fnLibDrawCallback() {

		mod.redrawChosen();
		mod.checkToolBarIcons();

		$('#library_display tr.lib-audio, tr.lib-pl, tr.lib-stream').draggable({
			helper: function(){

			    var $el = $(this),
			    	selected = mod.getChosenItemsLength(),
			    	container,
			    	thead = $("#show_builder_table thead"),
			    	colspan = thead.find("th").length,
			    	width = thead.find("tr:first").width(),
			    	message;

			    //dragging an element that has an unselected checkbox.
			    if (mod.isChosenItem($el) === false) {
			    	selected++;
			    }

			    if (selected === 1) {
			    	message = "Adding 1 Item.";
			    }
			    else {
			    	message = "Adding "+selected+" Items.";
			    }

			    container = $('
').attr('id', 'draggingContainer')
			    	.append('
')
			    	.find("tr")
				    	.append('')
				    	.find("td")
				    		.attr("colspan", colspan)
				    		.width(width)
				    		.addClass("ui-state-highlight")
				    		.append(message)
				    		.end()
				    	.end();

			    return container;
		    },
			cursor: 'pointer',
			connectToSortable: '#show_builder_table'
		});
	};

	mod.dblClickAdd = function(data, type) {
        var i,
            length,
            temp,
            aMediaIds = [],
            aSchedIds = [],
            aData = [];

        //process selected files/playlists.
        aMediaIds.push({"id": data.id, "type": type});

        $("#show_builder_table tr.cursor-selected-row").each(function(i, el){
            aData.push($(el).prev().data("aData"));
        });

        //process selected schedule rows to add media after.
        for (i=0, length = aData.length; i < length; i++) {
            temp = aData[i];
            aSchedIds.push({"id": temp.id, "instance": temp.instance, "timestamp": temp.timestamp});
        }

        if(aSchedIds.length == 0){
            alert("Please select a cursor position on timeline.");
            return false;
        }
        console.log(aMediaIds);
        AIRTIME.showbuilder.fnAdd(aMediaIds, aSchedIds);
	};

	mod.setupLibraryToolbar = function() {
		var $toolbar = $(".lib-content .fg-toolbar:first");

		$toolbar
			.append("
")
			.find('ul')
				.append('

')
				.append('

')
				.append('

');

		//add to timeline button
		$toolbar.find('.lib-button-add')
			.click(function() {

				if (AIRTIME.button.isDisabled('lib-button-add') === true) {
					return;
				}

				var selected = AIRTIME.library.getSelectedData(),
					data,
					i,
					length,
					temp,
					aMediaIds = [],
					aSchedIds = [],
					aData = [];

				//process selected files/playlists.
				for (i = 0, length = selected.length; i < length; i++) {
					data = selected[i];
					aMediaIds.push({"id": data.id, "type": data.ftype});
				}

				$("#show_builder_table tr.cursor-selected-row").each(function(i, el){
					aData.push($(el).prev().data("aData"));
				});

				//process selected schedule rows to add media after.
				for (i=0, length = aData.length; i < length; i++) {
					temp = aData[i];
					aSchedIds.push({"id": temp.id, "instance": temp.instance, "timestamp": temp.timestamp});
				}

				AIRTIME.showbuilder.fnAdd(aMediaIds, aSchedIds);
			});

		//delete from library.
		$toolbar.find('.lib-button-delete')
			.click(function() {

				if (AIRTIME.button.isDisabled('lib-button-delete') === true) {
					return;
				}

				AIRTIME.library.fnDeleteSelectedItems();
			});

		mod.createToolbarDropDown();
	};

	return AIRTIME;

}(AIRTIME || {}));
<commit_msg>-fixed formatting<commit_after>var AIRTIME = (function(AIRTIME) {
    var mod;

    if (AIRTIME.library === undefined) {
        AIRTIME.library = {};
    }

    mod = AIRTIME.library;

    mod.checkAddButton = function() {
        var selected = mod.getChosenItemsLength(), $cursor = $('tr.cursor-selected-row'), check = false;

        // make sure library items are selected and a cursor is selected.
        if (selected !== 0 && $cursor.length !== 0) {
            check = true;
        }

        if (check === true) {
            AIRTIME.button.enableButton("lib-button-add");
        } else {
            AIRTIME.button.disableButton("lib-button-add");
        }
    };

    mod.fnRowCallback = function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
        var $nRow = $(nRow);

        if (aData.ftype === "audioclip") {
            $nRow.addClass("lib-audio");
        } else if (aData.ftype === "stream") {
            $nRow.addClass("lib-stream");
        } else {
            $nRow.addClass("lib-pl");
        }

        $nRow.attr("id", aData["tr_id"]).data("aData", aData).data("screen",
                "timeline");
    };

    mod.fnDrawCallback = function fnLibDrawCallback() {

        mod.redrawChosen();
        mod.checkToolBarIcons();

        $('#library_display tr.lib-audio, tr.lib-pl, tr.lib-stream')
            .draggable(
                {
                    helper : function() {

                        var $el = $(this), selected = mod
                                .getChosenItemsLength(), container, thead = $("#show_builder_table thead"), colspan = thead
                                .find("th").length, width = thead.find(
                                "tr:first").width(), message;

                        // dragging an element that has an unselected
                        // checkbox.
                        if (mod.isChosenItem($el) === false) {
                            selected++;
                        }

                        if (selected === 1) {
                            message = "Adding 1 Item.";
                        } else {
                            message = "Adding " + selected + " Items.";
                        }

                        container = $('
').attr('id',
                                'draggingContainer').append('
')
                                .find("tr").append('').find("td")
                                .attr("colspan", colspan).width(width)
                                .addClass("ui-state-highlight").append(
                                        message).end().end();

                        return container;
                    },
                    cursor : 'pointer',
                    connectToSortable : '#show_builder_table'
                });
    };

    mod.dblClickAdd = function(data, type) {
        var i, length, temp, aMediaIds = [], aSchedIds = [], aData = [];

        // process selected files/playlists.
        aMediaIds.push( {
            "id" : data.id,
            "type" : type
        });

        $("#show_builder_table tr.cursor-selected-row").each(function(i, el) {
            aData.push($(el).prev().data("aData"));
        });

        // process selected schedule rows to add media after.
        for (i = 0, length = aData.length; i < length; i++) {
            temp = aData[i];
            aSchedIds.push( {
                "id" : temp.id,
                "instance" : temp.instance,
                "timestamp" : temp.timestamp
            });
        }

        if (aSchedIds.length == 0) {
            alert("Please select a cursor position on timeline.");
            return false;
        }
        console.log(aMediaIds);
        AIRTIME.showbuilder.fnAdd(aMediaIds, aSchedIds);
    };

    mod.setupLibraryToolbar = function() {
        var $toolbar = $(".lib-content .fg-toolbar:first");

        $toolbar
                .append("
")
                .find('ul')
                .append(
                        '

')
                .append(
                        '

')
                .append(
                        '

');

        // add to timeline button
        $toolbar
            .find('.lib-button-add')
            .click(
                    function() {

                        if (AIRTIME.button.isDisabled('lib-button-add') === true) {
                            return;
                        }

                        var selected = AIRTIME.library.getSelectedData(), data, i, length, temp, aMediaIds = [], aSchedIds = [], aData = [];

                        // process selected files/playlists.
                        for (i = 0, length = selected.length; i < length; i++) {
                            data = selected[i];
                            aMediaIds.push( {
                                "id" : data.id,
                                "type" : data.ftype
                            });
                        }

                        $("#show_builder_table tr.cursor-selected-row")
                                .each(function(i, el) {
                                    aData.push($(el).prev().data("aData"));
                                });

                        // process selected schedule rows to add media
                        // after.
                        for (i = 0, length = aData.length; i < length; i++) {
                            temp = aData[i];
                            aSchedIds.push( {
                                "id" : temp.id,
                                "instance" : temp.instance,
                                "timestamp" : temp.timestamp
                            });
                        }

                        AIRTIME.showbuilder.fnAdd(aMediaIds, aSchedIds);
                    });

        // delete from library.
        $toolbar.find('.lib-button-delete').click(function() {

            if (AIRTIME.button.isDisabled('lib-button-delete') === true) {
                return;
            }

            AIRTIME.library.fnDeleteSelectedItems();
        });

        mod.createToolbarDropDown();
    };

    return AIRTIME;

}(AIRTIME || {}));
<|endoftext|>


<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2019, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

define(function(require) {
  /*
    DEPENDENCIES
   */

  //  require('foundation.tab');
  var Config = require("sunstone-config");
  var Locale = require("utils/locale");
  var Tips = require("utils/tips");
  var WizardFields = require("utils/wizard-fields");
  var FilesTable = require("tabs/files-tab/datatable");
  var UniqueId = require("utils/unique-id");
  var OpenNebulaHost = require("opennebula/host");

  /*
    TEMPLATES
   */

  var TemplateHTML = require("hbs!./os/html");

  /*
    CONSTANTS
   */

  var WIZARD_TAB_ID = require("./os/wizardTabId");
  var GUESTOS = [
    "asianux3_64Guest",
    "asianux3Guest",
    "asianux4_64Guest",
    "asianux4Guest",
    "centos64Guest",
    "centosGuest",
    "darwin64Guest",
    "darwinGuest",
    "debian4_64Guest",
    "debian4Guest",
    "debian5_64Guest",
    "debian5Guest",
    "dosGuest",
    "eComStationGuest",
    "freebsd64Guest",
    "freebsdGuest",
    "mandriva64Guest",
    "mandrivaGuest",
    "netware4Guest",
    "netware5Guest",
    "netware6Guest",
    "nld9Guest",
    "oesGuest",
    "openServer5Guest",
    "openServer6Guest",
    "oracleLinux64Guest",
    "oracleLinuxGuest",
    "os2Guest",
    "other24xLinux64Guest",
    "other24xLinuxGuest",
    "other26xLinux64Guest",
    "other26xLinuxGuest",
    "otherGuest",
    "otherGuest64",
    "otherLinux64Guest",
    "otherLinuxGuest",
    "redhatGuest",
    "rhel2Guest",
    "rhel3_64Guest",
    "rhel3Guest",
    "rhel4_64Guest",
    "rhel4Guest",
    "rhel5_64Guest",
    "rhel5Guest",
    "rhel6_64Guest",
    "rhel6Guest",
    "sjdsGuest",
    "sles10_64Guest",
    "sles10Guest",
    "sles11_64Guest",
    "sles11Guest",
    "sles64Guest",
    "slesGuest",
    "solaris10_64Guest",
    "solaris10Guest",
    "solaris6Guest",
    "solaris7Guest",
    "solaris8Guest",
    "solaris9Guest",
    "suse64Guest",
    "suseGuest",
    "turboLinux64Guest",
    "turboLinuxGuest",
    "ubuntu64Guest",
    "ubuntuGuest",
    "unixWare7Guest",
    "win2000AdvServGuest",
    "win2000ProGuest",
    "win2000ServGuest",
    "win31Guest",
    "win95Guest",
    "win98Guest",
    "windows7_64Guest",
    "windows7Guest",
    "windows7Server64Guest",
    "winLonghorn64Guest",
    "winLonghornGuest",
    "winMeGuest",
    "winNetBusinessGuest",
    "winNetDatacenter64Guest",
    "winNetDatacenterGuest",
    "winNetEnterprise64Guest",
    "winNetEnterpriseGuest",
    "winNetStandard64Guest",
    "winNetStandardGuest",
    "winNetWebGuest",
    "winNTGuest",
    "winVista64Guest",
    "winVistaGuest",
    "winXPHomeGuest",
    "winXPPro64Guest",
    "winXPProGues"
  ];

  /*
    CONSTRUCTOR
   */

  function WizardTab(opts) {
    if (!Config.isTemplateCreationTabEnabled(opts.tabId, "os_booting")) {
      throw "Wizard Tab not enabled";
    }

    this.wizardTabId = WIZARD_TAB_ID + UniqueId.id();
    this.icon = "fa-power-off";
    this.title = Locale.tr("OS & CPU");
    this.classes = "hypervisor"

    this.kernelFilesTable = new FilesTable(
      this.wizardTabId + UniqueId.id(),
      { "select": true,
        "selectOptions": {
          "filter_fn": function(file) { return file.TYPE == 3; } // KERNEL
      }
    });
    this.initrdFilesTable = new FilesTable(
      this.wizardTabId + UniqueId.id(),
      { "select": true,
        "selectOptions": {
          "filter_fn": function(file) { return file.TYPE == 4; } // RAMDISK
      }
    });
  }

  WizardTab.prototype.constructor = WizardTab;
  WizardTab.prototype.html = _html;
  WizardTab.prototype.setup = _setup;
  WizardTab.prototype.onShow = _onShow;
  WizardTab.prototype.retrieve = _retrieve;
  WizardTab.prototype.fill = _fill;
  WizardTab.prototype.notify = _notify;

  return WizardTab;

  /*
    FUNCTION DEFINITIONS
   */

  function _html() {
    return TemplateHTML({
      "uniqueId": UniqueId.id(),
      "guestOS": GUESTOS,
      "kernelFilesTableHTML": this.kernelFilesTable.dataTableHTML,
      "initrdFilesTableHTML": this.initrdFilesTable.dataTableHTML
    });
  }

  function _onShow(context, panelForm) {
  }

  function _setup(context) {
    var that = this;
    Foundation.reflow(context, "tabs");

    context.on("click", "button.boot-order-up", function(){
      var tr = $(this).closest("tr");
      tr.prev().before(tr);

      _refreshBootValue(context);

      return false;
    });

    context.on("click", "button.boot-order-down", function(){
      var tr = $(this).closest("tr");
      tr.next().after(tr);

      _refreshBootValue(context);

      return false;
    });

    $("table.boot-order tbody", context).on("change", "input", function(){
      _refreshBootValue(context);
    });

    var kernelDSContext = $(".kernel_ds",  context);
    var kernelDSInputsContext = $("#kernel_path_inputs",  context);
    $("input[name='kernel_type']", context).change(function() {
      if ($("input[name='kernel_type']:checked", context).val() === "kernel_ds") {
        kernelDSContext.toggle();
        kernelDSInputsContext.hide();
        $("[wizard_field]", kernelDSContext).prop("wizard_field_disabled", false);
        $("[wizard_field]", kernelDSInputsContext).prop("wizard_field_disabled", true);
      } else {
        kernelDSContext.hide();
        kernelDSInputsContext.toggle();
        $("[wizard_field]", kernelDSInputsContext).prop("wizard_field_disabled", false);
        $("[wizard_field]", kernelDSContext).prop("wizard_field_disabled", true);
      }
    });

    var initrdDSContext = $(".initrd_ds",  context);
    var initrdDSInputsContext = $("#initrd_path_inputs",  context);
    $("input[name='initrd_type']", context).change(function() {
      if ($("input[name='initrd_type']:checked", context).val() === "initrd_ds") {
        initrdDSContext.toggle();
        initrdDSInputsContext.hide();
        $("[wizard_field]", initrdDSContext).prop("wizard_field_disabled", false);
        $("[wizard_field]", initrdDSInputsContext).prop("wizard_field_disabled", true);
      } else {
        initrdDSContext.hide();
        initrdDSInputsContext.toggle();
        $("[wizard_field]", initrdDSInputsContext).prop("wizard_field_disabled", false);
        $("[wizard_field]", initrdDSContext).prop("wizard_field_disabled", true);
      }
    });

    that.kernelFilesTable.initialize({
      "selectOptions": {
        "select_callback": function(aData, options) {
          $("#KERNEL_DS", context).val("$FILE[IMAGE_ID="+ aData[options.id_index] +"]");
        }
      }
    });
    that.kernelFilesTable.refreshResourceTableSelect();

    that.initrdFilesTable.initialize({
      "selectOptions": {
        "select_callback": function(aData, options) {
          $("#INITRD_DS", context).val("$FILE[IMAGE_ID="+ aData[options.id_index] +"]");
        }
      }
    });
    that.initrdFilesTable.refreshResourceTableSelect();

    fillMachineTypesAndCPUModel(context);

  }

  function fillMachineTypesAndCPUModel(context, cpuModel, machineType){
    OpenNebulaHost.kvmInfo({
      data : {},
      timeout: true,
      success: function (request, kvmInfo){
        if ($("#model-cpu", context).html() === undefined){
          machines = kvmInfo[0].set_kvm_machines;
          cpus = kvmInfo[0].set_cpu_models;

          var html = "<select id=\"machine-type\" wizard_field=\"MACHINE\">";
          html += "<option value=\"\">" + " " + "</option>";
          $.each(machines, function(i, machine){
            html += "<option value='" + machine + "'>" + machine + "</option>";
          });
          html += "</select>";
          $("#kvm-info", context).append(html);

          var html = "<select id=\"model-cpu\" wizard_field=\"MODEL\">";
          html += "<option value=\"\">" + " " + "</option>";
          html += "<option value=\"host-passthrough\">host-passthrough</option>";
          $.each(cpus, function(i, cpu){
            html += "<option value='" + cpu + "'>" + cpu + "</option>";
          });
          html += "</select>";
          $("#cpu-model", context).append(html);
        }

        if (machineType && machineType.MACHINE){ $("#machine-type", context).val(machineType.MACHINE); }
        if (cpuModel){ $("#model-cpu", context).val(cpuModel.MODEL); }
      },
      error: function(request, error_json){
        console.error("There was an error requesting the KVM info: " +
                      error_json.error.message);
      }
    });
  }

  function _retrieve(context) {
    var templateJSON = {};
    var osJSON = {};
    $.extend(osJSON, WizardFields.retrieve(".bootTab", context));
    $.extend(osJSON, WizardFields.retrieve(".kernelTab", context));
    $.extend(osJSON, WizardFields.retrieve(".ramdiskTab", context));

    var boot = _retrieveBootValue(context);

    if (boot && boot.length > 0) {
      osJSON["BOOT"] = boot;
    } else {
      osJSON["BOOT"] = "";
    }

    if (!$.isEmptyObject(osJSON)) { templateJSON["OS"] = osJSON; };

    var featuresJSON = WizardFields.retrieve(".featuresTab", context);
    if (!$.isEmptyObject(featuresJSON)) { templateJSON["FEATURES"] = featuresJSON; };

    var cpuModelJSON = WizardFields.retrieve(".cpuTab", context);
    if (!$.isEmptyObject(cpuModelJSON)) { templateJSON["CPU_MODEL"] = cpuModelJSON; };

    return templateJSON;
  }

  function _fill(context, templateJSON) {
    var osJSON = templateJSON["OS"];
    var modelJSON = templateJSON["CPU_MODEL"];
    if (osJSON) {

      if (osJSON["KERNEL_DS"] === undefined && osJSON["KERNEL"] !== undefined){
        $("input[value=\"kernel_path\"]", context).click();
      }

      if (osJSON["INITRD_DS"] === undefined && osJSON["INITRD"] !== undefined){
        $("input[value=\"initrd_path\"]", context).click();
      }

      WizardFields.fill(context, osJSON);

      if (osJSON && osJSON["BOOT"]) {
        _fillBootValue(context, osJSON["BOOT"]);
      }
    }

    var featuresJSON = templateJSON["FEATURES"];
    if (featuresJSON) {
      WizardFields.fill(context, featuresJSON);
      delete templateJSON["FEATURES"];
    }

    fillMachineTypesAndCPUModel(context, modelJSON, osJSON);

    delete templateJSON["OS"];
    delete templateJSON["CPU_MODEL"];
  }

  //----------------------------------------------------------------------------
  // Boot order
  //----------------------------------------------------------------------------

  function _retrieveBootValue(context) {
    return $("table.boot-order", context).attr("value");
  }

  function _fillBootValue(context, value) {
    return $("table.boot-order", context).attr("value", value);
  }

  function _refreshBootValue(context) {
    var table = $("table.boot-order", context);

    var devices = [];

    $.each($("tr", table), function(){
      if ($("input", this).is(":checked")){
        devices.push( $(this).attr("value") );
      }
    });

    table.attr("value", devices.join(","));
  }

  function _addBootRow(context, value, label) {
    $("table.boot-order tbody", context).append(
      "
"+
        "<input type=\"checkbox\"/>	"+
        ""+value+"	"+
        ""+label+"	"+
        ""+
          "<button class=\"boot-order-up button radius tiny secondary\"></button>"+
          "<button class=\"boot-order-down button radius tiny secondary\"></button>"+
        "	"+
      "
");
  }

  function _notify(context, templateJSON) {
    var table = $("table.boot-order", context);
    var prev_value = $(table).attr("value");

    $("table.boot-order tbody", context).html("");

    if (templateJSON.DISK !== undefined){
      var disks = templateJSON.DISK;

      if (!$.isArray(disks)){
        disks = [disks];
      }

      $.each(disks, function(i,disk){
        var label = " ";
		    var disk_name = "disk";

        if (disk.IMAGE !== undefined){
          label += disk.IMAGE;
        } else if (disk.IMAGE_ID !== undefined){
          label += Locale.tr("Image ID") + " " + disk.IMAGE_ID;
        } else {
          label += Locale.tr("Volatile");
        }

        if (disk.DISK_ID === undefined){
          disk_name += i;
        } else {
          disk_name += disk.DISK_ID;
        }

        _addBootRow(context, disk_name, label);
      });
    }

    if (templateJSON.NIC !== undefined){
      var nics = templateJSON.NIC;

      if (!$.isArray(nics)){
        nics = [nics];
      }
      $.each(nics, function(i, nic){
        var label = " ";

        if (nic.NETWORK !== undefined){
          label += nic.NETWORK;
        } else if (nic.NETWORK_ID !== undefined){
          label += Locale.tr("Network ID") + " " + nic.NETWORK_ID;
        } else {
          label += Locale.tr("Manual settings");
        }

        _addBootRow(context, "nic"+i, label);
      });
    }

    if (templateJSON.DISK === undefined && templateJSON.NIC === undefined){
      $("table.boot-order tbody", context).append(
        "
\
          " + Locale.tr("Disks and NICs will appear here") + "	\

");
    }

    if (prev_value.length > 0){
      var pos = 0;

      $.each(prev_value.split(","), function(i,device){
        var tr = $("tr[value=\"" + device + "\"]", table);

        if(tr.length > 0){
          $($("tr", table)[pos]).before(tr);
          $("input", tr).click();

          pos += 1;
        }
      });

      _refreshBootValue(context);
    }
  }
});
<commit_msg>B #3101: multiple entries conf VM (#3397)<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2019, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

define(function(require) {
  /*
    DEPENDENCIES
   */

  //  require('foundation.tab');
  var Config = require("sunstone-config");
  var Locale = require("utils/locale");
  var Tips = require("utils/tips");
  var WizardFields = require("utils/wizard-fields");
  var FilesTable = require("tabs/files-tab/datatable");
  var UniqueId = require("utils/unique-id");
  var OpenNebulaHost = require("opennebula/host");

  /*
    TEMPLATES
   */

  var TemplateHTML = require("hbs!./os/html");

  /*
    CONSTANTS
   */

  var WIZARD_TAB_ID = require("./os/wizardTabId");
  var GUESTOS = [
    "asianux3_64Guest",
    "asianux3Guest",
    "asianux4_64Guest",
    "asianux4Guest",
    "centos64Guest",
    "centosGuest",
    "darwin64Guest",
    "darwinGuest",
    "debian4_64Guest",
    "debian4Guest",
    "debian5_64Guest",
    "debian5Guest",
    "dosGuest",
    "eComStationGuest",
    "freebsd64Guest",
    "freebsdGuest",
    "mandriva64Guest",
    "mandrivaGuest",
    "netware4Guest",
    "netware5Guest",
    "netware6Guest",
    "nld9Guest",
    "oesGuest",
    "openServer5Guest",
    "openServer6Guest",
    "oracleLinux64Guest",
    "oracleLinuxGuest",
    "os2Guest",
    "other24xLinux64Guest",
    "other24xLinuxGuest",
    "other26xLinux64Guest",
    "other26xLinuxGuest",
    "otherGuest",
    "otherGuest64",
    "otherLinux64Guest",
    "otherLinuxGuest",
    "redhatGuest",
    "rhel2Guest",
    "rhel3_64Guest",
    "rhel3Guest",
    "rhel4_64Guest",
    "rhel4Guest",
    "rhel5_64Guest",
    "rhel5Guest",
    "rhel6_64Guest",
    "rhel6Guest",
    "sjdsGuest",
    "sles10_64Guest",
    "sles10Guest",
    "sles11_64Guest",
    "sles11Guest",
    "sles64Guest",
    "slesGuest",
    "solaris10_64Guest",
    "solaris10Guest",
    "solaris6Guest",
    "solaris7Guest",
    "solaris8Guest",
    "solaris9Guest",
    "suse64Guest",
    "suseGuest",
    "turboLinux64Guest",
    "turboLinuxGuest",
    "ubuntu64Guest",
    "ubuntuGuest",
    "unixWare7Guest",
    "win2000AdvServGuest",
    "win2000ProGuest",
    "win2000ServGuest",
    "win31Guest",
    "win95Guest",
    "win98Guest",
    "windows7_64Guest",
    "windows7Guest",
    "windows7Server64Guest",
    "winLonghorn64Guest",
    "winLonghornGuest",
    "winMeGuest",
    "winNetBusinessGuest",
    "winNetDatacenter64Guest",
    "winNetDatacenterGuest",
    "winNetEnterprise64Guest",
    "winNetEnterpriseGuest",
    "winNetStandard64Guest",
    "winNetStandardGuest",
    "winNetWebGuest",
    "winNTGuest",
    "winVista64Guest",
    "winVistaGuest",
    "winXPHomeGuest",
    "winXPPro64Guest",
    "winXPProGues"
  ];

  /*
    CONSTRUCTOR
   */

  function WizardTab(opts) {
    if (!Config.isTemplateCreationTabEnabled(opts.tabId, "os_booting")) {
      throw "Wizard Tab not enabled";
    }

    this.wizardTabId = WIZARD_TAB_ID + UniqueId.id();
    this.icon = "fa-power-off";
    this.title = Locale.tr("OS & CPU");
    this.classes = "hypervisor";

    this.kernelFilesTable = new FilesTable(
      this.wizardTabId + UniqueId.id(),
      { "select": true,
        "selectOptions": {
          "filter_fn": function(file) { return file.TYPE == 3; } // KERNEL
      }
    });
    this.initrdFilesTable = new FilesTable(
      this.wizardTabId + UniqueId.id(),
      { "select": true,
        "selectOptions": {
          "filter_fn": function(file) { return file.TYPE == 4; } // RAMDISK
      }
    });
  }

  WizardTab.prototype.constructor = WizardTab;
  WizardTab.prototype.html = _html;
  WizardTab.prototype.setup = _setup;
  WizardTab.prototype.onShow = _onShow;
  WizardTab.prototype.retrieve = _retrieve;
  WizardTab.prototype.fill = _fill;
  WizardTab.prototype.notify = _notify;

  return WizardTab;

  /*
    FUNCTION DEFINITIONS
   */

  function _html() {
    return TemplateHTML({
      "uniqueId": UniqueId.id(),
      "guestOS": GUESTOS,
      "kernelFilesTableHTML": this.kernelFilesTable.dataTableHTML,
      "initrdFilesTableHTML": this.initrdFilesTable.dataTableHTML
    });
  }

  function _onShow(context, panelForm) {
  }

  function _setup(context) {
    var that = this;
    Foundation.reflow(context, "tabs");

    context.on("click", "button.boot-order-up", function(){
      var tr = $(this).closest("tr");
      tr.prev().before(tr);

      _refreshBootValue(context);

      return false;
    });

    context.on("click", "button.boot-order-down", function(){
      var tr = $(this).closest("tr");
      tr.next().after(tr);

      _refreshBootValue(context);

      return false;
    });

    $("table.boot-order tbody", context).on("change", "input", function(){
      _refreshBootValue(context);
    });

    var kernelDSContext = $(".kernel_ds",  context);
    var kernelDSInputsContext = $("#kernel_path_inputs",  context);
    $("input[name='kernel_type']", context).change(function() {
      if ($("input[name='kernel_type']:checked", context).val() === "kernel_ds") {
        kernelDSContext.toggle();
        kernelDSInputsContext.hide();
        $("[wizard_field]", kernelDSContext).prop("wizard_field_disabled", false);
        $("[wizard_field]", kernelDSInputsContext).prop("wizard_field_disabled", true);
      } else {
        kernelDSContext.hide();
        kernelDSInputsContext.toggle();
        $("[wizard_field]", kernelDSInputsContext).prop("wizard_field_disabled", false);
        $("[wizard_field]", kernelDSContext).prop("wizard_field_disabled", true);
      }
    });

    var initrdDSContext = $(".initrd_ds",  context);
    var initrdDSInputsContext = $("#initrd_path_inputs",  context);
    $("input[name='initrd_type']", context).change(function() {
      if ($("input[name='initrd_type']:checked", context).val() === "initrd_ds") {
        initrdDSContext.toggle();
        initrdDSInputsContext.hide();
        $("[wizard_field]", initrdDSContext).prop("wizard_field_disabled", false);
        $("[wizard_field]", initrdDSInputsContext).prop("wizard_field_disabled", true);
      } else {
        initrdDSContext.hide();
        initrdDSInputsContext.toggle();
        $("[wizard_field]", initrdDSInputsContext).prop("wizard_field_disabled", false);
        $("[wizard_field]", initrdDSContext).prop("wizard_field_disabled", true);
      }
    });

    that.kernelFilesTable.initialize({
      "selectOptions": {
        "select_callback": function(aData, options) {
          $("#KERNEL_DS", context).val("$FILE[IMAGE_ID="+ aData[options.id_index] +"]");
        }
      }
    });
    that.kernelFilesTable.refreshResourceTableSelect();

    that.initrdFilesTable.initialize({
      "selectOptions": {
        "select_callback": function(aData, options) {
          $("#INITRD_DS", context).val("$FILE[IMAGE_ID="+ aData[options.id_index] +"]");
        }
      }
    });
    that.initrdFilesTable.refreshResourceTableSelect();

    fillMachineTypesAndCPUModel(context);

  }

  function fillMachineTypesAndCPUModel(context, cpuModel, machineType){
    OpenNebulaHost.kvmInfo({
      data : {},
      timeout: true,
      success: function (request, kvmInfo){
        if ($("#model-cpu", context).html() === undefined){
          machines = kvmInfo[0].set_kvm_machines;
          cpus = kvmInfo[0].set_cpu_models;

          var html = "<select id=\"machine-type\" wizard_field=\"MACHINE\">";
          html += "<option value=\"\">" + " " + "</option>";
          $.each(machines, function(i, machine){
            html += "<option value='" + machine + "'>" + machine + "</option>";
          });
          html += "</select>";
          $("#kvm-info", context).append(html);

          var html = "<select id=\"model-cpu\" wizard_field=\"MODEL\">";
          html += "<option value=\"\">" + " " + "</option>";
          html += "<option value=\"host-passthrough\">host-passthrough</option>";
          $.each(cpus, function(i, cpu){
            html += "<option value='" + cpu + "'>" + cpu + "</option>";
          });
          html += "</select>";
          $("#cpu-model", context).append(html);
        }

        if (machineType && machineType.MACHINE){ $("#machine-type", context).val(machineType.MACHINE); }
        if (cpuModel){ $("#model-cpu", context).val(cpuModel.MODEL); }
      },
      error: function(request, error_json){
        console.error("There was an error requesting the KVM info: " +
                      error_json.error.message);
      }
    });
  }

  function _retrieve(context) {
    var templateJSON = {};
    var osJSON = {};
    $.extend(osJSON, WizardFields.retrieve(".bootTab", context));
    $.extend(osJSON, WizardFields.retrieve(".kernelTab", context));
    $.extend(osJSON, WizardFields.retrieve(".ramdiskTab", context));

    var boot = _retrieveBootValue(context);

    if (boot && boot.length > 0) {
      osJSON["BOOT"] = boot;
    } else {
      osJSON["BOOT"] = "";
    }

    if (!$.isEmptyObject(osJSON)) { templateJSON["OS"] = osJSON; };

    var featuresJSON = WizardFields.retrieve(".featuresTab", context);
    if (!$.isEmptyObject(featuresJSON)) { templateJSON["FEATURES"] = featuresJSON; };

    var cpuModelJSON = WizardFields.retrieve(".cpuTab", context);
    if (!$.isEmptyObject(cpuModelJSON)) { templateJSON["CPU_MODEL"] = cpuModelJSON; };

    return templateJSON;
  }

  function _fill(context, templateJSON) {
    var osJSON = templateJSON["OS"];
    var modelJSON = templateJSON["CPU_MODEL"];
    if (osJSON) {

      if (osJSON["KERNEL_DS"] === undefined && osJSON["KERNEL"] !== undefined){
        $("input[value=\"kernel_path\"]", context).click();
      }

      if (osJSON["INITRD_DS"] === undefined && osJSON["INITRD"] !== undefined){
        $("input[value=\"initrd_path\"]", context).click();
      }

      WizardFields.fill(context, osJSON);

      if (osJSON && osJSON["BOOT"]) {
        _fillBootValue(context, osJSON["BOOT"]);
      }
    }

    var featuresJSON = templateJSON["FEATURES"];
    if (featuresJSON) {
      WizardFields.fill(context, featuresJSON);
      delete templateJSON["FEATURES"];
    }

    fillMachineTypesAndCPUModel(context, modelJSON, osJSON);

    delete templateJSON["OS"];
    delete templateJSON["CPU_MODEL"];
  }

  //----------------------------------------------------------------------------
  // Boot order
  //----------------------------------------------------------------------------

  function _retrieveBootValue(context) {
    return $("table.boot-order", context).attr("value");
  }

  function _fillBootValue(context, value) {
    return $("table.boot-order", context).attr("value", value);
  }

  function _refreshBootValue(context) {
    var table = $("table.boot-order", context);

    var devices = [];

    $.each($("tr", table), function(){
      if ($("input", this).is(":checked")){
        devices.push( $(this).attr("value") );
      }
    });

    table.attr("value", devices.join(","));
  }

  function _addBootRow(context, value, label) {
    $("table.boot-order tbody", context).append(
      "
"+
        "<input type=\"checkbox\"/>	"+
        ""+value+"	"+
        ""+label+"	"+
        ""+
          "<button class=\"boot-order-up button radius tiny secondary\"></button>"+
          "<button class=\"boot-order-down button radius tiny secondary\"></button>"+
        "	"+
      "
");
  }

  function _notify(context, templateJSON) {
    var table = $("table.boot-order", context);
    var prev_value = $(table).attr("value");

    $("table.boot-order tbody", context).html("");

    if (templateJSON.DISK !== undefined){
      var disks = templateJSON.DISK;

      if (!$.isArray(disks)){
        disks = [disks];
      }

      $.each(disks, function(i,disk){
        var label = " ";
		    var disk_name = "disk";

        if (disk.IMAGE !== undefined){
          label += disk.IMAGE;
        } else if (disk.IMAGE_ID !== undefined){
          label += Locale.tr("Image ID") + " " + disk.IMAGE_ID;
        } else {
          label += Locale.tr("Volatile");
        }

        if (disk.DISK_ID === undefined){
          disk_name += i;
        } else {
          disk_name += disk.DISK_ID;
        }

        _addBootRow(context, disk_name, label);
      });
    }

    if (templateJSON.NIC !== undefined){
      var nics = templateJSON.NIC;

      if (!$.isArray(nics)){
        nics = [nics];
      }
      $.each(nics, function(i, nic){
      var distinct = function(value, index, self){
        return self.indexOf(value)===index;
      };
      nics = nics.filter(distinct);
      nics.map(function(nic,i){
        var label = " ";
        if (nic && nic.NETWORK && nic.NETWORK !== undefined){
          label += nic.NETWORK;
        } else if (nic.NETWORK_ID !== undefined){
          label += Locale.tr("Network ID") + " " + nic.NETWORK_ID;
        } else {
          label += Locale.tr("Manual settings");
        }
        _addBootRow(context, "nic"+i, label);
      });
    }

    if (templateJSON.DISK === undefined && templateJSON.NIC === undefined){
      $("table.boot-order tbody", context).append(
        "
\
          " + Locale.tr("Disks and NICs will appear here") + "	\

");
    }

    if (prev_value.length > 0){
      var pos = 0;

      $.each(prev_value.split(","), function(i,device){
        var tr = $("tr[value=\"" + device + "\"]", table);

        if(tr.length > 0){
          $($("tr", table)[pos]).before(tr);
          $("input", tr).click();

          pos += 1;
        }
      });

      _refreshBootValue(context);
    }
  }
});
<|endoftext|>


<commit_before>//
// WARNING! READ BELOW.
//
// Before you add anything to this file think if it's sensitive. This data will
// be exposed on the client-side so it can not include things like sensitive
// API keys or other credentials that should only be used server-side.
//
// If it is sensitive configuration you should only add it to config.coffee and
// require that file directly *only* server-side.
//
// See this doc for more details: https://github.com/artsy/force/blob/master/docs/adding_an_env_var.md
//
import _ from "underscore"
import config from "../config"
import sharify from "sharify"

sharify.data = _.extend(
  _.pick(
    config,
    "ACTIVE_BIDS_POLL_INTERVAL",
    "ADMIN_URL",
    "API_REQUEST_TIMEOUT",
    "API_URL",
    "APP_URL",
    "APPLICATION_NAME",
    "APPLY_URL",
    "ARTIST_COLLECTIONS_RAIL_IDS",
    "ARTSY_EDITORIAL_CHANNEL",
    "AUTO_GRAVITY_LOGIN",
    "BIDDER_INFO_COPY_P1",
    "BIDDER_INFO_COPY_P2",
    "CALENDAR_URL",
    "CDN_URL",
    "CMS_URL",
    "COLLECT_PAGE_TITLES_URL",
    "CONSIGNMENTS_APP_URL",
    "CONVECTION_APP_ID",
    "CONVECTION_APP_URL",
    "CONVECTION_GEMINI_APP",
    "DEPLOY_ENV",
    "DISABLE_IMAGE_PROXY",
    "EDITORIAL_PATHS",
    "EF_GUCCI",
    "EF_VENICE",
    "EF_VIDEO_GUIDE",
    "EMAIL_SIGNUP_IMAGES_ID",
    "EMBEDLY_KEY",
    "ENABLE_INSTANT_PAGE",
    "ENABLE_REQUEST_CONDITION_REPORT",
    "ENABLE_SERVER_SIDE_CACHE",
    "ENABLE_SIGN_IN_WITH_APPLE",
    "ENABLE_QUERY_BATCHING",
    "ENABLE_WEB_CRAWLING",
    "EOY_2016_ARTICLE",
    "EOY_2016",
    "FACEBOOK_APP_NAMESPACE",
    "FACEBOOK_ID",
    "FORCE_CLOUDFRONT_URL",
    "GALAXY_PUBLISHABLE_TOKEN",
    "GALAXY_URL",
    "GALLERY_INSIGHTS_CHANNEL",
    "GALLERY_PARTNER_UPDATES_CHANNEL",
    "GEMINI_ACCOUNT_KEY",
    "GEMINI_APP",
    "GEMINI_CLOUDFRONT_URL",
    "GENOME_URL",
    "GEODATA_URL",
    "GOOGLE_ADWORDS_ID",
    "GOOGLE_ANALYTICS_ID",
    "GOOGLE_MAPS_API_KEY",
    "IMAGE_LAZY_LOADING",
    "IMAGE_PROXY",
    "INTERCOM_BUYER_APP_ID",
    "INTERCOM_BUYER_ENABLED",
    "INTERCOM_SELLER_APP_ID",
    "INTERCOM_SELLER_ENABLED",
    "MARKETING_SIGNUP_MODALS",
    "MAX_POLLS_FOR_MAX_BIDS",
    "METAPHYSICS_ENDPOINT",
    "MOBILE_MARKETING_SIGNUP_MODALS",
    "MOBILE_MEDIA_QUERY",
    "NODE_ENV",
    "NOTIFICATION_COUNT",
    "PARSELY_KEY",
    "PC_ARTSY_CHANNEL",
    "PC_AUCTION_CHANNEL",
    "POSITRON_URL",
    "PREDICTION_URL",
    "RECAPTCHA_KEY",
    "S3_BUCKET",
    "SAILTHRU_CUSTOMER_ID",
    "SAILTHRU_MASTER_LIST",
    "SECURE_IMAGES_URL",
    "SEGMENT_AMP_WRITE_KEY",
    "SEGMENT_WRITE_KEY",
    "SENTRY_PUBLIC_DSN",
    "SHOW_ANALYTICS_CALLS",
    "SITEMAP_BASE_URL",
    "STRIPE_PUBLISHABLE_KEY",
    "TARGET_CAMPAIGN_URL",
    "TEAM_BLOGS",
    "THIRD_PARTIES_DISABLED",
    "TRACK_PAGELOAD_PATHS",
    "VOLLEY_ENDPOINT",
    "WEBFONT_URL"
  ),
  {
    CSS_EXT: ["production", "staging"].includes(config.NODE_ENV)
      ? ".min.css.cgz"
      : ".css",
    JS_EXT: ["production", "staging"].includes(config.NODE_ENV)
      ? ".min.js.cgz"
      : ".js",
  }
)
<commit_msg>refactor: remove more intercom references<commit_after>//
// WARNING! READ BELOW.
//
// Before you add anything to this file think if it's sensitive. This data will
// be exposed on the client-side so it can not include things like sensitive
// API keys or other credentials that should only be used server-side.
//
// If it is sensitive configuration you should only add it to config.coffee and
// require that file directly *only* server-side.
//
// See this doc for more details: https://github.com/artsy/force/blob/master/docs/adding_an_env_var.md
//
import _ from "underscore"
import config from "../config"
import sharify from "sharify"

sharify.data = _.extend(
  _.pick(
    config,
    "ACTIVE_BIDS_POLL_INTERVAL",
    "ADMIN_URL",
    "API_REQUEST_TIMEOUT",
    "API_URL",
    "APP_URL",
    "APPLICATION_NAME",
    "APPLY_URL",
    "ARTIST_COLLECTIONS_RAIL_IDS",
    "ARTSY_EDITORIAL_CHANNEL",
    "AUTO_GRAVITY_LOGIN",
    "BIDDER_INFO_COPY_P1",
    "BIDDER_INFO_COPY_P2",
    "CALENDAR_URL",
    "CDN_URL",
    "CMS_URL",
    "COLLECT_PAGE_TITLES_URL",
    "CONSIGNMENTS_APP_URL",
    "CONVECTION_APP_ID",
    "CONVECTION_APP_URL",
    "CONVECTION_GEMINI_APP",
    "DEPLOY_ENV",
    "DISABLE_IMAGE_PROXY",
    "EDITORIAL_PATHS",
    "EF_GUCCI",
    "EF_VENICE",
    "EF_VIDEO_GUIDE",
    "EMAIL_SIGNUP_IMAGES_ID",
    "EMBEDLY_KEY",
    "ENABLE_INSTANT_PAGE",
    "ENABLE_REQUEST_CONDITION_REPORT",
    "ENABLE_SERVER_SIDE_CACHE",
    "ENABLE_SIGN_IN_WITH_APPLE",
    "ENABLE_QUERY_BATCHING",
    "ENABLE_WEB_CRAWLING",
    "EOY_2016_ARTICLE",
    "EOY_2016",
    "FACEBOOK_APP_NAMESPACE",
    "FACEBOOK_ID",
    "FORCE_CLOUDFRONT_URL",
    "GALAXY_PUBLISHABLE_TOKEN",
    "GALAXY_URL",
    "GALLERY_INSIGHTS_CHANNEL",
    "GALLERY_PARTNER_UPDATES_CHANNEL",
    "GEMINI_ACCOUNT_KEY",
    "GEMINI_APP",
    "GEMINI_CLOUDFRONT_URL",
    "GENOME_URL",
    "GEODATA_URL",
    "GOOGLE_ADWORDS_ID",
    "GOOGLE_ANALYTICS_ID",
    "GOOGLE_MAPS_API_KEY",
    "IMAGE_LAZY_LOADING",
    "IMAGE_PROXY",
    "MARKETING_SIGNUP_MODALS",
    "MAX_POLLS_FOR_MAX_BIDS",
    "METAPHYSICS_ENDPOINT",
    "MOBILE_MARKETING_SIGNUP_MODALS",
    "MOBILE_MEDIA_QUERY",
    "NODE_ENV",
    "NOTIFICATION_COUNT",
    "PARSELY_KEY",
    "PC_ARTSY_CHANNEL",
    "PC_AUCTION_CHANNEL",
    "POSITRON_URL",
    "PREDICTION_URL",
    "RECAPTCHA_KEY",
    "S3_BUCKET",
    "SAILTHRU_CUSTOMER_ID",
    "SAILTHRU_MASTER_LIST",
    "SECURE_IMAGES_URL",
    "SEGMENT_AMP_WRITE_KEY",
    "SEGMENT_WRITE_KEY",
    "SENTRY_PUBLIC_DSN",
    "SHOW_ANALYTICS_CALLS",
    "SITEMAP_BASE_URL",
    "STRIPE_PUBLISHABLE_KEY",
    "TARGET_CAMPAIGN_URL",
    "TEAM_BLOGS",
    "THIRD_PARTIES_DISABLED",
    "TRACK_PAGELOAD_PATHS",
    "VOLLEY_ENDPOINT",
    "WEBFONT_URL"
  ),
  {
    CSS_EXT: ["production", "staging"].includes(config.NODE_ENV)
      ? ".min.css.cgz"
      : ".css",
    JS_EXT: ["production", "staging"].includes(config.NODE_ENV)
      ? ".min.js.cgz"
      : ".js",
  }
)
<|endoftext|>


<commit_before><commit_msg>Update matching-parentheses.js<commit_after><|endoftext|>


<commit_before>(function($) {
	tinymce.create('tinymce.plugins.textorumInsertion', {
		init : function(ed, url) {
			var self = this,
				disabled = true,
				editor = ed,
				//cm = new tinymce.ControlManager(ed),
				//dropmenu = cm.createDropMenu('textorum-insertion-dropmenu'), // Not used in current editor
				dropmenuVisible = false,
				dropmenuJustClicked = false,
				ignoredElements = [
					'media',
					'xref',
					'disp-quote',
					'inline-graphic',
					'inline-formula',
					'disp-formula',
					'table-wrap',
					'bold',
					'italic',
					'monospace',
					'underline',
					'sup',
					'sub'
				];

			// Addresses Chrome 33 issue where fonts didnt displace unless repainted.
			jQuery.each(jQuery('.mceIcon'), function(index, el) {
				var $el = jQuery(el);
				var opacity = $el.css('opacity');
				$el.animate({opacity: opacity}, 1);
			})

			// Key Bindings
			//
			ed.onKeyDown.addToTop(function(ed, e) {
				var target, listItemParent;

				// Enter
				if (!e.shiftKey && e.keyCode == 13) {

					listItemParent = ed.dom.getParent(ed.selection.getNode(), '.list-item');

					// What to do if empty editor
					if (ed.getContent() == '') {

						// Abstract gets a
 tag
						if (ed.id == 'excerpt') {
							tinymce.dom.Event.cancel(e);
							return ed.setContent('

');
						}
						// Presumably article content.
						else {
							tinymce.dom.Event.cancel(e);
							return ed.setContent('

');
						}
					}

					// Ctrl + Enter
					if (e.ctrlKey) {
						tinymce.dom.Event.cancel(e);
						return ed.plugins.annoFormats.insertSection();
					}

					// List items
					if (listItemParent) {
						tinymce.dom.Event.cancel(e);
						return !self.insertElement('list-item', 'after', listItemParent);
					}

					// Get the parent tag and class
					parentTag = ed.dom.getParent(ed.selection.getNode().parentNode);
					elementClass = jQuery(ed.selection.getNode()).attr('class');
					parentClass = jQuery(parentTag).attr('class');

					// If it's a 'p' tag, we need its parent
					if (parentClass == 'p') {
						parentTag = ed.dom.getParent(parentTag.parentNode);
						parentClass = jQuery(ed.dom.getParent(parentTag)).attr('class');
					}

					// Only allow sections to be extended
					if (
						parentClass == 'caption' ||
						parentClass == 'fig' ||
						parentClass == 'tr'
					) {
						console.log(parentClass + ' cannot be extended');
						tinymce.dom.Event.cancel(e);
					}
					// If it's a title, then add a P tag instead of splitting
					else if (
						elementClass == 'title'
					) {
						tinymce.dom.Event.cancel(e);
						return !self.insertElement('p', 'after', ed.selection.getNode());
					}
				}
				return true;
			});

			editor.addCommand('Textorum_Insertion_Menu', function(ui, where) {
				var options, $button;

				$button = $('#'+editor.editorId).next('.mceEditor').find('.mceButton.mce_textorum-insertion-' + where);

				if (dropmenuVisible) {
					dropmenu.hideMenu();
					dropmenuVisible = false;
				}
				else {

					where = where || 'inside';
					options = self.getValidElements(editor.selection.getNode(), where);

					dropmenu.removeAll();

					if (options.length) {
						options = options.filter(function(a) { return ignoredElements.indexOf(a) === -1; });
						tinymce.each(options, function(element_name) {
							switch (element_name) {
								case 'list':
									dropmenu.add({ title: 'list (bulleted)', onclick: function() {
										self.insertElement(element_name, where, null, {
											'list-type': 'bullet'
										});
									}});

									dropmenu.add({ title: 'list (ordered)', onclick: function() {
										self.insertElement(element_name, where, null, {
											'list-type': 'order'
										});
									}});

									break;

								default:
									dropmenu.add(new tinymce.ui.MenuItem('textorum-insertion-item-' + element_name ,{
										title: element_name,
										onclick: function() {
											if (element_name == 'list') {
												self.insertElement(element_name, where, null, {
													'list-type': 'bullet'
												});
											}
											else {
												self.insertElement(element_name, where);
											}
										}
									}));
									break;
							}
						});
					}
					else {
						dropmenu.add(new tinymce.ui.MenuItem('textorum-insertion-item-none', {
							title: 'No elements available',
							style: 'color:#999',
							onclick: function() {
								dropmenuVisible = false;
								return false;
							}
						}));
					}

					dropmenu.showMenu($button.offset().left, $button.offset().top + 24);
					dropmenuJustClicked = dropmenuVisible = true;
					setTimeout(function() { dropmenuJustClicked = false; }, 250);

				}
			});

			editor.onNodeChange.add(function(ed, cm, node) {
				var options, inlineNames, buttonElementMap, firstBlock;
				if (node.nodeName == 'BR') {
					node = node.parentNode;
				}

				options = editor.plugins.textorum.validator.validElementsForNode(node, "inside", "array");
				inlineNames = ['SPAN', 'TT', 'EM', 'U', 'STRONG', 'SUP', 'SUB'];
				buttonElementMap = {
					list : [
						'annoorderedlist',
						'annobulletlist'
					],
					xref : [
						'annoreferences'
					],
					'disp-quote' : [
						'annoquote'
					],
					monospace : [
						'annomonospace'
					],
					preformat : [
						'annopreformat'
					],
					'table-wrap' : [
						'table'
					],
					sup : [
						'superscript'
					],
					sub : [
						'subscript'
					]
				};
				firstBlock = node;

				while (inlineNames.indexOf(firstBlock.nodeName) !== -1) {
					firstBlock = firstBlock.parentNode;
				}

				jQuery.each(buttonElementMap, function(elementName, buttons) {
					var tf = false;
					if (options.indexOf(elementName) === -1) {
						tf = true;
					}

					jQuery.each(buttons, function(index, buttonName) {
						buttonDisable(buttonName, tf);
					});
				});

				if (dropmenuVisible && !dropmenuJustClicked) {
					dropmenu.hideMenu();
					dropmenuVisible = false;
				}

				// enable indent when parent list
				if (ed.dom.getParent(node, '.list')) {
					buttonDisable('annooutdentlist', false);
					buttonDisable('annoindentlist', false);
					buttonDisable('annoorderedlist', false);
					buttonDisable('annobulletlist', false);

				}
				else {
					buttonDisable('annooutdentlist', true);
					buttonDisable('annoindentlist', true);
					buttonDisable('annoorderedlist', true);
					buttonDisable('annobulletlist', true);
				}

				if (firstBlock.getAttribute('data-xmlel') == 'p') {
					buttonDisable('annoorderedlist', false);
					buttonDisable('annobulletlist', false);
				}
				else {
					buttonDisable('annoorderedlist', true);
					buttonDisable('annobulletlist', true);
				}

				if (options.indexOf('inline-graphic') === -1 || options.indexOf('fig') === -1) {
					buttonDisable('annoimages', true);
					buttonDisable('annoequations', true);
				}
				else {
					buttonDisable('annoimages', false);
					buttonDisable('annoequations', false);
				}

				if (options.indexOf('disp-quote') === -1) {
					buttonDisable('annoquote', true);
				}
				else {
					buttonDisable('annoquote', false);
				}

				function buttonDisable(buttonName, tf) {
					return cm.setDisabled(buttonName, tf);
				}
			});

			// Register example button
			editor.addButton('textorum-insertion-before', {
				title : 'Insert Element Before',
				cmd : 'Textorum_Insertion_Menu',
				value: 'before'
			});

			editor.addButton('textorum-insertion-inside', {
				title : 'Insert Element Inside',
				cmd : 'Textorum_Insertion_Menu',
				value: 'inside'
			});

			editor.addButton('textorum-insertion-after', {
				title : 'Insert Element After',
				cmd : 'Textorum_Insertion_Menu',
				value: 'after'
			});

			editor.addShortcut('ctrl+enter', 'Insert Element', 'Textorum_Insertion');
		},

		insertElement: function(element_name, where, target, attrs) {
			var editor = tinyMCE.activeEditor,
				newNode = editor.dom.create(
					editor.plugins.textorum.translateElement(element_name),
					tinymce.extend({'class': element_name, 'data-xmlel': element_name}, attrs),
					' '
				),
				range, elYPos, options;

			where = where || 'inside';
			target = target || editor.selection.getNode();

			options = this.getValidElements(target, where);

			if (options.indexOf(element_name) === -1) {
				return false;
			}

			// Add additionally required child elements
			switch (element_name) {

				case 'sec':
					newNode.innerHTML = '';
					newNode.appendChild(
						editor.dom.create(
							editor.plugins.textorum.translateElement('title'),
							{'class': 'title', 'data-xmlel': 'title'},
							' '
						)
					);
					break;

				case 'fig':
					(function() {
						var cap = editor.dom.create(
							editor.plugins.textorum.translateElement('caption'),
							{'class': 'caption', 'data-xmlel': 'caption'}
						);

						newNode.innerHTML = '';
						newNode.appendChild(
							editor.dom.create(
								editor.plugins.textorum.translateElement('label'),
								{'class': 'label', 'data-xmlel': 'label'},
								' '
							)
						);

						cap.appendChild(
							editor.dom.create(
								editor.plugins.textorum.translateElement('p'),
								{'class': 'p', 'data-xmlel': 'p'},
								' '
							)
						);

						newNode.appendChild(cap);
					})();
					break;

				case 'list':
					newNode.innerHTML = "";
					this.insertElement('list-item', 'inside', newNode);
					break;

				case 'list-item':
					newNode.innerHTML = '';
					newNode.appendChild(
						editor.dom.create(
							editor.plugins.textorum.translateElement('p'),
							{'class': 'p', 'data-xmlel': 'p'},
							' '
						)
					);
					break;
			}

			dropmenuVisible = false;

			switch(where) {
				case 'before':
					newNode = target.parentNode.insertBefore(newNode, target);
					break;

				case 'inside':
					newNode = target.appendChild(newNode);
					break;

				case 'after':
					if (target.nextSibling) {
						newNode = target.parentNode.insertBefore(newNode, target.nextSibling);
					}
					else {
						newNode = target.parentNode.appendChild(newNode);
					}
					break;
			}

			if (document.createRange) {     // all browsers, except IE before version 9
				range = document.createRange();
				if (newNode.firstChild) {
					range.selectNodeContents(newNode.firstChild);
				}
				else {
					range.selectNodeContents(newNode);
				}
			}

			range.collapse(1);
			editor.selection.setRng(range);

			elYPos = editor.dom.getPos(newNode).y;
			// Scroll to new section
			if (elYPos > editor.dom.getViewPort(editor.getWin()).h) {
					editor.getWin().scrollTo(0, elYPos);
			}

			editor.nodeChanged();
			return newNode;
		},

		getValidElements: function(target, where) {
			var options, ed = tinyMCE.activeEditor;

			target = target || ed.selection.getNode();
			where = where || 'inside';

			options = ed.plugins.textorum.validator.validElementsForNode(target, where, "array");

			// Textorum doesn't like putting things at the top level body, so account for top level section availability
			if (!options.length && target.className.toUpperCase() == 'SEC' && where !== 'inside') {
				options.push('sec');
			}

			return options;
		},

		getInfo : function() {
			return {
				longname : 'Textorum Context Aware Element Insertion',
				author : 'Crowd Favorite',
				authorurl : 'http://crowdfavorite.com',
				infourl : '',
				version : "1.0"
			};
		}
	});

	// Register plugin
	tinymce.PluginManager.add('textorumInsertion', tinymce.plugins.textorumInsertion);
})(jQuery);
<commit_msg>If button is disabled, it should also be in an inactive state<commit_after>(function($) {
	tinymce.create('tinymce.plugins.textorumInsertion', {
		init : function(ed, url) {
			var self = this,
				disabled = true,
				editor = ed,
				//cm = new tinymce.ControlManager(ed),
				//dropmenu = cm.createDropMenu('textorum-insertion-dropmenu'), // Not used in current editor
				dropmenuVisible = false,
				dropmenuJustClicked = false,
				ignoredElements = [
					'media',
					'xref',
					'disp-quote',
					'inline-graphic',
					'inline-formula',
					'disp-formula',
					'table-wrap',
					'bold',
					'italic',
					'monospace',
					'underline',
					'sup',
					'sub'
				];

			// Addresses Chrome 33 issue where fonts didnt displace unless repainted.
			jQuery.each(jQuery('.mceIcon'), function(index, el) {
				var $el = jQuery(el);
				var opacity = $el.css('opacity');
				$el.animate({opacity: opacity}, 1);
			})

			// Key Bindings
			//
			ed.onKeyDown.addToTop(function(ed, e) {
				var target, listItemParent;

				// Enter
				if (!e.shiftKey && e.keyCode == 13) {

					listItemParent = ed.dom.getParent(ed.selection.getNode(), '.list-item');

					// What to do if empty editor
					if (ed.getContent() == '') {

						// Abstract gets a
 tag
						if (ed.id == 'excerpt') {
							tinymce.dom.Event.cancel(e);
							return ed.setContent('

');
						}
						// Presumably article content.
						else {
							tinymce.dom.Event.cancel(e);
							return ed.setContent('

');
						}
					}

					// Ctrl + Enter
					if (e.ctrlKey) {
						tinymce.dom.Event.cancel(e);
						return ed.plugins.annoFormats.insertSection();
					}

					// List items
					if (listItemParent) {
						tinymce.dom.Event.cancel(e);
						return !self.insertElement('list-item', 'after', listItemParent);
					}

					// Get the parent tag and class
					parentTag = ed.dom.getParent(ed.selection.getNode().parentNode);
					elementClass = jQuery(ed.selection.getNode()).attr('class');
					parentClass = jQuery(parentTag).attr('class');

					// If it's a 'p' tag, we need its parent
					if (parentClass == 'p') {
						parentTag = ed.dom.getParent(parentTag.parentNode);
						parentClass = jQuery(ed.dom.getParent(parentTag)).attr('class');
					}

					// Only allow sections to be extended
					if (
						parentClass == 'caption' ||
						parentClass == 'fig' ||
						parentClass == 'tr'
					) {
						console.log(parentClass + ' cannot be extended');
						tinymce.dom.Event.cancel(e);
					}
					// If it's a title, then add a P tag instead of splitting
					else if (
						elementClass == 'title'
					) {
						tinymce.dom.Event.cancel(e);
						return !self.insertElement('p', 'after', ed.selection.getNode());
					}
				}
				return true;
			});

			editor.addCommand('Textorum_Insertion_Menu', function(ui, where) {
				var options, $button;

				$button = $('#'+editor.editorId).next('.mceEditor').find('.mceButton.mce_textorum-insertion-' + where);

				if (dropmenuVisible) {
					dropmenu.hideMenu();
					dropmenuVisible = false;
				}
				else {

					where = where || 'inside';
					options = self.getValidElements(editor.selection.getNode(), where);

					dropmenu.removeAll();

					if (options.length) {
						options = options.filter(function(a) { return ignoredElements.indexOf(a) === -1; });
						tinymce.each(options, function(element_name) {
							switch (element_name) {
								case 'list':
									dropmenu.add({ title: 'list (bulleted)', onclick: function() {
										self.insertElement(element_name, where, null, {
											'list-type': 'bullet'
										});
									}});

									dropmenu.add({ title: 'list (ordered)', onclick: function() {
										self.insertElement(element_name, where, null, {
											'list-type': 'order'
										});
									}});

									break;

								default:
									dropmenu.add(new tinymce.ui.MenuItem('textorum-insertion-item-' + element_name ,{
										title: element_name,
										onclick: function() {
											if (element_name == 'list') {
												self.insertElement(element_name, where, null, {
													'list-type': 'bullet'
												});
											}
											else {
												self.insertElement(element_name, where);
											}
										}
									}));
									break;
							}
						});
					}
					else {
						dropmenu.add(new tinymce.ui.MenuItem('textorum-insertion-item-none', {
							title: 'No elements available',
							style: 'color:#999',
							onclick: function() {
								dropmenuVisible = false;
								return false;
							}
						}));
					}

					dropmenu.showMenu($button.offset().left, $button.offset().top + 24);
					dropmenuJustClicked = dropmenuVisible = true;
					setTimeout(function() { dropmenuJustClicked = false; }, 250);

				}
			});

			editor.onNodeChange.add(function(ed, cm, node) {
				var options, inlineNames, buttonElementMap, firstBlock;
				if (node.nodeName == 'BR') {
					node = node.parentNode;
				}

				options = editor.plugins.textorum.validator.validElementsForNode(node, "inside", "array");
				inlineNames = ['SPAN', 'TT', 'EM', 'U', 'STRONG', 'SUP', 'SUB'];
				buttonElementMap = {
					list : [
						'annoorderedlist',
						'annobulletlist'
					],
					xref : [
						'annoreferences'
					],
					'disp-quote' : [
						'annoquote'
					],
					monospace : [
						'annomonospace'
					],
					preformat : [
						'annopreformat'
					],
					'table-wrap' : [
						'table'
					],
					sup : [
						'superscript'
					],
					sub : [
						'subscript'
					]
				};
				firstBlock = node;

				while (inlineNames.indexOf(firstBlock.nodeName) !== -1) {
					firstBlock = firstBlock.parentNode;
				}

				jQuery.each(buttonElementMap, function(elementName, buttons) {
					var tf = false;
					if (options.indexOf(elementName) === -1) {
						tf = true;
					}

					jQuery.each(buttons, function(index, buttonName) {
						buttonDisable(buttonName, tf);
					});
				});

				if (dropmenuVisible && !dropmenuJustClicked) {
					dropmenu.hideMenu();
					dropmenuVisible = false;
				}

				// enable indent when parent list
				if (ed.dom.getParent(node, '.list')) {
					buttonDisable('annooutdentlist', false);
					buttonDisable('annoindentlist', false);
					buttonDisable('annoorderedlist', false);
					buttonDisable('annobulletlist', false);

				}
				else {
					buttonDisable('annooutdentlist', true);
					buttonDisable('annoindentlist', true);
					buttonDisable('annoorderedlist', true);
					buttonDisable('annobulletlist', true);
				}

				if (firstBlock.getAttribute('data-xmlel') == 'p') {
					buttonDisable('annoorderedlist', false);
					buttonDisable('annobulletlist', false);
				}
				else {
					buttonDisable('annoorderedlist', true);
					buttonDisable('annobulletlist', true);
				}

				if (options.indexOf('inline-graphic') === -1 || options.indexOf('fig') === -1) {
					buttonDisable('annoimages', true);
					buttonDisable('annoequations', true);
				}
				else {
					buttonDisable('annoimages', false);
					buttonDisable('annoequations', false);
				}

				if (options.indexOf('disp-quote') === -1) {
					buttonDisable('annoquote', true);
				}
				else {
					buttonDisable('annoquote', false);
				}

				function buttonDisable(buttonName, tf) {
					if (tf) {
						cm.setActive(buttonName, false);
					}
					return cm.setDisabled(buttonName, tf);
				}
			});

			// Register example button
			editor.addButton('textorum-insertion-before', {
				title : 'Insert Element Before',
				cmd : 'Textorum_Insertion_Menu',
				value: 'before'
			});

			editor.addButton('textorum-insertion-inside', {
				title : 'Insert Element Inside',
				cmd : 'Textorum_Insertion_Menu',
				value: 'inside'
			});

			editor.addButton('textorum-insertion-after', {
				title : 'Insert Element After',
				cmd : 'Textorum_Insertion_Menu',
				value: 'after'
			});

			editor.addShortcut('ctrl+enter', 'Insert Element', 'Textorum_Insertion');
		},

		insertElement: function(element_name, where, target, attrs) {
			var editor = tinyMCE.activeEditor,
				newNode = editor.dom.create(
					editor.plugins.textorum.translateElement(element_name),
					tinymce.extend({'class': element_name, 'data-xmlel': element_name}, attrs),
					' '
				),
				range, elYPos, options;

			where = where || 'inside';
			target = target || editor.selection.getNode();

			options = this.getValidElements(target, where);

			if (options.indexOf(element_name) === -1) {
				return false;
			}

			// Add additionally required child elements
			switch (element_name) {

				case 'sec':
					newNode.innerHTML = '';
					newNode.appendChild(
						editor.dom.create(
							editor.plugins.textorum.translateElement('title'),
							{'class': 'title', 'data-xmlel': 'title'},
							' '
						)
					);
					break;

				case 'fig':
					(function() {
						var cap = editor.dom.create(
							editor.plugins.textorum.translateElement('caption'),
							{'class': 'caption', 'data-xmlel': 'caption'}
						);

						newNode.innerHTML = '';
						newNode.appendChild(
							editor.dom.create(
								editor.plugins.textorum.translateElement('label'),
								{'class': 'label', 'data-xmlel': 'label'},
								' '
							)
						);

						cap.appendChild(
							editor.dom.create(
								editor.plugins.textorum.translateElement('p'),
								{'class': 'p', 'data-xmlel': 'p'},
								' '
							)
						);

						newNode.appendChild(cap);
					})();
					break;

				case 'list':
					newNode.innerHTML = "";
					this.insertElement('list-item', 'inside', newNode);
					break;

				case 'list-item':
					newNode.innerHTML = '';
					newNode.appendChild(
						editor.dom.create(
							editor.plugins.textorum.translateElement('p'),
							{'class': 'p', 'data-xmlel': 'p'},
							' '
						)
					);
					break;
			}

			dropmenuVisible = false;

			switch(where) {
				case 'before':
					newNode = target.parentNode.insertBefore(newNode, target);
					break;

				case 'inside':
					newNode = target.appendChild(newNode);
					break;

				case 'after':
					if (target.nextSibling) {
						newNode = target.parentNode.insertBefore(newNode, target.nextSibling);
					}
					else {
						newNode = target.parentNode.appendChild(newNode);
					}
					break;
			}

			if (document.createRange) {     // all browsers, except IE before version 9
				range = document.createRange();
				if (newNode.firstChild) {
					range.selectNodeContents(newNode.firstChild);
				}
				else {
					range.selectNodeContents(newNode);
				}
			}

			range.collapse(1);
			editor.selection.setRng(range);

			elYPos = editor.dom.getPos(newNode).y;
			// Scroll to new section
			if (elYPos > editor.dom.getViewPort(editor.getWin()).h) {
					editor.getWin().scrollTo(0, elYPos);
			}

			editor.nodeChanged();
			return newNode;
		},

		getValidElements: function(target, where) {
			var options, ed = tinyMCE.activeEditor;

			target = target || ed.selection.getNode();
			where = where || 'inside';

			options = ed.plugins.textorum.validator.validElementsForNode(target, where, "array");

			// Textorum doesn't like putting things at the top level body, so account for top level section availability
			if (!options.length && target.className.toUpperCase() == 'SEC' && where !== 'inside') {
				options.push('sec');
			}

			return options;
		},

		getInfo : function() {
			return {
				longname : 'Textorum Context Aware Element Insertion',
				author : 'Crowd Favorite',
				authorurl : 'http://crowdfavorite.com',
				infourl : '',
				version : "1.0"
			};
		}
	});

	// Register plugin
	tinymce.PluginManager.add('textorumInsertion', tinymce.plugins.textorumInsertion);
})(jQuery);
<|endoftext|>


<commit_before>define([
  'mps',
  'backbone',
  'handlebars',
  'widgets/views/WidgetView',
  'text!countries/templates/country-national-grid.handlebars',
], function(mps, Backbone, Handlebars, WidgetView, tpl) {

  var NationalView = Backbone.View.extend({

    el: '.gridgraphs',

    template: Handlebars.compile(tpl),

    initialize: function(options) {
      this.iso     = options.country;
      this.parent  = options.parent;
      this.widgets = options.status.widgets;

      this._setupGrid();
    },

    _setupGrid: function() {
      var promises = [];

      if (!!this.activeWidgets && !!this.activeWidgets.length) {
        this.destroy();
      };

      this.activeWidgets = [];

      _.map(this.widgets[this.iso], function(w, key) {

          var deferred = $.Deferred();
          var newWidget = new WidgetView({
            model: {
              id: w[0].id,
              slug: this.iso,
              location: {
                iso: this.iso,
                jurisdiction: 0,
                area: 0
              },
            },
            className: 'gridgraphs-widget',
            status: this.widgets[this.iso][w[0].id][0]
          });

          newWidget._loadMetaData(function() {
            deferred.resolve();
          });

          this.activeWidgets.push(newWidget);
          promises.push(deferred);

      }.bind(this));

      $.when.apply(null, promises).then(function() {
        this.render(widgetsArray);
        mps.publish('Grid/ready', [{
          iso: this.iso,
          options: {
            view: 'national'
          }
        }]);

      }.bind(this));
    },

    destroy: function() {
      this.activeWidgets.forEach(function(widget) {
        widget.destroy();
      });
    },

    render: function(widgetsArray) {
      this.$el.html('');

      this.$el.removeClass();
      this.$el.addClass('gridgraphs -national');

      this.$el.html(this.template);

      widgetsArray.forEach(function(widget) {
        this.$el.find('.gridgraphs-container').append(widget.render().el);
      }.bind(this));

      this.parent.append(this.el);
    }

  });

  return NationalView;

});
<commit_msg>Changed variable<commit_after>define([
  'mps',
  'backbone',
  'handlebars',
  'widgets/views/WidgetView',
  'text!countries/templates/country-national-grid.handlebars',
], function(mps, Backbone, Handlebars, WidgetView, tpl) {

  var NationalView = Backbone.View.extend({

    el: '.gridgraphs',

    template: Handlebars.compile(tpl),

    initialize: function(options) {
      this.iso     = options.country;
      this.parent  = options.parent;
      this.widgets = options.status.widgets;

      this._setupGrid();
    },

    _setupGrid: function() {
      var promises = [];

      if (!!this.activeWidgets && !!this.activeWidgets.length) {
        this.destroy();
      };

      this.activeWidgets = [];

      _.map(this.widgets[this.iso], function(w, key) {

          var deferred = $.Deferred();
          var newWidget = new WidgetView({
            model: {
              id: w[0].id,
              slug: this.iso,
              location: {
                iso: this.iso,
                jurisdiction: 0,
                area: 0
              },
            },
            className: 'gridgraphs-widget',
            status: this.widgets[this.iso][w[0].id][0]
          });

          newWidget._loadMetaData(function() {
            deferred.resolve();
          });

          this.activeWidgets.push(newWidget);
          promises.push(deferred);

      }.bind(this));

      $.when.apply(null, promises).then(function() {
        this.render(this.activeWidgets);
        mps.publish('Grid/ready', [{
          iso: this.iso,
          options: {
            view: 'national'
          }
        }]);

      }.bind(this));
    },

    destroy: function() {
      this.activeWidgets.forEach(function(widget) {
        widget.destroy();
      });
    },

    render: function(widgetsArray) {
      this.$el.html('');

      this.$el.removeClass();
      this.$el.addClass('gridgraphs -national');

      this.$el.html(this.template);

      widgetsArray.forEach(function(widget) {
        this.$el.find('.gridgraphs-container').append(widget.render().el);
      }.bind(this));

      this.parent.append(this.el);
    }

  });

  return NationalView;

});
<|endoftext|>


<commit_before>/* eslint-disable no-param-reassign */

require('../lib/utils/text_utility');
const DEFAULT_EVENT_OBJECTS = require('./default_event_objects');

((global) => {
  global.cycleAnalytics = global.cycleAnalytics || {};

  const EMPTY_STAGE_TEXTS = {
    issue: 'The issue stage shows the time it takes from creating an issue to assigning the issue to a milestone, or add the issue to a list on your Issue Board. Begin creating issues to see data for this stage.',
    plan: 'The planning stage shows the time from the previous step to pushing your first commit. This time will be added automatically once you push your first commit.',
    code: 'The coding stage shows the time from the first commit to creating the merge request. The data will automatically be added here once you create your first merge request.',
    test: 'The testing stage shows the time GitLab CI takes to run every pipeline for the related merge request. The data will automatically be added after your first pipeline finishes running.',
    review: 'The review stage shows the time from creating the merge request to merging it. The data will automatically be added after you merge your first merge request.',
    staging: 'The staging stage shows the time between merging the MR and deploying code to the production environment. The data will be automatically added once you deploy to production for the first time.',
    production: 'The production stage shows the total time it takes between creating an issue and deploying the code to production. The data will be automatically added once you have completed the full idea to production cycle.',
  };

  global.cycleAnalytics.CycleAnalyticsStore = {
    state: {
      summary: '',
      stats: '',
      analytics: '',
      events: [],
      stages: [],
    },
    setCycleAnalyticsData(data) {
      this.state = Object.assign(this.state, this.decorateData(data));
    },
    decorateData(data) {
      const newData = {};

      newData.stages = data.stats || [];
      newData.summary = data.summary || [];

      newData.summary.forEach((item) => {
        item.value = item.value || '-';
      });

      newData.stages.forEach((item) => {
        const stageSlug = gl.text.dasherize(item.title.toLowerCase());
        item.active = false;
        item.isUserAllowed = data.permissions[stageSlug];
        item.emptyStageText = EMPTY_STAGE_TEXTS[stageSlug];
        item.component = `stage-${stageSlug}-component`;
        item.slug = stageSlug;
      });
      newData.analytics = data;
      return newData;
    },
    setLoadingState(state) {
      this.state.isLoading = state;
    },
    setErrorState(state) {
      this.state.hasError = state;
    },
    deactivateAllStages() {
      this.state.stages.forEach((stage) => {
        stage.active = false;
      });
    },
    setActiveStage(stage) {
      this.deactivateAllStages();
      stage.active = true;
    },
    setStageEvents(events, stage) {
      this.state.events = this.decorateEvents(events, stage);
    },
    decorateEvents(events, stage) {
      const newEvents = [];

      events.forEach((item) => {
        if (!item) return;

        const eventItem = Object.assign({}, DEFAULT_EVENT_OBJECTS[stage.slug], item);

        eventItem.totalTime = eventItem.total_time;
        eventItem.author.webUrl = eventItem.author.web_url;
        eventItem.author.avatarUrl = eventItem.author.avatar_url;

        if (eventItem.created_at) eventItem.createdAt = eventItem.created_at;
        if (eventItem.short_sha) eventItem.shortSha = eventItem.short_sha;
        if (eventItem.commit_url) eventItem.commitUrl = eventItem.commit_url;

        delete eventItem.author.web_url;
        delete eventItem.author.avatar_url;
        delete eventItem.total_time;
        delete eventItem.created_at;
        delete eventItem.short_sha;
        delete eventItem.commit_url;

        newEvents.push(eventItem);
      });

      return newEvents;
    },
    currentActiveStage() {
      return this.state.stages.find(stage => stage.active);
    },
  };
})(window.gl || (window.gl = {}));
<commit_msg>Clone nested objects from default data. Checks if key is present before accessing it<commit_after>/* eslint-disable no-param-reassign */

require('../lib/utils/text_utility');
const DEFAULT_EVENT_OBJECTS = require('./default_event_objects');

((global) => {
  global.cycleAnalytics = global.cycleAnalytics || {};

  const EMPTY_STAGE_TEXTS = {
    issue: 'The issue stage shows the time it takes from creating an issue to assigning the issue to a milestone, or add the issue to a list on your Issue Board. Begin creating issues to see data for this stage.',
    plan: 'The planning stage shows the time from the previous step to pushing your first commit. This time will be added automatically once you push your first commit.',
    code: 'The coding stage shows the time from the first commit to creating the merge request. The data will automatically be added here once you create your first merge request.',
    test: 'The testing stage shows the time GitLab CI takes to run every pipeline for the related merge request. The data will automatically be added after your first pipeline finishes running.',
    review: 'The review stage shows the time from creating the merge request to merging it. The data will automatically be added after you merge your first merge request.',
    staging: 'The staging stage shows the time between merging the MR and deploying code to the production environment. The data will be automatically added once you deploy to production for the first time.',
    production: 'The production stage shows the total time it takes between creating an issue and deploying the code to production. The data will be automatically added once you have completed the full idea to production cycle.',
  };

  global.cycleAnalytics.CycleAnalyticsStore = {
    state: {
      summary: '',
      stats: '',
      analytics: '',
      events: [],
      stages: [],
    },
    setCycleAnalyticsData(data) {
      this.state = Object.assign(this.state, this.decorateData(data));
    },
    decorateData(data) {
      const newData = {};

      newData.stages = data.stats || [];
      newData.summary = data.summary || [];

      newData.summary.forEach((item) => {
        item.value = item.value || '-';
      });

      newData.stages.forEach((item) => {
        const stageSlug = gl.text.dasherize(item.title.toLowerCase());
        item.active = false;
        item.isUserAllowed = data.permissions[stageSlug];
        item.emptyStageText = EMPTY_STAGE_TEXTS[stageSlug];
        item.component = `stage-${stageSlug}-component`;
        item.slug = stageSlug;
      });
      newData.analytics = data;
      return newData;
    },
    setLoadingState(state) {
      this.state.isLoading = state;
    },
    setErrorState(state) {
      this.state.hasError = state;
    },
    deactivateAllStages() {
      this.state.stages.forEach((stage) => {
        stage.active = false;
      });
    },
    setActiveStage(stage) {
      this.deactivateAllStages();
      stage.active = true;
    },
    setStageEvents(events, stage) {
      this.state.events = this.decorateEvents(events, stage);
    },
    decorateEvents(events, stage) {
      const newEvents = [];

      events.forEach((item) => {
        if (!item) return;

        const eventItem = Object.assign({}, DEFAULT_EVENT_OBJECTS[stage.slug], item);

        eventItem.totalTime = eventItem.total_time;

        if (eventItem.author) {
          eventItem.author.webUrl = eventItem.author.web_url;
          eventItem.author.avatarUrl = eventItem.author.avatar_url;
        }

        if (eventItem.created_at) eventItem.createdAt = eventItem.created_at;
        if (eventItem.short_sha) eventItem.shortSha = eventItem.short_sha;
        if (eventItem.commit_url) eventItem.commitUrl = eventItem.commit_url;

        delete eventItem.author.web_url;
        delete eventItem.author.avatar_url;
        delete eventItem.total_time;
        delete eventItem.created_at;
        delete eventItem.short_sha;
        delete eventItem.commit_url;

        newEvents.push(eventItem);
      });

      return newEvents;
    },
    currentActiveStage() {
      return this.state.stages.find(stage => stage.active);
    },
  };
})(window.gl || (window.gl = {}));
<|endoftext|>


<commit_before>/* global analytics, dataLayer */

function ensureGTM(timeout) {
  var start = Date.now();
  return new Promise(waitForGTM);
  function waitForGTM(resolve, reject) {
    if (typeof dataLayer !== 'undefined') {
      return resolve();
    } else if (timeout && Date.now() - start >= timeout) {
      return reject(new Error('Timeout'));
    }
    setTimeout(waitForGTM.bind(this, resolve, reject), 50);
  }
}
/**
 * Analytics wrapper for the Segment to GTM integration
 */
const lmnAnalytics = {
  track: function (action, properties, options, callback) {
    return ensureGTM().then(() => {
      analytics.track.apply(this, arguments);
      if (typeof options === 'function') {
        callback = options;
        options = null;
      }
      if (typeof properties === 'function') {
        callback = properties;
        options = null;
        properties = {};
      }
      if (!properties) {
        properties = {};
      }
      if (!properties.category) {
        properties.category = 'All';
      }
      dataLayer.push(
        Object.assign(properties, {
          event: action,
          action: action,
          category: properties.category,
          label: properties.label,
          value: properties.value
        })
      );
      if (callback) {
        callback();
      }
    });
  },
  page: function (category, name, properties, options, callback) {
    return ensureGTM().then(() => {
      analytics.page.apply(this, arguments);
      if (typeof options === 'function') {
        callback = options;
        options = null;
      }
      if (typeof properties === 'function') {
        callback = properties;
        options = null;
        properties = null;
      }
      if (typeof name === 'function') {
        callback = name;
        options = null;
        properties = null;
        name = null;
      }
      if (typeof name === 'object') {
        options = properties;
        properties = name;
        name = null;
      }
      if (typeof category === 'string' && typeof name !== 'string') {
        name = category;
        category = null;
      }
      if (callback) {
        callback();
      }
      if (typeof properties !== 'function') {
        dataLayer.push(properties);
      }
      return this;
    });
  },
  identify: function (id, traits, options, callback) {
    return ensureGTM().then(() => {
      analytics.identify.apply(this, arguments);
      if (typeof options === 'function') {
        callback = options;
        options = null;
      }
      if (typeof traits === 'function') {
        callback = traits;
        options = null;
        traits = null;
      }
      dataLayer.push({
        user: {
          userId: id
        }
      });
      if (traits && typeof traits !== 'function') {
        Object.keys(traits).forEach(trait => {
          if (trait.startsWith('Experiment:')) {
            dataLayer.push({
              experimentName: trait,
              experimentVariant: traits[trait]
            });
          }
        });
      }

      if (callback) {
        callback();
      }
      return this;
    });
  },
  impression: function (impressions) {
    return ensureGTM().then(() => {
      impressions.forEach(impression => {
        analytics.track('Viewed Impression', impression);
      });
      dataLayer.push({
        ecommerce: {
          impressions: impressions
        }
      });
    });
  },
  ready: function (callback) {
    if (callback) {
      callback();
    }
    return this;
  }
};

export default lmnAnalytics;
<commit_msg>Remove type check<commit_after>/* global analytics, dataLayer */

function ensureGTM(timeout) {
  var start = Date.now();
  return new Promise(waitForGTM);
  function waitForGTM(resolve, reject) {
    if (typeof dataLayer !== 'undefined') {
      return resolve();
    } else if (timeout && Date.now() - start >= timeout) {
      return reject(new Error('Timeout'));
    }
    setTimeout(waitForGTM.bind(this, resolve, reject), 50);
  }
}
/**
 * Analytics wrapper for the Segment to GTM integration
 */
const lmnAnalytics = {
  track: function (action, properties, options, callback) {
    return ensureGTM().then(() => {
      analytics.track.apply(this, arguments);
      if (typeof options === 'function') {
        callback = options;
        options = null;
      }
      if (typeof properties === 'function') {
        callback = properties;
        options = null;
        properties = {};
      }
      if (!properties) {
        properties = {};
      }
      if (!properties.category) {
        properties.category = 'All';
      }
      dataLayer.push(
        Object.assign(properties, {
          event: action,
          action: action,
          category: properties.category,
          label: properties.label,
          value: properties.value
        })
      );
      if (callback) {
        callback();
      }
    });
  },
  page: function (category, name, properties, options, callback) {
    return ensureGTM().then(() => {
      analytics.page.apply(this, arguments);
      if (typeof options === 'function') {
        callback = options;
        options = null;
      }
      if (typeof properties === 'function') {
        callback = properties;
        options = null;
        properties = null;
      }
      if (typeof name === 'function') {
        callback = name;
        options = null;
        properties = null;
        name = null;
      }
      if (typeof name === 'object') {
        options = properties;
        properties = name;
        name = null;
      }
      if (typeof category === 'string' && typeof name !== 'string') {
        name = category;
        category = null;
      }
      if (callback) {
        callback();
      }
      dataLayer.push(properties);
      return this;
    });
  },
  identify: function (id, traits, options, callback) {
    return ensureGTM().then(() => {
      analytics.identify.apply(this, arguments);
      if (typeof options === 'function') {
        callback = options;
        options = null;
      }
      if (typeof traits === 'function') {
        callback = traits;
        options = null;
        traits = null;
      }
      dataLayer.push({
        user: {
          userId: id
        }
      });
      if (traits && typeof traits !== 'function') {
        Object.keys(traits).forEach(trait => {
          if (trait.startsWith('Experiment:')) {
            dataLayer.push({
              experimentName: trait,
              experimentVariant: traits[trait]
            });
          }
        });
      }

      if (callback) {
        callback();
      }
      return this;
    });
  },
  impression: function (impressions) {
    return ensureGTM().then(() => {
      impressions.forEach(impression => {
        analytics.track('Viewed Impression', impression);
      });
      dataLayer.push({
        ecommerce: {
          impressions: impressions
        }
      });
    });
  },
  ready: function (callback) {
    if (callback) {
      callback();
    }
    return this;
  }
};

export default lmnAnalytics;
<|endoftext|>


<commit_before>import fs from './fs';
import lodashModules from './lodashModules';
import parseForModules from './parseForModules';

import {flatten, includes, isArray, uniq} from 'lodash';
import Promise from 'bluebird';
const glob = Promise.promisify(require('glob'));

import esperantoBuild from './esperanto-build';
import cliBuild from './cli-build';
import Error from './Error';

export function resolve(files, options) {
  return Promise.map(files, file => {
    return fs.readFileAsync(file).then(blob => parseForModules(blob, file, options))
      .then(methods => {
        if (includes(methods, 'chain')) {
          throw new Error('Chaining syntax is not yet supported', file);
        }
        return methods;
      });
  })
  .then(methods => {
    return uniq(flatten(methods));
  });
}

export default function modularize(fileGlob, options) {
  let files = (isArray(fileGlob) ? Promise.resolve(fileGlob) : glob(fileGlob))
    .then(files => resolve(files, options));

  return Promise.all([files, lodashModules])
    .spread((methods, modules) => {
      // What to do with the resulting methods (e.g. export, list, etc)
      if (options.list) {
        return methods;
      }
      let code;
      if (options.compile) {
        code = cliBuild(methods, options);
      } else {
        code = esperantoBuild(methods, modules, options).code;
      }
      let $code = Promise.resolve(code);
      if (options.output) {
        return $code
          .then(code => fs.writeFileAsync(options.output, code))
          .then(() => $code);
      }
      return $code;
    });
}

module.exports = modularize;
<commit_msg>Sort modules before outputting them<commit_after>import fs from './fs';
import lodashModules from './lodashModules';
import parseForModules from './parseForModules';

import {flatten, includes, isArray, uniq} from 'lodash';
import Promise from 'bluebird';
const glob = Promise.promisify(require('glob'));

import esperantoBuild from './esperanto-build';
import cliBuild from './cli-build';
import Error from './Error';

export function resolve(files, options) {
  return Promise.map(files, file => {
    return fs.readFileAsync(file).then(blob => parseForModules(blob, file, options))
      .then(methods => {
        if (includes(methods, 'chain')) {
          throw new Error('Chaining syntax is not yet supported', file);
        }
        return methods;
      });
  })
  .then(methods => {
    return uniq(flatten(methods).sort(), true);
  });
}

export default function modularize(fileGlob, options) {
  let files = (isArray(fileGlob) ? Promise.resolve(fileGlob) : glob(fileGlob))
    .then(files => resolve(files, options));

  return Promise.all([files, lodashModules])
    .spread((methods, modules) => {
      // What to do with the resulting methods (e.g. export, list, etc)
      if (options.list) {
        return methods;
      }
      let code;
      if (options.compile) {
        code = cliBuild(methods, options);
      } else {
        code = esperantoBuild(methods, modules, options).code;
      }
      let $code = Promise.resolve(code);
      if (options.output) {
        return $code
          .then(code => fs.writeFileAsync(options.output, code))
          .then(() => $code);
      }
      return $code;
    });
}

module.exports = modularize;
<|endoftext|>