(function ($) {

	$.fn.MagentaSpeedComparison = function (options) {

		/* User variables */
		var defaults = {
			'selector': {
				'speedMeter': '.speed-meter',
				'speedTariff' : '.product h3'
			}
		};

		/* Combines Default settings and user options */
		this.settings = $.extend({}, defaults, options);

		var _self = this;

		/* INITIATE FUNCTION */
		function init() {
			$(document).on('scroll', animate);
			animate();

			_self.closest('section').find('.cmp-tabitem a').on('click', function() {
				setTimeout(function() {
					$(window).scrollTop($(window).scrollTop() + 1);
					$(window).scrollTop($(window).scrollTop() - 1);
				}, 600);
			});

			$('.cmp-tabitem a.cta').on('click', function(e) {
				e.preventDefault();
				var content = $('.cmp-tabitem-tab-content[data-tab="' + $(this).attr('data-tab') + '"]');
				var filler = content.find('.filler');
				var duration = [];
				filler.css({
					'width': 0,
					'transition-duration': ''
				});
				setTimeout(function() {
					$.each(filler, function(i) {
						$(this).css({
							'width': '',
							'transition-duration': $(this).parent().attr('data-speed')
						});
					});
				}, 100);
			});
		}

		function animate() {

			var topOfMeter = _self.offset().top;
			var bottomOfMeter = _self.offset().top + _self.outerHeight();
			var topOfViewport = $(window).scrollTop();
			var bottomOfViewport = $(window).scrollTop() + $(window).innerHeight();

			if ((bottomOfViewport > topOfMeter) && (topOfViewport < bottomOfMeter)) {
				setTimeout(function() {
					get('speedMeter').each(function() {
						$(this).find('.filler').css('transition-duration', $(this).data('speed'));
						if (_self.parents('.cmp-tabitem-tab-content').length) {
							$(this).addClass('animate-tab');
						} else {
							$(this).addClass('animate');
						}
					});
					get('speedTariff').each(function() {
						$(this).addClass('speedanimation');
					});	
				}, 1000);
				$(document).off('scroll', animate);
			}
		}

		function get(index, param) {
			if (typeof param != 'undefined') return _self.find(_self.settings.selector[index] + param);
			return _self.find(_self.settings.selector[index]);
		}

		/* INITIATE PLUGIN */
		//setTimeout(function () {
			init();
		//}, 0);

		// RETURN THE JQUERY OBJECT
		return this;

	};

}(jQuery));


$(function () {

	$('.consumer .speed-comparison').each(function () {
		$(this).MagentaSpeedComparison();
    });

});
