<commit_before>var Ui = {
  initialize: function() {
    if(typeof(Effects) !== 'undefined'){
      Effects.initialize();
    }
    var quick_question = $('.quick_question');
    quick_question.find('.buttons-quickq').hide();
    quick_question.find('form input[type=text]').focus(function(){
      quick_question.find('.buttons-quickq').show();
    });

    if(Ui.supports_input_placeholder()) {
      $('.hideifplaceholder').remove();
    };

    $('.langbox.jshide').hide();
    $('.show-more-lang').click(function(){
        $('.langbox.jshide').toggle();
        return false;
    });

      $('.lang-option').click(function(){
        var path = $('#lang-select-toggle').data('language');
        var language = $(this).data('language');
        console.log(path, language)
        $.ajax({type: 'POST', url: path,
                data: {'language[filter]': language},
                success: function(){window.location.reload()}
               });
      });

    $('#openid_url').parents('form').submit(function(){
      var openid = $('#openid_url').val();
      openid = openid.replace('http://','');
      openid = openid.replace('https://','');
      $('#openid_url').val(openid)
    })

    Ui.sort_values('#group_language', 'option', ':last', 'text', null);
    Ui.sort_values('#user_language', 'option',  false, 'text', null);
    Ui.sort_values('#lang_opts', '.radio_option', false, 'attr', 'id');
    Ui.sort_values('select#question_language', 'option', false, 'text', null);

    $(document.body).delegate("#ask_question", "submit", function(event) {
        if(Ui.offline()){
            Auth.startLoginDialog();
            return false;
        }
    });
    $(document.body).delegate("#join_dialog_link", "click", function(event) {
      Groups.join(this);
      return false;
    });
    $(document.body).delegate(".join_group", "click", function(event) {
      if(!$(this).hasClass('email')){
        Auth.startLoginDialog($(this).text(),1);
        return false;
      } else {document.location=$(this).attr('href')}
    })
    $(document.body).delegate(".toggle-action,.not_member", "click", function(event) {
      if(Ui.offline()){
        Auth.startLoginDialog();
      } else {
        var link = $(this);
        if(!link.hasClass('busy')){
          link.addClass('busy');
          var href = link.attr("href");
          var dataUndo = link.attr("data-undo");
          var title = link.attr("title");
          var dataTitle = link.attr("data-title");
          var img = link.children('img');
          var counter = $(link.attr('data-counter'));
          var text = link.text();
          var dataText = link.attr("data-text");
          var dataMethod = link.attr("data-method");
          var csrf = $('meta[name="csrf-token"]').attr('content');
          if(dataMethod == 'post'){
            $.ajax({url: href, headers:{'X-CSRF-Token': csrf}, data: {'authenticity_token': csrf}, dataType: "json", type: "post", success: function(data){
              if(data.success){
                link.attr({href: dataUndo, 'data-undo': href, title: dataTitle, 'data-title': title, 'data-text': text });
                if(dataText && $.trim(dataText)!='')
                  link.text(dataText);
                img.attr({src: img.attr('data-src'), 'data-src': img.attr('src')});
                if(typeof(data.increment)!='undefined'){
                  counter.text(parseFloat($.trim(counter.text()))+data.increment);
                }
                Messages.show(data.message, "notice");
              } else {
                Messages.show(data.message, "error");

                if(data.status == "unauthenticate") {
                  window.onbeforeunload = null;
                  window.location="/users/login";
                }
              }
              link.removeClass('busy');
            }});
          } else {
            $.getJSON(href, {format: "js"}, function(data){
              if(data.success){
                link.attr({href: dataUndo, 'data-undo': href, title: dataTitle, 'data-title': title, 'data-text': text });
                if(dataText && $.trim(dataText)!='')
                  link.text(dataText);
                img.attr({src: img.attr('data-src'), 'data-src': img.attr('src')});
                if(typeof(data.increment)!='undefined'){
                  counter.text(parseFloat($.trim(counter.text()))+data.increment);
                }
                Messages.show(data.message, "notice");
              } else {
                Messages.show(data.message, "error");

                if(data.status == "unauthenticate") {
                  window.onbeforeunload = null;
                  window.location="/users/login";
                }
              }
              link.removeClass('busy');
            }, "json");
          }
        }
      }
      return false;
    });
    Form.initialize();
  },
  initialize_feedback: function() {
    $("#feedbackform").dialog({ title: "Feedback", autoOpen: false, modal: true, width:"420px" });
    $('#feedbackform .cancel-feedback').click(function(){
      $("#feedbackform").dialog('close');
      return false;
    });
    $('#feedback').click(function(){
      var isOpen = $("#feedbackform").dialog('isOpen');
      if (isOpen){
        $("#feedbackform").dialog('close');
      } else {
        $("#feedbackform").dialog('open');
      }
      return false;
    });
  },
  supports_input_placeholder: function() {
    var i = document.createElement('input');
    return 'placeholder' in i;
  },
  sort_values: function(selectID, child, keepers, method, arg) {
    if(keepers){
      var any = $(selectID+' '+child+keepers);
      any.remove();
    }
    var sortedVals = $.makeArray($(selectID+' '+child)).sort(function(a,b){
      return $(a)[method](arg) > $(b)[method](arg) ? 1: -1;
    });
    $(selectID).html(sortedVals);
    if(keepers)
      $(selectID).prepend(any);
    // needed for firefox:
    $(selectID).val($(selectID+' '+child+'[selected=selected]').val());
  },
  offline: function(){
    return $('.offline').length>0 || Ui.not_member()
  },
  not_member: function(){
    return $('.not_member').length>0
  },
  center_scroll: function(tag, container){
    container = container || $('html,body');
    viewportHeight = $(window).height();
    if(window.innerHeight)
      viewportHeight = window.innerHeight;

    var top = tag.offset().top - (viewportHeight/2.0);

    container.scrollTop(top);
  },
  navigate_shortcuts: function(container, element_selector){
    elements = container.find(element_selector);
    var first_element = elements[0];
    if(first_element) {
      $(first_element).addClass("active");
    }

    container.delegate(element_selector, "click", function(ev) {
      elements.removeClass("active");
      next = $(this);
      next.addClass("active");
    });

    $(document).keydown(function(ev){

      if(container.is(':visible')){
        current_element = $(container.find(element_selector+'.active'));

        moved = false;
        next = null;
        if(ev.keyCode == 74){
          next = current_element.next(element_selector);
        } else if(ev.keyCode == 75){
          next = current_element.prev(element_selector);
        }

        if(next && next.length > 0) {
          current_element.removeClass("active");
          next.addClass("active");
          Ui.center_scroll(next);
        }
      }
    });
  },
  initialize_lang_fields: function(container){
    var fields = (container||$('body')).find('.lang-fields');
    if(fields.length > 0){
      fields.tabs();
    }
  }
};
<commit_msg>remove a console.log<commit_after>var Ui = {
  initialize: function() {
    if(typeof(Effects) !== 'undefined'){
      Effects.initialize();
    }
    var quick_question = $('.quick_question');
    quick_question.find('.buttons-quickq').hide();
    quick_question.find('form input[type=text]').focus(function(){
      quick_question.find('.buttons-quickq').show();
    });

    if(Ui.supports_input_placeholder()) {
      $('.hideifplaceholder').remove();
    };

    $('.langbox.jshide').hide();
    $('.show-more-lang').click(function(){
        $('.langbox.jshide').toggle();
        return false;
    });

      $('.lang-option').click(function(){
        var path = $('#lang-select-toggle').data('language');
        var language = $(this).data('language');
        $.ajax({type: 'POST', url: path,
                data: {'language[filter]': language},
                success: function(){window.location.reload()}
               });
      });

    $('#openid_url').parents('form').submit(function(){
      var openid = $('#openid_url').val();
      openid = openid.replace('http://','');
      openid = openid.replace('https://','');
      $('#openid_url').val(openid)
    })

    Ui.sort_values('#group_language', 'option', ':last', 'text', null);
    Ui.sort_values('#user_language', 'option',  false, 'text', null);
    Ui.sort_values('#lang_opts', '.radio_option', false, 'attr', 'id');
    Ui.sort_values('select#question_language', 'option', false, 'text', null);

    $(document.body).delegate("#ask_question", "submit", function(event) {
        if(Ui.offline()){
            Auth.startLoginDialog();
            return false;
        }
    });
    $(document.body).delegate("#join_dialog_link", "click", function(event) {
      Groups.join(this);
      return false;
    });
    $(document.body).delegate(".join_group", "click", function(event) {
      if(!$(this).hasClass('email')){
        Auth.startLoginDialog($(this).text(),1);
        return false;
      } else {document.location=$(this).attr('href')}
    })
    $(document.body).delegate(".toggle-action,.not_member", "click", function(event) {
      if(Ui.offline()){
        Auth.startLoginDialog();
      } else {
        var link = $(this);
        if(!link.hasClass('busy')){
          link.addClass('busy');
          var href = link.attr("href");
          var dataUndo = link.attr("data-undo");
          var title = link.attr("title");
          var dataTitle = link.attr("data-title");
          var img = link.children('img');
          var counter = $(link.attr('data-counter'));
          var text = link.text();
          var dataText = link.attr("data-text");
          var dataMethod = link.attr("data-method");
          var csrf = $('meta[name="csrf-token"]').attr('content');
          if(dataMethod == 'post'){
            $.ajax({url: href, headers:{'X-CSRF-Token': csrf}, data: {'authenticity_token': csrf}, dataType: "json", type: "post", success: function(data){
              if(data.success){
                link.attr({href: dataUndo, 'data-undo': href, title: dataTitle, 'data-title': title, 'data-text': text });
                if(dataText && $.trim(dataText)!='')
                  link.text(dataText);
                img.attr({src: img.attr('data-src'), 'data-src': img.attr('src')});
                if(typeof(data.increment)!='undefined'){
                  counter.text(parseFloat($.trim(counter.text()))+data.increment);
                }
                Messages.show(data.message, "notice");
              } else {
                Messages.show(data.message, "error");

                if(data.status == "unauthenticate") {
                  window.onbeforeunload = null;
                  window.location="/users/login";
                }
              }
              link.removeClass('busy');
            }});
          } else {
            $.getJSON(href, {format: "js"}, function(data){
              if(data.success){
                link.attr({href: dataUndo, 'data-undo': href, title: dataTitle, 'data-title': title, 'data-text': text });
                if(dataText && $.trim(dataText)!='')
                  link.text(dataText);
                img.attr({src: img.attr('data-src'), 'data-src': img.attr('src')});
                if(typeof(data.increment)!='undefined'){
                  counter.text(parseFloat($.trim(counter.text()))+data.increment);
                }
                Messages.show(data.message, "notice");
              } else {
                Messages.show(data.message, "error");

                if(data.status == "unauthenticate") {
                  window.onbeforeunload = null;
                  window.location="/users/login";
                }
              }
              link.removeClass('busy');
            }, "json");
          }
        }
      }
      return false;
    });
    Form.initialize();
  },
  initialize_feedback: function() {
    $("#feedbackform").dialog({ title: "Feedback", autoOpen: false, modal: true, width:"420px" });
    $('#feedbackform .cancel-feedback').click(function(){
      $("#feedbackform").dialog('close');
      return false;
    });
    $('#feedback').click(function(){
      var isOpen = $("#feedbackform").dialog('isOpen');
      if (isOpen){
        $("#feedbackform").dialog('close');
      } else {
        $("#feedbackform").dialog('open');
      }
      return false;
    });
  },
  supports_input_placeholder: function() {
    var i = document.createElement('input');
    return 'placeholder' in i;
  },
  sort_values: function(selectID, child, keepers, method, arg) {
    if(keepers){
      var any = $(selectID+' '+child+keepers);
      any.remove();
    }
    var sortedVals = $.makeArray($(selectID+' '+child)).sort(function(a,b){
      return $(a)[method](arg) > $(b)[method](arg) ? 1: -1;
    });
    $(selectID).html(sortedVals);
    if(keepers)
      $(selectID).prepend(any);
    // needed for firefox:
    $(selectID).val($(selectID+' '+child+'[selected=selected]').val());
  },
  offline: function(){
    return $('.offline').length>0 || Ui.not_member()
  },
  not_member: function(){
    return $('.not_member').length>0
  },
  center_scroll: function(tag, container){
    container = container || $('html,body');
    viewportHeight = $(window).height();
    if(window.innerHeight)
      viewportHeight = window.innerHeight;

    var top = tag.offset().top - (viewportHeight/2.0);

    container.scrollTop(top);
  },
  navigate_shortcuts: function(container, element_selector){
    elements = container.find(element_selector);
    var first_element = elements[0];
    if(first_element) {
      $(first_element).addClass("active");
    }

    container.delegate(element_selector, "click", function(ev) {
      elements.removeClass("active");
      next = $(this);
      next.addClass("active");
    });

    $(document).keydown(function(ev){

      if(container.is(':visible')){
        current_element = $(container.find(element_selector+'.active'));

        moved = false;
        next = null;
        if(ev.keyCode == 74){
          next = current_element.next(element_selector);
        } else if(ev.keyCode == 75){
          next = current_element.prev(element_selector);
        }

        if(next && next.length > 0) {
          current_element.removeClass("active");
          next.addClass("active");
          Ui.center_scroll(next);
        }
      }
    });
  },
  initialize_lang_fields: function(container){
    var fields = (container||$('body')).find('.lang-fields');
    if(fields.length > 0){
      fields.tabs();
    }
  }
};
<|endoftext|>


<commit_before>(function($, window) {

	var methods = {

		init: function(options) {
			var obj = options;
            console.log(obj.$element);
            obj.$element.on('click.cnv', 'a[data-toggle=conversation-reply]', function() {
				$('.ccm-conversation-wrapper').ccmconversationattachments('clearDropzoneQueues');
			});
			obj.$element.on('click.cnv', 'a.attachment-delete', function(event){
				event.preventDefault();
				$(this).ccmconversationattachments('attachmentDeleteTrigger', obj);
			});
            if((obj.$editMessageHolder) && (!(obj.$editMessageHolder.find('.dropzone').attr('data-dropzone-applied')))){
                obj.$editMessageHolder.find('.dropzone').not('[data-drozpone-applied="true"]').dropzone({  // dropzone reply form
                    'url': CCM_TOOLS_PATH + '/conversations/add_file',
                    'success' : function(file, raw) {
                        var self = this;
                        $(file.previewTemplate).click(function(){
                            self.removeFile(file);
                            $('input[rel="'+ $(this).attr('rel') +'"]').remove();
                        });
                        var response = JSON.parse(raw);
                        if(!response.error) {
                            $(this.element).closest('div.ccm-conversation-edit-message').find('form.aux-reply-form').append('<input rel="'+response.timestamp+'" type="hidden" name="attachments[]" value="'+response.id+'" />');
                        } else {
                            var $form = $('.preview.processing[rel="'+response.timestamp+'"]').closest('form');
                            obj.handlePostError($form, [response.error]);
                            $('.preview.processing[rel="'+response.timestamp+'"]').remove();
                            $form.children('.ccm-conversation-errors').delay(3000).fadeOut('slow', function() {
                                $(this).html('');
                            });
                        }
                    },
                    accept: function(file, done) {
                        var errors = [];
                        var attachmentCount = this.files.length;
                        if((obj.options.maxFiles > 0) && attachmentCount > obj.options.maxFiles) {
                            errors.push('Too many files');
                            var maxFilesExceeded = true;
                        }
                        var requiredExtensions = obj.options.fileExtensions.split(',');
                        if(file.name.split('.').pop().toLowerCase() && requiredExtensions.indexOf(file.name.split('.').pop().toLowerCase()) == -1 && requiredExtensions!='') {
                            errors.push('Invalid file extension');
                            var invalidFileExtension = true;
                        }
                        if((obj.options.maxFileSize > 0) && file.size > obj.options.maxFileSize * 1000000) {
                            errors.push('Max file size exceeded');
                            var maxFileSizeExceeded = true;
                        }

                        if(maxFileSizeExceeded || maxFilesExceeded || invalidFileExtension) {
                            var self = this;
                            $('input[rel="'+ $(file.previewTemplate).attr('rel') +'"]').remove();
                            var $form = $(file.previewTemplate).parent('.dropzone');
                            self.removeFile(file);
                            obj.handlePostError($form, errors);
                            $form.children('.ccm-conversation-errors').delay(3000).fadeOut('slow', function() {
                                $(this).html('');
                            });
                            var attachmentCount =- 1;
                            done('error');  // not displayed, just needs to have argument to trigger.
                        } else {
                            done();
                        }
                    },
                    'sending' : function(file, xhr, formData) {
                        $(file.previewTemplate).attr('rel', new Date().getTime());
                        formData.append("timestamp", $(file.previewTemplate).attr('rel'));
                        formData.append("tag", $(obj.$editMessageHOlder).parent('div').attr('rel'));
                        formData.append("fileCount", $(obj.$editMessageHolder).find('[name="attachments[]"]').length);
                    },
                    'init' : function() {
                        $(this.element).data('dropzone',this);
                    }
                });
            }
			if (obj.$newmessageform.dropzone && !($(obj.$newmessageform).attr('data-dropzone-applied'))) {  // dropzone new message form
				obj.$newmessageform.dropzone({
					accept: function(file, done) {
					    var errors = [];
						 var attachmentCount = this.files.length;
						 if((obj.options.maxFiles > 0) && attachmentCount > obj.options.maxFiles) {
						 	errors.push('Too many files');
						 	var maxFilesExceeded = true;
						 }
						 var requiredExtensions = obj.options.fileExtensions.split(',');
						 if(file.name.split('.').pop().toLowerCase() && requiredExtensions.indexOf(file.name.split('.').pop().toLowerCase()) == -1 && requiredExtensions!='') {
						 	errors.push('Invalid file extension');
						 	var invalidFileExtension = true;
						 }
						 if((obj.options.maxFileSize > 0) && file.size > obj.options.maxFileSize * 1000000) {
						 	errors.push('Max file size exceeded');
						 	var maxFileSizeExceeded = true;
						 }

						 if(maxFileSizeExceeded || maxFilesExceeded || invalidFileExtension) {
							var self = this;
							$('input[rel="'+ $(file.previewTemplate).attr('rel') +'"]').remove();
							var $form = $(file.previewTemplate).parent('.dropzone');
							self.removeFile(file);
							obj.handlePostError($form, errors);
							$form.children('.ccm-conversation-errors').delay(3000).fadeOut('slow', function() {
								$(this).html('');
							});
							var attachmentCount =- 1;
							done('error'); // not displayed, just needs to have argument to trigger.
						 } else {
						 	done();
						 }
				 	 },
					'url': CCM_TOOLS_PATH + '/conversations/add_file',
					'success' : function(file, raw) {
						var self = this;
						$(file.previewTemplate).click(function(){
								$('input[rel="'+ $(this).attr('rel') +'"]').remove();
							self.removeFile(file);
						});
						var response = JSON.parse(raw);
						if(!response.error) {
							$('div[rel="' + response.tag + '"] form.main-reply-form').append('<input rel="'+response.timestamp+'" type="hidden" name="attachments[]" value="'+response.id+'" />');
						} else {
							var $form = $('.preview.processing[rel="'+response.timestamp+'"]').closest('form');
							obj.handlePostError($form, [response.error]);
							$('.preview.processing[rel="'+response.timestamp+'"]').remove();
							$form.children('.ccm-conversation-errors').delay(3000).fadeOut('slow', function() {
								$(this).html('');
							});
						}
					},
					'sending' : function(file, xhr, formData) {

						$(file.previewTemplate).attr('rel', new Date().getTime());
						formData.append("timestamp", $(file.previewTemplate).attr('rel'));
						formData.append("tag", $(obj.$newmessageform).parent('div').attr('rel'));
						formData.append("fileCount", this.files.length);
					},
					'init' : function() {
						$(this.element).data('dropzone',this);
					}
				});
				$(obj.$newmessageform).attr('data-dropzone-applied', 'true');
			}

			if(!($(obj.$replyholder.find('.dropzone')).attr('data-dropzone-applied'))){
				obj.$replyholder.find('.dropzone').not('[data-drozpone-applied="true"]').dropzone({  // dropzone reply form
					'url': CCM_TOOLS_PATH + '/conversations/add_file',
					'success' : function(file, raw) {
						var self = this;
						$(file.previewTemplate).click(function(){
							self.removeFile(file);
							$('input[rel="'+ $(this).attr('rel') +'"]').remove();
						});
						var response = JSON.parse(raw);
						if(!response.error) {
							$(this.element).closest('div.ccm-conversation-add-reply').find('form.aux-reply-form').append('<input rel="'+response.timestamp+'" type="hidden" name="attachments[]" value="'+response.id+'" />');
						} else {
							var $form = $('.preview.processing[rel="'+response.timestamp+'"]').closest('form');
							obj.handlePostError($form, [response.error]);
							$('.preview.processing[rel="'+response.timestamp+'"]').remove();
							$form.children('.ccm-conversation-errors').delay(3000).fadeOut('slow', function() {
								$(this).html('');
							});
						}
					},
					accept: function(file, done) {
					    var errors = [];
						 var attachmentCount = this.files.length;
						 if((obj.options.maxFiles > 0) && attachmentCount > obj.options.maxFiles) {
						 	errors.push('Too many files');
						 	var maxFilesExceeded = true;
						 }
						 var requiredExtensions = obj.options.fileExtensions.split(',');
						 if(file.name.split('.').pop().toLowerCase() && requiredExtensions.indexOf(file.name.split('.').pop().toLowerCase()) == -1 && requiredExtensions!='') {
						 	errors.push('Invalid file extension');
						 	var invalidFileExtension = true;
						 }
						 if((obj.options.maxFileSize > 0) && file.size > obj.options.maxFileSize * 1000000) {
						 	errors.push('Max file size exceeded');
						 	var maxFileSizeExceeded = true;
						 }

						 if(maxFileSizeExceeded || maxFilesExceeded || invalidFileExtension) {
							var self = this;
							$('input[rel="'+ $(file.previewTemplate).attr('rel') +'"]').remove();
							var $form = $(file.previewTemplate).parent('.dropzone');
							self.removeFile(file);
							obj.handlePostError($form, errors);
							$form.children('.ccm-conversation-errors').delay(3000).fadeOut('slow', function() {
								$(this).html('');
							});
							var attachmentCount =- 1;
							done('error');  // not displayed, just needs to have argument to trigger.
						 } else {
						 	done();
						 }
				 	 },
					'sending' : function(file, xhr, formData) {
						$(file.previewTemplate).attr('rel', new Date().getTime());
						formData.append("timestamp", $(file.previewTemplate).attr('rel'));
						formData.append("tag", $(obj.$newmessageform).parent('div').attr('rel'));
						formData.append("fileCount", $(obj.$replyHolder).find('[name="attachments[]"]').length);
					},
					'init' : function() {
						$(this.element).data('dropzone',this);
					}
				});
			}
			$(obj.$replyholder.find('.dropzone')).attr('data-dropzone-applied', 'true');
			return $.each($(this), function(i, obj) {
				$(this).find('.ccm-conversation-attachment-container').each(function() {
					if($(this).is(':visible')) {
						$(this).toggle();
					}
				});
			});
         },

		attachmentDeleteTrigger: function(options){
			var obj = options;
			var link = $(this);
			obj.$attachmentdeletetdialog  = obj.$attachmentdeleteholder.clone();
			if (obj.$attachmentdeletetdialog.dialog) {
				obj.$attachmentdeletetdialog.dialog({
					modal: true,
					dialogClass: 'ccm-conversation-dialog',
					title: obj.$attachmentdeletetdialog.attr('data-dialog-title'),
					buttons: [
						{
							'text': obj.$attachmentdeleteholder.attr('data-cancel-button-title'),
							'class': 'btn pull-left',
							'click': function() {
								obj.$attachmentdeletetdialog.dialog('close');
							}
						},
						{
							'text': obj.$attachmentdeleteholder.attr('data-confirm-button-title'),
							'class': 'btn pull-right btn-danger',
							'click': function() {
								$(this).ccmconversationattachments('deleteAttachment',{ 'cnvMessageAttachmentID' : link.attr('rel'), 'cnvObj' : obj, 'dialogObj' : obj.$attachmentdeletetdialog });
							}
						}
					]
				});
			} else {
				if (confirm('Remove this attachment?')) {
					$(this).ccmconversationattachments('deleteAttachment',{ 'cnvMessageAttachmentID' : link.attr('rel'), 'cnvObj' : obj, 'dialogObj' :  obj.$attachmentdeletetdialog});
				}
			}
			return false;
		},

		clearDropzoneQueues : function() {
			$('.preview.processing').each(function(){    // first remove any previous attachments and hide dropzone if it was open.
				$('input[rel="'+ $(this).attr('rel') +'"]').remove();
			});
			$('form.dropzone').each(function(){
				var d = $(this).data('dropzone');
				$.each(d.files,function(k,v){
					d.removeFile(v);
				});
			});
		},

		deleteAttachment: function(options) {
			var cnvMessageAttachmentID = options.cnvMessageAttachmentID;
			var obj = options.cnvObj;
			var attachmentsDialog = options.dialogObj;
			/* var obj = this;
			obj.publish('conversationBeforeDeleteAttachment',{cnvMessageAttachmentID:cnvMessageAttachmentID}); */
			var	formArray = [{
				'name': 'cnvMessageAttachmentID',
				'value': cnvMessageAttachmentID
			}];

			$.ajax({
				type: 'post',
				data: formArray,
				url: CCM_TOOLS_PATH + '/conversations/delete_file',
				success: function(response) {
					var parsedData = JSON.parse(response);
					$('p[rel="'+parsedData.attachmentID+'"]').parent('.attachment-container').fadeOut(300, function() { $(this).remove() });
					if (attachmentsDialog.dialog) {
						attachmentsDialog.dialog('close');
						obj.publish('conversationDeleteAttachment',{cnvMessageAttachmentID:cnvMessageAttachmentID});
					}
				},
				error: function(e) {
					obj.publish('conversationDeleteAttachmentError',{cnvMessageAttachmentID:cnvMessageAttachmentID,error:arguments});
					window.alert('Something went wrong while deleting this attachment, please refresh and try again.');
				}
			});
		}
	}

	$.fn.ccmconversationattachments = function(method) {

		if ( methods[method] ) {
			return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( this, arguments );
		} else {
			$.error( 'Method ' +  method + ' does not exist on ccmconversationattachments' );
		}

	}

})(jQuery, window);
<commit_msg>aaaaaaand remove console log statement<commit_after>(function($, window) {

	var methods = {

		init: function(options) {
			var obj = options;
            obj.$element.on('click.cnv', 'a[data-toggle=conversation-reply]', function() {
				$('.ccm-conversation-wrapper').ccmconversationattachments('clearDropzoneQueues');
			});
			obj.$element.on('click.cnv', 'a.attachment-delete', function(event){
				event.preventDefault();
				$(this).ccmconversationattachments('attachmentDeleteTrigger', obj);
			});
            if((obj.$editMessageHolder) && (!(obj.$editMessageHolder.find('.dropzone').attr('data-dropzone-applied')))){
                obj.$editMessageHolder.find('.dropzone').not('[data-drozpone-applied="true"]').dropzone({  // dropzone reply form
                    'url': CCM_TOOLS_PATH + '/conversations/add_file',
                    'success' : function(file, raw) {
                        var self = this;
                        $(file.previewTemplate).click(function(){
                            self.removeFile(file);
                            $('input[rel="'+ $(this).attr('rel') +'"]').remove();
                        });
                        var response = JSON.parse(raw);
                        if(!response.error) {
                            $(this.element).closest('div.ccm-conversation-edit-message').find('form.aux-reply-form').append('<input rel="'+response.timestamp+'" type="hidden" name="attachments[]" value="'+response.id+'" />');
                        } else {
                            var $form = $('.preview.processing[rel="'+response.timestamp+'"]').closest('form');
                            obj.handlePostError($form, [response.error]);
                            $('.preview.processing[rel="'+response.timestamp+'"]').remove();
                            $form.children('.ccm-conversation-errors').delay(3000).fadeOut('slow', function() {
                                $(this).html('');
                            });
                        }
                    },
                    accept: function(file, done) {
                        var errors = [];
                        var attachmentCount = this.files.length;
                        if((obj.options.maxFiles > 0) && attachmentCount > obj.options.maxFiles) {
                            errors.push('Too many files');
                            var maxFilesExceeded = true;
                        }
                        var requiredExtensions = obj.options.fileExtensions.split(',');
                        if(file.name.split('.').pop().toLowerCase() && requiredExtensions.indexOf(file.name.split('.').pop().toLowerCase()) == -1 && requiredExtensions!='') {
                            errors.push('Invalid file extension');
                            var invalidFileExtension = true;
                        }
                        if((obj.options.maxFileSize > 0) && file.size > obj.options.maxFileSize * 1000000) {
                            errors.push('Max file size exceeded');
                            var maxFileSizeExceeded = true;
                        }

                        if(maxFileSizeExceeded || maxFilesExceeded || invalidFileExtension) {
                            var self = this;
                            $('input[rel="'+ $(file.previewTemplate).attr('rel') +'"]').remove();
                            var $form = $(file.previewTemplate).parent('.dropzone');
                            self.removeFile(file);
                            obj.handlePostError($form, errors);
                            $form.children('.ccm-conversation-errors').delay(3000).fadeOut('slow', function() {
                                $(this).html('');
                            });
                            var attachmentCount =- 1;
                            done('error');  // not displayed, just needs to have argument to trigger.
                        } else {
                            done();
                        }
                    },
                    'sending' : function(file, xhr, formData) {
                        $(file.previewTemplate).attr('rel', new Date().getTime());
                        formData.append("timestamp", $(file.previewTemplate).attr('rel'));
                        formData.append("tag", $(obj.$editMessageHOlder).parent('div').attr('rel'));
                        formData.append("fileCount", $(obj.$editMessageHolder).find('[name="attachments[]"]').length);
                    },
                    'init' : function() {
                        $(this.element).data('dropzone',this);
                    }
                });
            }
			if (obj.$newmessageform.dropzone && !($(obj.$newmessageform).attr('data-dropzone-applied'))) {  // dropzone new message form
				obj.$newmessageform.dropzone({
					accept: function(file, done) {
					    var errors = [];
						 var attachmentCount = this.files.length;
						 if((obj.options.maxFiles > 0) && attachmentCount > obj.options.maxFiles) {
						 	errors.push('Too many files');
						 	var maxFilesExceeded = true;
						 }
						 var requiredExtensions = obj.options.fileExtensions.split(',');
						 if(file.name.split('.').pop().toLowerCase() && requiredExtensions.indexOf(file.name.split('.').pop().toLowerCase()) == -1 && requiredExtensions!='') {
						 	errors.push('Invalid file extension');
						 	var invalidFileExtension = true;
						 }
						 if((obj.options.maxFileSize > 0) && file.size > obj.options.maxFileSize * 1000000) {
						 	errors.push('Max file size exceeded');
						 	var maxFileSizeExceeded = true;
						 }

						 if(maxFileSizeExceeded || maxFilesExceeded || invalidFileExtension) {
							var self = this;
							$('input[rel="'+ $(file.previewTemplate).attr('rel') +'"]').remove();
							var $form = $(file.previewTemplate).parent('.dropzone');
							self.removeFile(file);
							obj.handlePostError($form, errors);
							$form.children('.ccm-conversation-errors').delay(3000).fadeOut('slow', function() {
								$(this).html('');
							});
							var attachmentCount =- 1;
							done('error'); // not displayed, just needs to have argument to trigger.
						 } else {
						 	done();
						 }
				 	 },
					'url': CCM_TOOLS_PATH + '/conversations/add_file',
					'success' : function(file, raw) {
						var self = this;
						$(file.previewTemplate).click(function(){
								$('input[rel="'+ $(this).attr('rel') +'"]').remove();
							self.removeFile(file);
						});
						var response = JSON.parse(raw);
						if(!response.error) {
							$('div[rel="' + response.tag + '"] form.main-reply-form').append('<input rel="'+response.timestamp+'" type="hidden" name="attachments[]" value="'+response.id+'" />');
						} else {
							var $form = $('.preview.processing[rel="'+response.timestamp+'"]').closest('form');
							obj.handlePostError($form, [response.error]);
							$('.preview.processing[rel="'+response.timestamp+'"]').remove();
							$form.children('.ccm-conversation-errors').delay(3000).fadeOut('slow', function() {
								$(this).html('');
							});
						}
					},
					'sending' : function(file, xhr, formData) {

						$(file.previewTemplate).attr('rel', new Date().getTime());
						formData.append("timestamp", $(file.previewTemplate).attr('rel'));
						formData.append("tag", $(obj.$newmessageform).parent('div').attr('rel'));
						formData.append("fileCount", this.files.length);
					},
					'init' : function() {
						$(this.element).data('dropzone',this);
					}
				});
				$(obj.$newmessageform).attr('data-dropzone-applied', 'true');
			}

			if(!($(obj.$replyholder.find('.dropzone')).attr('data-dropzone-applied'))){
				obj.$replyholder.find('.dropzone').not('[data-drozpone-applied="true"]').dropzone({  // dropzone reply form
					'url': CCM_TOOLS_PATH + '/conversations/add_file',
					'success' : function(file, raw) {
						var self = this;
						$(file.previewTemplate).click(function(){
							self.removeFile(file);
							$('input[rel="'+ $(this).attr('rel') +'"]').remove();
						});
						var response = JSON.parse(raw);
						if(!response.error) {
							$(this.element).closest('div.ccm-conversation-add-reply').find('form.aux-reply-form').append('<input rel="'+response.timestamp+'" type="hidden" name="attachments[]" value="'+response.id+'" />');
						} else {
							var $form = $('.preview.processing[rel="'+response.timestamp+'"]').closest('form');
							obj.handlePostError($form, [response.error]);
							$('.preview.processing[rel="'+response.timestamp+'"]').remove();
							$form.children('.ccm-conversation-errors').delay(3000).fadeOut('slow', function() {
								$(this).html('');
							});
						}
					},
					accept: function(file, done) {
					    var errors = [];
						 var attachmentCount = this.files.length;
						 if((obj.options.maxFiles > 0) && attachmentCount > obj.options.maxFiles) {
						 	errors.push('Too many files');
						 	var maxFilesExceeded = true;
						 }
						 var requiredExtensions = obj.options.fileExtensions.split(',');
						 if(file.name.split('.').pop().toLowerCase() && requiredExtensions.indexOf(file.name.split('.').pop().toLowerCase()) == -1 && requiredExtensions!='') {
						 	errors.push('Invalid file extension');
						 	var invalidFileExtension = true;
						 }
						 if((obj.options.maxFileSize > 0) && file.size > obj.options.maxFileSize * 1000000) {
						 	errors.push('Max file size exceeded');
						 	var maxFileSizeExceeded = true;
						 }

						 if(maxFileSizeExceeded || maxFilesExceeded || invalidFileExtension) {
							var self = this;
							$('input[rel="'+ $(file.previewTemplate).attr('rel') +'"]').remove();
							var $form = $(file.previewTemplate).parent('.dropzone');
							self.removeFile(file);
							obj.handlePostError($form, errors);
							$form.children('.ccm-conversation-errors').delay(3000).fadeOut('slow', function() {
								$(this).html('');
							});
							var attachmentCount =- 1;
							done('error');  // not displayed, just needs to have argument to trigger.
						 } else {
						 	done();
						 }
				 	 },
					'sending' : function(file, xhr, formData) {
						$(file.previewTemplate).attr('rel', new Date().getTime());
						formData.append("timestamp", $(file.previewTemplate).attr('rel'));
						formData.append("tag", $(obj.$newmessageform).parent('div').attr('rel'));
						formData.append("fileCount", $(obj.$replyHolder).find('[name="attachments[]"]').length);
					},
					'init' : function() {
						$(this.element).data('dropzone',this);
					}
				});
			}
			$(obj.$replyholder.find('.dropzone')).attr('data-dropzone-applied', 'true');
			return $.each($(this), function(i, obj) {
				$(this).find('.ccm-conversation-attachment-container').each(function() {
					if($(this).is(':visible')) {
						$(this).toggle();
					}
				});
			});
         },

		attachmentDeleteTrigger: function(options){
			var obj = options;
			var link = $(this);
			obj.$attachmentdeletetdialog  = obj.$attachmentdeleteholder.clone();
			if (obj.$attachmentdeletetdialog.dialog) {
				obj.$attachmentdeletetdialog.dialog({
					modal: true,
					dialogClass: 'ccm-conversation-dialog',
					title: obj.$attachmentdeletetdialog.attr('data-dialog-title'),
					buttons: [
						{
							'text': obj.$attachmentdeleteholder.attr('data-cancel-button-title'),
							'class': 'btn pull-left',
							'click': function() {
								obj.$attachmentdeletetdialog.dialog('close');
							}
						},
						{
							'text': obj.$attachmentdeleteholder.attr('data-confirm-button-title'),
							'class': 'btn pull-right btn-danger',
							'click': function() {
								$(this).ccmconversationattachments('deleteAttachment',{ 'cnvMessageAttachmentID' : link.attr('rel'), 'cnvObj' : obj, 'dialogObj' : obj.$attachmentdeletetdialog });
							}
						}
					]
				});
			} else {
				if (confirm('Remove this attachment?')) {
					$(this).ccmconversationattachments('deleteAttachment',{ 'cnvMessageAttachmentID' : link.attr('rel'), 'cnvObj' : obj, 'dialogObj' :  obj.$attachmentdeletetdialog});
				}
			}
			return false;
		},

		clearDropzoneQueues : function() {
			$('.preview.processing').each(function(){    // first remove any previous attachments and hide dropzone if it was open.
				$('input[rel="'+ $(this).attr('rel') +'"]').remove();
			});
			$('form.dropzone').each(function(){
				var d = $(this).data('dropzone');
				$.each(d.files,function(k,v){
					d.removeFile(v);
				});
			});
		},

		deleteAttachment: function(options) {
			var cnvMessageAttachmentID = options.cnvMessageAttachmentID;
			var obj = options.cnvObj;
			var attachmentsDialog = options.dialogObj;
			/* var obj = this;
			obj.publish('conversationBeforeDeleteAttachment',{cnvMessageAttachmentID:cnvMessageAttachmentID}); */
			var	formArray = [{
				'name': 'cnvMessageAttachmentID',
				'value': cnvMessageAttachmentID
			}];

			$.ajax({
				type: 'post',
				data: formArray,
				url: CCM_TOOLS_PATH + '/conversations/delete_file',
				success: function(response) {
					var parsedData = JSON.parse(response);
					$('p[rel="'+parsedData.attachmentID+'"]').parent('.attachment-container').fadeOut(300, function() { $(this).remove() });
					if (attachmentsDialog.dialog) {
						attachmentsDialog.dialog('close');
						obj.publish('conversationDeleteAttachment',{cnvMessageAttachmentID:cnvMessageAttachmentID});
					}
				},
				error: function(e) {
					obj.publish('conversationDeleteAttachmentError',{cnvMessageAttachmentID:cnvMessageAttachmentID,error:arguments});
					window.alert('Something went wrong while deleting this attachment, please refresh and try again.');
				}
			});
		}
	}

	$.fn.ccmconversationattachments = function(method) {

		if ( methods[method] ) {
			return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( this, arguments );
		} else {
			$.error( 'Method ' +  method + ' does not exist on ccmconversationattachments' );
		}

	}

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


<commit_before>'use strict';

require('should');
var request = require('supertest');

var AnyFetchProvider = require('../../lib/');
var Token = require('../../lib/models/token.js');
var helpers = require('./helpers');

var connectFunctions = helpers.connectFunctions;
var workersFile = helpers.workersFile;
var updateFile = helpers.updateFile;
var config = helpers.config;

describe("POST /update endpoint", function() {
  var updateServer = function(server, identifier, done) {
    if(!done) {
      done = function(err) {
        if(err) {
          throw err;
        }
      };
    }

    request(server).post('/update' + (identifier ? '/' + identifier : ''))
      .send({
        access_token: server.token,
        api_url: 'http://api.anyfetch.com',
        documents_per_update: 100,
        force: server.force
      })
      .expect(202)
      .end(done);
  };

  var token;

  beforeEach(AnyFetchProvider.debug.cleanTokens);

  beforeEach(function createToken1(done) {
    // Create a token, as-if /init/ workflow was properly done
    token = new Token({
      anyfetchToken: 'thetoken',
      data: {
        foo: 'bar'
      },
      accountName: 'test@anyfetch.com'
    });

    token.save(done);
  });

  beforeEach(function createToken2(done) {
    // Create a token, as-if /init/ workflow was properly done
    token = new Token({
      anyfetchToken: 'thetoken2',
      data: {
        foo: 'bar'
      },
      accountName: 'test@anyfetch.com',
      isUpdating: true,
      lastUpdate: new Date()
    });

    token.save(done);
  });

  beforeEach(function createToken3(done) {
    // Create a token, as-if /init/ workflow was properly done
    token = new Token({
      anyfetchToken: 'thetoken3',
      data: {
        foo: 'bar'
      },
      accountName: 'test@anyfetch.com',
      isUpdating: true,
      lastUpdate: new Date(Date.now() - 5 * 3600 * 1000 - 1)
    });

    token.save(done);
  });

  it("should require access_token to update", function(done) {
    var server = AnyFetchProvider.createServer(connectFunctions, workersFile, updateFile, config);

    request(server)
      .post('/update')
      .send({
        api_url: process.env.ANYFETCH_MANAGER_URL,
        documents_per_update: 100
      })
      .expect(409)
      .expect(/access_token/)
      .end(done);
  });

  it("should require documents_per_update to update", function(done) {
    var server = AnyFetchProvider.createServer(connectFunctions, workersFile, updateFile, config);

    request(server)
      .post('/update')
      .send({
        access_token: 'thetoken',
        api_url: 'http://api.anyfetch.com',
      })
      .expect(409)
      .expect(/documents_per_update/)
      .end(done);
  });

  it("should require valid access_token to update", function(done) {
    var server = AnyFetchProvider.createServer(connectFunctions, workersFile, updateFile, config);

    request(server)
      .post('/update')
      .send({
        access_token: 'dummy_access_token',
        api_url: 'http://api.anyfetch.com',
        documents_per_update: 100
      })
      .expect(404)
      .end(done);
  });

  it("should require isUpdating to false to update", function(done) {
    var server = AnyFetchProvider.createServer(connectFunctions, workersFile, updateFile, config);

    request(server)
      .post('/update')
      .send({
        access_token: 'thetoken2',
        api_url: 'http://api.anyfetch.com',
        documents_per_update: 100
      })
      .expect(429)
      .end(done);
  });

  it("should update with isUpdating to true and force", function(done) {
    var server = AnyFetchProvider.createServer(connectFunctions, __dirname + '/../helpers/workers-test.js', __dirname + '/../helpers/update-test.js', config);

    server.token = 'thetoken2';
    server.force = true;

    updateServer(server, null, function(err) {
      if(err) {
        return done(err);
      }

      server.usersQueue.once('empty', function() {
        done();
      });
    });
  });

  it("should update with isUpdating to true and a good lastUpdate", function(done) {
    var server = AnyFetchProvider.createServer(connectFunctions, __dirname + '/../helpers/workers-test.js', __dirname + '/../helpers/update-test.js', config);

    server.token = 'thetoken3';

    updateServer(server, null, function(err) {
      if(err) {
        return done(err);
      }

      server.usersQueue.once('empty', function() {
        done();
      });
    });
  });

  it("should retrieve tasks and upload them", function(done) {
    this.timeout(10000);

    var counter = 0;
    var server = AnyFetchProvider.createServer(connectFunctions, __dirname + '/../helpers/workers-test-1.js', __dirname + '/../helpers/update-test.js', config);

    server.token = 'thetoken';
    server.force = false;

    server.usersQueue.on('job.task.completed', function() {
      counter += 1;
    });

    server.usersQueue.on('job.task.failed', function(job, err) {
      done(err);
    });

    server.usersQueue.on('job.update.failed', function(job, err) {
      done(err);
    });

    updateServer(server, null, function(err) {
      if(err) {
        return done(err);
      }

      server.usersQueue.once('empty', function() {
        server.usersQueue.removeAllListeners();
        counter.should.eql(3);
        done();
      });
    });
  });

  it("should retrieve tasks and upload just one task", function(done) {
    var counter = 0;
    var server = AnyFetchProvider.createServer(connectFunctions, __dirname + '/../helpers/workers-test-2.js', __dirname + '/../helpers/update-test.js', config);

    server.token = 'thetoken';
    server.force = false;

    server.usersQueue.on('job.task.completed', function() {
      counter += 1;
    });

    server.usersQueue.on('job.task.failed', function(job, err) {
      done(err);
    });

    server.usersQueue.on('job.update.failed', function(job, err) {
      done(err);
    });

    updateServer(server, 'b', function(err) {
      if(err) {
        return done(err);
      }

      server.usersQueue.once('empty', function() {
        server.usersQueue.removeAllListeners();
        counter.should.eql(1);
        done();
      });
    });
  });

  it("should allow to update token data", function(done) {
    var counter = 0;
    var server = AnyFetchProvider.createServer(connectFunctions, __dirname + '/../helpers/workers-test-3.js', __dirname + '/../helpers/update-test.js', config);

    server.token = 'thetoken';
    server.force = false;

    server.usersQueue.on('job.task.completed', function() {
      counter += 1;
    });

    server.usersQueue.on('job.task.failed', function(job, err) {
      done(err);
    });

    server.usersQueue.on('job.update.failed', function(job, err) {
      done(err);
    });

    updateServer(server, null, function(err) {
      if(err) {
        return done(err);
      }

      server.usersQueue.once('empty', function() {
        server.usersQueue.removeAllListeners();
        counter.should.eql(3);
        done();
      });
    });
  });
});
<commit_msg>Don't use ANYFETCH_MANAGER_URL<commit_after>'use strict';

require('should');
var request = require('supertest');

var AnyFetchProvider = require('../../lib/');
var Token = require('../../lib/models/token.js');
var helpers = require('./helpers');

var connectFunctions = helpers.connectFunctions;
var workersFile = helpers.workersFile;
var updateFile = helpers.updateFile;
var config = helpers.config;

describe("POST /update endpoint", function() {
  var updateServer = function(server, identifier, done) {
    if(!done) {
      done = function(err) {
        if(err) {
          throw err;
        }
      };
    }

    request(server).post('/update' + (identifier ? '/' + identifier : ''))
      .send({
        access_token: server.token,
        api_url: 'http://api.anyfetch.com',
        documents_per_update: 100,
        force: server.force
      })
      .expect(202)
      .end(done);
  };

  var token;

  beforeEach(AnyFetchProvider.debug.cleanTokens);

  beforeEach(function createToken1(done) {
    // Create a token, as-if /init/ workflow was properly done
    token = new Token({
      anyfetchToken: 'thetoken',
      data: {
        foo: 'bar'
      },
      accountName: 'test@anyfetch.com'
    });

    token.save(done);
  });

  beforeEach(function createToken2(done) {
    // Create a token, as-if /init/ workflow was properly done
    token = new Token({
      anyfetchToken: 'thetoken2',
      data: {
        foo: 'bar'
      },
      accountName: 'test@anyfetch.com',
      isUpdating: true,
      lastUpdate: new Date()
    });

    token.save(done);
  });

  beforeEach(function createToken3(done) {
    // Create a token, as-if /init/ workflow was properly done
    token = new Token({
      anyfetchToken: 'thetoken3',
      data: {
        foo: 'bar'
      },
      accountName: 'test@anyfetch.com',
      isUpdating: true,
      lastUpdate: new Date(Date.now() - 5 * 3600 * 1000 - 1)
    });

    token.save(done);
  });

  it("should require access_token to update", function(done) {
    var server = AnyFetchProvider.createServer(connectFunctions, workersFile, updateFile, config);

    request(server)
      .post('/update')
      .send({
        api_url: 'http://api.anyfetch.com',
        documents_per_update: 100
      })
      .expect(409)
      .expect(/access_token/)
      .end(done);
  });

  it("should require documents_per_update to update", function(done) {
    var server = AnyFetchProvider.createServer(connectFunctions, workersFile, updateFile, config);

    request(server)
      .post('/update')
      .send({
        access_token: 'thetoken',
        api_url: 'http://api.anyfetch.com',
      })
      .expect(409)
      .expect(/documents_per_update/)
      .end(done);
  });

  it("should require valid access_token to update", function(done) {
    var server = AnyFetchProvider.createServer(connectFunctions, workersFile, updateFile, config);

    request(server)
      .post('/update')
      .send({
        access_token: 'dummy_access_token',
        api_url: 'http://api.anyfetch.com',
        documents_per_update: 100
      })
      .expect(404)
      .end(done);
  });

  it("should require isUpdating to false to update", function(done) {
    var server = AnyFetchProvider.createServer(connectFunctions, workersFile, updateFile, config);

    request(server)
      .post('/update')
      .send({
        access_token: 'thetoken2',
        api_url: 'http://api.anyfetch.com',
        documents_per_update: 100
      })
      .expect(429)
      .end(done);
  });

  it("should update with isUpdating to true and force", function(done) {
    var server = AnyFetchProvider.createServer(connectFunctions, __dirname + '/../helpers/workers-test.js', __dirname + '/../helpers/update-test.js', config);

    server.token = 'thetoken2';
    server.force = true;

    updateServer(server, null, function(err) {
      if(err) {
        return done(err);
      }

      server.usersQueue.once('empty', function() {
        done();
      });
    });
  });

  it("should update with isUpdating to true and a good lastUpdate", function(done) {
    var server = AnyFetchProvider.createServer(connectFunctions, __dirname + '/../helpers/workers-test.js', __dirname + '/../helpers/update-test.js', config);

    server.token = 'thetoken3';

    updateServer(server, null, function(err) {
      if(err) {
        return done(err);
      }

      server.usersQueue.once('empty', function() {
        done();
      });
    });
  });

  it("should retrieve tasks and upload them", function(done) {
    this.timeout(10000);

    var counter = 0;
    var server = AnyFetchProvider.createServer(connectFunctions, __dirname + '/../helpers/workers-test-1.js', __dirname + '/../helpers/update-test.js', config);

    server.token = 'thetoken';
    server.force = false;

    server.usersQueue.on('job.task.completed', function() {
      counter += 1;
    });

    server.usersQueue.on('job.task.failed', function(job, err) {
      done(err);
    });

    server.usersQueue.on('job.update.failed', function(job, err) {
      done(err);
    });

    updateServer(server, null, function(err) {
      if(err) {
        return done(err);
      }

      server.usersQueue.once('empty', function() {
        server.usersQueue.removeAllListeners();
        counter.should.eql(3);
        done();
      });
    });
  });

  it("should retrieve tasks and upload just one task", function(done) {
    var counter = 0;
    var server = AnyFetchProvider.createServer(connectFunctions, __dirname + '/../helpers/workers-test-2.js', __dirname + '/../helpers/update-test.js', config);

    server.token = 'thetoken';
    server.force = false;

    server.usersQueue.on('job.task.completed', function() {
      counter += 1;
    });

    server.usersQueue.on('job.task.failed', function(job, err) {
      done(err);
    });

    server.usersQueue.on('job.update.failed', function(job, err) {
      done(err);
    });

    updateServer(server, 'b', function(err) {
      if(err) {
        return done(err);
      }

      server.usersQueue.once('empty', function() {
        server.usersQueue.removeAllListeners();
        counter.should.eql(1);
        done();
      });
    });
  });

  it("should allow to update token data", function(done) {
    var counter = 0;
    var server = AnyFetchProvider.createServer(connectFunctions, __dirname + '/../helpers/workers-test-3.js', __dirname + '/../helpers/update-test.js', config);

    server.token = 'thetoken';
    server.force = false;

    server.usersQueue.on('job.task.completed', function() {
      counter += 1;
    });

    server.usersQueue.on('job.task.failed', function(job, err) {
      done(err);
    });

    server.usersQueue.on('job.update.failed', function(job, err) {
      done(err);
    });

    updateServer(server, null, function(err) {
      if(err) {
        return done(err);
      }

      server.usersQueue.once('empty', function() {
        server.usersQueue.removeAllListeners();
        counter.should.eql(3);
        done();
      });
    });
  });
});
<|endoftext|>


<commit_before>/*
 * Copyright 2005-2011 The Kuali Foundation
 *
 * Licensed under the Educational Community License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.opensource.org/licenses/ecl2.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
(function($) {
    $.fn.extend({
        spinit: function(options) {
            var settings = $.extend({ min: 0, max: 100, callback: null, stepInc: 1, pageInc: 10, width: 50, height: 15, btnWidth: 10, mask: '' }, options);
            return this.each(function() {
                var UP = 38;
                var DOWN = 40;
                var PAGEUP = 33;
                var PAGEDOWN = 34;
                var mouseCaptured = false;
                var mouseIn = false;
                var interval;
                var direction = 'none';
                var isPgeInc = false;

                var value = Number($(this).val());
                var el = $(this).css('width', (settings.width) + 'px').css('height', settings.height + 'px').addClass('smartspinner');

				if (settings.initValue) {
				  value = Math.max(settings.initValue, settings.min);
				  $(this).val(value);
                  raiseCallback(value);
				}

                if (settings.mask != '') el.val(settings.mask);
                $.fn.reset = function(val) {
                    if (isNaN(val)) val = 0;
                    value = Math.max(val, settings.min);
                    $(this).val(value);
                    raiseCallback(value);
                };
                function setDirection(dir) {
                    direction = dir;
                    isPgeInc = false;
                    switch (dir) {
                        case 'up':
                            setClass('up');
                            break;
                        case 'down':
                            setClass('down');
                            break;
                        case 'pup':
                            isPgeInc = true;
                            setClass('up');
                            break;
                        case 'pdown':
                            isPgeInc = true;
                            setClass('down');
                            break;
                        case 'none':
                            setClass('');
                            break;
                    }
                }
                el.focusin(function() {
                    el.val(value);
                });
                el.click(function(e) {
                    mouseCaptured = true;
                    isPgeInc = false;
                    clearInterval(interval);
                    onValueChange();
                });
                el.mouseenter(function(e) {
                    el.val(value);
                });
                el.mousemove(function(e) {

                    if (e.pageX > (el.offset().left + settings.width) - settings.btnWidth - 4) {
                        if (e.pageY < el.offset().top + settings.height / 2)
                            setDirection('up');
                        else
                            setDirection('down');
                    }
                    else
                        setDirection('none');
                });
                el.mousedown(function(e) {
                    isPgeInc = false;
                  //  clearInterval(interval);
                   // interval = setInterval(onValueChange, 100);
                });
                el.mouseup(function(e) {
                    mouseCaptured = false;
                    isPgeInc = false;
                  //  clearInterval(interval);

                });
                el.mouseleave(function(e) {
                    setDirection('none');
                    if (settings.mask != '') el.val(settings.mask);
                }); el.keydown(function(e) {
                    switch (e.which) {
                        case UP:
                            setDirection('up');
                            onValueChange();
                            break; // Arrow Up
                        case DOWN:
                            setDirection('down');
                            onValueChange();
                            break; // Arrow Down
                        case PAGEUP:
                            setDirection('pup');
                            onValueChange();
                            break; // Page Up
                        case PAGEDOWN:
                            setDirection('pdown');
                            onValueChange();
                            break; // Page Down
                        default:
                            setDirection('none');
                            break;
                    }
                });

                el.keyup(function(e) {
                    setDirection('none');
                });
                el.keypress(function(e) {
                    if (el.val() == settings.mask) el.val(value);
                    var sText = getSelectedText();
                    if (sText != '') {
                        sText = el.val().replace(sText, '');
                        el.val(sText);
                    }
                    if (e.which >= 48 && e.which <= 57) {
                        var temp = parseFloat(el.val() + (e.which - 48));
                        if (temp >= settings.min && temp <= settings.max) {
                            value = temp;
                            raiseCallback(value);
                        }
                        else {
                            e.preventDefault();
                        }
                    }
                });
                el.blur(function() {
                    if (settings.mask == '') {
                        if (el.val() == '')
                            el.val(settings.min);
                    }
                    else {
                        el.val(settings.mask);
                    }
                });
                el.bind("mousewheel", function(e) {
                    if (e.wheelDelta >= 120) {
                        setDirection('down');
                        onValueChange();
                    }
                    else if (e.wheelDelta <= -120) {
                        setDirection('up');
                        onValueChange();
                    }

                    e.preventDefault();
                });
                if (this.addEventListener) {
                    this.addEventListener('DOMMouseScroll', function(e) {
                        if (e.detail > 0) {
                            setDirection('down');
                            onValueChange();
                        }
                        else if (e.detail < 0) {
                            setDirection('up');
                            onValueChange();
                        }
                        e.preventDefault();
                    }, false);
                }

                function raiseCallback(val) {
                    if (settings.callback != null) settings.callback(val);
                }
                function getSelectedText() {

                    var startPos = el.get(0).selectionStart;
                    var endPos = el.get(0).selectionEnd;
                    var doc = document.selection;

                    if (doc && doc.createRange().text.length != 0) {
                        return doc.createRange().text;
                    } else if (!doc && el.val().substring(startPos, endPos).length != 0) {
                        return el.val().substring(startPos, endPos);
                    }
                    return '';
                }
                function setValue(a, b) {
                    if (a >= settings.min && a <= settings.max) {
                        value = b;
                    } el.val(value);
                }
                function onValueChange() {
                    if (direction == 'up') {
                        value += settings.stepInc;
                        if (value > settings.max) value = settings.max;
                        setValue(parseFloat(el.val()), value);
                    }
                    if (direction == 'down') {
                        value -= settings.stepInc;
                        if (value < settings.min) value = settings.min;
                        setValue(parseFloat(el.val()), value);
                    }
                    if (direction == 'pup') {
                        value += settings.pageInc;
                        if (value > settings.max) value = settings.max;
                        setValue(parseFloat(el.val()), value);
                    }
                    if (direction == 'pdown') {
                        value -= settings.pageInc;
                        if (value < settings.min) value = settings.min;
                        setValue(parseFloat(el.val()), value);
                    }
                    raiseCallback(value);
                }
                function setClass(name) {
                    el.removeClass('up').removeClass('down');
                    if (name != '') el.addClass(name);
                }
            });
        }
    });
})(jQuery);<commit_msg>Fix smartspinner.js header<commit_after>/*
 * Copyright 2006-2011 The Kuali Foundation
 *
 * Licensed under the Educational Community License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.opensource.org/licenses/ecl2.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Copyright 2005-2011 The Kuali Foundation
 *
 * Licensed under the Educational Community License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.opensource.org/licenses/ecl2.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

(function($) {
    $.fn.extend({
        spinit: function(options) {
            var settings = $.extend({ min: 0, max: 100, callback: null, stepInc: 1, pageInc: 10, width: 50, height: 15, btnWidth: 10, mask: '' }, options);
            return this.each(function() {
                var UP = 38;
                var DOWN = 40;
                var PAGEUP = 33;
                var PAGEDOWN = 34;
                var mouseCaptured = false;
                var mouseIn = false;
                var interval;
                var direction = 'none';
                var isPgeInc = false;

                var value = Number($(this).val());
                var el = $(this).css('width', (settings.width) + 'px').css('height', settings.height + 'px').addClass('smartspinner');

				if (settings.initValue) {
				  value = Math.max(settings.initValue, settings.min);
				  $(this).val(value);
                  raiseCallback(value);
				}

                if (settings.mask != '') el.val(settings.mask);
                $.fn.reset = function(val) {
                    if (isNaN(val)) val = 0;
                    value = Math.max(val, settings.min);
                    $(this).val(value);
                    raiseCallback(value);
                };
                function setDirection(dir) {
                    direction = dir;
                    isPgeInc = false;
                    switch (dir) {
                        case 'up':
                            setClass('up');
                            break;
                        case 'down':
                            setClass('down');
                            break;
                        case 'pup':
                            isPgeInc = true;
                            setClass('up');
                            break;
                        case 'pdown':
                            isPgeInc = true;
                            setClass('down');
                            break;
                        case 'none':
                            setClass('');
                            break;
                    }
                }
                el.focusin(function() {
                    el.val(value);
                });
                el.click(function(e) {
                    mouseCaptured = true;
                    isPgeInc = false;
                    clearInterval(interval);
                    onValueChange();
                });
                el.mouseenter(function(e) {
                    el.val(value);
                });
                el.mousemove(function(e) {

                    if (e.pageX > (el.offset().left + settings.width) - settings.btnWidth - 4) {
                        if (e.pageY < el.offset().top + settings.height / 2)
                            setDirection('up');
                        else
                            setDirection('down');
                    }
                    else
                        setDirection('none');
                });
                el.mousedown(function(e) {
                    isPgeInc = false;
                  //  clearInterval(interval);
                   // interval = setInterval(onValueChange, 100);
                });
                el.mouseup(function(e) {
                    mouseCaptured = false;
                    isPgeInc = false;
                  //  clearInterval(interval);

                });
                el.mouseleave(function(e) {
                    setDirection('none');
                    if (settings.mask != '') el.val(settings.mask);
                }); el.keydown(function(e) {
                    switch (e.which) {
                        case UP:
                            setDirection('up');
                            onValueChange();
                            break; // Arrow Up
                        case DOWN:
                            setDirection('down');
                            onValueChange();
                            break; // Arrow Down
                        case PAGEUP:
                            setDirection('pup');
                            onValueChange();
                            break; // Page Up
                        case PAGEDOWN:
                            setDirection('pdown');
                            onValueChange();
                            break; // Page Down
                        default:
                            setDirection('none');
                            break;
                    }
                });

                el.keyup(function(e) {
                    setDirection('none');
                });
                el.keypress(function(e) {
                    if (el.val() == settings.mask) el.val(value);
                    var sText = getSelectedText();
                    if (sText != '') {
                        sText = el.val().replace(sText, '');
                        el.val(sText);
                    }
                    if (e.which >= 48 && e.which <= 57) {
                        var temp = parseFloat(el.val() + (e.which - 48));
                        if (temp >= settings.min && temp <= settings.max) {
                            value = temp;
                            raiseCallback(value);
                        }
                        else {
                            e.preventDefault();
                        }
                    }
                });
                el.blur(function() {
                    if (settings.mask == '') {
                        if (el.val() == '')
                            el.val(settings.min);
                    }
                    else {
                        el.val(settings.mask);
                    }
                });
                el.bind("mousewheel", function(e) {
                    if (e.wheelDelta >= 120) {
                        setDirection('down');
                        onValueChange();
                    }
                    else if (e.wheelDelta <= -120) {
                        setDirection('up');
                        onValueChange();
                    }

                    e.preventDefault();
                });
                if (this.addEventListener) {
                    this.addEventListener('DOMMouseScroll', function(e) {
                        if (e.detail > 0) {
                            setDirection('down');
                            onValueChange();
                        }
                        else if (e.detail < 0) {
                            setDirection('up');
                            onValueChange();
                        }
                        e.preventDefault();
                    }, false);
                }

                function raiseCallback(val) {
                    if (settings.callback != null) settings.callback(val);
                }
                function getSelectedText() {

                    var startPos = el.get(0).selectionStart;
                    var endPos = el.get(0).selectionEnd;
                    var doc = document.selection;

                    if (doc && doc.createRange().text.length != 0) {
                        return doc.createRange().text;
                    } else if (!doc && el.val().substring(startPos, endPos).length != 0) {
                        return el.val().substring(startPos, endPos);
                    }
                    return '';
                }
                function setValue(a, b) {
                    if (a >= settings.min && a <= settings.max) {
                        value = b;
                    } el.val(value);
                }
                function onValueChange() {
                    if (direction == 'up') {
                        value += settings.stepInc;
                        if (value > settings.max) value = settings.max;
                        setValue(parseFloat(el.val()), value);
                    }
                    if (direction == 'down') {
                        value -= settings.stepInc;
                        if (value < settings.min) value = settings.min;
                        setValue(parseFloat(el.val()), value);
                    }
                    if (direction == 'pup') {
                        value += settings.pageInc;
                        if (value > settings.max) value = settings.max;
                        setValue(parseFloat(el.val()), value);
                    }
                    if (direction == 'pdown') {
                        value -= settings.pageInc;
                        if (value < settings.min) value = settings.min;
                        setValue(parseFloat(el.val()), value);
                    }
                    raiseCallback(value);
                }
                function setClass(name) {
                    el.removeClass('up').removeClass('down');
                    if (name != '') el.addClass(name);
                }
            });
        }
    });
})(jQuery);<|endoftext|>


<commit_before>define([
    'flight/lib/component'
], function(
    defineComponent) {
    'use strict';

    return defineComponent(FindPath);

    function FindPath() {
        this.after('initialize', function() {
            this.$node.html('<button class="btn btn-mini btn-primary">Add Vertices</button>');
        });
    }
});
<commit_msg>Show how many vertices will be added<commit_after>define([
    'flight/lib/component',
    'service/longRunningProcess'
], function(
    defineComponent,
    LongRunningProcessService) {
    'use strict';

    var longRunningProcessService = new LongRunningProcessService();

    return defineComponent(FindPath);

    function FindPath() {
        this.after('teardown', function() {
            this.$node.empty();
        });

        this.after('initialize', function() {
            if (_.isNumber(this.attr.process.resultsCount)) {
                this.$node.html('<button class="btn btn-mini btn-primary">Add ' + this.attr.process.resultsCount + ' Vertices</button>');
            }
        });
    }
});
<|endoftext|>


<commit_before>import { expect } from 'chai'

import createSubstyle from '../src/createSubstyle'

describe('chaining', () => {

  it('should select the style definitions for all modifiers substyle calls', function () {
    const myStyle = {
      position: 'absolute',
      '&outer': {
        cursor: 'pointer',
      },
      '&inner': {
        color: 'red',
      },
    }
    const substyle = createSubstyle({ style: myStyle })
    const { style } = substyle('&outer')('&inner')
    expect(style).to.deep.equal({
      position: 'absolute',
      cursor: 'pointer',
      color: 'red',
    })

    const { style: sameStyle } = substyle(['&outer', '&inner'])
    expect(sameStyle).to.deep.equal(style)
  })

})
<commit_msg>added another basic chaining spec<commit_after>import { expect } from 'chai'

import createSubstyle from '../src/createSubstyle'

describe('chaining', () => {

  it('should support chaining calls to selected deeper nested styles', () => {
    const substyle = createSubstyle({
      style: {
        first: {
          color: 'red',
          second: {
            cursor: 'pointer',
          },
        },
      },
    })

    const { style } = substyle('first')('second')
    expect(style).to.deep.equal({
      cursor: 'pointer',
    })
  })

  it('should select the style definitions for all modifiers substyle calls', () => {
    const myStyle = {
      position: 'absolute',
      '&outer': {
        cursor: 'pointer',
      },
      '&inner': {
        color: 'red',
      },
    }
    const substyle = createSubstyle({ style: myStyle })
    const { style } = substyle('&outer')('&inner')
    expect(style).to.deep.equal({
      position: 'absolute',
      cursor: 'pointer',
      color: 'red',
    })

    const { style: sameStyle } = substyle(['&outer', '&inner'])
    expect(sameStyle).to.deep.equal(style)
  })

})
<|endoftext|>