<commit_before>//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require fe/fe.common.js
//= require fe/jquery.scrollTo-min.js
//= require fe/rails.extra.js
//= require fe/jquery.validate.pack.js

// used by answer sheets

(function($) {
  //debugger;
	$(function() {

		$(document).on('click', '.save_button', function() {
			$.fe.pageHandler.savePage($(this).closest('.answer-page'), true);
		});

    //debugger;
		$(document).on('keydown', '#payment_staff_first, #payment_staff_last', function(e) {
      //debugger;
			if (e.which == 13) {
        console.log('staff_search click');
				$('#staff_search').trigger('click');
				return false;
			}

		});
		$(document).on('click', '.reference_send_invite', function() {
            var el = this;
			var data = $(el).closest('form').serializeArray();

			data.push({name: 'answer_sheet_type', value: answer_sheet_type});
      $.ajax({url: $(el).attr('href'), data: data, dataType: 'script',  type: 'POST',
                        beforeSend: function (xhr) {
                            $('body').trigger('ajax:loading', xhr);
                        },
                        complete: function (xhr) {
                            $('body').trigger('ajax:complete', xhr);
                        },
                        error: function (xhr, status, error) {
                            $('body').trigger('ajax:failure', [xhr, status, error]);
                        }
										});
			return false;
		});
		$(document).on('focus', 'textarea[maxlength]', function() {
			var max = parseInt($(this).attr('maxlength'));
			$(this).parent().find('.charsRemaining').html('You have ' + (max - $(this).val().length) + ' characters remaining');
		}).on('keyup', 'textarea[maxlength]', function(){
			var max = parseInt($(this).attr('maxlength'));
			if($(this).val().length > max){
				$(this).val($(this).val().substr(0, $(this).attr('maxlength')));
			}
			$(this).parent().find('.charsRemaining').html('You have ' + (max - $(this).val().length) + ' characters remaining');
		}).on('blur', 'textarea[maxlength]', function() {
			$(this).parent().find('.charsRemaining').html('');
		});

    // Payment submission
    $(document).on('click', '.submit_payment', function() {
      console.log('do .submit_payment')
      var form = $(this).closest('form');
      $.ajax({url: $(this).attr('data-url'), data: form.serializeArray(), type: 'POST', dataType:'script',
             beforeSend: function (xhr) {
               $('body').trigger('ajax:loading', xhr);
             },
             complete: function (xhr) {
               $('body').trigger('ajax:complete', xhr);
             },
             error: function (xhr, status, error) {
               $('body').trigger('ajax:failure', [xhr, status, error]);
             }
      });
      return false;
    });

	});
	$.fe = {};
	$.fe.pageHandler = {
	  initialize : function(page) {
	    this.auto_save_frequency = 30;  // seconds
	    this.timer_id = null;
		  this.suspendLoad = false;

	    this.current_page = page;
			$('#' + page).data('form_data', this.captureForm($('#' + page)));
	    this.registerAutoSave();

	    this.page_validation = {};  // validation objects for each page
	    this.enableValidation(page);

	    // this.background_load = false;
	    // this.final_submission = false;
	  },

	  // swap to a different page
	  showPage : function(page) {
	    // hide the old
	    $('#' + this.current_page + '-li').removeClass('active');
	    $('#' + this.current_page).hide();

			// HACK: Need to clear the main error message when returning to the submit page
			//       It is very confusing to users to be there when they revisit the page
			if ((page=='submit_page') && ($('#submit_message')[0] != null)) $('#submit_message').hide();
			if ((page=='submit_page') && ($('#application_errors')[0] != null)) $('#application_errors').html('');

	    // show the new
			// $('#' + page + '-li').removeClass('incomplete');
			// $('#' + page + '-li').removeClass('valid');
			$('#' + page + '-li').addClass('active');
	    $('#' + page).show();
	    this.current_page = page;
	    this.registerAutoSave(page);
	    this.suspendLoad = false;
	    fixGridColumnWidths();
	  },

	  // callback onSuccess
	  pageLoaded : function(response) {
	    // var response = new String(transport.responseText);
	    var match = response.match(/<div id=\"(.*?)\"/i); // what did I just load? parse out the first div id
	    if( match != null )
	    {
	      var page = match[1];
	      $('#preview').append(response);
	      // if(this.background_load) $('#' + page).hide(); else
				$.fe.pageHandler.showPage(page);  // show after load, unless loading in background
				setUpJsHelpers();
	      $.fe.pageHandler.enableValidation(page);
				// $.fe.pageHandler.validatePage('#' + page);
				$('#' + page).data('form_data', $.fe.pageHandler.captureForm($('#' + page)));
	    }
			$('#page_ajax_spinner').hide();
			$('.reference_send_invite').button();
			updateTotals();
	  },

	  loadPage : function(page, url) {
	    if (!this.suspendLoad) {
				this.suspendLoad = true; // don't load a page if one is currently loading (prevent double-click behavior where two pages end up visible!)

				this.unregisterAutoSave();  // don't auto-save while loading/saving
			      // will register auto-save on new page once loaded/shown

				$.scrollTo('#main');

		    this.validatePage(this.current_page);   // mark current page as valid (or not) as we're leaving

		    this.savePage();

		    if( $.fe.pageHandler.isPageLoaded(page) && page.match('no_cache') == null )   // if already loaded (element exists) excluding pages that need reloading
		    {
		      $.fe.pageHandler.showPage(page);
					$('#page_ajax_spinner').hide();
		    }
		    else
		    {
					$.ajax({
             url: url,
             type: 'GET',
						 data: {'answer_sheet_type':answer_sheet_type},
						 success: $.fe.pageHandler.pageLoaded,
             error: function (xhr, status, error) {
                alert("There was a problem loading that page. We've been notified and will fix it as soon as possible. To work on other pages, please refresh the website.");
								document.location = document.location;
             },
             beforeSend: function (xhr) {
                 $('body').trigger('ajax:loading', xhr);
             },
             complete: function (xhr) {
                 $('body').trigger('ajax:complete', xhr);
             }
         });
		      // new Ajax.Request(url, {asynchronous:true, evalScripts:false, method:'get',
		      //     onSuccess:this.pageLoaded.bind(this)});
		    }
			}
	  },

	  // save form if any changes were made
	  savePage : function(page, force) {
			if (page == null) page = $('#' + this.current_page);
      // don't save more than once per second
      timeNow = new Date();
      if (typeof(lastSave) != "undefined" && lastSave && !force && (timeNow - lastSave < 1000)) {
        return true;
      }
      lastSave = timeNow;
      form_data = this.captureForm(page);
      if( form_data ) {
        if( page.data('form_data') == null || page.data('form_data').data !== form_data.data || force === true) {  // if any changes
          page.data('form_data', form_data);
          $.ajax({url: form_data.url, type: 'put', data: form_data.data,
                 beforeSend: function (xhr) {
                   $('#spinner_' + page.attr('id')).show();
                 },
                 complete: function (xhr) {
                   $('#spinner_' + page.attr('id')).hide();
                 },
                 error: function() {
                   page.data('form_data', null);    // on error, force save for next call to save
                   // WARNING: race conditions with load & show?
                   // sort of a mess if save fails while another page is already loading!!
                 }});
        }
      }
      // Update last saved stamp
    },

		savePages : function(force) {
			$('.answer-page').each(function() {$.fe.pageHandler.savePage($(this), force)})
		},

	  // setup a timer to auto-save (only one timer, for the page being viewed)
	  registerAutoSave: function(page) {
	    this.timer_id = setInterval(this.savePages, this.auto_save_frequency * 1000);
	  },

	  unregisterAutoSave: function() {
	    if( this.timer_id != null )
	    {
	      clearInterval(this.timer_id);
	      this.timer_id = null;
	    }
	  },

	  // serialize form data and extract url to post to
	  captureForm : function(page) {
	    form_el = $('#' + page.attr('id') + '-form');
	    if( form_el[0] == null ) return null;
			return {url: form_el.attr('action'), data: form_el.serialize() + '&answer_sheet_type=' + answer_sheet_type};
	  },

	  // enable form validation (when form is loaded)
	  enableValidation : function(page) {
	    $('#' + page + '-form').validate({onsubmit:false, focusInvalid:true, onfocusout: function(element) { this.element(element);}});
	    // $('#' + page + '-form').valid();
	  },

	  validatePage : function(page) {
			try {
			  var li = $('#' + page + '-li');
			  var form = $('#' + page + '-form');

		    valid = form.valid();
				// Move radio button errors up
				$('input[type=radio].error').closest('tr').addClass('error');
				$('.choice_field input[type=radio].error').removeClass('error')
					.closest('.choice_field')
					.addClass('error');
				$('div.yesno label.error').hide();

		    if(valid)  {
		      el.removeClass('incomplete');
				  el.addClass('complete');
		    } else {
				  el.removeClass('complete');
		      el.addClass('incomplete');
		    }
		    return valid;
			}
			catch(err) {

				// If the user clicks too quickly, sometimes the page element isn't properly defined yet.
				// If we don't catch the error, js stops execution. If we catch it, the user just has to click again.
			}
			$('page_ajax_spinner').hide();
	  },

  // callback when falls to 0 active Ajax requests
  completeAll : function()
  {
		$('#submit_button').attr('disabled', true)
		$('#submit_message').html('');
		$('#submit_message').hide();
		// validate all the pages
  	$('.page_link').each(function(index, page) {
			$.fe.pageHandler.validatePage($(page).attr('data-page-id'));
		});
		var all_valid = ($('#list-pages li.incomplete').length == 0);

		// Make sure any necessary payments are made
		var payments_made = $('.payment_question.required').length == $('.payment').length

		if(  payments_made)
		{
		  this.savePage($('#' + $.fe.pageHandler.current_page));  // in case any input fields on submit_page

		  // submit the application
		  if($('#submit_to')[0] != null)
		  {
		    url = $('#submit_to').val();
			  // clear out pages array to force reload.  This enables "frozen" apps
			  //       immediately after submission - :onSuccess (for USCM which stays in the application vs. redirecting to the dashboard)
			  var curr = $.fe.pageHandler.current_page;
			  $.ajax({url: url, dataType:'script',
			 		data: {answer_sheet_type: answer_sheet_type},
					type:'post',
					beforeSend: function(xhr) {
          	$('body').trigger('ajax:loading', xhr);
					},
					success: function(xhr) {
						$('#list-pages a').each(function() {
						  if ($(this).attr('data-page-id') != curr) $('#' + $(this).attr('data-page-id')).remove();
						})
					},
					complete: function(xhr) {
            $('body').trigger('ajax:complete', xhr);
		  			var btn = $('#submit_button');
						if (btn) { btn.attr('disabled', false); }
					}
				});
		  }
		}
		else
		{
		  // some pages aren't valid
 	    $('#submit_message').html("Please make a payment");
		  $('#submit_message').show();

		  var btn = $('#submit_button'); if (btn) { btn.attr('disabled', false); }
		}
  },

    // is page loaded? (useful for toggling enabled state of questions)
    isPageLoaded : function(page)
    {
      return $('#' + page)[0] != null
    },

    checkConditional : function($element_li) {
      matchable_answers = String($element_li.data('conditional_answer')).split(',').map(function(s) { return s.trim(); })
      if ($element_li.hasClass('fe::choicefield') && $element_li.hasClass('yes-no')) {
        if ($(matchable_answers).filter([1, '1', true, 'true', 'yes']).length > 0) {
          matchable_answers = [1, '1', true, 'true', 'yes'];
        }
        vals = $([$element_li.find("input[type=radio]:checked").val()]);
      } else if ($element_li.hasClass('fe::choicefield') && $element_li.hasClass('checkbox')) {
        vals = $element_li.find("input[type=checkbox]:checked").map(function(i, el) { return $(el).val(); });
      } else {
        vals = $([$element_li.find("input:visible, select:visible").val()]);
      }
      match = $(matchable_answers).filter(vals).length > 0;

      console.log('checkConditional match: ' + match);

      switch ($element_li.data('conditional_type')) {
        case 'Fe::Element':
          if (match) {
            $("#element_" + $element_li.data('conditional_id')).show();
          } else {
            $("#element_" + $element_li.data('conditional_id')).hide();
          }
        case 'Fe::Page':
          li_id = "li#fe_application_" + $element_li.data('application_id') + '-fe_page_' + $element_li.data('conditional_id') + '-li';
          if (match) {
            $(li_id).show();
          } else {
            $(li_id).hide();
          }
      }
    }

  };

  $(document).on('click', "li.conditional input, li.conditional select", function() {
    console.log('click');
    $.fe.pageHandler.checkConditional($(this).closest('li'));
  });
  $(document).on('keyup', "li.conditional input, li.conditional select", function() { $(this).click(); });
  $(document).on('blug', "li.conditional input, li.conditional select", function() { $(this).click(); });
  $(document).on('change', "li.conditional select", function() { $(this).click(); });

})(jQuery);

$(function() {
	fixGridColumnWidths();
});

function updateTotal(id) {
	try {
		total = 0;
		$(".col_" + id ).each(function(e) {
		  total += Number(e.val());
		});
		$('#total_' + id).val(total);
	} catch(e) {}
}

function submitToFrame(id, url)
{
  form = $('<form method="post" action="'+url+'.js" endtype="multipart/form-data"></form>')
  var csrf_token = $('meta[name=csrf-token]').attr('content'),
      csrf_param = $('meta[name=csrf-param]').attr('content'),
			dom_id = '#attachment_field_' + id,
			metadata_input = '<input name="'+csrf_param+'" value="'+csrf_token+'" type="hidden" />',
			file_field = '<input type="file" name="answers['+ id + ']>';
	if ($(dom_id).val() == '')	return;
  form.hide()
      .append(metadata_input)
      .append(file_field)
      .appendTo('body');
	$(dom_id + "-spinner").show();
  form.submit();
	return false
}
<commit_msg>Allow an application to be submitted if they’ve paid too many times.<commit_after>//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require fe/fe.common.js
//= require fe/jquery.scrollTo-min.js
//= require fe/rails.extra.js
//= require fe/jquery.validate.pack.js

// used by answer sheets

(function($) {
  //debugger;
	$(function() {

		$(document).on('click', '.save_button', function() {
			$.fe.pageHandler.savePage($(this).closest('.answer-page'), true);
		});

    //debugger;
		$(document).on('keydown', '#payment_staff_first, #payment_staff_last', function(e) {
      //debugger;
			if (e.which == 13) {
        console.log('staff_search click');
				$('#staff_search').trigger('click');
				return false;
			}

		});
		$(document).on('click', '.reference_send_invite', function() {
            var el = this;
			var data = $(el).closest('form').serializeArray();

			data.push({name: 'answer_sheet_type', value: answer_sheet_type});
      $.ajax({url: $(el).attr('href'), data: data, dataType: 'script',  type: 'POST',
                        beforeSend: function (xhr) {
                            $('body').trigger('ajax:loading', xhr);
                        },
                        complete: function (xhr) {
                            $('body').trigger('ajax:complete', xhr);
                        },
                        error: function (xhr, status, error) {
                            $('body').trigger('ajax:failure', [xhr, status, error]);
                        }
										});
			return false;
		});
		$(document).on('focus', 'textarea[maxlength]', function() {
			var max = parseInt($(this).attr('maxlength'));
			$(this).parent().find('.charsRemaining').html('You have ' + (max - $(this).val().length) + ' characters remaining');
		}).on('keyup', 'textarea[maxlength]', function(){
			var max = parseInt($(this).attr('maxlength'));
			if($(this).val().length > max){
				$(this).val($(this).val().substr(0, $(this).attr('maxlength')));
			}
			$(this).parent().find('.charsRemaining').html('You have ' + (max - $(this).val().length) + ' characters remaining');
		}).on('blur', 'textarea[maxlength]', function() {
			$(this).parent().find('.charsRemaining').html('');
		});

    // Payment submission
    $(document).on('click', '.submit_payment', function() {
      console.log('do .submit_payment')
      var form = $(this).closest('form');
      $.ajax({url: $(this).attr('data-url'), data: form.serializeArray(), type: 'POST', dataType:'script',
             beforeSend: function (xhr) {
               $('body').trigger('ajax:loading', xhr);
             },
             complete: function (xhr) {
               $('body').trigger('ajax:complete', xhr);
             },
             error: function (xhr, status, error) {
               $('body').trigger('ajax:failure', [xhr, status, error]);
             }
      });
      return false;
    });

	});
	$.fe = {};
	$.fe.pageHandler = {
	  initialize : function(page) {
	    this.auto_save_frequency = 30;  // seconds
	    this.timer_id = null;
		  this.suspendLoad = false;

	    this.current_page = page;
			$('#' + page).data('form_data', this.captureForm($('#' + page)));
	    this.registerAutoSave();

	    this.page_validation = {};  // validation objects for each page
	    this.enableValidation(page);

	    // this.background_load = false;
	    // this.final_submission = false;
	  },

	  // swap to a different page
	  showPage : function(page) {
	    // hide the old
	    $('#' + this.current_page + '-li').removeClass('active');
	    $('#' + this.current_page).hide();

			// HACK: Need to clear the main error message when returning to the submit page
			//       It is very confusing to users to be there when they revisit the page
			if ((page=='submit_page') && ($('#submit_message')[0] != null)) $('#submit_message').hide();
			if ((page=='submit_page') && ($('#application_errors')[0] != null)) $('#application_errors').html('');

	    // show the new
			// $('#' + page + '-li').removeClass('incomplete');
			// $('#' + page + '-li').removeClass('valid');
			$('#' + page + '-li').addClass('active');
	    $('#' + page).show();
	    this.current_page = page;
	    this.registerAutoSave(page);
	    this.suspendLoad = false;
	    fixGridColumnWidths();
	  },

	  // callback onSuccess
	  pageLoaded : function(response) {
	    // var response = new String(transport.responseText);
	    var match = response.match(/<div id=\"(.*?)\"/i); // what did I just load? parse out the first div id
	    if( match != null )
	    {
	      var page = match[1];
	      $('#preview').append(response);
	      // if(this.background_load) $('#' + page).hide(); else
				$.fe.pageHandler.showPage(page);  // show after load, unless loading in background
				setUpJsHelpers();
	      $.fe.pageHandler.enableValidation(page);
				// $.fe.pageHandler.validatePage('#' + page);
				$('#' + page).data('form_data', $.fe.pageHandler.captureForm($('#' + page)));
	    }
			$('#page_ajax_spinner').hide();
			$('.reference_send_invite').button();
			updateTotals();
	  },

	  loadPage : function(page, url) {
	    if (!this.suspendLoad) {
				this.suspendLoad = true; // don't load a page if one is currently loading (prevent double-click behavior where two pages end up visible!)

				this.unregisterAutoSave();  // don't auto-save while loading/saving
			      // will register auto-save on new page once loaded/shown

				$.scrollTo('#main');

		    this.validatePage(this.current_page);   // mark current page as valid (or not) as we're leaving

		    this.savePage();

		    if( $.fe.pageHandler.isPageLoaded(page) && page.match('no_cache') == null )   // if already loaded (element exists) excluding pages that need reloading
		    {
		      $.fe.pageHandler.showPage(page);
					$('#page_ajax_spinner').hide();
		    }
		    else
		    {
					$.ajax({
             url: url,
             type: 'GET',
						 data: {'answer_sheet_type':answer_sheet_type},
						 success: $.fe.pageHandler.pageLoaded,
             error: function (xhr, status, error) {
                alert("There was a problem loading that page. We've been notified and will fix it as soon as possible. To work on other pages, please refresh the website.");
								document.location = document.location;
             },
             beforeSend: function (xhr) {
                 $('body').trigger('ajax:loading', xhr);
             },
             complete: function (xhr) {
                 $('body').trigger('ajax:complete', xhr);
             }
         });
		      // new Ajax.Request(url, {asynchronous:true, evalScripts:false, method:'get',
		      //     onSuccess:this.pageLoaded.bind(this)});
		    }
			}
	  },

	  // save form if any changes were made
	  savePage : function(page, force) {
			if (page == null) page = $('#' + this.current_page);
      // don't save more than once per second
      timeNow = new Date();
      if (typeof(lastSave) != "undefined" && lastSave && !force && (timeNow - lastSave < 1000)) {
        return true;
      }
      lastSave = timeNow;
      form_data = this.captureForm(page);
      if( form_data ) {
        if( page.data('form_data') == null || page.data('form_data').data !== form_data.data || force === true) {  // if any changes
          page.data('form_data', form_data);
          $.ajax({url: form_data.url, type: 'put', data: form_data.data,
                 beforeSend: function (xhr) {
                   $('#spinner_' + page.attr('id')).show();
                 },
                 complete: function (xhr) {
                   $('#spinner_' + page.attr('id')).hide();
                 },
                 error: function() {
                   page.data('form_data', null);    // on error, force save for next call to save
                   // WARNING: race conditions with load & show?
                   // sort of a mess if save fails while another page is already loading!!
                 }});
        }
      }
      // Update last saved stamp
    },

		savePages : function(force) {
			$('.answer-page').each(function() {$.fe.pageHandler.savePage($(this), force)})
		},

	  // setup a timer to auto-save (only one timer, for the page being viewed)
	  registerAutoSave: function(page) {
	    this.timer_id = setInterval(this.savePages, this.auto_save_frequency * 1000);
	  },

	  unregisterAutoSave: function() {
	    if( this.timer_id != null )
	    {
	      clearInterval(this.timer_id);
	      this.timer_id = null;
	    }
	  },

	  // serialize form data and extract url to post to
	  captureForm : function(page) {
	    form_el = $('#' + page.attr('id') + '-form');
	    if( form_el[0] == null ) return null;
			return {url: form_el.attr('action'), data: form_el.serialize() + '&answer_sheet_type=' + answer_sheet_type};
	  },

	  // enable form validation (when form is loaded)
	  enableValidation : function(page) {
	    $('#' + page + '-form').validate({onsubmit:false, focusInvalid:true, onfocusout: function(element) { this.element(element);}});
	    // $('#' + page + '-form').valid();
	  },

	  validatePage : function(page) {
			try {
			  var li = $('#' + page + '-li');
			  var form = $('#' + page + '-form');

		    valid = form.valid();
				// Move radio button errors up
				$('input[type=radio].error').closest('tr').addClass('error');
				$('.choice_field input[type=radio].error').removeClass('error')
					.closest('.choice_field')
					.addClass('error');
				$('div.yesno label.error').hide();

		    if(valid)  {
		      el.removeClass('incomplete');
				  el.addClass('complete');
		    } else {
				  el.removeClass('complete');
		      el.addClass('incomplete');
		    }
		    return valid;
			}
			catch(err) {

				// If the user clicks too quickly, sometimes the page element isn't properly defined yet.
				// If we don't catch the error, js stops execution. If we catch it, the user just has to click again.
			}
			$('page_ajax_spinner').hide();
	  },

  // callback when falls to 0 active Ajax requests
  completeAll : function()
  {
		$('#submit_button').attr('disabled', true)
		$('#submit_message').html('');
		$('#submit_message').hide();
		// validate all the pages
  	$('.page_link').each(function(index, page) {
			$.fe.pageHandler.validatePage($(page).attr('data-page-id'));
		});
		var all_valid = ($('#list-pages li.incomplete').length == 0);

		// Make sure any necessary payments are made
		var payments_made = $('.payment_question.required').length >= $('.payment').length

		if(  payments_made)
		{
		  this.savePage($('#' + $.fe.pageHandler.current_page));  // in case any input fields on submit_page

		  // submit the application
		  if($('#submit_to')[0] != null)
		  {
		    url = $('#submit_to').val();
			  // clear out pages array to force reload.  This enables "frozen" apps
			  //       immediately after submission - :onSuccess (for USCM which stays in the application vs. redirecting to the dashboard)
			  var curr = $.fe.pageHandler.current_page;
			  $.ajax({url: url, dataType:'script',
			 		data: {answer_sheet_type: answer_sheet_type},
					type:'post',
					beforeSend: function(xhr) {
          	$('body').trigger('ajax:loading', xhr);
					},
					success: function(xhr) {
						$('#list-pages a').each(function() {
						  if ($(this).attr('data-page-id') != curr) $('#' + $(this).attr('data-page-id')).remove();
						})
					},
					complete: function(xhr) {
            $('body').trigger('ajax:complete', xhr);
		  			var btn = $('#submit_button');
						if (btn) { btn.attr('disabled', false); }
					}
				});
		  }
		}
		else
		{
		  // some pages aren't valid
 	    $('#submit_message').html("Please make a payment");
		  $('#submit_message').show();

		  var btn = $('#submit_button'); if (btn) { btn.attr('disabled', false); }
		}
  },

    // is page loaded? (useful for toggling enabled state of questions)
    isPageLoaded : function(page)
    {
      return $('#' + page)[0] != null
    },

    checkConditional : function($element_li) {
      matchable_answers = String($element_li.data('conditional_answer')).split(',').map(function(s) { return s.trim(); })
      if ($element_li.hasClass('fe::choicefield') && $element_li.hasClass('yes-no')) {
        if ($(matchable_answers).filter([1, '1', true, 'true', 'yes']).length > 0) {
          matchable_answers = [1, '1', true, 'true', 'yes'];
        }
        vals = $([$element_li.find("input[type=radio]:checked").val()]);
      } else if ($element_li.hasClass('fe::choicefield') && $element_li.hasClass('checkbox')) {
        vals = $element_li.find("input[type=checkbox]:checked").map(function(i, el) { return $(el).val(); });
      } else {
        vals = $([$element_li.find("input:visible, select:visible").val()]);
      }
      match = $(matchable_answers).filter(vals).length > 0;

      console.log('checkConditional match: ' + match);

      switch ($element_li.data('conditional_type')) {
        case 'Fe::Element':
          if (match) {
            $("#element_" + $element_li.data('conditional_id')).show();
          } else {
            $("#element_" + $element_li.data('conditional_id')).hide();
          }
        case 'Fe::Page':
          li_id = "li#fe_application_" + $element_li.data('application_id') + '-fe_page_' + $element_li.data('conditional_id') + '-li';
          if (match) {
            $(li_id).show();
          } else {
            $(li_id).hide();
          }
      }
    }

  };

  $(document).on('click', "li.conditional input, li.conditional select", function() {
    console.log('click');
    $.fe.pageHandler.checkConditional($(this).closest('li'));
  });
  $(document).on('keyup', "li.conditional input, li.conditional select", function() { $(this).click(); });
  $(document).on('blug', "li.conditional input, li.conditional select", function() { $(this).click(); });
  $(document).on('change', "li.conditional select", function() { $(this).click(); });

})(jQuery);

$(function() {
	fixGridColumnWidths();
});

function updateTotal(id) {
	try {
		total = 0;
		$(".col_" + id ).each(function(e) {
		  total += Number(e.val());
		});
		$('#total_' + id).val(total);
	} catch(e) {}
}

function submitToFrame(id, url)
{
  form = $('<form method="post" action="'+url+'.js" endtype="multipart/form-data"></form>')
  var csrf_token = $('meta[name=csrf-token]').attr('content'),
      csrf_param = $('meta[name=csrf-param]').attr('content'),
			dom_id = '#attachment_field_' + id,
			metadata_input = '<input name="'+csrf_param+'" value="'+csrf_token+'" type="hidden" />',
			file_field = '<input type="file" name="answers['+ id + ']>';
	if ($(dom_id).val() == '')	return;
  form.hide()
      .append(metadata_input)
      .append(file_field)
      .appendTo('body');
	$(dom_id + "-spinner").show();
  form.submit();
	return false
}
<|endoftext|>


<commit_before>// Copyright (c) 2013-2014 Quildreen Motta <quildreen@gmail.com>
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

/**
 * @module lib/maybe
 */
module.exports = Maybe

// -- Aliases ----------------------------------------------------------
var clone         = Object.create
var unimplemented = function(){ throw new Error('Not implemented.') }
var noop          = function(){ return this                         }

// -- Implementation ---------------------------------------------------

/**
 * A structure for values that may not be present, or computations that may
 * fail. `Maybe(a)` explicitly models the effects that are implicit in
 * `Nullable` types, thus has none of the problems associated with
 * `null` or `undefined` — like `NullPointerExceptions`.
 *
 * The class models two different cases:
 *
 *  + `Just a` — represents a `Maybe(a)` that contains a value. `a` may
 *     be any value, including `null` or `undefined`.
 *
 *  + `Nothing` — represents a `Maybe(a)` that has no values. Or a
 *     failure that needs no additional information.
 *
 * Common uses of this structure includes modelling values that may or may
 * not be present in a collection, thus instead of needing a
 * `collection.has(a)`, the `collection.get(a)` operation gives you all
 * the information you need — `collection.get(a).is-nothing` being
 * equivalent to `collection.has(a)`; Similarly the same reasoning may
 * be applied to computations that may fail to provide a value, e.g.:
 * `collection.find(predicate)` can safely return a `Maybe(a)` instance,
 * even if the collection contains nullable values.
 *
 * Furthermore, the values of `Maybe(a)` can be combined and manipulated
 * by using the expressive monadic operations. This allows safely
 * sequencing operations that may fail, and safely composing values that
 * you don't know whether they're present or not, failing early
 * (returning a `Nothing`) if any of the operations fail.
 *
 * If one wants to store additional information about failures, the
 * [Either][] and [Validation][] structures provide such a capability, and
 * should be used instead of the `Maybe(a)` structure.
 *
 * [Either]: https://github.com/folktale/data.either
 * [Validation]: https://github.com/folktale/data.validation
 *
 *
 * @class
 */
function Maybe() {}

// The case for successful values
Just.prototype = clone(Maybe.prototype)
function Just(a){
  this.value = a
}

// The case for failure values
Nothing.prototype = clone(Maybe.prototype)
function Nothing(){}

// -- Constructors -----------------------------------------------------

/**
 * Constructs a new `Maybe[α]` structure with an absent value. Commonly used
 * to represent a failure.
 *
 * @summary Void → Maybe[α]
 */
Maybe.Nothing = function() {
  return new Nothing
}
Maybe.prototype.Nothing = Maybe.Nothing

/**
 * Constructs a new `Maybe[α]` structure that holds the single value
 * `α`. Commonly used to represent a success.
 *
 * `α` can be any value, including `null`, `undefined` or another
 * `Maybe[α]` structure.
 *
 * @summary α → Maybe[α]
 */
Maybe.Just = function(a) {
  return new Just(a)
}
Maybe.prototype.Just = Maybe.Just

// -- Conversions ------------------------------------------------------

/**
 * Constructs a new `Maybe[α]` structure from a nullable type.
 *
 * If the value is either `null` or `undefined`, this function returns a
 * `Nothing`, otherwise the value is wrapped in a `Just(α)`.
 *
 * @summary α → Maybe[α]
 */
Maybe.fromNullable = function(a) {
  return a != null?       new Just(a)
  :      /* otherwise */  new Nothing
}
Maybe.prototype.fromNullable = Maybe.fromNullable

/**
 * Constructs a new `Maybe[β]` structure from an `Either[α, β]` type.
 *
 * The left side of the `Either` becomes `Nothing`, and the right side
 * is wrapped in a `Just(β)`.
 *
 * @summary Either[α, β] → Maybe[β]
 */
Maybe.fromEither = function(a) {
  return a.fold(Maybe.Nothing, Maybe.Just)
}
Maybe.prototype.fromEither = Maybe.fromEither

/**
 * Constructs a new `Maybe[β]` structure from a `Validation[α, β]` type.
 *
 * The failure side of the `Validation` becomes `Nothing`, and the right
 * side is wrapped in a `Just(β)`.
 *
 * @method
 * @summary Validation[α, β] → Maybe[β]
 */
Maybe.fromValidation           = Maybe.fromEither
Maybe.prototype.fromValidation = Maybe.fromEither

// -- Predicates -------------------------------------------------------

/**
 * True if the `Maybe[α]` structure contains a failure (i.e.: `Nothing`).
 *
 * @summary Boolean
 */
Maybe.prototype.isNothing   = false
Nothing.prototype.isNothing = true

/**
 * True if the `Maybe[α]` structure contains a single value (i.e.: `Just(α)`).
 *
 * @summary Boolean
 */
Maybe.prototype.isJust = false
Just.prototype.isJust  = true

// -- Applicative ------------------------------------------------------

/**
 * Creates a new `Maybe[α]` structure holding the single value `α`.
 *
 * `α` can be any value, including `null`, `undefined`, or another
 * `Maybe[α]` structure.
 *
 * @summary α → Maybe[α]
 */
Maybe.of = function(a) {
  return Maybe.prototype.Just(a)
}
Maybe.prototype.of = Maybe.of

/**
 * Applies the function inside the `Maybe[α]` structure to another
 * applicative type.
 *
 * The `Maybe[α]` structure should contain a function value, otherwise a
 * `TypeError` is thrown.
 *
 * @method
 * @summary (@Maybe[α → β], f:Applicative[_]) => f[α] → f[β]
 */
Maybe.prototype.ap = unimplemented

Nothing.prototype.ap = noop

Just.prototype.ap = function(b) {
  return b.map(this.value)
}

// -- Functor ----------------------------------------------------------

/**
 * Transforms the value of the `Maybe[α]` structure using a regular unary
 * function.
 *
 * @method
 * @summary @Maybe[α] => (α → β) → Maybe[β]
 */
Maybe.prototype.map   = unimplemented
Nothing.prototype.map = noop

Just.prototype.map = function(f) {
  return this.of(f(this.value))
}

// -- Chain ------------------------------------------------------------

/**
 * Transforms the value of the `Maybe[α]` structure using an unary function
 * to monads.
 *
 * @method
 * @summary (@Maybe[α], m:Monad[_]) => (α → m[β]) → m[β]
 */
Maybe.prototype.chain   = unimplemented
Nothing.prototype.chain = noop

Just.prototype.chain = function(f) {
  return f(this.value)
}

// -- Show -------------------------------------------------------------

/**
 * Returns a textual representation of the `Maybe[α]` structure.
 *
 * @method
 * @summary @Maybe[α] => Void → String
 */
Maybe.prototype.toString = unimplemented

Nothing.prototype.toString = function() {
  return 'Maybe.Nothing'
}

Just.prototype.toString = function() {
  return 'Maybe.Just(' + this.value + ')'
}

// -- Eq ---------------------------------------------------------------

/**
 * Tests if a `Maybe[α]` structure is equal to another `Maybe[α]` structure.
 *
 * @method
 * @summary @Maybe[α] => Maybe[α] → Boolean
 */
Maybe.prototype.isEqual = unimplemented

Nothing.prototype.isEqual = function(b) {
  return b.isNothing
}

Just.prototype.isEqual = function(b) {
  return b.isJust
  &&     b.value === this.value
}

// -- Extracting and recovering ----------------------------------------

/**
 * Extracts the value out of the `Maybe[α]` structure, if it
 * exists. Otherwise throws a `TypeError`.
 *
 * @method
 * @summary @Maybe[α] => Void → a,      :: partial, throws
 * @see {@link module:lib/maybe~Maybe#getOrElse} — A getter that can handle failures
 * @throws {TypeError} if the structure has no value (`Nothing`).
 */
Maybe.prototype.get = unimplemented

Nothing.prototype.get = function() {
  throw new TypeError("Can't extract the value of a Nothing.")
}

Just.prototype.get = function() {
  return this.value
}

/**
 * Extracts the value out of the `Maybe[α]` structure. If there is no value,
 * returns the given default.
 *
 * @method
 * @summary @Maybe[α] => α → α
 */
Maybe.prototype.getOrElse = unimplemented

Nothing.prototype.getOrElse = function(a) {
  return a
}

Just.prototype.getOrElse = function(_) {
  return this.value
}

/**
 * Transforms a failure into a new `Maybe[α]` structure. Does nothing if the
 * structure already contains a value.
 *
 * @method
 * @summary @Maybe[α] => (Void → Maybe[α]) → Maybe[α]
 */
Maybe.prototype.orElse = unimplemented

Nothing.prototype.orElse = function(f) {
  return f()
}

Just.prototype.orElse = function(_) {
  return this
}

/**
 * Catamorphism.
 *
 * @method
 * @summary @Maybe[α] => { Nothing: Void → β, Just: α → β } → β
 */
Maybe.prototype.cata = unimplemented

Nothing.prototype.cata = function(pattern) {
  return pattern.Nothing()
}

Just.prototype.cata = function(pattern) {
  return pattern.Just(this.value);
}<commit_msg>Fixes Nothing::ap<commit_after>// Copyright (c) 2013-2014 Quildreen Motta <quildreen@gmail.com>
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

/**
 * @module lib/maybe
 */
module.exports = Maybe

// -- Aliases ----------------------------------------------------------
var clone         = Object.create
var unimplemented = function(){ throw new Error('Not implemented.') }
var noop          = function(){ return this                         }

// -- Implementation ---------------------------------------------------

/**
 * A structure for values that may not be present, or computations that may
 * fail. `Maybe(a)` explicitly models the effects that are implicit in
 * `Nullable` types, thus has none of the problems associated with
 * `null` or `undefined` — like `NullPointerExceptions`.
 *
 * The class models two different cases:
 *
 *  + `Just a` — represents a `Maybe(a)` that contains a value. `a` may
 *     be any value, including `null` or `undefined`.
 *
 *  + `Nothing` — represents a `Maybe(a)` that has no values. Or a
 *     failure that needs no additional information.
 *
 * Common uses of this structure includes modelling values that may or may
 * not be present in a collection, thus instead of needing a
 * `collection.has(a)`, the `collection.get(a)` operation gives you all
 * the information you need — `collection.get(a).is-nothing` being
 * equivalent to `collection.has(a)`; Similarly the same reasoning may
 * be applied to computations that may fail to provide a value, e.g.:
 * `collection.find(predicate)` can safely return a `Maybe(a)` instance,
 * even if the collection contains nullable values.
 *
 * Furthermore, the values of `Maybe(a)` can be combined and manipulated
 * by using the expressive monadic operations. This allows safely
 * sequencing operations that may fail, and safely composing values that
 * you don't know whether they're present or not, failing early
 * (returning a `Nothing`) if any of the operations fail.
 *
 * If one wants to store additional information about failures, the
 * [Either][] and [Validation][] structures provide such a capability, and
 * should be used instead of the `Maybe(a)` structure.
 *
 * [Either]: https://github.com/folktale/data.either
 * [Validation]: https://github.com/folktale/data.validation
 *
 *
 * @class
 */
function Maybe() {}

// The case for successful values
Just.prototype = clone(Maybe.prototype)
function Just(a){
  this.value = a
}

// The case for failure values
Nothing.prototype = clone(Maybe.prototype)
function Nothing(){}

// -- Constructors -----------------------------------------------------

/**
 * Constructs a new `Maybe[α]` structure with an absent value. Commonly used
 * to represent a failure.
 *
 * @summary Void → Maybe[α]
 */
Maybe.Nothing = function() {
  return new Nothing
}
Maybe.prototype.Nothing = Maybe.Nothing

/**
 * Constructs a new `Maybe[α]` structure that holds the single value
 * `α`. Commonly used to represent a success.
 *
 * `α` can be any value, including `null`, `undefined` or another
 * `Maybe[α]` structure.
 *
 * @summary α → Maybe[α]
 */
Maybe.Just = function(a) {
  return new Just(a)
}
Maybe.prototype.Just = Maybe.Just

// -- Conversions ------------------------------------------------------

/**
 * Constructs a new `Maybe[α]` structure from a nullable type.
 *
 * If the value is either `null` or `undefined`, this function returns a
 * `Nothing`, otherwise the value is wrapped in a `Just(α)`.
 *
 * @summary α → Maybe[α]
 */
Maybe.fromNullable = function(a) {
  return a != null?       new Just(a)
  :      /* otherwise */  new Nothing
}
Maybe.prototype.fromNullable = Maybe.fromNullable

/**
 * Constructs a new `Maybe[β]` structure from an `Either[α, β]` type.
 *
 * The left side of the `Either` becomes `Nothing`, and the right side
 * is wrapped in a `Just(β)`.
 *
 * @summary Either[α, β] → Maybe[β]
 */
Maybe.fromEither = function(a) {
  return a.fold(Maybe.Nothing, Maybe.Just)
}
Maybe.prototype.fromEither = Maybe.fromEither

/**
 * Constructs a new `Maybe[β]` structure from a `Validation[α, β]` type.
 *
 * The failure side of the `Validation` becomes `Nothing`, and the right
 * side is wrapped in a `Just(β)`.
 *
 * @method
 * @summary Validation[α, β] → Maybe[β]
 */
Maybe.fromValidation           = Maybe.fromEither
Maybe.prototype.fromValidation = Maybe.fromEither

// -- Predicates -------------------------------------------------------

/**
 * True if the `Maybe[α]` structure contains a failure (i.e.: `Nothing`).
 *
 * @summary Boolean
 */
Maybe.prototype.isNothing   = false
Nothing.prototype.isNothing = true

/**
 * True if the `Maybe[α]` structure contains a single value (i.e.: `Just(α)`).
 *
 * @summary Boolean
 */
Maybe.prototype.isJust = false
Just.prototype.isJust  = true

// -- Applicative ------------------------------------------------------

/**
 * Creates a new `Maybe[α]` structure holding the single value `α`.
 *
 * `α` can be any value, including `null`, `undefined`, or another
 * `Maybe[α]` structure.
 *
 * @summary α → Maybe[α]
 */
Maybe.of = function(a) {
  return Maybe.prototype.Just(a)
}
Maybe.prototype.of = Maybe.of

/**
 * Applies the function inside the `Maybe[α]` structure to another
 * applicative type.
 *
 * The `Maybe[α]` structure should contain a function value, otherwise a
 * `TypeError` is thrown.
 *
 * @method
 * @summary (@Maybe[α → β], f:Applicative[_]) => f[α] → f[β]
 */
Maybe.prototype.ap = unimplemented

Nothing.prototype.ap = function(b) {
  return b
}

Just.prototype.ap = function(b) {
  return b.map(this.value)
}

// -- Functor ----------------------------------------------------------

/**
 * Transforms the value of the `Maybe[α]` structure using a regular unary
 * function.
 *
 * @method
 * @summary @Maybe[α] => (α → β) → Maybe[β]
 */
Maybe.prototype.map   = unimplemented
Nothing.prototype.map = noop

Just.prototype.map = function(f) {
  return this.of(f(this.value))
}

// -- Chain ------------------------------------------------------------

/**
 * Transforms the value of the `Maybe[α]` structure using an unary function
 * to monads.
 *
 * @method
 * @summary (@Maybe[α], m:Monad[_]) => (α → m[β]) → m[β]
 */
Maybe.prototype.chain   = unimplemented
Nothing.prototype.chain = noop

Just.prototype.chain = function(f) {
  return f(this.value)
}

// -- Show -------------------------------------------------------------

/**
 * Returns a textual representation of the `Maybe[α]` structure.
 *
 * @method
 * @summary @Maybe[α] => Void → String
 */
Maybe.prototype.toString = unimplemented

Nothing.prototype.toString = function() {
  return 'Maybe.Nothing'
}

Just.prototype.toString = function() {
  return 'Maybe.Just(' + this.value + ')'
}

// -- Eq ---------------------------------------------------------------

/**
 * Tests if a `Maybe[α]` structure is equal to another `Maybe[α]` structure.
 *
 * @method
 * @summary @Maybe[α] => Maybe[α] → Boolean
 */
Maybe.prototype.isEqual = unimplemented

Nothing.prototype.isEqual = function(b) {
  return b.isNothing
}

Just.prototype.isEqual = function(b) {
  return b.isJust
  &&     b.value === this.value
}

// -- Extracting and recovering ----------------------------------------

/**
 * Extracts the value out of the `Maybe[α]` structure, if it
 * exists. Otherwise throws a `TypeError`.
 *
 * @method
 * @summary @Maybe[α] => Void → a,      :: partial, throws
 * @see {@link module:lib/maybe~Maybe#getOrElse} — A getter that can handle failures
 * @throws {TypeError} if the structure has no value (`Nothing`).
 */
Maybe.prototype.get = unimplemented

Nothing.prototype.get = function() {
  throw new TypeError("Can't extract the value of a Nothing.")
}

Just.prototype.get = function() {
  return this.value
}

/**
 * Extracts the value out of the `Maybe[α]` structure. If there is no value,
 * returns the given default.
 *
 * @method
 * @summary @Maybe[α] => α → α
 */
Maybe.prototype.getOrElse = unimplemented

Nothing.prototype.getOrElse = function(a) {
  return a
}

Just.prototype.getOrElse = function(_) {
  return this.value
}

/**
 * Transforms a failure into a new `Maybe[α]` structure. Does nothing if the
 * structure already contains a value.
 *
 * @method
 * @summary @Maybe[α] => (Void → Maybe[α]) → Maybe[α]
 */
Maybe.prototype.orElse = unimplemented

Nothing.prototype.orElse = function(f) {
  return f()
}

Just.prototype.orElse = function(_) {
  return this
}

/**
 * Catamorphism.
 *
 * @method
 * @summary @Maybe[α] => { Nothing: Void → β, Just: α → β } → β
 */
Maybe.prototype.cata = unimplemented

Nothing.prototype.cata = function(pattern) {
  return pattern.Nothing()
}

Just.prototype.cata = function(pattern) {
  return pattern.Just(this.value);
}<|endoftext|>


<commit_before>#!/usr/bin/env node

"use strict";

require("babel-register");

const path = require("path");
const fs = require("fs");
const Mustache = require("mustache");
const webpack = require("webpack");
const express = require("express");
const webpackDevMiddleware = require("webpack-dev-middleware");
const webpackHotMiddleware = require("webpack-hot-middleware");
const http = require("http");
const serveIndex = require("serve-index");
const checkNode = require("check-node-version");

checkNode(">=5.0.0", function(_, opts) {
  if (!opts.nodeSatisfied) {
    const version = opts.node.raw;
    console.log(`Sorry, Your version of node is ${version}.`);
    console.log("The minimum requirement is >=5.0.0");
    exit();
  }
});

const { getValue, isDevelopment } = require("devtools-config");
const {registerConfig} = require("../../devtools-config/registerConfig");
registerConfig();

if (!getValue("firefox.webSocketConnection")) {
  const firefoxProxy = require("./firefox-proxy");
  firefoxProxy({ logging: getValue("logging.firefoxProxy") });
}

function httpGet(url, onResponse) {
  return http.get(url, (response) => {
    if (response.statusCode !== 200) {
      console.error(`error response: ${response.statusCode} to ${url}`);
      response.emit("statusCode", new Error(response.statusCode));
      return onResponse("{}");
    }
    let body = "";
    response.on("data", function(d) {
      body += d;
    });
    response.on("end", () => onResponse(body));
  });
}

const app = express();

// Webpack middleware
const webpackConfig = require("../../../webpack.config");
const compiler = webpack(webpackConfig);

app.use(webpackDevMiddleware(compiler, {
  publicPath: webpackConfig.output.publicPath,
  noInfo: true,
  stats: { colors: true }
}));

if (getValue("hotReloading")) {
  app.use(webpackHotMiddleware(compiler));
} else {
  console.log("Hot Reloading can be enabled by adding " +
  "\"hotReloading\": true to your local.json config");
}

// Static middleware
app.use(express.static("public"));

// Routes
app.get("/", function(req, res) {
  const tplPath = path.join(__dirname, "../index.html");
  const tplFile = fs.readFileSync(tplPath, "utf8");
  res.send(Mustache.render(tplFile, { isDevelopment: isDevelopment() }));
});

app.get("/get", function(req, res) {
  const url = req.query.url;
  if (url.indexOf("file://") === 0) {
    const path = url.replace("file://", "");
    res.json(JSON.parse(fs.readFileSync(path, "utf8")));
  }
  else {
    const httpReq = httpGet(
      req.query.url,
      body => {
        try {
          res.send(body);
        } catch (e) {
          res.status(500).send("Malformed json");
        }
      }
    );

    httpReq.on("error", err => res.status(500).send(err.code));
    httpReq.on("statusCode", err => res.status(err.message).send(err.message));
  }
});

// Listen'
const serverPort = getValue("development.serverPort");
app.listen(serverPort, "0.0.0.0", function(err, result) {
  if (err) {
    console.log(err);
  } else {
    console.log(`Development Server Listening at http://localhost:${serverPort}`);
  }
});

const examples = express();
examples.use(express.static("public/js/test/examples"));
examples.use(serveIndex("public/js/test/examples", { icons: true }));

const examplesPort = getValue("development.examplesPort");
examples.listen(examplesPort, "0.0.0.0", function(err, result) {
  if (err) {
    console.log(err);
  } else {
    console.log(`View debugger examples at http://localhost:${examplesPort}`);
  }
});
<commit_msg>Make development server work for node v5<commit_after>#!/usr/bin/env node

"use strict";

require("babel-register");

const path = require("path");
const fs = require("fs");
const Mustache = require("mustache");
const webpack = require("webpack");
const express = require("express");
const webpackDevMiddleware = require("webpack-dev-middleware");
const webpackHotMiddleware = require("webpack-hot-middleware");
const http = require("http");
const serveIndex = require("serve-index");
const checkNode = require("check-node-version");

checkNode(">=5.0.0", function(_, opts) {
  if (!opts.nodeSatisfied) {
    const version = opts.node.raw;
    console.log(`Sorry, Your version of node is ${version}.`);
    console.log("The minimum requirement is >=5.0.0");
    exit();
  }
});

const getValue = require("devtools-config").getValue;
const isDevelopment = require("devtools-config").isDevelopment;
const registerConfig = require("../../devtools-config/registerConfig").registerConfig;
registerConfig();

if (!getValue("firefox.webSocketConnection")) {
  const firefoxProxy = require("./firefox-proxy");
  firefoxProxy({ logging: getValue("logging.firefoxProxy") });
}

function httpGet(url, onResponse) {
  return http.get(url, (response) => {
    if (response.statusCode !== 200) {
      console.error(`error response: ${response.statusCode} to ${url}`);
      response.emit("statusCode", new Error(response.statusCode));
      return onResponse("{}");
    }
    let body = "";
    response.on("data", function(d) {
      body += d;
    });
    response.on("end", () => onResponse(body));
  });
}

const app = express();

// Webpack middleware
const webpackConfig = require("../../../webpack.config");
const compiler = webpack(webpackConfig);

app.use(webpackDevMiddleware(compiler, {
  publicPath: webpackConfig.output.publicPath,
  noInfo: true,
  stats: { colors: true }
}));

if (getValue("hotReloading")) {
  app.use(webpackHotMiddleware(compiler));
} else {
  console.log("Hot Reloading can be enabled by adding " +
  "\"hotReloading\": true to your local.json config");
}

// Static middleware
app.use(express.static("public"));

// Routes
app.get("/", function(req, res) {
  const tplPath = path.join(__dirname, "../index.html");
  const tplFile = fs.readFileSync(tplPath, "utf8");
  res.send(Mustache.render(tplFile, { isDevelopment: isDevelopment() }));
});

app.get("/get", function(req, res) {
  const url = req.query.url;
  if (url.indexOf("file://") === 0) {
    const path = url.replace("file://", "");
    res.json(JSON.parse(fs.readFileSync(path, "utf8")));
  }
  else {
    const httpReq = httpGet(
      req.query.url,
      body => {
        try {
          res.send(body);
        } catch (e) {
          res.status(500).send("Malformed json");
        }
      }
    );

    httpReq.on("error", err => res.status(500).send(err.code));
    httpReq.on("statusCode", err => res.status(err.message).send(err.message));
  }
});

// Listen'
const serverPort = getValue("development.serverPort");
app.listen(serverPort, "0.0.0.0", function(err, result) {
  if (err) {
    console.log(err);
  } else {
    console.log(`Development Server Listening at http://localhost:${serverPort}`);
  }
});

const examples = express();
examples.use(express.static("public/js/test/examples"));
examples.use(serveIndex("public/js/test/examples", { icons: true }));

const examplesPort = getValue("development.examplesPort");
examples.listen(examplesPort, "0.0.0.0", function(err, result) {
  if (err) {
    console.log(err);
  } else {
    console.log(`View debugger examples at http://localhost:${examplesPort}`);
  }
});
<|endoftext|>


<commit_before>ReactListView.actions = {
  updateItem: function(itemData, newItemData) {
    var payload = { itemData: itemData, newItemData: newItemData };
    console.log('updateItem action: ', payload.itemData.title);
    this.dispatch(ReactListView.constants.ITEM_UPDATE, payload);

    ReactListView.updateItem(
      payload,
      function(data) {
        this.dispatch(ReactListView.constants.ITEM_UPDATE_SUCCESS, data);
      }.bind(this),
      function(error) {
        this.dispatch(ReactListView.constants.ITEM_UPDATE_FAILURE, error);
      }.bind(this)
    );
  },

  addNewItem: function(newItemData) {
    var listID = this.flux.store("ListStore").getID();
    var listItemID = ReactListView.makeId();
    var itemData = {
      title: newItemData.title,
      link: newItemData.amazon_url,
      image_url: newItemData.thumbnail_url,
      list_id: listID,
      rank: 0,
      listItemID: listItemID
    };

    // Optimistically add item to UI.
    this.dispatch(ReactListView.constants.ITEM_ADD, itemData);

    ReactListView.saveItem(
      itemData,
      function(savedItem) {
        savedItem.listItemID = itemData.listItemID;
        this.dispatch(ReactListView.constants.ITEM_ADD_SUCCESS, savedItem);
      }.bind(this),
      function(error) {
        var payload = {
          listItemID: listItemID,
          error: 'Error saving: ' + itemTitle + '('+ error + ')'
        };
        this.dispatch(ReactListView.constants.ITEM_ADD_FAILURE, payload);
      }.bind(this)
    );
  },

  deleteItem: function(itemId) {
    // Optimistically add item to UI.
    this.dispatch(ReactListView.constants.ITEM_DELETE, itemId);
  },
};<commit_msg>Move success/error callbacks into app utils.<commit_after>App.actions = {
  updateItem: function(itemData, newItemData) {
    var payload = {
      itemData: itemData,
      newItemData: newItemData
    };
    this.dispatch(App.constants.ITEM_UPDATE, payload);
    App.updateItem(payload, this);
  },

  addNewItem: function(newItemData) {
    var listID = this.flux.store("ListStore").getID();
    var listItemID = App.makeId();
    var itemData = {
      title: newItemData.title,
      link: newItemData.amazon_url,
      image_url: newItemData.thumbnail_url,
      list_id: listID,
      rank: 0,
      listItemID: listItemID
    };

    // Optimistically add item to UI.
    this.dispatch(App.constants.ITEM_ADD, itemData);
    App.saveItem(itemData, this);
  },

  deleteItem: function(itemId) {
    // Optimistically add item to UI.
    this.dispatch(App.constants.ITEM_DELETE, itemId);
  },
};<|endoftext|>


<commit_before>var ref = require('ref');

var lib = require('./libvlc');
var TrackInfo = require('./libvlc_types').TrackInfo;

var metaName = require('./media_enum').metaName;

var trackType = {
  unknown: -1,
  '-1': 'unknown',
  audio: 0,
  '0': 'audio',
  video: 1,
  '1': 'video',
  text: 2,
  '2': 'text',
}

var Media = module.exports = function (parent, reinit, opts) {
  var self = this;
  var released = false;

  if (reinit) {
    self.instance = reinit;
  } else if (opts.path) {
    self.instance = lib.libvlc_media_new_path(parent, opts.path);
  } else if (opts.url) {
    self.instance = lib.libvlc_media_new_location(parent, opts.url);
  } else if (opts.fd) {
    self.instance = lib.libvlc_media_new_fd(parent, opts.fd);
  } else {
    self.instance = lib.libvlc_media_new_as_node(parent);
  }

  this.release = function () {
    if (!released) {
      lib.libvlc_media_release(self.instance);
      released = true;
    }
  };

  this.parseSync = function () {
    lib.libvlc_media_parse(self.instance);
  };

  this.saveSync = function () {
    lib.libvlc_media_save_meta(self.instance);
  };

  Object.defineProperty(this, 'mrl', {
    get: function () {
      return lib.libvlc_media_get_mrl(self.instance);
    },
  });

  Object.defineProperty(this, 'is_parsed', {
    get: function () {
      return lib.libvlc_media_is_parsed(self.instance);
    },
  });

  Object.defineProperty(this, 'duration', {
    get: function () {
      return lib.libvlc_media_get_duration(self.instance);
    },
  });

  Object.defineProperty(this, 'track_info', {
    get: function () {
      var i, ptr, tmp;
      var results = [];

      var info = new Buffer(ref.sizeof.pointer);
      var tracks = lib.libvlc_media_get_tracks_info(self.instance, info);
      info = info.readPointer(0, TrackInfo.size * tracks);

      for (i = 0; i < tracks; i++) {
        ptr = ref.get(info, i * TrackInfo.size, TrackInfo);

        tmp = {
          codec: ptr.i_codec,
          id: ptr.i_id,
          type: trackType[ptr.i_type],
          profile: ptr.i_profile,
          level: ptr.i_level,
        };

        switch (tmp.type) {
          case 'audio':
            tmp.channels = ptr.union1;
            tmp.rate = ptr.union2;
            break;
          case 'video':
            tmp.height = ptr.union1;
            tmp.width = ptr.union2;
            break;
        }

        results.push(tmp);
      }

      //TODO XXX FIXME
      //info.free();

      return results;
    },
  });

  Object.keys(metaName).forEach(function (meta) {
    Object.defineProperty(self, meta, {
      get: function () {
        return lib.libvlc_media_get_meta(self.instance, metaName[meta]);
      },
      set: function (val) {
        lib.libvlc_media_set_meta(self.instance, metaName[meta], val);
      },
      enumerable: true,
      configurable: true,
    });
  });
};
<commit_msg>free the vlc allocated data<commit_after>var ref = require('ref');

var lib = require('./libvlc');
var TrackInfo = require('./libvlc_types').TrackInfo;

var metaName = require('./media_enum').metaName;

var trackType = {
  unknown: -1,
  '-1': 'unknown',
  audio: 0,
  '0': 'audio',
  video: 1,
  '1': 'video',
  text: 2,
  '2': 'text',
}

var ffi = require('ffi')
var libc = ffi.Library(null, {
  'free': ['void', [ 'pointer' ]],
});

var Media = module.exports = function (parent, reinit, opts) {
  var self = this;
  var released = false;

  if (reinit) {
    self.instance = reinit;
  } else if (opts.path) {
    self.instance = lib.libvlc_media_new_path(parent, opts.path);
  } else if (opts.url) {
    self.instance = lib.libvlc_media_new_location(parent, opts.url);
  } else if (opts.fd) {
    self.instance = lib.libvlc_media_new_fd(parent, opts.fd);
  } else {
    self.instance = lib.libvlc_media_new_as_node(parent);
  }

  this.release = function () {
    if (!released) {
      lib.libvlc_media_release(self.instance);
      released = true;
    }
  };

  this.parseSync = function () {
    lib.libvlc_media_parse(self.instance);
  };

  this.saveSync = function () {
    lib.libvlc_media_save_meta(self.instance);
  };

  Object.defineProperty(this, 'mrl', {
    get: function () {
      return lib.libvlc_media_get_mrl(self.instance);
    },
  });

  Object.defineProperty(this, 'is_parsed', {
    get: function () {
      return lib.libvlc_media_is_parsed(self.instance);
    },
  });

  Object.defineProperty(this, 'duration', {
    get: function () {
      return lib.libvlc_media_get_duration(self.instance);
    },
  });

  Object.defineProperty(this, 'track_info', {
    get: function () {
      var i, ptr, tmp;
      var results = [];

      var info = new Buffer(ref.sizeof.pointer);
      var tracks = lib.libvlc_media_get_tracks_info(self.instance, info);
      info = info.readPointer(0, TrackInfo.size * tracks);

      for (i = 0; i < tracks; i++) {
        ptr = ref.get(info, i * TrackInfo.size, TrackInfo);

        tmp = {
          codec: ptr.i_codec,
          id: ptr.i_id,
          type: trackType[ptr.i_type],
          profile: ptr.i_profile,
          level: ptr.i_level,
        };

        switch (tmp.type) {
          case 'audio':
            tmp.channels = ptr.union1;
            tmp.rate = ptr.union2;
            break;
          case 'video':
            tmp.height = ptr.union1;
            tmp.width = ptr.union2;
            break;
        }

        results.push(tmp);
      }

      libc.free(info);
      info = undefined;

      return results;
    },
  });

  Object.keys(metaName).forEach(function (meta) {
    Object.defineProperty(self, meta, {
      get: function () {
        return lib.libvlc_media_get_meta(self.instance, metaName[meta]);
      },
      set: function (val) {
        lib.libvlc_media_set_meta(self.instance, metaName[meta], val);
      },
      enumerable: true,
      configurable: true,
    });
  });
};
<|endoftext|>


<commit_before>$(function(){

   parentGlobalController.suscription.status();

   var title = "Pausar Suscripción";
   var message1 = "
"+
      "Estas a punto de pausar tu suscripción a Curiosity Educación.
Una vez que presiones en el botón de CONTINUAR tu suscripción a Curiosity se pausará y el cobro a tu tarjeta no será realizado, por lo cual todas las cuentas para tus hijos no contarán con acceso a la plataforma.

Puedes reactivar tu suscripción solo iniciando sesión y dentro de esta misma sección dar clic en el botón de Reactivar.

Nota: Al reactivar tu suscripción las cuentas de tus hijos se reactivarán automáticamente."+
   "
"+
   "
"+
      "

"+
      "<button type='button' data-dismiss='modal' aria-hidden='true' class='btn btn-rounded' style='background-color: #ed6922;"+    "padding-left:2.5rem;padding-right: 2.5rem;' id='mvp-cancelchange'>Cancelar</button>"+
      "<button type='button' class='btn btn-rounded' style='background-color:#2262ae;' id='mvp-continue'>Continuar</button>"+
   "
";

   var message2 = "
"+
      "Estas a punto de renaudar

"+
   "
"+
   "
"+
      "

"+
      "<button type='button' data-dismiss='modal' aria-hidden='true' class='btn btn-rounded' style='background-color: #ed6922;"+    "padding-left:2.5rem;padding-right: 2.5rem;' id='mvp-cancelchange'>Cancelar</button>"+
      "<button type='button' class='btn btn-rounded' style='background-color:#2262ae;' id='mvp-continue'>Continuar</button>"+
   "
";

   $(".suscription_gst").click(function(){
      switch($(".suscription_gst").data('action')){
         case 'pause':
         Curiosity.windowMessage(title, message1);
         break;
         case 'resume':
         Curiosity.windowMessage(title, message2);
         break;
      }
   });

   $("body").on('click', '#mvp-continue', function() {
      switch($(".suscription_gst").data('action')){
         case 'pause':
         parentGlobalController.suscription.pause();
         break;
         case 'resume':
         parentGlobalController.suscription.resume();
         break;
      }
   });;

});
<commit_msg>Estableciendo texto para reactivar suscripcion<commit_after>$(function(){

   parentGlobalController.suscription.status();

   var title = "Pausar Suscripción";
   var message1 = "
"+
      "Estas a punto de pausar tu suscripción a Curiosity Educación.
Una vez que presiones en el botón de CONTINUAR tu suscripción a Curiosity se pausará y el cobro a tu tarjeta no será realizado, por lo cual todas las cuentas para tus hijos no contarán con acceso a la plataforma.

Puedes reactivar tu suscripción solo iniciando sesión y dentro de esta misma sección dar clic en el botón de Reactivar.

Nota: Al reactivar tu suscripción las cuentas de tus hijos se reactivarán automáticamente."+
   "
"+
   "
"+
      "

"+
      "<button type='button' data-dismiss='modal' aria-hidden='true' class='btn btn-rounded' style='background-color: #ed6922;"+    "padding-left:2.5rem;padding-right: 2.5rem;' id='mvp-cancelchange'>Cancelar</button>"+
      "<button type='button' class='btn btn-rounded' style='background-color:#2262ae;' id='mvp-continue'>Continuar</button>"+
   "
";

   var message2 = "
"+
      "Estas a punto de reactivar tu suscripción a Curiosity Educación.
Una vez que presiones en el botón de CONTINUAR tu suscripción a Curiosity se reactivará y el cobro a tu tarjeta se realizará en la fecha establecida, por lo cual todas las cuentas para tus hijos contarán nuevamente con acceso a la plataforma."+
   "
"+
   "
"+
      "

"+
      "<button type='button' data-dismiss='modal' aria-hidden='true' class='btn btn-rounded' style='background-color: #ed6922;"+    "padding-left:2.5rem;padding-right: 2.5rem;' id='mvp-cancelchange'>Cancelar</button>"+
      "<button type='button' class='btn btn-rounded' style='background-color:#2262ae;' id='mvp-continue'>Continuar</button>"+
   "
";

   $(".suscription_gst").click(function(){
      switch($(".suscription_gst").data('action')){
         case 'pause':
         Curiosity.windowMessage(title, message1);
         break;
         case 'resume':
         Curiosity.windowMessage(title, message2);
         break;
      }
   });

   $("body").on('click', '#mvp-continue', function() {
      switch($(".suscription_gst").data('action')){
         case 'pause':
         parentGlobalController.suscription.pause();
         break;
         case 'resume':
         parentGlobalController.suscription.resume();
         break;
      }
   });;

});
<|endoftext|>


<commit_before>var React = require('react');
var Variation = require('../../app/components/variation.react.js');

class VariationList extends React.Component {
  render(){
    return

            These variations are available:
            <Variation />
            <Variation />
            <Variation />

;
  }
};

module.exports = VariationList;
<commit_msg>Show categories.<commit_after>var React = require('react');
var VariationCategory = require('../../app/components/variation-category.react.js');

class VariationList extends React.Component {
  render(){
    var categories = this.props.categories.map((category) => {
      var variations = this.props.variations
        .filter((variation) => {
          return variation.category === category.id;
        });
      return <VariationCategory category={category} variations={variations} />
    });

    return

Diese Variationen sind verfügbar:

            {categories}

;
  }
};
module.exports = VariationList;
<|endoftext|>


<commit_before>$( document ).ready( function() {
  $('.sortable').sortable({
    stop: function(event, ui) {
      reNumber();
    },
  });

  $('#add-new').click(function() {
    var newField = $('.row.padded-field').last().clone(true);
    appendField(newField, setDefaultValues);
  });

  $('.remove').click(function() {
    var fields = $('.row.padded-field');
    var parentField = $(this).parents('.row.padded-field');
    if (fields.length > 1) {
      parentField.remove();
    } else { // If they want to remove the last field, just empty it instead.
      setDefaultValues(parentField);
    }
    reNumber();
  });

  $('.data-type select').change(function() {
    var placeholder = $(this).parents('.padded-field').find('.placeholder');
    var options = $(this).parents('.padded-field').find('.options');
    var value = this.value;
    if (takesPlaceholder(value) == true) {
      $('<input type="text" value="">').appendTo(placeholder);
    } else {
      placeholder.children().remove();
    }
    if (value == 'options') {
      var optionsField = $('<textarea class="form-control" rows="4">');
      optionsField.appendTo(options);
    } else {
      options.children().remove();
    }
  });

  // haha formform
  $('form#form').on('ajax:before', function(event, xhr, settings) {
    return false;
  });

  $('form#form').submit(function(e) {
    e.preventDefault;
    fields = $('.padded-field');
    var formData = {
      name: $('[name="form_draft[name]"]').val(),
      email: $('[name="form_draft[email]"]').val(),
      reply_to: $('[name="form_draft[reply_to]"]').val(),
      fields: extractFieldData(fields),
    };
    var data = {form_draft: formData};
    var ID = $('form').data('id');
    let URL = '/form_drafts/';
    var method = 'POST'; // create
    if (ID != undefined) {
      URL = '/form_drafts/' + ID;
      method = 'PUT'; // update
    }
    $.ajax({
      url: URL,
      method: method,
      data: data,
    }).done(function() {
      document.location.href = '/form_drafts/' + ID;
    });
  });
}); // END of document.ready

function takesPlaceholder(value) {
  return ['date', 'date/time', 'long-text', 'text', 'time'].includes(value);
}

function extractFieldData(fields) {
  var allFieldData = {};
  $('.padded-field').each( function(index) {
    var fieldData = {};
    fieldData['number'] = index + 1;
    fieldData['prompt'] = $(this).find('textarea').val();
    fieldData['placeholder'] = $(this).find('.placeholder').val();
    fieldData['required'] = $(this).find('.required :checkbox').prop('checked');
    fieldData['data_type'] = $(this).find('.data-type select').val();
    allFieldData[index] = fieldData;
    // TODO: $(this).find('.options')
  });
  return allFieldData;
}
function newNumber() {
  return $('.grabbable-number').length + 1;
}
function reNumber() {
  $('.grabbable-number').each(function(index) {
    $(this).text(index + 1);
  });
}
function setDefaultValues(field) {
  field.find('textarea').val('');
  field.find('.grabbable-number').text(newNumber());
  field.find('select').val('');
  field.find('input').val('');
}
function appendField(field, callback) {
  callback(field);
  field.appendTo('.container.sortable');
}

// $('.options').children('textarea').val() is how you grab options
<commit_msg>I forgot someone could switch between placeholder data types.<commit_after>$( document ).ready( function() {
  $('.sortable').sortable({
    stop: function(event, ui) {
      reNumber();
    },
  });

  $('#add-new').click(function() {
    var newField = $('.row.padded-field').last().clone(true);
    appendField(newField, setDefaultValues);
  });

  $('.remove').click(function() {
    var fields = $('.row.padded-field');
    var parentField = $(this).parents('.row.padded-field');
    if (fields.length > 1) {
      parentField.remove();
    } else { // If they want to remove the last field, just empty it instead.
      setDefaultValues(parentField);
    }
    reNumber();
  });

  $('.data-type select').change(function() {
    var placeholder = $(this).parents('.padded-field').find('.placeholder');
    var options = $(this).parents('.padded-field').find('.options');
    var value = this.value;
    if (takesPlaceholder(value) == true) {
      if (placeholder.children().length == 0) {
        $('<input type="text" value="">').appendTo(placeholder);
      }
    } else {
      placeholder.children().remove();
    }
    if (value == 'options') {
      var optionsField = $('<textarea class="form-control" rows="4">');
      optionsField.appendTo(options);
    } else {
      options.children().remove();
    }
  });

  // haha formform
  $('form#form').on('ajax:before', function(event, xhr, settings) {
    return false;
  });

  $('form#form').submit(function(e) {
    e.preventDefault;
    fields = $('.padded-field');
    var formData = {
      name: $('[name="form_draft[name]"]').val(),
      email: $('[name="form_draft[email]"]').val(),
      reply_to: $('[name="form_draft[reply_to]"]').val(),
      fields: extractFieldData(fields),
    };
    var data = {form_draft: formData};
    var ID = $('form').data('id');
    let URL = '/form_drafts/';
    var method = 'POST'; // create
    if (ID != undefined) {
      URL = '/form_drafts/' + ID;
      method = 'PUT'; // update
    }
    $.ajax({
      url: URL,
      method: method,
      data: data,
    }).done(function() {
      document.location.href = '/form_drafts/' + ID;
    });
  });
}); // END of document.ready

function takesPlaceholder(value) {
  return ['date', 'date/time', 'long-text', 'text', 'time'].includes(value);
}

function extractFieldData(fields) {
  var allFieldData = {};
  $('.padded-field').each( function(index) {
    var fieldData = {};
    fieldData['number'] = index + 1;
    fieldData['prompt'] = $(this).find('textarea').val();
    fieldData['placeholder'] = $(this).find('.placeholder').val();
    fieldData['required'] = $(this).find('.required :checkbox').prop('checked');
    fieldData['data_type'] = $(this).find('.data-type select').val();
    allFieldData[index] = fieldData;
    // TODO: $(this).find('.options')
  });
  return allFieldData;
}
function newNumber() {
  return $('.grabbable-number').length + 1;
}
function reNumber() {
  $('.grabbable-number').each(function(index) {
    $(this).text(index + 1);
  });
}
function setDefaultValues(field) {
  field.find('textarea').val('');
  field.find('.grabbable-number').text(newNumber());
  field.find('select').val('');
  field.find('input').val('');
}
function appendField(field, callback) {
  callback(field);
  field.appendTo('.container.sortable');
}

// $('.options').children('textarea').val() is how you grab options
<|endoftext|>


<commit_before>"use strict";

module.exports = function (window) {
    var getScrollOffsets = function() {
        var doc = window.document;
        // this works for all browsers in non quircks-mode and only for IE9+:
        if (window.pageXOffset) {
            return {
                x: window.pageXOffset,
                y: window.pageYOffset
            };
        }
        // for IE (or any other browser) in standards mode
        if (doc.compatMode === 'CSS1Compat') {
            return {
                x: doc.documentElement.scrollLeft,
                y: doc.documentElement.scrollTop
            };
        }
        // for browsers in quircks mode:
        return {
            x: doc.body.scrollLeft,
            y: doc.body.scrollTop
        };
    },

    getViewportSize = function() {
        var doc = window.document;
        // this works for all browsers in non quircks-mode and only for IE9+:
        if (window.innerWidth) {
            return {
                w: window.innerWidth,
                h: window.innerHeight
            };
        }
        // for IE (or any other browser) in standards mode
        if (doc.compatMode === 'CSS1Compat') {
            return {
                w: doc.documentElement.clientWidth,
                h: doc.documentElement.clientHeight
            };
        }
        // for browsers in quircks mode:
        return {
            w: doc.body.clientWidth,
            h: doc.body.clientHeight
        };
    };

    /**
     * Gets the left-scroll offset of the window.
     *
     * @method getScrollLeft
     * @return {Number} left-offset in pixels
     * @since 0.0.1
    */
    window.getScrollLeft = function() {
        return getScrollOffsets().x;
    };
    /**
     * Gets the top-scroll offset of the window.
     *
     * @method getScrollTop
     * @return {Number} top-offset in pixels
     * @since 0.0.1
    */
    window.getScrollTop = function() {
        return getScrollOffsets().y;
    };
   /**
    * Gets the width of the window.
    *
    * @method getWidth
    * @return {Number} width in pixels
    * @since 0.0.1
    */
    window.getWidth = function() {
        return getViewportSize().w;
    };
   /**
    * Gets the height of the window.
    *
    * @method getHeight
    * @return {Number} width in pixels
    * @since 0.0.1
    */
    window.getHeight = function() {
        return getViewportSize().h;
    };

};<commit_msg>intermediate saving<commit_after>"use strict";

module.exports = function (window) {
    var getScrollOffsets = function() {
        var doc = window.document;
        // this works for all browsers in non quircks-mode and only for IE9+:
        if (window.pageXOffset) {
            return {
                x: window.pageXOffset,
                y: window.pageYOffset
            };
        }
        // for IE (or any other browser) in standards mode
        if (doc.compatMode === 'CSS1Compat') {
            return {
                x: doc.documentElement.scrollLeft,
                y: doc.documentElement.scrollTop
            };
        }
        // for browsers in quircks mode:
        return {
            x: doc.body.scrollLeft,
            y: doc.body.scrollTop
        };
    },

    getViewportSize = function() {
        var doc = window.document;
        // this works for all browsers in non quircks-mode and only for IE9+:
        if (window.innerWidth) {
            return {
                w: window.innerWidth,
                h: window.innerHeight
            };
        }
        // for IE (or any other browser) in standards mode
        if (doc.compatMode === 'CSS1Compat') {
            return {
                w: doc.documentElement.clientWidth,
                h: doc.documentElement.clientHeight
            };
        }
        // for browsers in quircks mode:
        return {
            w: doc.body.clientWidth,
            h: doc.body.clientHeight
        };
    };

    // `window` has no prototype
    Object.defineProperties(window, {

       /**
        * Gets the height of the window in pixels.
        *
        * Values are numbers without unity.
        *
        * @property height
        * @type {Number}
        * @since 0.0.1
        */
        height: {
            get: function() {
                return getViewportSize().h;
            }
        },

       /**
        * Gets the left-scroll offset of the window in pixels.
        *
        * Values are numbers without unity.
        *
        * @property scrollLeft
        * @type {Number}
        * @since 0.0.1
        */
        scrollLeft: {
            get: function() {
                return getScrollOffsets().x;
            }
        },

       /**
        * Gets the top-scroll offset of the window in pixels.
        *
        * Values are numbers without unity.
        *
        * @property scrollTop
        * @type {Number}
        * @since 0.0.1
        */
        scrollTop: {
            get: function() {
                return getScrollOffsets().y;
            }
        },

       /**
        * Gets the width of the window in pixels.
        *
        * Values are numbers without unity.
        *
        * @property width
        * @type {Number}
        * @since 0.0.1
        */
        width: {
            get: function() {
                return getViewportSize().w;
            }
        }

    });

};<|endoftext|>


<commit_before>import Vue from 'vue';
import FileManager from 'src/components/file-manager/FileManager';

describe('FileManager.vue', () => {
  const Constructor = Vue.extend(FileManager);
  const vm = new Constructor().$mount();

  it('should render userInputs navbar component', () => {
    expect(vm.$el.querySelector('.navbar'))
      .to.not.equal(null);
  });
  it('should render userInputs userActions component', () => {
    expect(vm.$el.querySelector('.userActions'))
      .to.not.equal(null);
  });
  it('should render create folder button', () => {
    expect(vm.$el.querySelector('.userActions #button-create-folder'))
      .to.not.equal(null);
  });
  it('should render download button', () => {
    expect(vm.$el.querySelector('.userActions #button-file-download'))
      .to.not.equal(null);
  });
  it('should render delete button', () => {
    expect(vm.$el.querySelector('.userActions #button-delete'))
      .to.not.equal(null);
  });
  it('should render icon view button', () => {
    expect(vm.$el.querySelector('#button-icon-view'))
      .to.not.equal(null);
  });
  it('should render list view button', () => {
    expect(vm.$el.querySelector('#button-list-view'))
      .to.not.equal(null);
  });
  it('should render Documents component', () => {
    expect(vm.$el.querySelector('.documents'))
      .to.not.equal(null);
  });
});
<commit_msg>Get documentEle with getElementsByClassName<commit_after>import Vue from 'vue';
import FileManager from 'src/components/file-manager/FileManager';

describe('FileManager.vue', () => {
  const Constructor = Vue.extend(FileManager);
  const vm = new Constructor().$mount();

  it('should render userInputs navbar component', () => {
    expect(vm.$el.querySelector('.navbar'))
      .to.not.equal(null);
  });
  it('should render userInputs userActions component', () => {
    expect(vm.$el.querySelector('.userActions'))
      .to.not.equal(null);
  });
  it('should render create folder button', () => {
    expect(vm.$el.querySelector('.userActions #button-create-folder'))
      .to.not.equal(null);
  });
  it('should render download button', () => {
    expect(vm.$el.querySelector('.userActions #button-file-download'))
      .to.not.equal(null);
  });
  it('should render delete button', () => {
    expect(vm.$el.querySelector('.userActions #button-delete'))
      .to.not.equal(null);
  });
  it('should render icon view button', () => {
    expect(vm.$el.querySelector('#button-icon-view'))
      .to.not.equal(null);
  });
  it('should render list view button', () => {
    expect(vm.$el.querySelector('#button-list-view'))
      .to.not.equal(null);
  });
  it('should render Documents component', () => {
    const documentEle = vm.$el.getElementsByClassName('documents');
    expect(documentEle).to.not.equal(null);
  });
});
<|endoftext|>


<commit_before>import * as React from 'react';
import PropTypes from 'prop-types';
import styled from '../styles/styled';

const NotchedOutlineRoot = styled('fieldset')({
  textAlign: 'left',
  position: 'absolute',
  bottom: 0,
  right: 0,
  top: -5,
  left: 0,
  margin: 0,
  padding: '0 8px',
  pointerEvents: 'none',
  borderRadius: 'inherit',
  borderStyle: 'solid',
  borderWidth: 1,
  overflow: 'hidden',
  minWidth: '0%',
});

const NotchedOutlineLegend = styled('legend', { skipSx: true })(({ ownerState, theme }) => ({
  ...(ownerState.label === undefined && {
    padding: 0,
    lineHeight: '11px', // sync with `height` in `legend` styles
    transition: theme.transitions.create('width', {
      duration: 150,
      easing: theme.transitions.easing.easeOut,
    }),
  }),
  ...(ownerState.label !== undefined && {
    display: 'block',
    width: 'auto',
    padding: 0,
    height: 11, // sync with `lineHeight` in `legend` styles
    fontSize: '0.75em',
    visibility: 'hidden',
    maxWidth: 0.01,
    transition: theme.transitions.create('max-width', {
      duration: 50,
      easing: theme.transitions.easing.easeOut,
    }),
    '& > span': {
      paddingLeft: 5,
      paddingRight: 5,
      display: 'inline-block',
    },
    ...(ownerState.notched && {
      maxWidth: '100%',
      transition: theme.transitions.create('max-width', {
        duration: 100,
        easing: theme.transitions.easing.easeOut,
        delay: 50,
      }),
    }),
  }),
}));

/**
 * @ignore - internal component.
 */
export default function NotchedOutline(props) {
  const { children, classes, className, label, notched, ...other } = props;
  const ownerState = {
    ...props,
    notched,
    label,
  };
  return (
    <NotchedOutlineRoot aria-hidden className={className} ownerState={ownerState} {...other}>
      <NotchedOutlineLegend ownerState={ownerState}>
        {/* Use the nominal use case of the legend, avoid rendering artefacts. */}
        {label ? (
          {label}
        ) : (
          // notranslate needed while Google Translate will not fix zero-width space issue
          // eslint-disable-next-line react/no-danger

        )}
      </NotchedOutlineLegend>
    </NotchedOutlineRoot>
  );
}

NotchedOutline.propTypes = {
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   * See [CSS API](#css) below for more details.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The label.
   */
  label: PropTypes.node,
  /**
   * If `true`, the outline is notched to accommodate the label.
   */
  notched: PropTypes.bool.isRequired,
  /**
   * @ignore
   */
  style: PropTypes.object,
};
<commit_msg>[TextField] Fix invisible wrap within notched inputs (#29088)<commit_after>import * as React from 'react';
import PropTypes from 'prop-types';
import styled from '../styles/styled';

const NotchedOutlineRoot = styled('fieldset')({
  textAlign: 'left',
  position: 'absolute',
  bottom: 0,
  right: 0,
  top: -5,
  left: 0,
  margin: 0,
  padding: '0 8px',
  pointerEvents: 'none',
  borderRadius: 'inherit',
  borderStyle: 'solid',
  borderWidth: 1,
  overflow: 'hidden',
  minWidth: '0%',
});

const NotchedOutlineLegend = styled('legend', { skipSx: true })(({ ownerState, theme }) => ({
  ...(ownerState.label === undefined && {
    padding: 0,
    lineHeight: '11px', // sync with `height` in `legend` styles
    transition: theme.transitions.create('width', {
      duration: 150,
      easing: theme.transitions.easing.easeOut,
    }),
  }),
  ...(ownerState.label !== undefined && {
    display: 'block',
    width: 'auto',
    padding: 0,
    height: 11, // sync with `lineHeight` in `legend` styles
    fontSize: '0.75em',
    visibility: 'hidden',
    maxWidth: 0.01,
    transition: theme.transitions.create('max-width', {
      duration: 50,
      easing: theme.transitions.easing.easeOut,
    }),
    whiteSpace: 'nowrap',
    '& > span': {
      paddingLeft: 5,
      paddingRight: 5,
      display: 'inline-block',
    },
    ...(ownerState.notched && {
      maxWidth: '100%',
      transition: theme.transitions.create('max-width', {
        duration: 100,
        easing: theme.transitions.easing.easeOut,
        delay: 50,
      }),
    }),
  }),
}));

/**
 * @ignore - internal component.
 */
export default function NotchedOutline(props) {
  const { children, classes, className, label, notched, ...other } = props;
  const ownerState = {
    ...props,
    notched,
    label,
  };
  return (
    <NotchedOutlineRoot aria-hidden className={className} ownerState={ownerState} {...other}>
      <NotchedOutlineLegend ownerState={ownerState}>
        {/* Use the nominal use case of the legend, avoid rendering artefacts. */}
        {label ? (
          {label}
        ) : (
          // notranslate needed while Google Translate will not fix zero-width space issue
          // eslint-disable-next-line react/no-danger

        )}
      </NotchedOutlineLegend>
    </NotchedOutlineRoot>
  );
}

NotchedOutline.propTypes = {
  /**
   * The content of the component.
   */
  children: PropTypes.node,
  /**
   * Override or extend the styles applied to the component.
   * See [CSS API](#css) below for more details.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The label.
   */
  label: PropTypes.node,
  /**
   * If `true`, the outline is notched to accommodate the label.
   */
  notched: PropTypes.bool.isRequired,
  /**
   * @ignore
   */
  style: PropTypes.object,
};
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import themed from 'react-themed'
import Field from '../Field'

@themed(['Message', 'Label_Textarea'], { pure: true })
export default class Message extends PureComponent {
  static propTypes = {
    name: PropTypes.string,
    type: PropTypes.string,
    theme: PropTypes.object,
    label: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.object,
      PropTypes.func,
    ]),
  }

  static defaultProps = {
    theme: {},
    name: 'message',
    type: 'textarea',
  }

  render() {
    const { theme, ...props } = this.props
    return (
      <Field className={theme.Message} {...props} />
    )
  }
}
<commit_msg>removed wierd theme class that wasn't related<commit_after>import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import themed from 'react-themed'
import Field from '../Field'

@themed(['Message'], { pure: true })
export default class Message extends PureComponent {
  static propTypes = {
    name: PropTypes.string,
    type: PropTypes.string,
    theme: PropTypes.object,
    label: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.object,
      PropTypes.func,
    ]),
  }

  static defaultProps = {
    theme: {},
    name: 'message',
    type: 'textarea',
  }

  render() {
    const { theme, ...props } = this.props
    return (
      <Field className={theme.Message} {...props} />
    )
  }
}
<|endoftext|>


<commit_before>var accessToken;
var apiRoot = 'https://api.ciscospark.com/v1/';

/**
 * Default parameters used for all API requests.
 *
 * @type {{dataType: string, headers: {Authorization: string}}}
 */
var defaults;

/**
 * Initialization of module.
 */
var init = function(){
    defaults = {
        'dataType' : 'json',
        'error' : function(jqXHR, textStatus, errorThrown){
            console.log(jqXHR.status, errorThrown);
        },
        'headers' : {
            'Authorization' : 'Bearer ' + accessToken
        },
        'success' : function(data){
            console.log(data);
        }
    };
};

/**
 * Constructor for library.
 *
 * @param       _accessToken Valid access token form OAuth login
 * @constructor
 */
function Spark(_accessToken){
    accessToken = _accessToken;
    init();
}

/**
 * Gets details from logged in user.
 *
 * @param success   Callback on success, parameter will be JSON response
 * @param error     Callback on error, parameters will be jqXHR object, String textStatus, and String errorThrown
 */
Spark.prototype.getMyDetails = function(success, error){
    $.ajax($.extend(defaults, {
        'error' : error,
        'success' : success,
        'url' : apiRoot + 'people/me'
    }));
};

/**
 * Lists messages for a specific room.
 *
 * @param options   https://developer.ciscospark.com/endpoint-messages-get.html
 * @param success   Callback on success, parameter will be JSON response
 * @param error     Callback on error, parameters will be jqXHR object, String textStatus, and String errorThrown
 */
Spark.prototype.listMessages = function(options, success, error){
    $.ajax($.extend(defaults, {
        'data' : options,
        'error' : error,
        'success' : success,
        'url' : apiRoot + 'messages'
    }));
};

/**
 * Lists rooms that the logged in user is a member of.
 *
 * @param options   https://developer.ciscospark.com/endpoint-rooms-get.html
 * @param success   Callback on success, parameter will be JSON response
 * @param error     Callback on error, parameters will be jqXHR object, String textStatus, and String errorThrown
 */
Spark.prototype.listRooms = function(options, success, error){
    $.ajax($.extend(defaults, {
        'data' : options,
        'error' : error,
        'success' : success,
        'url' : apiRoot + 'rooms'
    }));
};

/**
 * Posts a plain text message, and optionally, a media content attachment, to a room.
 *
 * @param options   https://developer.ciscospark.com/endpoint-messages-post.html
 * @param success   Callback on success, parameter will be JSON response
 * @param error     Callback on error, parameters will be jqXHR object, String textStatus, and String errorThrown
 */
Spark.prototype.createMessage = function(options, success, error){
    $.ajax($.extend(defaults, {
        'data' : options,
        'error' : error,
        'success' : success,
        'type' : 'POST',
        'url' : apiRoot + 'messages'
    }));
};

module.exports = Spark;
<commit_msg>Added getter/setter for access token<commit_after>var accessToken;
var apiRoot = 'https://api.ciscospark.com/v1/';

/**
 * Default parameters used for all API requests.
 *
 * @type {{dataType: string, headers: {Authorization: string}}}
 */
var defaults;

/**
 * Initialization of module.
 */
var init = function(){
    defaults = {
        'dataType' : 'json',
        'error' : function(jqXHR, textStatus, errorThrown){
            console.log(jqXHR.status, errorThrown);
        },
        'headers' : {
            'Authorization' : 'Bearer ' + accessToken
        },
        'success' : function(data){
            console.log(data);
        }
    };
};

/**
 * Constructor for library.
 *
 * @param       _accessToken Valid access token form OAuth login
 * @constructor
 */
function Spark(_accessToken){
    accessToken = _accessToken;
    init();
}

/**
 * Sets new access token.
 *
 * @param _accessToken Valid access token form OAuth login
 */
Spark.prototype.setToken = function(_accessToken){
    accessToken = _accessToken;
    init();
};

/**
 * Retrieves access token.
 *
 * @returns String The access token
 */
Spark.prototype.getToken = function(){
    return accessToken;
};

/**
 * Gets details from logged in user.
 *
 * @param success   Callback on success, parameter will be JSON response
 * @param error     Callback on error, parameters will be jqXHR object, String textStatus, and String errorThrown
 */
Spark.prototype.getMyDetails = function(success, error){
    $.ajax($.extend(defaults, {
        'error' : error,
        'success' : success,
        'url' : apiRoot + 'people/me'
    }));
};

/**
 * Lists messages for a specific room.
 *
 * @param options   https://developer.ciscospark.com/endpoint-messages-get.html
 * @param success   Callback on success, parameter will be JSON response
 * @param error     Callback on error, parameters will be jqXHR object, String textStatus, and String errorThrown
 */
Spark.prototype.listMessages = function(options, success, error){
    $.ajax($.extend(defaults, {
        'data' : options,
        'error' : error,
        'success' : success,
        'url' : apiRoot + 'messages'
    }));
};

/**
 * Lists rooms that the logged in user is a member of.
 *
 * @param options   https://developer.ciscospark.com/endpoint-rooms-get.html
 * @param success   Callback on success, parameter will be JSON response
 * @param error     Callback on error, parameters will be jqXHR object, String textStatus, and String errorThrown
 */
Spark.prototype.listRooms = function(options, success, error){
    $.ajax($.extend(defaults, {
        'data' : options,
        'error' : error,
        'success' : success,
        'url' : apiRoot + 'rooms'
    }));
};

/**
 * Posts a plain text message, and optionally, a media content attachment, to a room.
 *
 * @param options   https://developer.ciscospark.com/endpoint-messages-post.html
 * @param success   Callback on success, parameter will be JSON response
 * @param error     Callback on error, parameters will be jqXHR object, String textStatus, and String errorThrown
 */
Spark.prototype.createMessage = function(options, success, error){
    $.ajax($.extend(defaults, {
        'data' : options,
        'error' : error,
        'success' : success,
        'type' : 'POST',
        'url' : apiRoot + 'messages'
    }));
};

module.exports = Spark;
<|endoftext|>