<commit_before>constructor(){
  super({
    requiresPageReload: true
  })
}

enabled(){
  // elements & data
  this.css = null;
  this.htmlModal = null;
  this.config = null;

  this.defaultConfig = {
    columnWidth: "310px",
    fontSize: "12px",
    hideTweetActions: true,
    moveTweetActionsToRight: true,
    revertReplies: false,
    roundedScrollBars: false,
    smallComposeTextSize: false,
    optimizeAnimations: true,
    avatarRadius: 10
  };

  // modal dialog loading
  $TDP.readFileRoot(this.$token, "modal.html").then(contents => {
    this.htmlModal = contents;
  }).catch(err => {
    $TD.alert("error", "Problem loading data for the design edit plugin: "+err.message);
  });

  // configuration
  const configFile = "config.json";
  this.tmpConfig = null;

  var loadConfigObject = obj => {
    this.tmpConfig = obj || {};

    if (TD.ready){
      this.onAppReady();
    }

    this.injectDeciderReplyHook(this.tmpConfig.revertReplies);
  };

  this.onAppReady = () => {
    if (this.tmpConfig !== null){
      this.config = $.extend(this.defaultConfig, this.tmpConfig);
      this.tmpConfig = null;
      this.reinjectAll();
    }
  };

  $TDP.checkFileExists(this.$token, configFile).then(exists => {
    if (!exists){
      loadConfigObject(null);
      $TDP.writeFile(this.$token, configFile, JSON.stringify(this.defaultConfig));
    }
    else{
      $TDP.readFile(this.$token, configFile, true).then(contents => {
        try{
          loadConfigObject(JSON.parse(contents));
        }catch(err){
          loadConfigObject(null);
        }
      }).catch(err => {
        loadConfigObject(null);
        $TD.alert("error", "Problem loading configuration for the design edit plugin: "+err.message);
      });
    }
  });

  this.saveConfig = () => {
    $TDP.writeFile(this.$token, configFile, JSON.stringify(this.config)).catch(err => {
      $TD.alert("error", "Problem saving configuration for the design edit plugin: "+err.message);
    });
  };

  // settings click event
  this.onSettingsMenuClickedEvent = () => {
    if (this.htmlModal === null || this.config === null){
      return;
    }

    setTimeout(() => {
      let menu = $(".js-dropdown-content").children("ul").first();
      if (menu.length === 0)return;

      let itemTD = menu.children("[data-std]").first();
      if (itemTD.length === 0)return;

      if (!itemTD.prev().hasClass("drp-h-divider")){
        itemTD.before('

');
      }

      let itemEditDesign = $('
Edit layout & design
');
      itemTD.after(itemEditDesign);

      itemEditDesign.on("click", "a", function(){
        new customDesignModal();
      });

      itemEditDesign.hover(function(){
        $(this).addClass("is-selected");
      }, function(){
        $(this).removeClass("is-selected");
      });
    }, 1);
  };

  // modal dialog setup
  var me = this;

  var updateKey = function(key, value){
    me.config[key] = value;

    setTimeout(function(){
      me.saveConfig();
      me.reinjectAll();
    }, 1); // delays the slight lag caused by saving and reinjection
  };

  var customDesignModal = TD.components.BaseModal.extend(function(){
    let modal = $("#td-design-plugin-modal");
    this.setAndShowContainer(modal, false);

    // RELOAD
    this.reloadPage = false;
    modal.find("[data-td-reload]").click(() => this.reloadPage = true);

    // UI EVENTS
    let getTextForCustom = function(key){
      return "Custom ("+me.config[key]+")";
    };

    modal.find("[data-td-key]").each(function(){
      let item = $(this);
      let tag = item.prop("tagName");
      let key = item.attr("data-td-key");

      // INPUTS
      if (tag === "INPUT"){
        let type = item.attr("type");

        if (type === "checkbox"){
          item.prop("checked", me.config[key]);

          item.change(function(){
            updateKey(key, item.prop("checked"));
          });
        }
      }
      // SELECTS
      else if (tag === "SELECT"){
        if (!item.val(me.config[key]).val()){
          let custom = item.find("option[value='custom']");

          if (custom.length === 1){
            item.val("custom");
            custom.text(getTextForCustom(key));
          }
        }

        item.change(function(){ // TODO change doesn't fire when Custom is already selected
          let val = item.val();

          if (val === "custom"){
            val = prompt("Enter custom value:");

            if (val){
              updateKey(key, val);
              item.find("option[value='custom']").text(getTextForCustom(key));
            }
          }
          else{
            updateKey(key, item.val());
          }
        });
      }
      // CUSTOM ELEMENTS
      else{
        let value = item.attr("data-td-value");

        if (value == me.config[key]){
          item.addClass("selected");
        }

        item.click(function(){
          modal.find("[data-td-key='"+key+"']").removeClass("selected");
          item.addClass("selected");
          updateKey(key, value);
        });
      }
    });

    // THEMES
    modal.find("[data-td-theme='"+TD.settings.getTheme()+"']").prop("checked", true);

    modal.find("[data-td-theme]").change(function(){
      setTimeout(function(){
        TD.settings.setTheme($(this).attr("data-td-theme"));
        $(document).trigger("uiToggleTheme");
      }, 1);
    });
  }).methods({
    _render: () => $(this.htmlModal),
    destroy: function(){
      if (this.reloadPage){
        location.reload();
        return;
      }

      $("#td-design-plugin-modal").hide();
      this.supr();
    }
  });

  // decider injections
  this.injectDeciderReplyHook = enable => {
    let prevFunc = TD.decider.updateFromBackend;

    TD.decider.updateFromBackend = function(data){
      data["simplified_replies"] = !enable;
      return prevFunc.apply(this, arguments);
    };

    TD.decider.updateForGuestId();
    this.$pluginSettings.requiresPageReload = enable;
  };

  // css and layout injection
  this.resetDesign = () => {
    if (this.css){
      this.css.remove();
    }

    this.css = window.TDPF_createCustomStyle(this);
  };

  this.reinjectAll = () => {
    this.resetDesign();

    this.css.insert("#general_settings .cf { display: none !important }");
    this.css.insert("#general_settings .divider-bar::after { display: inline-block; padding-top: 10px; line-height: 17px; content: 'Use the new | Edit layout & design | option in the Settings to modify TweetDeck theme, column width, font size, and other features.' }");

    this.css.insert(".txt-base-smallest:not(.icon), .txt-base-largest:not(.icon) { font-size: "+this.config.fontSize+" !important }");
    this.css.insert(".avatar { border-radius: "+this.config.avatarRadius+"% !important }");

    if (this.config.hideTweetActions){
      this.css.insert(".tweet-action { opacity: 0; }");
      this.css.insert(".is-favorite .tweet-action, .is-retweet .tweet-action { opacity: 0.5; visibility: visible !important }");
      this.css.insert(".tweet:hover .tweet-action, .is-favorite .tweet-action[rel='favorite'], .is-retweet .tweet-action[rel='retweet'] { opacity: 1; visibility: visible !important }");
    }

    if (this.config.moveTweetActionsToRight){
      this.css.insert(".tweet-actions { float: right !important; width: auto !important }");
      this.css.insert(".tweet-actions > li:nth-child(4) { margin-right: 2px !important }");
    }

    if (this.config.smallComposeTextSize){
      this.css.insert(".compose-text { font-size: 12px !important; height: 120px !important }");
    }

    if (!this.config.roundedScrollBars){
      this.css.insert(".scroll-styled-v:not(.antiscroll-inner)::-webkit-scrollbar { width: 8px }");
      this.css.insert(".scroll-styled-h:not(.antiscroll-inner)::-webkit-scrollbar { height: 8px }");
      this.css.insert(".scroll-styled-v::-webkit-scrollbar-thumb { border-radius: 0 }");
      this.css.insert(".scroll-styled-h::-webkit-scrollbar-thumb { border-radius: 0 }");
      this.css.insert(".antiscroll-scrollbar { border-radius: 0 }");
      this.css.insert(".antiscroll-scrollbar-vertical { margin-top: 0 }");
      this.css.insert(".antiscroll-scrollbar-horizontal { margin-left: 0 }");
    }

    if (this.config.optimizeAnimations){
      this.css.insert(".app-content { will-change: transform }");
      this.css.insert(".column-holder { will-change: transform }");
    }

    if (this.config.columnWidth[0] === '/'){
      let cols = this.config.columnWidth.slice(1);

      this.css.insert(".column { width: calc((100vw - 205px) / "+cols+" - 8px) !important }");
      this.css.insert(".is-condensed .column { width: calc((100vw - 55px) / "+cols+" - 8px) !important }");
    }
    else{
      this.css.insert(".column { width: "+this.config.columnWidth+" !important }");
    }

    switch(this.config.columnWidth){
      case "/6":
        TD.settings.setColumnWidth("narrow");
        break;

      case "310px":
      case "/5":
        TD.settings.setColumnWidth("medium");
        break;

      default:
        TD.settings.setColumnWidth(parseInt(this.config.columnWidth, 10) < 310 ? "narrow" : "wide"); // NaN will give "wide"
        break;
    }

    switch(this.config.fontSize){
      case "13px": TD.settings.setFontSize("small"); break;
      case "14px": TD.settings.setFontSize("medium"); break;
      case "15px": TD.settings.setFontSize("large"); break;
      default: TD.settings.setFontSize(parseInt(this.config.fontSize, 10) >= 16 ? "largest" : "smallest"); break;
    }

    $TDP.injectIntoNotificationsBefore(this.$token, "css", "", [
      ""
    ].join(""));
  };

  this.uiShowActionsMenuEvent = () => {
    if (this.config.moveTweetActionsToRight){
      $(".js-dropdown.pos-r").toggleClass("pos-r pos-l");
    }
  };
}

ready(){
  // configuration
  switch(TD.settings.getColumnWidth()){
    case "wide": this.defaultConfig.columnWidth = "350px"; break;
    case "narrow": this.defaultConfig.columnWidth = "270px"; break;
  }

  switch(TD.settings.getFontSize()){
    case "small": this.defaultConfig.fontSize = "13px"; break;
    case "medium": this.defaultConfig.fontSize = "14px"; break;
    case "large": this.defaultConfig.fontSize = "15px"; break;
    case "largest": this.defaultConfig.fontSize = "16px"; break;
  }

  this.onAppReady();

  // layout events
  $(document).on("uiShowActionsMenu", this.uiShowActionsMenuEvent);

  // modal
  $("[data-action='settings-menu']").on("click", this.onSettingsMenuClickedEvent);
  $(".js-app").append('

');
}

disabled(){
  if (this.css){
    this.css.remove();
  }

  $(document).off("uiShowActionsMenu", this.uiShowActionsMenuEvent);

  $("[data-action='settings-menu']").off("click", this.onSettingsMenuClickedEvent);
  $("#td-design-plugin-modal").remove();
}
<commit_msg>Make edit-design plugin animation optimizations active only when focused<commit_after>constructor(){
  super({
    requiresPageReload: true
  })
}

enabled(){
  // elements & data
  this.css = null;
  this.htmlModal = null;
  this.config = null;

  this.defaultConfig = {
    columnWidth: "310px",
    fontSize: "12px",
    hideTweetActions: true,
    moveTweetActionsToRight: true,
    revertReplies: false,
    roundedScrollBars: false,
    smallComposeTextSize: false,
    optimizeAnimations: true,
    avatarRadius: 10
  };

  // modal dialog loading
  $TDP.readFileRoot(this.$token, "modal.html").then(contents => {
    this.htmlModal = contents;
  }).catch(err => {
    $TD.alert("error", "Problem loading data for the design edit plugin: "+err.message);
  });

  // configuration
  const configFile = "config.json";
  this.tmpConfig = null;

  var loadConfigObject = obj => {
    this.tmpConfig = obj || {};

    if (TD.ready){
      this.onAppReady();
    }

    this.injectDeciderReplyHook(this.tmpConfig.revertReplies);
  };

  this.onAppReady = () => {
    if (this.tmpConfig !== null){
      this.config = $.extend(this.defaultConfig, this.tmpConfig);
      this.tmpConfig = null;
      this.reinjectAll();
    }
  };

  $TDP.checkFileExists(this.$token, configFile).then(exists => {
    if (!exists){
      loadConfigObject(null);
      $TDP.writeFile(this.$token, configFile, JSON.stringify(this.defaultConfig));
    }
    else{
      $TDP.readFile(this.$token, configFile, true).then(contents => {
        try{
          loadConfigObject(JSON.parse(contents));
        }catch(err){
          loadConfigObject(null);
        }
      }).catch(err => {
        loadConfigObject(null);
        $TD.alert("error", "Problem loading configuration for the design edit plugin: "+err.message);
      });
    }
  });

  this.saveConfig = () => {
    $TDP.writeFile(this.$token, configFile, JSON.stringify(this.config)).catch(err => {
      $TD.alert("error", "Problem saving configuration for the design edit plugin: "+err.message);
    });
  };

  // settings click event
  this.onSettingsMenuClickedEvent = () => {
    if (this.htmlModal === null || this.config === null){
      return;
    }

    setTimeout(() => {
      let menu = $(".js-dropdown-content").children("ul").first();
      if (menu.length === 0)return;

      let itemTD = menu.children("[data-std]").first();
      if (itemTD.length === 0)return;

      if (!itemTD.prev().hasClass("drp-h-divider")){
        itemTD.before('

');
      }

      let itemEditDesign = $('
Edit layout & design
');
      itemTD.after(itemEditDesign);

      itemEditDesign.on("click", "a", function(){
        new customDesignModal();
      });

      itemEditDesign.hover(function(){
        $(this).addClass("is-selected");
      }, function(){
        $(this).removeClass("is-selected");
      });
    }, 1);
  };

  // modal dialog setup
  var me = this;

  var updateKey = function(key, value){
    me.config[key] = value;

    setTimeout(function(){
      me.saveConfig();
      me.reinjectAll();
    }, 1); // delays the slight lag caused by saving and reinjection
  };

  var customDesignModal = TD.components.BaseModal.extend(function(){
    let modal = $("#td-design-plugin-modal");
    this.setAndShowContainer(modal, false);

    // RELOAD
    this.reloadPage = false;
    modal.find("[data-td-reload]").click(() => this.reloadPage = true);

    // UI EVENTS
    let getTextForCustom = function(key){
      return "Custom ("+me.config[key]+")";
    };

    modal.find("[data-td-key]").each(function(){
      let item = $(this);
      let tag = item.prop("tagName");
      let key = item.attr("data-td-key");

      // INPUTS
      if (tag === "INPUT"){
        let type = item.attr("type");

        if (type === "checkbox"){
          item.prop("checked", me.config[key]);

          item.change(function(){
            updateKey(key, item.prop("checked"));
          });
        }
      }
      // SELECTS
      else if (tag === "SELECT"){
        if (!item.val(me.config[key]).val()){
          let custom = item.find("option[value='custom']");

          if (custom.length === 1){
            item.val("custom");
            custom.text(getTextForCustom(key));
          }
        }

        item.change(function(){ // TODO change doesn't fire when Custom is already selected
          let val = item.val();

          if (val === "custom"){
            val = prompt("Enter custom value:");

            if (val){
              updateKey(key, val);
              item.find("option[value='custom']").text(getTextForCustom(key));
            }
          }
          else{
            updateKey(key, item.val());
          }
        });
      }
      // CUSTOM ELEMENTS
      else{
        let value = item.attr("data-td-value");

        if (value == me.config[key]){
          item.addClass("selected");
        }

        item.click(function(){
          modal.find("[data-td-key='"+key+"']").removeClass("selected");
          item.addClass("selected");
          updateKey(key, value);
        });
      }
    });

    // THEMES
    modal.find("[data-td-theme='"+TD.settings.getTheme()+"']").prop("checked", true);

    modal.find("[data-td-theme]").change(function(){
      setTimeout(function(){
        TD.settings.setTheme($(this).attr("data-td-theme"));
        $(document).trigger("uiToggleTheme");
      }, 1);
    });
  }).methods({
    _render: () => $(this.htmlModal),
    destroy: function(){
      if (this.reloadPage){
        location.reload();
        return;
      }

      $("#td-design-plugin-modal").hide();
      this.supr();
    }
  });

  // decider injections
  this.injectDeciderReplyHook = enable => {
    let prevFunc = TD.decider.updateFromBackend;

    TD.decider.updateFromBackend = function(data){
      data["simplified_replies"] = !enable;
      return prevFunc.apply(this, arguments);
    };

    TD.decider.updateForGuestId();
    this.$pluginSettings.requiresPageReload = enable;
  };

  // animation optimization
  this.optimizations = null;
  this.optimizationTimer = null;

  let clearOptimizationTimer = () => {
    if (this.optimizationTimer){
      window.clearTimeout(this.optimizationTimer);
      this.optimizationTimer = null;
    }
  };

  let runOptimizationTimer = timeout => {
    if (!this.optimizationTimer){
      this.optimizationTimer = window.setTimeout(optimizationTimerFunc, timeout);
    }
  };

  let optimizationTimerFunc = () => {
    this.optimizationTimer = null;

    if (this.config.optimizeAnimations){
      $TD.getIdleSeconds().then(s => {
        if (s >= 16){
          disableOptimizations();
          runOptimizationTimer(2500);
        }
        else{
          injectOptimizations();
        }
      });
    }
  };

  let injectOptimizations = force => {
    if (!this.optimizations && (force || document.hasFocus())){
      this.optimizations = window.TDPF_createCustomStyle(this);
      this.optimizations.insert(".app-content { will-change: transform }");
      this.optimizations.insert(".column-holder { will-change: transform }");
    }

    clearOptimizationTimer();
    runOptimizationTimer(10000);
  };

  let disableOptimizations = () => {
    if (this.optimizations){
      this.optimizations.remove();
      this.optimizations = null;
    }
  };

  this.onWindowFocusEvent = () => {
    if (this.config.optimizeAnimations){
      injectOptimizations(true);
    }
  };

  this.onWindowBlurEvent = () => {
    if (this.config.optimizeAnimations){
      disableOptimizations();
      clearOptimizationTimer();
    }
  };

  $(window).on("focus", this.onWindowFocusEvent);
  $(window).on("blur", this.onWindowBlurEvent);

  // css and layout injection
  this.resetDesign = () => {
    if (this.css){
      this.css.remove();
    }

    this.css = window.TDPF_createCustomStyle(this);
  };

  this.reinjectAll = () => {
    this.resetDesign();

    clearOptimizationTimer();

    if (this.config.optimizeAnimations){
      injectOptimizations();
    }
    else{
      disableOptimizations();
    }

    this.css.insert("#general_settings .cf { display: none !important }");
    this.css.insert("#general_settings .divider-bar::after { display: inline-block; padding-top: 10px; line-height: 17px; content: 'Use the new | Edit layout & design | option in the Settings to modify TweetDeck theme, column width, font size, and other features.' }");

    this.css.insert(".txt-base-smallest:not(.icon), .txt-base-largest:not(.icon) { font-size: "+this.config.fontSize+" !important }");
    this.css.insert(".avatar { border-radius: "+this.config.avatarRadius+"% !important }");

    if (this.config.hideTweetActions){
      this.css.insert(".tweet-action { opacity: 0; }");
      this.css.insert(".is-favorite .tweet-action, .is-retweet .tweet-action { opacity: 0.5; visibility: visible !important }");
      this.css.insert(".tweet:hover .tweet-action, .is-favorite .tweet-action[rel='favorite'], .is-retweet .tweet-action[rel='retweet'] { opacity: 1; visibility: visible !important }");
    }

    if (this.config.moveTweetActionsToRight){
      this.css.insert(".tweet-actions { float: right !important; width: auto !important }");
      this.css.insert(".tweet-actions > li:nth-child(4) { margin-right: 2px !important }");
    }

    if (this.config.smallComposeTextSize){
      this.css.insert(".compose-text { font-size: 12px !important; height: 120px !important }");
    }

    if (!this.config.roundedScrollBars){
      this.css.insert(".scroll-styled-v:not(.antiscroll-inner)::-webkit-scrollbar { width: 8px }");
      this.css.insert(".scroll-styled-h:not(.antiscroll-inner)::-webkit-scrollbar { height: 8px }");
      this.css.insert(".scroll-styled-v::-webkit-scrollbar-thumb { border-radius: 0 }");
      this.css.insert(".scroll-styled-h::-webkit-scrollbar-thumb { border-radius: 0 }");
      this.css.insert(".antiscroll-scrollbar { border-radius: 0 }");
      this.css.insert(".antiscroll-scrollbar-vertical { margin-top: 0 }");
      this.css.insert(".antiscroll-scrollbar-horizontal { margin-left: 0 }");
    }

    if (this.config.columnWidth[0] === '/'){
      let cols = this.config.columnWidth.slice(1);

      this.css.insert(".column { width: calc((100vw - 205px) / "+cols+" - 8px) !important }");
      this.css.insert(".is-condensed .column { width: calc((100vw - 55px) / "+cols+" - 8px) !important }");
    }
    else{
      this.css.insert(".column { width: "+this.config.columnWidth+" !important }");
    }

    switch(this.config.columnWidth){
      case "/6":
        TD.settings.setColumnWidth("narrow");
        break;

      case "310px":
      case "/5":
        TD.settings.setColumnWidth("medium");
        break;

      default:
        TD.settings.setColumnWidth(parseInt(this.config.columnWidth, 10) < 310 ? "narrow" : "wide"); // NaN will give "wide"
        break;
    }

    switch(this.config.fontSize){
      case "13px": TD.settings.setFontSize("small"); break;
      case "14px": TD.settings.setFontSize("medium"); break;
      case "15px": TD.settings.setFontSize("large"); break;
      default: TD.settings.setFontSize(parseInt(this.config.fontSize, 10) >= 16 ? "largest" : "smallest"); break;
    }

    $TDP.injectIntoNotificationsBefore(this.$token, "css", "", [
      ""
    ].join(""));
  };

  this.uiShowActionsMenuEvent = () => {
    if (this.config.moveTweetActionsToRight){
      $(".js-dropdown.pos-r").toggleClass("pos-r pos-l");
    }
  };
}

ready(){
  // configuration
  switch(TD.settings.getColumnWidth()){
    case "wide": this.defaultConfig.columnWidth = "350px"; break;
    case "narrow": this.defaultConfig.columnWidth = "270px"; break;
  }

  switch(TD.settings.getFontSize()){
    case "small": this.defaultConfig.fontSize = "13px"; break;
    case "medium": this.defaultConfig.fontSize = "14px"; break;
    case "large": this.defaultConfig.fontSize = "15px"; break;
    case "largest": this.defaultConfig.fontSize = "16px"; break;
  }

  this.onAppReady();

  // layout events
  $(document).on("uiShowActionsMenu", this.uiShowActionsMenuEvent);

  // modal
  $("[data-action='settings-menu']").on("click", this.onSettingsMenuClickedEvent);
  $(".js-app").append('

');
}

disabled(){
  if (this.css){
    this.css.remove();
  }

  if (this.optimizations){
    this.optimizations.remove();
  }

  if (this.optimizationTimer){
    window.clearTimeout(this.optimizationTimer);
  }

  $(document).off("uiShowActionsMenu", this.uiShowActionsMenuEvent);
  $(window).off("focus", this.onWindowFocusEvent);
  $(window).off("blur", this.onWindowBlurEvent);

  $("[data-action='settings-menu']").off("click", this.onSettingsMenuClickedEvent);
  $("#td-design-plugin-modal").remove();
}
<|endoftext|>


<commit_before>// @flow

import * as React from 'react'
import {TabNavigator} from '../components/tabbed-view'
import {TabBarIcon} from '../components/tabbar-icon'

import {RadioControllerView} from './radio'
// import WeeklyMovieView from './movie'
import {WebcamsView} from './webcams'
import {StreamListView} from './streams'

export {KSTOScheduleView} from './radio'

export default TabNavigator(
	{
		StreamingView: {screen: StreamListView},
		LiveWebcamsView: {screen: WebcamsView},
		KSTORadioView: {
			screen: ({navigation}) => (
				<RadioControllerView
					image={require('../../../images/streaming/ksto.png')}
					navigation={navigation}
					playerUrl="https://www.stolaf.edu/multimedia/play/embed/ksto.html"
					scheduleViewName="KSTOScheduleView"
					source={{
						useEmbeddedPlayer: true,
						embeddedPlayerUrl:
							'https://www.stolaf.edu/multimedia/play/embed/ksto.html',
						streamSourceUrl: '',
					}}
					stationName="KSTO 93.1 FM"
					stationNumber="+15077863602"
					title="St. Olaf College Radio"
				/>
			),
			navigationOptions: {
				tabBarLabel: 'KSTO',
				tabBarIcon: TabBarIcon('radio'),
			},
		},
		// WeeklyMovieView: {screen: WeeklyMovieView},
	},
	{
		navigationOptions: {
			title: 'Streaming Media',
		},
	},
)
<commit_msg>add KRLX source<commit_after>// @flow

import * as React from 'react'
import {TabNavigator} from '../components/tabbed-view'
import {TabBarIcon} from '../components/tabbar-icon'

import {RadioControllerView} from './radio'
// import WeeklyMovieView from './movie'
import {WebcamsView} from './webcams'
import {StreamListView} from './streams'

export {KSTOScheduleView} from './radio'

export default TabNavigator(
	{
		StreamingView: {screen: StreamListView},
		LiveWebcamsView: {screen: WebcamsView},
		KSTORadioView: {
			screen: ({navigation}) => (
				<RadioControllerView
					image={require('../../../images/streaming/ksto.png')}
					navigation={navigation}
					playerUrl="https://www.stolaf.edu/multimedia/play/embed/ksto.html"
					scheduleViewName="KSTOScheduleView"
					source={{
						useEmbeddedPlayer: true,
						embeddedPlayerUrl:
							'https://www.stolaf.edu/multimedia/play/embed/ksto.html',
						streamSourceUrl: '',
					}}
					stationName="KSTO 93.1 FM"
					stationNumber="+15077863602"
					title="St. Olaf College Radio"
				/>
			),
			navigationOptions: {
				tabBarLabel: 'KSTO',
				tabBarIcon: TabBarIcon('radio'),
			},
		},
		KRLXRadioView: {
			screen: ({navigation}) => (
				<RadioControllerView
					image={require('../../../images/streaming/krlx.png')}
					navigation={navigation}
					playerUrl="http://live.krlx.org"
					scheduleViewName="KRLXScheduleView"
					source={{
						useEmbeddedPlayer: false,
						embeddedPlayerUrl: 'http://live.krlx.org',
						streamSourceUrl: 'http://radio.krlx.org/mp3/high_quality',
					}}
					stationName="88.1 KRLX-FM"
					stationNumber="+15072224127"
					title="Carleton College Radio"
				/>
			),
			navigationOptions: {
				tabBarLabel: 'KRLX',
				tabBarIcon: TabBarIcon('microphone'),
			},
		},
		// WeeklyMovieView: {screen: WeeklyMovieView},
	},
	{
		navigationOptions: {
			title: 'Streaming Media',
		},
	},
)
<|endoftext|>


<commit_before>(function() {

	/*
	 * Using TineMCE Ext 4 Adaption found on:
	 * http://www.sencha.com/forum/showthread.php?143190-Ext.ux.TinyMCE-adaption-for-Ext4&p=635192
	 */

    Ext.define('HatimeriaAdmin.cms.form.EditForm', {
        extend: 'Ext.form.Panel',

        constructor: function(cfg)
        {
            var config = {
                api: {
                   submit: Actions.HatimeriaAdmin_Cms.edit
                }
            };
            Ext.apply(config, cfg || {});

            this.callParent([config]);
        },

        initComponent: function() {

            var config = {
                border: false,
                width: 700,
                bodyPadding: 10,
                dockedItems: [{
                    dock: 'bottom',
                    xtype: 'toolbar',
                    ui: 'footer',
                    style: 'margin: 0 5px 5px 0;',
                    items: ['->', {
                            text: 'Zapisz',
                            scope: this,
                            handler: function(){
                                var panel  = this;
                                var form   = panel.getForm();
                                var record = form.getRecord();
                                var params = {};

                                if(record) {
                                    params = {
                                        id: record.get('id')
                                    };
                                }

                                form.submit({
                                    params: params,
                                    success: function() {
                                        Ext.getStore('cms-store').load();
                                        panel.findParentByType('window').destroy();
                                    }
                                });
                            }
                        }
                    ]
                }],
                defaultType: 'textfield',
                defaults: {
                    anchor: '100%'
                },
                items: [{
                    fieldLabel: 'Tytuł',
                    name: 'title'
                },
                {
                    fieldLabel: 'Uri',
                    name: 'primary_path'
                },
                {
                    fieldLabel: 'Autor',
                    name: 'author'
                },
                {
                    fieldLabel: 'Meta description',
                    name: 'meta_description'
                },
                {
                    fieldLabel: 'Meta keywords',
                    name: 'meta_keywords'
                },
                {
                    xtype: 'form',
                    id: 'tiny-container',
                    height: 350,
                    border: 0,
                    layout: 'auto',
                    items: [
                        {
                            id: 'tinymce',
                            xtype: 'tinymce',
                            fieldLabel: 'Treść',
                            width: 573,
                            height: 240,
                            name: 'body',
                            tinymceSettings: {
                                theme: 'advanced',
                                plugins: 'pagebreak,style,layer,table,advhr,advimage,advlink,emotions,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,noneditable,visualchars,nonbreaking,xhtmlxtras,template',
                                theme_advanced_buttons1: 'bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect',
                                theme_advanced_buttons2: 'bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor',
                                theme_advanced_buttons3: 'tablecontrols,|,hr,sub,sup,|,charmap,media,advhr,|,print,|,ltr,rtl,|',
                                theme_advanced_buttons4: 'insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak',
                                theme_advanced_toolbar_location: 'top',
                                theme_advanced_toolbar_align: 'left',
                                theme_advanced_statusbar_location: 'bottom',
                                file_browser_callback: 'tinymce_upload',
                                theme_advanced_resizing: false,
                                //extended_valid_elements: 'a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]'
                            }
                        }
                    ]
                },
                {
                    fieldLabel: 'Od kiedy publikowac',
                    name: 'publish_from',
                    xtype: 'datefield'
                },
                {
                    fieldLabel: 'Do kiedy publikowac',
                    name: 'publish_to',
                    xtype: 'datefield'
                },
                {
                    fieldLabel: 'Opublikowany',
                    name: 'is_published',
                    xtype: 'checkboxfield'
                }]
            };

            Ext.apply(this, Ext.apply(config, this.initialConfig));

            this.callParent();
        },

        /**
         * Populating
         */
        populate: function(record)
        {
            var _this = this;
            window.setTimeout(function() {
                _this.getForm().loadRecord(record);
            }, 500);
        }
    });
})();<commit_msg>fix: url-case form<commit_after>(function() {

	/*
	 * Using TineMCE Ext 4 Adaption found on:
	 * http://www.sencha.com/forum/showthread.php?143190-Ext.ux.TinyMCE-adaption-for-Ext4&p=635192
	 */

    Ext.define('HatimeriaAdmin.cms.form.EditForm', {
        extend: 'Ext.form.Panel',

        constructor: function(cfg)
        {
            var config = {
                api: {
                   submit: Actions.HatimeriaAdmin_Cms.edit
                }
            };
            Ext.apply(config, cfg || {});

            this.callParent([config]);
        },

        initComponent: function() {

            var config = {
                border: false,
                width: 700,
                bodyPadding: 10,
                dockedItems: [{
                    dock: 'bottom',
                    xtype: 'toolbar',
                    ui: 'footer',
                    style: 'margin: 0 5px 5px 0;',
                    items: ['->', {
                            text: 'Zapisz',
                            scope: this,
                            handler: function(){
                                var panel  = this;
                                var form   = panel.getForm();
                                var record = form.getRecord();
                                var params = {};

                                if(record) {
                                    params = {
                                        id: record.get('id')
                                    };
                                }

                                form.submit({
                                    params: params,
                                    success: function() {
                                        Ext.getStore('cms-store').load();
                                        panel.findParentByType('window').destroy();
                                    }
                                });
                            }
                        }
                    ]
                }],
                defaultType: 'textfield',
                defaults: {
                    anchor: '100%'
                },
                items: [{
                    fieldLabel: 'Tytuł',
                    name: 'title'
                },
                {
                    fieldLabel: 'Uri',
                    name: 'primary_path'
                },
                {
                    fieldLabel: 'Autor',
                    name: 'author'
                },
                {
                    fieldLabel: 'Meta description',
                    name: 'meta_description'
                },
                {
                    fieldLabel: 'Meta keywords',
                    name: 'meta_keywords'
                },
                {
                    xtype: 'form',
                    id: 'tiny-container',
                    height: 350,
                    border: 0,
                    layout: 'auto',
                    items: [
                        {
                            id: 'tinymce',
                            xtype: 'tinymce',
                            fieldLabel: 'Treść',
                            width: 573,
                            height: 240,
                            name: 'body',
                            tinymceSettings: {
                                theme: 'advanced',
                                plugins: 'pagebreak,style,layer,table,advhr,advimage,advlink,emotions,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,noneditable,visualchars,nonbreaking,xhtmlxtras,template',
                                theme_advanced_buttons1: 'bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect',
                                theme_advanced_buttons2: 'bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor',
                                theme_advanced_buttons3: 'tablecontrols,|,hr,sub,sup,|,charmap,media,advhr,|,print,|,ltr,rtl,|',
                                theme_advanced_buttons4: 'insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak',
                                theme_advanced_toolbar_location: 'top',
                                theme_advanced_toolbar_align: 'left',
                                theme_advanced_statusbar_location: 'bottom',
                                file_browser_callback: 'tinymce_upload',
                                theme_advanced_resizing: false,
                                extended_valid_elements: 'a[name|href|target|title|onclick],img[class|src|border|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]'
                            }
                        }
                    ]
                },
                {
                    fieldLabel: 'Od kiedy publikowac',
                    name: 'publish_from',
                    xtype: 'datefield'
                },
                {
                    fieldLabel: 'Do kiedy publikowac',
                    name: 'publish_to',
                    xtype: 'datefield'
                },
                {
                    fieldLabel: 'Opublikowany',
                    name: 'is_published',
                    xtype: 'checkboxfield'
                }]
            };

            Ext.apply(this, Ext.apply(config, this.initialConfig));

            this.callParent();
        },

        /**
         * Populating
         */
        populate: function(record)
        {
            var _this = this;
            window.setTimeout(function() {
                _this.getForm().loadRecord(record);
            }, 500);
        }
    });
})();<|endoftext|>


<commit_before>$.widget( "kalamu.kalamuDashboardSection", {

    options: {
        dashboard: null,
        type: null,
        title: null,
        identifier: null,
        params: null,
        rows: null
    },

    _create: function() {

        this.element.addClass('row kalamu-dashboard-section');

        this.options.editLink = $('');
        this.element.prepend( $('

').append(this.options.editLink) )
        this._on(this.options.editLink, { 'click': this.editElement });

        this.options.innerDashboard = $('
');
        this.element.append(this.options.innerDashboard);
        this.options.innerDashboard.kalamuCmsDashboard({
            explorerWidget: this.options.dashboard.options.explorerWidget,
            enable_widget: true,
            enable_section: false
        });
        if(this.options.childs){
            this.options.innerDashboard.kalamuCmsDashboard('import', {childs: this.options.childs});
        }

        this._updateTitle();

    },

    /**
     * Update the title of the Section
     * @returns {undefined}
     */
    _updateTitle: function(){
        this.options.dashboard.options.explorerSection.kalamuElementExplorer('loadElementInfos', this.options.identifier, this.options.params, $.proxy(function(datas){
            this.options.title = datas.title;
            this.options.editLink.find('.section-name').text(this.options.title);
        }, this));
    },

    editElement: function(e){
        e.preventDefault();
        this.options.dashboard.options.explorerSection.kalamuElementExplorer('showElementInfos', this.options.identifier, this.options.params);

        updateElementFct = $.proxy(this.updateElement, this);
        this.options.dashboard.options.explorerSection.on('kalamu.dashboard.valid_element', updateElementFct);
        this.options.dashboard.options.explorerSection.on('kalamu.dashboard.close_explorer', $.proxy(function(updateElementFct){
            this.options.dashboard.options.explorerSection.off('kalamu.dashboard.valid_element', updateElementFct);
        }, this, updateElementFct));
    },

    updateElement: function(e, infos){
        this.options.identifier = infos.identifier;
        this.options.params = infos.params;

        this._updateTitle();
    },

    export: function(){
        var json = {
            type: this.options.type,
            identifier: this.options.identifier,
            params: this.options.params,
        };
        json._content = this.options.innerDashboard.kalamuCmsDashboard('export');

        return json;
    },

    up: function(e){
        e.preventDefault();
        if(this.element.prev().not('.stick-top').length){
            this.element.prev().before( this.element.detach() );
            this.options.dashboard.element.trigger("kalamu.dashboard.move_section");
        }
    },

    down: function(e){
        e.preventDefault();
        if(this.element.next().not('.stick-bottom').length){
            this.element.next().after( this.element.detach() );
            this.options.dashboard.element.trigger("kalamu.dashboard.move_section");
        }
    },

    _delete: function(e){
        e.preventDefault();
        this.element.remove();
        this.options.dashboard.element.trigger("kalamu.dashboard.delete_section");
    }

});<commit_msg>fix import of section content<commit_after>$.widget( "kalamu.kalamuDashboardSection", {

    options: {
        dashboard: null,
        type: null,
        title: null,
        identifier: null,
        params: null,
        rows: null
    },

    _create: function() {

        this.element.addClass('row kalamu-dashboard-section');

        this.options.editLink = $('');
        this.element.prepend( $('

').append(this.options.editLink) )
        this._on(this.options.editLink, { 'click': this.editElement });

        this.options.innerDashboard = $('
');
        this.element.append(this.options.innerDashboard);
        this.options.innerDashboard.kalamuCmsDashboard({
            explorerWidget: this.options.dashboard.options.explorerWidget,
            enable_widget: true,
            enable_section: false
        });
        if(this.options._content){
            this.options.innerDashboard.kalamuCmsDashboard('import', this.options._content);
        }

        this._updateTitle();

    },

    /**
     * Update the title of the Section
     * @returns {undefined}
     */
    _updateTitle: function(){
        this.options.dashboard.options.explorerSection.kalamuElementExplorer('loadElementInfos', this.options.identifier, this.options.params, $.proxy(function(datas){
            this.options.title = datas.title;
            this.options.editLink.find('.section-name').text(this.options.title);
        }, this));
    },

    editElement: function(e){
        e.preventDefault();
        this.options.dashboard.options.explorerSection.kalamuElementExplorer('showElementInfos', this.options.identifier, this.options.params);

        updateElementFct = $.proxy(this.updateElement, this);
        this.options.dashboard.options.explorerSection.on('kalamu.dashboard.valid_element', updateElementFct);
        this.options.dashboard.options.explorerSection.on('kalamu.dashboard.close_explorer', $.proxy(function(updateElementFct){
            this.options.dashboard.options.explorerSection.off('kalamu.dashboard.valid_element', updateElementFct);
        }, this, updateElementFct));
    },

    updateElement: function(e, infos){
        this.options.identifier = infos.identifier;
        this.options.params = infos.params;

        this._updateTitle();
    },

    export: function(){
        var json = {
            type: this.options.type,
            identifier: this.options.identifier,
            params: this.options.params,
        };
        json._content = this.options.innerDashboard.kalamuCmsDashboard('export');

        return json;
    },

    up: function(e){
        e.preventDefault();
        if(this.element.prev().not('.stick-top').length){
            this.element.prev().before( this.element.detach() );
            this.options.dashboard.element.trigger("kalamu.dashboard.move_section");
        }
    },

    down: function(e){
        e.preventDefault();
        if(this.element.next().not('.stick-bottom').length){
            this.element.next().after( this.element.detach() );
            this.options.dashboard.element.trigger("kalamu.dashboard.move_section");
        }
    },

    _delete: function(e){
        e.preventDefault();
        this.element.remove();
        this.options.dashboard.element.trigger("kalamu.dashboard.delete_section");
    }

});<|endoftext|>


<commit_before>// TODO handle those browsers that natively handle offline events (like Firefox via Work Offline)
(function () {

function triggerEvent(type) {
  var event = document.createEvent('HTMLEvents');
  event.initEvent(type, true, true);
  event.eventName = type;
  (document.body || window).dispatchEvent(event);
}

function testConnection() {
  // make sync-ajax request
  var xhr = new XMLHttpRequest();
  // phone home
  xhr.open('HEAD', '/', false); // async=false
  try {
    xhr.send();
    onLine = true;
  } catch (e) {
    // throws NETWORK_ERR when disconnected
    onLine = false;
  }

  return onLine;
}

var onLine = true,
    lastOnLineStatus = true;

// note: this doesn't allow us to define a getter in Safari
navigator.__defineGetter__("onLine", testConnection);
testConnection();

if (onLine === false) {
  lastOnLineStatus = false;
  // trigger offline event
  triggerEvent('offline');
}

setInterval(function () {
  testConnection();
  if (onLine !== lastOnLineStatus) {
    triggerEvent(onLine ? 'online' : 'offline');
    lastOnLineStatus = onLine;
  }
}, 5000); // 5 seconds, made up - can't find docs to suggest interval time
})();
<commit_msg>included url to example<commit_after>// Working demo: http://jsbin.com/ozusa6/2/
(function () {

function triggerEvent(type) {
  var event = document.createEvent('HTMLEvents');
  event.initEvent(type, true, true);
  event.eventName = type;
  (document.body || window).dispatchEvent(event);
}

function testConnection() {
  // make sync-ajax request
  var xhr = new XMLHttpRequest();
  // phone home
  xhr.open('HEAD', '/', false); // async=false
  try {
    xhr.send();
    onLine = true;
  } catch (e) {
    // throws NETWORK_ERR when disconnected
    onLine = false;
  }

  return onLine;
}

var onLine = true,
    lastOnLineStatus = true;

// note: this doesn't allow us to define a getter in Safari
navigator.__defineGetter__("onLine", testConnection);
testConnection();

if (onLine === false) {
  lastOnLineStatus = false;
  // trigger offline event
  triggerEvent('offline');
}

setInterval(function () {
  testConnection();
  if (onLine !== lastOnLineStatus) {
    triggerEvent(onLine ? 'online' : 'offline');
    lastOnLineStatus = onLine;
  }
}, 5000); // 5 seconds, made up - can't find docs to suggest interval time
})();
<|endoftext|>


<commit_before>/*global logger*/

/* config variables */
var config = {
    BTKey: "",
    radius: 300,
    logger: true,
    MaximumStopVisits: 20,
    MinimumStopVisitsPerLine: 2
};

/* enable or disable the logging */
(function () {
    if (config.logger === true) {
        logger.enableLogger();
    } else {
        logger.disableLogger();
    }
})();<commit_msg>update<commit_after>/*global logger*/

/* config variables */
var config = {
    BTKey: "",
    radius: 200,
    logger: true,
    MaximumStopVisits: 15,
    MinimumStopVisitsPerLine: 2
};

/* enable or disable the logging */
(function () {
    if (config.logger === true) {
        logger.enableLogger();
    } else {
        logger.disableLogger();
    }
})();<|endoftext|>


<commit_before>var initModal = function () {

    var modal = $('.modal:not([data-initialized])');
    var remote = $('.modal.remote:not([data-initialized])');

    var loading = '

';

    // Loading state
    modal.on('loading', function() {
        $(this).find('.modal-content').append(loading);
    });

    // Clear remote modals when closed.
    remote.on('hidden.bs.modal', function () {

        $(this).removeData('bs.modal');

        $(this).find('.modal-content').html(loading);
    });

    // Show loader for remote modals.
    remote.on('show.bs.modal', function () {
        $(this).find('.modal-content').html(loading);
    });

    // Handle ajax links in modals.
    modal.on('click', 'a.ajax, .pagination a', function (e) {

        e.preventDefault();

        var wrapper = $(this).closest('.modal-content');

        wrapper.append(loading);

        $.get($(this).attr('href'), function (html) {
            wrapper.html(html);
        });
    });

    // Handle ajax forms in modals.
    modal.on('submit', 'form.ajax', function (e) {

        e.preventDefault();

        var wrapper = $(this).closest('.modal-content');

        wrapper.append(loading);

        if ($(this).attr('method') == 'GET') {
            $.get($(this).attr('action'), $(this).serializeArray(), function (html) {
                wrapper.html(html);
            });
        } else {
            $.post($(this).attr('action'), $(this).serializeArray(), function (html) {
                wrapper.html(html);
            });
        }
    });

    // Mark as initialized.
    modal.attr('data-initialized', '');
    remote.attr('data-initialized', '');
};

$(document).ready(function () {
    initModal();
});

$(document).ajaxComplete(function () {
    initModal();
});
<commit_msg>More better<commit_after>var initModal = function () {

    var modal = $('.modal.remote:not([data-initialized])');

    var loading = '

';

    // Loading state
    modal.on('loading', function() {
        $(this).find('.modal-content').append(loading);
    });

    // Clear remote modals when closed.
    modal.on('hidden.bs.modal', function () {

        $(this).removeData('bs.modal');

        $(this).find('.modal-content').html(loading);
    });

    // Show loader for remote modals.
    modal.on('show.bs.modal', function () {
        $(this).find('.modal-content').html(loading);
    });

    // Handle ajax links in modals.
    modal.on('click', 'a.ajax, .pagination a', function (e) {

        e.preventDefault();

        var wrapper = $(this).closest('.modal-content');

        wrapper.append(loading);

        $.get($(this).attr('href'), function (html) {
            wrapper.html(html);
        });
    });

    // Handle ajax forms in modals.
    modal.on('submit', 'form.ajax', function (e) {

        e.preventDefault();

        var wrapper = $(this).closest('.modal-content');

        wrapper.append(loading);

        if ($(this).attr('method') == 'GET') {
            $.get($(this).attr('action'), $(this).serializeArray(), function (html) {
                wrapper.html(html);
            });
        } else {
            $.post($(this).attr('action'), $(this).serializeArray(), function (html) {
                wrapper.html(html);
            });
        }
    });

    // Mark as initialized.
    modal.attr('data-initialized', '');
};

$(document).ready(function () {
    initModal();
});

$(document).ajaxComplete(function () {
    initModal();
});

$(document).on('show.bs.modal', '.modal', function () {
    var zIndex = 1040 + (10 * $('.modal:visible').length);
    $(this).css('z-index', zIndex);
    setTimeout(function() {
        $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
    }, 0);
});
<|endoftext|>


<commit_before>/**
 * TaskFeedController
 * @namespace crowdsource.task-feed.controllers
 * @author dmorina
 */
(function () {
    'use strict';

    angular
        .module('crowdsource.task-feed.controllers')
        .controller('TaskFeedController', TaskFeedController);

    TaskFeedController.$inject = ['$window', '$location', '$scope', '$mdToast', 'TaskFeed',
        '$filter', 'Authentication', 'TaskWorker', 'Project', '$rootScope', '$routeParams'];

    /**
     * @namespace TaskFeedController
     */
    function TaskFeedController($window, $location, $scope, $mdToast, TaskFeed,
                                $filter, Authentication, TaskWorker, Project, $rootScope, $routeParams) {
        var userAccount = Authentication.getAuthenticatedAccount();
        if (!userAccount) {
            $location.path('/login');
            return;
        }

        var self = this;
        self.toggleBookmark = toggleBookmark;
        self.projects = [];
        self.previewedModule = null;
        self.showPreview = showPreview;
        self.openTask = openTask;
        self.openComments = openComments;
        self.saveComment = saveComment;
        self.loading = true;
        self.getStatusName = getStatusName;
        activate();

        function activate(){
            if($routeParams.moduleId){
                self.openTask($routeParams.moduleId);
            }
            else{
                getModules();
            }
        }
        function getModules() {
            TaskFeed.getModules().then(
                function success(data) {
                    self.modules = data[0];
                    self.availableTasks = false;
                    for (var j = 0; j < self.modules.length; j++) {
                        if (self.modules[j].available_tasks != 0) {
                            self.availableTasks = true;
                            return;
                        }
                    }
                },
                function error(errData) {
                    self.error = errData[0].detail;
                    $mdToast.showSimple('Could projects.');
                }
            ).
            finally(function () {
                self.loading = false;
            });
        }

        function toggleBookmark(project) {
            project.is_bookmarked = !project.is_bookmarked;
        }

        function showPreview(module) {
            self.previewedModule = module;
        }

        function openTask(module_id) {
            TaskWorker.attemptAllocateTask(module_id).then(
                function success(data, status) {
                    if(data[1]==204){
                        $mdToast.showSimple('Error: No more tasks left.');
                        $location.path('/task-feed');
                    }
                    else{
                        var task_id = data[0].task;
                        var taskWorkerId = data[0].id;
                        $location.path('/task/' + task_id + '/' + taskWorkerId);
                    }

                },
                function error(errData) {
                    var err = errData[0];
                    var message = null;
                    if (err.hasOwnProperty('detail')) {
                        message = err.detail;
                    }
                    else {
                        message = JSON.stringify(err);
                    }
                    $mdToast.showSimple('Error: ' + message);
                }
            ).finally(function () {
                });
        }

        function openComments(module) {
            if (module.comments && module.is_comment_expanded) {
                module.is_comment_expanded = false;
            }
            else if (module.comments && !module.is_comment_expanded) {
                module.is_comment_expanded = true;
            }
            else {
                Project.getModuleComments(module.id).then(
                    function success(data) {
                        angular.extend(module, {'comments': data[0].comments});
                        module.is_comment_expanded = true;
                    },
                    function error(errData) {
                        var err = errData[0];
                        $mdToast.showSimple('Error fetching comments - ' + JSON.stringify(err));
                    }
                ).finally(function () {
                    });
            }
        }

        function saveComment(module) {
            TaskFeed.saveComment(module.id, self.comment.body).then(
                function success(data) {
                    if (module.comments == undefined) {
                        angular.extend(module, {'comments': []});
                    }
                    module.comments.push(data[0]);
                    self.comment.body = null;
                },
                function error(errData) {
                    var err = errData[0];
                    $mdToast.showSimple('Error saving comment - ' + JSON.stringify(err));
                }
            ).finally(function () {
                });
        }

        function getStatusName(statusId) {
            if (statusId == 5) return 'Paused';
            else if (statusId == 4) return 'Completed';
            else return 'Running';
        }
    }

})
();
<commit_msg>remove available task flicker in task feed<commit_after>/**
 * TaskFeedController
 * @namespace crowdsource.task-feed.controllers
 * @author dmorina
 */
(function () {
    'use strict';

    angular
        .module('crowdsource.task-feed.controllers')
        .controller('TaskFeedController', TaskFeedController);

    TaskFeedController.$inject = ['$window', '$location', '$scope', '$mdToast', 'TaskFeed',
        '$filter', 'Authentication', 'TaskWorker', 'Project', '$rootScope', '$routeParams'];

    /**
     * @namespace TaskFeedController
     */
    function TaskFeedController($window, $location, $scope, $mdToast, TaskFeed,
                                $filter, Authentication, TaskWorker, Project, $rootScope, $routeParams) {
        var userAccount = Authentication.getAuthenticatedAccount();
        if (!userAccount) {
            $location.path('/login');
            return;
        }

        var self = this;
        self.toggleBookmark = toggleBookmark;
        self.projects = [];
        self.previewedModule = null;
        self.showPreview = showPreview;
        self.openTask = openTask;
        self.openComments = openComments;
        self.saveComment = saveComment;
        self.loading = true;
        self.getStatusName = getStatusName;
        activate();

        function activate(){
            if($routeParams.moduleId){
                self.openTask($routeParams.moduleId);
            }
            else{
                getModules();
            }
        }
        function getModules() {
            TaskFeed.getModules().then(
                function success(data) {
                    self.modules = data[0].filter(function(module){
                        return module.available_tasks>0;
                    });
                    self.availableTasks = self.modules.length > 0;
                },
                function error(errData) {
                    self.error = errData[0].detail;
                    $mdToast.showSimple('Could projects.');
                }
            ).
            finally(function () {
                self.loading = false;
            });
        }

        function toggleBookmark(project) {
            project.is_bookmarked = !project.is_bookmarked;
        }

        function showPreview(module) {
            self.previewedModule = module;
        }

        function openTask(module_id) {
            TaskWorker.attemptAllocateTask(module_id).then(
                function success(data, status) {
                    if(data[1]==204){
                        $mdToast.showSimple('Error: No more tasks left.');
                        $location.path('/task-feed');
                    }
                    else{
                        var task_id = data[0].task;
                        var taskWorkerId = data[0].id;
                        $location.path('/task/' + task_id + '/' + taskWorkerId);
                    }

                },
                function error(errData) {
                    var err = errData[0];
                    var message = null;
                    if (err.hasOwnProperty('detail')) {
                        message = err.detail;
                    }
                    else {
                        message = JSON.stringify(err);
                    }
                    $mdToast.showSimple('Error: ' + message);
                }
            ).finally(function () {
                });
        }

        function openComments(module) {
            if (module.comments && module.is_comment_expanded) {
                module.is_comment_expanded = false;
            }
            else if (module.comments && !module.is_comment_expanded) {
                module.is_comment_expanded = true;
            }
            else {
                Project.getModuleComments(module.id).then(
                    function success(data) {
                        angular.extend(module, {'comments': data[0].comments});
                        module.is_comment_expanded = true;
                    },
                    function error(errData) {
                        var err = errData[0];
                        $mdToast.showSimple('Error fetching comments - ' + JSON.stringify(err));
                    }
                ).finally(function () {
                    });
            }
        }

        function saveComment(module) {
            TaskFeed.saveComment(module.id, self.comment.body).then(
                function success(data) {
                    if (module.comments == undefined) {
                        angular.extend(module, {'comments': []});
                    }
                    module.comments.push(data[0]);
                    self.comment.body = null;
                },
                function error(errData) {
                    var err = errData[0];
                    $mdToast.showSimple('Error saving comment - ' + JSON.stringify(err));
                }
            ).finally(function () {
                });
        }

        function getStatusName(statusId) {
            if (statusId == 5) return 'Paused';
            else if (statusId == 4) return 'Completed';
            else return 'Running';
        }
    }

})
();
<|endoftext|>


<commit_before>/**
 * @preserve Copyright (c) 2014 British Broadcasting Corporation
 * (http://www.bbc.co.uk) and TAL Contributors (1)
 *
 * (1) TAL Contributors are listed in the AUTHORS file and at
 *     https://github.com/fmtvp/TAL/AUTHORS - please extend this file,
 *     not this notice.
 *
 * @license 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.
 *
 * All rights reserved
 * Please contact us for an alternative licence
 */

(function() {
    this.CEHTMLMediaPlayerTests = AsyncTestCase("CEHTMLMediaPlayer");

    var config = {"modules":{"base":"antie/devices/browserdevice","modifiers":["antie/devices/mediaplayer/cehtml"]}, "input":{"map":{}},"layouts":[{"width":960,"height":540,"module":"fixtures/layouts/default","classes":["browserdevice540p"]}],"deviceConfigurationKey":"devices-html5-1"};

    // Setup device specific mocking
    var deviceMockingHooks = {
        setup: function(sandbox, application) {

        },
        sendMetadata: function(mediaPlayer, currentTime, range) {
            mediaPlayer._range = range; // FIXME - do not do this in an actual implementation - replace it with proper event mock / whatever.
            mediaPlayer._currentTime = currentTime; // FIXME - do not do this in an actual implementation - replace it with proper event mock / whatever.
        },
        finishBuffering: function(mediaPlayer) {
            mediaPlayer._currentTime = mediaPlayer._targetSeekTime ? mediaPlayer._targetSeekTime : mediaPlayer._currentTime;  // FIXME - do not do this in an actual implementation - replace it with proper event mock / whatever.
            mediaPlayer._onFinishedBuffering(); // FIXME - do not do this in an actual implementation - replace it with proper event mock / whatever.
        },
        emitPlaybackError: function(mediaPlayer) {
            mediaPlayer._onDeviceError(); // FIXME - do not do this in an actual implementation - replace it with proper event mock / whatever.
        },
        reachEndOfMedia: function(mediaPlayer) {
            mediaPlayer._onEndOfMedia();  // FIXME - do not do this in an actual implementation - replace it with proper event mock / whatever.
        },
        startBuffering: function(mediaPlayer) {
            mediaPlayer._onDeviceBuffering();  // FIXME - do not do this in an actual implementation - replace it with proper event mock / whatever.
        },
        mockTime: function(mediaplayer) {
            // FIXME - Implementations can use this hook to set up fake timers if required
        },
        makeOneSecondPass: function(mediaplayer, time) {
            mediaplayer._onStatus();  // FIXME - do not do this in an actual implementation - replace it with proper event / setTimeout mock / whatever.
        },
        unmockTime: function(mediaplayer) {
            // FIXME - Implementations can use this hook to tear down fake timers if required
        }
    };

    this.CEHTMLMediaPlayerTests.prototype.setUp = function() {
        this.sandbox = sinon.sandbox.create();
    };

    this.CEHTMLMediaPlayerTests.prototype.tearDown = function() {
        this.sandbox.restore();
    };

    //---------------------
    // Samsung Maple specific tests
    //---------------------

    // **** WARNING **** WARNING **** WARNING: These TODOs are NOT complete/exhaustive
    // TODO: Make setSource actually set the source and start the media loading
    // TODO: Make playFrom actually seek
    // TODO: Make playFrom actually seek
    // TODO: Make pause actually pause
    // TODO: Make stop actually stop
    // TODO: Make resume actually resume
    // TODO: Ensure reset actually clears the state
    // TODO: Ensure errore are handled
    // TODO: Ensure errors are logged.
    // TODO: Ensure playFrom(...) and play() both clamp to the available range (there's a _getClampedTime helper in the MediaPlayer)
    // TODO: Determine if status event 'ticks' need to be done through a setInterval method rather than as a result of events from the object (see media/cehtml.js)
    // TODO: Determine if the seekTo call blocks until it is complete (see media/cehtml.js:240)
    // TODO: media/cehtmlmediatypefix.js equivalent
    // TODO: Ensure the object data attribute is set tot the URL of the content (CEA-2014-A 5.7.1)
    // TODO: Ensure the object type attribute is set to the MIME-type of the content (CEA-2014-A 5.7.1.a (1))
    // TODO: Ensure the object element contains a dlna_res_attr param element (CEA-2014-A req 5.7.1.a (2))
    // TODO: Determine if it's possible to support CEA-2014-A req 5.7.1.a (3) - "An <object> element of type video… SHOULD contain a <param> element set to the aspect ratio"
    // TODO: Determine if we should use full screen or windowed mode, which are handled differently. (CEA-2014-A 5.7.1.c / 5.7.3)
    //    - 5.7.1.c - there are differences in full screen and windowed modes - fullscreen is 5.7.3
    //    - 5.7.1.g (5) - setFullScreen (default false, 5.7.1.g (3)) - changing modes SHALL not affect the Z-index. If the <overlay> capability is not none other element can be put on top.
    //    - 5.7.3.a (1) - [full screen] SHOULD scale the video content…
    //    - 5.7.3.b - Inside the browser area, full-screen video objects are regular video objects that SHALL cover the entire browser area
    //    - 5.7.3.c - If there is no longer a visible full-screen video object in the browser area … [it] SHALL switch to non-full-screen mode [which MAY scale the browser area - 5.7.3.d]
    // TODO: Handle "seek" failing (CEA-2014-A 5.7.1.F (13))
    // TODO: Handle "seek" not affecting play state (CEA-2014-A 5.7.1.F (13))
    // TODO: Handle "stop" reverting play position to 0 (CEA-2014-A req 5.7.1.f (12))
    // TODO: Create the object element using document.write or the DOM createElement method instead of directly including an oject tag in the CE-HTML page (CEA-2014-A 5.7.1.j)
    // TODO: ensure we are using XHTML 1.0 transitional and object tags (CEA-2014-1 5.4.a).
    // TODO: ensure that we provide non-CSS settings for properties that don't apply to <object> tags (CEA-2014-A Annex G, p 99 - <object>)
    // TODO: Handle that semantics change if the data is a playlist or a single media item (CEA-2014-A 5.7.1.f) - particularly playPosition, playTime

    //---------------------
    // Common tests
    //---------------------

    // Mixin the common tests shared by all MediaPlayer implementations (last, so it can detect conflicts)
    MixinCommonMediaTests(this.CEHTMLMediaPlayerTests, "antie/devices/mediaplayer/cehtml", config, deviceMockingHooks);

})();
<commit_msg>Added runMediaPlayerTest helper function, for parity with other implementations.<commit_after>/**
 * @preserve Copyright (c) 2014 British Broadcasting Corporation
 * (http://www.bbc.co.uk) and TAL Contributors (1)
 *
 * (1) TAL Contributors are listed in the AUTHORS file and at
 *     https://github.com/fmtvp/TAL/AUTHORS - please extend this file,
 *     not this notice.
 *
 * @license 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.
 *
 * All rights reserved
 * Please contact us for an alternative licence
 */

(function() {
    this.CEHTMLMediaPlayerTests = AsyncTestCase("CEHTMLMediaPlayer");

    var config = {"modules":{"base":"antie/devices/browserdevice","modifiers":["antie/devices/mediaplayer/cehtml"]}, "input":{"map":{}},"layouts":[{"width":960,"height":540,"module":"fixtures/layouts/default","classes":["browserdevice540p"]}],"deviceConfigurationKey":"devices-html5-1"};

    // Setup device specific mocking
    var deviceMockingHooks = {
        setup: function(sandbox, application) {

        },
        sendMetadata: function(mediaPlayer, currentTime, range) {
            mediaPlayer._range = range; // FIXME - do not do this in an actual implementation - replace it with proper event mock / whatever.
            mediaPlayer._currentTime = currentTime; // FIXME - do not do this in an actual implementation - replace it with proper event mock / whatever.
        },
        finishBuffering: function(mediaPlayer) {
            mediaPlayer._currentTime = mediaPlayer._targetSeekTime ? mediaPlayer._targetSeekTime : mediaPlayer._currentTime;  // FIXME - do not do this in an actual implementation - replace it with proper event mock / whatever.
            mediaPlayer._onFinishedBuffering(); // FIXME - do not do this in an actual implementation - replace it with proper event mock / whatever.
        },
        emitPlaybackError: function(mediaPlayer) {
            mediaPlayer._onDeviceError(); // FIXME - do not do this in an actual implementation - replace it with proper event mock / whatever.
        },
        reachEndOfMedia: function(mediaPlayer) {
            mediaPlayer._onEndOfMedia();  // FIXME - do not do this in an actual implementation - replace it with proper event mock / whatever.
        },
        startBuffering: function(mediaPlayer) {
            mediaPlayer._onDeviceBuffering();  // FIXME - do not do this in an actual implementation - replace it with proper event mock / whatever.
        },
        mockTime: function(mediaplayer) {
            // FIXME - Implementations can use this hook to set up fake timers if required
        },
        makeOneSecondPass: function(mediaplayer, time) {
            mediaplayer._onStatus();  // FIXME - do not do this in an actual implementation - replace it with proper event / setTimeout mock / whatever.
        },
        unmockTime: function(mediaplayer) {
            // FIXME - Implementations can use this hook to tear down fake timers if required
        }
    };

    this.CEHTMLMediaPlayerTests.prototype.setUp = function() {
        this.sandbox = sinon.sandbox.create();
    };

    this.CEHTMLMediaPlayerTests.prototype.tearDown = function() {
        this.sandbox.restore();
    };

    this.CEHTMLMediaPlayerTests.prototype.runMediaPlayerTest = function (queue, action) {
        var self = this;
        queuedApplicationInit(queue, 'lib/mockapplication', ["antie/devices/mediaplayer/cehtml", "antie/devices/mediaplayer/mediaplayer"],
            function(application, MediaPlayerImpl, MediaPlayer) {
                this._device = application.getDevice();
                self._mediaPlayer = this._device.getMediaPlayer();
                action.call(self, MediaPlayer);
            }, config);
    };

    //---------------------
    // CEHTML specific tests
    //---------------------

    // **** WARNING **** WARNING **** WARNING: These TODOs are NOT complete/exhaustive
    // TODO: Make setSource actually set the source and start the media loading
    // TODO: Make playFrom actually seek
    // TODO: Make playFrom actually seek
    // TODO: Make pause actually pause
    // TODO: Make stop actually stop
    // TODO: Make resume actually resume
    // TODO: Ensure reset actually clears the state
    // TODO: Ensure errore are handled
    // TODO: Ensure errors are logged.
    // TODO: Ensure playFrom(...) and play() both clamp to the available range (there's a _getClampedTime helper in the MediaPlayer)
    // TODO: Determine if status event 'ticks' need to be done through a setInterval method rather than as a result of events from the object (see media/cehtml.js)
    // TODO: Determine if the seekTo call blocks until it is complete (see media/cehtml.js:240)
    // TODO: media/cehtmlmediatypefix.js equivalent
    // TODO: Ensure the object data attribute is set tot the URL of the content (CEA-2014-A 5.7.1)
    // TODO: Ensure the object type attribute is set to the MIME-type of the content (CEA-2014-A 5.7.1.a (1))
    // TODO: Ensure the object element contains a dlna_res_attr param element (CEA-2014-A req 5.7.1.a (2))
    // TODO: Determine if it's possible to support CEA-2014-A req 5.7.1.a (3) - "An <object> element of type video… SHOULD contain a <param> element set to the aspect ratio"
    // TODO: Determine if we should use full screen or windowed mode, which are handled differently. (CEA-2014-A 5.7.1.c / 5.7.3)
    //    - 5.7.1.c - there are differences in full screen and windowed modes - fullscreen is 5.7.3
    //    - 5.7.1.g (5) - setFullScreen (default false, 5.7.1.g (3)) - changing modes SHALL not affect the Z-index. If the <overlay> capability is not none other element can be put on top.
    //    - 5.7.3.a (1) - [full screen] SHOULD scale the video content…
    //    - 5.7.3.b - Inside the browser area, full-screen video objects are regular video objects that SHALL cover the entire browser area
    //    - 5.7.3.c - If there is no longer a visible full-screen video object in the browser area … [it] SHALL switch to non-full-screen mode [which MAY scale the browser area - 5.7.3.d]
    // TODO: Handle "seek" failing (CEA-2014-A 5.7.1.F (13))
    // TODO: Handle "seek" not affecting play state (CEA-2014-A 5.7.1.F (13))
    // TODO: Handle "stop" reverting play position to 0 (CEA-2014-A req 5.7.1.f (12))
    // TODO: Create the object element using document.write or the DOM createElement method instead of directly including an oject tag in the CE-HTML page (CEA-2014-A 5.7.1.j)
    // TODO: ensure we are using XHTML 1.0 transitional and object tags (CEA-2014-1 5.4.a).
    // TODO: ensure that we provide non-CSS settings for properties that don't apply to <object> tags (CEA-2014-A Annex G, p 99 - <object>)
    // TODO: Handle that semantics change if the data is a playlist or a single media item (CEA-2014-A 5.7.1.f) - particularly playPosition, playTime

    //---------------------
    // Common tests
    //---------------------

    // Mixin the common tests shared by all MediaPlayer implementations (last, so it can detect conflicts)
    MixinCommonMediaTests(this.CEHTMLMediaPlayerTests, "antie/devices/mediaplayer/cehtml", config, deviceMockingHooks);

})();
<|endoftext|>


<commit_before>Core.Object.extend('Core.HttpRequest',
/**@lends Core.HttpRequest#*/
{
	url: undefined,
	method: 'GET',
	binary: false,
	request: undefined,
	arguments: undefined,
	content: undefined,
	headers: undefined,

	/**
	*	@constructs
	*	@class
	*	@extends Core.Object
	*/
	constructor: function(config) {
		this.addEvents('error', 'done');

		this.request = new XMLHttpRequest();

		var wrapper = function() {
			var httprequest = arguments.callee.httprequest;
			if(httprequest.request.readyState == 4) {
				if((httprequest.request.status >= 200) && (httprequest.request.status < 300))
					httprequest.fireEvent('done', httprequest);
				else
					httprequest.fireEvent('error', httprequest, httprequest.request.status);
				httprequest.request.onreadystatechange = null;
				httprequest.request = undefined;
			}
		}
		wrapper.httprequest = this;
		this.request.onreadystatechange = wrapper;
	},

	setUrl: function(url) {
		this.url = url;
	},

	setBinary: function(binary) {
		this.binary = binary;
	},

	setMethod: function(method) {
		this.method = method;
	},

	setRequestHeader: function(header, value) {
		if(this.headers == undefined)
			this.headers = {};
		this.headers[header] = value;
	},

	setArguments: function(arguments) {
		this.arguments = arguments;
	},

	addArgument: function(argName, argValue) {
		if(this.arguments == undefined)
			this.arguments = {};
		this.arguments[argName] = argValue;
	},

	setContent: function(content) {
		this.content = content;
	},

	abort: function() {
		this.request.abort();
	},

	send: function() {
		if(this.url == undefined)
			throw('url MUST be given for an HttpRequest');
		// encode arguments
		var args = '';
		if(this.arguments != undefined) {
			args = Core.Util.encodeURIQuery(this.arguments);
		}
		var url = this.url;

		if(((this.method == 'GET') || (this.method == 'DELETE') || (this.content != undefined)) && (args != '')) {
			if(this.url.indexOf('?') == -1)
				url += '?'+args;
			else
				url += '&'+args;
		}
		this.request.open(this.method, url, true);
		if(this.binary)
			this.request.overrideMimeType('text/plain; charset=x-user-defined');
		this.request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
		if(Core.HttpRequest.requestHeaders != undefined) {
			for(var header in Core.HttpRequest.requestHeaders)
				this.request.setRequestHeader(header, Core.HttpRequest.requestHeaders[header]);
		}
		if(this.headers != undefined) {
			for(var header in this.headers)
				this.request.setRequestHeader(header, this.headers[header]);
		}
		if((this.method == 'POST') || (this.method == 'PUT')) {
			if(this.content == undefined) {
				if((this.headers == undefined) || (this.headers["Content-Type"] == undefined))
					this.request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
				this.request.send(args);
			}
			else {
				if((this.headers == undefined) || (this.headers["Content-Type"] == undefined))
					this.request.setRequestHeader('Content-Type', 'text/plain; charset=utf-8');
				this.request.send(this.content);
			}
		}
		// GET, DELETE... method
		else {
			this.request.send();
		}
	},

	getResponseHeader: function(header) {
		return this.request.getResponseHeader(header);
	},

	getResponseText: function() {
		return this.request.responseText;
	},

	getResponseBase64: function() {
		var value = this.request.responseText;
		var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
		var res = '';
		var i = 0;
		while(i + 2 < value.length) {
			var val1 = value.charCodeAt(i++) & 0xff;
			var val2 = value.charCodeAt(i++) & 0xff;
			var val3 = value.charCodeAt(i++) & 0xff;
			var enc1 = code[val1 >> 2];
			var enc2 = code[((val1 & 3) << 4) | (val2 >> 4)];
			var enc3 = code[((val2 & 15) << 2) | (val3 >> 6)];
			var enc4 = code[val3 & 63];
			res += enc1+enc2+enc3+enc4;
		}
		// 2 bytes
		if(i + 1 < value.length) {
			var val1 = value.charCodeAt(i++) & 0xff;
			var val2 = value.charCodeAt(i++) & 0xff;
			var enc1 = code[val1 >> 2];
			var enc2 = code[((val1 & 3) << 4) | (val2 >> 4)];
			var enc3 = code[(val2 & 15) << 2];
			res += enc1+enc2+enc3+'=';
		}
		// 1 byte
		else if(i < value.length) {
			var val1 = value.charCodeAt(i++) & 0xff;
			var enc1 = code[val1 >> 2];
			var enc2 = code[(val1 & 3) << 4];
			res += enc1+enc2+'==';
		}
		return res;
	},

	getResponseJSON: function() {
		var res;
		try {
			res = JSON.parse(this.getResponseText());
		}
		catch(err) {
			res = undefined;
		}
		return res;
	},

	getResponseXML: function() {
		var parser=new DOMParser();
		try {
			var xmlDoc = parser.parseFromString(this.getResponseText(), 'text/xml');
			return xmlDoc;
		} catch(e) {}
		return undefined;
	},

	getStatus: function() {
		return this.request.status;
	}
}, {}, {
	requestHeaders: undefined,

	setRequestHeader: function(header, value) {
		if(Core.HttpRequest.requestHeaders == undefined)
			Core.HttpRequest.requestHeaders =  {};
		Core.HttpRequest.requestHeaders[header] = value;
	}
});

<commit_msg>dont used arguments because it is javascript reserved<commit_after>Core.Object.extend('Core.HttpRequest',
/**@lends Core.HttpRequest#*/
{
	url: undefined,
	method: 'GET',
	binary: false,
	request: undefined,
	arguments: undefined,
	content: undefined,
	headers: undefined,

	/**
	*	@constructs
	*	@class
	*	@extends Core.Object
	*/
	constructor: function(config) {
		this.addEvents('error', 'done');

		this.request = new XMLHttpRequest();

		var wrapper = function() {
			var httprequest = arguments.callee.httprequest;
			if(httprequest.request.readyState == 4) {
				if((httprequest.request.status >= 200) && (httprequest.request.status < 300))
					httprequest.fireEvent('done', httprequest);
				else
					httprequest.fireEvent('error', httprequest, httprequest.request.status);
				httprequest.request.onreadystatechange = null;
				httprequest.request = undefined;
			}
		}
		wrapper.httprequest = this;
		this.request.onreadystatechange = wrapper;
	},

	setUrl: function(url) {
		this.url = url;
	},

	setBinary: function(binary) {
		this.binary = binary;
	},

	setMethod: function(method) {
		this.method = method;
	},

	setRequestHeader: function(header, value) {
		if(this.headers == undefined)
			this.headers = {};
		this.headers[header] = value;
	},

	setArguments: function(args) {
		this.arguments = args;
	},

	addArgument: function(argName, argValue) {
		if(this.arguments == undefined)
			this.arguments = {};
		this.arguments[argName] = argValue;
	},

	setContent: function(content) {
		this.content = content;
	},

	abort: function() {
		this.request.abort();
	},

	send: function() {
		if(this.url == undefined)
			throw('url MUST be given for an HttpRequest');
		// encode arguments
		var args = '';
		if(this.arguments != undefined) {
			args = Core.Util.encodeURIQuery(this.arguments);
		}
		var url = this.url;

		if(((this.method == 'GET') || (this.method == 'DELETE') || (this.content != undefined)) && (args != '')) {
			if(this.url.indexOf('?') == -1)
				url += '?'+args;
			else
				url += '&'+args;
		}
		this.request.open(this.method, url, true);
		if(this.binary)
			this.request.overrideMimeType('text/plain; charset=x-user-defined');
		this.request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
		if(Core.HttpRequest.requestHeaders != undefined) {
			for(var header in Core.HttpRequest.requestHeaders)
				this.request.setRequestHeader(header, Core.HttpRequest.requestHeaders[header]);
		}
		if(this.headers != undefined) {
			for(var header in this.headers)
				this.request.setRequestHeader(header, this.headers[header]);
		}
		if((this.method == 'POST') || (this.method == 'PUT')) {
			if(this.content == undefined) {
				if((this.headers == undefined) || (this.headers["Content-Type"] == undefined))
					this.request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
				this.request.send(args);
			}
			else {
				if((this.headers == undefined) || (this.headers["Content-Type"] == undefined))
					this.request.setRequestHeader('Content-Type', 'text/plain; charset=utf-8');
				this.request.send(this.content);
			}
		}
		// GET, DELETE... method
		else {
			this.request.send();
		}
	},

	getResponseHeader: function(header) {
		return this.request.getResponseHeader(header);
	},

	getResponseText: function() {
		return this.request.responseText;
	},

	getResponseBase64: function() {
		var value = this.request.responseText;
		var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
		var res = '';
		var i = 0;
		while(i + 2 < value.length) {
			var val1 = value.charCodeAt(i++) & 0xff;
			var val2 = value.charCodeAt(i++) & 0xff;
			var val3 = value.charCodeAt(i++) & 0xff;
			var enc1 = code[val1 >> 2];
			var enc2 = code[((val1 & 3) << 4) | (val2 >> 4)];
			var enc3 = code[((val2 & 15) << 2) | (val3 >> 6)];
			var enc4 = code[val3 & 63];
			res += enc1+enc2+enc3+enc4;
		}
		// 2 bytes
		if(i + 1 < value.length) {
			var val1 = value.charCodeAt(i++) & 0xff;
			var val2 = value.charCodeAt(i++) & 0xff;
			var enc1 = code[val1 >> 2];
			var enc2 = code[((val1 & 3) << 4) | (val2 >> 4)];
			var enc3 = code[(val2 & 15) << 2];
			res += enc1+enc2+enc3+'=';
		}
		// 1 byte
		else if(i < value.length) {
			var val1 = value.charCodeAt(i++) & 0xff;
			var enc1 = code[val1 >> 2];
			var enc2 = code[(val1 & 3) << 4];
			res += enc1+enc2+'==';
		}
		return res;
	},

	getResponseJSON: function() {
		var res;
		try {
			res = JSON.parse(this.getResponseText());
		}
		catch(err) {
			res = undefined;
		}
		return res;
	},

	getResponseXML: function() {
		var parser=new DOMParser();
		try {
			var xmlDoc = parser.parseFromString(this.getResponseText(), 'text/xml');
			return xmlDoc;
		} catch(e) {}
		return undefined;
	},

	getStatus: function() {
		return this.request.status;
	}
}, {}, {
	requestHeaders: undefined,

	setRequestHeader: function(header, value) {
		if(Core.HttpRequest.requestHeaders == undefined)
			Core.HttpRequest.requestHeaders =  {};
		Core.HttpRequest.requestHeaders[header] = value;
	}
});

<|endoftext|>


<commit_before>import React, { Component } from "react";
import styled from "styled-components";
import { Link } from "react-router-dom";

import itlogo from "./itlogo.svg";

class AppHeader extends Component {
  render() {
    return (
      <Banner>
        <HeaderContainer>
          <Header>
            <Title>
              speakIT <SmallTitle>digital talarlista</SmallTitle>
            </Title>
            <Link to="/">
              <ITLogo src={itlogo} />
            </Link>
          </Header>
        </HeaderContainer>

        <NavigationContainer>
          <Navigation>
            <NavigationItem to="/user">Användare</NavigationItem>
            <NavigationItem to="/list">Listor</NavigationItem>
            <NavigationItem to="/admin">Admin</NavigationItem>
          </Navigation>
        </NavigationContainer>
      </Banner>
    );
  }
}

const HeaderContainer = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-around;
  height: 250px;
`;

const Banner = styled.div`
  height: 250px;
  background-color: #ffffff;
  box-shadow: 0 0 9px 2px rgba(0, 0, 0, 0.3);
  margin-bottom: 5rem;
`;

const Header = styled.header`
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-flow: row-wrap;
  width: 100%;
  padding: 0 1rem;
`;

const ITLogo = styled.img`
  width: 142px;
  height: 142px;
`;

const Title = styled.div`
  height: 68px;
  font-family: Helvetica Neue, Helvetica, Roboto, Arial, sans-serif;
  font-size: 3rem;
  font-weight: 500;
  color: #4a4a4a;
`;

const SmallTitle = styled.small`
  font-weight: 200;
  font-size: 80%;
`;

const NavigationContainer = styled.div`
  height: 3em;
  box-shadow: 0 5px 5px 0 rgba(0, 0, 0, 0.3);
  background-color: #c4c4c4;
  display: flex;
  justify-content: space-around;
`;

const Navigation = styled.nav`display: flex;`;

const NavigationItem = styled(Link)`
  width: 200px;
  display: flex;
  align-items: center;
  justify-content: space-around;
  background-color: #c4c4c4;
  text-decoration: none;
  color: #4a4a4a;
  font-family: AvenirNext;
  font-weight: bold;
  font-size: 1.25rem;
  :hover {
    background-color: #E4E4E4;
  }
  :active {
    background-color: #D4D4D4;
  }
`;

export default AppHeader;
<commit_msg>Add header max-width for larger displays.<commit_after>import React, { Component } from "react";
import styled from "styled-components";
import { Link } from "react-router-dom";

import itlogo from "./itlogo.svg";

class AppHeader extends Component {
  render() {
    return (
      <Banner>
        <HeaderContainer>
          <Header>
            <Title>
              speakIT <SmallTitle>digital talarlista</SmallTitle>
            </Title>
            <Link to="/">
              <ITLogo src={itlogo} />
            </Link>
          </Header>
        </HeaderContainer>

        <NavigationContainer>
          <Navigation>
            <NavigationItem to="/user">Användare</NavigationItem>
            <NavigationItem to="/list">Listor</NavigationItem>
            <NavigationItem to="/admin">Admin</NavigationItem>
          </Navigation>
        </NavigationContainer>
      </Banner>
    );
  }
}

const HeaderContainer = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-around;
  height: 250px;
`;

const Banner = styled.div`
  height: 250px;
  background-color: #ffffff;
  box-shadow: 0 0 9px 2px rgba(0, 0, 0, 0.3);
  margin-bottom: 5rem;
`;

const Header = styled.header`
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-flow: row-wrap;
  width: 100%;
  max-width: 75em;
  padding: 0 1rem;
`;

const ITLogo = styled.img`
  width: 142px;
  height: 142px;
`;

const Title = styled.div`
  height: 68px;
  font-family: Helvetica Neue, Helvetica, Roboto, Arial, sans-serif;
  font-size: 3rem;
  font-weight: 500;
  color: #4a4a4a;
`;

const SmallTitle = styled.small`
  font-weight: 200;
  font-size: 80%;
`;

const NavigationContainer = styled.div`
  height: 3em;
  box-shadow: 0 5px 5px 0 rgba(0, 0, 0, 0.3);
  background-color: #c4c4c4;
  display: flex;
  justify-content: space-around;
`;

const Navigation = styled.nav`display: flex;`;

const NavigationItem = styled(Link)`
  width: 200px;
  display: flex;
  align-items: center;
  justify-content: space-around;
  background-color: #c4c4c4;
  text-decoration: none;
  color: #4a4a4a;
  font-family: AvenirNext;
  font-weight: bold;
  font-size: 1.25rem;
  :hover {
    background-color: #E4E4E4;
  }
  :active {
    background-color: #D4D4D4;
  }
`;

export default AppHeader;
<|endoftext|>