<commit_before>$.fn.Selector = function(options) {
    var self = {};
    var selectorMidLine, sIndex, arrows, currentTop, margin = {},
        allowSetSelected = true;
    var selector = $(this);
    var initialized = false;
    var settings = $.extend({
        clickToOpen: false,
        setActiveOnClick: true,
        checkedClass: 'checked',
        setOrder: true,
        transitionTime: 300,
        valueAttr: 'data-value',
        arrows: 300,
        onSelectorChange: false,
        onActiveChange: false,
        onCheckedChange: false,
        onGoTo: false
    }, options);

    if(options.onMobile){
      var maxScreen;
      if(options.mobileScreen){
        maxScreen = options.mobileScreen;
      } else { maxScreen = 750; }
      if($(window).outerWidth() <= maxScreen){
        settings = $.extend({},settings,options.onMobile);
      }
    }

    return this.each(function(i, el) {

        var init = function(callback) {
            if (settings.init) {
                var initInterval = setInterval(function() {
                    if (initialized) {
                        clearInterval(initInterval);
                    } else {
                        initialize();
                    }
                }, 1000);
            }

            if (settings.arrows) {
                arrows = $('<div>').addClass('selector-arrows');
                arrows.append($('<a>').addClass('selector-arrows-up').on('click', function() {
                    goToOption('up');
                }));
                arrows.append($('<a>').addClass('selector-arrows-down').on('click', function() {
                    goToOption('down');
                }));
                selector.prepend(arrows);
            }

            // Click Actions

            if (!settings.clickToOpen) {
                selector.on('click', 'li', function(e) {
                    e.preventDefault();
                    scrollToSelected($(this));
                });
            }

            if (settings.setActiveOnClick) {
                selector.on('click', 'li a', function(e) {
                    var clickedElement = $(this);
                    setActive(selector, $(this).parent());
                    scrollToSelected($(this).parent());
                    if (!settings.clickToOpen) {
                        e.preventDefault();
                    }
                    selector.find('.active').each(function() {
                        $(this).removeClass('active');
                    });
                    $(this).parent().addClass('active');
                });
            }

            // On Active change
            selector.on('activeChange', function() {
                if (isFunction(settings.onActiveChange)) {
                    settings.onActiveChange();
                }
            });
            // On Checked change
            selector.on('checkedChange', function() {
                if (isFunction(settings.onCheckedChange)) {
                    settings.onCheckedChange();
                }
            });
            // On Checked change
            selector.on('selectorChange', function() {
                if (isFunction(settings.onSelectorChange)) {
                    settings.onSelectorChange();
                }
            });
            // On Checked change
            selector.on('selectorChange', function() {
                if (isFunction(settings.onSelectorChange)) {
                    settings.onSelectorChange();
                }
            });

            // When leaving the Selector
            selector.mouseleave(function() {
                setTimeout(function() {
                    scrollToSelected(selector.find('li.' + settings.checkedClass));
                }, 200);
            });

            // When scrolling into Selector
            selector.scroll(function() {
                setSelected(selector);
                currentTop = selector.scrollTop();
                if (settings.arrows) {
                    keepArrowsInPlace();
                }
            });
            if (callback && typeof(callback) === "function") {
                callback();
            }
        };

        // Check if var is function
        var isFunction = function isFunction(functionToCheck) {
            var getType = {};
            return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
        };
        var initialize = function initialize() {
            if (!initialized) {
                initSelector(selector);
                scrollToSelected(selector.find('li.' + settings.activeClass));
                if (settings.arrows) {
                    keepArrowsInPlace();
                }
                console.log('Selector: #' + $(this).attr('id') + ' initialized');
                initialized = true;
            }
        };

        // Create Functions

        var goToUrl = function goToUrl(el) {
            setTimeout(function() {
                if (el.attr('href').length() > 0) {
                    window.location.href = el.attr('href');
                } else if (el.attr('data-url').length > 0) {
                    window.location.href = el.attr('data-url');
                }
            }, settings.transitionTime);
        };

        var scrollToSelected = function scrollToSelected(el) {
            var scrollToIndex = el.index();
            var scrollToPx = scrollToIndex * el.outerHeight();
            selector.animate({
                scrollTop: scrollToPx
            }, settings.transitionTime);
            //  setSelected(selector);
        };

        var initSelector = function initSelector(selector) {
            selectorMidLine = selector.outerHeight() / 2;
            var checked = selector.find('li.' + settings.checkedClass);
            setActive(selector, checked);
            setChecked(selector, checked);

            margin.top = (selectorMidLine - (checked.outerHeight() / 2));
            margin.bottom = margin.top;
            if (settings.arrows) {
                //    margin.top = margin.top - arrows.outerHeight();
            }
            selector.find('ul').css({
                'margin-top': margin.top,
                'margin-bottom': margin.bottom
            });
            initialized = true;
        };

        var setSelected = function setSelected(selector) {
            selector.find('li').each(function() {
                if ($(this).position().top < selectorMidLine && ($(this).position().top + $(this).outerHeight()) > selectorMidLine && !$(this).hasClass('checked')) {
                    sIndex = $(this).index();
                    selector.find('li').each(function() {
                        $(this).removeClass('checked').attr('data-order', sIndex - $(this).index());
                    });
                    $(this).addClass('checked');
                    setChecked(selector, $(this));
                }
            });
        };

        var setChecked = function setChecked(selector, el) {
            selector.attr('data-checked', el.attr(settings.valueAttr)).triggerAll('checkedChange selectorChange');
        };
        var setActive = function setActive(selector, el) {
            selector.attr('data-active', el.attr(settings.valueAttr)).triggerAll('activeChange selectorChange');
        };

        var keepArrowsInPlace = function keepArrowsInPlace(selector) {
            arrows.css('top', selectorMidLine + currentTop);
        };

        var goToOption = function goToOption(goto) {
            var goIndex;
            if (goto === 'up') {
                goIndex = selector.find('li.' + settings.checkedClass).index() - 1;
            } else if (goto === 'down') {
                goIndex = selector.find('li.' + settings.checkedClass).index() + 1;
            } else {
                goIndex = goto;
            }
            scrollToSelected(selector.find('li:eq(' + goIndex + ')'));
        };

        var underline = function() {
            $(el).addClass("underline");
        };

        var goto = function(callback) {
            scrollToSelected($(settings.goto));
            if (isFunction(callback)) {
                callback();
            }
        };

        if (settings.init) {
            init();
        }
        if (settings.goto) {
            goto(settings.goto);
        }
    });

};

(function($) {
    $.fn.extend({
        triggerAll: function(events, params) {
            var el = this,
                i, evts = events.split(' ');
            for (i = 0; i < evts.length; i += 1) {
                el.trigger(evts[i], params);
            }
            return el;
        }
    });
})(jQuery);
<commit_msg>small fix so init doesn’t reinit selector<commit_after>$.fn.Selector = function(options) {
    var self = {};
    var selectorMidLine, sIndex, arrows, currentTop, margin = {},
        allowSetSelected = true;
    var selector = $(this);
    var initialized = false;
    var settings = $.extend({
        clickToOpen: false,
        setActiveOnClick: true,
        checkedClass: 'checked',
        setOrder: true,
        transitionTime: 300,
        valueAttr: 'data-value',
        arrows: 300,
        onSelectorChange: false,
        onActiveChange: false,
        onCheckedChange: false,
        onGoTo: false
    }, options);

    if(options.onMobile){
      var maxScreen;
      if(options.mobileScreen){
        maxScreen = options.mobileScreen;
      } else { maxScreen = 750; }
      if($(window).outerWidth() <= maxScreen){
        settings = $.extend({},settings,options.onMobile);
      }
    }

    return this.each(function(i, el) {

        var init = function(callback) {
            if (settings.init) {
                var initInterval = setInterval(function() {
                    if (initialized) {
                        clearInterval(initInterval);
                    } else {
                        initialize();
                    }
                }, 1000);
            }

            if (settings.arrows) {
                arrows = $('<div>').addClass('selector-arrows');
                arrows.append($('<a>').addClass('selector-arrows-up').on('click', function() {
                    goToOption('up');
                }));
                arrows.append($('<a>').addClass('selector-arrows-down').on('click', function() {
                    goToOption('down');
                }));
                selector.prepend(arrows);
            }

            // Click Actions

            if (!settings.clickToOpen) {
                selector.on('click', 'li', function(e) {
                    e.preventDefault();
                    scrollToSelected($(this));
                });
            }

            if (settings.setActiveOnClick) {
                selector.on('click', 'li a', function(e) {
                    var clickedElement = $(this);
                    setActive(selector, $(this).parent());
                    scrollToSelected($(this).parent());
                    if (!settings.clickToOpen) {
                        e.preventDefault();
                    }
                    selector.find('.active').each(function() {
                        $(this).removeClass('active');
                    });
                    $(this).parent().addClass('active');
                });
            }

            // On Active change
            selector.on('activeChange', function() {
                if (isFunction(settings.onActiveChange)) {
                    settings.onActiveChange();
                }
            });
            // On Checked change
            selector.on('checkedChange', function() {
                if (isFunction(settings.onCheckedChange)) {
                    settings.onCheckedChange();
                }
            });
            // On Checked change
            selector.on('selectorChange', function() {
                if (isFunction(settings.onSelectorChange)) {
                    settings.onSelectorChange();
                }
            });
            // On Checked change
            selector.on('selectorChange', function() {
                if (isFunction(settings.onSelectorChange)) {
                    settings.onSelectorChange();
                }
            });

            // When leaving the Selector
            selector.mouseleave(function() {
                setTimeout(function() {
                    scrollToSelected(selector.find('li.' + settings.checkedClass));
                }, 200);
            });

            // When scrolling into Selector
            selector.scroll(function() {
                setSelected(selector);
                currentTop = selector.scrollTop();
                if (settings.arrows) {
                    keepArrowsInPlace();
                }
            });
            if (callback && typeof(callback) === "function") {
                callback();
            }
        };

        // Check if var is function
        var isFunction = function isFunction(functionToCheck) {
            var getType = {};
            return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
        };
        var initialize = function initialize() {
            if (!initialized) {
                initSelector(selector);
                if(settings.activeClass){
                  scrollToSelected(selector.find('li.' + settings.activeClass));
                }
                if (settings.arrows) {
                    keepArrowsInPlace();
                }
                console.log('Selector: #' + $(this).attr('id') + ' initialized');
                initialized = true;
            }
        };

        // Create Functions

        var goToUrl = function goToUrl(el) {
            setTimeout(function() {
                if (el.attr('href').length() > 0) {
                    window.location.href = el.attr('href');
                } else if (el.attr('data-url').length > 0) {
                    window.location.href = el.attr('data-url');
                }
            }, settings.transitionTime);
        };

        var scrollToSelected = function scrollToSelected(el) {
            var scrollToIndex = el.index();
            var scrollToPx = scrollToIndex * el.outerHeight();
            selector.animate({
                scrollTop: scrollToPx
            }, settings.transitionTime);
            //  setSelected(selector);
        };

        var initSelector = function initSelector(selector) {
            selectorMidLine = selector.outerHeight() / 2;
            var checked = selector.find('li.' + settings.checkedClass);
            setActive(selector, checked);
            setChecked(selector, checked);

            margin.top = (selectorMidLine - (checked.outerHeight() / 2));
            margin.bottom = margin.top;
            if (settings.arrows) {
                //    margin.top = margin.top - arrows.outerHeight();
            }
            selector.find('ul').css({
                'margin-top': margin.top,
                'margin-bottom': margin.bottom
            });
            initialized = true;
        };

        var setSelected = function setSelected(selector) {
            selector.find('li').each(function() {
                if ($(this).position().top < selectorMidLine && ($(this).position().top + $(this).outerHeight()) > selectorMidLine && !$(this).hasClass('checked')) {
                    sIndex = $(this).index();
                    selector.find('li').each(function() {
                        $(this).removeClass('checked').attr('data-order', sIndex - $(this).index());
                    });
                    $(this).addClass('checked');
                    setChecked(selector, $(this));
                }
            });
        };

        var setChecked = function setChecked(selector, el) {
            selector.attr('data-checked', el.attr(settings.valueAttr)).triggerAll('checkedChange selectorChange');
        };
        var setActive = function setActive(selector, el) {
            selector.attr('data-active', el.attr(settings.valueAttr)).triggerAll('activeChange selectorChange');
        };

        var keepArrowsInPlace = function keepArrowsInPlace(selector) {
            arrows.css('top', selectorMidLine + currentTop);
        };

        var goToOption = function goToOption(goto) {
            var goIndex;
            if (goto === 'up') {
                goIndex = selector.find('li.' + settings.checkedClass).index() - 1;
            } else if (goto === 'down') {
                goIndex = selector.find('li.' + settings.checkedClass).index() + 1;
            } else {
                goIndex = goto;
            }
            scrollToSelected(selector.find('li:eq(' + goIndex + ')'));
        };

        var underline = function() {
            $(el).addClass("underline");
        };

        var goto = function(callback) {
            scrollToSelected($(settings.goto));
            if (isFunction(callback)) {
                callback();
            }
        };

        if (settings.init) {
            init();
        }
        if (settings.goto) {
            goto(settings.goto);
        }
    });

};

(function($) {
    $.fn.extend({
        triggerAll: function(events, params) {
            var el = this,
                i, evts = events.split(' ');
            for (i = 0; i < evts.length; i += 1) {
                el.trigger(evts[i], params);
            }
            return el;
        }
    });
})(jQuery);
<|endoftext|>


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

  var tableDefaultSelector = '.ocenyZwykle-table';
  var tableDetailsSelector = '.ocenySzczegoly-table';
  var tableHeaderSelector = tableDefaultSelector + ' > thead > tr';
  var subjetsSelector = 'tbody tr';
  var ratingsSelector = 'td.break-word span';
  var gradesSelector = 'tbody tr'
  var summaryContainerId = 'whole-avarage';

  (function(){
    if(document.getElementById(summaryContainerId)) {
      return;
    }

    if (document.querySelector(tableDefaultSelector)) {
      var subjects = document.querySelectorAll(subjetsSelector);
      var averages = [];

      for (var i = 0, max = subjects.length; i < max; i++) {
        var avarage = getGradesAverage(subjects[i]);
        putGradesAverageCellToSubjectRow(subjects[i], avarage);
        averages.push(avarage);
      }

      addWholeGradesAverageToTableFoot(averages);
      calculateAndAddRealWholeGradesAverageToTableFoot();

    } else if(document.querySelector(tableDetailsSelector)) {
      var grades = document.querySelectorAll(gradesSelector);

      var weightedAverage = calculateAverageFromGrades(grades);
      addWeightedAverageToTableFoot(weightedAverage);
    }
  })();

  function calculateAverageFromGrades(grades) {
    var counter = 0;
    var denominator = 0;

    for (let i = 0; i < grades.length; i++) {
      let grade = getGradeValue(grades[i]);

      if (grade.value) {
        counter += grade.value * grade.weight;
        denominator += grade.weight;
      }
    }

    if (0 == denominator) {
      return null;
    }

    return counter / denominator;
  }

  function getGradeValue(gradeRow) {
    let value = gradeRow.querySelector('td:nth-child(2)').textContent;
    let weight = gradeRow.querySelector('td:nth-child(4)').textContent;

    value = getRatingValue(value);
    weight = parseFloat(weight.replace(/,/, '.'));

    if (value) {
      return {
        "value": value,
        "weight": weight
      };
    }

    return false;
  }

  function getGradesAverage(row) {
    var grades = row.querySelectorAll(ratingsSelector);

    var counter = 0;
    var denominator = 0;

    for (var i = 0, max = grades.length; i < max; i++) {
      var value = getRatingValue(grades[i].innerHTML);
      var weight = getWeightOfGradeFromAlt(grades[i]);

      if (value) {
        counter += value * weight;
        denominator += weight;
      }
    }

    if (0 == denominator) {
      return null;
    }

    return counter / denominator;
  }

  function putGradesAverageCellToSubjectRow(row, avarage) {
    if (null == avarage) {
      var text = '-';
      avarage = '-';
    } else {
      var text = Math.round(avarage * 100) / 100;
    }

    var newNode = document.createElement('td');
    newNode.textContent = text;
    newNode.title = avarage;
    row.appendChild(newNode)
  }

  /**
   * Extract weight of grade from span alt.
   * @param  {Object} span Span
   * @return {Number} Grade weight
   */
  function getWeightOfGradeFromAlt(span) {
    var alt = span.getAttribute('alt');
    var weight = alt.match(/[0-9]{1,2},[0-9]{2}/)[0];
    var weight = parseFloat(weight.replace(/,/, '.'));

    return weight;
  }

  /**
   * Check is rating value valid.
   * @param  {*}  rating Rating value
   * @return {Boolean}
   */
  function isRatingValueValid(rating) {
    return /^(\+|\-)?[0-6](\+|\-)?$/.test(rating);
  }

  /**
   * Get real rating value.
   * @param  {*} rating Rating
   * @return {Number}
   */
  function getRatingValue(rating) {
    if (!isRatingValueValid(rating)) {
      return false;
    }

    if (/^(\+)[0-6]$/.test(rating) || /^[0-6](\+)$/.test(rating)) {
      return parseInt(rating) + 0.25;
    }

    if (/^(\-)[0-6]$/.test(rating) || /^[0-6](\-)$/.test(rating)) {
      return parseInt(rating) - 0.25;
    }

    return rating;
  }

  /**
   * Add header cell to table.
   * @param {String} text Cell text content
   */
  function addHeaderCellToTable(text) {
    var header = document.querySelector(tableHeaderSelector);
    var newNode = document.createElement('th');
    newNode.textContent = text;
    header.appendChild(newNode);
  }

  /**
   * Calculate average from array values.
   * @param  {Array} averages
   * @return {Number}
   */
  function calculateAverage(averages) {
    console.log(averages);
    // remove null values
    averages = averages.filter(function(e){ return e });

    // round averages
    for (var i = 0, roundedAverages = Array(); i < averages.length; i++) {
      var rounded = Math.round(averages[i]);

      // with this check, average be calculating even when doesn't have all ratings
      if (!isNaN(rounded)) {
        roundedAverages.push(rounded);
      }
    }

    // if array no contains any average, nothing shows
    if (roundedAverages.length == 0) {
      return NaN;
    }

    var sum = roundedAverages.reduce(function(a, b) { return a + b });
    var avg = sum / roundedAverages.length;

    return avg;
  }

  /**
   * Add whole grades average to table foot.
   * @param {Array} averages Average grades
   */
  function addWholeGradesAverageToTableFoot(averages) {
    addHeaderCellToTable('Obliczona średnia');

    var table = document.querySelector(tableDefaultSelector);
    var thead = table.querySelector('thead tr');

    var tfoot = document.createElement('thead');
    var tr = document.createElement('tr');
    var th = document.createElement('th');

    var avg = calculateAverage(averages);
    if (!isNaN(avg)) {
      th.textContent = Math.round(avg * 100) / 100;
      th.title = avg;
    } else {
      th.textContent = '-';
    }
    th.id = summaryContainerId;

    var docFrag = document.createDocumentFragment();
    for (var i = 0; i < thead.children.length - 1; i++) {
      docFrag.appendChild(document.createElement('th'));
    }
    tr.appendChild(docFrag);

    tr.appendChild(th);
    tfoot.appendChild(tr);
    table.appendChild(tfoot)
  }

  function calculateAndAddRealWholeGradesAverageToTableFoot() {
    // get subject rows
    var subjects = document.querySelectorAll(subjetsSelector);
    var averages = [];

    // iterate over each subject
    for (var i = 0, max = subjects.length; i < max; i++) {
      // check is any grades exists
      if (subjects[i].querySelector(ratingsSelector)) {
        var average = subjects[i].querySelector('td:nth-last-child(2)').innerHTML;
        averages.push(normalizeRating(average));
      }
    }

    var table = document.querySelector(tableDefaultSelector);
    var cell = table.querySelector('thead:last-of-type th:nth-last-child(2)');
    var avg = calculateAverage(averages);

    if (!isNaN(avg)) {
      cell.textContent = Math.round(avg * 100) / 100;
      cell.title = avg;
    } else {
      cell.textContent = '-';
    }
  }

  function addWeightedAverageToTableFoot(average) {
    var table = document.querySelector(tableDetailsSelector);
    var thead = table.querySelector('thead tr');
    var tfoot = document.createElement('thead');
    var tr = document.createElement('tr');
    var th = document.createElement('th');

    if (!isNaN(average)) {
      th.textContent = Math.round(average * 100) / 100;
      th.title = average;
    } else {
      th.textContent = '-';
    }
    th.id = summaryContainerId;

    var docFrag = document.createDocumentFragment();
    for (var i = 0; i < thead.children.length; i++) {
      if (i == 1) {
        docFrag.appendChild(th);
      } else {
        docFrag.appendChild(document.createElement('th'));
      }
    }
    tr.appendChild(docFrag);

    tfoot.appendChild(tr);
    table.appendChild(tfoot);
  }

  /**
   * Normalize rating value.
   * @param  {Number|String} rating Rating value
   * @return {Number} Rating number value
   */
  function normalizeRating(rating) {
    if (isRatingValueValid(rating)) {
      return getRatingValue(rating);
    }

    switch(rating) {
      case 'celujący': rating = 6; break;
      case 'bardzo dobry': rating = 5; break;
      case 'dobry': rating = 4; break;
      case 'dostateczny': rating = 3; break;
      case 'dopuszczający': rating = 2; break;
      case 'niedostateczny': rating = 1; break;
      default: rating = 0;
    }

    return rating;
  }

})();
<commit_msg>Delete debug code<commit_after>(function(){
  "use strict";

  var tableDefaultSelector = '.ocenyZwykle-table';
  var tableDetailsSelector = '.ocenySzczegoly-table';
  var tableHeaderSelector = tableDefaultSelector + ' > thead > tr';
  var subjetsSelector = 'tbody tr';
  var ratingsSelector = 'td.break-word span';
  var gradesSelector = 'tbody tr'
  var summaryContainerId = 'whole-avarage';

  (function(){
    if(document.getElementById(summaryContainerId)) {
      return;
    }

    if (document.querySelector(tableDefaultSelector)) {
      var subjects = document.querySelectorAll(subjetsSelector);
      var averages = [];

      for (var i = 0, max = subjects.length; i < max; i++) {
        var avarage = getGradesAverage(subjects[i]);
        putGradesAverageCellToSubjectRow(subjects[i], avarage);
        averages.push(avarage);
      }

      addWholeGradesAverageToTableFoot(averages);
      calculateAndAddRealWholeGradesAverageToTableFoot();

    } else if(document.querySelector(tableDetailsSelector)) {
      var grades = document.querySelectorAll(gradesSelector);

      var weightedAverage = calculateAverageFromGrades(grades);
      addWeightedAverageToTableFoot(weightedAverage);
    }
  })();

  function calculateAverageFromGrades(grades) {
    var counter = 0;
    var denominator = 0;

    for (let i = 0; i < grades.length; i++) {
      let grade = getGradeValue(grades[i]);

      if (grade.value) {
        counter += grade.value * grade.weight;
        denominator += grade.weight;
      }
    }

    if (0 == denominator) {
      return null;
    }

    return counter / denominator;
  }

  function getGradeValue(gradeRow) {
    let value = gradeRow.querySelector('td:nth-child(2)').textContent;
    let weight = gradeRow.querySelector('td:nth-child(4)').textContent;

    value = getRatingValue(value);
    weight = parseFloat(weight.replace(/,/, '.'));

    if (value) {
      return {
        "value": value,
        "weight": weight
      };
    }

    return false;
  }

  function getGradesAverage(row) {
    var grades = row.querySelectorAll(ratingsSelector);

    var counter = 0;
    var denominator = 0;

    for (var i = 0, max = grades.length; i < max; i++) {
      var value = getRatingValue(grades[i].innerHTML);
      var weight = getWeightOfGradeFromAlt(grades[i]);

      if (value) {
        counter += value * weight;
        denominator += weight;
      }
    }

    if (0 == denominator) {
      return null;
    }

    return counter / denominator;
  }

  function putGradesAverageCellToSubjectRow(row, avarage) {
    if (null == avarage) {
      var text = '-';
      avarage = '-';
    } else {
      var text = Math.round(avarage * 100) / 100;
    }

    var newNode = document.createElement('td');
    newNode.textContent = text;
    newNode.title = avarage;
    row.appendChild(newNode)
  }

  /**
   * Extract weight of grade from span alt.
   * @param  {Object} span Span
   * @return {Number} Grade weight
   */
  function getWeightOfGradeFromAlt(span) {
    var alt = span.getAttribute('alt');
    var weight = alt.match(/[0-9]{1,2},[0-9]{2}/)[0];
    var weight = parseFloat(weight.replace(/,/, '.'));

    return weight;
  }

  /**
   * Check is rating value valid.
   * @param  {*}  rating Rating value
   * @return {Boolean}
   */
  function isRatingValueValid(rating) {
    return /^(\+|\-)?[0-6](\+|\-)?$/.test(rating);
  }

  /**
   * Get real rating value.
   * @param  {*} rating Rating
   * @return {Number}
   */
  function getRatingValue(rating) {
    if (!isRatingValueValid(rating)) {
      return false;
    }

    if (/^(\+)[0-6]$/.test(rating) || /^[0-6](\+)$/.test(rating)) {
      return parseInt(rating) + 0.25;
    }

    if (/^(\-)[0-6]$/.test(rating) || /^[0-6](\-)$/.test(rating)) {
      return parseInt(rating) - 0.25;
    }

    return rating;
  }

  /**
   * Add header cell to table.
   * @param {String} text Cell text content
   */
  function addHeaderCellToTable(text) {
    var header = document.querySelector(tableHeaderSelector);
    var newNode = document.createElement('th');
    newNode.textContent = text;
    header.appendChild(newNode);
  }

  /**
   * Calculate average from array values.
   * @param  {Array} averages
   * @return {Number}
   */
  function calculateAverage(averages) {
    // remove null values
    averages = averages.filter(function(e){ return e });

    // round averages
    for (var i = 0, roundedAverages = Array(); i < averages.length; i++) {
      var rounded = Math.round(averages[i]);

      // with this check, average be calculating even when doesn't have all ratings
      if (!isNaN(rounded)) {
        roundedAverages.push(rounded);
      }
    }

    // if array no contains any average, nothing shows
    if (roundedAverages.length == 0) {
      return NaN;
    }

    var sum = roundedAverages.reduce(function(a, b) { return a + b });
    var avg = sum / roundedAverages.length;

    return avg;
  }

  /**
   * Add whole grades average to table foot.
   * @param {Array} averages Average grades
   */
  function addWholeGradesAverageToTableFoot(averages) {
    addHeaderCellToTable('Obliczona średnia');

    var table = document.querySelector(tableDefaultSelector);
    var thead = table.querySelector('thead tr');

    var tfoot = document.createElement('thead');
    var tr = document.createElement('tr');
    var th = document.createElement('th');

    var avg = calculateAverage(averages);
    if (!isNaN(avg)) {
      th.textContent = Math.round(avg * 100) / 100;
      th.title = avg;
    } else {
      th.textContent = '-';
    }
    th.id = summaryContainerId;

    var docFrag = document.createDocumentFragment();
    for (var i = 0; i < thead.children.length - 1; i++) {
      docFrag.appendChild(document.createElement('th'));
    }
    tr.appendChild(docFrag);

    tr.appendChild(th);
    tfoot.appendChild(tr);
    table.appendChild(tfoot)
  }

  function calculateAndAddRealWholeGradesAverageToTableFoot() {
    // get subject rows
    var subjects = document.querySelectorAll(subjetsSelector);
    var averages = [];

    // iterate over each subject
    for (var i = 0, max = subjects.length; i < max; i++) {
      // check is any grades exists
      if (subjects[i].querySelector(ratingsSelector)) {
        var average = subjects[i].querySelector('td:nth-last-child(2)').innerHTML;
        averages.push(normalizeRating(average));
      }
    }

    var table = document.querySelector(tableDefaultSelector);
    var cell = table.querySelector('thead:last-of-type th:nth-last-child(2)');
    var avg = calculateAverage(averages);

    if (!isNaN(avg)) {
      cell.textContent = Math.round(avg * 100) / 100;
      cell.title = avg;
    } else {
      cell.textContent = '-';
    }
  }

  function addWeightedAverageToTableFoot(average) {
    var table = document.querySelector(tableDetailsSelector);
    var thead = table.querySelector('thead tr');
    var tfoot = document.createElement('thead');
    var tr = document.createElement('tr');
    var th = document.createElement('th');

    if (!isNaN(average)) {
      th.textContent = Math.round(average * 100) / 100;
      th.title = average;
    } else {
      th.textContent = '-';
    }
    th.id = summaryContainerId;

    var docFrag = document.createDocumentFragment();
    for (var i = 0; i < thead.children.length; i++) {
      if (i == 1) {
        docFrag.appendChild(th);
      } else {
        docFrag.appendChild(document.createElement('th'));
      }
    }
    tr.appendChild(docFrag);

    tfoot.appendChild(tr);
    table.appendChild(tfoot);
  }

  /**
   * Normalize rating value.
   * @param  {Number|String} rating Rating value
   * @return {Number} Rating number value
   */
  function normalizeRating(rating) {
    if (isRatingValueValid(rating)) {
      return getRatingValue(rating);
    }

    switch(rating) {
      case 'celujący': rating = 6; break;
      case 'bardzo dobry': rating = 5; break;
      case 'dobry': rating = 4; break;
      case 'dostateczny': rating = 3; break;
      case 'dopuszczający': rating = 2; break;
      case 'niedostateczny': rating = 1; break;
      default: rating = 0;
    }

    return rating;
  }

})();
<|endoftext|>


<commit_before>$.fn.Selector = function(options) {
    var self = {};
    var selectorMidLine, sIndex, arrows, currentTop, margin = {},
        allowSetSelected = true;
    var selector = $(this);
    var initialized = false;
    var settings = $.extend({
        clickToOpen: false,
        setActiveOnClick: true,
        checkedClass: 'checked',
        activeClass: 'active',
        setOrder: true,
        transitionTime: 300,
        valueAttr: 'data-value',
        arrows: 300,
        onSelectorChange: false,
        onActiveChange: false,
        onCheckedChange: false,
        onGoTo: false
    }, options);

    if(options.onMobile){
      var maxScreen;
      if(options.mobileScreen){
        maxScreen = options.mobileScreen;
      } else { maxScreen = 750; }
      if($(window).outerWidth() <= maxScreen){
        settings = $.extend({},settings,options.onMobile);
      }
    }

    return this.each(function(i, el) {

        var init = function(callback) {
            if (settings.init) {
                var initInterval = setInterval(function() {
                    if (initialized) {
                        clearInterval(initInterval);
                    } else {
                        initialize();
                    }
                }, 1000);
            }

            if (settings.arrows) {
                arrows = $('<div>').addClass('selector-arrows');
                arrows.append($('<a>').addClass('selector-arrows-up').on('click', function() {
                    goToOption('up');
                }));
                arrows.append($('<a>').addClass('selector-arrows-down').on('click', function() {
                    goToOption('down');
                }));
                selector.prepend(arrows);
            }

            // Click Actions

            if (!settings.clickToOpen) {
                selector.on('click', 'li', function(e) {
                    e.preventDefault();
                    scrollToSelected($(this));
                });
            }

            if (settings.setActiveOnClick) {
                selector.on('click', 'li a', function(e) {
                    var clickedElement = $(this);
                    setActive(selector, $(this).parent());
                    scrollToSelected($(this).parent());
                    if (!settings.clickToOpen) {
                        e.preventDefault();
                    }
                });
            }

            // On Active change
            selector.on('activeChange', function() {
                if (isFunction(settings.onActiveChange)) {
                    settings.onActiveChange();
                }
            });
            // On Checked change
            selector.on('checkedChange', function() {
                if (isFunction(settings.onCheckedChange)) {
                    settings.onCheckedChange();
                }
            });
            // On Checked change
            selector.on('selectorChange', function() {
                if (isFunction(settings.onSelectorChange)) {
                    settings.onSelectorChange();
                }
            });
            // On Checked change
            selector.on('selectorChange', function() {
                if (isFunction(settings.onSelectorChange)) {
                    settings.onSelectorChange();
                }
            });

            // When leaving the Selector
            selector.mouseleave(function() {
              setTimeout(function() {
                scrollToSelected(selector.find('li.' + settings.activeClass));
              }, 200);
            });

            // When scrolling into Selector
            selector.scroll(function() {
                setSelected(selector);
                currentTop = selector.scrollTop();
                if (settings.arrows) {
                    keepArrowsInPlace();
                }
            });
            if (callback && typeof(callback) === "function") {
                callback();
            }
        };

        // Check if var is function
        var isFunction = function isFunction(functionToCheck) {
            var getType = {};
            return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
        };
        var initialize = function initialize() {
            if (!initialized) {
                initSelector(selector);
                if(settings.activeClass){
                  scrollToSelected(selector.find('li.' + settings.activeClass));
                }
                if (settings.arrows) {
                    keepArrowsInPlace();
                }
                console.log('Selector: #' + $(this).attr('id') + ' initialized');
                initialized = true;
            }
        };

        // Create Functions

        var goToUrl = function goToUrl(el) {
            setTimeout(function() {
                if (el.attr('href').length() > 0) {
                    window.location.href = el.attr('href');
                } else if (el.attr('data-url').length > 0) {
                    window.location.href = el.attr('data-url');
                }
            }, settings.transitionTime);
        };

        var scrollToSelected = function scrollToSelected(el) {
            var scrollToIndex = el.index();
            var scrollToPx = scrollToIndex * el.outerHeight();
            selector.animate({
                scrollTop: scrollToPx
            }, settings.transitionTime);
            //  setSelected(selector);
        };

        var initSelector = function initSelector(selector) {
            selectorMidLine = selector.outerHeight() / 2;
            var checked = selector.find('li.' + settings.checkedClass);
            setActive(selector, checked);
            setChecked(selector, checked);

            margin.top = (selectorMidLine - (checked.outerHeight() / 2));
            margin.bottom = margin.top;
            if (settings.arrows) {
                //    margin.top = margin.top - arrows.outerHeight();
            }
            selector.find('ul').css({
                'margin-top': margin.top,
                'margin-bottom': margin.bottom
            });
            initialized = true;
        };

        var setSelected = function setSelected(selector) {
            selector.find('li').each(function() {
                if ($(this).position().top < selectorMidLine && ($(this).position().top + $(this).outerHeight()) > selectorMidLine && !$(this).hasClass('checked')) {
                    sIndex = $(this).index();

                    setChecked(selector, $(this));
                }
            });
        };

        var setChecked = function setChecked(selector, el) {
            selector.find('li').each(function() {
                $(this).removeClass('checked').attr('data-order', sIndex - $(this).index());
            });
            el.addClass('checked');
            selector.attr('data-checked', el.attr(settings.valueAttr)).triggerAll('checkedChange selectorChange');
        };
        var setActive = function setActive(selector, el) {
            selector.find('.active').each(function() {
                $(this).removeClass('active');
            });
            el.addClass('active');
            selector.attr('data-active', el.attr(settings.valueAttr)).triggerAll('activeChange selectorChange');
        };

        var keepArrowsInPlace = function keepArrowsInPlace(selector) {
            arrows.css('top', selectorMidLine + currentTop);
        };

        var goToOption = function goToOption(goto) {
            var goIndex;
            if (goto === 'up') {
                goIndex = selector.find('li.' + settings.checkedClass).index() - 1;
            } else if (goto === 'down') {
                goIndex = selector.find('li.' + settings.checkedClass).index() + 1;
            } else {
                goIndex = goto;
            }
            scrollToSelected(selector.find('li:eq(' + goIndex + ')'));
        };

        var underline = function() {
            $(el).addClass("underline");
        };

        var goto = function(callback) {
          setActive(selector,$(settings.goto));
          setChecked(selector,$(settings.goto));

          scrollToSelected($(settings.goto));
          if (isFunction(callback)) {
              callback();
          }
        };

        if (settings.init) {
            init();
        }
        if (settings.goto) {
            goto(settings.goto);
        }
    });

};

(function($) {
    $.fn.extend({
        triggerAll: function(events, params) {
            var el = this,
                i, evts = events.split(' ');
            for (i = 0; i < evts.length; i += 1) {
                el.trigger(evts[i], params);
            }
            return el;
        }
    });
})(jQuery);
<commit_msg>Select first child if there is no active li<commit_after>$.fn.Selector = function(options) {
    var self = {};
    var selectorMidLine, sIndex, arrows, currentTop, margin = {},
        allowSetSelected = true;
    var selector = $(this);
    var initialized = false;
    var settings = $.extend({
        clickToOpen: false,
        setActiveOnClick: true,
        checkedClass: 'checked',
        activeClass: 'active',
        setOrder: true,
        transitionTime: 300,
        valueAttr: 'data-value',
        arrows: 300,
        onSelectorChange: false,
        onActiveChange: false,
        onCheckedChange: false,
        onGoTo: false
    }, options);

    if(options.onMobile){
      var maxScreen;
      if(options.mobileScreen){
        maxScreen = options.mobileScreen;
      } else { maxScreen = 750; }
      if($(window).outerWidth() <= maxScreen){
        settings = $.extend({},settings,options.onMobile);
      }
    }

    return this.each(function(i, el) {

        var init = function(callback) {
            if (settings.init) {
                var initInterval = setInterval(function() {
                    if (initialized) {
                        clearInterval(initInterval);
                    } else {
                        initialize();
                    }
                }, 1000);
            }

            if (settings.arrows) {
                arrows = $('<div>').addClass('selector-arrows');
                arrows.append($('<a>').addClass('selector-arrows-up').on('click', function() {
                    goToOption('up');
                }));
                arrows.append($('<a>').addClass('selector-arrows-down').on('click', function() {
                    goToOption('down');
                }));
                selector.prepend(arrows);
            }

            // Click Actions

            if (!settings.clickToOpen) {
                selector.on('click', 'li', function(e) {
                    e.preventDefault();
                    scrollToSelected($(this));
                });
            }

            if (settings.setActiveOnClick) {
                selector.on('click', 'li a', function(e) {
                    var clickedElement = $(this);
                    setActive(selector, $(this).parent());
                    scrollToSelected($(this).parent());
                    if (!settings.clickToOpen) {
                        e.preventDefault();
                    }
                });
            }

            // On Active change
            selector.on('activeChange', function() {
                if (isFunction(settings.onActiveChange)) {
                    settings.onActiveChange();
                }
            });
            // On Checked change
            selector.on('checkedChange', function() {
                if (isFunction(settings.onCheckedChange)) {
                    settings.onCheckedChange();
                }
            });
            // On Checked change
            selector.on('selectorChange', function() {
                if (isFunction(settings.onSelectorChange)) {
                    settings.onSelectorChange();
                }
            });
            // On Checked change
            selector.on('selectorChange', function() {
                if (isFunction(settings.onSelectorChange)) {
                    settings.onSelectorChange();
                }
            });

            // When leaving the Selector
            selector.mouseleave(function() {
              setTimeout(function() {
                scrollToSelected(selector.find('li.' + settings.activeClass));
              }, 200);
            });

            // When scrolling into Selector
            selector.scroll(function() {
                setSelected(selector);
                currentTop = selector.scrollTop();
                if (settings.arrows) {
                    keepArrowsInPlace();
                }
            });
            if (callback && typeof(callback) === "function") {
                callback();
            }
        };

        // Check if var is function
        var isFunction = function isFunction(functionToCheck) {
            var getType = {};
            return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
        };
        var initialize = function initialize() {
            if (!initialized) {
                initSelector(selector);
                // check if the selection return something
                if(selector.find('li.' + settings.activeClass).length > 0){
                  scrollToSelected(selector.find('li.' + settings.activeClass));
                }
                //no match => select the first li
                else{
                    setSelected(selector);
                }
                if (settings.arrows) {
                    keepArrowsInPlace();
                }
                console.log('Selector: #' + $(this).attr('id') + ' initialized');
                initialized = true;
            }
        };

        // Create Functions

        var goToUrl = function goToUrl(el) {
            setTimeout(function() {
                if (el.attr('href').length() > 0) {
                    window.location.href = el.attr('href');
                } else if (el.attr('data-url').length > 0) {
                    window.location.href = el.attr('data-url');
                }
            }, settings.transitionTime);
        };

        var scrollToSelected = function scrollToSelected(el) {
            var scrollToIndex = el.index();
            var scrollToPx = scrollToIndex * el.outerHeight();
            selector.animate({
                scrollTop: scrollToPx
            }, settings.transitionTime);
            //  setSelected(selector);
        };

        var initSelector = function initSelector(selector) {
            selectorMidLine = selector.outerHeight() / 2;
            var checked = selector.find('li.' + settings.checkedClass);
            setActive(selector, checked);
            setChecked(selector, checked);

            margin.top = (selectorMidLine - (checked.outerHeight() / 2));
            margin.bottom = margin.top;
            if (settings.arrows) {
                //    margin.top = margin.top - arrows.outerHeight();
            }
            selector.find('ul').css({
                'margin-top': margin.top,
                'margin-bottom': margin.bottom
            });
            initialized = true;
        };

        var setSelected = function setSelected(selector) {
            selector.find('li').each(function() {
                if ($(this).position().top < selectorMidLine && ($(this).position().top + $(this).outerHeight()) > selectorMidLine && !$(this).hasClass('checked')) {
                    sIndex = $(this).index();

                    setChecked(selector, $(this));
                }
            });
        };

        var setChecked = function setChecked(selector, el) {
            selector.find('li').each(function() {
                $(this).removeClass('checked').attr('data-order', sIndex - $(this).index());
            });
            el.addClass('checked');
            selector.attr('data-checked', el.attr(settings.valueAttr)).triggerAll('checkedChange selectorChange');
        };
        var setActive = function setActive(selector, el) {
            selector.find('.active').each(function() {
                $(this).removeClass('active');
            });
            el.addClass('active');
            selector.attr('data-active', el.attr(settings.valueAttr)).triggerAll('activeChange selectorChange');
        };

        var keepArrowsInPlace = function keepArrowsInPlace(selector) {
            arrows.css('top', selectorMidLine + currentTop);
        };

        var goToOption = function goToOption(goto) {
            var goIndex;
            if (goto === 'up') {
                goIndex = selector.find('li.' + settings.checkedClass).index() - 1;
            } else if (goto === 'down') {
                goIndex = selector.find('li.' + settings.checkedClass).index() + 1;
            } else {
                goIndex = goto;
            }
            scrollToSelected(selector.find('li:eq(' + goIndex + ')'));
        };

        var underline = function() {
            $(el).addClass("underline");
        };

        var goto = function(callback) {
          setActive(selector,$(settings.goto));
          setChecked(selector,$(settings.goto));

          scrollToSelected($(settings.goto));
          if (isFunction(callback)) {
              callback();
          }
        };

        if (settings.init) {
            init();
        }
        if (settings.goto) {
            goto(settings.goto);
        }
    });

};

(function($) {
    $.fn.extend({
        triggerAll: function(events, params) {
            var el = this,
                i, evts = events.split(' ');
            for (i = 0; i < evts.length; i += 1) {
                el.trigger(evts[i], params);
            }
            return el;
        }
    });
})(jQuery);
<|endoftext|>


<commit_before>
/**
 * WPCOM module
 */

var WPCOM = require('../');
var Site = require('../lib/site');
var Media = require('../lib/media');
var util = require('./util');
var fs = require('fs');
var assert = require('assert');

/**
 * Testing data
 */

var test = require('./data');

/**
 * WPCOM instance
 */

describe('WPCOM#Site#Media', function(){
  var post_added;

  // Create a new_media before to start the tests

  var new_media;
  before(function(done){
    util.addMedia(function(err, media) {
      if (err) throw err;

      new_media = media;
      done();
    });
  });

  after(function(done){
    var site = util.private_site();

    // clean new_post post
    site.deleteMedia(media_added.media[0].id, function(err, data) {
      if (err) throw err;

      // clean post_added post
      site.deleteMedia(media_added.media[1].id, function(err, data) {
        if (err) throw err;
        done();
      });
    });
  });

  describe('sync', function(){

    it('should create an `Media` instance from `Site`', function(){
      var media = WPCOM().site().media();
      assert.ok(media instanceof Media);
    });

  });

  describe('async', function(){

    describe('media.get()', function(){

      it('should get added media', function(done){
        var site = util.private_site();
        var media = site.media(test.media_id);

        media.get(function(err, info){
          if (err) throw err;

          assert.equal(3, info.id);
          done();
        });
      });

    });

    describe('media.update()', function(){

      it('should edit the media title', function(done){
        var site = util.private_site();
        var edited_title = "This is the new title";

	site
        .media(new_media.media[0].id)
        .update( { title: edited_title }, function(err, data){
          if (err) throw err;

          assert.ok(data);
          assert.equal(edited_title, data.title);

          done();
        });
      });

    });

    describe('media.addFiles([fs])', function(){

      it('should create a new media from a file', function(done){
        var site = util.private_site();

        // pass streams
        var files = [];
        for (var i = 0; i < test.new_media_data.files.length; i++) {
          files.push(fs.createReadStream(test.new_media_data.files[i]));
        }

        site
        .media()
        .addFiles(files, function(err, data){
          if (err) throw err;

          assert.ok(data);
          assert.ok(data.media instanceof Array);
          assert.equal(test.new_media_data.files.length, data.media.length);
          done();
        });

      });

    });

    describe('media.addUrls([\'url1\', \'url2\'])', function(){

      it('should create a new media', function(done){
        var site = util.private_site();

        site
        .media()
        .addUrls(test.new_media_data.media_urls, function(err, data){
          if (err) throw err;

          assert.ok(data);
          assert.ok(data.media instanceof Array);
          assert.equal(test.new_media_data.media_urls.length, data.media.length);

          media_added = data;

          done();
        });

      });

    });

    describe('media.delete()', function(){

      it('should delete a media', function(done){
        var site = util.private_site();

        site
        .media(new_media.media[0].id)
        .del(function(err, data){
          if (err) throw err;

          assert.equal(new_media.media[0].id, data.id);
          done();
        });

      });

    });

  });

});
<commit_msg>test: tabbing media#update method<commit_after>
/**
 * WPCOM module
 */

var WPCOM = require('../');
var Site = require('../lib/site');
var Media = require('../lib/media');
var util = require('./util');
var fs = require('fs');
var assert = require('assert');

/**
 * Testing data
 */

var test = require('./data');

/**
 * WPCOM instance
 */

describe('WPCOM#Site#Media', function(){
  var post_added;

  // Create a new_media before to start the tests

  var new_media;
  before(function(done){
    util.addMedia(function(err, media) {
      if (err) throw err;

      new_media = media;
      done();
    });
  });

  after(function(done){
    var site = util.private_site();

    // clean new_post post
    site.deleteMedia(media_added.media[0].id, function(err, data) {
      if (err) throw err;

      // clean post_added post
      site.deleteMedia(media_added.media[1].id, function(err, data) {
        if (err) throw err;
        done();
      });
    });
  });

  describe('sync', function(){

    it('should create an `Media` instance from `Site`', function(){
      var media = WPCOM().site().media();
      assert.ok(media instanceof Media);
    });

  });

  describe('async', function(){

    describe('media.get()', function(){

      it('should get added media', function(done){
        var site = util.private_site();
        var media = site.media(test.media_id);

        media.get(function(err, info){
          if (err) throw err;

          assert.equal(3, info.id);
          done();
        });
      });

    });

    describe('media.update()', function(){

      it('should edit the media title', function(done){
        var site = util.private_site();
        var edited_title = "This is the new title";

        site
        .media(new_media.media[0].id)
        .update( { title: edited_title }, function(err, data){
          if (err) throw err;

          assert.ok(data);
          assert.equal(edited_title, data.title);

          done();
        });
      });

    });

    describe('media.addFiles([fs])', function(){

      it('should create a new media from a file', function(done){
        var site = util.private_site();

        // pass streams
        var files = [];
        for (var i = 0; i < test.new_media_data.files.length; i++) {
          files.push(fs.createReadStream(test.new_media_data.files[i]));
        }

        site
        .media()
        .addFiles(files, function(err, data){
          if (err) throw err;

          assert.ok(data);
          assert.ok(data.media instanceof Array);
          assert.equal(test.new_media_data.files.length, data.media.length);
          done();
        });

      });

    });

    describe('media.addUrls([\'url1\', \'url2\'])', function(){

      it('should create a new media', function(done){
        var site = util.private_site();

        site
        .media()
        .addUrls(test.new_media_data.media_urls, function(err, data){
          if (err) throw err;

          assert.ok(data);
          assert.ok(data.media instanceof Array);
          assert.equal(test.new_media_data.media_urls.length, data.media.length);

          media_added = data;

          done();
        });

      });

    });

    describe('media.delete()', function(){

      it('should delete a media', function(done){
        var site = util.private_site();

        site
        .media(new_media.media[0].id)
        .del(function(err, data){
          if (err) throw err;

          assert.equal(new_media.media[0].id, data.id);
          done();
        });

      });

    });

  });

});
<|endoftext|>


<commit_before>/**
 * jQuery AutoLink
 *
 * @link	https://github.com/MarQuisKnox/jQuery.AutoLink
 * @license	MIT <http://en.wikipedia.org/wiki/MIT_License>
 *
 * @copyright	2013 - 2015 Andreas Savvides et al
 * @copyright	2014 - 2017 MarQuis Knox
 */

(function($) {

    'use strict';

    $.fn.autolink = function(options) {
        return this.each( function() {
            var $el			= $(this);
            var linkifiedContent	= _linkify( $el, options );

            $el.html( linkifiedContent );
        });
    };

    function _linkify( $el, options ) {
        var links = {
                local: {
                    baseUrl: '//' + window.location.host + '/',
                    hashtagSearchUrl: 'search/',
                    target: '_self',
                    scheme: '//'
                },
                twitter: {
                    baseUrl: "https://twitter.com/",
                    hashtagSearchUrl: "search?q=",
                    target: '_blank',
                    scheme: 'https://'
                },
                instagram: {
                    baseUrl: "http://instagram.com/",
                    hashtagSearchUrl: "explore/tags/",
                    target: '_blank',
                    scheme: 'http://'
                },
                github: {
                    baseUrl: "https://github.com/",
                    hashtagSearchUrl: null,
                    target: '_blank',
                    scheme: 'https://'
                }
            },
            defaultOptions = {
                mentions: true,
                hashtags: false,
                urls: true,
                linkTo: 'local',
                target: '_self',
                scheme: '//'
            },
            extendedOptions = $.extend(defaultOptions, options),
            elContent = $el.html(),

            // @link	http://snipplr.com/view/68530/regular-expression-for-matching-urls-with-or-without-https
            urlRegEx = /(?:(?:http|https):\/\/)?([-a-zA-Z0-9.]{2,256}\.[a-z]{2,4})\b(?:\/[-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)?((\?|\/)(.*))?/gi,
            matches;

        // Linkifying URLs
        if ( extendedOptions.urls ) {
            matches = elContent.match( urlRegEx );
            if ( matches ) {
                elContent = _linkifyUrls( matches, $el, extendedOptions );
            }
        }

        // Linkify Mentions
        if ( extendedOptions.mentions ) {
            if( _isMention( elContent ) ) {
                elContent = _linkifyMentions( elContent, links[extendedOptions.linkTo].baseUrl, $el, extendedOptions );
            }
        }

        // Linkify Hashtags
        if ( extendedOptions.hashtags ) {
            elContent = _linkifyHashtags( elContent, links[extendedOptions.linkTo], $el );
        }

        return elContent;
    }

    function _hasScheme( url ) {
        var regEx = /ed2k|ftp|http|https|news|nntp/;
        if( url.match( regEx ) ) {
            return true;
        }

        return false;
    }

    function _isEmbed( url ) {

        // check for Dailymotion embed
        var isDailymotionEmbed	= url.match( /dailymotion\.com\/embed/ig );
        isDailymotionEmbed		= ( isDailymotionEmbed !== null ) ? true : false;

        if( isDailymotionEmbed ) {
            return true;
        }

        // check for SoundCloud embed
        var isSoundCloudEmbed	= url.match( /w\.soundcloud\.com\/player|api\.soundcloud\.com/ig );
        isSoundCloudEmbed		= ( isSoundCloudEmbed !== null ) ? true : false;

        if( isSoundCloudEmbed ) {
            return true;
        }

        // check for Vimeo embed
        var isVimeoEmbed = url.match( /player\.vimeo\.com\/video/ig );
        isVimeoEmbed = ( isVimeoEmbed !== null ) ? true : false;

        if( isVimeoEmbed ) {
            return true;
        }

        var isVevoEmbed = url.match( /cache\.vevo\.com/ig );
        if( isVevoEmbed ) {
            return true;
        }

        // check for YouTube embed
        var isYouTubeEmbed	= url.match( /youtube\.com\/embed|youtube\-nocookie\.com\/embed/ig );
        isYouTubeEmbed		= ( isYouTubeEmbed !== null ) ? true : false;

        if( isYouTubeEmbed ) {
            return true;
        }

        return false;

    }

    function _linkifyUrls( matches, $el, linkObj )
    {
        var elContent = $el.html();
        $.each( matches, function( index, value ) {

            // check if embed
            var isEmbed = _isEmbed( value );

            // check for scheme
            var scheme = ( _hasScheme( value ) ) ? '' : linkObj.scheme;

            if ( !isEmbed && $el.find('a[href="' + scheme + this + '"]').length === 0 ) {
                elContent = elContent.replace( this, '' + this + '' );
            }

        });

        return elContent;
    }

    function _isMention( string )
    {
        var regEx		= /@(\w+)/ig;
        var isMention	= string.match( regEx );

        if( isMention ) {
            return true;
        }

        return false;
    }

    function _getMentions( string )
    {
        var regEx		= /@(\w+)/ig;
        var mentions	= string.match( regEx );

        if( mentions ) {
            return mentions;
        }

        return null;
    }

    // Find any mentions (e.g. @andreassavvides) and turn them into links that
    // refer to the appropriate social profile (e.g. twitter or instagram).
    function _linkifyMentions( text, baseUrl, element, options ) {
        if( !element.hasClass('parsed') && !element.hasClass('autoLinked') ) {
            // get mentions
            var mentions = _getMentions( text );

            // if mentions
            if( mentions ) {
                $.each( mentions, function( index, value ) {
                    // replace @ sign
                    var link = value.replace('@', '');

                    // replacement text
                    var replacement = ''+ value +'';

                    // new content
                    var newContent = str_replace( value, replacement, element.html() );

                    // replace in the element
                    element.html( newContent );
                });
            }
        }
    }

    // Find any hashtags (e.g. #linkyrocks) and turn them into links that refer
    // to the appropriate social profile.
    function _linkifyHashtags( text, links, element ) {
        if( typeof text === 'undefined' ) {
            return;
        }

        // If there is no search URL for a hashtag, there isn't much we can do
        if ( links.hashtagSearchUrl === null ) {
            return text;
        }

        if ( element.find('a[href="' + this + '"]').length === 0 ) {
            return text.replace(/(^|\s|\(|>)#((\w|[\u00A1-\uFFFF])+)/g, "$1#$2");
        }
    }

}(jQuery));
<commit_msg>FIXED:  URL Linking<commit_after>/**
 * jQuery AutoLink
 *
 * @link	https://github.com/MarQuisKnox/jQuery.AutoLink
 * @license	MIT <http://en.wikipedia.org/wiki/MIT_License>
 *
 * @copyright	2013 - 2015 Andreas Savvides et al
 * @copyright	2014 - 2017 MarQuis Knox
 */

(function($) {

    'use strict';

    var URL_REGEX = /(<a href=")?(?:(^|[ ]|\n|
))(?:(?:http|https):\/\/)?([-a-zA-Z0-9.]{2,256}\.[a-z]{2,4})\b(?:\/[-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)?((\?|\/)(.*))?/gi;

    $.fn.autolink = function(options) {
        return this.each( function() {
            var $el			= $(this);
            var linkifiedContent	= _linkify( $el, options );

            $el.html( linkifiedContent );
        });
    };

    function _linkify( $el, options ) {
        var links = {
                local: {
                    baseUrl: '//' + window.location.host + '/',
                    hashtagSearchUrl: 'search/',
                    target: '_self',
                    scheme: '//'
                },
                twitter: {
                    baseUrl: "https://twitter.com/",
                    hashtagSearchUrl: "search?q=",
                    target: '_blank',
                    scheme: 'https://'
                },
                instagram: {
                    baseUrl: "http://instagram.com/",
                    hashtagSearchUrl: "explore/tags/",
                    target: '_blank',
                    scheme: 'http://'
                },
                github: {
                    baseUrl: "https://github.com/",
                    hashtagSearchUrl: null,
                    target: '_blank',
                    scheme: 'https://'
                }
            },
            defaultOptions = {
                mentions: true,
                hashtags: false,
                urls: true,
                linkTo: 'local',
                target: '_self',
                scheme: '//'
            },
            extendedOptions = $.extend(defaultOptions, options),
            elContent = $el.html(),

            // @link	http://snipplr.com/view/68530/regular-expression-for-matching-urls-with-or-without-https
            urlRegEx = URL_REGEX,
            matches;

        // Linkify Hashtags
        if ( extendedOptions.hashtags ) {
            elContent = _linkifyHashtags( elContent, links[extendedOptions.linkTo], $el );
        }

        // Linkifying URLs
        if ( extendedOptions.urls ) {
            matches = elContent.match( urlRegEx );
            if ( matches ) {
                elContent = _linkifyUrls( matches, $el, extendedOptions );
            }
        }

        // Linkify Mentions
        if ( extendedOptions.mentions ) {
            if( _isMention( elContent ) ) {
                elContent = _linkifyMentions( elContent, links[extendedOptions.linkTo].baseUrl, $el, extendedOptions );
            }
        }

        return elContent;
    }

    function _hasScheme( url ) {
        var regEx = /ed2k|ftp|http|https|news|nntp/;
        if( url.match( regEx ) ) {
            return true;
        }

        return false;
    }

    function _isEmbed( url ) {

        // check for Dailymotion embed
        var isDailymotionEmbed	= url.match( /dailymotion\.com\/embed/ig );
        isDailymotionEmbed		= ( isDailymotionEmbed !== null ) ? true : false;

        if( isDailymotionEmbed ) {
            return true;
        }

        // check for SoundCloud embed
        var isSoundCloudEmbed	= url.match( /w\.soundcloud\.com\/player|api\.soundcloud\.com/ig );
        isSoundCloudEmbed		= ( isSoundCloudEmbed !== null ) ? true : false;

        if( isSoundCloudEmbed ) {
            return true;
        }

        // check for Vimeo embed
        var isVimeoEmbed = url.match( /player\.vimeo\.com\/video/ig );
        isVimeoEmbed = ( isVimeoEmbed !== null ) ? true : false;

        if( isVimeoEmbed ) {
            return true;
        }

        var isVevoEmbed = url.match( /cache\.vevo\.com/ig );
        if( isVevoEmbed ) {
            return true;
        }

        // check for YouTube embed
        var isYouTubeEmbed	= url.match( /youtube\.com\/embed|youtube\-nocookie\.com\/embed/ig );
        isYouTubeEmbed		= ( isYouTubeEmbed !== null ) ? true : false;

        if( isYouTubeEmbed ) {
            return true;
        }

        return false;

    }

    function _linkifyUrls( matches, $el, linkObj )
    {
        var elContent = $el.html();
        matches = array_unique( matches );

        $.each( matches, function( index, value ) {

            // check if embed
            var isEmbed = _isEmbed( value );

            // check for scheme
            var scheme = ( _hasScheme( value ) ) ? '' : linkObj.scheme;

            // trim
            var text = value.trim();

            // remove certain chars
            text = text.replace( '
', '' );

            if ( !isEmbed && value.length > 0 ) {
                elContent = elContent.split( new RegExp( value ) ).join( ''+ value +'' );
            }

        });

        return elContent;
    }

    function _isMention( string )
    {
        var regEx		= /(?:(^|[ ]|\n|
))\B@([a-zA-Z0-9-.]+)/ig;
        var isMention	= string.match( regEx );

        if( isMention ) {
            return true;
        }

        return false;
    }

    function _getMentions( string )
    {
        var regEx		= /(?:(^|[ ]|\n|
))\B@([a-zA-Z0-9-.]+)/ig;
        var mentions	= string.match( regEx );

        if( mentions ) {
            return mentions;
        }

        return null;
    }

    // Find any mentions (e.g. @andreassavvides) and turn them into links that
    // refer to the appropriate social profile (e.g. twitter or instagram).
    function _linkifyMentions( text, baseUrl, element, options ) {
        var newContent = text;

        if( !element.hasClass('parsed') && !element.hasClass('autoLinked') && !element.hasClass('linkified') ) {
            // get mentions
            var mentions = _getMentions( text );

            // if mentions
            if( mentions ) {
                $.each( mentions, function( index, value ) {
                    // trim
                    var trimmedText = value.trim();

                    // replace @ sign
                    var link = trimmedText.replace('@', '');

                    // replace breaks
                    link = link.replace('
', '');

                    // replacement text
                    var replacement = ''+ value +'';

                    // new content
                    newContent = newContent.replaceAllByRegex( /(?:(^|[ ]|\n|
))\B@([a-zA-Z0-9-.]+)/, replacement, element.html() );
                });
            }
        }

        return newContent;
    }

    // Find any hashtags (e.g. #linkyrocks) and turn them into links that refer
    // to the appropriate social profile.
    function _linkifyHashtags( text, links, element ) {

        if( typeof text === 'undefined' ) {
            return;
        }

        // If there is no search URL for a hashtag, there isn't much we can do
        if ( links.hashtagSearchUrl === null ) {
            return text;
        }

        //if ( !element.hasClass('linkified') && element.find('a[href="' + this + '"]').length === 0 ) {
        return text.replace(/(^|\s|\(|>)#([a-zA-Z0-9-.]+)/g, "$1#$2");
        //}
    }

    function array_unique (inputArr) {
        var key = ''
        var tmpArr2 = {}
        var val = ''
        var _arraySearch = function (needle, haystack) {
            var fkey = ''
            for (fkey in haystack) {
                if (haystack.hasOwnProperty(fkey)) {
                    if ((haystack[fkey] + '') === (needle + '')) {
                        return fkey
                    }
                }
            }
            return false
        }
        for (key in inputArr) {
            if (inputArr.hasOwnProperty(key)) {
                val = inputArr[key]
                if (_arraySearch(val, tmpArr2) === false) {
                    tmpArr2[key] = val
                }
            }
        }
        return tmpArr2
    }

    function array_walk (array, funcname, userdata) {
        var key, value, ini

        if (!array || typeof array !== 'object') {
            return false
        }
        if (typeof array === 'object' && array.change_key_case) {
            // Duck-type check for our own array()-created PHPJS_Array
            if (arguments.length > 2) {
                return array.walk(funcname, userdata)
            } else {
                return array.walk(funcname)
            }
        }

        try {
            if (typeof funcname === 'function') {
                for (key in array) {
                    if (arguments.length > 2) {
                        funcname(array[key], key, userdata)
                    } else {
                        funcname(array[key], key)
                    }
                }
            } else if (typeof funcname === 'string') {
                this.php_js = this.php_js || {}
                this.php_js.ini = this.php_js.ini || {}
                ini = this.php_js.ini['phpjs.no-eval']
                if (ini && (
                        parseInt(ini.local_value, 10) !== 0 && (!ini.local_value.toLowerCase || ini.local_value.toLowerCase() !==
                        'off')
                    )) {
                    if (arguments.length > 2) {
                        for (key in array) {
                            this.window[funcname](array[key], key, userdata)
                        }
                    } else {
                        for (key in array) {
                            this.window[funcname](array[key], key)
                        }
                    }
                } else {
                    if (arguments.length > 2) {
                        for (key in array) {
                            eval(funcname + '(array[key], key, userdata)')
                        }
                    } else {
                        for (key in array) {
                            eval(funcname + '(array[key], key)')
                        }
                    }
                }
            } else if (funcname && typeof funcname === 'object' && funcname.length === 2) {
                var obj = funcname[0],
                    func = funcname[1]
                if (arguments.length > 2) {
                    for (key in array) {
                        obj[func](array[key], key, userdata)
                    }
                } else {
                    for (key in array) {
                        obj[func](array[key], key)
                    }
                }
            } else {
                return false
            }
        } catch (e) {
            return false
        }

        return true;
    }

    function trim (str, charlist) {
        var whitespace = [
            ' ',
            '\n',
            '\r',
            '\t',
            '\f',
            '\x0b',
            '\xa0',
            '\u2000',
            '\u2001',
            '\u2002',
            '\u2003',
            '\u2004',
            '\u2005',
            '\u2006',
            '\u2007',
            '\u2008',
            '\u2009',
            '\u200a',
            '\u200b',
            '\u2028',
            '\u2029',
            '\u3000'
        ].join('')
        var l = 0
        var i = 0
        str += ''
        if (charlist) {
            whitespace = (charlist + '').replace(/([[\]().?/*{}+$^:])/g, '$1')
        }
        l = str.length
        for (i = 0; i < l; i++) {
            if (whitespace.indexOf(str.charAt(i)) === -1) {
                str = str.substring(i)
                break
            }
        }
        l = str.length
        for (i = l - 1; i >= 0; i--) {
            if (whitespace.indexOf(str.charAt(i)) === -1) {
                str = str.substring(0, i + 1)
                break
            }
        }
        return whitespace.indexOf(str.charAt(0)) === -1 ? str : ''
    }

    function preg_quote (str, delimiter) {
        return String(str)
            .replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + (delimiter || '') + '-]', 'g'), '\\$&')
    }

    String.prototype.replaceAllByRegex = function(search, replacement) {
        var target = this;
        return target.replace(new RegExp(search, 'g'), replacement);
    };

    String.prototype.replaceAll = function(search, replacement) {
        var target = this;
        return target.split(search).join(replacement);
    };

}(jQuery));
<|endoftext|>


<commit_before><commit_msg>Render alternate med names as a list<commit_after><|endoftext|>


<commit_before>// Copyright 2014 Google Inc. All rights reserved.
//
// 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.

(function(scope, testing) {
  function consumeLengthPercentOrAuto(string) {
    return scope.consumeLengthOrPercent(string) || scope.consumeToken(/^auto/, string);
  }
  function parseBox(string) {
    var result = scope.consumeList([
      scope.ignore(scope.consumeToken.bind(null, /^rect/)),
      scope.ignore(scope.consumeToken.bind(null, /^\(/)),
      scope.consumeRepeated.bind(null, consumeLengthPercentOrAuto, /^,/),
      scope.ignore(scope.consumeToken.bind(null, /^\)/)),
    ], string);
    if (result && result[0].length == 4) {
      return result[0];
    }
  }

  function mergeComponent(left, right) {
    if (left == 'auto' || right == 'auto') {
      return [true, false, function(t) {
        var result = t ? left : right;
        if (result == 'auto') {
          return 'auto';
        }
        // FIXME: There's probably a better way to turn a dimension back into a string.
        var merged = scope.mergeDimensions(result, result);
        return merged[2](merged[0]);
      }];
    }
    return scope.mergeDimensions(left, right);
  }

  function wrap(result) {
    return 'rect(' + result + ')';
  }

  var mergeBoxes = scope.mergeWrappedNestedRepeated.bind(null, wrap, mergeComponent, ',');

  scope.parseBox = parseBox;
  scope.mergeBoxes = mergeBoxes;

  scope.addPropertiesHandler(parseBox, mergeBoxes, ['clip']);

})(webAnimationsMinifill, webAnimationsTesting);
<commit_msg>Output rect components separated by ', '<commit_after>// Copyright 2014 Google Inc. All rights reserved.
//
// 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.

(function(scope, testing) {
  function consumeLengthPercentOrAuto(string) {
    return scope.consumeLengthOrPercent(string) || scope.consumeToken(/^auto/, string);
  }
  function parseBox(string) {
    var result = scope.consumeList([
      scope.ignore(scope.consumeToken.bind(null, /^rect/)),
      scope.ignore(scope.consumeToken.bind(null, /^\(/)),
      scope.consumeRepeated.bind(null, consumeLengthPercentOrAuto, /^,/),
      scope.ignore(scope.consumeToken.bind(null, /^\)/)),
    ], string);
    if (result && result[0].length == 4) {
      return result[0];
    }
  }

  function mergeComponent(left, right) {
    if (left == 'auto' || right == 'auto') {
      return [true, false, function(t) {
        var result = t ? left : right;
        if (result == 'auto') {
          return 'auto';
        }
        // FIXME: There's probably a better way to turn a dimension back into a string.
        var merged = scope.mergeDimensions(result, result);
        return merged[2](merged[0]);
      }];
    }
    return scope.mergeDimensions(left, right);
  }

  function wrap(result) {
    return 'rect(' + result + ')';
  }

  var mergeBoxes = scope.mergeWrappedNestedRepeated.bind(null, wrap, mergeComponent, ', ');

  scope.parseBox = parseBox;
  scope.mergeBoxes = mergeBoxes;

  scope.addPropertiesHandler(parseBox, mergeBoxes, ['clip']);

})(webAnimationsMinifill, webAnimationsTesting);
<|endoftext|>


<commit_before>/**
 * Copyright 2019-present Facebook.
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 * @format
 */

import {colors, styled} from 'flipper';
import type {Element} from 'react';

type Props = {
  statusColor: string,
  diameter?: number | string,
  title?: string,
};

const StatusIndicator: Props => Element<'div'> = styled('div')(
  ({statusColor, diameter = 10, title}) => ({
    alignSelf: 'center',
    backgroundColor: statusColor,
    border: `1px solid ${colors.blackAlpha30}`,
    borderRadius: '50%',
    flexShrink: 0,
    height: diameter,
    title,
    width: diameter,
  }),
);

export default StatusIndicator;
<commit_msg>`StatusIndicator`: support inline contexts.<commit_after>/**
 * Copyright 2019-present Facebook.
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 * @format
 */

import {colors, styled} from 'flipper';
import type {Element} from 'react';

type Props = {
  statusColor: string,
  diameter?: number | string,
  title?: string,
};

const StatusIndicator: Props => Element<'div'> = styled('div')(
  ({statusColor, diameter = 10, title}) => ({
    alignSelf: 'center',
    backgroundColor: statusColor,
    border: `1px solid ${colors.blackAlpha30}`,
    borderRadius: '50%',
    display: 'inline-block',
    flexShrink: 0,
    height: diameter,
    title,
    width: diameter,
  }),
);

export default StatusIndicator;
<|endoftext|>


<commit_before>/*
 * jQuery Fanimate, version 0.1 (2011-03-30)
 *
 * Copyright(c) 2011 Kai Schlamp
 *
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
(function($) {
	var oldCss = $.css;
	$.css = function(elem, name, extra) {
		if (!(elem.selectorText)) {
			return oldCss(elem, name, extra);
		}
		else {
			var origName = $.camelCase(name),
			prop = $.cssProps[origName] || origName;
			return elem.style[prop];
		}
	}

	var sheet = null;
	$(document).ready(function() {
		var elem = $('<style rel="fanimate" type="text/css"></style>')
		.appendTo($('head'))[0];

		if (elem.sheet) {
			sheet = elem.sheet;
		}
		else {
			sheet = elem.styleSheet;
		}
	});

	function insertRule(sheet, selector) {
		if (sheet.insertRule) {
			sheet.insertRule(selector + ' { }', 0);
		}
		else if (sheet.addRule) {
			sheet.addRule(selector, null, 0);
		}

		var rule = null;
		if (sheet.cssRules) {
			rule = sheet.cssRules[0];
		} else {
			rule = sheet.rules[0];
		}

		// IE<9 support
		if (rule && !rule.parentStyleSheet) {
			rule.parentStyleSheet = sheet;
		}

		return rule;
	}

	function deleteRule(rule) {
		var rules = sheet.cssRules || sheet.rules;
		for (var i = 0, length = rules.length; i < length; i++) {
			if (rules[i] === rule) {
				if (sheet.deleteRule) {
					sheet.deleteRule(i);
				}
				else if (sheet.removeRule) {
					sheet.removeRule(i);
				}
				break;
			}
		}
	}

	function setStyle(rule, name, value) {
		$.access([rule], name, value, true, function(elem, name, value) {
			$.style(elem, name, value);
		});
	}

	$.fanimate = function(selector) {
		var rule = insertRule(sheet, selector);

		return {
			css: function(name, value) {
				setStyle(rule, name, value);
				return this;
			},
			animate: function(properties, duration, easing, callback) {
				$.fn.animate.call($(rule), properties, duration, easing, callback);
				return this;
			},
			remove: function() {
				var queue = $.queue(rule);
				if (queue && queue[0] === "inprogress") {
					$.queue(rule, "fx", function(next) {
						deleteRule(rule);
						next();
					});
				}
				else {
					deleteRule(rule);
				}
			}
		}
	}
})(jQuery)
<commit_msg>Deleted one more unused and by IE unsupported parentStyleSheet call.<commit_after>/*
 * jQuery Fanimate, version 0.1 (2011-03-30)
 *
 * Copyright(c) 2011 Kai Schlamp
 *
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
(function($) {
	var oldCss = $.css;
	$.css = function(elem, name, extra) {
		if (!(elem.selectorText)) {
			return oldCss(elem, name, extra);
		}
		else {
			var origName = $.camelCase(name),
			prop = $.cssProps[origName] || origName;
			return elem.style[prop];
		}
	}

	var sheet = null;
	$(document).ready(function() {
		var elem = $('<style rel="fanimate" type="text/css"></style>')
		.appendTo($('head'))[0];

		if (elem.sheet) {
			sheet = elem.sheet;
		}
		else {
			sheet = elem.styleSheet;
		}
	});

	function insertRule(sheet, selector) {
		if (sheet.insertRule) {
			sheet.insertRule(selector + ' { }', 0);
		}
		else if (sheet.addRule) {
			sheet.addRule(selector, null, 0);
		}

		var rule = null;
		if (sheet.cssRules) {
			rule = sheet.cssRules[0];
		} else {
			rule = sheet.rules[0];
		}

		return rule;
	}

	function deleteRule(rule) {
		var rules = sheet.cssRules || sheet.rules;
		for (var i = 0, length = rules.length; i < length; i++) {
			if (rules[i] === rule) {
				if (sheet.deleteRule) {
					sheet.deleteRule(i);
				}
				else if (sheet.removeRule) {
					sheet.removeRule(i);
				}
				break;
			}
		}
	}

	function setStyle(rule, name, value) {
		$.access([rule], name, value, true, function(elem, name, value) {
			$.style(elem, name, value);
		});
	}

	$.fanimate = function(selector) {
		var rule = insertRule(sheet, selector);

		return {
			css: function(name, value) {
				setStyle(rule, name, value);
				return this;
			},
			animate: function(properties, duration, easing, callback) {
				$.fn.animate.call($(rule), properties, duration, easing, callback);
				return this;
			},
			remove: function() {
				var queue = $.queue(rule);
				if (queue && queue[0] === "inprogress") {
					$.queue(rule, "fx", function(next) {
						deleteRule(rule);
						next();
					});
				}
				else {
					deleteRule(rule);
				}
			}
		}
	}
})(jQuery)
<|endoftext|>


<commit_before>// ==========================================================================
//                               DG.main
//
//  Copyright (c) 2014 by The Concord Consortium, Inc. All rights reserved.
//
//  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.
// ==========================================================================

sc_require('controllers/app_controller');
sc_require('controllers/authorization');

// This is the function that will start your app running.  The default
// implementation will load any fixtures you have created then instantiate
// your controllers and awake the elements on your page.
//
// As you develop your application you will probably want to override this.
// See comments for some pointers on what to do next.
//
DG.main = function main() {

//  var host = SC.$(location).attr('host'),
//      bodyclass = "";

 DG.Browser.init(); // Import any DG specific browser hacks we need.

 // We will set a CSS class on the <body> tag based on the hostname in the URL
 // This will allow e.g. different backgrounds on a local or dev build.
// if( !SC.empty(host))
// {
//    var patt=new RegExp(/[^:\.]*(?=[:\.])/);
//    bodyclass = patt.exec(host);
//    if( bodyclass)
//      bodyclass = bodyclass[0];
//    else
//      bodyclass = 'dg';
//  }
//
// if( !SC.empty(bodyclass)) {
//  SC.$('body').addClass(bodyclass);
// }

  SC.$('body' ).addClass( 'dg');

  DG.getPath('mainPage.mainPane').append();

  DG.splash.showSplash();

  var documentLoaded = false,
    splashChanged = function() {
      // When the splash screen times out, we will display the user entry dialog
      // unless the url contained information about the document to open
      if (!DG.splash.get('isShowing')
          && !documentLoaded
          && SC.empty(DG.startingDocName)
          && SC.empty(DG.startingDocId)
          && SC.empty(DG.startingDocUrl)
      ) {
        DG.userEntryController.setup(); // Create the user entry dialog.
        DG.splash.removeObserver('isShowing', splashChanged);
      }
    };
  // DG.splash.addObserver('isShowing', splashChanged);

  if( DG.componentMode !== 'yes') { // Usual DG game situation is that we're not in component mode
    if (DG.documentServer) {
      DG.authorizationController.requireLogin();
    } else {
      DG.authorizationController.sendLoginAsGuestRequest();
    }
  }
  else {  // If componentMode is requested, open starting doc found in url params
    DG.currGameController.set('gameIsReady', false);  // So user can't make graphs right away
    DG.mainPage.addGameIfNotPresent();
    if( !SC.empty( DG.startingDocName)) {
      var owner = !SC.empty( DG.startingDocOwner) ? DG.startingDocOwner : DG.iUser;
      DG.appController.openDocumentNamed( DG.startingDocName, owner);
      DG.startingDocName = '';  // Signal that there is no longer a starting doc to open
      documentLoaded = true;
    } else if( !SC.empty( DG.startingDocId)) {
      DG.appController.openDocumentWithId( DG.startingDocId);
      DG.startingDocId = '';  // Signal that there is no longer a starting doc to open
      documentLoaded = true;
    } else if ( !SC.empty(DG.startingDocUrl)) {
      DG.appController.openDocumentFromUrl(DG.startingDocUrl);
      documentLoaded = true;
    }
  }
  // set initial game in title
  DG.appController.documentNameDidChange();
};

/* jshint unused:false */
function main() { DG.main(); }

/* Cloud File Manager Integration */
var cfm = parent && parent.CloudFileManager ? parent.CloudFileManager : null,
    client;

if (cfm) {
  cfm.clientConnect(function (event) {
    console.log(event);
    switch (event.type) {
      case 'connected':
        client = event.data.client;
        client.setProviderOptions("documentStore",
          {appName: DG.APPNAME,
           appVersion: DG.VERSION,
           appBuildNum: DG.BUILD_NUM
          });
        client._ui.setMenuBarInfo("Version "+DG.VERSION+" ("+DG.BUILD_NUM+")");
        break;

      case 'getContent':
        DG.serializeDocument().then(event.callback);
        break;

      case 'newedFile':
        DG.newDocument();
        break;

      case 'openedFile':
        DG.loadDocument(JSON.parse(event.data.content));
        break;
    }
  });
}

/* External API for saving and loading documents */

/**
 * Starts a new document
 */
DG.newDocument = function() {
  DG.appController.closeAndNewDocument()
}

/**
 * Capture the current document as an object
 *
 * @returns Promise
 */
DG.serializeDocument = function() {
  var documentController = DG.currDocumentController();
  return documentController.captureCurrentDocumentState(true);
}

/**
 * Loads a document
 *
 * @param {Object} doc
 */
DG.loadDocument = function(doc) {
  DG.store = DG.ModelStore.create();
  var newDocument = DG.Document.createDocument(doc);
  DG.currDocumentController().setDocument(newDocument);
}
<commit_msg>New document before opening<commit_after>// ==========================================================================
//                               DG.main
//
//  Copyright (c) 2014 by The Concord Consortium, Inc. All rights reserved.
//
//  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.
// ==========================================================================

sc_require('controllers/app_controller');
sc_require('controllers/authorization');

// This is the function that will start your app running.  The default
// implementation will load any fixtures you have created then instantiate
// your controllers and awake the elements on your page.
//
// As you develop your application you will probably want to override this.
// See comments for some pointers on what to do next.
//
DG.main = function main() {

//  var host = SC.$(location).attr('host'),
//      bodyclass = "";

 DG.Browser.init(); // Import any DG specific browser hacks we need.

 // We will set a CSS class on the <body> tag based on the hostname in the URL
 // This will allow e.g. different backgrounds on a local or dev build.
// if( !SC.empty(host))
// {
//    var patt=new RegExp(/[^:\.]*(?=[:\.])/);
//    bodyclass = patt.exec(host);
//    if( bodyclass)
//      bodyclass = bodyclass[0];
//    else
//      bodyclass = 'dg';
//  }
//
// if( !SC.empty(bodyclass)) {
//  SC.$('body').addClass(bodyclass);
// }

  SC.$('body' ).addClass( 'dg');

  DG.getPath('mainPage.mainPane').append();

  DG.splash.showSplash();

  var documentLoaded = false,
    splashChanged = function() {
      // When the splash screen times out, we will display the user entry dialog
      // unless the url contained information about the document to open
      if (!DG.splash.get('isShowing')
          && !documentLoaded
          && SC.empty(DG.startingDocName)
          && SC.empty(DG.startingDocId)
          && SC.empty(DG.startingDocUrl)
      ) {
        DG.userEntryController.setup(); // Create the user entry dialog.
        DG.splash.removeObserver('isShowing', splashChanged);
      }
    };
  // DG.splash.addObserver('isShowing', splashChanged);

  if( DG.componentMode !== 'yes') { // Usual DG game situation is that we're not in component mode
    if (DG.documentServer) {
      DG.authorizationController.requireLogin();
    } else {
      DG.authorizationController.sendLoginAsGuestRequest();
    }
  }
  else {  // If componentMode is requested, open starting doc found in url params
    DG.currGameController.set('gameIsReady', false);  // So user can't make graphs right away
    DG.mainPage.addGameIfNotPresent();
    if( !SC.empty( DG.startingDocName)) {
      var owner = !SC.empty( DG.startingDocOwner) ? DG.startingDocOwner : DG.iUser;
      DG.appController.openDocumentNamed( DG.startingDocName, owner);
      DG.startingDocName = '';  // Signal that there is no longer a starting doc to open
      documentLoaded = true;
    } else if( !SC.empty( DG.startingDocId)) {
      DG.appController.openDocumentWithId( DG.startingDocId);
      DG.startingDocId = '';  // Signal that there is no longer a starting doc to open
      documentLoaded = true;
    } else if ( !SC.empty(DG.startingDocUrl)) {
      DG.appController.openDocumentFromUrl(DG.startingDocUrl);
      documentLoaded = true;
    }
  }
  // set initial game in title
  DG.appController.documentNameDidChange();
};

/* jshint unused:false */
function main() { DG.main(); }

/* Cloud File Manager Integration */
var cfm = parent && parent.CloudFileManager ? parent.CloudFileManager : null,
    client;

if (cfm) {
  cfm.clientConnect(function (event) {
    console.log(event);
    switch (event.type) {
      case 'connected':
        client = event.data.client;
        client.setProviderOptions("documentStore",
          {appName: DG.APPNAME,
           appVersion: DG.VERSION,
           appBuildNum: DG.BUILD_NUM
          });
        client._ui.setMenuBarInfo("Version "+DG.VERSION+" ("+DG.BUILD_NUM+")");
        break;

      case 'getContent':
        DG.serializeDocument().then(event.callback);
        break;

      case 'newedFile':
        DG.newDocument();
        break;

      case 'openedFile':
        DG.loadDocument(JSON.parse(event.data.content));
        break;
    }
  });
}

/* External API for saving and loading documents */

/**
 * Starts a new document
 */
DG.newDocument = function() {
  DG.appController.closeAndNewDocument()
}

/**
 * Capture the current document as an object
 *
 * @returns Promise
 */
DG.serializeDocument = function() {
  var documentController = DG.currDocumentController();
  return documentController.captureCurrentDocumentState(true);
}

/**
 * Loads a document
 *
 * @param {Object} doc
 */
DG.loadDocument = function(doc) {
  DG.appController.closeAndNewDocument()
  DG.store = DG.ModelStore.create();
  var newDocument = DG.Document.createDocument(doc);
  DG.currDocumentController().setDocument(newDocument);
}
<|endoftext|>