<commit_before>/*global define, console, declare */

/*
 | Copyright 2015 ESRI (UK) Limited
 |
 | 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([
    "dojo/_base/declare",
    "dojo/_base/lang",
    "dijit/_Widget",
    "dijit/_TemplatedMixin",
    "dijit/_WidgetsInTemplateMixin",
    "esri/dijit/Search",
    "dojo/dom-construct",
    "dijit/layout/ContentPane",
    "dijit/TitlePane",
    "dojox/widget/TitleGroup",
    "dojo/on",
    "dojo/Deferred",
    "dojo/query",
    "dojo/i18n",
    "dojo/NodeList-data",
    "dojo/i18n!./nls/Drilldown"
], function (declare, lang, _Widget, _TemplatedMixin, _WidgetsInTemplateMixin, Search, domConstruct, ContentPane, TitlePane, TitleGroup, on, Deferred, query, i18n) {

    return declare([_Widget, _TemplatedMixin, _WidgetsInTemplateMixin, Search], {
        // description:
        //      Search for and display address details in a hierarchical list

        baseClass: "drilldown",
        widgetsInTemplate: true,
        resultsElement: null,
        _titleGroups: [],

        constructor: function (args) {
            declare.safeMixin(this, args);
        },

        destroy: function () {
            // connections/subscriptions will be cleaned up during the destroy() lifecycle phase
            // call the superclass method of the same name.
            this._clearPicklist();
            this.inherited(arguments);

        },

        search: function () {
            // Override the Search widget search method

            var _this = this, results = new Deferred();

            this.inherited(arguments).then(function (res) {
                _this._buildPickListUi(res);
            });

            return results.promise;
        },

        _hydratePickListResult: function (picklist) {

            return this.inherited(arguments);
        },

        clear: function() {
            this._clearPicklist();
            this.inherited(arguments);
        },

        _hydrateResults: function (a) {
            if (a.PickListItems) {
                return a; //this._hydratePickListResult(a);
            }
            return this.inherited(arguments);
        },

        _isNullOrEmpty: function (/*Anything*/ obj) {
            // summary:
            //		Checks to see if the passed in thing is undefined, null or empty.
            // tags:
            //		private

            return (obj === undefined || obj === null || obj === '');
        },

        _formatResults: function (resultArray, sourceIndex, searchValue) {
            var c = {
                activeSourceIndex: sourceIndex,
                value: searchValue,
                numResults: 0,
                numErrors: 0,
                errors: null,
                results: null
            };
            var d = {}, e = {};

            if (resultArray) {
                if(sourceIndex === this._allIndex) {
                    // Using all locators
                    for (b = 0; b < resultArray.length; b++) {
                        if (!this._isNullOrEmpty(this.sources[b].locator.locatorType)) {
                            // Custom locator with picklists
                            e[sourceIndex] = resultArray[0];
                            c.numResults += resultArray[0].PickListItems.length;
                        }
                        else {
                            c = this.inherited(arguments);
                        }
                    }
                    c.results = e;
                    c.err = d;
                    return c;
                }
                else {
                    if (!this._isNullOrEmpty(this.activeSource.locator.locatorType)) {
                        // Custom locator with picklists
                        e[sourceIndex] = resultArray[0];
                        c.numResults += resultArray[0].PickListItems.length;
                        c.results = e;
                        c.err = d;
                        return c;
                    }
                    return this.inherited(arguments);
                }
            }
            return c;
        },

        _clearPicklist: function() {
            var m, mL;
            if (this._titleGroups.length > 0) {
                for (m = 0, mL = this._titleGroups.length; m < mL; m++) {
                    this._titleGroups[m].destroy();
                }
                this._titleGroups = [];
            }
        },

        _toggleTitleGroups: function(close) {
            var m, mL;
            if (this._titleGroups.length > 0) {
                for (m = 0, mL = this._titleGroups.length; m < mL; m++) {
                    if (close && this._titleGroups[m].open) {
                        this._titleGroups[m].toggle();
                    }
                    if (!close && !this._titleGroups[m].open) {
                        this._titleGroups[m].toggle;
                    }
                }
            }
        },

        _showNoResults: function() {
            this._noResults(this.value);
            this._showNoResultsMenu();
        },

        _isSingleResult: function(results) {
            var numberOfResults = 0, pickListItems;

            for (var source in results) {
                numberOfResults++;
            }

            if (numberOfResults === 1) {
                pickListItems = results[0].PickListItems;

                if (pickListItems.length === 1 && pickListItems[0].Addresses.length === 1) {
                    if (this._isNullOrEmpty(pickListItems[0].Addresses[0].Addresses)) {
                        return true;
                    }
                    if (!this._isNullOrEmpty(pickListItems[0].Addresses[0].Addresses) && pickListItems[0].Addresses[0].Addresses.length === 1) {
                        return true;
                    }
                }
                return false;
            }

            return false;
        },

        _buildPickListUi: function(results) {
            var _this = this, pickListItems, i = 0, iL = 0, resultsContainer, premiseList, premiseTitleGroup, m = 0, mL = 0,
                resultSource, noResults = false;

            // Clear list of title groups
            this._clearPicklist();

            // Create the TitleGroup container
            this.resultsElement = domConstruct.create("div", { id: "picklistResults", "class": "arcgisSearch searchGroup" }, this.domNode, "last");

            // Check to see if we only have a single results
            if ((_this.activeSourceIndex !== this._allIndex) && this._isSingleResult(results)) {
                var res = this._hydrateResult(results[0].PickListItems[0].Addresses[0], _this.activeSourceIndex, false);
                this.select(res);
            }
            else {

                if (!this._isNullOrEmpty(results)) {
                    for (resultSource in results) {

                        // Check we have some results
                        if (!this._isNullOrEmpty(results[resultSource]) && !this._isNullOrEmpty(results[resultSource].PickListItems)) {
                            // Get the picklist
                            pickListItems = results[resultSource].PickListItems;
                            iL = pickListItems.length;

                            if (iL > 0) {
                                var sourceContainer = domConstruct.create("div", { id: resultSource }, this.resultsElement, "last");
                                resultsContainer = new TitleGroup(null, sourceContainer);

                                // Keep a list of all groups
                                this._titleGroups.push(resultsContainer);

                                for (i = 0; i < iL; i++) {
                                    // Create the list of premises
                                    premiseList = [];

                                    premiseTitleGroup = this._createGroup(pickListItems[i]);

                                    titlePane = new TitlePane({
                                        title: pickListItems[i].Description,
                                        content: premiseTitleGroup,
                                        open: (iL === 1) ? true : false
                                    });
                                    titlePane.startup();

                                    resultsContainer.startup();

                                    // Output each street as a title pane
                                    resultsContainer.addChild(titlePane);
                                    noResults = false;
                                }
                            }
                            else {
                                // No results
                                noResults = true;
                            }
                        }
                        else {
                            // Output and error message
                            noResults = true;
                        }

                        if (!this._isNullOrEmpty(resultsContainer)) {
                            on(resultsContainer, ".drilldownResult:click", function (e) {
                                var loc = query(this).data()[0];
                                var res = _this._hydrateResult(loc.result, _this.activeSourceIndex, false);

                                _this._toggleTitleGroups(true);

                                _this.select(res);
                            });
                        }

                    }
                }

                if (noResults) {
                    this._showNoResults();
                }
            }
        },

        _createSubGroup: function (premiseList, titleGroup) {
            var k = 0, kL = 0, subPremiseTitleGroup = new TitleGroup(),
                subPremiseList = premiseList.Addresses;

            for (k = 0, kL = subPremiseList.length; k < kL; k++) {
                var node = domConstruct.toDom("" + subPremiseList[k].address + "");
                query(node).data("result", subPremiseList[k]);

                subPremiseTitleGroup.addChild(new ContentPane({
                    content: node
                }));
            }
            subPremiseTitleGroup.startup();

            titleGroup.addChild(new TitlePane({
                title: premiseList.Description,
                content: subPremiseTitleGroup,
                open: false
            }));
        },

        _createGroup: function (pickList) {
            var _this = this, j = 0, jL = 0, premiseTitleGroup = new TitleGroup(), premiseList, address = "", node;

            if (!this._isNullOrEmpty(pickList.Addresses) && pickList.Addresses.length > 1) {

                // Create a title group to hold the premise list
                premiseList = pickList.Addresses;

                for (j = 0, jL = premiseList.length; j < jL; j++) {
                    // Do we have a sub premise list?
                    if (!this._isNullOrEmpty(premiseList[j].Addresses) && premiseList[j].Addresses.length > 1) {
                        _this._createSubGroup(premiseList[j], premiseTitleGroup);
                    }
                    else {
                        // Single premise
                        if (!this._isNullOrEmpty(premiseList[j].address)) {
                            node = domConstruct.toDom("" + premiseList[j].address + "");
                            query(node).data("result", premiseList[j]);
                        }
                        else {
                            node = domConstruct.toDom("" + premiseList[j].Addresses[0].address + "");
                            query(node).data("result", premiseList[j].Addresses[0]);
                        }
                        premiseTitleGroup.addChild(new ContentPane({
                            content: node
                        }));
                    }
                }

                premiseTitleGroup.startup();
            }
            else {
                // Single result
                if (!this._isNullOrEmpty(pickList.Addresses[0].address)) {
                    node = domConstruct.toDom("" + pickList.Addresses[0].address + "");
                    query(node).data("result", pickList.Addresses[0]);

                    premiseTitleGroup = new ContentPane({
                        content: node
                    });
                }
                else if (!this._isNullOrEmpty(pickList.Addresses[0].Addresses) && pickList.Addresses[0].Addresses.length > 0) {
                    _this._createSubGroup(pickList.Addresses[0], premiseTitleGroup);
                    premiseTitleGroup.startup();
                }
            }
            return premiseTitleGroup;
        }

    });
});<commit_msg>Remove ID<commit_after>/*global define, console, declare */

/*
 | Copyright 2015 ESRI (UK) Limited
 |
 | 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([
    "dojo/_base/declare",
    "dojo/_base/lang",
    "dijit/_Widget",
    "dijit/_TemplatedMixin",
    "dijit/_WidgetsInTemplateMixin",
    "esri/dijit/Search",
    "dojo/dom-construct",
    "dijit/layout/ContentPane",
    "dijit/TitlePane",
    "dojox/widget/TitleGroup",
    "dojo/on",
    "dojo/Deferred",
    "dojo/query",
    "dojo/i18n",
    "dojo/NodeList-data",
    "dojo/i18n!./nls/Drilldown"
], function (declare, lang, _Widget, _TemplatedMixin, _WidgetsInTemplateMixin, Search, domConstruct, ContentPane, TitlePane, TitleGroup, on, Deferred, query, i18n) {

    return declare([_Widget, _TemplatedMixin, _WidgetsInTemplateMixin, Search], {
        // description:
        //      Search for and display address details in a hierarchical list

        baseClass: "drilldown",
        widgetsInTemplate: true,
        resultsElement: null,
        _titleGroups: [],

        constructor: function (args) {
            declare.safeMixin(this, args);
        },

        destroy: function () {
            // connections/subscriptions will be cleaned up during the destroy() lifecycle phase
            // call the superclass method of the same name.
            this._clearPicklist();
            this.inherited(arguments);

        },

        search: function () {
            // Override the Search widget search method

            var _this = this, results = new Deferred();

            this.inherited(arguments).then(function (res) {
                _this._buildPickListUi(res);
            });

            return results.promise;
        },

        _hydratePickListResult: function (picklist) {

            return this.inherited(arguments);
        },

        clear: function() {
            this._clearPicklist();
            this.inherited(arguments);
        },

        _hydrateResults: function (a) {
            if (a.PickListItems) {
                return a; //this._hydratePickListResult(a);
            }
            return this.inherited(arguments);
        },

        _isNullOrEmpty: function (/*Anything*/ obj) {
            // summary:
            //		Checks to see if the passed in thing is undefined, null or empty.
            // tags:
            //		private

            return (obj === undefined || obj === null || obj === '');
        },

        _formatResults: function (resultArray, sourceIndex, searchValue) {
            var c = {
                activeSourceIndex: sourceIndex,
                value: searchValue,
                numResults: 0,
                numErrors: 0,
                errors: null,
                results: null
            };
            var d = {}, e = {};

            if (resultArray) {
                if(sourceIndex === this._allIndex) {
                    // Using all locators
                    for (b = 0; b < resultArray.length; b++) {
                        if (!this._isNullOrEmpty(this.sources[b].locator.locatorType)) {
                            // Custom locator with picklists
                            e[sourceIndex] = resultArray[0];
                            c.numResults += resultArray[0].PickListItems.length;
                        }
                        else {
                            c = this.inherited(arguments);
                        }
                    }
                    c.results = e;
                    c.err = d;
                    return c;
                }
                else {
                    if (!this._isNullOrEmpty(this.activeSource.locator.locatorType)) {
                        // Custom locator with picklists
                        e[sourceIndex] = resultArray[0];
                        c.numResults += resultArray[0].PickListItems.length;
                        c.results = e;
                        c.err = d;
                        return c;
                    }
                    return this.inherited(arguments);
                }
            }
            return c;
        },

        _clearPicklist: function() {
            var m, mL;
            if (this._titleGroups.length > 0) {
                for (m = 0, mL = this._titleGroups.length; m < mL; m++) {
                    this._titleGroups[m].destroy();
                }
                this._titleGroups = [];
            }
        },

        _toggleTitleGroups: function(close) {
            var m, mL;
            if (this._titleGroups.length > 0) {
                for (m = 0, mL = this._titleGroups.length; m < mL; m++) {
                    if (close && this._titleGroups[m].open) {
                        this._titleGroups[m].toggle();
                    }
                    if (!close && !this._titleGroups[m].open) {
                        this._titleGroups[m].toggle;
                    }
                }
            }
        },

        _showNoResults: function() {
            this._noResults(this.value);
            this._showNoResultsMenu();
        },

        _isSingleResult: function(results) {
            var numberOfResults = 0, pickListItems;

            for (var source in results) {
                numberOfResults++;
            }

            if (numberOfResults === 1) {
                pickListItems = results[0].PickListItems;

                if (pickListItems.length === 1 && pickListItems[0].Addresses.length === 1) {
                    if (this._isNullOrEmpty(pickListItems[0].Addresses[0].Addresses)) {
                        return true;
                    }
                    if (!this._isNullOrEmpty(pickListItems[0].Addresses[0].Addresses) && pickListItems[0].Addresses[0].Addresses.length === 1) {
                        return true;
                    }
                }
                return false;
            }

            return false;
        },

        _buildPickListUi: function(results) {
            var _this = this, pickListItems, i = 0, iL = 0, resultsContainer, premiseList, premiseTitleGroup, m = 0, mL = 0,
                resultSource, noResults = false;

            // Clear list of title groups
            this._clearPicklist();

            // Create the TitleGroup container
            this.resultsElement = domConstruct.create("div", { "class": "arcgisSearch searchGroup picklistResults" }, this.domNode, "last");

            // Check to see if we only have a single results
            if ((_this.activeSourceIndex !== this._allIndex) && this._isSingleResult(results)) {
                var res = this._hydrateResult(results[0].PickListItems[0].Addresses[0], _this.activeSourceIndex, false);
                this.select(res);
            }
            else {

                if (!this._isNullOrEmpty(results)) {
                    for (resultSource in results) {

                        // Check we have some results
                        if (!this._isNullOrEmpty(results[resultSource]) && !this._isNullOrEmpty(results[resultSource].PickListItems)) {
                            // Get the picklist
                            pickListItems = results[resultSource].PickListItems;
                            iL = pickListItems.length;

                            if (iL > 0) {
                                var sourceContainer = domConstruct.create("div", { id: resultSource }, this.resultsElement, "last");
                                resultsContainer = new TitleGroup(null, sourceContainer);

                                // Keep a list of all groups
                                this._titleGroups.push(resultsContainer);

                                for (i = 0; i < iL; i++) {
                                    // Create the list of premises
                                    premiseList = [];

                                    premiseTitleGroup = this._createGroup(pickListItems[i]);

                                    titlePane = new TitlePane({
                                        title: pickListItems[i].Description,
                                        content: premiseTitleGroup,
                                        open: (iL === 1) ? true : false
                                    });
                                    titlePane.startup();

                                    resultsContainer.startup();

                                    // Output each street as a title pane
                                    resultsContainer.addChild(titlePane);
                                    noResults = false;
                                }
                            }
                            else {
                                // No results
                                noResults = true;
                            }
                        }
                        else {
                            // Output and error message
                            noResults = true;
                        }

                        if (!this._isNullOrEmpty(resultsContainer)) {
                            on(resultsContainer, ".drilldownResult:click", function (e) {
                                var loc = query(this).data()[0];
                                var res = _this._hydrateResult(loc.result, _this.activeSourceIndex, false);

                                _this._toggleTitleGroups(true);

                                _this.select(res);
                            });
                        }

                    }
                }

                if (noResults) {
                    this._showNoResults();
                }
            }
        },

        _createSubGroup: function (premiseList, titleGroup) {
            var k = 0, kL = 0, subPremiseTitleGroup = new TitleGroup(),
                subPremiseList = premiseList.Addresses;

            for (k = 0, kL = subPremiseList.length; k < kL; k++) {
                var node = domConstruct.toDom("" + subPremiseList[k].address + "");
                query(node).data("result", subPremiseList[k]);

                subPremiseTitleGroup.addChild(new ContentPane({
                    content: node
                }));
            }
            subPremiseTitleGroup.startup();

            titleGroup.addChild(new TitlePane({
                title: premiseList.Description,
                content: subPremiseTitleGroup,
                open: false
            }));
        },

        _createGroup: function (pickList) {
            var _this = this, j = 0, jL = 0, premiseTitleGroup = new TitleGroup(), premiseList, address = "", node;

            if (!this._isNullOrEmpty(pickList.Addresses) && pickList.Addresses.length > 1) {

                // Create a title group to hold the premise list
                premiseList = pickList.Addresses;

                for (j = 0, jL = premiseList.length; j < jL; j++) {
                    // Do we have a sub premise list?
                    if (!this._isNullOrEmpty(premiseList[j].Addresses) && premiseList[j].Addresses.length > 1) {
                        _this._createSubGroup(premiseList[j], premiseTitleGroup);
                    }
                    else {
                        // Single premise
                        if (!this._isNullOrEmpty(premiseList[j].address)) {
                            node = domConstruct.toDom("" + premiseList[j].address + "");
                            query(node).data("result", premiseList[j]);
                        }
                        else {
                            node = domConstruct.toDom("" + premiseList[j].Addresses[0].address + "");
                            query(node).data("result", premiseList[j].Addresses[0]);
                        }
                        premiseTitleGroup.addChild(new ContentPane({
                            content: node
                        }));
                    }
                }

                premiseTitleGroup.startup();
            }
            else {
                // Single result
                if (!this._isNullOrEmpty(pickList.Addresses[0].address)) {
                    node = domConstruct.toDom("" + pickList.Addresses[0].address + "");
                    query(node).data("result", pickList.Addresses[0]);

                    premiseTitleGroup = new ContentPane({
                        content: node
                    });
                }
                else if (!this._isNullOrEmpty(pickList.Addresses[0].Addresses) && pickList.Addresses[0].Addresses.length > 0) {
                    _this._createSubGroup(pickList.Addresses[0], premiseTitleGroup);
                    premiseTitleGroup.startup();
                }
            }
            return premiseTitleGroup;
        }

    });
});<|endoftext|>


<commit_before>var url = 'http://localhost/RegisterParts/index.php/';
var url_controller = 'http://localhost/buscapiezas/index.php/'; //'http://www.devetechnologies.com/RegisterParts/index.php/';
var folder = 'helpers/'; //Webservises
var controller = 'Api_ws/'; //Webservises
var controller_1 = 'api/';
var format = 'format/'; //Webservises
var format_type = 'json'; //Webservises
//var is_succes = false;
/*Script para asignar los valores de ciudad y pais en el formulario de registro usuario*/
$(document).ready(function () {
    $("#btnCreateAccount").click(function (e) {
        var country = $('#idSelectCountry option:selected').text();
        var city = $('#idSelectCity option:selected').text();
        $("#idNameCountry").val(country);
        $("#idNameCity").val(city);
    });
});
/*Se llenan los select box list dependiendo de lo seleccionado*/
$(document).ready(function () {
    getSystemPart();
    getMakes();
    $("#idSelectMake").change(function () {
        getVehicleMotorTypes($("#idSelectMake").val());
    });
    $("#idSelectVehiMotor").change(function () {
        getModelFormake($("#idSelectMake").val(), $('#idSelectVehiMotor').val());
    });
    $("#idSelectModel").change(function () {
        getGenerationForModel($("#idSelectModel").val());
        getModelGas($("#idSelectModel").val());
    });
    $("#idSelectGeneration").change(function () {
        getVehicleType($("#idSelectVehiMotor").val(), $("#idSelectMake").val(), $("#idSelectModel").val(), $('#idSelectGeneration').val());
    });
    $("#idButtonPart").click(function () {
        $(".removeTrParts").remove();
        getParts($('#idSelectCategory').val(), $('#idSelectType').val());
        /*Muestra la lista de piezas por categoria y tipo de vehiculo*/
        document.getElementById('idContainerlist').style.display = 'block';
        //$('#idButtonPart').attr("disabled", true);
    });
    $("#idButtonPartForUserReplacement").click(function (e) {
         $(".removeTrReplacement").remove();
        getPartsForUserReplacement($('#idInputUser').val(),
                $('#idSelectCategory').val(),
                $("#idSelectMake").val(),
                $("#idSelectVehiMotor").val(),
                $("#idSelectModel").val());
        /*Muestra la lista de piezas por usuarios*/
        document.getElementById('idContainerlist').style.display = 'block';
      //  $('#idButtonPartForUserReplacement').attr("disabled", true);
    });
});
/*Carga los sistemas a colocarle sus piezas*/
function getSystemPart() {
    var selectCategory = $('#idSelectCategory');
    //alert(url + folder + controller + 'system/' + format + format_type);
    $.ajax({
        url: url + folder + controller + 'system/' + format + format_type,
        type: 'GET',
        dataType: 'json',
        cache: false,
        success: function (data) {
            selectCategory.find('option').remove();
            selectCategory.append('<option value="0" selected>Todos los sistemas</option>');
            $(data.systems).each(function (i, v) {
                //console.log(v.name_category);
                selectCategory.append('<option value="' + v.id_category + '">' + v.name_category + '</option>');
            });
            selectCategory.prop('disabled', false);
        }, error: function (jqXHR, textStatus, errorThrown) {
            console.log('ERROR DESCONOCIDO ' + jqXHR);
        }
    });
}

/*Carga los vehiculos de motor dependiendo de la marca enviada mediante WS*/
function getVehicleMotorTypes(idMake) {
    var vehicleMotorType = $('#idSelectVehiMotor');
    $.ajax({
        url: url + folder + controller + 'vehiclemotortype/' + idMake + '/' + format + format_type,
        type: 'GET',
        dataType: 'json',
        cache: false,
        success: function (data) {
            vehicleMotorType.find('option').remove();
            vehicleMotorType.append('<option value="0" selected>Todos los vehiculos de motor</option>');
            $(data.typeMotors).each(function (i, v) {
                //console.log(v.type_name_vehicle);
                vehicleMotorType.append('<option value="' + v.id_type_vehicle_motor + '">' + v.type_name_vehicle + '</option>');
            });
            vehicleMotorType.prop('disabled', false);
        }, error: function () {
            alert('ERROR');
        }
    });
}

/*Carga las marcas enviadas mediante el webservices de registro piezas*/
function getMakes() {
    var makes = $('#idSelectMake');
    $.ajax({
        url: url + folder + controller + 'makes/' + format + format_type,
        type: 'GET',
        dataType: 'json',
        cache: false,
        success: function (data) {
            makes.find('option').remove();
            makes.append('<option value="0" selected>Todas las marcas</option>');
            $(data.makes).each(function (i, v) {
                //console.log(v.name_vehicle_make);
                makes.append('<option value="' + v.id_vehicle_make + '">' + v.name_vehicle_make + '</option>');
            });
            makes.prop('disabled', false);
        }, error: function () {

        }
    });
}

/*Carga los modelos por marca seleccionada mediante el webservises registro piezas*/
function getModelFormake(idMake, idSelectVehiMotor) {
    var model = $('#idSelectModel');
    $.ajax({
        url: url + folder + controller + 'modelformake/' + idMake + '/' + idSelectVehiMotor + '/' + format + format_type,
        type: 'GET',
        dataType: 'json',
        cache: false,
        success: function (data) {
            model.find('option').remove();
            model.append('<option value="0" selected>Todos los modelos</option>');
            $(data.models).each(function (i, v) {
                //console.log(v.model_name);
                model.append('<option value="' + v.id_model + '">' + v.model_name + '</option>');
            });
            model.prop('disabled', false);
        }, error: function () {
            alert('ERROR');
        }
    });
}

/*Carga los modelos por marca seleccionada mediante el webservises registro piezas*/
function getGenerationForModel(idModel) {
    var selectGeneration = $('#idSelectGeneration');
    $.ajax({
        url: url + folder + controller + 'generationformodel/' + idModel + '/' + format + format_type,
        type: 'GET',
        dataType: 'json',
        cache: false,
        success: function (data) {
            selectGeneration.find('option').remove();
            selectGeneration.append('<option value="0" selected>Todas las generaciones</option>');
            $(data.generations).each(function (i, v) {
                //console.log(v.generation);
                selectGeneration.append('<option value="' + v.id_generation + '">' + v.generation + '</option>');
            });
            selectGeneration.prop('disabled', false);
        }, error: function () {
            alert('ERROR');
        }
    });
}

/*Carga los tipos de vehiculos dependiendo de los parametros enviados al webservises*/
function getVehicleType(idVehicleMotor, idVehicleMake, idModel, idGeneration) {
    var selectType = $('#idSelectType');
    $.ajax({
        url: url + folder + controller + 'typesVehicles/' + idVehicleMotor + '/' + idVehicleMake + '/' + idModel + '/' + idGeneration + '/' + format + format_type,
        type: 'GET',
        dataType: 'json',
        cache: false,
        success: function (data) {
            selectType.find('option').remove();
            selectType.append('<option value="0" selected>Todos los tipos de vehiculos</option>');
            $(data.typesVehicles).each(function (i, v) {
                //console.log(v.name_vehicle_type);
                selectType.append('<option value="' + v.id_vehicle_type + '">' + v.name_vehicle_type + '</option>');
            });
            selectType.prop('disabled', false);
        }, error: function () {
            alert('ERROR');
        }
    });
}

/*Carga los combustibles existentes por modelo definido*/
function getModelGas(idModel) {
    var selectGas = $('#idSelectGas');
    $.ajax({
        url: url + folder + controller + 'gasformodel/' + idModel + '/' + format + format_type,
        type: 'GET',
        dataType: 'json',
        cache: false,
        success: function (data) {
            selectGas.find('option').remove();
            selectGas.append('<option value="0" selected>Todos los combustibles</option>');
            $(data.gasForModel).each(function (i, v) {
                // console.log(v.type_combustible);
                selectGas.append('<option value="' + v.id_combustible + '">' + v.type_combustible + '</option>');
            });
            selectGas.prop('disabled', false);
        }, error: function () {
            alert('ERROR');
        }
    });
}
/*Retorna todas las piezas por tipo de vehiculo*/
function getParts(idCategory, idVehicleType) {
    var listParts = $('#idBodyTable');
    $.ajax({
        url: url + folder + controller + 'partsForVehicleType/' + idCategory + '/' + idVehicleType + '/' + format + format_type,
        type: 'GET',
        dataType: 'Json',
        cache: false,
        success: function (data, textStatus, jqXHR) {
            $(data.parts).each(function (i, v) {
                listParts.append('
<input type="checkbox" class="checkthis" name="checkVal" value ="' + v.id_part + '"/>	 \n\
                        ' + v.name_part + '	' + v.name_category + '	' + v.name_vehicle_type + '	\n\
                        <input type="text" class="form-control input-lg" id="idPrice" name="' + v.id_part + '" value=""/>	\n\
                        <input type="text" class="form-control input-lg" id="idComent" name="' + v.id_part + '_comment" value=""/>	\n\

');
            });
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert('ERROR');
        }
    });
}

/*Retorna todas las piezas por repuesto*/
function getPartsForUserReplacement(idUser, idCategory, idmake, idVehicleTypeMotor, idModel) {
    var listParts = $('#idBodyTable');
    $.ajax({
        url: url + folder + controller + 'partForUserReplacement/' + idUser + '/' + idCategory + '/' + idmake + '/' + idVehicleTypeMotor + '/' + idModel + '/' + format + format_type,
        type: 'GET',
        dataType: 'Json',
        cache: false,
        success: function (data, textStatus, jqXHR) {
            // console.log(data.partsUserReplacement);
            $(data.partsUserReplacement).each(function (i, v) {
                listParts.append('
<input type="checkbox" class="checkthis" name="checkVal" value ="' + v.id_replacement + '"/>	\n\
                        ' + v.name_category + '	' + v.name_vehicle_make + '	' + v.model_name + '	\n\
                        ' + v.generation + '	' + v.name_category + '	' + v.name_part + '	' + v.state_name + '	\n\
                        ' + v.type_combustible + '	' + v.company_name + '	\n\
                        <input type="text" class="form-control input-lg" id="idPrice" name="' + v.id_replacement + '_price" value="' + v.price + '"/>	\n\
                        <input type="text" class="form-control input-lg" id="idComent" name="' + v.id_replacement + '_comment" value="' + v.comment + '"/>	\n\

');
            });
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert('ERROR');
        }
    });
}
/*Actualiza las piezas por repuesto*/
$(document).ready(function () {
    $("#idButtonUpdateParts").click(function (e) {
        $('#idButtonUpdateParts').attr("disabled", true);
        var idCamp = null;
        var urlController = url_controller + 'search_parts_control/updatePart';
        var idForm = "#idSearchPartForm";
        $("input:checkbox:checked").each(function (i, v) {
            if (v.value !== 'on') {
                $('#idPartReplacement').val(v.value); //Asigna el id del replacement
                updateRepalcementParts(idCamp, urlController, idForm);
            }
        });
        $('#idClose').click(function (e) {
            location.reload();
        });
        $('#idClose_error').click(function (e) {
            location.reload();
        });
    });
});
/*inserta las piezas por categoria, tipo de vehiculo y repuesto*/
$(document).ready(function () {
    $("#idButtonSavePart").click(function (e) {
        var idCamp = null;
        var urlController = url_controller + 'create_parts_control/createPart';
        var idForm = "#idPartForm";
        $("input:checkbox:checked").each(function (i, v) {
            if (v.value !== 'on') {
                $('#idVehiclePart').val(v.value); //Asigna el id de cada pieza
                $("#idButtonSavePart").attr("disabled", true);
                insertRegyster(idCamp, urlController, idForm);
            }
        });
        $('#idClose').click(function (e) {
            location.reload();
        });
        $('#idClose_error').click(function (e) {
            location.reload();
        });
    });
});
/*Inserta registros en la DB de manera dinamica*/
function insertRegyster(idCamp, url, idForm) {
    if ($(idCamp).val() !== "") {
        $.ajax({
            url: url,
            type: 'POST',
            data: $(idForm).serialize(),
            success: function (respuesta) {
                alert(respuesta);
                document.getElementById('idMesage_succes').style.display = 'block';
            },
            complete: function (jqXHR, textStatus) {

            },
            error: function (jqXHR, textStatus, errorThrown) {
                document.getElementById('idMesage_error').style.display = 'block';
                console.log('ERROR DESCONOCIDO ' + jqXHR);
            }
        });
    }

}

/*Actualiza registro data table piezas por repuestos*/
function updateRepalcementParts(idCamp, url, idForm) {
    if ($(idCamp).val() !== "") {
        $.ajax({
            url: url,
            type: 'POST',
            data: $(idForm).serialize(),
            success: function (respuesta) {
                //alert(respuesta);
                document.getElementById('idMesage_succes').style.display = 'block';
            },
            complete: function (jqXHR, textStatus) {

            },
            error: function (jqXHR, textStatus, errorThrown) {
                document.getElementById('idMesage_error').style.display = 'block';
                console.log('ERROR DESCONOCIDO ' + jqXHR);
            }
        });
    }

}

/*Manejo de sesion activa o inactiva*/
$(document).ready(function () {
    $.idleTimer(600000);
    $(document).bind("idle.idleTimer", function () {
        $.ajax({
            url: url_controller + folder + controller_1 + 'endSesionInactivity',
            type: 'POST',
            data: '',
            success: function (respuesta) {
                $('#idButtonPart').attr("disabled", true);
                document.getElementById('idMesage_sesion').style.display = 'block';
                $('#idCloseSesion').click(function (e) {
                    window.location.href = url_controller;
                });
            }
        });
        // function you want to fire when the user goes idle
    });
    $(document).bind("active.idleTimer", function () {
        //llama mediante ajax para borrar todos los datos de sesion y ir a la
        //pagina de login
        // function you want to fire when the user becomes active again
        // alert('Hola');
    });
});
<commit_msg>Se corrige el error para la consulta combustible modelo y se comenta la traza<commit_after>var url = 'http://localhost/RegisterParts/index.php/';
var url_controller = 'http://localhost/buscapiezas/index.php/'; //'http://www.devetechnologies.com/RegisterParts/index.php/';
var folder = 'helpers/'; //Webservises
var controller = 'Api_ws/'; //Webservises
var controller_1 = 'api/';
var format = 'format/'; //Webservises
var format_type = 'json'; //Webservises
//var is_succes = false;
/*Script para asignar los valores de ciudad y pais en el formulario de registro usuario*/
$(document).ready(function () {
    $("#btnCreateAccount").click(function (e) {
        var country = $('#idSelectCountry option:selected').text();
        var city = $('#idSelectCity option:selected').text();
        $("#idNameCountry").val(country);
        $("#idNameCity").val(city);
    });
});
/*Se llenan los select box list dependiendo de lo seleccionado*/
$(document).ready(function () {
    getSystemPart();
    getMakes();
    $("#idSelectMake").change(function () {
        getVehicleMotorTypes($("#idSelectMake").val());
    });
    $("#idSelectVehiMotor").change(function () {
        getModelFormake($("#idSelectMake").val(), $('#idSelectVehiMotor').val());
    });
    $("#idSelectModel").change(function () {
        getGenerationForModel($("#idSelectModel").val());
        getModelGas($("#idSelectModel").val());
    });
    $("#idSelectGeneration").change(function () {
        getVehicleType($("#idSelectVehiMotor").val(), $("#idSelectMake").val(), $("#idSelectModel").val(), $('#idSelectGeneration').val());
    });
    $("#idButtonPart").click(function () {
        $(".removeTrParts").remove();
        getParts($('#idSelectCategory').val(), $('#idSelectType').val());
        /*Muestra la lista de piezas por categoria y tipo de vehiculo*/
        document.getElementById('idContainerlist').style.display = 'block';
        //$('#idButtonPart').attr("disabled", true);
    });
    $("#idButtonPartForUserReplacement").click(function (e) {
         $(".removeTrReplacement").remove();
        getPartsForUserReplacement($('#idInputUser').val(),
                $('#idSelectCategory').val(),
                $("#idSelectMake").val(),
                $("#idSelectVehiMotor").val(),
                $("#idSelectModel").val());
        /*Muestra la lista de piezas por usuarios*/
        document.getElementById('idContainerlist').style.display = 'block';
      //  $('#idButtonPartForUserReplacement').attr("disabled", true);
    });
});
/*Carga los sistemas a colocarle sus piezas*/
function getSystemPart() {
    var selectCategory = $('#idSelectCategory');
    //alert(url + folder + controller + 'system/' + format + format_type);
    $.ajax({
        url: url + folder + controller + 'system/' + format + format_type,
        type: 'GET',
        dataType: 'json',
        cache: false,
        success: function (data) {
            selectCategory.find('option').remove();
            selectCategory.append('<option value="0" selected>Todos los sistemas</option>');
            $(data.systems).each(function (i, v) {
                //console.log(v.name_category);
                selectCategory.append('<option value="' + v.id_category + '">' + v.name_category + '</option>');
            });
            selectCategory.prop('disabled', false);
        }, error: function (jqXHR, textStatus, errorThrown) {
            console.log('ERROR DESCONOCIDO ' + jqXHR);
        }
    });
}

/*Carga los vehiculos de motor dependiendo de la marca enviada mediante WS*/
function getVehicleMotorTypes(idMake) {
    var vehicleMotorType = $('#idSelectVehiMotor');
    $.ajax({
        url: url + folder + controller + 'vehiclemotortype/' + idMake + '/' + format + format_type,
        type: 'GET',
        dataType: 'json',
        cache: false,
        success: function (data) {
            vehicleMotorType.find('option').remove();
            vehicleMotorType.append('<option value="0" selected>Todos los vehiculos de motor</option>');
            $(data.typeMotors).each(function (i, v) {
                //console.log(v.type_name_vehicle);
                vehicleMotorType.append('<option value="' + v.id_type_vehicle_motor + '">' + v.type_name_vehicle + '</option>');
            });
            vehicleMotorType.prop('disabled', false);
        }, error: function () {
            alert('ERROR');
        }
    });
}

/*Carga las marcas enviadas mediante el webservices de registro piezas*/
function getMakes() {
    var makes = $('#idSelectMake');
    $.ajax({
        url: url + folder + controller + 'makes/' + format + format_type,
        type: 'GET',
        dataType: 'json',
        cache: false,
        success: function (data) {
            makes.find('option').remove();
            makes.append('<option value="0" selected>Todas las marcas</option>');
            $(data.makes).each(function (i, v) {
                //console.log(v.name_vehicle_make);
                makes.append('<option value="' + v.id_vehicle_make + '">' + v.name_vehicle_make + '</option>');
            });
            makes.prop('disabled', false);
        }, error: function () {

        }
    });
}

/*Carga los modelos por marca seleccionada mediante el webservises registro piezas*/
function getModelFormake(idMake, idSelectVehiMotor) {
    var model = $('#idSelectModel');
    $.ajax({
        url: url + folder + controller + 'modelformake/' + idMake + '/' + idSelectVehiMotor + '/' + format + format_type,
        type: 'GET',
        dataType: 'json',
        cache: false,
        success: function (data) {
            model.find('option').remove();
            model.append('<option value="0" selected>Todos los modelos</option>');
            $(data.models).each(function (i, v) {
                //console.log(v.model_name);
                model.append('<option value="' + v.id_model + '">' + v.model_name + '</option>');
            });
            model.prop('disabled', false);
        }, error: function () {
            alert('ERROR');
        }
    });
}

/*Carga los modelos por marca seleccionada mediante el webservises registro piezas*/
function getGenerationForModel(idModel) {
    var selectGeneration = $('#idSelectGeneration');
    $.ajax({
        url: url + folder + controller + 'generationformodel/' + idModel + '/' + format + format_type,
        type: 'GET',
        dataType: 'json',
        cache: false,
        success: function (data) {
            selectGeneration.find('option').remove();
            selectGeneration.append('<option value="0" selected>Todas las generaciones</option>');
            $(data.generations).each(function (i, v) {
                //console.log(v.generation);
                selectGeneration.append('<option value="' + v.id_generation + '">' + v.generation + '</option>');
            });
            selectGeneration.prop('disabled', false);
        }, error: function () {
            alert('ERROR');
        }
    });
}

/*Carga los tipos de vehiculos dependiendo de los parametros enviados al webservises*/
function getVehicleType(idVehicleMotor, idVehicleMake, idModel, idGeneration) {
    var selectType = $('#idSelectType');
    $.ajax({
        url: url + folder + controller + 'typesVehicles/' + idVehicleMotor + '/' + idVehicleMake + '/' + idModel + '/' + idGeneration + '/' + format + format_type,
        type: 'GET',
        dataType: 'json',
        cache: false,
        success: function (data) {
            selectType.find('option').remove();
            selectType.append('<option value="0" selected>Todos los tipos de vehiculos</option>');
            $(data.typesVehicles).each(function (i, v) {
                //console.log(v.name_vehicle_type);
                selectType.append('<option value="' + v.id_vehicle_type + '">' + v.name_vehicle_type + '</option>');
            });
            selectType.prop('disabled', false);
        }, error: function () {
            alert('ERROR');
        }
    });
}

/*Carga los combustibles existentes por modelo definido*/
function getModelGas(idModel) {
    var selectGas = $('#idSelectGas');
    $.ajax({
        url: url + folder + controller + 'gasformodel/' + idModel + '/' + format + format_type,
        type: 'GET',
        dataType: 'json',
        cache: false,
        success: function (data) {
            selectGas.find('option').remove();
            selectGas.append('<option value="0" selected>Todos los combustibles</option>');
            $(data.gasForModel).each(function (i, v) {
                // console.log(v.type_combustible);
                selectGas.append('<option value="' + v.id_combustible + '">' + v.type_combustible + '</option>');
            });
            selectGas.prop('disabled', false);
        }, error: function () {
            alert('ERROR');
        }
    });
}
/*Retorna todas las piezas por tipo de vehiculo*/
function getParts(idCategory, idVehicleType) {
    var listParts = $('#idBodyTable');
    $.ajax({
        url: url + folder + controller + 'partsForVehicleType/' + idCategory + '/' + idVehicleType + '/' + format + format_type,
        type: 'GET',
        dataType: 'Json',
        cache: false,
        success: function (data, textStatus, jqXHR) {
            $(data.parts).each(function (i, v) {
                listParts.append('
<input type="checkbox" class="checkthis" name="checkVal" value ="' + v.id_part + '"/>	 \n\
                        ' + v.name_part + '	' + v.name_category + '	' + v.name_vehicle_type + '	\n\
                        <input type="text" class="form-control input-lg" id="idPrice" name="' + v.id_part + '" value=""/>	\n\
                        <input type="text" class="form-control input-lg" id="idComent" name="' + v.id_part + '_comment" value=""/>	\n\

');
            });
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert('ERROR');
        }
    });
}

/*Retorna todas las piezas por repuesto*/
function getPartsForUserReplacement(idUser, idCategory, idmake, idVehicleTypeMotor, idModel) {
    var listParts = $('#idBodyTable');
    $.ajax({
        url: url + folder + controller + 'partForUserReplacement/' + idUser + '/' + idCategory + '/' + idmake + '/' + idVehicleTypeMotor + '/' + idModel + '/' + format + format_type,
        type: 'GET',
        dataType: 'Json',
        cache: false,
        success: function (data, textStatus, jqXHR) {
            // console.log(data.partsUserReplacement);
            $(data.partsUserReplacement).each(function (i, v) {
                listParts.append('
<input type="checkbox" class="checkthis" name="checkVal" value ="' + v.id_replacement + '"/>	\n\
                        ' + v.name_category + '	' + v.name_vehicle_make + '	' + v.model_name + '	\n\
                        ' + v.generation + '	' + v.name_category + '	' + v.name_part + '	' + v.state_name + '	\n\
                        ' + v.type_combustible + '	' + v.company_name + '	\n\
                        <input type="text" class="form-control input-lg" id="idPrice" name="' + v.id_replacement + '_price" value="' + v.price + '"/>	\n\
                        <input type="text" class="form-control input-lg" id="idComent" name="' + v.id_replacement + '_comment" value="' + v.comment + '"/>	\n\

');
            });
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert('ERROR');
        }
    });
}
/*Actualiza las piezas por repuesto*/
$(document).ready(function () {
    $("#idButtonUpdateParts").click(function (e) {
        $('#idButtonUpdateParts').attr("disabled", true);
        var idCamp = null;
        var urlController = url_controller + 'search_parts_control/updatePart';
        var idForm = "#idSearchPartForm";
        $("input:checkbox:checked").each(function (i, v) {
            if (v.value !== 'on') {
                $('#idPartReplacement').val(v.value); //Asigna el id del replacement
                updateRepalcementParts(idCamp, urlController, idForm);
            }
        });
        $('#idClose').click(function (e) {
            location.reload();
        });
        $('#idClose_error').click(function (e) {
            location.reload();
        });
    });
});
/*inserta las piezas por categoria, tipo de vehiculo y repuesto*/
$(document).ready(function () {
    $("#idButtonSavePart").click(function (e) {
        var idCamp = null;
        var urlController = url_controller + 'create_parts_control/createPart';
        var idForm = "#idPartForm";
        $("input:checkbox:checked").each(function (i, v) {
            if (v.value !== 'on') {
                $('#idVehiclePart').val(v.value); //Asigna el id de cada pieza
                $("#idButtonSavePart").attr("disabled", true);
                insertRegyster(idCamp, urlController, idForm);
            }
        });
        $('#idClose').click(function (e) {
            location.reload();
        });
        $('#idClose_error').click(function (e) {
            location.reload();
        });
    });
});
/*Inserta registros en la DB de manera dinamica*/
function insertRegyster(idCamp, url, idForm) {
    if ($(idCamp).val() !== "") {
        $.ajax({
            url: url,
            type: 'POST',
            data: $(idForm).serialize(),
            success: function (respuesta) {
                //alert(respuesta);
                document.getElementById('idMesage_succes').style.display = 'block';
            },
            complete: function (jqXHR, textStatus) {

            },
            error: function (jqXHR, textStatus, errorThrown) {
                document.getElementById('idMesage_error').style.display = 'block';
                console.log('ERROR DESCONOCIDO ' + jqXHR);
            }
        });
    }

}

/*Actualiza registro data table piezas por repuestos*/
function updateRepalcementParts(idCamp, url, idForm) {
    if ($(idCamp).val() !== "") {
        $.ajax({
            url: url,
            type: 'POST',
            data: $(idForm).serialize(),
            success: function (respuesta) {
                //alert(respuesta);
                document.getElementById('idMesage_succes').style.display = 'block';
            },
            complete: function (jqXHR, textStatus) {

            },
            error: function (jqXHR, textStatus, errorThrown) {
                document.getElementById('idMesage_error').style.display = 'block';
                console.log('ERROR DESCONOCIDO ' + jqXHR);
            }
        });
    }

}

/*Manejo de sesion activa o inactiva*/
$(document).ready(function () {
    $.idleTimer(600000);
    $(document).bind("idle.idleTimer", function () {
        $.ajax({
            url: url_controller + folder + controller_1 + 'endSesionInactivity',
            type: 'POST',
            data: '',
            success: function (respuesta) {
                $('#idButtonPart').attr("disabled", true);
                document.getElementById('idMesage_sesion').style.display = 'block';
                $('#idCloseSesion').click(function (e) {
                    window.location.href = url_controller;
                });
            }
        });
        // function you want to fire when the user goes idle
    });
    $(document).bind("active.idleTimer", function () {
        //llama mediante ajax para borrar todos los datos de sesion y ir a la
        //pagina de login
        // function you want to fire when the user becomes active again
        // alert('Hola');
    });
});
<|endoftext|>


<commit_before>/* global MO5 */
MO5().define("MO5.types", function () {

    var types = {};

    types.isObject = function (thing) {
        return (typeof thing === "object" && thing !== null);
    };

    return types;

});<commit_msg>Added isString() function to MO5.types.<commit_after>/* global MO5 */
MO5().define("MO5.types", function () {

    var types = {};

    types.isObject = function (thing) {
        return (typeof thing === "object" && thing !== null);
    };

    types.isString = function (thing) {
        return typeof thing === "string";
    };

    return types;

});<|endoftext|>


<commit_before>/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set ft=javascript ts=2 et sw=2 tw=80: */
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

function threadIsPaused(dbg, index) {
  return findElement(dbg, "threadsPaneItem", index).querySelector(
    ".pause-badge"
  );
}

function threadIsSelected(dbg, index) {
  return findElement(dbg, "threadsPaneItem", index).classList.contains(
    "selected"
  );
}

// Test basic windowless worker functionality: the main thread and worker can be
// separately controlled from the same debugger.
add_task(async function() {
  await pushPref("devtools.debugger.features.windowless-workers", true);

  const dbg = await initDebugger("doc-windowless-workers.html");
  const mainThread = dbg.toolbox.threadClient.actor;

  const workers = await getWorkers(dbg);
  ok(workers.length == 2, "Got two workers");
  const worker1Thread = workers[0].actor;
  const worker2Thread = workers[1].actor;

  const mainThreadSource = findSource(dbg, "doc-windowless-workers.html");
  const workerSource = findSource(dbg, "simple-worker.js");

  info("Test pausing in the main thread");
  assertNotPaused(dbg);
  await dbg.actions.breakOnNext();
  await waitForPaused(dbg, "doc-windowless-workers.html");
  assertPausedAtSourceAndLine(dbg, mainThreadSource.id, 10);

  info("Test pausing in a worker");
  await dbg.actions.selectThread(worker1Thread);
  assertNotPaused(dbg);
  await dbg.actions.breakOnNext();
  await waitForPaused(dbg, "simple-worker.js");
  assertPausedAtSourceAndLine(dbg, workerSource.id, 3);

  info("Test stepping in a worker");
  await stepOver(dbg);
  assertPausedAtSourceAndLine(dbg, workerSource.id, 4);

  info("Test resuming in a worker");
  await resume(dbg);
  assertNotPaused(dbg);

  info("Test stepping in the main thread");
  dbg.actions.selectThread(mainThread);
  await stepOver(dbg);
  assertPausedAtSourceAndLine(dbg, mainThreadSource.id, 11);

  info("Test resuming in the mainThread");
  await resume(dbg);
  assertNotPaused(dbg);

  info("Test pausing in both workers");
  await addBreakpoint(dbg, "simple-worker", 10);
  invokeInTab("sayHello");
  dbg.actions.selectThread(worker1Thread);
  await waitForPaused(dbg);
  assertPausedAtSourceAndLine(dbg, workerSource.id, 10);

  dbg.actions.selectThread(worker2Thread);
  await waitForPaused(dbg);
  assertPausedAtSourceAndLine(dbg, workerSource.id, 10);

  info("Test stepping in second worker and not the first");
  await stepOver(dbg);
  assertPausedAtSourceAndLine(dbg, workerSource.id, 11);
  dbg.actions.selectThread(worker1Thread);
  assertPausedAtSourceAndLine(dbg, workerSource.id, 10);
});
<commit_msg>[sync] Bug 1530554 - Fix expression evaluation in worker threads; r=bhackett<commit_after>/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set ft=javascript ts=2 et sw=2 tw=80: */
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

function threadIsPaused(dbg, index) {
  return findElement(dbg, "threadsPaneItem", index).querySelector(
    ".pause-badge"
  );
}

function threadIsSelected(dbg, index) {
  return findElement(dbg, "threadsPaneItem", index).classList.contains(
    "selected"
  );
}

function getLabel(dbg, index) {
  return findElement(dbg, "expressionNode", index).innerText;
}

function getValue(dbg, index) {
  return findElement(dbg, "expressionValue", index).innerText;
}

// Test basic windowless worker functionality: the main thread and worker can be
// separately controlled from the same debugger.
add_task(async function() {
  await pushPref("devtools.debugger.features.windowless-workers", true);

  const dbg = await initDebugger("doc-windowless-workers.html");
  const mainThread = dbg.toolbox.threadClient.actor;

  const workers = await getWorkers(dbg);
  ok(workers.length == 2, "Got two workers");
  const worker1Thread = workers[0].actor;
  const worker2Thread = workers[1].actor;

  const mainThreadSource = findSource(dbg, "doc-windowless-workers.html");
  const workerSource = findSource(dbg, "simple-worker.js");

  info("Test pausing in the main thread");
  assertNotPaused(dbg);
  await dbg.actions.breakOnNext();
  await waitForPaused(dbg, "doc-windowless-workers.html");
  assertPausedAtSourceAndLine(dbg, mainThreadSource.id, 10);

  info("Test pausing in a worker");
  await dbg.actions.selectThread(worker1Thread);
  assertNotPaused(dbg);
  await dbg.actions.breakOnNext();
  await waitForPaused(dbg, "simple-worker.js");
  assertPausedAtSourceAndLine(dbg, workerSource.id, 3);

  await addExpression(dbg, "count");
  is(getLabel(dbg, 1), "count");
  const v = getValue(dbg, 1);
  ok(v == "" + +v, "Value of count should be a number");

  info("Test stepping in a worker");
  await stepOver(dbg);
  assertPausedAtSourceAndLine(dbg, workerSource.id, 4);

  // The watch expression should update with an incremented value.
  await waitUntil(() => {
    const v2 = getValue(dbg, 1);
    return +v2 == +v + 1;
  });

  info("Test resuming in a worker");
  await resume(dbg);
  assertNotPaused(dbg);

  info("Test stepping in the main thread");
  dbg.actions.selectThread(mainThread);
  await stepOver(dbg);
  assertPausedAtSourceAndLine(dbg, mainThreadSource.id, 11);

  info("Test resuming in the mainThread");
  await resume(dbg);
  assertNotPaused(dbg);

  info("Test pausing in both workers");
  await addBreakpoint(dbg, "simple-worker", 10);
  invokeInTab("sayHello");
  dbg.actions.selectThread(worker1Thread);
  await waitForPaused(dbg);
  assertPausedAtSourceAndLine(dbg, workerSource.id, 10);

  dbg.actions.selectThread(worker2Thread);
  await waitForPaused(dbg);
  assertPausedAtSourceAndLine(dbg, workerSource.id, 10);

  info("Test stepping in second worker and not the first");
  await stepOver(dbg);
  assertPausedAtSourceAndLine(dbg, workerSource.id, 11);
  dbg.actions.selectThread(worker1Thread);
  assertPausedAtSourceAndLine(dbg, workerSource.id, 10);
});
<|endoftext|>


<commit_before>(function (global) {
    System.config({
        paths: {
            // paths serve as alias
            'npm:': 'node_modules/'
        },
        // map tells the System loader where to look for things
        map: {
            // our app is within the app folder
            app: 'app',
            // angular bundles
            '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
            '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
            '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
            '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
            '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
            '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
            '@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',
            '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
            '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
            '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
            '@angular/animations': 'npm:@angular/animations/bundles/animations.umd.js',
            '@angular/animations/browser': 'npm:@angular/animations/bundles/animations-browser.umd.js',
            '@angular/platform-browser/animations': 'npm:@angular/platform-browser/bundles/platform-browser-animations.umd.js',

             //material
            '@angular/material': 'npm:@angular/material/bundles/material.umd.js',
         //   '@angular/cdk': 'npm:@angular/cdk/bundles/cdk.umd.js',
            '@angular/cdk/a11y': 'npm:@angular/cdk/bundles/cdk-a11y.umd.js',
            '@angular/cdk/bidi': 'npm:@angular/cdk/bundles/cdk-bidi.umd.js',
            '@angular/cdk/coercion': 'npm:@angular/cdk/bundles/cdk-coercion.umd.js',
            '@angular/cdk/collections': 'npm:@angular/cdk/bundles/cdk-collections.umd.js',
            '@angular/cdk/keycodes': 'npm:@angular/cdk/bundles/cdk-keycodes.umd.js',
            '@angular/cdk/observers': 'npm:@angular/cdk/bundles/cdk-observers.umd.js',
            '@angular/cdk/overlay': 'npm:@angular/cdk/bundles/cdk-overlay.umd.js',
            '@angular/cdk/platform': 'npm:@angular/cdk/bundles/cdk-platform.umd.js',
            '@angular/cdk/portal': 'npm:@angular/cdk/bundles/cdk-portal.umd.js',
            '@angular/cdk/accordion' : 'npm:@angular/cdk/bundles/cdk-accordion.umd.js',
            '@angular/cdk/layout' : 'npm:@angular/cdk/bundles/cdk-layout.umd.js',
            '@angular/cdk/scrolling': 'npm:@angular/cdk/bundles/cdk-scrolling.umd.js',
            '@angular/cdk/table': 'npm:@angular/cdk/bundles/cdk-table.umd.js',
            '@angular/cdk/text-field': 'npm:@angular/cdk/bundles/cdk-text-field.umd.js',
            '@angular/cdk/tree': 'npm:@angular/cdk/bundles/cdk-tree.umd.js',
            '@angular/cdk/stepper': 'npm:@angular/cdk/bundles/cdk-stepper.umd.js',

            // other libraries
            'rxjs': 'npm:rxjs',
            'rxjs-compat': 'npm:rxjs-compat',
            'rxjs-system-bundle': 'npm:rxjs-system-bundle',
            'hammerjs': 'npm:hammerjs',
            'tslib': 'npm:tslib/tslib.js'
        },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
            app: {main: './main.js',defaultExtension: 'js'},
            'rxjs': {main: 'index.js', defaultExtension: 'js'},
            'rxjs/operators': {main: 'index.js', defaultExtension: 'js'},
             hammerjs:  { main: './hammer.js', defaultExtension: 'js'}
        }
    });
})(this);
<commit_msg>Update systemjs.config.js<commit_after>(function (global) {
    System.config({
        paths: {
            // paths serve as alias
            'npm:': 'node_modules/'
        },
        // map tells the System loader where to look for things
        map: {
            // our app is within the app folder
            app: 'app',
            // angular bundles
            '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
            '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
            '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
            '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
            '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
            '@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',
            '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
            '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
            '@angular/animations': 'npm:@angular/animations/bundles/animations.umd.js',
            '@angular/animations/browser': 'npm:@angular/animations/bundles/animations-browser.umd.js',
            '@angular/platform-browser/animations': 'npm:@angular/platform-browser/bundles/platform-browser-animations.umd.js',

             //material
            '@angular/material': 'npm:@angular/material/bundles/material.umd.js',
            '@angular/cdk/a11y': 'npm:@angular/cdk/bundles/cdk-a11y.umd.js',
            '@angular/cdk/bidi': 'npm:@angular/cdk/bundles/cdk-bidi.umd.js',
            '@angular/cdk/coercion': 'npm:@angular/cdk/bundles/cdk-coercion.umd.js',
            '@angular/cdk/collections': 'npm:@angular/cdk/bundles/cdk-collections.umd.js',
            '@angular/cdk/keycodes': 'npm:@angular/cdk/bundles/cdk-keycodes.umd.js',
            '@angular/cdk/observers': 'npm:@angular/cdk/bundles/cdk-observers.umd.js',
            '@angular/cdk/overlay': 'npm:@angular/cdk/bundles/cdk-overlay.umd.js',
            '@angular/cdk/platform': 'npm:@angular/cdk/bundles/cdk-platform.umd.js',
            '@angular/cdk/portal': 'npm:@angular/cdk/bundles/cdk-portal.umd.js',
            '@angular/cdk/accordion' : 'npm:@angular/cdk/bundles/cdk-accordion.umd.js',
            '@angular/cdk/layout' : 'npm:@angular/cdk/bundles/cdk-layout.umd.js',
            '@angular/cdk/scrolling': 'npm:@angular/cdk/bundles/cdk-scrolling.umd.js',
            '@angular/cdk/table': 'npm:@angular/cdk/bundles/cdk-table.umd.js',
            '@angular/cdk/text-field': 'npm:@angular/cdk/bundles/cdk-text-field.umd.js',
            '@angular/cdk/tree': 'npm:@angular/cdk/bundles/cdk-tree.umd.js',
            '@angular/cdk/stepper': 'npm:@angular/cdk/bundles/cdk-stepper.umd.js',

            // other libraries
            'rxjs': 'npm:rxjs',
            'rxjs-compat': 'npm:rxjs-compat',
            'rxjs-system-bundle': 'npm:rxjs-system-bundle',
            'hammerjs': 'npm:hammerjs',
            'tslib': 'npm:tslib/tslib.js'
        },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
            app: {main: './main.js',defaultExtension: 'js'},
            'rxjs': {main: 'index.js', defaultExtension: 'js'},
            'rxjs/operators': {main: 'index.js', defaultExtension: 'js'},
             hammerjs:  { main: './hammer.js', defaultExtension: 'js'}
        }
    });
})(this);
<|endoftext|>


<commit_before>(function ( mw, $ ) {
	"use strict";

	mw.PluginManager.add( 'mediaList', mw.KBaseMediaList.extend( {

			defaultConfig: {
				'parent': 'sideBarContainer',
				'containerPosition': null,//'after',
				'order': 2,
				'showTooltip': false,
				"displayImportance": 'high',
				'templatePath': 'components/mediaList/mediaList.tmpl.html',
				'cuePointType': ['thumbCuePoint.Thumb'],
				'oneSecRotatorSlidesLimit': 61,
				'twoSecRotatorSlidesLimit': 250,
				'maxRotatorSlides': 125,
				'mediaItemWidth': 290,
				'titleLimit': 29,
				'descriptionLimit': 80,
				'thumbnailWidth' : 100,
				'horizontalMediaItemWidth': 290,
				'overflow': false,
				'includeThumbnail': true,
				'includeItemStartTime': true,
				'includeItemNumberPattern': false,
				'includeMediaItemDuration': true
			},

			mediaList: [],

			isDisabled: true,

			setup: function ( embedPlayer ) {
				this.addBindings();
			},
			addBindings: function () {
				var _this = this;

				this.bind( 'KalturaSupport_ThumbCuePointsReady', function () {
					//Get chapters data from cuepoints
					var chaptersRawData =_this.getChaptersData();
					//Create media items from raw data
					_this.addMediaItems(chaptersRawData);
					//Need to recalc all durations after we have all the items startTime values
					_this.setMediaItemTime();
					//Set data initialized flag for handlers to start working
					_this.dataIntialized = true;
					//Render the media list
					_this.renderMediaList();
				} );

				this.bind( 'playerReady updatePlayHeadPercent', function ( e, newState ) {
					if (_this.dataIntialized) {
						_this.updateActiveItem();
					}
				});

				this.bind( 'onChangeMedia', function(){
					_this.destroy();
					// redraw the list
					_this.shouldAddScroll();
				});
			},
			isSafeEnviornment: function(){
				var _this = this;
				var res = false;
				if (this.getPlayer().kCuePoints){
					var cuePoints = this.getPlayer().kCuePoints.getCuePoints();
					var filteredCuePoints = $.grep(cuePoints, function(cuePoint){
						var found = false;
						$.each(_this.getConfig('cuePointType'), function(i, cuePointType){
							if (cuePointType == cuePoint.cuePointType) {
								found = true;
								return false;
							}
						});
						return found;
					});
					res =  (filteredCuePoints.length > 0) ? true : false;
				}
				return res;
			},

			getChaptersData: function(){
				var _this = this;
				//Init data provider
				var cuePoints = this.getPlayer().kCuePoints.getCuePoints();
				//Generate data transfer object
				var filteredCuePoints = $.grep(cuePoints, function(cuePoint){
					var found = false;
					$.each(_this.getConfig('cuePointType'), function(i, cuePointType){
						if (cuePointType == cuePoint.cuePointType) {
							found = true;
							return false;
						}
					});
					return found;
				});

				filteredCuePoints.sort( function ( a, b ) {
					return a.startTime - b.startTime;
				} );
				return filteredCuePoints;
			},
			addMediaItems: function(items ,index){
				var _this = this;
				$.each(items, function(i, item){
					var mediaItem;
					var customData = item.partnerData ? JSON.parse(item.partnerData) :  {};
					var title = item.title || customData.title;
					var description = item.description || customData.desc;
					var thumbnailUrl = item.thumbnailUrl || customData.thumbUrl || _this.getThumbUrl(item);
					var thumbnailRotatorUrl = _this.getConfig( 'thumbnailRotator' ) ? _this.getThumRotatorUrl() : '';

					mediaItem = {
						order: index,
						id: item.id,
						title: title,
						description: description,
						width: _this.getConfig( 'mediaItemWidth' ),
						thumbnail: {
							url: thumbnailUrl,
							thumbAssetId: item.assetId,
							rotatorUrl: thumbnailRotatorUrl,
							width: _this.getThumbWidth(),
							height: _this.getThumbHeight()
						},
						startTime: item.startTime / 1000,
						startTimeDisplay: _this.formatTimeDisplayValue(kWidget.seconds2npt( item.startTime / 1000 )),
						endTime: null,
						durationDisplay: null,
						chapterNumber: _this.getItemNumber(index)

					};
					_this.mediaList.push(mediaItem);
				});
			},
			getMediaItemThumbs: function(callback){
				var _this = this;
				var requestArray = [];
				var response = [];
				$.each(this.mediaList, function(index, item) {
					requestArray.push(
						{
							'service': 'thumbAsset',
							'action': 'getUrl',
							'id': item.thumbnail.thumbAssetId
						}
					);
					response[index] = { id: item.id, url: null};
				});

				// do the api request
				this.getKalturaClient().doRequest( requestArray, function ( data ) {
					// Validate result
					if ( !_this.isValidResult( data ) ) {
						return;
					}
					$.each(data, function(index, url) {
						response[index]['url'] = url;

					});
					callback.apply(_this, [response]);
				} );
			},
			setMediaItemTime: function(){
				var _this = this;
				$.each(this.mediaList, function(index, item){
					if (_this.mediaList[index + 1]){
						item.endTime = _this.mediaList[index + 1].startTime;
					} else {
						item.endTime = _this.getPlayer().duration;
					}

					item.durationDisplay = kWidget.seconds2npt((item.endTime - item.startTime) );
				});
			},
			formatTimeDisplayValue: function(time){
				// Add 0 padding to start time min
				var timeParts = time.split(':');
				if( timeParts.length == 2 && timeParts[0].length == 1 ) {
					time = '0' + time;
				}
				return time;
			},

			isValidResult: function( data ){
				// Check if we got error
				if( !data
					||
					( data.code && data.message )
					){
					//this.log('Error getting related items: ' + data.message);
					//this.getBtn().hide();
					this.error = true;
					return false;
				}
				this.error = false;
				return true;
			},
			//UI Handlers
			mediaClicked: function(mediaIndex){
				// start playback
				this.getPlayer().sendNotification( 'doPlay' );
				// see to start time and play ( +.1 to avoid highlight of prev chapter )
				this.getPlayer().sendNotification( 'doSeek', ( this.mediaList[mediaIndex].startTime ) + .1 );
			},
			updateActiveItem: function( ){
				var _this = this;
				// search chapter for current active
				var activeIndex = 0;
				var time = this.getPlayer().currentTime;
				$.each( this.mediaList, function( inx, item){
					if( time > ( item.startTime ) ){
						activeIndex = inx;
					}
				});
				var $activeChapter = this.getActiveItem();
				var actualActiveIndex = this.selectedMediaItemIndex;
				// Check if active is not already set:
				if( actualActiveIndex == activeIndex ){
					// update duration count down:
					var item = this.mediaList[ activeIndex ];
					if( item ){
						this.setSelectedMedia(activeIndex);
						item.active = true;
						var endTime = item.endTime;
						var countDown =  Math.abs( time - endTime );
						this.updateActiveItemDuration(countDown);
					}
				} else {
					var item = _this.mediaList[ actualActiveIndex ];
					if ( item ) {
						item.active = false;
						var startTime = item.startTime ;
						var endTime = item.endTime;
						this.updateActiveItemDuration( endTime - startTime );
					}

					// Check if we should pause on chapter update:
					if ( this.getConfig( 'pauseAfterChapter' ) && !this.skipPauseFlag ) {
						this.getPlayer().sendNotification( 'doPause' );
					}
					// restore skip pause flag:
					this.skipPauseFlag = false;

					if ( this.mediaList[ activeIndex ] ) {
						this.setSelectedMedia(activeIndex);
					}
				}
			}
		} )
	);

})( window.mw, window.jQuery );<commit_msg>Prevent multiple calls for setting activeItem<commit_after>(function ( mw, $ ) {
	"use strict";

	mw.PluginManager.add( 'mediaList', mw.KBaseMediaList.extend( {

			defaultConfig: {
				'parent': 'sideBarContainer',
				'containerPosition': null,
				'order': 2,
				'showTooltip': false,
				"displayImportance": 'high',
				'templatePath': 'components/mediaList/mediaList.tmpl.html',
				'cuePointType': ['thumbCuePoint.Thumb'],
				'oneSecRotatorSlidesLimit': 61,
				'twoSecRotatorSlidesLimit': 250,
				'maxRotatorSlides': 125,
				'mediaItemWidth': 290,
				'titleLimit': 29,
				'descriptionLimit': 80,
				'thumbnailWidth' : 100,
				'horizontalMediaItemWidth': 290,
				'overflow': false,
				'includeThumbnail': true,
				'includeItemStartTime': true,
				'includeItemNumberPattern': false,
				'includeMediaItemDuration': true
			},

			mediaList: [],

			isDisabled: true,

			setup: function ( embedPlayer ) {
				this.addBindings();
			},
			addBindings: function () {
				var _this = this;

				this.bind( 'KalturaSupport_ThumbCuePointsReady', function () {
					//Get chapters data from cuepoints
					var chaptersRawData =_this.getChaptersData();
					//Create media items from raw data
					_this.addMediaItems(chaptersRawData);
					//Need to recalc all durations after we have all the items startTime values
					_this.setMediaItemTime();
					//Set data initialized flag for handlers to start working
					_this.dataIntialized = true;
					//Render the media list
					_this.renderMediaList();
				} );

				this.bind( 'playerReady updatePlayHeadPercent', function ( e, newState ) {
					if (_this.dataIntialized) {
						_this.updateActiveItem();
					}
				});

				this.bind( 'onChangeMedia', function(){
					_this.destroy();
					// redraw the list
					_this.shouldAddScroll();
				});
			},
			isSafeEnviornment: function(){
				var _this = this;
				var res = false;
				if (this.getPlayer().kCuePoints){
					var cuePoints = this.getPlayer().kCuePoints.getCuePoints();
					var filteredCuePoints = $.grep(cuePoints, function(cuePoint){
						var found = false;
						$.each(_this.getConfig('cuePointType'), function(i, cuePointType){
							if (cuePointType == cuePoint.cuePointType) {
								found = true;
								return false;
							}
						});
						return found;
					});
					res =  (filteredCuePoints.length > 0) ? true : false;
				}
				return res;
			},

			getChaptersData: function(){
				var _this = this;
				//Init data provider
				var cuePoints = this.getPlayer().kCuePoints.getCuePoints();
				//Generate data transfer object
				var filteredCuePoints = $.grep(cuePoints, function(cuePoint){
					var found = false;
					$.each(_this.getConfig('cuePointType'), function(i, cuePointType){
						if (cuePointType == cuePoint.cuePointType) {
							found = true;
							return false;
						}
					});
					return found;
				});

				filteredCuePoints.sort( function ( a, b ) {
					return a.startTime - b.startTime;
				} );
				return filteredCuePoints;
			},
			addMediaItems: function(items ,index){
				var _this = this;
				$.each(items, function(i, item){
					var mediaItem;
					var customData = item.partnerData ? JSON.parse(item.partnerData) :  {};
					var title = item.title || customData.title;
					var description = item.description || customData.desc;
					var thumbnailUrl = item.thumbnailUrl || customData.thumbUrl || _this.getThumbUrl(item);
					var thumbnailRotatorUrl = _this.getConfig( 'thumbnailRotator' ) ? _this.getThumRotatorUrl() : '';

					mediaItem = {
						order: index,
						id: item.id,
						title: title,
						description: description,
						width: _this.getConfig( 'mediaItemWidth' ),
						thumbnail: {
							url: thumbnailUrl,
							thumbAssetId: item.assetId,
							rotatorUrl: thumbnailRotatorUrl,
							width: _this.getThumbWidth(),
							height: _this.getThumbHeight()
						},
						startTime: item.startTime / 1000,
						startTimeDisplay: _this.formatTimeDisplayValue(kWidget.seconds2npt( item.startTime / 1000 )),
						endTime: null,
						durationDisplay: null,
						chapterNumber: _this.getItemNumber(index)

					};
					_this.mediaList.push(mediaItem);
				});
			},
			getMediaItemThumbs: function(callback){
				var _this = this;
				var requestArray = [];
				var response = [];
				$.each(this.mediaList, function(index, item) {
					requestArray.push(
						{
							'service': 'thumbAsset',
							'action': 'getUrl',
							'id': item.thumbnail.thumbAssetId
						}
					);
					response[index] = { id: item.id, url: null};
				});

				// do the api request
				this.getKalturaClient().doRequest( requestArray, function ( data ) {
					// Validate result
					if ( !_this.isValidResult( data ) ) {
						return;
					}
					$.each(data, function(index, url) {
						response[index]['url'] = url;

					});
					callback.apply(_this, [response]);
				} );
			},
			setMediaItemTime: function(){
				var _this = this;
				$.each(this.mediaList, function(index, item){
					if (_this.mediaList[index + 1]){
						item.endTime = _this.mediaList[index + 1].startTime;
					} else {
						item.endTime = _this.getPlayer().duration;
					}

					item.durationDisplay = kWidget.seconds2npt((item.endTime - item.startTime) );
				});
			},
			formatTimeDisplayValue: function(time){
				// Add 0 padding to start time min
				var timeParts = time.split(':');
				if( timeParts.length == 2 && timeParts[0].length == 1 ) {
					time = '0' + time;
				}
				return time;
			},

			isValidResult: function( data ){
				// Check if we got error
				if( !data
					||
					( data.code && data.message )
					){
					//this.log('Error getting related items: ' + data.message);
					//this.getBtn().hide();
					this.error = true;
					return false;
				}
				this.error = false;
				return true;
			},
			//UI Handlers
			mediaClicked: function(mediaIndex){
				// start playback
				this.getPlayer().sendNotification( 'doPlay' );
				// see to start time and play ( +.1 to avoid highlight of prev chapter )
				this.getPlayer().sendNotification( 'doSeek', ( this.mediaList[mediaIndex].startTime ) + .1 );
			},
			updateActiveItem: function( ){
				var _this = this;
				// search chapter for current active
				var activeIndex = 0;
				var time = this.getPlayer().currentTime;
				$.each( this.mediaList, function( inx, item){
					if( time > ( item.startTime ) ){
						activeIndex = inx;
					}
				});
				var $activeChapter = this.getActiveItem();
				var actualActiveIndex = this.selectedMediaItemIndex;
				// Check if active is not already set:
				if( actualActiveIndex == activeIndex ) {
					// update duration count down:
					var item = this.mediaList[ activeIndex ];
					if ( item ) {
						if (!item.active){
							this.setSelectedMedia( activeIndex );
							item.active = true;
						}
						var endTime = item.endTime;
						var countDown = Math.abs( time - endTime );
						this.updateActiveItemDuration( countDown );
					}
				} else {
					var item = _this.mediaList[ actualActiveIndex ];
					if ( item && item.active) {
						item.active = false;
						var startTime = item.startTime ;
						var endTime = item.endTime;
						this.updateActiveItemDuration( endTime - startTime );
					}

					// Check if we should pause on chapter update:
					if ( this.getConfig( 'pauseAfterChapter' ) && !this.skipPauseFlag ) {
						this.getPlayer().sendNotification( 'doPause' );
					}
					// restore skip pause flag:
					this.skipPauseFlag = false;

					if ( this.mediaList[ activeIndex ] ) {
						this.setSelectedMedia(activeIndex);
					}
				}
			}
		} )
	);

})( window.mw, window.jQuery );<|endoftext|>