var kartypracy = (function($, undefined) {
	"use strict"

	var view = $('#KartyPracyPracownikow');

	var tabsInfo = {
		moje: ['moje', 'tab1'],
		pracownikow: ['pracownikow', 'tab2'],
		tab1: ['moje', 'tab1'],
		tab2: ['pracownikow', 'tab2'],
	}

	//=========================================
	//	START INIT LISTENER LISTA
	//=========================================

	//view.ready(function() {
		ajaxList(kartypracy_tab_active.name, kartypracy_tab_active.id,kartypracy_tab_active.nrewid);
		$('.tab-pane').removeClass('active');
		$('#' + kartypracy_tab_active.id).addClass('active');
	//});

	view.on('click', 'li', function() {
		var item = $(this),
			a = item.children('a').eq(0),
			filter = a.data('value');

		if (filter !== undefined) {

			kartypracy_tab_active.name = tabsInfo[filter][0];
			kartypracy_tab_active.id = tabsInfo[filter][1];

			ajaxList(kartypracy_tab_active.name, kartypracy_tab_active.id, kartypracy_tab_active.nrewid);


		}
	});

	view.on('change', '#kartypracy-pracownicy', function() {
		var nrewid = $(this).val(),
			filtr = getDateFitlr();

		if (nrewid !== undefined) {

			kartypracy_tab_active.nrewid = nrewid;

			ajaxList(kartypracy_tab_active.name, kartypracy_tab_active.id, kartypracy_tab_active.nrewid, filtr.od, filtr.do);
		}
	});

	view.on('click', '.kartypracy-button-trigger', function () {

		var filtr = getDateFitlr();

		ajaxList(kartypracy_tab_active.name, kartypracy_tab_active.id, kartypracy_tab_active.nrewid, filtr.od, filtr.do);
	});


	//=========================================
	//	END INIT LISTENER LISTA
	//=========================================

	//=========================================
	//	START FUNCTIONS LISTA
	//=========================================

	function getDateFitlr() {
		var okres = $('#' + kartypracy_tab_active.id + ' .kartypracy_filtr'),
			cod = okres.length >= 1 ? $(okres[0]) : null,
			cdo = okres.length >= 2 ? $(okres[1]) : null;

		console.log(cod.val() + ' ' + cdo.val());
		return {od: cod.val(), do: cdo.val()};
	}

	function ajaxList(filter, tab, nrewid, okresOd, okresDo) {
		var loader = $('#' + tab + ' .custom-loader'),
			container = $('#' + tab + ' .box-body');

		$.ajax({
			url: local_url + 'ajax/kartypracy/lista_' + filter,
			method: 'GET',
			data: {
				tab: filter,
				nrewid: nrewid,
				okresOd: okresOd,
				okresDo: okresDo,
			},
			beforeSend: function () {
				loader.css('display', 'block');
			},
			success: function (data) {
				if(trim(data) === 'login') {
					window.location = local_url + 'login';
				}
				container.html(data);
			},
			complete: function (xhr, status) {
				loader.css('display', 'none');
			}
		});
	}

	var app = {}

	console.log('aaaa');

	return app;

})(jQuery);
