<commit_before>(function() {
	var $canvas = $('.sim-canvas');
	var $canvasImage = $('.canvas--image');
	var $canvasQuote = $('.canvas--quote');
	var $quoteText = $('.quote--text');
	var $quoteAttribution = $('.quote--attribution');
	var $story = $('.story');
	var $thinking = $('.thinking');

	var _canvasOptions;

	var FONT_SIZE = { max: 56, min: 24 };

	var init = function() {
		setupOptions();
		if(SETTINGS.embedlyKey) {
			setupEvents();
			checkDev();
		} else {
	 		alert('You must setup an embedly key and add it to the to main.js');
		}
	};

	var checkDev = function() {
		if(SETTINGS.embedlyKey === 'dev') {
			showOptions({images:[{url:'img/placeholder.jpg'}]});
		}
	};

	var setupOptions = function() {
		for(var name in SETTINGS.options) {
			var option = SETTINGS.options[name];
			appendChoices(name, option);
		}
	};

	var appendChoices = function(name, option) {
		var select = $('.option--' + name).find('select');
		for(var choice in option.choices) {
			var selected = choice === SETTINGS.options[name]['default'] ? ' selected' : '';
			var html = '<option data-prop="' + name + '" value="' + choice + '" ' + selected + '>' + choice + '</option>';
			select.append(html);
		}
	};

 	// handle user input
	var setupEvents = function() {
		$('.options--item button').on('click', function() {
			var el = $(this);
			var prop = el.attr('data-prop');
			var val = el.attr('data-val');
			_canvasOptions[prop]({ el: el, val: val });
		});

		$('.options--item select').on('change', function() {
			var el = $(this);
			var prop = el.attr('data-prop');
			var val = el.val();
			_canvasOptions[prop]({ el: el, val: val });
		});

		$('.options--item input').on('keyup', function() {
			var el = $(this);
			var prop = el.attr('data-prop');
			var val = el.val();
			_canvasOptions[prop]({ el: el, val: val });
		});

		$('.generate').on('click', createOutput );

		$('.story-form').on('submit', extract);
	};

	// get data from embedly
	var extract = function(e) {
		e.preventDefault();
		var $el = $('.story-form--input');
		var url = $el.val().trim();
		$el.val('');

		$('.thinking').removeClass('hide');
		$.embedly.extract(url, {key: SETTINGS.embedlyKey}).progress(function(data) {
			showOptions(data);
		});
		return false;
	};

	// reveal options ui
	var showOptions = function(data) {
		$thinking.addClass('hide');
		$story.removeClass('hide');

		// default to light text on dark bg
		$canvas.addClass('light-on-dark');

		if(data.error) {
			alert('something is wrong.');
		} else {
			createCanvas(data);

		}
	};

	// append image and set proper color
	var createCanvas = function(data) {
		// get image src
		var img = data.images[0];

		var src = img.url;

		if(SETTINGS.imageHelper && typeof SETTINGS.imageHelper === 'function') {
			src = SETTINGS.imageHelper(src);
		}

		var bg = 'url("' + src + '")';
		// set canvas bg
		$('.canvas--image').css('background-image', bg);

		// set dimensions based on default platform
		var defaultPlatform = SETTINGS.options['platform'].default;
		var defaultFont = SETTINGS.options['font'].default;

		$canvas.css({
			'width': SETTINGS.options['platform'].choices[defaultPlatform].w,
			'height': SETTINGS.options['platform'].choices[defaultPlatform].h,
			'font-family': SETTINGS.options['font'].choices[defaultFont]

		});
	};

	// toggle selected button in options view
	var toggleSelected = function(params) {
		params.el.siblings().removeClass('selected');
		params.el.addClass('selected');
	};

	// create png from canvas
	var createOutput = function() {
		var el = $canvas[0];
		html2canvas(el, {
			letterRendering: true,
			allowTaint: true,
		    onrendered: function(canvas) {
		    	var html = '
Right click and save image. Now go sim it all over the internet.
';
		    	$('.sim-output').empty().append(html).append(canvas);
		    }
		});
	};

	// calculate offset based on height of el for true middle
	var updateLayoutMargin = function() {
		var margin = 0;
		var middle = $canvas.hasClass('middle');
		if(middle) {
			var h = $canvasQuote.height();
			margin = -h * 0.5;
		}
		$canvasQuote.css('margin-top', margin);
	};

	// functionality for each option selected
	_canvasOptions = {
		quoteText: function(params) {
			var val = params.val.trim();
			$quoteText.text(val);
			updateLayoutMargin();
		},
		quoteAttribution: function(params) {
			var val = params.val.trim();
			$quoteAttribution.text(val);
			updateLayoutMargin();
		},
		platform: function(params) {
			$canvas.css({
				width: SETTINGS.options['platform'].choices[params.val].w,
				height: SETTINGS.options['platform'].choices[params.val].h
			});
		},
		position: function(params) {
			var cssProp;
			var bgPosition;
			if(params.val === 'up' || params.val === 'down') {
				cssProp = 'background-position-y';
			} else {
				cssProp = 'background-position-x';
			}
			bgPosition = parseInt($canvasImage.css(cssProp));
			bgPosition += (params.val === 'up' || params.val === 'right') ? 5 : -5;
			bgPosition = Math.min(Math.max(0, bgPosition), 100);
			bgPosition += '%';
			$canvasImage.css(cssProp, bgPosition);
		},
		layout: function(params) {
			$canvas.removeClass('top bottom middle').addClass(params.val);
			updateLayoutMargin();
		},
		align: function(params) {
			$canvasQuote.removeClass('left center right').addClass(params.val);
		},
		font: function(params) {
			var stack = SETTINGS.options['font'].choices[params.val];
			$canvas.css('font-family', stack);
		},
		size: function(params) {
			params.val = parseInt(params.val);
			var size = parseInt($canvasQuote.css('font-size')) + params.val;
			size = Math.min(FONT_SIZE.max, Math.max(FONT_SIZE.min, size));
			$canvasQuote.css('font-size', size);
		},
		shadow: function(params) {
			if(params.val === 'on') {
				$canvasQuote.addClass('text-shadow');
			} else {
				$canvasQuote.removeClass('text-shadow');
			}
		}
	};

	init();
})();
<commit_msg>update copy<commit_after>(function() {
	var $canvas = $('.sim-canvas');
	var $canvasImage = $('.canvas--image');
	var $canvasQuote = $('.canvas--quote');
	var $quoteText = $('.quote--text');
	var $quoteAttribution = $('.quote--attribution');
	var $story = $('.story');
	var $thinking = $('.thinking');

	var _canvasOptions;

	var FONT_SIZE = { max: 56, min: 24 };

	var init = function() {
		setupOptions();
		if(SETTINGS.embedlyKey) {
			setupEvents();
			checkDev();
		} else {
	 		alert('You must setup an embedly key and add it to the to main.js');
		}
	};

	var checkDev = function() {
		if(SETTINGS.embedlyKey === 'dev') {
			showOptions({images:[{url:'img/placeholder.jpg'}]});
		}
	};

	var setupOptions = function() {
		for(var name in SETTINGS.options) {
			var option = SETTINGS.options[name];
			appendChoices(name, option);
		}
	};

	var appendChoices = function(name, option) {
		var select = $('.option--' + name).find('select');
		for(var choice in option.choices) {
			var selected = choice === SETTINGS.options[name]['default'] ? ' selected' : '';
			var html = '<option data-prop="' + name + '" value="' + choice + '" ' + selected + '>' + choice + '</option>';
			select.append(html);
		}
	};

 	// handle user input
	var setupEvents = function() {
		$('.options--item button').on('click', function() {
			var el = $(this);
			var prop = el.attr('data-prop');
			var val = el.attr('data-val');
			_canvasOptions[prop]({ el: el, val: val });
		});

		$('.options--item select').on('change', function() {
			var el = $(this);
			var prop = el.attr('data-prop');
			var val = el.val();
			_canvasOptions[prop]({ el: el, val: val });
		});

		$('.options--item input').on('keyup', function() {
			var el = $(this);
			var prop = el.attr('data-prop');
			var val = el.val();
			_canvasOptions[prop]({ el: el, val: val });
		});

		$('.generate').on('click', createOutput );

		$('.story-form').on('submit', extract);
	};

	// get data from embedly
	var extract = function(e) {
		e.preventDefault();
		var $el = $('.story-form--input');
		var url = $el.val().trim();
		$el.val('');

		$('.thinking').removeClass('hide');
		$.embedly.extract(url, {key: SETTINGS.embedlyKey}).progress(function(data) {
			showOptions(data);
		});
		return false;
	};

	// reveal options ui
	var showOptions = function(data) {
		$thinking.addClass('hide');
		$story.removeClass('hide');

		// default to light text on dark bg
		$canvas.addClass('light-on-dark');

		if(data.error) {
			alert('something is wrong.');
		} else {
			createCanvas(data);

		}
	};

	// append image and set proper color
	var createCanvas = function(data) {
		// get image src
		var img = data.images[0];

		var src = img.url;

		if(SETTINGS.imageHelper && typeof SETTINGS.imageHelper === 'function') {
			src = SETTINGS.imageHelper(src);
		}

		var bg = 'url("' + src + '")';
		// set canvas bg
		$('.canvas--image').css('background-image', bg);

		// set dimensions based on default platform
		var defaultPlatform = SETTINGS.options['platform'].default;
		var defaultFont = SETTINGS.options['font'].default;

		$canvas.css({
			'width': SETTINGS.options['platform'].choices[defaultPlatform].w,
			'height': SETTINGS.options['platform'].choices[defaultPlatform].h,
			'font-family': SETTINGS.options['font'].choices[defaultFont]

		});
	};

	// toggle selected button in options view
	var toggleSelected = function(params) {
		params.el.siblings().removeClass('selected');
		params.el.addClass('selected');
	};

	// create png from canvas
	var createOutput = function() {
		var el = $canvas[0];
		html2canvas(el, {
			letterRendering: true,
			allowTaint: true,
		    onrendered: function(canvas) {
		    	var html = '
Right click and save image to download.
';
		    	$('.sim-output').empty().append(html).append(canvas);
		    }
		});
	};

	// calculate offset based on height of el for true middle
	var updateLayoutMargin = function() {
		var margin = 0;
		var middle = $canvas.hasClass('middle');
		if(middle) {
			var h = $canvasQuote.height();
			margin = -h * 0.5;
		}
		$canvasQuote.css('margin-top', margin);
	};

	// functionality for each option selected
	_canvasOptions = {
		quoteText: function(params) {
			var val = params.val.trim();
			$quoteText.text(val);
			updateLayoutMargin();
		},
		quoteAttribution: function(params) {
			var val = params.val.trim();
			$quoteAttribution.text(val);
			updateLayoutMargin();
		},
		platform: function(params) {
			$canvas.css({
				width: SETTINGS.options['platform'].choices[params.val].w,
				height: SETTINGS.options['platform'].choices[params.val].h
			});
		},
		position: function(params) {
			var cssProp;
			var bgPosition;
			if(params.val === 'up' || params.val === 'down') {
				cssProp = 'background-position-y';
			} else {
				cssProp = 'background-position-x';
			}
			bgPosition = parseInt($canvasImage.css(cssProp));
			bgPosition += (params.val === 'up' || params.val === 'right') ? 5 : -5;
			bgPosition = Math.min(Math.max(0, bgPosition), 100);
			bgPosition += '%';
			$canvasImage.css(cssProp, bgPosition);
		},
		layout: function(params) {
			$canvas.removeClass('top bottom middle').addClass(params.val);
			updateLayoutMargin();
		},
		align: function(params) {
			$canvasQuote.removeClass('left center right').addClass(params.val);
		},
		font: function(params) {
			var stack = SETTINGS.options['font'].choices[params.val];
			$canvas.css('font-family', stack);
		},
		size: function(params) {
			params.val = parseInt(params.val);
			var size = parseInt($canvasQuote.css('font-size')) + params.val;
			size = Math.min(FONT_SIZE.max, Math.max(FONT_SIZE.min, size));
			$canvasQuote.css('font-size', size);
		},
		shadow: function(params) {
			if(params.val === 'on') {
				$canvasQuote.addClass('text-shadow');
			} else {
				$canvasQuote.removeClass('text-shadow');
			}
		}
	};

	init();
})();
<|endoftext|>


<commit_before>

var rows = document.getElementsByClassName("row");

function addChecker(tile, color) {
  var checker = document.createElement('div');
  checker.className = "checker checker--" + color;
  checker.draggable = "true";
  tile.appendChild(checker);

  return checker;
}

function CheckerPiece(id, color) {
  var self = this;
  self.id = id,
  self.color = color,
  self.addChecker = function(tile, color) {
    var checker = document.createElement('div');
    checker.className = "checker checker--" + color;
    checker.draggable = "true";
    tile.appendChild(checker);
    self.element = checker;
  },
    self.location = function(){
      return [Number(self.element.parentNode.attributes.x.value), Number(self.element.parentNode.attributes.y.value)];
    }
}

var redTeam = [];
var blueTeam = [];
var redCounter = 0;
var blueCounter = 0;
//Ridiculously long board setup
for (var x = 0; x < rows.length; x++) {
  var tiles = rows[x].getElementsByClassName('tile');

  for (var y = 0; y < tiles.length; y++) {
    if (x < 3) {
      if (x % 2 === 0 && y % 2 === 0) {
        // var checker = addChecker(tiles[y], "red");
        var redChecker = new CheckerPiece(redCounter, "red");
        redChecker.addChecker(tiles[y], "red");
        redTeam.push(redChecker);
        redCounter++;
      }
      else if (x % 2 != 0 && y % 2 !== 0) {
        var redChecker = new CheckerPiece(redCounter, "red");
        redChecker.addChecker(tiles[y], "red");
        redTeam.push(redChecker);
        redChecker.index = redCounter;
        redCounter++;
      }
    }
    else if (x > 4) {
      if (x % 2 != 0 && y % 2 != 0) {
        var blueChecker = new CheckerPiece(blueCounter, "blue");
        blueChecker.addChecker(tiles[y], "blue");
        blueTeam.push(blueChecker);
        blueCounter++;
      }
      else if (x % 2 == 0 && y % 2 == 0 ) {
        var blueChecker = new CheckerPiece(blueCounter, "blue");
        blueChecker.addChecker(tiles[y], "blue");
        blueTeam.push(blueChecker);
        blueCounter++;
      }
    }
  }
}

document.addEventListener("dragstart", function( event ) {
    // store a ref. on the dragged.element elem
    for (var x = 0; x < redTeam.length; x++) {
      if (event.target == redTeam[x].element) {
        dragged = redTeam[x];
      }
    }
    for (var x = 0; x < blueTeam.length; x++) {
     if (event.target == blueTeam[x].element) {
        dragged = blueTeam[x];
      }
    }
}, false);

document.addEventListener("dragover", function( event ) {
    // prevent default to allow drop
    event.preventDefault();
}, false);

//Checker movement
//If tile is playable highlight color to green
document.addEventListener("dragenter", function( event ) {
    // highlight potential drop target when the draggable element enters it
    // check drop location for all drags
    if (checkDropLocation(event) != false && event.target.classList[0] == 'tile') {
      //logic for diagonal move
      if ( moveDiagonal(event, dragged.element) == true  ) {
          event.target.style.background = "green";
      }
      // logic for jump will go here
      else if ( (jumpDiagonal(event, dragged) == true ) ) {
        event.target.style.background = "green";
      }
    }
}, false);

//reset after hightlight
document.addEventListener("dragleave", function( event ) {
    // reset background of potential drop target when the draggable element leaves it
    if ( event.target.classList[0] == "tile" ) {
        event.target.style.background = "";
    }
}, false);

document.addEventListener("drop", function( event ) {
    // prevent default action (open as link for some elements)
    event.preventDefault();
    // move dragged.element elem to the selected drop target
    if ( checkDropLocation(event) != false && dragged.element.parentNode != event.target && dragged.element != event.target ) {
      if ( moveDiagonal(event, dragged.element) == true ) {
        event.target.style.background = "";
        dragged.element.parentNode.removeChild(dragged.element);
        event.target.appendChild( dragged.element );
      }
      else if ( jumpDiagonal(event, dragged) == true ) {
        if (Number(event.target.attributes.x.value) > dragged.location()[0]) {
          var jumped = adjacentChecker(dragged).xPlusOne
          removeCheckerFromTeam(jumped);
        }
        else if (Number(event.target.attributes.x.value) < dragged.location()[0]) {
          var jumped = adjacentChecker(dragged).xMinusOne;
          removeCheckerFromTeam(jumped);
        }
        event.target.style.background = "";
        dragged.element.parentNode.removeChild(dragged.element);
        event.target.appendChild( dragged.element );
      }
    }
}, false);

function checkDropLocation (dropLocation) {
  if ( ( dropLocation.target.classList[0] == "tile" && dropLocation.target.childElementCount > 0 ) || ( dropLocation.target.classList[0] == 'checker' ) || ( dropLocation.target.classList[0] != "tile" )) {
    return false
  }
}

function tileOccuppied(tileLocation) {
  if (tileLocation.childElementCount > 0) {
    return true;
  }
}

function moveDiagonal (dropLocation, checker) {
  var checkerCurrentYLocation = Number(checker.parentNode.attributes.y.value);
  var checkerCurrentXLocation = Number(checker.parentNode.attributes.x.value);

  var targetXLocation = Number(dropLocation.target.attributes.x.value);
  var targetYLocation = Number(dropLocation.target.attributes.y.value);

  var checkerTeam = (checker.classList[1] == 'checker--red' ? 'red' : 'blue');
  if (checkerTeam == 'red') {
    //check if movement is up one, over one
    if ( ( checkerCurrentYLocation + 1 == targetYLocation ) &&
        ( checkerCurrentXLocation - 1 == targetXLocation || (checkerCurrentXLocation + 1 == targetXLocation) ) ) {
      return true;
    }
  } else {
    if ( ( checkerCurrentYLocation - 1 == targetYLocation ) &&
      ( checkerCurrentXLocation - 1 == targetXLocation || (checkerCurrentXLocation + 1 == targetXLocation ) ) ) {
      return true;
    }
  }
}

function jumpDiagonal (dropLocation, checker) {
  var targetXLocation = Number(dropLocation.target.attributes.x.value);
  var targetYLocation = Number(dropLocation.target.attributes.y.value);

  if (checker.color == 'red') {
    //check if movement is up two, over two
    if ( ( checker.location()[1] + 2 == targetYLocation ) &&
        ( (checker.location()[0] - 2 == targetXLocation &&
        adjacentChecker(checker).xMinusOne != undefined) || (checker.location()[0] + 2 == targetXLocation &&
          adjacentChecker(checker).xPlusOne != undefined) )
      ) {
      return true;
    }
  }
  if (checker.color == 'blue') {
    //check if movement is up two, over two
    if ( ( checker.location()[1] - 2 == targetYLocation ) &&
        ( (checker.location()[0] - 2 == targetXLocation &&
        adjacentChecker(checker).xMinusOne != undefined) || (checker.location()[0] + 2 == targetXLocation &&
          adjacentChecker(checker).xPlusOne != undefined) )
      ) {
      return true;
    }
  }
}

function adjacentChecker(checker) {
  var matches = {};
  if (checker.color == "red") {
    for (var i = 0; i < blueTeam.length; i++) {
      if (blueTeam[i].location()[0] === checker.location()[0] + 1 && blueTeam[i].location()[1] === checker.location()[1] + 1) {
        matches.xPlusOne = blueTeam[i];
      } else if (blueTeam[i].location()[0] === checker.location()[0] - 1 && blueTeam[i].location()[1] === checker.location()[1] + 1) {
        matches.xMinusOne = blueTeam[i];
      }
    }
  }
  else {
    for (var i = 0; i < redTeam.length; i++) {
      if (redTeam[i].location()[0] === checker.location()[0] + 1 && redTeam[i].location()[1] === checker.location()[1] - 1) {
        matches.xPlusOne = redTeam[i];
      } else if ( redTeam[i].location()[0] === checker.location()[0] - 1 && redTeam[i].location()[1] === checker.location()[1] - 1 ) {
        matches.xMinusOne = redTeam[i];
      }
    }
  }
  return matches;
}

function removeCheckerFromTeam(checker) {
  if (checker.color === 'red') {
    redTeam.splice(checker.id, 1);
  } else {
    blueTeam.splice(checker.id, 1);
  }

  checker.element.parentNode.removeChild(checker.element);
}
//Logic:
//-team turn
//-who starts?
//-where can you drop a checker?
//if you drop piece where you picked it up it disappears --done
<commit_msg>little bit of cleanup<commit_after>var rows = document.getElementsByClassName("row");

function addChecker(tile, color) {
  var checker = document.createElement('div');
  checker.className = "checker checker--" + color;
  checker.draggable = "true";
  tile.appendChild(checker);

  return checker;
}

function CheckerPiece(id, color) {
  var self = this;
  self.id = id,
  self.color = color,
  self.addChecker = function(tile, color) {
    var checker = document.createElement('div');
    checker.className = "checker checker--" + color;
    checker.draggable = "true";
    tile.appendChild(checker);
    self.element = checker;
  },
  self.location = function(){
    return [Number(self.element.parentNode.attributes.x.value), Number(self.element.parentNode.attributes.y.value)];
  }
}

var redTeam = [];
var blueTeam = [];
var redCounter = 0;
var blueCounter = 0;
//Ridiculously long board setup
for (var x = 0; x < rows.length; x++) {
  var tiles = rows[x].getElementsByClassName('tile');

  for (var y = 0; y < tiles.length; y++) {
    if (x < 3) {
      if (x % 2 === 0 && y % 2 === 0) {
        var redChecker = new CheckerPiece(redCounter, "red");
        redChecker.addChecker(tiles[y], "red");
        redTeam.push(redChecker);
        redCounter++;
      }
      else if (x % 2 != 0 && y % 2 !== 0) {
        var redChecker = new CheckerPiece(redCounter, "red");
        redChecker.addChecker(tiles[y], "red");
        redTeam.push(redChecker);
        redCounter++;
      }
    }
    else if (x > 4) {
      if (x % 2 != 0 && y % 2 != 0) {
        var blueChecker = new CheckerPiece(blueCounter, "blue");
        blueChecker.addChecker(tiles[y], "blue");
        blueTeam.push(blueChecker);
        blueCounter++;
      }
      else if (x % 2 == 0 && y % 2 == 0 ) {
        var blueChecker = new CheckerPiece(blueCounter, "blue");
        blueChecker.addChecker(tiles[y], "blue");
        blueTeam.push(blueChecker);
        blueCounter++;
      }
    }
  }
}

document.addEventListener("dragstart", function( event ) {
    // store a ref. on the dragged.element elem
    for (var x = 0; x < redTeam.length; x++) {
      if (event.target == redTeam[x].element) {
        dragged = redTeam[x];
      }
    }
    for (var x = 0; x < blueTeam.length; x++) {
     if (event.target == blueTeam[x].element) {
        dragged = blueTeam[x];
      }
    }
}, false);

document.addEventListener("dragover", function( event ) {
    // prevent default to allow drop
    event.preventDefault();
}, false);

//Checker movement
//If tile is playable highlight color to green
document.addEventListener("dragenter", function( event ) {
    // highlight potential drop target when the draggable element enters it
    // check drop location for all drags
    if (checkDropLocation(event) != false && event.target.classList[0] == 'tile') {
      //logic for diagonal move
      if ( moveDiagonal(event, dragged) == true  ) {
          event.target.style.background = "green";
      }
      // logic for jump will go here
      else if ( (jumpDiagonal(event, dragged) == true ) ) {
        event.target.style.background = "green";
      }
    }
}, false);

//reset after hightlight
document.addEventListener("dragleave", function( event ) {
    // reset background of potential drop target when the draggable element leaves it
    if ( event.target.classList[0] == "tile" ) {
        event.target.style.background = "";
    }
}, false);

document.addEventListener("drop", function( event ) {
    // prevent default action (open as link for some elements)
    event.preventDefault();
    // move dragged.element elem to the selected drop target
    if ( checkDropLocation(event) != false && dragged.element.parentNode != event.target && dragged.element != event.target ) {
      if ( moveDiagonal(event, dragged) == true ) {
        event.target.style.background = "";
        dragged.element.parentNode.removeChild(dragged.element);
        event.target.appendChild(dragged.element);
      }
      else if ( jumpDiagonal(event, dragged) == true ) {
        if (Number(event.target.attributes.x.value) > dragged.location()[0]) {
          var jumped = adjacentChecker(dragged).xPlusOne
          removeCheckerFromTeam(jumped);
        }
        else if (Number(event.target.attributes.x.value) < dragged.location()[0]) {
          var jumped = adjacentChecker(dragged).xMinusOne;
          removeCheckerFromTeam(jumped);
        }
        event.target.style.background = "";
        dragged.element.parentNode.removeChild(dragged.element);
        event.target.appendChild(dragged.element);
      }
    }
}, false);

function checkDropLocation (dropLocation) {
  if ( ( dropLocation.target.classList[0] == "tile" && dropLocation.target.childElementCount > 0 ) || ( dropLocation.target.classList[0] == 'checker' ) || ( dropLocation.target.classList[0] != "tile" )) {
    return false
  }
}

function tileOccuppied(tileLocation) {
  if (tileLocation.childElementCount > 0) {
    return true;
  }
}

function moveDiagonal (dropLocation, checker) {
  var checkerCurrentYLocation = checker.location()[0];
  var checkerCurrentXLocation = checker.location()[1];

  var targetXLocation = Number(dropLocation.target.attributes.x.value);
  var targetYLocation = Number(dropLocation.target.attributes.y.value);

  if (checker.color === 'red') {
    //check if movement is up one, over one
    if ( ( checkerCurrentYLocation + 1 == targetYLocation ) &&
        ( checkerCurrentXLocation - 1 == targetXLocation || (checkerCurrentXLocation + 1 == targetXLocation) ) ) {
      return true;
    }
  } else {
    if ( ( checkerCurrentYLocation - 1 == targetYLocation ) &&
      ( checkerCurrentXLocation - 1 == targetXLocation || (checkerCurrentXLocation + 1 == targetXLocation ) ) ) {
      return true;
    }
  }
}

function jumpDiagonal (dropLocation, checker) {
  var targetXLocation = Number(dropLocation.target.attributes.x.value);
  var targetYLocation = Number(dropLocation.target.attributes.y.value);

  if (checker.color == 'red') {
    //check if movement is up two, over two
    if ( ( checker.location()[1] + 2 == targetYLocation ) &&
        ( (checker.location()[0] - 2 == targetXLocation &&
        adjacentChecker(checker).xMinusOne != undefined) || (checker.location()[0] + 2 == targetXLocation &&
          adjacentChecker(checker).xPlusOne != undefined) )
      ) {
      return true;
    }
  }
  if (checker.color == 'blue') {
    //check if movement is up two, over two
    if ( ( checker.location()[1] - 2 == targetYLocation ) &&
        ( (checker.location()[0] - 2 == targetXLocation &&
        adjacentChecker(checker).xMinusOne != undefined) || (checker.location()[0] + 2 == targetXLocation &&
          adjacentChecker(checker).xPlusOne != undefined) )
      ) {
      return true;
    }
  }
}

function adjacentChecker(checker) {
  var matches = {};
  if (checker.color == "red") {
    for (var i = 0; i < blueTeam.length; i++) {
      if (blueTeam[i].location()[0] === checker.location()[0] + 1 && blueTeam[i].location()[1] === checker.location()[1] + 1) {
        matches.xPlusOne = blueTeam[i];
      } else if (blueTeam[i].location()[0] === checker.location()[0] - 1 && blueTeam[i].location()[1] === checker.location()[1] + 1) {
        matches.xMinusOne = blueTeam[i];
      }
    }
  }
  else {
    for (var i = 0; i < redTeam.length; i++) {
      if (redTeam[i].location()[0] === checker.location()[0] + 1 && redTeam[i].location()[1] === checker.location()[1] - 1) {
        matches.xPlusOne = redTeam[i];
      } else if ( redTeam[i].location()[0] === checker.location()[0] - 1 && redTeam[i].location()[1] === checker.location()[1] - 1 ) {
        matches.xMinusOne = redTeam[i];
      }
    }
  }
  return matches;
}

function removeCheckerFromTeam(checker) {
  if (checker.color === 'red') {
    redTeam.splice(checker.id, 1);
  } else {
    blueTeam.splice(checker.id, 1);
  }

  checker.element.parentNode.removeChild(checker.element);
}
//Logic:
//-team turn
//-who starts?
//-where can you drop a checker?
//if you drop piece where you picked it up it disappears --done
<|endoftext|>


<commit_before>function initialize()
  {var mapCenter=new google.maps.LatLng(40.741,-74.182);
  var mapOptions =
    {center: mapCenter,
    zoom: 14
    }
  var map=new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
  }
google.maps.event.addDomListener(window, 'load', initialize);
<commit_msg>Removed the map type control<commit_after>function initialize()
  {var mapCenter=new google.maps.LatLng(40.741,-74.182);
  var mapOptions =
    {center: mapCenter,
    zoom: 14,
    mapTypeControl:false
    }
  var map=new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
  }
google.maps.event.addDomListener(window, 'load', initialize);
<|endoftext|>


<commit_before>/* global  Log, Loader, Module, config, defaults */
/* jshint -W020 */

/* Magic Mirror
 * Main System
 *
 * By Michael Teeuw http://michaelteeuw.nl
 * MIT Licensed.
 */

var MM = (function() {

	var modules = [];

	/* Private Methods */

	/* createDomObjects()
	 * Create dom objects for all modules that
	 * are configured for a specific position.
	 */
	var createDomObjects = function() {
		for (var m in modules) {
			var module = modules[m];

			if (typeof module.data.position === "string") {

				var wrapper = selectWrapper(module.data.position);

				var dom = document.createElement("div");
				dom.id = module.identifier;
				dom.className = module.name;

				if (typeof module.data.classes === "string") {
					dom.className = "module " + dom.className + " " + module.data.classes;
				}

				dom.opacity = 0;
				wrapper.appendChild(dom);

				if (typeof module.data.header !== "undefined" && module.data.header !== "") {
					var moduleHeader = document.createElement("header");
					moduleHeader.innerHTML = module.data.header;
					moduleHeader.className = "module-header";
					dom.appendChild(moduleHeader);
				}

				var moduleContent = document.createElement("div");
				moduleContent.className = "module-content";
				dom.appendChild(moduleContent);

				updateDom(module, 0);
			}
		}

		sendNotification("DOM_OBJECTS_CREATED");
	};

	/* selectWrapper(position)
	 * Select the wrapper dom object for a specific position.
	 *
	 * argument position string - The name of the position.
	 */
	var selectWrapper = function(position) {
		var classes = position.replace("_"," ");
		var parentWrapper = document.getElementsByClassName(classes);
		if (parentWrapper.length > 0) {
			var wrapper =  parentWrapper[0].getElementsByClassName("container");
			if (wrapper.length > 0) {
				return wrapper[0];
			}
		}
	};

	/* sendNotification(notification, payload, sender)
	 * Send a notification to all modules.
	 *
	 * argument notification string - The identifier of the noitication.
	 * argument payload mixed - The payload of the notification.
	 * argument sender Module - The module that sent the notification.
	 */
	var sendNotification = function(notification, payload, sender) {
		for (var m in modules) {
			var module = modules[m];
			if (module !== sender) {
				module.notificationReceived(notification, payload, sender);
			}
		}
	};

	/* updateDom(module, speed)
	 * Update the dom for a specific module.
	 *
	 * argument module Module - The module that needs an update.
	 * argument speed Number - The number of microseconds for the animation. (optional)
	 */
	var updateDom = function(module, speed) {
		var newContent = module.getDom();
		var newHeader = module.getHeader();

		if (!module.hidden) {

			if (!moduleNeedsUpdate(module, newHeader, newContent)) {
				return;
			}

			if (!speed) {
				updateModuleContent(module, newHeader, newContent);
				return;
			}

			hideModule(module, speed / 2, function() {
				updateModuleContent(module, newHeader, newContent);
				if (!module.hidden) {
					showModule(module, speed / 2);
				}
			});
		} else {
			updateModuleContent(module, newHeader, newContent);
		}
	};

	/* moduleNeedsUpdate(module, newContent)
	 * Check if the content has changed.
	 *
	 * argument module Module - The module to check.
	 * argument newContent Domobject - The new content that is generated.
	 *
	 * return bool - Does the module need an update?
	 */
	var moduleNeedsUpdate = function(module, newHeader, newContent) {
		var moduleWrapper = document.getElementById(module.identifier);
		var contentWrapper = moduleWrapper.getElementsByClassName("module-content");
		var headerWrapper = moduleWrapper.getElementsByClassName("module-header");

		var headerNeedsUpdate = false;
		var contentNeedsUpdate = false;

		if (headerWrapper.length > 0) {
			headerNeedsUpdate = newHeader !== headerWrapper.innerHTML;
		}

		var tempContentWrapper = document.createElement("div");
		tempContentWrapper.appendChild(newContent);
		contentNeedsUpdate = tempContentWrapper.innerHTML !== contentWrapper[0].innerHTML;

		return headerNeedsUpdate || contentNeedsUpdate;
	};

	/* moduleNeedsUpdate(module, newContent)
	 * Update the content of a module on screen.
	 *
	 * argument module Module - The module to check.
	 * argument newContent Domobject - The new content that is generated.
	 */
	var updateModuleContent = function(module, newHeader, newContent) {
		var moduleWrapper = document.getElementById(module.identifier);
		var headerWrapper = moduleWrapper.getElementsByClassName("module-header");
		var contentWrapper = moduleWrapper.getElementsByClassName("module-content");

		contentWrapper[0].innerHTML = "";
		contentWrapper[0].appendChild(newContent);

		if( headerWrapper.length > 0 && newHeader) {
			headerWrapper[0].innerHTML = newHeader;
		}

	};

	/* hideModule(module, speed, callback)
	 * Hide the module.
	 *
	 * argument module Module - The module to hide.
	 * argument speed Number - The speed of the hide animation.
	 * argument callback function - Called when the animation is done.
	 */
	var hideModule = function(module, speed, callback, options) {
		options = options || {};

		// set lockString if set in options.
		if (options.lockString) {
			// Log.log("Has lockstring: " + options.lockString);
			if (module.lockStrings.indexOf(options.lockString) === -1) {
				module.lockStrings.push(options.lockString);
			}
		}

		var moduleWrapper = document.getElementById(module.identifier);
		if (moduleWrapper !== null) {
			moduleWrapper.style.transition = "opacity " + speed / 1000 + "s";
			moduleWrapper.style.opacity = 0;

			clearTimeout(module.showHideTimer);
			module.showHideTimer = setTimeout(function() {
				// To not take up any space, we just make the position absolute.
				// since it's fade out anyway, we can see it lay above or
				// below other modules. This works way better than adjusting
				// the .display property.
				moduleWrapper.style.position = "absolute";

				if (typeof callback === "function") { callback(); }
			}, speed);
		}
	};

	/* showModule(module, speed, callback)
	 * Show the module.
	 *
	 * argument module Module - The module to show.
	 * argument speed Number - The speed of the show animation.
	 * argument callback function - Called when the animation is done.
	 */
	var showModule = function(module, speed, callback, options) {
		options = options || {};

		// remove lockString if set in options.
		if (options.lockString) {
			var index = module.lockStrings.indexOf(options.lockString)
			if ( index !== -1) {
				module.lockStrings.splice(index, 1);
			}
		}

		// Check if there are no more lockstrings set, or the force option is set.
		// Otherwise cancel show action.
		if (module.lockStrings.length !== 0 && options.force !== true) {
			Log.log("Will not show " + module.name + ". LockStrings active: " + module.lockStrings.join(","));
			return;
		}

		// If forced show, clean current lockstrings.
		if (module.lockStrings.length !== 0 && options.force === true) {
			Log.log("Force show of module: " + module.name);
			module.lockStrings = [];
		}

		var moduleWrapper = document.getElementById(module.identifier);
		if (moduleWrapper !== null) {
			moduleWrapper.style.transition = "opacity " + speed / 1000 + "s";
			// Restore the postition. See hideModule() for more info.
			moduleWrapper.style.position = "static";
			moduleWrapper.style.opacity = 1;

			clearTimeout(module.showHideTimer);
			module.showHideTimer = setTimeout(function() {
				if (typeof callback === "function") { callback(); }
			}, speed);

		}
	};

	/* loadConfig()
	 * Loads the core config and combines it with de system defaults.
	 */
	var loadConfig = function() {
		if (typeof config === "undefined") {
			config = defaults;
			Log.error("Config file is missing! Please create a config file.");
			return;
		}

		config = Object.assign(defaults, config);
	};

	/* setSelectionMethodsForModules()
	 * Adds special selectors on a collection of modules.
	 *
	 * argument modules array - Array of modules.
	 */
	var setSelectionMethodsForModules = function(modules) {

		/* withClass(className)
		 * filters a collection of modules based on classname(s).
		 *
		 * argument className string/array - one or multiple classnames. (array or space devided)
		 *
		 * return array - Filtered collection of modules.
		 */
		var withClass = function(className) {
			var searchClasses = className;
			if (typeof className === "string") {
				searchClasses = className.split(" ");
			}

			var newModules = modules.filter(function(module) {
				var classes = module.data.classes.toLowerCase().split(" ");

				for (var c in searchClasses) {
					var searchClass = searchClasses[c];
					if (classes.indexOf(searchClass.toLowerCase()) !== -1) {
						return true;
					}
				}

				return false;
			});

			setSelectionMethodsForModules(newModules);
			return newModules;
		};

		/* exceptWithClass(className)
		 * filters a collection of modules based on classname(s). (NOT)
		 *
		 * argument className string/array - one or multiple classnames. (array or space devided)
		 *
		 * return array - Filtered collection of modules.
		 */
		var exceptWithClass  = function(className) {
			var searchClasses = className;
			if (typeof className === "string") {
				searchClasses = className.split(" ");
			}

			var newModules = modules.filter(function(module) {
				var classes = module.data.classes.toLowerCase().split(" ");

				for (var c in searchClasses) {
					var searchClass = searchClasses[c];
					if (classes.indexOf(searchClass.toLowerCase()) !== -1) {
						return false;
					}
				}

				return true;
			});

			setSelectionMethodsForModules(newModules);
			return newModules;
		};

		/* exceptModule(module)
		 * Removes a module instance from the collection.
		 *
		 * argument module Module object - The module instance to remove from the collection.
		 *
		 * return array - Filtered collection of modules.
		 */
		var exceptModule = function(module) {
			var newModules = modules.filter(function(mod) {
				return mod.identifier !== module.identifier;
			});

			setSelectionMethodsForModules(newModules);
			return newModules;
		};

		/* enumerate(callback)
		 * Walks thru a collection of modules and executes the callback with the module as an argument.
		 *
		 * argument callback function - The function to execute with the module as an argument.
		 */
		var enumerate = function(callback) {
			modules.map(function(module) {
				callback(module);
			});
		};

		if (typeof modules.withClass === "undefined") { Object.defineProperty(modules, "withClass",  {value: withClass, enumerable: false}); }
		if (typeof modules.exceptWithClass === "undefined") { Object.defineProperty(modules, "exceptWithClass",  {value: exceptWithClass, enumerable: false}); }
		if (typeof modules.exceptModule === "undefined") { Object.defineProperty(modules, "exceptModule",  {value: exceptModule, enumerable: false}); }
		if (typeof modules.enumerate === "undefined") { Object.defineProperty(modules, "enumerate",  {value: enumerate, enumerable: false}); }
	};

	return {
		/* Public Methods */

		/* init()
		 * Main init method.
		 */
		init: function() {
			Log.info("Initializing MagicMirror.");
			loadConfig();
			Translator.loadCoreTranslations(config.language);
			Loader.loadModules();
		},

		/* modulesStarted(moduleObjects)
		 * Gets called when all modules are started.
		 *
		 * argument moduleObjects array<Module> - All module instances.
		 */
		modulesStarted: function(moduleObjects) {
			modules = [];
			for (var m in moduleObjects) {
				var module = moduleObjects[m];
				modules[module.data.index] = module;
			}

			Log.info("All modules started!");
			sendNotification("ALL_MODULES_STARTED");

			createDomObjects();
		},

		/* sendNotification(notification, payload, sender)
		 * Send a notification to all modules.
		 *
		 * argument notification string - The identifier of the noitication.
		 * argument payload mixed - The payload of the notification.
		 * argument sender Module - The module that sent the notification.
		 */
		sendNotification: function(notification, payload, sender) {
			if (arguments.length < 3) {
				Log.error("sendNotification: Missing arguments.");
				return;
			}

			if (typeof notification !== "string") {
				Log.error("sendNotification: Notification should be a string.");
				return;
			}

			if (!(sender instanceof Module)) {
				Log.error("sendNotification: Sender should be a module.");
				return;
			}

			// Further implementation is done in the private method.
			sendNotification(notification, payload, sender);
		},

		/* updateDom(module, speed)
		 * Update the dom for a specific module.
		 *
		 * argument module Module - The module that needs an update.
		 * argument speed Number - The number of microseconds for the animation. (optional)
		 */
		updateDom: function(module, speed) {
			if (!(module instanceof Module)) {
				Log.error("updateDom: Sender should be a module.");
				return;
			}

			// Further implementation is done in the private method.
			updateDom(module, speed);
		},

		/* getModules(module, speed)
		 * Returns a collection of all modules currently active.
		 *
		 * return array - A collection of all modules currently active.
		 */
		getModules: function() {
			setSelectionMethodsForModules(modules);
			return modules;
		},

		/* hideModule(module, speed, callback)
		 * Hide the module.
		 *
		 * argument module Module - The module hide.
		 * argument speed Number - The speed of the hide animation.
		 * argument callback function - Called when the animation is done.
		 * argument options object - Optional settings for the hide method.
		 */
		hideModule: function(module, speed, callback, options) {
			module.hidden = true;
			hideModule(module, speed, callback, options);
		},

		/* showModule(module, speed, callback)
		 * Show the module.
		 *
		 * argument module Module - The module show.
		 * argument speed Number - The speed of the show animation.
		 * argument callback function - Called when the animation is done.
		 * argument options object - Optional settings for the hide method.
		 */
		showModule: function(module, speed, callback, options) {
			module.hidden = false;
			showModule(module, speed, callback, options);
		}
	};

})();

// Add polyfill for Object.assign.
if (typeof Object.assign != "function") {
	(function() {
		Object.assign = function(target) {
			"use strict";
			if (target === undefined || target === null) {
				throw new TypeError("Cannot convert undefined or null to object");
			}
			var output = Object(target);
			for (var index = 1; index < arguments.length; index++) {
				var source = arguments[index];
				if (source !== undefined && source !== null) {
					for (var nextKey in source) {
						if (source.hasOwnProperty(nextKey)) {
							output[nextKey] = source[nextKey];
						}
					}
				}
			}
			return output;
		};
	})();
}

MM.init();
<commit_msg>change position from absolute to fixed<commit_after>/* global  Log, Loader, Module, config, defaults */
/* jshint -W020 */

/* Magic Mirror
 * Main System
 *
 * By Michael Teeuw http://michaelteeuw.nl
 * MIT Licensed.
 */

var MM = (function() {

	var modules = [];

	/* Private Methods */

	/* createDomObjects()
	 * Create dom objects for all modules that
	 * are configured for a specific position.
	 */
	var createDomObjects = function() {
		for (var m in modules) {
			var module = modules[m];

			if (typeof module.data.position === "string") {

				var wrapper = selectWrapper(module.data.position);

				var dom = document.createElement("div");
				dom.id = module.identifier;
				dom.className = module.name;

				if (typeof module.data.classes === "string") {
					dom.className = "module " + dom.className + " " + module.data.classes;
				}

				dom.opacity = 0;
				wrapper.appendChild(dom);

				if (typeof module.data.header !== "undefined" && module.data.header !== "") {
					var moduleHeader = document.createElement("header");
					moduleHeader.innerHTML = module.data.header;
					moduleHeader.className = "module-header";
					dom.appendChild(moduleHeader);
				}

				var moduleContent = document.createElement("div");
				moduleContent.className = "module-content";
				dom.appendChild(moduleContent);

				updateDom(module, 0);
			}
		}

		sendNotification("DOM_OBJECTS_CREATED");
	};

	/* selectWrapper(position)
	 * Select the wrapper dom object for a specific position.
	 *
	 * argument position string - The name of the position.
	 */
	var selectWrapper = function(position) {
		var classes = position.replace("_"," ");
		var parentWrapper = document.getElementsByClassName(classes);
		if (parentWrapper.length > 0) {
			var wrapper =  parentWrapper[0].getElementsByClassName("container");
			if (wrapper.length > 0) {
				return wrapper[0];
			}
		}
	};

	/* sendNotification(notification, payload, sender)
	 * Send a notification to all modules.
	 *
	 * argument notification string - The identifier of the noitication.
	 * argument payload mixed - The payload of the notification.
	 * argument sender Module - The module that sent the notification.
	 */
	var sendNotification = function(notification, payload, sender) {
		for (var m in modules) {
			var module = modules[m];
			if (module !== sender) {
				module.notificationReceived(notification, payload, sender);
			}
		}
	};

	/* updateDom(module, speed)
	 * Update the dom for a specific module.
	 *
	 * argument module Module - The module that needs an update.
	 * argument speed Number - The number of microseconds for the animation. (optional)
	 */
	var updateDom = function(module, speed) {
		var newContent = module.getDom();
		var newHeader = module.getHeader();

		if (!module.hidden) {

			if (!moduleNeedsUpdate(module, newHeader, newContent)) {
				return;
			}

			if (!speed) {
				updateModuleContent(module, newHeader, newContent);
				return;
			}

			hideModule(module, speed / 2, function() {
				updateModuleContent(module, newHeader, newContent);
				if (!module.hidden) {
					showModule(module, speed / 2);
				}
			});
		} else {
			updateModuleContent(module, newHeader, newContent);
		}
	};

	/* moduleNeedsUpdate(module, newContent)
	 * Check if the content has changed.
	 *
	 * argument module Module - The module to check.
	 * argument newContent Domobject - The new content that is generated.
	 *
	 * return bool - Does the module need an update?
	 */
	var moduleNeedsUpdate = function(module, newHeader, newContent) {
		var moduleWrapper = document.getElementById(module.identifier);
		var contentWrapper = moduleWrapper.getElementsByClassName("module-content");
		var headerWrapper = moduleWrapper.getElementsByClassName("module-header");

		var headerNeedsUpdate = false;
		var contentNeedsUpdate = false;

		if (headerWrapper.length > 0) {
			headerNeedsUpdate = newHeader !== headerWrapper.innerHTML;
		}

		var tempContentWrapper = document.createElement("div");
		tempContentWrapper.appendChild(newContent);
		contentNeedsUpdate = tempContentWrapper.innerHTML !== contentWrapper[0].innerHTML;

		return headerNeedsUpdate || contentNeedsUpdate;
	};

	/* moduleNeedsUpdate(module, newContent)
	 * Update the content of a module on screen.
	 *
	 * argument module Module - The module to check.
	 * argument newContent Domobject - The new content that is generated.
	 */
	var updateModuleContent = function(module, newHeader, newContent) {
		var moduleWrapper = document.getElementById(module.identifier);
		var headerWrapper = moduleWrapper.getElementsByClassName("module-header");
		var contentWrapper = moduleWrapper.getElementsByClassName("module-content");

		contentWrapper[0].innerHTML = "";
		contentWrapper[0].appendChild(newContent);

		if( headerWrapper.length > 0 && newHeader) {
			headerWrapper[0].innerHTML = newHeader;
		}

	};

	/* hideModule(module, speed, callback)
	 * Hide the module.
	 *
	 * argument module Module - The module to hide.
	 * argument speed Number - The speed of the hide animation.
	 * argument callback function - Called when the animation is done.
	 */
	var hideModule = function(module, speed, callback, options) {
		options = options || {};

		// set lockString if set in options.
		if (options.lockString) {
			// Log.log("Has lockstring: " + options.lockString);
			if (module.lockStrings.indexOf(options.lockString) === -1) {
				module.lockStrings.push(options.lockString);
			}
		}

		var moduleWrapper = document.getElementById(module.identifier);
		if (moduleWrapper !== null) {
			moduleWrapper.style.transition = "opacity " + speed / 1000 + "s";
			moduleWrapper.style.opacity = 0;

			clearTimeout(module.showHideTimer);
			module.showHideTimer = setTimeout(function() {
				// To not take up any space, we just make the position absolute.
				// since it's fade out anyway, we can see it lay above or
				// below other modules. This works way better than adjusting
				// the .display property.
				moduleWrapper.style.position = "fixed";

				if (typeof callback === "function") { callback(); }
			}, speed);
		}
	};

	/* showModule(module, speed, callback)
	 * Show the module.
	 *
	 * argument module Module - The module to show.
	 * argument speed Number - The speed of the show animation.
	 * argument callback function - Called when the animation is done.
	 */
	var showModule = function(module, speed, callback, options) {
		options = options || {};

		// remove lockString if set in options.
		if (options.lockString) {
			var index = module.lockStrings.indexOf(options.lockString)
			if ( index !== -1) {
				module.lockStrings.splice(index, 1);
			}
		}

		// Check if there are no more lockstrings set, or the force option is set.
		// Otherwise cancel show action.
		if (module.lockStrings.length !== 0 && options.force !== true) {
			Log.log("Will not show " + module.name + ". LockStrings active: " + module.lockStrings.join(","));
			return;
		}

		// If forced show, clean current lockstrings.
		if (module.lockStrings.length !== 0 && options.force === true) {
			Log.log("Force show of module: " + module.name);
			module.lockStrings = [];
		}

		var moduleWrapper = document.getElementById(module.identifier);
		if (moduleWrapper !== null) {
			moduleWrapper.style.transition = "opacity " + speed / 1000 + "s";
			// Restore the postition. See hideModule() for more info.
			moduleWrapper.style.position = "static";
			moduleWrapper.style.opacity = 1;

			clearTimeout(module.showHideTimer);
			module.showHideTimer = setTimeout(function() {
				if (typeof callback === "function") { callback(); }
			}, speed);

		}
	};

	/* loadConfig()
	 * Loads the core config and combines it with de system defaults.
	 */
	var loadConfig = function() {
		if (typeof config === "undefined") {
			config = defaults;
			Log.error("Config file is missing! Please create a config file.");
			return;
		}

		config = Object.assign(defaults, config);
	};

	/* setSelectionMethodsForModules()
	 * Adds special selectors on a collection of modules.
	 *
	 * argument modules array - Array of modules.
	 */
	var setSelectionMethodsForModules = function(modules) {

		/* withClass(className)
		 * filters a collection of modules based on classname(s).
		 *
		 * argument className string/array - one or multiple classnames. (array or space devided)
		 *
		 * return array - Filtered collection of modules.
		 */
		var withClass = function(className) {
			var searchClasses = className;
			if (typeof className === "string") {
				searchClasses = className.split(" ");
			}

			var newModules = modules.filter(function(module) {
				var classes = module.data.classes.toLowerCase().split(" ");

				for (var c in searchClasses) {
					var searchClass = searchClasses[c];
					if (classes.indexOf(searchClass.toLowerCase()) !== -1) {
						return true;
					}
				}

				return false;
			});

			setSelectionMethodsForModules(newModules);
			return newModules;
		};

		/* exceptWithClass(className)
		 * filters a collection of modules based on classname(s). (NOT)
		 *
		 * argument className string/array - one or multiple classnames. (array or space devided)
		 *
		 * return array - Filtered collection of modules.
		 */
		var exceptWithClass  = function(className) {
			var searchClasses = className;
			if (typeof className === "string") {
				searchClasses = className.split(" ");
			}

			var newModules = modules.filter(function(module) {
				var classes = module.data.classes.toLowerCase().split(" ");

				for (var c in searchClasses) {
					var searchClass = searchClasses[c];
					if (classes.indexOf(searchClass.toLowerCase()) !== -1) {
						return false;
					}
				}

				return true;
			});

			setSelectionMethodsForModules(newModules);
			return newModules;
		};

		/* exceptModule(module)
		 * Removes a module instance from the collection.
		 *
		 * argument module Module object - The module instance to remove from the collection.
		 *
		 * return array - Filtered collection of modules.
		 */
		var exceptModule = function(module) {
			var newModules = modules.filter(function(mod) {
				return mod.identifier !== module.identifier;
			});

			setSelectionMethodsForModules(newModules);
			return newModules;
		};

		/* enumerate(callback)
		 * Walks thru a collection of modules and executes the callback with the module as an argument.
		 *
		 * argument callback function - The function to execute with the module as an argument.
		 */
		var enumerate = function(callback) {
			modules.map(function(module) {
				callback(module);
			});
		};

		if (typeof modules.withClass === "undefined") { Object.defineProperty(modules, "withClass",  {value: withClass, enumerable: false}); }
		if (typeof modules.exceptWithClass === "undefined") { Object.defineProperty(modules, "exceptWithClass",  {value: exceptWithClass, enumerable: false}); }
		if (typeof modules.exceptModule === "undefined") { Object.defineProperty(modules, "exceptModule",  {value: exceptModule, enumerable: false}); }
		if (typeof modules.enumerate === "undefined") { Object.defineProperty(modules, "enumerate",  {value: enumerate, enumerable: false}); }
	};

	return {
		/* Public Methods */

		/* init()
		 * Main init method.
		 */
		init: function() {
			Log.info("Initializing MagicMirror.");
			loadConfig();
			Translator.loadCoreTranslations(config.language);
			Loader.loadModules();
		},

		/* modulesStarted(moduleObjects)
		 * Gets called when all modules are started.
		 *
		 * argument moduleObjects array<Module> - All module instances.
		 */
		modulesStarted: function(moduleObjects) {
			modules = [];
			for (var m in moduleObjects) {
				var module = moduleObjects[m];
				modules[module.data.index] = module;
			}

			Log.info("All modules started!");
			sendNotification("ALL_MODULES_STARTED");

			createDomObjects();
		},

		/* sendNotification(notification, payload, sender)
		 * Send a notification to all modules.
		 *
		 * argument notification string - The identifier of the noitication.
		 * argument payload mixed - The payload of the notification.
		 * argument sender Module - The module that sent the notification.
		 */
		sendNotification: function(notification, payload, sender) {
			if (arguments.length < 3) {
				Log.error("sendNotification: Missing arguments.");
				return;
			}

			if (typeof notification !== "string") {
				Log.error("sendNotification: Notification should be a string.");
				return;
			}

			if (!(sender instanceof Module)) {
				Log.error("sendNotification: Sender should be a module.");
				return;
			}

			// Further implementation is done in the private method.
			sendNotification(notification, payload, sender);
		},

		/* updateDom(module, speed)
		 * Update the dom for a specific module.
		 *
		 * argument module Module - The module that needs an update.
		 * argument speed Number - The number of microseconds for the animation. (optional)
		 */
		updateDom: function(module, speed) {
			if (!(module instanceof Module)) {
				Log.error("updateDom: Sender should be a module.");
				return;
			}

			// Further implementation is done in the private method.
			updateDom(module, speed);
		},

		/* getModules(module, speed)
		 * Returns a collection of all modules currently active.
		 *
		 * return array - A collection of all modules currently active.
		 */
		getModules: function() {
			setSelectionMethodsForModules(modules);
			return modules;
		},

		/* hideModule(module, speed, callback)
		 * Hide the module.
		 *
		 * argument module Module - The module hide.
		 * argument speed Number - The speed of the hide animation.
		 * argument callback function - Called when the animation is done.
		 * argument options object - Optional settings for the hide method.
		 */
		hideModule: function(module, speed, callback, options) {
			module.hidden = true;
			hideModule(module, speed, callback, options);
		},

		/* showModule(module, speed, callback)
		 * Show the module.
		 *
		 * argument module Module - The module show.
		 * argument speed Number - The speed of the show animation.
		 * argument callback function - Called when the animation is done.
		 * argument options object - Optional settings for the hide method.
		 */
		showModule: function(module, speed, callback, options) {
			module.hidden = false;
			showModule(module, speed, callback, options);
		}
	};

})();

// Add polyfill for Object.assign.
if (typeof Object.assign != "function") {
	(function() {
		Object.assign = function(target) {
			"use strict";
			if (target === undefined || target === null) {
				throw new TypeError("Cannot convert undefined or null to object");
			}
			var output = Object(target);
			for (var index = 1; index < arguments.length; index++) {
				var source = arguments[index];
				if (source !== undefined && source !== null) {
					for (var nextKey in source) {
						if (source.hasOwnProperty(nextKey)) {
							output[nextKey] = source[nextKey];
						}
					}
				}
			}
			return output;
		};
	})();
}

MM.init();
<|endoftext|>


<commit_before>var app = null;
var TIMEOUT = 10000;
var devicePlatform = null;
var config_streaming = null;

app = new kendo.mobile.Application($(document.body), {
    skin: "flat"
});

document.addEventListener("deviceready", onDeviceReady, false);

var jqxhr = $.ajax({
    url: "http://cyoung.com.br/mobile/api/public/json/tvcorreio.json",
    dataType: "jsonp",
    jsonpCallback: "load_config",
    success: function(data) {
        if (data.banner.itens.length > 0) {
            $('#banner > .banner').cycle({
                fx: "scrollHorz",
                timeout: data.banner.timeout
            });

            $.each(data.banner.itens, function(i, item) {
                $('#banner > .banner').cycle('add', '');
            });

        }
        config_streaming = data.streaming;
    }
});

function onDeviceReady() {
    //adicionar o evento online
    document.addEventListener("online", onOnline, false);
    //adicionar o evento offline
    document.addEventListener("offline", onOffline, false);
    //monitorar o click no backbutton
    document.addEventListener("backbutton", function(e) {

        navigator.notification.confirm(
                'Você realmente deseja sair do aplicativo?',
                exitFromApp,
                'Sair',
                'Não,Sim'
                );

    }
    , false);

    navigator.splashscreen.hide();
    devicePlatform = device.platform;
}

function onOffline() {
    showAlert('Sem conexão a internet!');
}

function onOnline() {
    //$("#modal-alert").data("kendoMobileModalView").close();
    //hideLoader();
}

function exitFromApp(buttonIndex) {
    if (buttonIndex == 2) {
        if (navigator.app) {
            navigator.app.exitApp();
        } else if (navigator.device) {
            navigator.device.exitApp();
        }
    }
}

function exitFromAccount(buttonIndex) {
    if (buttonIndex == 2) {
        onLogout();
    }
}

function onClickToPlayer() {
    alert(config_streaming.url.devicePlatform);
    window.open(config_streaming.url.devicePlatform, '_system');
    return false;
}<commit_msg>- load config json<commit_after>var app = null;
var TIMEOUT = 10000;
var devicePlatform = null;
var config_streaming = null;

app = new kendo.mobile.Application($(document.body), {
    skin: "flat"
});

document.addEventListener("deviceready", onDeviceReady, false);

var jqxhr = $.ajax({
    url: "http://cyoung.com.br/mobile/api/public/json/tvcorreio.json",
    dataType: "jsonp",
    jsonpCallback: "load_config",
    cache: false,
    success: function(data) {
        if (data.banner.itens.length > 0) {
            $('#banner > .banner').cycle({
                fx: "scrollHorz",
                timeout: data.banner.timeout
            });

            $.each(data.banner.itens, function(i, item) {
                $('#banner > .banner').cycle('add', '');
            });

        }
        config_streaming = data.streaming;
    }
});

function onDeviceReady() {
    //adicionar o evento online
    document.addEventListener("online", onOnline, false);
    //adicionar o evento offline
    document.addEventListener("offline", onOffline, false);
    //monitorar o click no backbutton
    document.addEventListener("backbutton", function(e) {

        navigator.notification.confirm(
                'Você realmente deseja sair do aplicativo?',
                exitFromApp,
                'Sair',
                'Não,Sim'
                );

    }
    , false);

    navigator.splashscreen.hide();
    devicePlatform = device.platform;
}

function onOffline() {
    showAlert('Sem conexão a internet!');
}

function onOnline() {
    //$("#modal-alert").data("kendoMobileModalView").close();
    //hideLoader();
}

function exitFromApp(buttonIndex) {
    if (buttonIndex == 2) {
        if (navigator.app) {
            navigator.app.exitApp();
        } else if (navigator.device) {
            navigator.device.exitApp();
        }
    }
}

function exitFromAccount(buttonIndex) {
    if (buttonIndex == 2) {
        onLogout();
    }
}

function onClickToPlayer() {
    alert(config_streaming.url.devicePlatform);
    window.open(config_streaming.url.devicePlatform, '_system');
    return false;
}<|endoftext|>


<commit_before>'use strict';
(function() {
	//cache DOM
	//viewports
	const $aboutViewport = $('#aboutViewport');
	const $skillsViewport = $('#skillsViewport');
	const $projectsViewport = $('#projectsViewport');
	const $cvViewport = $('#cvViewport');
	const $contactViewPort = $('#contactViewPort');
	const $headerMenu = $('#headerMenu');

	//links
	const $btnLogo = $('#btnLogo');
	const $btnAbout = $('#btnAbout');
	const $btnSkills = $('#btnSkills');
	const $btnProjects = $('#btnProjects');
	const $btnCV = $('#btnCV');
	const $btnContact = $('#btnContact');
	const $btnCVLinkToSkills = $('#btnCVLinkToSkills');

	//links - menu
	const $btnMenuAbout = $('#btnMenuAbout');
	const $btnMenuSkills = $('#btnMenuSkills');
	const $btnMenuProjects = $('#btnMenuProjects');
	const $btnMenuCV = $('#btnMenuCV');
	const $btnMenuContact = $('#btnMenuContact');

	//Get header height for offset
	const headerHeight = $('#headerContainer').css('height').replace('px','');

	$headerMenu.removeClass('hide');

	function scrollTo(e) {
		$('html, body').stop().animate ({
			scrollTop: e.offset().top - headerHeight
		}, 1000);
	};

	//Event listeners
	//Header links
	$btnLogo.on('click', () => {
		scrollTo($aboutViewport);
	});

	$btnAbout.on('click', () => {
		scrollTo($aboutViewport);
	});

	$btnSkills.on('click', () => {
		scrollTo($skillsViewport);
	});

	$btnProjects.on('click', () => {
		scrollTo($projectsViewport);
	});

	$btnCV.on('click', () => {
		scrollTo($cvViewport);
	});

	$btnContact.on('click', () => {
		scrollTo($contactViewPort);
	});

	//Header menu links
	$btnMenuAbout.on('click', () => {
		scrollTo($aboutViewport);
	});

	$btnMenuSkills.on('click', () => {
		scrollTo($skillsViewport);
	});

	$btnMenuProjects.on('click', () => {
		scrollTo($projectsViewport);
	});

	$btnMenuCV.on('click', () => {
		scrollTo($cvViewport);
	});

	$btnMenuContact.on('click', () => {
		scrollTo($contactViewPort);
	});

	//Core skills link in cv
	$btnCVLinkToSkills.on('click', () => {
		scrollTo($skillsViewport);
	});

}());<commit_msg>slight modification to js variable definitions<commit_after>'use strict';
(function() {
	//cache DOM
	//viewports
	const $aboutViewport = $('#aboutViewport'),
	$skillsViewport = $('#skillsViewport'),
	$projectsViewport = $('#projectsViewport'),
	$cvViewport = $('#cvViewport'),
	$contactViewPort = $('#contactViewPort'),
	$headerMenu = $('#headerMenu');

	//links
	const $btnLogo = $('#btnLogo'),
	$btnAbout = $('#btnAbout'),
	$btnSkills = $('#btnSkills'),
	$btnProjects = $('#btnProjects'),
	$btnCV = $('#btnCV'),
	$btnContact = $('#btnContact'),
	$btnCVLinkToSkills = $('#btnCVLinkToSkills');

	//links - menu
	const $btnMenuAbout = $('#btnMenuAbout'),
	$btnMenuSkills = $('#btnMenuSkills'),
	$btnMenuProjects = $('#btnMenuProjects'),
	$btnMenuCV = $('#btnMenuCV'),
	$btnMenuContact = $('#btnMenuContact');

	//Get header height for offset
	const headerHeight = $('#headerContainer').css('height').replace('px','');

	$headerMenu.removeClass('hide');

	function scrollTo(e) {
		$('html, body').stop().animate ({
			scrollTop: e.offset().top - headerHeight
		}, 1000);
	};

	//Event listeners
	//Header links
	$btnLogo.on('click', () => {
		scrollTo($aboutViewport);
	});

	$btnAbout.on('click', () => {
		scrollTo($aboutViewport);
	});

	$btnSkills.on('click', () => {
		scrollTo($skillsViewport);
	});

	$btnProjects.on('click', () => {
		scrollTo($projectsViewport);
	});

	$btnCV.on('click', () => {
		scrollTo($cvViewport);
	});

	$btnContact.on('click', () => {
		scrollTo($contactViewPort);
	});

	//Header menu links
	$btnMenuAbout.on('click', () => {
		scrollTo($aboutViewport);
	});

	$btnMenuSkills.on('click', () => {
		scrollTo($skillsViewport);
	});

	$btnMenuProjects.on('click', () => {
		scrollTo($projectsViewport);
	});

	$btnMenuCV.on('click', () => {
		scrollTo($cvViewport);
	});

	$btnMenuContact.on('click', () => {
		scrollTo($contactViewPort);
	});

	//Core skills link in cv
	$btnCVLinkToSkills.on('click', () => {
		scrollTo($skillsViewport);
	});

}());<|endoftext|>


<commit_before>!function ($) {
	$(function(){
		// IE10 viewport hack for Surface/desktop Windows 8 bug
		if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
			var msViewportStyle = document.createElement("style");
			msViewportStyle.appendChild(
				document.createTextNode(
					"@-ms-viewport{width:auto!important}"
					)
				);
			document.getElementsByTagName("head")[0].
			appendChild(msViewportStyle);
		}

		// Bootstrap affix sidebar
		var $sideBar = $('#sidebar')
		$sideBar.affix({
			offset: {
				top: -1 // Always has affix property
			}
		})
	})
}(jQuery)

// Enabling light boxes
var myCustomLightbox = new RGlightbox({/*options*/});
<commit_msg>Unused in new update<commit_after><|endoftext|>


<commit_before>/*
* ADR Reporting
* Copyright (C) 2017 Divay Prakash
* GNU Affero General Public License 3.0 (https://github.com/divayprakash/adr/blob/master/LICENSE)
*/
$(document).ready(function(){
  $('.button-collapse').sideNav();
  var helpOpen = false;
  $('#help-fab').click(function(e) {
    if (helpOpen) {
      $('#help-tap-target').tapTarget('close');
      helpOpen = false;
    }
    else {
      $('#help-tap-target').tapTarget('open');
      helpOpen = true;
    }
  });
  $('.chips').material_chip();
  $('.datepicker').pickadate({
    format: 'dd/mm/yyyy',
    selectMonths: true
  });
  $('.datepicker-year').pickadate({
    format: 'dd/mm/yyyy',
    selectMonths: true,
    selectYears: 7
  });
  $('#medication-add').modal();
  enableSpecFieldOnRadio('stop','#stop-reduced','yes');
  //enableSpecFieldOnRadio('reintro','#reintro-reduced');
  enableSpecFieldOnRadio2('serious','other','#serious-spec','death','#date-death','#date-death-label');
  enableSpecFieldOnRadio('outcome','#outcome-spec','other');
  setupTabs();
});

function enableSpecFieldOnRadio2(radioId, caseId1, fieldSelector1, caseId2, fieldSelector2, labelSelector) {
  $('input[type=radio][name=' + radioId + ']').on('change', function() {
    switch($(this).val()) {
      case caseId1:
        $(fieldSelector1).prop('disabled', false);
        $(fieldSelector2).val("");
        $(fieldSelector2).removeClass('valid');
        $(fieldSelector2).removeClass('invalid');
        $(fieldSelector2).prop('disabled', true);
        $(labelSelector).css('color', 'rgba(0, 0, 0, 0.26)');
        break;
      case caseId2:
        $(fieldSelector2).prop('disabled', false);
        $(labelSelector).css('color', '#000');
        $(fieldSelector1).val("");
        $(fieldSelector1).removeClass('valid');
        $(fieldSelector1).removeClass('invalid');
        $(fieldSelector1).prop('disabled', true);
        break;
      default:
        $(fieldSelector1).val("");
        $(fieldSelector1).removeClass('valid');
        $(fieldSelector1).removeClass('invalid');
        $(fieldSelector1).prop('disabled', true);
        $(fieldSelector2).val("");
        $(fieldSelector2).removeClass('valid');
        $(fieldSelector2).removeClass('invalid');
        $(fieldSelector2).prop('disabled', true);
        $(labelSelector).css('color', 'rgba(0, 0, 0, 0.26)');
        break;
    }
  });
}

function setupTabs() {
  var tabUl = document.getElementById('tabs-list');
  var tabs = tabUl.getElementsByTagName('li');
  for (var i = 0; i < tabs.length; i++) {
    if (tabs[i].classList.contains('disabled')) {
      tabs[i].classList.remove('lighten-4');
      tabs[i].classList.add('lighten-5');
    }
    else {
      tabs[i].classList.remove('lighten-5');
      tabs[i].classList.add('lighten-4');
    }
  }
}

function formSubmit(id) {
  switch(id) {
    case 'patient-submit':
      if (processPatientData()) gotoNextTab('patient-tab', 'reaction-tab', 'reaction');
      break;
    case 'reaction-submit':
      if (processReactionData()) gotoNextTab('reaction-tab', 'medication-tab', 'medication');
      break;
    case 'medication-submit':
      if (processMedicationData()) gotoNextTab('medication-tab', 'outcome-tab', 'outcome');
      break;
    case 'outcome-submit':
      if (processOutcomeData()) gotoNextTab('outcome-tab', 'reporter-tab', 'reporter');
      break;
    case 'reporter-submit':
      if (processReporterData()) alert('TODO!!!');
      break;
  }
}

function processPatientData() {
  var flag = true;
  var initials = document.getElementById('initials').value;
  var age = document.getElementById('age').value;
  var genderFields = document.getElementsByName('gender');
  var gender;
  for (var i = 0; i < genderFields.length; i++) {
      if (genderFields[i].checked){
          gender = genderFields[i].id;
      }
  }
  var weight = document.getElementById('weight').value;
  if (initials == "") {
    makeToast('Initials is a required field!');
    flag = false;
  }
  if (age == "") {
    makeToast('Age is a required field!');
    flag = false;
  }
  if (gender == null) {
    makeToast('Gender is a required field!');
    flag = false;
  }
  if (weight <= 0) {
    makeToast('Weight is a required field!');
    flag = false;
  }
  return flag;
}

function processReactionData() {
  var flag = true;
  var chips = $('#reaction-description').material_chip('data');
  var startDate = $('#date-start').pickadate().pickadate('picker').get();
  var endDate = $('#date-end').pickadate().pickadate('picker').get();
  if (chips.length <= 0) {
    makeToast('Description is a required field!');
    flag = false;
  }
  if (startDate == "") {
    makeToast('Start date is a required field!');
    flag = false;
  }
  if (endDate == "") {
    makeToast('End date is a required field!');
    flag = false;
  }
  startDateCorrected = new Date(changeDateFormat(startDate)).getTime();
  endDateCorrected = new Date(changeDateFormat(endDate)).getTime();
  todaysDate = new Date(getTodaysDate()).getTime();
  if (startDateCorrected > todaysDate) {
    makeToast('Start date must be before or on the date today!');
    flag = false;
  }
  if (endDateCorrected > todaysDate) {
    makeToast('End date must be before or on the date today!');
    flag = false;
  }
  if (startDateCorrected > endDateCorrected) {
    makeToast('Start date must be before end date!');
    flag = false;
  }
  return flag;
}

function processMedicationData() {
  if (medicationCount > 0) return true;
  else {
    makeToast('Atleast 1 medication must be added!');
    return false;
  }
}

function processOutcomeData() {
  var flag = true;
  var concomitant = $('#concomitant').val();
  var test = $('#test').val();
  var history = $('#history').val();
  var serious = $("input[type='radio'][name='serious']:checked").val();
  if (serious == null) {
    makeToast('Seriousness of reaction is a required field!');
    flag = false;
  }
  var seriousSpec;
  if (serious == 'other') {
    seriousSpec = $('#serious-spec').val();
    if (seriousSpec == "") {
      makeToast('Specific other response is a required field!');
      flag = false;
    }
  }
  var outcome = $("input[type='radio'][name='outcome']:checked").val();
  if (outcome == null) {
    makeToast('Outcome of reaction is a required field!');
    flag = false;
  }
  var outcomeSpec;
  if (outcome == 'other') {
    outcomeSpec = $('#outcome-spec').val();
    if (outcomeSpec == "") {
      makeToast('Specific other response is a required field!');
      flag = false;
    }
  }
  return flag;
}

function processReporterData() {
  var flag = true;
  var reporterName = $('#reporter-name').val();
  if (reporterName == "") {
    makeToast('Repoter name is a required field!');
    flag = false;
  }
  var address1 = $('#address1').val();
  if (address1 == "") {
    makeToast('Address line 1 is a required field!');
    flag = false;
  }
  var address2 = $('#address2').val();
  var pincode = $('#pincode').val();
  var pincodeRegex = /^[0-9]{6,6}$/;
  if (pincode == "") {
    makeToast('Pincode is a required field!');
    flag = false;
  }
  else if (!pincodeRegex.test(pincode)) {
    makeToast('Incorrect pincode');
    flag = false;
  }
  var email = $('#email').val();
  var emailRegex = /^([a-zA-Z0-9+_\-\.])+@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,6})$/;
  if (email == "") {
    makeToast('Email is a required field!');
    flag = false;
  }
  else if (!emailRegex.test(email)) {
    makeToast('Invalid email');
    flag = false;
  }
  var phone = $('#phone').val();
  var phoneRegex = /^[0-9-+]{8,15}$/;
  if (phone == "") {
    makeToast('Telephone number is a required field!');
    flag = false;
  }
  else if (!phoneRegex.test(phone)) {
    makeToast('Invalid telephone number');
    flag = false;
  }
  var speciality = $('#speciality').val();
  var occupation = $('#occupation').val();
  if (occupation == "") {
    makeToast('Occupation is a required field!');
    flag = false;
  }
  var dateReport = changeDateFormat(getTodaysDate());
  return flag;
}

function changeDateFormat(date) {
  s = date.split('/');
  if (s.length == 3) newDate = s[2] + "/" + s[1] + "/" + s[0];
  else newDate = "1970/01/01";
  return newDate;
}

function getTodaysDate() {
  var today = new Date();
  var dd = today.getDate();
  var mm = today.getMonth() + 1;
  var yyyy = today.getFullYear();
  if (dd < 10) dd = '0' + dd;
  if (mm < 10) mm = '0' + mm;
  today = yyyy + '/' + mm + '/' + dd;
  return today;
}

function makeToast(msg) {
  Materialize.toast(msg, 4000, 'rounded');
}

function gotoNextTab(present, next, sel) {
  var presentTab = document.getElementById(present);
  var nextTab = document.getElementById(next);
  presentTab.classList.add('disabled');
  nextTab.classList.remove('disabled');
  setupTabs();
  $('ul.tabs').tabs('select_tab', sel);
}

function enableSpecFieldOnRadio(radioId, fieldSelector, caseId) {
  $('input[type=radio][name=' + radioId + ']').on('change', function() {
    switch($(this).val()) {
      case caseId:
        $(fieldSelector).prop('disabled', false);
        break;
      default:
        $(fieldSelector).val("");
        $(fieldSelector).removeClass('valid');
        $(fieldSelector).removeClass('invalid');
        $(fieldSelector).prop('disabled', true);
        break;
    }
  });
}

var medicationCount = 0;
function medicationAdd() {
  var flag = true;
  var name = $('#medication-name').val();
  if (name == "") {
    makeToast('Medication name is a required field!');
    flag = false;
  }
  var manufacturer = $('#manufacturer').val();
  if (manufacturer == "") {
    makeToast('Manufacturer is a required field!');
    flag = false;
  }
  var batch = $('#batch').val();
  if (batch == "") {
    makeToast('Batch/lot number is a required field!');
    flag = false;
  }
  var expiry = $('#expiry').pickadate().pickadate('picker').get();
  var dose = $('#dose').val();
  if (dose == "") {
    makeToast('Dose is a required field!');
    flag = false;
  }
  var route = $("input[type='radio'][name='route']:checked").val();
  if (route == null) {
    makeToast('Route is a required field!');
    flag = false;
  }
  var frequency = $('#freq').val();
  if (frequency == null) {
    makeToast('Frequency is a required field!');
    flag = false;
  }
  var therapyStart = $('#therapy-start').pickadate().pickadate('picker').get();
  var therapyEnd = $('#therapy-end').pickadate().pickadate('picker').get();
  var therapyStartCorrected = new Date(changeDateFormat(therapyStart)).getTime();
  var therapyEndCorrected = new Date(changeDateFormat(therapyEnd)).getTime();
  var todaysDate = new Date(getTodaysDate()).getTime();
  if (therapyStart == "") {
    makeToast('Therapy start date is a required field!');
    flag = false;
  }
  if (therapyEnd == "") {
    makeToast('Therapy end date is a required field!');
    flag = false;
  }
  if (therapyStartCorrected > todaysDate) {
    makeToast('Therapy start date must be before or on the date today!');
    flag = false;
  }
  if (therapyEndCorrected > todaysDate) {
    makeToast('Therapy end date must be before or on the date today!');
    flag = false;
  }
  if (therapyStartCorrected > therapyEndCorrected) {
    makeToast('Therapy start date must be before therapy end date!');
    flag = false;
  }
  var duration;
  if (flag) duration = (therapyEndCorrected - therapyStartCorrected) / (1000 * 24 * 60 * 60);
  var reason = $('#reason').val();
  if (reason == "") {
    makeToast('Reason for use is a required field!');
    flag = false;
  }
  var stop = $("input[type='radio'][name='stop']:checked").val();
  if (stop == null) {
    makeToast('Reaction abated after drug stopped or dose reduced is a required field!');
    flag = false;
  }
  var stopReduced;
  if (stop == "yes") {
    stopReduced = $('#stop-reduced').val();
    if (stopReduced != "" && stopReduced > dose) {
      makeToast('Reduced dose must be less than original dose!');
      flag = false;
    }
  }
  //var reintro = $("input[type='radio'][name='reintro']:checked").val();
  //var reintroReduced = 0;
  //if (reintro == "yes")  reintroReduced = $('reintro-reduced').val();
  if (flag) {
    medicationCount = medicationCount + 1;
    formReset();
    $('#medication-add').modal('close');
    Materialize.toast('Medication added!', 4000, 'rounded');
    var divToAdd = "

"+ name +"
"+ manufacturer + "

";
    $('#insert').before(divToAdd);
    if (medicationCount == 4) {
      makeToast("No more medications can be added!");
      document.findElementById('medication-add').disabled = true;
    }
  }
}

function formReset(){
  $('#medication-form').each(function(){
      this.reset();
  });
  $('#medication-add').scrollTop(0);
}
<commit_msg>Validate date of death field<commit_after>/*
* ADR Reporting
* Copyright (C) 2017 Divay Prakash
* GNU Affero General Public License 3.0 (https://github.com/divayprakash/adr/blob/master/LICENSE)
*/
$(document).ready(function(){
  $('.button-collapse').sideNav();
  var helpOpen = false;
  $('#help-fab').click(function(e) {
    if (helpOpen) {
      $('#help-tap-target').tapTarget('close');
      helpOpen = false;
    }
    else {
      $('#help-tap-target').tapTarget('open');
      helpOpen = true;
    }
  });
  $('.chips').material_chip();
  $('.datepicker').pickadate({
    format: 'dd/mm/yyyy',
    selectMonths: true
  });
  $('.datepicker-year').pickadate({
    format: 'dd/mm/yyyy',
    selectMonths: true,
    selectYears: 7
  });
  $('#medication-add').modal();
  enableSpecFieldOnRadio('stop','#stop-reduced','yes');
  //enableSpecFieldOnRadio('reintro','#reintro-reduced');
  enableSpecFieldOnRadio2('serious','other','#serious-spec','death','#date-death','#date-death-label');
  enableSpecFieldOnRadio('outcome','#outcome-spec','other');
  setupTabs();
});

function enableSpecFieldOnRadio2(radioId, caseId1, fieldSelector1, caseId2, fieldSelector2, labelSelector) {
  $('input[type=radio][name=' + radioId + ']').on('change', function() {
    switch($(this).val()) {
      case caseId1:
        $(fieldSelector1).prop('disabled', false);
        $(fieldSelector2).val("");
        $(fieldSelector2).removeClass('valid');
        $(fieldSelector2).removeClass('invalid');
        $(fieldSelector2).prop('disabled', true);
        $(labelSelector).css('color', 'rgba(0, 0, 0, 0.26)');
        break;
      case caseId2:
        $(fieldSelector2).prop('disabled', false);
        $(labelSelector).css('color', '#000');
        $(fieldSelector1).val("");
        $(fieldSelector1).removeClass('valid');
        $(fieldSelector1).removeClass('invalid');
        $(fieldSelector1).prop('disabled', true);
        break;
      default:
        $(fieldSelector1).val("");
        $(fieldSelector1).removeClass('valid');
        $(fieldSelector1).removeClass('invalid');
        $(fieldSelector1).prop('disabled', true);
        $(fieldSelector2).val("");
        $(fieldSelector2).removeClass('valid');
        $(fieldSelector2).removeClass('invalid');
        $(fieldSelector2).prop('disabled', true);
        $(labelSelector).css('color', 'rgba(0, 0, 0, 0.26)');
        break;
    }
  });
}

function setupTabs() {
  var tabUl = document.getElementById('tabs-list');
  var tabs = tabUl.getElementsByTagName('li');
  for (var i = 0; i < tabs.length; i++) {
    if (tabs[i].classList.contains('disabled')) {
      tabs[i].classList.remove('lighten-4');
      tabs[i].classList.add('lighten-5');
    }
    else {
      tabs[i].classList.remove('lighten-5');
      tabs[i].classList.add('lighten-4');
    }
  }
}

function formSubmit(id) {
  switch(id) {
    case 'patient-submit':
      if (processPatientData()) gotoNextTab('patient-tab', 'reaction-tab', 'reaction');
      break;
    case 'reaction-submit':
      if (processReactionData()) gotoNextTab('reaction-tab', 'medication-tab', 'medication');
      break;
    case 'medication-submit':
      if (processMedicationData()) gotoNextTab('medication-tab', 'outcome-tab', 'outcome');
      break;
    case 'outcome-submit':
      if (processOutcomeData()) gotoNextTab('outcome-tab', 'reporter-tab', 'reporter');
      break;
    case 'reporter-submit':
      if (processReporterData()) alert('TODO!!!');
      break;
  }
}

function processPatientData() {
  var flag = true;
  var initials = document.getElementById('initials').value;
  var age = document.getElementById('age').value;
  var genderFields = document.getElementsByName('gender');
  var gender;
  for (var i = 0; i < genderFields.length; i++) {
      if (genderFields[i].checked){
          gender = genderFields[i].id;
      }
  }
  var weight = document.getElementById('weight').value;
  if (initials == "") {
    makeToast('Initials is a required field!');
    flag = false;
  }
  if (age == "") {
    makeToast('Age is a required field!');
    flag = false;
  }
  if (gender == null) {
    makeToast('Gender is a required field!');
    flag = false;
  }
  if (weight <= 0) {
    makeToast('Weight is a required field!');
    flag = false;
  }
  return flag;
}

function processReactionData() {
  var flag = true;
  var chips = $('#reaction-description').material_chip('data');
  var startDate = $('#date-start').pickadate().pickadate('picker').get();
  var endDate = $('#date-end').pickadate().pickadate('picker').get();
  if (chips.length <= 0) {
    makeToast('Description is a required field!');
    flag = false;
  }
  if (startDate == "") {
    makeToast('Start date is a required field!');
    flag = false;
  }
  if (endDate == "") {
    makeToast('End date is a required field!');
    flag = false;
  }
  startDateCorrected = new Date(changeDateFormat(startDate)).getTime();
  endDateCorrected = new Date(changeDateFormat(endDate)).getTime();
  todaysDate = new Date(getTodaysDate()).getTime();
  if (startDateCorrected > todaysDate) {
    makeToast('Start date must be before or on the date today!');
    flag = false;
  }
  if (endDateCorrected > todaysDate) {
    makeToast('End date must be before or on the date today!');
    flag = false;
  }
  if (startDateCorrected > endDateCorrected) {
    makeToast('Start date must be before end date!');
    flag = false;
  }
  return flag;
}

function processMedicationData() {
  if (medicationCount > 0) return true;
  else {
    makeToast('Atleast 1 medication must be added!');
    return false;
  }
}

function processOutcomeData() {
  var flag = true;
  var concomitant = $('#concomitant').val();
  var test = $('#test').val();
  var history = $('#history').val();
  var serious = $("input[type='radio'][name='serious']:checked").val();
  if (serious == null) {
    makeToast('Seriousness of reaction is a required field!');
    flag = false;
  }
  var seriousSpec;
  if (serious == 'other') {
    seriousSpec = $('#serious-spec').val();
    if (seriousSpec == "") {
      makeToast('Specific other response is a required field!');
      flag = false;
    }
  }
  var outcome = $("input[type='radio'][name='outcome']:checked").val();
  if (outcome == null) {
    makeToast('Outcome of reaction is a required field!');
    flag = false;
  }
  var outcomeSpec;
  if (outcome == 'other') {
    outcomeSpec = $('#outcome-spec').val();
    if (outcomeSpec == "") {
      makeToast('Specific other response is a required field!');
      flag = false;
    }
  }
  var outcomeDateDeath;
  if (outcome == 'death') {
    outcomeDateDeath = $('#date-death').val();
    if (outcomeDateDeath == "") {
      makeToast('Specific date of death is a required field!');
      flag = false;
    }
    else {
      outcomeDateDeathCorrected = new Date(changeDateFormat(outcomeDateDeath)).getTime();
      todaysDate = new Date(getTodaysDate()).getTime();
      if (endDateCorrected > todaysDate) {
        makeToast('Date of death must be before or on the date today!');
        flag = false;
      }
    }
  }
  return flag;
}

function processReporterData() {
  var flag = true;
  var reporterName = $('#reporter-name').val();
  if (reporterName == "") {
    makeToast('Repoter name is a required field!');
    flag = false;
  }
  var address1 = $('#address1').val();
  if (address1 == "") {
    makeToast('Address line 1 is a required field!');
    flag = false;
  }
  var address2 = $('#address2').val();
  var pincode = $('#pincode').val();
  var pincodeRegex = /^[0-9]{6,6}$/;
  if (pincode == "") {
    makeToast('Pincode is a required field!');
    flag = false;
  }
  else if (!pincodeRegex.test(pincode)) {
    makeToast('Incorrect pincode');
    flag = false;
  }
  var email = $('#email').val();
  var emailRegex = /^([a-zA-Z0-9+_\-\.])+@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,6})$/;
  if (email == "") {
    makeToast('Email is a required field!');
    flag = false;
  }
  else if (!emailRegex.test(email)) {
    makeToast('Invalid email');
    flag = false;
  }
  var phone = $('#phone').val();
  var phoneRegex = /^[0-9-+]{8,15}$/;
  if (phone == "") {
    makeToast('Telephone number is a required field!');
    flag = false;
  }
  else if (!phoneRegex.test(phone)) {
    makeToast('Invalid telephone number');
    flag = false;
  }
  var speciality = $('#speciality').val();
  var occupation = $('#occupation').val();
  if (occupation == "") {
    makeToast('Occupation is a required field!');
    flag = false;
  }
  var dateReport = changeDateFormat(getTodaysDate());
  return flag;
}

function changeDateFormat(date) {
  s = date.split('/');
  if (s.length == 3) newDate = s[2] + "/" + s[1] + "/" + s[0];
  else newDate = "1970/01/01";
  return newDate;
}

function getTodaysDate() {
  var today = new Date();
  var dd = today.getDate();
  var mm = today.getMonth() + 1;
  var yyyy = today.getFullYear();
  if (dd < 10) dd = '0' + dd;
  if (mm < 10) mm = '0' + mm;
  today = yyyy + '/' + mm + '/' + dd;
  return today;
}

function makeToast(msg) {
  Materialize.toast(msg, 4000, 'rounded');
}

function gotoNextTab(present, next, sel) {
  var presentTab = document.getElementById(present);
  var nextTab = document.getElementById(next);
  presentTab.classList.add('disabled');
  nextTab.classList.remove('disabled');
  setupTabs();
  $('ul.tabs').tabs('select_tab', sel);
}

function enableSpecFieldOnRadio(radioId, fieldSelector, caseId) {
  $('input[type=radio][name=' + radioId + ']').on('change', function() {
    switch($(this).val()) {
      case caseId:
        $(fieldSelector).prop('disabled', false);
        break;
      default:
        $(fieldSelector).val("");
        $(fieldSelector).removeClass('valid');
        $(fieldSelector).removeClass('invalid');
        $(fieldSelector).prop('disabled', true);
        break;
    }
  });
}

var medicationCount = 0;
function medicationAdd() {
  var flag = true;
  var name = $('#medication-name').val();
  if (name == "") {
    makeToast('Medication name is a required field!');
    flag = false;
  }
  var manufacturer = $('#manufacturer').val();
  if (manufacturer == "") {
    makeToast('Manufacturer is a required field!');
    flag = false;
  }
  var batch = $('#batch').val();
  if (batch == "") {
    makeToast('Batch/lot number is a required field!');
    flag = false;
  }
  var expiry = $('#expiry').pickadate().pickadate('picker').get();
  var dose = $('#dose').val();
  if (dose == "") {
    makeToast('Dose is a required field!');
    flag = false;
  }
  var route = $("input[type='radio'][name='route']:checked").val();
  if (route == null) {
    makeToast('Route is a required field!');
    flag = false;
  }
  var frequency = $('#freq').val();
  if (frequency == null) {
    makeToast('Frequency is a required field!');
    flag = false;
  }
  var therapyStart = $('#therapy-start').pickadate().pickadate('picker').get();
  var therapyEnd = $('#therapy-end').pickadate().pickadate('picker').get();
  var therapyStartCorrected = new Date(changeDateFormat(therapyStart)).getTime();
  var therapyEndCorrected = new Date(changeDateFormat(therapyEnd)).getTime();
  var todaysDate = new Date(getTodaysDate()).getTime();
  if (therapyStart == "") {
    makeToast('Therapy start date is a required field!');
    flag = false;
  }
  if (therapyEnd == "") {
    makeToast('Therapy end date is a required field!');
    flag = false;
  }
  if (therapyStartCorrected > todaysDate) {
    makeToast('Therapy start date must be before or on the date today!');
    flag = false;
  }
  if (therapyEndCorrected > todaysDate) {
    makeToast('Therapy end date must be before or on the date today!');
    flag = false;
  }
  if (therapyStartCorrected > therapyEndCorrected) {
    makeToast('Therapy start date must be before therapy end date!');
    flag = false;
  }
  var duration;
  if (flag) duration = (therapyEndCorrected - therapyStartCorrected) / (1000 * 24 * 60 * 60);
  var reason = $('#reason').val();
  if (reason == "") {
    makeToast('Reason for use is a required field!');
    flag = false;
  }
  var stop = $("input[type='radio'][name='stop']:checked").val();
  if (stop == null) {
    makeToast('Reaction abated after drug stopped or dose reduced is a required field!');
    flag = false;
  }
  var stopReduced;
  if (stop == "yes") {
    stopReduced = $('#stop-reduced').val();
    if (stopReduced != "" && stopReduced > dose) {
      makeToast('Reduced dose must be less than original dose!');
      flag = false;
    }
  }
  //var reintro = $("input[type='radio'][name='reintro']:checked").val();
  //var reintroReduced = 0;
  //if (reintro == "yes")  reintroReduced = $('reintro-reduced').val();
  if (flag) {
    medicationCount = medicationCount + 1;
    formReset();
    $('#medication-add').modal('close');
    Materialize.toast('Medication added!', 4000, 'rounded');
    var divToAdd = "

"+ name +"
"+ manufacturer + "

";
    $('#insert').before(divToAdd);
    if (medicationCount == 4) {
      makeToast("No more medications can be added!");
      document.findElementById('medication-add').disabled = true;
    }
  }
}

function formReset(){
  $('#medication-form').each(function(){
      this.reset();
  });
  $('#medication-add').scrollTop(0);
}
<|endoftext|>