<commit_before>/**
	* SinglePro HTML 2.0
	* Template Scripts
	* Created by WpFreeware Team

	Custom JS

	1. Superslides Slider
	2. Fixed Top Menubar
	3. Featured Slider
	4. Skill Circle
	5. Wow animation
	6. Project Counter
	7. TEAM SLIDER
	8. BLOG SLIDER
	9. TESTIMONIAL SLIDER
	10. CLIENTS SLIDER
	11. Google Map
	12. SCROLL TOP BUTTON
	13. PRELOADER
	14. MENU SCROLL
	15. MOBILE MENU CLOSE

**/

jQuery(function($){

	/* -----------------------------------------------------------  */
	/*  1. Superslides Slider										*/
	/* -----------------------------------------------------------  */
	jQuery('#slides').superslides({
      animation: 'slide',
      play: '5000'
    });

	/* -----------------------------------------------------------  */
	/*  2. Fixed Top Menubar										*/
	/* -----------------------------------------------------------  */

	// For fixed top bar
       $(window).scroll(function(){
        if($(window).scrollTop() >100 /*or $(window).height()*/){
            $(".navbar-fixed-top").addClass('past-main');
        }
    else{
      $(".navbar-fixed-top").removeClass('past-main');
      }
    });

	/* -----------------------------------------------------------  */
	/*  3. Featured Slider											*/
	/* -----------------------------------------------------------  */

    $('.featured_slider').slick({
      dots: true,
      infinite: true,
      speed: 800,
      arrows:false,
      slidesToShow: 1,
      slide: 'div',
      autoplay: true,
      fade: true,
      autoplaySpeed: 5000,
      cssEase: 'linear'
    });

	/* ----------------------------------------------------------- */
	/*  4. Skill Circle
	/* ----------------------------------------------------------- */

	$('#myStathalf').circliful();
	$('#myStat').circliful();
	$('#myStathalf2').circliful();
	$('#myStat2').circliful();
	$('#myStat3').circliful();
	$('#myStat4').circliful();
	$('#myStathalf3').circliful();

	/* ----------------------------------------------------------- */
	/*  5. Wow smooth animation
	/* ----------------------------------------------------------- */

	wow = new WOW(
      {
        animateClass: 'animated',
        offset:       100
      }
    );
    wow.init();

	/* ----------------------------------------------------------- */
	/*  6. Project Counter
	/* ----------------------------------------------------------- */
 var test = function() {
	(function ($) {

		$.fn.countTo = function (options) {
			options = options || {};

			return $(this).each(function () {
				// set options for current element
				var settings = $.extend({}, $.fn.countTo.defaults, {
					from:            $(this).data('from'),
					to:              $(this).data('to'),
					speed:           $(this).data('speed'),
					refreshInterval: $(this).data('refresh-interval'),
					decimals:        $(this).data('decimals')
				}, options);

				// how many times to update the value, and how much to increment the value on each update
				var loops = Math.ceil(settings.speed / settings.refreshInterval),
					increment = (settings.to - settings.from) / loops;

				// references & variables that will change with each update
				var self = this,
					$self = $(this),
					loopCount = 0,
					value = settings.from,
					data = $self.data('countTo') || {};

				$self.data('countTo', data);

				// if an existing interval can be found, clear it first
				if (data.interval) {
					clearInterval(data.interval);
				}
				data.interval = setInterval(updateTimer, settings.refreshInterval);

				// initialize the element with the starting value
				render(value);

				function updateTimer() {
					value += increment;
					loopCount++;

					render(value);

					if (typeof(settings.onUpdate) == 'function') {
						settings.onUpdate.call(self, value);
					}

					if (loopCount >= loops) {
						// remove the interval
						$self.removeData('countTo');
						clearInterval(data.interval);
						value = settings.to;

						if (typeof(settings.onComplete) == 'function') {
							settings.onComplete.call(self, value);
						}
					}
				}

				function render(value) {
					var formattedValue = settings.formatter.call(self, value, settings);
					$self.html(formattedValue);
				}
			});
		};

		$.fn.countTo.defaults = {
			from: 0,               // the number the element should start at
			to: 0,                 // the number the element should end at
			speed: 1000,           // how long it should take to count between the target numbers
			refreshInterval: 100,  // how often the element should be updated
			decimals: 0,           // the number of decimal places to show
			formatter: formatter,  // handler for formatting the value before rendering
			onUpdate: null,        // callback method for every time the element is updated
			onComplete: null       // callback method for when the element finishes updating
		};

		function formatter(value, settings) {
			return value.toFixed(settings.decimals);
		}
	}(jQuery));

	jQuery(function ($) {
	  // custom formatting example
	  $('#count-number').data('countToOptions', {
		formatter: function (value, options) {
		  return value.toFixed(options.decimals).replace(/\B(?=(?:\d{3})+(?!\d))/g, ',');
		}
	  });

	   $('#count-number2').data('countToOptions', {
		formatter: function (value, options) {
		  return value.toFixed(options.decimals).replace(/\B(?=(?:\d{3})+(?!\d))/g, ',');
		}
	  });

	    $('#count-number3').data('countToOptions', {
		formatter: function (value, options) {
		  return value.toFixed(options.decimals).replace(/\B(?=(?:\d{3})+(?!\d))/g, ',');
		}
	  });

	    $('#count-number4').data('countToOptions', {
		formatter: function (value, options) {
		  return value.toFixed(options.decimals).replace(/\B(?=(?:\d{3})+(?!\d))/g, ',');
		}
	  });

	  // start all the timers
	  $('.timer').each(count);

	  function count(options) {
		var $this = $(this);
		options = $.extend({}, options || {}, $this.data('countToOptions') || {});
		$this.countTo(options);
	  }
	});
};

// Get Meetup Members and Events numbers from cache
$.ajax({
  async: "false",
  url: "http://testing.neurotechx.com/john/social_media_apis/cache/cached-meetup-count.JSON",
  dataType: "json",
  success: function(data) {
  	$(".meetup-members").attr("data-to",data.meetupMembersCount.total);
  	$(".meetup-events").attr("data-to",data.meetupEventsCount.total);
  }
});

// Get Twitter, Facebook and Slack numbers from cache, then add them to the 'onlineCommunity' variable
var onlineCommunity = 0;

$.ajax({
  async: "false",
  url: "http://testing.neurotechx.com/john/social_media_apis/cache/cached-twitter-count.JSON",
  dataType: "json",
  success: function(data) {
    onlineCommunity += data.twitterFollowersCount.total;
    getFacebookCount();
  }
});

var getFacebookCount = function(){
  $.ajax({
    async: "false",
    url: "http://testing.neurotechx.com/john/social_media_apis/cache/cached-facebook-count.JSON",
    dataType: "json",
    success: function(data) {
	    onlineCommunity += data.facebookGroupMembersCount.neurotechx;
    	onlineCommunity += data.facebookPageLikesCount.neurotechx;
	    getSlackCount();
    }
  });
}

var getSlackCount = function(){
  $.ajax({
    async: "false",
    url: "http://testing.neurotechx.com/john/social_media_apis/cache/cached-slack-count.JSON",
    dataType: "json",
    success: function(data) {
	    onlineCommunity += data.slackMembersCount;
	    $(".community-members").attr("data-to", onlineCommunity);
	    test();
    }
  });
};

// Make API calls and update the cache files
$.getJSON( "http://testing.neurotechx.com/john/social_media_apis/meetup-count.php" );
$.getJSON( "http://testing.neurotechx.com/john/social_media_apis/twitter-count.php" );
$.getJSON( "http://testing.neurotechx.com/john/social_media_apis/facebook-count.php" );
$.getJSON( "http://testing.neurotechx.com/john/social_media_apis/slack-count.php" );

	/* ----------------------------------------------------------- */
	/*  7. TEAM SLIDER
	/* ----------------------------------------------------------- */

		$('.team_slider').slick({
		  dots: false,
		  infinite: true,
		  speed: 300,
		  slidesToShow: 4,
		  slidesToScroll: 4,
		  responsive: [
		    {
		      breakpoint: 1024,
		      settings: {
		        slidesToShow: 3,
		        slidesToScroll: 3,
		        infinite: true,
		        dots: true
		      }
		    },
		    {
		      breakpoint: 600,
		      settings: {
		        slidesToShow: 2,
		        slidesToScroll: 2
		      }
		    },
		    {
		      breakpoint: 480,
		      settings: {
		        slidesToShow: 1,
		        slidesToScroll: 1
		      }
		    }
		  ]
		});

	/* ----------------------------------------------------------- */
	/*  8. BLOG SLIDER
	/* ----------------------------------------------------------- */

    $('.blog_slider').slick({
		  dots: false,
		  infinite: true,
		  speed: 300,
		  slidesToShow: 3,
		  slidesToScroll: 3,
		  responsive: [
		    {
		      breakpoint: 1024,
		      settings: {
		        slidesToShow: 3,
		        slidesToScroll: 3,
		        infinite: true,
		        dots: true
		      }
		    },
		    {
		      breakpoint: 600,
		      settings: {
		        slidesToShow: 2,
		        slidesToScroll: 2
		      }
		    },
		    {
		      breakpoint: 480,
		      settings: {
		        slidesToShow: 1,
		        slidesToScroll: 1
		      }
		    }
		]
	});

	/* ----------------------------------------------------------- */
	/*  9. TESTIMONIAL SLIDER
	/* ----------------------------------------------------------- */

	$('.testimonial_slider').slick({
      dots: true,
      infinite: true,
      speed: 800,
      arrows:false,
      slidesToShow: 1,
      slide: 'li',
      autoplay: true,
      fade: true,
      autoplaySpeed: 3000,
      cssEase: 'linear'
    });

    /* ----------------------------------------------------------- */
	/*  10. CLIENTS SLIDER
	/* ----------------------------------------------------------- */

    $('.clients_slider').slick({
		  dots: false,
		  infinite: true,
		  speed: 300,
		  slidesToShow: 4,
		  slidesToScroll: 4,
		  responsive: [
		    {
		      breakpoint: 1199,
		      settings: {
		        slidesToShow: 3,
		        slidesToScroll: 3,
		        infinite: true,
		        dots: true
		      }
		    },
		    {
		      breakpoint: 600,
		      settings: {
		        slidesToShow: 2,
		        slidesToScroll: 2
		      }
		    },
		    {
		      breakpoint: 480,
		      settings: {
		        slidesToShow: 1,
		        slidesToScroll: 1
		      }
		    }
		]
	});

	/* ----------------------------------------------------------- */
	/*  12. SCROLL TOP BUTTON
	/* ----------------------------------------------------------- */

	//Check to see if the window is top if not then display button

	  $(window).scroll(function(){
	    if ($(this).scrollTop() > 300) {
	      $('.scrollToTop').fadeIn();
	    } else {
	      $('.scrollToTop').fadeOut();
	    }
	  });

	  //Click event to scroll to top

	  $('.scrollToTop').click(function(){
	    $('html, body').animate({scrollTop : 0},800);
	    return false;
	  });

	/* ----------------------------------------------------------- */
	/*  13. PRELOADER
	/* ----------------------------------------------------------- */

	  jQuery(window).load(function() { // makes sure the whole site is loaded
      $('#status').fadeOut(); // will first fade out the loading animation
      $('#preloader').delay(100).fadeOut('slow'); // will fade out the white DIV that covers the website.
      $('body').delay(100).css({'overflow':'visible'});
    })

	/* ----------------------------------------------------------- */
	/*  14. MENU SCROLL
	/* ----------------------------------------------------------- */

	//MENU SCROLLING WITH ACTIVE ITEM SELECTED

	// Cache selectors
	var lastId,
	topMenu = $("#top-menu"),
	topMenuHeight = topMenu.outerHeight()+13,
	// All list items
	menuItems = topMenu.find("a"),
	// Anchors corresponding to menu items
	scrollItems = menuItems.map(function(){
	  var item = $($(this).attr("href"));
	  if (item.length) { return item; }
	});

	// Bind click handler to menu items
	// so we can get a fancy scroll animation
	menuItems.click(function(e){
	  var href = $(this).attr("href"),
	      offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight+1;
	  $('html, body').stop().animate({
	      scrollTop: offsetTop
	  }, 900);
	  e.preventDefault();
	});

	// Bind to scroll
	$(window).scroll(function(){
	   // Get container scroll position
	   var fromTop = $(this).scrollTop()+topMenuHeight;

	   // Get id of current scroll item
	   var cur = scrollItems.map(function(){
	     if ($(this).offset().top < fromTop)
	       return this;
	   });
	   // Get the id of the current element
	   cur = cur[cur.length-1];
	   var id = cur && cur.length ? cur[0].id : "";

	   if (lastId !== id) {
	       lastId = id;
	       // Set/remove active class
	       menuItems
	         .parent().removeClass("active")
	         .end().filter("[href=#"+id+"]").parent().addClass("active");
	   }
	})

	/* ----------------------------------------------------------- */
	/*  15. MOBILE MENU ACTIVE CLOSE
	/* ----------------------------------------------------------- */

	$('.navbar-nav').on('click', 'li a', function() {
	  $('.navbar-collapse').collapse('hide');
	});

});<commit_msg>Edit AJAX URLs for the NTX live site<commit_after>/**
	* SinglePro HTML 2.0
	* Template Scripts
	* Created by WpFreeware Team

	Custom JS

	1. Superslides Slider
	2. Fixed Top Menubar
	3. Featured Slider
	4. Skill Circle
	5. Wow animation
	6. Project Counter
	7. TEAM SLIDER
	8. BLOG SLIDER
	9. TESTIMONIAL SLIDER
	10. CLIENTS SLIDER
	11. Google Map
	12. SCROLL TOP BUTTON
	13. PRELOADER
	14. MENU SCROLL
	15. MOBILE MENU CLOSE

**/

jQuery(function($){

	/* -----------------------------------------------------------  */
	/*  1. Superslides Slider										*/
	/* -----------------------------------------------------------  */
	jQuery('#slides').superslides({
      animation: 'slide',
      play: '5000'
    });

	/* -----------------------------------------------------------  */
	/*  2. Fixed Top Menubar										*/
	/* -----------------------------------------------------------  */

	// For fixed top bar
       $(window).scroll(function(){
        if($(window).scrollTop() >100 /*or $(window).height()*/){
            $(".navbar-fixed-top").addClass('past-main');
        }
    else{
      $(".navbar-fixed-top").removeClass('past-main');
      }
    });

	/* -----------------------------------------------------------  */
	/*  3. Featured Slider											*/
	/* -----------------------------------------------------------  */

    $('.featured_slider').slick({
      dots: true,
      infinite: true,
      speed: 800,
      arrows:false,
      slidesToShow: 1,
      slide: 'div',
      autoplay: true,
      fade: true,
      autoplaySpeed: 5000,
      cssEase: 'linear'
    });

	/* ----------------------------------------------------------- */
	/*  4. Skill Circle
	/* ----------------------------------------------------------- */

	$('#myStathalf').circliful();
	$('#myStat').circliful();
	$('#myStathalf2').circliful();
	$('#myStat2').circliful();
	$('#myStat3').circliful();
	$('#myStat4').circliful();
	$('#myStathalf3').circliful();

	/* ----------------------------------------------------------- */
	/*  5. Wow smooth animation
	/* ----------------------------------------------------------- */

	wow = new WOW(
      {
        animateClass: 'animated',
        offset:       100
      }
    );
    wow.init();

	/* ----------------------------------------------------------- */
	/*  6. Project Counter
	/* ----------------------------------------------------------- */
 var test = function() {
	(function ($) {

		$.fn.countTo = function (options) {
			options = options || {};

			return $(this).each(function () {
				// set options for current element
				var settings = $.extend({}, $.fn.countTo.defaults, {
					from:            $(this).data('from'),
					to:              $(this).data('to'),
					speed:           $(this).data('speed'),
					refreshInterval: $(this).data('refresh-interval'),
					decimals:        $(this).data('decimals')
				}, options);

				// how many times to update the value, and how much to increment the value on each update
				var loops = Math.ceil(settings.speed / settings.refreshInterval),
					increment = (settings.to - settings.from) / loops;

				// references & variables that will change with each update
				var self = this,
					$self = $(this),
					loopCount = 0,
					value = settings.from,
					data = $self.data('countTo') || {};

				$self.data('countTo', data);

				// if an existing interval can be found, clear it first
				if (data.interval) {
					clearInterval(data.interval);
				}
				data.interval = setInterval(updateTimer, settings.refreshInterval);

				// initialize the element with the starting value
				render(value);

				function updateTimer() {
					value += increment;
					loopCount++;

					render(value);

					if (typeof(settings.onUpdate) == 'function') {
						settings.onUpdate.call(self, value);
					}

					if (loopCount >= loops) {
						// remove the interval
						$self.removeData('countTo');
						clearInterval(data.interval);
						value = settings.to;

						if (typeof(settings.onComplete) == 'function') {
							settings.onComplete.call(self, value);
						}
					}
				}

				function render(value) {
					var formattedValue = settings.formatter.call(self, value, settings);
					$self.html(formattedValue);
				}
			});
		};

		$.fn.countTo.defaults = {
			from: 0,               // the number the element should start at
			to: 0,                 // the number the element should end at
			speed: 1000,           // how long it should take to count between the target numbers
			refreshInterval: 100,  // how often the element should be updated
			decimals: 0,           // the number of decimal places to show
			formatter: formatter,  // handler for formatting the value before rendering
			onUpdate: null,        // callback method for every time the element is updated
			onComplete: null       // callback method for when the element finishes updating
		};

		function formatter(value, settings) {
			return value.toFixed(settings.decimals);
		}
	}(jQuery));

	jQuery(function ($) {
	  // custom formatting example
	  $('#count-number').data('countToOptions', {
		formatter: function (value, options) {
		  return value.toFixed(options.decimals).replace(/\B(?=(?:\d{3})+(?!\d))/g, ',');
		}
	  });

	   $('#count-number2').data('countToOptions', {
		formatter: function (value, options) {
		  return value.toFixed(options.decimals).replace(/\B(?=(?:\d{3})+(?!\d))/g, ',');
		}
	  });

	    $('#count-number3').data('countToOptions', {
		formatter: function (value, options) {
		  return value.toFixed(options.decimals).replace(/\B(?=(?:\d{3})+(?!\d))/g, ',');
		}
	  });

	    $('#count-number4').data('countToOptions', {
		formatter: function (value, options) {
		  return value.toFixed(options.decimals).replace(/\B(?=(?:\d{3})+(?!\d))/g, ',');
		}
	  });

	  // start all the timers
	  $('.timer').each(count);

	  function count(options) {
		var $this = $(this);
		options = $.extend({}, options || {}, $this.data('countToOptions') || {});
		$this.countTo(options);
	  }
	});
};

// Get Meetup Members and Events numbers from cache
$.ajax({
  async: "false",
  url: "http://neurotechx.com/social_media_apis/cache/cached-meetup-count.JSON",
  dataType: "json",
  success: function(data) {
  	$(".meetup-members").attr("data-to",data.meetupMembersCount.total);
  	$(".meetup-events").attr("data-to",data.meetupEventsCount.total);
  }
});

// Get Twitter, Facebook and Slack numbers from cache, then add them to the 'onlineCommunity' variable
var onlineCommunity = 0;

$.ajax({
  async: "false",
  url: "http://neurotechx.com/social_media_apis/cache/cached-twitter-count.JSON",
  dataType: "json",
  success: function(data) {
    onlineCommunity += data.twitterFollowersCount.total;
    getFacebookCount();
  }
});

var getFacebookCount = function(){
  $.ajax({
    async: "false",
    url: "http://neurotechx.com/social_media_apis/cache/cached-facebook-count.JSON",
    dataType: "json",
    success: function(data) {
	    onlineCommunity += data.facebookGroupMembersCount.neurotechx;
    	onlineCommunity += data.facebookPageLikesCount.neurotechx;
	    getSlackCount();
    }
  });
}

var getSlackCount = function(){
  $.ajax({
    async: "false",
    url: "http://neurotechx.com/social_media_apis/cache/cached-slack-count.JSON",
    dataType: "json",
    success: function(data) {
	    onlineCommunity += data.slackMembersCount;
	    $(".community-members").attr("data-to", onlineCommunity);
	    test();
    }
  });
};

// Make API calls and update the cache files
$.getJSON( "http://neurotechx.com/social_media_apis/meetup-count.php" );
$.getJSON( "http://neurotechx.com/social_media_apis/twitter-count.php" );
$.getJSON( "http://neurotechx.com/social_media_apis/facebook-count.php" );
$.getJSON( "http://neurotechx.com/social_media_apis/slack-count.php" );

	/* ----------------------------------------------------------- */
	/*  7. TEAM SLIDER
	/* ----------------------------------------------------------- */

		$('.team_slider').slick({
		  dots: false,
		  infinite: true,
		  speed: 300,
		  slidesToShow: 4,
		  slidesToScroll: 4,
		  responsive: [
		    {
		      breakpoint: 1024,
		      settings: {
		        slidesToShow: 3,
		        slidesToScroll: 3,
		        infinite: true,
		        dots: true
		      }
		    },
		    {
		      breakpoint: 600,
		      settings: {
		        slidesToShow: 2,
		        slidesToScroll: 2
		      }
		    },
		    {
		      breakpoint: 480,
		      settings: {
		        slidesToShow: 1,
		        slidesToScroll: 1
		      }
		    }
		  ]
		});

	/* ----------------------------------------------------------- */
	/*  8. BLOG SLIDER
	/* ----------------------------------------------------------- */

    $('.blog_slider').slick({
		  dots: false,
		  infinite: true,
		  speed: 300,
		  slidesToShow: 3,
		  slidesToScroll: 3,
		  responsive: [
		    {
		      breakpoint: 1024,
		      settings: {
		        slidesToShow: 3,
		        slidesToScroll: 3,
		        infinite: true,
		        dots: true
		      }
		    },
		    {
		      breakpoint: 600,
		      settings: {
		        slidesToShow: 2,
		        slidesToScroll: 2
		      }
		    },
		    {
		      breakpoint: 480,
		      settings: {
		        slidesToShow: 1,
		        slidesToScroll: 1
		      }
		    }
		]
	});

	/* ----------------------------------------------------------- */
	/*  9. TESTIMONIAL SLIDER
	/* ----------------------------------------------------------- */

	$('.testimonial_slider').slick({
      dots: true,
      infinite: true,
      speed: 800,
      arrows:false,
      slidesToShow: 1,
      slide: 'li',
      autoplay: true,
      fade: true,
      autoplaySpeed: 3000,
      cssEase: 'linear'
    });

    /* ----------------------------------------------------------- */
	/*  10. CLIENTS SLIDER
	/* ----------------------------------------------------------- */

    $('.clients_slider').slick({
		  dots: false,
		  infinite: true,
		  speed: 300,
		  slidesToShow: 4,
		  slidesToScroll: 4,
		  responsive: [
		    {
		      breakpoint: 1199,
		      settings: {
		        slidesToShow: 3,
		        slidesToScroll: 3,
		        infinite: true,
		        dots: true
		      }
		    },
		    {
		      breakpoint: 600,
		      settings: {
		        slidesToShow: 2,
		        slidesToScroll: 2
		      }
		    },
		    {
		      breakpoint: 480,
		      settings: {
		        slidesToShow: 1,
		        slidesToScroll: 1
		      }
		    }
		]
	});

	/* ----------------------------------------------------------- */
	/*  12. SCROLL TOP BUTTON
	/* ----------------------------------------------------------- */

	//Check to see if the window is top if not then display button

	  $(window).scroll(function(){
	    if ($(this).scrollTop() > 300) {
	      $('.scrollToTop').fadeIn();
	    } else {
	      $('.scrollToTop').fadeOut();
	    }
	  });

	  //Click event to scroll to top

	  $('.scrollToTop').click(function(){
	    $('html, body').animate({scrollTop : 0},800);
	    return false;
	  });

	/* ----------------------------------------------------------- */
	/*  13. PRELOADER
	/* ----------------------------------------------------------- */

	  jQuery(window).load(function() { // makes sure the whole site is loaded
      $('#status').fadeOut(); // will first fade out the loading animation
      $('#preloader').delay(100).fadeOut('slow'); // will fade out the white DIV that covers the website.
      $('body').delay(100).css({'overflow':'visible'});
    })

	/* ----------------------------------------------------------- */
	/*  14. MENU SCROLL
	/* ----------------------------------------------------------- */

	//MENU SCROLLING WITH ACTIVE ITEM SELECTED

	// Cache selectors
	var lastId,
	topMenu = $("#top-menu"),
	topMenuHeight = topMenu.outerHeight()+13,
	// All list items
	menuItems = topMenu.find("a"),
	// Anchors corresponding to menu items
	scrollItems = menuItems.map(function(){
	  var item = $($(this).attr("href"));
	  if (item.length) { return item; }
	});

	// Bind click handler to menu items
	// so we can get a fancy scroll animation
	menuItems.click(function(e){
	  var href = $(this).attr("href"),
	      offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight+1;
	  $('html, body').stop().animate({
	      scrollTop: offsetTop
	  }, 900);
	  e.preventDefault();
	});

	// Bind to scroll
	$(window).scroll(function(){
	   // Get container scroll position
	   var fromTop = $(this).scrollTop()+topMenuHeight;

	   // Get id of current scroll item
	   var cur = scrollItems.map(function(){
	     if ($(this).offset().top < fromTop)
	       return this;
	   });
	   // Get the id of the current element
	   cur = cur[cur.length-1];
	   var id = cur && cur.length ? cur[0].id : "";

	   if (lastId !== id) {
	       lastId = id;
	       // Set/remove active class
	       menuItems
	         .parent().removeClass("active")
	         .end().filter("[href=#"+id+"]").parent().addClass("active");
	   }
	})

	/* ----------------------------------------------------------- */
	/*  15. MOBILE MENU ACTIVE CLOSE
	/* ----------------------------------------------------------- */

	$('.navbar-nav').on('click', 'li a', function() {
	  $('.navbar-collapse').collapse('hide');
	});

});<|endoftext|>


<commit_before>var oldCursor = null;
var isMiddleMouse = false;
var isDown = false;

const FPDragHandleNone = 0;
const FPDragHandleTopLeft = 1;
const FPDragHandleBottomLeft = 2;
const FPDragHandleTopRight = 3;
const FPDragHandleBottomRight = 4;
const FPDragHandleMiddleLeft = 5;
const FPDragHandleMiddleTop = 6;
const FPDragHandleMiddleRight = 7;
const FPDragHandleMiddleBottom = 8;

function levelMouseDown(e)
{
    isDown = true;

    var cursor = getCursorPosition(levelCanvas.canvas, e);

    if (e.button == 1)
        isMiddleMouse = true;
    else
        isMiddleMouse = false;

    if (isMiddleMouse)
    {
        alignCursorOnGrid(cursor);
    }
    else if (paletteCanvas.activeFactory != null)
    {
        alignCursorOnGrid(cursor);

        var beforeLength = levelCanvas.levelObjects.length;
        paletteCanvas.activeFactory.create(levelCanvas.levelObjects, cursor.x, cursor.y);
        levelCanvas.draggedObject = levelCanvas.levelObjects[beforeLength];
        levelCanvas.draw();
    }
    else if (levelCanvas.currentHandle == FPDragHandleNone)
    {
        levelCanvas.draggedObject = levelCanvas.objectUnderMouse(cursor.x, cursor.y);
        if (levelCanvas.draggedObject == null)
        {
            levelCanvas.selectionStart = new FPPoint(cursor.x, cursor.y);
            levelCanvas.selectionEnd = new FPPoint(cursor.x, cursor.y);
        }
        else if (!levelCanvas.draggedObject.selected)
        {
            levelCanvas.deselectAll();
        }
    }

    oldCursor = new FPPoint(cursor.x, cursor.y);
}

function alignCursorOnGrid(cursor)
{
    cursor.x -= 16.0;
    cursor.y -= 16.0;
    cursor.x = Math.round(cursor.x / 32.0) * 32.0;
    cursor.y = Math.round(cursor.y / 32.0) * 32.0;
}

function levelMouseMove(e)
{
    var cursor = getCursorPosition(levelCanvas.canvas, e);

    if (!isDown)
    {
        if (levelCanvas.draggedObject != null)
        {
            var draggedObjectRect = levelCanvas.draggedObject.rect();
            var handleRect = new FPRect(0.0, 0.0, 14.0, 14.0);

            levelCanvas.currentHandle = FPDragHandleNone;

            for (var handle = FPDragHandleTopLeft; handle <= FPDragHandleMiddleBottom; handle++)
            {
    			var handlePoint = levelCanvas.pointFromHandle(handle, draggedObjectRect);

    			handleRect.origin.x = handlePoint.x - handleRect.size.width / 2.0;
    			handleRect.origin.y = handlePoint.y - handleRect.size.height / 2.0;

    			if (handleRect.containsPoint(cursor.x, cursor.y))
    			{
    				levelCanvas.currentHandle = handle;
    				break;
    			}
    		}

    		levelCanvas.draw();
	    }

        return;
    }

    if (isMiddleMouse)
    {
       alignCursorOnGrid(cursor);
       levelCanvas.moveAll(cursor.x - oldCursor.x, cursor.y - oldCursor.y);
       oldCursor.x = cursor.x;
       oldCursor.y = cursor.y;
       levelCanvas.draw();
    }
    else if (levelCanvas.selectionEnd != null)
    {
        levelCanvas.selectionEnd = new FPPoint(cursor.x, cursor.y);
        levelCanvas.draw();
    }
    else if (levelCanvas.draggedObject != null)
    {
        alignCursorOnGrid(cursor);

        var widthSegments = Math.floor((cursor.x - oldCursor.x + 16.0) / 32.0);
        var heightSegments = Math.floor((cursor.y - oldCursor.y + 16.0) / 32.0);

        if (paletteCanvas.activeFactory != null)
        {
        	var draggedObjectLocation = new FPPoint(oldCursor.x, oldCursor.y);
        	if (widthSegments < 0)
        		draggedObjectLocation.x += widthSegments * 32.0;
        	if (heightSegments < 0)
        		draggedObjectLocation.y += heightSegments * 32.0;

        	widthSegments = Math.max(Math.abs(widthSegments), 1);
        	heightSegments = Math.max(Math.abs(heightSegments), 1);

            levelCanvas.draggedObject.x = draggedObjectLocation.x;
            levelCanvas.draggedObject.y = draggedObjectLocation.y;

            levelCanvas.draggedObject.widthSegments = widthSegments;
            levelCanvas.draggedObject.heightSegments = heightSegments;
        }
        else if (levelCanvas.currentHandle != FPDragHandleNone)
        {
            levelCanvas.resizeDraggedObject(widthSegments, heightSegments);
        }
        else
        {
            widthSegments *= 32.0;
            heightSegments *= 32.0;

            levelCanvas.moveSelected(widthSegments, heightSegments);

            oldCursor.x += widthSegments;
            oldCursor.y += heightSegments;
        }

        levelCanvas.draw();
    }
}

function levelMouseUp(e)
{
    isDown = false;

    if (levelCanvas.selectionStart != null)
    {
        levelCanvas.draggedObject = null;

        levelCanvas.selectObjects();

        levelCanvas.selectionStart = null;
        levelCanvas.selectionEnd = null;
    }

    paletteCanvas.activeFactory = null;
    oldCursor = null;

    levelCanvas.draw();
    paletteCanvas.draw();
}

function FPLevelCanvas(canvasName)
{
    this.canvas = document.getElementById(canvasName);
    this.context = this.canvas.getContext('2d');

    this.canvas.width = document.width - 110;
    this.canvas.height = document.height - 4;

    this.levelObjects = new Array();

    this.draggedObject = null;

    this.selectionStart = null;
    this.selectionEnd = null;

    this.canvas.addEventListener('mousedown', levelMouseDown, false);
    this.canvas.addEventListener('mousemove', levelMouseMove, false);
    this.canvas.addEventListener('mouseup', levelMouseUp, false);

    this.currentHandle = FPDragHandleNone;

    this.drawGrid = function()
    {
        this.context.strokeStyle = "rgba(255,255,255, 0.2)";

        var rect = new FPRect(0, 0, this.canvas.width, this.canvas.height);

        for (var y = rect.origin.y; y < rect.size.height; y += 32)
    	{
    	    this.context.beginPath();
    	    this.context.moveTo(rect.origin.x, y);
    	    this.context.lineTo(rect.size.width, y);
    	    this.context.stroke();
    	}

    	for (var x = rect.origin.x; x < rect.size.width; x += 32)
    	{
    	    this.context.beginPath();
    		this.context.moveTo(x, rect.origin.y);
    		this.context.lineTo(x, rect.size.height);
    		this.context.stroke();
    	}
    }

    this.draw = function()
    {
        this.context.fillStyle = "rgb(55,60,89)";
        this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);

        this.drawGrid();

        for (i in this.levelObjects)
        {
            var levelObject = this.levelObjects[i];
            levelObject.draw(this.context);

            if (levelObject.selected || levelObject == this.draggedObject)
            {
                var levelObjectRect = levelObject.rect();
                this.context.strokeStyle = "rgba(255,255,255, 1.0)";
                this.context.strokeRect(levelObjectRect.origin.x, levelObjectRect.origin.y, levelObjectRect.size.width, levelObjectRect.size.height);
            }

             if (levelObject == this.draggedObject)
                this.drawHandles(levelObject);
        }

        if (this.selectionStart != null)
        {
            this.context.fillStyle = "rgba(255,255,255, 0.15)";
            this.context.strokeStyle = "rgba(255,255,255, 1.0)";

            var selectionRect = FPRectFromPoints(this.selectionStart, this.selectionEnd);

            this.context.fillRect(selectionRect.origin.x, selectionRect.origin.y, selectionRect.size.width, selectionRect.size.height);
            this.context.strokeRect(selectionRect.origin.x, selectionRect.origin.y, selectionRect.size.width, selectionRect.size.height);
        }
    }

    this.objectUnderMouse = function(x, y)
    {
        for (i in this.levelObjects)
        {
            var levelObject = this.levelObjects[i];

            if (levelObject.rect().containsPoint(x, y))
                return levelObject;
        }

        return null;
    }

    this.selectObjects = function()
    {
        var selectionRect = FPRectFromPoints(this.selectionStart, this.selectionEnd);

        for (i in this.levelObjects)
        {
            var levelObject = this.levelObjects[i];

            if (FPRectIntersectsRect(selectionRect, levelObject.rect()))
                levelObject.selected = true;
            else
                levelObject.selected = false;
        }
    }

    this.deselectAll = function()
    {
        for (i in this.levelObjects)
        {
            var levelObject = this.levelObjects[i];
            levelObject.selected = false;
        }
    }

    this.moveSelected = function(offsetX, offsetY)
    {
        for (i in this.levelObjects)
        {
            var levelObject = this.levelObjects[i];
            if (levelObject.selected || levelObject == this.draggedObject)
                levelObject.move(offsetX, offsetY);
        }
    }

    this.moveAll = function(offsetX, offsetY)
    {
        for (i in this.levelObjects)
        {
            var levelObject = this.levelObjects[i];
            levelObject.move(offsetX, offsetY);
        }
    }

    this.deleteSelected = function()
    {
        this.levelObjects = this.levelObjects.filter(function (obj) { return !obj.selected; });
        this.draw();
    }

    this.pointFromHandle = function(handle, rect)
    {
        switch (handle)
        {
    		case FPDragHandleTopLeft:
    			return new FPPoint(rect.origin.x, rect.origin.y);
    		case FPDragHandleBottomLeft:
    			return new FPPoint(rect.origin.x, rect.origin.y + rect.size.height);
    		case FPDragHandleTopRight:
    			return new FPPoint(rect.origin.x + rect.size.width, rect.origin.y);
    		case FPDragHandleBottomRight:
    			return new FPPoint(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height);

    		case FPDragHandleMiddleLeft:
    			return new FPPoint(rect.origin.x, rect.origin.y + rect.size.height / 2.0);
    		case FPDragHandleMiddleTop:
    			return new FPPoint(rect.origin.x + rect.size.width / 2.0, rect.origin.y);
    		case FPDragHandleMiddleRight:
    			return new FPPoint(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height / 2.0);
    		case FPDragHandleMiddleBottom:
    			return new FPPoint(rect.origin.x + rect.size.width / 2.0, rect.origin.y + rect.size.height);

    		default:
    			return new FPPoint(0.0, 0.0);
    	}
    }

    this.drawHandles = function(levelObject)
    {
        for (var handle = FPDragHandleTopLeft; handle <= FPDragHandleMiddleBottom; handle++)
        {
    		/*if (!widthHandles && [self isWidthHandle:handle])
    			continue;

    		if (!heightHandles && [self isHeightHandle:handle])
    			continue;		*/

    		if (handle == this.currentHandle)
    		    this.context.fillStyle = "rgba(255, 0, 0, 0.8)";
    		else
    		    this.context.fillStyle = "rgba(255, 255, 128, 0.8)";

            var levelObjectRect = levelObject.rect();
    		var handlePoint = this.pointFromHandle(handle, levelObjectRect);
    		this.context.fillRect(handlePoint.x - 3.0, handlePoint.y - 3.0, 6.0, 6.0);
    	}
    }

    this.resizeDraggedObject = function(widthSegments, heightSegments)
    {
        switch (this.currentHandle)
        {
		case FPDragHandleTopLeft:
			this.resizeDraggedObjectTop(heightSegments);
			this.resizeDraggedObjectLeft(widthSegments);
			break;
		case FPDragHandleTopRight:
            this.resizeDraggedObjectTop(heightSegments);
			this.resizeDraggedObjectRight(widthSegments);
			break;
		case FPDragHandleBottomLeft:
			this.resizeDraggedObjectBottom(heightSegments);
			this.resizeDraggedObjectLeft(widthSegments);
			break;
		case FPDragHandleBottomRight:
			this.resizeDraggedObjectBottom(heightSegments);
			this.resizeDraggedObjectRight(widthSegments);
			break;
		case FPDragHandleMiddleTop:
			this.resizeDraggedObjectTop(heightSegments);
			break;
		case FPDragHandleMiddleBottom:
			this.resizeDraggedObjectBottom(heightSegments);
			break;
		case FPDragHandleMiddleLeft:
			this.resizeDraggedObjectLeft(widthSegments);
			break;
		case FPDragHandleMiddleRight:
		    this.resizeDraggedObjectRight(widthSegments);
			break;
		}
    }

    this.resizeDraggedObjectLeft = function(widthSegments)
    {
    	if (this.draggedObject.widthSegments - widthSegments < 1)
    		widthSegments = 0;

        this.draggedObject.move(widthSegments * 32.0, 0.0);
    	oldCursor.x += widthSegments * 32.0;
    	this.draggedObject.widthSegments -= widthSegments;
    }

    this.resizeDraggedObjectRight = function(widthSegments)
    {
    	if (this.draggedObject.widthSegments + widthSegments < 1)
    		widthSegments = 0;

    	oldCursor.x += widthSegments * 32.0;
    	this.draggedObject.widthSegments += widthSegments;
    }

    this.resizeDraggedObjectTop = function(heightSegments)
    {
    	if (this.draggedObject.heightSegments - heightSegments < 1)
    		heightSegments = 0;

        this.draggedObject.move(0.0, heightSegments * 32.0);
    	oldCursor.y += heightSegments * 32.0;
    	this.draggedObject.heightSegments -= heightSegments;
    }

    this.resizeDraggedObjectBottom = function(heightSegments)
    {
    	if (this.draggedObject.heightSegments + heightSegments < 1)
    		heightSegments = 0;

    	oldCursor.y += heightSegments * 32.0;
    	this.draggedObject.heightSegments += heightSegments;
    }
}<commit_msg>Fixed delete<commit_after>var oldCursor = null;
var isMiddleMouse = false;
var isDown = false;

const FPDragHandleNone = 0;
const FPDragHandleTopLeft = 1;
const FPDragHandleBottomLeft = 2;
const FPDragHandleTopRight = 3;
const FPDragHandleBottomRight = 4;
const FPDragHandleMiddleLeft = 5;
const FPDragHandleMiddleTop = 6;
const FPDragHandleMiddleRight = 7;
const FPDragHandleMiddleBottom = 8;

function levelMouseDown(e)
{
    isDown = true;

    var cursor = getCursorPosition(levelCanvas.canvas, e);

    if (e.button == 1)
        isMiddleMouse = true;
    else
        isMiddleMouse = false;

    if (isMiddleMouse)
    {
        alignCursorOnGrid(cursor);
    }
    else if (paletteCanvas.activeFactory != null)
    {
        alignCursorOnGrid(cursor);

        var beforeLength = levelCanvas.levelObjects.length;
        paletteCanvas.activeFactory.create(levelCanvas.levelObjects, cursor.x, cursor.y);
        levelCanvas.draggedObject = levelCanvas.levelObjects[beforeLength];
        levelCanvas.draw();
    }
    else if (levelCanvas.currentHandle == FPDragHandleNone)
    {
        levelCanvas.draggedObject = levelCanvas.objectUnderMouse(cursor.x, cursor.y);
        if (levelCanvas.draggedObject == null)
        {
            levelCanvas.selectionStart = new FPPoint(cursor.x, cursor.y);
            levelCanvas.selectionEnd = new FPPoint(cursor.x, cursor.y);
        }
        else if (!levelCanvas.draggedObject.selected)
        {
            levelCanvas.deselectAll();
        }
    }

    oldCursor = new FPPoint(cursor.x, cursor.y);
}

function alignCursorOnGrid(cursor)
{
    cursor.x -= 16.0;
    cursor.y -= 16.0;
    cursor.x = Math.round(cursor.x / 32.0) * 32.0;
    cursor.y = Math.round(cursor.y / 32.0) * 32.0;
}

function levelMouseMove(e)
{
    var cursor = getCursorPosition(levelCanvas.canvas, e);

    if (!isDown)
    {
        if (levelCanvas.draggedObject != null)
        {
            var draggedObjectRect = levelCanvas.draggedObject.rect();
            var handleRect = new FPRect(0.0, 0.0, 14.0, 14.0);

            levelCanvas.currentHandle = FPDragHandleNone;

            for (var handle = FPDragHandleTopLeft; handle <= FPDragHandleMiddleBottom; handle++)
            {
    			var handlePoint = levelCanvas.pointFromHandle(handle, draggedObjectRect);

    			handleRect.origin.x = handlePoint.x - handleRect.size.width / 2.0;
    			handleRect.origin.y = handlePoint.y - handleRect.size.height / 2.0;

    			if (handleRect.containsPoint(cursor.x, cursor.y))
    			{
    				levelCanvas.currentHandle = handle;
    				break;
    			}
    		}

    		levelCanvas.draw();
	    }

        return;
    }

    if (isMiddleMouse)
    {
       alignCursorOnGrid(cursor);
       levelCanvas.moveAll(cursor.x - oldCursor.x, cursor.y - oldCursor.y);
       oldCursor.x = cursor.x;
       oldCursor.y = cursor.y;
       levelCanvas.draw();
    }
    else if (levelCanvas.selectionEnd != null)
    {
        levelCanvas.selectionEnd = new FPPoint(cursor.x, cursor.y);
        levelCanvas.draw();
    }
    else if (levelCanvas.draggedObject != null)
    {
        alignCursorOnGrid(cursor);

        var widthSegments = Math.floor((cursor.x - oldCursor.x + 16.0) / 32.0);
        var heightSegments = Math.floor((cursor.y - oldCursor.y + 16.0) / 32.0);

        if (paletteCanvas.activeFactory != null)
        {
        	var draggedObjectLocation = new FPPoint(oldCursor.x, oldCursor.y);
        	if (widthSegments < 0)
        		draggedObjectLocation.x += widthSegments * 32.0;
        	if (heightSegments < 0)
        		draggedObjectLocation.y += heightSegments * 32.0;

        	widthSegments = Math.max(Math.abs(widthSegments), 1);
        	heightSegments = Math.max(Math.abs(heightSegments), 1);

            levelCanvas.draggedObject.x = draggedObjectLocation.x;
            levelCanvas.draggedObject.y = draggedObjectLocation.y;

            levelCanvas.draggedObject.widthSegments = widthSegments;
            levelCanvas.draggedObject.heightSegments = heightSegments;
        }
        else if (levelCanvas.currentHandle != FPDragHandleNone)
        {
            levelCanvas.resizeDraggedObject(widthSegments, heightSegments);
        }
        else
        {
            widthSegments *= 32.0;
            heightSegments *= 32.0;

            levelCanvas.moveSelected(widthSegments, heightSegments);

            oldCursor.x += widthSegments;
            oldCursor.y += heightSegments;
        }

        levelCanvas.draw();
    }
}

function levelMouseUp(e)
{
    isDown = false;

    if (levelCanvas.selectionStart != null)
    {
        levelCanvas.draggedObject = null;

        levelCanvas.selectObjects();

        levelCanvas.selectionStart = null;
        levelCanvas.selectionEnd = null;
    }

    paletteCanvas.activeFactory = null;
    oldCursor = null;

    levelCanvas.draw();
    paletteCanvas.draw();
}

function FPLevelCanvas(canvasName)
{
    this.canvas = document.getElementById(canvasName);
    this.context = this.canvas.getContext('2d');

    this.canvas.width = document.width - 110;
    this.canvas.height = document.height - 4;

    this.levelObjects = new Array();

    this.draggedObject = null;

    this.selectionStart = null;
    this.selectionEnd = null;

    this.canvas.addEventListener('mousedown', levelMouseDown, false);
    this.canvas.addEventListener('mousemove', levelMouseMove, false);
    this.canvas.addEventListener('mouseup', levelMouseUp, false);

    this.currentHandle = FPDragHandleNone;

    this.drawGrid = function()
    {
        this.context.strokeStyle = "rgba(255,255,255, 0.2)";

        var rect = new FPRect(0, 0, this.canvas.width, this.canvas.height);

        for (var y = rect.origin.y; y < rect.size.height; y += 32)
    	{
    	    this.context.beginPath();
    	    this.context.moveTo(rect.origin.x, y);
    	    this.context.lineTo(rect.size.width, y);
    	    this.context.stroke();
    	}

    	for (var x = rect.origin.x; x < rect.size.width; x += 32)
    	{
    	    this.context.beginPath();
    		this.context.moveTo(x, rect.origin.y);
    		this.context.lineTo(x, rect.size.height);
    		this.context.stroke();
    	}
    }

    this.draw = function()
    {
        this.context.fillStyle = "rgb(55,60,89)";
        this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);

        this.drawGrid();

        for (i in this.levelObjects)
        {
            var levelObject = this.levelObjects[i];
            levelObject.draw(this.context);

            if (levelObject.selected || levelObject == this.draggedObject)
            {
                var levelObjectRect = levelObject.rect();
                this.context.strokeStyle = "rgba(255,255,255, 1.0)";
                this.context.strokeRect(levelObjectRect.origin.x, levelObjectRect.origin.y, levelObjectRect.size.width, levelObjectRect.size.height);
            }

             if (levelObject == this.draggedObject)
                this.drawHandles(levelObject);
        }

        if (this.selectionStart != null)
        {
            this.context.fillStyle = "rgba(255,255,255, 0.15)";
            this.context.strokeStyle = "rgba(255,255,255, 1.0)";

            var selectionRect = FPRectFromPoints(this.selectionStart, this.selectionEnd);

            this.context.fillRect(selectionRect.origin.x, selectionRect.origin.y, selectionRect.size.width, selectionRect.size.height);
            this.context.strokeRect(selectionRect.origin.x, selectionRect.origin.y, selectionRect.size.width, selectionRect.size.height);
        }
    }

    this.objectUnderMouse = function(x, y)
    {
        for (i in this.levelObjects)
        {
            var levelObject = this.levelObjects[i];

            if (levelObject.rect().containsPoint(x, y))
                return levelObject;
        }

        return null;
    }

    this.selectObjects = function()
    {
        var selectionRect = FPRectFromPoints(this.selectionStart, this.selectionEnd);

        for (i in this.levelObjects)
        {
            var levelObject = this.levelObjects[i];

            if (FPRectIntersectsRect(selectionRect, levelObject.rect()))
                levelObject.selected = true;
            else
                levelObject.selected = false;
        }
    }

    this.deselectAll = function()
    {
        for (i in this.levelObjects)
        {
            var levelObject = this.levelObjects[i];
            levelObject.selected = false;
        }
    }

    this.moveSelected = function(offsetX, offsetY)
    {
        for (i in this.levelObjects)
        {
            var levelObject = this.levelObjects[i];
            if (levelObject.selected || levelObject == this.draggedObject)
                levelObject.move(offsetX, offsetY);
        }
    }

    this.moveAll = function(offsetX, offsetY)
    {
        for (i in this.levelObjects)
        {
            var levelObject = this.levelObjects[i];
            levelObject.move(offsetX, offsetY);
        }
    }

    this.deleteSelected = function()
    {
        this.levelObjects = this.levelObjects.filter(function (obj) { return !obj.selected && obj != this.draggedObject; });
        this.draw();
    }

    this.pointFromHandle = function(handle, rect)
    {
        switch (handle)
        {
    		case FPDragHandleTopLeft:
    			return new FPPoint(rect.origin.x, rect.origin.y);
    		case FPDragHandleBottomLeft:
    			return new FPPoint(rect.origin.x, rect.origin.y + rect.size.height);
    		case FPDragHandleTopRight:
    			return new FPPoint(rect.origin.x + rect.size.width, rect.origin.y);
    		case FPDragHandleBottomRight:
    			return new FPPoint(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height);

    		case FPDragHandleMiddleLeft:
    			return new FPPoint(rect.origin.x, rect.origin.y + rect.size.height / 2.0);
    		case FPDragHandleMiddleTop:
    			return new FPPoint(rect.origin.x + rect.size.width / 2.0, rect.origin.y);
    		case FPDragHandleMiddleRight:
    			return new FPPoint(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height / 2.0);
    		case FPDragHandleMiddleBottom:
    			return new FPPoint(rect.origin.x + rect.size.width / 2.0, rect.origin.y + rect.size.height);

    		default:
    			return new FPPoint(0.0, 0.0);
    	}
    }

    this.drawHandles = function(levelObject)
    {
        for (var handle = FPDragHandleTopLeft; handle <= FPDragHandleMiddleBottom; handle++)
        {
    		/*if (!widthHandles && [self isWidthHandle:handle])
    			continue;

    		if (!heightHandles && [self isHeightHandle:handle])
    			continue;		*/

    		if (handle == this.currentHandle)
    		    this.context.fillStyle = "rgba(255, 0, 0, 0.8)";
    		else
    		    this.context.fillStyle = "rgba(255, 255, 128, 0.8)";

            var levelObjectRect = levelObject.rect();
    		var handlePoint = this.pointFromHandle(handle, levelObjectRect);
    		this.context.fillRect(handlePoint.x - 3.0, handlePoint.y - 3.0, 6.0, 6.0);
    	}
    }

    this.resizeDraggedObject = function(widthSegments, heightSegments)
    {
        switch (this.currentHandle)
        {
		case FPDragHandleTopLeft:
			this.resizeDraggedObjectTop(heightSegments);
			this.resizeDraggedObjectLeft(widthSegments);
			break;
		case FPDragHandleTopRight:
            this.resizeDraggedObjectTop(heightSegments);
			this.resizeDraggedObjectRight(widthSegments);
			break;
		case FPDragHandleBottomLeft:
			this.resizeDraggedObjectBottom(heightSegments);
			this.resizeDraggedObjectLeft(widthSegments);
			break;
		case FPDragHandleBottomRight:
			this.resizeDraggedObjectBottom(heightSegments);
			this.resizeDraggedObjectRight(widthSegments);
			break;
		case FPDragHandleMiddleTop:
			this.resizeDraggedObjectTop(heightSegments);
			break;
		case FPDragHandleMiddleBottom:
			this.resizeDraggedObjectBottom(heightSegments);
			break;
		case FPDragHandleMiddleLeft:
			this.resizeDraggedObjectLeft(widthSegments);
			break;
		case FPDragHandleMiddleRight:
		    this.resizeDraggedObjectRight(widthSegments);
			break;
		}
    }

    this.resizeDraggedObjectLeft = function(widthSegments)
    {
    	if (this.draggedObject.widthSegments - widthSegments < 1)
    		widthSegments = 0;

        this.draggedObject.move(widthSegments * 32.0, 0.0);
    	oldCursor.x += widthSegments * 32.0;
    	this.draggedObject.widthSegments -= widthSegments;
    }

    this.resizeDraggedObjectRight = function(widthSegments)
    {
    	if (this.draggedObject.widthSegments + widthSegments < 1)
    		widthSegments = 0;

    	oldCursor.x += widthSegments * 32.0;
    	this.draggedObject.widthSegments += widthSegments;
    }

    this.resizeDraggedObjectTop = function(heightSegments)
    {
    	if (this.draggedObject.heightSegments - heightSegments < 1)
    		heightSegments = 0;

        this.draggedObject.move(0.0, heightSegments * 32.0);
    	oldCursor.y += heightSegments * 32.0;
    	this.draggedObject.heightSegments -= heightSegments;
    }

    this.resizeDraggedObjectBottom = function(heightSegments)
    {
    	if (this.draggedObject.heightSegments + heightSegments < 1)
    		heightSegments = 0;

    	oldCursor.y += heightSegments * 32.0;
    	this.draggedObject.heightSegments += heightSegments;
    }
}<|endoftext|>


<commit_before>var url = "http://81.204.121.229/IntelliCloudService/IntelliCloudService.svc/";

/*
* This function is called when the page is loaded.
*
* The question & answer is loaded into the right fields
* The accept & decline methods are bound to the buttons
*/
$(document).ready(function()
{
	loadQuestionWithId($.urlParam('QuestionId'));
});

/*
* This function extracts the paramaters from the url
*/
$.urlParam = function(name)
{
	var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
	return results[1] || 0;
}

/*
* This function loads data from the backend and fils the answerfield & questionfield
*/
function loadQuestionWithId(id)
{
	var request = $.get(url + "GetQuestionById/" + id, null, null, "json");

	request.done(function (response)
	{
		$("#answerfield").html(response.Answer.Content);
		$("#questionfield").html(response.Content);

		$("#btnAccept").click(function()
		{
			accept(response.Answer.Id, id);
		});

		$("#btnDecline").click(function()
		{
			decline(response.Answer.Id, id);
		});
	});
	request.fail(function (response)
	{
		alert("Error loading answer: " + response);
	});
}

/*
* This function accepts an answer and sends the feedback to the backend
*/
function accept(answerId, questionId)
{
	var request = $.post(url + "AcceptAnswer", {"feedback" : feedback.value , "answerId" : answerId, "questionId" : questionId}, null, "json");

	request.done(function (response)
	{
		var message = "accepted with feedback: " + feedback.value;
		alert(message);
	});
	request.fail(function (response)
	{
		alert("Error accepting answer");
	});
}

/*
* This function declines an answer and sends the feedback to the backend
*/
function decline(answerId, questionId)
{
	var request = $.post(url + "DeclineAnswer", {"feedback" : feedback.value , "answerId" : answerId, "questionId" : questionId}, null, "json");

	request.done(function (response)
	{
		var message = "declined with feedback: " + feedback.value;
		alert(message);
	});
	request.fail(function (response)
	{
		alert("Error declining answer");
	});
}<commit_msg>Added the token<commit_after>var url = "http://81.204.121.229/IntelliCloudService/IntelliCloudService.svc/";

/*
* This function is called when the page is loaded.
*
* The loadQestion method is invoked
*/
$(document).ready(function()
{
	loadQuestionWithId($.urlParam('QuestionId'), $.urlParam('Token'));
});

/*
* This function extracts the paramaters from the url
*/
$.urlParam = function(name)
{
	var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
	return results[1] || 0;
}

/*
* This function loads data from the backend and fils the answerfield & questionfield
* The accept & decline methods are bound to the buttons
*/
function loadQuestionWithId(questionid, token)
{
	var request = $.get(url + "GetQuestionById/" + questionid, null, null, "json");

	request.done(function (response)
	{
		$("#answerfield").html(response.Answer.Content);
		$("#questionfield").html(response.Content);

		$("#btnAccept").click(function()
		{
			accept(response.Answer.Id, questionid, token);
		});

		$("#btnDecline").click(function()
		{
			decline(response.Answer.Id, questionid, token);
		});
	});
	request.fail(function (response)
	{
		alert("Error loading answer: " + response);
	});
}

/*
* This function accepts an answer and sends the feedback to the backend
*/
function accept(answerId, questionId, token)
{
	var request = $.post(url + "AcceptAnswer", {"feedback" : feedback.value , "answerId" : answerId, "questionId" : questionId, "token" : token}, null, "json");

	request.done(function (response)
	{
		var message = "accepted with feedback: " + feedback.value;
		alert(message);
	});
	request.fail(function (response)
	{
		alert("Error accepting answer");
	});
}

/*
* This function declines an answer and sends the feedback to the backend
*/
function decline(answerId, questionId, token)
{
	var request = $.post(url + "DeclineAnswer", {"feedback" : feedback.value , "answerId" : answerId, "questionId" : questionId, "token" : token}, null, "json");

	request.done(function (response)
	{
		var message = "declined with feedback: " + feedback.value;
		alert(message);
	});
	request.fail(function (response)
	{
		alert("Error declining answer");
	});
}<|endoftext|>


<commit_before>(function (exports) {

	/**
	 * Expose constructor
	 */
	exports.GameStorage = GameStorage;

	/**
	 * GameStorage interface
	 *
	 * @api public
	 */

	function GameStorage (game, options) {
	  this.game = game;
	  this.options = options;
	  this.clients = {};
	};

	/**
	 * Write data into the memory of a client
	 * It overwrites the same key
	 *
	 * @param {String} client
	 * @data {Object}
	 * @api public
	 */

	GameStorage.prototype.add = function (client, data) {
	  if (!this.clients[client]) {
	    this.clients[client] = {};
	  }
	  var state = this.game.gameState.toString();
	  if (!this.clients[client][state]) {
		  this.clients[client][state] = {};
	  }

	  for (var i in data) {
		  if (data.hasOwnProperty(i)) {
			  this.clients[client][state][i] = data[i];
			  console.log('Added ' +  i + ' ' + data[i]);
		  }
	  }

	  if (this.dump(reverse))

	  return true;
	};

	// Reverse the memory: instead of the history of a player for all rounds,
	// we get the history of a round of all players
	GameStorage.prototype.reverse = function () {
		var reverse = {};

		for( var c in this.clients) {
			if (this.clients.hasOwnProperty(c)) {
				for (var s in this.clients[c]) {
					if (this.clients[c].hasOwnProperty(s)) {

						if (!reverse[s]) {
							reverse[s] = {};
						}

						if (!reverse[s][c]) {
							reverse[s][c] = {};
						}

						var data = this.clients[c][s];

						for (var i in data) {
						  if (data.hasOwnProperty(i)) {
							  reverse[s][c][i] = data[i];
							  console.log('Reversed ' +  i + ' ' + data[i]);
						  }
						}
					}
			    }
			}
		}

		return reverse;
	};

	GameStorage.prototype.dump = function (reverse) {

		return (reverse) ? this.reverse() : this.clients;
	};

	GameStorage.prototype.getValues = function (reverse) {

		var values = [];

		var dump = this.dump(reverse);
		for (var i in dump) {
			if (dump.hasOwnProperty(i)) {
				var line = this.getLine(i, dump);
				for (var j in line) {
					values.push(line[j]);
				}
			}
		}
		return values;
	};

	GameStorage.prototype.getLine = function (id, storage) {
		var storage = storage || this.clients;
		if (!storage[id]) return;

		var lines = [];

		for (var i in storage[id]) {
			if (storage[id].hasOwnProperty(i)) {
				var line = [];
				line.push(id);
				line.push(i);

				for (var j in storage[id][i]) {
					if (storage[id][i].hasOwnProperty(j)) {
						line.push(storage[id][i][j]);
					}
				}

				lines.push(line);
			}
		}

		return lines;
	};
})(
	'undefined' != typeof node ? node : module.exports
);<commit_msg>Changes to widgets<commit_after>(function (exports) {

	/**
	 * Expose constructor
	 */
	exports.GameStorage = GameStorage;

	/**
	 * GameStorage interface
	 *
	 * @api public
	 */

	function GameStorage (game, options) {
	  this.game = game;
	  this.options = options;
	  this.clients = {};
	};

	/**
	 * Write data into the memory of a client
	 * It overwrites the same key
	 *
	 * @param {String} client
	 * @data {Object}
	 * @api public
	 */

	GameStorage.prototype.add = function (client, data) {
	  if (!this.clients[client]) {
	    this.clients[client] = {};
	  }
	  var state = this.game.gameState.toString();
	  if (!this.clients[client][state]) {
		  this.clients[client][state] = {};
	  }

	  for (var i in data) {
		  if (data.hasOwnProperty(i)) {
			  this.clients[client][state][i] = data[i];
			  console.log('Added ' +  i + ' ' + data[i]);
		  }
	  }

	  return true;
	};

	// Reverse the memory: instead of the history of a player for all rounds,
	// we get the history of a round of all players
	GameStorage.prototype.reverse = function () {
		var reverse = {};

		for( var c in this.clients) {
			if (this.clients.hasOwnProperty(c)) {
				for (var s in this.clients[c]) {
					if (this.clients[c].hasOwnProperty(s)) {

						if (!reverse[s]) {
							reverse[s] = {};
						}

						if (!reverse[s][c]) {
							reverse[s][c] = {};
						}

						var data = this.clients[c][s];

						for (var i in data) {
						  if (data.hasOwnProperty(i)) {
							  reverse[s][c][i] = data[i];
							  console.log('Reversed ' +  i + ' ' + data[i]);
						  }
						}
					}
			    }
			}
		}

		return reverse;
	};

	GameStorage.prototype.dump = function (reverse) {

		return (reverse) ? this.reverse() : this.clients;
	};

	GameStorage.prototype.getValues = function (reverse) {

		var values = [];

		var dump = this.dump(reverse);
		for (var i in dump) {
			if (dump.hasOwnProperty(i)) {
				var line = this.getLine(i, dump);
				for (var j in line) {
					values.push(line[j]);
				}
			}
		}
		return values;
	};

	GameStorage.prototype.getLine = function (id, storage) {
		var storage = storage || this.clients;
		if (!storage[id]) return;

		var lines = [];

		for (var i in storage[id]) {
			if (storage[id].hasOwnProperty(i)) {
				var line = [];
				line.push(id);
				line.push(i);

				for (var j in storage[id][i]) {
					if (storage[id][i].hasOwnProperty(j)) {
						line.push(storage[id][i][j]);
					}
				}

				lines.push(line);
			}
		}

		return lines;
	};
})(
	'undefined' != typeof node ? node : module.exports
);<|endoftext|>


<commit_before>var syncManager = require('lsyncmanager');

module.exports = function(locker) {
    // get all the information about synclets
    locker.get('/synclets', function(req, res) {
        res.writeHead(200, {
            'Content-Type': 'text/javascript',
            "Access-Control-Allow-Origin" : "*"
        });
        var synclets = JSON.parse(JSON.stringify(syncManager.synclets()));
        for(var s in synclets.installed) delete synclets.installed[s].config;
        res.end(JSON.stringify(synclets));
    });

    // given a bunch of json describing a synclet, make a home for it on disk and add it to our map
    locker.post('/synclets/install', function(req, res) {
        if (!req.body.hasOwnProperty("srcdir")) {
            res.writeHead(400);
            res.end("{}")
            return;
        }
        var metaData = syncManager.install(req.body);
        if (!metaData) {
            res.writeHead(404);
            res.end("{}");
            return;
        }
        res.writeHead(200, {
            'Content-Type': 'application/json'
        });
        res.end(JSON.stringify(metaData));
    });

    locker.get('/synclets/:id/run', function(req, res) {
        syncManager.syncNow(req.params.id, req.query.id, function() {
            res.send(true);
        });
    });

    require('synclet/dataaccess')(locker);
};
<commit_msg>Fixes #340<commit_after>var syncManager = require('lsyncmanager');

module.exports = function(locker) {
    // get all the information about synclets
    locker.get('/synclets', function(req, res) {
        res.writeHead(200, {
            'Content-Type': 'text/javascript',
            "Access-Control-Allow-Origin" : "*"
        });
        var synclets = JSON.parse(JSON.stringify(syncManager.synclets()));
        for(var s in synclets.installed) {
            delete synclets.installed[s].config;
            delete synclets.installed[s].auth;
        }
        res.end(JSON.stringify(synclets));
    });

    // given a bunch of json describing a synclet, make a home for it on disk and add it to our map
    locker.post('/synclets/install', function(req, res) {
        if (!req.body.hasOwnProperty("srcdir")) {
            res.writeHead(400);
            res.end("{}")
            return;
        }
        var metaData = syncManager.install(req.body);
        if (!metaData) {
            res.writeHead(404);
            res.end("{}");
            return;
        }
        res.writeHead(200, {
            'Content-Type': 'application/json'
        });
        res.end(JSON.stringify(metaData));
    });

    locker.get('/synclets/:id/run', function(req, res) {
        syncManager.syncNow(req.params.id, req.query.id, function() {
            res.send(true);
        });
    });

    require('synclet/dataaccess')(locker);
};
<|endoftext|>


<commit_before>function URLParser(){this.plugins={}}URLParser.prototype.parse=function(a){var b=a.match(/(?:https?:\/\/)?(?:[^\.]+\.)?(\w+)\./i),d=b?b[1]:void 0;if(b&&d&&this.plugins[d]&&(a=this.plugins[d].parse.call(this,a)))return a.provider=this.plugins[d].provider,a};URLParser.prototype.bind=function(a){this.plugins[a.provider]=a;if(a.alternatives){var b;for(b=0;b<a.alternatives.length;b+=1)this.plugins[a.alternatives[b]]=a}};
URLParser.prototype.create=function(a){var b=a.videoInfo;a.format=a.format||"short";if(this.plugins[b.provider].create)return this.plugins[b.provider].create.call(this,a)};window.urlParser=new URLParser;function getTime(a){var b=0,d={s:1,m:60,h:3600,d:86400,w:604800};if(!a.match(/^(\d+[smhdw]?)+$/))return 0;a=a.replace(/([smhdw])/g," $1 ").trim();a=a.split(" ");for(var c=0;c<a.length;c+=2)console.log(a[c]),console.log(a[c+1]),b+=parseInt(a[c],10)*d[a[c+1]||"s"];return b}
"function"!==typeof String.prototype.format&&(String.prototype.format=function(){var a=this,b,d;for(b=0;b<arguments.length;b+=1)d=new RegExp("\\{"+b+"\\}","gm"),a=a.replace(d,arguments[b]);return a});
urlParser.bind({provider:"dailymotion",alternatives:["dai"],parse:function(a){var b,d,c={};d=(b=a.match(/(?:\/video|ly)\/([A-Za-z0-9]+)/i))?b[1]:void 0;a=(b=a.match(/[#\?&]start=([A-Za-z0-9]+)/i))?getTime(b[1]):void 0;if(d)return c.mediaType="video",c.videoId=d,a&&(c.startTime=a),c},create:function(a){var b=a.videoInfo;return b.startTime?"https://www.dailymotion.com/video/{0}?start={1}".format(b.videoId,b.startTime):"short"===a.format?"https://dai.ly/{0}".format(b.videoId):"https://www.dailymotion.com/video/{0}".format(b.videoId)}});
urlParser.bind({provider:"livestream",parse:function(a){return(a=(a=a.match(/livestream\.com\/(\w+)/i))?a[1]:void 0)?{mediaType:"stream",channel:a}:void 0}});
urlParser.bind({provider:"twitch",parse:function(a){var b,d,c,f,e={};c=(b=a.match(/twitch\.tv\/(\w+)(?:\/(.)\/(\d+))?/i))?b[1]:void 0;f=b?b[2]:void 0;d=b?b[3]:void 0;if(c=(b=a.match(/(?:\?channel|\&utm_content)=(\w+)/i))?b[1]:c)return d?(e.mediaType="video",e.videoId=d,e.videoIdPrefix=f):e.mediaType="stream",e.channel=c,e},create:function(a){a=op.videoInfo;return"stream"===a.mediaType?"https://twitch.tv/{0}".format(a.channel):"https://twitch.tv/{0}/{1}/{2}".format(a.channel,a.videoIdPrefix,a.videoId)}});
urlParser.bind({provider:"vimeo",alternatives:["vimeopro"],parse:function(a){return(a=(a=a.match(/(?:\/(?:channels\/[\w]+|(?:album\/\d+\/)?videos?))?\/(\d+)/i))?a[1]:void 0)?{mediaType:"video",videoId:a}:void 0},create:function(a){return"https://vimeo.com/{0}".format(op.videoInfo.videoId)}});
urlParser.bind({provider:"youtube",alternatives:["youtu"],parse:function(a){var b,d,c,f,e={};d=(b=a.match(/(?:(?:v|be|videos)\/|v=)([\w\-]{11})/i))?b[1]:void 0;c=(b=a.match(/list=([\w\-]+)/i))?b[1]:void 0;f=(b=a.match(/index=(\d+)/i))?Number(b[1]):void 0;a=(b=a.match(/[#\?&](?:star)?t=([A-Za-z0-9]+)/i))?getTime(b[1]):void 0;if(d)e.mediaType="video",e.videoId=d,c&&(e.playlistId=c,f&&(e.playlistIndex=f)),a&&(e.startTime=a);else if(c)e.mediaType="playlist",e.playlistId=c;else return;return e},create:function(a){var b=
  a.videoInfo;if("playlist"===b.mediaType)return"https://www.youtube.com/playlist?feature=share&list={0}".format(b.playlistId);b.playlistId?(a="https://www.youtube.com/watch?v={0}&list={1}".format(b.videoId,b.playlistId),b.playlistIndex&&(a+="&index={0}".format(b.playlistIndex))):a="short"===a.format?"https://youtu.be/{0}".format(b.videoId):"https://www.youtube.com/watch?v={0}".format(b.videoId);b.startTime&&(a+="#t={0}".format(b.startTime));return a}});
<commit_msg>Update urlParser.min.js<commit_after>function URLParser(){this.plugins={}}URLParser.prototype.parse=function(a){var b=a.match(/(?:https?:\/\/)?(?:[^\.]+\.)?(\w+)\./i),c=b?b[1]:void 0;if(b&&c&&this.plugins[c]&&(a=this.plugins[c].parse.call(this,a)))return a.provider=this.plugins[c].provider,a};URLParser.prototype.bind=function(a){this.plugins[a.provider]=a;if(a.alternatives){var b;for(b=0;b<a.alternatives.length;b+=1)this.plugins[a.alternatives[b]]=a}};
URLParser.prototype.create=function(a){var b=a.videoInfo;a.format=a.format||"short";if(this.plugins[b.provider].create)return this.plugins[b.provider].create.call(this,a)};var urlParser=new URLParser;function getTime(a){var b=0,c={s:1,m:60,h:3600,d:86400,w:604800};if(!a.match(/^(\d+[smhdw]?)+$/))return 0;a=a.replace(/([smhdw])/g," $1 ").trim();a=a.split(" ");for(var d=0;d<a.length;d+=2)b+=parseInt(a[d],10)*c[a[d+1]||"s"];return b}
"function"!==typeof String.prototype.format&&(String.prototype.format=function(){var a=this,b,c;for(b=0;b<arguments.length;b+=1)c=new RegExp("\\{"+b+"\\}","gm"),a=a.replace(c,arguments[b]);return a});
urlParser.bind({provider:"dailymotion",alternatives:["dai"],parse:function(a){var b,c,d={};c=(b=a.match(/(?:\/video|ly)\/([A-Za-z0-9]+)/i))?b[1]:void 0;a=(b=a.match(/[#\?&]start=([A-Za-z0-9]+)/i))?getTime(b[1]):void 0;if(c)return d.mediaType="video",d.videoId=c,a&&(d.startTime=a),d},create:function(a){var b=a.videoInfo;return b.startTime?"https://www.dailymotion.com/video/{0}?start={1}".format(b.videoId,b.startTime):"short"===a.format?"https://dai.ly/{0}".format(b.videoId):"https://www.dailymotion.com/video/{0}".format(b.videoId)}});
urlParser.bind({provider:"livestream",parse:function(a){return(a=(a=a.match(/livestream\.com\/(\w+)/i))?a[1]:void 0)?{mediaType:"stream",channel:a}:void 0}});
urlParser.bind({provider:"twitch",parse:function(a){var b,c,d,f,e={};d=(b=a.match(/twitch\.tv\/(\w+)(?:\/(.)\/(\d+))?/i))?b[1]:void 0;f=b?b[2]:void 0;c=b?b[3]:void 0;if(d=(b=a.match(/(?:\?channel|\&utm_content)=(\w+)/i))?b[1]:d)return c?(e.mediaType="video",e.videoId=c,e.videoIdPrefix=f):e.mediaType="stream",e.channel=d,e},create:function(a){a=op.videoInfo;return"stream"===a.mediaType?"https://twitch.tv/{0}".format(a.channel):"https://twitch.tv/{0}/{1}/{2}".format(a.channel,a.videoIdPrefix,a.videoId)}});
urlParser.bind({provider:"vimeo",alternatives:["vimeopro"],parse:function(a){return(a=(a=a.match(/(?:\/(?:channels\/[\w]+|(?:album\/\d+\/)?videos?))?\/(\d+)/i))?a[1]:void 0)?{mediaType:"video",videoId:a}:void 0},create:function(a){return"https://vimeo.com/{0}".format(op.videoInfo.videoId)}});
urlParser.bind({provider:"youtube",alternatives:["youtu"],parse:function(a){var b,c,d,f,e={};c=(b=a.match(/(?:(?:v|be|videos)\/|v=)([\w\-]{11})/i))?b[1]:void 0;d=(b=a.match(/list=([\w\-]+)/i))?b[1]:void 0;f=(b=a.match(/index=(\d+)/i))?Number(b[1]):void 0;a=(b=a.match(/[#\?&](?:star)?t=([A-Za-z0-9]+)/i))?getTime(b[1]):void 0;if(c)e.mediaType="video",e.videoId=c,d&&(e.playlistId=d,f&&(e.playlistIndex=f)),a&&(e.startTime=a);else if(d)e.mediaType="playlist",e.playlistId=d;else return;return e},create:function(a){var b=
a.videoInfo;if("playlist"===b.mediaType)return"https://www.youtube.com/playlist?feature=share&list={0}".format(b.playlistId);b.playlistId?(a="https://www.youtube.com/watch?v={0}&list={1}".format(b.videoId,b.playlistId),b.playlistIndex&&(a+="&index={0}".format(b.playlistIndex))):a="short"===a.format?"https://youtu.be/{0}".format(b.videoId):"https://www.youtube.com/watch?v={0}".format(b.videoId);b.startTime&&(a+="#t={0}".format(b.startTime));return a}});
<|endoftext|>


<commit_before>/* global Dropzone*/
import Ember from 'ember';

export default Ember.Component.extend({
  classNames: ['dropzone'],

  myDropzone:undefined,

  element: null,

  dropzoneOptions: null,

  // Configuration Options

  url: '#',
  withCredentials: null,
  method: null,
  parallelUploads: null,
  maxFilesize: null,
  filesizeBase: null,
  paramName: null,
  uploadMultiple: null,
  headers: null,
  addRemoveLinks: null,
  previewsContainer: null,
  clickable: null,
  maxThumbnailsize: null,
  thumbnailWidth: null,
  thumbnailHeight: null,
  maxFiles: null,

  // resize: not available
  acceptedFiles: null,
  autoProcessQueue: null,
  forceFallback: null,
  previewTemplate: null,

  // Dropzone translations
  dictDefaultMessage: null,
  dictFallbackMessage: null,
  dictFallbackText: null,
  dictInvalidFileType: null,
  dictFileTooBig: null,
  dictResponseError: null,
  dictCancelUpload: null,
  dictCancelUploadConfirmation: null,
  dictRemoveFile: null,
  dictMaxFilesExceeded: null,

  // Events

  // All of these receive the event as first parameter:
  drop: null,
  dragstart: null,
  dragend: null,
  dragenter: null,
  dragover: null,
  dragleave: null,

  // All of these receive the file as first parameter:
  addedfile: null,
  removedfile: null,
  thumbnail: null,
  error: null,
  processing: null,
  uploadprogress: null,
  sending: null,
  success: null,
  complete: null,
  canceled: null,
  maxfilesreached: null,
  maxfilesexceeded: null,

  // All of these receive a list of files as first parameter and are only called if the uploadMultiple option is true:
  processingmultiple: null,
  sendingmultiple: null,
  successmultiple: null,
  completemultiple: null,
  canceledmultiple: null,

  // Special events:
  totaluploadprogress: null,
  reset: null,
  queuecomplete: null,
  files: null,

  // Callback functions
  accept: null,

  setEvents() {
    let myDropzone = this.get('myDropzone');
    let events = {
      drop: this.drop,
      dragstart: this.dragstart,
      dragend: this.dragend,
      dragenter: this.dragenter,
      dragover: this.dragover,
      dragleave: this.dragleave,
      addedfile: this.addedfile,
      removedfile: this.removedfile,
      thumbnail: this.thumbnail,
      error: this.error,
      processing: this.processing,
      uploadprogress: this.uploadprogress,
      sending: this.sending,
      success: this.success,
      complete: this.complete,
      canceled: this.canceled,
      maxfilesreached: this.maxfilesreached,
      maxfilesexceeded: this.maxfilesexceeded,
      processingmultiple: this.processingmultiple,
      sendingmultiple: this.sendingmultiple,
      successmultiple: this.successmultiple,
      completemultiple: this.completemultiple,
      canceledmultiple: this.canceledmultiple,
      totaluploadprogress: this.totaluploadprogress,
      reset: this.reset,
      queuecomplete: this.queuecomplete,
      files: this.files,
      accept: this.accept,
    };

    for (let e in events) {
      if (events[e] !== null) {
        myDropzone.on(e, events[e]);
      }
    }
  },

  getDropzoneOptions() {
    let dropzoneOptions = {};
    let dropzoneConfig = {
      url: this.url,
      withCredentials: this.withCredentials,
      method: this.method,
      parallelUploads: this.parallelUploads,
      maxFilesize: this.maxFilesize,
      filesizeBase: this.filesizeBase,
      paramName: this.paramName,
      uploadMultiple: this.uploadMultiple,
      headers: this.headers,
      addRemoveLinks: this.addRemoveLinks,
      previewsContainer: this.previewsContainer,
      clickable: this.clickable,
      maxThumbnailsize: this.maxThumbnailsize,
      thumbnailWidth: this.thumbnailWidth,
      thumbnailHeight: this.thumbnailHeight,
      maxFiles: this.maxFiles,

      // resize: not available
      acceptedFiles: this.acceptedFiles,
      autoProcessQueue: this.autoProcessQueue,
      forceFallback: this.forceFallback,
      previewTemplate: this.previewTemplate,

      // Dropzone translations
      dictDefaultMessage: this.dictDefaultMessage,
      dictFallbackMessage: this.dictFallbackMessage,
      dictFallbackText: this.dictFallbackText,
      dictInvalidFileType: this.dictInvalidFileType,
      dictFileTooBig: this.dictFileTooBig,
      dictResponseError: this.dictResponseError,
      dictCancelUpload: this.dictCancelUpload,
      dictCancelUploadConfirmation: this.dictCancelUploadConfirmation,
      dictRemoveFile: this.dictRemoveFile,
      dictMaxFilesExceeded: this.dictMaxFilesExceeded,
    };

    for (let option in dropzoneConfig) {
      let data = dropzoneConfig[option];
      if (data !== null) {
        dropzoneOptions[option] = data;
      } else if (option === 'thumbnailHeight' || option === 'thumbnailWidth') {
        dropzoneOptions[option] = data;
      }
    }

    this.set('dropzoneOptions', dropzoneOptions);
  },

  createDropzone(element) {
    this.set('myDropzone', new Dropzone(element, this.dropzoneOptions));
  },

  insertDropzone: Ember.on('didInsertElement', function() {
    let _this = this;
    this.getDropzoneOptions();
    Dropzone.autoDiscover = false;
    this.createDropzone(this.element);

    if (this.files && this.files.length > 0) {
      this.files.map(function(file) {
        let dropfile = {
          name: file.get('name'),
          type: file.get('type'),
          size: file.get('size'),
          status: Dropzone.ADDED,
        };
        let thumbnail = file.get('thumbnail');

        if (typeof (thumbnail) === 'string') {
          dropfile.thumbnail = thumbnail;
        }

        _this.myDropzone.emit('addedfile', dropfile);

        if (typeof (thumbnail) === 'string') {

          _this.myDropzone.emit('thumbnail', dropfile, thumbnail);
        }

        _this.myDropzone.emit('complete', dropfile);
        _this.myDropzone.files.push(file);
      });
    }

    this.setEvents();
    return this.myDropzone;
  }),
});
<commit_msg>incorrect option name for maxThumbnailFilesize<commit_after>/* global Dropzone*/
import Ember from 'ember';

export default Ember.Component.extend({
  classNames: ['dropzone'],

  myDropzone:undefined,

  element: null,

  dropzoneOptions: null,

  // Configuration Options

  url: '#',
  withCredentials: null,
  method: null,
  parallelUploads: null,
  maxFilesize: null,
  filesizeBase: null,
  paramName: null,
  uploadMultiple: null,
  headers: null,
  addRemoveLinks: null,
  previewsContainer: null,
  clickable: null,
  maxThumbnailFilesize: null,
  thumbnailWidth: null,
  thumbnailHeight: null,
  maxFiles: null,

  // resize: not available
  acceptedFiles: null,
  autoProcessQueue: null,
  forceFallback: null,
  previewTemplate: null,

  // Dropzone translations
  dictDefaultMessage: null,
  dictFallbackMessage: null,
  dictFallbackText: null,
  dictInvalidFileType: null,
  dictFileTooBig: null,
  dictResponseError: null,
  dictCancelUpload: null,
  dictCancelUploadConfirmation: null,
  dictRemoveFile: null,
  dictMaxFilesExceeded: null,

  // Events

  // All of these receive the event as first parameter:
  drop: null,
  dragstart: null,
  dragend: null,
  dragenter: null,
  dragover: null,
  dragleave: null,

  // All of these receive the file as first parameter:
  addedfile: null,
  removedfile: null,
  thumbnail: null,
  error: null,
  processing: null,
  uploadprogress: null,
  sending: null,
  success: null,
  complete: null,
  canceled: null,
  maxfilesreached: null,
  maxfilesexceeded: null,

  // All of these receive a list of files as first parameter and are only called if the uploadMultiple option is true:
  processingmultiple: null,
  sendingmultiple: null,
  successmultiple: null,
  completemultiple: null,
  canceledmultiple: null,

  // Special events:
  totaluploadprogress: null,
  reset: null,
  queuecomplete: null,
  files: null,

  // Callback functions
  accept: null,

  setEvents() {
    let myDropzone = this.get('myDropzone');
    let events = {
      drop: this.drop,
      dragstart: this.dragstart,
      dragend: this.dragend,
      dragenter: this.dragenter,
      dragover: this.dragover,
      dragleave: this.dragleave,
      addedfile: this.addedfile,
      removedfile: this.removedfile,
      thumbnail: this.thumbnail,
      error: this.error,
      processing: this.processing,
      uploadprogress: this.uploadprogress,
      sending: this.sending,
      success: this.success,
      complete: this.complete,
      canceled: this.canceled,
      maxfilesreached: this.maxfilesreached,
      maxfilesexceeded: this.maxfilesexceeded,
      processingmultiple: this.processingmultiple,
      sendingmultiple: this.sendingmultiple,
      successmultiple: this.successmultiple,
      completemultiple: this.completemultiple,
      canceledmultiple: this.canceledmultiple,
      totaluploadprogress: this.totaluploadprogress,
      reset: this.reset,
      queuecomplete: this.queuecomplete,
      files: this.files,
      accept: this.accept,
    };

    for (let e in events) {
      if (events[e] !== null) {
        myDropzone.on(e, events[e]);
      }
    }
  },

  getDropzoneOptions() {
    let dropzoneOptions = {};
    let dropzoneConfig = {
      url: this.url,
      withCredentials: this.withCredentials,
      method: this.method,
      parallelUploads: this.parallelUploads,
      maxFilesize: this.maxFilesize,
      filesizeBase: this.filesizeBase,
      paramName: this.paramName,
      uploadMultiple: this.uploadMultiple,
      headers: this.headers,
      addRemoveLinks: this.addRemoveLinks,
      previewsContainer: this.previewsContainer,
      clickable: this.clickable,
      maxThumbnailFilesize: this.maxThumbnailFilesize,
      thumbnailWidth: this.thumbnailWidth,
      thumbnailHeight: this.thumbnailHeight,
      maxFiles: this.maxFiles,

      // resize: not available
      acceptedFiles: this.acceptedFiles,
      autoProcessQueue: this.autoProcessQueue,
      forceFallback: this.forceFallback,
      previewTemplate: this.previewTemplate,

      // Dropzone translations
      dictDefaultMessage: this.dictDefaultMessage,
      dictFallbackMessage: this.dictFallbackMessage,
      dictFallbackText: this.dictFallbackText,
      dictInvalidFileType: this.dictInvalidFileType,
      dictFileTooBig: this.dictFileTooBig,
      dictResponseError: this.dictResponseError,
      dictCancelUpload: this.dictCancelUpload,
      dictCancelUploadConfirmation: this.dictCancelUploadConfirmation,
      dictRemoveFile: this.dictRemoveFile,
      dictMaxFilesExceeded: this.dictMaxFilesExceeded,
    };

    for (let option in dropzoneConfig) {
      let data = dropzoneConfig[option];
      if (data !== null) {
        dropzoneOptions[option] = data;
      } else if (option === 'thumbnailHeight' || option === 'thumbnailWidth') {
        dropzoneOptions[option] = data;
      }
    }

    this.set('dropzoneOptions', dropzoneOptions);
  },

  createDropzone(element) {
    this.set('myDropzone', new Dropzone(element, this.dropzoneOptions));
  },

  insertDropzone: Ember.on('didInsertElement', function() {
    let _this = this;
    this.getDropzoneOptions();
    Dropzone.autoDiscover = false;
    this.createDropzone(this.element);

    if (this.files && this.files.length > 0) {
      this.files.map(function(file) {
        let dropfile = {
          name: file.get('name'),
          type: file.get('type'),
          size: file.get('size'),
          status: Dropzone.ADDED,
        };
        let thumbnail = file.get('thumbnail');

        if (typeof (thumbnail) === 'string') {
          dropfile.thumbnail = thumbnail;
        }

        _this.myDropzone.emit('addedfile', dropfile);

        if (typeof (thumbnail) === 'string') {

          _this.myDropzone.emit('thumbnail', dropfile, thumbnail);
        }

        _this.myDropzone.emit('complete', dropfile);
        _this.myDropzone.files.push(file);
      });
    }

    this.setEvents();
    return this.myDropzone;
  }),
});
<|endoftext|>


<commit_before>/* global Dropzone*/
import Ember from 'ember';

export default Ember.Component.extend({
  classNames: ['dropzone'],

  myDropzone:undefined,

  element: null,

  dropzoneOptions: null,

  // Configuration Options

  url: '#',
  withCredentials: null,
  method: null,
  parallelUploads: null,
  maxFilesize: null,
  filesizeBase: null,
  paramName: null,
  uploadMultiple: null,
  headers: null,
  addRemoveLinks: null,
  previewsContainer: null,
  clickable: null,
  maxThumbnailFilesize: null,
  thumbnailWidth: null,
  thumbnailHeight: null,
  maxFiles: null,

  // resize: not available
  acceptedFiles: null,
  autoProcessQueue: null,
  forceFallback: null,
  previewTemplate: null,

  // Dropzone translations
  dictDefaultMessage: null,
  dictFallbackMessage: null,
  dictFallbackText: null,
  dictInvalidFileType: null,
  dictFileTooBig: null,
  dictResponseError: null,
  dictCancelUpload: null,
  dictCancelUploadConfirmation: null,
  dictRemoveFile: null,
  dictMaxFilesExceeded: null,

  // Events

  // All of these receive the event as first parameter:
  drop: null,
  dragstart: null,
  dragend: null,
  dragenter: null,
  dragover: null,
  dragleave: null,

  // All of these receive the file as first parameter:
  addedfile: null,
  removedfile: null,
  thumbnail: null,
  error: null,
  processing: null,
  uploadprogress: null,
  sending: null,
  success: null,
  complete: null,
  canceled: null,
  maxfilesreached: null,
  maxfilesexceeded: null,

  // All of these receive a list of files as first parameter and are only called if the uploadMultiple option is true:
  processingmultiple: null,
  sendingmultiple: null,
  successmultiple: null,
  completemultiple: null,
  canceledmultiple: null,

  // Special events:
  totaluploadprogress: null,
  reset: null,
  queuecomplete: null,
  files: null,

  // Callback functions
  accept: null,

  setEvents() {
    let myDropzone = this.get('myDropzone');
    let events = {
      drop: this.drop,
      dragstart: this.dragstart,
      dragend: this.dragend,
      dragenter: this.dragenter,
      dragover: this.dragover,
      dragleave: this.dragleave,
      addedfile: this.addedfile,
      removedfile: this.removedfile,
      thumbnail: this.thumbnail,
      error: this.error,
      processing: this.processing,
      uploadprogress: this.uploadprogress,
      sending: this.sending,
      success: this.success,
      complete: this.complete,
      canceled: this.canceled,
      maxfilesreached: this.maxfilesreached,
      maxfilesexceeded: this.maxfilesexceeded,
      processingmultiple: this.processingmultiple,
      sendingmultiple: this.sendingmultiple,
      successmultiple: this.successmultiple,
      completemultiple: this.completemultiple,
      canceledmultiple: this.canceledmultiple,
      totaluploadprogress: this.totaluploadprogress,
      reset: this.reset,
      queuecomplete: this.queuecomplete,
      files: this.files,
      accept: this.accept,
    };

    for (let e in events) {
      if (events[e] !== null) {
        myDropzone.on(e, events[e]);
      }
    }
  },

  getDropzoneOptions() {
    const onDragEnterLeaveHandler = function(dropzoneInstance) {
      const onDrag = ( element => {
        let dragCounter = 0;

        return {
          enter(event) {
            event.preventDefault();
            dragCounter++;
            element.classList.add('dz-drag-hover');
          },
          leave() {
            dragCounter--;

            if (dragCounter === 0) {
              element.classList.remove('dz-drag-hover');
            }
          }
        };
      }).call(dropzoneInstance.element);

      dropzoneInstance.on('dragenter', onDrag.enter);
      dropzoneInstance.on('dragleave', onDrag.leave);
    };

    let dropzoneOptions = {};
    let dropzoneConfig = {
      url: this.url,
      withCredentials: this.withCredentials,
      method: this.method,
      parallelUploads: this.parallelUploads,
      maxFilesize: this.maxFilesize,
      filesizeBase: this.filesizeBase,
      paramName: this.paramName,
      uploadMultiple: this.uploadMultiple,
      headers: this.headers,
      addRemoveLinks: this.addRemoveLinks,
      previewsContainer: this.previewsContainer,
      clickable: this.clickable,
      maxThumbnailFilesize: this.maxThumbnailFilesize,
      thumbnailWidth: this.thumbnailWidth,
      thumbnailHeight: this.thumbnailHeight,
      maxFiles: this.maxFiles,

      // resize: not available
      acceptedFiles: this.acceptedFiles,
      autoProcessQueue: this.autoProcessQueue,
      forceFallback: this.forceFallback,
      previewTemplate: this.previewTemplate,

      // Dropzone translations
      dictDefaultMessage: this.dictDefaultMessage,
      dictFallbackMessage: this.dictFallbackMessage,
      dictFallbackText: this.dictFallbackText,
      dictInvalidFileType: this.dictInvalidFileType,
      dictFileTooBig: this.dictFileTooBig,
      dictResponseError: this.dictResponseError,
      dictCancelUpload: this.dictCancelUpload,
      dictCancelUploadConfirmation: this.dictCancelUploadConfirmation,
      dictRemoveFile: this.dictRemoveFile,
      dictMaxFilesExceeded: this.dictMaxFilesExceeded,

      // Fix flickering dragging over child elements: https://github.com/enyo/dropzone/issues/438
      dragenter: Ember.$.noop,
      dragleave: Ember.$.noop,
      init: function () { onDragEnterLeaveHandler(this); }
    };

    for (let option in dropzoneConfig) {
      let data = dropzoneConfig[option];
      if (data !== null) {
        dropzoneOptions[option] = data;
      } else if (option === 'thumbnailHeight' || option === 'thumbnailWidth') {
        dropzoneOptions[option] = data;
      }
    }

    this.set('dropzoneOptions', dropzoneOptions);
  },

  createDropzone(element) {
    this.set('myDropzone', new Dropzone(element, this.dropzoneOptions));
  },

  insertDropzone: Ember.on('didInsertElement', function() {
    let _this = this;
    this.getDropzoneOptions();
    Dropzone.autoDiscover = false;
    this.createDropzone(this.element);

    if (this.files && this.files.length > 0) {
      this.files.map(function(file) {
        let dropfile = {
          name: file.get('name'),
          type: file.get('type'),
          size: file.get('size'),
          status: Dropzone.ADDED,
        };
        let thumbnail = file.get('thumbnail');

        if (typeof (thumbnail) === 'string') {
          dropfile.thumbnail = thumbnail;
        }

        _this.myDropzone.emit('addedfile', dropfile);

        if (typeof (thumbnail) === 'string') {

          _this.myDropzone.emit('thumbnail', dropfile, thumbnail);
        }

        _this.myDropzone.emit('complete', dropfile);
        _this.myDropzone.files.push(file);
      });
    }

    this.setEvents();
    return this.myDropzone;
  }),
});
<commit_msg>Fix  issue<commit_after>/* global Dropzone*/
import Ember from 'ember';

export default Ember.Component.extend({
  classNames: ['dropzone'],

  myDropzone:undefined,

  element: null,

  dropzoneOptions: null,

  // Configuration Options

  url: '#',
  withCredentials: null,
  method: null,
  parallelUploads: null,
  maxFilesize: null,
  filesizeBase: null,
  paramName: null,
  uploadMultiple: null,
  headers: null,
  addRemoveLinks: null,
  previewsContainer: null,
  clickable: null,
  maxThumbnailFilesize: null,
  thumbnailWidth: null,
  thumbnailHeight: null,
  maxFiles: null,

  // resize: not available
  acceptedFiles: null,
  autoProcessQueue: null,
  forceFallback: null,
  previewTemplate: null,

  // Dropzone translations
  dictDefaultMessage: null,
  dictFallbackMessage: null,
  dictFallbackText: null,
  dictInvalidFileType: null,
  dictFileTooBig: null,
  dictResponseError: null,
  dictCancelUpload: null,
  dictCancelUploadConfirmation: null,
  dictRemoveFile: null,
  dictMaxFilesExceeded: null,

  // Events

  // All of these receive the event as first parameter:
  drop: null,
  dragstart: null,
  dragend: null,
  dragenter: null,
  dragover: null,
  dragleave: null,

  // All of these receive the file as first parameter:
  addedfile: null,
  removedfile: null,
  thumbnail: null,
  error: null,
  processing: null,
  uploadprogress: null,
  sending: null,
  success: null,
  complete: null,
  canceled: null,
  maxfilesreached: null,
  maxfilesexceeded: null,

  // All of these receive a list of files as first parameter and are only called if the uploadMultiple option is true:
  processingmultiple: null,
  sendingmultiple: null,
  successmultiple: null,
  completemultiple: null,
  canceledmultiple: null,

  // Special events:
  totaluploadprogress: null,
  reset: null,
  queuecomplete: null,
  files: null,

  // Callback functions
  accept: null,

  setEvents() {
    let myDropzone = this.get('myDropzone');
    let events = {
      drop: this.drop,
      dragstart: this.dragstart,
      dragend: this.dragend,
      dragenter: this.dragenter,
      dragover: this.dragover,
      dragleave: this.dragleave,
      addedfile: this.addedfile,
      removedfile: this.removedfile,
      thumbnail: this.thumbnail,
      error: this.error,
      processing: this.processing,
      uploadprogress: this.uploadprogress,
      sending: this.sending,
      success: this.success,
      complete: this.complete,
      canceled: this.canceled,
      maxfilesreached: this.maxfilesreached,
      maxfilesexceeded: this.maxfilesexceeded,
      processingmultiple: this.processingmultiple,
      sendingmultiple: this.sendingmultiple,
      successmultiple: this.successmultiple,
      completemultiple: this.completemultiple,
      canceledmultiple: this.canceledmultiple,
      totaluploadprogress: this.totaluploadprogress,
      reset: this.reset,
      queuecomplete: this.queuecomplete,
      files: this.files,
      accept: this.accept,
    };

    for (let e in events) {
      if (events[e] !== null) {
        myDropzone.on(e, events[e]);
      }
    }
  },

  getDropzoneOptions() {
    const onDragEnterLeaveHandler = function(dropzoneInstance) {
      const onDrag = ( element => {
        let dragCounter = 0;

        return {
          enter(event) {
            event.preventDefault();
            dragCounter++;
            element.classList.add('dz-drag-hover');
          },
          leave() {
            dragCounter--;

            if (dragCounter === 0) {
              element.classList.remove('dz-drag-hover');
            }
          }
        };
      }).call(this, dropzoneInstance.element);

      dropzoneInstance.on('dragenter', onDrag.enter);
      dropzoneInstance.on('dragleave', onDrag.leave);
    };

    let dropzoneOptions = {};
    let dropzoneConfig = {
      url: this.url,
      withCredentials: this.withCredentials,
      method: this.method,
      parallelUploads: this.parallelUploads,
      maxFilesize: this.maxFilesize,
      filesizeBase: this.filesizeBase,
      paramName: this.paramName,
      uploadMultiple: this.uploadMultiple,
      headers: this.headers,
      addRemoveLinks: this.addRemoveLinks,
      previewsContainer: this.previewsContainer,
      clickable: this.clickable,
      maxThumbnailFilesize: this.maxThumbnailFilesize,
      thumbnailWidth: this.thumbnailWidth,
      thumbnailHeight: this.thumbnailHeight,
      maxFiles: this.maxFiles,

      // resize: not available
      acceptedFiles: this.acceptedFiles,
      autoProcessQueue: this.autoProcessQueue,
      forceFallback: this.forceFallback,
      previewTemplate: this.previewTemplate,

      // Dropzone translations
      dictDefaultMessage: this.dictDefaultMessage,
      dictFallbackMessage: this.dictFallbackMessage,
      dictFallbackText: this.dictFallbackText,
      dictInvalidFileType: this.dictInvalidFileType,
      dictFileTooBig: this.dictFileTooBig,
      dictResponseError: this.dictResponseError,
      dictCancelUpload: this.dictCancelUpload,
      dictCancelUploadConfirmation: this.dictCancelUploadConfirmation,
      dictRemoveFile: this.dictRemoveFile,
      dictMaxFilesExceeded: this.dictMaxFilesExceeded,

      // Fix flickering dragging over child elements: https://github.com/enyo/dropzone/issues/438
      dragenter: Ember.$.noop,
      dragleave: Ember.$.noop,
      init: function () { onDragEnterLeaveHandler(this); }
    };

    for (let option in dropzoneConfig) {
      let data = dropzoneConfig[option];
      if (data !== null) {
        dropzoneOptions[option] = data;
      } else if (option === 'thumbnailHeight' || option === 'thumbnailWidth') {
        dropzoneOptions[option] = data;
      }
    }

    this.set('dropzoneOptions', dropzoneOptions);
  },

  createDropzone(element) {
    this.set('myDropzone', new Dropzone(element, this.dropzoneOptions));
  },

  insertDropzone: Ember.on('didInsertElement', function() {
    let _this = this;
    this.getDropzoneOptions();
    Dropzone.autoDiscover = false;
    this.createDropzone(this.element);

    if (this.files && this.files.length > 0) {
      this.files.map(function(file) {
        let dropfile = {
          name: file.get('name'),
          type: file.get('type'),
          size: file.get('size'),
          status: Dropzone.ADDED,
        };
        let thumbnail = file.get('thumbnail');

        if (typeof (thumbnail) === 'string') {
          dropfile.thumbnail = thumbnail;
        }

        _this.myDropzone.emit('addedfile', dropfile);

        if (typeof (thumbnail) === 'string') {

          _this.myDropzone.emit('thumbnail', dropfile, thumbnail);
        }

        _this.myDropzone.emit('complete', dropfile);
        _this.myDropzone.files.push(file);
      });
    }

    this.setEvents();
    return this.myDropzone;
  }),
});
<|endoftext|>