<commit_before>Vue.component('panel-navbar', {
	template: '#panel-navbar',
	props: {
		current_panel: {
			type: String,
			required: true
		},
		button_menus: {
			type: Array,
			required: true
		},
		dropdown_menu: {
			type: Array,
			required: true
		},
		current_panel_view: {
			type: String,
			required: true
		}
	},
	data: function() {
		return {
			open_panel_menu: false
		}
	},
	methods: {
		togglePanelMenu: function() {
			this.open_panel_menu = !this.open_panel_menu
		},
		panelSelected: function(panel) {
			this.open_panel_menu = false
			bus.$emit('panel-selected', panel)
		},
		panelViewSelected: function(panel_view) {
			this.open_panel_menu = false
			bus.$emit('panel-view-selected', panel_view)
		}
	}
})

Vue.component('app-navbar', {
	template: '#app-navbar',
	props: {
		nav_state: {
			type: Object,
			required: true
		},
		open_submenu: {
			type: String,
			required: true
		},
		title: {
			type: String,
			required: true
		},
		nav_menus: {
			type: Array,
			required: true
		},

	},
	methods: {
		maindropdown: function() {
			this.$emit('maindropdown')
		},
		subdropdown: function(menu) {
			this.$emit('subdropdown', menu)
		}
	}
})

Vue.component('app-sidebar', {
	template: "#app-sidebar",
	props: {
		current_panel: {
			type: String,
			required: true
		},
		panels: {
			type: Array,
			required: true
		}
	},
	methods: {
		panelSelected: function(panel) {
			bus.$emit('panel-selected', panel)
		}
	}
})

Vue.component('form-pane', {
	template: '#form-pane',
	props: {
		form : {
			type: Object,
			required: true
		}
	},
	methods: {
		validateAll: function() {
			this.$validator.validateAll().then(function(result) {
				alert('Form Submitted')
			}).catch(function(failure) {
				alert('Please correct form details')
			})
		}
	}
})

Vue.component('table-pane', {
	template: '#table-pane',
	props: {
		list: {
			type: Object,
			required: true
		},
		table_headers: {
			type: Array,
			required: true
		}
	},
	methods: {
		openRelation: function(relation_id) {
			bus.$emit('open-relation-modal', relation_id)
		},
		deleteRelation: function(relation_id) {
			bus.$emit('delete-relation', relation_id)
		}
	}
})

Vue.component('modal-window', {
	template: '#modal-window',
	props: {
		relationship_data: {
			type: Object,
			required: true
		},
		form_labels: {
			type: Array,
			required: true
		}
	},
	data: function() {
		return {
			active_form_fields : []
		}
	},
	methods: {
		closeModal: function() {
			bus.$emit('close-modal')
		},
		activateFormField: function(form_field) {
			this.active_form_fields.push(form_field)
		}
	}
})

Vue.use(VeeValidate);

var bus = new Vue()

var vm = new Vue({
	el: '#app',
	data: {
		current_view: 'Relationships',
		current_panel_view: 'List Relationships',
		open_main_dropdown: false,
		open_sub_dropdown_name: '',
		open_modal_state: false,
		open_modal_relationship_id: '',
		panels: [
			{
				name: 'Overview',
				menus: [],
				views: []
			},{
				name: 'Relationships',
				menus: [
					{
						name: 'List Relationships',
						reference: 'List all your relationships',
						icon: 'fa fa-users fa-lg',
						class: 'btn btn-lg btn-primary btn-block',
						length: 'col-md-6 col-sm-6 col-xs-6'
					},
					{
						name: 'Add Relationships',
						reference: 'Add a relationship',
						icon: 'fa fa-user-plus fa-lg',
						class: 'btn btn-lg btn-info btn-block',
						length: 'col-md-6 col-sm-6 col-xs-6'
					}
				],
				views: [
					{
						type: 'Form',
						name: 'Add Relationships',
						inputs: [
							{ placeholder: 'JohnOlooDoe@gmail.com', validate: "email" , name: 'Email', type: 'email'},
							{ placeholder: 'John', validate: "required|alpha" , name: 'First Name', type: 'alpha'},
							{ placeholder: 'Oloo', validate: "required|alpha" , name: 'Ethnic Name', type: 'alpha'},
							{ placeholder: 'Doe', validate: "required|alpha" , name: 'Last Name', type: 'alpha'},
							{ placeholder: 'Father', validate: "required|alpha" , name: 'Relationship Name', type: 'alpha'}
						],
						submit: 'Add'
					},
					{
						type: 'Table',
						name: 'List Relationships',
						data: [
							{id:'1', first_name: 'John', baptism_name: 'Charles', ethnic_name: 'Mwaura', last_name: 'Ndungu', relation_name: 'Father'},
							{id:'2', first_name: 'Jane', baptism_name: 'Christine', ethnic_name: 'Moraa', last_name: 'Ndungu', relation_name: 'Mother'},
							{id:'3', first_name: 'Jack', baptism_name: 'Christian', ethnic_name: 'Mutuku', last_name: 'Ndungu', relation_name: 'Brother'},
						]
					}
				]
			},{
				name: 'Visualisation',
				menus: [],
				views: []
			},{
				name: 'Share',
				menus: [],
				views: []
			}
		],
		title: 'MIMINANI',
		nav_menus: [
			{
				caption: 'Info',
				icon: 'fa fa-info-circle fa-lg',
				link: '#',
				class: '',
				dropdown: [],
				reference: 'Read more about the miminani project'
			},
			{
				caption: 'Github',
				icon: 'fa fa-github fa-lg',
				link: 'http://github.com/squarenomad/miminani',
				class: '',
				dropdown: [],
				reference: 'View our open source code'
			},
			{
				caption: 'Messages',
				icon: 'fa fa-inbox fa-lg',
				link: '#',
				class: '',
				dropdown: [],
				reference: 'Notifications and alerts'
			},
			{
				caption: 'User',
				icon: 'fa fa-user-circle fa-lg',
				link: '#',
				class: 'dropdown active',
				dropdown: [
					{
						caption:'Profile',
						link: '#',
						class: 'disabled'
					},
					{
						caption:'Settings',
						link: '#',
						class: 'disabled'
					},
					{
						caption:'Sign Out',
						link: '#',
						class: ''
					}
				],
				reference: 'Manage your profile'
			}
		]
	},
	methods: {
		toggleMenu: function() {
			this.open_main_dropdown = !this.open_main_dropdown
			this.open_sub_dropdown_name = ''
		},
		toggleSubMenu: function(menu_name) {
			if (this.open_sub_dropdown_name == menu_name) {
				this.open_sub_dropdown_name = ''
			} else {
				this.open_sub_dropdown_name = menu_name
			}
		},
		navigateAllowed: function(current_view, current_panel_view, view_type_list) {
			if (view_type_list.indexOf(current_panel_view) != -1) {
				for (i=0; i<this.panels.length; i++) {
					if (this.panels[i].name == current_view) {
						for (j=0; j<this.panels[i].views.length; j++) {
							if (this.panels[i].views[j].name == current_panel_view) {
								return true
							}
						}
						return false
					}
				}
			}
			return false
		},
		getPanelView: function(current_panel_view) {
			for (i=0; i < this.panels.length; i++) {
				if (this.panels[i].name == this.current_view) {
					for (j=0; j<this.panels[i].views.length; j++) {
						if (this.panels[i].views[j].name == current_panel_view) {
							return this.panels[i].views[j]
						}
					}
				}
			}
		},
		getTableHeaders: function(current_panel_view) {
			headers = []
			for (i=0; i < this.panels.length; i++) {
				if (this.panels[i].name == this.current_view) {
					for (j=0; j<this.panels[i].views.length; j++) {
						if (this.panels[i].views[j].name == current_panel_view) {
							if (this.panels[i].views[j].type == 'Table') {
								for (k=0; k<this.panels[i].views[j].data.length; k++) {
									row_headers = Object.keys(this.panels[i].views[j].data[k])
									for (l=0; l<row_headers.length; l++) {
										if (headers.indexOf(row_headers[l]) == -1 && row_headers[l] != 'id') {
											headers.push(row_headers[l])
										}
									}
								}
							}
						}
					}
				}
			}
			return headers
		}
	},
	computed: {
		allPanelNames: function() {
			panel_names_array = []
			for (i = 0; i < this.panels.length; i++) {
				panel_names_array.push(this.panels[i].name)
			}
			return panel_names_array
		},
		currentPanelMenus: function() {
			for (i = 0; i < this.panels.length; i++) {
				if (this.panels[i].name == this.current_view) {
					return this.panels[i].menus
				}
			}
		},
		formViews: function() {
			view_type_list = []
			for (i=0; i < this.panels.length; i++) {
				if (this.panels[i].name == this.current_view) {
					for (j=0; j<this.panels[i].views.length; j++) {
						if (this.panels[i].views[j].type == 'Form') {
							view_type_list.push(this.panels[i].views[j].name)
						}
					}
				}
			}
			return view_type_list
		},
		tableViews: function() {
			view_type_list = []
			for (i=0; i < this.panels.length; i++) {
				if (this.panels[i].name == this.current_view) {
					for (j=0; j<this.panels[i].views.length; j++) {
						if (this.panels[i].views[j].type == 'Table') {
							view_type_list.push(this.panels[i].views[j].name)
						}
					}
				}
			}
			return view_type_list
		},
		relationshipData: function() {
			for (i=0; i < this.panels.length; i++) {
				if (this.panels[i].name == this.current_view) {
					for (j=0; j<this.panels[i].views.length; j++) {
						if (this.panels[i].views[j].type == 'Table') {
							for (k=0; k<this.panels[i].views[j].data.length; k++) {
								if (this.panels[i].views[j].data[k].id == this.open_modal_relationship_id) {
									return this.panels[i].views[j].data[k]
								}
							}
						}
					}
				}
			}
		}
	},
	created: function() {
		bus.$on('panel-selected', function(panel) {
			this.current_view = panel
			this.open_main_dropdown = false
			this.open_sub_dropdown_name = ''
		}.bind(this)),
		bus.$on('panel-view-selected', function(panel_view) {
			this.current_panel_view = panel_view
		}.bind(this)),
		bus.$on('open-relation-modal', function(relationship_id) {
			this.open_modal_state = true
			this.open_modal_relationship_id = relationship_id
		}.bind(this)),
		bus.$on('close-modal', function() {
			this.open_modal_state = false
			this.open_modal_relationship_id = ''
		}.bind(this)),
		bus.$on('delete-relation', function(relationship_id) {
		}.bind(this))
	},
	filters: {
		capitalize : function(value) {
			if (!value) return ''
			if (typeof value == "object") {
				cap_array = []
				for (i=0; i<value.length; i++) {
					new_value = value[i].charAt(0).toUpperCase() + value[i].slice(1)
					cap_array.push(new_value)
				}
			return cap_array
			}
			value = value.toString()
			return value.charAt(0).toUpperCase() + value.slice(1)
		},
		spacereplace: function(value) {
			if (!value) return ''
			if (typeof value == "object") {
				spaced_array = []
				for (i=0; i<value.length; i++) {
					new_value = value[i].toString().replace('_',' ')
					spaced_array.push(new_value)
				}
			return spaced_array
			}
			value = value.toString()
			return value.charAt(0).toUpperCase() + value.slice(1)
		}
	}
})<commit_msg>delete relation implemented, lacking API hook<commit_after>Vue.component('panel-navbar', {
	template: '#panel-navbar',
	props: {
		current_panel: {
			type: String,
			required: true
		},
		button_menus: {
			type: Array,
			required: true
		},
		dropdown_menu: {
			type: Array,
			required: true
		},
		current_panel_view: {
			type: String,
			required: true
		}
	},
	data: function() {
		return {
			open_panel_menu: false
		}
	},
	methods: {
		togglePanelMenu: function() {
			this.open_panel_menu = !this.open_panel_menu
		},
		panelSelected: function(panel) {
			this.open_panel_menu = false
			bus.$emit('panel-selected', panel)
		},
		panelViewSelected: function(panel_view) {
			this.open_panel_menu = false
			bus.$emit('panel-view-selected', panel_view)
		}
	}
})

Vue.component('app-navbar', {
	template: '#app-navbar',
	props: {
		nav_state: {
			type: Object,
			required: true
		},
		open_submenu: {
			type: String,
			required: true
		},
		title: {
			type: String,
			required: true
		},
		nav_menus: {
			type: Array,
			required: true
		},

	},
	methods: {
		maindropdown: function() {
			this.$emit('maindropdown')
		},
		subdropdown: function(menu) {
			this.$emit('subdropdown', menu)
		}
	}
})

Vue.component('app-sidebar', {
	template: "#app-sidebar",
	props: {
		current_panel: {
			type: String,
			required: true
		},
		panels: {
			type: Array,
			required: true
		}
	},
	methods: {
		panelSelected: function(panel) {
			bus.$emit('panel-selected', panel)
		}
	}
})

Vue.component('form-pane', {
	template: '#form-pane',
	props: {
		form : {
			type: Object,
			required: true
		}
	},
	methods: {
		validateAll: function() {
			this.$validator.validateAll().then(function(result) {
				alert('Form Submitted')
			}).catch(function(failure) {
				alert('Please correct form details')
			})
		}
	}
})

Vue.component('table-pane', {
	template: '#table-pane',
	props: {
		list: {
			type: Object,
			required: true
		},
		table_headers: {
			type: Array,
			required: true
		}
	},
	methods: {
		openRelation: function(relation_id) {
			bus.$emit('open-relation-modal', relation_id)
		},
		deleteRelation: function(relation_id) {
			bus.$emit('delete-relation', relation_id)
		}
	}
})

Vue.component('modal-window', {
	template: '#modal-window',
	props: {
		relationship_data: {
			type: Object,
			required: true
		},
		form_labels: {
			type: Array,
			required: true
		}
	},
	data: function() {
		return {
			active_form_fields : []
		}
	},
	methods: {
		closeModal: function() {
			bus.$emit('close-modal')
		},
		activateFormField: function(form_field) {
			this.active_form_fields.push(form_field)
		}
	}
})

Vue.use(VeeValidate);

var bus = new Vue()

var vm = new Vue({
	el: '#app',
	data: {
		current_view: 'Relationships',
		current_panel_view: 'List Relationships',
		open_main_dropdown: false,
		open_sub_dropdown_name: '',
		open_modal_state: false,
		open_modal_relationship_id: '',
		panels: [
			{
				name: 'Overview',
				menus: [],
				views: []
			},{
				name: 'Relationships',
				menus: [
					{
						name: 'List Relationships',
						reference: 'List all your relationships',
						icon: 'fa fa-users fa-lg',
						class: 'btn btn-lg btn-primary btn-block',
						length: 'col-md-6 col-sm-6 col-xs-6'
					},
					{
						name: 'Add Relationships',
						reference: 'Add a relationship',
						icon: 'fa fa-user-plus fa-lg',
						class: 'btn btn-lg btn-info btn-block',
						length: 'col-md-6 col-sm-6 col-xs-6'
					}
				],
				views: [
					{
						type: 'Form',
						name: 'Add Relationships',
						inputs: [
							{ placeholder: 'JohnOlooDoe@gmail.com', validate: "email" , name: 'Email', type: 'email'},
							{ placeholder: 'John', validate: "required|alpha" , name: 'First Name', type: 'alpha'},
							{ placeholder: 'Oloo', validate: "required|alpha" , name: 'Ethnic Name', type: 'alpha'},
							{ placeholder: 'Doe', validate: "required|alpha" , name: 'Last Name', type: 'alpha'},
							{ placeholder: 'Father', validate: "required|alpha" , name: 'Relationship Name', type: 'alpha'}
						],
						submit: 'Add'
					},
					{
						type: 'Table',
						name: 'List Relationships',
						data: [
							{id:'1', first_name: 'John', baptism_name: 'Charles', ethnic_name: 'Mwaura', last_name: 'Ndungu', relation_name: 'Father'},
							{id:'2', first_name: 'Jane', baptism_name: 'Christine', ethnic_name: 'Moraa', last_name: 'Ndungu', relation_name: 'Mother'},
							{id:'3', first_name: 'Jack', baptism_name: 'Christian', ethnic_name: 'Mutuku', last_name: 'Ndungu', relation_name: 'Brother'},
						]
					}
				]
			},{
				name: 'Visualisation',
				menus: [],
				views: []
			},{
				name: 'Share',
				menus: [],
				views: []
			}
		],
		title: 'MIMINANI',
		nav_menus: [
			{
				caption: 'Info',
				icon: 'fa fa-info-circle fa-lg',
				link: '#',
				class: '',
				dropdown: [],
				reference: 'Read more about the miminani project'
			},
			{
				caption: 'Github',
				icon: 'fa fa-github fa-lg',
				link: 'http://github.com/squarenomad/miminani',
				class: '',
				dropdown: [],
				reference: 'View our open source code'
			},
			{
				caption: 'Messages',
				icon: 'fa fa-inbox fa-lg',
				link: '#',
				class: '',
				dropdown: [],
				reference: 'Notifications and alerts'
			},
			{
				caption: 'User',
				icon: 'fa fa-user-circle fa-lg',
				link: '#',
				class: 'dropdown active',
				dropdown: [
					{
						caption:'Profile',
						link: '#',
						class: 'disabled'
					},
					{
						caption:'Settings',
						link: '#',
						class: 'disabled'
					},
					{
						caption:'Sign Out',
						link: '#',
						class: ''
					}
				],
				reference: 'Manage your profile'
			}
		]
	},
	methods: {
		toggleMenu: function() {
			this.open_main_dropdown = !this.open_main_dropdown
			this.open_sub_dropdown_name = ''
		},
		toggleSubMenu: function(menu_name) {
			if (this.open_sub_dropdown_name == menu_name) {
				this.open_sub_dropdown_name = ''
			} else {
				this.open_sub_dropdown_name = menu_name
			}
		},
		navigateAllowed: function(current_view, current_panel_view, view_type_list) {
			if (view_type_list.indexOf(current_panel_view) != -1) {
				for (i=0; i<this.panels.length; i++) {
					if (this.panels[i].name == current_view) {
						for (j=0; j<this.panels[i].views.length; j++) {
							if (this.panels[i].views[j].name == current_panel_view) {
								return true
							}
						}
						return false
					}
				}
			}
			return false
		},
		getPanelView: function(current_panel_view) {
			for (i=0; i < this.panels.length; i++) {
				if (this.panels[i].name == this.current_view) {
					for (j=0; j<this.panels[i].views.length; j++) {
						if (this.panels[i].views[j].name == current_panel_view) {
							return this.panels[i].views[j]
						}
					}
				}
			}
		},
		getTableHeaders: function(current_panel_view) {
			headers = []
			for (i=0; i < this.panels.length; i++) {
				if (this.panels[i].name == this.current_view) {
					for (j=0; j<this.panels[i].views.length; j++) {
						if (this.panels[i].views[j].name == current_panel_view) {
							if (this.panels[i].views[j].type == 'Table') {
								for (k=0; k<this.panels[i].views[j].data.length; k++) {
									row_headers = Object.keys(this.panels[i].views[j].data[k])
									for (l=0; l<row_headers.length; l++) {
										if (headers.indexOf(row_headers[l]) == -1 && row_headers[l] != 'id') {
											headers.push(row_headers[l])
										}
									}
								}
							}
						}
					}
				}
			}
			return headers
		}
	},
	computed: {
		allPanelNames: function() {
			panel_names_array = []
			for (i = 0; i < this.panels.length; i++) {
				panel_names_array.push(this.panels[i].name)
			}
			return panel_names_array
		},
		currentPanelMenus: function() {
			for (i = 0; i < this.panels.length; i++) {
				if (this.panels[i].name == this.current_view) {
					return this.panels[i].menus
				}
			}
		},
		formViews: function() {
			view_type_list = []
			for (i=0; i < this.panels.length; i++) {
				if (this.panels[i].name == this.current_view) {
					for (j=0; j<this.panels[i].views.length; j++) {
						if (this.panels[i].views[j].type == 'Form') {
							view_type_list.push(this.panels[i].views[j].name)
						}
					}
				}
			}
			return view_type_list
		},
		tableViews: function() {
			view_type_list = []
			for (i=0; i < this.panels.length; i++) {
				if (this.panels[i].name == this.current_view) {
					for (j=0; j<this.panels[i].views.length; j++) {
						if (this.panels[i].views[j].type == 'Table') {
							view_type_list.push(this.panels[i].views[j].name)
						}
					}
				}
			}
			return view_type_list
		},
		relationshipData: function() {
			for (i=0; i < this.panels.length; i++) {
				if (this.panels[i].name == this.current_view) {
					for (j=0; j<this.panels[i].views.length; j++) {
						if (this.panels[i].views[j].type == 'Table') {
							for (k=0; k<this.panels[i].views[j].data.length; k++) {
								if (this.panels[i].views[j].data[k].id == this.open_modal_relationship_id) {
									return this.panels[i].views[j].data[k]
								}
							}
						}
					}
				}
			}
		}
	},
	created: function() {
		bus.$on('panel-selected', function(panel) {
			this.current_view = panel
			this.open_main_dropdown = false
			this.open_sub_dropdown_name = ''
		}.bind(this)),
		bus.$on('panel-view-selected', function(panel_view) {
			this.current_panel_view = panel_view
		}.bind(this)),
		bus.$on('open-relation-modal', function(relationship_id) {
			this.open_modal_state = true
			this.open_modal_relationship_id = relationship_id
		}.bind(this)),
		bus.$on('close-modal', function() {
			this.open_modal_state = false
			this.open_modal_relationship_id = ''
		}.bind(this)),
		bus.$on('delete-relation', function(relationship_id) {
			for (i=0; i < this.panels.length; i++) {
				if (this.panels[i].name == this.current_view) {
					for (j=0; j<this.panels[i].views.length; j++) {
						if (this.panels[i].views[j].type == 'Table') {
							for (k=0; k<this.panels[i].views[j].data.length; k++) {
								if (this.panels[i].views[j].data[k].id == relationship_id) {
									// invoke API DELETE method to remove from database
									this.panels[i].views[j].data.splice(k,1)
								}
							}
						}
					}
				}
			}
		}.bind(this))
	},
	filters: {
		capitalize : function(value) {
			if (!value) return ''
			if (typeof value == "object") {
				cap_array = []
				for (i=0; i<value.length; i++) {
					new_value = value[i].charAt(0).toUpperCase() + value[i].slice(1)
					cap_array.push(new_value)
				}
			return cap_array
			}
			value = value.toString()
			return value.charAt(0).toUpperCase() + value.slice(1)
		},
		spacereplace: function(value) {
			if (!value) return ''
			if (typeof value == "object") {
				spaced_array = []
				for (i=0; i<value.length; i++) {
					new_value = value[i].toString().replace('_',' ')
					spaced_array.push(new_value)
				}
			return spaced_array
			}
			value = value.toString()
			return value.charAt(0).toUpperCase() + value.slice(1)
		}
	}
})<|endoftext|>


<commit_before>$(document).ready(function(){
	if (!collectionId) {
		$("#search-terms").keypress(
			function(evt){
				var keyNum;
				if (window.event) { keyNum = evt.keyCode; }
				else { keyNum = evt.which; }

				if(keyNum == 13) { performSearch("full", $("#search-terms").val(), 0);}
			}
		);

		if($("#search-terms").val()){
			performSearch("full", $("#search-terms").val(), 0);
		}
	} else {
		performSearch("collection", collectionId, 0);
	}
});

function performSearch(index, terms, begin) {
	searchObj = { index: index, terms: escape(terms), limit: 10, skip: begin};

	///Send request to get the search results
	$.post("/search/", searchObj, function(response) {
		console.log(response); ///For debug purpose, to monitor the response object
		searchResults(response);
	});
}

function searchResults(response){
	$("#results-container").empty(); ///Clear the previous search results
	///Set number of results found
	if (!collectionId) { $("#results-container").append("
You found " + response.total_rows + " results
"); }
	else { $("#results-container").append("
Containing " + response.total_rows + " records
"); }

	listSearchResults(response.rows);
}

function pageSwitcher(numRows){
	var numPages = (numRows - 1) / 10 + 1;

}

///List the search results in "results-container" element
///Parameters:
/////rows - search results object
function listSearchResults(rows) {
	///List the search results
	$("#results-container").append("

");

	///Parse each search result object
	for( var iObj = 0; iObj < rows.length; iObj++) {
		eachResult("#results", rows[iObj]);
	}
}

function eachResult(containerId, thisRespObj) {
	///Set title item
	$(containerId).append(getResultTitleDt(thisRespObj.id, thisRespObj.doc.Title));
	///Set description and other information
	$(containerId).append(getResultDetailDd(thisRespObj));

}

///Return the string of the title element
///Parameters:
/////id - this result object's id
/////title - this result object's title
function getResultTitleDt(id, title) {
	var hLink = "/resource/" + id +"/html"; ///Define the link to metadata

	var titleString = "
";
	titleString += "";
	titleString += title; ///Define the title content
	titleString += "";
	titleString += "
";

	return titleString;
}

///Return the string of other information element
///Parameters:
/////thisResp - this search result object
function getResultDetailDd(thisResp) {
	var detailString = "
";

	///Get description string
	detailString += getProps("Description", thisResp.doc.Description, "search-results-description");
	///Get author and date information string
	rInfoTypes = ["Authors", "PublishDate", "ModifyDate"];
	rInfoValues = [thisResp.doc.Authors, thisResp.doc.PublicationDate, thisResp.doc.ModifiedDate];
	detailString += getProps(rInfoTypes, rInfoValues, "search-results-info");

	detailString += "
";

	return detailString;
}

///Return the string of the search result information elements
///Parameters:
/////propType - the type/type array for this property
/////propValue - the value/value array for this property
/////idClass - the id used to apply css for those element(s)
function getProps(propType, propValue, idClass){
	if(!propValue) {return "";}

	var propString;
	if(idClass) {
		propString = "
";
	} else {
		propString = "
";
	}

	if(propType.constructor.toString().indexOf("Array") != -1) {
		propString += parseValues(propType, propValue);
	} else {
		propString += parseValue(propType, propValue);
	}
	propString += "
";

	return propString;

}

///Return the string of a single property element
///Parameters:
/////type - a single property type
/////value - a single property value
function parseValue(type, value) {
	switch (type){
		case "Description":
			if(value.length > 200) {
				return value.slice(0, 200) + " . . .";
			}else {
				return value;
			}
	}
}

///Return the string of property array elements
///Parameters:
/////types - the property type array
/////values - the property value array
function parseValues(types, values) {
	var valueString = "";
	for(var iTy = 0; iTy < types.length; iTy ++){
		var type = types[iTy];
		var value = values[iTy];

		if(value) {

			///Set connection symbol between different kinds of information
			if(valueString){
				valueString += " - ";
			}

			///Parse different information using different way
			switch (type){
				case "Authors":
					var authors = "";
					for(var iAu = 0; iAu < value.length; iAu ++){
						if(iAu == 0){
							authors = value[iAu].Name;
						}else{
							authors += ", " + value[iAu].Name;
						}
					}
					valueString += authors;
					break;
				case "PublishDate":
					value = value.replace("T", " ");
					value = value.replace("Z", " ");
					valueString += "Published on " + value;
					break;
				case "ModifyDate":
					value = value.replace("T", " ");
					value = value.replace("Z", " ");
					valueString += "Modified on " + value;
					break;
				default:
					valueString -= " - ";
					break;
			}
		}
	}

	return valueString;
}

/**********************Page Switcher****************************************/
function addPager(resultCount){
	var pageCount = (resultCount - 1) / 10 + 1;

	$("#page-switcher").append("
");

	$("#page-switcher").append("
");
}
<commit_msg>Adjusment to search results to show OrgName if name is not present<commit_after>$(document).ready(function(){
	if (!collectionId) {
		$("#search-terms").keypress(
			function(evt){
				var keyNum;
				if (window.event) { keyNum = evt.keyCode; }
				else { keyNum = evt.which; }

				if(keyNum == 13) { performSearch("full", $("#search-terms").val(), 0);}
			}
		);

		if($("#search-terms").val()){
			performSearch("full", $("#search-terms").val(), 0);
		}
	} else {
		performSearch("collection", collectionId, 0);
	}
});

function performSearch(index, terms, begin) {
	searchObj = { index: index, terms: escape(terms), limit: 10, skip: begin};

	///Send request to get the search results
	$.post("/search/", searchObj, function(response) {
		console.log(response); ///For debug purpose, to monitor the response object
		searchResults(response);
	});
}

function searchResults(response){
	$("#results-container").empty(); ///Clear the previous search results
	///Set number of results found
	if (!collectionId) { $("#results-container").append("
You found " + response.total_rows + " results
"); }
	else { $("#results-container").append("
Containing " + response.total_rows + " records
"); }

	listSearchResults(response.rows);
}

function pageSwitcher(numRows){
	var numPages = (numRows - 1) / 10 + 1;

}

///List the search results in "results-container" element
///Parameters:
/////rows - search results object
function listSearchResults(rows) {
	///List the search results
	$("#results-container").append("

");

	///Parse each search result object
	for( var iObj = 0; iObj < rows.length; iObj++) {
		eachResult("#results", rows[iObj]);
	}
}

function eachResult(containerId, thisRespObj) {
	///Set title item
	$(containerId).append(getResultTitleDt(thisRespObj.id, thisRespObj.doc.Title));
	///Set description and other information
	$(containerId).append(getResultDetailDd(thisRespObj));

}

///Return the string of the title element
///Parameters:
/////id - this result object's id
/////title - this result object's title
function getResultTitleDt(id, title) {
	var hLink = "/resource/" + id +"/html"; ///Define the link to metadata

	var titleString = "
";
	titleString += "";
	titleString += title; ///Define the title content
	titleString += "";
	titleString += "
";

	return titleString;
}

///Return the string of other information element
///Parameters:
/////thisResp - this search result object
function getResultDetailDd(thisResp) {
	var detailString = "
";

	///Get description string
	detailString += getProps("Description", thisResp.doc.Description, "search-results-description");
	///Get author and date information string
	rInfoTypes = ["Authors", "PublishDate", "ModifyDate"];
	rInfoValues = [thisResp.doc.Authors, thisResp.doc.PublicationDate, thisResp.doc.ModifiedDate];
	detailString += getProps(rInfoTypes, rInfoValues, "search-results-info");

	detailString += "
";

	return detailString;
}

///Return the string of the search result information elements
///Parameters:
/////propType - the type/type array for this property
/////propValue - the value/value array for this property
/////idClass - the id used to apply css for those element(s)
function getProps(propType, propValue, idClass){
	if(!propValue) {return "";}

	var propString;
	if(idClass) {
		propString = "
";
	} else {
		propString = "
";
	}

	if(propType.constructor.toString().indexOf("Array") != -1) {
		propString += parseValues(propType, propValue);
	} else {
		propString += parseValue(propType, propValue);
	}
	propString += "
";

	return propString;

}

///Return the string of a single property element
///Parameters:
/////type - a single property type
/////value - a single property value
function parseValue(type, value) {
	switch (type){
		case "Description":
			if(value.length > 200) {
				return value.slice(0, 200) + " . . .";
			}else {
				return value;
			}
	}
}

///Return the string of property array elements
///Parameters:
/////types - the property type array
/////values - the property value array
function parseValues(types, values) {
	var valueString = "";
	for(var iTy = 0; iTy < types.length; iTy ++){
		var type = types[iTy];
		var value = values[iTy];

		if(value) {

			///Set connection symbol between different kinds of information
			if(valueString){
				valueString += " - ";
			}

			///Parse different information using different way
			switch (type){
				case "Authors":
					var authors = "";
					for(var iAu = 0; iAu < value.length; iAu ++){
						if(iAu == 0){
							authors = value[iAu].Name || value[iAu].OrganizationName;
						}else{
							authors += ", " + value[iAu].Name || value[iAu].OrganizationName;
						}
					}
					valueString += authors;
					break;
				case "PublishDate":
					value = value.replace("T", " ");
					value = value.replace("Z", " ");
					valueString += "Published on " + value;
					break;
				case "ModifyDate":
					value = value.replace("T", " ");
					value = value.replace("Z", " ");
					valueString += "Modified on " + value;
					break;
				default:
					valueString -= " - ";
					break;
			}
		}
	}

	return valueString;
}

/**********************Page Switcher****************************************/
function addPager(resultCount){
	var pageCount = (resultCount - 1) / 10 + 1;

	$("#page-switcher").append("
");

	$("#page-switcher").append("
");
}
<|endoftext|>


<commit_before>var windowWidth = window.innerWidth,
    $sliderImages = document.getElementsByClassName('sliderImages')[0],
    howManyChildren = $sliderImages.children.length,
    $imageSlider = document.getElementsByClassName('slimg'),
    sliderButtons = Array.prototype.slice.call(document.getElementsByClassName('sliderButton')),
    cantButtons = sliderButtons.length;

function slide() {
    for (i = 0; i < $imageSlider.length; i++) {
        $imageSlider[i].style.width = windowWidth + "px";
    }

    $sliderImages.style.width = windowWidth * howManyChildren + "px";
}

function buttonChange () {
    for (i = 0; i < cantButtons; i++) {
        var button = sliderButtons[i];

        button.addEventListener("click", function(e) {
            var index = sliderButtons.indexOf(e.currentTarget);
            $sliderImages.style.left = windowWidth * (index) * (-1) + "px";
        })
    }
}

(function() {
    slide();
    buttonChange();
})();<commit_msg>Slider without overflow 2nd version<commit_after>var windowWidth = window.innerWidth,
    $sliderImages = document.getElementsByClassName('sliderImages')[0],
    howManyChildren = $sliderImages.children.length,
    $imageSlider = document.getElementsByClassName('slimg'),
    sliderButtons = Array.prototype.slice.call(document.getElementsByClassName('sliderButton')),
    cantButtons = sliderButtons.length;

function slide() {
    for (i = 0; i < $imageSlider.length; i++) {
        $imageSlider[i].style.width = windowWidth + "px";
    }

    $sliderImages.style.width = windowWidth * howManyChildren + "px";
}

function buttonAction () {
    for (i = 0; i < cantButtons; i++) {
        var button = sliderButtons[i];

        button.addEventListener("click", function(e) {
            var index = sliderButtons.indexOf(e.currentTarget);
            $sliderImages.style.left = windowWidth * (index) * (-1) + "px";
        })
    }
}

(function() {
    slide();
    buttonChange();
})();<|endoftext|>


<commit_before>var themes = [ {
  file : 'clear.css',
  label : 'Clear',
  id : 'clear'
}, {
  file : 'jungle.css',
  label : 'Jungle',
  id : 'jungle'
}, {
  file : 'yotsuba_b.css',
  label : 'Yotsuba B',
  id : 'yotsubab'
}, {
  file : 'yotsuba.css',
  label : 'Yotsuba',
  id : 'yotsuba'
} ];

var customCss;
var addedTheme;

function updateCss() {

  if (addedTheme) {
    addedTheme.parentNode.removeChild(addedTheme);
    addedTheme = null;
  }

  for (var i = 0; i < themes.length; i++) {
    var theme = themes[i];

    if (theme.id === localStorage.selectedTheme) {
      addedTheme = theme.element;
      document.head.insertBefore(theme.element, customCss);
    }
  }

}

if (!DISABLE_JS) {

  for (var i = 0; i < document.head.children.length; i++) {
    var element = document.head.children[i];

    if (element.rel === 'stylesheet'
        && element.href.indexOf('/custom.css') > -1) {

      customCss = element;
      break;
    }

  }

  for (var i = 0; i < themes.length; i++) {
    themes[i].element = document.createElement('link');
    themes[i].element.type = 'text/css';
    themes[i].element.rel = 'stylesheet';
    themes[i].element.href = '/.static/css/' + themes[i].file;
  }

  updateCss();

  var postingLink = document.getElementById('navPosting');

  if (postingLink) {

    var divider = document.createElement('span');
    divider.innerHTML = '/';

    var referenceNode = postingLink.nextSibling;

    postingLink.parentNode.insertBefore(divider, referenceNode);

    var themeSelector = document.createElement('select');
    themeSelector.id = 'themeSelector';

    var vanillaOption = document.createElement('option');
    vanillaOption.innerHTML = 'Default';
    themeSelector.appendChild(vanillaOption);

    for (i = 0; i < themes.length; i++) {

      var theme = themes[i];

      var themeOption = document.createElement('option');
      themeOption.innerHTML = theme.label;

      if (theme.id === localStorage.selectedTheme) {
        themeOption.selected = true;
      }

      themeSelector.appendChild(themeOption);

    }

    themeSelector.onchange = function() {

      if (!themeSelector.selectedIndex) {

        if (localStorage.selectedTheme) {

          delete localStorage.selectedTheme;

          updateCss();
        }

        return;
      }

      var selectedTheme = themes[themeSelector.selectedIndex - 1];

      if (selectedTheme.id === localStorage.selectedTheme) {
        return;
      }

      localStorage.selectedTheme = selectedTheme.id;

      updateCss();

    };

    postingLink.parentNode.insertBefore(themeSelector, referenceNode);

  }

}
<commit_msg>Yotsuba is not completed; we let this be known<commit_after>var themes = [ {
  file : 'clear.css',
  label : 'Clear',
  id : 'clear'
}, {
  file : 'jungle.css',
  label : 'Jungle',
  id : 'jungle'
}, {
  file : 'yotsuba_b.css',
  label : 'Yotsuba B',
  id : 'yotsubab'
}, {
  file : 'yotsuba.css',
  label : 'Yotsuba (NOT COMPLETED)',
  id : 'yotsuba'
} ];

var customCss;
var addedTheme;

function updateCss() {

  if (addedTheme) {
    addedTheme.parentNode.removeChild(addedTheme);
    addedTheme = null;
  }

  for (var i = 0; i < themes.length; i++) {
    var theme = themes[i];

    if (theme.id === localStorage.selectedTheme) {
      addedTheme = theme.element;
      document.head.insertBefore(theme.element, customCss);
    }
  }

}

if (!DISABLE_JS) {

  for (var i = 0; i < document.head.children.length; i++) {
    var element = document.head.children[i];

    if (element.rel === 'stylesheet'
        && element.href.indexOf('/custom.css') > -1) {

      customCss = element;
      break;
    }

  }

  for (var i = 0; i < themes.length; i++) {
    themes[i].element = document.createElement('link');
    themes[i].element.type = 'text/css';
    themes[i].element.rel = 'stylesheet';
    themes[i].element.href = '/.static/css/' + themes[i].file;
  }

  updateCss();

  var postingLink = document.getElementById('navPosting');

  if (postingLink) {

    var divider = document.createElement('span');
    divider.innerHTML = '/';

    var referenceNode = postingLink.nextSibling;

    postingLink.parentNode.insertBefore(divider, referenceNode);

    var themeSelector = document.createElement('select');
    themeSelector.id = 'themeSelector';

    var vanillaOption = document.createElement('option');
    vanillaOption.innerHTML = 'Default';
    themeSelector.appendChild(vanillaOption);

    for (i = 0; i < themes.length; i++) {

      var theme = themes[i];

      var themeOption = document.createElement('option');
      themeOption.innerHTML = theme.label;

      if (theme.id === localStorage.selectedTheme) {
        themeOption.selected = true;
      }

      themeSelector.appendChild(themeOption);

    }

    themeSelector.onchange = function() {

      if (!themeSelector.selectedIndex) {

        if (localStorage.selectedTheme) {

          delete localStorage.selectedTheme;

          updateCss();
        }

        return;
      }

      var selectedTheme = themes[themeSelector.selectedIndex - 1];

      if (selectedTheme.id === localStorage.selectedTheme) {
        return;
      }

      localStorage.selectedTheme = selectedTheme.id;

      updateCss();

    };

    postingLink.parentNode.insertBefore(themeSelector, referenceNode);

  }

}
<|endoftext|>


<commit_before>function FileAPI (c, t, d, f, bin, uploadURL, binURL) {

    var fileCount = c,
        fileList = t,
        dropZone = d,
        fileField = f,
        counter_queue = 0,
        counter_uploading = 0,
        counter_completed = 0,
        counter_failed = 0,
        concurrency = 4,
        fileQueue = new Array(),
        preview = null;

    this.init = function () {
        fileField.onchange = this.addFiles;
        dropZone.addEventListener("dragenter",  this.stopProp, false);
        dropZone.addEventListener("dragleave",  this.dragExit, false);
        dropZone.addEventListener("dragover",  this.dragOver, false);
        dropZone.addEventListener("drop",  this.showDroppedFiles, false);
    }

    this.addFiles = function () {
        addFileListItems(this.files);
    }

    function updateFileCount() {
	var box = document.getElementById('fileCount');

        // XXX: Make this less messy
        var text = counter_completed + " of " + counter_queue + " file";
        if (counter_queue != 1){
            text = text + "s";
        }
        text = text + " uploaded";
        if (counter_failed > 0) {
            text = text + ". " + counter_failed + " failed.";
            box.className = "alert alert-danger";
        } else if (counter_completed == counter_queue) {
            text = text + ", all done!";
            box.className = "alert alert-success";

            // Automatic refresh when uploads complete
            window.location.assign(binURL)
        }

        if ((counter_completed + counter_failed) != counter_queue) {
            text = text + "...";
            box.className = "alert alert-info";
        }

        fileCount.textContent = text;
	box.style.display = 'block';
    }
    this.showDroppedFiles = function (ev) {
        ev.stopPropagation();
        ev.preventDefault();
        dropZone.style["backgroundColor"] = "#FFFFFF";
        var files = ev.dataTransfer.files;
        addFileListItems(files);
    }

    this.dragOver = function (ev) {
        ev.stopPropagation();
        ev.preventDefault();
        this.style["backgroundColor"] = "#EEEEEE";
    }

    this.dragExit = function (ev) {
        ev.stopPropagation();
        ev.preventDefault();
        dropZone.style["backgroundColor"] = "#FFFFFF";
    }
    this.stopProp = function (ev) {
        ev.stopPropagation();
        ev.preventDefault();
    }

    this.uploadQueue = function (ev) {
        ev.preventDefault();

        // Loop that will wait 100ms between each iteration
        var i = setInterval(function(){
            // Initiate a upload if within the concurrency limit
            if (counter_uploading < concurrency) {
                var item = fileQueue.pop();
                uploadFile(item.file, item.container);
            }

            // Break out of the loop when the queue is empty
            if (fileQueue.length == 0) {
                clearInterval(i);
            }
        }, 100);
    }

    var addFileListItems = function (files) {
        counter_queue += files.length;
        updateFileCount();
        for (var i = 0; i < files.length; i++) {
            showFileInList(files[i])
        }
    }

    var showFileInList = function (file) {
        //var file = ev.target.file;
        if (file) {
            var container = document.createElement("p");
            //container.className = "list-group-item";

            var meta = document.createElement("div");
            meta.className = "row";

            var name = document.createElement("div");
            var strong = document.createElement("strong");
            var nameText = document.createTextNode(file.name);
            strong.appendChild(nameText);
            name.appendChild(strong);
	    name.className = "col";
            meta.appendChild(name);

            var filesize = getReadableFileSizeString(file.size);
            //var size = document.createElement("div");
            //var sizeText = document.createTextNode(filesize);
            //size.appendChild(sizeText);
	    //size.className = "col-md-2";
            //meta.appendChild(size)

            var speed = document.createElement("div");
            //var mimeText = document.createTextNode(mimetype);
            speed.textContent = "Pending (" + filesize + ")";
            speed.className = "col text-right";
            meta.appendChild(speed)

            // Progressbar
            var bar_row = document.createElement("div");
            bar_row.className = "row";

            var bar_col = document.createElement("div");
	    bar_col.className = "col-12";

            var progress = document.createElement("div");
            progress.className = "progress";

            var bar = document.createElement("div");
            bar.className = "progress-bar";

            bar.setAttribute("style", "width: 0%");
            bar.setAttribute("aria-valuemin", 0);
            bar.setAttribute("aria-valuemax", 100);
            bar.setAttribute("aria-valuenow", 0);

            progress.appendChild(bar);
            bar_col.appendChild(progress);
            bar_row.appendChild(bar_col);

            container.appendChild(meta)
            container.appendChild(bar_row)

            fileList.insertBefore(container, fileList.childNodes[0]);
            updateFileCount();
            fileQueue.push({
                file : file,
                container : container
            });
        }
    }

    function roundNumber(num, dec) {
        var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
        return result;
    }

    function humanizeBytesPerSecond(speed) {
        var unit = "KB/s";
        if (speed >= 1024) {
            unit = "MB/s";
            speed /=1024;
        }
        return (speed.toFixed(1) + unit);
    };

    var uploadFile = function (file, container) {
        if (container && file) {
            counter_uploading += 1;

            var filesize = getReadableFileSizeString(file.size);
            var speed = container.getElementsByTagName("div")[2];
            var bar = container.getElementsByTagName("div")[6];

            var xhr = new XMLHttpRequest();
            upload = xhr.upload;

            // For speed measurements
            var startTime = (new Date()).getTime();

            // Upload in progress
            upload.addEventListener("progress", function (e) {
                if (e.lengthComputable) {
                    bar.className = "progress-bar progress-bar-striped progress-bar-animated";
                    progress_in_percent = (e.loaded / e.total) * 100;
                    bar.setAttribute("aria-valuenow", progress_in_percent);
                    bar.setAttribute("style", "width: " + progress_in_percent + "%");

                    if (e.loaded == e.total && e.total > 0) {
                        // Upload complete
                        speedText = "Server side processing... (" + filesize + ")";
                    } else if (e.loaded > 0) {
                        // Upload in progress
                        var curTime = (new Date()).getTime();
                        var seconds = curTime - startTime;
                        var bps = seconds ? e.loaded / seconds : 0;
                        if (isNaN(bps)) {
                            speedText = "Uploading... (" + filesize + ")";
                        } else {
                            speedText = "Uploading at " + humanizeBytesPerSecond(bps) + " (" + filesize + ")";
                        }
                    } else {
                        // Upload just initiated
                        speedText = "(" + filesize + ")";
                    }

                    speed.textContent = speedText;
                }
            }, false);

            // Upload complete
            xhr.onload = function(e) {
                bar.setAttribute("aria-valuenow", 100);
                counter_uploading -= 1;
		var body = xhr.response;
                if (xhr.status == 201 && xhr.readyState == 4) {
                    bar.className = "progress-bar bg-success";
                    speed.textContent = "Complete (" + filesize + ")";
                    counter_completed += 1;
                } else {
                    bar.className = "progress-bar bg-danger";
                    speed.textContent = body + " (" + filesize + ")";
                    console.log("Unexpected response code: " + xhr.status);
                    console.log("Response body: " + xhr.response);
                    counter_failed += 1;
                }
                updateFileCount();
            };

            // Handle upload errors here
            xhr.onerror = function (e) {
                console.log("onerror: status: " + xhr.status + ", readystate: " + xhr.readyState);
                console.log(e);
                bar.className = "progress progress-danger";
                bar.setAttribute("aria-valuenow", 100);
                speed.textContent = "Failed due to network error (" + filesize + ")";
                counter_failed += 1;
                counter_uploading -= 1;
                updateFileCount();
            };

            xhr.open(
                "POST",
                uploadURL
            );
            xhr.setRequestHeader("Cache-Control", "no-cache");
            xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            xhr.setRequestHeader("Filename", file.name.replace(/[^A-Za-z0-9-_=,.]/g, "_"));
            xhr.setRequestHeader("Size", file.size);
            xhr.setRequestHeader("Bin", bin);
            xhr.send(file);
        }
    }
}

// http://stackoverflow.com/q/10420352
function getReadableFileSizeString(fileSizeInBytes) {
    var i = -1;
    var byteUnits = ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    do {
        fileSizeInBytes = fileSizeInBytes / 1024;
        i++;
    } while (fileSizeInBytes > 1024);

    return Math.max(fileSizeInBytes, 0.1).toFixed(1) + byteUnits[i];
};

function deleteURL (url, messageBoxID) {
    console.log("Delete url: " + url);
    var xhr = new XMLHttpRequest();
    var box = document.getElementById(messageBoxID);

    box.textContent = "Delete in progress ..."
    box.className = "alert alert-dark";

    xhr.onload = function(e) {
        if (xhr.status == 200 && xhr.readyState == 4) {
            console.log("Deleted successfully");
            box.textContent = "Delete operation completed successfully.";
            box.className = "alert alert-success";
        } else if (xhr.status  == 404 && xhr.readyState == 4) {
            box.textContent = "Not found.";
            box.className = "alert alert-warning";
        } else {
            console.log("Failed to delete");
            box.textContent = "Error " + xhr.status + ". Unable to verify the operation.";
            box.className = "alert alert-danger";
        }
    };

    xhr.onerror = function (e) {
        console.log("onerror: status: " + xhr.status + ", readystate: " + xhr.readyState);
    };

    xhr.open(
        "DELETE",
        url
    );

    xhr.send();
};
<commit_msg>Improve text in text box<commit_after>function FileAPI (c, t, d, f, bin, uploadURL, binURL) {

    var fileCount = c,
        fileList = t,
        dropZone = d,
        fileField = f,
        counter_queue = 0,
        counter_uploading = 0,
        counter_completed = 0,
        counter_failed = 0,
        concurrency = 4,
        fileQueue = new Array(),
        preview = null;

    this.init = function () {
        fileField.onchange = this.addFiles;
        dropZone.addEventListener("dragenter",  this.stopProp, false);
        dropZone.addEventListener("dragleave",  this.dragExit, false);
        dropZone.addEventListener("dragover",  this.dragOver, false);
        dropZone.addEventListener("drop",  this.showDroppedFiles, false);
    }

    this.addFiles = function () {
        addFileListItems(this.files);
    }

    function updateFileCount() {
	var box = document.getElementById('fileCount');

        // XXX: Make this less messy
        var text = counter_completed + " of " + counter_queue + " file";
        if (counter_queue != 1){
            text = text + "s";
        }
        text = text + " uploaded";
        if (counter_failed > 0) {
            text = text + ". " + counter_failed + " failed.";
            box.className = "alert alert-danger";
        } else if (counter_completed == counter_queue) {
            text = text + ", all done!";
            box.className = "alert alert-success";

            // Automatic refresh when uploads complete
            window.location.assign(binURL)
        }

        if ((counter_completed + counter_failed) != counter_queue) {
            text = text + "...";
            box.className = "alert alert-info";
        }

        fileCount.textContent = text;
	box.style.display = 'block';
    }
    this.showDroppedFiles = function (ev) {
        ev.stopPropagation();
        ev.preventDefault();
        dropZone.style["backgroundColor"] = "#FFFFFF";
        var files = ev.dataTransfer.files;
        addFileListItems(files);
    }

    this.dragOver = function (ev) {
        ev.stopPropagation();
        ev.preventDefault();
        this.style["backgroundColor"] = "#EEEEEE";
    }

    this.dragExit = function (ev) {
        ev.stopPropagation();
        ev.preventDefault();
        dropZone.style["backgroundColor"] = "#FFFFFF";
    }
    this.stopProp = function (ev) {
        ev.stopPropagation();
        ev.preventDefault();
    }

    this.uploadQueue = function (ev) {
        ev.preventDefault();

        // Loop that will wait 100ms between each iteration
        var i = setInterval(function(){
            // Initiate a upload if within the concurrency limit
            if (counter_uploading < concurrency) {
                var item = fileQueue.pop();
                uploadFile(item.file, item.container);
            }

            // Break out of the loop when the queue is empty
            if (fileQueue.length == 0) {
                clearInterval(i);
            }
        }, 100);
    }

    var addFileListItems = function (files) {
        counter_queue += files.length;
        updateFileCount();
        for (var i = 0; i < files.length; i++) {
            showFileInList(files[i])
        }
    }

    var showFileInList = function (file) {
        //var file = ev.target.file;
        if (file) {
            var container = document.createElement("p");
            //container.className = "list-group-item";

            var meta = document.createElement("div");
            meta.className = "row";

            var name = document.createElement("div");
            var strong = document.createElement("strong");
            var nameText = document.createTextNode(file.name);
            strong.appendChild(nameText);
            name.appendChild(strong);
	    name.className = "col";
            meta.appendChild(name);

            var filesize = getReadableFileSizeString(file.size);
            //var size = document.createElement("div");
            //var sizeText = document.createTextNode(filesize);
            //size.appendChild(sizeText);
	    //size.className = "col-md-2";
            //meta.appendChild(size)

            var speed = document.createElement("div");
            //var mimeText = document.createTextNode(mimetype);
            speed.textContent = "Pending (" + filesize + ")";
            speed.className = "col text-right";
            meta.appendChild(speed)

            // Progressbar
            var bar_row = document.createElement("div");
            bar_row.className = "row";

            var bar_col = document.createElement("div");
	    bar_col.className = "col-12";

            var progress = document.createElement("div");
            progress.className = "progress";

            var bar = document.createElement("div");
            bar.className = "progress-bar";

            bar.setAttribute("style", "width: 0%");
            bar.setAttribute("aria-valuemin", 0);
            bar.setAttribute("aria-valuemax", 100);
            bar.setAttribute("aria-valuenow", 0);

            progress.appendChild(bar);
            bar_col.appendChild(progress);
            bar_row.appendChild(bar_col);

            container.appendChild(meta)
            container.appendChild(bar_row)

            fileList.insertBefore(container, fileList.childNodes[0]);
            updateFileCount();
            fileQueue.push({
                file : file,
                container : container
            });
        }
    }

    function roundNumber(num, dec) {
        var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
        return result;
    }

    function humanizeBytesPerSecond(speed) {
        var unit = "KB/s";
        if (speed >= 1024) {
            unit = "MB/s";
            speed /=1024;
        }
        return (speed.toFixed(1) + unit);
    };

    var uploadFile = function (file, container) {
        if (container && file) {
            counter_uploading += 1;

            var filesize = getReadableFileSizeString(file.size);
            var speed = container.getElementsByTagName("div")[2];
            var bar = container.getElementsByTagName("div")[6];

            var xhr = new XMLHttpRequest();
            upload = xhr.upload;

            // For speed measurements
            var startTime = (new Date()).getTime();

            // Upload in progress
            upload.addEventListener("progress", function (e) {
                if (e.lengthComputable) {
                    bar.className = "progress-bar progress-bar-striped progress-bar-animated";
                    progress_in_percent = (e.loaded / e.total) * 100;
                    bar.setAttribute("aria-valuenow", progress_in_percent);
                    bar.setAttribute("style", "width: " + progress_in_percent + "%");

                    if (e.loaded == e.total && e.total > 0) {
                        // Upload complete
                        speedText = "Server side processing... (" + filesize + ")";
                    } else if (e.loaded > 0) {
                        // Upload in progress
                        var curTime = (new Date()).getTime();
                        var seconds = curTime - startTime;
                        var bps = seconds ? e.loaded / seconds : 0;
                        if (isNaN(bps)) {
                            speedText = "Uploading... (" + filesize + ")";
                        } else {
                            speedText = "Uploading at " + humanizeBytesPerSecond(bps) + " (" + filesize + ")";
                        }
                    } else {
                        // Upload just initiated
                        speedText = "(" + filesize + ")";
                    }

                    speed.textContent = speedText;
                }
            }, false);

            // Upload complete
            xhr.onload = function(e) {
                bar.setAttribute("aria-valuenow", 100);
                counter_uploading -= 1;
		var body = xhr.response;
                if (xhr.status == 201 && xhr.readyState == 4) {
                    bar.className = "progress-bar bg-success";
                    speed.textContent = "Complete (" + filesize + ")";
                    counter_completed += 1;
                } else {
                    bar.className = "progress-bar bg-danger";
                    speed.textContent = body + " (" + filesize + ")";
                    console.log("Unexpected response code: " + xhr.status);
                    console.log("Response body: " + xhr.response);
                    counter_failed += 1;
                }
                updateFileCount();
            };

            // Handle upload errors here
            xhr.onerror = function (e) {
                console.log("onerror: status: " + xhr.status + ", readystate: " + xhr.readyState);
                console.log(e);
                bar.className = "progress progress-danger";
                bar.setAttribute("aria-valuenow", 100);
                speed.textContent = "Failed due to network error (" + filesize + ")";
                counter_failed += 1;
                counter_uploading -= 1;
                updateFileCount();
            };

            xhr.open(
                "POST",
                uploadURL
            );
            xhr.setRequestHeader("Cache-Control", "no-cache");
            xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            xhr.setRequestHeader("Filename", file.name.replace(/[^A-Za-z0-9-_=,.]/g, "_"));
            xhr.setRequestHeader("Size", file.size);
            xhr.setRequestHeader("Bin", bin);
            xhr.send(file);
        }
    }
}

// http://stackoverflow.com/q/10420352
function getReadableFileSizeString(fileSizeInBytes) {
    var i = -1;
    var byteUnits = ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    do {
        fileSizeInBytes = fileSizeInBytes / 1024;
        i++;
    } while (fileSizeInBytes > 1024);

    return Math.max(fileSizeInBytes, 0.1).toFixed(1) + byteUnits[i];
};

function deleteURL (url, messageBoxID) {
    console.log("Delete url: " + url);
    var xhr = new XMLHttpRequest();
    var box = document.getElementById(messageBoxID);

    box.textContent = "Delete operation in progress ..."
    box.className = "alert alert-dark";

    xhr.onload = function(e) {
        if (xhr.status == 200 && xhr.readyState == 4) {
            console.log("Deleted successfully");
            box.textContent = "Delete operation completed successfully.";
            box.className = "alert alert-success";
        } else if (xhr.status  == 404 && xhr.readyState == 4) {
            box.textContent = "Not found.";
            box.className = "alert alert-warning";
        } else {
            console.log("Failed to delete");
            box.textContent = "Error " + xhr.status + ". Unable to verify the operation.";
            box.className = "alert alert-danger";
        }
    };

    xhr.onerror = function (e) {
        console.log("onerror: status: " + xhr.status + ", readystate: " + xhr.readyState);
    };

    xhr.open(
        "DELETE",
        url
    );

    xhr.send();
};
<|endoftext|>


<commit_before>if (typeof MiroCommunity === 'undefined') {
    MiroCommunity = {
        Widget: function(args) {
            this.init(args);
        },
        jsonP: function(path) {
            script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = path;
            document.getElementsByTagName('head')[0].appendChild(script);
            return script;
        },
        createElement: function(name, attrs) {
            elm = document.createElement(name);
            for (attr in attrs) {
                elm[attr] = attrs[attr];
            }
            return elm;
        },
        createSpan: function(content, className) {
            span = document.createElement('span');
            span.className = className;
            span.innerHTML = content;
            return span;
        }
    };
    MiroCommunity.Widget._counter = 0;
    MiroCommunity.Widget._addedStyles = false;
    MiroCommunity.Widget.prototype = function() {
        return {
            init: function(options) {
                this.opts = options;
                this.counter = ++MiroCommunity.Widget._counter;
                this.id = 'mc-widget-' + this.counter;
                this.scriptTag = null;
            },
            versioned: function(method, args) {
                func = null;
                if (this.opts.version !== undefined) {
                    func = this[method + '_v' + this.opts.version]
                }
                if (!func) {
                    func = this[method];
                }
                return func.apply(this, Array.prototype.slice.call(arguments, 1));
            },
            render: function () {
                this.addStyle();
                if (this.opts.version && this.opts.version !== 1) {
                    widget_class = 'mc-widget-v' + this.opts.version
                } else {
                    widget_class = 'mc-widget'
                }
                document.write('

');
                this.versioned('beforeLoad');
                this.load();
            },
            addStyle: function() {
                head = document.getElementsByTagName('head')[0];
                if (!MiroCommunity.Widget._addedStyles && this.opts.stylesheet !== '') {
                    link = document.createElement('link');
                    link.rel = 'stylesheet';
                    if (this.opts.stylesheet) {
                        link.href = this.opts.stylesheet;
                    } else {
                        link.href = 'http://' + this.opts.domain + '/css/widget.css';
                    }
                    head.appendChild(link);
                    MiroCommunity.Widget._addedStyles = true;
                }
            },
            load: function() {
                var t = this;
                ajax_path = 'http://' + t.opts.domain + '/feeds/json/' + t.opts.source;
                MiroCommunity['callback_' + t.counter] = function(json) {
                    t.scriptTag.parentNode.removeChild(t.scriptTag);
                    t.scriptTag = null;
                    var div = document.getElementById(t.id);
                    t.versioned('update', div, json);
                };
                t.scriptTag = MiroCommunity.jsonP(ajax_path + '?jsoncallback=MiroCommunity.callback_' + t.counter);
            },
            // Widget version 1
            beforeLoad: function () {
                width = this.opts.width ? this.opts.width : 300;
                div = document.getElementById(this.id);
                title = MiroCommunity.createElement('h2')
                title.innerText = this.opts.title ? this.opts.title : 'Watch Videos from Miro Community';
                div.appendChild(title);
                ul = MiroCommunity.createElement('ul', {className: "mc-loading"});
                ul.style.width = width + 'px';
                div.appendChild(ul);
                footer = MiroCommunity.createElement('a', {className: "mc-from",
                                                           href: "http://" + this.opts.domain + '/'})
                footer.innerText = this.opts.domain;
                div.appendChild(footer);
            },
            update: function(div, json) {
                var ul = div.getElementsByTagName('ul')[0];
                ul.innerHTML = ul.className = '';
                var count = this.opts.count ? this.opts.count : 4;
                var li = null;
                for (var i=0; i < json.items.length && i < count; i++) {
                    video = json.items[i];
                    li = MiroCommunity.createElement('li', {className: 'mc-video'});
                    link = MiroCommunity.createElement('a', {href: video.link});
                    thumb = MiroCommunity.createElement('span', {className: 'mc-thumbnail'});
                    var thumbnail = null;
                    if (video.thumbnail) {
                        thumbnail = video.thumbnail;
                    } else {
                        thumbnail = 'http://' + this.opts.domain + '/images/default_vid.gif';
                    }
                    thumb.appendChild(MiroCommunity.createElement('img', {
                        width: 120,
                        height: 90,
                        src: thumbnail}));
                    thumb.appendChild(MiroCommunity.createSpan('', 'mc-play'));
                    link.appendChild(thumb);
                    link.appendChild(MiroCommunity.createSpan(video.title, 'mc-title'));
                    link.appendChild(MiroCommunity.createSpan(video.when, 'mc-when'));
                    li.appendChild(link);
                    ul.appendChild(li);
                }
                if (li !== null) {
                    li.className += ' mc-last';
                }
            },
            // Widget version 2
            beforeLoad_v2: function () {
                widget_wrapper = document.getElementById(this.id);
                if (this.opts.width) {
                    widget_wrapper.style.width = this.opts.width + 'px';
                } else if (this.opts.size === 'small') {
                    widget_wrapper.style.width = '108px';
                } else if (this.opts.size === 'medium') {
                   widget_wrapper.style.width = '160px';
                } else if (this.opts.size == 'large') {
                    widget_wrapper.style.width = '242px';
                }
                if (this.opts.border) {
                    widget_wrapper.style.background = this.opts.border;
                }
                widget_wrapper.className = widget_wrapper.className + ' mc-widget-' + this.opts.size;
                div = document.createElement('div');
                if (this.opts.bg) {
                    div.style.background = this.opts.bg;
                }
                title = MiroCommunity.createElement('div', {className: 'mc-widget-title'});
                if (this.opts.text) {
                    title.style.color = this.opts.text;
                }
                title.innerText = title.textContent = this.opts.title ? this.opts.title : 'Watch Videos from Miro Community';
                div.appendChild(title);
                ul = MiroCommunity.createElement('ul', {className: "mc-loading"});
                div.appendChild(ul);
                footer_box = MiroCommunity.createElement('div', {className: "mc-footer"});
                if (this.opts.logo) {
                    img = MiroCommunity.createElement('img', {src: this.opts.logo})
                    a = MiroCommunity.createElement('a', {href: "http://" + this.opts.domain + '/'});
                    a.appendChild(img);
                    footer_box.appendChild(a);
                }
                more_link = MiroCommunity.createElement('a', {href: "http://" + this.opts.domain + '/'});
                more_link.innerText = more_link.textContent = 'See More';
                more_link_wrapper = document.createElement('div');
                more_link_wrapper.appendChild(more_link);
                footer_box.appendChild(more_link_wrapper);
                div.appendChild(footer_box);
                widget_wrapper.appendChild(div);
            },
            update_v2: function(div, json) {
                links = div.getElementsByTagName('a');
                more_link = links[links.length-1];
                more_link.href = json.link;
                var ul = div.getElementsByTagName('ul')[0];
                ul.innerHTML = ul.className = '';
                var count = this.opts.count ? this.opts.count : 4;
                var li = null;
                var widget_size = this.opts.size;
                flat_bg = MiroCommunity.createElement('img', {src: 'http://' + this.opts.domain + '/images/widget/flat_' + widget_size + '.png',
                                                              className: 'mc-flat-bg'});
                separator = MiroCommunity.createElement('div', {className: 'mc-separator'});
                for (var i=0; i < json.items.length && i < count; i++) {
                    video = json.items[i];
                    li = MiroCommunity.createElement('li', {className: 'mc-video'});
                    if (video.thumbnail) {
                        for (j=0; j < video.thumbnails_resized.length; j++){
                            resized = video.thumbnails_resized[j];
                            width = resized.width; height = resized.height;
                            if ((width === 140 && height === 110 && widget_size == 'medium') ||
                                (width === 88 && height == 68 && widget_size == 'small') ||
                                (width === 222 && height == 169 && widget_size == 'large')) {
                                li.style.backgroundImage = 'url(' + resized.url + ')';
                            }
                        }
                    }
                    box = document.createElement('div');
                    link = MiroCommunity.createElement('a', {href: video.link});
                    link.appendChild(flat_bg.cloneNode(false));
                    if (widget_size !== 'small') {
                        title_span = MiroCommunity.createSpan(video.title, 'mc-title');
                        when_span = MiroCommunity.createSpan(video.when, 'mc-when');
                        if (this.opts.text) {
                            title_span.style.color = when_span.style.color = this.opts.text;
                        }
                        link.appendChild(title_span);
                        link.appendChild(when_span);
                    }
                    if (widget_size === 'large') {
                        fake_description = document.createElement('div');
                        fake_description.innerHTML = video.description;
                        fake_description_divs = fake_description.getElementsByTagName('div');
                        for(j=0; j < fake_description_divs.length; j++) {
                            div = fake_description_divs[j];
                            if (div.className === 'miro-community-description') {
                                desc_span = MiroCommunity.createSpan(div.innerText || div.textContent, 'mc-description');
                                if (this.opts.text) {
                                    desc_span.style.color = this.opts.text;
                                }
                                link.appendChild(desc_span);
                            }
                        }
                    }
                    box.appendChild(link);
                    li.appendChild(box);
                    li.appendChild(separator.cloneNode(false));
                    ul.appendChild(li);
                }
                if (li !== null) {
                    li.className += ' mc-last';
                }
            }
        };
    }();
}<commit_msg>don't put in the play background if there's no thumbnail<commit_after>if (typeof MiroCommunity === 'undefined') {
    MiroCommunity = {
        Widget: function(args) {
            this.init(args);
        },
        jsonP: function(path) {
            script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = path;
            document.getElementsByTagName('head')[0].appendChild(script);
            return script;
        },
        createElement: function(name, attrs) {
            elm = document.createElement(name);
            for (attr in attrs) {
                elm[attr] = attrs[attr];
            }
            return elm;
        },
        createSpan: function(content, className) {
            span = document.createElement('span');
            span.className = className;
            span.innerHTML = content;
            return span;
        }
    };
    MiroCommunity.Widget._counter = 0;
    MiroCommunity.Widget._addedStyles = false;
    MiroCommunity.Widget.prototype = function() {
        return {
            init: function(options) {
                this.opts = options;
                this.counter = ++MiroCommunity.Widget._counter;
                this.id = 'mc-widget-' + this.counter;
                this.scriptTag = null;
            },
            versioned: function(method, args) {
                func = null;
                if (this.opts.version !== undefined) {
                    func = this[method + '_v' + this.opts.version]
                }
                if (!func) {
                    func = this[method];
                }
                return func.apply(this, Array.prototype.slice.call(arguments, 1));
            },
            render: function () {
                this.addStyle();
                if (this.opts.version && this.opts.version !== 1) {
                    widget_class = 'mc-widget-v' + this.opts.version
                } else {
                    widget_class = 'mc-widget'
                }
                document.write('

');
                this.versioned('beforeLoad');
                this.load();
            },
            addStyle: function() {
                head = document.getElementsByTagName('head')[0];
                if (!MiroCommunity.Widget._addedStyles && this.opts.stylesheet !== '') {
                    link = document.createElement('link');
                    link.rel = 'stylesheet';
                    if (this.opts.stylesheet) {
                        link.href = this.opts.stylesheet;
                    } else {
                        link.href = 'http://' + this.opts.domain + '/css/widget.css';
                    }
                    head.appendChild(link);
                    MiroCommunity.Widget._addedStyles = true;
                }
            },
            load: function() {
                var t = this;
                ajax_path = 'http://' + t.opts.domain + '/feeds/json/' + t.opts.source;
                MiroCommunity['callback_' + t.counter] = function(json) {
                    t.scriptTag.parentNode.removeChild(t.scriptTag);
                    t.scriptTag = null;
                    var div = document.getElementById(t.id);
                    t.versioned('update', div, json);
                };
                t.scriptTag = MiroCommunity.jsonP(ajax_path + '?jsoncallback=MiroCommunity.callback_' + t.counter);
            },
            // Widget version 1
            beforeLoad: function () {
                width = this.opts.width ? this.opts.width : 300;
                div = document.getElementById(this.id);
                title = MiroCommunity.createElement('h2')
                title.innerText = this.opts.title ? this.opts.title : 'Watch Videos from Miro Community';
                div.appendChild(title);
                ul = MiroCommunity.createElement('ul', {className: "mc-loading"});
                ul.style.width = width + 'px';
                div.appendChild(ul);
                footer = MiroCommunity.createElement('a', {className: "mc-from",
                                                           href: "http://" + this.opts.domain + '/'})
                footer.innerText = this.opts.domain;
                div.appendChild(footer);
            },
            update: function(div, json) {
                var ul = div.getElementsByTagName('ul')[0];
                ul.innerHTML = ul.className = '';
                var count = this.opts.count ? this.opts.count : 4;
                var li = null;
                for (var i=0; i < json.items.length && i < count; i++) {
                    video = json.items[i];
                    li = MiroCommunity.createElement('li', {className: 'mc-video'});
                    link = MiroCommunity.createElement('a', {href: video.link});
                    thumb = MiroCommunity.createElement('span', {className: 'mc-thumbnail'});
                    var thumbnail = null;
                    if (video.thumbnail) {
                        thumbnail = video.thumbnail;
                    } else {
                        thumbnail = 'http://' + this.opts.domain + '/images/default_vid.gif';
                    }
                    thumb.appendChild(MiroCommunity.createElement('img', {
                        width: 120,
                        height: 90,
                        src: thumbnail}));
                    thumb.appendChild(MiroCommunity.createSpan('', 'mc-play'));
                    link.appendChild(thumb);
                    link.appendChild(MiroCommunity.createSpan(video.title, 'mc-title'));
                    link.appendChild(MiroCommunity.createSpan(video.when, 'mc-when'));
                    li.appendChild(link);
                    ul.appendChild(li);
                }
                if (li !== null) {
                    li.className += ' mc-last';
                }
            },
            // Widget version 2
            beforeLoad_v2: function () {
                widget_wrapper = document.getElementById(this.id);
                if (this.opts.width) {
                    widget_wrapper.style.width = this.opts.width + 'px';
                } else if (this.opts.size === 'small') {
                    widget_wrapper.style.width = '108px';
                } else if (this.opts.size === 'medium') {
                   widget_wrapper.style.width = '160px';
                } else if (this.opts.size == 'large') {
                    widget_wrapper.style.width = '242px';
                }
                if (this.opts.border) {
                    widget_wrapper.style.background = this.opts.border;
                }
                widget_wrapper.className = widget_wrapper.className + ' mc-widget-' + this.opts.size;
                div = document.createElement('div');
                if (this.opts.bg) {
                    div.style.background = this.opts.bg;
                }
                title = MiroCommunity.createElement('div', {className: 'mc-widget-title'});
                if (this.opts.text) {
                    title.style.color = this.opts.text;
                }
                title.innerText = title.textContent = this.opts.title ? this.opts.title : 'Watch Videos from Miro Community';
                div.appendChild(title);
                ul = MiroCommunity.createElement('ul', {className: "mc-loading"});
                div.appendChild(ul);
                footer_box = MiroCommunity.createElement('div', {className: "mc-footer"});
                if (this.opts.logo) {
                    img = MiroCommunity.createElement('img', {src: this.opts.logo})
                    a = MiroCommunity.createElement('a', {href: "http://" + this.opts.domain + '/'});
                    a.appendChild(img);
                    footer_box.appendChild(a);
                }
                more_link = MiroCommunity.createElement('a', {href: "http://" + this.opts.domain + '/'});
                more_link.innerText = more_link.textContent = 'See More';
                more_link_wrapper = document.createElement('div');
                more_link_wrapper.appendChild(more_link);
                footer_box.appendChild(more_link_wrapper);
                div.appendChild(footer_box);
                widget_wrapper.appendChild(div);
            },
            update_v2: function(div, json) {
                links = div.getElementsByTagName('a');
                more_link = links[links.length-1];
                more_link.href = json.link;
                var ul = div.getElementsByTagName('ul')[0];
                ul.innerHTML = ul.className = '';
                var count = this.opts.count ? this.opts.count : 4;
                var li = null;
                var widget_size = this.opts.size;
                flat_bg = MiroCommunity.createElement('img', {src: 'http://' + this.opts.domain + '/images/widget/flat_' + widget_size + '.png',
                                                              className: 'mc-flat-bg'});
                separator = MiroCommunity.createElement('div', {className: 'mc-separator'});
                for (var i=0; i < json.items.length && i < count; i++) {
                    video = json.items[i];
                    li = MiroCommunity.createElement('li', {className: 'mc-video'});
                    if (video.thumbnail) {
                        for (j=0; j < video.thumbnails_resized.length; j++){
                            resized = video.thumbnails_resized[j];
                            width = resized.width; height = resized.height;
                            if ((width === 140 && height === 110 && widget_size == 'medium') ||
                                (width === 88 && height == 68 && widget_size == 'small') ||
                                (width === 222 && height == 169 && widget_size == 'large')) {
                                li.style.backgroundImage = 'url(' + resized.url + ')';
                            }
                        }
                    }
                    box = document.createElement('div');
                    link = MiroCommunity.createElement('a', {href: video.link});
                    if (video.thumbnail) {
                        link.appendChild(flat_bg.cloneNode(false));
                    }
                    if (widget_size !== 'small') {
                        title_span = MiroCommunity.createSpan(video.title, 'mc-title');
                        when_span = MiroCommunity.createSpan(video.when, 'mc-when');
                        if (this.opts.text) {
                            title_span.style.color = when_span.style.color = this.opts.text;
                        }
                        link.appendChild(title_span);
                        link.appendChild(when_span);
                    }
                    if (widget_size === 'large') {
                        fake_description = document.createElement('div');
                        fake_description.innerHTML = video.description;
                        fake_description_divs = fake_description.getElementsByTagName('div');
                        for(j=0; j < fake_description_divs.length; j++) {
                            div = fake_description_divs[j];
                            if (div.className === 'miro-community-description') {
                                desc_span = MiroCommunity.createSpan(div.innerText || div.textContent, 'mc-description');
                                if (this.opts.text) {
                                    desc_span.style.color = this.opts.text;
                                }
                                link.appendChild(desc_span);
                            }
                        }
                    }
                    box.appendChild(link);
                    li.appendChild(box);
                    li.appendChild(separator.cloneNode(false));
                    ul.appendChild(li);
                }
                if (li !== null) {
                    li.className += ' mc-last';
                }
            }
        };
    }();
}<|endoftext|>


<commit_before>function genUni() {
	var code = prompt("Generate Unicode Character:");
	$('#code').val($('#code').val() + String.fromCharCode(parseInt(code)));
	updateByteCount();
};

function getByteCount(s) {
    var count = 0, stringLength = s.length;
    s = String(s || "");
    for (var i = 0; i < stringLength; i++) {
        var partCount = encodeURI(s[i]).split("%").length;
        count += partCount == 1 ? 1 : partCount - 1;
    }
    return count;
}

function t(s){for(var i=0;i<s.length;i++){console.log(s.charCodeAt(i));}}

function updateByteCount() {
	var c = $('#code').val();
	var byteCount = getByteCount(c);
	var charCount = c.length;
	var s = byteCount + " bytes and " + charCount + " chars long.";
	$('#byteCount').html(s);
}

function getStrippedCode() {
	var stripped = $('#code').val();
	$('#stripped').html(
			'Stripped code: ' + stripped + ' Byte count: '
					+ getByteCount(stripped));
}

var string = false;
var codeBlock = false;

function getExplanation() {
	$('#explanation').html('');
	var code = $('#code').val();
    var explain = '';
    var indent = '   ';
	for (var x = 0, c = ''; c = code.charAt(x); x++) {
        if(c === '"') {
            string = !string;
        } else if(c === '`') {
            codeBlock = !codeBlock;
        }
        if(string) {
            explain = '';
        } else {
            explain = explanations[c.charCodeAt()]
        }
        if(codeBlock) {
            indent = '    ';
        } else {
            indent = '';
        }
		var original = $('#explanation').html();
		$('#explanation').html(
				original
						+ " "
                        + indent
                        + explain
								+ "\r\n");
	}

}

function updateUtils() {
	updateByteCount();
	getStrippedCode();
	getExplanation();
}

updateUtils();

$(document).ready(
		function() {
			$("#permalink").click(
					function() {
						var code = $.param({
							code : $('#code').val(),
							input : $('#input').val()
						});
						prompt("Permalink:", "http://"
								+ window.location.hostname + "/link/" + code);
						window.location.pathname = "/link/" + code;
					});
			$('#code').on('input propertychange paste', function() {
				updateUtils();
			});
		});<commit_msg>fix explanations?<commit_after>function genUni() {
	var code = prompt("Generate Unicode Character:");
	$('#code').val($('#code').val() + String.fromCharCode(parseInt(code)));
	updateByteCount();
};

function getByteCount(s) {
    var count = 0, stringLength = s.length;
    s = String(s || "");
    for (var i = 0; i < stringLength; i++) {
        var partCount = encodeURI(s[i]).split("%").length;
        count += partCount == 1 ? 1 : partCount - 1;
    }
    return count;
}

function t(s){for(var i=0;i<s.length;i++){console.log(s.charCodeAt(i));}}

function updateByteCount() {
	var c = $('#code').val();
	var byteCount = getByteCount(c);
	var charCount = c.length;
	var s = byteCount + " bytes and " + charCount + " chars long.";
	$('#byteCount').html(s);
}

function getStrippedCode() {
	var stripped = $('#code').val();
	$('#stripped').html(
			'Stripped code: ' + stripped + ' Byte count: '
					+ getByteCount(stripped));
}

var string = false;
var codeBlock = false;

function getExplanation() {
	$('#explanation').html('');
	var code = $('#code').val();
    var explain = '';
    var indent = '   ';
	for (var x = 0, c = ''; c = code.charAt(x); x++) {
        string = false;
        if(c === '"') {
            x++;
            var start = x;
            while(code.charAt(x) !== '"') {
                x++;
            }
            explain = 'push string literal "'+code.slice(start,x)+'"';
            string = true;
        } else if(c === '`') {
            codeBlock = !codeBlock;
        }
        if(!string) {
            explain = explanations[c.charCodeAt(x)];
        }
        if(codeBlock) {
            indent = '    ';
        } else {
            indent = '';
        }
		var original = $('#explanation').html();
		$('#explanation').html(
				original
						+ " "
                        + indent
                        + explain
								+ "\r\n");
	}

}

function updateUtils() {
	updateByteCount();
	getStrippedCode();
	getExplanation();
}

updateUtils();

$(document).ready(
		function() {
			$("#permalink").click(
					function() {
						var code = $.param({
							code : $('#code').val(),
							input : $('#input').val()
						});
						prompt("Permalink:", "http://"
								+ window.location.hostname + "/link/" + code);
						window.location.pathname = "/link/" + code;
					});
			$('#code').on('input propertychange paste', function() {
				updateUtils();
			});
		});<|endoftext|>


<commit_before>(function () {
  'use strict'
  var queue = []
  var active = undefined
  var server
  var init = () => new Promise((resolve, reject) => {
    server = window.io()
    resolve()
  })

  var displayMessage = (data) => {
    if (data.data.message) {
        parseMessage(data.data.message.toString(), data.data.delay * 1000)
    } else if (data.data.changeSource) {
      console.log("change source", data.data)
      // active = data.data.// IDEA:
    } else {
      console.log("added quueue", data.data)
      // queue.push(data.data.identifier)
    }

    /*
    console.log(data.data.message)
    document.getElementById('demoMessage').innerHTML = data.data.message
    setTimeout(clearScreen, parseInt(data.data.duration) * 1000)
    */
  }

  var clearScreen = () => {
    document.getElementById('demoMessage').innerHTML = ''
  }

  var addListeners = () => {
    server.on('global', displayMessage)
  }

  init()
    .then(addListeners)
    .then(() => server.emit('register', 'display'))
    .catch(err => console.log(err))
}())

function parseMessage (messageData, messageParameter) {
  // Display message for debugging
  console.log(messageData + ' ' + messageParameter)
  document.getElementById('demoMessage').innerHTML = messageData + ' ' + messageParameter

  var messageArr = messageData.split(',')

  if (messageArr[0] === 'checkMiningBlock') {
    // Hilight a mining target block that is being checked
    // eg: "checkMiningBlock,1"
    var blockNum = parseInt(messageParameter)
    console.log('blockNum: ' + blockNum)
    selectMiningBlock(messageArr[1])
  } else if (messageArr[0] === 'miningTargets') {
    // Set the mining target blocks displayed on the screen
    // eg: "miningTargets,800900000"
    for (var i = 1; i <= 9; i++) {
      console.log('miningTargets setting: ' + i)
      var miningtargetblocktypeid = messageArr[1].charAt(i - 1)
      if (miningtargetblocktypeid === '0') {
        $('#mining' + i).html('')
      } else {
        $('#mining' + i).html('')
      }
    }
  } else if (messageArr[0] === 'mineBlock') {
    // mineBlock,2
    // TODO: display the mining of the block on screen

  } else if (messageArr[0] === 'recipeComplete') {
    // recipeComplete,32
    $('#success3').html($('#success2').html())
    $('#success2').html($('#success1').html())

    $('#success1').removeClass('animated zoomInUp')

    setTimeout(function () {
      $('#success1').html('')
      $('#success1').addClass('animated zoomInUp')
    }, 100)
  } else if (messageArr[0] === 'queue') {
    console.log('message: ' + messageArr[1].charAt(0))
    $('#queue1').html('
Now:
')
    $('#queue2').html('
Next:
')
    $('#queue3').html('
Next:
')
  }
}

function selectMiningBlock (blockNum) {
  for (var i = 1; i <= 9; i++) {
    if (i === blockNum) {
      $('#mining' + i).addClass('selectedbox')
    } else {
      $('#mining' + i).removeClass('selectedbox')
    }
  }
}
<commit_msg>fix the queue system active = currently being used queue = the rest, in order<commit_after>(function () {
  'use strict'
  var queue = []
  var active = undefined
  var server
  var init = () => new Promise((resolve, reject) => {
    server = window.io()
    resolve()
  })

  var displayMessage = (data) => {
    console.log("GOT DATA", data)
    if (data.evt === 'message') {
        parseMessage(data.data.message.toString(), data.data.delay * 1000)
    } else if (data.evt === 'changeSource') {
      console.log("change source", data.data.identifier)
      // active = data.data.// IDEA:
      active = queue.shift()
    } else if (data.evt === 'addedToQueue'){

      queue.push(data.data)
    }

    console.log(queue)

    /*
    console.log(data.data.message)
    document.getElementById('demoMessage').innerHTML = data.data.message
    setTimeout(clearScreen, parseInt(data.data.duration) * 1000)
    */
  }

  var clearScreen = () => {
    document.getElementById('demoMessage').innerHTML = ''
  }

  var addListeners = () => {
    server.on('global', displayMessage)
  }

  init()
    .then(addListeners)
    .then(() => server.emit('register', 'display'))
    .catch(err => console.log(err))
}())

function parseMessage (messageData, messageParameter) {
  // Display message for debugging
  console.log(messageData + ' ' + messageParameter)
  document.getElementById('demoMessage').innerHTML = messageData + ' ' + messageParameter

  var messageArr = messageData.split(',')

  if (messageArr[0] === 'checkMiningBlock') {
    // Hilight a mining target block that is being checked
    // eg: "checkMiningBlock,1"
    var blockNum = parseInt(messageParameter)
    console.log('blockNum: ' + blockNum)
    selectMiningBlock(messageArr[1])
  } else if (messageArr[0] === 'miningTargets') {
    // Set the mining target blocks displayed on the screen
    // eg: "miningTargets,800900000"
    for (var i = 1; i <= 9; i++) {
      console.log('miningTargets setting: ' + i)
      var miningtargetblocktypeid = messageArr[1].charAt(i - 1)
      if (miningtargetblocktypeid === '0') {
        $('#mining' + i).html('')
      } else {
        $('#mining' + i).html('')
      }
    }
  } else if (messageArr[0] === 'mineBlock') {
    // mineBlock,2
    // TODO: display the mining of the block on screen

  } else if (messageArr[0] === 'recipeComplete') {
    // recipeComplete,32
    $('#success3').html($('#success2').html())
    $('#success2').html($('#success1').html())

    $('#success1').removeClass('animated zoomInUp')

    setTimeout(function () {
      $('#success1').html('')
      $('#success1').addClass('animated zoomInUp')
    }, 100)
  } else if (messageArr[0] === 'queue') {
    console.log('message: ' + messageArr[1].charAt(0))
    $('#queue1').html('
Now:
')
    $('#queue2').html('
Next:
')
    $('#queue3').html('
Next:
')
  }
}

function selectMiningBlock (blockNum) {
  for (var i = 1; i <= 9; i++) {
    if (i === blockNum) {
      $('#mining' + i).addClass('selectedbox')
    } else {
      $('#mining' + i).removeClass('selectedbox')
    }
  }
}
<|endoftext|>