<commit_before>var siteUrl = undefined;

function setSiteUrl(url) {
    siteUrl = url
}

/**
 * Acts in a similar fashion to Core->buildUrl() function within the PHP code
 * so that we do not have to pass in fully built URL to JS functions, but rather
 * construct them there as it makes sense (which helps on cutting down on potential
 * duplication of effort where we can replicate JS functions across multiple pages).
 *
 * @param parts - Object representing URL parts to append to the URL
 * @returns {string} - Built up URL to use
 */
function buildUrl(parts) {
    var url = siteUrl;
    var constructed = "";
    for (var part in parts) {
        if (parts.hasOwnProperty(part)) {
            constructed += "&" + part + "=" + parts[part];
        }
    }
    return url + constructed;
}

/**
 *
 */
function editUserForm(user_id) {
    var url = buildUrl({'component': 'admin', 'page': 'users', 'action': 'get_user_details', 'user_id': user_id});
    $.ajax({
        url: url,
        success: function(data) {
            var json = JSON.parse(data);
            var form = $("#edit-user-form");
            form.css("display", "block");
            $('[name="edit_user"]', form).val("true");
            var user = $('[name="user_id"]', form);
            user.val(json['user_id']);
            user.attr('readonly', 'readonly');
            if (!user.hasClass('readonly')) {
                user.addClass('readonly');
            }
            $('[name="user_firstname"]', form).val(json['user_firstname']);
            if (json['user_preferred_firstname'] == null) {
                json['user_preferred_firstname'] = "";
            }
            $('[name="user_preferred_firstname"]', form).val(json['user_preferred_firstname']);
            $('[name="user_lastname"]', form).val(json['user_lastname']);
            $('[name="user_email"]', form).val(json['user_email']);
            var registration_section;
            if (json['registration_section'] == null) {
                registration_section = "null";
            }
            else {
                registration_section = json['registration_section'].toString();
            }
            var rotating_section;
            if (json['rotating_section'] == null) {
                rotating_section = "null";
            }
            else {
                rotating_section = json['rotating_section'].toString();
            }
            $('[name="registered_section"] option[value="' + registration_section + '"]', form).prop('selected', true);
            $('[name="rotating_section"] option[value="' + rotating_section + '"]', form).prop('selected', true);
            $('[name="manual_registration"]', form).prop('checked', json['manual_registration']);
            $('[name="user_group"] option[value="' + json['user_group'] + '"]', form).prop('selected', true);
            $("[name='grading_registration_section[]']").prop('checked', false);
            if (json['grading_registration_sections'] != null && json['grading_registration_sections'] != undefined) {
                json['grading_registration_sections'].forEach(function(val) {
                    $('#grs_' + val).prop('checked', true);
                });
            }

        },
        error: function() {
            alert("Could not load user data, please refresh the page and try again.");
        }
    })
}

function newUserForm() {
    var form = $("#edit-user-form");
    form.css("display", "block");
    $('[name="edit_user"]', form).val("false");
    $('[name="user_id"]', form).removeClass('readonly').removeAttr('readonly').val("");
    $('[name="user_firstname"]', form).val("");
    $('[name="user_preferred_firstname"]', form).val("");
    $('[name="user_lastname"]', form).val("");
    $('[name="user_email"]', form).val("");
    $('[name="registered_section"] option[value="null"]', form).prop('selected', true);
    $('[name="rotating_section"] option[value="null"]', form).prop('selected', true);
    $('[name="manual_registration"]', form).prop('checked', true);
    $('[name="user_group"] option[value="4"]', form).prop('selected', true);
    $("[name='grading_registration_section[]']").prop('checked', false);
}

/**
 * Toggles the page details box of the page, showing or not showing various information
 * such as number of queries run, length of time for script execution, and other details
 * useful for developers, but shouldn't be shown to normal users
 */
function togglePageDetails() {
    if (document.getElementById('page-info').style.visibility == 'visible') {
        document.getElementById('page-info').style.visibility = 'hidden';
    }
    else {
        document.getElementById('page-info').style.visibility = 'visible';
    }
}

/**
 * Remove an alert message from display. This works for successes, warnings, or errors to the
 * user
 * @param elem
 */
function removeMessagePopup(elem) {
    $('#' + elem).fadeOut('slow', function() {
        $('#' + elem).remove();
    });
}

function gradeableChange(url, sel){
    url = url + sel.value;
    window.location.href = url;
}
function versionChange(url, sel){
    url = url + sel.value;
    window.location.href = url;
}

function checkVersionChange(days_late, late_days_allowed){
    if(days_late > late_days_allowed){
        var message = "The max late days allowed for this assignment is " + late_days_allowed + " days. ";
        message += "You are not supposed to change your active version after this time unless you have permission from the instructor. Are you sure you want to continue?";
        return confirm(message);
    }
    return true;
}

function checkVersionsUsed(gradeable, versions_used, versions_allowed) {
    versions_used = parseInt(versions_used);
    versions_allowed = parseInt(versions_allowed);
    if (versions_used >= versions_allowed) {
        return confirm("Are you sure you want to upload for " + gradeable + "? You have already used up all of your free submissions (" + versions_used + " / " + versions_allowed + "). Uploading may result in loss of points.");
    }
    return true;
}

function toggleDiv(id) {
    $("#" + id).toggle();
    return true;
}

function checkRefreshSubmissionPage(url) {
    setTimeout(function() {
        check_server(url)
    }, 1000);
}

function check_server(url) {
    $.post(url,
        function(data) {
            if (data.indexOf("REFRESH_ME") > -1) {
                location.reload(true);
            } else {
                checkRefreshSubmissionPage(url);
            }
        }
    );
}

function batchImportJSON(url, csrf_token){
    $.ajax(url, {
        type: "POST",
        data: {
            csrf_token: csrf_token
        }
    })
    .done(function(response) {
        window.alert(response);
        location.reload(true);
    })
    .fail(function() {
        window.alert("[AJAX ERROR] Refresh page");
    });
}

var hasNav = false;

function UpdateTableHeaders() {
    var count = 0;
    var scrollTop = parseInt($(window).scrollTop());
    $(".persist-area").each(function() {
        var el = $(".persist-thead", this);
        var height = parseFloat(el.height());
        var offset = parseFloat(el.offset().top);
        var floatingHeader = $(".floating-thead", this);
        if (scrollTop > (offset - height)) {
            if (floatingHeader.css("visibility") != "visible") {
                var cnt = 0;
                $("#floating-thead-0>td").each(function() {
                    $(this).css("width", $($("#anchor-thead").children()[cnt]).width());
                    cnt++;
                });
                floatingHeader.css("visibility", "visible");
            }
        }
        else {
            floatingHeader.css("visibility", "hidden");
        }
        $(".persist-header", this).each(function() {
            floatingHeader = $("#floating-header-" + count);
            el = $(this);
            height = parseFloat(el.height());
            offset = parseFloat(el.offset().top);
            if (scrollTop > (offset - height)) {
                if (floatingHeader.css("visibility") != "visible") {
                    floatingHeader.css("visibility", "visible");
                    var cnt = 0;
                    $("#floating-header-" + count + ">td").each(function() {
                        $(this).css("width", $($("#anchor-head-" + count).children()[cnt]).width());
                        cnt++;
                    });
                }
            }
            else {
                floatingHeader.css("visibility", "hidden");
            }
            count++;
        });
    });
}

$(function() {
    //hasNav = $("#nav").length > 0;
    hasNav = false; // nav doesn't float anymore so we don't have to account for it.
    // Each persist-area can have multiple persist-headers, we need to create each one with a new z-index
    var persist = $(".persist-area");
    var z_index = 900;
    var count = 0;
    persist.each(function() {
        var el = $(".persist-thead>tr", this);
        el.attr('id', 'anchor-thead');

        el.before(el.clone()).css({"width": el.width(), "top": "30px", "z-index": "899"}).addClass('floating-thead')
            .attr('id', 'floating-thead-' + count);
        $(".floating-thead", this).each(function() {
           $(this).children().removeAttr('width');
        });
        $(".persist-header", this).each(function() {
            $(this).attr('id', 'anchor-head-' + count);
            var clone = $(this);
            clone.before(clone.clone()).css({
                "width": clone.width(),
                "top": (30 + el.height()) + "px",
                "z-index": "" + z_index
            }).addClass("floating-header").removeClass("persist-header").attr('id', 'floating-header-' + count);
            z_index++;
            count++;
        });
    });

    if (persist.length > 0) {
        $(window).scroll(UpdateTableHeaders).trigger("scroll");
    }

    if (window.location.hash != "") {
        if ($(window.location.hash).offset().top > 0) {
            var minus = 60;
            if (hasNav) {
                minus += 30;
            }
            $("html, body").animate({scrollTop: ($(window.location.hash).offset().top - minus)}, 800);
        }
    }

    setTimeout(function() {
        $('.inner-message').fadeOut();
    }, 5000);
});<commit_msg>comment out JS for floating header bars (#840)<commit_after>var siteUrl = undefined;

function setSiteUrl(url) {
    siteUrl = url
}

/**
 * Acts in a similar fashion to Core->buildUrl() function within the PHP code
 * so that we do not have to pass in fully built URL to JS functions, but rather
 * construct them there as it makes sense (which helps on cutting down on potential
 * duplication of effort where we can replicate JS functions across multiple pages).
 *
 * @param parts - Object representing URL parts to append to the URL
 * @returns {string} - Built up URL to use
 */
function buildUrl(parts) {
    var url = siteUrl;
    var constructed = "";
    for (var part in parts) {
        if (parts.hasOwnProperty(part)) {
            constructed += "&" + part + "=" + parts[part];
        }
    }
    return url + constructed;
}

/**
 *
 */
function editUserForm(user_id) {
    var url = buildUrl({'component': 'admin', 'page': 'users', 'action': 'get_user_details', 'user_id': user_id});
    $.ajax({
        url: url,
        success: function(data) {
            var json = JSON.parse(data);
            var form = $("#edit-user-form");
            form.css("display", "block");
            $('[name="edit_user"]', form).val("true");
            var user = $('[name="user_id"]', form);
            user.val(json['user_id']);
            user.attr('readonly', 'readonly');
            if (!user.hasClass('readonly')) {
                user.addClass('readonly');
            }
            $('[name="user_firstname"]', form).val(json['user_firstname']);
            if (json['user_preferred_firstname'] == null) {
                json['user_preferred_firstname'] = "";
            }
            $('[name="user_preferred_firstname"]', form).val(json['user_preferred_firstname']);
            $('[name="user_lastname"]', form).val(json['user_lastname']);
            $('[name="user_email"]', form).val(json['user_email']);
            var registration_section;
            if (json['registration_section'] == null) {
                registration_section = "null";
            }
            else {
                registration_section = json['registration_section'].toString();
            }
            var rotating_section;
            if (json['rotating_section'] == null) {
                rotating_section = "null";
            }
            else {
                rotating_section = json['rotating_section'].toString();
            }
            $('[name="registered_section"] option[value="' + registration_section + '"]', form).prop('selected', true);
            $('[name="rotating_section"] option[value="' + rotating_section + '"]', form).prop('selected', true);
            $('[name="manual_registration"]', form).prop('checked', json['manual_registration']);
            $('[name="user_group"] option[value="' + json['user_group'] + '"]', form).prop('selected', true);
            $("[name='grading_registration_section[]']").prop('checked', false);
            if (json['grading_registration_sections'] != null && json['grading_registration_sections'] != undefined) {
                json['grading_registration_sections'].forEach(function(val) {
                    $('#grs_' + val).prop('checked', true);
                });
            }

        },
        error: function() {
            alert("Could not load user data, please refresh the page and try again.");
        }
    })
}

function newUserForm() {
    var form = $("#edit-user-form");
    form.css("display", "block");
    $('[name="edit_user"]', form).val("false");
    $('[name="user_id"]', form).removeClass('readonly').removeAttr('readonly').val("");
    $('[name="user_firstname"]', form).val("");
    $('[name="user_preferred_firstname"]', form).val("");
    $('[name="user_lastname"]', form).val("");
    $('[name="user_email"]', form).val("");
    $('[name="registered_section"] option[value="null"]', form).prop('selected', true);
    $('[name="rotating_section"] option[value="null"]', form).prop('selected', true);
    $('[name="manual_registration"]', form).prop('checked', true);
    $('[name="user_group"] option[value="4"]', form).prop('selected', true);
    $("[name='grading_registration_section[]']").prop('checked', false);
}

/**
 * Toggles the page details box of the page, showing or not showing various information
 * such as number of queries run, length of time for script execution, and other details
 * useful for developers, but shouldn't be shown to normal users
 */
function togglePageDetails() {
    if (document.getElementById('page-info').style.visibility == 'visible') {
        document.getElementById('page-info').style.visibility = 'hidden';
    }
    else {
        document.getElementById('page-info').style.visibility = 'visible';
    }
}

/**
 * Remove an alert message from display. This works for successes, warnings, or errors to the
 * user
 * @param elem
 */
function removeMessagePopup(elem) {
    $('#' + elem).fadeOut('slow', function() {
        $('#' + elem).remove();
    });
}

function gradeableChange(url, sel){
    url = url + sel.value;
    window.location.href = url;
}
function versionChange(url, sel){
    url = url + sel.value;
    window.location.href = url;
}

function checkVersionChange(days_late, late_days_allowed){
    if(days_late > late_days_allowed){
        var message = "The max late days allowed for this assignment is " + late_days_allowed + " days. ";
        message += "You are not supposed to change your active version after this time unless you have permission from the instructor. Are you sure you want to continue?";
        return confirm(message);
    }
    return true;
}

function checkVersionsUsed(gradeable, versions_used, versions_allowed) {
    versions_used = parseInt(versions_used);
    versions_allowed = parseInt(versions_allowed);
    if (versions_used >= versions_allowed) {
        return confirm("Are you sure you want to upload for " + gradeable + "? You have already used up all of your free submissions (" + versions_used + " / " + versions_allowed + "). Uploading may result in loss of points.");
    }
    return true;
}

function toggleDiv(id) {
    $("#" + id).toggle();
    return true;
}

function checkRefreshSubmissionPage(url) {
    setTimeout(function() {
        check_server(url)
    }, 1000);
}

function check_server(url) {
    $.post(url,
        function(data) {
            if (data.indexOf("REFRESH_ME") > -1) {
                location.reload(true);
            } else {
                checkRefreshSubmissionPage(url);
            }
        }
    );
}

function batchImportJSON(url, csrf_token){
    $.ajax(url, {
        type: "POST",
        data: {
            csrf_token: csrf_token
        }
    })
    .done(function(response) {
        window.alert(response);
        location.reload(true);
    })
    .fail(function() {
        window.alert("[AJAX ERROR] Refresh page");
    });
}

/*
var hasNav = false;

function UpdateTableHeaders() {
    var count = 0;
    var scrollTop = parseInt($(window).scrollTop());
    $(".persist-area").each(function() {
        var el = $(".persist-thead", this);
        var height = parseFloat(el.height());
        var offset = parseFloat(el.offset().top);
        var floatingHeader = $(".floating-thead", this);
        if (scrollTop > (offset - height)) {
            if (floatingHeader.css("visibility") != "visible") {
                var cnt = 0;
                $("#floating-thead-0>td").each(function() {
                    $(this).css("width", $($("#anchor-thead").children()[cnt]).width());
                    cnt++;
                });
                floatingHeader.css("visibility", "visible");
            }
        }
        else {
            floatingHeader.css("visibility", "hidden");
        }
        $(".persist-header", this).each(function() {
            floatingHeader = $("#floating-header-" + count);
            el = $(this);
            height = parseFloat(el.height());
            offset = parseFloat(el.offset().top);
            if (scrollTop > (offset - height)) {
                if (floatingHeader.css("visibility") != "visible") {
                    floatingHeader.css("visibility", "visible");
                    var cnt = 0;
                    $("#floating-header-" + count + ">td").each(function() {
                        $(this).css("width", $($("#anchor-head-" + count).children()[cnt]).width());
                        cnt++;
                    });
                }
            }
            else {
                floatingHeader.css("visibility", "hidden");
            }
            count++;
        });
    });
}

$(function() {
    //hasNav = $("#nav").length > 0;
    hasNav = false; // nav doesn't float anymore so we don't have to account for it.
    // Each persist-area can have multiple persist-headers, we need to create each one with a new z-index
    var persist = $(".persist-area");
    var z_index = 900;
    var count = 0;
    persist.each(function() {
        var el = $(".persist-thead>tr", this);
        el.attr('id', 'anchor-thead');

        el.before(el.clone()).css({"width": el.width(), "top": "30px", "z-index": "899"}).addClass('floating-thead')
            .attr('id', 'floating-thead-' + count);
        $(".floating-thead", this).each(function() {
           $(this).children().removeAttr('width');
        });
        $(".persist-header", this).each(function() {
            $(this).attr('id', 'anchor-head-' + count);
            var clone = $(this);
            clone.before(clone.clone()).css({
                "width": clone.width(),
                "top": (30 + el.height()) + "px",
                "z-index": "" + z_index
            }).addClass("floating-header").removeClass("persist-header").attr('id', 'floating-header-' + count);
            z_index++;
            count++;
        });
    });

    if (persist.length > 0) {
        $(window).scroll(UpdateTableHeaders).trigger("scroll");
    }

    if (window.location.hash != "") {
        if ($(window.location.hash).offset().top > 0) {
            var minus = 60;
            if (hasNav) {
                minus += 30;
            }
            $("html, body").animate({scrollTop: ($(window.location.hash).offset().top - minus)}, 800);
        }
    }

    setTimeout(function() {
        $('.inner-message').fadeOut();
    }, 5000);
});
*/

$(function() {
    if (window.location.hash !== "") {
        if ($(window.location.hash).offset().top > 0) {
            var minus = 60;
            $("html, body").animate({scrollTop: ($(window.location.hash).offset().top - minus)}, 800);
        }
    }

    setTimeout(function() {
        $('.inner-message').fadeOut();
    }, 5000);
});<|endoftext|>


<commit_before>// Copyright 2014 Globo.com Player authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

var UIPlugin = require('../../base/ui_plugin')
var Styler = require('../../base/styler')
var JST = require('../../base/jst')
var _ = require("underscore")
var Mediator = require('../../components/mediator')
var Browser = require('../../components/browser')

var objectIE = '<object type="application/x-shockwave-flash" id="<%= cid %>" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" data-hls=""><param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="transparent"> <param name="tabindex" value="1"> </object>'

class HLS extends UIPlugin {
  get name() { return 'hls' }
  get tagName() { return 'object' }
  get template() { return JST.hls }
  get attributes() {
    return {
      'data-hls': '',
      'type': 'application/x-shockwave-flash'
    }
  }

  constructor(options) {
    super(options)
    this.src = options.src
    this.swfPath = options.swfPath || "http://cdn.clappr.io/latest/assets/HLSPlayer.swf"
    this.highDefinition = false
    this.autoPlay = options.autoPlay
    this.defaultSettings = {
      left: ["playstop", "volume"],
      default: ['seekbar'],
      right: ["fullscreen", "hd-indicator"],
      seekEnabled: true
    }
    this.settings = _.extend({}, this.defaultSettings)
    this.addListeners()
  }

  addListeners() {
    Mediator.on(this.uniqueId + ':flashready', () => this.bootstrap())
    Mediator.on(this.uniqueId + ':timeupdate', () => this.updateTime())
    Mediator.on(this.uniqueId + ':playbackstate', (state) => this.setPlaybackState(state))
    Mediator.on(this.uniqueId + ':highdefinition', (isHD) => this.updateHighDefinition(isHD))
    Mediator.on(this.uniqueId + ':playbackerror', () => this.flashPlaybackError())
  }

  stopListening() {
    super()
    Mediator.off(this.uniqueId + ':flashready')
    Mediator.off(this.uniqueId + ':timeupdate')
    Mediator.off(this.uniqueId + ':playbackstate')
    Mediator.off(this.uniqueId + ':highdefinition')
    Mediator.off(this.uniqueId + ':playbackerror')
  }

  bootstrap() {
    this.el.width = "100%"
    this.el.height = "100%"
    this.trigger('playback:ready', this.name)
    this.currentState = "IDLE"
    this.el.globoPlayerSetflushLiveURLCache(true)
    this.autoPlay && this.play()
  }

  updateHighDefinition(isHD) {
    this.highDefinition = (isHD === "true");
    this.trigger('playback:highdefinitionupdate')
  }

  updateTime() {
    var duration = this.getDuration()
    var position = this.el.globoGetPosition()
    if (this.playbackType === 'live' && position >= duration) {
      position = duration
    }
    this.trigger('playback:timeupdate', position, duration, this.name)

    var previousDVRStatus = this.dvrEnabled
    this.dvrEnabled = (this.playbackType === 'live' && duration > 240)
    if (this.dvrEnabled !== previousDVRStatus) {
      this.updateSettings()
    }

    var previousDvrInUse = !!this.dvrInUse
    this.dvrInUse = this.dvrEnabled && (duration - position >= 2)
    if (this.dvrInUse !== previousDvrInUse) {
      this.trigger('playback:dvr', this.dvrInUse)
    }
  }

  play() {
    if(this.currentState === 'PAUSED') {
      this.el.globoPlayerResume()
    } else {
      this.firstPlay()
    }
    this.trigger('playback:play', this.name)
  }

  getPlaybackType() {
    if (this.playbackType)
      return this.playbackType
    return null
  }

  getCurrentBitrate() {
    var currentLevel = this.getLevels()[this.el.globoGetLevel()]
    return currentLevel.bitrate
  }

  getLastProgramDate() {
    var programDate = this.el.globoGetLastProgramDate()
    // normalizing for BRT
    return programDate - 1.08e+7
  }

  isHighDefinitionInUse() {
    return this.highDefinition
  }

  getLevels() {
    if (!this.levels || this.levels.length === 0) {
      this.levels = this.el.globoGetLevels()
    }
    return this.levels
  }

  setPlaybackState(state) {
    var bufferLength = this.el.globoGetbufferLength()
    if (state === "PLAYING_BUFFERING" && bufferLength < 1)  {
      this.trigger('playback:buffering', this.name)
      this.updateCurrentState(state)
    } else if (state === "PLAYING") {
      if (_.contains(["PLAYING_BUFFERING", "IDLE"], this.currentState) && bufferLength !== this.lastBufferLength) {
        this.trigger('playback:bufferfull', this.name)
        this.updateCurrentState(state)
      }
    } else if (state === "IDLE") {
      this.trigger('playback:ended', this.name)
      this.trigger('playback:timeupdate', 0, this.el.globoGetDuration(), this.name)
      this.updateCurrentState(state)
    }
    this.lastBufferLength = bufferLength
  }

  updateCurrentState(state) {
    this.currentState = state
    this.updatePlaybackType()
  }

  updatePlaybackType() {
    if (!this.playbackType) {
      this.playbackType = this.el.globoGetType()
      if (this.playbackType) {
        this.playbackType = this.playbackType.toLowerCase()
      }
      this.trigger('playback:playbackstate');
    }
  }

  firstPlay() {
    this.el.globoPlayerLoad(this.src)
    this.el.globoPlayerPlay()
  }

  volume(value) {
    this.el.globoPlayerVolume(value)
  }

  pause() {
    this.el.globoPlayerPause()
    if (this.playbackType === 'live' && this.dvrEnabled) {
      this.trigger('playback:dvr', true);
    }
  }

  stop() {
    this.el.globoPlayerStop()
    this.trigger('playback:timeupdate', 0, this.name)
  }

  isPlaying() {
    if (this.currentState) {
      return !!(this.currentState.match(/playing/i))
    }
    return false
  }

  getDuration() {
    var duration = this.el.globoGetDuration()
    if (this.playbackType === 'live') {
      // estimate 10 seconds of buffer time for live streams for seek positions
      duration = duration - 10
    }
    return duration
  }

  seek(time) {
    var duration = this.getDuration()
    if (time > 0) {
      time = duration * time / 100
    }
    // seek operations to a time within 2 seconds from live stream will position playhead back to live
    if (this.playbackType === 'live' && duration - time < 2) {
      time = -1
    }
    this.el.globoPlayerSeek(time)
  }

  flashPlaybackError() {
    this.trigger('playback:stop')
  }

  timeUpdate(time, duration) {
    this.trigger('playback:timeupdate', time, duration, this.name)
  }

  destroy() {
    this.stopListening()
    this.$el.remove()
  }

  setupFirefox() {
    var $el = this.$('embed')
    $el.attr('data-hls', '')
    this.setElement($el[0])
  }

  setupIE() {
    this.setElement($(_.template(objectIE)({cid: this.cid, swfPath: this.swfPath})))
  }

  updateSettings() {
    this.settings = _.extend({}, this.defaultSettings)
    if (this.playbackType === "vod" || this.dvrEnabled) {
      this.settings.left = ["playpause", "position", "duration"]
      this.settings.default = ["seekbar"]
    } else {
      this.settings.seekEnabled = false
    }
    this.trigger('playback:settingsupdate', this.name)
  }

  render() {
    var style = Styler.getStyleFor(this.name)
    this.$el.html(this.template({cid: this.cid, swfPath: this.swfPath, playbackId: this.uniqueId}))
    this.$el.append(style)
    this.el.id = this.cid
    if(Browser.isFirefox) {
      this.setupFirefox()
    } else if(Browser.isLegacyIE) {
      this.setupIE()
    }
    return this
  }
}

HLS.canPlay = function(resource) {
  return !!resource.match(/^http(.*).m3u8/)
}

module.exports = HLS
<commit_msg>hls: avoid call firstPlay() with videos already playing<commit_after>// Copyright 2014 Globo.com Player authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

var UIPlugin = require('../../base/ui_plugin')
var Styler = require('../../base/styler')
var JST = require('../../base/jst')
var _ = require("underscore")
var Mediator = require('../../components/mediator')
var Browser = require('../../components/browser')

var objectIE = '<object type="application/x-shockwave-flash" id="<%= cid %>" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" data-hls=""><param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="transparent"> <param name="tabindex" value="1"> </object>'

class HLS extends UIPlugin {
  get name() { return 'hls' }
  get tagName() { return 'object' }
  get template() { return JST.hls }
  get attributes() {
    return {
      'data-hls': '',
      'type': 'application/x-shockwave-flash'
    }
  }

  constructor(options) {
    super(options)
    this.src = options.src
    this.swfPath = options.swfPath || "http://cdn.clappr.io/latest/assets/HLSPlayer.swf"
    this.highDefinition = false
    this.autoPlay = options.autoPlay
    this.defaultSettings = {
      left: ["playstop", "volume"],
      default: ['seekbar'],
      right: ["fullscreen", "hd-indicator"],
      seekEnabled: true
    }
    this.settings = _.extend({}, this.defaultSettings)
    this.addListeners()
  }

  addListeners() {
    Mediator.on(this.uniqueId + ':flashready', () => this.bootstrap())
    Mediator.on(this.uniqueId + ':timeupdate', () => this.updateTime())
    Mediator.on(this.uniqueId + ':playbackstate', (state) => this.setPlaybackState(state))
    Mediator.on(this.uniqueId + ':highdefinition', (isHD) => this.updateHighDefinition(isHD))
    Mediator.on(this.uniqueId + ':playbackerror', () => this.flashPlaybackError())
  }

  stopListening() {
    super()
    Mediator.off(this.uniqueId + ':flashready')
    Mediator.off(this.uniqueId + ':timeupdate')
    Mediator.off(this.uniqueId + ':playbackstate')
    Mediator.off(this.uniqueId + ':highdefinition')
    Mediator.off(this.uniqueId + ':playbackerror')
  }

  bootstrap() {
    this.el.width = "100%"
    this.el.height = "100%"
    this.trigger('playback:ready', this.name)
    this.currentState = "IDLE"
    this.el.globoPlayerSetflushLiveURLCache(true)
    this.autoPlay && this.play()
  }

  updateHighDefinition(isHD) {
    this.highDefinition = (isHD === "true");
    this.trigger('playback:highdefinitionupdate')
  }

  updateTime() {
    var duration = this.getDuration()
    var position = this.el.globoGetPosition()
    if (this.playbackType === 'live' && position >= duration) {
      position = duration
    }
    this.trigger('playback:timeupdate', position, duration, this.name)

    var previousDVRStatus = this.dvrEnabled
    this.dvrEnabled = (this.playbackType === 'live' && duration > 240)
    if (this.dvrEnabled !== previousDVRStatus) {
      this.updateSettings()
    }

    var previousDvrInUse = !!this.dvrInUse
    this.dvrInUse = this.dvrEnabled && (duration - position >= 2)
    if (this.dvrInUse !== previousDvrInUse) {
      this.trigger('playback:dvr', this.dvrInUse)
    }
  }

  play() {
    if(this.currentState === 'PAUSED') {
      this.el.globoPlayerResume()
    } else if (this.currentState !== "PLAYING") {
      this.firstPlay()
    }
    this.trigger('playback:play', this.name)
  }

  getPlaybackType() {
    if (this.playbackType)
      return this.playbackType
    return null
  }

  getCurrentBitrate() {
    var currentLevel = this.getLevels()[this.el.globoGetLevel()]
    return currentLevel.bitrate
  }

  getLastProgramDate() {
    var programDate = this.el.globoGetLastProgramDate()
    // normalizing for BRT
    return programDate - 1.08e+7
  }

  isHighDefinitionInUse() {
    return this.highDefinition
  }

  getLevels() {
    if (!this.levels || this.levels.length === 0) {
      this.levels = this.el.globoGetLevels()
    }
    return this.levels
  }

  setPlaybackState(state) {
    var bufferLength = this.el.globoGetbufferLength()
    if (state === "PLAYING_BUFFERING" && bufferLength < 1)  {
      this.trigger('playback:buffering', this.name)
      this.updateCurrentState(state)
    } else if (state === "PLAYING") {
      if (_.contains(["PLAYING_BUFFERING", "IDLE"], this.currentState) && bufferLength !== this.lastBufferLength) {
        this.trigger('playback:bufferfull', this.name)
        this.updateCurrentState(state)
      }
    } else if (state === "IDLE") {
      this.trigger('playback:ended', this.name)
      this.trigger('playback:timeupdate', 0, this.el.globoGetDuration(), this.name)
      this.updateCurrentState(state)
    }
    this.lastBufferLength = bufferLength
  }

  updateCurrentState(state) {
    this.currentState = state
    this.updatePlaybackType()
  }

  updatePlaybackType() {
    if (!this.playbackType) {
      this.playbackType = this.el.globoGetType()
      if (this.playbackType) {
        this.playbackType = this.playbackType.toLowerCase()
      }
      this.trigger('playback:playbackstate');
    }
  }

  firstPlay() {
    this.el.globoPlayerLoad(this.src)
    this.el.globoPlayerPlay()
  }

  volume(value) {
    this.el.globoPlayerVolume(value)
  }

  pause() {
    this.el.globoPlayerPause()
    if (this.playbackType === 'live' && this.dvrEnabled) {
      this.trigger('playback:dvr', true);
    }
  }

  stop() {
    this.el.globoPlayerStop()
    this.trigger('playback:timeupdate', 0, this.name)
  }

  isPlaying() {
    if (this.currentState) {
      return !!(this.currentState.match(/playing/i))
    }
    return false
  }

  getDuration() {
    var duration = this.el.globoGetDuration()
    if (this.playbackType === 'live') {
      // estimate 10 seconds of buffer time for live streams for seek positions
      duration = duration - 10
    }
    return duration
  }

  seek(time) {
    var duration = this.getDuration()
    if (time > 0) {
      time = duration * time / 100
    }
    // seek operations to a time within 2 seconds from live stream will position playhead back to live
    if (this.playbackType === 'live' && duration - time < 2) {
      time = -1
    }
    this.el.globoPlayerSeek(time)
  }

  flashPlaybackError() {
    this.trigger('playback:stop')
  }

  timeUpdate(time, duration) {
    this.trigger('playback:timeupdate', time, duration, this.name)
  }

  destroy() {
    this.stopListening()
    this.$el.remove()
  }

  setupFirefox() {
    var $el = this.$('embed')
    $el.attr('data-hls', '')
    this.setElement($el[0])
  }

  setupIE() {
    this.setElement($(_.template(objectIE)({cid: this.cid, swfPath: this.swfPath})))
  }

  updateSettings() {
    this.settings = _.extend({}, this.defaultSettings)
    if (this.playbackType === "vod" || this.dvrEnabled) {
      this.settings.left = ["playpause", "position", "duration"]
      this.settings.default = ["seekbar"]
    } else {
      this.settings.seekEnabled = false
    }
    this.trigger('playback:settingsupdate', this.name)
  }

  render() {
    var style = Styler.getStyleFor(this.name)
    this.$el.html(this.template({cid: this.cid, swfPath: this.swfPath, playbackId: this.uniqueId}))
    this.$el.append(style)
    this.el.id = this.cid
    if(Browser.isFirefox) {
      this.setupFirefox()
    } else if(Browser.isLegacyIE) {
      this.setupIE()
    }
    return this
  }
}

HLS.canPlay = function(resource) {
  return !!resource.match(/^http(.*).m3u8/)
}

module.exports = HLS
<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter,
    deepEqual = require('deep-equal'),
    encodeResults = require('./results');

var nextTick = process && process.nextTick || setTimeout;

function instantiate(){
    var testsToRun = [],
        testsRun = [],
        totalTests = 0,
        totalAssersions = 0,
        completedAssersions = 0,
        begun = false,
        timeout = 0,
        only;

    function Test(name, testFunction){
        this._plan = 0;
        this._count = 0;
        this._assersions = [];
        this.name = name;
        this._testFunction = testFunction;
    }

    // Unused currently.
    // Test.prototype = Object.create(EventEmitter.prototype);
    // Test.prototype.constructor = Test;

    function setTestTimeout(time){
        timeout = Math.max(timeout, time);
    }

    Test.prototype.timeout = setTestTimeout;

    Test.prototype.comment = function (message) {
        // ToDo
    };

    Test.prototype.plan = function(ammount){
        this._plan = ammount;
    };

    Test.prototype._run = function(){
        var test = this;
        try {
            test._testFunction(this);
        }
        catch (err) {
            test.error(err);
        }
    };

    Test.prototype._assert = function(details){
        if(details.operator !== 'end'){
            this._count++;
        }
        if(this._ended){
            if(details.operator === 'end' || details.operator === 'fail'){
                return;
            }
            this.fail('asserted after test has ended');
        }
        this._assersions.push(details);
    };

    Test.prototype.end = function (message) {
        var ok = this._plan === this._count;

        if(this._ended){
            return;
        }

        if(ok){
            this._assert({
                ok: true,
                message: message,
                operator: 'end'
            });
        }else{
            this._assert({
                ok: false,
                expected: this._plan,
                actual: this._count,
                message: 'plan != count',
                operator: 'end'
            });
        }

        this._ended = true;
    };

    Test.prototype.error = function(error, message){
        this._assert({
            ok: !error,
            message : message || String(error),
            operator : 'error',
            actual : error
        });
    };

    Test.prototype.pass = function(message){
        this._assert({
            ok: true,
            message: message,
            operator: 'pass'
        });
    };

    Test.prototype.fail = function(message){
        this._assert({
            message: message,
            operator: 'fail'
        });
    };

    Test.prototype.skip = function(message){
        this._assert({
            message: message,
            skip: true,
            operator: 'skip'
        });
    };

    Test.prototype.ok = function(value, message){
        this._assert({
            actual: value,
            ok: !!value,
            message: message,
            operator: 'ok'
        });
    };

    Test.prototype.notOk = function(value, message){
        this._assert({
            actual: value,
            ok:!value,
            message: message,
            operator: 'notOk'
        });
    };

    Test.prototype.equal = function(value, expected, message){
        this._assert({
            actual: value,
            expected: expected,
            ok: value === expected,
            message: message,
            operator: 'equal'
        });
    };

    Test.prototype.notEqual = function(value, expected, message){
        this._assert({
            actual: value,
            expected: expected,
            ok: value !== expected,
            message: message,
            operator: 'notEqual'
        });
    };

    Test.prototype.deepEqual = function(value, expected, message){
        this._assert({
            actual: value,
            expected: expected,
            ok: deepEqual(value, expected, { strict: true }),
            message: message,
            operator: 'deepEqual'
        });
    };

    Test.prototype.deepLooseEqual = function(value, expected, message){
        this._assert({
            actual: value,
            expected: expected,
            ok: deepEqual(value, expected),
            message: message,
            operator: 'deepLooseEqual'
        });
    };

    Test.prototype.notDeepEqual = function(value, expected, message){
        this._assert({
            actual: value,
            expected: expected,
            ok: !deepEqual(value, expected, { strict: true }),
            message: message,
            operator: 'notDeepEqual'
        });
    };

    Test.prototype.notDeepLooseEqual = function(value, expected, message){
        this._assert({
            actual: value,
            expected: expected,
            ok: !deepEqual(value, expected),
            message: message,
            operator: 'notDeepLooseEqual'
        });
    };

    Test.prototype['throws'] = function (fn, expected, message) {
        var caughtError,
            passed;

        if(typeof expected === 'string'){
            message = expected;
            expected = undefined;
        }

        try{
            fn();
        }catch(error){
            caughtError = {error: error};
        }

        passed = caughtError;

        if(expected instanceof RegExp){
            passed = expected.test(caughtError && caughtError.error);
            expected = String(expected);
        }

        this._assert({
            ok: passed,
            message : message || 'should throw',
            operator : 'throws',
            actual : caughtError && caughtError.error,
            expected : expected,
            error: !passed && caughtError && caughtError.error
        });
    };

    Test.prototype.doesNotThrow = function (fn, expected, message) {
        var caughtError;

        if(typeof expected === 'string'){
            message = expected;
            expected = undefined;
        }

        try{
            fn();
        }catch(error){
            caughtError = { error : error };
        }

        this._assert({
            ok: !caughtError,
            message: message || 'should not throw',
            operator: 'doesNotThrow',
            actual: caughtError && caughtError.error,
            expected: expected,
            error: caughtError && caughtError.error
        });
    };

    function runNextTest(){
        while(testsToRun.length){
            var nextTest = testsToRun.shift();
            nextTest._run();
            testsRun.push(nextTest);
        }
    }

    function complete(){
        var results = encodeResults(testsRun);

        if(testsToRun.length !== totalTests){
            // tests level problem
        }

        grape.emit('complete', results[0]);

        if(!grape.silent){
            console.log(results[0]);
            if(process && process.exit){
                process.exit(results[1]);
            }
        }
    }

    function begin(){
        if(!begun){
            begun = true;
            nextTick(runNextTest);
            nextTick(function(){
                if(!process || !process.on || grape.useTimeout){
                    setTimeout(complete, timeout);
                }else{
                    process.on('exit', complete);
                }
            });
        }
    }

    function grape(name, testFunction){
        if(only){
            return;
        }
        totalTests++;
        testsToRun.push(new Test(name, testFunction));
        begin();
    }
    grape.timeout = setTestTimeout;

    grape.only = function(name, testFunction){
        if(only){
            throw "There can be only one only";
        }
        only = true;
        testsToRun = [new Test(name, testFunction)];
        begin();
    };

    for(var key in EventEmitter.prototype){
        grape[key] = EventEmitter.prototype[key];
    }

    grape.createNewInstance = instantiate;
    grape.Test = Test;

    return grape;
}

module.exports = instantiate();
<commit_msg>Improved browser detection<commit_after>var EventEmitter = require('events').EventEmitter,
    deepEqual = require('deep-equal'),
    encodeResults = require('./results');

var nextTick = process && process.nextTick || setTimeout;

function instantiate(){
    var testsToRun = [],
        testsRun = [],
        totalTests = 0,
        totalAssersions = 0,
        completedAssersions = 0,
        begun = false,
        timeout = 0,
        only;

    function Test(name, testFunction){
        this._plan = 0;
        this._count = 0;
        this._assersions = [];
        this.name = name;
        this._testFunction = testFunction;
    }

    // Unused currently.
    // Test.prototype = Object.create(EventEmitter.prototype);
    // Test.prototype.constructor = Test;

    function setTestTimeout(time){
        timeout = Math.max(timeout, time);
    }

    Test.prototype.timeout = setTestTimeout;

    Test.prototype.comment = function (message) {
        // ToDo
    };

    Test.prototype.plan = function(ammount){
        this._plan = ammount;
    };

    Test.prototype._run = function(){
        var test = this;
        try {
            test._testFunction(this);
        }
        catch (err) {
            test.error(err);
        }
    };

    Test.prototype._assert = function(details){
        if(details.operator !== 'end'){
            this._count++;
        }
        if(this._ended){
            if(details.operator === 'end' || details.operator === 'fail'){
                return;
            }
            this.fail('asserted after test has ended');
        }
        this._assersions.push(details);
    };

    Test.prototype.end = function (message) {
        var ok = this._plan === this._count;

        if(this._ended){
            return;
        }

        if(ok){
            this._assert({
                ok: true,
                message: message,
                operator: 'end'
            });
        }else{
            this._assert({
                ok: false,
                expected: this._plan,
                actual: this._count,
                message: 'plan != count',
                operator: 'end'
            });
        }

        this._ended = true;
    };

    Test.prototype.error = function(error, message){
        this._assert({
            ok: !error,
            message : message || String(error),
            operator : 'error',
            actual : error
        });
    };

    Test.prototype.pass = function(message){
        this._assert({
            ok: true,
            message: message,
            operator: 'pass'
        });
    };

    Test.prototype.fail = function(message){
        this._assert({
            message: message,
            operator: 'fail'
        });
    };

    Test.prototype.skip = function(message){
        this._assert({
            message: message,
            skip: true,
            operator: 'skip'
        });
    };

    Test.prototype.ok = function(value, message){
        this._assert({
            actual: value,
            ok: !!value,
            message: message,
            operator: 'ok'
        });
    };

    Test.prototype.notOk = function(value, message){
        this._assert({
            actual: value,
            ok:!value,
            message: message,
            operator: 'notOk'
        });
    };

    Test.prototype.equal = function(value, expected, message){
        this._assert({
            actual: value,
            expected: expected,
            ok: value === expected,
            message: message,
            operator: 'equal'
        });
    };

    Test.prototype.notEqual = function(value, expected, message){
        this._assert({
            actual: value,
            expected: expected,
            ok: value !== expected,
            message: message,
            operator: 'notEqual'
        });
    };

    Test.prototype.deepEqual = function(value, expected, message){
        this._assert({
            actual: value,
            expected: expected,
            ok: deepEqual(value, expected, { strict: true }),
            message: message,
            operator: 'deepEqual'
        });
    };

    Test.prototype.deepLooseEqual = function(value, expected, message){
        this._assert({
            actual: value,
            expected: expected,
            ok: deepEqual(value, expected),
            message: message,
            operator: 'deepLooseEqual'
        });
    };

    Test.prototype.notDeepEqual = function(value, expected, message){
        this._assert({
            actual: value,
            expected: expected,
            ok: !deepEqual(value, expected, { strict: true }),
            message: message,
            operator: 'notDeepEqual'
        });
    };

    Test.prototype.notDeepLooseEqual = function(value, expected, message){
        this._assert({
            actual: value,
            expected: expected,
            ok: !deepEqual(value, expected),
            message: message,
            operator: 'notDeepLooseEqual'
        });
    };

    Test.prototype['throws'] = function (fn, expected, message) {
        var caughtError,
            passed;

        if(typeof expected === 'string'){
            message = expected;
            expected = undefined;
        }

        try{
            fn();
        }catch(error){
            caughtError = {error: error};
        }

        passed = caughtError;

        if(expected instanceof RegExp){
            passed = expected.test(caughtError && caughtError.error);
            expected = String(expected);
        }

        this._assert({
            ok: passed,
            message : message || 'should throw',
            operator : 'throws',
            actual : caughtError && caughtError.error,
            expected : expected,
            error: !passed && caughtError && caughtError.error
        });
    };

    Test.prototype.doesNotThrow = function (fn, expected, message) {
        var caughtError;

        if(typeof expected === 'string'){
            message = expected;
            expected = undefined;
        }

        try{
            fn();
        }catch(error){
            caughtError = { error : error };
        }

        this._assert({
            ok: !caughtError,
            message: message || 'should not throw',
            operator: 'doesNotThrow',
            actual: caughtError && caughtError.error,
            expected: expected,
            error: caughtError && caughtError.error
        });
    };

    function runNextTest(){
        while(testsToRun.length){
            var nextTest = testsToRun.shift();
            nextTest._run();
            testsRun.push(nextTest);
        }
    }

    function complete(){
        var results = encodeResults(testsRun);

        if(testsToRun.length !== totalTests){
            // tests level problem
        }

        grape.emit('complete', results[0]);

        if(!grape.silent){
            console.log(results[0]);
            if(process && process.exit){
                process.exit(results[1]);
            }
        }
    }

    function begin(){
        if(!begun){
            begun = true;
            nextTick(runNextTest);
            nextTick(function(){
                if(!process || process.title === 'browser' || grape.useTimeout){
                    setTimeout(complete, timeout);
                }else{
                    process.on('exit', complete);
                }
            });
        }
    }

    function grape(name, testFunction){
        if(only){
            return;
        }
        totalTests++;
        testsToRun.push(new Test(name, testFunction));
        begin();
    }
    grape.timeout = setTestTimeout;

    grape.only = function(name, testFunction){
        if(only){
            throw "There can be only one only";
        }
        only = true;
        testsToRun = [new Test(name, testFunction)];
        begin();
    };

    for(var key in EventEmitter.prototype){
        grape[key] = EventEmitter.prototype[key];
    }

    grape.createNewInstance = instantiate;
    grape.Test = Test;

    return grape;
}

module.exports = instantiate();
<|endoftext|>


<commit_before>/** section: Effects
 *  class s2.fx.Parallel < s2.fx.Base
 *
 *  Effect to execute several other effects in parallel.
**/
s2.fx.Parallel = Class.create(s2.fx.Base, {
  initialize: function($super, effects, options) {
    this.effects = effects || [];
    return $super(options);
  },

  setup: function() {
    this.effects.invoke('setup');
  },

  update: function(position) {
    this.effects.invoke('update', position);
  }
});<commit_msg>pass empty object if no options given<commit_after>/** section: Effects
 *  class s2.fx.Parallel < s2.fx.Base
 *
 *  Effect to execute several other effects in parallel.
**/
s2.fx.Parallel = Class.create(s2.fx.Base, {
  initialize: function($super, effects, options) {
    this.effects = effects || [];
    return $super(options || {});
  },

  setup: function() {
    this.effects.invoke('setup');
  },

  update: function(position) {
    this.effects.invoke('update', position);
  }
});<|endoftext|>


<commit_before>'use strict';

/**
 * controller for map on entry page
 */
analyticsControllers.controller('OLMapController', ['$scope', '$attrs',  '$location', 'EntrySvc',
    function($scope, $attrs, $location, EntrySvc) {
		var self = this;
		this.mapElement = null;
		this.slider = null;
		this.sliderTicks = null;
		this.map = null;
		this.citiesLayer = null;
		this.countriesLayer = null;

		this.init = function init (element) {
			self.mapElement = element;

			// create map
			self.map = new OpenLayers.Map('map', {theme: null});

			// create OSM layer
			var osm = new OpenLayers.Layer.OSM();
			// add target so we won't try to open in frame
			osm.attribution = "© OpenStreetMap contributors";
			osm.url = [
			           $location.protocol() + '://a.tile.openstreetmap.org/${z}/${x}/${y}.png',
			           $location.protocol() + '://b.tile.openstreetmap.org/${z}/${x}/${y}.png',
			           $location.protocol() + '://c.tile.openstreetmap.org/${z}/${x}/${y}.png'
			           ];

			self.map.addLayer(osm);
			self.map.zoomToMaxExtent();

			self.map.events.register('zoomend', this, function (event) {
				if (!self.citiesLayer) return; // if no layers no need to toggle.

		        var zLevel = self.map.getZoom();
		        if( zLevel < 4)
		        {
		        	// show countries
		        	self.citiesLayer.setVisibility(false);
		            self.countriesLayer.setVisibility(true);
		        }
		        else {
		        	// show cities
		        	self.citiesLayer.setVisibility(true);
		            self.countriesLayer.setVisibility(false);
		        }
		    });

			// create slider
			var d = new Date();
			var t = Math.floor(d.getTime() / 1000);
			self.slider = angular.element('#mapslider');
			self.slider.slider({
				max: t,
				min: t - 129600, // 36 hrs
				value: t,
				step: 10,
				change: self.sliderChangeHandler,
				slide: function (event, ui) {
					d = new Date(ui.value*1000);
					angular.element('#maptip .tooltip-inner').text(self.formatTime(d));
					angular.element('#maptip').css('left', $(ui.handle).css('left'));
					angular.element('#maptip').removeClass('hidden');
			    }
			});

			angular.element('#mapslider .ui-slider-handle').mouseleave(function() {
				angular.element('#maptip').addClass('hidden');
				angular.element('#maptip .tooltip-inner').text("");
				angular.element('#maptip').css('left', $(this).css('left'));
			});

			// create ticks
			self.sliderTicks = angular.element('#sliderticks');
			self.createSliderTicks(t-12960, t);

		};

		/**
		 * event handler for the slider drag
		 */
		this.sliderChangeHandler = function sliderChangeHandler(event, ui) {
			angular.element('#maptip').addClass('hidden');
			angular.element('#maptip .tooltip-inner').text("");
			self.getMapData(ui.value);
		};

		/**
		 * @param min, max - timestamp (seconds)
		 */
		this.createSliderTicks = function createSliderTicks(min, max) {
			// remove existing ticks
			self.sliderTicks.html('');
			// create new ticks
			var step, left, label, range = max-min, cnt = 6;
			for (var i = 0; i<cnt; i++) {
				step = i / cnt;
				label = min + range * step;
				var d = new Date(Math.floor(label*1000));
				label = self.formatTime(d);
				left = step * 100;
				self.createSliderTick(left + '%', label);
			}

		};

		this.createSliderTick = function createSliderTick(left, txt) {
			var element = document.createElement('div');
			element.style.left = left;
			element.classList.add('slidertick');
			var title = document.createElement('div');
			title.classList.add('title');
			title.innerHTML = txt;
			element.appendChild(title);
			self.sliderTicks[0].appendChild(element);
		};

		this.formatTime = function formatTime(d) {
			return d.toString().match(/(\d+:\d+):/)[1];
		};

		/**
		 * create a style map for the dots
		 * @param min the smallest data point value
		 * @param max the largest data point value
		 */
		this.createStyleMap = function createStyleMap(min, max) {
			var sRadius = 4;
			var lRadius = 10;
			// style
			var style = new OpenLayers.Style({
				pointRadius: "${radius}",
				fillColor: "#ffcc66",
				fillOpacity: 0.8,
				strokeColor: "#cc6633",
				strokeWidth: 2,
				strokeOpacity: 0.8,
				title : "${tooltip}"
			},
			{
				context: {
					radius: function(feature) {
						// data point size normalization
						if (max == min) return lRadius;
						return lRadius - ((max - feature.attributes.data) * (lRadius - sRadius) / (max - min));
					},
					tooltip: function(feature) {
						return feature.attributes.text+ " " + feature.attributes.data;
					}
				}
			}
			);

			// create a styleMap with a custom default symbolizer
			var styleMap = new OpenLayers.StyleMap({
				"default": style,
				"select": {
					fillColor: "#8aeeef",
					strokeColor: "#32a8a9"
				}
			});

			return styleMap;
		};

		/**
		 * get data to display on map
		 * @param time unix timestamp (seconds). if null, current time is used.
		 */
		this.getMapData = function getMapData(time) {
			EntrySvc.getMap($scope.entryId, time).then(function(data) {
				self.displayData(data.objects);
			});

		};

		/**
		 * recreate data layers on map
		 * @param value array of KalturaGeoTimeLiveStats
		 */
		this.displayData = function displayData(value) {
			// remove existing layers
			if (self.citiesLayer) {
				self.map.removeLayer(self.citiesLayer);
				self.citiesLayer = null;
			}
			if (self.countriesLayer) {
				self.map.removeLayer(self.countriesLayer);
				self.countriesLayer = null;
			}
			if (value) {
				// process data to create new layers
				var countriesData = {};
				var features = new Array();
				var point;
				var min = 0;
				var max = 0;
				for ( var i = 0; i < value.length; i++) {
					var val = parseInt(value[i].audience, 10); // convert string to int
					if (val == 0) continue; // leave out points where audience is zero - we got them because they have plays)
					// accumulate data for country-level layer
					if (!countriesData[value[i].country.name]) {
						// init - keep whole value for lat/long
						countriesData[value[i].country.name] = value[i];
						countriesData[value[i].country.name]['audience'] = val;
					}
					else {
						// sum audience
						countriesData[value[i].country.name]['audience'] += val;
					}
					point = new OpenLayers.Geometry.Point(value[i].city.longitude, value[i].city.latitude).transform('EPSG:4326', 'EPSG:3857');
					features[i] = new OpenLayers.Feature.Vector(
							point,
							{
								"data" : val,
								"text" : value[i].city.name
							}
							);

					// update cities min-max
					if (min == 0 || val < min) {
						min = val;
					}
					if (val > max) {
						max = val;
					}
				}

				// create cities layer
				var layer = self.citiesLayer = new OpenLayers.Layer.Vector('Cities', {
					"projection": "EPSG:3857",
					"visibility" : self.map.zoom > 3,
					"styleMap" : self.createStyleMap(min, max)
				});
				layer.addFeatures(features);
				self.map.addLayer(layer);

				// create countries layer
				min = max = 0;
				features = new Array();
				for (var key in countriesData) {
					var val = parseInt(countriesData[key].audience, 10);
					point = new OpenLayers.Geometry.Point(countriesData[key].country.longitude, countriesData[key].country.latitude).transform('EPSG:4326', 'EPSG:3857');
					features.push(new OpenLayers.Feature.Vector(
							point,
							{
								"data" : val,
								"text" : countriesData[key].country.name
							}
							));
					// update countries min-max
					if (min == 0 || val < min) {
						min = val;
					}
					if (val > max) {
						max = val;
					}
				}

				// create countries layer
				layer = self.countriesLayer = new OpenLayers.Layer.Vector('Countries', {
					"projection": "EPSG:3857",
					"visibility" : self.map.zoom < 4,
					"styleMap" : self.createStyleMap(min, max)
				});
				layer.addFeatures(features);
				self.map.addLayer(layer);

				layer.refresh();
			}
		};

		this.adjustSlider = function adjustSlider(oldmax, newmax, val) {
			var n = newmax - oldmax;
			var min = self.slider.slider("option", "min");
			self.slider.slider("option", "max", newmax);
			self.slider.slider("option", "min", min + n);
			if (val) {
				self.slider.slider("option", "value", val);
			}
			self.createSliderTicks(min+n, newmax);
		};

		/**
		 * event handler for main screen update interval
		 * @param event
		 * @param timestamp (seconds)
		 */
		this.updateScreenHandler = function updateScreenHandler(event, time) {
			time -= 60; // we only have data about 60 seconds back, so we adjust what we got
			var val = self.slider.slider("option", "value"); // current slider value
			var max = self.slider.slider("option", "max"); // max slider value
			if (val == max) {
				// we are at the right edge, auto update
				//self.getMapData(time); // adjusting the slider will also trigger the update
				// update scrollbar and handle (keep handle on right edge)
				self.adjustSlider(max, time, time);
			}
			else {
				// update range
				self.adjustSlider(max, time);
			}
		};

		this.timeBoundsSetHandler = function timeBoundsSetHandler(event, start, end) {
			start = parseInt(start, 10);
			end = parseInt(end, 10);
			var val = self.slider.slider("option", "value"); // current slider value
			var max = self.slider.slider("option", "max"); // max slider value
			if (val == max) {
				// we are at the right edge, stay there
				self.slider.slider("option", "max", end);
				self.slider.slider("option", "min", start);
				self.slider.slider("option", "value", end);
			}
			else {
				var updateVal = false;
				if (val < start) {
					val = start;
					updateVal = true;
				}
				if (val > end) {
					val = end;
					updateVal = true;
				}
				self.slider.slider("option", "max", end);
				self.slider.slider("option", "min", start);
				if (updateVal) {
					self.slider.slider("option", "value", val);
				}
			}
			self.createSliderTicks(start, end);
		};

		$scope.$on('setupScreen', self.updateScreenHandler);
		$scope.$on('updateScreen', self.updateScreenHandler);
		$scope.$on('TimeBoundsSet', self.timeBoundsSetHandler);

}]);

<commit_msg>PLAT-2411 update slider on gototime<commit_after>'use strict';

/**
 * controller for map on entry page
 */
analyticsControllers.controller('OLMapController', ['$scope', '$attrs',  '$location', 'EntrySvc',
    function($scope, $attrs, $location, EntrySvc) {
		var self = this;
		this.mapElement = null;
		this.slider = null;
		this.sliderTicks = null;
		this.map = null;
		this.citiesLayer = null;
		this.countriesLayer = null;

		this.init = function init (element) {
			self.mapElement = element;

			// create map
			self.map = new OpenLayers.Map('map', {theme: null});

			// create OSM layer
			var osm = new OpenLayers.Layer.OSM();
			// add target so we won't try to open in frame
			osm.attribution = "© OpenStreetMap contributors";
			osm.url = [
			           $location.protocol() + '://a.tile.openstreetmap.org/${z}/${x}/${y}.png',
			           $location.protocol() + '://b.tile.openstreetmap.org/${z}/${x}/${y}.png',
			           $location.protocol() + '://c.tile.openstreetmap.org/${z}/${x}/${y}.png'
			           ];

			self.map.addLayer(osm);
			self.map.zoomToMaxExtent();

			self.map.events.register('zoomend', this, function (event) {
				if (!self.citiesLayer) return; // if no layers no need to toggle.

		        var zLevel = self.map.getZoom();
		        if( zLevel < 4)
		        {
		        	// show countries
		        	self.citiesLayer.setVisibility(false);
		            self.countriesLayer.setVisibility(true);
		        }
		        else {
		        	// show cities
		        	self.citiesLayer.setVisibility(true);
		            self.countriesLayer.setVisibility(false);
		        }
		    });

			// create slider
			var d = new Date();
			var t = Math.floor(d.getTime() / 1000);
			self.slider = angular.element('#mapslider');
			self.slider.slider({
				max: t,
				min: t - 129600, // 36 hrs
				value: t,
				step: 10,
				change: self.sliderChangeHandler,
				slide: function (event, ui) {
					d = new Date(ui.value*1000);
					angular.element('#maptip .tooltip-inner').text(self.formatTime(d));
					angular.element('#maptip').css('left', $(ui.handle).css('left'));
					angular.element('#maptip').removeClass('hidden');
			    }
			});

			angular.element('#mapslider .ui-slider-handle').mouseleave(function() {
				angular.element('#maptip').addClass('hidden');
				angular.element('#maptip .tooltip-inner').text("");
				angular.element('#maptip').css('left', $(this).css('left'));
			});

			// create ticks
			self.sliderTicks = angular.element('#sliderticks');
			self.createSliderTicks(t-12960, t);

		};

		$scope.$on('gotoTime', function (event, time) {
			// show required time data on map
			self.slider.slider("option", "value", time);
		});

		/**
		 * event handler for the slider drag
		 */
		this.sliderChangeHandler = function sliderChangeHandler(event, ui) {
			angular.element('#maptip').addClass('hidden');
			angular.element('#maptip .tooltip-inner').text("");
			self.getMapData(ui.value);
		};

		/**
		 * @param min, max - timestamp (seconds)
		 */
		this.createSliderTicks = function createSliderTicks(min, max) {
			// remove existing ticks
			self.sliderTicks.html('');
			// create new ticks
			var step, left, label, range = max-min, cnt = 6;
			for (var i = 0; i<cnt; i++) {
				step = i / cnt;
				label = min + range * step;
				var d = new Date(Math.floor(label*1000));
				label = self.formatTime(d);
				left = step * 100;
				self.createSliderTick(left + '%', label);
			}

		};

		this.createSliderTick = function createSliderTick(left, txt) {
			var element = document.createElement('div');
			element.style.left = left;
			element.classList.add('slidertick');
			var title = document.createElement('div');
			title.classList.add('title');
			title.innerHTML = txt;
			element.appendChild(title);
			self.sliderTicks[0].appendChild(element);
		};

		this.formatTime = function formatTime(d) {
			return d.toString().match(/(\d+:\d+):/)[1];
		};

		/**
		 * create a style map for the dots
		 * @param min the smallest data point value
		 * @param max the largest data point value
		 */
		this.createStyleMap = function createStyleMap(min, max) {
			var sRadius = 4;
			var lRadius = 10;
			// style
			var style = new OpenLayers.Style({
				pointRadius: "${radius}",
				fillColor: "#ffcc66",
				fillOpacity: 0.8,
				strokeColor: "#cc6633",
				strokeWidth: 2,
				strokeOpacity: 0.8,
				title : "${tooltip}"
			},
			{
				context: {
					radius: function(feature) {
						// data point size normalization
						if (max == min) return lRadius;
						return lRadius - ((max - feature.attributes.data) * (lRadius - sRadius) / (max - min));
					},
					tooltip: function(feature) {
						return feature.attributes.text+ " " + feature.attributes.data;
					}
				}
			}
			);

			// create a styleMap with a custom default symbolizer
			var styleMap = new OpenLayers.StyleMap({
				"default": style,
				"select": {
					fillColor: "#8aeeef",
					strokeColor: "#32a8a9"
				}
			});

			return styleMap;
		};

		/**
		 * get data to display on map
		 * @param time unix timestamp (seconds). if null, current time is used.
		 */
		this.getMapData = function getMapData(time) {
			EntrySvc.getMap($scope.entryId, time).then(function(data) {
				self.displayData(data.objects);
			});

		};

		/**
		 * recreate data layers on map
		 * @param value array of KalturaGeoTimeLiveStats
		 */
		this.displayData = function displayData(value) {
			// remove existing layers
			if (self.citiesLayer) {
				self.map.removeLayer(self.citiesLayer);
				self.citiesLayer = null;
			}
			if (self.countriesLayer) {
				self.map.removeLayer(self.countriesLayer);
				self.countriesLayer = null;
			}
			if (value) {
				// process data to create new layers
				var countriesData = {};
				var features = new Array();
				var point;
				var min = 0;
				var max = 0;
				for ( var i = 0; i < value.length; i++) {
					var val = parseInt(value[i].audience, 10); // convert string to int
					if (val == 0) continue; // leave out points where audience is zero - we got them because they have plays)
					// accumulate data for country-level layer
					if (!countriesData[value[i].country.name]) {
						// init - keep whole value for lat/long
						countriesData[value[i].country.name] = value[i];
						countriesData[value[i].country.name]['audience'] = val;
					}
					else {
						// sum audience
						countriesData[value[i].country.name]['audience'] += val;
					}
					point = new OpenLayers.Geometry.Point(value[i].city.longitude, value[i].city.latitude).transform('EPSG:4326', 'EPSG:3857');
					features[i] = new OpenLayers.Feature.Vector(
							point,
							{
								"data" : val,
								"text" : value[i].city.name
							}
							);

					// update cities min-max
					if (min == 0 || val < min) {
						min = val;
					}
					if (val > max) {
						max = val;
					}
				}

				// create cities layer
				var layer = self.citiesLayer = new OpenLayers.Layer.Vector('Cities', {
					"projection": "EPSG:3857",
					"visibility" : self.map.zoom > 3,
					"styleMap" : self.createStyleMap(min, max)
				});
				layer.addFeatures(features);
				self.map.addLayer(layer);

				// create countries layer
				min = max = 0;
				features = new Array();
				for (var key in countriesData) {
					var val = parseInt(countriesData[key].audience, 10);
					point = new OpenLayers.Geometry.Point(countriesData[key].country.longitude, countriesData[key].country.latitude).transform('EPSG:4326', 'EPSG:3857');
					features.push(new OpenLayers.Feature.Vector(
							point,
							{
								"data" : val,
								"text" : countriesData[key].country.name
							}
							));
					// update countries min-max
					if (min == 0 || val < min) {
						min = val;
					}
					if (val > max) {
						max = val;
					}
				}

				// create countries layer
				layer = self.countriesLayer = new OpenLayers.Layer.Vector('Countries', {
					"projection": "EPSG:3857",
					"visibility" : self.map.zoom < 4,
					"styleMap" : self.createStyleMap(min, max)
				});
				layer.addFeatures(features);
				self.map.addLayer(layer);

				layer.refresh();
			}
		};

		this.adjustSlider = function adjustSlider(oldmax, newmax, val) {
			var n = newmax - oldmax;
			var min = self.slider.slider("option", "min");
			self.slider.slider("option", "max", newmax);
			self.slider.slider("option", "min", min + n);
			if (val) {
				self.slider.slider("option", "value", val);
			}
			self.createSliderTicks(min+n, newmax);
		};

		/**
		 * event handler for main screen update interval
		 * @param event
		 * @param timestamp (seconds)
		 */
		this.updateScreenHandler = function updateScreenHandler(event, time) {
			time -= 60; // we only have data about 60 seconds back, so we adjust what we got
			var val = self.slider.slider("option", "value"); // current slider value
			var max = self.slider.slider("option", "max"); // max slider value
			if (val == max) {
				// we are at the right edge, auto update
				//self.getMapData(time); // adjusting the slider will also trigger the update
				// update scrollbar and handle (keep handle on right edge)
				self.adjustSlider(max, time, time);
			}
			else {
				// update range
				self.adjustSlider(max, time);
			}
		};

		this.timeBoundsSetHandler = function timeBoundsSetHandler(event, start, end) {
			start = parseInt(start, 10);
			end = parseInt(end, 10);
			var val = self.slider.slider("option", "value"); // current slider value
			var max = self.slider.slider("option", "max"); // max slider value
			if (val == max) {
				// we are at the right edge, stay there
				self.slider.slider("option", "max", end);
				self.slider.slider("option", "min", start);
				self.slider.slider("option", "value", end);
			}
			else {
				var updateVal = false;
				if (val < start) {
					val = start;
					updateVal = true;
				}
				if (val > end) {
					val = end;
					updateVal = true;
				}
				self.slider.slider("option", "max", end);
				self.slider.slider("option", "min", start);
				if (updateVal) {
					self.slider.slider("option", "value", val);
				}
			}
			self.createSliderTicks(start, end);
		};

		$scope.$on('setupScreen', self.updateScreenHandler);
		$scope.$on('updateScreen', self.updateScreenHandler);
		$scope.$on('TimeBoundsSet', self.timeBoundsSetHandler);

}]);

<|endoftext|>


<commit_before>/*
 * Copyright 2006 Shinya Kasatani
 *
 * 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.
 */

if (!this.SeleniumIDE) this.SeleniumIDE = {};

SeleniumIDE.Preferences = {
    TEST_BRANCH: Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("extensions.selenium-ide.test."),
    branch: Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("extensions.selenium-ide."),

    // use test branch for unit tests
    useTestBranch: function() {
        this.branch = this.TEST_BRANCH;
    },

    getString: function(name, defaultValue) {
        if (this.branch && this.branch.prefHasUserValue(name)) {
            return this.branch.getComplexValue(name, Components.interfaces.nsISupportsString).data;
        } else {
            return defaultValue;
        }
    },

    setString: function(name, value) {
        var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
        str.data = value;
        this.branch.setComplexValue(name, Components.interfaces.nsISupportsString, str);
    },

    getBool: function(name, defaultValue) {
        if (this.branch && this.branch.prefHasUserValue(name)) {
            return this.branch.getBoolPref(name);
        } else {
            return defaultValue;
        }
    },

    setBool: function(name, value) {
        this.branch.setBoolPref(name, value);
    },

    getArray: function(name) {
        var length = this.getString(name + ".length");
        if (length == null) return [];
        var value = [];
        for (var i = 0; i < length; i++) {
            value.push(this.getString(name + "." + i));
        }
        return value;
    },

    setArray: function(name, value) {
        this.setString(name + ".length", value.length);
        for (var i = 0; i < value.length; i++) {
            this.setString(name + "." + i, value[i]);
        }
    },

    getType: function(name) {
        return this.branch.getPrefType(name);
    },

    load: function() {
        var options = {};
        var name;
        for (name in this.DEFAULT_OPTIONS) {
            options[name] = this.DEFAULT_OPTIONS[name];
        }
        var names = this.branch.getChildList('', []);
        for (var i = 0; i < names.length; i++) {
            name = names[i];
            if (this.getType(name) == this.branch.PREF_BOOL) {
                options[name] = this.getBool(name);
            } else {
                options[name] = this.getString(name, this.DEFAULT_OPTIONS[name] || '');
            }
        }
        return options;
    },

    save: function(options, prop_name) {
        if (prop_name) {
            this.setString(prop_name, options[prop_name]);
        } else {
            this.branch.deleteBranch("formats");
            var name;
            for (name in options) {
                this.setString(name, options[name]);
            }
        }
    }
}

SeleniumIDE.Preferences.DEFAULT_OPTIONS = {
    encoding: "UTF-8",

    // This should be called 'userExtensionsPaths', but it is left for backward compatibility.
    userExtensionsURL:
    "",

    ideExtensionsPaths:
    "",

    rememberBaseURL:
    "true",

    baseURL:
    "",

    recordAssertTitle:
    "false",

    timeout:
    "30000",

    recordAbsoluteURL:
    "false",

    pluginProvidedUserExtensions:
    "",

    pluginProvidedFormatters:
    "",

    showDeveloperTools:
    "false"
};

<commit_msg>AdamGoucher - oh ya. adding 'plugins' to the default preferences<commit_after>/*
 * Copyright 2006 Shinya Kasatani
 *
 * 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.
 */

if (!this.SeleniumIDE) this.SeleniumIDE = {};

SeleniumIDE.Preferences = {
    TEST_BRANCH: Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("extensions.selenium-ide.test."),
    branch: Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("extensions.selenium-ide."),

    // use test branch for unit tests
    useTestBranch: function() {
        this.branch = this.TEST_BRANCH;
    },

    getString: function(name, defaultValue) {
        if (this.branch && this.branch.prefHasUserValue(name)) {
            return this.branch.getComplexValue(name, Components.interfaces.nsISupportsString).data;
        } else {
            return defaultValue;
        }
    },

    setString: function(name, value) {
        var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
        str.data = value;
        this.branch.setComplexValue(name, Components.interfaces.nsISupportsString, str);
    },

    getBool: function(name, defaultValue) {
        if (this.branch && this.branch.prefHasUserValue(name)) {
            return this.branch.getBoolPref(name);
        } else {
            return defaultValue;
        }
    },

    setBool: function(name, value) {
        this.branch.setBoolPref(name, value);
    },

    getArray: function(name) {
        var length = this.getString(name + ".length");
        if (length == null) return [];
        var value = [];
        for (var i = 0; i < length; i++) {
            value.push(this.getString(name + "." + i));
        }
        return value;
    },

    setArray: function(name, value) {
        this.setString(name + ".length", value.length);
        for (var i = 0; i < value.length; i++) {
            this.setString(name + "." + i, value[i]);
        }
    },

    getType: function(name) {
        return this.branch.getPrefType(name);
    },

    load: function() {
        var options = {};
        var name;
        for (name in this.DEFAULT_OPTIONS) {
            options[name] = this.DEFAULT_OPTIONS[name];
        }
        var names = this.branch.getChildList('', []);
        for (var i = 0; i < names.length; i++) {
            name = names[i];
            if (this.getType(name) == this.branch.PREF_BOOL) {
                options[name] = this.getBool(name);
            } else {
                options[name] = this.getString(name, this.DEFAULT_OPTIONS[name] || '');
            }
        }
        return options;
    },

    save: function(options, prop_name) {
        if (prop_name) {
            this.setString(prop_name, options[prop_name]);
        } else {
            this.branch.deleteBranch("formats");
            var name;
            for (name in options) {
                this.setString(name, options[name]);
            }
        }
    }
}

SeleniumIDE.Preferences.DEFAULT_OPTIONS = {
    encoding: "UTF-8",

    // This should be called 'userExtensionsPaths', but it is left for backward compatibility.
    userExtensionsURL:
    "",

    ideExtensionsPaths:
    "",

    rememberBaseURL:
    "true",

    baseURL:
    "",

    recordAssertTitle:
    "false",

    timeout:
    "30000",

    recordAbsoluteURL:
    "false",

    pluginProvidedUserExtensions:
    "",

    pluginProvidedFormatters:
    "",

    plugins:
    "",

    showDeveloperTools:
    "false"
};

<|endoftext|>


<commit_before>var angularApp = angular.module('angular', ['ngAnimate', 'ngRoute', 'LocalStorageModule', 'ngMaterial'])

angularApp.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){

    $routeProvider
    .when('/', {
        templateUrl: 'views/home.html',
        controller: "homeController"
    })
    .when('/about', {
        templateUrl: "views/about.html",
        controller: "mainController"
    })
    .when('/projects', {
        templateUrl: "views/projects.html",
        controller: "mainController"
    })
    .when('/contact', {
        templateUrl: "views/contact.html",
        controller: 'mainController'
    })
    .otherwise('/404', {
        templateUrl: 'views/404.html'
    })

    $locationProvider.hashPrefix('!')

}])
.config(['localStorageServiceProvider', function(localStorageServiceProvider){
    localStorageServiceProvider.setPrefix('localStorage')
}])

angularApp.controller('homeController', ['$scope', 'localStorageService', function($scope, localStorageService){
    localStorageService.set('view', 'home');
    $scope.currentPage = localStorageService.get('view')

}])

angularApp.controller('mainController', ['$scope', '$routeParams', 'localStorageService', '$mdBottomSheet', '$mdDialog', function($scope, $routeParams, localStorageService, $mdBottomSheet, $mdDialog){

    $scope.currentPage = localStorageService.get('view') ? localStorageService.get('view') : localStorageService.set('view', 'about');
    console.log('view:', localStorageService.get('view'))
    console.log('currentPage:', $scope.currentPage)
    $scope.changePage = function(view){
        switch(view){
            case "home":
                localStorageService.set('view', 'home');
                $scope.currentPage = localStorageService.get('view');
                break;
            case "about":
                localStorageService.set('view', 'about');
                $scope.currentPage = localStorageService.get('view');
                break;
            case "projects":
                localStorageService.set('view', 'projects');
                $scope.currentPage = localStorageService.get('view');
                break;
            case "contact":
                localStorageService.set('view', 'contact');
                $scope.currentPage = localStorageService.get('view');
                break;
        }
        console.log($scope.currentPage)
    }
    $scope.activeView = function(view){
        if(localStorageService.get('view') == view) return 'active'
        }
    $scope.openBottomSheet = function(){
        $mdBottomSheet.show({
            template: '<md-bottom-sheet>' +
                      '
' +
                       '
' +
                       'JavaScript, Ruby, HTML5, CSS3, Rails, Sails.js, Angular JS, Express.js, Postgres, MongoDB, Sequelize, Active Record, jQuery, Git/GitHub, Heroku, Bootstrap, MaterializeCSS, Angular Material, Twilio, Bcrypt.' +
                       '
' +
                       '
' +
                       '</md-bottom-sheet>',
            controller: 'mainController'

        })
    }
    $scope.openDialog = function(){
        $mdDialog.show({
            template: '<md-dialog><md-card><md-card-content>here is th informations</md-card-content></md-card></md-dialog>',
            controller: 'otherController',
            clickOutsideToClose: true,
            escapeToClose: true
        })
    }

}])
angularApp.controller('otherController', ['$scope', function($scope){

}])<commit_msg>moved languages to partial<commit_after>var angularApp = angular.module('angular', ['ngAnimate', 'ngRoute', 'LocalStorageModule', 'ngMaterial'])

angularApp.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){

    $routeProvider
    .when('/', {
        templateUrl: 'views/home.html',
        controller: "homeController"
    })
    .when('/about', {
        templateUrl: "views/about.html",
        controller: "mainController"
    })
    .when('/projects', {
        templateUrl: "views/projects.html",
        controller: "mainController"
    })
    .when('/contact', {
        templateUrl: "views/contact.html",
        controller: 'mainController'
    })
    .otherwise('/404', {
        templateUrl: 'views/404.html'
    })

    $locationProvider.hashPrefix('!')

}])
.config(['localStorageServiceProvider', function(localStorageServiceProvider){
    localStorageServiceProvider.setPrefix('localStorage')
}])

angularApp.controller('homeController', ['$scope', 'localStorageService', function($scope, localStorageService){
    localStorageService.set('view', 'home');
    $scope.currentPage = localStorageService.get('view')

}])

angularApp.controller('mainController', ['$scope', '$routeParams', 'localStorageService', '$mdBottomSheet', '$mdDialog', function($scope, $routeParams, localStorageService, $mdBottomSheet, $mdDialog){

    $scope.currentPage = localStorageService.get('view') ? localStorageService.get('view') : localStorageService.set('view', 'about');
    console.log('view:', localStorageService.get('view'))
    console.log('currentPage:', $scope.currentPage)
    $scope.changePage = function(view){
        switch(view){
            case "home":
                localStorageService.set('view', 'home');
                $scope.currentPage = localStorageService.get('view');
                break;
            case "about":
                localStorageService.set('view', 'about');
                $scope.currentPage = localStorageService.get('view');
                break;
            case "projects":
                localStorageService.set('view', 'projects');
                $scope.currentPage = localStorageService.get('view');
                break;
            case "contact":
                localStorageService.set('view', 'contact');
                $scope.currentPage = localStorageService.get('view');
                break;
        }
        console.log($scope.currentPage)
    }
    $scope.activeView = function(view){
        if(localStorageService.get('view') == view) return 'active'
        }
    $scope.openBottomSheet = function(){
        $mdBottomSheet.show({
            templateUrl: '../views/partials/languages.html',
            controller: 'mainController'

        })
    }
    $scope.openDialog = function(){
        $mdDialog.show({
            template: '<md-dialog><md-card><md-card-content>here is th informations</md-card-content></md-card></md-dialog>',
            controller: 'otherController',
            clickOutsideToClose: true,
            escapeToClose: true
        })
    }

}])
angularApp.controller('otherController', ['$scope', function($scope){

}])<|endoftext|>


<commit_before>describe('pglogicalReplicationFormController', function() {
  var $scope, $controller, $httpBackend, miqService;

  beforeEach(module('ManageIQ'));

  beforeEach(inject(function($rootScope, _$controller_, _$httpBackend_, _miqService_) {
    miqService = _miqService_;
    spyOn(miqService, 'miqFlash');
    spyOn(miqService, 'miqAjaxButton');
    spyOn(miqService, 'sparkleOn');
    spyOn(miqService, 'sparkleOff');
    $scope = $rootScope.$new();
    $scope.pglogicalReplicationModel = {
      replication_type: 'none',
      subscriptions   : [],
      exclusion_list  : ""
    };
    $httpBackend = _$httpBackend_;
    $controller = _$controller_('pglogicalReplicationFormController', {
      $scope: $scope,
      pglogicalReplicationFormId: 'new',
      miqService: miqService
    });
  }));

  beforeEach(inject(function(_$controller_) {
    var pglogicalReplicationFormResponse = {
      replication_type: 'none',
      subscriptions   : [],
      exclusion_list  : ""
    };
    $httpBackend.whenGET('/ops/pglogical_subscriptions_form_fields/new').respond(pglogicalReplicationFormResponse);
    $httpBackend.flush();
  }));

  afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });

  describe('initialization', function() {
    it('sets the replication type returned with http request', function() {
      expect($scope.pglogicalReplicationModel.replication_type).toEqual('none');
    });

    it('sets the subscriptions value returned with http request', function() {
      expect($scope.pglogicalReplicationModel.subscriptions).toEqual([]);
    });

    it('sets the exclusion list to the value returned by the http request', function() {
      expect($scope.pglogicalReplicationModel.exclusion_list).toEqual("");
    });
  });

  describe('#resetClicked', function() {
    beforeEach(function() {
      $scope.angularForm = {
        $setPristine: function (value){},
        $setUntouched: function (value){}
      };
      $scope.resetClicked();
    });

    it('sets total spinner count to be 1', function() {
      expect(miqService.sparkleOn.calls.count()).toBe(1);
    });
  });

  describe('#saveClicked', function() {
    beforeEach(function() {
      $scope.angularForm = {
        $setPristine: function (value){}
      };
      $scope.saveClicked();
    });

    it('turns the spinner on via the miqService', function() {
      expect(miqService.sparkleOn).toHaveBeenCalled();
    });

    it('delegates to miqService.miqAjaxButton', function() {
      var submitContent = {
        replication_type: $scope.pglogicalReplicationModel.replication_type,
        subscriptions:    $scope.pglogicalReplicationModel.subscriptions,
        exclusion_list:   $scope.pglogicalReplicationModel.exclusion_list};

      expect(miqService.miqAjaxButton).toHaveBeenCalledWith('/ops/pglogical_save_subscriptions/new?button=save', submitContent);
    });
  });
});
<commit_msg>Fix spec for replication form fix<commit_after>describe('pglogicalReplicationFormController', function() {
  var $scope, $controller, $httpBackend, miqService;

  beforeEach(module('ManageIQ'));

  beforeEach(inject(function($rootScope, _$controller_, _$httpBackend_, _miqService_) {
    miqService = _miqService_;
    spyOn(miqService, 'miqFlash');
    spyOn(miqService, 'sparkleOn');
    spyOn(miqService, 'sparkleOff');
    spyOn(window, "miqJqueryRequest");
    $scope = $rootScope.$new();
    $scope.pglogicalReplicationModel = {
      replication_type: 'none',
      subscriptions   : [],
      exclusion_list  : ""
    };
    $httpBackend = _$httpBackend_;
    $controller = _$controller_('pglogicalReplicationFormController', {
      $scope: $scope,
      pglogicalReplicationFormId: 'new',
      miqService: miqService
    });
  }));

  beforeEach(inject(function(_$controller_) {
    var pglogicalReplicationFormResponse = {
      replication_type: 'none',
      subscriptions   : [],
      exclusion_list  : ""
    };
    $httpBackend.whenGET('/ops/pglogical_subscriptions_form_fields/new').respond(pglogicalReplicationFormResponse);
    $httpBackend.flush();
  }));

  afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });

  describe('initialization', function() {
    it('sets the replication type returned with http request', function() {
      expect($scope.pglogicalReplicationModel.replication_type).toEqual('none');
    });

    it('sets the subscriptions value returned with http request', function() {
      expect($scope.pglogicalReplicationModel.subscriptions).toEqual([]);
    });

    it('sets the exclusion list to the value returned by the http request', function() {
      expect($scope.pglogicalReplicationModel.exclusion_list).toEqual("");
    });
  });

  describe('#resetClicked', function() {
    beforeEach(function() {
      $scope.angularForm = {
        $setPristine: function (value){},
        $setUntouched: function (value){}
      };
      $scope.resetClicked();
    });

    it('sets total spinner count to be 1', function() {
      expect(miqService.sparkleOn.calls.count()).toBe(1);
    });
  });

  describe('#saveClicked', function() {
    beforeEach(function() {
      $scope.angularForm = {
        $setPristine: function (value){}
      };
      $scope.saveClicked();
    });

    it('turns the spinner on via the miqService', function() {
      expect(miqService.sparkleOn).toHaveBeenCalled();
    });

    it('delegates to miqJqueryRequest', function() {
      var submitContent = {
        replication_type: $scope.pglogicalReplicationModel.replication_type,
        subscriptions:    $scope.pglogicalReplicationModel.subscriptions,
        exclusion_list:   $scope.pglogicalReplicationModel.exclusion_list};

      expect(miqJqueryRequest).toHaveBeenCalledWith('/ops/pglogical_save_subscriptions/new?button=save', {data: submitContent, complete: true});
    });
  });
});
<|endoftext|>