<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { formatNumber, formatPercentage } from 'common/format';
import Toggle from 'react-toggle';
import ReactTooltip from 'react-tooltip';
import PerformanceBar from 'common/performanceBar';
import SpellLink from 'common/SpellLink';

class HealingEfficiencyBreakdown extends React.Component {
  static propTypes = {
    tracker: PropTypes.object.isRequired,
  };

  constructor() {
    super();
    this.state = {
      showHealing: true,
      detailedView: false,
      showCooldowns: false,
    };
  }

  HealingEfficiencyTable = (props) => {
    const { tracker } = props;
    const { spells, topHpm, topDpm, topHpet, topDpet } = tracker.getAllSpellStats(this.state.showCooldowns);

    const spellArray = Object.values(spells);

    spellArray.sort((a, b) => {
      if (this.state.showHealing) {
        if (a.hpm  b.hpm) {
          return -1;
        }
      } else {
        if (a.dpm  b.dpm) {
          return -1;
        }
      }

      return 0;
    });

    const spellRows = spellArray.map((spellDetail => {
      if (spellDetail.casts > 0) {
        return this.HealingEfficiencySpellRow(spellDetail, topHpm, topDpm, topHpet, topDpet);
      }
      return null;
    }));

    return spellRows;
  };

  HealingEfficiencySpellRow = (spellDetail, topHpm, topDpm, topHpet, topDpet) => {
    return (

          <SpellLink id={spellDetail.spell.id} />

        {this.state.detailedView ? <this.DetailView spellDetail={spellDetail} /> : <this.BarView spellDetail={spellDetail} topHpm={topHpm} topDpm={topDpm} topHpet={topHpet} topDpet={topDpet} />}

    );
  };

  BarHeader = () => {
    return (
      <>
        Mana Spent
        {this.state.showHealing && (
          <>
            Healing per mana spent
            Healing per second spent casting
          </>
        )}
        {!this.state.showHealing && (
          <>
            Damage per mana spent
            Damage per second spent casting
          </>
        )}
      </>
    );
  };

  BarView = (props) => {
    const { spellDetail, topHpm, topDpm, topHpet, topDpet } = props;
    const hasHealing = spellDetail.healingDone;
    const hasDamage = spellDetail.damageDone > 0;
    const barWidth = 20;

    return (
      <>

          {formatNumber(spellDetail.manaSpent)}
          {' (' + formatPercentage(spellDetail.manaPercentSpent) + '%)'}

        {this.state.showHealing && (
          <>
            {hasHealing ? formatNumber(spellDetail.hpm) : '-'}
            <PerformanceBar percent={spellDetail.hpm / topHpm} />

            {hasHealing ? formatNumber(spellDetail.hpet * 1000) : '-'}
            <PerformanceBar percent={(spellDetail.hpet / topHpet)} />
          </>
        )}
        {!this.state.showHealing && (
          <>
            {hasDamage ? formatNumber(spellDetail.dpm) : '-'}
            <PerformanceBar percent={spellDetail.dpm / topDpm} />

            {hasDamage ? formatNumber(spellDetail.dpet * 1000) : '-'}
            <PerformanceBar percent={(spellDetail.dpet / topDpet)} />
          </>
        )}
      </>
    );
  };

  DetailHeader = () => {
    return (
      <>

          <dfn data-tip={`Total Casts (Number of targets hit)`}>Casts</dfn>

        Mana Spent
        {this.state.showHealing && (
          <>
            Healing Done
            Overhealing

              <dfn data-tip={`Healing per mana spent casting the spell`}>HPM</dfn>

              <dfn data-tip={`Healing per second spent casting the spell`}>HPET</dfn>

          </>
        )}
        {!this.state.showHealing && (
          <>
            Damage Done

              <dfn data-tip={`Damage per mana spent casting the spell`}>DPM</dfn>

              <dfn data-tip={`Damage per second spent casting the spell`}>DPET</dfn>

          </>
        )}
      </>
    );
  };

  DetailView = (props) => {
    const { spellDetail } = props;
    const hasHealing = spellDetail.healingDone;
    const hasOverhealing = spellDetail.healingDone > 0 || spellDetail.overhealingDone > 0;
    const hasDamage = spellDetail.damageDone > 0;

    return (
      <>
        {spellDetail.casts} ({this.state.showHealing ? Math.floor(spellDetail.healingHits) : Math.floor(spellDetail.damageHits)})

          {formatNumber(spellDetail.manaSpent)}
          {' (' + formatPercentage(spellDetail.manaPercentSpent) + '%)'}

        {this.state.showHealing && (
          <>

              {hasHealing ? formatNumber(spellDetail.healingDone) : '-'}
              {hasHealing ? ' (' + formatPercentage(spellDetail.percentHealingDone) + '%)' : ''}

              {hasOverhealing ? formatNumber(spellDetail.overhealingDone) : '-'}
              {hasOverhealing ? ' (' + formatPercentage(spellDetail.percentOverhealingDone) + '%)' : ''}

            {hasHealing ? formatNumber(spellDetail.hpm) : '-'}
            {hasHealing ? formatNumber(spellDetail.hpet * 1000) : '-'}
          </>
        )}
        {!this.state.showHealing && (
          <>

              {hasDamage ? formatNumber(spellDetail.damageDone) : '-'}
              {hasDamage ? ' (' + formatPercentage(spellDetail.percentDamageDone) + '%)' : ''}

            {hasDamage ? formatNumber(spellDetail.dpm) : '-'}
            {hasDamage ? formatNumber(spellDetail.dpet * 1000) : '-'}
          </>
        )}
      </>
    );
  };

  componentDidUpdate() {
    ReactTooltip.rebuild();
  }

  render() {
    const { tracker } = this.props;
console.log(tracker);
    return (

                <Toggle
                  defaultChecked={false}
                  icons={false}
                  onChange={event => this.setState({ detailedView: event.target.checked })}
                  id="detailed-toggle"
                />

                  Detailed View

                <Toggle
                  defaultChecked={false}
                  icons={false}
                  onChange={event => this.setState({ showCooldowns: event.target.checked })}
                  id="cooldown-toggle"
                />

                  Show Cooldowns

                  Show Damage

                <Toggle
                  defaultChecked
                  icons={false}
                  onChange={event => this.setState({ showHealing: event.target.checked })}
                  id="healing-toggle"
                />

                  Show Healing

                  Ability
                  {this.state.detailedView ? <this.DetailHeader /> : <this.BarHeader />}

                <this.HealingEfficiencyTable tracker={tracker} showHealing={this.state.showHealing} />

    );
  }
}

export default HealingEfficiencyBreakdown;
<commit_msg>whoops<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { formatNumber, formatPercentage } from 'common/format';
import Toggle from 'react-toggle';
import ReactTooltip from 'react-tooltip';
import PerformanceBar from 'common/performanceBar';
import SpellLink from 'common/SpellLink';

class HealingEfficiencyBreakdown extends React.Component {
  static propTypes = {
    tracker: PropTypes.object.isRequired,
  };

  constructor() {
    super();
    this.state = {
      showHealing: true,
      detailedView: false,
      showCooldowns: false,
    };
  }

  HealingEfficiencyTable = (props) => {
    const { tracker } = props;
    const { spells, topHpm, topDpm, topHpet, topDpet } = tracker.getAllSpellStats(this.state.showCooldowns);

    const spellArray = Object.values(spells);

    spellArray.sort((a, b) => {
      if (this.state.showHealing) {
        if (a.hpm  b.hpm) {
          return -1;
        }
      } else {
        if (a.dpm  b.dpm) {
          return -1;
        }
      }

      return 0;
    });

    const spellRows = spellArray.map((spellDetail => {
      if (spellDetail.casts > 0) {
        return this.HealingEfficiencySpellRow(spellDetail, topHpm, topDpm, topHpet, topDpet);
      }
      return null;
    }));

    return spellRows;
  };

  HealingEfficiencySpellRow = (spellDetail, topHpm, topDpm, topHpet, topDpet) => {
    return (

          <SpellLink id={spellDetail.spell.id} />

        {this.state.detailedView ? <this.DetailView spellDetail={spellDetail} /> : <this.BarView spellDetail={spellDetail} topHpm={topHpm} topDpm={topDpm} topHpet={topHpet} topDpet={topDpet} />}

    );
  };

  BarHeader = () => {
    return (
      <>
        Mana Spent
        {this.state.showHealing && (
          <>
            Healing per mana spent
            Healing per second spent casting
          </>
        )}
        {!this.state.showHealing && (
          <>
            Damage per mana spent
            Damage per second spent casting
          </>
        )}
      </>
    );
  };

  BarView = (props) => {
    const { spellDetail, topHpm, topDpm, topHpet, topDpet } = props;
    const hasHealing = spellDetail.healingDone;
    const hasDamage = spellDetail.damageDone > 0;
    const barWidth = 20;

    return (
      <>

          {formatNumber(spellDetail.manaSpent)}
          {' (' + formatPercentage(spellDetail.manaPercentSpent) + '%)'}

        {this.state.showHealing && (
          <>
            {hasHealing ? formatNumber(spellDetail.hpm) : '-'}
            <PerformanceBar percent={spellDetail.hpm / topHpm} />

            {hasHealing ? formatNumber(spellDetail.hpet * 1000) : '-'}
            <PerformanceBar percent={(spellDetail.hpet / topHpet)} />
          </>
        )}
        {!this.state.showHealing && (
          <>
            {hasDamage ? formatNumber(spellDetail.dpm) : '-'}
            <PerformanceBar percent={spellDetail.dpm / topDpm} />

            {hasDamage ? formatNumber(spellDetail.dpet * 1000) : '-'}
            <PerformanceBar percent={(spellDetail.dpet / topDpet)} />
          </>
        )}
      </>
    );
  };

  DetailHeader = () => {
    return (
      <>

          <dfn data-tip={`Total Casts (Number of targets hit)`}>Casts</dfn>

        Mana Spent
        {this.state.showHealing && (
          <>
            Healing Done
            Overhealing

              <dfn data-tip={`Healing per mana spent casting the spell`}>HPM</dfn>

              <dfn data-tip={`Healing per second spent casting the spell`}>HPET</dfn>

          </>
        )}
        {!this.state.showHealing && (
          <>
            Damage Done

              <dfn data-tip={`Damage per mana spent casting the spell`}>DPM</dfn>

              <dfn data-tip={`Damage per second spent casting the spell`}>DPET</dfn>

          </>
        )}
      </>
    );
  };

  DetailView = (props) => {
    const { spellDetail } = props;
    const hasHealing = spellDetail.healingDone;
    const hasOverhealing = spellDetail.healingDone > 0 || spellDetail.overhealingDone > 0;
    const hasDamage = spellDetail.damageDone > 0;

    return (
      <>
        {spellDetail.casts} ({this.state.showHealing ? Math.floor(spellDetail.healingHits) : Math.floor(spellDetail.damageHits)})

          {formatNumber(spellDetail.manaSpent)}
          {' (' + formatPercentage(spellDetail.manaPercentSpent) + '%)'}

        {this.state.showHealing && (
          <>

              {hasHealing ? formatNumber(spellDetail.healingDone) : '-'}
              {hasHealing ? ' (' + formatPercentage(spellDetail.percentHealingDone) + '%)' : ''}

              {hasOverhealing ? formatNumber(spellDetail.overhealingDone) : '-'}
              {hasOverhealing ? ' (' + formatPercentage(spellDetail.percentOverhealingDone) + '%)' : ''}

            {hasHealing ? formatNumber(spellDetail.hpm) : '-'}
            {hasHealing ? formatNumber(spellDetail.hpet * 1000) : '-'}
          </>
        )}
        {!this.state.showHealing && (
          <>

              {hasDamage ? formatNumber(spellDetail.damageDone) : '-'}
              {hasDamage ? ' (' + formatPercentage(spellDetail.percentDamageDone) + '%)' : ''}

            {hasDamage ? formatNumber(spellDetail.dpm) : '-'}
            {hasDamage ? formatNumber(spellDetail.dpet * 1000) : '-'}
          </>
        )}
      </>
    );
  };

  componentDidUpdate() {
    ReactTooltip.rebuild();
  }

  render() {
    const { tracker } = this.props;

    return (

                <Toggle
                  defaultChecked={false}
                  icons={false}
                  onChange={event => this.setState({ detailedView: event.target.checked })}
                  id="detailed-toggle"
                />

                  Detailed View

                <Toggle
                  defaultChecked={false}
                  icons={false}
                  onChange={event => this.setState({ showCooldowns: event.target.checked })}
                  id="cooldown-toggle"
                />

                  Show Cooldowns

                  Show Damage

                <Toggle
                  defaultChecked
                  icons={false}
                  onChange={event => this.setState({ showHealing: event.target.checked })}
                  id="healing-toggle"
                />

                  Show Healing

                  Ability
                  {this.state.detailedView ? <this.DetailHeader /> : <this.BarHeader />}

                <this.HealingEfficiencyTable tracker={tracker} showHealing={this.state.showHealing} />

    );
  }
}

export default HealingEfficiencyBreakdown;
<|endoftext|>


<commit_before>// Script for new page and edit page form

window.slugChecking = false;
$(() => {
    const url = $(".main-form")
            .first()
            .data("get-content-types-url");

    $.ajax({
        url,
        success: (response) => {
            AllTypes = response;
            showAndHideFieldsByTypeWithoutEffects();
            $(".loadspinner").hide();
            $(".pageform").show();
            // Refresh CodeMirror
            refreshCodeMirrors();
            $(".accordion-header").click(() => refreshCodeMirrors());
        }
    });

    bindEvents();
    slugOrLanguageChanged();
    filterParentPages();

    $(".new-page-form #btn-submit").click((event) => {
        const form = $(event.target).closest("form");

        event.preventDefault();
        event.stopPropagation();

        if (!form.hasClass("edit-page-form") && form.get(0).reportValidity()) {
            $(window).off("beforeunload");
            $(form).off("submit");
            form.submit();
        } else {
            const hiddenInvalidElements = form.find(
                    "input, select, checkbox, textarea, radio"
                    ).filter(':hidden').toArray().
                    filter((x) => !x.checkValidity());

            if (hiddenInvalidElements.length) {
                bootbox.alert(PageTranslation.FillAllRequiredFields);
            }
        }
    });

    // AJAX submit page edit form
    $(".edit-page-form").ajaxForm({
        beforeSubmit: () => {
            $("#message-page-edit").html("");
            $("#message-page-edit").hide();
            $(".loading").show();
        },
        beforeSerialize: () => {
            updateCKEditors()
            return true;
        },
        success: () => {
            $(".loading").hide();
            $("#message-page-edit").html(
                    `
                        ${Translation.PageSaved}
                     `
                    );
            $("#message-page-edit").show();
        }
    });

    // check if a slug is free on changing system title or menu
    $("input[name='slug']").blur(() => slugOrLanguageChanged());
    $("input[name='title']").blur(() => slugOrLanguageChanged());

    $("select[name='menu']").change(() => filterParentPages());

    // check if slug is free and update parent page options
    $("select[name='language']").change(() => {
        slugOrLanguageChanged();
        filterParentPages();
    });

    // bind event to "View" button at the bottom of page edit form
    $("#btn-view-page").click(() => {
        const url = "../?goid=" + $("#page_id").val();
        // if page has unsaved changes open it in new window/tab
        // else open it in the same window/tab
        if (formChanged && !submitted) {
            window.open(url);
        } else {
            location.href = url;
        }
    });
});

showAndHideFieldsByTypeWithoutEffects = () => {
    const type = $("input[name=type]:checked").val();

    $(".typedep").hide();
    if (typeof AllTypes[type] === 'undefined') {
        return;
    }

    const typeData = AllTypes[type];
    const show = typeData["show"];

    show.forEach((element) => $(element).show());

    if ($("#type_snippet").is(":checked")) {
        unbindEvents();
        $("select[name='hidden']")
                .val("1")
                .trigger("change");
        $("select[name='menu']")
                .val("not_in_menu")
                .trigger("change");
        bindEvents();
    }

    $(".custom-field-tab").each((index, el) => {
        if ($(el).data("type") === $("input[name='type']:checked").val()) {
            $(el).find("input, select, checkbox, radio, button, submit").prop("disabled", false);
            $(el).show();
        } else {
            $(el).hide();
            $(el).find("input, select, checkbox, radio, button, submit").prop("disabled", true);
        }
    });

    if ($("#type_node").is(":checked") || $("#type_snippet").is(":checked")) {
        $("#btn-view-page").hide();
    } else {
        $("#btn-view-page").show();
    }

    if ($("select[name='menu']").val() === "not_in_menu") {
        $("#parent-div").hide();
        $("#menu_image_div").hide();
    } else {
        $("#parent-div").show();
        $("#menu_image_div").show();
    }
};

// this function shows and hides areas for the selected content type
showAndHideFieldsByType = () => {
    const type = $("input[name=type]:checked").val();
    const showSelector = AllTypes[type]["show"].join(",");
    $(".typedep")
            .not(showSelector)
            .slideUp();
    const typeData = AllTypes[type];
    const show = typeData["show"];

    show.forEach((element) => $(element).slideDown());

    if ($("#type_snippet").is(":checked")) {
        unbindEvents();
        $("select[name='hidden']")
                .val("1")
                .trigger("change");
        $("select[name='menu']")
                .val("not_in_menu")
                .trigger("change");
        bindEvents();
    }

    $(".custom-field-tab").each((index, el) => {
        if ($(el).data("type") === $("input[name='type']:checked").val()) {
            $(el).slideDown();
            $(el).find("input, select, button, submit").prop("disabled", false);
        } else {
            $(el).slideUp();
            $(el).find("input, select, button, submit").prop("disabled", true);
        }
    });

    if ($("#type_node").is(":checked") || $("#type_snippet").is(":checked")) {
        $("#btn-view-page").slideUp();
    } else {
        $("#btn-view-page").slideDown();
    }

    if ($("select[name='menu']").val() === "not_in_menu") {
        $("#parent-div").slideUp();
        $("#menu_image_div").slideUp();
    } else {
        $("#parent-div").slideDown();
        $("#menu_image_div").slideDown();
    }
};

/* global Translation, formChanged, submitted, bootbox, instance, CKEDITOR */

let AllTypes = {};

// this shows a thumbnail of the selected file on text inputs with
// fm image uploader attached
refreshFieldThumbnails = () => {
    $("input.fm[data-fm-type=images]").each((index, element) => {
        const id = $(element).attr("name");
        if ($(element).val().length > 0) {
            $("img#thumbnail-" + id).attr("src", $(element).val());
            $("img#thumbnail-" + id).show();
        } else {
            $("img#thumbnail-" + id).hide();
        }
    });
};

// Bind events for dependend fields, clear-buttons, and file inputs
bindEvents = () => {
    $('input[name="type"]').change(showAndHideFieldsByType);
    $("select[name='menu']").change(showAndHideFieldsByType);
    $("select[name='menu']")
            .select2("destroy")
            .select2({
                width: "100%"
            });
    $(".clear-field").on("click", (event) => {
        event.preventDefault();
        event.stopPropagation()
        const element = $(event.target);
        const linkFor = $(element).data("for");
        $(linkFor).val("");
        refreshFieldThumbnails();
    });

    refreshFieldThumbnails();
    $("input.fm").on("click", (event) => {
        const field = $(event.target);

        const name = $(field).attr("id")
                ? $(field).attr("id")
                : $(field).attr("name")

        const type = $(field).data("fm-type")
                ? $(field).data("fm-type")
                : "images";

        window.open(
                "fm/dialog.php?fldr=" +
                type +
                "&editor=ckeditor&type=2&langCode=" +
                $("html").data("select2-language") + "&popup=1&field_id=" + field.attr("id"),
                name,
                "status=0, toolbar=0, location=0, menubar=0, directories=0, " +
                "resizable=1, scrollbars=0, width=850, height=600"
                );
    });
};
// undbindEvents to prevent endless loop when selecting specific content types
unbindEvents = () => {
    $('input[name="type"]').off("change");
    $("select[name='menu']").off("change");
    $("input.fm").off("click");
    $(".clear-field").off("click");
};

// this suggest a slug which may be used as the url for a page
suggestSlug = (text) => {
    const pageSlug = slug(text, {lower: true});
    $("#slug").val(pageSlug);
};

// this checks if a slug is free within the selected language
// the combination of slug + language must be unique
slugOrLanguageChanged = () => {
    if (window.slugChecking) {
        return;
    }
    window.slugChecking = true;
    const id_field = $("input[name='page_id']");
    let myid = 0;
    if (id_field) {
        myid = $(id_field).val();
    }
    const data = {
        csrf_token: $("input[name=csrf_token]")
                .first()
                .val(),
        slug: $("input[name='slug']").val(),
        language: $("select[name='language']").val(),
        id: myid
    };
    const url = $(".main-form")
            .first()
            .data("slug-free-url");

    $.get(url, data, function (text) {
        if (text.length > $("input[name='slug']").val().length) {
            $("input[name='slug']").val(text);
        }
        window.slugChecking = false;
    });
};

// filter parent pages by selected language and menu
filterParentPages = () => {
    const data = {
        csrf_token: $("input[name=csrf_token]")
                .first()
                .val(),
        mlang: $("select[name='language']").val(),
        mmenu: $("select[name='menu']").val(),
        mparent: $("select[name='parent_id']").val()
    };

    const url = $(".main-form")
            .first()
            .data("parent-pages-url");
    $.get(url, data, function (text, status) {
        $("select[name='parent_id']").html(text);
    });
};
<commit_msg>Update form.js<commit_after>// Script for new page and edit page form

window.slugChecking = false;
$(() => {
    const url = $(".main-form")
            .first()
            .data("get-content-types-url");

    $.ajax({
        url,
        success: (response) => {
            AllTypes = response;
            showAndHideFieldsByTypeWithoutEffects();
            $(".loadspinner").hide();
            $(".pageform").show();
            // Refresh CodeMirror
            refreshCodeMirrors();
            $(".accordion-header").click(() => refreshCodeMirrors());
        }
    });

    bindEvents();
    slugOrLanguageChanged();
    filterParentPages();

    $(".new-page-form #btn-submit").click((event) => {
        const form = $(event.target).closest("form");

        event.preventDefault();
        event.stopPropagation();

        if (!form.hasClass("edit-page-form") && form.get(0).reportValidity()) {
            $(window).off("beforeunload");
            $(form).off("submit");
            form.submit();
        } else {
            const hiddenInvalidElements = form.find(
                    "input, select, checkbox, textarea, radio"
                    ).filter(':hidden').toArray().
                    filter((x) => !x.checkValidity());

            if (hiddenInvalidElements.length) {
                bootbox.alert(PageTranslation.FillAllRequiredFields);
            }
        }
    });

    // AJAX submit page edit form
    $(".edit-page-form").ajaxForm({
        beforeSubmit: () => {
            $("#message-page-edit").html("");
            $("#message-page-edit").hide();
            $(".loading").show();
        },
        beforeSerialize: () => {
            updateCKEditors();
            return true;
        },
        success: () => {
            $(".loading").hide();
            $("#message-page-edit").html(
                    `
                        ${Translation.PageSaved}
                     `
                    );
            $("#message-page-edit").show();
        }
    });

    // check if a slug is free on changing system title or menu
    $("input[name='slug']").blur(() => slugOrLanguageChanged());
    $("input[name='title']").blur(() => slugOrLanguageChanged());

    $("select[name='menu']").change(() => filterParentPages());

    // check if slug is free and update parent page options
    $("select[name='language']").change(() => {
        slugOrLanguageChanged();
        filterParentPages();
    });

    // bind event to "View" button at the bottom of page edit form
    $("#btn-view-page").click(() => {
        const url = "../?goid=" + $("#page_id").val();
        // if page has unsaved changes open it in new window/tab
        // else open it in the same window/tab
        if (formChanged && !submitted) {
            window.open(url);
        } else {
            location.href = url;
        }
    });
});

showAndHideFieldsByTypeWithoutEffects = () => {
    const type = $("input[name=type]:checked").val();

    $(".typedep").hide();
    if (typeof AllTypes[type] === 'undefined') {
        return;
    }

    const typeData = AllTypes[type];
    const show = typeData["show"];

    show.forEach((element) => $(element).show());

    if ($("#type_snippet").is(":checked")) {
        unbindEvents();
        $("select[name='hidden']")
                .val("1")
                .trigger("change");
        $("select[name='menu']")
                .val("not_in_menu")
                .trigger("change");
        bindEvents();
    }

    $(".custom-field-tab").each((index, el) => {
        if ($(el).data("type") === $("input[name='type']:checked").val()) {
            $(el).find("input, select, checkbox, radio, button, submit").prop("disabled", false);
            $(el).show();
        } else {
            $(el).hide();
            $(el).find("input, select, checkbox, radio, button, submit").prop("disabled", true);
        }
    });

    if ($("#type_node").is(":checked") || $("#type_snippet").is(":checked")) {
        $("#btn-view-page").hide();
    } else {
        $("#btn-view-page").show();
    }

    if ($("select[name='menu']").val() === "not_in_menu") {
        $("#parent-div").hide();
        $("#menu_image_div").hide();
    } else {
        $("#parent-div").show();
        $("#menu_image_div").show();
    }
};

// this function shows and hides areas for the selected content type
showAndHideFieldsByType = () => {
    const type = $("input[name=type]:checked").val();
    const showSelector = AllTypes[type]["show"].join(",");
    $(".typedep")
            .not(showSelector)
            .slideUp();
    const typeData = AllTypes[type];
    const show = typeData["show"];

    show.forEach((element) => $(element).slideDown());

    if ($("#type_snippet").is(":checked")) {
        unbindEvents();
        $("select[name='hidden']")
                .val("1")
                .trigger("change");
        $("select[name='menu']")
                .val("not_in_menu")
                .trigger("change");
        bindEvents();
    }

    $(".custom-field-tab").each((index, el) => {
        if ($(el).data("type") === $("input[name='type']:checked").val()) {
            $(el).slideDown();
            $(el).find("input, select, button, submit").prop("disabled", false);
        } else {
            $(el).slideUp();
            $(el).find("input, select, button, submit").prop("disabled", true);
        }
    });

    if ($("#type_node").is(":checked") || $("#type_snippet").is(":checked")) {
        $("#btn-view-page").slideUp();
    } else {
        $("#btn-view-page").slideDown();
    }

    if ($("select[name='menu']").val() === "not_in_menu") {
        $("#parent-div").slideUp();
        $("#menu_image_div").slideUp();
    } else {
        $("#parent-div").slideDown();
        $("#menu_image_div").slideDown();
    }
};

/* global Translation, formChanged, submitted, bootbox, instance, CKEDITOR, PageTranslation */

let AllTypes = {};

// this shows a thumbnail of the selected file on text inputs with
// fm image uploader attached
refreshFieldThumbnails = () => {
    $("input.fm[data-fm-type=images]").each((index, element) => {
        const id = $(element).attr("name");
        if ($(element).val().length > 0) {
            $("img#thumbnail-" + id).attr("src", $(element).val());
            $("img#thumbnail-" + id).show();
        } else {
            $("img#thumbnail-" + id).hide();
        }
    });
};

// Bind events for dependend fields, clear-buttons, and file inputs
bindEvents = () => {
    $('input[name="type"]').change(showAndHideFieldsByType);
    $("select[name='menu']").change(showAndHideFieldsByType);
    $("select[name='menu']")
            .select2("destroy")
            .select2({
                width: "100%"
            });
    $(".clear-field").on("click", (event) => {
        event.preventDefault();
        event.stopPropagation();
        const element = $(event.target);
        const linkFor = $(element).data("for");
        $(linkFor).val("");
        refreshFieldThumbnails();
    });

    refreshFieldThumbnails();
    $("input.fm").on("click", (event) => {
        const field = $(event.target);

        const name = $(field).attr("id")
                ? $(field).attr("id")
                : $(field).attr("name");
        const type = $(field).data("fm-type")
                ? $(field).data("fm-type")
                : "images";

        window.open(
                "fm/dialog.php?fldr=" +
                type +
                "&editor=ckeditor&type=2&langCode=" +
                $("html").data("select2-language") + "&popup=1&field_id=" + field.attr("id"),
                name,
                "status=0, toolbar=0, location=0, menubar=0, directories=0, " +
                "resizable=1, scrollbars=0, width=850, height=600"
                );
    });
};
// undbindEvents to prevent endless loop when selecting specific content types
unbindEvents = () => {
    $('input[name="type"]').off("change");
    $("select[name='menu']").off("change");
    $("input.fm").off("click");
    $(".clear-field").off("click");
};

// this suggest a slug which may be used as the url for a page
suggestSlug = (text) => {
    const pageSlug = slug(text, {lower: true});
    $("#slug").val(pageSlug);
};

// this checks if a slug is free within the selected language
// the combination of slug + language must be unique
slugOrLanguageChanged = () => {
    if (window.slugChecking) {
        return;
    }
    window.slugChecking = true;
    const id_field = $("input[name='page_id']");
    let myid = 0;
    if (id_field) {
        myid = $(id_field).val();
    }
    const data = {
        csrf_token: $("input[name=csrf_token]")
                .first()
                .val(),
        slug: $("input[name='slug']").val(),
        language: $("select[name='language']").val(),
        id: myid
    };
    const url = $(".main-form")
            .first()
            .data("slug-free-url");

    $.get(url, data, function (text) {
        if (text.length > $("input[name='slug']").val().length) {
            $("input[name='slug']").val(text);
        }
        window.slugChecking = false;
    });
};

// filter parent pages by selected language and menu
filterParentPages = () => {
    const data = {
        csrf_token: $("input[name=csrf_token]")
                .first()
                .val(),
        mlang: $("select[name='language']").val(),
        mmenu: $("select[name='menu']").val(),
        mparent: $("select[name='parent_id']").val()
    };

    const url = $(".main-form")
            .first()
            .data("parent-pages-url");
    $.get(url, data, function (text, status) {
        $("select[name='parent_id']").html(text);
    });
};
<|endoftext|>


<commit_before>// @flow
import createLogger from '../../../utils/logger';
import type { Transaction } from './types';
import ActionTypes from './actionTypes';
import { storeTransactions, loadTransactions } from './historyStorage';
import { allTrackedTxs } from './selectors';
import { dispatchRpcError } from '../screen/screenActions';

const log = createLogger('historyActions');
const txStoreKey = (chainId) => `chain-${chainId}-trackedTransactions`;
const currentChainId = (state) => state.wallet.history.get('chainId');

function persistTransactions(state) {
  storeTransactions(
    txStoreKey(currentChainId(state)),
    allTrackedTxs(state).toJS()
  );
}

function loadPersistedTransactions(state): Array<Transaction> {
  return loadTransactions(txStoreKey(currentChainId(state)));
}

function updateAndTrack(dispatch, getState, api, txs) {
  const pendingTxs = txs.filter((tx) => !tx.blockNumber);
  const nonPendingTxs = txs.filter((tx) => pendingTxs.indexOf(tx) === -1);

  let returnPromise;

  if (pendingTxs.length !== 0) {
    dispatch({type: ActionTypes.TRACK_TXS, txs: pendingTxs});
  }

  if (nonPendingTxs.length !== 0) {
    const blockNumbers = nonPendingTxs.map((tx) => tx.blockNumber);
    returnPromise = api.geth.ext.getBlocksByNumbers(blockNumbers).then((blocks) => {
      return nonPendingTxs.map((tx) => ({
        ...tx,
        timestamp: blocks.find(({ hash }) => hash === tx.blockHash).timestamp,
      }));
    })
      .then((transactions) => {
        dispatch({type: ActionTypes.TRACK_TXS, txs: transactions});
      }).catch(dispatchRpcError(dispatch));
  }

  persistTransactions(getState());
  return returnPromise;
}

export function trackTx(tx) { return (...args) => updateAndTrack(...args, [tx]); }
export function trackTxs(txs) { return (...args) => updateAndTrack(...args, txs); }

export function init(chainId: number) {
  return (dispatch, getState) => {
    log.debug(`Switching to chainId = ${chainId}`);

    // set chain
    dispatch({
      type: ActionTypes.CHAIN_CHANGED,
      chainId,
    });

    // load history for chain
    const storedTxs = loadPersistedTransactions(getState());
    dispatch({
      type: ActionTypes.LOAD_STORED_TXS,
      transactions: storedTxs,
    });
  };
}

const txUnconfirmed = (state, tx) => {
  const currentBlock = state.network.get('currentBlock').get('height');
  const txBlockNumber = tx.get('blockNumber');

  if (!txBlockNumber) {
    return true;
  }

  const numConfirmsForTx = txBlockNumber - currentBlock;

  const requiredConfirms = state.wallet.settings.get('numConfirmations');
  return requiredConfirms < numConfirmsForTx;
};

/**
 * Refresh only tx with totalRetries <= 10
 */
export function refreshTrackedTransactions() {
  return (dispatch, getState, api) => {
    const state = getState();

    const hashes = allTrackedTxs(state)
      .filter((tx) => tx.get('totalRetries', 0) <= 10)
      .filter((tx) => txUnconfirmed(state, tx))
      .map((tx) => tx.get('hash'));

    if (hashes.size === 0) {
      return;
    }

    return api.geth.ext.getTransactions(hashes.toJS()).then((results) => {
      const transactions = results.map((r) => r.result).filter((tx) => tx && tx.blockNumber);

      if (transactions.length === 0) { return; }

      return api.geth.ext.getBlocksByNumbers(transactions.map((tx) => tx.blockNumber)).then((blocks) => {
        return transactions.map((tx) => ({
          ...tx,
          timestamp: blocks.find(({ hash }) => hash === tx.blockHash).timestamp,
        }));
      });
    }).then((transactions) => {
      if (!transactions || transactions.length === 0) { return; }

      dispatch({ type: ActionTypes.UPDATE_TXS, transactions });

      return persistTransactions(getState());
    }).catch(dispatchRpcError(dispatch));
  };
}
<commit_msg>problem: wrong tx status solution: fix error when tracked txs check<commit_after>// @flow
import createLogger from '../../../utils/logger';
import type { Transaction } from './types';
import ActionTypes from './actionTypes';
import { storeTransactions, loadTransactions } from './historyStorage';
import { allTrackedTxs } from './selectors';
import { dispatchRpcError } from '../screen/screenActions';

const log = createLogger('historyActions');
const txStoreKey = (chainId) => `chain-${chainId}-trackedTransactions`;
const currentChainId = (state) => state.wallet.history.get('chainId');

function persistTransactions(state) {
  storeTransactions(
    txStoreKey(currentChainId(state)),
    allTrackedTxs(state).toJS()
  );
}

function loadPersistedTransactions(state): Array<Transaction> {
  return loadTransactions(txStoreKey(currentChainId(state)));
}

function updateAndTrack(dispatch, getState, api, txs) {
  const pendingTxs = txs.filter((tx) => !tx.blockNumber);
  const nonPendingTxs = txs.filter((tx) => pendingTxs.indexOf(tx) === -1);

  let returnPromise;

  if (pendingTxs.length !== 0) {
    dispatch({type: ActionTypes.TRACK_TXS, txs: pendingTxs});
  }

  if (nonPendingTxs.length !== 0) {
    const blockNumbers = nonPendingTxs.map((tx) => tx.blockNumber);
    returnPromise = api.geth.ext.getBlocksByNumbers(blockNumbers).then((blocks) => {
      return nonPendingTxs.map((tx) => ({
        ...tx,
        timestamp: blocks.find(({ hash }) => hash === tx.blockHash).timestamp,
      }));
    })
      .then((transactions) => {
        dispatch({type: ActionTypes.TRACK_TXS, txs: transactions});
      }).catch(dispatchRpcError(dispatch));
  }

  persistTransactions(getState());
  return returnPromise;
}

export function trackTx(tx) { return (...args) => updateAndTrack(...args, [tx]); }
export function trackTxs(txs) { return (...args) => updateAndTrack(...args, txs); }

export function init(chainId: number) {
  return (dispatch, getState) => {
    log.debug(`Switching to chainId = ${chainId}`);

    // set chain
    dispatch({
      type: ActionTypes.CHAIN_CHANGED,
      chainId,
    });

    // load history for chain
    const storedTxs = loadPersistedTransactions(getState());
    dispatch({
      type: ActionTypes.LOAD_STORED_TXS,
      transactions: storedTxs,
    });
  };
}

const txUnconfirmed = (state, tx) => {
  const currentBlock = state.network.get('currentBlock').get('height');
  const txBlockNumber = tx.get('blockNumber');

  if (!txBlockNumber) {
    return true;
  }

  const numConfirmsForTx = txBlockNumber - currentBlock;

  const requiredConfirms = state.wallet.settings.get('numConfirmations');
  return requiredConfirms < numConfirmsForTx;
};

/**
 * Refresh only tx with totalRetries <= 10
 */
export function refreshTrackedTransactions() {
  return (dispatch, getState, api) => {
    const state = getState();

    const hashes = allTrackedTxs(state)
      .filter((tx) => tx.get('totalRetries', 0) <= 10)
      .filter((tx) => txUnconfirmed(state, tx))
      .map((tx) => tx.get('hash'));

    if (hashes.size === 0) {
      return;
    }

    return api.geth.ext.getTransactions(hashes.toJS()).then((results) => {
      const transactions = results.filter((tx) => tx && tx.blockNumber);

      if (transactions.length === 0) { return; }

      return api.geth.ext.getBlocksByNumbers(transactions.map((tx) => tx.blockNumber)).then((blocks) => {
        return transactions.map((tx) => ({
          ...tx,
          timestamp: blocks.find(({ hash }) => hash === tx.blockHash).timestamp,
        }));
      });
    }).then((transactions) => {
      if (!transactions || transactions.length === 0) { return; }

      dispatch({ type: ActionTypes.UPDATE_TXS, transactions });

      return persistTransactions(getState());
    }).catch(dispatchRpcError(dispatch));
  };
}
<|endoftext|>


<commit_before>angular.module('starter.controllers', ['starter.services'])

.controller('AppCtrl', function($scope, $ionicModal, $timeout) {

  // With the new view caching in Ionic, Controllers are only called
  // when they are recreated or on app start, instead of every page change.
  // To listen for when this page is active (for example, to refresh data),
  // listen for the $ionicView.enter event:
  //$scope.$on('$ionicView.enter', function(e) {
  //});

  // Form data for the login modal
  $scope.loginData = {};

  // Create the login modal that we will use later
  $ionicModal.fromTemplateUrl('templates/login.html', {
    scope: $scope
  }).then(function(modal) {
    $scope.modal = modal;
  });

  // Triggered in the login modal to close it
  $scope.closeLogin = function() {
    $scope.modal.hide();
  };

  // Open the login modal
  $scope.login = function() {
    $scope.modal.show();
  };

  // Perform the login action when the user submits the login form
  $scope.doLogin = function() {
    // Simulate a login delay. Remove this and replace with your login
    // code if using a login system
    $timeout(function() {
      $scope.closeLogin();
    }, 1000);
  };
})

.controller('SearchCtrl', function($scope, $ionicFilterBar, $location, $interpolate, $state, $resource){
  var filterBarInstance;
  function getItems () {
    $scope.all = [];
    var routes = $resource('http://bustracker.pvta.com/infopoint/rest/routes/getallroutes').query({}, function(){
      for(var i = 0; i < routes.length; i++){
        $scope.all.push({name: routes[i].ShortName + ": " + routes[i].LongName,
                        type: 'route',
                        id: routes[i].RouteId
                        });
      }
    });
    var stops = $resource('http://bustracker.pvta.com/infopoint/rest/stops/getallstops').query({}, function(){
      for(var i = 0; i < stops.length; i++){
        $scope.all.push({name: stops[i].Name,
                        type: 'stopDeparture',
                        id: stops[i].StopId
                        });
      }
    });
    }
  getItems();
  $scope.showFilterBar = function () {
      filterBarInstance = $ionicFilterBar.show({
        items: $scope.all,
        update: function (filteredItems, filterText) {
          $scope.all = filteredItems;
        }
      });
    };
  $scope.refreshItems = function () {
      if (filterBarInstance) {
        filterBarInstance();
        filterBarInstance = null;
      }

      $timeout(function () {
        getItems();
        $scope.$broadcast('scroll.refreshComplete');
      }, 1000);
    };
})

.controller('VehiclesCtrl', function($scope, $resource, Vehicle){
  $scope.vehicles = $resource('http://bustracker.pvta.com/infopoint/rest/vehicles/getallvehicles').query(function(){
    $scope.vehicles.sort(function(a, b){return a.Name - b.Name});
  });
})

.controller('VehicleCtrl', function($scope, $stateParams, Vehicle, LatLong, $location){
  $scope.vehicle = Vehicle.get({vehicleId: $stateParams.vehicleId});
  $scope.setCoordinates = function(lat, long){
    LatLong.push(lat, long);
    $location.path('/app/map')
  }
})

.controller('RouteController', function($scope, $resource){
  $scope.routes = $resource('http://bustracker.pvta.com/infopoint/rest/routes/getvisibleroutes').query(function(){
    $scope.routes.sort(function(a, b){return a.ShortName - b.ShortName})
  });
})

.controller('RouteCtrl', function($scope, $stateParams, Route, RouteVehicles){
  var size = 0
  var route = Route.get({routeId: $stateParams.routeId}, function() {
    route.$save();
    groups(route.Stops.length);
  });
  $scope.route = route;
  $scope.groups = [];
  $scope.vehicles = RouteVehicles.query({routeId: $stateParams.routeId});
  $scope.groups.push(route);
    $scope.groups[0] = {
    //  name: 'stops',
      items: []
    };
  var j = $scope.size
  var groups = function(length){
    for (var j=0; j < length; j++) {
      $scope.groups[0].items.push(route.Stops[j]);
    }
  };
  $scope.toggleGroup = function(group) {
    if ($scope.isGroupShown(group)) {
      $scope.shownGroup = null;
    } else {
      $scope.shownGroup = group;
    }
  };
  $scope.isGroupShown = function(group) {
    return $scope.shownGroup === group;
  };
})

.controller('StopDeparturesController', function($scope, $stateParams, $resource, $location, $interval, $rootScope, Stop, StopDeparture, moment, LatLong, getDepartureInfo){
  var originalGoBack = $rootScope.$ionicGoBack;
  $rootScope.$ionicGoBack = function() {
    $interval.cancel(timer);
    originalGoBack();
  };
  var timer=$interval(function(){
        getDepartures();
      },3000);
  var getDepartures = function(){
    var deps = StopDeparture.query({stopId: $stateParams.stopId}, function(){
      var directions = deps[0].RouteDirections;
      $scope.departures = [];
        console.log("refreshed!");
        for(var i = 0; i < directions.length; i++){
          if(directions[i].Departures.length !== 0 && !directions[i].IsDone){
            var departureNum = 0;
            var sdt = directions[i].Departures[departureNum].SDT;
            var edt = directions[i].Departures[departureNum].EDT;
            var times = {s: moment(sdt).fromNow(), e: moment(edt).fromNow()};
            while(times.e.includes('ago')){
              departureNum++;
              sdt = directions[i].Departures[departureNum].SDT;
              edt = directions[i].Departures[departureNum].EDT;
              times = {s: moment(sdt).fromNow(), e: moment(edt).fromNow()};
            }
            directions[i].StringifiedTimes = times;
            var r = {route: directions[i].RouteId, trip: directions[i].Departures[departureNum].Trip, departures: times};
            $scope.departures.push(r);
          }
        }
    });
  } // end getDepartures
  $scope.stop = Stop.get({stopId: $stateParams.stopId});

  $scope.setCoordinates = function(lat, long){
    LatLong.push(lat, long);
    $interval.cancel(timer);
    $location.path('/app/map')
  }
})

.controller('MapCtrl', function($scope, $state, $resource, $stateParams, $cordovaGeolocation, Route, Vehicle, LatLong) {
  var options = {timeout: 10000, enableHighAccuracy: true};

  var ll = LatLong.pop();
  $scope.lats = ll;

  $cordovaGeolocation.getCurrentPosition(options).then(function(position){

    var latLng = new google.maps.LatLng(ll.lat, ll.long);
    var myLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

    var bounds = new google.maps.LatLngBounds();
    bounds.extend(latLng);
    bounds.extend(myLocation);

    var mapOptions = {
      center: bounds.getCenter(),
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    $scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);

    //Wait until the map is loaded
    google.maps.event.addListenerOnce($scope.map, 'idle', function(){
      $scope.map.fitBounds(bounds);
      var neededMarker = new google.maps.Marker({
        map: $scope.map,
        icon: 'http://www.google.com/mapfiles/kml/paddle/go.png',
        animation: google.maps.Animation.DROP,
        position: latLng
      });
      var myMarker = new google.maps.Marker({
        map: $scope.map,
        animation: google.maps.Animation.DROP,
        position: myLocation,
        title: "You're here!"
        });
      google.maps.event.addListener(myMarker, 'click', function () {
          var infoWindow = new google.maps.InfoWindow({
            content: "You are here!"
          });
          infoWindow.open($scope.map, myMarker);
      });
      google.maps.event.addListener(neededMarker, 'click', function () {
          var infoWindow = new google.maps.InfoWindow({
            content: "Here's what you're looking for!"
          });
          infoWindow.open($scope.map, neededMarker);
      });
    });

    }, function(error){
      console.log("Could not get location");
    });
});
<commit_msg>When leaving the StopDepartures page, the timer now stops<commit_after>angular.module('starter.controllers', ['starter.services'])

.controller('AppCtrl', function($scope, $ionicModal, $timeout) {

  // With the new view caching in Ionic, Controllers are only called
  // when they are recreated or on app start, instead of every page change.
  // To listen for when this page is active (for example, to refresh data),
  // listen for the $ionicView.enter event:
  //$scope.$on('$ionicView.enter', function(e) {
  //});

  // Form data for the login modal
  $scope.loginData = {};

  // Create the login modal that we will use later
  $ionicModal.fromTemplateUrl('templates/login.html', {
    scope: $scope
  }).then(function(modal) {
    $scope.modal = modal;
  });

  // Triggered in the login modal to close it
  $scope.closeLogin = function() {
    $scope.modal.hide();
  };

  // Open the login modal
  $scope.login = function() {
    $scope.modal.show();
  };

  // Perform the login action when the user submits the login form
  $scope.doLogin = function() {
    // Simulate a login delay. Remove this and replace with your login
    // code if using a login system
    $timeout(function() {
      $scope.closeLogin();
    }, 1000);
  };
})

.controller('SearchCtrl', function($scope, $ionicFilterBar, $location, $interpolate, $state, $resource){
  var filterBarInstance;
  function getItems () {
    $scope.all = [];
    var routes = $resource('http://bustracker.pvta.com/infopoint/rest/routes/getallroutes').query({}, function(){
      for(var i = 0; i < routes.length; i++){
        $scope.all.push({name: routes[i].ShortName + ": " + routes[i].LongName,
                        type: 'route',
                        id: routes[i].RouteId
                        });
      }
    });
    var stops = $resource('http://bustracker.pvta.com/infopoint/rest/stops/getallstops').query({}, function(){
      for(var i = 0; i < stops.length; i++){
        $scope.all.push({name: stops[i].Name,
                        type: 'stopDeparture',
                        id: stops[i].StopId
                        });
      }
    });
    }
  getItems();
  $scope.showFilterBar = function () {
      filterBarInstance = $ionicFilterBar.show({
        items: $scope.all,
        update: function (filteredItems, filterText) {
          $scope.all = filteredItems;
        }
      });
    };
  $scope.refreshItems = function () {
      if (filterBarInstance) {
        filterBarInstance();
        filterBarInstance = null;
      }

      $timeout(function () {
        getItems();
        $scope.$broadcast('scroll.refreshComplete');
      }, 1000);
    };
})

.controller('VehiclesCtrl', function($scope, $resource, Vehicle){
  $scope.vehicles = $resource('http://bustracker.pvta.com/infopoint/rest/vehicles/getallvehicles').query(function(){
    $scope.vehicles.sort(function(a, b){return a.Name - b.Name});
  });
})

.controller('VehicleCtrl', function($scope, $stateParams, Vehicle, LatLong, $location){
  $scope.vehicle = Vehicle.get({vehicleId: $stateParams.vehicleId});
  $scope.setCoordinates = function(lat, long){
    LatLong.push(lat, long);
    $location.path('/app/map')
  }
})

.controller('RouteController', function($scope, $resource){
  $scope.routes = $resource('http://bustracker.pvta.com/infopoint/rest/routes/getvisibleroutes').query(function(){
    $scope.routes.sort(function(a, b){return a.ShortName - b.ShortName})
  });
})

.controller('RouteCtrl', function($scope, $stateParams, Route, RouteVehicles){
  var size = 0
  var route = Route.get({routeId: $stateParams.routeId}, function() {
    route.$save();
    groups(route.Stops.length);
  });
  $scope.route = route;
  $scope.groups = [];
  $scope.vehicles = RouteVehicles.query({routeId: $stateParams.routeId});
  $scope.groups.push(route);
    $scope.groups[0] = {
    //  name: 'stops',
      items: []
    };
  var j = $scope.size
  var groups = function(length){
    for (var j=0; j < length; j++) {
      $scope.groups[0].items.push(route.Stops[j]);
    }
  };
  $scope.toggleGroup = function(group) {
    if ($scope.isGroupShown(group)) {
      $scope.shownGroup = null;
    } else {
      $scope.shownGroup = group;
    }
  };
  $scope.isGroupShown = function(group) {
    return $scope.shownGroup === group;
  };
})

.controller('StopDeparturesController', function($scope, $stateParams, $resource, $location, $interval, $rootScope, Stop, StopDeparture, moment, LatLong, getDepartureInfo){
  var originalGoBack = $rootScope.$ionicGoBack;
  $rootScope.$ionicGoBack = function() {
    $interval.cancel(timer);
    originalGoBack();
  };
  var timer=$interval(function(){
        getDepartures();
      },3000);
  var getDepartures = function(){
    var deps = StopDeparture.query({stopId: $stateParams.stopId}, function(){
      var directions = deps[0].RouteDirections;
      $scope.departures = [];
        console.log("refreshed!");
        for(var i = 0; i < directions.length; i++){
          if(directions[i].Departures.length !== 0 && !directions[i].IsDone){
            var departureNum = 0;
            var sdt = directions[i].Departures[departureNum].SDT;
            var edt = directions[i].Departures[departureNum].EDT;
            var times = {s: moment(sdt).fromNow(), e: moment(edt).fromNow()};
            while(times.e.includes('ago')){
              departureNum++;
              sdt = directions[i].Departures[departureNum].SDT;
              edt = directions[i].Departures[departureNum].EDT;
              times = {s: moment(sdt).fromNow(), e: moment(edt).fromNow()};
            }
            directions[i].StringifiedTimes = times;
            var r = {route: directions[i].RouteId, trip: directions[i].Departures[departureNum].Trip, departures: times};
            $scope.departures.push(r);
          }
        }
    });
  } // end getDepartures
  $scope.stop = Stop.get({stopId: $stateParams.stopId});
  $scope.$on('$destroy', function() {
    $interval.cancel(timer);
  });
  $scope.setCoordinates = function(lat, long){
    LatLong.push(lat, long);
    $interval.cancel(timer);
    $location.path('/app/map')
  }
})

.controller('MapCtrl', function($scope, $state, $resource, $stateParams, $cordovaGeolocation, Route, Vehicle, LatLong) {
  var options = {timeout: 10000, enableHighAccuracy: true};

  var ll = LatLong.pop();
  $scope.lats = ll;

  $cordovaGeolocation.getCurrentPosition(options).then(function(position){

    var latLng = new google.maps.LatLng(ll.lat, ll.long);
    var myLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

    var bounds = new google.maps.LatLngBounds();
    bounds.extend(latLng);
    bounds.extend(myLocation);

    var mapOptions = {
      center: bounds.getCenter(),
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    $scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);

    //Wait until the map is loaded
    google.maps.event.addListenerOnce($scope.map, 'idle', function(){
      $scope.map.fitBounds(bounds);
      var neededMarker = new google.maps.Marker({
        map: $scope.map,
        icon: 'http://www.google.com/mapfiles/kml/paddle/go.png',
        animation: google.maps.Animation.DROP,
        position: latLng
      });
      var myMarker = new google.maps.Marker({
        map: $scope.map,
        animation: google.maps.Animation.DROP,
        position: myLocation,
        title: "You're here!"
        });
      google.maps.event.addListener(myMarker, 'click', function () {
          var infoWindow = new google.maps.InfoWindow({
            content: "You are here!"
          });
          infoWindow.open($scope.map, myMarker);
      });
      google.maps.event.addListener(neededMarker, 'click', function () {
          var infoWindow = new google.maps.InfoWindow({
            content: "Here's what you're looking for!"
          });
          infoWindow.open($scope.map, neededMarker);
      });
    });

    }, function(error){
      console.log("Could not get location");
    });
});
<|endoftext|>


<commit_before>"use strict";

module.exports = {
    "env": {
        "browser": true,
        "es6": true,
        "node": true,
        "mocha": true
    },
    "extends": ["ash-nazg/sauron-node"],
    "parserOptions": {
        "ecmaVersion": 2018,
        "sourceType": "module"
    },
    "settings": {
        "polyfills": [
            "console",
            "JSON"
        ]
    },
    "overrides": [
        {
            files: "docs/jsdoc-config.js",
            globals: {
                "module": "readonly"
            },
            rules: {
                strict: "off",
                "import/unambiguous": "off",
                "import/no-commonjs": "off"
            }
        },
        {
            files: ["**/*.md"],
            rules: {
                "eol-last": "off",
                "no-console": "off",
                "no-undef": "off",
                "padded-blocks": "off",
                "import/unambiguous": "off",
                "import/no-unresolved": "off",
                "node/no-missing-import": "off",
                "no-unused-vars": ["warn"],
                "no-unused-vars": ["error", {
                    "varsIgnorePattern": "Point2D"
                }],
                "node/no-missing-require": ["error", {
                    "allowModules": ["kld-intersections"]
                }]
            }
        }
    ],
    "rules": {
        "indent": [
            "error",
            4,
            {"SwitchCase": 1}
        ],
        "quotes": [
            "error",
            "double"
        ],
        "space-before-function-paren": [
            "error",
            "never"
        ],
        "brace-style": [
            "error",
            "stroustrup"
        ],
        "arrow-parens": [
            "error",
            "as-needed"
        ],
        "no-console": "off",
        "no-multiple-empty-lines": "off",
        "max-len": "off",
        "node/exports-style": "off",
        "unicorn/no-zero-fractions": "off",
        "require-unicode-regexp": "off",
        "yoda": "off",
        "valid-jsdoc": 0
    }
};
<commit_msg>Add polyfill reference<commit_after>"use strict";

module.exports = {
    "env": {
        "browser": true,
        "es6": true,
        "node": true,
        "mocha": true
    },
    "extends": ["ash-nazg/sauron-node"],
    "parserOptions": {
        "ecmaVersion": 2018,
        "sourceType": "module"
    },
    "settings": {
        "polyfills": [
            "console",
            "JSON",
            "Array.isArray"
        ]
    },
    "overrides": [
        {
            files: "docs/jsdoc-config.js",
            globals: {
                "module": "readonly"
            },
            rules: {
                strict: "off",
                "import/unambiguous": "off",
                "import/no-commonjs": "off"
            }
        },
        {
            files: ["**/*.md"],
            rules: {
                "eol-last": "off",
                "no-console": "off",
                "no-undef": "off",
                "padded-blocks": "off",
                "import/unambiguous": "off",
                "import/no-unresolved": "off",
                "node/no-missing-import": "off",
                "no-unused-vars": ["warn"],
                "no-unused-vars": ["error", {
                    "varsIgnorePattern": "Point2D"
                }],
                "node/no-missing-require": ["error", {
                    "allowModules": ["kld-intersections"]
                }]
            }
        }
    ],
    "rules": {
        "indent": [
            "error",
            4,
            {"SwitchCase": 1}
        ],
        "quotes": [
            "error",
            "double"
        ],
        "space-before-function-paren": [
            "error",
            "never"
        ],
        "brace-style": [
            "error",
            "stroustrup"
        ],
        "arrow-parens": [
            "error",
            "as-needed"
        ],
        "no-console": "off",
        "no-multiple-empty-lines": "off",
        "max-len": "off",
        "node/exports-style": "off",
        "unicorn/no-zero-fractions": "off",
        "require-unicode-regexp": "off",
        "yoda": "off",
        "valid-jsdoc": 0
    }
};
<|endoftext|>


<commit_before>(function() {
    'use strict';

    angular
        .module('webApp')
        .controller('NuevoCtrl', NuevoCtrl);

    NuevoCtrl.$inject = ['ApiTest', 'FragmentDataService', 'TemplateDataService', '$filter', '$modal'];

    function NuevoCtrl(ApiTest, FragmentDataService, TemplateDataService, $filter, $modal) {
        /*jshint validthis: true*/
       var vm = this;

       vm.getInputs = getInputs;
       vm.deleteInput = deleteInput;
       vm.getInputTypes = getInputTypes;
       vm.createInput = createInput;
       vm.modifyInput = modifyInput;
       vm.createInputModal = createInputModal;
       vm.modifyInputModal = modifyInputModal;
       vm.deleteInputConfirm = deleteInputConfirm;
       vm.getPoliciesNames = getPoliciesNames;
       vm.setInputsId = setInputsId;
       vm.inputTypes = [];
       vm.inputId = 1;

       init();

        /////////////////////////////////

        function init() {
            getInputs();
        };

        function getInputs() {
            ApiTest.get().$promise.then(function (result) {
                vm.inputsData = vm.setInputsId(result);
                vm.getInputTypes(result);
            });
        };

        function deleteInput(fragmentType, fragmentName, index) {
            console.log(index);
            var policiesToDelete = FragmentDataService.GetPolicyByFragmentName(fragmentType, fragmentName);

            policiesToDelete.then(function (result) {
                console.log('*********Controller');
                console.log(result);

                var policies = vm.getPoliciesNames(result);
                var inputToDelete =
                {
                    'type':fragmentType,
                    'name': fragmentName,
                    'policies': policies,
                    'index': index
                };
                vm.deleteInputConfirm('lg', inputToDelete);
            });
        };

        function duplicateInput(inputName) {
            var inputSelected = $filter('filter')(angular.copy(vm.inputsData), {name:inputName}, true)[0];

            var newName = autoIncrementName(inputSelected.name);
            inputSelected.name = newName;

            var newName = SetDuplicatetedInput('sm', inputSelected);
       };

        function createInput() {
           var inputFragmentTemplate = TemplateDataService.GetNewFragmentTemplate('input');

           inputFragmentTemplate.then(function (result) {
               console.log('*********Controller');
               console.log(result);

               vm.createInputModal(result);
           });
        };

        function modifyInput(inputName, index) {
           var inputSelected = $filter('filter')(angular.copy(vm.inputsData), {name:inputName}, true)[0];
           var id = inputSelected.id;

           delete inputSelected["id"];

           var inputFragmentTemplate = TemplateDataService.GetNewFragmentTemplate('input');

           inputFragmentTemplate.then(function (result) {
               console.log('*********Controller');
               console.log(result);

               var modifyInputData = {
                   'index': index,
                   'id': id,
                   'action': 'modify',
                   'inputSelected': inputSelected,
                   'inputDataTemplate': result
               };

               vm.modifyInputModal(modifyInputData);
           });
        };

        function setInputsId(inputsData) {
            for (var i=0; i < inputsData.length; i++) {
                inputsData[i].id = vm.inputId;
                vm.inputId++;
            }
            return inputsData;
        };

        function getPoliciesNames(policiesData) {
            var policies = [];

            for (var i=0; i<policiesData.length; i++){
                policies.push(policiesData[i].name);
            }

            return policies;
        };

        function getInputTypes(inputs) {
            for (var i=0; i<inputs.length; i++) {
                var newType = false;
                var type    = inputs[i].element.type;

                if (i === 0) {
                    vm.inputTypes.push({'type': type, 'count': 1});
                }
                else {
                    for (var j=0; j<vm.inputTypes.length; j++) {
                        if (vm.inputTypes[j].type === type) {
                            vm.inputTypes[j].count++;
                            newType = false;
                            break;
                        }
                        else if (vm.inputTypes[j].type !== type){
                            newType = true;
                        }
                    }
                    if (newType) {
                        vm.inputTypes.push({'type': type, 'count':1});
                    }
                }
            }
        };

        function createInputModal(newInputTemplateData) {
            var modalInstance = $modal.open({
               animation: true,
               templateUrl: 'templates/inputs/input-details.tpl.html',
               controller: 'NewFragmentModalCtrl as vm',
               size: 'lg',
               resolve: {
                   item: function () {
                       return newInputTemplateData;
                   }
               }
            });

            modalInstance.result.
               then(function (newInputData) {
                   console.log('*************** Controller back');
                   console.log(newInputData);

                   var newFragment = FragmentDataService.InsertFragment(newInputData.data);

                   newFragment
                       .then(function (result) {
                           console.log('*********Fragment created');
                           console.log(result);

                           var newId = vm.inputsData[vm.inputsData.length-1].id + 1;
                           result.id = newId;

                           vm.inputsData.push(result);
                           console.log(vm.inputsData);
                       },
                       function (error) {
                           console.log(error);
                           console.log('Modal dismissed at: ' + new Date())
                       });

               }, function () {
                   console.log('Modal dismissed at: ' + new Date())
               });
            };

        function modifyInputModal(modidyInputData) {
           var modalInstance = $modal.open({
               animation: true,
               templateUrl: 'templates/inputs/input-details.tpl.html',
               controller: 'NewFragmentModalCtrl as vm',
               size: 'lg',
               resolve: {
                   item: function () {
                       return modidyInputData;
                   }
               }
           });

           modalInstance.result.
               then(function (updatedInputData) {
                   console.log('*************** Controller back');
                   console.log(updatedInputData);

                   var updatedFragment = FragmentDataService.UpdateFragment(updatedInputData.data);

                   updatedFragment
                       .then(function (result) {
                           console.log('*********Fragment updated');
                           console.log(result);

                           result.id = updatedInputData.id;

                           vm.inputsData[updatedInputData.index] = result;
                           console.log(vm.inputsData);
                       },
                       function (error) {
                           console.log(error);
                           console.log('Modal dismissed at: ' + new Date())
                       });

               }, function () {
                   console.log('Modal dismissed at: ' + new Date())
               });
        };

        function deleteInputConfirm(size, input) {
            var modalInstance = $modal.open({
                animation: true,
                templateUrl: 'templates/components/st_delete_modal.tpl.html',
                controller: 'ModalInstanceCtrl',
                size: size,
                resolve: {
                    item: function () {
                        return input;
                    }
                }
            });

            modalInstance.result
                .then(function (selectedItem) {
                    console.log(selectedItem);
                    var fragmentDeleted = FragmentDataService.DeleteFragment(selectedItem.type, selectedItem.name);

                    fragmentDeleted
                        .then(function (result) {
                            console.log('*********Fragment deleted');
                            vm.inputsData.splice(selectedItem.index, 1);

                        });
                },
                function () {
                    console.log('Modal dismissed at: ' + new Date())
                });
        };

        function SetDuplicatetedInput(size, inputName) {
            var modalInstance = $modal.open({
                animation: true,
                templateUrl: 'templates/components/st_duplicate_modal.tpl.html',
                controller: 'NewFragmentCtrl',
                size: 'lg',
                resolve: {
                    item: function () {
                        return inputName;
                    }
                }
            });

            modalInstance.result
                .then(function (selectedItem) {
                    delete selectedItem["id"];
                    console.log(selectedItem);

                    var newFragment = FragmentDataService.InsertFragment(selectedItem);

                    newFragment
                        .then(function (result) {
                            console.log('*********Fragment created');
                            console.log(result);

                            var newId = vm.inputsData[vm.inputsData.length-1].id + 1;
                            selectedItem.id = newId;

                            vm.inputsData.push(selectedItem);
                        },
                        function (error) {
                            console.log(error);
                            console.log('Modal dismissed at: ' + new Date())
                        });

                },
                function () {
                    console.log('Modal dismissed at: ' + new Date())
                });
        };
    };

    /*NEW FRAGMENT MODAL CONTROLLER*/
    angular
        .module('webApp')
        .controller('NewFragmentModalCtrl', NewFragmentModalCtrl);

    NewFragmentModalCtrl.$inject = ['$modalInstance', 'item'];

    function NewFragmentModalCtrl($modalInstance, item) {
        /*jshint validthis: true*/
        var vm = this;

        vm.setProperties = setProperties;
        vm.ok = ok;
        vm.cancel = cancel;
        vm.initFragmentObecjt = initFragmentObecjt;
        vm.setFragmentData = setFragmentData;
        vm.createTypeModels = createTypeModels;
        vm.dataSource = {};
        vm.dataSource.element = {};
        vm.templateInputsData = [];
        vm.properties = [];

        init();

        /////////////////////////////////

        function init() {
            console.log('*********Modal');
            console.log(item);

            vm.action = item.action;

            if (vm.action === 'modify') {
                vm.templateInputsData = item.inputDataTemplate;
                vm.dataSource = item.inputSelected;
                vm.createTypeModels(vm.templateInputsData);
                vm.selectedIndex = vm.index;
            }
            else {
                vm.templateInputsData = item;
                vm.initFragmentObecjt(vm.templateInputsData);
                vm.createTypeModels(vm.templateInputsData);
                vm.selectedIndex = 0;
            }
        };

        function initFragmentObecjt(fragmentData) {
            /*Init fragment*/
            vm.dataSource.fragmentType = 'input';
            vm.dataSource.name = '';

            /*Init fragment.element*/
            vm.dataSource.element.type = fragmentData[0].name;
            vm.dataSource.element.name = 'in-' + vm.dataSource.element.type;

            /*Init fragment.element.configuration*/
            vm.dataSource.element.configuration = {};

            vm.setFragmentData(0);
        };

        function createTypeModels(fragmentData) {
            /*Create one properties model for each input type*/
            for (var i=0; i<fragmentData.length; i++){
                vm.properties[fragmentData[i].name] = {};

                for (var j=0; j<fragmentData[i].properties.length; j++) {
                    if (fragmentData[i].properties[j].propertyId !== 'name' && fragmentData[i].properties[j].propertyId !== 'type'){
                        vm.properties[fragmentData[i].name][fragmentData[i].properties[j].propertyId] = '';
                    }
                }

                /*Init properties*/
                if(i === 0 && vm.action !== 'modify') {
                    vm.dataSource.element.configuration = vm.properties[fragmentData[i].name];
                }

                else if(vm.action === 'modify' && fragmentData[i].name === vm.dataSource.element.type) {
                    vm.properties[fragmentData[i].name] = vm.dataSource.element.configuration;
                    vm.dataSource.element.configuration = vm.properties[fragmentData[i].name];
                    vm.index = i;
                }
            }
        };

        function setFragmentData(index) {
            /*Set fragment*/
            vm.dataSource.description = vm.templateInputsData[index].description.long;
            vm.dataSource.shortDescription = vm.templateInputsData[index].description.short;
            vm.dataSource.icon = vm.templateInputsData[index].icon.url;
            vm.dataSource.element.name = 'in-' + vm.dataSource.element.type;
        };

        function setProperties(index, inputName) {
            vm.selectedIndex = index;
            vm.dataSource.element.configuration = vm.properties[inputName];
            vm.setFragmentData(index);
        };

        function ok() {
            var callBackData = {
                'index': item.index,
                'id': item.id,
                'data': vm.dataSource,
            };
            $modalInstance.close(callBackData);
        };

        function cancel() {
            $modalInstance.dismiss('cancel');
        };
    };

    /*NEW INPUT & DELETE INPUT MODALS CONTROLLER */
    angular
        .module('webApp')
        .controller('ModalInstanceCtrl', ModalInstanceCtrl);

    ModalInstanceCtrl.$inject = ['$scope', '$modalInstance', 'item'];

    function ModalInstanceCtrl($scope, $modalInstance, item) {
        console.log('*********Modal');
        console.log(item);

        $scope.inputs = item;

        $scope.ok = function () {
            $modalInstance.close($scope.inputs);
        };

        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
    };

    /*DUPLICATE INPUT MODAL CONTROLLER */
    angular
        .module('webApp')
        .controller('NewFragmentCtrl', NewFragmentCtrl);

    NewFragmentCtrl.$inject = ['$scope', '$modalInstance', 'item'];

    function NewFragmentCtrl($scope, $modalInstance, item) {
        console.log('*********Modal');
        console.log(item);

        $scope.inputData = item;

        $scope.ok = function () {
            $modalInstance.close(item);
        };

        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
    };
})();
<commit_msg>fix(merge): fix merge conflicts<commit_after>(function() {
    'use strict';

    angular
        .module('webApp')
        .controller('NuevoCtrl', NuevoCtrl);

    NuevoCtrl.$inject = ['ApiTest', 'FragmentDataService', 'TemplateDataService', '$filter', '$modal'];

    function NuevoCtrl(ApiTest, FragmentDataService, TemplateDataService, $filter, $modal) {
        /*jshint validthis: true*/
       var vm = this;

       vm.getInputs = getInputs;
       vm.deleteInput = deleteInput;
       vm.getInputTypes = getInputTypes;
       vm.createInput = createInput;
       vm.modifyInput = modifyInput;
       vm.createInputModal = createInputModal;
       vm.modifyInputModal = modifyInputModal;
       vm.duplicateInput = duplicateInput;
       vm.deleteInputConfirm = deleteInputConfirm;
       vm.getPoliciesNames = getPoliciesNames;
       vm.setInputsId = setInputsId;
       vm.inputTypes = [];
       vm.inputId = 1;

       init();

        /////////////////////////////////

        function init() {
            getInputs();
        };

        function getInputs() {
            ApiTest.get().$promise.then(function (result) {
                vm.inputsData = vm.setInputsId(result);
                vm.getInputTypes(result);
            });
        };

        function deleteInput(fragmentType, fragmentName, index) {
            console.log(index);
            var policiesToDelete = FragmentDataService.GetPolicyByFragmentName(fragmentType, fragmentName);

            policiesToDelete.then(function (result) {
                console.log('*********Controller');
                console.log(result);

                var policies = vm.getPoliciesNames(result);
                var inputToDelete =
                {
                    'type':fragmentType,
                    'name': fragmentName,
                    'policies': policies,
                    'index': index
                };
                vm.deleteInputConfirm('lg', inputToDelete);
            });
        };

        function duplicateInput(inputName) {
            var inputSelected = $filter('filter')(angular.copy(vm.inputsData), {name:inputName}, true)[0];

            var newName = autoIncrementName(inputSelected.name);
            inputSelected.name = newName;

            var newName = SetDuplicatetedInput('sm', inputSelected);
       };

        function createInput() {
           var inputFragmentTemplate = TemplateDataService.GetNewFragmentTemplate('input');

           inputFragmentTemplate.then(function (result) {
               console.log('*********Controller');
               console.log(result);

               vm.createInputModal(result);
           });
        };

        function modifyInput(inputName, index) {
           var inputSelected = $filter('filter')(angular.copy(vm.inputsData), {name:inputName}, true)[0];
           var id = inputSelected.id;

           delete inputSelected["id"];

           var inputFragmentTemplate = TemplateDataService.GetNewFragmentTemplate('input');

           inputFragmentTemplate.then(function (result) {
               console.log('*********Controller');
               console.log(result);

               var modifyInputData = {
                   'index': index,
                   'id': id,
                   'action': 'modify',
                   'inputSelected': inputSelected,
                   'inputDataTemplate': result
               };

               vm.modifyInputModal(modifyInputData);
           });
        };

        function setInputsId(inputsData) {
            for (var i=0; i < inputsData.length; i++) {
                inputsData[i].id = vm.inputId;
                vm.inputId++;
            }
            return inputsData;
        };

        function getPoliciesNames(policiesData) {
            var policies = [];

            for (var i=0; i<policiesData.length; i++){
                policies.push(policiesData[i].name);
            }

            return policies;
        };

        function getInputTypes(inputs) {
            for (var i=0; i<inputs.length; i++) {
                var newType = false;
                var type    = inputs[i].element.type;

                if (i === 0) {
                    vm.inputTypes.push({'type': type, 'count': 1});
                }
                else {
                    for (var j=0; j<vm.inputTypes.length; j++) {
                        if (vm.inputTypes[j].type === type) {
                            vm.inputTypes[j].count++;
                            newType = false;
                            break;
                        }
                        else if (vm.inputTypes[j].type !== type){
                            newType = true;
                        }
                    }
                    if (newType) {
                        vm.inputTypes.push({'type': type, 'count':1});
                    }
                }
            }
        };

        function createInputModal(newInputTemplateData) {
            var modalInstance = $modal.open({
               animation: true,
               templateUrl: 'templates/inputs/input-details.tpl.html',
               controller: 'NewFragmentModalCtrl as vm',
               size: 'lg',
               resolve: {
                   item: function () {
                       return newInputTemplateData;
                   }
               }
            });

            modalInstance.result.
               then(function (newInputData) {
                   console.log('*************** Controller back');
                   console.log(newInputData);

                   var newFragment = FragmentDataService.InsertFragment(newInputData.data);

                   newFragment
                       .then(function (result) {
                           console.log('*********Fragment created');
                           console.log(result);

                           var newId = vm.inputsData[vm.inputsData.length-1].id + 1;
                           result.id = newId;

                           vm.inputsData.push(result);
                           console.log(vm.inputsData);
                       },
                       function (error) {
                           console.log(error);
                           console.log('Modal dismissed at: ' + new Date())
                       });

               }, function () {
                   console.log('Modal dismissed at: ' + new Date())
               });
            };

        function modifyInputModal(modidyInputData) {
           var modalInstance = $modal.open({
               animation: true,
               templateUrl: 'templates/inputs/input-details.tpl.html',
               controller: 'NewFragmentModalCtrl as vm',
               size: 'lg',
               resolve: {
                   item: function () {
                       return modidyInputData;
                   }
               }
           });

           modalInstance.result.
               then(function (updatedInputData) {
                   console.log('*************** Controller back');
                   console.log(updatedInputData);

                   var updatedFragment = FragmentDataService.UpdateFragment(updatedInputData.data);

                   updatedFragment
                       .then(function (result) {
                           console.log('*********Fragment updated');
                           console.log(result);

                           result.id = updatedInputData.id;

                           vm.inputsData[updatedInputData.index] = result;
                           console.log(vm.inputsData);
                       },
                       function (error) {
                           console.log(error);
                           console.log('Modal dismissed at: ' + new Date())
                       });

               }, function () {
                   console.log('Modal dismissed at: ' + new Date())
               });
        };

        function deleteInputConfirm(size, input) {
            var modalInstance = $modal.open({
                animation: true,
                templateUrl: 'templates/components/st_delete_modal.tpl.html',
                controller: 'ModalInstanceCtrl',
                size: size,
                resolve: {
                    item: function () {
                        return input;
                    }
                }
            });

            modalInstance.result
                .then(function (selectedItem) {
                    console.log(selectedItem);
                    var fragmentDeleted = FragmentDataService.DeleteFragment(selectedItem.type, selectedItem.name);

                    fragmentDeleted
                        .then(function (result) {
                            console.log('*********Fragment deleted');
                            vm.inputsData.splice(selectedItem.index, 1);

                        });
                },
                function () {
                    console.log('Modal dismissed at: ' + new Date())
                });
        };

        function SetDuplicatetedInput(size, inputName) {
            var modalInstance = $modal.open({
                animation: true,
                templateUrl: 'templates/components/st_duplicate_modal.tpl.html',
                controller: 'NewFragmentCtrl',
                size: 'lg',
                resolve: {
                    item: function () {
                        return inputName;
                    }
                }
            });

            modalInstance.result
                .then(function (selectedItem) {
                    delete selectedItem["id"];
                    console.log(selectedItem);

                    var newFragment = FragmentDataService.InsertFragment(selectedItem);

                    newFragment
                        .then(function (result) {
                            console.log('*********Fragment created');
                            console.log(result);

                            var newId = vm.inputsData[vm.inputsData.length-1].id + 1;
                            selectedItem.id = newId;

                            vm.inputsData.push(selectedItem);
                        },
                        function (error) {
                            console.log(error);
                            console.log('Modal dismissed at: ' + new Date())
                        });

                },
                function () {
                    console.log('Modal dismissed at: ' + new Date())
                });
        };
    };

    /*NEW FRAGMENT MODAL CONTROLLER*/
    angular
        .module('webApp')
        .controller('NewFragmentModalCtrl', NewFragmentModalCtrl);

    NewFragmentModalCtrl.$inject = ['$modalInstance', 'item'];

    function NewFragmentModalCtrl($modalInstance, item) {
        /*jshint validthis: true*/
        var vm = this;

        vm.setProperties = setProperties;
        vm.ok = ok;
        vm.cancel = cancel;
        vm.initFragmentObecjt = initFragmentObecjt;
        vm.setFragmentData = setFragmentData;
        vm.createTypeModels = createTypeModels;
        vm.dataSource = {};
        vm.dataSource.element = {};
        vm.templateInputsData = [];
        vm.properties = [];

        init();

        /////////////////////////////////

        function init() {
            console.log('*********Modal');
            console.log(item);

            vm.action = item.action;

            if (vm.action === 'modify') {
                vm.templateInputsData = item.inputDataTemplate;
                vm.dataSource = item.inputSelected;
                vm.createTypeModels(vm.templateInputsData);
                vm.selectedIndex = vm.index;
            }
            else {
                vm.templateInputsData = item;
                vm.initFragmentObecjt(vm.templateInputsData);
                vm.createTypeModels(vm.templateInputsData);
                vm.selectedIndex = 0;
            }
        };

        function initFragmentObecjt(fragmentData) {
            /*Init fragment*/
            vm.dataSource.fragmentType = 'input';
            vm.dataSource.name = '';

            /*Init fragment.element*/
            vm.dataSource.element.type = fragmentData[0].name;
            vm.dataSource.element.name = 'in-' + vm.dataSource.element.type;

            /*Init fragment.element.configuration*/
            vm.dataSource.element.configuration = {};

            vm.setFragmentData(0);
        };

        function createTypeModels(fragmentData) {
            /*Create one properties model for each input type*/
            for (var i=0; i<fragmentData.length; i++){
                vm.properties[fragmentData[i].name] = {};

                for (var j=0; j<fragmentData[i].properties.length; j++) {
                    if (fragmentData[i].properties[j].propertyId !== 'name' && fragmentData[i].properties[j].propertyId !== 'type'){
                        vm.properties[fragmentData[i].name][fragmentData[i].properties[j].propertyId] = '';
                    }
                }

                /*Init properties*/
                if(i === 0 && vm.action !== 'modify') {
                    vm.dataSource.element.configuration = vm.properties[fragmentData[i].name];
                }

                else if(vm.action === 'modify' && fragmentData[i].name === vm.dataSource.element.type) {
                    vm.properties[fragmentData[i].name] = vm.dataSource.element.configuration;
                    vm.dataSource.element.configuration = vm.properties[fragmentData[i].name];
                    vm.index = i;
                }
            }
        };

        function setFragmentData(index) {
            /*Set fragment*/
            vm.dataSource.description = vm.templateInputsData[index].description.long;
            vm.dataSource.shortDescription = vm.templateInputsData[index].description.short;
            vm.dataSource.icon = vm.templateInputsData[index].icon.url;
            vm.dataSource.element.name = 'in-' + vm.dataSource.element.type;
        };

        function setProperties(index, inputName) {
            vm.selectedIndex = index;
            vm.dataSource.element.configuration = vm.properties[inputName];
            vm.setFragmentData(index);
        };

        function ok() {
            var callBackData = {
                'index': item.index,
                'id': item.id,
                'data': vm.dataSource,
            };
            $modalInstance.close(callBackData);
        };

        function cancel() {
            $modalInstance.dismiss('cancel');
        };
    };

    /*NEW INPUT & DELETE INPUT MODALS CONTROLLER */
    angular
        .module('webApp')
        .controller('ModalInstanceCtrl', ModalInstanceCtrl);

    ModalInstanceCtrl.$inject = ['$scope', '$modalInstance', 'item'];

    function ModalInstanceCtrl($scope, $modalInstance, item) {
        console.log('*********Modal');
        console.log(item);

        $scope.inputs = item;

        $scope.ok = function () {
            $modalInstance.close($scope.inputs);
        };

        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
    };

    /*DUPLICATE INPUT MODAL CONTROLLER */
    angular
        .module('webApp')
        .controller('NewFragmentCtrl', NewFragmentCtrl);

    NewFragmentCtrl.$inject = ['$scope', '$modalInstance', 'item'];

    function NewFragmentCtrl($scope, $modalInstance, item) {
        console.log('*********Modal');
        console.log(item);

        $scope.inputData = item;

        $scope.ok = function () {
            $modalInstance.close(item);
        };

        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
    };
})();
<|endoftext|>