<commit_before>var duplicateArray = new Array();
var tdColorArray = new Array();
var highlightColor = '#FFF3D3';

/**
 * Run a function checking if we already have items in the bag
 */
function checkIfAlreadyInTheBag() {
    // run a function checking if we already have items in the bag
    jQuery('span.fakelink').each(function(index) {
      // get the element id
      var id = jQuery(this).attr("id");
      // parse out the actual identifier
      var identifier = id.substring(id.lastIndexOf("_") + 1);

      // check if we have it
      if (isIdentifierInTheBag(identifier)) {
        // ...then select it
        jQuery(this).click();
        // ...and remove the controls
        jQuery(this).parent().html("
Already in your list.
")
      }
    });
}

/**
 * give us a list of items in the bag currently
 */
function getIdentifiersInTheBag() {
  return jQuery("#matchIDs").val().split(" ");
}

/**
 * check if value is already in a bag
 * @param identifier, actual object ID
 * @returns {Boolean}
 */
function isIdentifierInTheBag(identifier) {
  var array = getIdentifiersInTheBag();
  for (var i = 0; i < array.length; i++) {
    if (identifier == array[i]) {
      return true;
    }
  }
  return false;
}

/**
 * Add an identifier into the bag
 * @param objectId of the actual row
 * @param row number relative to the table in question
 * @param parentId is the identifier we were trying to upload
 * @param issueType, e.g.: 'duplicate' etc.
 * @return
 */
function addId2Bag(objectId, row, parentId, issueType) {
  // I can remove now...
  setLinkState('removeAllLink', 'active');

  if (jQuery('#add_' + issueType + '_' + objectId).hasClass('fakelink')) {
      // switch the class on add/remove links
      jQuery('span#add_' + issueType + '_' + objectId).removeClass('fakelink');
      jQuery('span#rem_' + issueType + '_' + objectId).addClass('fakelink');

      // colour the row columns (even associated rows, based on object id)
      jQuery('span#add_' + issueType + '_' + objectId).each(function(i) {
        var rowId = jQuery(this).parent().attr('class').split(" ")[1];
        colourRow(rowId, true);
      });

      if (!isIdentifierInTheBag(objectId)) {
        // update the number of matches count
        updateCount('#matchCount', 1);

        // now update the count of items in a JS var from bagUploadConfirm.jsp
        if (matchCount != null) {
          matchCount++;
        }
      }

      // remove identifier from a list of additional matches to upload
      addIdToListOfMatches(objectId);

      var idArray = duplicateArray[parentId];
      if (idArray == null) {
        duplicateArray[parentId] = new Array(objectId);

        // decrease count
        updateCount('#' + issueType + 'Count', -1);

        // apply bg color to identifier(s)
        jQuery('span#add_' + issueType + '_' + objectId).each(function(i) {
          var tdId = jQuery(this).parent().parent().attr('id').substring(3);
          jQuery('td#td_' + issueType + '_' + tdId).addClass('highlight');
        });

        // decrease count
        updateCount('#initialIdCount', -1);
      } else {
        idArray[idArray.length] = objectId;
        duplicateArray[parentId] = idArray;
      }

      setLinkState(issueType + 'removeAllLink', 'active');

      // update the text of the button that saves our list
      updateFurtherMatchesDisplay();
    } else {
      // update the color anyways, we are already included through another object
      //jQuery('span#add_' + issueType + '_' + objectId).parent().parent().css('background-color', highlightColor);
    }
}

/**
 * Remove identifier from the bag
 * @param objectId of the actual row
 * @param row number relative to the table in question
 * @param parentId is the identifier we were trying to upload
 * @param issueType, e.g.: 'duplicate' etc.
 * @return
 */
function removeIdFromBag(objectId, row, parentId, issueType) {
    setLinkState('addAllLink', 'active');

    if (jQuery('#rem_' + issueType + '_' + objectId).hasClass('fakelink')) {
    // switch the class on remove/add links
    jQuery('span#rem_' + issueType + '_' + objectId).removeClass('fakelink');
    jQuery('span#add_' + issueType + '_' + objectId).addClass('fakelink');

    // decolour the row columns (even associated rows, based on object id)
    jQuery('span#add_' + issueType + '_' + objectId).each(function(i) {
      var rowId = jQuery(this).parent().attr('class').split(" ")[1];
      colourRow(rowId, false);
    });

    if (isIdentifierInTheBag(objectId)) {
      // update the number of matches count
      updateCount('#matchCount', -1);

      // now update the count of items in a JS var from bagUploadConfirm.jsp
      if (matchCount != null) {
        matchCount--;
      }
    }

    // remove identifier from a list of additional matches to upload
    removeIdFromListOfMatches(objectId);

    var idArray = duplicateArray[parentId];
    if (idArray != null) {
      if (idArray.length == 1) {
        // increase count
        updateCount('#' + issueType + 'Count', 1);

        // 'remove' background color from identifier
        jQuery('span#add_' + issueType + '_' + objectId).each(function(i){
          var tdId = jQuery(this).parent().parent().attr('id').substring(3);
          jQuery('td#td_' + issueType + '_' + tdId).removeClass('highlight');
        });

        // reduce count
        updateCount('#initialCount', -1);

        duplicateArray[parentId] = null;
      } else {
        var idArrayCopy = new Array();

        jQuery.each(idArray, function(i, value) {
          if (objectId != value) {
            idArrayCopy[idArrayCopy.length] = idArray[i];
          }
        });

        duplicateArray[parentId] = idArrayCopy;
      }
    }

    setLinkState(issueType + 'addAllLink', 'active');

    // update the text of the button that saves our list
    updateFurtherMatchesDisplay();
  }
}

/**
 * Set color on row elements
 * @param rowClass
 * @param highlighted true if we are highlighting now
 * @return
 */
function colourRow(rowClass, highlighted) {
  // match all 'row_duplicate_0' elements
  jQuery('td.' + rowClass).each(function(index) {
    // are we highlighting?
    if (highlighted) {
      tdColorArray[rowClass] = jQuery(this).css('background-color');
      jQuery(this).css('background-color', highlightColor);
    } else {
      // set color back (transparent)
      jQuery(this).css('background-color', tdColorArray[rowClass]);
    }
  });

}

/**
 * Will update a count in an element, checks if element exists first
 * @param element jQuery syntax
 * @param amount integer
 * @return
 * @deprecated possibly... :)
 */
function updateCount(element, amount) {
  // exists?
  if (jQuery(element).length > 0) {
    // parse value
    var count = parseInt(jQuery(element).text()) + amount;
    // set value
    jQuery(element).text(count);
  }
}

/**
 * Will check the current number of matches vs the total count and appropriately show info message
 *  and update form button text with the totals
 * @return
 */
function updateFurtherMatchesDisplay() {
  // update the text of the button that saves our list
  if (jQuery('input#saveList').length > 0) {
    if (matchCount > 0) {
      // button style
      jQuery('input#saveList').parent().removeClass('inactive');
      // button text
      if (matchCount > 1) {
        jQuery('input#saveList').val("Save a list of " + matchCount + " " + listType + "s");
      } else {
        jQuery('input#saveList').val("Save a list of " + matchCount + " " + listType);
      }
    } else {
      // button style
      jQuery('input#saveList').parent().addClass('inactive');
      // button text
      jQuery('input#saveList').val("0 " + listType);
    }
    // "further matches" text
    if (jQuery('p#furtherMatches').length > 0) {
      if (matchCount < totalCount) {
        jQuery('p#furtherMatches').html(furtherMatchesText);
      } else {
        jQuery('p#furtherMatches').html(null);
      }
    }
  }
}

function unHighlightRow(rowId) {
    colourRow(rowId, false);
}

/**
 * Will add an identifier to a list of matches in #matchIDs hidden input element
 * @param identifier we were trying to upload
 * @return
 */
function addIdToListOfMatches(identifier) {
  var bagList = jQuery('input#matchIDs').val();

  if (bagList.indexOf(identifier) == -1) {
    // add an extra space if we have elements inside already
    if (bagList.length > 0) {
      bagList += " ";
    }
    jQuery('input#matchIDs').val(bagList + identifier);
  }
}

/**
 * Will remove an identifier from a list of matches in #matchIDs hidden input element
 * @param identifier we were trying to upload
 * @return
 */
function removeIdFromListOfMatches(identifier) {
  // get the list of identifiers
  var bagList = jQuery("#matchIDs").val();

  // if we have found the identifier in the string
  if (bagList.indexOf(identifier) > -1) { // jQuery.inArray() not consistent...
    // remove the identifier from an array
    bagList = jQuery.grep(bagList.split(' '), function(value) { return value != identifier; });
    // turn array into string and replace all "," with a space
    jQuery("#matchIDs").val(bagList.toString().replace(new RegExp(",","g"), ' '));
  } else {
    // trying to remove an element that is not in the list
  }
}

function addAll(issue, flatArray){
  // split string into rows
  // a,b,c,d|e,f,g,h
  var a = flatArray.split("|");
    if (a.length > 1000 || (a.length > 200 && BrowserDetect.browser == 'Explorer')) {
        var r = window.confirm('There are many items in the table. This operation can take a while. Please be patient and do not stop script or cancel it now.');
        if (! (r == true)) {
            return;
        }
    }
  for (i = 0; i  1000 || (a.length > 500 && BrowserDetect.browser == 'Explorer')) {
        var r = window.confirm('There are many items in the table. This operation can take a while. Please be patient and do not stop script or cancel it now.');
        if (! (r == true)) {
            return;
        }
    }
  for (i = 0; i < a.length -1; i++) {
    // split rows into vars
    var b = a[i].split(",");
    removeIdFromBag(b[0], b[1], b[2], b[3]);
  }
  toggleBagLinks(issue, 'remove');
}

function toggleBagLinks(issue, action) {

  toggleBagLink(issue, action);
  if (issue == 'all') {
    toggleBagLink('lowQ', action);
    toggleBagLink('duplicate', action);
    toggleBagLink('converted', action);
  }
}

function toggleBagLink(issue, action) {

  var addAllLink = 'addAllLink';
  var removeAllLink = 'removeAllLink';

  if (issue != 'all') {
    addAllLink = issue + addAllLink;
    removeAllLink = issue + removeAllLink;

    // update individual adders in the sidebar as well
    if (jQuery('#sidebar').length > 0) {
      jQuery('#sidebar ul li.' + issue).toggleClass('added');
    }
  }
  if (action == 'remove') {
    setLinkState(addAllLink, 'active');
    setLinkState(removeAllLink, 'passive');
  } else {
    setLinkState(addAllLink, 'passive');
    setLinkState(removeAllLink, 'active');
  }

}

/**
 * Switch between the state of the 'links' that add/remove identifiers
 * @param link
 * @param state
 * @return
 */
function setLinkState(link, state) {
  if (jQuery('#' + link).length > 0) {
    if (state == 'active') {
      jQuery('#' + link).addClass("fakelink");
    } else {
      jQuery('#' + link).removeClass("fakelink");
    }
  }
}

<commit_msg>Bag Upload Confirm check if matches remaining with jQuery<commit_after>var duplicateArray = new Array();
var tdColorArray = new Array();
var highlightColor = '#FFF3D3';

/**
 * Run a function checking if we already have items in the bag
 */
function checkIfAlreadyInTheBag() {
    // run a function checking if we already have items in the bag
    jQuery('span.fakelink').each(function(index) {
      // get the element id
      var id = jQuery(this).attr("id");
      // parse out the actual identifier
      var identifier = id.substring(id.lastIndexOf("_") + 1);

      // check if we have it
      if (isIdentifierInTheBag(identifier)) {
        // ...then select it
        jQuery(this).click();
        // ...and remove the controls
        jQuery(this).parent().html("
Already in your list.
")
      }
    });
}

/**
 * give us a list of items in the bag currently
 */
function getIdentifiersInTheBag() {
  return jQuery("#matchIDs").val().split(" ");
}

/**
 * check if value is already in a bag
 * @param identifier, actual object ID
 * @returns {Boolean}
 */
function isIdentifierInTheBag(identifier) {
  var array = getIdentifiersInTheBag();
  for (var i = 0; i < array.length; i++) {
    if (identifier == array[i]) {
      return true;
    }
  }
  return false;
}

/**
 * We cannot rely on JSP to give us an accurate number of matches we have
 * in a bag anymore, thus run this method to count the number of rows
 * highlighted (= used)
 */
function hasUnhighlightedRows() {
  var unhighlighted = false;
  jQuery("#additionalMatches table.inlineResultsTable tbody tr").each(function(index) {
    if (jQuery(this).find('td:not(.identifier)').first().attr('style') != 'background-color: rgb(255, 243, 211);') {
      unhighlighted = true;
      return false;
    }
  });
  return unhighlighted;
}

/**
 * Add an identifier into the bag
 * @param objectId of the actual row
 * @param row number relative to the table in question
 * @param parentId is the identifier we were trying to upload
 * @param issueType, e.g.: 'duplicate' etc.
 * @return
 */
function addId2Bag(objectId, row, parentId, issueType) {
  // I can remove now...
  setLinkState('removeAllLink', 'active');

  if (jQuery('#add_' + issueType + '_' + objectId).hasClass('fakelink')) {
      // switch the class on add/remove links
      jQuery('span#add_' + issueType + '_' + objectId).removeClass('fakelink');
      jQuery('span#rem_' + issueType + '_' + objectId).addClass('fakelink');

      // colour the row columns (even associated rows, based on object id)
      jQuery('span#add_' + issueType + '_' + objectId).each(function(i) {
        var rowId = jQuery(this).parent().attr('class').split(" ")[1];
        colourRow(rowId, true);
      });

      if (!isIdentifierInTheBag(objectId)) {
        // update the number of matches count
        updateCount('#matchCount', 1);

        // now update the count of items in a JS var from bagUploadConfirm.jsp
        if (matchCount != null) {
          matchCount++;
        }
      }

      // remove identifier from a list of additional matches to upload
      addIdToListOfMatches(objectId);

      var idArray = duplicateArray[parentId];
      if (idArray == null) {
        duplicateArray[parentId] = new Array(objectId);

        // decrease count
        updateCount('#' + issueType + 'Count', -1);

        // apply bg color to identifier(s)
        jQuery('span#add_' + issueType + '_' + objectId).each(function(i) {
          var tdId = jQuery(this).parent().parent().attr('id').substring(3);
          jQuery('td#td_' + issueType + '_' + tdId).addClass('highlight');
        });

        // decrease count
        updateCount('#initialIdCount', -1);
      } else {
        idArray[idArray.length] = objectId;
        duplicateArray[parentId] = idArray;
      }

      setLinkState(issueType + 'removeAllLink', 'active');

      // update the text of the button that saves our list
      updateFurtherMatchesDisplay();
    } else {
      // update the color anyways, we are already included through another object
      //jQuery('span#add_' + issueType + '_' + objectId).parent().parent().css('background-color', highlightColor);
    }
}

/**
 * Remove identifier from the bag
 * @param objectId of the actual row
 * @param row number relative to the table in question
 * @param parentId is the identifier we were trying to upload
 * @param issueType, e.g.: 'duplicate' etc.
 * @return
 */
function removeIdFromBag(objectId, row, parentId, issueType) {
    setLinkState('addAllLink', 'active');

    if (jQuery('#rem_' + issueType + '_' + objectId).hasClass('fakelink')) {
    // switch the class on remove/add links
    jQuery('span#rem_' + issueType + '_' + objectId).removeClass('fakelink');
    jQuery('span#add_' + issueType + '_' + objectId).addClass('fakelink');

    // decolour the row columns (even associated rows, based on object id)
    jQuery('span#add_' + issueType + '_' + objectId).each(function(i) {
      var rowId = jQuery(this).parent().attr('class').split(" ")[1];
      colourRow(rowId, false);
    });

    if (isIdentifierInTheBag(objectId)) {
      // update the number of matches count
      updateCount('#matchCount', -1);

      // now update the count of items in a JS var from bagUploadConfirm.jsp
      if (matchCount != null) {
        matchCount--;
      }
    }

    // remove identifier from a list of additional matches to upload
    removeIdFromListOfMatches(objectId);

    var idArray = duplicateArray[parentId];
    if (idArray != null) {
      if (idArray.length == 1) {
        // increase count
        updateCount('#' + issueType + 'Count', 1);

        // 'remove' background color from identifier
        jQuery('span#add_' + issueType + '_' + objectId).each(function(i){
          var tdId = jQuery(this).parent().parent().attr('id').substring(3);
          jQuery('td#td_' + issueType + '_' + tdId).removeClass('highlight');
        });

        // reduce count
        updateCount('#initialCount', -1);

        duplicateArray[parentId] = null;
      } else {
        var idArrayCopy = new Array();

        jQuery.each(idArray, function(i, value) {
          if (objectId != value) {
            idArrayCopy[idArrayCopy.length] = idArray[i];
          }
        });

        duplicateArray[parentId] = idArrayCopy;
      }
    }

    setLinkState(issueType + 'addAllLink', 'active');

    // update the text of the button that saves our list
    updateFurtherMatchesDisplay();
  }
}

/**
 * Set color on row elements
 * @param rowClass
 * @param highlighted true if we are highlighting now
 * @return
 */
function colourRow(rowClass, highlighted) {
  // match all 'row_duplicate_0' elements
  jQuery('td.' + rowClass).each(function(index) {
    // are we highlighting?
    if (highlighted) {
      tdColorArray[rowClass] = jQuery(this).css('background-color');
      jQuery(this).css('background-color', highlightColor);
    } else {
      // set color back (transparent)
      jQuery(this).css('background-color', tdColorArray[rowClass]);
    }
  });

}

/**
 * Will update a count in an element, checks if element exists first
 * @param element jQuery syntax
 * @param amount integer
 * @return
 * @deprecated possibly... :)
 */
function updateCount(element, amount) {
  // exists?
  if (jQuery(element).length > 0) {
    // parse value
    var count = parseInt(jQuery(element).text()) + amount;
    // set value
    jQuery(element).text(count);
  }
}

/**
 * Will check the current number of matches vs the total count and appropriately show info message
 *  and update form button text with the totals
 * @return
 */
function updateFurtherMatchesDisplay() {
  // update the text of the button that saves our list
  if (jQuery('input#saveList').length > 0) {
    if (matchCount > 0) {
      // button style
      jQuery('input#saveList').parent().removeClass('inactive');
      // button text
      if (matchCount > 1) {
        jQuery('input#saveList').val("Save a list of " + matchCount + " " + listType + "s");
      } else {
        jQuery('input#saveList').val("Save a list of " + matchCount + " " + listType);
      }
    } else {
      // button style
      jQuery('input#saveList').parent().addClass('inactive');
      // button text
      jQuery('input#saveList').val("0 " + listType);
    }
    // "further matches" text
    if (jQuery('p#furtherMatches').length > 0) {
      if (hasUnhighlightedRows()) {
        jQuery('p#furtherMatches').html(furtherMatchesText);
      } else {
        jQuery('p#furtherMatches').html(null);
      }
    }
  }
}

function unHighlightRow(rowId) {
    colourRow(rowId, false);
}

/**
 * Will add an identifier to a list of matches in #matchIDs hidden input element
 * @param identifier we were trying to upload
 * @return
 */
function addIdToListOfMatches(identifier) {
  var bagList = jQuery('input#matchIDs').val();

  if (bagList.indexOf(identifier) == -1) {
    // add an extra space if we have elements inside already
    if (bagList.length > 0) {
      bagList += " ";
    }
    jQuery('input#matchIDs').val(bagList + identifier);
  }
}

/**
 * Will remove an identifier from a list of matches in #matchIDs hidden input element
 * @param identifier we were trying to upload
 * @return
 */
function removeIdFromListOfMatches(identifier) {
  // get the list of identifiers
  var bagList = jQuery("#matchIDs").val();

  // if we have found the identifier in the string
  if (bagList.indexOf(identifier) > -1) { // jQuery.inArray() not consistent...
    // remove the identifier from an array
    bagList = jQuery.grep(bagList.split(' '), function(value) { return value != identifier; });
    // turn array into string and replace all "," with a space
    jQuery("#matchIDs").val(bagList.toString().replace(new RegExp(",","g"), ' '));
  } else {
    // trying to remove an element that is not in the list
  }
}

function addAll(issue, flatArray){
  // split string into rows
  // a,b,c,d|e,f,g,h
  var a = flatArray.split("|");
    if (a.length > 1000 || (a.length > 200 && BrowserDetect.browser == 'Explorer')) {
        var r = window.confirm('There are many items in the table. This operation can take a while. Please be patient and do not stop script or cancel it now.');
        if (! (r == true)) {
            return;
        }
    }
  for (i = 0; i  1000 || (a.length > 500 && BrowserDetect.browser == 'Explorer')) {
        var r = window.confirm('There are many items in the table. This operation can take a while. Please be patient and do not stop script or cancel it now.');
        if (! (r == true)) {
            return;
        }
    }
  for (i = 0; i < a.length -1; i++) {
    // split rows into vars
    var b = a[i].split(",");
    removeIdFromBag(b[0], b[1], b[2], b[3]);
  }
  toggleBagLinks(issue, 'remove');
}

function toggleBagLinks(issue, action) {

  toggleBagLink(issue, action);
  if (issue == 'all') {
    toggleBagLink('lowQ', action);
    toggleBagLink('duplicate', action);
    toggleBagLink('converted', action);
  }
}

function toggleBagLink(issue, action) {

  var addAllLink = 'addAllLink';
  var removeAllLink = 'removeAllLink';

  if (issue != 'all') {
    addAllLink = issue + addAllLink;
    removeAllLink = issue + removeAllLink;

    // update individual adders in the sidebar as well
    if (jQuery('#sidebar').length > 0) {
      jQuery('#sidebar ul li.' + issue).toggleClass('added');
    }
  }
  if (action == 'remove') {
    setLinkState(addAllLink, 'active');
    setLinkState(removeAllLink, 'passive');
  } else {
    setLinkState(addAllLink, 'passive');
    setLinkState(removeAllLink, 'active');
  }

}

/**
 * Switch between the state of the 'links' that add/remove identifiers
 * @param link
 * @param state
 * @return
 */
function setLinkState(link, state) {
  if (jQuery('#' + link).length > 0) {
    if (state == 'active') {
      jQuery('#' + link).addClass("fakelink");
    } else {
      jQuery('#' + link).removeClass("fakelink");
    }
  }
}

<|endoftext|>


<commit_before>// EMAIL NEWSLETTER SIGNUPS

const changeEmailContainerBackground = ({ element, visible }) => {
	const color = !visible
		? '#fff'
		: '#333'
	const mode = !visible
		? 'add'
		: 'remove'
	for (let i = 0; i < element.children.length; i++) {
		// Elements are contained inside `email-form` class...
		if (element.children[i].className === 'email-form') {
      // Make the email signup box title and button white instead of charcoal.
      const title = element.children[i].querySelectorAll('div.title.small')[0]
      title.style.color = color
      const button = element.children[i].querySelectorAll('a.button.transparent')[0]
      button.style.color = color
      // Input elements are listed as children...
			for (let j = 0; j < element.children[i].length; j++) {
				const inputElement = element.children[i][j]
				// ...so make the input placeholders white instead of charcoal.
				if (inputElement.className.includes('input') || inputElement.className.includes('textarea')) {
					if (mode === 'add') {
						inputElement.classList.add('white-placeholder')
					}
					else {
						inputElement.classList.remove('white-placeholder')
					}
				}
			}
		}
	}

	}

// 1. Define all input fields
const formNames = [
	'hero',
]
const formFields = [
	'first_name',
	'last_name',
	'email',
	'verification'
]

// 2. Only once all fields are entered, enable button.
const verifyEmailSignup = e => {
	formNames.forEach(inputCategory => {
		// If change was made in a certain email signup category...
		if (e.target.id.includes(inputCategory)) {
			// ...check to see if every field has been filled out correctly...
			const complete = formFields.every(inputField => {
				const field = document.getElementById(inputCategory + '_' + inputField)
				if (inputField === 'first_name' || inputField === 'last_name') {
					// Prevent ALL CAPS
					field.value = field.value.toLowerCase()
					// Title case
					field.value = field.value.charAt(0).toUpperCase() + field.value.slice(1)
					// No empty spaces
					if (field.value.includes(' ')) {
						field.value = field.value.replace(' ', '')
					}
				}
				const emailRegex = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/igm
				// return true if all fields have been filled out
				return (
					((inputField === 'first_name' || inputField === 'last_name') && field.value.length > 1)
					|| (inputField === 'email' && field.value.length > 4 && emailRegex.test(field.value))
				)
			})
			const showAlert = formFields.every(inputField => {
				const field = document.getElementById(inputCategory + '_' + inputField)
				return (
					// Only show alert once every field has been touched...
					field.value.length > 0
				)
			})
			// ...and if so, change button class to active, and submit form.
			const buttonField = document.getElementById(inputCategory + '_button')
			const alertField = document.getElementById(inputCategory + '_alert')
			// Only show alert if all fields have been filled out somewhat, but not yet validated
			if (showAlert) {
				alertField.classList.remove('hidden')
			}
			else {
				alertField.classList.add('hidden')
			}
			if (complete && !showAlert) {
				buttonField.classList.remove('disabled')
				const formField = document.getElementById(inputCategory + '_form')
				formField.action = 'https://app.getresponse.com/add_subscriber.html'
				buttonField.addEventListener('click', () => formField.submit())
			}
			// ...otherwise, disable form.
			else {
				buttonField.classList.add('disabled')
				const formField = document.getElementById(inputCategory + '_form')
				formField.action = ''
				buttonField.removeEventListener('click', () => null)
			}
		}
	})
}

// 3. Assign enable button function to all relevant fields, and trigger submit if user presses enter
formNames.forEach(inputCategory => {
	formFields.forEach(inputField => {
		const field = document.getElementById(inputCategory + '_' + inputField)
		if (field) {
			field.oninput = verifyEmailSignup
			field.addEventListener('keypress', e => {
				const key = e.which || e.keyCode
				// If `enter` key is pressed, attempt to submit form
				if (key === 13) {
					const buttonField = document.getElementById(inputCategory + '_button')
					buttonField.click()
				}
			})
		}
	})
})<commit_msg>Reg form modal display.<commit_after>// EMAIL NEWSLETTER SIGNUPS

const changeEmailContainerBackground = ({ element, visible }) => {
	const color = !visible
		? '#fff'
		: '#333'
	const mode = !visible
		? 'add'
		: 'remove'
	for (let i = 0; i < element.children.length; i++) {
		// Elements are contained inside `email-form` class...
		if (element.children[i].className === 'email-form') {
      // Make the email signup box title and button white instead of charcoal.
      console.log(element)
      console.log(element.children)
      console.log(element.children[i])
      const title = element.children[i].querySelectorAll('div.title.small')[0]
      title.style.color = color
      const button = element.children[i].querySelectorAll('a.button.transparent')[0]
      button.style.color = color
      // Input elements are listed as children...
			for (let j = 0; j < element.children[i].length; j++) {
				const inputElement = element.children[i][j]
				// ...so make the input placeholders white instead of charcoal.
				if (inputElement.className.includes('input') || inputElement.className.includes('textarea')) {
					if (mode === 'add') {
						inputElement.classList.add('white-placeholder')
					}
					else {
						inputElement.classList.remove('white-placeholder')
					}
				}
			}
		}
	}

	}

// 1. Define all input fields
const formNames = [
	'hero',
]
const formFields = [
	'first_name',
	'last_name',
	'email',
	'verification'
]

// 2. Only once all fields are entered, enable button.
const verifyEmailSignup = e => {
	formNames.forEach(inputCategory => {
		// If change was made in a certain email signup category...
		if (e.target.id.includes(inputCategory)) {
			// ...check to see if every field has been filled out correctly...
			const complete = formFields.every(inputField => {
				const field = document.getElementById(inputCategory + '_' + inputField)
				if (inputField === 'first_name' || inputField === 'last_name') {
					// Prevent ALL CAPS
					field.value = field.value.toLowerCase()
					// Title case
					field.value = field.value.charAt(0).toUpperCase() + field.value.slice(1)
					// No empty spaces
					if (field.value.includes(' ')) {
						field.value = field.value.replace(' ', '')
					}
				}
				const emailRegex = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/igm
				// return true if all fields have been filled out
				return (
					((inputField === 'first_name' || inputField === 'last_name') && field.value.length > 1)
					|| (inputField === 'email' && field.value.length > 4 && emailRegex.test(field.value))
				)
			})
			const showAlert = formFields.every(inputField => {
				const field = document.getElementById(inputCategory + '_' + inputField)
				return (
					// Only show alert once every field has been touched...
					field.value.length > 0
				)
			})
			// ...and if so, change button class to active, and submit form.
			const buttonField = document.getElementById(inputCategory + '_button')
			const alertField = document.getElementById(inputCategory + '_alert')
			// Only show alert if all fields have been filled out somewhat, but not yet validated
			if (showAlert) {
				alertField.classList.remove('hidden')
			}
			else {
				alertField.classList.add('hidden')
			}
			if (complete && !showAlert) {
				buttonField.classList.remove('disabled')
				const formField = document.getElementById(inputCategory + '_form')
				formField.action = 'https://app.getresponse.com/add_subscriber.html'
				buttonField.addEventListener('click', () => formField.submit())
			}
			// ...otherwise, disable form.
			else {
				buttonField.classList.add('disabled')
				const formField = document.getElementById(inputCategory + '_form')
				formField.action = ''
				buttonField.removeEventListener('click', () => null)
			}
		}
	})
}

// 3. Assign enable button function to all relevant fields, and trigger submit if user presses enter
formNames.forEach(inputCategory => {
	formFields.forEach(inputField => {
		const field = document.getElementById(inputCategory + '_' + inputField)
		if (field) {
			field.oninput = verifyEmailSignup
			field.addEventListener('keypress', e => {
				const key = e.which || e.keyCode
				// If `enter` key is pressed, attempt to submit form
				if (key === 13) {
					const buttonField = document.getElementById(inputCategory + '_button')
					buttonField.click()
				}
			})
		}
	})
})<|endoftext|>


<commit_before>const sanitizeHtml = require('sanitize-html')
const sanitizeOpts = require('./sanitizeOpts')
const loadingImg = require('./loadingImg')
const equationImageSelector = 'img[src^="/math.svg"]'

const SCREENSHOT_LIMIT_ERROR = () => new Bacon.Error('Screenshot limit reached!')
module.exports = {
    isKey,
    isCtrlKey,
    insertToTextAreaAtCursor,
    persistInlineImages,
    sanitize,
    sanitizeContent,
    setCursorAfter,
    equationImageSelector,
    totalImageCount,
    SCREENSHOT_LIMIT_ERROR,
    existingScreenshotCount
}

function convertLinksToRelative(html) {
    return html.replace(new RegExp(document.location.origin, 'g'), '')
}

function sanitize(html) {
    return sanitizeHtml(convertLinksToRelative(html), sanitizeOpts)
}
function insertToTextAreaAtCursor(field, value) {
    const startPos = field.selectionStart
    const endPos = field.selectionEnd
    let oldValue = field.value
    field.value = oldValue.substring(0, startPos) + value + oldValue.substring(endPos, oldValue.length)
    field.selectionStart = field.selectionEnd = startPos + value.length
}

function decodeBase64Image(dataString) {
    if (!dataString)
        return null
    const matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/)
    if (matches.length !== 3) {
        return null
    }
    return {
        type: matches[1],
        data: new Buffer(matches[2], 'base64')
    }
}

function isKey(e, key) { return preventIfTrue(e, !e.altKey && !e.shiftKey && !e.ctrlKey  && keyOrKeyCode(e, key))}

function isCtrlKey(e, key) { return preventIfTrue(e, !e.altKey && !e.shiftKey && e.ctrlKey && keyOrKeyCode(e, key))}

function keyOrKeyCode(e, val) { return typeof val === 'string' ? e.key === val : e.keyCode === val }
function preventIfTrue(e, val) {
    if(val) e.preventDefault()
    return val
}

function sanitizeContent(answerElement) {
    const $answerElement = $(answerElement)
    const $mathEditor = $answerElement.find('[data-js="mathEditor"]')
    $mathEditor.hide()
    const text = $answerElement.text()
    $mathEditor.show()

    const html = sanitize($answerElement.html())

    return { answerHTML: html, answerText: text }
}

function setCursorAfter($img) {
    const range = document.createRange()
    const img = $img.get(0)
    const nextSibling = img.nextSibling && img.nextSibling.tagName === 'BR' ? img.nextSibling : img
    range.setStart(nextSibling, 0)
    range.setEnd(nextSibling, 0)
    const sel = window.getSelection()
    sel.removeAllRanges()
    sel.addRange(range)
}

function markAndGetInlineImages($editor) {
    const images = $editor.find('img[src^="data"]').toArray()
        .map((el, index) => Object.assign(decodeBase64Image(el.getAttribute('src')), {
            $el: $(el)
        }))
    images.filter(({type}) => type !== 'image/png').forEach(({$el}) => $el.remove())
    const pngImages = images.filter(({type}) => type === 'image/png')
    pngImages.forEach(({$el}) => $el.attr('src', loadingImg))
    return pngImages
}

function existingScreenshotCount($editor) {
    const imageCount = $editor.find('img').length
    const equationCount = $editor.find(equationImageSelector).length
    return imageCount - equationCount
}

function checkForImageLimit($editor, imageData, limit) {
    return Bacon.once(existingScreenshotCount($editor) > limit ? new Bacon.Error() : imageData)
}

function persistInlineImages($editor, screenshotSaver, screenshotCountLimit, onValueChanged) {
    setTimeout(() => Bacon.combineAsArray(markAndGetInlineImages($editor)
        .map(data => checkForImageLimit($editor, data, screenshotCountLimit)
            .doError(() => onValueChanged(SCREENSHOT_LIMIT_ERROR()))
            .flatMapLatest(() => Bacon.fromPromise(screenshotSaver(data)))
            .doAction(screenShotUrl => data.$el.attr('src', screenShotUrl))
            .doError(() => data.$el.remove()))
    ).onValue(k => $editor.trigger('input')), 0)
}

function totalImageCount($answer, clipboardDataAsHtml) {
    return existingScreenshotCount($answer) + existingScreenshotCount($(`<div>${clipboardDataAsHtml}</div>`))
}
<commit_msg>Fix work count bug<commit_after>const sanitizeHtml = require('sanitize-html')
const sanitizeOpts = require('./sanitizeOpts')
const loadingImg = require('./loadingImg')
const equationImageSelector = 'img[src^="/math.svg"]'

const SCREENSHOT_LIMIT_ERROR = () => new Bacon.Error('Screenshot limit reached!')
module.exports = {
    isKey,
    isCtrlKey,
    insertToTextAreaAtCursor,
    persistInlineImages,
    sanitize,
    sanitizeContent,
    setCursorAfter,
    equationImageSelector,
    totalImageCount,
    SCREENSHOT_LIMIT_ERROR,
    existingScreenshotCount
}

function convertLinksToRelative(html) {
    return html.replace(new RegExp(document.location.origin, 'g'), '')
}

function sanitize(html) {
    return sanitizeHtml(convertLinksToRelative(html), sanitizeOpts)
}
function insertToTextAreaAtCursor(field, value) {
    const startPos = field.selectionStart
    const endPos = field.selectionEnd
    let oldValue = field.value
    field.value = oldValue.substring(0, startPos) + value + oldValue.substring(endPos, oldValue.length)
    field.selectionStart = field.selectionEnd = startPos + value.length
}

function decodeBase64Image(dataString) {
    if (!dataString)
        return null
    const matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/)
    if (matches.length !== 3) {
        return null
    }
    return {
        type: matches[1],
        data: new Buffer(matches[2], 'base64')
    }
}

function isKey(e, key) { return preventIfTrue(e, !e.altKey && !e.shiftKey && !e.ctrlKey  && keyOrKeyCode(e, key))}

function isCtrlKey(e, key) { return preventIfTrue(e, !e.altKey && !e.shiftKey && e.ctrlKey && keyOrKeyCode(e, key))}

function keyOrKeyCode(e, val) { return typeof val === 'string' ? e.key === val : e.keyCode === val }
function preventIfTrue(e, val) {
    if(val) e.preventDefault()
    return val
}

function sanitizeContent(answerElement) {
    const $answerElement = $(answerElement)
    const $mathEditor = $answerElement.find('[data-js="mathEditor"]')
    $mathEditor.hide()
    const text = $answerElement.get(0).innerText
    $mathEditor.show()

    const html = sanitize($answerElement.html())

    return { answerHTML: html, answerText: text }
}

function setCursorAfter($img) {
    const range = document.createRange()
    const img = $img.get(0)
    const nextSibling = img.nextSibling && img.nextSibling.tagName === 'BR' ? img.nextSibling : img
    range.setStart(nextSibling, 0)
    range.setEnd(nextSibling, 0)
    const sel = window.getSelection()
    sel.removeAllRanges()
    sel.addRange(range)
}

function markAndGetInlineImages($editor) {
    const images = $editor.find('img[src^="data"]').toArray()
        .map((el, index) => Object.assign(decodeBase64Image(el.getAttribute('src')), {
            $el: $(el)
        }))
    images.filter(({type}) => type !== 'image/png').forEach(({$el}) => $el.remove())
    const pngImages = images.filter(({type}) => type === 'image/png')
    pngImages.forEach(({$el}) => $el.attr('src', loadingImg))
    return pngImages
}

function existingScreenshotCount($editor) {
    const imageCount = $editor.find('img').length
    const equationCount = $editor.find(equationImageSelector).length
    return imageCount - equationCount
}

function checkForImageLimit($editor, imageData, limit) {
    return Bacon.once(existingScreenshotCount($editor) > limit ? new Bacon.Error() : imageData)
}

function persistInlineImages($editor, screenshotSaver, screenshotCountLimit, onValueChanged) {
    setTimeout(() => Bacon.combineAsArray(markAndGetInlineImages($editor)
        .map(data => checkForImageLimit($editor, data, screenshotCountLimit)
            .doError(() => onValueChanged(SCREENSHOT_LIMIT_ERROR()))
            .flatMapLatest(() => Bacon.fromPromise(screenshotSaver(data)))
            .doAction(screenShotUrl => data.$el.attr('src', screenShotUrl))
            .doError(() => data.$el.remove()))
    ).onValue(k => $editor.trigger('input')), 0)
}

function totalImageCount($answer, clipboardDataAsHtml) {
    return existingScreenshotCount($answer) + existingScreenshotCount($(`<div>${clipboardDataAsHtml}</div>`))
}
<|endoftext|>


<commit_before>/*
Up : 38
Down : 40
Right : 39
Left : 37
Enter : 13
SpaceBar : 32
Shift : 16
*/

var walking;

$(document).keydown(function(e) {
	//var element = $(".joshua");
	if(e.keyCode == 32) {
		//alert("hi");
		$(".joshua").css("width", "80px");
		$(".joshua").css("background-image", "url(../image/joshua-sprite-walk.png)";
		$(".joshua").css("-webkit-animation-name", "joshua-sprite-walk");
	}
});

$(document).keyup(function(e) {
	if(e.keyCode == 32) {
		$(".joshua").css("width", "88px");
		$(".joshua").css("-webkit-animation-name", "joshua-sprite-idle");
	}
});
<commit_msg>Update joshuaSprite.js<commit_after>/*
Up : 38
Down : 40
Right : 39
Left : 37
Enter : 13
SpaceBar : 32
Shift : 16
*/

var walking;

$(document).keydown(function(e) {
	//var element = $(".joshua");
	if(e.keyCode == 32) {
		//alert("hi");
		$(".joshua").css("width", "80px");
		$(".joshua").css("background-image", "url(../image/joshua-sprite-walk.png)");
		$(".joshua").css("-webkit-animation-name", "joshua-sprite-walk");
	}
});

$(document).keyup(function(e) {
	if(e.keyCode == 32) {
		$(".joshua").css("width", "88px");
		$(".joshua").css("-webkit-animation-name", "joshua-sprite-idle");
	}
});
<|endoftext|>


<commit_before>openerp.account_move_line_search_extension = function (instance) {
    var _t = instance.web._t,
        _lt = instance.web._lt;
    var QWeb = instance.web.qweb;

    instance.account_move_line_search_extension = {};

    instance.web.views.add('account_move_line_search_extension', 'instance.account_move_line_search_extension.ListSearchView');
    instance.account_move_line_search_extension.ListSearchView = instance.web.ListView.extend({

        init: function() {
            this._super.apply(this, arguments);
            this.journals = [];
            this.current_account = null;
            this.current_partner = null;
            this.current_journal = null;
            this.current_period = null;
        },

        start:function(){
            var tmp = this._super.apply(this, arguments);
            var self = this;
            this.$el.parent().prepend(QWeb.render('AccountMoveLineSearchExtension', {widget: this}));

            this.$el.parent().find('.oe_account_select_account').change(function() {
                    self.current_account = this.value === '' ? null : this.value;
                    self.do_search(self.last_domain, self.last_context, self.last_group_by);
                });
            this.$el.parent().find('.oe_account_select_partner').change(function() {
                    self.current_partner = this.value === '' ? null : this.value;
                    self.do_search(self.last_domain, self.last_context, self.last_group_by);
                });
            this.$el.parent().find('.oe_account_select_journal').change(function() {
                    self.current_journal = this.value === '' ? null : parseInt(this.value);
                    //console.log('start, oasj, self.current_journal=', self.current_journal, 'self.last_domain=', self.last_domain, 'self.last_context=', self.last_context, 'self.last_group_by=', self.last_group_by);
                    self.do_search(self.last_domain, self.last_context, self.last_group_by);
                });
            this.$el.parent().find('.oe_account_select_period').change(function() {
                    self.current_period = this.value === '' ? null : this.value;
                    self.do_search(self.last_domain, self.last_context, self.last_group_by);
                });
            this.on('edit:after', this, function () {
                self.$el.parent().find('.oe_account_select_account').attr('disabled', 'disabled');
                self.$el.parent().find('.oe_account_select_partner').attr('disabled', 'disabled');
                self.$el.parent().find('.oe_account_select_journal').attr('disabled', 'disabled');
                self.$el.parent().find('.oe_account_select_period').attr('disabled', 'disabled');
            });
            this.on('save:after cancel:after', this, function () {
                self.$el.parent().find('.oe_account_select_account').removeAttr('disabled');
                self.$el.parent().find('.oe_account_select_partner').removeAttr('disabled');
                self.$el.parent().find('.oe_account_select_journal').removeAttr('disabled');
                self.$el.parent().find('.oe_account_select_period').removeAttr('disabled');
            });
            return tmp;
        },

        do_search: function(domain, context, group_by) {
            var self = this;
            this.last_domain = domain;
            this.last_context = context;
            this.last_group_by = group_by;
            this.old_search = _.bind(this._super, this);
            var aj_mod = new instance.web.Model('account.journal');
            return $.when(aj_mod.query(['name']).all().then(function(result) {
                self.journals = result;
            })).then(function () {
                var o;
                self.$el.parent().find('.oe_account_select_journal').children().remove().end();
                self.$el.parent().find('.oe_account_select_journal').append(new Option('', ''));
                for (var i = 0;i < self.journals.length;i++){
                    o = new Option(self.journals[i].name, self.journals[i].id);
                    if (self.journals[i].id === self.current_journal){
                        $(o).attr('selected',true);
                    }
                    self.$el.parent().find('.oe_account_select_journal').append(o);
                }
                return self.search_by_selection();
            });
        },

        search_by_selection: function() {
            var self = this;
            var domain = [];
            if (self.current_account) domain.push(['account_id.code', 'ilike', self.current_account]);
            if (self.current_partner) domain.push(['partner_id.name', 'ilike', self.current_partner],'|',['partner_id.parent_id','=',false],['partner_id.is_company','=',true]);
            if (self.current_journal) domain.push(['journal_id', '=', self.current_journal]);
            if (self.current_period) domain.push('|',['period_id.code', 'ilike', self.current_period],['period_id.name', 'ilike', self.current_period]);
            //_.each(domain, function(x) {console.log('search_by_journal_period, domain_part = ', x)});
            return self.old_search(new instance.web.CompoundDomain(self.last_domain, domain), self.last_context, self.last_group_by);
        },

    });
};
<commit_msg>[FIX] remove create + rencode file in from dos to unix CR/LF<commit_after>openerp.account_move_line_search_extension = function (instance) {
    var _t = instance.web._t,
        _lt = instance.web._lt;
    var QWeb = instance.web.qweb;

    instance.account_move_line_search_extension = {};

    instance.web.views.add('account_move_line_search_extension', 'instance.account_move_line_search_extension.ListSearchView');
    instance.account_move_line_search_extension.ListSearchView = instance.web.ListView.extend({

        init: function() {
            this._super.apply(this, arguments);
            this.journals = [];
            this.current_account = null;
            this.current_partner = null;
            this.current_journal = null;
            this.current_period = null;
            this.options.addable = false;
        },

        start:function(){
            var tmp = this._super.apply(this, arguments);
            var self = this;
            this.$el.parent().prepend(QWeb.render('AccountMoveLineSearchExtension', {widget: this}));

            this.$el.parent().find('.oe_account_select_account').change(function() {
                    self.current_account = this.value === '' ? null : this.value;
                    self.do_search(self.last_domain, self.last_context, self.last_group_by);
                });
            this.$el.parent().find('.oe_account_select_partner').change(function() {
                    self.current_partner = this.value === '' ? null : this.value;
                    self.do_search(self.last_domain, self.last_context, self.last_group_by);
                });
            this.$el.parent().find('.oe_account_select_journal').change(function() {
                    self.current_journal = this.value === '' ? null : parseInt(this.value);
                    //console.log('start, oasj, self.current_journal=', self.current_journal, 'self.last_domain=', self.last_domain, 'self.last_context=', self.last_context, 'self.last_group_by=', self.last_group_by);
                    self.do_search(self.last_domain, self.last_context, self.last_group_by);
                });
            this.$el.parent().find('.oe_account_select_period').change(function() {
                    self.current_period = this.value === '' ? null : this.value;
                    self.do_search(self.last_domain, self.last_context, self.last_group_by);
                });
            this.on('edit:after', this, function () {
                self.$el.parent().find('.oe_account_select_account').attr('disabled', 'disabled');
                self.$el.parent().find('.oe_account_select_partner').attr('disabled', 'disabled');
                self.$el.parent().find('.oe_account_select_journal').attr('disabled', 'disabled');
                self.$el.parent().find('.oe_account_select_period').attr('disabled', 'disabled');
            });
            this.on('save:after cancel:after', this, function () {
                self.$el.parent().find('.oe_account_select_account').removeAttr('disabled');
                self.$el.parent().find('.oe_account_select_partner').removeAttr('disabled');
                self.$el.parent().find('.oe_account_select_journal').removeAttr('disabled');
                self.$el.parent().find('.oe_account_select_period').removeAttr('disabled');
            });
            return tmp;
        },

        do_search: function(domain, context, group_by) {
            var self = this;
            this.last_domain = domain;
            this.last_context = context;
            this.last_group_by = group_by;
            this.old_search = _.bind(this._super, this);
            var aj_mod = new instance.web.Model('account.journal');
            return $.when(aj_mod.query(['name']).all().then(function(result) {
                self.journals = result;
            })).then(function () {
                var o;
                self.$el.parent().find('.oe_account_select_journal').children().remove().end();
                self.$el.parent().find('.oe_account_select_journal').append(new Option('', ''));
                for (var i = 0;i < self.journals.length;i++){
                    o = new Option(self.journals[i].name, self.journals[i].id);
                    if (self.journals[i].id === self.current_journal){
                        $(o).attr('selected',true);
                    }
                    self.$el.parent().find('.oe_account_select_journal').append(o);
                }
                return self.search_by_selection();
            });
        },

        search_by_selection: function() {
            var self = this;
            var domain = [];
            if (self.current_account) domain.push(['account_id.code', 'ilike', self.current_account]);
            if (self.current_partner) domain.push(['partner_id.name', 'ilike', self.current_partner],'|',['partner_id.parent_id','=',false],['partner_id.is_company','=',true]);
            if (self.current_journal) domain.push(['journal_id', '=', self.current_journal]);
            if (self.current_period) domain.push('|',['period_id.code', 'ilike', self.current_period],['period_id.name', 'ilike', self.current_period]);
            //_.each(domain, function(x) {console.log('search_by_journal_period, domain_part = ', x)});
            return self.old_search(new instance.web.CompoundDomain(self.last_domain, domain), self.last_context, self.last_group_by);
        },

    });
};
<|endoftext|>


<commit_before>/*global jQuery*/
/*jslint nomen:true*/
(function ($) {
	"use strict";

	$.widget("ui.layerListItem", {
		options: {
			layer: null,
			layerList: null
		},
		/** Mandatory method - automatically called by jQuery Mobile to initialise the widget. */
		_create: function () {
			var $this = this, perLayerTools;

			$this.element.addClass("ui-layer-list-item");

			// Create a checkbox that will turn the layer on and off.
			$("<input type='checkbox'>").prop("checked", $this.options.layer.visible).appendTo($this.element).click(function () {
				if (this.checked === true) {
					$this.options.layer.show();
				} else {
					$this.options.layer.hide();
				}
			});
			// Label the checkbox with the ID of the layer.
			$("").text($this.options.layer.id).appendTo($this.element);

			perLayerTools = $("
").appendTo($this.element);

			$("").text("×").appendTo(perLayerTools).click(function () {
				// Remove the layer from the map.
				$this.options.layerList.options.map.removeLayer($this.options.layer);
				// Remove this control from its parent.
				$($this.element).remove();
				return false;
			});
			return this;
		},
		_setOption: function (key, value) {
			var $this = this;
			// Put custom code here
			$this._super();
			return this;
		},
		_destroy: function () {
			$this.element.removeClass("ui-layer-list-item");
			this._super();
			return this;
		}
	});

	$.widget("ui.layerList", {
		options: {
			map: null
		},
		_list: null,
		/** Creates the layer list widget.
		* @param {esri.Map} map
		* @returns {jQuery}
		*/
		_create: function () {
			var $this = this, map;

			if (!$this.options.map) {
				throw new Error("Map option not specified.");
			}

			$this.element.addClass("ui-layer-list");
			map = $this.options.map;

			// Create the list and make it sortable.
			// TODO: Layers should be listed in reverse order.  Layer at top of list should be the one on top of all layers in the map.
			$this._list = $("
").appendTo($this.element).sortable({
				/**
				@param {Event} event
				@param {Object} ui
				@param {jQuery} helper
				@param {jQuery} item
				@param {Object} offset
				@param {Object} position
				@param {Object} originalPosition
				@param {jQuery} sender
				*/
				stop: function (event, ui) {
					var layer = ui.item.layerListItem("option", "layer"), newPosition = ui.item.nextAll().length;
					map.reorderLayer(layer, newPosition);
				}
			}).disableSelection();

			dojo.connect(map, "onLayerAdd", function (layer) {
				$("
").prependTo($this._list).layerListItem({ layer: layer, layerList: $this });
			});

			return this;
		},
		_setOption: function (key, value) {
			var $this = this;
			// Put custom code here
			$this.element.removeClass("ui-layer-list");

			$this._super();
			return this;
		},
		_destroy: function () {
			this._list.remove();
			this._super();
			return this;
		}
	});
}(jQuery));<commit_msg>Applied ui-helper-reset to layer list.<commit_after>/*global jQuery*/
/*jslint nomen:true*/
(function ($) {
	"use strict";

	$.widget("ui.layerListItem", {
		options: {
			layer: null,
			layerList: null
		},
		/** Mandatory method - automatically called by jQuery Mobile to initialise the widget. */
		_create: function () {
			var $this = this, perLayerTools;

			$this.element.addClass("ui-layer-list-item");

			// Create a checkbox that will turn the layer on and off.
			$("<input type='checkbox'>").prop("checked", $this.options.layer.visible).appendTo($this.element).click(function () {
				if (this.checked === true) {
					$this.options.layer.show();
				} else {
					$this.options.layer.hide();
				}
			});
			// Label the checkbox with the ID of the layer.
			$("").text($this.options.layer.id).appendTo($this.element);

			perLayerTools = $("
").appendTo($this.element);

			$("").text("…").appendTo(perLayerTools).click(function () {
				return false;
			});

			// Create the layer remove link.
			$("").text("×").appendTo(perLayerTools).click(function () {
				// Remove the layer from the map.
				$this.options.layerList.options.map.removeLayer($this.options.layer);
				// Remove this control from its parent.
				$($this.element).remove();
				return false;
			});

			return this;
		},
		_setOption: function (key, value) {
			var $this = this;
			// Put custom code here
			$this._super();
			return this;
		},
		_destroy: function () {
			$this.element.removeClass("ui-layer-list-item");
			this._super();
			return this;
		}
	});

	$.widget("ui.layerList", {
		options: {
			map: null
		},
		_list: null,
		/** Creates the layer list widget.
		* @param {esri.Map} map
		* @returns {jQuery}
		*/
		_create: function () {
			var $this = this, map;

			if (!$this.options.map) {
				throw new Error("Map option not specified.");
			}

			$this.element.addClass("ui-layer-list");
			map = $this.options.map;

			// Create the list and make it sortable.
			// TODO: Layers should be listed in reverse order.  Layer at top of list should be the one on top of all layers in the map.
			$this._list = $("
").addClass("ui-helper-reset").appendTo($this.element).sortable({
				/**
				@param {Event} event
				@param {Object} ui
				@param {jQuery} helper
				@param {jQuery} item
				@param {Object} offset
				@param {Object} position
				@param {Object} originalPosition
				@param {jQuery} sender
				*/
				stop: function (event, ui) {
					var layer = ui.item.layerListItem("option", "layer"), newPosition = ui.item.nextAll().length;
					map.reorderLayer(layer, newPosition);
				}
			}).disableSelection();

			dojo.connect(map, "onLayerAdd", function (layer) {
				$("
").addClass("ui-heler-reset").prependTo($this._list).layerListItem({ layer: layer, layerList: $this });
			});

			return this;
		},
		_setOption: function (key, value) {
			var $this = this;
			// Put custom code here
			$this.element.removeClass("ui-layer-list");

			$this._super();
			return this;
		},
		_destroy: function () {
			this._list.remove();
			this._super();
			return this;
		}
	});
}(jQuery));<|endoftext|>


<commit_before>define(['angular'],function(angular) {

  var app = angular.module('Leaf');

  app.register.controller('themesController',['$rootScope','$scope',function($rootScope,$scope) {

  }]);

});<commit_msg>Delete themes.js<commit_after><|endoftext|>


<commit_before>var closeColorRange = 60,
    colorRange = "Full",
    colors,
    MAX_RGB = 255,
    messageDisplay = document.querySelector("#message"),
    modeButtons = document.querySelectorAll(".modeButton"),
    modeElement = document.querySelector(".mode"),
    numOfGuesses = 6,
    possibleGuesses = document.querySelectorAll(".colorGuess"),
    rangeButtons = document.querySelectorAll(".rangeButton"),
    resetButton = document.getElementById("reset"),
    winningColor;

function getBackgroundColor() {
    var backgroundColor,
        element,
        style;

    element = document.querySelector("body");
    style = window.getComputedStyle(element, null);
    backgroundColor = style.getPropertyValue("background-color");

    return backgroundColor;
}

function changeAllColors(color) {
    for (var i = 0; i < possibleGuesses.length; i += 1) {
        possibleGuesses[i].style.background = color;
    }
}

function setGuess() {
    if (this.style.background === winningColor) {
        messageDisplay.textContent = "Correct!";
        resetButton.textContent = "Play again";
        changeAllColors(winningColor);
        document.querySelector("h1").style.background = winningColor;
    } else {
        messageDisplay.textContent = "Try Again";
        this.style.background = getBackgroundColor();
    }
}

function setModeOptions(totalGuesses, difficulty, width) {
    numOfGuesses = totalGuesses;
    modeElement.innerHTML = difficulty + "

";
    document.querySelector("#container").style.maxWidth = width;
}

function selectModeOptions(str) {
    if (str === "Easy") {
        numOfGuesses = 3;
        setModeOptions(numOfGuesses, "Easy", "600px");
    } else if (str === "Hard") {
        numOfGuesses = 6;
        setModeOptions(numOfGuesses, "Hard", "600px");
    } else {
        numOfGuesses = 16;
        setModeOptions(numOfGuesses, "Hardest", "800px");
    }
}

function randomColor() {
    var blue = Math.floor(Math.random() * MAX_RGB),
        green = Math.floor(Math.random() * MAX_RGB),
        red = Math.floor(Math.random() * MAX_RGB);
    return "rgb(" + red + ", " + green + ", " + blue + ")";
}

function closeRandomColor(str) {
    var i,
        rgb = str.match(/\d+/g),
        variance;

    for (i = 0; i < rgb.length; i += 1) {
        rgb[i] = Number(rgb[i]);
        if (Math.round(Math.random()) === 0) {
            variance = Math.floor(Math.random() * closeColorRange);
        } else {
            variance = -Math.floor(Math.random() * closeColorRange);
        }

        if (rgb[i] + variance > MAX_RGB || rgb[i] + variance < 0) {
            rgb[i] = rgb[i] - variance;
        } else {
            rgb[i] = rgb[i] + variance;
        }
    }
    return "rgb(" + rgb[0] + ", " + rgb[1] + ", " + rgb[2] + ")";
}

//Using Durstenfeld shuffle algorithm.
function shuffleColors(arr) {
    var i, swap, temp;
    for (i = arr.length - 1; i > 0; i -= 1) {
        swap = Math.floor(Math.random() * (i + 1));
        temp = arr[i];
        arr[i] = arr[swap];
        arr[swap] = temp;
    }
    return arr;
}

function generateRandomColors(num) {
    var arr = [], i;
    arr.push(randomColor());
    for (i = 1; i < num; i += 1) {
        if (colorRange === "Full") {
            arr.push(randomColor());
        } else {
            arr.push(closeRandomColor(arr[i - 1]));
        }
    }
    arr = shuffleColors(arr);
    return arr;
}

function setColors(num) {
    colors = generateRandomColors(num);
    winningColor = colors[Math.floor(Math.random() * colors.length)];
    document.getElementById("colorToGuess").textContent = winningColor;
    for (var i = 0; i < possibleGuesses.length; i += 1) {
        if (colors[i]) {
            possibleGuesses[i].style.display = "block";
            possibleGuesses[i].style.background = colors[i];
        } else {
            possibleGuesses[i].style.display = "none";
        }
    }
}

function resetText() {
    resetButton.textContent = "New Colors";
    messageDisplay.textContent = "";
    document.querySelector("h1").style.background = "steelblue";
    setColors(numOfGuesses);
}

function changeMode() {
    modeElement.innerHTML = this.textContent + " ";
    selectModeOptions(this.textContent);
    resetText();
}

function changeRange() {
    var rangeText;

    if (this.textContent === "Full") {
        rangeText = "Full Colors

";
    } else {
        rangeText = "Close Colors

";
    }
    document.querySelector(".range").innerHTML = rangeText;
    colorRange = this.textContent;
    resetText();
}

function init() {
    var i;

    for (i = 0; i < possibleGuesses.length; i += 1) {
        possibleGuesses[i].addEventListener("click", setGuess);
    }

    for (i = 0; i < modeButtons.length; i += 1) {
        modeButtons[i].addEventListener("click", changeMode);
    }

    for (i = 0; i < rangeButtons.length; i += 1) {
        rangeButtons[i].addEventListener("click", changeRange);
    }

    resetButton.addEventListener("click", function() {
        messageDisplay.textContent = "";
        this.textContent = "New Colors";
        document.querySelector("h1").style.background = "steelblue";
        setColors(numOfGuesses);
    });
    setColors(numOfGuesses);
}

init();
<commit_msg>Fix miscellaneous linting errors.<commit_after>var closeColorRange = 60,
    colorRange = "Full",
    colors,
    MAX_RGB = 255,
    messageDisplay = document.querySelector("#message"),
    modeButtons = document.querySelectorAll(".modeButton"),
    modeElement = document.querySelector(".mode"),
    numOfGuesses = 6,
    possibleGuesses = document.querySelectorAll(".colorGuess"),
    rangeButtons = document.querySelectorAll(".rangeButton"),
    resetButton = document.getElementById("reset"),
    winningColor;

function getBackgroundColor() {
    var backgroundColor,
        element,
        style;

    element = document.querySelector("body");
    style = window.getComputedStyle(element, null);
    backgroundColor = style.getPropertyValue("background-color");

    return backgroundColor;
}

function changeAllColors(color) {
    var i;

    for (i = 0; i < possibleGuesses.length; i += 1) {
        possibleGuesses[i].style.background = color;
    }
}

function setGuess() {
    if (this.style.background === winningColor) {
        messageDisplay.textContent = "Correct!";
        resetButton.textContent = "Play again";
        changeAllColors(winningColor);
        document.querySelector("h1").style.background = winningColor;
    } else {
        messageDisplay.textContent = "Try Again";
        this.style.background = getBackgroundColor();
    }
}

function setModeOptions(totalGuesses, difficulty, width) {
    numOfGuesses = totalGuesses;
    modeElement.innerHTML = difficulty + "

";
    document.querySelector("#container").style.maxWidth = width;
}

function selectModeOptions(str) {
    if (str === "Easy") {
        numOfGuesses = 3;
        setModeOptions(numOfGuesses, "Easy", "600px");
    } else if (str === "Hard") {
        numOfGuesses = 6;
        setModeOptions(numOfGuesses, "Hard", "600px");
    } else {
        numOfGuesses = 16;
        setModeOptions(numOfGuesses, "Hardest", "800px");
    }
}

function randomColor() {
    var blue = Math.floor(Math.random() * MAX_RGB),
        green = Math.floor(Math.random() * MAX_RGB),
        red = Math.floor(Math.random() * MAX_RGB);

    return "rgb(" + red + ", " + green + ", " + blue + ")";
}

function closeRandomColor(str) {
    var i,
        rgb = str.match(/\d+/g),
        variance;

    for (i = 0; i < rgb.length; i += 1) {
        rgb[i] = Number(rgb[i]);
        if (Math.round(Math.random()) === 0) {
            variance = Math.floor(Math.random() * closeColorRange);
        } else {
            variance = -Math.floor(Math.random() * closeColorRange);
        }

        if (rgb[i] + variance > MAX_RGB || rgb[i] + variance < 0) {
            rgb[i] -= variance;
        } else {
            rgb[i] += variance;
        }
    }

    return "rgb(" + rgb[0] + ", " + rgb[1] + ", " + rgb[2] + ")";
}

//Using Durstenfeld shuffle algorithm.
function shuffleColors(arr) {
    var i, swap, temp;

    for (i = arr.length - 1; i > 0; i -= 1) {
        swap = Math.floor(Math.random() * (i + 1));
        temp = arr[i];
        arr[i] = arr[swap];
        arr[swap] = temp;
    }

    return arr;
}

function generateRandomColors(num) {
    var arr = [],
        i;

    arr.push(randomColor());
    for (i = 1; i < num; i += 1) {
        if (colorRange === "Full") {
            arr.push(randomColor());
        } else {
            arr.push(closeRandomColor(arr[i - 1]));
        }
    }
    arr = shuffleColors(arr);
    return arr;
}

function setColors(num) {
    colors = generateRandomColors(num);
    winningColor = colors[Math.floor(Math.random() * colors.length)];
    document.getElementById("colorToGuess").textContent = winningColor;
    for (var i = 0; i < possibleGuesses.length; i += 1) {
        if (colors[i]) {
            possibleGuesses[i].style.display = "block";
            possibleGuesses[i].style.background = colors[i];
        } else {
            possibleGuesses[i].style.display = "none";
        }
    }
}

function resetText() {
    resetButton.textContent = "New Colors";
    messageDisplay.textContent = "";
    document.querySelector("h1").style.background = "steelblue";
    setColors(numOfGuesses);
}

function changeMode() {
    modeElement.innerHTML = this.textContent + " ";
    selectModeOptions(this.textContent);
    resetText();
}

function changeRange() {
    var rangeText;

    if (this.textContent === "Full") {
        rangeText = "Full Colors

";
    } else {
        rangeText = "Close Colors

";
    }
    document.querySelector(".range").innerHTML = rangeText;
    colorRange = this.textContent;
    resetText();
}

function init() {
    var i;

    for (i = 0; i < possibleGuesses.length; i += 1) {
        possibleGuesses[i].addEventListener("click", setGuess);
    }

    for (i = 0; i < modeButtons.length; i += 1) {
        modeButtons[i].addEventListener("click", changeMode);
    }

    for (i = 0; i < rangeButtons.length; i += 1) {
        rangeButtons[i].addEventListener("click", changeRange);
    }

    resetButton.addEventListener("click", function reset() {
        messageDisplay.textContent = "";
        this.textContent = "New Colors";
        document.querySelector("h1").style.background = "steelblue";
        setColors(numOfGuesses);
    });
    setColors(numOfGuesses);
}

init();
<|endoftext|>


<commit_before>Ext.require([
    'Ext.layout.container.*'
]);

Ext.define('ASPIREdb.view.filter.FilterPanel', {
    extend: 'Ext.Panel',
    closable: true,
    collapsible: true,
    header: false,
    width: 950,
    padding: '10 5 10 5' ,
    layout: {
        type: 'vbox',
        align: 'stretch'
    },

    initComponent: function () {
        this.callParent();

        var ref = this;

        this.insert(0,{
    	xtype: 'container',
    	layout:{type:'hbox',
    		align:'right'
    	},
    	items: [
    	    {xtype: 'label',

        	text: this.title,
        	padding: '5 5 5 5'    },
        	{
        		xtype : 'image',
        		itemId: 'closeImage',
    			margin : '5 5 5 5',

    				src : 'scripts/ASPIREdb/resources/images/icons/cross.png',
    				listeners: {
    			        render: function(c) {
    			            c.getEl().on('click', function(e) {
    			                ref.close();
    			                ASPIREdb.EVENT_BUS.fireEvent('query_update');
    			            }, c);
    			        }
    			    }

        	}]
    });

    },

    closeEmptyFilter : function(){
		var filterContainer = this.getComponent('filterContainer');

		if(filterContainer.items.length == 0){
			this.close();
		}

        ASPIREdb.EVENT_BUS.fireEvent('query_update');
	}
});
<commit_msg>Bug 3839 - Filter window: red X's should be right aligned<commit_after>Ext.require([
    'Ext.layout.container.*'
]);

Ext.define('ASPIREdb.view.filter.FilterPanel', {
    extend: 'Ext.Panel',
    closable: true,
    collapsible: true,
    header: false,
    width: 950,
    padding: '10 5 10 5' ,
    layout: {
        type: 'vbox',
        align: 'stretch'
    },

    initComponent: function () {
        this.callParent();

        var ref = this;

        this.insert(0,{
    	xtype: 'container',
    	layout:{type:'hbox',
    		align:'right'
    	},
    	items: [
    	    {xtype: 'label',

        	text: this.title,
        	padding: '5 5 5 5'    },
        	{
        		xtype : 'image',
        		itemId: 'closeImage',
    			margin : '5 5 5 650',

    				src : 'scripts/ASPIREdb/resources/images/icons/cross.png',
    				listeners: {
    			        render: function(c) {
    			            c.getEl().on('click', function(e) {
    			                ref.close();
    			                ASPIREdb.EVENT_BUS.fireEvent('query_update');
    			            }, c);
    			        }
    			    }

        	}]
    });

    },

    closeEmptyFilter : function(){
		var filterContainer = this.getComponent('filterContainer');

		if(filterContainer.items.length == 0){
			this.close();
		}

        ASPIREdb.EVENT_BUS.fireEvent('query_update');
	}
});
<|endoftext|>


<commit_before>import DS from 'ember-data';

import OsfModel from './osf-model';
import FileItemMixin from 'ember-osf/mixins/file-item';
import { authenticatedAJAX } from 'ember-osf/utils/ajax-helpers';

/**
 * @module ember-osf
 * @submodule models
 */

/**
 * Model for OSF APIv2 files. This model may be used with one of several API endpoints. It may be queried directly,
 *  or (more commonly) accessed via relationship fields.
 * This model is used for basic file metadata. To interact with file contents directly, see the `file-manager` service.
 * For field and usage information, see:
 * * https://api.osf.io/v2/docs/#!/v2/File_Detail_GET
 * * https://api.osf.io/v2/docs/#!/v2/Node_Files_List_GET
 * * https://api.osf.io/v2/docs/#!/v2/Node_File_Detail_GET
 * * https://api.osf.io/v2/docs/#!/v2/Registration_Files_List_GET
 * * https://api.osf.io/v2/docs/#!/v2/Registration_File_Detail_GET
 * @class File
 */
export default OsfModel.extend(FileItemMixin, {
    _isFileModel: true,

    name: DS.attr('fixstring'),
    kind: DS.attr('fixstring'),
    guid: DS.attr('fixstring'),
    path: DS.attr('string'),
    size: DS.attr('number'),
    currentVersion: DS.attr('number'),
    provider: DS.attr('fixstring'),
    materializedPath: DS.attr('string'),
    lastTouched: DS.attr('date'),
    dateModified: DS.attr('date'),
    dateCreated: DS.attr('date'),
    extra: DS.attr(),
    tags: DS.attr(),

    parentFolder: DS.belongsTo('file', { inverse: 'files' }),

    // Folder attributes
    files: DS.hasMany('file', { inverse: 'parentFolder' }),

    // File attributes
    versions: DS.hasMany('file-version'),
    comments: DS.hasMany('comment'),
    node: DS.belongsTo('node'),  // TODO: In the future apiv2 may also need to support this pointing at nodes OR registrations
    user: DS.belongsTo('user'),
    checkout: DS.attr('fixstring'),

    rename(newName, conflict = 'replace') {
        return authenticatedAJAX({
            url: this.get('links.upload'),
            type: 'POST',
            xhrFields: {
                withCredentials: true
            },
            headers: {
                'Content-Type': 'Application/json'
            },
            data: JSON.stringify({
                action: 'rename',
                rename: newName,
                conflict: conflict
            }),
        }).done(response => {
            this.set('name', response.data.attributes.name);
        });
    }
});
<commit_msg>Added getGuid() method to file model<commit_after>import DS from 'ember-data';

import OsfModel from './osf-model';
import FileItemMixin from 'ember-osf/mixins/file-item';
import { authenticatedAJAX } from 'ember-osf/utils/ajax-helpers';

/**
 * @module ember-osf
 * @submodule models
 */

/**
 * Model for OSF APIv2 files. This model may be used with one of several API endpoints. It may be queried directly,
 *  or (more commonly) accessed via relationship fields.
 * This model is used for basic file metadata. To interact with file contents directly, see the `file-manager` service.
 * For field and usage information, see:
 * * https://api.osf.io/v2/docs/#!/v2/File_Detail_GET
 * * https://api.osf.io/v2/docs/#!/v2/Node_Files_List_GET
 * * https://api.osf.io/v2/docs/#!/v2/Node_File_Detail_GET
 * * https://api.osf.io/v2/docs/#!/v2/Registration_Files_List_GET
 * * https://api.osf.io/v2/docs/#!/v2/Registration_File_Detail_GET
 * @class File
 */
export default OsfModel.extend(FileItemMixin, {
    _isFileModel: true,

    name: DS.attr('fixstring'),
    kind: DS.attr('fixstring'),
    guid: DS.attr('fixstring'),
    path: DS.attr('string'),
    size: DS.attr('number'),
    currentVersion: DS.attr('number'),
    provider: DS.attr('fixstring'),
    materializedPath: DS.attr('string'),
    lastTouched: DS.attr('date'),
    dateModified: DS.attr('date'),
    dateCreated: DS.attr('date'),
    extra: DS.attr(),
    tags: DS.attr(),

    parentFolder: DS.belongsTo('file', { inverse: 'files' }),

    // Folder attributes
    files: DS.hasMany('file', { inverse: 'parentFolder' }),

    // File attributes
    versions: DS.hasMany('file-version'),
    comments: DS.hasMany('comment'),
    node: DS.belongsTo('node'),  // TODO: In the future apiv2 may also need to support this pointing at nodes OR registrations
    user: DS.belongsTo('user'),
    checkout: DS.attr('fixstring'),

    rename(newName, conflict = 'replace') {
        return authenticatedAJAX({
            url: this.get('links.upload'),
            type: 'POST',
            xhrFields: {
                withCredentials: true
            },
            headers: {
                'Content-Type': 'Application/json'
            },
            data: JSON.stringify({
                action: 'rename',
                rename: newName,
                conflict: conflict
            }),
        }).done(response => {
            this.set('name', response.data.attributes.name);
        });
    },
    getGuid() {
        this.store.findRecord(
            this.constructor.modelName,
            this.id,
            {
                reload: true,
                adapterOptions: {
                    query: {
                        create_guid: 1,
                    },
                },
            }
        );
    },
});
<|endoftext|>


<commit_before>exports.checkUser = async function checkUser(app) {
  let uid;
  if (app.auth.isAuthenticated()) {
    app.authenticated = true; // Logout element is reliant upon a local var;
    try {
      uid = app.auth.getTokenPayload().sub;
    } catch (e) {
      app.logout();
      return Promise.resolve('bad token');
    }
    app.user = await app.appState.getUser(uid);
    if (app.user !== undefined) app.role = app.user.userType;
  }
  return Promise.resolve(true);
};

exports.checkIfLoggedIn = function checkIfLoggedIn(app) {
  const token = localStorage.getItem('aurelia_id_token');
  if (token !== null && token !== undefined) {
    try {
      app.auth.getTokenPayload();
      app.auth.setToken(token);
      app.authenticated = true;
      app.router.navigate('dashboard');
      return true;
    } catch (e) {
      app.logout();
      return false;
    }
  }
  return false;
};

exports.returnIsWide = function returnIsWide(app, isWide, drawer, mobileMenuToggle) {
  const swipeArea = document.getElementsByClassName('swipe-area')[0];
  if (isWide) {
    if (drawer !== null && drawer !== undefined) {
      if (app.contentWidth === '0px') { app.contentWidth = '182px'; }
      drawer.style.display = 'block';
      swipeArea.style.display = 'none';
      $(drawer).parent().css('display', 'block');
      mobileMenuToggle.style.display = 'none';
    }
  } else { app.contentWidth = '0px'; }
  const mainP = doc.getElementsByClassName('main-panel')[0];
  if (mainP !== null && mainP !== undefined) {
    mainP.style.marginRight = app.contentWidth;
  }
  return isWide;
};

exports.handleScreenSize = function checkIfWidescreen(app, isWide) {
  // const isWide = document.documentElement.clientWidth > 766;
  const drawer = document.getElementsByClassName('drawer')[0];
  const mobileMenuToggle = document.getElementsByClassName('mobile-menu-toggle')[0];
  const swipeArea = document.getElementsByClassName('swipe-area')[0];
  if (!app.menuToggled && !isWide) {
    /* istanbul ignore else */
    if (drawer !== null && drawer !== undefined) {
      drawer.style.display = 'none';
      $(drawer).parent().css('display', 'none');
      mobileMenuToggle.style.display = 'block';
      swipeArea.style.display = 'block';
    }
  }
  return this.returnIsWide(app, isWide, drawer, mobileMenuToggle);
};

exports.clickFunc = function (event) {
  const drawer = document.getElementsByClassName('drawer')[0];
  const toggleIcon = document.getElementsByClassName('mobile-menu-toggle')[0];
  /* istanbul ignore else */
  if (event.target.className !== 'menu-item') {
    document.getElementsByClassName('swipe-area')[0].style.display = 'none';
    drawer.style.display = 'none';
    $(drawer).parent().css('display', 'none');
    toggleIcon.style.display = 'block';
    document.getElementsByClassName('page-host')[0].style.overflow = 'auto';
  }
};
<commit_msg>fix doc error<commit_after>exports.checkUser = async function checkUser(app) {
  let uid;
  if (app.auth.isAuthenticated()) {
    app.authenticated = true; // Logout element is reliant upon a local var;
    try {
      uid = app.auth.getTokenPayload().sub;
    } catch (e) {
      app.logout();
      return Promise.resolve('bad token');
    }
    app.user = await app.appState.getUser(uid);
    if (app.user !== undefined) app.role = app.user.userType;
  }
  return Promise.resolve(true);
};

exports.checkIfLoggedIn = function checkIfLoggedIn(app) {
  const token = localStorage.getItem('aurelia_id_token');
  if (token !== null && token !== undefined) {
    try {
      app.auth.getTokenPayload();
      app.auth.setToken(token);
      app.authenticated = true;
      app.router.navigate('dashboard');
      return true;
    } catch (e) {
      app.logout();
      return false;
    }
  }
  return false;
};

exports.returnIsWide = function returnIsWide(app, isWide, drawer, mobileMenuToggle) {
  const swipeArea = document.getElementsByClassName('swipe-area')[0];
  if (isWide) {
    if (drawer !== null && drawer !== undefined) {
      if (app.contentWidth === '0px') { app.contentWidth = '182px'; }
      drawer.style.display = 'block';
      swipeArea.style.display = 'none';
      $(drawer).parent().css('display', 'block');
      mobileMenuToggle.style.display = 'none';
    }
  } else { app.contentWidth = '0px'; }
  const mainP = document.getElementsByClassName('main-panel')[0];
  if (mainP !== null && mainP !== undefined) {
    mainP.style.marginRight = app.contentWidth;
  }
  return isWide;
};

exports.handleScreenSize = function checkIfWidescreen(app, isWide) {
  // const isWide = document.documentElement.clientWidth > 766;
  const drawer = document.getElementsByClassName('drawer')[0];
  const mobileMenuToggle = document.getElementsByClassName('mobile-menu-toggle')[0];
  const swipeArea = document.getElementsByClassName('swipe-area')[0];
  if (!app.menuToggled && !isWide) {
    /* istanbul ignore else */
    if (drawer !== null && drawer !== undefined) {
      drawer.style.display = 'none';
      $(drawer).parent().css('display', 'none');
      mobileMenuToggle.style.display = 'block';
      swipeArea.style.display = 'block';
    }
  }
  return this.returnIsWide(app, isWide, drawer, mobileMenuToggle);
};

exports.clickFunc = function (event) {
  const drawer = document.getElementsByClassName('drawer')[0];
  const toggleIcon = document.getElementsByClassName('mobile-menu-toggle')[0];
  /* istanbul ignore else */
  if (event.target.className !== 'menu-item') {
    document.getElementsByClassName('swipe-area')[0].style.display = 'none';
    drawer.style.display = 'none';
    $(drawer).parent().css('display', 'none');
    toggleIcon.style.display = 'block';
    document.getElementsByClassName('page-host')[0].style.overflow = 'auto';
  }
};
<|endoftext|>


<commit_before>export default function() {

  // These comments are here to help you get started. Feel free to delete them.

  /*
    Config (with defaults).

    Note: these only affect routes defined *after* them!
  */

  // this.urlPrefix = '';    // make this `http://localhost:8080`, for example, if your API is on a different server
  // this.namespace = '';    // make this `/api`, for example, if your API is namespaced
  // this.timing = 400;      // delay for each request, automatically set to 0 during testing

  /*
    Shorthand cheatsheet:

    this.get('/posts');
    this.post('/posts');
    this.get('/posts/:id');
    this.put('/posts/:id'); // or this.patch
    this.del('/posts/:id');

    http://www.ember-cli-mirage.com/docs/v0.3.x/shorthands/
  */
}
<commit_msg>Updated link to shorthands<commit_after>export default function() {

  // These comments are here to help you get started. Feel free to delete them.

  /*
    Config (with defaults).

    Note: these only affect routes defined *after* them!
  */

  // this.urlPrefix = '';    // make this `http://localhost:8080`, for example, if your API is on a different server
  // this.namespace = '';    // make this `/api`, for example, if your API is namespaced
  // this.timing = 400;      // delay for each request, automatically set to 0 during testing

  /*
    Shorthand cheatsheet:

    this.get('/posts');
    this.post('/posts');
    this.get('/posts/:id');
    this.put('/posts/:id'); // or this.patch
    this.del('/posts/:id');

    http://www.ember-cli-mirage.com/docs/v0.4.x/shorthands/
  */
}
<|endoftext|>


<commit_before>// FIX reconsider name, but compiler.compile.compiler.compile() method calls would rock.
compiler.compile.compiler = def(
  [
    compiler.meta.metalator,
    compiler.tools.io,
    compiler.tools.error,
    ephox.bolt.kernel.module.analyser,
    ephox.bolt.kernel.fp.functions,
    ephox.bolt.kernel.fp.object
  ],

  function (metalator, io, error, analyser, fn, obj) {
    var modules = {};  // id -> [id]
    var rendered = {}; // id -> rendered
    var printed = {};

    var unexpected = fn.curry(error.die, "unexpected call to require, define or demand by compile modulator.");

    var load = function (regulator, id) {
      if (!regulator.can(id, unexpected))
        error.die("No modulator can load module: " + id);
      var spec = regulator.regulate(id, unexpected, unexpected, unexpected);
      spec.load(function (id, dependencies) {
        modules[id] = dependencies;
        rendered[id] = "";
      });
      rendered[id] = spec.render();
    };

    var analyse = function (ids) {
      var results = analyser.analyse(ids, modules);
      if (results.cycle)
        error.die('cycle detected whilst compiling modules: ' + results.cycle.join(' ~> '));
      return results;
    };

    var render = function (ids) {
      var renderer = function (id) {
        if (printed[id])
          return "";
        var dependencies = modules[id];
        var deps = dependencies.map(renderer);
        printed[id] = true;
        return deps.join('\n') + '\n' + rendered[id];
      };
      return ids.map(renderer).join('\n');
    };

    var compile = function (regulator, ids) {
      var loader = fn.curry(load, regulator);
      var results = analyse(ids);
      while (results.load.length > 0) {
        results.load.forEach(loader);
        results = analyse(ids);
      }
      return render(ids);
    };

    var write = function (regulator, ids, target) {
      var header = metalator.render(ids);
      var content = compile(regulator, ids);
      io.write(target, header + content);
      return obj.keys(rendered);
    };

    return {
      compile: compile,
      write: write
    };
  }
);
<commit_msg>Added constant mapper.<commit_after>// FIX reconsider name, but compiler.compile.compiler.compile() method calls would rock.
compiler.compile.compiler = def(
  [
    compiler.meta.metalator,
    compiler.tools.io,
    compiler.tools.error,
    ephox.bolt.kernel.module.analyser,
    ephox.bolt.kernel.fp.functions,
    ephox.bolt.kernel.fp.object
  ],

  function (metalator, io, error, analyser, fn, obj) {
    var modules = {};  // id -> [id]
    var rendered = {}; // id -> rendered
    var printed = {};

    var unexpected = fn.curry(error.die, "unexpected call to require, define or demand by compile modulator.");

    // FIX split
    var load = function (regulator, id) {
      if (!regulator.can(id, unexpected))
        error.die("No modulator can load module: " + id);
      var spec = regulator.regulate(id, unexpected, unexpected, unexpected);
      spec.load(function (id, dependencies) {
        modules[id] = dependencies;
        rendered[id] = "";
      });
      if (modules[id] === undefined)
        error.die("Module id could not be loaded: " + id);
      rendered[id] = spec.render();
    };

    var analyse = function (ids) {
      var results = analyser.analyse(ids, modules);
      if (results.cycle)
        error.die('cycle detected whilst compiling modules: ' + results.cycle.join(' ~> '));
      return results;
    };

    var render = function (ids) {
      var renderer = function (id) {
        if (printed[id])
          return "";
        var dependencies = modules[id];
        var deps = dependencies.map(renderer);
        printed[id] = true;
        return deps.join('\n') + '\n' + rendered[id];
      };
      return ids.map(renderer).join('\n');
    };

    var compile = function (regulator, ids) {
      var loader = fn.curry(load, regulator);
      var results = analyse(ids);
      while (results.load.length > 0) {
        results.load.forEach(loader);
        results = analyse(ids);
      }
      return render(ids);
    };

    var write = function (regulator, ids, target) {
      var content = compile(regulator, ids);
      var all = obj.keys(modules);
      var header = metalator.render(all);
      io.write(target, header + content);
      return obj.keys(rendered);
    };

    return {
      compile: compile,
      write: write
    };
  }
);
<|endoftext|>