<commit_before>/**
 * Basic concrete5 toolbar class
 */

var ConcreteToolbar = function() {

	var $toolbar = $('#ccm-toolbar');
	var $searchInput = $('#ccm-nav-intelligent-search');
	var $searchResults = $('#ccm-intelligent-search-results');
	var remotesearchquery, ajaxtimer;

    if ($searchInput.length) {
        $searchResults.css('right', $(window).width() - $searchInput.offset().left - $searchResults.width() - 1);
    }

	setupHelpNotifications = function() {
        $('.ccm-notification .dialog-launch').dialog();
		$(document.body).on('click', 'a[data-dismiss]', function() {
			var action = ($(this).attr('data-dismiss') == 'help-all') ? 'all' : 'this';
			$(this).parentsUntil('.ccm-notification-help').parent().queue(function() {
				$(this).addClass('animated fadeOut');
				$(this).dequeue();
			}).delay(500).queue(function() {
				$(this).remove();
				$(this).dequeue();
			});

			$.ajax({
				type: 'post',
				data: {
					'type': $(this).attr('data-help-notification-type'),
					'identifier': $(this).attr('data-help-notification-identifier'),
					'action': action,
					'ccm_token': CCM_SECURITY_TOKEN
				},
				url: CCM_TOOLS_PATH + '/help/dismiss',
				success: function(r) {}
			});
			return false;
		});
	}

	setupPageAlerts = function() {
		$(document.body).on('click', 'a[data-dismiss-alert=page-alert]', function(e) {
			e.stopPropagation();
			$('.ccm-notification').queue(function() {
				$(this).addClass('animated fadeOut');
				$(this).dequeue();
			}).delay(500).queue(function() {
				$(this).remove();
				$(this).dequeue();
			});
			return false;
		});

		$('#ccm-notification-page-alert form').ajaxForm({
			dataType: 'json',
			beforeSubmit: function() {
				jQuery.fn.dialog.showLoader();
			},
			success: function(r) {
				if (r.redirect) {
					window.location.href = r.redirect;
				}
			}
		});

	}

	setupTooltips = function() {
		if ($("#ccm-tooltip-holder").length == 0) {
			$('
').attr('id','ccm-tooltip-holder').attr('class', 'ccm-ui').prependTo(document.body);
		}
		$('.launch-tooltip').tooltip({'container': '#ccm-tooltip-holder'});
	}

	setupPanels = function() {
		$('
', {'id': 'ccm-panel-overlay'}).appendTo($(document.body));
        $('[data-launch-panel]').each(function() {
            $(this).prepend('

')
        });

		$('[data-launch-panel]').unbind().on('click', function() {
			var panelID = $(this).attr('data-launch-panel');
			$(this).toggleClass('ccm-launch-panel-loading');
			var panel = ConcretePanelManager.getByIdentifier(panelID);
			panel.toggle();
			return false;
		});
		$('html').addClass('ccm-panel-ready');

		ConcreteEvent.subscribe('PanelOpen',function(e, data) {
			var panel = data.panel;
			if (panel.options.identifier == 'page') {
				$('#' + panel.getDOMID()).find('[data-launch-panel-detail=\'page-composer\']').click();
			}
			$('a[data-toolbar-action=check-in]').on('click.close-check-in', function() {
				ConcretePanelManager.exitPanelMode();
				return false;
			});
		});

		ConcreteEvent.subscribe('PanelClose',function(e) {
			$('a[data-toolbar-action=check-in]').unbind('click.close-check-in');
		});

	};

	setupIntelligentSearch = function() {
		$searchInput.bind('keydown.ccm-intelligent-search', function(e) {
			if (e.keyCode == 13 || e.keyCode == 40 || e.keyCode == 38) {
				e.preventDefault();
				e.stopPropagation();

				if (e.keyCode == 13 && $("a.ccm-intelligent-search-result-selected").length > 0) {
					var href = $("a.ccm-intelligent-search-result-selected").attr('href');
					if (!href || href == '#' || href == 'javascript:void(0)') {
						$("a.ccm-intelligent-search-result-selected").click();
					} else {
						window.location.href = href;
					}
				}
				var visibleitems = $("#ccm-intelligent-search-results li:visible");
				var sel;

				if (e.keyCode == 40 || e.keyCode == 38) {
					$.each(visibleitems, function(i, item) {
						if ($(item).children('a').hasClass('ccm-intelligent-search-result-selected')) {
							if (e.keyCode == 38) {
								io = visibleitems[i-1];
							} else {
								io = visibleitems[i+1];
							}
							sel = $(io).find('a');
						}
					});
					if (sel && sel.length > 0) {
						$("a.ccm-intelligent-search-result-selected").removeClass();
						$(sel).addClass('ccm-intelligent-search-result-selected');
					}
				}
			}
		});

		$searchInput.liveUpdate('ccm-intelligent-search-results', 'intelligent-search');
		$searchInput.bind('keyup.ccm-intelligent-search', function(e) {
			doRemoteSearchCall($(this).val());
		});
		$searchInput.bind('click', function(e) { if ( this.value=="") {
			$searchResults.hide();
		}});

	}

   setupMobileNav = function(){
        $('.ccm-toolbar-mobile-menu-button').click(function(){
            $(this).toggleClass('ccm-mobile-close');   // slide out mobile nav
            $('.ccm-mobile-menu-overlay').slideToggle();
        });
        $('.ccm-mobile-menu-overlay .parent-ul a').click(function(event) {
            if(!($(this).parent('li').hasClass('last-li'))) {
                $(this).parent('li').siblings().children('ul').hide();
                if(!($(this).parent('li').children('ul').is(':visible'))) {
                    $(this).next('ul').show();
                    event.preventDefault();
                }
            }
        });
    }

	activateIntelligentSearchResults = function() {
		if ($("#ccm-intelligent-search-results div:visible").length == 0) {
			$("#ccm-intelligent-search-results").hide();
		}
		$("#ccm-intelligent-search-results a").hover(function() {
			$('a.ccm-intelligent-search-result-selected').removeClass();
			$(this).addClass('ccm-intelligent-search-result-selected');
		}, function() {
			$(this).removeClass('ccm-intelligent-search-result-selected');
		});
	}

	doRemoteSearchCall = function(query) {
		query = jQuery.trim(query);
		if (!query) {
			return;
		}
		if (query.length > 2) {
			if (query == remotesearchquery) {
				return;
			}

			if (ajaxtimer) {
				window.clearTimeout(ajaxtimer);
			}
			remotesearchquery = query;
			ajaxtimer = window.setTimeout(function() {
				ajaxtimer = null;
				$("#ccm-intelligent-search-results-list-marketplace").parent().show();
				$("#ccm-intelligent-search-results-list-help").parent().show();
				$("#ccm-intelligent-search-results-list-your-site").parent().show();
				$("#ccm-intelligent-search-results-list-marketplace").parent().removeClass('ccm-intelligent-search-results-module-loaded');
				$("#ccm-intelligent-search-results-list-help").parent().removeClass('ccm-intelligent-search-results-module-loaded');
				$("#ccm-intelligent-search-results-list-your-site").parent().removeClass('ccm-intelligent-search-results-module-loaded');

				$.getJSON(CCM_DISPATCHER_FILENAME + '/ccm/system/marketplace/search', {
					'q': remotesearchquery
				},
				function(r) {
					$("#ccm-intelligent-search-results-list-marketplace").parent().addClass('ccm-intelligent-search-results-module-loaded');
					$("#ccm-intelligent-search-results-list-marketplace").html('');
					for (i = 0; i < r.length; i++) {
						var rr= r[i];
						var _onclick = "ConcreteMarketplace.getMoreInformation(" + rr.mpID + ")";
						$("#ccm-intelligent-search-results-list-marketplace").append('
' + rr.name + '
');
					}
					if (r.length == 0) {
						$("#ccm-intelligent-search-results-list-marketplace").parent().hide();
					}
					if ($('.ccm-intelligent-search-result-selected').length == 0) {
						$("#ccm-intelligent-search-results").find('li a').removeClass('ccm-intelligent-search-result-selected');
						$("#ccm-intelligent-search-results li:visible a:first").addClass('ccm-intelligent-search-result-selected');
					}
					activateIntelligentSearchResults();
				}).error(function() {
					$("#ccm-intelligent-search-results-list-marketplace").parent().hide();
				});

				$.getJSON(CCM_TOOLS_PATH + '/get_remote_help', {
					'q': remotesearchquery
				},
				function(r) {

					$("#ccm-intelligent-search-results-list-help").parent().addClass('ccm-intelligent-search-results-module-loaded');
					$("#ccm-intelligent-search-results-list-help").html('');
					for (i = 0; i < r.length; i++) {
						var rr= r[i];
						$("#ccm-intelligent-search-results-list-help").append('
' + rr.name + '
');
					}
					if (r.length == 0) {
						$("#ccm-intelligent-search-results-list-help").parent().hide();
					}
					if ($('.ccm-intelligent-search-result-selected').length == 0) {
						$("#ccm-intelligent-search-results").find('li a').removeClass('ccm-intelligent-search-result-selected');
						$("#ccm-intelligent-search-results li:visible a:first").addClass('ccm-intelligent-search-result-selected');
					}
					activateIntelligentSearchResults();

				}).error(function() {
					$("#ccm-intelligent-search-results-list-help").parent().hide();
				});

				$.getJSON(CCM_TOOLS_PATH + '/pages/intelligent_search', {
					'q': remotesearchquery
				},
				function(r) {

					$("#ccm-intelligent-search-results-list-your-site").parent().addClass('ccm-intelligent-search-results-module-loaded');
					$("#ccm-intelligent-search-results-list-your-site").html('');
					for (i = 0; i < r.length; i++) {
						var rr= r[i];
						$("#ccm-intelligent-search-results-list-your-site").append('
' + rr.name + '
');
					}
					if (r.length == 0) {
						$("#ccm-intelligent-search-results-list-your-site").parent().hide();
					}
					if ($('.ccm-intelligent-search-result-selected').length == 0) {
						$("#ccm-intelligent-search-results").find('li a').removeClass('ccm-intelligent-search-result-selected');
						$("#ccm-intelligent-search-results li:visible a:first").addClass('ccm-intelligent-search-result-selected');
					}
					activateIntelligentSearchResults();

				}).error(function() {
					$("#ccm-intelligent-search-results-list-your-site").parent().hide();
				});
			}, 500);
		}
	}

	return {
		start: function() {
			if ($toolbar.length > 0) {

				$toolbar.find('.dialog-launch').dialog();

				setupIntelligentSearch();
				setupPanels();
				setupTooltips();
				setupPageAlerts();
				setupHelpNotifications();
                setupMobileNav();

			}
		},

		disable: function() {
			$('#ccm-toolbar-disabled').remove();
			$('
', {'id': 'ccm-toolbar-disabled'}).appendTo(document.body);
			setTimeout(function() {
				$('#ccm-toolbar-disabled').css('opacity', 1);
			}, 10);
		},

		enable: function() {
			$('#ccm-toolbar-disabled').remove();
		},

		disableDirectExit: function() {
			var $link = $('li.ccm-toolbar-page-edit a');
			if ($link.attr('data-launch-panel') != 'check-in') {
				$link.attr('data-launch-panel', 'check-in').on('click', function() {
					$(this).toggleClass('ccm-launch-panel-active');
					var panel = ConcretePanelManager.getByIdentifier('check-in');
					panel.toggle();
					return false;
				});
			}
		}

	}
}();
<commit_msg>added visual feedback on the add button<commit_after>/**
 * Basic concrete5 toolbar class
 */

var ConcreteToolbar = function() {

	var $toolbar = $('#ccm-toolbar');
	var $searchInput = $('#ccm-nav-intelligent-search');
	var $searchResults = $('#ccm-intelligent-search-results');
	var remotesearchquery, ajaxtimer;

    if ($searchInput.length) {
        $searchResults.css('right', $(window).width() - $searchInput.offset().left - $searchResults.width() - 1);
    }

	setupHelpNotifications = function() {
        $('.ccm-notification .dialog-launch').dialog();
		$(document.body).on('click', 'a[data-dismiss]', function() {
			var action = ($(this).attr('data-dismiss') == 'help-all') ? 'all' : 'this';
			$(this).parentsUntil('.ccm-notification-help').parent().queue(function() {
				$(this).addClass('animated fadeOut');
				$(this).dequeue();
			}).delay(500).queue(function() {
				$(this).remove();
				$(this).dequeue();
			});

			$.ajax({
				type: 'post',
				data: {
					'type': $(this).attr('data-help-notification-type'),
					'identifier': $(this).attr('data-help-notification-identifier'),
					'action': action,
					'ccm_token': CCM_SECURITY_TOKEN
				},
				url: CCM_TOOLS_PATH + '/help/dismiss',
				success: function(r) {}
			});
			return false;
		});
	}

	setupPageAlerts = function() {
		$(document.body).on('click', 'a[data-dismiss-alert=page-alert]', function(e) {
			e.stopPropagation();
			$('.ccm-notification').queue(function() {
				$(this).addClass('animated fadeOut');
				$(this).dequeue();
			}).delay(500).queue(function() {
				$(this).remove();
				$(this).dequeue();
			});
			return false;
		});

		$('#ccm-notification-page-alert form').ajaxForm({
			dataType: 'json',
			beforeSubmit: function() {
				jQuery.fn.dialog.showLoader();
			},
			success: function(r) {
				if (r.redirect) {
					window.location.href = r.redirect;
				}
			}
		});

	}

	setupTooltips = function() {
		if ($("#ccm-tooltip-holder").length == 0) {
			$('
').attr('id','ccm-tooltip-holder').attr('class', 'ccm-ui').prependTo(document.body);
		}
		$('.launch-tooltip').tooltip({'container': '#ccm-tooltip-holder'});
	}

	setupPanels = function() {
		$('
', {'id': 'ccm-panel-overlay'}).appendTo($(document.body));
        $('[data-launch-panel]').each(function() {
            $(this).prepend('

')
        });

		$('[data-launch-panel]').unbind().on('click', function() {
            var $this = $(this);
			var panelID = $this.attr('data-launch-panel');
			var panel = ConcretePanelManager.getByIdentifier(panelID);
            if ( !panel.willBePinned() ) $this.toggleClass('ccm-launch-panel-loading');

            if ( panel.isPinable() )
            {
                var parent = $($this.parent());
                if ( panel.willBePinned() || panel.pinned() ) parent.toggleClass("ccm-toolbar-page-edit-mode-active");
            }
			panel.toggle();
			return false;
		});
		$('html').addClass('ccm-panel-ready');

		ConcreteEvent.subscribe('PanelOpen',function(e, data) {
			var panel = data.panel;
			if (panel.options.identifier == 'page') {
				$('#' + panel.getDOMID()).find('[data-launch-panel-detail=\'page-composer\']').click();
			}
			$('a[data-toolbar-action=check-in]').on('click.close-check-in', function() {
				ConcretePanelManager.exitPanelMode();
				return false;
			});
		});

		ConcreteEvent.subscribe('PanelClose',function(e) {
			$('a[data-toolbar-action=check-in]').unbind('click.close-check-in');
		});

	};

	setupIntelligentSearch = function() {
		$searchInput.bind('keydown.ccm-intelligent-search', function(e) {
			if (e.keyCode == 13 || e.keyCode == 40 || e.keyCode == 38) {
				e.preventDefault();
				e.stopPropagation();

				if (e.keyCode == 13 && $("a.ccm-intelligent-search-result-selected").length > 0) {
					var href = $("a.ccm-intelligent-search-result-selected").attr('href');
					if (!href || href == '#' || href == 'javascript:void(0)') {
						$("a.ccm-intelligent-search-result-selected").click();
					} else {
						window.location.href = href;
					}
				}
				var visibleitems = $("#ccm-intelligent-search-results li:visible");
				var sel;

				if (e.keyCode == 40 || e.keyCode == 38) {
					$.each(visibleitems, function(i, item) {
						if ($(item).children('a').hasClass('ccm-intelligent-search-result-selected')) {
							if (e.keyCode == 38) {
								io = visibleitems[i-1];
							} else {
								io = visibleitems[i+1];
							}
							sel = $(io).find('a');
						}
					});
					if (sel && sel.length > 0) {
						$("a.ccm-intelligent-search-result-selected").removeClass();
						$(sel).addClass('ccm-intelligent-search-result-selected');
					}
				}
			}
		});

		$searchInput.liveUpdate('ccm-intelligent-search-results', 'intelligent-search');
		$searchInput.bind('keyup.ccm-intelligent-search', function(e) {
			doRemoteSearchCall($(this).val());
		});
		$searchInput.bind('click', function(e) { if ( this.value=="") {
			$searchResults.hide();
		}});

	}

   setupMobileNav = function(){
        $('.ccm-toolbar-mobile-menu-button').click(function(){
            $(this).toggleClass('ccm-mobile-close');   // slide out mobile nav
            $('.ccm-mobile-menu-overlay').slideToggle();
        });
        $('.ccm-mobile-menu-overlay .parent-ul a').click(function(event) {
            if(!($(this).parent('li').hasClass('last-li'))) {
                $(this).parent('li').siblings().children('ul').hide();
                if(!($(this).parent('li').children('ul').is(':visible'))) {
                    $(this).next('ul').show();
                    event.preventDefault();
                }
            }
        });
    }

	activateIntelligentSearchResults = function() {
		if ($("#ccm-intelligent-search-results div:visible").length == 0) {
			$("#ccm-intelligent-search-results").hide();
		}
		$("#ccm-intelligent-search-results a").hover(function() {
			$('a.ccm-intelligent-search-result-selected').removeClass();
			$(this).addClass('ccm-intelligent-search-result-selected');
		}, function() {
			$(this).removeClass('ccm-intelligent-search-result-selected');
		});
	}

	doRemoteSearchCall = function(query) {
		query = jQuery.trim(query);
		if (!query) {
			return;
		}
		if (query.length > 2) {
			if (query == remotesearchquery) {
				return;
			}

			if (ajaxtimer) {
				window.clearTimeout(ajaxtimer);
			}
			remotesearchquery = query;
			ajaxtimer = window.setTimeout(function() {
				ajaxtimer = null;
				$("#ccm-intelligent-search-results-list-marketplace").parent().show();
				$("#ccm-intelligent-search-results-list-help").parent().show();
				$("#ccm-intelligent-search-results-list-your-site").parent().show();
				$("#ccm-intelligent-search-results-list-marketplace").parent().removeClass('ccm-intelligent-search-results-module-loaded');
				$("#ccm-intelligent-search-results-list-help").parent().removeClass('ccm-intelligent-search-results-module-loaded');
				$("#ccm-intelligent-search-results-list-your-site").parent().removeClass('ccm-intelligent-search-results-module-loaded');

				$.getJSON(CCM_DISPATCHER_FILENAME + '/ccm/system/marketplace/search', {
					'q': remotesearchquery
				},
				function(r) {
					$("#ccm-intelligent-search-results-list-marketplace").parent().addClass('ccm-intelligent-search-results-module-loaded');
					$("#ccm-intelligent-search-results-list-marketplace").html('');
					for (i = 0; i < r.length; i++) {
						var rr= r[i];
						var _onclick = "ConcreteMarketplace.getMoreInformation(" + rr.mpID + ")";
						$("#ccm-intelligent-search-results-list-marketplace").append('
' + rr.name + '
');
					}
					if (r.length == 0) {
						$("#ccm-intelligent-search-results-list-marketplace").parent().hide();
					}
					if ($('.ccm-intelligent-search-result-selected').length == 0) {
						$("#ccm-intelligent-search-results").find('li a').removeClass('ccm-intelligent-search-result-selected');
						$("#ccm-intelligent-search-results li:visible a:first").addClass('ccm-intelligent-search-result-selected');
					}
					activateIntelligentSearchResults();
				}).error(function() {
					$("#ccm-intelligent-search-results-list-marketplace").parent().hide();
				});

				$.getJSON(CCM_TOOLS_PATH + '/get_remote_help', {
					'q': remotesearchquery
				},
				function(r) {

					$("#ccm-intelligent-search-results-list-help").parent().addClass('ccm-intelligent-search-results-module-loaded');
					$("#ccm-intelligent-search-results-list-help").html('');
					for (i = 0; i < r.length; i++) {
						var rr= r[i];
						$("#ccm-intelligent-search-results-list-help").append('
' + rr.name + '
');
					}
					if (r.length == 0) {
						$("#ccm-intelligent-search-results-list-help").parent().hide();
					}
					if ($('.ccm-intelligent-search-result-selected').length == 0) {
						$("#ccm-intelligent-search-results").find('li a').removeClass('ccm-intelligent-search-result-selected');
						$("#ccm-intelligent-search-results li:visible a:first").addClass('ccm-intelligent-search-result-selected');
					}
					activateIntelligentSearchResults();

				}).error(function() {
					$("#ccm-intelligent-search-results-list-help").parent().hide();
				});

				$.getJSON(CCM_TOOLS_PATH + '/pages/intelligent_search', {
					'q': remotesearchquery
				},
				function(r) {

					$("#ccm-intelligent-search-results-list-your-site").parent().addClass('ccm-intelligent-search-results-module-loaded');
					$("#ccm-intelligent-search-results-list-your-site").html('');
					for (i = 0; i < r.length; i++) {
						var rr= r[i];
						$("#ccm-intelligent-search-results-list-your-site").append('
' + rr.name + '
');
					}
					if (r.length == 0) {
						$("#ccm-intelligent-search-results-list-your-site").parent().hide();
					}
					if ($('.ccm-intelligent-search-result-selected').length == 0) {
						$("#ccm-intelligent-search-results").find('li a').removeClass('ccm-intelligent-search-result-selected');
						$("#ccm-intelligent-search-results li:visible a:first").addClass('ccm-intelligent-search-result-selected');
					}
					activateIntelligentSearchResults();

				}).error(function() {
					$("#ccm-intelligent-search-results-list-your-site").parent().hide();
				});
			}, 500);
		}
	}

	return {
		start: function() {
			if ($toolbar.length > 0) {

				$toolbar.find('.dialog-launch').dialog();

				setupIntelligentSearch();
				setupPanels();
				setupTooltips();
				setupPageAlerts();
				setupHelpNotifications();
                setupMobileNav();

			}
		},

		disable: function() {
			$('#ccm-toolbar-disabled').remove();
			$('
', {'id': 'ccm-toolbar-disabled'}).appendTo(document.body);
			setTimeout(function() {
				$('#ccm-toolbar-disabled').css('opacity', 1);
			}, 10);
		},

		enable: function() {
			$('#ccm-toolbar-disabled').remove();
		},

		disableDirectExit: function() {
			var $link = $('li.ccm-toolbar-page-edit a');
			if ($link.attr('data-launch-panel') != 'check-in') {
				$link.attr('data-launch-panel', 'check-in').on('click', function() {
					$(this).toggleClass('ccm-launch-panel-active');
					var panel = ConcretePanelManager.getByIdentifier('check-in');
					panel.toggle();
					return false;
				});
			}
		}

	}
}();
<|endoftext|>


<commit_before>
/** Stores data in the OpenSocial gadget */
function addInput(){
	// Getting the state
	var state = wave.getState();
	// Push textbox value into the array and set the textbox to blank
	var url = document.getElementById('textBox').value;
	document.getElementById('textBox').value = '';

	// Submit url to storage
	state.submitDelta({'snapshot':url});
}

// Renders the gadget
function renderInfo() {
    /** Get state */
    if (!wave.getState()) {
        return;
    }
    var state = wave.getState();
    var url = state.get('snapshot');

    if(url){
    	var frame_snap='';
	document.getElementById('body').innerHTML = frame_snap;
	document.getElementById('link').innerHTML ='Snapshot URL:'+url +'';
	var html = '<input type="text" id="textBox" value=""/><button id="addInput" onclick="addInput()">update Snapshot URL</button>';
    	document.getElementById('footer').innerHTML = html;
    }
    else{
    	var html = '<input type="text" id="textBox" value=""/><button id="addInput" onclick="addInput()">Add Snapshot URL</button>';
    	document.getElementById('footer').innerHTML = html;
    }
    /** Adjust window size dynamically */
    gadgets.window.adjustHeight();
}

// Initializes gadget, sets callbacks
function init() {
    if (wave && wave.isInWaveContainer()) {
    	// Loads the gadget's initial state and the subsequent changes to it
        wave.setStateCallback(renderInfo);

        // Loads participants and any changes to them
        wave.setParticipantCallback(renderInfo);
    }
}

// Initializes gadget after receiving a notification that the page is loaded and the DOM is ready.
gadgets.util.registerOnLoadHandler(init);
<commit_msg>Update adding_topics_2.js<commit_after>
/** Stores data in the OpenSocial gadget */
function addInput(){
	// Getting the state
	var state = wave.getState();
	// Push textbox value into the array and set the textbox to blank
	var url = document.getElementById('textBox').value;
	document.getElementById('textBox').value = '';

	// Submit url to storage
	state.submitDelta({'snapshot':url});
}

// Renders the gadget
function renderInfo() {
    /** Get state */
    if (!wave.getState()) {
        return;
    }
    var state = wave.getState();
    var url = state.get('snapshot');
    if(url){
    	var frame_snap='';
	document.getElementById('body').innerHTML = frame_snap;
	document.getElementById('link').innerHTML ='Snapshot URL:'+url +'';
	var html = '<input type="text" id="textBox" value=""/><button id="addInput" onclick="addInput()">update Snapshot URL</button>';
    	document.getElementById('footer').innerHTML = html;
    }
    else{
    	var html = '<input type="text" id="textBox" value=""/><button id="addInput" onclick="addInput()">Add Snapshot URL</button>';
    	document.getElementById('footer').innerHTML = html;
    }
    /** Adjust window size dynamically */
    gadgets.window.adjustHeight();
}

// Initializes gadget, sets callbacks
function init() {
    if (wave && wave.isInWaveContainer()) {
    	// Loads the gadget's initial state and the subsequent changes to it
        wave.setStateCallback(renderInfo);

        // Loads participants and any changes to them
        wave.setParticipantCallback(renderInfo);
    }
}

// Initializes gadget after receiving a notification that the page is loaded and the DOM is ready.
gadgets.util.registerOnLoadHandler(init);
<|endoftext|>


<commit_before>var PromiseSolver = require('./PromiseSolver.js');
var P = require('bluebird');

/**
 * Object promise resolver
 *
 * @extends PromiseSolver
 * @constructor
 */
function ObjectPromiseSolver() {}
ObjectPromiseSolver.prototype = Object.create(PromiseSolver.prototype);
ObjectPromiseSolver.prototype.constructor = ObjectPromiseSolver;

/**
 * Takes an array of objects and resolve or reject them all.
 *
 * @param {array} promises
 * @returns {Array}
 */
ObjectPromiseSolver.prototype.all = function(promises) {
  return P.all(
    promises.map(
      function(promise) {
        var error, success;
        error = function (res) {
          promise.err = true;
          promise.res = res;
          return  promise;
        };
        success = function (res) {
          promise.err = false;
          promise.res = res;
          return  promise;
        };

        if (!promise.p || !promise.p.then) return error(new Error('The object missing p property that holds the promise.'));
        return promise.p.then(success,error)
      }
    )
  );
};

/**
 * Overrides parent and simply return the Array
 *
 * @param {Array} res
 * @returns {Array}
 */
ObjectPromiseSolver.prototype.clearResponse = function(res) { return res;};

module.exports = (function(){ return ObjectPromiseSolver; })();
<commit_msg>Update ObjectPromiseSolver.js<commit_after>var PromiseSolver = require('./PromiseSolver.js');
var P = require('bluebird');

/**
 * Object promise resolver
 *
 * @extends PromiseSolver
 * @constructor
 */
function ObjectPromiseSolver() {}
ObjectPromiseSolver.prototype = Object.create(PromiseSolver.prototype);
ObjectPromiseSolver.prototype.constructor = ObjectPromiseSolver;

/**
 * Takes an array of objects and resolve or reject them all.
 *
 * @param {array} promises
 * @returns {Array}
 */
ObjectPromiseSolver.prototype.all = function(promises) {
  return P.all(
    promises.map(
      function(promise) {
        var error, success;
        error = function (res) {
          promise.err = true;
          promise.res = res;
          return  promise;
        };
        success = function (res) {
          promise.err = false;
          promise.res = res;
          return  promise;
        };

        if (!promise.p || !promise.p.then) return error(new Error('The object missing p property that holds the promise.'));
        return promise.p.then(success,error)
      }
    )
  );
};

/**
 * Overrides parent and simply return the Array
 *
 * @param {Array} res
 * @returns {Array}
 */
ObjectPromiseSolver.prototype.clearResponse = function(res) { return res; };

module.exports = (function(){ return ObjectPromiseSolver; })();
<|endoftext|>


<commit_before>/**
* @class
*/
OpenLayers.Tile.WFS = Class.create();
OpenLayers.Tile.WFS.prototype =
  Object.extend( new OpenLayers.Tile(), {

    /** @type Array of Function */
    handlers: null,

    /** @type Array of */
    features: null,

    /**
    * @constructor
    *
    * @param {OpenLayers.Grid} grid
    * @param {OpenLayers.Bounds} bounds
    * @param {String} url
    * @param {OpenLayers.Size} size
    */
    initialize: function(grid, bounds, url, size) {
        OpenLayers.Tile.prototype.initialize.apply(this, arguments);

        this.features = new Array();

        this.handlers = new Array();
        this.handlers["requestSuccess"] = this._requestSuccess;
    },

    /**
    */
    draw:function() {
        OpenLayers.Tile.prototype.draw.apply(this, arguments);
        this.loadFeaturesForRegion("requestSuccess");
    },

    /**
     * @param OpenLayers.Pixel
     */
    setPosition:function(pixel) {
        this.position = pixel;
    },

    /** get the full request string from the ds and the tile params
    *     and call the AJAX loadURL().
    *
    *     input are function pointers for what to do on success and failure.
    *
    * @param {function} success
    * @param {function} failure
    */
    loadFeaturesForRegion:function(success, failure) {

        if (!this.loaded) {

            if (this.url != "") {

                // TODO: Hmmm, this stops multiple loads of the data when a
                //       result isn't immediately retrieved, but it's hacky.
                //       Do it better.
                this.loaded = true;
                ol.Log.info("request string: " + this.url);
                ol.Application.loadURL(this.url, null, this, success, failure);
            }
        }
    },

    /** Return from AJAX request
    *
    * @param {} request
    */
    requestSuccess:function(request) {

        var doc = request.responseXML;

        if (!doc || request.fileType!="XML") {
            doc = ol.Application.parseXMLString(request.responseText);
        }

        var resultFeatures = ol.Application.getNodes(doc, "gml:featureMember");
        ol.Log.info(this.grid.name + " found " +
                     resultFeatures.length + " features");

        //clear old featureList
        this.features = new Array();

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

            //make new Feature
            var feature = new ol.Feature(resultFeatures[i]);

            //make new Icon
            var icon = new OpenLayers.Icon(feature.markerImage, feature.size);

            //make new marker
            var marker = new OpenLayers.Marker(icon, feature.lonlat);
    	}

    },

    /** @final @type String */
    CLASS_NAME: "OpenLayers.Tile.WFS"
  }
);
<commit_msg>this is a dummy commit just because on the last commit, i forgot to specify that i didnt want to commit the changes i had made to Tile/WFS.js. So, know that in [186], the change to fix the bug was *just* the modification to Grid.js.    The modifications to Tile/WFS.js were just more small steps in the process of getting WFS ported and working again... <commit_after>/**
* @class
*/
OpenLayers.Tile.WFS = Class.create();
OpenLayers.Tile.WFS.prototype =
  Object.extend( new OpenLayers.Tile(), {

    /** @type Array of Function */
    handlers: null,

    /** @type Array of */
    features: null,

    /**
    * @constructor
    *
    * @param {OpenLayers.Grid} grid
    * @param {OpenLayers.Bounds} bounds
    * @param {String} url
    * @param {OpenLayers.Size} size
    */
    initialize: function(grid, bounds, url, size) {
        OpenLayers.Tile.prototype.initialize.apply(this, arguments);

        this.features = new Array();

        this.handlers = new Array();
        this.handlers["requestSuccess"] = this._requestSuccess;
    },

    /**
    */
    draw:function() {
        OpenLayers.Tile.prototype.draw.apply(this, arguments);
        this.loadFeaturesForRegion("requestSuccess");
    },

    /**
     * @param OpenLayers.Pixel
     */
    setPosition:function(pixel) {
        this.position = pixel;
    },

    /** get the full request string from the ds and the tile params
    *     and call the AJAX loadURL().
    *
    *     input are function pointers for what to do on success and failure.
    *
    * @param {function} success
    * @param {function} failure
    */
    loadFeaturesForRegion:function(success, failure) {

        if (!this.loaded) {

            if (this.url != "") {

                // TODO: Hmmm, this stops multiple loads of the data when a
                //       result isn't immediately retrieved, but it's hacky.
                //       Do it better.
                this.loaded = true;
                ol.Log.info("request string: " + this.url);
                ol.Application.loadURL(this.url, null, this, success, failure);
            }
        }
    },

    /** Return from AJAX request
    *
    * @param {} request
    */
    requestSuccess:function(request) {

        var doc = request.responseXML;

        if (!doc || request.fileType!="XML") {
            doc = ol.Application.parseXMLString(request.responseText);
        }

        var resultFeatures = ol.Application.getNodes(doc, "gml:featureMember");
        ol.Log.info(this.grid.name + " found " +
                     resultFeatures.length + " features");

        //clear old featureList
        this.features = new Array();

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

            //make new Feature
            var feature = new ol.Feature(resultFeatures[i]);

            //make new Icon
            var icon = new OpenLayers.Icon(feature.markerImage, feature.size);

            //make new marker
            var marker = new OpenLayers.Marker(icon, feature.lonlat);
    	}

    },

    /** @final @type String */
    CLASS_NAME: "OpenLayers.Tile.WFS"
  }
);

<|endoftext|>


<commit_before>// chortle.js
// a quest for chortle

// ADDME: common verbs
var dictionary = {
  "yes": "UH",
  "no": "DT",

  "i": "PRP",
  "you": "PRP",
  "he": "PRP",
  "she": "PRP",
  "it": "PRP",
  "we": "PRP",
  "they": "PRP",
  "me": "PRP",
  "him": "PRP",
  "her": "PRP",
  "us": "PRP",
  "them": "PRP",
  "my": "PRP",
  "your": "PRP",

  "because": "IN",

  "eat": "VBP",
  "eats": "VBZ",
  "is": "VBZ",
  "like": "VBP",

  "salt": "NN",
}

// question: expected pattern response from user
var questions = [
  {"question": "what is your _name_?", "expected": "UNKNOWN,UNKNOWN|UNKNOWN"},
  {"question": "what is your _favorite food_?", "expected": "UNKNOWN,UNKNOWN|UNKNOWN"},
]

var askedQuestions = Array();

var learned = {}
var userResponses = new Array();

function init() {
  var commands = new Array();
  // commands.push("PRP VBP|VBZ NN|UNKNOWN ... i eat cake");
  for (i = 0; i < commands.length; i++) {
    document.getElementById('command-list').innerHTML +=
      "
" + commands[i] + "
";
  }

  // first bot question
  var question = "hello, " + questions[0]["question"];
  ask(question);
  logger(question.replace(/_/g, ""));
  console.log(askedQuestions);
}

function ask(question) {
  output(question.replace(/_/g, ""));
  askedQuestions.push(question);
  return question;
}

function botResponseLogic(input) {
  var botResponse = "";
  // check POS pattern input

  console.log(input);
  console.log(questions[1]["expected"]);

  // make sure there is input (no whitespace)
  if (userResponses[userResponses.length-1][0].split("/")[1].replace(/\s/g, "").length > 0) {

    /*
        my  name        is  al
        PRP NN|UNKNOWN  VBZ NN|UNKNOWN
    */

    if (input.match(/PRP(.*)VBZ/i)) {
      // PRP(.*)VBZ (ex: my ** ** is **)
      var generatedKeyList = Array();
      var generatedValueList = Array();
      var generatedValuePatternList = Array();
      var pastVerb = false;

      // divide up how we learn this data (key:value)
      for (var i = 0; i < userResponses[userResponses.length-1].length; i++) {
        if (pastVerb) {
          // if after verb (goes into value)
          generatedValueList.push(userResponses[userResponses.length-1][i].split("/")[1]);
          generatedValuePatternList.push(userResponses[userResponses.length-1][i].split("/")[0]);
        } else {
          // if before or equal to verb (goes into key)
          generatedKeyList.push(userResponses[userResponses.length-1][i].split("/")[1]);
        }

        if (userResponses[userResponses.length-1][i].split("/")[0].match(/VBZ/i)) {
          pastVerb = true;
        }
      }
      console.log("generated key/value lists joined individually");
      console.log(generatedKeyList.join(" "));
      console.log(generatedValueList.join(" "));
      console.log(generatedValuePatternList.join(","));

      var valueMatchedPattern = generatedValuePatternList.join(",");
      if (questions[1]["expected"].match(valueMatchedPattern) && valueMatchedPattern.replace(/\s/g, "").length > 0) {
        console.log("response as expected...");
        var item = new Object();
        item[generatedKeyList.join(" ")] = generatedValueList.join(" ");
        learn(item);
      } else {
        console.log("unexpected response!");
        botResponse += "what do you mean? ";
        // TODO: repeat question
        // TODO: know what question number we are on...
      }

    } else if (input.match(/NN|UNKNOWN/i)) {
      // one word answer ... add question data to learned information
      var generatedValueList = Array();

      // collect values for learned data
      for (var i = 0; i < userResponses[userResponses.length-1].length; i++) {
        generatedValueList.push(userResponses[userResponses.length-1][i].split("/")[1]);
      }

      var item = new Object();
      item[askedQuestions[askedQuestions.length-1]] = generatedValueList.join(" ");
      learn(item);
    }

    if (input.match(/PRP,VBP,NN|PRP,VBZ,NN|PRP,VBP,UNKNOWN|PRP,VBZ,UNKNOWN/i)) {
      // PRP,VBP,NN (ex: i eat salt)
      // PRP,VBZ,NN (ex: he eats salt)
      if (userResponses[userResponses.length-1][0].split("/")[1] == "i") {
        botResponse += "you";
      } else {
        // ADDME: who are we talking about?
        botResponse += userResponses[userResponses.length-1][0].split("/")[1];
      }
      botResponse += " " + userResponses[userResponses.length-1][1].split("/")[1] + " " + userResponses[userResponses.length-1][2].split("/")[1] + "?";
    } else if (input == "UH" || input == "IN") {
      // UH (yes)
      // IN (because)
      botResponse += "I see... ";
      if (userResponses[userResponses.length-2][0].split("/")[1] != "yes") {
        if (userResponses[userResponses.length-2][2])
          botResponse += "do you like " + userResponses[userResponses.length-2][2].split("/")[1] + "?";
      }
    } else {
      // FIXME: add question askBehaviors
      //botResponse += "oh, why?";
      botResponse += questions[1]["question"];
      if (askedQuestions[questions[1]["question"]]) {
        // go on to another behavior

      }
    }
  } else {
    botResponse += "no answer, eh...?";
  }

  return botResponse;
}

function getPOS(key) {
  var result = "";
  if (dictionary[key])
    result = dictionary[key];
  else
    result = "UNKNOWN";
  return result;
}

function learn(info) {
  for (var item in info) {
    learned[item] = info[item];
  }
}

function logger(output) {
  document.getElementById("log").innerHTML +=
    "> " + output + "
";
}

function output(output) {
  document.getElementById("output").value = output;
}

function parse(phrase) {
  var result = new Array();
  var preUserResponsePush = new Array();
  items = tokenize(phrase);

  for (i = 0; i < items.length; i++) {
    console.log(getPOS(items[i]));
    result.push(getPOS(items[i]));
    preUserResponsePush.push(getPOS(items[i]) + "/" + items[i]);
  }

  // add to user phrase stack
  userResponses.push(preUserResponsePush);
  console.log(userResponses);

  return result.join(",");
}

function tokenize(input) {
  input = input.replace(/([\.?\/])/g, " $1");
  input = input.toLowerCase();
  var items = input.split(" ");
  console.log("tokens: " + items);
  return items;
}

function main() {
  input = document.getElementById("input").value;
  result = parse(input);

  console.log("result");
  console.log(result);

  console.log(userResponses);
  console.log(userResponses[0][0].split("/")[1]);

  // bot response logic
  var botResponse = botResponseLogic(result);
  output(botResponse.replace(/_/g, ""));

  // add to running log

  logger(input);
  logger(botResponse.replace(/_/g, ""));
  console.log(askedQuestions);

  document.getElementById("input").value = "";    // clear input textbox
  console.log("learned:");
  console.log(learned);   // display what we've learned
}
<commit_msg>general updates<commit_after>// chortle.js
// a quest for chortle

// ADDME: common verbs
var dictionary = {
  "yes": "UH",
  "no": "DT",

  "i": "PRP",
  "you": "PRP",
  "he": "PRP",
  "she": "PRP",
  "it": "PRP",
  "we": "PRP",
  "they": "PRP",
  "me": "PRP",
  "him": "PRP",
  "her": "PRP",
  "us": "PRP",
  "them": "PRP",
  "my": "PRP",
  "your": "PRP",

  "because": "IN",

  "eat": "VBP",
  "eats": "VBZ",
  "is": "VBZ",
  "like": "VBP",

  "salt": "NN",
}

var botLearnedPatterns = Array();

// question: expected pattern response from user
var questions = [
  {"question": "what is your _name_?", "expected": "UNKNOWN,UNKNOWN|UNKNOWN"},
  {"question": "what is your _favorite food_?", "expected": "UNKNOWN,UNKNOWN|UNKNOWN"},
]

var askedQuestions = Array();

var learned = {}
var userResponses = new Array();

function init() {
  var commands = new Array();
  // commands.push("PRP VBP|VBZ NN|UNKNOWN ... i eat cake");
  for (i = 0; i < commands.length; i++) {
    document.getElementById('command-list').innerHTML +=
      "
" + commands[i] + "
";
  }

  // first bot question
  var question = "hello, " + questions[0]["question"];
  ask(question);
  logger(question.replace(/_/g, ""));
  console.log(askedQuestions);
}

function ask(question) {
  output(question.replace(/_/g, ""));
  askedQuestions.push(question);
  return question;
}

function botResponseLogic(input) {
  var botResponse = "";
  // check POS pattern input

  console.log(input);
  console.log(questions[1]["expected"]);

  // make sure there is input (no whitespace)
  if (userResponses[userResponses.length-1][0].split("/")[1].replace(/\s/g, "").length > 0) {

    // my  name        is  al
    // PRP NN|UNKNOWN  VBZ NN|UNKNOWN

    if (input.match(/PRP(.*)VBZ/i)) {
      // PRP(.*)VBZ (ex: my ** ** is **)
      var generatedKeyList = Array();
      var generatedValueList = Array();
      var generatedValuePatternList = Array();
      var pastVerb = false;

      // divide up how we learn this data (key:value)
      for (var i = 0; i < userResponses[userResponses.length-1].length; i++) {
        if (pastVerb) {
          // if after verb (goes into value)
          generatedValueList.push(userResponses[userResponses.length-1][i].split("/")[1]);
          generatedValuePatternList.push(userResponses[userResponses.length-1][i].split("/")[0]);
        } else {
          // if before or equal to verb (goes into key)
          generatedKeyList.push(userResponses[userResponses.length-1][i].split("/")[1]);
        }

        if (userResponses[userResponses.length-1][i].split("/")[0].match(/VBZ/i)) {
          pastVerb = true;
        }
      }
      console.log("generated key/value lists joined individually");
      console.log(generatedKeyList.join(" "));
      console.log(generatedValueList.join(" "));
      console.log(generatedValuePatternList.join(","));

      var valueMatchedPattern = generatedValuePatternList.join(",");
      if (questions[1]["expected"].match(valueMatchedPattern) && valueMatchedPattern.replace(/\s/g, "").length > 0) {
        console.log("response as expected...");
        var item = new Object();
        item[generatedKeyList.join(" ")] = generatedValueList.join(" ");
        learn(item);
      } else {
        console.log("unexpected response!");
        botResponse += "what do you mean? ";
        // TODO: repeat question
        // TODO: know what question number we are on...
      }

    } else if (input.match(/NN|UNKNOWN/i)) {
      // one word answer ... add question data to learned information
      var generatedValueList = Array();

      // collect values for learned data
      for (var i = 0; i < userResponses[userResponses.length-1].length; i++) {
        generatedValueList.push(userResponses[userResponses.length-1][i].split("/")[1]);
      }

      var item = new Object();
      item[askedQuestions[askedQuestions.length-1]] = generatedValueList.join(" ");
      learn(item);
    }

    if (input.match(/PRP,VBP,NN|PRP,VBZ,NN|PRP,VBP,UNKNOWN|PRP,VBZ,UNKNOWN/i)) {
      // PRP,VBP,NN (ex: i eat salt)
      // PRP,VBZ,NN (ex: he eats salt)
      if (userResponses[userResponses.length-1][0].split("/")[1] == "i") {
        botResponse += "you";
      } else {
        // ADDME: who are we talking about?
        botResponse += userResponses[userResponses.length-1][0].split("/")[1];
      }
      botResponse += " " + userResponses[userResponses.length-1][1].split("/")[1] + " " + userResponses[userResponses.length-1][2].split("/")[1] + "?";
    } else if (input == "UH" || input == "IN") {
      // UH (yes)
      // IN (because)
      botResponse += "I see... ";
      if (userResponses[userResponses.length-2][0].split("/")[1] != "yes") {
        if (userResponses[userResponses.length-2][2])
          botResponse += "do you like " + userResponses[userResponses.length-2][2].split("/")[1] + "?";
      }
    } else {
      // FIXME: add question askBehaviors
      //botResponse += "oh, why?";
      botResponse += questions[1]["question"];
      if (askedQuestions[questions[1]["question"]]) {
        // go on to another behavior

      }
    }
  } else {
    botResponse += "no answer, eh...?";
  }

  return botResponse;
}

function getPOS(key) {
  var result = "";
  if (dictionary[key])
    result = dictionary[key];
  else
    result = "UNKNOWN";
  return result;
}

function learn(info) {
  for (var item in info) {
    learned[item] = info[item];
  }
}

function logger(output) {
  document.getElementById("log").innerHTML +=
    "> " + output + "
";
}

function output(output) {
  document.getElementById("output").value = output;
}

function parse(phrase) {
  var result = new Array();
  var preUserResponsePush = new Array();
  items = tokenize(phrase);

  for (i = 0; i < items.length; i++) {
    console.log(getPOS(items[i]));
    result.push(getPOS(items[i]));
    preUserResponsePush.push(getPOS(items[i]) + "/" + items[i]);
  }

  // add to user phrase stack
  userResponses.push(preUserResponsePush);
  console.log(userResponses);

  return result.join(",");
}

function tokenize(input) {
  input = input.replace(/([\.?\/])/g, " $1");
  input = input.toLowerCase();
  var items = input.split(" ");
  console.log("tokens: " + items);
  return items;
}

function randomIntFromInterval(min,max)
{
    return Math.floor(Math.random()*(max-min+1)+min);
}

function main() {
  input = document.getElementById("input").value;
  result = parse(input);

  console.log("result");
  console.log(result);

  console.log(userResponses);
  console.log(userResponses[0][0].split("/")[1]);

  // teacher time
  var botResponse = "";
  botResponse = botLearnedPatterns[randomIntFromInterval(0,botLearnedPatterns.length)];
  if (!botResponse) botResponse = input;

  /*
  // bot response logic
  var botResponse = botResponseLogic(result);
  output(botResponse.replace(/_/g, ""));
  */

  // add to running log
  logger(input);
  logger(botResponse);
  //logger(botResponse.replace(/_/g, ""));
  console.log(askedQuestions);

  document.getElementById("input").value = "";    // clear input textbox
  console.log("learned:");
  console.log(learned);   // display what we've learned

  console.log("learned responses:");
  console.log(botLearnedPatterns);
}
<|endoftext|>


<commit_before>( function( mw, $ ) {"use strict";

	mw.PluginManager.add( 'playbackRateSelector', mw.KBaseComponent.extend({

		defaultConfig: {
			"parent": "controlsContainer",
		 	"order": 61,
		 	"displayImportance": "medium",
		 	"align": "right",
		 	"showTooltip": true,
		 	'defaultSpeed': '1',
			'speeds': ".5,.75,1,1.5,2",
			'enableKeyboardShortcuts': true,
			'serverSpeedPlayback': false,
			'title': gM( 'mwe-embedplayer-speed' ),
			'smartContainer': 'qualitySettings',
			'smartContainerCloseEvent': 'updatedPlaybackRate'
		},

		isDisabled: false,
		currentSpeed: 1,
		manifestSource: null,

		isSafeEnviornment: function(){
			var _this = this,
			deferred = $.Deferred();
			if ( mw.isMobileDevice() && !this.getConfig("serverSpeedPlayback")){
				return false;
			}
			this.bind('playerReady', function(){
				if ( _this.getConfig("serverSpeedPlayback") === true && _this.manifestSource ){
					deferred.resolve(true);
				}
				if ( _this.embedPlayer.isLive() ){
					deferred.resolve(false);
				}
				// check if we have sources that can play with Native library:
				if (_this.embedPlayer.mediaElement.getNativePlayableSources().length > 0){
					deferred.resolve(document.createElement( "video" ).playbackRate && !mw.isMobileDevice());
				}
			});
			return deferred.promise();
		},

		setup: function(){
			this.currentSpeed = Math.abs(this.getConfig('defaultSpeed')) || 1;
			this.speedSet = this.getConfig('speeds').split(',');
			var i;
			for ( i=0; i < this.speedSet.length; i++) {
				this.speedSet[i] = Math.abs( this.speedSet[i] );
			}
			this.addBindings();
		},

		addBindings: function(){
			var _this = this;
			this.bind( 'playerReady', function(){
				_this.buildMenu();
			});

			this.bind( 'onChangeMedia', function(){
				_this.currentSpeed = 1;
				if ( !_this.embedPlayer.isMobileSkin() ){
					_this.getBtn().text( '1x' );
				}
				_this.buildMenu();

				_this.manifestSource = null;
			});

			this.bind( 'SourceSelected', function(e, source){
				if (source.src.indexOf("playManifest") !== -1 && (source.src.indexOf("/a.f4m") !== -1 || source.src.indexOf("/a.m3u8") !==-1)){
					_this.manifestSource = source.src;
				}
			});

			this.bind( 'onRemovePlayerSpinner', function(){
				 if ( _this.getPlayer().getPlayerElement() && !_this.getConfig("serverSpeedPlayback")) {
					 if (_this.getPlayer().instanceOf === 'Native') {
						 _this.getPlayer().getPlayerElement().playbackRate = _this.currentSpeed;
					 }
					 //Unfortunately until we transform the DASH player API to be same as native
					 //we have to do this
					 if (_this.getPlayer().instanceOf === 'MultiDRM'){
						 _this.getPlayer().getPlayerElement().setPlaybackRate(_this.currentSpeed);
					 }
				 }
			});
			this.bind( 'playbackRateChangeSpeed', function(e, arg ){
				_this.setSpeedFromApi( arg );
			});

			this.bind( 'onDisableInterfaceComponents', function(e, arg ){
				_this.getMenu().close();
			});

			if( this.getConfig('enableKeyboardShortcuts') ){
				this.bind( 'addKeyBindCallback', function( e, addKeyCallback ){
					_this.addKeyboardShortcuts( addKeyCallback );
				});
			}
		},
		// API for this plugin. With this API any external plugin or JS code will be able to set
		// a specific speed, or a faster/slower/fastest/slowest
		setSpeedFromApi: function( arg ) {
			var newSpeed;
			switch(arg){
				case 'faster':
					newSpeed = this.getFasterSpeed();
				break;
				case 'fastest':
					newSpeed = this.speedSet[this.speedSet.length-1] ;
				break;
				case 'slower':
					newSpeed = this.getSlowerSpeed();
				break;
				case 'slowest':
					newSpeed = this.speedSet[0] ;
				break;
				default:
					newSpeed = arg;
				break
			}
			this.setSpeed(newSpeed);
		},
		addKeyboardShortcuts: function( addKeyCallback ){
			var _this = this;
			// Add + Sign for faster speed
			addKeyCallback( 'shift+187', function(){
				_this.setSpeed( _this.getFasterSpeed() );
			});
			// Add - Sigh for slower speed
			addKeyCallback( 189, function(){
				_this.setSpeed( _this.getSlowerSpeed() );
			});
			// Add = Sigh for normal speed
			addKeyCallback( 187, function(){
				_this.setSpeed( _this.getConfig('defaultSpeed') );
			});
		},

		getFasterSpeed: function(){
			if( this.speedSet[this.getCurrentSpeedIndex()+1] ){
				return this.speedSet[this.getCurrentSpeedIndex()+1];
			}
			return this.speedSet[this.getCurrentSpeedIndex()];
		},
		getSlowerSpeed: function(){
			if( this.speedSet[this.getCurrentSpeedIndex()-1] ){
				return this.speedSet[this.getCurrentSpeedIndex()-1];
			}
			return this.speedSet[this.getCurrentSpeedIndex()];
		},

		buildMenu: function(){
			var _this = this;

			// Destroy old menu
			this.getMenu().destroy();

			$.each( this.speedSet, function( idx, speedFloat ){
				var active = ( _this.currentSpeed == speedFloat );
				_this.getMenu().addItem({
					'label': speedFloat + 'x',
					'callback': function(){
						_this.setSpeed( speedFloat );
					},
					'active': active
				});
				if (_this.embedPlayer.isMobileSkin() && active){
					_this.getMenu().setActive(idx);
				}
			});
		},
		setSpeed: function( newSpeed ){
			var _this = this;
			this.log('Set Speed to: ' + newSpeed);
			var previousSpeed = this.currentSpeed;
			this.currentSpeed = newSpeed;
			// check if we need to switch interfaces:
			if( (this.getPlayer().instanceOf != 'Native' && this.getPlayer().instanceOf != 'MultiDRM') || (mw.isMobileDevice() && this.getConfig("serverSpeedPlayback") && this.manifestSource)){
				this.handlePlayerInstanceUpdate( newSpeed, previousSpeed );
				return ;
			}
			this.updatePlaybackRate( newSpeed );
		},
		handlePlayerInstanceUpdate: function( newSpeed, previousSpeed ){
			var _this = this;
			var currentPlayTime = this.getPlayer().currentTime;
			this.currentSpeed = newSpeed;
			if (this.getConfig("serverSpeedPlayback") && this.currentSpeed <= 2 && (this.getPlayer().instanceOf === 'Kplayer' || mw.isMobileDevice())){
				this.switchServerSideSpeed(newSpeed, previousSpeed, currentPlayTime);
			}else{
				this.switchClientSideSpeed(newSpeed, previousSpeed, currentPlayTime);
			}
		},
		switchServerSideSpeed: function(newSpeed, previousSpeed, currentPlayTime){
			this.log('Set Speed on the server side to: ' + newSpeed);
			var _this = this;
			// for decimal numbers, make sure we have only one digit after the dot (server limitation)
			if ( this.currentSpeed % 1 !== 0 ){
				this.currentSpeed = this.currentSpeed.toFixed(1);
			}
			var source = this.manifestSource;
			if (this.manifestSource){ // for HLS and HDS, since the movie duration changes, we need to recalculate the position
				currentPlayTime = currentPlayTime * previousSpeed / this.currentSpeed;
			}
			var fileName = source.substr(source.lastIndexOf("/"));
			var base = source.substr(0,source.lastIndexOf("/"));
			if (fileName.indexOf("/a.f4m") === 0){
				base = base.substr(0,base.length-3);
			}
			if (source.indexOf("playbackRate") !== -1){
				base = base.substr(0,base.lastIndexOf("playbackRate")-1);
			}
			var newSrc = base + "/playbackRate/" + this.currentSpeed + fileName;
			this.updatePlaybackRate( newSpeed );

			if (mw.isMobileDevice()){
				this.getPlayer().getPlayerElement().src = newSrc;
				this.getPlayer().mediaElement.selectedSource.src = newSrc;
				if (mw.isIOS()){
					this.getPlayer().getPlayerElement().load();
				}
			}else{
				this.embedPlayer.playerObject.sendNotification("changeMedia", { "entryUrl" : newSrc});
				this.embedPlayer.play();
			}

			if ( currentPlayTime > 0 ){
				this.embedPlayer.stopMonitor();
				$(this.embedPlayer).bind("playing", function(){
					$(_this.embedPlayer).unbind("playing");
					setTimeout(function(){
						if (mw.isIOS()){
							_this.getPlayer().getPlayerElement().currentTime =  currentPlayTime ;
						}else{
							_this.embedPlayer.seek( currentPlayTime );
						}
						_this.embedPlayer.startMonitor();
					},0);
				});
			}
		},
		switchClientSideSpeed: function(newSpeed, previousSpeed, currentPlayTime){
			this.log('Set Speed on the client side to: ' + newSpeed);
			var _this = this;
			// look for native sources and send them to the autoSelectSource function
			var nativeSources = [];
			var playableSources = this.getPlayer().mediaElement.getPlayableSources();
			$.each( playableSources, function(i, source ){
				if ( source.mimeType == 'video/mp4' || source.mimeType == 'video/h264' ) {
					nativeSources.push( source );
				}
			});
			var options = nativeSources.length ? { 'sources' : nativeSources } : {};
			var source = this.getPlayer().mediaElement.autoSelectSource(options);
			var player = mw.EmbedTypes.getMediaPlayers().getNativePlayer( source.mimeType );
			this.getPlayer().selectPlayer ( player );
			this.getPlayer().updatePlaybackInterface( function(){
				// update playback rate:
				if( currentPlayTime == 0 ){
					_this.updatePlaybackRate( newSpeed );
				}else{
					setTimeout(function(){
						_this.bind("seeked", function(){
							_this.updatePlaybackRate( newSpeed );
							_this.unbind("seeked");
						});
						_this.getPlayer().seek( currentPlayTime ); // issue a seek if given new seek time
					}, 200);
				}
			});
		},
		/**
		 * updatePlaybackRate issues a call to native player element to update playbackRate to target speed.
		 * @param {float} newSpeed target playback rate in float 1.0 = normal playback rate.
		 */
		updatePlaybackRate: function( newSpeed ){
			// workaround for Firefox and IE - changing playbackRate before media loads causes player to stuck
			if (this.getPlayer().mediaLoadedFlag){
				if (this.getPlayer().instanceOf === 'Native') {
					this.getPlayer().getPlayerElement().playbackRate = newSpeed;
				}
				//Unfortunately until we transform the DASH player API to be same as native
				//we have to do this
				if (this.getPlayer().instanceOf === 'MultiDRM'){
					this.getPlayer().getPlayerElement().setPlaybackRate(newSpeed);
				}
			}
			if (!this.embedPlayer.isMobileSkin()){
				this.getBtn().text( newSpeed + 'x' );
			}
			this.getPlayer().triggerHelper( 'updatedPlaybackRate', newSpeed);
		},
		getCurrentSpeedIndex: function(){
			var _this = this;
			var index = null;
			$.each(this.speedSet, function( idx, speed){
				if( _this.currentSpeed == speed ){
					index = idx;
					return true;
				}
			});
			return index;
		},
		toggleMenu: function(){
			if ( this.isDisabled ) {
				return;
			}
			this.getMenu().toggle();
		},
		getComponent: function() {
			var _this = this;
			if( !this.$el ) {
				var $menu = $( '<ul />' );
				var text = this.embedPlayer.isMobileSkin() ? '' : this.currentSpeed + 'x';
				var classes = this.embedPlayer.isMobileSkin() ? 'btn icon-speedrate' : 'btn';
				var $button = $( '<button />' )
								.addClass( classes )
								.attr('title', this.getConfig('title'))
								.text( text )
								.click( function(e){
									_this.toggleMenu();
								});

				this.$el = $( '<div />' )
								.addClass( 'dropup' + this.getCssClass() )
								.append( $button, $menu );
			}
			return this.$el;
		},
		getMenu: function(){
			if( !this.menu ) {
				this.menu = new mw.KMenu(this.getComponent().find('ul'), {
					tabIndex: this.getBtn().attr('tabindex')
				});
			}
			return this.menu;
		},
		getBtn: function(){
			return this.getComponent().find( 'button' );
		},
		onEnable: function(){
			this.isDisabled = false;
			this.getBtn().removeClass( 'disabled' );
		},
		onDisable: function(){
			this.isDisabled = true;
			this.getComponent().removeClass( 'open' );
			this.getBtn().addClass( 'disabled' );
		}
	}));

} )( window.mw, window.jQuery );<commit_msg>Change playbackrate api in playManifest request<commit_after>( function( mw, $ ) {"use strict";

	mw.PluginManager.add( 'playbackRateSelector', mw.KBaseComponent.extend({

		defaultConfig: {
			"parent": "controlsContainer",
		 	"order": 61,
		 	"displayImportance": "medium",
		 	"align": "right",
		 	"showTooltip": true,
		 	'defaultSpeed': '1',
			'speeds': ".5,.75,1,1.5,2",
			'enableKeyboardShortcuts': true,
			'serverSpeedPlayback': false,
			'title': gM( 'mwe-embedplayer-speed' ),
			'smartContainer': 'qualitySettings',
			'smartContainerCloseEvent': 'updatedPlaybackRate'
		},

		isDisabled: false,
		currentSpeed: 1,
		manifestSource: null,

		isSafeEnviornment: function(){
			var _this = this,
			deferred = $.Deferred();
			if ( mw.isMobileDevice() && !this.getConfig("serverSpeedPlayback")){
				return false;
			}
			this.bind('playerReady', function(){
				if ( _this.getConfig("serverSpeedPlayback") === true && _this.manifestSource ){
					deferred.resolve(true);
				}
				if ( _this.embedPlayer.isLive() ){
					deferred.resolve(false);
				}
				// check if we have sources that can play with Native library:
				if (_this.embedPlayer.mediaElement.getNativePlayableSources().length > 0){
					deferred.resolve(document.createElement( "video" ).playbackRate && !mw.isMobileDevice());
				}
			});
			return deferred.promise();
		},

		setup: function(){
			this.currentSpeed = Math.abs(this.getConfig('defaultSpeed')) || 1;
			this.speedSet = this.getConfig('speeds').split(',');
			var i;
			for ( i=0; i < this.speedSet.length; i++) {
				this.speedSet[i] = Math.abs( this.speedSet[i] );
			}
			this.addBindings();
		},

		addBindings: function(){
			var _this = this;
			this.bind( 'playerReady', function(){
				_this.buildMenu();
			});

			this.bind( 'onChangeMedia', function(){
				_this.currentSpeed = 1;
				if ( !_this.embedPlayer.isMobileSkin() ){
					_this.getBtn().text( '1x' );
				}
				_this.buildMenu();

				_this.manifestSource = null;
			});

			this.bind( 'SourceSelected', function(e, source){
				if (source.src.indexOf("playManifest") !== -1 && (source.src.indexOf("/a.f4m") !== -1 || source.src.indexOf("/a.m3u8") !==-1)){
					_this.manifestSource = source.src;
				}
			});

			this.bind( 'onRemovePlayerSpinner', function(){
				 if ( _this.getPlayer().getPlayerElement() && !_this.getConfig("serverSpeedPlayback")) {
					 if (_this.getPlayer().instanceOf === 'Native') {
						 _this.getPlayer().getPlayerElement().playbackRate = _this.currentSpeed;
					 }
					 //Unfortunately until we transform the DASH player API to be same as native
					 //we have to do this
					 if (_this.getPlayer().instanceOf === 'MultiDRM'){
						 _this.getPlayer().getPlayerElement().setPlaybackRate(_this.currentSpeed);
					 }
				 }
			});
			this.bind( 'playbackRateChangeSpeed', function(e, arg ){
				_this.setSpeedFromApi( arg );
			});

			this.bind( 'onDisableInterfaceComponents', function(e, arg ){
				_this.getMenu().close();
			});

			if( this.getConfig('enableKeyboardShortcuts') ){
				this.bind( 'addKeyBindCallback', function( e, addKeyCallback ){
					_this.addKeyboardShortcuts( addKeyCallback );
				});
			}
		},
		// API for this plugin. With this API any external plugin or JS code will be able to set
		// a specific speed, or a faster/slower/fastest/slowest
		setSpeedFromApi: function( arg ) {
			var newSpeed;
			switch(arg){
				case 'faster':
					newSpeed = this.getFasterSpeed();
				break;
				case 'fastest':
					newSpeed = this.speedSet[this.speedSet.length-1] ;
				break;
				case 'slower':
					newSpeed = this.getSlowerSpeed();
				break;
				case 'slowest':
					newSpeed = this.speedSet[0] ;
				break;
				default:
					newSpeed = arg;
				break
			}
			this.setSpeed(newSpeed);
		},
		addKeyboardShortcuts: function( addKeyCallback ){
			var _this = this;
			// Add + Sign for faster speed
			addKeyCallback( 'shift+187', function(){
				_this.setSpeed( _this.getFasterSpeed() );
			});
			// Add - Sigh for slower speed
			addKeyCallback( 189, function(){
				_this.setSpeed( _this.getSlowerSpeed() );
			});
			// Add = Sigh for normal speed
			addKeyCallback( 187, function(){
				_this.setSpeed( _this.getConfig('defaultSpeed') );
			});
		},

		getFasterSpeed: function(){
			if( this.speedSet[this.getCurrentSpeedIndex()+1] ){
				return this.speedSet[this.getCurrentSpeedIndex()+1];
			}
			return this.speedSet[this.getCurrentSpeedIndex()];
		},
		getSlowerSpeed: function(){
			if( this.speedSet[this.getCurrentSpeedIndex()-1] ){
				return this.speedSet[this.getCurrentSpeedIndex()-1];
			}
			return this.speedSet[this.getCurrentSpeedIndex()];
		},

		buildMenu: function(){
			var _this = this;

			// Destroy old menu
			this.getMenu().destroy();

			$.each( this.speedSet, function( idx, speedFloat ){
				var active = ( _this.currentSpeed == speedFloat );
				_this.getMenu().addItem({
					'label': speedFloat + 'x',
					'callback': function(){
						_this.setSpeed( speedFloat );
					},
					'active': active
				});
				if (_this.embedPlayer.isMobileSkin() && active){
					_this.getMenu().setActive(idx);
				}
			});
		},
		setSpeed: function( newSpeed ){
			var _this = this;
			this.log('Set Speed to: ' + newSpeed);
			var previousSpeed = this.currentSpeed;
			this.currentSpeed = newSpeed;
			// check if we need to switch interfaces:
			if( (this.getPlayer().instanceOf != 'Native' && this.getPlayer().instanceOf != 'MultiDRM') || (mw.isMobileDevice() && this.getConfig("serverSpeedPlayback") && this.manifestSource)){
				this.handlePlayerInstanceUpdate( newSpeed, previousSpeed );
				return ;
			}
			this.updatePlaybackRate( newSpeed );
		},
		handlePlayerInstanceUpdate: function( newSpeed, previousSpeed ){
			var _this = this;
			var currentPlayTime = this.getPlayer().currentTime;
			this.currentSpeed = newSpeed;
			if (this.getConfig("serverSpeedPlayback") && this.currentSpeed <= 2 && (this.getPlayer().instanceOf === 'Kplayer' || mw.isMobileDevice())){
				this.switchServerSideSpeed(newSpeed, previousSpeed, currentPlayTime);
			}else{
				this.switchClientSideSpeed(newSpeed, previousSpeed, currentPlayTime);
			}
		},
		switchServerSideSpeed: function(newSpeed, previousSpeed, currentPlayTime){
			this.log('Set Speed on the server side to: ' + newSpeed);
			var _this = this;
			// for decimal numbers, make sure we have only one digit after the dot (server limitation)
			if ( this.currentSpeed % 1 !== 0 ){
				this.currentSpeed = this.currentSpeed.toFixed(1);
			}
			var source = this.manifestSource;
			if (this.manifestSource){ // for HLS and HDS, since the movie duration changes, we need to recalculate the position
				currentPlayTime = currentPlayTime * previousSpeed / this.currentSpeed;
			}
			var fileName = source.substr(source.lastIndexOf("/"));
			var base = source.substr(0,source.lastIndexOf("/"));
			if (fileName.indexOf("/a.f4m") === 0){
				base = base.substr(0,base.length-3);
			}
			if (source.indexOf("playbackrate") !== -1){
				base = base.substr(0,base.lastIndexOf("playbackrate")-1);
			}
			var newSrc = base + "/playbackrate/" + this.currentSpeed + fileName;
			this.updatePlaybackRate( newSpeed );

			if (mw.isMobileDevice()){
				this.getPlayer().getPlayerElement().src = newSrc;
				this.getPlayer().mediaElement.selectedSource.src = newSrc;
				if (mw.isIOS()){
					this.getPlayer().getPlayerElement().load();
				}
			}else{
				this.embedPlayer.playerObject.sendNotification("changeMedia", { "entryUrl" : newSrc});
				this.embedPlayer.play();
			}

			if ( currentPlayTime > 0 ){
				this.embedPlayer.stopMonitor();
				$(this.embedPlayer).bind("playing", function(){
					$(_this.embedPlayer).unbind("playing");
					setTimeout(function(){
						if (mw.isIOS()){
							_this.getPlayer().getPlayerElement().currentTime =  currentPlayTime ;
						}else{
							_this.embedPlayer.seek( currentPlayTime );
						}
						_this.embedPlayer.startMonitor();
					},0);
				});
			}
		},
		switchClientSideSpeed: function(newSpeed, previousSpeed, currentPlayTime){
			this.log('Set Speed on the client side to: ' + newSpeed);
			var _this = this;
			// look for native sources and send them to the autoSelectSource function
			var nativeSources = [];
			var playableSources = this.getPlayer().mediaElement.getPlayableSources();
			$.each( playableSources, function(i, source ){
				if ( source.mimeType == 'video/mp4' || source.mimeType == 'video/h264' ) {
					nativeSources.push( source );
				}
			});
			var options = nativeSources.length ? { 'sources' : nativeSources } : {};
			var source = this.getPlayer().mediaElement.autoSelectSource(options);
			var player = mw.EmbedTypes.getMediaPlayers().getNativePlayer( source.mimeType );
			this.getPlayer().selectPlayer ( player );
			this.getPlayer().updatePlaybackInterface( function(){
				// update playback rate:
				if( currentPlayTime == 0 ){
					_this.updatePlaybackRate( newSpeed );
				}else{
					setTimeout(function(){
						_this.bind("seeked", function(){
							_this.updatePlaybackRate( newSpeed );
							_this.unbind("seeked");
						});
						_this.getPlayer().seek( currentPlayTime ); // issue a seek if given new seek time
					}, 200);
				}
			});
		},
		/**
		 * updatePlaybackRate issues a call to native player element to update playbackRate to target speed.
		 * @param {float} newSpeed target playback rate in float 1.0 = normal playback rate.
		 */
		updatePlaybackRate: function( newSpeed ){
			// workaround for Firefox and IE - changing playbackRate before media loads causes player to stuck
			if (this.getPlayer().mediaLoadedFlag){
				if (this.getPlayer().instanceOf === 'Native') {
					this.getPlayer().getPlayerElement().playbackRate = newSpeed;
				}
				//Unfortunately until we transform the DASH player API to be same as native
				//we have to do this
				if (this.getPlayer().instanceOf === 'MultiDRM'){
					this.getPlayer().getPlayerElement().setPlaybackRate(newSpeed);
				}
			}
			if (!this.embedPlayer.isMobileSkin()){
				this.getBtn().text( newSpeed + 'x' );
			}
			this.getPlayer().triggerHelper( 'updatedPlaybackRate', newSpeed);
		},
		getCurrentSpeedIndex: function(){
			var _this = this;
			var index = null;
			$.each(this.speedSet, function( idx, speed){
				if( _this.currentSpeed == speed ){
					index = idx;
					return true;
				}
			});
			return index;
		},
		toggleMenu: function(){
			if ( this.isDisabled ) {
				return;
			}
			this.getMenu().toggle();
		},
		getComponent: function() {
			var _this = this;
			if( !this.$el ) {
				var $menu = $( '<ul />' );
				var text = this.embedPlayer.isMobileSkin() ? '' : this.currentSpeed + 'x';
				var classes = this.embedPlayer.isMobileSkin() ? 'btn icon-speedrate' : 'btn';
				var $button = $( '<button />' )
								.addClass( classes )
								.attr('title', this.getConfig('title'))
								.text( text )
								.click( function(e){
									_this.toggleMenu();
								});

				this.$el = $( '<div />' )
								.addClass( 'dropup' + this.getCssClass() )
								.append( $button, $menu );
			}
			return this.$el;
		},
		getMenu: function(){
			if( !this.menu ) {
				this.menu = new mw.KMenu(this.getComponent().find('ul'), {
					tabIndex: this.getBtn().attr('tabindex')
				});
			}
			return this.menu;
		},
		getBtn: function(){
			return this.getComponent().find( 'button' );
		},
		onEnable: function(){
			this.isDisabled = false;
			this.getBtn().removeClass( 'disabled' );
		},
		onDisable: function(){
			this.isDisabled = true;
			this.getComponent().removeClass( 'open' );
			this.getBtn().addClass( 'disabled' );
		}
	}));

} )( window.mw, window.jQuery );<|endoftext|>


<commit_before>/* global $:false */
(function () {
  'use strict';

  // Applications controller
  angular
  .module('applications')
  .controller('ApplicationsController', ApplicationsController);

  ApplicationsController.$inject = ['$scope', '$state', '$timeout', '$window', 'Authentication', 'FileUploader',
  'applicationResolve', 'CompaniesService'];

  function ApplicationsController ($scope, $state, $timeout, $window, Authentication, FileUploader,
    application, CompaniesService) {
    var vm = this;

    vm.authentication = Authentication;
    vm.application = application;
    vm.application.resume = {};
    vm.error = null;
    vm.form = {};
    vm.remove = remove;
    vm.save = save;
    vm.application.year = "";
    vm.application.times = [];
    vm.application.companies = [];
    vm.createMode = !vm.application._id;

    //filuppladdning
    $scope.user = Authentication.user;
    $scope.imgUrlBase = 'public/uploads/';
    $scope.pdfURL = $scope.imgUrlBase + vm.application._id + '.pdf';
    //slut

    //fetches the company names from the database
    $scope.companyNames = [];
    CompaniesService.query().$promise.then(function(result) {
      angular.forEach(result, function(company) {
        $scope.companyNames.push(company.name);
      });
    });

    //meeting times
    $scope.times = ['16/11 10-11',
    '16/11 11-12',
    '16/11 12-13',
    '16/11 13-14',
    '16/11 14-15',
    '16/11 15-16',
    '17/11 9-10',
    '17/11 10-11',
    '17/11 11-12',
    '17/11 12-13',
    '17/11 13-14',
    '17/11 14-15',];

    //programs
    var allPrograms = ['Byggteknik med arkitektur / Civil Engineering - Architecture',
                  'Arkitekt / Architect',
                  'Arkitekt / Architect',
                  'Medicin och teknik / Biomedical Engineering',
                  'Bioteknik / Biotechnology',
                  'Bioteknik / Biotechnology',
                  'Kemiteknik / Chemical Engineering',
                  'Kemiteknik / Chemical Engineering',
                  'Brandingenjörsutbildning / Fire Protection Engineering',
                  'Brandingenjörsutbildning / Fire Protection Engineering',
                  'Byggteknik med arkitektur / Civil Engineering - Architecture',
                  'Byggteknik med järnvägsteknik / Civil Engineering - Railway Construction',
                  'Byggteknik med järnvägsteknik / Civil Engineering - Railway Construction',
                  'Civil Engineering- Road and Traffic Technology / Civil Engineering- Road and Traffic Technology',
                  'Civil Engineering- Road and Traffic Technology / Civil Engineering- Road and Traffic Technology',
                  'Väg- och vattenbyggnad / Civil Engineering',
                  'Väg- och vattenbyggnad / Civil Engineering',
                  'Datateknik / Computer Science and Engineering',
                  'Datateknik / Computer Science and Engineering',
                  'Informations- och kommunikationsteknik / Information and Communication Engineering',
                  'Informations- och kommunikationsteknik / Information and Communication Engineering',
                  'Ekosystemteknik / Environmental Engineering',
                  'Elektroteknik / Electrical Engineering',
                  'Elektroteknik / Electrical Engineering',
                  'Teknisk Matematik / Engineering Mathematics',
                  'Teknisk Nanovetenskap / Engineering Nanoscience',
                  'Teknisk Fysik / Engineering Physics',
                  'Teknisk Matematik / Engineering Mathematics',
                  'Teknisk Fysik / Engineering Physics',
                  'Teknisk Nanovetenskap / Engineering Nanoscience',
                  'Ekosystemteknik / Environmental Engineering',
                  'Industridesign / Industrial Design',
                  'Industriell ekonomi / Industrial Engineering and Management',
                  'Industridesign / Industrial Design',
                  'Industriell ekonomi / Industrial Engineering and Management',
                  'Lantmäteri / Surveying',
                  'Maskinteknik med teknisk design / Mechanical Engineering with Industrial Design',
                  'Maskinteknik med teknisk design / Mechanical Engineering with Industrial Design',
                  'Maskinteknik / Mechanical Engineering',
                  'Maskinteknik / Mechanical Engineering',
                  'Medicin och teknik / Biomedical Engineering',
                  'Lantmäteri / Surveying'];

    var set = new Set(allPrograms);
    $scope.programs = Array.from(set);

    $scope.years = [1, 2, 3, 4, 5];

    /*------------------------------ File Uploaders --------------------------------------------------------*/

    // Creation of the file uploaders
    $scope.swedishFileUploader = new FileUploader({ url: 'api/applications/resume', alias: 'newResume' });
    $scope.englishFileUploader = new FileUploader({ url: 'api/applications/resume', alias: 'newResume' });

    // Methods for an pdf uploader
    var pdfFilter = {
      name: 'pdfFilter',
      fn: function (item, options) {
        var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
        return '|pdf|'.indexOf(type) !== -1;
      }
    };

    // Connecting of file uploaders to their methods (filters etc.)
    $scope.swedishFileUploader.filters.push(pdfFilter);

    // Called after the user selected a file
    $scope.swedishFileUploader.onAfterAddingFile = function(fileItem) {
      if ($window.FileReader) {
        var fileReader = new FileReader();
        fileReader.readAsDataURL(fileItem._file);

        fileReader.onload = function (fileReaderEvent) {
          $timeout(function () {
            //$scope.pdfURL = fileReaderEvent.target.result;
          }, 0);
        };
      }
    };

    // Called after the user has successfully uploaded a new resume
    $scope.swedishFileUploader.onSuccessItem = function(fileItem, response, status, headers) {
      // URL to resume put into database
      vm.application.resume.swedishLink = response;
      // Show success message
      $scope.swedishUploadSuccess = true;
      // Clear uploader queue
      $scope.swedishFileUploader.clearQueue();
      return;
    };

    // Resets the upload as unsuccessful
    $scope.swedishUploadUnsuccess = function () {
      $scope.swedishUploadSuccess = false;
    };

    $scope.englishFileUploader.filters.push(pdfFilter);
    // Called after the user selected a file
    $scope.englishFileUploader.onAfterAddingFile = function(fileItem) {
      if ($window.FileReader) {
        var fileReader = new FileReader();
        fileReader.readAsDataURL(fileItem._file);

        fileReader.onload = function (fileReaderEvent) {
          $timeout(function () {
          //$scope.pdfURL = fileReaderEvent.target.result;
          }, 0);
        };
      }
    };

    // Called after the user has successfully uploaded a new resume
    $scope.englishFileUploader.onSuccessItem = function(fileItem, response, status, headers) {
      // URL to resume put into database
      $scope.vm.application.resume.englishLink = response;
      // Show success message
      $scope.englishUploadSuccess = true;
      // Clear uploader queue
      $scope.englishFileUploader.clearQueue();
      return;
    };

    // Resets the upload as unsuccessful
    $scope.englishUploadUnsuccess = function () {
      $scope.englishUploadSuccess = false;
    };

    /*------------------------------ End of File Uploaders --------------------------------------------------------*/

    $scope.removeSwedishResume = function() {
      $scope.vm.application.resume.swedishLink = '';
      $scope.swedishUploadSuccess = false;
    };

    $scope.removeEnglishResume = function() {
      $scope.vm.application.resume.englishLink = '';
      $scope.englishUploadSuccess = false;
    };

    //limit length of 'vm.application.description'
    $scope.monitorLength = function (maxLength) {
      if ($scope.vm.application.description.length > maxLength) {
        $scope.vm.application.description = $scope.vm.application.description.substring(0, maxLength);
      }
    };

    // Remove existing Application
    function remove() {
      if (confirm('Are you sure you want to delete?')) {
        vm.application.$remove($state.go('applications.list'));
      }
    }

    // Resets the upload as unsuccessful
    $scope.unsuccess = function () {
      $scope.success = false;
    };

    // Save Application
    function save(isValid) {
      vm.error = false;
      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'vm.form.applicationForm');
        vm.error = 'Du har inte fyllt i alla fält / You need to fill all fields';
        return false;
      } else if (vm.application.resume === undefined ||
        (vm.application.resume.englishLink === undefined && vm.application.resume.swedishLink === undefined) ||
        (vm.application.resume.englishLink === "" && vm.application.resume.swedishLink === undefined) ||
        (vm.application.resume.englishLink === undefined && vm.application.resume.swedishLink === "") ||
        (vm.application.resume.englishLink === "" && vm.application.resume.swedishLink === "")) {
        vm.error = 'Du måste bifoga minst ett CV / You must attach at least one resume';
        return false;
      } else if (vm.application.companies === undefined || vm.application.companies.length === 0) {
        vm.error = 'Du måste välja minst ett företag / You must choose at least one company';
        return false;
      } else if (vm.application.times === undefined || vm.application.times.length === 0) {
        vm.error = 'Du måste välja minst en tid / You must tell when you are available';
        return false;
      }

      // TODO: move create/update logic to service
      if (vm.application._id) {
        vm.application.$update(successCallback, errorCallback);
      } else {
        vm.application.$save(successCallback, errorCallback);
      }

      function successCallback(res) {
        if(vm.createMode){
          $state.go('applications.submitted', { name: vm.application.name, email: vm.application.email });
        } else {
          $state.go('applications.view', { applicationId: res._id });
        }
      }

      function errorCallback(res) {
        vm.error = res.data.message;
      }
    }

    function prettify(str) {
      return str.replace(/\s/g, '')
        .replace(/å/g, 'a')
        .replace(/Å/g, 'A')
        .replace(/ä/g, 'a')
        .replace(/Ä/g, 'A')
        .replace(/ö/g, 'o')
        .replace(/Ö/g, 'O');
    }

    // Angular needs to complete rendering before applying 'chosen'
    $timeout(function () {
      // Chosen methods
      $(".program_select_box").chosen({
        no_results_text: "Oops, nothing found!",
        width: "100%"
      });
      $(".company_select_box").chosen({
        no_results_text: "Oops, nothing found!",
        width: "100%"
      });
      $(".time_select_box").chosen({
        no_results_text: "Oops, nothing found!",
        width: "100%"
      });
      $(".year_select_box").chosen({
        no_results_text: "Oops, nothing found!",
        width: "100%"
      });
    }, 0, false);

    $('.program_select_box').on('change', function(evt, params) {
      vm.application.program = $scope.programs[params.selected];
      $scope.$apply();
    });

    $('.company_select_box').on('change', function(evt, params) {
      var element = $('.company_select_box');
      if(params.selected){
        vm.application.companies.push($scope.companyNames[params.selected]);
      } else if(params.deselected) {
        var position = vm.application.companies.indexOf($scope.companyNames[params.deselected]);
        vm.application.companies.splice(position, 1);
      }
      $scope.$apply();
    });

    $('.time_select_box').on('change', function(evt, params) {
      var element = $('.time_select_box');
      if(params.selected){
        vm.application.times.push($scope.times[params.selected]);
      } else if(params.deselected) {
        var position = vm.application.times.indexOf($scope.times[params.deselected]);
        vm.application.times.splice(position, 1);
      }
      $scope.$apply();
    });

    $('.year_select_box').on('change', function(evt, params) {
      vm.application.year = parseInt(params.selected) + 1;
      $scope.$apply();
    });
  }
})();
<commit_msg>Fixed warnings<commit_after>/* global $:false */
(function () {
  'use strict';

  // Applications controller
  angular
  .module('applications')
  .controller('ApplicationsController', ApplicationsController);

  ApplicationsController.$inject = ['$scope', '$state', '$timeout', '$window', 'Authentication', 'FileUploader',
  'applicationResolve', 'CompaniesService'];

  function ApplicationsController ($scope, $state, $timeout, $window, Authentication, FileUploader,
    application, CompaniesService) {
    var vm = this;

    vm.authentication = Authentication;
    vm.application = application;
    vm.application.resume = {};
    vm.error = null;
    vm.form = {};
    vm.remove = remove;
    vm.save = save;
    vm.application.year = '';
    vm.application.times = [];
    vm.application.companies = [];
    vm.createMode = !vm.application._id;

    //filuppladdning
    $scope.user = Authentication.user;
    $scope.imgUrlBase = 'public/uploads/';
    $scope.pdfURL = $scope.imgUrlBase + vm.application._id + '.pdf';
    //slut

    //fetches the company names from the database
    $scope.companyNames = [];
    CompaniesService.query().$promise.then(function(result) {
      angular.forEach(result, function(company) {
        $scope.companyNames.push(company.name);
      });
    });

    //meeting times
    $scope.times = ['16/11 10-11',
    '16/11 11-12',
    '16/11 12-13',
    '16/11 13-14',
    '16/11 14-15',
    '16/11 15-16',
    '17/11 9-10',
    '17/11 10-11',
    '17/11 11-12',
    '17/11 12-13',
    '17/11 13-14',
    '17/11 14-15'];

    //programs
    var allPrograms = ['Byggteknik med arkitektur / Civil Engineering - Architecture',
                  'Arkitekt / Architect',
                  'Arkitekt / Architect',
                  'Medicin och teknik / Biomedical Engineering',
                  'Bioteknik / Biotechnology',
                  'Bioteknik / Biotechnology',
                  'Kemiteknik / Chemical Engineering',
                  'Kemiteknik / Chemical Engineering',
                  'Brandingenjörsutbildning / Fire Protection Engineering',
                  'Brandingenjörsutbildning / Fire Protection Engineering',
                  'Byggteknik med arkitektur / Civil Engineering - Architecture',
                  'Byggteknik med järnvägsteknik / Civil Engineering - Railway Construction',
                  'Byggteknik med järnvägsteknik / Civil Engineering - Railway Construction',
                  'Civil Engineering- Road and Traffic Technology / Civil Engineering- Road and Traffic Technology',
                  'Civil Engineering- Road and Traffic Technology / Civil Engineering- Road and Traffic Technology',
                  'Väg- och vattenbyggnad / Civil Engineering',
                  'Väg- och vattenbyggnad / Civil Engineering',
                  'Datateknik / Computer Science and Engineering',
                  'Datateknik / Computer Science and Engineering',
                  'Informations- och kommunikationsteknik / Information and Communication Engineering',
                  'Informations- och kommunikationsteknik / Information and Communication Engineering',
                  'Ekosystemteknik / Environmental Engineering',
                  'Elektroteknik / Electrical Engineering',
                  'Elektroteknik / Electrical Engineering',
                  'Teknisk Matematik / Engineering Mathematics',
                  'Teknisk Nanovetenskap / Engineering Nanoscience',
                  'Teknisk Fysik / Engineering Physics',
                  'Teknisk Matematik / Engineering Mathematics',
                  'Teknisk Fysik / Engineering Physics',
                  'Teknisk Nanovetenskap / Engineering Nanoscience',
                  'Ekosystemteknik / Environmental Engineering',
                  'Industridesign / Industrial Design',
                  'Industriell ekonomi / Industrial Engineering and Management',
                  'Industridesign / Industrial Design',
                  'Industriell ekonomi / Industrial Engineering and Management',
                  'Lantmäteri / Surveying',
                  'Maskinteknik med teknisk design / Mechanical Engineering with Industrial Design',
                  'Maskinteknik med teknisk design / Mechanical Engineering with Industrial Design',
                  'Maskinteknik / Mechanical Engineering',
                  'Maskinteknik / Mechanical Engineering',
                  'Medicin och teknik / Biomedical Engineering',
                  'Lantmäteri / Surveying'];

    var set = new Set(allPrograms);
    $scope.programs = Array.from(set);

    $scope.years = [1, 2, 3, 4, 5];

    /*------------------------------ File Uploaders --------------------------------------------------------*/

    // Creation of the file uploaders
    $scope.swedishFileUploader = new FileUploader({ url: 'api/applications/resume', alias: 'newResume' });
    $scope.englishFileUploader = new FileUploader({ url: 'api/applications/resume', alias: 'newResume' });

    // Methods for an pdf uploader
    var pdfFilter = {
      name: 'pdfFilter',
      fn: function (item, options) {
        var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
        return '|pdf|'.indexOf(type) !== -1;
      }
    };

    // Connecting of file uploaders to their methods (filters etc.)
    $scope.swedishFileUploader.filters.push(pdfFilter);

    // Called after the user selected a file
    $scope.swedishFileUploader.onAfterAddingFile = function(fileItem) {
      if ($window.FileReader) {
        var fileReader = new FileReader();
        fileReader.readAsDataURL(fileItem._file);

        fileReader.onload = function (fileReaderEvent) {
          $timeout(function () {
            //$scope.pdfURL = fileReaderEvent.target.result;
          }, 0);
        };
      }
    };

    // Called after the user has successfully uploaded a new resume
    $scope.swedishFileUploader.onSuccessItem = function(fileItem, response, status, headers) {
      // URL to resume put into database
      vm.application.resume.swedishLink = response;
      // Show success message
      $scope.swedishUploadSuccess = true;
      // Clear uploader queue
      $scope.swedishFileUploader.clearQueue();
      return;
    };

    // Resets the upload as unsuccessful
    $scope.swedishUploadUnsuccess = function () {
      $scope.swedishUploadSuccess = false;
    };

    $scope.englishFileUploader.filters.push(pdfFilter);
    // Called after the user selected a file
    $scope.englishFileUploader.onAfterAddingFile = function(fileItem) {
      if ($window.FileReader) {
        var fileReader = new FileReader();
        fileReader.readAsDataURL(fileItem._file);

        fileReader.onload = function (fileReaderEvent) {
          $timeout(function () {
          //$scope.pdfURL = fileReaderEvent.target.result;
          }, 0);
        };
      }
    };

    // Called after the user has successfully uploaded a new resume
    $scope.englishFileUploader.onSuccessItem = function(fileItem, response, status, headers) {
      // URL to resume put into database
      $scope.vm.application.resume.englishLink = response;
      // Show success message
      $scope.englishUploadSuccess = true;
      // Clear uploader queue
      $scope.englishFileUploader.clearQueue();
      return;
    };

    // Resets the upload as unsuccessful
    $scope.englishUploadUnsuccess = function () {
      $scope.englishUploadSuccess = false;
    };

    /*------------------------------ End of File Uploaders --------------------------------------------------------*/

    $scope.removeSwedishResume = function() {
      $scope.vm.application.resume.swedishLink = '';
      $scope.swedishUploadSuccess = false;
    };

    $scope.removeEnglishResume = function() {
      $scope.vm.application.resume.englishLink = '';
      $scope.englishUploadSuccess = false;
    };

    //limit length of 'vm.application.description'
    $scope.monitorLength = function (maxLength) {
      if ($scope.vm.application.description.length > maxLength) {
        $scope.vm.application.description = $scope.vm.application.description.substring(0, maxLength);
      }
    };

    // Remove existing Application
    function remove() {
      if (confirm('Are you sure you want to delete?')) {
        vm.application.$remove($state.go('applications.list'));
      }
    }

    // Resets the upload as unsuccessful
    $scope.unsuccess = function () {
      $scope.success = false;
    };

    // Save Application
    function save(isValid) {
      vm.error = false;
      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'vm.form.applicationForm');
        vm.error = 'Du har inte fyllt i alla fält / You need to fill all fields';
        return false;
      } else if (vm.application.resume === undefined ||
        (vm.application.resume.englishLink === undefined && vm.application.resume.swedishLink === undefined) ||
        (vm.application.resume.englishLink === '' && vm.application.resume.swedishLink === undefined) ||
        (vm.application.resume.englishLink === undefined && vm.application.resume.swedishLink === '') ||
        (vm.application.resume.englishLink === '' && vm.application.resume.swedishLink === '')) {
        vm.error = 'Du måste bifoga minst ett CV / You must attach at least one resume';
        return false;
      } else if (vm.application.companies === undefined || vm.application.companies.length === 0) {
        vm.error = 'Du måste välja minst ett företag / You must choose at least one company';
        return false;
      } else if (vm.application.times === undefined || vm.application.times.length === 0) {
        vm.error = 'Du måste välja minst en tid / You must tell when you are available';
        return false;
      }

      // TODO: move create/update logic to service
      if (vm.application._id) {
        vm.application.$update(successCallback, errorCallback);
      } else {
        vm.application.$save(successCallback, errorCallback);
      }

      function successCallback(res) {
        if(vm.createMode){
          $state.go('applications.submitted', { name: vm.application.name, email: vm.application.email });
        } else {
          $state.go('applications.view', { applicationId: res._id });
        }
      }

      function errorCallback(res) {
        vm.error = res.data.message;
      }
    }

    function prettify(str) {
      return str.replace(/\s/g, '')
        .replace(/å/g, 'a')
        .replace(/Å/g, 'A')
        .replace(/ä/g, 'a')
        .replace(/Ä/g, 'A')
        .replace(/ö/g, 'o')
        .replace(/Ö/g, 'O');
    }

    // Angular needs to complete rendering before applying 'chosen'
    $timeout(function () {
      // Chosen methods
      $('.program_select_box').chosen({
        no_results_text: 'Oops, nothing found!',
        width: '100%'
      });
      $('.company_select_box').chosen({
        no_results_text: 'Oops, nothing found!',
        width: '100%'
      });
      $('.time_select_box').chosen({
        no_results_text: 'Oops, nothing found!',
        width: '100%'
      });
      $('.year_select_box').chosen({
        no_results_text: 'Oops, nothing found!',
        width: '100%'
      });
    }, 0, false);

    $('.program_select_box').on('change', function(evt, params) {
      vm.application.program = $scope.programs[params.selected];
      $scope.$apply();
    });

    $('.company_select_box').on('change', function(evt, params) {
      var element = $('.company_select_box');
      if(params.selected){
        vm.application.companies.push($scope.companyNames[params.selected]);
      } else if(params.deselected) {
        var position = vm.application.companies.indexOf($scope.companyNames[params.deselected]);
        vm.application.companies.splice(position, 1);
      }
      $scope.$apply();
    });

    $('.time_select_box').on('change', function(evt, params) {
      var element = $('.time_select_box');
      if(params.selected){
        vm.application.times.push($scope.times[params.selected]);
      } else if(params.deselected) {
        var position = vm.application.times.indexOf($scope.times[params.deselected]);
        vm.application.times.splice(position, 1);
      }
      $scope.$apply();
    });

    $('.year_select_box').on('change', function(evt, params) {
      vm.application.year = parseInt(params.selected) + 1;
      $scope.$apply();
    });
  }
})();
<|endoftext|>