<commit_before>// ==UserScript==
// @name		Mega Scratch Userscript (base/bootstrap)
// @author		MegaScratchUserscript (collab with some Scratch ATers: https://github.com/MegaScratchUserscript/Mega-Scratch-Userscript#-mega-scratch-userscript)
// @description	A mega userscript with tons of epic uses!
// @include		http://scratch.mit.edu/*
// @version		0.1
// @grant		unsafeWindow
// @grant		GM_getResourceText
// @grant		GM_addStyle
// @icon		resources/icon.png
// @require		https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @require		https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js
// @require		resources/waitForKeyElements.js
// @require		resources/msuinit.js
// @require		resources/extensions.js
// @require		parts/scratchforum.part.js
// @require		parts/scratchtheme.part.js
// @require		parts/scratchystuff.part.js
// @require		parts/feed.part.js
// @resource	settingshtml resources/settings.htmlpart
// @resource	settingscss resources/settings.css
// ==/UserScript==

// I called this base.user.js in case this is the main script
var ScratchUserscript = {
    MODE_DEV: true, // change to false in the release; use this flag to print data to console for debug, etc
	_settingsHTML: $("

"),
	_partsEnabled: {},
	_init: function(){
		if(typeof localStorage != 'undefined'){
			if(typeof localStorage.msuPartsEnabled == 'undefined'){
				localStorage.msuPartsEnabled = "{themeeffects:false}";
			}
			ScratchUserscript._partsEnabled = JSON.parse(localStorage.msuPartsEnabled);
		}
		ScratchUserscript._settingsHTML.css("display","none").appendTo(document.body).dialog({autoOpen: false, width: 800, height: 400});
		$("#msu-settings-dialog").parent().append('<html><head></head><body></body></html>');
		ScratchUserscript._settingsHTML.html(GM_getResourceText("settingshtml"));
		GM_addStyle(GM_getResourceText("settingscss"));
		var openSettings = $("<acronym title='Mega Scratch Userscript'>MSU</acronym> Settings");
		openSettings.click(function(){
			ScratchUserscript._settingsHTML.dialog("open");
		});
		$("

").append(openSettings).insertBefore($(".user-nav .logout"));

		for(x in msuParts){
			if(typeof msuParts[x] !== "undefined"){
				(msuParts[x])(ScratchUserscript);
			}
		}
		if(ScratchUserscript.MODE_DEV){
			console.log("Scratchuserscript started!");
		}
	},
	readSetting: function(partName, settingName, defaultValue){
		if(typeof localStorage != 'undefined'){
			var settings = {};
			if(typeof localStorage.msuSettingsStorage != 'undefined'){
				settings = JSON.parse(localStorage.msuSettingsStorage);
			}
			if(settings.hasOwnProperty(partName+"-"+settingName)){
				return settings[partName+"-"+settingName];
			} else return defaultValue;
		}
	},
	writeSetting: function(partName, settingName, settingValue){
		if(typeof localStorage != 'undefined'){
			var settings = {};
			if(typeof localStorage.msuSettingsStorage != 'undefined'){
				settings = JSON.parse(localStorage.msuSettingsStorage);
			}
			settings[partName+"-"+settingName] = settingValue;
			localStorage.msuSettingsStorage = JSON.stringify(settings);
		}
	},
	/**
	 * Returns if a part is enabled (as per the settings GUI)
	 * It's up to parts to call this and check
	 * @return true if enabled, false otherwise
	 */
	isPartEnabled: function(name){
		if(!ScratchUserscript._partsEnabled.hasOwnProperty(name.replace(/[^a-zA-Z\d]/g, "").toLowerCase())){
			return true; // not in the object = enabled
		}
		if(ScratchUserscript._partsEnabled[name.replace(/[^a-zA-Z\d]/g, "").toLowerCase()]){
			return true;
		}
		return false;
	},
	/**
	 * Registers a part of the userscript onto the settings dialog
	 * @param name The name of the part
	 * @param description A description
	 * @param settings HTML for the part's settings page, if any
	 */
	registerPart: function(name, description, settings){
		// almost verbatim copied from my test JSFiddle: http://jsfiddle.net/a8cewv3u/
		// very messy, should be cleaned up

		var qualifiedName = name.replace(/[^a-zA-Z\d]/g, "").toLowerCase();
		if(ScratchUserscript.MODE_DEV)
			console.log("Part registered name="+name+" qualifiedName="+qualifiedName);
		var li = $("

");
		var isEnabled = ScratchUserscript.isPartEnabled(name);
		li.append($("<input data-ischeck='yup' type='checkbox' title='Enable this' id='enable-" + qualifiedName + "' data-for='" + qualifiedName + "' />")
				.bind('change', function () {
			ck = $(this).is(":checked");
			$("#isenabled-" + $(this).attr("data-for")).text(ck ? "yes":"no");
			ScratchUserscript._partsEnabled[$(this).attr("data-for")] = ck;
			if(typeof localStorage != 'undefined'){
				localStorage.msuPartsEnabled = JSON.stringify(ScratchUserscript._partsEnabled);
			}
		}).attr("checked", isEnabled));
		li.append($("" + name + "").attr("data-for", qualifiedName));
		li.click(function (e) {
			if ($(e.target).attr("data-ischeck") == 'yup') return;
			ScratchUserscript._settingsHTML.find(".msu-settings-content-div").slideUp();
			ScratchUserscript._settingsHTML.find("#msu-settings-content-" + $(this).find("label").attr("data-for")).slideDown();
			ScratchUserscript._settingsHTML.find(".msu-settings-side-tabs li").removeClass("sel");
			$(this).addClass("sel");
		});
		ScratchUserscript._settingsHTML.find(".msu-settings-side-tabs").append(li);
		var content = $("

");
		content.append("
" + name + "
").append("Enabled: no
");
		if(isEnabled) content.find("#isenabled-"+qualifiedName).text("yes");
		content.append("Description: "+description + "

")
			.append(settings == null ? "No additional settings" : settings);
		content.attr("id", "msu-settings-content-" + qualifiedName)
			.css("display", "none").addClass("msu-settings-content-div")
			.appendTo(ScratchUserscript._settingsHTML.find(".msu-settings-content"));
		if(ScratchUserscript._settingsHTML.find('.msu-settings-side-tabs li.sel').length==0){
			li.addClass("sel");
			content.show();
		}
	},
	/**
	 * Gets the page type
	 * @return The type, in the form of a JSON object:
	 *		type: either project, studio, messages, mystuff, settings, forum, or unknown
	 *		subtype: in forums, either section, topic, or null
	 *  	id: the forum topic id, project id, studio id, etc
	 */
	getPageType: function(){
		var obj = {type: "unknown", subtype: null, id: null};
		if (/^\/projects\/\d+\/$/.test(location.pathname)){
			obj.type = "project";
			obj.id = parseInt(/^\/projects\/(\d+)\/$/.exec(location.pathname)[1]);
		}
		if (/^\/studios\/\d+\/$/.test(location.pathname)){
			obj.type = "studio";
			obj.id = parseInt(/^\/studios\/(\d+)\/$/.exec(location.pathname)[1]);
		}
		if(/^\/discuss\//.test(location.pathname)){
			obj.type = "forum";
			if(/^\/discuss\/\d+\/$/.test(location.pathname)){
				obj.subtype = "section";
				obj.id = parseInt(/^\/discuss\/(\d+)\/$/.exec(location.pathname)[1]);
			}
			if(/^\/discuss\/topic\/\d+\//.test(location.pathname)){
				obj.subtype = "topic";
				obj.id = parseInt(/^\/discuss\/topic\/(\d+)\//.exec(location.pathname)[1]);
			}
		}
		if (/^\/accounts\/(password_change|email_change|change_country)\/$/.test(location.pathname)){
			obj.type = "settings";
		}
		if (location.pathname == '/messages/'){
			obj.type = "messages";
		}
		if (location.pathname == '/mystuff/'){
			obj.type = "mystuff";
		}
		return obj;
	},
	/**
	 * @return The username of the currently logged in user, or null if not logged in
	 */
	getUsername: function(){
		return unsafeWindow.Scratch.INIT_DATA.LOGGED_IN_USER.model ? unsafeWindow.Scratch.INIT_DATA.LOGGED_IN_USER.model.username : null;
	}
};

$(document).ready(ScratchUserscript._init);
<commit_msg>Added 'profile page' to getPageType function.<commit_after>// ==UserScript==
// @name		Mega Scratch Userscript (base/bootstrap)
// @author		MegaScratchUserscript (collab with some Scratch ATers: https://github.com/MegaScratchUserscript/Mega-Scratch-Userscript#-mega-scratch-userscript)
// @description	A mega userscript with tons of epic uses!
// @include		http://scratch.mit.edu/*
// @version		0.1
// @grant		unsafeWindow
// @grant		GM_getResourceText
// @grant		GM_addStyle
// @icon		resources/icon.png
// @require		https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @require		https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js
// @require		resources/waitForKeyElements.js
// @require		resources/msuinit.js
// @require		resources/extensions.js
// @require		parts/scratchforum.part.js
// @require		parts/scratchtheme.part.js
// @require		parts/scratchystuff.part.js
// @require		parts/feed.part.js
// @resource	settingshtml resources/settings.htmlpart
// @resource	settingscss resources/settings.css
// ==/UserScript==

// I called this base.user.js in case this is the main script
var ScratchUserscript = {
    MODE_DEV: true, // change to false in the release; use this flag to print data to console for debug, etc
	_settingsHTML: $("

"),
	_partsEnabled: {},
	_init: function(){
		if(typeof localStorage != 'undefined'){
			if(typeof localStorage.msuPartsEnabled == 'undefined'){
				localStorage.msuPartsEnabled = "{themeeffects:false}";
			}
			ScratchUserscript._partsEnabled = JSON.parse(localStorage.msuPartsEnabled);
		}
		ScratchUserscript._settingsHTML.css("display","none").appendTo(document.body).dialog({autoOpen: false, width: 800, height: 400});
		$("#msu-settings-dialog").parent().append('<html><head></head><body></body></html>');
		ScratchUserscript._settingsHTML.html(GM_getResourceText("settingshtml"));
		GM_addStyle(GM_getResourceText("settingscss"));
		var openSettings = $("<acronym title='Mega Scratch Userscript'>MSU</acronym> Settings");
		openSettings.click(function(){
			ScratchUserscript._settingsHTML.dialog("open");
		});
		$("

").append(openSettings).insertBefore($(".user-nav .logout"));

		for(x in msuParts){
			if(typeof msuParts[x] !== "undefined"){
				(msuParts[x])(ScratchUserscript);
			}
		}
		if(ScratchUserscript.MODE_DEV){
			console.log("Scratchuserscript started!");
		}
	},
	readSetting: function(partName, settingName, defaultValue){
		if(typeof localStorage != 'undefined'){
			var settings = {};
			if(typeof localStorage.msuSettingsStorage != 'undefined'){
				settings = JSON.parse(localStorage.msuSettingsStorage);
			}
			if(settings.hasOwnProperty(partName+"-"+settingName)){
				return settings[partName+"-"+settingName];
			} else return defaultValue;
		}
	},
	writeSetting: function(partName, settingName, settingValue){
		if(typeof localStorage != 'undefined'){
			var settings = {};
			if(typeof localStorage.msuSettingsStorage != 'undefined'){
				settings = JSON.parse(localStorage.msuSettingsStorage);
			}
			settings[partName+"-"+settingName] = settingValue;
			localStorage.msuSettingsStorage = JSON.stringify(settings);
		}
	},
	/**
	 * Returns if a part is enabled (as per the settings GUI)
	 * It's up to parts to call this and check
	 * @return true if enabled, false otherwise
	 */
	isPartEnabled: function(name){
		if(!ScratchUserscript._partsEnabled.hasOwnProperty(name.replace(/[^a-zA-Z\d]/g, "").toLowerCase())){
			return true; // not in the object = enabled
		}
		if(ScratchUserscript._partsEnabled[name.replace(/[^a-zA-Z\d]/g, "").toLowerCase()]){
			return true;
		}
		return false;
	},
	/**
	 * Registers a part of the userscript onto the settings dialog
	 * @param name The name of the part
	 * @param description A description
	 * @param settings HTML for the part's settings page, if any
	 */
	registerPart: function(name, description, settings){
		// almost verbatim copied from my test JSFiddle: http://jsfiddle.net/a8cewv3u/
		// very messy, should be cleaned up

		var qualifiedName = name.replace(/[^a-zA-Z\d]/g, "").toLowerCase();
		if(ScratchUserscript.MODE_DEV)
			console.log("Part registered name="+name+" qualifiedName="+qualifiedName);
		var li = $("

");
		var isEnabled = ScratchUserscript.isPartEnabled(name);
		li.append($("<input data-ischeck='yup' type='checkbox' title='Enable this' id='enable-" + qualifiedName + "' data-for='" + qualifiedName + "' />")
				.bind('change', function () {
			ck = $(this).is(":checked");
			$("#isenabled-" + $(this).attr("data-for")).text(ck ? "yes":"no");
			ScratchUserscript._partsEnabled[$(this).attr("data-for")] = ck;
			if(typeof localStorage != 'undefined'){
				localStorage.msuPartsEnabled = JSON.stringify(ScratchUserscript._partsEnabled);
			}
		}).attr("checked", isEnabled));
		li.append($("" + name + "").attr("data-for", qualifiedName));
		li.click(function (e) {
			if ($(e.target).attr("data-ischeck") == 'yup') return;
			ScratchUserscript._settingsHTML.find(".msu-settings-content-div").slideUp();
			ScratchUserscript._settingsHTML.find("#msu-settings-content-" + $(this).find("label").attr("data-for")).slideDown();
			ScratchUserscript._settingsHTML.find(".msu-settings-side-tabs li").removeClass("sel");
			$(this).addClass("sel");
		});
		ScratchUserscript._settingsHTML.find(".msu-settings-side-tabs").append(li);
		var content = $("

");
		content.append("
" + name + "
").append("Enabled: no
");
		if(isEnabled) content.find("#isenabled-"+qualifiedName).text("yes");
		content.append("Description: "+description + "

")
			.append(settings == null ? "No additional settings" : settings);
		content.attr("id", "msu-settings-content-" + qualifiedName)
			.css("display", "none").addClass("msu-settings-content-div")
			.appendTo(ScratchUserscript._settingsHTML.find(".msu-settings-content"));
		if(ScratchUserscript._settingsHTML.find('.msu-settings-side-tabs li.sel').length==0){
			li.addClass("sel");
			content.show();
		}
	},
	/**
	 * Gets the page type
	 * @return The type, in the form of a JSON object:
	 *		type: either project, studio, messages, mystuff, settings, forum, profile, or unknown
	 *		subtype: in forums, either section, topic, or null
	 *  	id: the forum topic id, project id, studio id, etc
	 */
	getPageType: function(){
		var obj = {type: "unknown", subtype: null, id: null};
		if (/^\/projects\/\d+\/$/.test(location.pathname)){
			obj.type = "project";
			obj.id = parseInt(/^\/projects\/(\d+)\/$/.exec(location.pathname)[1]);
		}
		if (/^\/studios\/\d+\/$/.test(location.pathname)){
			obj.type = "studio";
			obj.id = parseInt(/^\/studios\/(\d+)\/$/.exec(location.pathname)[1]);
		}
		if (/^\/users\/\d+\/$/.test(location.pathname)){
			obj.type = "profile";
			obj.id = parseInt(/^\/users\/(\d+)\/$/.exec(location.pathname)[1]);
		}
		if(/^\/discuss\//.test(location.pathname)){
			obj.type = "forum";
			if(/^\/discuss\/\d+\/$/.test(location.pathname)){
				obj.subtype = "section";
				obj.id = parseInt(/^\/discuss\/(\d+)\/$/.exec(location.pathname)[1]);
			}
			if(/^\/discuss\/topic\/\d+\//.test(location.pathname)){
				obj.subtype = "topic";
				obj.id = parseInt(/^\/discuss\/topic\/(\d+)\//.exec(location.pathname)[1]);
			}
		}
		if (/^\/accounts\/(password_change|email_change|change_country)\/$/.test(location.pathname)){
			obj.type = "settings";
		}
		if (location.pathname == '/messages/'){
			obj.type = "messages";
		}
		if (location.pathname == '/mystuff/'){
			obj.type = "mystuff";
		}
		return obj;
	},
	/**
	 * @return The username of the currently logged in user, or null if not logged in
	 */
	getUsername: function(){
		return unsafeWindow.Scratch.INIT_DATA.LOGGED_IN_USER.model ? unsafeWindow.Scratch.INIT_DATA.LOGGED_IN_USER.model.username : null;
	}
};

$(document).ready(ScratchUserscript._init);
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { fetchPost, deletePost } from '../actions';

class PostsShow extends Component {
  componentDidMount() {
    const { id } = this.props.match.params;
    this.props.fetchPost(id);
  }

  onDeleteClick() {
    const { id } = this.props.match.params;
    this.props.deletePost(id, () => {
      this.props.history.push('/');
    });
  }

  render() {
    const { post } = this.props;

    if (!post) {
      return
Loading...
;
    }

    return (

        <Link to="/">Back To Index</Link>
        <button
          className="btn btn-danger pull-xs-right"
          onClick={this.onDeleteClick.bind(this)}
        >
          Delete Post
        </button>

{post.title}

Categories: {post.categories}

{post.content}

    );
  }
}

function mapStateToProps({ posts }, ownProps) {
  return { post: posts[ownProps.match.params.id] };
}

export default connect(mapStateToProps, { fetchPost, deletePost })(PostsShow);
<commit_msg>Add comments to PostsShow<commit_after>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { fetchPost, deletePost } from '../actions';

class PostsShow extends Component {
  componentDidMount() {
    // fetch post with id that matches ID param value in URL
    const { id } = this.props.match.params;
    this.props.fetchPost(id);
  }

  onDeleteClick() {
    // delete post with id that matches ID param value in URL
    const { id } = this.props.match.params;
    // pass callback to action creator to redirect after post deletion
    this.props.deletePost(id, () => {
      this.props.history.push('/');
    });
  }

  render() {
    const { post } = this.props;

    if (!post) {
      return
Loading...
;
    }

    return (

        <Link to="/">Back To Index</Link>
        <button
          className="btn btn-danger pull-xs-right"
          onClick={this.onDeleteClick.bind(this)}
        >
          Delete Post
        </button>

{post.title}

Categories: {post.categories}

{post.content}

    );
  }
}

function mapStateToProps({ posts }, ownProps) {
  // in 'posts' state, find post with key/id that matches id param value in URL
  // pass as prop
  return { post: posts[ownProps.match.params.id] };
}

// connect Redux state to PostsIndex component by having Redux pass
// necessary pieces of state and action creators as props
export default connect(mapStateToProps, { fetchPost, deletePost })(PostsShow);
<|endoftext|>


<commit_before>import React from 'react'
import styles from '../styles/QuotesListStyles.scss'
import Firebase from 'firebase'
import constants from 'utils/constants'
import { Link } from 'react-router'

const ref = new Firebase(constants.FIREBASE)

export class QuoteTile extends React.Component {

  static propTypes = {
    quote: React.PropTypes.object,
    id: React.PropTypes.string
  }

  viewItem (e) {
    console.log('view')
  }

  editItem (e) {
    console.log(this.props)
  }

  deleteItem (e) {
    let quote = ref.child('quotes/' + this.props.id)
    if (window.confirm('Do you really want to delete this?')) {
      quote.remove()
    }
  }

  render () {
    console.log(this.props)
    return (

          {this.props.quote.text}

          <Link to={`/quotes/view/${this.props.id}`}>View</Link>
          <Link to={`/quotes/edit/${this.props.id}`}>Edit</Link>
          Delete

    )
  }
}

export default QuoteTile
<commit_msg>style (bg image)<commit_after>import React from 'react'
import styles from '../styles/QuotesListStyles.scss'
import Firebase from 'firebase'
import constants from 'utils/constants'
import { Link } from 'react-router'

const ref = new Firebase(constants.FIREBASE)

export class QuoteTile extends React.Component {

  static propTypes = {
    quote: React.PropTypes.object,
    id: React.PropTypes.string
  }

  viewItem (e) {
    console.log('view')
  }

  editItem (e) {
    console.log(this.props)
  }

  deleteItem (e) {
    let quote = ref.child('quotes/' + this.props.id)
    if (window.confirm('Do you really want to delete this?')) {
      quote.remove()
    }
  }

  render () {
    console.log(this.props)

    var bgImage = {
        backgroundImage: 'url('+this.props.quote.image+')'
    }

    return (

          {this.props.quote.text}

          <Link to={`/quotes/view/${this.props.id}`}>View</Link>
          <Link to={`/quotes/edit/${this.props.id}`}>Edit</Link>
          Delete

    )
  }
}

export default QuoteTile
<|endoftext|>


<commit_before>PER_PAGE = 50;

var authorTemplate = Handlebars.compile($('#timeline-author-template').html());

Handlebars.registerHelper('eachCommit', function(context, options) {
  var ret = "";

  for(var i=0, j=context.length; i<j; i++) {
    ret = ret + options.fn(context[i]);
  }

  return ret;
});

function formatAuthor(author) {
    var login = author.login;
    var avatarURL = author.avatar_url;
    var githubURL = 'http://github.com/' + login;

    return {
        username: login,
        avatar: avatarURL,
        githubURL: githubURL
    };
}

function formatPayload (payload) {
  var data = {
    comment: '',
    count: '',
    commits: '',
    diffTree: '',
    labels: []
  };
  if (payload.comment) {
    data.comment = payload.comment.body;
    // FIXME: @piatra
    if (payload.issue) {
      data.count = payload.issue.comments;
    } else {
      data.count = 0;
    }
  }
  if (payload.issue) {
    data.labels = payload.issue.labels;
  }
  if (payload.commits) {
    data.diffTree = payload.before.substr(0,10) + '...' + payload.head.substr(0,10);
    data.commits = payload.commits.map(function(commit) {
      return {
        commitUrl: commit.url,
        message: commit.message,
        sha: commit.sha.substr(0,10)
      };
    });
  }
  return data;
}

function formatLink(href, text, title) {
    if (title) {
        return '' + text + '';
    }
    return '' + text + '';
}

function formatIssue(issue) {
    return formatLink(issue.html_url, '#' + issue.number, issue.title);
}

var TIMELINE_MAPPING = {
    'CommitCommentEvent': {
        action: function(e) {
            return "commented on";
        },
        object: function(e) {
            var url = e.payload.comment.html_url;
            url = url.substring(0, url.lastIndexOf('#'));

            var sha = url.substring(url.lastIndexOf('/') + 1);
            return formatLink(url, sha.substring(0, 7));
        },
        link: function(e) {
            return e.payload.comment.html_url;
        }
    },
    'CreateEvent': {
        action: function(e) {
            var s = "created";
            if (e.payload.ref_type == 'branch') {
                return s + " branch";
            } else if (e.payload.ref_type == 'tag') {
                return s + " tag";
            }
            return s;
        },
        object: function(e) {
            return e.payload.ref;
        },
    },
    'DeleteEvent': {
        action: function(e) {
            var s = "deleted";
            if (e.payload.ref_type == 'branch') {
                return s + " branch";
            } else if (e.payload.ref_type == 'tag') {
                return s + " tag";
            }
            return s;
        },
        object: function(e) {
            return e.payload.ref;
        },
    },
    'ForkEvent': {
        action: function(e) {
            return "forked to";
        },
        object: function(e) {
            var name = e.payload.forkee.full_name;
            var url = e.payload.forkee.html_url;
            return formatLink(url, name);
        }
    },
    'GollumEvent': {
        action: function(e) {
            var page = e.payload.pages[0];
            return page.action;
        },
        object: function(e) {
            var page = e.payload.pages[0];
            return "wiki page " + formatLink(page.html_url, page.page_name);
        }
    },
    'IssueCommentEvent': {
        title: function(e) {
          return e.payload.issue.title;
        },
        action: function(e) {
            return "commented on";
        },
        object: function(e) {
            return formatIssue(e.payload.issue);
        },
        link: function(e) {
            return e.payload.comment.html_url;
        },
        assignee: function(e) {
            var assignee = e.payload.issue.assignee;
            if (assignee) {
                return assignee.login;
            }
            return 'no one';
        },
        number: function(e) {
          return e.payload.issue.number;
        },
        issue_age: function(e) {
          return moment().from(e.payload.issue.created_at, true);
        },
        issueURL: function(e) {
          if (e.payload && e.payload.comment) {
            var url = e.payload.comment.html_url.split('#')[0];
            return url;
          } else {
            return '';
          }
        }
    },
    'IssuesEvent': {
        action: function(e) {
            return e.payload.action;
        },
        object: function(e) {
            return formatIssue(e.payload.issue);
        },
        assignee: function(e) {
            var assignee = e.payload.issue.assignee;
            if (assignee) {
                return assignee.login;
            }
            return 'nobody';
        },
        title: function(e) {
          return e.payload.issue.title;
        },
        number: function(e) {
          return e.payload.issue.number;
        },
        issue_age: function(e) {
          return moment().from(e.payload.issue.created_at, true);
        },
        issueURL: function(e) {
          if (e.payload && e.payload.comment) {
            var url = e.payload.comment.html_url.split('#')[0];
            return url;
          } else {
            return '';
          }
        }
    },
    'MemberEvent': {
        action: function(e) {
            return "added";
        },
        object: function(e) {
            var user = e.payload.member;
            return formatLink(user.html_url, user.login) + " as a collaborator";
        }
    },
    'PublicEvent': {
        action: function(e) {
            return "open sourced";
        },
        object: function(e) {
            return "the repository";
        }
    },
    'PullRequestEvent': {
        action: function(e) {
            return e.payload.action;
        },
        object: function(e) {
            var pullReq = e.payload.pull_request;
            return "pull request " + formatIssue(pullReq);
        },
        title: function(e) {
          return e.payload.pull_request.title;
        },
        number: function(e) {
          return e.payload.pull_request.number;
        },
        issueURL: function(e) {
          return e.payload.pull_request.comments_url;
        },
        changes: function(e) {
          return {
            additions: e.payload.pull_request.additions,
            deletions: e.payload.pull_request.deletions
          };
        },
        issue_age: function(e) {
          return moment().from(e.payload.pull_request.created_at, true);
        },
    },
    'PullRequestReviewCommentEvent': {
        action: function(e) {
            return "reviewed";
        },
        object: function(e) {
            var url = e.payload.comment.pull_request_url;
            var number = url.substring(url.lastIndexOf('/') + 1);
            var htmlURL = e.payload.comment.html_url;
            var pullReqURL = htmlURL.substring(0, htmlURL.lastIndexOf('#'));
            return "pull request " + makeLink(pullReqURL, '#' + number);
        },
        link: function(e) {
            return e.payload.comment.html_url;
        }
    },
    'PushEvent': {
        action: function(e) {
            return "pushed";
        },
        object: function(e) {
            var count = e.payload.size;
            return count + " commits";
        },
        link: function(e) {
            var head = e.payload.head;
            var repo = e.repo.name;
            var url = 'http://github.com/' + repo + '/commit/' + head;
            return url;
        }
    },
    'WatchEvent': {
        action: function(e) {
            return "starred";
        },
        object: function(e) {
            return "the repository";
        }
    },
    'TeamAddEvent': {
      action: function(e) {
        return 'Team add event';
      },
      object: function(e) {
        return 'for ' + e.payload.team.name;
      }
    },
    'EndOfTimeline': {
        action: function (e) {
            return "No more events available";
        },
        object: function (e) {
            return;
        }
    }
};

function formatContext (e) {
  var mapping = TIMELINE_MAPPING[e.type];

  if (!mapping) {
    if (!e.body) {
      // FIXME: need better handling for this
      // can't figure out what kind of event this is
      return;
    }
    context = {
      avatar: e.user.avatar_url,
      username: e.user.login,
      comment: e.body,
      number: e.number,
      issue_age: moment().from(e.created_at, true),
      commentCount: e.comments,
      commits: [],
      diffTree: '',
      url: '',
      assignee: e.assignee || 'no one',
      action: 'commented: ',
      object: '',
      timestamp: moment().from(e.created_at, true),
      title: e.title
    };
  } else {
    context = {
      avatar: formatAuthor(e.actor).avatar,
      username: formatAuthor(e.actor).username,
      comment: formatPayload(e.payload).comment,
      number: mapping.number ? mapping.number(e) : 0,
      issue_age: mapping.issue_age ? mapping.issue_age(e) : 0,
      labels: formatPayload(e.payload).labels,
      commentCount: formatPayload(e.payload).count,
      commits: formatPayload(e.payload).commits,
      diffTree: formatPayload(e.payload).diffTree,
      url: e.repo.name,
      assignee: mapping.assignee ? mapping.assignee(e) : 'no one',
      action: mapping.action(e),
      object: mapping.object(e),
      timestamp: moment(e.created_at).fromNow(),
      title: mapping.title ? mapping.title(e) : ''
    };
  }

  if (context.number && context.title) {
    if (mapping) {
      context.issueURL = mapping.issueURL(e);
    } else {
      context.issueURL = e.html_url;
    }
  }
  if (mapping && mapping.changes) {
    // changes refer to additions & deletions in a pull request
    context.changes = mapping.changes(e);
  }
  return context;
}

function populateTimeline(count, starting_from) {
    var $timeline = $('#timeline');
    var template = Handlebars.compile($('#timeline-item-template').html());
    var templateBasic = Handlebars.compile($('#timeline-item-basic').html());
    var $loading = $('#timeline-loading');

    // if we don't have a specified index, don't do anythin
    if (API_BASE.indexOf('undefined/undefined') >= 0) {
        return;
    }

    if (!count) {
        count = PER_PAGE;
    }
    if (!starting_from) {
        starting_from = 0;
    }

    $.get(API_BASE + '/recent_events',
          {count: count, starting_from: starting_from})
          .success(function(data) {
              var fragment = document.createDocumentFragment();
              data.data.forEach(function(e) {
                  mapping = TIMELINE_MAPPING[e.type];
                  var context = formatContext(e);
                  if (!context) return;
                  if (mapping && mapping.link) {
                      context.link = mapping.link(e);
                  }
                  var $item;
                  if (e.type == 'CommitCommentEvent' || context.action == 'starred' || context.action == 'forked to') {
                    context.img = context.action == 'starred' ? 'starred' : 'forked';
                    if (e.type == 'CommitCommentEvent') context.img = 'comment';
                    $item = $(templateBasic(context));
                  } else {
                    $item = $(template(context));
                  }
                  fragment.appendChild($item[0]);
              });
              $(fragment).insertBefore($loading);

              if (!data.data.length) {
                  mapping = TIMELINE_MAPPING['EndOfTimeline'];
                  context = {
                      author: "Sorry!",
                      action: mapping.action(),
                      object: mapping.object(),
                      timestamp: ""
                  };
                  var $item = $(template(context));
                  $loading.remove();
                  $timeline.append($item);
                  $('#tab-1').off('scroll');
              }
          }).fail(logFailure);

          if (!starting_from) {
            $(document).on('scroll', function () {
              if($(window).scrollTop() + $(window).height() >= $(document).height() - 10) {
                populateTimeline(PER_PAGE, $timeline.children('.timeline-item').length);
              }
            });
          }
}
<commit_msg>Fix indentation<commit_after>PER_PAGE = 50;

var authorTemplate = Handlebars.compile($('#timeline-author-template').html());

Handlebars.registerHelper('eachCommit', function(context, options) {
  var ret = "";

  for(var i=0, j=context.length; i<j; i++) {
    ret = ret + options.fn(context[i]);
  }

  return ret;
});

function formatAuthor(author) {
    var login = author.login;
    var avatarURL = author.avatar_url;
    var githubURL = 'http://github.com/' + login;

    return {
        username: login,
        avatar: avatarURL,
        githubURL: githubURL
    };
}

function formatPayload (payload) {
  var data = {
    comment: '',
    count: '',
    commits: '',
    diffTree: '',
    labels: []
  };
  if (payload.comment) {
    data.comment = payload.comment.body;
    // FIXME: @piatra
    if (payload.issue) {
      data.count = payload.issue.comments;
    } else {
      data.count = 0;
    }
  }
  if (payload.issue) {
    data.labels = payload.issue.labels;
  }
  if (payload.commits) {
    data.diffTree = payload.before.substr(0,10) + '...' + payload.head.substr(0,10);
    data.commits = payload.commits.map(function(commit) {
      return {
        commitUrl: commit.url,
        message: commit.message,
        sha: commit.sha.substr(0,10)
      };
    });
  }
  return data;
}

function formatLink(href, text, title) {
    if (title) {
        return '' + text + '';
    }
    return '' + text + '';
}

function formatIssue(issue) {
    return formatLink(issue.html_url, '#' + issue.number, issue.title);
}

var TIMELINE_MAPPING = {
    'CommitCommentEvent': {
        action: function(e) {
            return "commented on";
        },
        object: function(e) {
            var url = e.payload.comment.html_url;
            url = url.substring(0, url.lastIndexOf('#'));

            var sha = url.substring(url.lastIndexOf('/') + 1);
            return formatLink(url, sha.substring(0, 7));
        },
        link: function(e) {
            return e.payload.comment.html_url;
        }
    },
    'CreateEvent': {
        action: function(e) {
            var s = "created";
            if (e.payload.ref_type == 'branch') {
                return s + " branch";
            } else if (e.payload.ref_type == 'tag') {
                return s + " tag";
            }
            return s;
        },
        object: function(e) {
            return e.payload.ref;
        },
    },
    'DeleteEvent': {
        action: function(e) {
            var s = "deleted";
            if (e.payload.ref_type == 'branch') {
                return s + " branch";
            } else if (e.payload.ref_type == 'tag') {
                return s + " tag";
            }
            return s;
        },
        object: function(e) {
            return e.payload.ref;
        },
    },
    'ForkEvent': {
        action: function(e) {
            return "forked to";
        },
        object: function(e) {
            var name = e.payload.forkee.full_name;
            var url = e.payload.forkee.html_url;
            return formatLink(url, name);
        }
    },
    'GollumEvent': {
        action: function(e) {
            var page = e.payload.pages[0];
            return page.action;
        },
        object: function(e) {
            var page = e.payload.pages[0];
            return "wiki page " + formatLink(page.html_url, page.page_name);
        }
    },
    'IssueCommentEvent': {
        title: function(e) {
          return e.payload.issue.title;
        },
        action: function(e) {
            return "commented on";
        },
        object: function(e) {
            return formatIssue(e.payload.issue);
        },
        link: function(e) {
            return e.payload.comment.html_url;
        },
        assignee: function(e) {
            var assignee = e.payload.issue.assignee;
            if (assignee) {
                return assignee.login;
            }
            return 'no one';
        },
        number: function(e) {
          return e.payload.issue.number;
        },
        issue_age: function(e) {
          return moment().from(e.payload.issue.created_at, true);
        },
        issueURL: function(e) {
          if (e.payload && e.payload.comment) {
            var url = e.payload.comment.html_url.split('#')[0];
            return url;
          } else {
            return '';
          }
        }
    },
    'IssuesEvent': {
        action: function(e) {
            return e.payload.action;
        },
        object: function(e) {
            return formatIssue(e.payload.issue);
        },
        assignee: function(e) {
            var assignee = e.payload.issue.assignee;
            if (assignee) {
                return assignee.login;
            }
            return 'nobody';
        },
        title: function(e) {
          return e.payload.issue.title;
        },
        number: function(e) {
          return e.payload.issue.number;
        },
        issue_age: function(e) {
          return moment().from(e.payload.issue.created_at, true);
        },
        issueURL: function(e) {
          if (e.payload && e.payload.comment) {
            var url = e.payload.comment.html_url.split('#')[0];
            return url;
          } else {
            return '';
          }
        }
    },
    'MemberEvent': {
        action: function(e) {
            return "added";
        },
        object: function(e) {
            var user = e.payload.member;
            return formatLink(user.html_url, user.login) + " as a collaborator";
        }
    },
    'PublicEvent': {
        action: function(e) {
            return "open sourced";
        },
        object: function(e) {
            return "the repository";
        }
    },
    'PullRequestEvent': {
        action: function(e) {
            return e.payload.action;
        },
        object: function(e) {
            var pullReq = e.payload.pull_request;
            return "pull request " + formatIssue(pullReq);
        },
        title: function(e) {
          return e.payload.pull_request.title;
        },
        number: function(e) {
          return e.payload.pull_request.number;
        },
        issueURL: function(e) {
          return e.payload.pull_request.comments_url;
        },
        changes: function(e) {
          return {
            additions: e.payload.pull_request.additions,
            deletions: e.payload.pull_request.deletions
          };
        },
        issue_age: function(e) {
          return moment().from(e.payload.pull_request.created_at, true);
        },
    },
    'PullRequestReviewCommentEvent': {
        action: function(e) {
            return "reviewed";
        },
        object: function(e) {
            var url = e.payload.comment.pull_request_url;
            var number = url.substring(url.lastIndexOf('/') + 1);
            var htmlURL = e.payload.comment.html_url;
            var pullReqURL = htmlURL.substring(0, htmlURL.lastIndexOf('#'));
            return "pull request " + makeLink(pullReqURL, '#' + number);
        },
        link: function(e) {
            return e.payload.comment.html_url;
        }
    },
    'PushEvent': {
        action: function(e) {
            return "pushed";
        },
        object: function(e) {
            var count = e.payload.size;
            return count + " commits";
        },
        link: function(e) {
            var head = e.payload.head;
            var repo = e.repo.name;
            var url = 'http://github.com/' + repo + '/commit/' + head;
            return url;
        }
    },
    'WatchEvent': {
        action: function(e) {
            return "starred";
        },
        object: function(e) {
            return "the repository";
        }
    },
    'TeamAddEvent': {
      action: function(e) {
        return 'Team add event';
      },
      object: function(e) {
        return 'for ' + e.payload.team.name;
      }
    },
    'EndOfTimeline': {
        action: function (e) {
            return "No more events available";
        },
        object: function (e) {
            return;
        }
    }
};

function formatContext (e) {
  var mapping = TIMELINE_MAPPING[e.type];

  if (!mapping) {
    if (!e.body) {
      // FIXME: need better handling for this
      // can't figure out what kind of event this is
      return;
    }
    context = {
      avatar: e.user.avatar_url,
      username: e.user.login,
      comment: e.body,
      number: e.number,
      issue_age: moment().from(e.created_at, true),
      commentCount: e.comments,
      commits: [],
      diffTree: '',
      url: '',
      assignee: e.assignee || 'no one',
      action: 'commented: ',
      object: '',
      timestamp: moment().from(e.created_at, true),
      title: e.title
    };
  } else {
    context = {
      avatar: formatAuthor(e.actor).avatar,
      username: formatAuthor(e.actor).username,
      comment: formatPayload(e.payload).comment,
      number: mapping.number ? mapping.number(e) : 0,
      issue_age: mapping.issue_age ? mapping.issue_age(e) : 0,
      labels: formatPayload(e.payload).labels,
      commentCount: formatPayload(e.payload).count,
      commits: formatPayload(e.payload).commits,
      diffTree: formatPayload(e.payload).diffTree,
      url: e.repo.name,
      assignee: mapping.assignee ? mapping.assignee(e) : 'no one',
      action: mapping.action(e),
      object: mapping.object(e),
      timestamp: moment(e.created_at).fromNow(),
      title: mapping.title ? mapping.title(e) : ''
    };
  }

  if (context.number && context.title) {
    if (mapping) {
      context.issueURL = mapping.issueURL(e);
    } else {
      context.issueURL = e.html_url;
    }
  }
  if (mapping && mapping.changes) {
    // changes refer to additions & deletions in a pull request
    context.changes = mapping.changes(e);
  }
  return context;
}

function populateTimeline(count, starting_from) {
  var $timeline = $('#timeline');
  var template = Handlebars.compile($('#timeline-item-template').html());
  var templateBasic = Handlebars.compile($('#timeline-item-basic').html());
  var $loading = $('#timeline-loading');

  // if we don't have a specified index, don't do anythin
  if (API_BASE.indexOf('undefined/undefined') >= 0) {
    return;
  }

  if (!count) {
    count = PER_PAGE;
  }
  if (!starting_from) {
    starting_from = 0;
  }

  $.get(API_BASE + '/recent_events', {count: count, starting_from: starting_from})
    .success(function(data) {
      var fragment = document.createDocumentFragment();
      data.data.forEach(function(e) {
        mapping = TIMELINE_MAPPING[e.type];
        var context = formatContext(e);

        if (!context) return;

        if (mapping && mapping.link) {
          context.link = mapping.link(e);
        }

        var $item;

        if (e.type == 'CommitCommentEvent' || context.action == 'starred' || context.action == 'forked to') {
          context.img = context.action == 'starred' ? 'starred' : 'forked';

          if (e.type == 'CommitCommentEvent') context.img = 'comment';

          $item = $(templateBasic(context));

        } else {

          $item = $(template(context));

        }

        fragment.appendChild($item[0]);
      });

      $(fragment).insertBefore($loading);

      if (!data.data.length) {
        mapping = TIMELINE_MAPPING['EndOfTimeline'];
        context = {
          author: "Sorry!",
          action: mapping.action(),
          object: mapping.object(),
          timestamp: ""
        };

        var $item = $(template(context));
        $loading.remove();
        $timeline.append($item);
        $('#tab-1').off('scroll');
      }

    }).fail(logFailure);

    if (!starting_from) {
      $(document).on('scroll', function () {
        if($(window).scrollTop() + $(window).height() >= $(document).height() - 10) {
          populateTimeline(PER_PAGE, $timeline.children('.timeline-item').length);
        }
      });
    }
}
<|endoftext|>


<commit_before>import React from 'react';

export default class SwitchBox extends React.Component {
  constructor() {
    super();

    this.state = {
      hasStarted: false,
      isComplete: false,
      hasClicked: false
    };

    this.startTime = null;
    this.stopTime = null;
  }

  componentWillMount() {
    // setTimeout(() => {this._finish()}, 10000)
  }

  render() {
    let boxDiv =

    let resultsDiv =

    let actionButton =

    if (this.state.isComplete) {
      if (this.state.hasClicked) {
        boxDiv =

✓

;
        resultsDiv =

{this._latency()} ms

        actionButton =

<button onClick={this._reset.bind(this)}>TRY AGAIN!</button>

      }
      else {
        // wonder if should detect key press instead of click
        boxDiv =

;
      }
    } else {
      boxDiv =

;
      if (this.state.hasStarted) {
        actionButton =

      } else {
        actionButton =

<button onClick={this._timeout.bind(this)}>GO!</button>

      }
    }

    return(

        {boxDiv}
        {resultsDiv}
        {actionButton}

    );
  }

  _finish() {
    this.setState({
      isComplete: true
    });
    this._start_timer();
  }

  _start_timer() {
    this.startTime = performance.now();
    console.log('startTime:', this.startTime);
  }

  _stop_timer() {
    this.stopTime = performance.now();
    console.log('stopTime', this.stopTime);
  }

  _reset() {
    this.startTime = null;
    this.stopTime = null;
    this.setState({
      hasClicked: false,
      isComplete: false,
      hasStarted: false
    });
  }

  _timeout() {
    // maybe have some random timeout between green and red states
    this.setState({
      hasStarted: true
    })
    let rand = Math.round(Math.random() * (3000 - 500)) + 500;
    setTimeout(() => {
      console.log("Wait for it...");
      this._finish();
    }, rand);
  }

  _countdown() {
    // maybe have a countdown before the test starts
  }

  _latency() {
    return (this.stopTime - this.startTime).toFixed(2)
  }

  _record_click() {
    this._stop_timer();
    this.setState({
      hasClicked: true
    });
  }
}
<commit_msg>fix lint error<commit_after>import React from 'react';

export default class SwitchBox extends React.Component {
  constructor() {
    super();

    this.state = {
      hasStarted: false,
      isComplete: false,
      hasClicked: false
    };

    this.startTime = null;
    this.stopTime = null;
  }

  componentWillMount() {
    // setTimeout(() => {this._finish()}, 10000)
  }

  render() {
    let boxDiv =

    let resultsDiv =

    let actionButton =

    if (this.state.isComplete) {
      if (this.state.hasClicked) {
        boxDiv =

✓

;
        resultsDiv =

{this._latency()} ms

        actionButton =

<button onClick={this._reset.bind(this)}>TRY AGAIN!</button>

      }
      else {
        // wonder if should detect key press instead of click
        boxDiv =

;
      }
    } else {
      boxDiv =

;
      if (this.state.hasStarted) {
        actionButton =

      } else {
        actionButton =

<button onClick={this._timeout.bind(this)}>GO!</button>

      }
    }

    return(

        {boxDiv}
        {resultsDiv}
        {actionButton}

    );
  }

  _finish() {
    this.setState({
      isComplete: true
    });
    this._start_timer();
  }

  _start_timer() {
    this.startTime = performance.now();
    console.log('startTime:', this.startTime);
  }

  _stop_timer() {
    this.stopTime = performance.now();
    console.log('stopTime', this.stopTime);
  }

  _reset() {
    this.startTime = null;
    this.stopTime = null;
    this.setState({
      hasClicked: false,
      isComplete: false,
      hasStarted: false
    });
  }

  _timeout() {
    // maybe have some random timeout between green and red states
    this.setState({
      hasStarted: true
    })
    const rand = Math.round(Math.random() * (3000 - 500)) + 500;
    setTimeout(() => {
      console.log("Wait for it...");
      this._finish();
    }, rand);
  }

  _countdown() {
    // maybe have a countdown before the test starts
  }

  _latency() {
    return (this.stopTime - this.startTime).toFixed(2)
  }

  _record_click() {
    this._stop_timer();
    this.setState({
      hasClicked: true
    });
  }
}
<|endoftext|>


<commit_before>'use strict';

module.exports = exports = require('../../view/print-base');

exports._title = function () { return "eRegistrations: Prototype demo print"; };

exports.head = function () {
	meta({ name: 'viewport', content: 'width=device-width' });
	script({ src: stUrl('prototype.legacy.js') });
	link({ href: stUrl('prototype-print.css'), rel: 'stylesheet' });
};

exports._logo = function () { return img({ src: '/img/logo-2.png' }); };
<commit_msg>Title export fix in print base proto app. #680<commit_after>'use strict';

module.exports = exports = require('../../view/print-base');

exports.title = "eRegistrations: Prototype demo print";

exports.head = function () {
	meta({ name: 'viewport', content: 'width=device-width' });
	script({ src: stUrl('prototype.legacy.js') });
	link({ href: stUrl('prototype-print.css'), rel: 'stylesheet' });
};

exports._logo = function () { return img({ src: '/img/logo-2.png' }); };
<|endoftext|>


<commit_before>/**
 * HTTP Service
 *
 * Base class for HTTP data services, default settings are designed for JSON
 * REST APIs; parseFunction required for XML data sources
 *
 * @class		conbo.HttpService
 * @augments	conbo.EventDispatcher
 * @author 		Neil Rackett
 */
conbo.HttpService = conbo.EventDispatcher.extend(
/** @lends conbo.HttpService.prototype */
{
	constructor: function(options)
	{
		conbo.setValues(this, conbo.pick(options || {},
		    'rootUrl',
		    'contentType',
		    'dataType',
		    'isRpc',
		    'headers',
		    'parseFunction',
		    'resultClass',
		    'makeObjectsBindable'
		));

		conbo.EventDispatcher.prototype.constructor.apply(this, arguments);
	},

	get rootUrl()
	{
		return this._rootUrl || '';
	},

	set rootUrl(value)
	{
		value = String(value);

		if (value && value.slice(-1) != '/')
		{
			value += '/';
		}

		this._rootUrl = value;
	},

	call: function(command, data, method, resultClass)
	{
		var contentType;

		data = conbo.clone(data) || {};
		method || (method = 'GET');
		resultClass || (resultClass = this.resultClass);

		contentType = this.contentType
			|| (this.isRpc ? 'application/json' : 'application/x-www-form-urlencoded');

		command = this.parseUrl(command, data);

		data = this.isRpc
			? (method == 'GET' ? undefined : JSON.stringify(conbo.isFunction(data.toJSON) ? data.toJSON() : data))
			: data;

		var promise = $.ajax
		({
			data: data,
			type: 'GET',
			headers: this.headers,
			url: this.rootUrl+command,
			contentType: contentType,
			dataType: this.dataType,
			dataFilter: this.parseFunction
		});

		var token = new conbo.AsyncToken
		({
			promise: promise,
			resultClass: resultClass,
			makeObjectsBindable: this.makeObjectsBindable
		});

		token.addResponder(new conbo.Responder(this.dispatchEvent, this.dispatchEvent, this));

		return token;
	},

	/**
	 * Add one or more remote commands as methods of this class instance
	 * @param	{String}	command
	 * @param	{String}	method
	 * @param	{Class}		resultClass
	 */
	addCommand: function(command, method, resultClass)
	{
		if (conbo.isObject(command))
		{
			method = command.method;
			resultClass = command.resultClass;
			command = command.command;
		}

		this[conbo.toCamelCase(command)] = function(data)
		{
			return this.call(command, data, method, resultClass);
		};

		return this;
	},

	/**
	 * Add multiple commands as methods of this class instance
	 * @param	{Array}		commands
	 */
	addCommands: function(commands)
	{
		if (!conbo.isArray(commands))
		{
			return this;
		}

		commands.forEach(function(command)
		{
			this.addCommand(command);
		},
		this);

		return this;
	},

	/**
	 * Splice data into URL and remove spliced properties from data object
	 */
	parseUrl: function(url, data)
	{
		var parsedUrl = url,
			matches = parsedUrl.match(/:\b\w+\b/g);

		if (!!matches)
		{
			matches.forEach(function(key)
			{
				key = key.substr(1);

				if (!(key in data))
				{
					throw new Error('Property "'+key+'" required but not found in data');
				}
			});
		}

		conbo.keys(data).forEach(function(key)
		{
			var regExp = new RegExp(':\\b'+key+'\\b', 'g');

			if (regExp.test(parsedUrl))
			{
				parsedUrl = parsedUrl.replace(regExp, data[key]);
				delete data[key];
			}
		});

		return parsedUrl;
	},

	toString: function()
	{
		return 'conbo.HttpService';
	}

}).implement(conbo.IInjectable);

<commit_msg>Update RPC data encoding<commit_after>/**
 * HTTP Service
 *
 * Base class for HTTP data services, default settings are designed for JSON
 * REST APIs; parseFunction required for XML data sources
 *
 * @class		conbo.HttpService
 * @augments	conbo.EventDispatcher
 * @author 		Neil Rackett
 */
conbo.HttpService = conbo.EventDispatcher.extend(
/** @lends conbo.HttpService.prototype */
{
	constructor: function(options)
	{
		conbo.setValues(this, conbo.pick(options || {},
		    'rootUrl',
		    'contentType',
		    'dataType',
		    'isRpc',
		    'headers',
		    'parseFunction',
		    'resultClass',
		    'makeObjectsBindable'
		));

		conbo.EventDispatcher.prototype.constructor.apply(this, arguments);
	},

	get rootUrl()
	{
		return this._rootUrl || '';
	},

	set rootUrl(value)
	{
		value = String(value);

		if (value && value.slice(-1) != '/')
		{
			value += '/';
		}

		this._rootUrl = value;
	},

	call: function(command, data, method, resultClass)
	{
		var contentType;

		data = conbo.clone(data) || {};
		method || (method = 'GET');
		resultClass || (resultClass = this.resultClass);

		contentType = this.contentType
			|| (this.isRpc ? 'application/json' : 'application/x-www-form-urlencoded');

		command = this.parseUrl(command, data);
		data = this.isRpc ? JSON.stringify(data) : data;

		var promise = $.ajax
		({
			data: data,
			type: method,
			headers: this.headers,
			url: this.rootUrl+command,
			contentType: contentType,
			dataType: this.dataType,
			dataFilter: this.parseFunction
		});

		var token = new conbo.AsyncToken
		({
			promise: promise,
			resultClass: resultClass,
			makeObjectsBindable: this.makeObjectsBindable
		});

		token.addResponder(new conbo.Responder(this.dispatchEvent, this.dispatchEvent, this));

		return token;
	},

	/**
	 * Add one or more remote commands as methods of this class instance
	 * @param	{String}	command
	 * @param	{String}	method
	 * @param	{Class}		resultClass
	 */
	addCommand: function(command, method, resultClass)
	{
		if (conbo.isObject(command))
		{
			method = command.method;
			resultClass = command.resultClass;
			command = command.command;
		}

		this[conbo.toCamelCase(command)] = function(data)
		{
			return this.call(command, data, method, resultClass);
		};

		return this;
	},

	/**
	 * Add multiple commands as methods of this class instance
	 * @param	{Array}		commands
	 */
	addCommands: function(commands)
	{
		if (!conbo.isArray(commands))
		{
			return this;
		}

		commands.forEach(function(command)
		{
			this.addCommand(command);
		},
		this);

		return this;
	},

	/**
	 * Splice data into URL and remove spliced properties from data object
	 */
	parseUrl: function(url, data)
	{
		var parsedUrl = url,
			matches = parsedUrl.match(/:\b\w+\b/g);

		if (!!matches)
		{
			matches.forEach(function(key)
			{
				key = key.substr(1);

				if (!(key in data))
				{
					throw new Error('Property "'+key+'" required but not found in data');
				}
			});
		}

		conbo.keys(data).forEach(function(key)
		{
			var regExp = new RegExp(':\\b'+key+'\\b', 'g');

			if (regExp.test(parsedUrl))
			{
				parsedUrl = parsedUrl.replace(regExp, data[key]);
				delete data[key];
			}
		});

		return parsedUrl;
	},

	toString: function()
	{
		return 'conbo.HttpService';
	}

}).implement(conbo.IInjectable);

<|endoftext|>


<commit_before>/*
* mvcRoutes
* author: ruleechen
* contact: rulee@live.cn
* create date: 2014.7.6
*/

'use strict';

var events = require('events'),
    utils = require('zoo-utils'),
    caching = require('zoo-cache'),
    mvcRoute = require('./mvcRoute');

var mvcRoutes = module.exports = function(set, store) {
    utils.extend(this, set);
    if (!this.ownerAreaName) { throw new Error('Parameter "ownerAreaName" is required'); }
    this._inner = caching.region('mvc-' + this.ownerAreaName + '-area-routes-cache', store);
    mvcRoutes.superclass.constructor.call(this);
};

utils.inherit(mvcRoutes, events.EventEmitter, {

    ownerAreaName: null, _inner: null,

    all: function() {
        return this._inner.all();
    },

    get: function(name) {
        return this._inner.get(name);
    },

    exists: function(name) {
        return this._inner.exists(name);
    },

    remove: function(name) {
        this._inner.remove(name);
        this.emit('changed');
    },

    count: function() {
        return this._inner.count();
    },

    clear: function() {
        this._inner.clear();
        this.emit('changed');
    },

    set: function(name, route) {
        if (!utils.isString(name)) { throw new Error(utils.format('Route name requires string type but got {0} type', utils.type(name))); }
        if (!name) { throw new Error('Route name is required'); }
        if (!(route instanceof mvcRoute)) { throw new Error('Route is not instance of mvcRoute'); }
        this._inner.set(name, route);
        this.emit('changed');
    },

    register: function(name, expression, defaultValues) {
        if (!utils.isString(name)) { throw new Error(utils.format('Route name requires string type but got {0} type', utils.type(name))); }
        if (!name) { throw new Error('Route name is required'); }
        if (this.exists(name)) { throw new Error(utils.format('Route "{0}" already exists', name)); }
        this._inner.set(name, new mvcRoute({
            name: name,
            expression: expression,
            defaultValues: defaultValues,
            ownerAreaName: this.ownerAreaName
        }));
        this.emit('changed');
    }
});
<commit_msg>verifyName + return-this<commit_after>/*
* mvcRoutes
* author: ruleechen
* contact: rulee@live.cn
* create date: 2014.7.6
*/

'use strict';

var events = require('events'),
    utils = require('zoo-utils'),
    caching = require('zoo-cache'),
    mvcRoute = require('./mvcRoute');

var mvcRoutes = module.exports = function(set, store) {
    utils.extend(this, set);
    if (!this.ownerAreaName) { throw new Error('Parameter "ownerAreaName" is required'); }
    this._inner = caching.region('mvc-' + this.ownerAreaName + '-area-routes-cache', store);
    mvcRoutes.superclass.constructor.call(this);
};

utils.inherit(mvcRoutes, events.EventEmitter, {

    ownerAreaName: null, _inner: null,

    all: function() {
        return this._inner.all();
    },

    get: function(name) {
        return this._inner.get(name);
    },

    exists: function(name) {
        return this._inner.exists(name);
    },

    remove: function(name) {
        var ret = this._inner.remove(name);
        this.emit('changed');
        return ret;
    },

    count: function() {
        return this._inner.count();
    },

    clear: function() {
        this._inner.clear();
        this.emit('changed');
        return this;
    },

    set: function(name, route) {
        verifyName(name);
        if (!(route instanceof mvcRoute)) { throw new Error('Route is not instance of mvcRoute'); }
        this._inner.set(name, route);
        this.emit('changed');
        return this;
    },

    register: function(name, expression, defaultValues) {
        verifyName(name);
        if (this.exists(name)) { throw new Error(utils.format('Route "{0}" already exists', name)); }
        this._inner.set(name, new mvcRoute({
            name: name,
            expression: expression,
            defaultValues: defaultValues,
            ownerAreaName: this.ownerAreaName
        }));
        this.emit('changed');
    }
});

var verifyName = function(name) {
    if (!utils.isString(name)) { throw new Error(utils.format('Route name requires string type but got {0} type', utils.type(name))); }
    if (!name) { throw new Error('Route name is required'); }
};
<|endoftext|>


<commit_before>/*@cc_on@if(@_jscript_version<9){'video audio source track'.replace(/\w+/g,function(n){document.createElement(n)})}@end@*/

/**
* Kaltura html5 library loader
* For more info on mwEmbed / kaltura html5 library see:
* http://www.kaltura.org/project/HTML5_Video_Media_JavaScript_Library
*
* HTML5 Library usage is driven by html5 attributes see:
* http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
*
* Kaltura Configuration options are set via mw.setConfig( option, value ) or
* mw.setConfig( {json set of option value pairs } );
*
* Some config options and their defualt values:
*
*	// Enable analytics tracking for html5 devices
*	'Kaltura.EnableAnalytics' : true
*
*	// Base url for your api
*	'Kaltura.ServiceUrl' : 'http://www.kaltura.com'
*
*	// Path to kaltura api
*	'Kaltura.ServiceBase' : '/api_v3/index.php?service=',
*
*	// The CDN url that hosts your assets.
*	'Kaltura.CdnUrl' : 'http://cdn.kaltura.com'
*
*/

var kURID = '1.1q';
// Static script loader url:
var SCRIPT_LOADER_URL = 'http://www.kaltura.org/apis/html5lib/mwEmbed/ResourceLoader.php';
var SCRIPT_FORCE_DEBUG = false;
var FORCE_LOAD_JQUERY = false;

// These Lines are for local testing:
SCRIPT_FORCE_DEBUG = true;
SCRIPT_LOADER_URL = 'http://192.168.1.101/html5.kaltura/mwEmbed/ResourceLoader.php';
//kURID = new Date().getTime();

if( typeof console != 'undefined' && console.log ) {
	console.log( 'Kaltura MwEmbed Loader Version: ' + kURID );
}

// Define mw ( if not already set )
if( !window['mw'] ){
	window['mw'] = {};
}

// Magic url parameter to enable debug mode
if( document.URL.indexOf('debugKalturaPlayer=true') != -1 ){
	SCRIPT_FORCE_DEBUG = true;
}
if( document.URL.indexOf('debugKalturaForceJquery=true') != -1 ){
	FORCE_LOAD_JQUERY = true
}

// Define the dom ready flag
var kAlreadyRunDomReadyFlag = false;

// Try and override the swfObject at runtime
// In case it was included before mwEmbedLoader and the embedSWF call is inline
kOverideSwfObject();

// Setup preMwEmbedReady queue
if( !preMwEmbedReady ){
	var preMwEmbedReady = [];
}
// Wrap mw.ready to preMwEmbedReady values
if( !mw.ready){
	mw.ready = function( fn ){
		preMwEmbedReady.push( fn );
		// Check if mw.ready was called after the dom is ready:
		if( kAlreadyRunDomReadyFlag ){
			kCheckAddScript();
		}
	}
}
// Setup a preMwEmbedConfig var
if( ! preMwEmbedConfig ) {
	var preMwEmbedConfig = [];
}
if( !mw.setConfig ){
	mw.setConfig = function( set, value ){
		var valueQueue = {};
		if( typeof value != 'undefined'  ) {
			preMwEmbedConfig[ set	] = value;
		} else if ( typeof set == 'object' ){
			for( var i in set ){
				preMwEmbedConfig[ i ] = set[i];
			}
		}
	}
}

// Test if swfObject exists, try and override its embed method to wrap html5 rewrite calls.
function kOverideSwfObject(){

	var doEmbedSettingsWrite = function ( kEmbedSettings, replaceTarget, widthStr, heightStr ){
		// Make sure we have kaltura script:
		kAddScript();

		// Add a ready event to re-write:
		mw.ready(function(){
			// Setup the embedPlayer attributes
			var embedPlayerAttributes = {
					'kwidgetid' : kEmbedSettings.widgetId,
					'kuiconfid' : kEmbedSettings.uiconfId
			}

			var width = ( widthStr )? parseInt( widthStr ) : $j('#' + replaceTarget ).width();
			var height = ( heightStr)? parseInt( heightStr ) : $j('#' + replaceTarget ).height();

			if( kEmbedSettings.entryId ){
				embedPlayerAttributes.kentryid = kEmbedSettings.entryId;
				embedPlayerAttributes.poster = 'http://cdnakmi.kaltura.com/p/' + kEmbedSettings.partnerId + '/sp/' +
				kEmbedSettings.partnerId + '00/thumbnail/entry_id/' + kEmbedSettings.entryId + '/width/' +
				height + '/height/' + width;
			}
			$j('#' + replaceTarget ).css({
				'width' : width,
				'height' : height
			}).embedPlayer( embedPlayerAttributes );
		});
	}

	// SWFObject v 1.5
	if( window['SWFObject']  && !window['SWFObject'].prototype['originalWrite']){
		window['SWFObject'].prototype['originalWrite'] = window['SWFObject'].prototype.write;
		window['SWFObject'].prototype['write'] = function( targetId ){
			var flashVarsSet = this.params.flashVars.split('&');
			flashVars = {};
			for( var i =0 ;i < flashVarsSet.length; i ++){
				var flashVar = flashVarsSet[i].split('=');
				if( flashVar[0] &&   flashVar[1]){
					flashVars[ flashVar[0] ] = flashVar[1];
				}
			}

			var kEmbedSettings = kGetKalturaEmbedSettings( this.attributes.swf, flashVars);
			if( kBrowserAgentShouldUseHTML5() && kEmbedSettings.uiconfId ){
				doEmbedSettingsWrite( kEmbedSettings, targetId, this.attributes.width, this.attributes.height);
			} else {
				// use the original flash player embed:
				this.originalWrite( targetId );
			}
		}
	}

	// SWFObject v 2.0
	if( window['swfobject'] && !window['swfobject']['embedSWF'] ){
		window['swfobject']['originalEmbedSWF'] = window['swfobject']['embedSWF'];
		// override embedObject for our own ends
		window['swfobject']['embedSWF'] = function( swfUrlStr, replaceElemIdStr, widthStr,
				heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn)
		{
			var kEmbedSettings = kGetKalturaEmbedSettings( swfUrlStr, flashvarsObj);
			// Check if mobile safari:

			if( kBrowserAgentShouldUseHTML5() && kEmbedSettings.uiconfId ){
				doEmbedSettingsWrite( kEmbedSettings, replaceElemIdStr, widthStr,  heightStr);
			} else {
				// Else call the original EmbedSWF with all its arguments
				window['swfobject']['originalEmbedSWF']( swfUrlStr, replaceElemIdStr, widthStr,
						heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn )
			}
		}
	}
}

// Check dom for kaltura embeds ( fall forward )
// && html5 video tag ( for fallback & html5 player interface )
function kCheckAddScript(){
	// If user javascript is using mw.ready add script
	if( preMwEmbedReady.length ) {
		kAddScript();
		return ;
	}

	// If document includes audio or video tags
	if( document.getElementsByTagName('video').length != 0
		|| document.getElementsByTagName('audio').length != 0 ) {
		kAddScript();
		return ;
	}
	// If document includes kaltura embed tags && isMobile safari:
	if ( kBrowserAgentShouldUseHTML5() ) {
		// Check for Kaltura objects in the page
		if( kGetKalturaPlayerList().length ){
			kAddScript();
		}
	}
}
function kBrowserAgentShouldUseHTML5(){
	return (  (navigator.userAgent.indexOf('iPhone') != -1) ||
	(navigator.userAgent.indexOf('iPod') != -1) ||
	(navigator.userAgent.indexOf('iPad') != -1) ||
	(navigator.userAgent.indexOf('Android 2.') != -1) ||
	// to debug in chrome / desktop safari
	(document.URL.indexOf('forceMobileHTML5') != -1 )
	);
}

// Add the kaltura html5 mwEmbed script
var kAddedScript = false;
function kAddScript(){

	if( kAddedScript ){
		return ;
	}
	kAddedScript = true;
	var url = SCRIPT_LOADER_URL + '?class=';
	var jsPlayerRequest = [];

	if( typeof window.jQuery == 'undefined' || FORCE_LOAD_JQUERY ) {
		jsPlayerRequest.push( 'window.jQuery' )
	}

	// Add all the classes needed for video
	jsPlayerRequest = jsPlayerRequest.concat( [
	    'mwEmbed',
		// core skin:
		'mw.style.mwCommon',
		'mw.style.ui_redmond',

		// embed player:
		'mw.EmbedPlayer',
		'mw.style.EmbedPlayer',
		'mw.PlayerControlBuilder',

		// default skin:
		'mw.PlayerSkinMvpcf',
		'mw.style.PlayerSkinMvpcf',

		// common playback methods:
		'mw.EmbedPlayerNative',
		'mw.EmbedPlayerKplayer',
		'mw.EmbedPlayerJava',

		// jQuery lib
		'$j.ui',
		'$j.widget',
		'$j.ui.mouse',
		'$j.fn.hoverIntent',
		'$j.cookie',
		'JSON',
		'$j.ui.slider',
		'$j.fn.menu',
		'mw.style.jquerymenu',

		// Timed Text module
		'mw.TimedText',
		'mw.style.TimedText',

		// Player themer module
		'mw.PlayerThemer'
	]);
	url+= jsPlayerRequest.join(',');

	url+='&urid=' + kURID;
	url+='&uselang=en';

	if ( SCRIPT_FORCE_DEBUG ){
		url+='&debug=true';
	}

	var script = document.createElement( 'script' );
	script.type = 'text/javascript';
	script.src = url;
	// no handlers:
	document.getElementsByTagName('body')[0].appendChild( script );
};
/**
* DOM-ready setup ( similar to jQuery.ready )
*/
function kRunMwDomReady(){
	kAlreadyRunDomReadyFlag  = true;
	kOverideSwfObject();
	kCheckAddScript();
}
// Check if already ready:
if ( document.readyState === "complete" ) {
	kRunMwDomReady();
}

// Cleanup functions for the document ready method
if ( document.addEventListener ) {
	DOMContentLoaded = function() {
		document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
		kRunMwDomReady();
	};

} else if ( document.attachEvent ) {
	DOMContentLoaded = function() {
		// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
		if ( document.readyState === "complete" ) {
			document.detachEvent( "onreadystatechange", DOMContentLoaded );
			kRunMwDomReady();
		}
	};
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
	// Use the handy event callback
	document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );

	// A fallback to window.onload, that will always work
	window.addEventListener( "load", kRunMwDomReady, false );

// If IE event model is used
} else if ( document.attachEvent ) {
	// ensure firing before onload,
	// maybe late but safe also for iframes
	document.attachEvent("onreadystatechange", DOMContentLoaded);

	// A fallback to window.onload, that will always work
	window.attachEvent( "onload", kRunMwDomReady );

	// If IE and not a frame
	// continually check to see if the document is ready
	var toplevel = false;

	try {
		toplevel = window.frameElement == null;
	} catch(e) {}

	if ( document.documentElement.doScroll && toplevel ) {
		doScrollCheck();
	}
}
// The DOM ready check for Internet Explorer
function doScrollCheck() {
	if ( kAlreadyRunDomReadyFlag ) {
		return;
	}
	try {
		// If IE is used, use the trick by Diego Perini
		// http://javascript.nwbox.com/IEContentLoaded/
		document.documentElement.doScroll("left");
	} catch( error ) {
		setTimeout( doScrollCheck, 1 );
		return;
	}
	// and execute any waiting functions
	kRunMwDomReady();
}

/**
 * Get the list of embed objects on the page that are 'kaltura players'
 * Copied from kalturaSupport loader mw.getKalturaPlayerList
 */
kGetKalturaPlayerList = function(){
	var kalturaPlayers = [];
	// check all objects for kaltura compatible urls
	var objectList = document.getElementsByTagName('object');
	var tryAddKalturaEmbed = function( url ){
		var settings = kGetKalturaEmbedSettings( url );
		if( settings && settings.uiconfId && settings.widgetId ){
			kalturaPlayers.push(  objectList[i] );
			return true;
		}
		return false;
	}
	for( var i =0; i < objectList.length; i++){
		if( objectList[i].getAttribute('data') ){
			if( tryAddKalturaEmbed( objectList[i].getAttribute('data') ) )
				continue;
		}
		var paramTags = objectList[i].getElementsByTagName('param');
		for( var j = 0; j < paramTags.length; j++){
			if( paramTags[j].getAttribute('name') == 'data'
				||
				paramTags[j].getAttribute('name') == 'src' )
			{
				if( tryAddKalturaEmbed( paramTags[j].getAttribute('value') ) )
					break;
			}
		}
	}
	return kalturaPlayers;
}
// Copied from kalturaSupport loader mw.getKalturaEmbedSettings
kGetKalturaEmbedSettings = function( swfUrl, flashvars ){
	if( !flashvars )
		flashvars= {};

	var dataUrlParts = swfUrl.split('/');
	var embedSettings = {};

	// Search backward for key value pairs
	var prevUrlPart = null;
	while( dataUrlParts.length ){
		var curUrlPart =  dataUrlParts.pop();
		switch( curUrlPart ){
			case 'p':
				embedSettings.widgetId = '_' + prevUrlPart;
				embedSettings.partnerId = prevUrlPart;
			break;
			case 'wid':
				embedSettings.widgetId = prevUrlPart;
				embedSettings.partnerId = prevUrlPart.replace(/_/,'');
			break;
			case 'entry_id':
				embedSettings.entryId = prevUrlPart;
			break;
			case 'uiconf_id':
				embedSettings.uiconfId = prevUrlPart;
			break;
			case 'cache_st':
				embedSettings.cacheSt = prevUrlPart;
			break;
		}
		prevUrlPart = curUrlPart;
	}
	// Add in Flash vars embedSettings ( they take precedence over embed url )
	for( var i in  flashvars){
		embedSettings[i] = flashvars[i];
	}
	return embedSettings;
};<commit_msg>removed debug<commit_after>/*@cc_on@if(@_jscript_version<9){'video audio source track'.replace(/\w+/g,function(n){document.createElement(n)})}@end@*/

/**
* Kaltura html5 library loader
* For more info on mwEmbed / kaltura html5 library see:
* http://www.kaltura.org/project/HTML5_Video_Media_JavaScript_Library
*
* HTML5 Library usage is driven by html5 attributes see:
* http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
*
* Kaltura Configuration options are set via mw.setConfig( option, value ) or
* mw.setConfig( {json set of option value pairs } );
*
* Some config options and their defualt values:
*
*	// Enable analytics tracking for html5 devices
*	'Kaltura.EnableAnalytics' : true
*
*	// Base url for your api
*	'Kaltura.ServiceUrl' : 'http://www.kaltura.com'
*
*	// Path to kaltura api
*	'Kaltura.ServiceBase' : '/api_v3/index.php?service=',
*
*	// The CDN url that hosts your assets.
*	'Kaltura.CdnUrl' : 'http://cdn.kaltura.com'
*
*/

var kURID = '1.1q';
// Static script loader url:
var SCRIPT_LOADER_URL = 'http://www.kaltura.org/apis/html5lib/mwEmbed/ResourceLoader.php';
var SCRIPT_FORCE_DEBUG = false;
var FORCE_LOAD_JQUERY = false;

// These Lines are for local testing:
//SCRIPT_FORCE_DEBUG = true;
//SCRIPT_LOADER_URL = 'http://192.168.1.101/html5.kaltura/mwEmbed/ResourceLoader.php';
//kURID = new Date().getTime();

if( typeof console != 'undefined' && console.log ) {
	console.log( 'Kaltura MwEmbed Loader Version: ' + kURID );
}

// Define mw ( if not already set )
if( !window['mw'] ){
	window['mw'] = {};
}

// Magic url parameter to enable debug mode
if( document.URL.indexOf('debugKalturaPlayer=true') != -1 ){
	SCRIPT_FORCE_DEBUG = true;
}
if( document.URL.indexOf('debugKalturaForceJquery=true') != -1 ){
	FORCE_LOAD_JQUERY = true
}

// Define the dom ready flag
var kAlreadyRunDomReadyFlag = false;

// Try and override the swfObject at runtime
// In case it was included before mwEmbedLoader and the embedSWF call is inline
kOverideSwfObject();

// Setup preMwEmbedReady queue
if( !preMwEmbedReady ){
	var preMwEmbedReady = [];
}
// Wrap mw.ready to preMwEmbedReady values
if( !mw.ready){
	mw.ready = function( fn ){
		preMwEmbedReady.push( fn );
		// Check if mw.ready was called after the dom is ready:
		if( kAlreadyRunDomReadyFlag ){
			kCheckAddScript();
		}
	}
}
// Setup a preMwEmbedConfig var
if( ! preMwEmbedConfig ) {
	var preMwEmbedConfig = [];
}
if( !mw.setConfig ){
	mw.setConfig = function( set, value ){
		var valueQueue = {};
		if( typeof value != 'undefined'  ) {
			preMwEmbedConfig[ set	] = value;
		} else if ( typeof set == 'object' ){
			for( var i in set ){
				preMwEmbedConfig[ i ] = set[i];
			}
		}
	}
}

// Test if swfObject exists, try and override its embed method to wrap html5 rewrite calls.
function kOverideSwfObject(){

	var doEmbedSettingsWrite = function ( kEmbedSettings, replaceTarget, widthStr, heightStr ){
		// Make sure we have kaltura script:
		kAddScript();

		// Add a ready event to re-write:
		mw.ready(function(){
			// Setup the embedPlayer attributes
			var embedPlayerAttributes = {
					'kwidgetid' : kEmbedSettings.widgetId,
					'kuiconfid' : kEmbedSettings.uiconfId
			}

			var width = ( widthStr )? parseInt( widthStr ) : $j('#' + replaceTarget ).width();
			var height = ( heightStr)? parseInt( heightStr ) : $j('#' + replaceTarget ).height();

			if( kEmbedSettings.entryId ){
				embedPlayerAttributes.kentryid = kEmbedSettings.entryId;
				embedPlayerAttributes.poster = 'http://cdnakmi.kaltura.com/p/' + kEmbedSettings.partnerId + '/sp/' +
				kEmbedSettings.partnerId + '00/thumbnail/entry_id/' + kEmbedSettings.entryId + '/width/' +
				height + '/height/' + width;
			}
			$j('#' + replaceTarget ).css({
				'width' : width,
				'height' : height
			}).embedPlayer( embedPlayerAttributes );
		});
	}

	// SWFObject v 1.5
	if( window['SWFObject']  && !window['SWFObject'].prototype['originalWrite']){
		window['SWFObject'].prototype['originalWrite'] = window['SWFObject'].prototype.write;
		window['SWFObject'].prototype['write'] = function( targetId ){
			var flashVarsSet = this.params.flashVars.split('&');
			flashVars = {};
			for( var i =0 ;i < flashVarsSet.length; i ++){
				var flashVar = flashVarsSet[i].split('=');
				if( flashVar[0] &&   flashVar[1]){
					flashVars[ flashVar[0] ] = flashVar[1];
				}
			}

			var kEmbedSettings = kGetKalturaEmbedSettings( this.attributes.swf, flashVars);
			if( kBrowserAgentShouldUseHTML5() && kEmbedSettings.uiconfId ){
				doEmbedSettingsWrite( kEmbedSettings, targetId, this.attributes.width, this.attributes.height);
			} else {
				// use the original flash player embed:
				this.originalWrite( targetId );
			}
		}
	}

	// SWFObject v 2.0
	if( window['swfobject'] && !window['swfobject']['embedSWF'] ){
		window['swfobject']['originalEmbedSWF'] = window['swfobject']['embedSWF'];
		// override embedObject for our own ends
		window['swfobject']['embedSWF'] = function( swfUrlStr, replaceElemIdStr, widthStr,
				heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn)
		{
			var kEmbedSettings = kGetKalturaEmbedSettings( swfUrlStr, flashvarsObj);
			// Check if mobile safari:

			if( kBrowserAgentShouldUseHTML5() && kEmbedSettings.uiconfId ){
				doEmbedSettingsWrite( kEmbedSettings, replaceElemIdStr, widthStr,  heightStr);
			} else {
				// Else call the original EmbedSWF with all its arguments
				window['swfobject']['originalEmbedSWF']( swfUrlStr, replaceElemIdStr, widthStr,
						heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn )
			}
		}
	}
}

// Check dom for kaltura embeds ( fall forward )
// && html5 video tag ( for fallback & html5 player interface )
function kCheckAddScript(){
	// If user javascript is using mw.ready add script
	if( preMwEmbedReady.length ) {
		kAddScript();
		return ;
	}

	// If document includes audio or video tags
	if( document.getElementsByTagName('video').length != 0
		|| document.getElementsByTagName('audio').length != 0 ) {
		kAddScript();
		return ;
	}
	// If document includes kaltura embed tags && isMobile safari:
	if ( kBrowserAgentShouldUseHTML5() ) {
		// Check for Kaltura objects in the page
		if( kGetKalturaPlayerList().length ){
			kAddScript();
		}
	}
}
function kBrowserAgentShouldUseHTML5(){
	return (  (navigator.userAgent.indexOf('iPhone') != -1) ||
	(navigator.userAgent.indexOf('iPod') != -1) ||
	(navigator.userAgent.indexOf('iPad') != -1) ||
	(navigator.userAgent.indexOf('Android 2.') != -1) ||
	// to debug in chrome / desktop safari
	(document.URL.indexOf('forceMobileHTML5') != -1 )
	);
}

// Add the kaltura html5 mwEmbed script
var kAddedScript = false;
function kAddScript(){

	if( kAddedScript ){
		return ;
	}
	kAddedScript = true;
	var url = SCRIPT_LOADER_URL + '?class=';
	var jsPlayerRequest = [];

	if( typeof window.jQuery == 'undefined' || FORCE_LOAD_JQUERY ) {
		jsPlayerRequest.push( 'window.jQuery' )
	}

	// Add all the classes needed for video
	jsPlayerRequest = jsPlayerRequest.concat( [
	    'mwEmbed',
		// core skin:
		'mw.style.mwCommon',
		'mw.style.ui_redmond',

		// embed player:
		'mw.EmbedPlayer',
		'mw.style.EmbedPlayer',
		'mw.PlayerControlBuilder',

		// default skin:
		'mw.PlayerSkinMvpcf',
		'mw.style.PlayerSkinMvpcf',

		// common playback methods:
		'mw.EmbedPlayerNative',
		'mw.EmbedPlayerKplayer',
		'mw.EmbedPlayerJava',

		// jQuery lib
		'$j.ui',
		'$j.widget',
		'$j.ui.mouse',
		'$j.fn.hoverIntent',
		'$j.cookie',
		'JSON',
		'$j.ui.slider',
		'$j.fn.menu',
		'mw.style.jquerymenu',

		// Timed Text module
		'mw.TimedText',
		'mw.style.TimedText',

		// Player themer module
		'mw.PlayerThemer'
	]);
	url+= jsPlayerRequest.join(',');

	url+='&urid=' + kURID;
	url+='&uselang=en';

	if ( SCRIPT_FORCE_DEBUG ){
		url+='&debug=true';
	}

	var script = document.createElement( 'script' );
	script.type = 'text/javascript';
	script.src = url;
	// no handlers:
	document.getElementsByTagName('body')[0].appendChild( script );
};
/**
* DOM-ready setup ( similar to jQuery.ready )
*/
function kRunMwDomReady(){
	kAlreadyRunDomReadyFlag  = true;
	kOverideSwfObject();
	kCheckAddScript();
}
// Check if already ready:
if ( document.readyState === "complete" ) {
	kRunMwDomReady();
}

// Cleanup functions for the document ready method
if ( document.addEventListener ) {
	DOMContentLoaded = function() {
		document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
		kRunMwDomReady();
	};

} else if ( document.attachEvent ) {
	DOMContentLoaded = function() {
		// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
		if ( document.readyState === "complete" ) {
			document.detachEvent( "onreadystatechange", DOMContentLoaded );
			kRunMwDomReady();
		}
	};
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
	// Use the handy event callback
	document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );

	// A fallback to window.onload, that will always work
	window.addEventListener( "load", kRunMwDomReady, false );

// If IE event model is used
} else if ( document.attachEvent ) {
	// ensure firing before onload,
	// maybe late but safe also for iframes
	document.attachEvent("onreadystatechange", DOMContentLoaded);

	// A fallback to window.onload, that will always work
	window.attachEvent( "onload", kRunMwDomReady );

	// If IE and not a frame
	// continually check to see if the document is ready
	var toplevel = false;

	try {
		toplevel = window.frameElement == null;
	} catch(e) {}

	if ( document.documentElement.doScroll && toplevel ) {
		doScrollCheck();
	}
}
// The DOM ready check for Internet Explorer
function doScrollCheck() {
	if ( kAlreadyRunDomReadyFlag ) {
		return;
	}
	try {
		// If IE is used, use the trick by Diego Perini
		// http://javascript.nwbox.com/IEContentLoaded/
		document.documentElement.doScroll("left");
	} catch( error ) {
		setTimeout( doScrollCheck, 1 );
		return;
	}
	// and execute any waiting functions
	kRunMwDomReady();
}

/**
 * Get the list of embed objects on the page that are 'kaltura players'
 * Copied from kalturaSupport loader mw.getKalturaPlayerList
 */
kGetKalturaPlayerList = function(){
	var kalturaPlayers = [];
	// check all objects for kaltura compatible urls
	var objectList = document.getElementsByTagName('object');
	var tryAddKalturaEmbed = function( url ){
		var settings = kGetKalturaEmbedSettings( url );
		if( settings && settings.uiconfId && settings.widgetId ){
			kalturaPlayers.push(  objectList[i] );
			return true;
		}
		return false;
	}
	for( var i =0; i < objectList.length; i++){
		if( objectList[i].getAttribute('data') ){
			if( tryAddKalturaEmbed( objectList[i].getAttribute('data') ) )
				continue;
		}
		var paramTags = objectList[i].getElementsByTagName('param');
		for( var j = 0; j < paramTags.length; j++){
			if( paramTags[j].getAttribute('name') == 'data'
				||
				paramTags[j].getAttribute('name') == 'src' )
			{
				if( tryAddKalturaEmbed( paramTags[j].getAttribute('value') ) )
					break;
			}
		}
	}
	return kalturaPlayers;
}
// Copied from kalturaSupport loader mw.getKalturaEmbedSettings
kGetKalturaEmbedSettings = function( swfUrl, flashvars ){
	if( !flashvars )
		flashvars= {};

	var dataUrlParts = swfUrl.split('/');
	var embedSettings = {};

	// Search backward for key value pairs
	var prevUrlPart = null;
	while( dataUrlParts.length ){
		var curUrlPart =  dataUrlParts.pop();
		switch( curUrlPart ){
			case 'p':
				embedSettings.widgetId = '_' + prevUrlPart;
				embedSettings.partnerId = prevUrlPart;
			break;
			case 'wid':
				embedSettings.widgetId = prevUrlPart;
				embedSettings.partnerId = prevUrlPart.replace(/_/,'');
			break;
			case 'entry_id':
				embedSettings.entryId = prevUrlPart;
			break;
			case 'uiconf_id':
				embedSettings.uiconfId = prevUrlPart;
			break;
			case 'cache_st':
				embedSettings.cacheSt = prevUrlPart;
			break;
		}
		prevUrlPart = curUrlPart;
	}
	// Add in Flash vars embedSettings ( they take precedence over embed url )
	for( var i in  flashvars){
		embedSettings[i] = flashvars[i];
	}
	return embedSettings;
};<|endoftext|>


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

  function debug() {
    //console.log(arguments);
  }

  function skip() {}

  var states = {
    PENDING: 0,
    FULFILLED: 1,
    REJECTED: 2
  };

  var vPromise = function (fn) {
    this._state = states.PENDING;
    this.value = null;
    this._resolveChain = [];
    var that = this;

    var onFulfilled = function (resolve) {
      if (typeof resolve !== 'function') { // 2.2.1
        return;
      }

      if (that._state !== states.PENDING) {
        that._state = states.FULFILLED;
        resolve(that.value);
      }
    };

    var onReject = function (reject, reason) {
      if (typeof reject !== 'function') { // 2.2.1
        return;
      }
      if (that._state !== states.PENDING && that._state !== states.FULFILLED) {
        that._state = states.REJECTED;
        reject(reason);
      }
    };

    var handle = function (resolve, reject) {
      if (that._state === states.PENDING) {
        return;
      }

      setTimeout(function () {
          try {
            fn(onFulfilled(resolve), onReject(reject, that.reason));
          } catch (e) {
            debug(e);
          }
      }, 1);
    };

    if (fn !== skip) {
      fn(function (value) {
        that.value = value;
        setTimeout(function () {
          if (that._state !== states.PENDING) {
            return;
          }
          var ii;
          var chainLength = that._resolveChain.length;
          for (ii = 0; ii < chainLength; ii++) {
            that._resolveChain[ii](value);
          }
          that._resolve(value);
          that._state = states.FULFILLED;
         }, 1);
      },
      function (reason) {
        that.reason = reason;
        setTimeout(function () {
          if (that._state !== states.PENDING) {
            return;
          }
          that._reject(reason);
          that._state = states.REJECTED;
         }, 1);
      });
    }

    this.then = function (resolve, reject) {
      if (that._state === states.PENDING) {
        if (typeof that._resolve == "function") {
          that._resolveChain.push(that._resolve);
        }
        that._resolve = resolve;
        that._reject = reject;
        return;
      }

      var next = new vPromise(fn);
      handle(resolve, reject);
      next._state = -1; // placeholder
      return next;
    };

    this.catch = function (fn) {
    };

    return this;
  };

  vPromise.resolve = function (value) {
    var skipped = new vPromise(skip);
    return doResolve(skipped, value);
  };

  function doResolve(skipped, value) {
    skipped._state = states.FULFILLED;
    skipped.value = value;
    return skipped;
  }

  vPromise.reject = function (reason) {
    var skipped = new vPromise(skip);
    return doReject(skipped, reason);
  };

  function doReject(skipped, reason) {
    skipped._state = states.REJECTED;
    skipped.reason = reason;
    return skipped;
  }

  if (typeof module != 'undefined') {
    module.exports = vPromise;
  }

}());
<commit_msg>More of 2.2.6.1 to passing<commit_after>(function () {
  'use strict';

  function debug() {
    //console.log(arguments);
  }

  function skip() {}

  var states = {
    PENDING: 0,
    FULFILLED: 1,
    REJECTED: 2
  };

  var vPromise = function (fn) {
    this._state = states.PENDING;
    this.value = null;
    this._resolveChain = [];
    var that = this;

    var onFulfilled = function (resolve) {
      if (typeof resolve !== 'function') { // 2.2.1
        return;
      }

      if (that._state !== states.PENDING) {
        that._state = states.FULFILLED;
        resolve(that.value);
      }
    };

    var onReject = function (reject, reason) {
      if (typeof reject !== 'function') { // 2.2.1
        return;
      }
      if (that._state !== states.PENDING && that._state !== states.FULFILLED) {
        that._state = states.REJECTED;
        reject(reason);
      }
    };

    var handle = function (resolve, reject) {
      if (that._state === states.PENDING) {
        return;
      }

      setTimeout(function () {
          try {
            fn(onFulfilled(resolve), onReject(reject, that.reason));
          } catch (e) {
            debug(e);
          }
      }, 1);
    };

    if (fn !== skip) {
      fn(function (value) {
        that.value = value;
        setTimeout(function () {
          if (that._state !== states.PENDING) {
            return;
          }
          var ii;
          var chainLength = that._resolveChain.length;
          for (ii = 0; ii < chainLength; ii++) {
            try {
              that._resolveChain[ii](value);
            } catch (e) {}
          }
          that._resolve(value);
          that._state = states.FULFILLED;
         }, 1);
      },
      function (reason) {
        that.reason = reason;
        setTimeout(function () {
          if (that._state !== states.PENDING) {
            return;
          }
          that._reject(reason);
          that._state = states.REJECTED;
         }, 1);
      });
    }

    this.then = function (resolve, reject) {
      if (that._state === states.PENDING) {
        if (typeof that._resolve == "function") {
          that._resolveChain.push(that._resolve);
        }
        that._resolve = resolve;
        that._reject = reject;
        return;
      }

      var next = new vPromise(fn);
      handle(resolve, reject);
      next._state = -1; // placeholder
      return next;
    };

    this.catch = function (fn) {
    };

    return this;
  };

  vPromise.resolve = function (value) {
    var skipped = new vPromise(skip);
    return doResolve(skipped, value);
  };

  function doResolve(skipped, value) {
    skipped._state = states.FULFILLED;
    skipped.value = value;
    return skipped;
  }

  vPromise.reject = function (reason) {
    var skipped = new vPromise(skip);
    return doReject(skipped, reason);
  };

  function doReject(skipped, reason) {
    skipped._state = states.REJECTED;
    skipped.reason = reason;
    return skipped;
  }

  if (typeof module != 'undefined') {
    module.exports = vPromise;
  }

}());
<|endoftext|>


<commit_before>define("script-2",["require","exports"],function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.default=function(e,t){return e+t}}),define("scripts",["require","exports","script-2"],function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),console.log(r.default(1,2))});<commit_msg>Testing with tsconfig.json<commit_after>define("script-2", ["require", "exports"], function (require, exports) {
    "use strict";
    exports.__esModule = true;
    var sum = function (x, y) { return (x + y); };
    var mult = function (x, y) { return (x * y); };
    function greetings() {
        console.log('Hello World!');
    }
    exports.greetings = greetings;
});
define("scripts", ["require", "exports", "script-2"], function (require, exports, script_2_1) {
    "use strict";
    exports.__esModule = true;
    script_2_1.greetings();
});
<|endoftext|>