(function ($) {

	$.fn.InternetOverview = function (options) {

		/* User variables */
		var defaults = {
			'selector': {
				'offer_switch': 'div.switch-section .switch .option', //Auswahl
				'offer_section': 'div.offers', //Container über Angebote
				'offer_tab': 'div.offers .offer', //Angebot
			},
		};

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

		var _self = this;

		/* INITIATE FUNCTION */
		function init() {
			initOffers();
		}
		
		function initOffers() {
			get('offer_switch').on('click', switchOffer);
			
			var deeplink = window.location.hash.substr(1);
			var option = get('offer_switch', '[id="' + deeplink + '"]');
			
			if(option.length > 0) option.trigger('click');
		}
		
		function switchOffer(e) {
		var nextContent = get('offer_tab', '[id="' + $(this).attr('id') + '"]');
		console.log(nextContent);
		if (nextContent.is(":visible")) return;
		
		var duration = 400;
		if(get('offer_tab', ':visible').length < 1) duration = 0;
		
		get('offer_switch').removeClass('active').addClass('not-active');

		$(this).addClass('active').removeClass('not-active');
		
		get('offer_tab').removeClass('active').slideUp(duration);
		
		setTimeout(function() {
			nextContent.slideDown(function() {
				$(this).addClass('active');
				$('.cmp-tariff-table').each(function() {
					$(document).trigger('reinitializeTariffTable', $(this).parent());
				});
				
				if(isMobile()) {
				var top = getTargetOffset(get('offer_section')) + 50;
						$('html, body').animate({
						'scrollTop': top
					});
				}		
			});
		}, duration);
		}
		
		function isMobile() {
			return $(window).innerWidth() >= 320;
		}

		function getTargetOffset(element, snapToSection) {
			if(typeof snapToSection == 'undefined') snapToSection = true;
			if(snapToSection && !element.is('div')) element = element.parents('div.switch');
			var targetOffset = element.offset().top;
			targetOffset -= $('#magenta-page-header').outerHeight();
			
			// calculate actual section begin
			if(snapToSection) {
			  var margin = parseInt(element.css('margin-top'));
			  targetOffset -= margin;
			}
			
			return targetOffset;
		  }

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

		/* INITIATE PLUGIN */
		init();

		// RETURN THE JQUERY OBJECT
		return this;

	};

}(jQuery));


$(function() {
	$('body').InternetOverview();
});