<commit_before>$(document).ready(function () {
    /**
     * All filtering related code
     **/
    function filtering() {
        var resultsToolbar = $('.toolbar-pf-results');
        var countResults = $('#count-results');
        var activeFilters = $('#active-filters');
        var filterInput = $('#filter');
        var filterDiv = $('#filter-div');
        var filterOptionsList = filterDiv.find('ul.dropdown-menu').first();
        var filterByLabel = $('.filter-by, #filter-by'); // $('.filter-by');
        var clearFiltersButton = $('#clear-filters');
        var filterTypeDiv = $('#filter-type');

        /** Active filters */
        var filters = [];

        var hasItemInArrayCallback = function(element, filterOption) {
            var filteringData = $(element).data('filtering');

            if (!filteringData || !filteringData.hasOwnProperty('tags') || filteringData.tags.length === 0) {
                return false;
            }
            var searchText = filterOption.data.text;
            var regex = filterOption.data.isRegex ? new RegExp(filterOption.data.text, 'i') : null;

            var filtered = filteringData.tags.filter(function(element) {
                if (regex != null)
                    if (element.match(regex) !== null) return true;

                // Always try a literal match if there is no regex match
                if (element.toString().toLowerCase().indexOf(searchText.toLowerCase()) != -1) return true;

                return false;
            });

            return filtered.length > 0;
        };

        var checkNameMatchCallback = function(element, filterOption) {
            var name = $(element).data('name');
            var searchText = filterOption.data.text;

            if (filterOption.data.isRegex) {
                var regex = new RegExp(searchText, 'i');
                return name.match(regex) !== null;
            } else {
                if (name.toString().toLowerCase().indexOf(searchText.toLowerCase()) != -1) return true;
            }
        };

        /** Available filter options */
        var filterOptions = [
            { name: 'Name', value: 'name', data: '', callback:  checkNameMatchCallback },
            { name: 'Tags', value: 'tags', callback: hasItemInArrayCallback, data: '' }
        ];

        var andReducer = function(prev, curr) { return prev && curr; };
        var orReducer  = function(prev, curr) { return prev || curr; };

        var filterTypes = [
            { name: 'Matches all filters (AND)', reducer: andReducer, default: true },
            { name: 'Matches any filter (OR)',  reducer: orReducer,  default: false }
        ];

        /** Currently selected filter option */
        var currentFilterConfiguration = {
            filterBy: filterOptions[0],
            type: filterTypes[0]
        };

        function initialize() {
            $('div.real div.appInfo').each(function () {
                var tags = $(this).find('div.techs span.label').map(function() {
                    return $(this).text().trim();
                }).toArray();

                var filtering = {
                    tags: tags
                };

                $(this).data('filtering', filtering);
            });

            filterOptions.forEach(function(option) {
                filterOptionsList.append(makeFilterOptionListItem(option));
            });

            filterByLabel.text(currentFilterConfiguration.filterBy.name);

            makeTagsClickable();

            // initialise collapsable element, disabling toggle-on-init parameter
            $("#searchTermError").collapse({toggle:false});

            /**
             * Event handler for <enter> on filter-by input
             */
            $('#filter-form').on('submit', function(e) {
                e.preventDefault();
                var filterValue = filterInput.val().trim();
                if (addFilter(filterValue, currentFilterConfiguration.filterBy, true))
                {
                    filterInput.val('');
                    $("#searchTermError").collapse('hide');
                }
                else
                {
                    filterInput.addClass('alert alert-warning');
                    filterInput.attr('title', 'Invalid Input');
                    $("#searchTermError").collapse('show');
                }
            });

            filterInput.on('input', function(e) {
                e.preventDefault();
                filterInput.removeClass('alert alert-warning');
                filterInput.attr('title', '');
            });

            /** Event handler for clear filters action */
            clearFiltersButton.on('click', function() {
                filters = [];
                filterData();
            });

            /** Use first item from list for filtering */
            filterOptionsList.find('li a').first().click();

            filterTypes.forEach(function(filterType) {
                filterTypeDiv.find('ul.dropdown-menu').append(makeFilterType(filterType));
            });

            /** Use first filter-type (AND) for filtering */
            filterTypeDiv.find('li a').first().click();
        }

        /**
         * Makes tags in application row clickable and adds them to filter after clicking
         *
         */
        function makeTagsClickable() {
            $('div.techs span.label').each(function() {
                var anchored = $('');
                anchored.append($(this).clone());
                anchored.on('click', function() {
                    addFilter($(this).text().trim(), filterOptions[1], false);
                });

                $(this).replaceWith(anchored);
            });
        }

        function makeFilterType(filterType) {
            var html = $('

');
            var a = html.find('a');
            a.text(filterType.name);
            a.data('filterBy', filterType);

            a.on('click', function() {
                $('#filter-type').find('li a').removeClass('selected');
                $(this).addClass('selected');
                currentFilterConfiguration.type = filterType;
                $('.filter-type').text(filterType.name);
                filterData();
            });

            return html;
        }

        /**
         * Checks if object has callback
         *
         * @param object
         * @returns {boolean}
         */
        function hasCallback(object) {
            return object.hasOwnProperty('callback') && typeof object.callback === 'function';
        }

        /**
         * Filters data by filters array
         *
         */
        function filterData() {
            var filterFailed = false;
            var filteredDivs = $('div.real div.appInfo').map(function(idx, element) {
                var show = true;

                if (filters.length > 0) {
                    var filterResults = filters.map(function (filterOption) {
                        if (hasCallback(filterOption)) {
                            try
                            {
                                return filterOption.callback(element, filterOption);
                            }
                            catch(e)
                            {
                                console.error('Invalid input regular expression');
                                filterFailed = true;
                                return true;
                            }
                        } else {
                            console.error('Expected callback to be defined on filterOption');
                        }
                    });

                    var reduceOptions = currentFilterConfiguration.type;
                    show = filterResults.reduce(reduceOptions.reducer, reduceOptions.default);
                }

                if(!filterFailed) {
                    if (!show) {
                        $(this).hide();
                    } else {
                        $(this).show();
                    }
                }
                return show;
            }).toArray();
            if (!filterFailed) {
                var countUnfiltered = filteredDivs.length;
                var countFiltered = filteredDivs.filter(function(show) { return show; }).length;

                countResults.text(countFiltered);

                refreshFilterPanel();
                return true;
            }
            else
            {
                return false;
            }
        }

        /**
         * Redraws filter panel with used filters labels
         *
         */
        function refreshFilterPanel() {
            activeFilters =  $('#active-filters');
            var newActiveFilters = activeFilters.clone(false);
            newActiveFilters.empty();

            filters.forEach(function(filter) {
                newActiveFilters.append(makeFilteredByLabel(filter));
            });

            activeFilters.replaceWith(newActiveFilters);

            if (filters.length === 0) {
                resultsToolbar.addClass('hidden');
            } else {
                resultsToolbar.removeClass('hidden');
            }
        }

        /**
         * Removes filter from filters array
         *
         * @param item
         * @param node
         */
        function removeFilter(item, node) {
            filters = filters.filter(function(currentItem) { return currentItem !== item; });
            node.remove();
            filterData();
        }

        /**
         * Makes new filtered-by label
         * (used in filtered-by toolbar)
         *
         * @param item {object}
         * @returns {jQuery|HTMLElement}
         */
        function makeFilteredByLabel(item) {
            var html = $('
\
                    \

');

            var a = html.find('a');
            html.find('span.label').prepend(item.name + ': ' + item.data);
            a.on('click', function() {
                removeFilter(item, html);
            });

            html.data('filter', item);

            return html;
        }

        /**
         * Adds filter to filters array and filters data by it
         *
         * @param value {string}
         * @param option {object}
         */
        function addFilter(value, option, isRegex) {
            var returnValue = true;
            var filter = $.extend({}, option);
            filter.data = { text: value, isRegex: isRegex };
            filters.push(filter);

            if (!filterData())
            {
                filters.pop();
                returnValue = false;
            }

            return returnValue;
        }

        /**
         * Creates HTML element for available filters list
         *
         * @param filterOption {object}
         * @returns {jQuery|HTMLElement}
         */
        function makeFilterOptionListItem(filterOption) {
            var html = $('

');
            var a = html.find('a');
            a.text(filterOption.name);
            a.data('filterBy', filterOption);

            a.on('click', function() {
                filterOptionsList.find('li a').removeClass('selected');
                $(this).addClass('selected');
                currentFilterConfiguration.filterBy = filterOption;
                filterByLabel.text(filterOption.name);
            });

            return html;
        }

        initialize();
    }

    /**
     * All sorting related code
     */
    function sorting() {
        var sortDiv = $('#sort');
        var sortBy = $('#sort-by');
        var sortOrder = $('#sort-order');
        var sortIcon = sortOrder.find('span.fa');
        var sortList = sortDiv.find('ul.dropdown-menu');

        var lowerCaseStringComparator = function(a, b) {
            return a.localeCompare(b);
        };

        var storyPointComparator = function(a, b) {
            a = parseInt(a.replace(/[^0-9]/g, ''));
            b = parseInt(b.replace(/[^0-9]/g, ''));
            return parseInt(a) - parseInt(b);
        };

        var sortOptions = [
            { name: 'Name', value: 'name', comparator:  lowerCaseStringComparator },
            { name: 'Story Points', value: 'storypoints', comparator: storyPointComparator }
        ];

        var currentSortConfiguration = {
            sortBy: sortOptions[0],
            order: 1 // +1 ascending, -1 descending
        };

        var sortOrderClasses = {
            ASC: 'fa-sort-alpha-asc',
            DESC: 'fa-sort-alpha-desc'
        };

        function initialize() {
            $('div.real div.appInfo').each(function (idx, el) {
                $(this).data('name', $(this).find('.fileName').text().trim());
                $(this).data('storypoints', $(this).find('.effortPoints.total .points').text().trim());
            });

            sortOptions.forEach(function(option) {
                sortList.append(makeSortListItem(option));
            });

            /** Sorts applications by name */
            sortList.find('li a').first().click();

            /**
             * On click handler for sort order button
             * Switches between ASC/DESC sorting
             */
            sortOrder.on('click', function() {
                var currentClass;
                var newClass;

                if (currentSortConfiguration.order === 1) {
                    currentClass = sortOrderClasses.ASC;
                    newClass = sortOrderClasses.DESC;
                } else {
                    currentClass = sortOrderClasses.DESC;
                    newClass = sortOrderClasses.ASC;
                }

                currentSortConfiguration.order *= -1;

                sortIcon.removeClass(currentClass);
                sortIcon.addClass(newClass);

                sortData();
            });
        }

        function makeSortListItem(sortOption) {
            var html = $('

');
            var a = html.find('a');
            a.text(sortOption.name);
            a.data('sortBy', sortOption);

            a.on('click', function() {
                sortList.find('li a').removeClass('selected');
                $(this).addClass('selected');
                currentSortConfiguration.sortBy = sortOption;
                sortBy.text(sortOption.name);
                sortData();
            });

            return html;
        }

        /**
         * Checks if object has comparator
         *
         * @param object
         * @returns {boolean}
         */
        function hasComparator(object) {
            return object.hasOwnProperty('comparator') && typeof object.comparator === 'function';
        }

        /**
         * Sorts applications by specified criteria
         */
        function sortData() {
            $('div.real div.appInfo').sortElements(function(elementA, elementB) {
                var result = 0;

                var a = $(elementA).data(currentSortConfiguration.sortBy.value);
                var b = $(elementB).data(currentSortConfiguration.sortBy.value);

                if (hasComparator(currentSortConfiguration.sortBy)) {
                    result = currentSortConfiguration.sortBy.comparator(a, b);
                } else {
                    result = a > b ? 1 : -1;
                }

                return result * currentSortConfiguration.order;
            });
        }

        initialize();
    }

    filtering();
    sorting();
});
<commit_msg>WINDUP-2035: Fixed tag presentation (tags vs tag, placeholder text, and label)<commit_after>$(document).ready(function () {
    /**
     * All filtering related code
     **/
    function filtering() {
        var resultsToolbar = $('.toolbar-pf-results');
        var countResults = $('#count-results');
        var activeFilters = $('#active-filters');
        var filterInput = $('#filter');
        var filterDiv = $('#filter-div');
        var filterOptionsList = filterDiv.find('ul.dropdown-menu').first();
        var filterByLabel = $('.filter-by, #filter-by'); // $('.filter-by');
        var clearFiltersButton = $('#clear-filters');
        var filterTypeDiv = $('#filter-type');

        /** Active filters */
        var filters = [];

        var hasItemInArrayCallback = function(element, filterOption) {
            var filteringData = $(element).data('filtering');

            if (!filteringData || !filteringData.hasOwnProperty('tags') || filteringData.tags.length === 0) {
                return false;
            }
            var searchText = filterOption.data.text;
            var regex = filterOption.data.isRegex ? new RegExp(filterOption.data.text, 'i') : null;

            var filtered = filteringData.tags.filter(function(element) {
                if (regex != null)
                    if (element.match(regex) !== null) return true;

                // Always try a literal match if there is no regex match
                if (element.toString().toLowerCase().indexOf(searchText.toLowerCase()) != -1) return true;

                return false;
            });

            return filtered.length > 0;
        };

        var checkNameMatchCallback = function(element, filterOption) {
            var name = $(element).data('name');
            var searchText = filterOption.data.text;

            if (filterOption.data.isRegex) {
                var regex = new RegExp(searchText, 'i');
                return name.match(regex) !== null;
            } else {
                if (name.toString().toLowerCase().indexOf(searchText.toLowerCase()) != -1) return true;
            }
        };

        /** Available filter options */
        var filterOptions = [
            { name: 'Name', value: 'name', hint: "Filter By Name...", data: '', callback:  checkNameMatchCallback },
            { name: 'Tag', value: 'tags', hint: "Filter By Tag...", callback: hasItemInArrayCallback, data: '' }
        ];

        var andReducer = function(prev, curr) { return prev && curr; };
        var orReducer  = function(prev, curr) { return prev || curr; };

        var filterTypes = [
            { name: 'Matches all filters (AND)', reducer: andReducer, default: true },
            { name: 'Matches any filter (OR)',  reducer: orReducer,  default: false }
        ];

        /** Currently selected filter option */
        var currentFilterConfiguration = {
            filterBy: filterOptions[0],
            type: filterTypes[0]
        };

        function initialize() {
            $('div.real div.appInfo').each(function () {
                var tags = $(this).find('div.techs span.label').map(function() {
                    return $(this).text().trim();
                }).toArray();

                var filtering = {
                    tags: tags
                };

                $(this).data('filtering', filtering);
            });

            filterOptions.forEach(function(option) {
                filterOptionsList.append(makeFilterOptionListItem(option));
            });

            filterByLabel.text(currentFilterConfiguration.filterBy.name);

            makeTagsClickable();

            // initialise collapsable element, disabling toggle-on-init parameter
            $("#searchTermError").collapse({toggle:false});

            /**
             * Event handler for <enter> on filter-by input
             */
            $('#filter-form').on('submit', function(e) {
                e.preventDefault();
                var filterValue = filterInput.val().trim();
                if (addFilter(filterValue, currentFilterConfiguration.filterBy, true))
                {
                    filterInput.val('');
                    $("#searchTermError").collapse('hide');
                }
                else
                {
                    filterInput.addClass('alert alert-warning');
                    filterInput.attr('title', 'Invalid Input');
                    $("#searchTermError").collapse('show');
                }
            });

            filterInput.on('input', function(e) {
                e.preventDefault();
                filterInput.removeClass('alert alert-warning');
                filterInput.attr('title', '');
            });

            /** Event handler for clear filters action */
            clearFiltersButton.on('click', function() {
                filters = [];
                filterData();
            });

            /** Use first item from list for filtering */
            filterOptionsList.find('li a').first().click();

            filterTypes.forEach(function(filterType) {
                filterTypeDiv.find('ul.dropdown-menu').append(makeFilterType(filterType));
            });

            /** Use first filter-type (AND) for filtering */
            filterTypeDiv.find('li a').first().click();
        }

        /**
         * Makes tags in application row clickable and adds them to filter after clicking
         *
         */
        function makeTagsClickable() {
            $('div.techs span.label').each(function() {
                var anchored = $('');
                anchored.append($(this).clone());
                anchored.on('click', function() {
                    addFilter($(this).text().trim(), filterOptions[1], false);
                });

                $(this).replaceWith(anchored);
            });
        }

        function makeFilterType(filterType) {
            var html = $('

');
            var a = html.find('a');
            a.text(filterType.name);
            a.data('filterBy', filterType);

            a.on('click', function() {
                $('#filter-type').find('li a').removeClass('selected');
                $(this).addClass('selected');
                currentFilterConfiguration.type = filterType;
                $('.filter-type').text(filterType.name);
                filterData();
            });

            return html;
        }

        /**
         * Checks if object has callback
         *
         * @param object
         * @returns {boolean}
         */
        function hasCallback(object) {
            return object.hasOwnProperty('callback') && typeof object.callback === 'function';
        }

        /**
         * Filters data by filters array
         *
         */
        function filterData() {
            var filterFailed = false;
            var filteredDivs = $('div.real div.appInfo').map(function(idx, element) {
                var show = true;

                if (filters.length > 0) {
                    var filterResults = filters.map(function (filterOption) {
                        if (hasCallback(filterOption)) {
                            try
                            {
                                return filterOption.callback(element, filterOption);
                            }
                            catch(e)
                            {
                                console.error('Invalid input regular expression');
                                filterFailed = true;
                                return true;
                            }
                        } else {
                            console.error('Expected callback to be defined on filterOption');
                        }
                    });

                    var reduceOptions = currentFilterConfiguration.type;
                    show = filterResults.reduce(reduceOptions.reducer, reduceOptions.default);
                }

                if(!filterFailed) {
                    if (!show) {
                        $(this).hide();
                    } else {
                        $(this).show();
                    }
                }
                return show;
            }).toArray();
            if (!filterFailed) {
                var countUnfiltered = filteredDivs.length;
                var countFiltered = filteredDivs.filter(function(show) { return show; }).length;

                countResults.text(countFiltered);

                refreshFilterPanel();
                return true;
            }
            else
            {
                return false;
            }
        }

        /**
         * Redraws filter panel with used filters labels
         *
         */
        function refreshFilterPanel() {
            activeFilters =  $('#active-filters');
            var newActiveFilters = activeFilters.clone(false);
            newActiveFilters.empty();

            filters.forEach(function(filter) {
                newActiveFilters.append(makeFilteredByLabel(filter));
            });

            activeFilters.replaceWith(newActiveFilters);

            if (filters.length === 0) {
                resultsToolbar.addClass('hidden');
            } else {
                resultsToolbar.removeClass('hidden');
            }
        }

        /**
         * Removes filter from filters array
         *
         * @param item
         * @param node
         */
        function removeFilter(item, node) {
            filters = filters.filter(function(currentItem) { return currentItem !== item; });
            node.remove();
            filterData();
        }

        /**
         * Makes new filtered-by label
         * (used in filtered-by toolbar)
         *
         * @param item {object}
         * @returns {jQuery|HTMLElement}
         */
        function makeFilteredByLabel(item) {
            var html = $('
\
                    \

');

            var a = html.find('a');
            html.find('span.label').prepend(item.name + ': ' + item.data.text);
            a.on('click', function() {
                removeFilter(item, html);
            });

            html.data('filter', item);

            return html;
        }

        /**
         * Adds filter to filters array and filters data by it
         *
         * @param value {string}
         * @param option {object}
         */
        function addFilter(value, option, isRegex) {
            var returnValue = true;
            var filter = $.extend({}, option);
            filter.data = { text: value, isRegex: isRegex };
            filters.push(filter);

            if (!filterData())
            {
                filters.pop();
                returnValue = false;
            }

            return returnValue;
        }

        /**
         * Creates HTML element for available filters list
         *
         * @param filterOption {object}
         * @returns {jQuery|HTMLElement}
         */
        function makeFilterOptionListItem(filterOption) {
            var html = $('

');
            var a = html.find('a');
            a.text(filterOption.name);
            a.data('filterBy', filterOption);

            a.on('click', function() {
                filterOptionsList.find('li a').removeClass('selected');
                $(this).addClass('selected');
                currentFilterConfiguration.filterBy = filterOption;
                filterInput.attr("placeholder", filterOption.hint).blur();
                filterByLabel.text(filterOption.name);
            });

            return html;
        }

        initialize();
    }

    /**
     * All sorting related code
     */
    function sorting() {
        var sortDiv = $('#sort');
        var sortBy = $('#sort-by');
        var sortOrder = $('#sort-order');
        var sortIcon = sortOrder.find('span.fa');
        var sortList = sortDiv.find('ul.dropdown-menu');

        var lowerCaseStringComparator = function(a, b) {
            return a.localeCompare(b);
        };

        var storyPointComparator = function(a, b) {
            a = parseInt(a.replace(/[^0-9]/g, ''));
            b = parseInt(b.replace(/[^0-9]/g, ''));
            return parseInt(a) - parseInt(b);
        };

        var sortOptions = [
            { name: 'Name', value: 'name', comparator:  lowerCaseStringComparator },
            { name: 'Story Points', value: 'storypoints', comparator: storyPointComparator }
        ];

        var currentSortConfiguration = {
            sortBy: sortOptions[0],
            order: 1 // +1 ascending, -1 descending
        };

        var sortOrderClasses = {
            ASC: 'fa-sort-alpha-asc',
            DESC: 'fa-sort-alpha-desc'
        };

        function initialize() {
            $('div.real div.appInfo').each(function (idx, el) {
                $(this).data('name', $(this).find('.fileName').text().trim());
                $(this).data('storypoints', $(this).find('.effortPoints.total .points').text().trim());
            });

            sortOptions.forEach(function(option) {
                sortList.append(makeSortListItem(option));
            });

            /** Sorts applications by name */
            sortList.find('li a').first().click();

            /**
             * On click handler for sort order button
             * Switches between ASC/DESC sorting
             */
            sortOrder.on('click', function() {
                var currentClass;
                var newClass;

                if (currentSortConfiguration.order === 1) {
                    currentClass = sortOrderClasses.ASC;
                    newClass = sortOrderClasses.DESC;
                } else {
                    currentClass = sortOrderClasses.DESC;
                    newClass = sortOrderClasses.ASC;
                }

                currentSortConfiguration.order *= -1;

                sortIcon.removeClass(currentClass);
                sortIcon.addClass(newClass);

                sortData();
            });
        }

        function makeSortListItem(sortOption) {
            var html = $('

');
            var a = html.find('a');
            a.text(sortOption.name);
            a.data('sortBy', sortOption);

            a.on('click', function() {
                sortList.find('li a').removeClass('selected');
                $(this).addClass('selected');
                currentSortConfiguration.sortBy = sortOption;
                sortBy.text(sortOption.name);
                sortData();
            });

            return html;
        }

        /**
         * Checks if object has comparator
         *
         * @param object
         * @returns {boolean}
         */
        function hasComparator(object) {
            return object.hasOwnProperty('comparator') && typeof object.comparator === 'function';
        }

        /**
         * Sorts applications by specified criteria
         */
        function sortData() {
            $('div.real div.appInfo').sortElements(function(elementA, elementB) {
                var result = 0;

                var a = $(elementA).data(currentSortConfiguration.sortBy.value);
                var b = $(elementB).data(currentSortConfiguration.sortBy.value);

                if (hasComparator(currentSortConfiguration.sortBy)) {
                    result = currentSortConfiguration.sortBy.comparator(a, b);
                } else {
                    result = a > b ? 1 : -1;
                }

                return result * currentSortConfiguration.order;
            });
        }

        initialize();
    }

    filtering();
    sorting();
});
<|endoftext|>


<commit_before>/*
* jQuery ytShownotes Plugin 0.1.0
* https://github.com/MichaelDanilov/jQuery.ytShownotes
*
* Copyright 2013, Michael Danilov
* http://danilov.me
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
* ./LICENSE
*/

var iframe_api = document.createElement('script');
	iframe_api.type = 'text/javascript';
	iframe_api.src = '//www.youtube.com/iframe_api';
document.getElementsByTagName('head')[0].appendChild(iframe_api);

var constants = {
	ytPlayer: {
		wrapper: 'ytShownotesWrapper',
		place: 'ytShownotesPlayer'
	},
	ytVideo: {
		videoID: '00000000000',
		// startTime: '0',
		// endTime: '60',
		playerWidth: '640',
		playerHeight: '360',
	}
};

var methods = {
	addPlayer:function(options) {
		options = $.extend(true, {}, constants, options);
		$('#' + options.ytPlayer.place).remove();
		$('#' + options.ytPlayer.wrapper).append('

');
		window.yt_player = new YT.Player(
			options.ytPlayer.place,
			{
				height: String(options.ytVideo.playerHeight),
				width: String(options.ytVideo.playerWidth),
				playerVars: {
					'rel': 0,
					'showinfo':	0,
					'hidecontrols': 1
				},
				events: {
					'onReady': function(e) {
						e.target.cueVideoById(
							{
								videoId: String(options.ytVideo.videoID),
								startSeconds: String(options.ytVideo.startTime),
								endSeconds: String(options.ytVideo.endTime)
							}
						);
						e.target.playVideo();
					}
				}
			}
		);
		return this;
	},
	click:function(params) {
		this.unbind('click.ytShownotes');

		return this.bind('click.ytShownotes',function() {
			var data = {
				ytVideo: {
					videoID: $(this).data('ytvideoid'),
					startTime: $(this).data('ytstarttime'),
					endTime: $(this).data('ytendtime'),
				}
			}
			methods.addPlayer($.extend(true, data, params));
		});
	}
};

(function($) {
	$.fn.ytShownotes = function(method) {
		if ( methods[method] ) {
			return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( !method ) {
			return methods.click.apply( this, arguments );
		} else if ( typeof method === 'object') {
			return methods.addPlayer.apply( this, arguments );
		} else {
			$.error( 'Method "' +  method + '" is not exist in jQuery.ytShownotes plugin.' );
		}
	};
}(jQuery));<commit_msg>Add getHTML() method<commit_after>/*
* jQuery ytShownotes Plugin 0.2.0
* https://github.com/MichaelDanilov/jQuery.ytShownotes
*
* Copyright 2013, Michael Danilov
* http://danilov.me
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
* ./LICENSE
*/

var iframe_api = document.createElement('script');
	iframe_api.type = 'text/javascript';
	iframe_api.src = '//www.youtube.com/iframe_api';
document.getElementsByTagName('head')[0].appendChild(iframe_api);

var constants = {
	ytPlayer: {
		wrapper: 'ytShownotesWrapper',
		place: 'ytShownotesPlayer'
	},
	ytVideo: {
		videoID: '00000000000',
		// startTime: '0',
		// endTime: '60',
		playerWidth: '640',
		playerHeight: '360',
		caption: '',
	}
};

var methods = {
	addPlayer:function(options) {
		options = $.extend(true, {}, constants, options);
		$('#' + options.ytPlayer.place).remove();
		$('#' + options.ytPlayer.wrapper).append('

');
		window.yt_player = new YT.Player(
			options.ytPlayer.place,
			{
				height: String(options.ytVideo.playerHeight),
				width: String(options.ytVideo.playerWidth),
				playerVars: {
					'rel': 0,
					'showinfo':	0,
					'hidecontrols': 1
				},
				events: {
					'onReady': function(e) {
						e.target.cueVideoById(
							{
								videoId: String(options.ytVideo.videoID),
								startSeconds: String(options.ytVideo.startTime),
								endSeconds: String(options.ytVideo.endTime)
							}
						);
						e.target.playVideo();
					}
				}
			}
		);
		return this;
	},
	click:function(params) {
		this.unbind('click.ytShownotes');

		return this.bind('click.ytShownotes',function() {
			var data = {
				ytVideo: {
					videoID: $(this).data('ytvideoid'),
					startTime: $(this).data('ytstarttime'),
					endTime: $(this).data('ytendtime'),
				}
			}
			methods.addPlayer($.extend(true, data, params));
		});
	},
	getHTML:function(list, tag = 'div', tagClass = 'ytShownotes', safe = false) {
		if (tag === undefined) {
			tag = 'div';
		};
		if (tagClass === undefined) {
			tagClass = 'ytShownotes';
		} else {
			tagClass = tagClass.replace(/( )+/gi,' ');
		}
		var html = '';
		for (var i = 0; i < list.length; i++) {
			html += '<' + tag + ' class="' + tagClass + '"';
			if (list[i].ytVideo.videoID !== undefined) {
				html += ' data-ytvideoid="' + list[i].ytVideo.videoID + '"';
			};
			if (list[i].ytVideo.startTime !== undefined) {
				html += ' data-ytstarttime="' + list[i].ytVideo.startTime + '"';
			};
			if (list[i].ytVideo.endTime !== undefined) {
				html += ' data-ytendtime="' + list[i].ytVideo.endTime + '"';
			};
			html += '>' + list[i].ytVideo.caption;
			html += '</' + tag + '>\n';
		}
		if (safe) {
			html = html.replace('<', '<', 'gi');
			html = html.replace('>', '>', 'gi');
		};
		return html;
	}
};

(function($) {
	$.fn.ytShownotes = function(method) {
		if ( methods[method] ) {
			return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( !method ) {
			return methods.click.apply( this, arguments );
		} else if ( typeof method === 'object') {
			return methods.addPlayer.apply( this, arguments );
		} else if ( typeof method === 'array') {
			return methods.getHTML.apply( this, arguments );
		} else {
			$.error( 'Method "' +  method + '" is not exist in jQuery.ytShownotes plugin.' );
		}
	};
}(jQuery));<|endoftext|>


<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.
(function($, cloudStack) {
    /**
     * Zone details chart
     */
    cloudStack.uiCustom.systemChart = function(chartID, chartFunc) {
        /**
         * Make view all button
         */
        var viewAllButton = function(args) {
            var $viewAll = $('<div>').addClass('button view-all');
            var $label = $('<span>').addClass('view-all-label').html(args.label ? args.label : _l('label.view.all'));
            var $browser = args.$browser;
            var action = args.action;
            // Launch a list view
            //var $multiple-click=$viewAll.data('multiple-click',false);
            $viewAll.click(function() {
                if ($viewAll.data('multiple-click')) return false;
                //@pranav-handling the multiple clicks by using a flag variable
                $viewAll.data('multiple-click', true);
                $browser.cloudBrowser('addPanel', {
                    title: args.title,
                    maximizeIfSelected: true,
                    complete: function($newPanel) {
                        $viewAll.data('multiple-click', false);
                        action({
                            $panel: $newPanel
                        });
                    }
                });
            });

            $viewAll.append($label);

            return $viewAll;
        };

        /**
         * Chart button action generators
         */
        var actions = {
            /**
             * Makes a list view from given zone sub-section
             */
            listView: function(targetID, context) {
                return function(args) {
                    var $elem = args.$panel;
                    var listView = cloudStack.sections.system.subsections[targetID];

                    $elem.listView($.extend(true, {}, listView, {
                        context: context
                    }));
                };
            },

            providerListView: function(context) {
                return function(args) {
                    var $elem = args.$panel;
                    var listViewArgs = cloudStack.sections.system.naas.providerListView;

                    $elem.listView({
                        context: context,
                        listView: listViewArgs
                    });
                };
            },

            /**
             * Makes details for a given traffic type
             */
            trafficTypeDetails: function(targetID, context) {
                return function(args) {
                    var $elem = args.$panel;
                    var detailViewArgs = cloudStack.sections.system.naas.mainNetworks[targetID].detailView;

                    $elem.detailView($.extend(true, {}, detailViewArgs, {
                        $browser: $('#browser .container'),
                        context: context
                    }));
                };
            }
        };

        /**
         * Chart generators
         */
        var charts = {
            /**
             * Compute tab
             */
            compute: function(args) {
                var $chart = $('<div>');
                var $browser = $('#browser .container');
                var context = args.context;

                // Resource items
                var computeResources = {
                    zone: {
                        label: 'label.zone'
                    },

                    pods: {
                        label: 'label.pods',
                        viewAll: {
                            action: actions.listView('pods', context)
                        }
                    },

                    clusters: {
                        label: 'label.clusters',
                        viewAll: {
                            action: actions.listView('clusters', context)
                        }
                    },

                    hosts: {
                        label: 'label.hosts',
                        viewAll: {
                            action: actions.listView('hosts', context)
                        }
                    },

                    primaryStorage: {
                        label: 'label.primary.storage',
                        viewAll: {
                            action: actions.listView('primary-storage', context)
                        }
                    },

                    ucs: {
                        label: 'label.ucs',
                        viewAll: {
                            action: actions.listView('ucs', context)
                        }
                    },

                    secondaryStorage: {
                        label: 'label.secondary.storage',
                        viewAll: {
                            action: actions.listView('secondary-storage', context)
                        }
                    }
                };

                var $computeResources = $('<ul>').addClass('resources');

                // Make resource items
                $.each(computeResources, function(id, resource) {
                    var $li = $('<li>');
                    var $label = $('<span>').addClass('label');

                    $li.addClass(id);
                    $label.html(_l(resource.label));
                    $label.appendTo($li);

                    // View all
                    if (resource.viewAll) {
                        viewAllButton($.extend(resource.viewAll, {
                            title: _l(resource.label),
                            $browser: $browser,
                            context: context
                        })).appendTo($li);
                    }

                    $li.appendTo($computeResources);
                });

                $chart.append($computeResources);

                return $chart;
            },

            network: function(args) {
                var $chart = $('<div>');
                var $browser = $('#browser .container');
                var $loading = $('<div>').addClass('loading-overlay');
                var context = args.context;
                var networkDataProvider = cloudStack.sections.system.naas.networks.dataProvider;
                var trafficTypeDataProvider = cloudStack.sections.system.naas.trafficTypes.dataProvider;

                $loading.appendTo($chart);

                var renderChart = function(args) {
                    var $targetChart = args.$chart ? args.$chart : $chart;
                    var targetContext = $.extend(true, {}, context, {
                        physicalNetworks: [args.data]
                    });

                    // Get traffic type data
                    trafficTypeDataProvider({
                        context: targetContext,
                        response: {
                            success: function(args) {
                                var $networkChart = $('<div>').addClass('system-network-chart');
                                var $trafficTypes = $('<ul>').addClass('resources traffic-types');

                                $loading.remove();

                                var trafficTypes = {
                                    'public': {
                                        label: _l('label.public'),
                                        configure: {
                                            action: actions.trafficTypeDetails('public', targetContext)
                                        }
                                    },

                                    'guest': {
                                        label: _l('label.guest'),
                                        configure: {
                                            action: actions.trafficTypeDetails('guest', targetContext)
                                        }
                                    },

                                    'management': {
                                        label: _l('label.management'),
                                        configure: {
                                            action: actions.trafficTypeDetails('management', targetContext)
                                        }
                                    },

                                    'storage': {
                                        label: _l('label.storage'),
                                        configure: {
                                            action: actions.trafficTypeDetails('storage', targetContext)
                                        }
                                    },

                                    'providers': {
                                        label: _l('label.network.service.providers'),
                                        ignoreChart: true,
                                        dependsOn: 'guest',
                                        configure: {
                                            action: actions.providerListView(targetContext)
                                        }
                                    }
                                };

                                var validTrafficTypes = $.map(args.data, function(trafficType) {
                                    return trafficType.name.toLowerCase();
                                });

                                // Make traffic type elems
                                $.each(trafficTypes, function(id, trafficType) {
                                    if ($.inArray(id, validTrafficTypes) == -1) { //if it is not a valid traffic type
                                        if (trafficType.dependsOn != null && trafficType.dependsOn.length > 0) { //if it has dependsOn
                                            if ($.inArray(trafficType.dependsOn, validTrafficTypes) == -1) { //if its dependsOn is not a valid traffic type, either
                                                return true; //skip this item
                                            }
                                            //else, if its dependsOn is a valid traffic type, continue to Make list item	(e.g. providers.dependsOn is 'guest')
                                        } else {
                                            return true; //if it doesn't have dependsOn, skip this item
                                        }
                                    }

                                    // Make list item
                                    var $li = $('<li>').addClass(id);
                                    var $label = $('<span>').addClass('label').html(trafficType.label);
                                    var $configureButton = viewAllButton($.extend(trafficType.configure, {
                                        label: _l('label.configure'),
                                        title: trafficType.label,
                                        $browser: $browser,
                                        targetContext: targetContext
                                    }));

                                    $li.append($label, $configureButton);
                                    $li.appendTo($trafficTypes);

                                    // Make chart
                                    if (trafficType.ignoreChart)
                                        return true;

                                    var $targetChartItem = $('<div>').addClass('network-chart-item').addClass(id);
                                    $targetChartItem.appendTo($networkChart);
                                });

                                var $switchIcon = $('<div>').addClass('network-switch-icon').append(
                                    $('<span>').html('L2/L3 switch')
                                );
                                var $circleIcon = $('<div>').addClass('base-circle-icon');

                                $targetChart.append($trafficTypes, $switchIcon, $networkChart, $circleIcon);
                            }
                        }
                    });
                };

                // Get network data
                networkDataProvider({
                    context: context,
                    response: {
                        success: function(args) {
                            var data = args.data;
                            var actionFilter = args.actionFilter;

                            $chart.listView({
                                listView: $.extend(true, {}, cloudStack.sections.system.naas.networks.listView, {
                                    dataProvider: function(args) {
                                        args.response.success({
                                            actionFilter: actionFilter,
                                            data: data
                                        });
                                    },
                                    detailView: {
                                        noCompact: true,
                                        tabs: {
                                            network: {
                                                title: 'Network',
                                                custom: function(args) {
                                                    var $chart = $('<div>').addClass('system-chart network');

                                                    renderChart({
                                                        $chart: $chart,
                                                        data: args.context.physicalNetworks[0]
                                                    });

                                                    return $chart;
                                                }
                                            }
                                        }
                                    }
                                })
                            });
                            $loading.remove();
                        }
                    }
                });

                return $chart;
            },

            resources: function(args) {
                var $chart = $('<div>').addClass('dashboard admin');
                var $chartItems = $('<ul>');
                var $stats = $('<div>').addClass('stats');
                var $container = $('<div>').addClass('dashboard-container head');
                var $top = $('<div>').addClass('top');
                var $title = $('<div>').addClass('title').append($('<span>').html(_l('label.system.wide.capacity')));

                var chartItems = {
                    // The keys are based on the internal type ID associated with each capacity
                    0: {
                        name: _l('label.memory')
                    },
                    1: {
                        name: _l('label.cpu')
                    },
                    2: {
                        name: _l('label.storage')
                    },
                    3: {
                        name: _l('label.primary.allocated')
                    },
                    6: {
                        name: _l('label.secondary.storage')
                    },
                    9: {
                        name: _l('label.local.storage')
                    },
                    4: {
                        name: _l('label.public.ips')
                    },
                    5: {
                        name: _l('label.management.ips')
                    },
                    8: {
                        name: _l('label.direct.ips')
                    },
                    7: {
                        name: _l('label.vlan')
                    },
                    19: {
                        name: _l('GPU')
                    }
                };

                $top.append($title);
                $container.append($top, $stats.append($chartItems));
                $chart.append($container);
                var $loading = $('<div>').addClass('loading-overlay').prependTo($chart);

                cloudStack.sections.system.zoneDashboard({
                    context: args.context,
                    response: {
                        success: function(args) {
                            $loading.remove();
                            $.each(chartItems, function(id, chartItem) {
                                var data = args.data[id] ? args.data[id] : {
                                    used: 0,
                                    total: 0,
                                    percent: 0
                                };
                                var $item = $('<li>');
                                var $name = $('<div>').addClass('name').html(chartItem.name);
                                var $value = $('<div>').addClass('value');
                                var $content = $('<div>').addClass('content').html('Allocated: ');
                                var $allocatedValue = $('<span>').addClass('allocated').html(data.used);
                                var $totalValue = $('<span>').addClass('total').html(data.total);
                                var $chart = $('<div>').addClass('chart');
                                var $chartLine = $('<div>').addClass('chart-line')
                                    .css({
                                        width: '0%'
                                    })
                                    .animate({
                                        width: data.percent + '%'
                                    });
                                var $percent = $('<div>').addClass('percentage');
                                var $percentValue = $('<soan>').addClass('value').html(data.percent);

                                $chartItems.append(
                                    $item.append(
                                        $name,
                                        $value.append(
                                            $content.append(
                                                $allocatedValue,
                                                ' / ',
                                                $totalValue
                                            )
                                        ),
                                        $chart.append($chartLine),
                                        $percent.append($percentValue, '%')
                                    )
                                );
                            });
                        }
                    }
                });

                return $chart;
            }
        };

        return function(args) {
            // Fix zone context naming
            args.context.zones = args.context.physicalResources;

            if (chartFunc == null)
                chartFunc = charts[chartID];

            var $chart = chartFunc(args).addClass('system-chart').addClass(chartID);

            return $chart;
        };
    };
})(jQuery, cloudStack);
<commit_msg>CLOUDSTACK-7838: UI - Update category names on Resources tab of a Zone -Changed wording: "Storage" -> "Primary Storage Used", "CPU" -> "CPU allocated", Memory -> "Memory Allocated"<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.
(function($, cloudStack) {
    /**
     * Zone details chart
     */
    cloudStack.uiCustom.systemChart = function(chartID, chartFunc) {
        /**
         * Make view all button
         */
        var viewAllButton = function(args) {
            var $viewAll = $('<div>').addClass('button view-all');
            var $label = $('<span>').addClass('view-all-label').html(args.label ? args.label : _l('label.view.all'));
            var $browser = args.$browser;
            var action = args.action;
            // Launch a list view
            //var $multiple-click=$viewAll.data('multiple-click',false);
            $viewAll.click(function() {
                if ($viewAll.data('multiple-click')) return false;
                //@pranav-handling the multiple clicks by using a flag variable
                $viewAll.data('multiple-click', true);
                $browser.cloudBrowser('addPanel', {
                    title: args.title,
                    maximizeIfSelected: true,
                    complete: function($newPanel) {
                        $viewAll.data('multiple-click', false);
                        action({
                            $panel: $newPanel
                        });
                    }
                });
            });

            $viewAll.append($label);

            return $viewAll;
        };

        /**
         * Chart button action generators
         */
        var actions = {
            /**
             * Makes a list view from given zone sub-section
             */
            listView: function(targetID, context) {
                return function(args) {
                    var $elem = args.$panel;
                    var listView = cloudStack.sections.system.subsections[targetID];

                    $elem.listView($.extend(true, {}, listView, {
                        context: context
                    }));
                };
            },

            providerListView: function(context) {
                return function(args) {
                    var $elem = args.$panel;
                    var listViewArgs = cloudStack.sections.system.naas.providerListView;

                    $elem.listView({
                        context: context,
                        listView: listViewArgs
                    });
                };
            },

            /**
             * Makes details for a given traffic type
             */
            trafficTypeDetails: function(targetID, context) {
                return function(args) {
                    var $elem = args.$panel;
                    var detailViewArgs = cloudStack.sections.system.naas.mainNetworks[targetID].detailView;

                    $elem.detailView($.extend(true, {}, detailViewArgs, {
                        $browser: $('#browser .container'),
                        context: context
                    }));
                };
            }
        };

        /**
         * Chart generators
         */
        var charts = {
            /**
             * Compute tab
             */
            compute: function(args) {
                var $chart = $('<div>');
                var $browser = $('#browser .container');
                var context = args.context;

                // Resource items
                var computeResources = {
                    zone: {
                        label: 'label.zone'
                    },

                    pods: {
                        label: 'label.pods',
                        viewAll: {
                            action: actions.listView('pods', context)
                        }
                    },

                    clusters: {
                        label: 'label.clusters',
                        viewAll: {
                            action: actions.listView('clusters', context)
                        }
                    },

                    hosts: {
                        label: 'label.hosts',
                        viewAll: {
                            action: actions.listView('hosts', context)
                        }
                    },

                    primaryStorage: {
                        label: 'label.primary.storage',
                        viewAll: {
                            action: actions.listView('primary-storage', context)
                        }
                    },

                    ucs: {
                        label: 'label.ucs',
                        viewAll: {
                            action: actions.listView('ucs', context)
                        }
                    },

                    secondaryStorage: {
                        label: 'label.secondary.storage',
                        viewAll: {
                            action: actions.listView('secondary-storage', context)
                        }
                    }
                };

                var $computeResources = $('<ul>').addClass('resources');

                // Make resource items
                $.each(computeResources, function(id, resource) {
                    var $li = $('<li>');
                    var $label = $('<span>').addClass('label');

                    $li.addClass(id);
                    $label.html(_l(resource.label));
                    $label.appendTo($li);

                    // View all
                    if (resource.viewAll) {
                        viewAllButton($.extend(resource.viewAll, {
                            title: _l(resource.label),
                            $browser: $browser,
                            context: context
                        })).appendTo($li);
                    }

                    $li.appendTo($computeResources);
                });

                $chart.append($computeResources);

                return $chart;
            },

            network: function(args) {
                var $chart = $('<div>');
                var $browser = $('#browser .container');
                var $loading = $('<div>').addClass('loading-overlay');
                var context = args.context;
                var networkDataProvider = cloudStack.sections.system.naas.networks.dataProvider;
                var trafficTypeDataProvider = cloudStack.sections.system.naas.trafficTypes.dataProvider;

                $loading.appendTo($chart);

                var renderChart = function(args) {
                    var $targetChart = args.$chart ? args.$chart : $chart;
                    var targetContext = $.extend(true, {}, context, {
                        physicalNetworks: [args.data]
                    });

                    // Get traffic type data
                    trafficTypeDataProvider({
                        context: targetContext,
                        response: {
                            success: function(args) {
                                var $networkChart = $('<div>').addClass('system-network-chart');
                                var $trafficTypes = $('<ul>').addClass('resources traffic-types');

                                $loading.remove();

                                var trafficTypes = {
                                    'public': {
                                        label: _l('label.public'),
                                        configure: {
                                            action: actions.trafficTypeDetails('public', targetContext)
                                        }
                                    },

                                    'guest': {
                                        label: _l('label.guest'),
                                        configure: {
                                            action: actions.trafficTypeDetails('guest', targetContext)
                                        }
                                    },

                                    'management': {
                                        label: _l('label.management'),
                                        configure: {
                                            action: actions.trafficTypeDetails('management', targetContext)
                                        }
                                    },

                                    'storage': {
                                        label: _l('label.storage'),
                                        configure: {
                                            action: actions.trafficTypeDetails('storage', targetContext)
                                        }
                                    },

                                    'providers': {
                                        label: _l('label.network.service.providers'),
                                        ignoreChart: true,
                                        dependsOn: 'guest',
                                        configure: {
                                            action: actions.providerListView(targetContext)
                                        }
                                    }
                                };

                                var validTrafficTypes = $.map(args.data, function(trafficType) {
                                    return trafficType.name.toLowerCase();
                                });

                                // Make traffic type elems
                                $.each(trafficTypes, function(id, trafficType) {
                                    if ($.inArray(id, validTrafficTypes) == -1) { //if it is not a valid traffic type
                                        if (trafficType.dependsOn != null && trafficType.dependsOn.length > 0) { //if it has dependsOn
                                            if ($.inArray(trafficType.dependsOn, validTrafficTypes) == -1) { //if its dependsOn is not a valid traffic type, either
                                                return true; //skip this item
                                            }
                                            //else, if its dependsOn is a valid traffic type, continue to Make list item	(e.g. providers.dependsOn is 'guest')
                                        } else {
                                            return true; //if it doesn't have dependsOn, skip this item
                                        }
                                    }

                                    // Make list item
                                    var $li = $('<li>').addClass(id);
                                    var $label = $('<span>').addClass('label').html(trafficType.label);
                                    var $configureButton = viewAllButton($.extend(trafficType.configure, {
                                        label: _l('label.configure'),
                                        title: trafficType.label,
                                        $browser: $browser,
                                        targetContext: targetContext
                                    }));

                                    $li.append($label, $configureButton);
                                    $li.appendTo($trafficTypes);

                                    // Make chart
                                    if (trafficType.ignoreChart)
                                        return true;

                                    var $targetChartItem = $('<div>').addClass('network-chart-item').addClass(id);
                                    $targetChartItem.appendTo($networkChart);
                                });

                                var $switchIcon = $('<div>').addClass('network-switch-icon').append(
                                    $('<span>').html('L2/L3 switch')
                                );
                                var $circleIcon = $('<div>').addClass('base-circle-icon');

                                $targetChart.append($trafficTypes, $switchIcon, $networkChart, $circleIcon);
                            }
                        }
                    });
                };

                // Get network data
                networkDataProvider({
                    context: context,
                    response: {
                        success: function(args) {
                            var data = args.data;
                            var actionFilter = args.actionFilter;

                            $chart.listView({
                                listView: $.extend(true, {}, cloudStack.sections.system.naas.networks.listView, {
                                    dataProvider: function(args) {
                                        args.response.success({
                                            actionFilter: actionFilter,
                                            data: data
                                        });
                                    },
                                    detailView: {
                                        noCompact: true,
                                        tabs: {
                                            network: {
                                                title: 'Network',
                                                custom: function(args) {
                                                    var $chart = $('<div>').addClass('system-chart network');

                                                    renderChart({
                                                        $chart: $chart,
                                                        data: args.context.physicalNetworks[0]
                                                    });

                                                    return $chart;
                                                }
                                            }
                                        }
                                    }
                                })
                            });
                            $loading.remove();
                        }
                    }
                });

                return $chart;
            },

            resources: function(args) {
                var $chart = $('<div>').addClass('dashboard admin');
                var $chartItems = $('<ul>');
                var $stats = $('<div>').addClass('stats');
                var $container = $('<div>').addClass('dashboard-container head');
                var $top = $('<div>').addClass('top');
                var $title = $('<div>').addClass('title').append($('<span>').html(_l('label.system.wide.capacity')));

                var chartItems = {
                    // The keys are based on the internal type ID associated with each capacity
                    0: {
                        name: _l('label.memory.allocated')
                    },
                    1: {
                        name: _l('label.cpu.allocated')
                    },
                    2: {
                        name: _l('label.primary.used')
                    },
                    3: {
                        name: _l('label.primary.allocated')
                    },
                    6: {
                        name: _l('label.secondary.storage')
                    },
                    9: {
                        name: _l('label.local.storage')
                    },
                    4: {
                        name: _l('label.public.ips')
                    },
                    5: {
                        name: _l('label.management.ips')
                    },
                    8: {
                        name: _l('label.direct.ips')
                    },
                    7: {
                        name: _l('label.vlan')
                    },
                    19: {
                        name: _l('GPU')
                    }
                };

                $top.append($title);
                $container.append($top, $stats.append($chartItems));
                $chart.append($container);
                var $loading = $('<div>').addClass('loading-overlay').prependTo($chart);

                cloudStack.sections.system.zoneDashboard({
                    context: args.context,
                    response: {
                        success: function(args) {
                            $loading.remove();
                            $.each(chartItems, function(id, chartItem) {
                                var data = args.data[id] ? args.data[id] : {
                                    used: 0,
                                    total: 0,
                                    percent: 0
                                };
                                var $item = $('<li>');
                                var $name = $('<div>').addClass('name').html(chartItem.name);
                                var $value = $('<div>').addClass('value');
                                var $content = $('<div>').addClass('content').html('Allocated: ');
                                var $allocatedValue = $('<span>').addClass('allocated').html(data.used);
                                var $totalValue = $('<span>').addClass('total').html(data.total);
                                var $chart = $('<div>').addClass('chart');
                                var $chartLine = $('<div>').addClass('chart-line')
                                    .css({
                                        width: '0%'
                                    })
                                    .animate({
                                        width: data.percent + '%'
                                    });
                                var $percent = $('<div>').addClass('percentage');
                                var $percentValue = $('<soan>').addClass('value').html(data.percent);

                                $chartItems.append(
                                    $item.append(
                                        $name,
                                        $value.append(
                                            $content.append(
                                                $allocatedValue,
                                                ' / ',
                                                $totalValue
                                            )
                                        ),
                                        $chart.append($chartLine),
                                        $percent.append($percentValue, '%')
                                    )
                                );
                            });
                        }
                    }
                });

                return $chart;
            }
        };

        return function(args) {
            // Fix zone context naming
            args.context.zones = args.context.physicalResources;

            if (chartFunc == null)
                chartFunc = charts[chartID];

            var $chart = chartFunc(args).addClass('system-chart').addClass(chartID);

            return $chart;
        };
    };
})(jQuery, cloudStack);
<|endoftext|>


<commit_before>import Component from 'ember-component';
import Ember from 'ember';
import injectService from 'ember-service/inject';
import {task, timeout} from 'ember-concurrency';

const {testing} = Ember;
const INTERVAL = testing ? 20 : 2000;

export default Component.extend({
    ajax: injectService(),
    ghostPaths: injectService(),

    count: '',

    _poll: task(function* () {
        let url = this.get('ghostPaths.count');
        let pattern = /(-?\d+)(\d{3})/;

        try {
            let data = yield this.get('ajax').request(url);
            let count = data.count.toString();

            while (pattern.test(count)) {
                count = count.replace(pattern, '$1,$2');
            }

            this.set('count', count);

            if (!testing) {
                yield timeout(INTERVAL);
                this.get('_poll').perform();
            }
        } catch (e) {
            // no-op - we don't want to create noise for a failed download count
        }
    }),

    didInsertElement() {
        this.get('_poll').perform();
    }
});
<commit_msg>🎨 fix download count position on setup/one (#801)<commit_after>import Component from 'ember-component';
import Ember from 'ember';
import injectService from 'ember-service/inject';
import {task, timeout} from 'ember-concurrency';

const {testing} = Ember;
const INTERVAL = testing ? 20 : 2000;

export default Component.extend({
    ajax: injectService(),
    ghostPaths: injectService(),

    tagName: '',
    count: '',

    _poll: task(function* () {
        let url = this.get('ghostPaths.count');
        let pattern = /(-?\d+)(\d{3})/;

        try {
            let data = yield this.get('ajax').request(url);
            let count = data.count.toString();

            while (pattern.test(count)) {
                count = count.replace(pattern, '$1,$2');
            }

            this.set('count', count);

            if (!testing) {
                yield timeout(INTERVAL);
                this.get('_poll').perform();
            }
        } catch (e) {
            // no-op - we don't want to create noise for a failed download count
        }
    }),

    didInsertElement() {
        this.get('_poll').perform();
    }
});
<|endoftext|>


<commit_before>/**
 * The module defining {@link Filters}.
 *
 * @class Filters
 * @classdesc The logic behind the filters.
 *
 * @module model/filter/filters
 */
define([
    'underscore',
    'backbone',

    'i18n'
], function (_, Backbone, i18n) {
    'use strict';

    /**
     * The filter key to enable all teas.
     * @type {string}
     * @constant
     * @default
     */
    var FILTER_KEYWORD_TEAS = 'teas';

    /**
     * The filter key to enable auto-time.
     * @type {string}
     * @constant
     * @default
     */
    var FILTER_KEYWORD_TIME = 'autoTime';

    var MORNING_START = 5,
        MORNING_END = 11,
        DAYTIME_START = 10,
        DAYTIME_END = 20,
        EVENING_START = 18,
        EVENING_END = 2;
    var AUTO_TIME_RANGE = Object.freeze({
        morning: [MORNING_START, MORNING_END],
        daytime: [DAYTIME_START, DAYTIME_END],
        evening: [EVENING_START, EVENING_END]
    });

    var _isInTimeRange = function (range) {
        if (!_.has(AUTO_TIME_RANGE, range)) {
            return false;
        }

        var min = AUTO_TIME_RANGE[range][0],
            max = AUTO_TIME_RANGE[range][1],
            hour = new Date().getHours();
        return min <= max ? min <= hour && hour < max : min <= hour || hour < max;
    };

    var _testRegexpAgainstModelFields = function (rgx, model) {
        for (var i = 2; i < arguments.length; i++) {
            var fieldValue = model.get(arguments[i]);
            if (_.isString(fieldValue) && rgx.test(fieldValue)) {
                return true;
            } else if (_.isArray(fieldValue) && _.find(fieldValue, function (item) {
                    return rgx.test(item);
                })) {
                return true;
            }
        }
        return false;
    };

    var FilterSet = Backbone.Collection.extend({
        model: Backbone.Model.extend({
            idAttribute: 'key'
        })
    });

    // eslint-disable-next-line no-inline-comments
    return /** @alias module:model/filter/filters */ Backbone.Model.extend(
        /** @lends Filters.prototype */
        {
            defaults: {
                text: ''
            },

            splitText: [],

            /**
             * Creates new filters.
             *
             * @param {{bases: Array.<String>, moments: Array.<String>, autoTime: boolean}} [options] the options for
             * the filters
             * @constructs
             */
            initialize: function (options) {
                var opt = options || {};

                this._initBasesFilters(opt.bases);
                this._initMomentsFilters(opt.moments, opt[FILTER_KEYWORD_TIME]);

                this.on('change:text', function (model, text) {
                    this.splitText = (text || '').trim().split(/\s+/);
                }, this);
            },

            _initBasesFilters: function (bases) {
                var allowAllTeas = _.contains(bases, FILTER_KEYWORD_TEAS);
                this.set('bases', new FilterSet(
                    _.chain(i18n.basis)
                        .keys()
                        .map(function (basis) {
                            return {
                                key: basis,
                                active: Boolean(!bases || allowAllTeas && (/^tea-/).test(basis)
                                    || _.contains(bases, basis))
                            };
                        })
                        .value()
                ));
            },

            _initMomentsFilters: function (moments, autoTime) {
                var isActive = !moments && !autoTime ? function () {
                    return true;
                } : function (moment) {
                    return Boolean(_.contains(moments, moment)
                        || autoTime && _isInTimeRange(moment));
                };

                this.set('moments', new FilterSet(
                    _.chain(i18n.moment)
                        .keys()
                        .map(function (moment) {
                            return {
                                key: moment,
                                active: isActive(moment)
                            };
                        })
                        .value()
                ));
            },

            /**
             * Tests whether a beverage matches the filters.
             * @param {Beverage} beverage the beverage to test
             * @return {boolean} true if the beverage matches all the filter criteria, false
             * otherwise
             */
            match: function (beverage) {
                return this._isBasisActive(beverage) && this._isMomentActive(beverage) && this._containsText(beverage);
            },

            _isBasisActive: function (beverage) {
                var filter = this.get('bases').get(beverage.get('basis'));
                return filter ? filter.get('active') : true;
            },

            _isMomentActive: function (beverage) {
                var times = beverage.get('time'),
                    timeFilters = this.get('moments');

                return _.isObject(times)
                    ? Boolean(_.chain(times)
                    .keys()
                    .find(function (time) {
                        var active = times[time];
                        if (_.isUndefined(active) || _.isNull(active)) {
                            return timeFilters.get('unknown').get('active');
                        } else if (active) {
                            var filter = timeFilters.get(time);
                            return filter && filter.get('active');
                        }
                        return false;
                    })
                    .value())
                    : timeFilters.get('unknown').get('active');
            },

            _containsText: function (beverage) {
                if (this.get('text')) {
                    return !_.find(this.splitText, function (text) {
                        return !_testRegexpAgainstModelFields(
                            new RegExp(text, 'i'), beverage,
                            'name', 'brand', 'note', 'benefits', 'ingredients');
                    });
                }
                return true;
            }
        }
    );
});
<commit_msg>Remove Sonar tech debt<commit_after>/**
 * The module defining {@link Filters}.
 *
 * @class Filters
 * @classdesc The logic behind the filters.
 *
 * @module model/filter/filters
 */
define([
    'underscore',
    'backbone',

    'i18n'
], function (_, Backbone, i18n) {
    'use strict';

    /**
     * The filter key to enable all teas.
     * @type {string}
     * @constant
     * @default
     */
    var FILTER_KEYWORD_TEAS = 'teas';

    /**
     * The filter key to enable auto-time.
     * @type {string}
     * @constant
     * @default
     */
    var FILTER_KEYWORD_TIME = 'autoTime';

    var MORNING_START = 5,
        MORNING_END = 11,
        DAYTIME_START = 10,
        DAYTIME_END = 20,
        EVENING_START = 18,
        EVENING_END = 2;
    var AUTO_TIME_RANGE = Object.freeze({
        morning: [MORNING_START, MORNING_END],
        daytime: [DAYTIME_START, DAYTIME_END],
        evening: [EVENING_START, EVENING_END]
    });

    var _isInTimeRange = function (range) {
        if (!_.has(AUTO_TIME_RANGE, range)) {
            return false;
        }

        var min = AUTO_TIME_RANGE[range][0],
            max = AUTO_TIME_RANGE[range][1],
            hour = new Date().getHours();
        return min <= max ? min <= hour && hour < max : min <= hour || hour < max;
    };

    var _testRegexpAgainstModelFields = function (rgx, model) {
        var testString = function(str) {
            return rgx.test(str);
        };
        for (var i = 2; i < arguments.length; i++) {
            var fieldValue = model.get(arguments[i]);
            if (_.isString(fieldValue) && testString(fieldValue)
                || _.isArray(fieldValue) && _.find(fieldValue, testString)) {
                return true;
            }
        }
        return false;
    };

    var FilterSet = Backbone.Collection.extend({
        model: Backbone.Model.extend({
            idAttribute: 'key'
        })
    });

    // eslint-disable-next-line no-inline-comments
    return /** @alias module:model/filter/filters */ Backbone.Model.extend(
        /** @lends Filters.prototype */
        {
            defaults: {
                text: ''
            },

            splitText: [],

            /**
             * Creates new filters.
             *
             * @param {{bases: Array.<String>, moments: Array.<String>, autoTime: boolean}} [options] the options for
             * the filters
             * @constructs
             */
            initialize: function (options) {
                var opt = options || {};

                this._initBasesFilters(opt.bases);
                this._initMomentsFilters(opt.moments, opt[FILTER_KEYWORD_TIME]);

                this.on('change:text', function (model, text) {
                    this.splitText = (text || '').trim().split(/\s+/);
                }, this);
            },

            _initBasesFilters: function (bases) {
                var allowAllTeas = _.contains(bases, FILTER_KEYWORD_TEAS);
                this.set('bases', new FilterSet(
                    _.chain(i18n.basis)
                        .keys()
                        .map(function (basis) {
                            return {
                                key: basis,
                                active: Boolean(!bases || allowAllTeas && (/^tea-/).test(basis)
                                    || _.contains(bases, basis))
                            };
                        })
                        .value()
                ));
            },

            _initMomentsFilters: function (moments, autoTime) {
                var isActive = !moments && !autoTime ? function () {
                    return true;
                } : function (moment) {
                    return Boolean(_.contains(moments, moment)
                        || autoTime && _isInTimeRange(moment));
                };

                this.set('moments', new FilterSet(
                    _.chain(i18n.moment)
                        .keys()
                        .map(function (moment) {
                            return {
                                key: moment,
                                active: isActive(moment)
                            };
                        })
                        .value()
                ));
            },

            /**
             * Tests whether a beverage matches the filters.
             * @param {Beverage} beverage the beverage to test
             * @return {boolean} true if the beverage matches all the filter criteria, false
             * otherwise
             */
            match: function (beverage) {
                return this._isBasisActive(beverage) && this._isMomentActive(beverage) && this._containsText(beverage);
            },

            _isBasisActive: function (beverage) {
                var filter = this.get('bases').get(beverage.get('basis'));
                return filter ? filter.get('active') : true;
            },

            _isMomentActive: function (beverage) {
                var times = beverage.get('time'),
                    timeFilters = this.get('moments');

                return _.isObject(times)
                    ? Boolean(_.chain(times)
                    .keys()
                    .find(function (time) {
                        var active = times[time];
                        if (_.isUndefined(active) || _.isNull(active)) {
                            return timeFilters.get('unknown').get('active');
                        } else if (active) {
                            var filter = timeFilters.get(time);
                            return filter && filter.get('active');
                        }
                        return false;
                    })
                    .value())
                    : timeFilters.get('unknown').get('active');
            },

            _containsText: function (beverage) {
                if (this.get('text')) {
                    return !_.find(this.splitText, function (text) {
                        return !_testRegexpAgainstModelFields(
                            new RegExp(text, 'i'), beverage,
                            'name', 'brand', 'note', 'benefits', 'ingredients');
                    });
                }
                return true;
            }
        }
    );
});
<|endoftext|>