var criteria;
var wniosek;


function Template(name, url, urlError) {

	this.name = name;

	this.url = url;

	this.urlError = urlError;

	this.listModal = null;

	this.listBody = null;

	this.listLoader = null;

	this.items = [];

	this.itemsIndex = 0;

	this.sortable = function() {
		var that = this;
		$('.path-rows-' + that.name).sortable({
			axis: 'y',
			helper: "original",
			forcePlaceholderSize: true,
			stop: function (event, ui) {
				that.reorder();
			}
		});
	};

	this.list =  function () {
		var that = this;
		$('#'+ this.name +'-search-trigger').click(function (e) {
			e.preventDefault();
			that.listModal = $('#'+ that.name +'-list-modal');
			that.listBody = that.listModal.find('#'+ that.name +'-list-body');
			that.listLoader = that.listBody.find('#'+ that.name +'-list-loader');
			that.getList();
		});
	};

	this.getList = function() {
		var that = this;

		that.listModal.modal('show');

		$.ajax({
			url: that.url,
			type: 'POST',
			data: {},
			dataType: 'HTML',
			async: true,
			beforeSend: function () {
				showLoader(that.listLoader);
			},
			success: function (response) {
				if(trim(response) === 'login') {
					window.location = that.urlError;
				} else {
					if (response != 'empty') {
						that.listBody.html(response);
						that.listLoader = that.listBody.find('#'+ this.name +'-list-loader');

						$('#'+ that.name +'-list').find('#ALL').on('ifToggled', function () {
							var is_checked = $(this).is(':checked');
							$('#'+ that.name +'-list .checkboxes-right:not(.check-all):visible').each(function () {
								if(is_checked) {
									$(this).find('input[type="checkbox"]').iCheck('check');
								} else {
									$(this).find('input[type="checkbox"]').iCheck('uncheck');
								}
							});
						});

						checkboxesInit('#'+ that.name +'-list-modal');
						if (that.items.length > 0) {
							$.each(that.items, function (index, value) {
								that.listBody.find('#' + value).iCheck('check');
							});
						}
					}
					that.filtering();
					hideLoader(that.listLoader);
				}
			},
			error: function (err) {
				if(err.status === 403) {
					window.location = that.urlError;
				}
			}
		});

	};

	this.filtering =  function () {
		$.expr[":"].contains = $.expr.createPseudo(function (arg) {
			return function (elem) {
				return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
			};
		});
		var that = this;
		$('#'+ that.name +'-filter').keyup(function () {
			var filter = $(this).val();
			console.log(filter);
			if (filter.length > 0) {
				$('#'+ that.name +'-list > div').hide();
				$('#'+ that.name +'-list > div:contains(Wszystkie)').show();
				$('#'+ that.name +'-list > div:contains(' + filter + ')').show();
			} else {
				$('#'+ that.name +'-list > div').show();
			}
		});
	};

	this.reorder = function reorder() {
		var that = this;
		var name = '';
		var regex = /\d/;
		$('#'+ that.name +'-rows .path-row').each(function (index) {
			$(this).attr('id', that.name  + '-' + index);
			$(this).find('.path-index').text((index+1));
			$(this).find('input[type=hidden]').each(function() {
				name = $(this).attr('name');
				$(this).attr('name', name.replace(regex, index));
			});
		});
	};

	this.delete = function(gid, row) {
		var index = this.items.indexOf(gid);
		if (index > -1) {
			this.items.splice(index, 1);
		}
		$(row).remove();
		this.reorder();
	};

	this.add = function(input, gid) {
		var row;

		if ($.inArray(gid, this.items) == -1) {
			switch (this.name) {
				case 'criteria':
					row = addCriteria(input.data('nazwa'), input.data('rodzaj'), gid, this.itemsIndex);
					break;
				case 'wniosek':
					row = addWniosek(input.data('nazwa'), gid, this.itemsIndex);
					break;

			}

			if (row) {
				$('#'+ this.name +'-rows').append(row);
				this.items.push(gid);
				this.itemsIndex++;
			}
			//checkboxesInit();
			this.reorder();
		}
	};

	this.addToItem = function(gid) {

		if ($.inArray(gid, this.items) == -1) {
			this.items.push(gid);
			this.itemsIndex++;

			this.reorder();
		}

	};

	this.listModalSubmit = function() {
		var checkedCriteria = this.listModal.find('input[type=checkbox]:checked');
		var that = this;
		$.each(checkedCriteria, function (index) {
			that.add($(this), $(this).attr('id'));
		});
		var uncheckedReceivers = this.listModal.find('input[type=checkbox]:not(:checked)');
		$.each(uncheckedReceivers, function (index) {
			var	gid = $(this).attr('id');
			var input = $('.' + that.name + '-gid[value="' + gid + '"]');
			if (input.length > 0) {
				that.delete(gid, input.parent());
			}
		});
		this.listModal.modal('hide');
	};

}


function addCriteria(nazwa, rodzaj, gid, index) {

	var row = "data[bKryteriumOceny][" + index + "]";
	var rowGid = row + "[dat:Gid]";
	var rowReq = row + "[dat:CzyObowiazkowe]";
	var rowName = row + "[dat:Nazwa]";
	var rowKind = row + "[dat:Rodzaj]";
	var grey;

	if (typeof nazwa === 'undefined') {
		return false;
	}

	if (rodzaj === 'Grupa') {
		grey = 'style="color: grey;"';
	} else {
		grey = '';
	}


	var path_row = $('<div class="row path-row" id="criteria-' + index + '"></div>');
	var path_column1 = $('<div class="col-xs-2 path-index">' + (index+1) + '</div>');
	var path_column2 = $('<div class="col-xs-3" '+ grey +' >' + nazwa + '</div>');
	var path_column3 = $('<div class="col-xs-2" '+ grey +' >' + rodzaj + '</div>');
	var path_column4 = $('<div class="col-xs-2"></div>');
	var path_column4_info = $('<input type="checkbox" class="criteria-req" name="' + rowReq + '" value="1"> Wymagane </input>');
	var path_column5 = $('<div class="col-xs-3"></div>');
	var path_column5_info = $('<a href="#" class="delete-criteria-element btn btn-flat btn-danger pull-right"><i class="fa fa-trash"></i></a>');
	var path_row_gid = $('<input type="hidden" class="criteria-gid" name="' + rowGid + '" value="' + gid + '">');
	var path_row_name = $('<input type="hidden" class="criteria-name" name="' + rowName + '" value="' + nazwa + '">');
	var path_row_kind = $('<input type="hidden" class="criteria-kind" name="' + rowKind + '" value="' + rodzaj + '">');

	if (grey === '') {
		path_column4.append(path_column4_info);
	}
	path_column5.append(path_column5_info);

	path_row.append(path_row_gid)
		.append(path_row_name)
		.append(path_row_kind)
		.append(path_column1)
		.append(path_column2)
		.append(path_column3)
		.append(path_column4)
		.append(path_column5);

	return path_row;
}

function addWniosek(nazwa, gid, index) {

	var row = "data[bWniosekOceny][" + index + "]";
	var rowGid = row + "[dat:Gid]";
	var rowName = row + "[dat:Nazwa]";

	if (typeof nazwa === 'undefined') {
		return false;
	}

	var path_row = $('<div class="row path-row" id="wniosek-' + index + '"></div>');
	var path_column1 = $('<div class="col-xs-2 path-index">' + (index+1) + '</div>');
	var path_column2 = $('<div class="col-xs-7">' + nazwa + '</div>');
	var path_column3 = $('<div class="col-xs-3"></div>');
	var path_column3_info = $('<a href="#" class="delete-wniosek-element btn btn-flat btn-danger pull-right"><i class="fa fa-trash"></i></a>');
	var path_row_gid = $('<input type="hidden" class="wniosek-gid" name="' + rowGid + '" value="' + gid + '">');
	var path_row_name = $('<input type="hidden" class="wniosek-name" name="' + rowName + '" value="' + nazwa + '">');

	path_column3.append(path_column3_info);

	path_row.append(path_row_gid)
		.append(path_row_name)
		.append(path_column1)
		.append(path_column2)
		.append(path_column3);

	return path_row;
}

$(document).ready(function () {

	criteria = new Template('criteria', (local_url + 'ajax/api/daj_kryteria_oceny_pracownika'), (local_url + 'login'));
	criteria.list();
	criteria.sortable();

	wniosek = new Template('wniosek', (local_url + 'ajax/api/daj_wnioski_oceny_pracownika'), (local_url + 'login'));
	wniosek.list();
	wniosek.sortable();

});

$(document).on('click', '#wniosek-list-submit', function () {
	if (wniosek) {
		wniosek.listModalSubmit();
	}
});

$(document).on('click', '.delete-wniosek-element', function (e) {
	e.preventDefault();
	if (confirm('Usunąć z listy wniosków?')) {
		var gid = $(this).parents('.path-row').find('.wniosek-gid').val();
		var row = $(this).parents('.path-row');
		if (wniosek) {
			wniosek.delete(gid, row);
		}
	}
});

$(document).on('click', '#criteria-list-submit', function () {
	if (criteria) {
		criteria.listModalSubmit();
	}
});

$(document).on('click', '.delete-criteria-element', function (e) {
	e.preventDefault();
	if (confirm('Usunąć z listy krytriów?')) {
		var gid = $(this).parents('.path-row').find('.criteria-gid').val();
		var row = $(this).parents('.path-row');
		if (criteria) {
			criteria.delete(gid, row);
		}
	}
});
