/* Minification failed. Returning unminified contents.
(10,1): run-time error CSS1019: Unexpected token, found '('
(10,2): run-time error CSS1019: Unexpected token, found 'function('
(10,11): run-time error CSS1019: Unexpected token, found '$'
(10,12): run-time error CSS1019: Unexpected token, found ')'
(10,14): run-time error CSS1019: Unexpected token, found '{'
(11,2): run-time error CSS1019: Unexpected token, found '"use strict"'
(12,16): run-time error CSS1031: Expected selector, found '='
(12,16): run-time error CSS1025: Expected comma or open brace, found '='
(14,16): run-time error CSS1031: Expected selector, found '='
(14,16): run-time error CSS1025: Expected comma or open brace, found '='
(20,22): run-time error CSS1031: Expected selector, found '='
(20,22): run-time error CSS1025: Expected comma or open brace, found '='
(372,10): run-time error CSS1031: Expected selector, found '='
(372,10): run-time error CSS1025: Expected comma or open brace, found '='
(374,2): run-time error CSS1019: Unexpected token, found '$'
(374,17): run-time error CSS1031: Expected selector, found '='
(374,17): run-time error CSS1025: Expected comma or open brace, found '='
(412,2): run-time error CSS1019: Unexpected token, found '$'
(412,26): run-time error CSS1031: Expected selector, found '='
(412,26): run-time error CSS1025: Expected comma or open brace, found '='
(430,2): run-time error CSS1019: Unexpected token, found '$'
(430,28): run-time error CSS1031: Expected selector, found '='
(430,28): run-time error CSS1025: Expected comma or open brace, found '='
(435,2): run-time error CSS1019: Unexpected token, found '$'
(435,3): run-time error CSS1019: Unexpected token, found '('
(435,4): run-time error CSS1019: Unexpected token, found 'function('
(435,13): run-time error CSS1019: Unexpected token, found ')'
(435,15): run-time error CSS1019: Unexpected token, found '{'
(436,3): run-time error CSS1019: Unexpected token, found '$'
(436,4): run-time error CSS1019: Unexpected token, found '('
(436,5): run-time error CSS1019: Unexpected token, found ''.filestyle''
(436,17): run-time error CSS1019: Unexpected token, found ')'
(436,19): run-time error CSS1030: Expected identifier, found 'each('
(436,19): run-time error CSS1019: Unexpected token, found 'each('
(436,24): run-time error CSS1019: Unexpected token, found 'function('
(436,33): run-time error CSS1019: Unexpected token, found ')'
(436,35): run-time error CSS1019: Unexpected token, found '{'
(437,8): run-time error CSS1031: Expected selector, found '$'
(437,8): run-time error CSS1025: Expected comma or open brace, found '$'
(451,4): run-time error CSS1019: Unexpected token, found '$'
(451,10): run-time error CSS1030: Expected identifier, found 'filestyle('
(451,10): run-time error CSS1031: Expected selector, found 'filestyle('
(451,10): run-time error CSS1025: Expected comma or open brace, found 'filestyle('
(452,3): run-time error CSS1019: Unexpected token, found '}'
(452,4): run-time error CSS1019: Unexpected token, found ')'
(453,2): run-time error CSS1019: Unexpected token, found '}'
(453,3): run-time error CSS1019: Unexpected token, found ')'
(454,1): run-time error CSS1019: Unexpected token, found '}'
(454,2): run-time error CSS1019: Unexpected token, found ')'
(454,3): run-time error CSS1019: Unexpected token, found '('
(454,17): run-time error CSS1031: Expected selector, found ')'
(454,17): run-time error CSS1025: Expected comma or open brace, found ')'
(461,10): run-time error CSS1031: Expected selector, found 'DanijelTable('
(461,10): run-time error CSS1025: Expected comma or open brace, found 'DanijelTable('
(469,10): run-time error CSS1031: Expected selector, found 'DodajFilterRow('
(469,10): run-time error CSS1025: Expected comma or open brace, found 'DodajFilterRow('
(568,10): run-time error CSS1031: Expected selector, found 'DodajNoviRed('
(568,10): run-time error CSS1025: Expected comma or open brace, found 'DodajNoviRed('
(582,10): run-time error CSS1031: Expected selector, found 'PostaviEvente('
(582,10): run-time error CSS1025: Expected comma or open brace, found 'PostaviEvente('
(625,10): run-time error CSS1031: Expected selector, found 'SetClickEvent('
(625,10): run-time error CSS1025: Expected comma or open brace, found 'SetClickEvent('
(654,10): run-time error CSS1031: Expected selector, found 'AnaimirajTr('
(654,10): run-time error CSS1025: Expected comma or open brace, found 'AnaimirajTr('
(667,10): run-time error CSS1031: Expected selector, found 'AnaimirajInput('
(667,10): run-time error CSS1025: Expected comma or open brace, found 'AnaimirajInput('
(677,10): run-time error CSS1031: Expected selector, found 'PostaviSortiranje('
(677,10): run-time error CSS1025: Expected comma or open brace, found 'PostaviSortiranje('
(724,10): run-time error CSS1031: Expected selector, found 'comparer('
(724,10): run-time error CSS1025: Expected comma or open brace, found 'comparer('
(752,10): run-time error CSS1031: Expected selector, found 'getCellValue('
(752,10): run-time error CSS1025: Expected comma or open brace, found 'getCellValue('
(762,10): run-time error CSS1031: Expected selector, found 'loader_start2('
(762,10): run-time error CSS1025: Expected comma or open brace, found 'loader_start2('
(778,10): run-time error CSS1031: Expected selector, found 'loader_stop2('
(778,10): run-time error CSS1025: Expected comma or open brace, found 'loader_stop2('
(782,1): run-time error CSS1019: Unexpected token, found '$'
(782,2): run-time error CSS1019: Unexpected token, found '('
(782,11): run-time error CSS1031: Expected selector, found ')'
(782,11): run-time error CSS1025: Expected comma or open brace, found ')'
(796,2): run-time error CSS1019: Unexpected token, found ')'
(797,10): run-time error CSS1031: Expected selector, found 'OnChange('
(797,10): run-time error CSS1025: Expected comma or open brace, found 'OnChange('
(800,10): run-time error CSS1031: Expected selector, found 'CheckForChanges('
(800,10): run-time error CSS1025: Expected comma or open brace, found 'CheckForChanges('
(819,10): run-time error CSS1031: Expected selector, found 'DropDownButton('
(819,10): run-time error CSS1025: Expected comma or open brace, found 'DropDownButton('
(827,10): run-time error CSS1031: Expected selector, found 'PageDownUpEvent('
(827,10): run-time error CSS1025: Expected comma or open brace, found 'PageDownUpEvent('
(844,10): run-time error CSS1031: Expected selector, found 'PostaviPagerEvente('
(844,10): run-time error CSS1025: Expected comma or open brace, found 'PostaviPagerEvente('
(859,10): run-time error CSS1031: Expected selector, found 'KreirajTabelu('
(859,10): run-time error CSS1025: Expected comma or open brace, found 'KreirajTabelu('
(910,10): run-time error CSS1031: Expected selector, found 'setCookie('
(910,10): run-time error CSS1025: Expected comma or open brace, found 'setCookie('
(916,10): run-time error CSS1031: Expected selector, found 'getCookie('
(916,10): run-time error CSS1025: Expected comma or open brace, found 'getCookie('
(931,10): run-time error CSS1031: Expected selector, found 'PageDownUpEvent('
(931,10): run-time error CSS1025: Expected comma or open brace, found 'PageDownUpEvent('
(946,10): run-time error CSS1031: Expected selector, found 'scrollbottom('
(946,10): run-time error CSS1025: Expected comma or open brace, found 'scrollbottom('
(950,1): run-time error CSS1019: Unexpected token, found '$'
(950,3): run-time error CSS1030: Expected identifier, found 'widget('
(950,3): run-time error CSS1019: Unexpected token, found 'widget('
(950,10): run-time error CSS1019: Unexpected token, found ''custom.mcautocomplete''
(950,33): run-time error CSS1019: Unexpected token, found ','
(950,35): run-time error CSS1019: Unexpected token, found '$'
(951,24): run-time error CSS1036: Expected expression, found ')'
(951,25): run-time error CSS1062: Expected semicolon or closing curly-brace, found ' '
(985,2): run-time error CSS1019: Unexpected token, found ')'
(987,3): run-time error CSS1019: Unexpected token, found '('
(987,13): run-time error CSS1031: Expected selector, found '('
(987,13): run-time error CSS1025: Expected comma or open brace, found '('
(1016,2): run-time error CSS1019: Unexpected token, found ')'
(1016,3): run-time error CSS1019: Unexpected token, found '('
(1016,10): run-time error CSS1031: Expected selector, found ')'
(1016,10): run-time error CSS1025: Expected comma or open brace, found ')'
(1086,1): run-time error CSS1019: Unexpected token, found '('
(1086,11): run-time error CSS1031: Expected selector, found '('
(1086,11): run-time error CSS1025: Expected comma or open brace, found '('
(1481,2): run-time error CSS1019: Unexpected token, found ')'
(1481,3): run-time error CSS1019: Unexpected token, found '('
(1481,10): run-time error CSS1031: Expected selector, found ')'
(1481,10): run-time error CSS1025: Expected comma or open brace, found ')'
(1484,1): run-time error CSS1019: Unexpected token, found '!'
(1484,2): run-time error CSS1019: Unexpected token, found '('
(1484,12): run-time error CSS1031: Expected selector, found '('
(1484,12): run-time error CSS1025: Expected comma or open brace, found '('
(1771,2): run-time error CSS1019: Unexpected token, found ')'
(1771,3): run-time error CSS1019: Unexpected token, found '('
(1771,4): run-time error CSS1019: Unexpected token, found ')'
(1783,1): run-time error CSS1019: Unexpected token, found '('
(1783,11): run-time error CSS1031: Expected selector, found '('
(1783,11): run-time error CSS1025: Expected comma or open brace, found '('
(1789,2): run-time error CSS1019: Unexpected token, found '('
(1789,12): run-time error CSS1031: Expected selector, found '('
(1789,12): run-time error CSS1025: Expected comma or open brace, found '('
(2091,2): run-time error CSS1019: Unexpected token, found ')'
(2091,3): run-time error CSS1019: Unexpected token, found ')'
(2106,1): run-time error CSS1019: Unexpected token, found '('
(2106,2): run-time error CSS1019: Unexpected token, found 'function('
(2106,18): run-time error CSS1031: Expected selector, found ')'
(2106,18): run-time error CSS1025: Expected comma or open brace, found ')'
(2119,2): run-time error CSS1019: Unexpected token, found '('
(2119,3): run-time error CSS1019: Unexpected token, found 'function('
(2119,12): run-time error CSS1019: Unexpected token, found '$'
(2119,13): run-time error CSS1019: Unexpected token, found ')'
(2119,15): run-time error CSS1019: Unexpected token, found '{'
(2121,5): run-time error CSS1019: Unexpected token, found ''use strict''
(2123,5): run-time error CSS1019: Unexpected token, found '$'
(2123,24): run-time error CSS1031: Expected selector, found '='
(2123,24): run-time error CSS1025: Expected comma or open brace, found '='
 */
/*
 * bootstrap-filestyle
 * doc: http://markusslima.github.io/bootstrap-filestyle/
 * github: https://github.com/markusslima/bootstrap-filestyle
 *
 * Copyright (c) 2017 Markus Vinicius da Silva Lima
 * Version 2.1.0
 * Licensed under the MIT license.
 */
(function($) {
	"use strict";
    var nextId = 0;

	var Filestyle = function(element, options) {
		this.options = options;
		this.$elementFilestyle = [];
		this.$element = $(element);
	};

	Filestyle.prototype = {
		clear : function() {
			this.$element.val('');
			this.$elementFilestyle.find(':text').val('');
			this.$elementFilestyle.find('.badge').remove();
		},

		destroy : function() {
			this.$element.removeAttr('style').removeData('filestyle');
			this.$elementFilestyle.remove();
		},

		disabled : function(value) {
			if (value === true || value === false) {
				this.options.disabled = value;
				this.$element.prop('disabled', this.options.disabled);
				this.$elementFilestyle.find('label').prop('disabled', this.options.disabled);

				if (this.options.disabled)
					this.$elementFilestyle.find('label').css('opacity', '0.65');
				else
					this.$elementFilestyle.find('label').css('opacity', '1');
			} else {
				return this.options.disabled;
			}
		},

		dragdrop : function(value) {
			if (value === true || value === false) {
				this.options.dragdrop = value;
			} else {
				return this.options.dragdrop;
			}
		},

		buttonBefore : function(value) {
			if (value === true) {
				if (!this.options.buttonBefore) {
					this.options.buttonBefore = value;
					if (this.options.input) {
						this.$elementFilestyle.remove();
						this.constructor();
						this.pushNameFiles();
					}
				}
			} else if (value === false) {
				if (this.options.buttonBefore) {
					this.options.buttonBefore = value;
					if (this.options.input) {
						this.$elementFilestyle.remove();
						this.constructor();
						this.pushNameFiles();
					}
				}
			} else {
				return this.options.buttonBefore;
			}
		},
		
		input : function(value) {
			if (value === true) {
				if (!this.options.input) {
					this.options.input = value;

					if (this.options.buttonBefore) {
						this.$elementFilestyle.append(this.htmlInput());
					} else {
						this.$elementFilestyle.prepend(this.htmlInput());
					}

					this.pushNameFiles();
					this.$elementFilestyle.find('.group-span-filestyle').addClass('input-group-btn');
				}
			} else if (value === false) {
				if (this.options.input) {
					this.options.input = value;
					this.$elementFilestyle.find(':text').remove();
					this.$elementFilestyle.find('.group-span-filestyle').removeClass('input-group-btn');
				}
			} else {
				return this.options.input;
			}
		},

		size : function(value) {
			if (value !== undefined) {
				this.options.size = value;
				var btn = this.$elementFilestyle.find('label'), input = this.$elementFilestyle.find('input');

				btn.removeClass('btn-lg btn-sm');
				input.removeClass('form-control-lg form-control-sm');
				if (this.options.size != 'nr') {
					btn.addClass('btn-' + this.options.size);
					input.addClass('form-control-' + this.options.size);
				}
			} else {
				return this.options.size;
			}
		},
		
		placeholder : function(value) {
			if (value !== undefined) {
				this.options.placeholder = value;
				this.$elementFilestyle.find('input').attr('placeholder', value);
			} else {
				return this.options.placeholder;
			}
		},		

		text : function(value) {
			if (value !== undefined) {
				this.options.text = value;
				this.$elementFilestyle.find('label .text').html(this.options.text);
			} else {
				return this.options.text;
			}
		},
		
		btnClass : function(value) {
			if (value !== undefined) {
				this.options.btnClass = value;
				this.$elementFilestyle.find('label').attr({
					'class' : 'btn ' + this.options.btnClass + ' btn-' + this.options.size
				});
			} else {
				return this.options.btnClass;
			}
		},

		badge : function(value) {
			if (value === true) {
				this.options.badge = value;
				var files = this.pushNameFiles();
				this.$elementFilestyle.find('label').append(' <span class="badge '+this.options.badgeName+'">' + files.length + '</span>');
			} else if (value === false) {
				this.options.badge = value;
				this.$elementFilestyle.find('.badge').remove();
			} else {
				return this.options.badge;
			}
		},

		badgeName : function(value) {
			if (value !== undefined) {
				this.options.badgeName = value;
				this.$elementFilestyle.find('.badge').attr({
					'class' : 'badge ' + this.options.badgeName
				});
			} else {
				return this.options.badgeName;
			}
		},

		htmlIcon : function(value) {
			if (value !== undefined) {
				this.options.htmlIcon = value;
			}

			return this.options.htmlIcon;
		},

		htmlInput : function() {
			if (this.options.input) {
				return '<input type="text" class="form-control ' + (this.options.size == 'nr' ? '' : 'form-control-' + this.options.size) + '" placeholder="'+ this.options.placeholder +'" disabled> ';
			} else {
				return '';
			}
		},

		// puts the name of the input files
		// return files
		pushNameFiles : function() {
			var content = '', files = [];
			if (this.$element[0].files === undefined) {
				files[0] = {
					'name' : this.$element[0] && this.$element[0].value
				};
			} else {
				files = this.$element[0].files;
			}

			for (var i = 0; i < files.length; i++) {
				content += files[i].name.split("\\").pop() + ', ';
			}

			if (content !== '') {
				this.$elementFilestyle.find(':text').val(content.replace(/\, $/g, ''));
			} else {
				this.$elementFilestyle.find(':text').val('');
			}
			
			return files;
		},

		constructor : function() {
			var _self = this, 
				html = '', 
				id = _self.$element.attr('id'), 
				files = [], 
				btn = '', 
				$label;

			if (id === '' || !id) {
				id = 'filestyle-' + nextId;
				_self.$element.attr({
					'id' : id
				});
                nextId++;
			}

			btn = '<span class="group-span-filestyle ' + (_self.options.input ? 'input-group-btn' : '') + '">' + 
			  '<label for="' + id + '" style="margin-bottom: 0;" class="btn ' + _self.options.btnClass + ' ' +
			(_self.options.size == 'nr' ? '' : 'btn-' + _self.options.size) + '" ' + 
			(_self.options.disabled || _self.$element.attr('disabled') ? ' disabled="true"' : '') + '>' + 
			_self.htmlIcon() + '<span class="buttonText">' + _self.options.text + '</span>' + 
			  '</label>' + 
			  '</span>';
			
			html = _self.options.buttonBefore ? btn + _self.htmlInput() : _self.htmlInput() + btn;
			_self.$elementFilestyle = $('<div class="bootstrap-filestyle input-group"><div name="filedrag"></div>' + html + '</div>');
            //_self.$elementFilestyle = $('<div class="bootstrap-filestyle input-group">' + html + '</div>');
			_self.$elementFilestyle.find('.group-span-filestyle').attr('tabindex', "0").keypress(function(e) {
			if (e.keyCode === 13 || e.charCode === 32) {
				_self.$elementFilestyle.find('label').click();
					return false;
				}
			});

			// hidding input file and add filestyle
			_self.$element.css({
				'position' : 'absolute',
				'clip' : 'rect(0px 0px 0px 0px)' // using 0px for work in IE8
			}).attr('tabindex', "-1").after(_self.$elementFilestyle);

			_self.$elementFilestyle.find(_self.options.buttonBefore ? 'label' : ':input').css({
				'border-top-left-radius': '.25rem',
				'border-bottom-left-radius': '.25rem'
			});

			_self.$elementFilestyle.find('[name="filedrag"]').css({
				position: 'absolute',
				width: '100%',
				height: _self.$elementFilestyle.height()+'px',
				'z-index': -1
			});

			if (_self.options.disabled || _self.$element.attr('disabled')) {
				_self.$element.attr('disabled', 'true');
				if (_self.options.disabled)
					_self.$elementFilestyle.find('label').css('opacity', '0.65');
				else
					_self.$elementFilestyle.find('label').css('opacity', '1');
			}

			// Getting input file value
			_self.$element.change(function () {
				var files = _self.pushNameFiles();
				if (_self.options.badge) {
					if (_self.$elementFilestyle.find('.badge').length == 0) {
						_self.$elementFilestyle.find('label').append(' <span class="badge '+_self.options.badgeName+'">' + files.length + '</span>');
					} else if (files.length == 0) {
						_self.$elementFilestyle.find('.badge').remove();
					} else {
						_self.$elementFilestyle.find('.badge').html(files.length);
					}
				} else {
					_self.$elementFilestyle.find('.badge').remove();
				}

				_self.options.onChange(files);
			});

			// Check if browser is Firefox
			if (window.navigator.userAgent.search(/firefox/i) > -1) {
				// Simulating choose file for firefox
				_self.$elementFilestyle.find('label').click(function() {
					_self.$element.click();
					return false;
				});
			}

			/** DRAG AND DROP EVENTS **/
			$(document)
				.on('dragover', function (e) {
					e.preventDefault();
				    e.stopPropagation();
				    if (_self.options.dragdrop) {
				    	$('[name="filedrag"]').css('z-index', '9');
				    }
				})
				.on('drop', function (e) {
					e.preventDefault();
				    e.stopPropagation();
				    if (_self.options.dragdrop) {
				  		$('[name="filedrag"]').css('z-index', '-1');
				    }
				});

			_self.$elementFilestyle.find('[name="filedrag"]')
				.on('dragover',
				    function (e) {
				        e.preventDefault();
                        e.stopPropagation();
                       // $(e).css('border', '2px solid black');
				    }
				)
				.on('dragenter',
				    function (e) {
				        e.preventDefault();
                        e.stopPropagation();
                        $(e.currentTarget).css('border', '3px solid #06ff0033');
                        console.log(e.currentTarget);
				    }
                )
                .on('dragleave',
                function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                    $(e.currentTarget).css('border', 'none');
                    console.log(e.currentTarget);
                }
                )
				.on('drop',
				    function (e) {
				        if (e.originalEvent.dataTransfer && !_self.options.disabled && _self.options.dragdrop) {
				            if (e.originalEvent.dataTransfer.files.length) {
				                e.preventDefault();
				                e.stopPropagation();
				                _self.$element[0].files = e.originalEvent.dataTransfer.files;
				                var files = _self.pushNameFiles();
								if (_self.options.badge) {
									if (_self.$elementFilestyle.find('.badge').length == 0) {
										_self.$elementFilestyle.find('label').append(' <span class="badge '+_self.options.badgeName+'">' + files.length + '</span>');
									} else if (files.length == 0) {
										_self.$elementFilestyle.find('.badge').remove();
									} else {
										_self.$elementFilestyle.find('.badge').html(files.length);
									}
								} else {
									_self.$elementFilestyle.find('.badge').remove();
								}

				        		$('[name="filedrag"]').css('z-index', '-1');
				            }   
                        }
                        console.log('droped');
                        eval($(_self.$element[0]).attr('OnDrop'));
				    }
				);
		}
	};

	let old = $.fn.filestyle;

	$.fn.filestyle = function(option, value) {
		var get = '', element = this.each(function() {
			if ($(this).attr('type') === 'file') {
				var $this = $(this), data = $this.data('filestyle'), options = $.extend({}, $.fn.filestyle.defaults, option, typeof option === 'object' && option);

				if (!data) {
					$this.data('filestyle', ( data = new Filestyle(this, options)));
					data.constructor();
				}

				if ( typeof option === 'string') {
					get = data[option](value);
				}
			}
		});

		if ( typeof get !== undefined) {
			return get;
		} else {
			return element;
		}
	};

	/*$.fn.filestyle.defaults = {
		'text' : 'Odaberi dokument',
        'htmlIcon': '',
        'btnClass': 'btn-default',
		'size' : 'nr',
		'input' : true,
		'badge' : true,
		'badgeName': 'badge-light',
		'buttonBefore' : true,
		'dragdrop' : true,
		'disabled' : false,
		'placeholder': 'privuci fajl...',
        'onChange': function () {
            console.log('changed');}
	};*/
	$.fn.filestyle.defaults = {
		'text': 'Dodaj dokument',
		'htmlIcon': '<i class="iconFileUpload"></i>',
		'btnClass': 'btn controls headControls',
		'size': 'nr',
		'input': true,
		'badge': true,
		'badgeName': 'badge-light',
		'buttonBefore': true,
		'dragdrop': true,
		'disabled': false,
		'placeholder': 'privuci fajl...',
		'onChange': function () {
			console.log('upload file changed');
			OnUpload();
		}
	};	

	$.fn.filestyle.noConflict = function() {
		$.fn.filestyle = old;
		return this;
	};

	$(function() {
		$('.filestyle').each(function() {
			let $this = $(this), options = {
				'input' : $this.attr('data-input') !== 'false',
				'htmlIcon' : $this.attr('data-icon'),
				'buttonBefore' : $this.attr('data-buttonBefore') === 'true',
				'disabled' : $this.attr('data-disabled') === 'true',
				'size' : $this.attr('data-size'),
				'text' : $this.attr('data-text'),
				'btnClass' : $this.attr('data-btnClass'),
				'badge' : $this.attr('data-badge') === 'true',
				'dragdrop' : $this.attr('data-dragdrop') !== 'false',
				'badgeName' : $this.attr('data-badgeName'),
				'placeholder': $this.attr('data-placeholder')
			};

			$this.filestyle(options);
		});
	});
})(window.jQuery);

/*
skripta gleda prvi red i dodaje filter na osnovu inputa u tim redovima
radi za input type text i input type checkbox

 */
function DanijelTable(tableselector, onRowLosingFocus) {
        DodajNoviRed(tableselector);
        DodajFilterRow(tableselector);
    PostaviSortiranje(tableselector, "", 0);
    SetClickEvent(tableselector);
    $(tableselector + ' tbody').scrollTop(10000);
    $('#newrow2').hide();
}
function DodajFilterRow(tableselector) {
    $(tableselector).children('#filterrow').remove();
    var trhtml = '<tr id="filterrow">';
    $(tableselector + ' tbody tr:first').children().each(function (i, td) {
        //console.log(i);
        var input = $(td).find('input:not(:hidden)');

        if (input == 'undefined') {
            //console.log('inputundefined');
            trhtml = trhtml + "<td style='padding:0px' id='ncolumn'></td>";
            return true;
        }
        var inputtype = $(input).attr('type');
        if (typeof (inputtype) == 'undefined') {
            //console.log('inputtypeundefined');
            if ($(td).attr('id') == 'ncolumn') {
                trhtml = trhtml + "<td style='padding:0px' id='ncolumn'><span class='glyphicon glyphicon-filter'></span></td>";
            }
            else {
                trhtml = trhtml + "<td style='padding:0px' id='ncolumn'></td>";
            }
            return true;
        }
        else if (inputtype == 'text' || inputtype == 'password') {
            var inputid = $(input).attr('id');
            //console.log('inputtype:text');
            trhtml = trhtml + "<td style='padding:0px' class='tdtext'><input id=" + inputid + " class='form-control filterinput' type='text' style='width:100%;border:none'/></td>";
            return true;
        }
        else if (inputtype == 'checkbox') {
            var inputid = $(input).attr('id');
            //console.log('inputtype:checkbox');
            trhtml = trhtml + "<td style='padding:0px' class='tdcheckbox'><input id=" + inputid + " class='filterinput' type='checkbox'/></td>";
            return true;
        }
        //         console.log(trhtml);

    });
    var trhtml = trhtml + '</tr>';
    $(tableselector + ' thead').append(trhtml);
   /* $("#filterrow input").on('change', function (pinput) {
        alert($(pinput));
        $(pinput).attr('Changed', 'true');
    });*/
  /*  $("#filterrow input").on('keyup change', function (pinput) {
        $(tableselector + ' tbody tr').css('display', '');
        $("#newrowtemplate").css('display', 'none');
        $("#filterrow input").each(function (i, pinput) {
            var vfinputtype = $(pinput).attr('type');
            var vfinputid = $(pinput).attr('id');
            var vfinputvalue = '';
            if (vfinputtype == 'text') {
                vfinputvalue = $(pinput).val();
            }
            else if (vfinputtype == 'checkbox') {
                vfinputvalue = $(pinput).prop('checked');
            }
            console.log('vinputid:' + vfinputid + ',vfinputvalue:' + vfinputvalue);
            $(tableselector + ' tbody tr').each(function (i, row) {
                var vrow = $(row);
                if (vrow.attr('id').indexOf('new') != -1) {
                    return true;
                }
                if (vrow.attr('id') == 'newrowtemplate') {
                    $(vrow).css('display', 'none');
                    return true;
                }
                if ($(vrow).css('display') == 'none') {
                    return true;
                }
                var vinput = vrow.find('input[id*="' + vfinputid + '"]');
                var vinputtype = $(vinput).attr('type');
                var vinputid = $(vinput).attr('id');
                var vinputvalue = '-1';
                if (vinputtype == 'text' || vinputtype == 'password') {
                    vinputvalue = $(vinput).val();
                }
                else if (vinputtype == 'checkbox') {
                    vinputvalue = $(vinput).prop('checked');
                }
                else {
                    return true;
                }
                $(vrow).css('display', '');
                if (vfinputvalue == '') {
                    return true;
                }
                if (vinputid == vfinputid) {
                    if (vinputvalue.toString().toLowerCase().indexOf(vfinputvalue.toString().toLowerCase()) == -1) {
                        $(vrow).css('display', 'none');
                        return true;
                    }
                }
            });
        });
    });*/
    $('#filterrow :input').css('background', 'transparent');//nek su providni
    $('#filterrow :input').attr('placeholder', '...kucaj za pretragu');
}
function DodajNoviRed(tableselector) {
    //console.log('DodajNoviRed');
    var newrow = $("#newrowtemplate").html();
    $("#newrow").attr("id", "editrow");
    $("#newrow2").attr("id", "newrow");
    if ($('#newrow').length < 1) {
        $('<tr id="newrow">' + newrow + '</tr>').insertBefore('#newrowtemplate');
    }
    $('<tr id="newrow2">' + newrow + '</tr>').insertBefore('#newrowtemplate');
    $('#newrow').find("#nimage").attr("src", "/Content/Images/plus.png");
    $('#newrow').find("#nimage").show();
    PostaviEvente(tableselector);

}
function PostaviEvente(tableselector) {
    $(tableselector).find('input').css('background', 'transparent');
    $(tableselector).on('rowLosingFocus', function (event, ptr) {
        onRowLosingFocus(ptr);
    });
    SetClickEvent(tableselector);
    $(tableselector + ' tbody').scrollTop(10000);
    $(tableselector + ' input').focusout(function () {
        if ($(this).is(':checkbox')) {
            $(this).css('box-shadow', 'none');
        }
        else {
            $(this).css('background', 'transparent none repeat scroll 0% 0%');
        }
    })
    $(tableselector + ' input').focusin(function () {
        if ($(this).is(':checkbox')) {

            $(this).css('box-shadow', '0px 0px 3px 2px #b0b0b0');
        }
        else {
            $(this).css('background', 'white');
        }
    });
    //ako je escape da vrati staru vrijednost iz taga title
    $(function () {
        $(tableselector + ' :input').keydown(function (e) {
           // console.log('keydown:' + e.keyCode );
            if (e.keyCode == 27) {//escape
                //console.log('escape pritisnut');
                var attr = $(this).attr('StaraVrijednost');
                if (typeof attr !== typeof undefined && attr !== false) {
                    $(this).val($(this).attr('StaraVrijednost'));
                }
                //ako je combobox tu koristimo atribut sifru 
                var attr2 = $(this).attr('StaraSifra');
                if (typeof attr2 !== typeof undefined && attr2 !== false) {
                    $(this).attr('Sifra', $(this).attr('StaraSifra'));
                }
            }
        });
    });
}
function SetClickEvent(tableselector) {
    //Click event
    $(tableselector + ' tr td').click(function () {
        if ($(this).parent().hasClass('rowFocus'))
            return;
        //alert('click occur');
        if ($(tableselector + ' tr').hasClass('rowFocus')) {
            $(tableselector).trigger('rowLosingFocus', $(tableselector + ' tr.rowFocus'))
        }
        $(this).parent().addClass('rowFocus');
    });
    $(tableselector + ' tr td :input').focus(function () {
        if ($(this).closest('tr').hasClass('rowFocus'))
            return;
        //alert('click occur');
        if ($(tableselector + ' tr').hasClass('rowFocus')) {
            $(tableselector).trigger('rowLosingFocus', $(tableselector + ' tr.rowFocus'))
        }
        // $(this).parent().addClass('rowFocus');
        $(this).closest('tr').addClass('rowFocus');
        //novo
        if ($('#newrow').hasClass('rowFocus') || $('#newrow2').hasClass('rowFocus')) {
            $('#newrow2').show();
        }
        else {
            $('#newrow2').hide();
        }
    });
}
function AnaimirajTr(ptr) {
    var backgroundColor = "rgb(85, 249, 0,0.2)";
    $(ptr).find("#nimage").fadeIn(300);
    //$(ptr).find("#nimage").fadeOut(300);
    var oldBackground = $(ptr).css('background-color');
    $(ptr).find("input").css('background', 'transparent');
    $(ptr).animate({
        backgroundColor: backgroundColor
    });
    $(ptr).animate({
        backgroundColor: oldBackground
    });
}
function AnaimirajInput(pinput) {
    var backgroundColor = "rgb(85, 249, 0)";
    var oldBackground = $(pinput).css('background-color');
    $(pinput).animate({
        backgroundColor: backgroundColor
    },200);
    $(pinput).animate({
        backgroundColor: oldBackground
    },200);
}
function PostaviSortiranje(tabela, KolonaRenum, DefaultSortColIndex) {
    $( tabela).css('cursor', 'pointer');
    var kolone = $( tabela + ' > thead > tr:eq(0) > th');
    if (KolonaRenum.length > 0) kolone = kolone.not(":eq(" + KolonaRenum + ")");
    kolone.click(function () {
        if (KolonaRenum.length > 0) {
            if ($(this).index() === KolonaRenum) return;
        }
        $(this).parent().find('span').remove();
        if (this.asc) {
            $(this).append('<span class="glyphicon glyphicon-sort-by-attributes-alt"></span>');
        }
        else {
            $(this).append('<span class="glyphicon glyphicon-sort-by-attributes"></span>');
        }
        //var table = $(this).parents('table').eq(0);//neradi sa float headers
        var table = $(tabela);
        var rows, i;
        if (DefaultSortColIndex >= 0) {
            rows = table.find('tbody > tr').filter('[NR!="1"]').toArray().sort(comparer(DefaultSortColIndex));
            for (i = 0; i < rows.length; i++) {
                table.append(rows[i]);
                table.append(table.find('tbody > tr').filter('[NR="1"]'));
            }
        }

        rows = table.find('tbody > tr').filter('[NR!="1"]').toArray().sort(comparer($(this).index()));
        this.asc = !this.asc;
        if (!this.asc) rows = rows.reverse();
        for (i = 0; i < rows.length; i++) {
            table.append(rows[i]);
            table.append(table.find('tbody > tr').filter('[NR="1"]'));
        }
        $('#tUsers #newrow').insertAfter($(tabela+' tr:last'));
        $('#tUsers #newrow2').insertAfter($(tabela +' tr:last'));
        $('#tUsers #newrowtemplate').insertAfter($(tabela +' tr:last'));
    });

   /* $( tabela + ' > thead > tr:eq(0) > th').mouseover(function () {
        $(this).css('color', 'black')
    });

    $( tabela + ' > thead > tr:eq(0) > th').mouseout(function () {
        $(this).css('color','');
    });*/

}
function comparer(index) {
    return function (a, b) {
        try {
            var valA = getCellValue(a, index), valB = getCellValue(b, index);
            var bDatum = false;
            var BrojTacakaA = (valA.split(".").length - 1);
            var BrojTacakaB = (valB.split(".").length - 1);
            if ((valA.length === 10 && BrojTacakaA === 2) || (valA.length === 11 && BrojTacakaA === 3)) bDatum = true;
            if ((valB.length === 10 && BrojTacakaB === 2) || (valB.length === 11 && BrojTacakaB === 3)) bDatum = true;
            if (bDatum) {
                var valAdat = Datum_YYYY_MM_DD(valA);
                var valBdat = Datum_YYYY_MM_DD(valB);
                if (valAdat !== "") valA = valAdat;
                if (valBdat !== "") valB = valBdat;
                return valA.toString().localeCompare(valB);
            }
            else {
                var valAnum = valA.replace('.', '').replace(',', '.');
                var valBnum = valB.replace('.', '').replace(',', '.');
                if ($.isNumeric(valAnum) && $.isNumeric(valBnum)) return valAnum - valBnum;
                else return valA.toString().localeCompare(valB);
            }
        }
        catch (err) {

        }
    }
}
function getCellValue(row, index) {
    var i1 = $(row).children('td:eq(' + index + ')').find('input:eq(0)');
    if (i1.attr("type") === "checkbox") {
        return i1.prop("checked").toString();
    }
    else {
        return i1.val();
    }

}
function loader_start2(element) {
    var light = $(element);
    $(light).block({
        message: '<i class="fas fa-spinner fa-spin"></i>',
        overlayCSS: {
            backgroundColor: '#fff',
            opacity: 0.8,
            cursor: 'wait'
        },
        css: {
            border: 0,
            padding: 0,
            backgroundColor: 'none'
        }
    });
}
function loader_stop2(element) {
    var light = $(element);
    $(light).unblock();
}
$(document).on('keydown', ':tabbable', function (e) {
    //onsole.log(e.target.localName);
    //onsole.log(e.target.localName == 'textarea' );
    if (e.target.localName == 'textarea' || e.target.localName == 'div') {
        return;
    }
    if (e.which == 13 || e.keyCode == 13) {
        e.preventDefault();
        var $canfocus = $(':tabbable:visible')
        var index = $canfocus.index(document.activeElement) + 1;
        if (index >= $canfocus.length) index = 0;
        $canfocus.eq(index).focus();
    }

});
function OnChange(object) {
    $(object).closest('tr').attr('changed', true);
}
function CheckForChanges(ptr) {
    var result = false;
    $(ptr).find(':input:not(:button)').each(function (a) {
        if ($(this).attr('type') == 'checkbox') {
            if (Number($(this).prop('checked')) != Number($(this).attr('staravrijednost'))) {
                result = true;
               // console.log($(this).attr('id') + ',' + Number($(this).prop('checked')) + ',' + $(this).attr('staravrijednost'));
            }
        }
        else {
            if ($(this).val() != $(this).attr('staravrijednost')) {
                result = true;
               // console.log($(this).attr('id') + ',' + $(this).val() + ',' + $(this).attr('staravrijednost') );
            }
               
        }
    });
    return result;
}
function DropDownButton() {
    $('.input-group-addon').click(function () {
        $(this).closest('.input-group').find('input[type=text]').focus();
        var e = jQuery.Event("keydown", { keyCode: 20 });
        $(this).closest('.input-group').find('input[type=text]').trigger(e);
        tmpSvi = true;
    });
}
function PageDownUpEvent(DajPodatke) {
   /* $(function () {
        $('#currentPage').unbind('keydown');
        $('#currentPage').keydown(function (e) {
            if (e.keyCode == 34) {//pageDown
                currentPage = parseInt(currentPage) + 1;
                DajPodatke();

            } else if (e.keyCode == 33) {//page up
                if (currentPage > 1)
                    currentPage = parseInt(currentPage) - 1;
                DajPodatke();
            }
           
        });
    });*/
}
function PostaviPagerEvente(DajPodatke) {
    $("#next").click(function () {
        currentPage = parseInt(currentPage) + 1;
        DajPodatke();
    });
    $("#previous").click(function () {
        currentPage = parseInt(currentPage) - 1;
        DajPodatke();
    });
    $("#currentPage").focusout(function () {
        console.log('currentPage focus out');
        currentPage = $("#currentPage").val();
        DajPodatke();
    });
}
function KreirajTabelu(tableid, sql,loaderid) {
   // var tableid = "#tSSNabavka";
    //var sql = `select top 1 InvBroj 'Inventurni broj',LEFT(CONVERT(VARCHAR, DatumN, 104), 10)  'Datum nabavke' from tSSNabavka where Firma=0`;
   // var poruka = '';
    //  console.log(sql);
   // loader_start2($(loaderid));
    $.ajax({
        url: "/json/GetData", dataType: 'json', data: { sql: sql, database: 'SQLSredstva' },
        success: function (data) {
            //alert(data);
            $(tableid).empty();
            if (JSON.parse(data).length == 0) { return; }
            var trHTML = '';
            var thHTML = '<thead>';
            $.each(Object.keys(JSON.parse(data)[0]), function (i, item) {
                thHTML += '<th>' + item + '</th>';
            });
            thHTML += '</thead>';
            $(tableid).append(thHTML);
            $(tableid).append('<tbody></tbody>');
            // console.log(thHTML);
            var trHTML = '';
            $.each(JSON.parse(data), function (i, item) {
                trHTML += `<tr>`;
                $.each(item, function (i, item) {
                   // console.log(item);
                    //console.log(String(item) == String('true'));
                    if (String(item) == 'true'  ) {
                        trHTML += '<td> <input type="checkbox" checked/></td>';
                    }
                    else if (String(item) == 'false')
                    {
                        trHTML += '<td> <input type="checkbox"/></td>';
                    }
                    else {
                        trHTML += '<td>' + item + '</td>';
                    }
                });
                trHTML += `</tr>`;
            });
            $(tableid + ' tbody').append(trHTML);
           // $(tableid).append('<tfoot></tfoot>');
            //console.log(trHTML);
           // loader_stop2($(loaderid));
        },
        error: function (xhr, ajaxOptions, thrownError) {
          //  loader_stop2($(loaderid));
            alert(thrownError);
        }
    });
}
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}
function PageDownUpEvent() {
   /* $(function () {
        $('#currentPage').unbind();
        $('#currentPage').keydown(function (e) {
            if (e.keyCode == 34) {//pageDown
                currentPage = parseInt(currentPage) + 1;

            } else if (e.keyCode == 33) {//page up
                if (currentPage > 1)
                    currentPage = parseInt(currentPage) - 1;
            }
           
        });
    });*/
}
function scrollbottom() {
    $('.mainpanel-body').scrollTop($('.mainpanel-body')[0].scrollHeight);
}
/*combobox*/
$.widget('custom.mcautocomplete', $.ui.autocomplete, {
    _create: function () {
       
        this._super();
        this.widget().menu("option", "items", "> :not(.ui-widget-header)");
    },
    _renderMenu: function (ul, items) {
        let columnname = $(this.element).attr("columnname");
        var self = this,
            thead;
        if (this.options.showHeader) {
            table = $(`<div class="ui-widget-header ${columnname}" style="width:100%"></div>`);
            $.each(this.options.columns, function (index, item) {
                table.append('<span style="padding:0 4px;float:left;width:' + item.width + ';">' + item.name + '</span>');
            });
            table.append('<div style="clear: both;"></div>');
            ul.append(table);
        }
        $.each(items, function (index, item) {
            self._renderItem(ul, item);
        });
    },
    _renderItem: function (ul, item) {
        let columnname = $(this.element).attr("columnname");
        var t = '',
            result = '';
        $.each(this.options.columns, function (index, column) {
            t += '<span style="padding:0 4px;float:left;width:' + column.width + ';" class=" mcautocomplete ' + columnname +'">' + item[column.valueField ? column.valueField : index] + '</span>'
        });
        result = $('<li></li>')
            .data('ui-autocomplete-item', item)
            .append('<a class="mcacAnchor ' + columnname +'">' + t + '<div style="clear: both;"></div></a>')
            .appendTo(ul);
        return result;
    }
});
// Scroll
; (function ($, undefined) {
    'use strict';
    $.widget('ui.autocomplete', $.ui.autocomplete, {
        _resizeMenu: function () {
            var ul, lis, ulW, barW;
            if (isNaN(this.options.maxShowItems)) { return; }
            ul = this.menu.element
                .scrollLeft(0).scrollTop(0) // Resetovanje pozicije scroll-a
                .css({ overflowX: '', overflowY: '', width: '', maxHeight: '' }); // Restore
            lis = ul.children('li').css('whiteSpace', 'nowrap');

            if (lis.length > this.options.maxShowItems) {
                ulW = ul.prop('clientWidth');
                ul.css({
                    overflowX: 'hidden', overflowY: 'auto',
                    maxHeight: lis.eq(0).outerHeight() * this.options.maxShowItems + 1
                }); // 1px za Firefox
                barW = ulW - ul.prop('clientWidth');
                ul.width('+=' + barW);
            }

            // Originalni kod iz jquery.ui.autocomplete.js _resizeMenu()
            ul.outerWidth(Math.max(
                ul.outerWidth() + 1,
                this.element.outerWidth()
            ));
        }
    });

})(jQuery);

/*primjer sa artiklima
<input id="test" class="form-control text-box single-line" placeholder="kucaj za pretragu..." style="width:400px"/>
@section scripts {
    <script>
        $('#test').mcautocomplete({

            maxShowItems: 10,
            showHeader: true,
            columns: [{
                name: 'Šifra',
                width: '70px',
                valueField: 'ArSif'
                },
                {
                name: 'Artikal',
                width: '150px',
                valueField: 'ArNa1'
            }],
            select: function (event, ui) {
                this.value = (ui.item ? ui.item.ArNa1 : '');
                $(this).attr('Sifra', ui.item.ArSif);
                return false;
            },
            minLength: 0,
            source: function (request, response) {
                $.ajax({
                    url: "/json/GetData",
                    dataType: 'json',
                    data: {
                        sql: "select top 100 * from dbo.tArtikli where lower(ArNa1) like lower('%" + $(':focus').val()+"%')",
                        database: "SQLRobno"
                    },
                    success: function (data) {
                        // console.log(data);
                        var result;
                        if (!data || data.length === 0) {
                        } else {
                            result = data;
                        }
                        response(result);
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert(thrownError);
                    }
                });
            }
        });
    </script>
    }
*/
/**
			   _ _____           _          _     _      
			  | |  __ \         (_)        | |   | |     
	  ___ ___ | | |__) |___  ___ _ ______ _| |__ | | ___ 
	 / __/ _ \| |  _  // _ \/ __| |_  / _` | '_ \| |/ _ \
	| (_| (_) | | | \ \  __/\__ \ |/ / (_| | |_) | |  __/
	 \___\___/|_|_|  \_\___||___/_/___\__,_|_.__/|_|\___|
	 
	v1.6 - jQuery plugin created by Alvaro Prieto Lauroba
	
	Licences: MIT & GPL
	Feel free to use or modify this plugin as far as my full name is kept	
	
	If you are going to use this plug-in in production environments it is 
	strongly recommended to use its minified version: colResizable.min.js

*/

(function ($) {

	var d = $(document); 		//window object
	var h = $("head");			//head object
	var drag = null;			//reference to the current grip that is being dragged
	var tables = {};			//object of the already processed tables (table.id as key)
	var count = 0;				//internal count to create unique IDs when needed.	

	//common strings for packing
	var ID = "id";
	var PX = "px";
	var SIGNATURE = "JColResizer";
	var FLEX = "JCLRFlex";

	//short-cuts
	var I = parseInt;
	var M = Math;
	var ie = navigator.userAgent.indexOf('Trident/4.0') > 0;
	var S;
	try { S = sessionStorage; } catch (e) { }	//Firefox crashes when executed as local file system

	//append required CSS rules  
	h.append("<style type='text/css'>  .JColResizer{table-layout:fixed;} .JColResizer > tbody > tr > td, .JColResizer > tbody > tr > th{overflow:hidden;padding-left:0!important; padding-right:0!important;}  .JCLRgrips{ height:0px; position:relative;} .JCLRgrip{margin-left:-5px; position:absolute; z-index:5; } .JCLRgrip .JColResizer{position:absolute;background-color:red;filter:alpha(opacity=1);opacity:0;width:10px;height:100%;cursor: e-resize;top:0px} .JCLRLastGrip{position:absolute; width:1px; } .JCLRgripDrag{ border-left:1px dotted black;	} .JCLRFlex{width:auto!important;} .JCLRgrip.JCLRdisabledGrip .JColResizer{cursor:default; display:none;}</style>");


	/**
	 * Function to allow column resizing for table objects. It is the starting point to apply the plugin.
	 * @param {DOM node} tb - reference to the DOM table object to be enhanced
	 * @param {Object} options	- some customization values
	 */
	var init = function (tb, options) {
		var t = $(tb);				    //the table object is wrapped
		t.opt = options;                //each table has its own options available at anytime
		t.mode = options.resizeMode;    //shortcuts
		t.dc = t.opt.disabledColumns;
		if (t.opt.disable) return destroy(t);				//the user is asking to destroy a previously colResized table
		var id = t.id = t.attr(ID) || SIGNATURE + count++;	//its id is obtained, if null new one is generated		
		t.p = t.opt.postbackSafe; 							//short-cut to detect postback safe 		
		if (!t.is("table") || tables[id] && !t.opt.partialRefresh) return; 		//if the object is not a table or if it was already processed then it is ignored.
		if (t.opt.hoverCursor !== 'e-resize') h.append("<style type='text/css'>.JCLRgrip .JColResizer:hover{cursor:" + t.opt.hoverCursor + "!important}</style>");  //if hoverCursor has been set, append the style
		t.addClass(SIGNATURE).attr(ID, id).before('<div class="JCLRgrips"/>');	//the grips container object is added. Signature class forces table rendering in fixed-layout mode to prevent column's min-width
		t.g = []; t.c = []; t.w = t.width(); t.gc = t.prev(); t.f = t.opt.fixed;	//t.c and t.g are arrays of columns and grips respectively				
		if (options.marginLeft) t.gc.css("marginLeft", options.marginLeft);  	//if the table contains margins, it must be specified
		if (options.marginRight) t.gc.css("marginRight", options.marginRight);  	//since there is no (direct) way to obtain margin values in its original units (%, em, ...)
		t.cs = I(ie ? tb.cellSpacing || tb.currentStyle.borderSpacing : t.css('border-spacing')) || 2;	//table cellspacing (not even jQuery is fully cross-browser)
		t.b = I(ie ? tb.border || tb.currentStyle.borderLeftWidth : t.css('border-left-width')) || 1;	//outer border width (again cross-browser issues)
		// if(!(tb.style.width || tb.width)) t.width(t.width()); //I am not an IE fan at all, but it is a pity that only IE has the currentStyle attribute working as expected. For this reason I can not check easily if the table has an explicit width or if it is rendered as "auto"
		tables[id] = t; 	//the table object is stored using its id as key	
		createGrips(t);		//grips are created 

	};


	/**
	 * This function allows to remove any enhancements performed by this plugin on a previously processed table.
	 * @param {jQuery ref} t - table object
	 */
	var destroy = function (t) {
		var id = t.attr(ID), t = tables[id];		//its table object is found
		if (!t || !t.is("table")) return;			//if none, then it wasn't processed	 
		t.removeClass(SIGNATURE + " " + FLEX).gc.remove();	//class and grips are removed
		delete tables[id];						//clean up data
	};


	/**
	 * Function to create all the grips associated with the table given by parameters 
	 * @param {jQuery ref} t - table object
	 */
	var createGrips = function (t) {

		var th = t.find(">thead>tr:first>th,>thead>tr:first>td"); //table headers are obtained
		if (!th.length) th = t.find(">tbody>tr:first>th,>tr:first>th,>tbody>tr:first>td, >tr:first>td");	 //but headers can also be included in different ways
		th = th.filter(":visible");					//filter invisible columns
		t.cg = t.find("col"); 						//a table can also contain a colgroup with col elements		
		t.ln = th.length;							//table length is stored	
		if (t.p && S && S[t.id]) memento(t, th);		//if 'postbackSafe' is enabled and there is data for the current table, its coloumn layout is restored
		th.each(function (i) {						//iterate through the table column headers			
			var c = $(this); 						//jquery wrap for the current column		
			var dc = t.dc.indexOf(i) != -1;           //is this a disabled column?
			var g = $(t.gc.append('<div class="JCLRgrip"></div>')[0].lastChild); //add the visual node to be used as grip
			g.append(dc ? "" : t.opt.gripInnerHtml).append('<div class="' + SIGNATURE + '"></div>');
			if (i == t.ln - 1) {                        //if the current grip is the las one 
				g.addClass("JCLRLastGrip");         //add a different css class to stlye it in a different way if needed
				if (t.f) g.html("");                 //if the table resizing mode is set to fixed, the last grip is removed since table with can not change
			}
			g.bind('touchstart mousedown', onGripMouseDown); //bind the mousedown event to start dragging 

			if (!dc) {
				//if normal column bind the mousedown event to start dragging, if disabled then apply its css class
				g.removeClass('JCLRdisabledGrip').bind('touchstart mousedown', onGripMouseDown);
			} else {
				g.addClass('JCLRdisabledGrip');
			}

			g.t = t; g.i = i; g.c = c; c.w = c.width();		//some values are stored in the grip's node data as shortcut
			t.g.push(g); t.c.push(c);						//the current grip and column are added to its table object
			c.width(c.w).removeAttr("width");				//the width of the column is converted into pixel-based measurements
			g.data(SIGNATURE, { i: i, t: t.attr(ID), last: i == t.ln - 1 });	 //grip index and its table name are stored in the HTML 												
		});
		t.cg.removeAttr("width");	//remove the width attribute from elements in the colgroup 

		t.find('td, th').not(th).not('table th, table td').each(function () {
			$(this).removeAttr('width');	//the width attribute is removed from all table cells which are not nested in other tables and dont belong to the header
		});
		if (!t.f) {
			t.removeAttr('width').addClass(FLEX); //if not fixed, let the table grow as needed
		}
		syncGrips(t); 				//the grips are positioned according to the current table layout			
		//there is a small problem, some cells in the table could contain dimension values interfering with the 
		//width value set by this plugin. Those values are removed

	};


	/**
	 * Function to allow the persistence of columns dimensions after a browser postback. It is based in
	 * the HTML5 sessionStorage object, which can be emulated for older browsers using sessionstorage.js
	 * @param {jQuery ref} t - table object
	 * @param {jQuery ref} th - reference to the first row elements (only set in deserialization)
	 */
	var memento = function (t, th) {
		var w, m = 0, i = 0, aux = [], tw;
		if (th) {										//in deserialization mode (after a postback)
			t.cg.removeAttr("width");
			if (t.opt.flush) { S[t.id] = ""; return; } 	//if flush is activated, stored data is removed
			w = S[t.id].split(";");					//column widths is obtained
			tw = w[t.ln + 1];
			if (!t.f && tw) {							//if not fixed and table width data available its size is restored
				t.width(tw *= 1);
				if (t.opt.overflow) {				//if overfolw flag is set, restore table width also as table min-width
					t.css('min-width', tw + PX);
					t.w = tw;
				}
			}
			for (; i < t.ln; i++) {						//for each column
				aux.push(100 * w[i] / w[t.ln] + "%"); 	//width is stored in an array since it will be required again a couple of lines ahead
				th.eq(i).css("width", aux[i]); 	//each column width in % is restored
			}
			for (i = 0; i < t.ln; i++)
				t.cg.eq(i).css("width", aux[i]);	//this code is required in order to create an inline CSS rule with higher precedence than an existing CSS class in the "col" elements
		} else {							//in serialization mode (after resizing a column)
			S[t.id] = "";				//clean up previous data
			for (; i < t.c.length; i++) {	//iterate through columns
				w = t.c[i].width();		//width is obtained
				S[t.id] += w + ";";		//width is appended to the sessionStorage object using ID as key
				m += w;					//carriage is updated to obtain the full size used by columns
			}
			S[t.id] += m;							//the last item of the serialized string is the table's active area (width), 
			//to be able to obtain % width value of each columns while deserializing
			if (!t.f) S[t.id] += ";" + t.width(); 	//if not fixed, table width is stored
		}
	};


	/**
	 * Function that places each grip in the correct position according to the current table layout	 
	 * @param {jQuery ref} t - table object
	 */
	var syncGrips = function (t) {
		t.gc.width(t.w);			//the grip's container width is updated				
		for (var i = 0; i < t.ln; i++) {	//for each column
			var c = t.c[i];
			t.g[i].css({			//height and position of the grip is updated according to the table layout
				left: c.offset().left - t.offset().left + c.outerWidth(false) + t.cs / 2 + PX,
				height: t.opt.headerOnly ? t.c[0].outerHeight(false) : t.outerHeight(false)
			});
		}
	};



	/**
	* This function updates column's width according to the horizontal position increment of the grip being
	* dragged. The function can be called while dragging if liveDragging is enabled and also from the onGripDragOver
	* event handler to synchronize grip's position with their related columns.
	* @param {jQuery ref} t - table object
	* @param {number} i - index of the grip being dragged
	* @param {bool} isOver - to identify when the function is being called from the onGripDragOver event	
	*/
	var syncCols = function (t, i, isOver) {
		var inc = drag.x - drag.l, c = t.c[i], c2 = t.c[i + 1];
		var w = c.w + inc; var w2 = c2.w - inc;	//their new width is obtained					
		c.width(w + PX);
		t.cg.eq(i).width(w + PX);
		if (t.f) { //if fixed mode
			c2.width(w2 + PX);
			t.cg.eq(i + 1).width(w2 + PX);
		} else if (t.opt.overflow) {				//if overflow is set, incriment min-width to force overflow
			t.css('min-width', t.w + inc);
		}
		if (isOver) {
			c.w = w;
			c2.w = t.f ? w2 : c2.w;
		}
	};


	/**
	* This function updates all columns width according to its real width. It must be taken into account that the 
	* sum of all columns can exceed the table width in some cases (if fixed is set to false and table has some kind 
	* of max-width).
	* @param {jQuery ref} t - table object	
	*/
	var applyBounds = function (t) {
		var w = $.map(t.c, function (c) {			//obtain real widths
			return c.width();
		});
		t.width(t.w = t.width()).removeClass(FLEX);	//prevent table width changes
		$.each(t.c, function (i, c) {
			c.width(w[i]).w = w[i];				//set column widths applying bounds (table's max-width)
		});
		t.addClass(FLEX);						//allow table width changes
	};


	/**
	 * Event handler used while dragging a grip. It checks if the next grip's position is valid and updates it. 
	 * @param {event} e - mousemove event binded to the window object
	 */
	var onGripDrag = function (e) {
		if (!drag) return;
		var t = drag.t;		//table object reference 
		var oe = e.originalEvent.touches;
		var ox = oe ? oe[0].pageX : e.pageX;    //original position (touch or mouse)
		var x = ox - drag.ox + drag.l;	        //next position according to horizontal mouse position increment
		var mw = t.opt.minWidth, i = drag.i;	//cell's min width
		var l = t.cs * 1.5 + mw + t.b;
		var last = i == t.ln - 1;                 			//check if it is the last column's grip (usually hidden)
		var min = i ? t.g[i - 1].position().left + t.cs + mw : l;	//min position according to the contiguous cells
		var max = t.f ? 	//fixed mode?
			i == t.ln - 1 ?
				t.w - l :
				t.g[i + 1].position().left - t.cs - mw :
			Infinity; 								//max position according to the contiguous cells 
		x = M.max(min, M.min(max, x));				//apply bounding		
		drag.x = x; drag.css("left", x + PX); 	//apply position increment	
		if (last) {									//if it is the last grip
			var c = t.c[drag.i];					//width of the last column is obtained
			drag.w = c.w + x - drag.l;
		}
		if (t.opt.liveDrag) { 			//if liveDrag is enabled
			if (last) {
				c.width(drag.w);
				if (!t.f && t.opt.overflow) {			//if overflow is set, incriment min-width to force overflow
					t.css('min-width', t.w + x - drag.l);
				} else {
					t.w = t.width();
				}
			} else {
				syncCols(t, i); 			//columns are synchronized
			}
			syncGrips(t);
			var cb = t.opt.onDrag;							//check if there is an onDrag callback
			if (cb) { e.currentTarget = t[0]; cb(e); }		//if any, it is fired			
		}
		return false; 	//prevent text selection while dragging				
	};


	/**
	 * Event handler fired when the dragging is over, updating table layout
	 * @param {event} e - grip's drag over event
	 */
	var onGripDragOver = function (e) {

		d.unbind('touchend.' + SIGNATURE + ' mouseup.' + SIGNATURE).unbind('touchmove.' + SIGNATURE + ' mousemove.' + SIGNATURE);
		$("head :last-child").remove(); 				//remove the dragging cursor style	
		if (!drag) return;
		drag.removeClass(drag.t.opt.draggingClass);		//remove the grip's dragging css-class
		if (!(drag.x - drag.l == 0)) {
			var t = drag.t;
			var cb = t.opt.onResize; 	    //get some values	
			var i = drag.i;                 //column index
			var last = i == t.ln - 1;         //check if it is the last column's grip (usually hidden)
			var c = t.g[i].c;               //the column being dragged
			if (last) {
				c.width(drag.w);
				c.w = drag.w;
			} else {
				syncCols(t, i, true);	//the columns are updated
			}
			if (!t.f) applyBounds(t);	//if not fixed mode, then apply bounds to obtain real width values
			syncGrips(t);				//the grips are updated
			if (cb) { e.currentTarget = t[0]; cb(e); }	//if there is a callback function, it is fired
			if (t.p && S) memento(t); 	//if postbackSafe is enabled and there is sessionStorage support, the new layout is serialized and stored
		}
		drag = null;   //since the grip's dragging is over									
	};


	/**
	 * Event handler fired when the grip's dragging is about to start. Its main goal is to set up events 
	 * and store some values used while dragging.
	 * @param {event} e - grip's mousedown event
	 */
	var onGripMouseDown = function (e) {
		var o = $(this).data(SIGNATURE);			//retrieve grip's data
		var t = tables[o.t], g = t.g[o.i];			//shortcuts for the table and grip objects
		var oe = e.originalEvent.touches;           //touch or mouse event?
		g.ox = oe ? oe[0].pageX : e.pageX;            //the initial position is kept
		g.l = g.position().left;
		g.x = g.l;

		d.bind('touchmove.' + SIGNATURE + ' mousemove.' + SIGNATURE, onGripDrag).bind('touchend.' + SIGNATURE + ' mouseup.' + SIGNATURE, onGripDragOver);	//mousemove and mouseup events are bound
		h.append("<style type='text/css'>*{cursor:" + t.opt.dragCursor + "!important}</style>"); 	//change the mouse cursor
		g.addClass(t.opt.draggingClass); 	//add the dragging class (to allow some visual feedback)				
		drag = g;							//the current grip is stored as the current dragging object
		if (t.c[o.i].l) for (var i = 0, c; i < t.ln; i++) { c = t.c[i]; c.l = false; c.w = c.width(); } 	//if the colum is locked (after browser resize), then c.w must be updated		
		return false; 	//prevent text selection
	};


	/**
	 * Event handler fired when the browser is resized. The main purpose of this function is to update
	 * table layout according to the browser's size synchronizing related grips 
	 */
	var onResize = function () {
		for (var t in tables) {
			if (tables.hasOwnProperty(t)) {
				t = tables[t];
				var i, mw = 0;
				t.removeClass(SIGNATURE);   //firefox doesn't like layout-fixed in some cases
				if (t.f) {                  //in fixed mode
					t.w = t.width();        //its new width is kept
					for (i = 0; i < t.ln; i++) mw += t.c[i].w;
					//cell rendering is not as trivial as it might seem, and it is slightly different for
					//each browser. In the beginning i had a big switch for each browser, but since the code
					//was extremely ugly now I use a different approach with several re-flows. This works 
					//pretty well but it's a bit slower. For now, lets keep things simple...   
					for (i = 0; i < t.ln; i++) t.c[i].css("width", M.round(1000 * t.c[i].w / mw) / 10 + "%").l = true;
					//c.l locks the column, telling us that its c.w is outdated									
				} else {     //in non fixed-sized tables
					applyBounds(t);         //apply the new bounds 
					if (t.mode == 'flex' && t.p && S) {   //if postbackSafe is enabled and there is sessionStorage support,
						memento(t);                     //the new layout is serialized and stored for 'flex' tables
					}
				}
				syncGrips(t.addClass(SIGNATURE));
			}
		}

	};


	//bind resize event, to update grips position 
	$(window).bind('resize.' + SIGNATURE, onResize);


	/**
	 * The plugin is added to the jQuery library
	 * @param {Object} options -  an object that holds some basic customization values 
	 */
	$.fn.extend({
		colResizable: function (options) {
			var defaults = {

				//attributes:

				resizeMode: 'fit',                    //mode can be 'fit', 'flex' or 'overflow'
				draggingClass: 'JCLRgripDrag',	//css-class used when a grip is being dragged (for visual feedback purposes)
				gripInnerHtml: '',				//if it is required to use a custom grip it can be done using some custom HTML				
				liveDrag: false,				//enables table-layout updating while dragging	
				minWidth: 15, 					//minimum width value in pixels allowed for a column 
				headerOnly: false,				//specifies that the size of the the column resizing anchors will be bounded to the size of the first row 
				hoverCursor: "e-resize",  		//cursor to be used on grip hover
				dragCursor: "e-resize",  		//cursor to be used while dragging
				postbackSafe: false, 			//when it is enabled, table layout can persist after postback or page refresh. It requires browsers with sessionStorage support (it can be emulated with sessionStorage.js). 
				flush: false, 					//when postbakSafe is enabled, and it is required to prevent layout restoration after postback, 'flush' will remove its associated layout data 
				marginLeft: null,				//in case the table contains any margins, colResizable needs to know the values used, e.g. "10%", "15em", "5px" ...
				marginRight: null, 				//in case the table contains any margins, colResizable needs to know the values used, e.g. "10%", "15em", "5px" ...
				disable: false,					//disables all the enhancements performed in a previously colResized table	
				partialRefresh: false,			//can be used in combination with postbackSafe when the table is inside of an updatePanel,
				disabledColumns: [],            //column indexes to be excluded

				//events:
				onDrag: null, 					//callback function to be fired during the column resizing process if liveDrag is enabled
				onResize: null					//callback function fired when the dragging process is over
			}
			var options = $.extend(defaults, options);

			//since now there are 3 different ways of resizing columns, I changed the external interface to make it clear
			//calling it 'resizeMode' but also to remove the "fixed" attribute which was confusing for many people
			options.fixed = true;
			options.overflow = false;
			switch (options.resizeMode) {
				case 'flex': options.fixed = false; break;
				case 'overflow': options.fixed = false; options.overflow = true; break;
			}

			return this.each(function () {
				init(this, options);
			});
		}
	});
})(jQuery);


!(function () {
    "use strict";
    function e(e) {
        function t(t, n) {
            var s,
                h,
                k = t == window,
                y = n && void 0 !== n.message ? n.message : void 0;
            if (((n = e.extend({}, e.blockUI.defaults, n || {})), !n.ignoreIfBlocked || !e(t).data("blockUI.isBlocked"))) {
                if (
                    ((n.overlayCSS = e.extend({}, e.blockUI.defaults.overlayCSS, n.overlayCSS || {})),
                        (s = e.extend({}, e.blockUI.defaults.css, n.css || {})),
                        n.onOverlayClick && (n.overlayCSS.cursor = "pointer"),
                        (h = e.extend({}, e.blockUI.defaults.themedCSS, n.themedCSS || {})),
                        (y = void 0 === y ? n.message : y),
                        k && p && o(window, { fadeOut: 0 }),
                        y && "string" != typeof y && (y.parentNode || y.jquery))
                ) {
                    var m = y.jquery ? y[0] : y,
                        v = {};
                    e(t).data("blockUI.history", v), (v.el = m), (v.parent = m.parentNode), (v.display = m.style.display), (v.position = m.style.position), v.parent && v.parent.removeChild(m);
                }
                e(t).data("blockUI.onUnblock", n.onUnblock);
                var g,
                    I,
                    w,
                    U,
                    x = n.baseZ;
                (g = e(
                    r || n.forceIframe
                        ? '<iframe class="blockUI" style="z-index:2000;display:none;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="' + n.iframeSrc + '"></iframe>'
                        : '<div class="blockUI" style="display:none"></div>'
                )),
                    (I = e(
                        n.theme
                            ? '<div class="blockUI blockOverlay ui-widget-overlay" style="z-index:1999;display:none"></div>'
                            : '<div class="blockUI blockOverlay" style="z-index:1999;display:none;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>'
                    )),
                    n.theme && k
                        ? ((U = '<div class="blockUI ' + n.blockMsgClass + ' blockPage ui-dialog ui-widget ui-corner-all" style="z-index:' + (x + 10) + ';display:none;position:fixed">'),
                            n.title && (U += '<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">' + (n.title || "&nbsp;") + "</div>"),
                            (U += '<div class="ui-widget-content ui-dialog-content"></div>'),
                            (U += "</div>"))
                        : n.theme
                            ? ((U = '<div class="blockUI ' + n.blockMsgClass + ' blockElement ui-dialog ui-widget ui-corner-all" style="z-index:' + (x + 10) + ';display:none;position:absolute">'),
                                n.title && (U += '<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">' + (n.title || "&nbsp;") + "</div>"),
                                (U += '<div class="ui-widget-content ui-dialog-content"></div>'),
                                (U += "</div>"))
                            : (U = k
                                ? '<div class="blockUI ' + n.blockMsgClass + ' blockPage" style="z-index:2000;display:none;position:fixed"></div>'
                                : '<div class="blockUI ' + n.blockMsgClass + ' blockElement" style="z-index:2000;display:none;position:absolute"></div>'),
                    (w = e(U)),
                    y && (n.theme ? (w.css(h), w.addClass("ui-widget-content")) : w.css(s)),
                    n.theme || I.css(n.overlayCSS),
                    I.css("position", k ? "fixed" : "absolute"),
                    (r || n.forceIframe) && g.css("opacity", 0);
                var C = [g, I, w],
                    S = e(k ? "body" : t);
                e.each(C, function () {
                    this.appendTo(S);
                }),
                    n.theme && n.draggable && e.fn.draggable && w.draggable({ handle: ".ui-dialog-titlebar", cancel: "li" });
                var O = f && (!e.support.boxModel || e("object,embed", k ? null : t).length > 0);
                if (u || O) {
                    if ((k && n.allowBodyStretch && e.support.boxModel && e("html,body").css("height", "100%"), (u || !e.support.boxModel) && !k))
                        var E = d(t, "borderTopWidth"),
                            T = d(t, "borderLeftWidth"),
                            M = E ? "(0 - " + E + ")" : 0,
                            B = T ? "(0 - " + T + ")" : 0;
                    e.each(C, function (e, t) {
                        var o = t[0].style;
                        if (((o.position = "absolute"), 2 > e))
                            k
                                ? o.setExpression("height", "Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.support.boxModel?0:" + n.quirksmodeOffsetHack + ') + "px"')
                                : o.setExpression("height", 'this.parentNode.offsetHeight + "px"'),
                                k ? o.setExpression("width", 'jQuery.support.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"') : o.setExpression("width", 'this.parentNode.offsetWidth + "px"'),
                                B && o.setExpression("left", B),
                                M && o.setExpression("top", M);
                        else if (n.centerY)
                            k &&
                                o.setExpression(
                                    "top",
                                    '(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"'
                                ),
                                (o.marginTop = 0);
                        else if (!n.centerY && k) {
                            var i = n.css && n.css.top ? parseInt(n.css.top, 10) : 0,
                                s = "((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + " + i + ') + "px"';
                            o.setExpression("top", s);
                        }
                    });
                }
                if ((y && (n.theme ? w.find(".ui-widget-content").append(y) : w.append(y), (y.jquery || y.nodeType) && e(y).show()), (r || n.forceIframe) && n.showOverlay && g.show(), n.fadeIn)) {
                    var j = n.onBlock ? n.onBlock : c,
                        H = n.showOverlay && !y ? j : c,
                        z = y ? j : c;
                    n.showOverlay && I._fadeIn(n.fadeIn, H), y && w._fadeIn(n.fadeIn, z);
                } else n.showOverlay && I.show(), y && w.show(), n.onBlock && n.onBlock.bind(w)();
                if ((i(1, t, n), k ? ((p = w[0]), (b = e(n.focusableElements, p)), n.focusInput && setTimeout(l, 20)) : a(w[0], n.centerX, n.centerY), n.timeout)) {
                    var W = setTimeout(function () {
                        k ? e.unblockUI(n) : e(t).unblock(n);
                    }, n.timeout);
                    e(t).data("blockUI.timeout", W);
                }
            }
        }
        function o(t, o) {
            var s,
                l = t == window,
                a = e(t),
                d = a.data("blockUI.history"),
                c = a.data("blockUI.timeout");
            c && (clearTimeout(c), a.removeData("blockUI.timeout")), (o = e.extend({}, e.blockUI.defaults, o || {})), i(0, t, o), null === o.onUnblock && ((o.onUnblock = a.data("blockUI.onUnblock")), a.removeData("blockUI.onUnblock"));
            var r;
            (r = l ? e("body").children().filter(".blockUI").add("body > .blockUI") : a.find(">.blockUI")),
                o.cursorReset && (r.length > 1 && (r[1].style.cursor = o.cursorReset), r.length > 2 && (r[2].style.cursor = o.cursorReset)),
                l && (p = b = null),
                o.fadeOut
                    ? ((s = r.length),
                        r.stop().fadeOut(o.fadeOut, function () {
                            0 === --s && n(r, d, o, t);
                        }))
                    : n(r, d, o, t);
        }
        function n(t, o, n, i) {
            var s = e(i);
            if (!s.data("blockUI.isBlocked")) {
                t.each(function (e, t) {
                    this.parentNode && this.parentNode.removeChild(this);
                }),
                    o && o.el && ((o.el.style.display = o.display), (o.el.style.position = o.position), (o.el.style.cursor = "default"), o.parent && o.parent.appendChild(o.el), s.removeData("blockUI.history")),
                    s.data("blockUI.static") && s.css("position", "static"),
                    "function" == typeof n.onUnblock && n.onUnblock(i, n);
                var l = e(document.body),
                    a = l.width(),
                    d = l[0].style.width;
                l.width(a - 1).width(a), (l[0].style.width = d);
            }
        }
        function i(t, o, n) {
            var i = o == window,
                l = e(o);
            if ((t || ((!i || p) && (i || l.data("blockUI.isBlocked")))) && (l.data("blockUI.isBlocked", t), i && n.bindEvents && (!t || n.showOverlay))) {
                var a = "mousedown mouseup keydown keypress keyup touchstart touchend touchmove";
                t ? e(document).bind(a, n, s) : e(document).unbind(a, s);
            }
        }
        function s(t) {
            if ("keydown" === t.type && t.keyCode && 9 == t.keyCode && p && t.data.constrainTabKey) {
                var o = b,
                    n = !t.shiftKey && t.target === o[o.length - 1],
                    i = t.shiftKey && t.target === o[0];
                if (n || i)
                    return (
                        setTimeout(function () {
                            l(i);
                        }, 10),
                        !1
                    );
            }
            var s = t.data,
                a = e(t.target);
            return a.hasClass("blockOverlay") && s.onOverlayClick && s.onOverlayClick(t), a.parents("div." + s.blockMsgClass).length > 0 ? !0 : 0 === a.parents().children().filter("div.blockUI").length;
        }
        function l(e) {
            if (b) {
                var t = b[e === !0 ? b.length - 1 : 0];
                t && t.focus();
            }
        }
        function a(e, t, o) {
            var n = e.parentNode,
                i = e.style,
                s = (n.offsetWidth - e.offsetWidth) / 2 - d(n, "borderLeftWidth"),
                l = (n.offsetHeight - e.offsetHeight) / 2 - d(n, "borderTopWidth");
            t && (i.left = s > 0 ? s + "px" : "0"), o && (i.top = l > 0 ? l + "px" : "0");
        }
        function d(t, o) {
            return parseInt(e.css(t, o), 10) || 0;
        }
        e.fn._fadeIn = e.fn.fadeIn;
        var c = e.noop || function () { },
            r = /MSIE/.test(navigator.userAgent),
            u = /MSIE 6.0/.test(navigator.userAgent) && !/MSIE 8.0/.test(navigator.userAgent),
            f = (document.documentMode || 0, e.isFunction(document.createElement("div").style.setExpression));
        (e.blockUI = function (e) {
            t(window, e);
        }),
            (e.unblockUI = function (e) {
                o(window, e);
            }),
            (e.growlUI = function (t, o, n, i) {
                var s = e('<div class="growlUI"></div>');
                t && s.append("<h1>" + t + "</h1>"), o && s.append("<h2>" + o + "</h2>"), void 0 === n && (n = 3e3);
                var l = function (t) {
                    (t = t || {}),
                        e.blockUI({
                            message: s,
                            fadeIn: "undefined" != typeof t.fadeIn ? t.fadeIn : 700,
                            fadeOut: "undefined" != typeof t.fadeOut ? t.fadeOut : 1e3,
                            timeout: "undefined" != typeof t.timeout ? t.timeout : n,
                            centerY: !1,
                            showOverlay: !1,
                            onUnblock: i,
                            css: e.blockUI.defaults.growlCSS,
                        });
                };
                l();
                s.css("opacity");
                s.mouseover(function () {
                    l({ fadeIn: 0, timeout: 3e4 });
                    var t = e(".blockMsg");
                    t.stop(), t.fadeTo(300, 1);
                }).mouseout(function () {
                    e(".blockMsg").fadeOut(1e3);
                });
            }),
            (e.fn.block = function (o) {
                if (this[0] === window) return e.blockUI(o), this;
                var n = e.extend({}, e.blockUI.defaults, o || {});
                return (
                    this.each(function () {
                        var t = e(this);
                        (n.ignoreIfBlocked && t.data("blockUI.isBlocked")) || t.unblock({ fadeOut: 0 });
                    }),
                    this.each(function () {
                        "static" == e.css(this, "position") && ((this.style.position = "relative"), e(this).data("blockUI.static", !0)), (this.style.zoom = 1), t(this, o);
                    })
                );
            }),
            (e.fn.unblock = function (t) {
                return this[0] === window
                    ? (e.unblockUI(t), this)
                    : this.each(function () {
                        o(this, t);
                    });
            }),
            (e.blockUI.version = 2.7),
            (e.blockUI.defaults = {
                message: "<span class='blockUIicon fas fa-spinner fa-spin'></span><span class='blockUItext'>Učitavanje...</span>",
                title: null,
                draggable: !0,
                theme: !1,
                css: { padding: 0, margin: 0, width: "30%", top: "40%", left: "35%", textAlign: "center", color: "#000", border: "0px solid #aaa", backgroundColor: "#fff", cursor: "wait" },
                themedCSS: { width: "30%", top: "40%", left: "35%" },
                overlayCSS: { backgroundColor: "#000", opacity: 0.6, cursor: "wait" },
                cursorReset: "default",
                growlCSS: {
                    width: "350px",
                    top: "10px",
                    left: "",
                    right: "10px",
                    border: "none",
                    padding: "5px",
                    opacity: 0.6,
                    cursor: "default",
                    color: "white",
                    backgroundColor: "#000",
                    "-webkit-border-radius": "10px",
                    "-moz-border-radius": "10px",
                    "border-radius": "10px",
                },
                iframeSrc: /^https/i.test(window.location.href || "") ? "javascript:false" : "about:blank",
                forceIframe: !1,
                baseZ: 1e3,
                centerX: !0,
                centerY: !0,
                allowBodyStretch: !0,
                bindEvents: !0,
                constrainTabKey: !0,
                fadeIn: 200,
                fadeOut: 400,
                timeout: 0,
                showOverlay: !0,
                focusInput: !0,
                focusableElements: ":input:enabled:visible",
                onBlock: null,
                onUnblock: null,
                onOverlayClick: null,
                quirksmodeOffsetHack: 4,
                blockMsgClass: "blockMsg",
                ignoreIfBlocked: !1,
            });
        var p = null,
            b = [];
    }
    "function" == typeof define && define.amd && define.amd.jQuery ? define(["jquery"], e) : e(jQuery);
})();

/*
 *
 * Copyright (c) 2006-2014 Sam Collett (http://www.texotela.co.uk)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Version 1.4.1
 * Demo: http://www.texotela.co.uk/code/jquery/numeric/
 *
 */
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], factory);
    } else {
        factory(window.jQuery);
    }
}(function ($) {
    /*
     * Allows only valid characters to be entered into input boxes.
     * Note: fixes value when pasting via Ctrl+V, but not when using the mouse to paste
      *      side-effect: Ctrl+A does not work, though you can still use the mouse to select (or double-click to select all)
     *
     * @name     numeric
     * @param    config      { decimal : "." , negative : true }
     * @param    callback     A function that runs if the number is not valid (fires onblur)
     * @author   Sam Collett (http://www.texotela.co.uk)
     * @example  $(".numeric").numeric();
     * @example  $(".numeric").numeric(","); // use , as separator
     * @example  $(".numeric").numeric({ decimal : "," }); // use , as separator
     * @example  $(".numeric").numeric({ altDecimal : "," }); // accept , as alternative separator, but use . as separator in output
     * @example  $(".numeric").numeric({ negative : false }); // do not allow negative values
     * @example  $(".numeric").numeric({ decimalPlaces : 2 }); // only allow 2 decimal places
     * @example  $(".numeric").numeric(null, callback); // use default values, pass on the 'callback' function
     *
     */
    $.fn.numeric = function (config, callback) {
        if (typeof config === 'boolean') {
            config = { decimal: config, negative: true, decimalPlaces: -1 };
        }
        config = config || {};
        // if config.negative undefined, set to true (default is to allow negative numbers)
        if (typeof config.negative == "undefined") { config.negative = true; }
        // set decimal point
        var decimal = (config.decimal === false) ? "" : config.decimal || ".";
        // set alternative key as decimal point
        var altDecimal = (config.altDecimal === false) ? "" : config.altDecimal || decimal;
        // allow negatives
        var negative = (config.negative === true) ? true : false;
        // set decimal places
        var decimalPlaces = (typeof config.decimalPlaces == "undefined") ? -1 : config.decimalPlaces;
        // callback function
        callback = (typeof (callback) == "function" ? callback : function () { });
        // set data and methods
        return this.data("numeric.decimal", decimal).data("numeric.altDecimal", altDecimal).data("numeric.negative", negative).data("numeric.callback", callback).data("numeric.decimalPlaces", decimalPlaces).keypress($.fn.numeric.keypress).keyup($.fn.numeric.keyup).blur($.fn.numeric.blur);
    };

    $.fn.numeric.keypress = function (e) {
        // get decimal character and determine if negatives are allowed
        var decimal = $.data(this, "numeric.decimal");
        var negative = $.data(this, "numeric.negative");
        var decimalPlaces = $.data(this, "numeric.decimalPlaces");
        // get an alternative decimal separator
        var altDecimal = $.data(this, "numeric.altDecimal");
        // get the key that was pressed
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        // allow enter/return key (only when in an input box)
        if (key == 13 && this.nodeName.toLowerCase() == "input") {
            return true;
        }
        else if (key == 13) {
            return false;
        }
        //dont allow #, $, %
        else if (key == 35 || key == 36 || key == 37) {
            return false;
        }
        var allow = false;
        // allow Ctrl+A
        if ((e.ctrlKey && key == 97 /* firefox */) || (e.ctrlKey && key == 65) /* opera */) { return true; }
        // allow Ctrl+X (cut)
        if ((e.ctrlKey && key == 120 /* firefox */) || (e.ctrlKey && key == 88) /* opera */) { return true; }
        // allow Ctrl+C (copy)
        if ((e.ctrlKey && key == 99 /* firefox */) || (e.ctrlKey && key == 67) /* opera */) { return true; }
        // allow Ctrl+Z (undo)
        if ((e.ctrlKey && key == 122 /* firefox */) || (e.ctrlKey && key == 90) /* opera */) { return true; }
        // allow or deny Ctrl+V (paste), Shift+Ins
        if ((e.ctrlKey && key == 118 /* firefox */) || (e.ctrlKey && key == 86) /* opera */ ||
            (e.shiftKey && key == 45)) { return true; }
        // if a number was not pressed
        if (key < 48 || key > 57) {
            var value = $(this).val();
            /* '-' only allowed at start and if negative numbers allowed */
            if ($.inArray('-', value.split('')) !== 0 && negative && key == 45 && (value.length === 0 || parseInt($.fn.getSelectionStart(this), 10) === 0)) { return true; }
            /* only one decimal separator allowed */
            if (decimal && key == decimal.charCodeAt(0) && $.inArray(decimal, value.split('')) != -1) {
                allow = false;
            }
            // check for other keys that have special purposes
            if (
                key != 8 /* backspace */ &&
                key != 9 /* tab */ &&
                key != 13 /* enter */ &&
                key != 35 /* end */ &&
                key != 36 /* home */ &&
                key != 37 /* left */ &&
                key != 39 /* right */ &&
                key != 46 /* del */
            ) {
                allow = false;
            }
            else {
                // for detecting special keys (listed above)
                // IE does not support 'charCode' and ignores them in keypress anyway
                if (typeof e.charCode != "undefined") {
                    // special keys have 'keyCode' and 'which' the same (e.g. backspace)
                    if (e.keyCode == e.which && e.which !== 0) {
                        allow = true;
                        // . and delete share the same code, don't allow . (will be set to true later if it is the decimal point)
                        if (e.which == 46) { allow = false; }
                    }
                    // or keyCode != 0 and 'charCode'/'which' = 0
                    else if (e.keyCode !== 0 && e.charCode === 0 && e.which === 0) {
                        allow = true;
                    }
                }
            }
            // if key pressed is the decimal or altDecimal and decimal is not already in the field 
            if (decimal && key == decimal.charCodeAt(0) || altDecimal && key == altDecimal.charCodeAt(0)) {
                if ($.inArray(decimal, value.split('')) == -1) {
                    allow = true;
                }
                else {
                    allow = false;
                }
            }
        }
        else {
            allow = true;
            // remove extra decimal places
            if (decimal && decimalPlaces > 0) {
                var selectionStart = $.fn.getSelectionStart(this);
                var selectionEnd = $.fn.getSelectionEnd(this);
                var dot = $.inArray(decimal, $(this).val().split(''));
                if (selectionStart === selectionEnd && dot >= 0 && selectionStart > dot && $(this).val().length > dot + decimalPlaces) {
                    allow = false;
                }
            }

        }
        return allow;
    };

    $.fn.numeric.keyup = function (e) {
        var val = $(this).val();
        if (val && val.length > 0) {
            // get carat (cursor) position
            var carat = $.fn.getSelectionStart(this);
            var selectionEnd = $.fn.getSelectionEnd(this);
            // get decimal character and determine if negatives are allowed
            var decimal = $.data(this, "numeric.decimal");
            var negative = $.data(this, "numeric.negative");
            var decimalPlaces = $.data(this, "numeric.decimalPlaces");
            // get an alternative decimal separator
            var altDecimal = $.data(this, "numeric.altDecimal");

            // prepend a 0 if necessary
            if (decimal !== "" && decimal !== null) {
                // find decimal point
                var dot = $.inArray(decimal, val.split(''));
                // if dot at start, add 0 before
                if (dot === 0) {
                    this.value = "0" + val;
                    carat++;
                    selectionEnd++;
                }
                // if dot at position 1, check if there is a - symbol before it
                if (dot == 1 && val.charAt(0) == "-") {
                    this.value = "-0" + val.substring(1);
                    carat++;
                    selectionEnd++;
                }
                val = this.value;
            }

            // if pasted in, only allow the following characters
            var validChars = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, '-', decimal];
            // get length of the value (to loop through)
            var length = val.length;
            // loop backwards (to prevent going out of bounds)
            for (var i = length - 1; i >= 0; i--) {
                var ch = val.charAt(i);
                // remove '-' if it is in the wrong place
                if (i !== 0 && ch == "-") {
                    val = val.substring(0, i) + val.substring(i + 1);
                }
                // remove character if it is at the start, a '-' and negatives aren't allowed
                else if (i === 0 && !negative && ch == "-") {
                    val = val.substring(1);
                }
                var validChar = false;
                // loop through validChars
                for (var j = 0; j < validChars.length; j++) {
                    // if it is valid, break out the loop
                    if (ch == validChars[j]) {
                        validChar = true;
                        break;
                    }
                }
                // if not a valid character and character is altDecimal, replace 
                if (!validChar && ch == altDecimal) {
                    val = val.substring(0, i) + decimal + val.substring(i + 1);
                    validChar = true;
                }
                // if not a valid character, or a space, remove
                if (!validChar || ch == " ") {
                    val = val.substring(0, i) + val.substring(i + 1);
                }
            }
            // remove extra decimal characters
            var firstDecimal = $.inArray(decimal, val.split(''));
            if (firstDecimal > 0) {
                for (var k = length - 1; k > firstDecimal; k--) {
                    var chch = val.charAt(k);
                    // remove decimal character
                    if (chch == decimal) {
                        val = val.substring(0, k) + val.substring(k + 1);
                    }
                }
            }

            // remove extra decimal places
            if (decimal && decimalPlaces > 0) {
                var dot = $.inArray(decimal, val.split(''));
                if (dot >= 0) {
                    val = val.substring(0, dot + decimalPlaces + 1);
                    selectionEnd = Math.min(val.length, selectionEnd);
                }
            }
            // set the value and prevent the cursor moving to the end
            this.value = val;
            $.fn.setSelection(this, [carat, selectionEnd]);
        }
    };

    $.fn.numeric.blur = function () {
        var decimal = $.data(this, "numeric.decimal");
        var callback = $.data(this, "numeric.callback");
        var negative = $.data(this, "numeric.negative");
        var val = this.value;
        if (val !== "") {
            var re = new RegExp("^" + (negative ? "-?" : "") + "\\d+$|^" + (negative ? "-?" : "") + "\\d*" + decimal + "\\d+$");
            if (!re.exec(val)) {
                callback.apply(this);
            }
        }
    };

    $.fn.removeNumeric = function () {
        return this.data("numeric.decimal", null).data("numeric.altDecimal", null).data("numeric.negative", null).data("numeric.callback", null).data("numeric.decimalPlaces", null).unbind("keypress", $.fn.numeric.keypress).unbind("keyup", $.fn.numeric.keyup).unbind("blur", $.fn.numeric.blur);
    };

    // Based on code from http://javascript.nwbox.com/cursor_position/ (Diego Perini <dperini@nwbox.com>)
    $.fn.getSelectionStart = function (o) {
        if (o.type === "number") {
            return undefined;
        }
        else if (o.createTextRange && document.selection) {
            var r = document.selection.createRange().duplicate();
            r.moveEnd('character', o.value.length);
            if (r.text == '') return o.value.length;

            return Math.max(0, o.value.lastIndexOf(r.text));
        } else {
            try { return o.selectionStart; }
            catch (e) { return 0; }
        }
    };

    // Based on code from http://javascript.nwbox.com/cursor_position/ (Diego Perini <dperini@nwbox.com>)
    $.fn.getSelectionEnd = function (o) {
        if (o.type === "number") {
            return undefined;
        }
        else if (o.createTextRange && document.selection) {
            var r = document.selection.createRange().duplicate()
            r.moveStart('character', -o.value.length)
            return r.text.length
        } else return o.selectionEnd
    }

    // set the selection, o is the object (input), p is the position ([start, end] or just start)
    $.fn.setSelection = function (o, p) {
        // if p is number, start and end are the same
        if (typeof p == "number") { p = [p, p]; }
        // only set if p is an array of length 2
        if (p && p.constructor == Array && p.length == 2) {
            if (o.type === "number") {
                o.focus();
            }
            else if (o.createTextRange) {
                var r = o.createTextRange();
                r.collapse(true);
                r.moveStart('character', p[0]);
                r.moveEnd('character', p[1] - p[0]);
                r.select();
            }
            else {
                o.focus();
                try {
                    if (o.setSelectionRange) {
                        o.setSelectionRange(p[0], p[1]);
                    }
                } catch (e) {
                }
            }
        }
    };

}));

/**
 *  Zebra_DatePicker
 *
 *  Zebra_DatePicker is a small, compact and highly configurable date picker / time picker jQuery plugin
 *
 *  Read more {@link https://github.com/stefangabos/Zebra_Datepicker/ here}
 *
 *  @author     Stefan Gabos <contact@stefangabos.ro>
 *  @version    1.9.12 (last revision: November 24, 2018)
 *  @copyright  (c) 2011 - 2018 Stefan Gabos
 *  @license    http://www.gnu.org/licenses/lgpl-3.0.txt GNU LESSER GENERAL PUBLIC LICENSE
 *  @package    Zebra_DatePicker
 */
(function(factory) {

    'use strict';

    // AMD
    if (typeof define === 'function' && define.amd) define(['jquery'], factory);    // jshint ignore:line

    // CommonJS
    else if (typeof exports === 'object') factory(require('jquery'));   // jshint ignore:line

    // browser globals
    else factory(jQuery);

}(function($) {

    'use strict';

    $.Zebra_DatePicker = function(element, options) {

        // so you can tell the version number even if all you have is the minified source
        this.version = '1.9.12';

        var defaults = {

                //  setting this property to a jQuery element, will result in the date picker being always visible, the indicated
                //  element being the date picker's container;
                //
                //  setting this to boolean TRUE will keep will result in the date picker not closing when selecting a
                //  date but only when the user clicks outside the date picker.
                //
                //  note that when a date format is used that also involves time, this property will be automatically
                //  set to TRUE!
                //
                //  default is FALSE
                always_visible: false,

                //  by default, the date picker is injected into the <body>; use this property to tell the library to inject
                //  the date picker into a custom element - useful when you want the date picker to open at a specific position
                //
                //  must be a jQuery element
                //
                //  default is $('body')
                container: $('body'),

                //  by default, the current date (the value of *Today*) is taken from the system where the date picker is run on.
                //  set this to a date in the format of 'YYYY-MM-DD' to use a different date.
                //
                //  default is FALSE which means "the current system's date"
                current_date: false,

                //  dates that should have custom classes applied to them
                //  an object in the form of
                //  {
                //      'myclass1': [dates_to_apply_the_custom_class_to],
                //      'myclass2': [dates_to_apply_the_custom_class_to]
                //  }
                //  where "dates_to_apply_the_custom_class_to" is an array of dates in the same format as required for
                //  "disabled_dates" property.
                //
                //  custom classes will be applied *only* in the day picker view and not on month/year views!
                //  also note that the class name will have the "_disabled" suffix added if the day the class is applied to
                //  is disabled
                //
                //  in order for the styles in your custom classes to be applied, make sure you are using the following syntax:
                //
                //  .Zebra_DatePicker .dp_daypicker td.myclass1 { .. }
                //  .Zebra_DatePicker .dp_daypicker td.myclass1_disabled { .. }
                //
                //  default is FALSE, no custom classes
                custom_classes: false,

                //  days of the week; Sunday to Saturday
                days: ['Nedjelja', 'Ponedjeljak', 'Utorak', 'Srijeda', 'Četvrtak', 'Petak', 'Subota'],

                //  by default, the abbreviated name of a day consists of the first 2 letters from the day's full name;
                //  while this is common for most languages, there are also exceptions for languages like Thai, Loa, Myanmar,
                //  etc. where this is not correct; for these cases, specify an array with the abbreviations to be used for
                //  the 7 days of the week; leave it FALSE to use the first 2 letters of a day's name as the abbreviation.
                //
                //  default is FALSE
                days_abbr: false,

                //  the position of the date picker relative to the element it is attached to. note that, regardless of this
                //  setting, the date picker's position will be automatically adjusted to fit in the viewport, if needed.
                //
                //  possible values are "above" and "below"
                //
                //  default is "above"
                default_position: 'above',

                //  direction of the calendar
                //
                //  a positive or negative integer: n (a positive integer) creates a future-only calendar beginning at n days
                //  after today; -n (a negative integer); if n is 0, the calendar has no restrictions. use boolean true for
                //  a future-only calendar starting with today and use boolean false for a past-only calendar ending today.
                //
                //  you may also set this property to an array with two elements in the following combinations:
                //
                //  -   first item is boolean TRUE (calendar starts today), an integer > 0 (calendar starts n days after
                //      today), or a valid date given in the format defined by the "format" attribute, using English for
                //      month names (calendar starts at the specified date), and the second item is boolean FALSE (the calendar
                //      has no ending date), an integer > 0 (calendar ends n days after the starting date), or a valid date
                //      given in the format defined by the "format" attribute, using English for month names, and which occurs
                //      after the starting date (calendar ends at the specified date)
                //
                //  -   first item is boolean FALSE (calendar ends today), an integer < 0 (calendar ends n days before today),
                //      or a valid date given in the format defined by the "format" attribute, using English for month names
                //      (calendar ends at the specified date), and the second item is an integer > 0 (calendar ends n days
                //      before the ending date), or a valid date given in the format defined by the "format" attribute, using
                //      English for month names  and which occurs before the starting date (calendar starts at the specified
                //      date)
                //
                //  [1, 7] - calendar starts tomorrow and ends seven days after that
                //  [true, 7] - calendar starts today and ends seven days after that
                //  ['2013-01-01', false] - calendar starts on January 1st 2013 and has no ending date ("format" is YYYY-MM-DD)
                //  [false, '2012-01-01'] - calendar ends today and starts on January 1st 2012 ("format" is YYYY-MM-DD)
                //
                //  note that "disabled_dates" property will still apply!
                //
                //  default is 0 (no restrictions)
                direction: 0,

                //  by default, setting a format that also involves time (h, H, g, G, i, s, a, A) will automatically enable
                //  the time picker. if you want to use a format that involves time but you don't want the time picker, set
                //  this property to TRUE.
                //
                //  default is FALSE
                disable_time_picker: false,

                //  an array of disabled dates in the following format: 'day month year weekday' where "weekday" is optional
                //  and can be 0-6 (Saturday to Sunday); the syntax is similar to cron's syntax: the values are separated by
                //  spaces and may contain * (asterisk) - (dash) and , (comma) delimiters:
                //
                //  ['1 1 2012'] would disable January 1, 2012;
                //  ['* 1 2012'] would disable all days in January 2012;
                //  ['1-10 1 2012'] would disable January 1 through 10 in 2012;
                //  ['1,10 1 2012'] would disable January 1 and 10 in 2012;
                //  ['1-10,20,22,24 1-3 *'] would disable 1 through 10, plus the 22nd and 24th of January through March for every year;
                //  ['* * * 0,6'] would disable all Saturdays and Sundays;
                //  ['01 07 2012', '02 07 2012', '* 08 2012'] would disable 1st and 2nd of July 2012, and all of August of 2012
                //
                //  default is FALSE, no disabled dates
                //
                //  DISABLING ALL DATES AND NOT SPECIFYING AT LEAST ONE ENABLED DATE WILL SEND THE SCRIPT INTO AN INFINITE
                //  LOOP SEARCHING FOR AN ENABLED DATE TO DISPLAY!
                disabled_dates: false,

                //  an array of enabled dates in the same format as required for "disabled_dates" property.
                //  to be used together with the "disabled_dates" property by first setting the "disabled_dates" property to
                //  something like "[* * * *]" (which will disable everything) and the setting the "enabled_dates" property to,
                //  say, "[* * * 0,6]" to enable just weekends.
                enabled_dates: false,

                //  an array of selectable hours.
                //  default is FALSE, all hours are selectable.
                enabled_hours: false,

                //  an array of selectable minutes.
                //  default is FALSE, all minutes are selectable.
                enabled_minutes: false,

                //  an array of selectable seconds.
                //  default is FALSE, all seconds are selectable.
                enabled_seconds: false,

                //  allows the users to quickly navigate through months and years by clicking on the date picker's top label.
                //  default is TRUE.
                fast_navigation: true,

                //  week's starting day
                //
                //  valid values are 0 to 6, Sunday to Saturday
                //
                //  default is 1, Monday
                first_day_of_week: 1,

                //  format of the returned date
                //
                //  accepts the following characters for date formatting: d, D, j, l, N, w, S, F, m, M, n, Y, y, h, H,
                //  g, G, i, s, a, A borrowing the syntax from PHP's "date" function.
                //
                //  note that when setting a date format without days ('d', 'j'), the users will be able to select only years
                //  and months, and when setting a format without months and days ('F', 'm', 'M', 'n', 'd', 'j'), the
                //  users will be able to select only years; likewise, when setting a date format with just months ('F', 'm',
                //  'M', 'n') or just years ('Y', 'y'), users will be able to select only months and years, respectively.
                //
                //  setting a format that also involves time (h, H, g, G, i, s, a, A) will automatically enable the time
                //  picker. if you want to use a format that involves time but you don't want the time picker, set the
                //  "disable_time_picker" property to TRUE.
                //
                //  setting a time format containing "a" or "A" (12-hour format) but using "H" or "G" as the hour's format
                //  will result in the hour's format being changed to "h" or "g", respectively.
                //
                //  also note that the value of the "view" property (see below) may be overridden if it is the case: a value of
                //  "days" for the "view" property makes no sense if the date format doesn't allow the selection of days.
                //
                //  default is Y-m-d
                format: 'Y-m-d',

                //  captions in the datepicker's header, for the 3 possible views: days, months, years
                //
                //  for each of the 3 views the following special characters may be used borrowing from PHP's "date" function's
                //  syntax: m, n, F, M, y and Y; any of these will be replaced at runtime with the appropriate date fragment,
                //  depending on the currently viewed date. two more special characters are also available Y1 and Y2 (upper
                //  case representing years with 4 digits, lowercase representing years with 2 digits) which represent
                //  "currently selected year - 7" and "currently selected year + 4" and which only make sense used in the
                //  "years" view.
                //
                //  even though any of these special characters may be used in any of the 3 views, you should use m, n, F, M
                //  for the "days" view and y, Y, Y1, Y2, y1, y2 for the "months" and "years" view or you may get unexpected
                //  results!
                //
                //  Text and HTML can also be used, and will be rendered as it is, as in the example below (the library is
                //  smart enough to not replace special characters when used in words or HTML tags):
                //
                //  header_captions: {
                //      'days':     'Departure:<br>F, Y',
                //      'months':   'Departure:<br>Y',
                //      'years':    'Departure:<br>Y1 - Y2'
                //  }
                //
                //  Default is
                //
                //  header_captions: {
                //      'days':     'F, Y',
                //      'months':   'Y',
                //      'years':    'Y1 - Y2'
                //  }
                header_captions: {
                    days:   'F, Y',
                    months: 'Y',
                    years:  'Y1 - Y2'
                },

                //  the left and right white-space around the icon
                //  if the "inside" property is set to TRUE then the target element's padding will be altered so that
                //  the element's left or right padding (depending on the value of "icon_position") will be 2 x icon_margin
                //  plus the icon's width
                //  if the "inside" property is set to FALSE, then this will be the distance between the element and the icon.
                //  leave it to FALSE to use the element's existing padding
                //
                //  default is FALSE
                icon_margin: false,

                //  icon's position
                //  accepted values are "left" and "right"
                //  if the "inside" property is set to TRUE, this will always be "right"
                //
                //  default is "right"
                icon_position: 'right',

                //  should the icon for opening the datepicker be inside the element?
                //  if set to FALSE, the icon will be placed to the right of the parent element, while if set to TRUE it will
                //  be placed to the right of the parent element, but *inside* the element itself
                //
                //  default is TRUE
                inside: true,

                //  the caption for the "Clear" button
                lang_clear_date: 'Poništi',

                //  months names
                months: ['Januar', 'Februar', 'Mart', 'April', 'Maj', 'Jun', 'Jul', 'Avgust', 'Septembar', 'Oktobar', 'Novembar', 'Decembar'],

                //  by default, the abbreviated name of a month consists of the first 3 letters from the month's full name;
                //  while this is common for most languages, there are also exceptions for languages like Thai, Loa, Myanmar,
                //  etc. where this is not correct; for these cases, specify an array with the abbreviations to be used for
                //  the months of the year; leave it FALSE to use the first 3 letters of a month's name as the abbreviation.
                //
                //  default is FALSE
                months_abbr: false,

                //  HTML to be used for previous/next and up/down buttons, in that order
                //
                //  default is ['&#9664;', '&#9654;', '&#9650;', '&#9660;']
                navigation: ['&#9664;', '&#9654;', '&#9650;', '&#9660;'],

                //  the offset, in pixels (x, y), to shift the date picker's position relative to the top-right of the icon
                //  that toggles the date picker or, if the icon is disabled, relative to the top-right corner of the element
                //  the plugin is attached to.
                //
                //  note that this only applies if the position of element relative to the browser's viewport doesn't require
                //  the date picker to be placed automatically so that it is visible!
                //
                //  default is [5, -5]
                offset: [5, -5],

                //  set whether the date picker should be shown *only* when interacting with the icon
                //  note that if you also set the "show_icon" property to FALSE, you will not be able to show the date picker anymore!
                //
                //  default is FALSE
                open_icon_only: false,

                //  set this property to TRUE if you want the date picker to be shown when the parent element (if
                //  "open_icon_only" is not set to FALSE) or the associated calendar icon (if "show_icon" is set to TRUE)
                //  receive focus.
                //
                //  default is FALSE
                open_on_focus: false,

                //  if set as a jQuery element with a Zebra_DatePicker attached, that particular date picker will use the
                //  current date picker's value as starting date
                //  note that the rules set in the "direction" property will still apply, only that the reference date will
                //  not be the current system date but the value selected in the current date picker
                //  default is FALSE (not paired with another date picker)
                pair: false,

                //  should the element the calendar is attached to, be read-only?
                //  if set to TRUE, a date can be set only through the date picker and cannot be entered manually
                //
                //  default is TRUE
                readonly_element: true,

                //  enables rtl text.
                //
                //  default is FALSE
                rtl: false,

                //  should days from previous and/or next month be selectable when visible?
                //  note that if the value of this property is set to TRUE, the value of "show_other_months" will be considered
                //  TRUE regardless of the actual value!
                //
                //  default is FALSE
                select_other_months: false,

                //  should the "Clear date" button be visible?
                //
                //  accepted values are:
                //
                //  - 0 (zero) - the button for clearing a previously selected date is shown only if a previously selected date
                //  already exists; this means that if the input the date picker is attached to is empty, and the user selects
                //  a date for the first time, this button will not be visible; once the user picked a date and opens the date
                //  picker again, this time the button will be visible.
                //
                //  - TRUE will make the button visible all the time
                //
                //  - FALSE will disable the button
                //
                //  default is "0" (without quotes)
                show_clear_date: 0,

                //  should a calendar icon be added to the elements the plugin is attached to?
                //
                //  default is TRUE
                show_icon: true,

                //  should days from previous and/or next month be visible?
                //
                //  default is TRUE
                show_other_months: true,

                //  should the "Today" button be visible?
                //  setting it to anything but boolean FALSE will enable the button and will use the property's value as
                //  caption for the button; setting it to FALSE will disable the button
                //
                //  default is "Today"
                show_select_today: 'Danas',

                //  should an extra column be shown, showing the number of each week?
                //  anything other than FALSE will enable this feature, and use the given value as column title
                //  i.e. show_week_number: 'Wk' would enable this feature and have "Wk" as the column's title
                //
                //  default is FALSE
                show_week_number: false,

                //  a default date to start the date picker with
                //  must be specified in the format defined by the "format" property, or as a JavaScript Date object
                //  note that this value is used only if there is no value in the field the date picker is attached to!
                //
                //  default is FALSE
                start_date: false,

                //  should default values, in the input field the date picker is attached to, be deleted if they are not valid
                //  according to "direction" and/or "disabled_dates"?
                //
                //  default is FALSE
                strict: false,

                //  how should the date picker start; valid values are "days", "months" and "years"
                //  note that the date picker is always cycling days-months-years when clicking in the date picker's header,
                //  and years-months-days when selecting dates (unless one or more of the views are missing due to the date's
                //  format)
                //
                //  also note that the value of the "view" property may be overridden if the date's format requires so! (i.e.
                //  "days" for the "view" property makes no sense if the date format doesn't allow the selection of days)
                //
                //  default is "days"
                view: 'days',

                //  days of the week that are considered "weekend days"
                //  valid values are 0 to 6, Sunday to Saturday
                //
                //  default values are 0 and 6 (Saturday and Sunday)
                weekend_days: [0, 6],

                //  when set to TRUE, day numbers < 10 will be prefixed with 0; set to FALSE if you don't want that
                //
                //  default is TRUE
                zero_pad: false,

                //  callback function to be executed whenever the user changes the view (days/months/years), as well as when
                //  the user navigates by clicking on the "next"/"previous" icons in any of the views
                //
                //  the callback function called by this event takes 2 arguments - the first argument represents the current
                //  view (can be "days", "months" or "years"), the second argument represents an array containing the "active"
                //  elements (not disabled) from the view, as jQuery elements, allowing for easy customization and interaction
                //  with particular cells in the date picker's view
                //
                //  the "this" keyword inside the callback function refers to the element the date picker is attached to,
                //  as a jQuery object
                //
                //  for simplifying searching for particular dates, each element in the second argument will also have a
                //  "date" data attribute whose format depends on the value of the "view" argument:
                //  - YYYY-MM-DD for elements in the "days" view
                //  - YYYY-MM for elements in the "months" view
                //  - YYYY for elements in the "years" view
                //
                //  the "this" keyword inside the callback function refers to the element the date picker is attached to!
                onChange: null,

                //  callback function to be executed when the user clicks the "Clear" button
                //
                //  the callback function takes no arguments; the "this" keyword inside the callback function refers to
                //  the element the date picker is attached to, as a jQuery object
                onClear: null,

                //  callback function to be executed when the date picker is shown
                //
                //  the callback function takes no arguments; the "this" keyword inside the callback function refers to
                //  the element the date picker is attached to, as a jQuery object
                onOpen: null,

                //  callback function to be executed when the date picker is closed, but only when the "always_visible"
                //  property is set to FALSE
                //
                //  the callback function takes no arguments; the "this" keyword inside the callback function refers to
                //  the element the date picker is attached to, as a jQuery object
                onClose: null,

                //  callback function to be executed when a date is selected
                //  the callback function takes 3 arguments:
                //  -   the date in the format specified by the "format" attribute;
                //  -   the date in YYYY-MM-DD format
                //  -   the date as a JavaScript Date object
                //
                //  the "this" keyword inside the callback function refers to the element the date picker is attached to,
                //  as a jQuery object
                onSelect: null

            },

            // private properties
            cleardate, clickables, confirm_selection, current_system_day, current_system_month, current_system_year,
            custom_class_names, custom_classes = {}, datepicker, daypicker, daypicker_cells, default_day,
            default_month, default_year, disabled_dates, enabled_dates, end_date, first_selectable_day,
            first_selectable_month, first_selectable_year, footer, header, icon, last_selectable_day, last_selectable_month,
            last_selectable_year, monthpicker, monthpicker_cells, original_attributes = {}, selected_hour, selected_minute,
            selected_second, selected_ampm, view_toggler, selected_month, selected_year, selecttoday, shim,
            show_select_today, start_date, timeout, timepicker, timepicker_config, touchmove = false, uniqueid = '', yearpicker,
            yearpicker_cells, view, views, is_touch = false,

            // are we running on an iOS powered device?
            is_iOS = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform),

            // to avoid confusions, we use "plugin" to reference the current instance of the object
            plugin = this,

            // the jQuery version of the element
            // "element" (without the $) will point to the DOM element
            $element = $(element),

            /**
             *  Constructor method. Initializes the date picker.
             *
             *  @return void
             */
            init = function(update) {

                var

                    // the characters that may be present in the date format and that represent days, months, years, hours,
                    // minutes and seconds
                    date_chars = {
                        days:       ['d', 'j', 'D'],
                        months:     ['F', 'm', 'M', 'n', 't'],
                        years:      ['o', 'Y', 'y'],
                        hours:      ['G', 'g', 'H', 'h'],
                        minutes:    ['i'],
                        seconds:    ['s'],
                        ampm:       ['A', 'a']
                    },

                    // some defaults
                    type = null, data, dates, k, l, format_is_valid = false;

                // generate a random ID for each date picker (we'll use this if later a certain date picker is destroyed to
                // remove related events)
                // the code is taken from http://stackoverflow.com/a/105074
                for (k = 0; k < 3; k++) uniqueid += Math.floor((1 + Math.random()) * 0x10000).toString(16);

                // start by assuming there are no enabled/disabled dates
                disabled_dates = [];
                enabled_dates = [];

                // unless we're not just updating settings
                if (!update) {

                    // merge default settings with user-settings (
                    plugin.settings = $.extend({}, defaults, $.fn.Zebra_DatePicker.defaults, options);

                    // preserve some of element's original attributes
                    original_attributes.readonly = $element.attr('readonly');
                    original_attributes.style = $element.attr('style');
                    original_attributes.padding_left = parseInt($element.css('paddingLeft'), 10) || 0;
                    original_attributes.padding_right = parseInt($element.css('paddingRight'), 10) || 0;

                    // iterate through the element's data attributes (if any)
                    for (data in $element.data())

                        // if data attribute's name starts with "zdp_"
                        if (data.indexOf('zdp_') === 0) {

                            // remove the "zdp_" prefix
                            data = data.replace(/^zdp\_/, '');

                            // if such a property exists
                            if (undefined !== defaults[data])

                                // update the property's value
                                // (note that for the "pair" property we need to convert the property to an element)
                                plugin.settings[data] = (data === 'pair' ? $($element.data('zdp_' + data)) : $element.data('zdp_' + data));

                        }

                }

                // if the element should be read-only, set the "readonly" attribute
                if (plugin.settings.readonly_element) $element.attr('readonly', 'readonly');

                // otherwise remove it (in case it is present)
                else $element.removeAttr('readonly');

                // assume there's no timepicker
                timepicker_config = false;

                // the views the user can cycle through
                views = [];

                // as long as the format is invalid
                while (!format_is_valid) {

                    // determine the views the user can cycle through, depending on the format
                    // that is, if the format doesn't contain the day, the user will be able to cycle only through years and months,
                    // whereas if the format doesn't contain months nor days, the user will only be able to select years

                    // iterate through all the character blocks
                    for (type in date_chars)

                        // iterate through the characters of each block
                        $.each(date_chars[type], function(index, character) {

                            var i, max;

                            // if current character exists in the "format" property
                            if (plugin.settings.format.indexOf(character) > -1)

                                // if user can cycle through the "days" view
                                if (type === 'days') views.push('days');

                                // if user can cycle through the "months" view
                                else if (type === 'months') views.push('months');

                                // if user can cycle through the "years" view
                                else if (type === 'years') views.push('years');

                                // if time is available in the date's format and time picker is not explicitly disabled
                                else if ((type === 'hours' || type === 'minutes' || type === 'seconds' || type === 'ampm') && !plugin.settings.disable_time_picker) {

                                    // if variable is not yet initialized
                                    if (!timepicker_config) {

                                        // initialize the variable now
                                        timepicker_config = {is12hour: false};

                                        // users may access the "time" view
                                        views.push('time');

                                    }

                                    // if hours are available in the date's format
                                    if (type === 'hours') {

                                        // store the hour's format
                                        timepicker_config.hour_format = character;

                                        // selectable hours (12 or 24) depending on the format
                                        if (character === 'g' || character === 'h') {

                                            max = 12;

                                            // set a flag telling that the hour is 12 hour format
                                            timepicker_config.is12hour = true;

                                        } else max = 24;

                                        timepicker_config.hours = [];

                                        // iterate through valid hours
                                        for (i = (max === 12 ? 1 : 0); i < (max === 12 ? 13 : max); i++)

                                            // and add them to the lookup array if a user-defined list of values doesn't exist, or if the value is in that list
                                            if (!$.isArray(plugin.settings.enabled_hours) || $.inArray(i, plugin.settings.enabled_hours) > -1) timepicker_config.hours.push(i);

                                    // if minutes are available in the date's format
                                    } else if (type === 'minutes') {

                                        timepicker_config.minutes = [];

                                        // iterate through valid minutes
                                        for (i = 0; i < 60; i++)

                                            // and add them to the lookup array if a user-defined list of values doesn't exist, or if the value is in that list
                                            if (!$.isArray(plugin.settings.enabled_minutes) || $.inArray(i, plugin.settings.enabled_minutes) > -1) timepicker_config.minutes.push(i);

                                    // if seconds are available in the date's format
                                    } else if (type === 'seconds') {

                                        timepicker_config.seconds = [];

                                        // iterate through valid minutes
                                        for (i = 0; i < 60; i++)

                                            // and add them to the lookup array if a user-defined list of values doesn't exist, or if the value is in that list
                                            if (!$.isArray(plugin.settings.enabled_seconds) || $.inArray(i, plugin.settings.enabled_seconds) > -1) timepicker_config.seconds.push(i);

                                    // if am/pm is available in the date's format
                                    } else

                                        // pre-fill the array of selectable seconds
                                        timepicker_config.ampm = ['am', 'pm'];

                                }

                        });

                    // if time format contains hours, am/pm needs to be shown but the hours are in 24-hour format
                    if (timepicker_config.hour_format && timepicker_config.ampm && timepicker_config.is12hour === false)

                        // replace the hour's format from a 24-hour format to a 12-hour format
                        plugin.settings.format = plugin.settings.format.replace(timepicker_config.hour_format, timepicker_config.hour_format.toLowerCase());

                    // otherwise, consider the format as valid
                    else format_is_valid = true;

                }

                // if invalid format (no days, no months, no years) use the default where the user is able to cycle through
                // all the views, except time
                if (views.length === 0) views = ['years', 'months', 'days'];

                // if the starting view is not amongst the views the user can cycle through, set the correct starting view
                if ($.inArray(plugin.settings.view, views) === -1) plugin.settings.view = views[views.length - 1];

                // parse the rules for disabling dates and turn them into arrays of arrays

                custom_class_names = [];
                for (k in plugin.settings.custom_classes) if (plugin.settings.custom_classes.hasOwnProperty(k) && custom_class_names.indexOf(k) === -1) custom_class_names.push(k);

                // it's the same logic for preparing the enabled/disable dates, as well as dates that have custom classes
                for (l = 0; l < 2 + custom_class_names.length; l++) {

                    // first time we're doing disabled dates,
                    if (l === 0) dates = plugin.settings.disabled_dates;

                    // second time we're doing enabled_dates
                    else if (l === 1) dates = plugin.settings.enabled_dates;

                    // otherwise, we're doing dates that will have custom classes
                    else dates = plugin.settings.custom_classes[custom_class_names[l - 2]];

                    // if we have a non-empty array
                    if ($.isArray(dates) && dates.length > 0)

                        // iterate through the rules
                        $.each(dates, function() {

                            // split the values in rule by white space
                            var rules = this.split(' '), i, j, k, limits;

                            // there can be a maximum of 4 rules (days, months, years and, optionally, day of the week)
                            for (i = 0; i < 4; i++) {

                                // if one of the values is not available
                                // replace it with a * (wildcard)
                                if (!rules[i]) rules[i] = '*';

                                // if rule contains a comma, create a new array by splitting the rule by commas
                                // if there are no commas create an array containing the rule's string
                                rules[i] = (rules[i].indexOf(',') > -1 ? rules[i].split(',') : new Array(rules[i]));

                                // iterate through the items in the rule
                                for (j = 0; j < rules[i].length; j++)

                                    // if item contains a dash (defining a range)
                                    if (rules[i][j].indexOf('-') > -1) {

                                        // get the lower and upper limits of the range
                                        limits = rules[i][j].match(/^([0-9]+)\-([0-9]+)/);

                                        // if range is valid
                                        if (null !== limits) {

                                            // iterate through the range
                                            for (k = to_int(limits[1]); k <= to_int(limits[2]); k++)

                                                // if value is not already among the values of the rule
                                                // add it to the rule
                                                if ($.inArray(k, rules[i]) === -1) rules[i].push(k + '');

                                            // remove the range indicator
                                            rules[i].splice(j, 1);

                                        }

                                    }

                                // iterate through the items in the rule
                                // and make sure that numbers are numbers
                                for (j = 0; j < rules[i].length; j++) rules[i][j] = (isNaN(to_int(rules[i][j])) ? rules[i][j] : to_int(rules[i][j]));

                            }

                            // add to the correct list of processed rules
                            // first time we're doing disabled dates,
                            if (l === 0) disabled_dates.push(rules);

                            // second time we're doing enabled_dates
                            else if (l === 1) enabled_dates.push(rules);

                            // otherwise, we're doing the dates to which custom classes need to be applied
                            else {

                                if (undefined === custom_classes[custom_class_names[l - 2]]) custom_classes[custom_class_names[l - 2]] = [];
                                custom_classes[custom_class_names[l - 2]].push(rules);

                            }

                        });

                }

                var

                    // cache the current date (which is either the system's date or a custom one, if given)
                    date = plugin.settings.current_date !== false ? new Date(plugin.settings.current_date) : new Date(),

                    // when the date picker's starting date depends on the value of another date picker, this value will be
                    // set by the other date picker
                    // this value will be used as base for all calculations (if not set, will be the same as the current
                    // system date)
                    reference_date = (!plugin.settings.reference_date ? ($element.data('zdp_reference_date') && undefined !== $element.data('zdp_reference_date') ? $element.data('zdp_reference_date') : date) : plugin.settings.reference_date),

                    tmp_start_date, tmp_end_date;

                // reset these values here as this method might be called more than once during a date picker's lifetime
                // (when the selectable dates depend on the values from another date picker)
                start_date = undefined; end_date = undefined;

                // extract the date parts
                // also, save the current system month/day/year - we'll use them to highlight the current system date
                first_selectable_month = reference_date.getMonth();
                current_system_month = date.getMonth();
                first_selectable_year = reference_date.getFullYear();
                current_system_year = date.getFullYear();
                first_selectable_day = reference_date.getDate();
                current_system_day = date.getDate();

                // check if the calendar has any restrictions

                // calendar is future-only, starting today
                // it means we have a starting date (the current system date), but no ending date
                if (plugin.settings.direction === true) start_date = reference_date;

                // calendar is past only, ending today
                else if (plugin.settings.direction === false) {

                    // it means we have an ending date (the reference date), but no starting date
                    end_date = reference_date;

                    // extract the date parts
                    last_selectable_month = end_date.getMonth();
                    last_selectable_year = end_date.getFullYear();
                    last_selectable_day = end_date.getDate();

                } else if (

                    // if direction is not given as an array and the value is an integer > 0
                    (!$.isArray(plugin.settings.direction) && is_integer(plugin.settings.direction) && to_int(plugin.settings.direction) > 0) ||

                    // or direction is given as an array
                    ($.isArray(plugin.settings.direction) && (

                        // and first entry is a valid date
                        (tmp_start_date = check_date(plugin.settings.direction[0])) ||
                        // or a boolean TRUE
                        plugin.settings.direction[0] === true ||
                        // or an integer > 0
                        (is_integer(plugin.settings.direction[0]) && plugin.settings.direction[0] > 0)

                    ) && (

                        // and second entry is a valid date
                        (tmp_end_date = check_date(plugin.settings.direction[1])) ||
                        // or a boolean FALSE
                        plugin.settings.direction[1] === false ||
                        // or integer >= 0
                        (is_integer(plugin.settings.direction[1]) && plugin.settings.direction[1] >= 0)

                    ))

                ) {

                    // if an exact starting date was given, use that as a starting date
                    if (tmp_start_date) start_date = tmp_start_date;

                    // otherwise
                    else

                        // figure out the starting date
                        // use the Date object to normalize the date
                        // for example, 2011 05 33 will be transformed to 2011 06 02
                        start_date = new Date(
                            first_selectable_year,
                            first_selectable_month,
                            first_selectable_day + (!$.isArray(plugin.settings.direction) ? to_int(plugin.settings.direction) : to_int(plugin.settings.direction[0] === true ? 0 : plugin.settings.direction[0]))
                        );

                    // re-extract the date parts
                    first_selectable_month = start_date.getMonth();
                    first_selectable_year = start_date.getFullYear();
                    first_selectable_day = start_date.getDate();

                    // if an exact ending date was given and the date is after the starting date, use that as a ending date
                    if (tmp_end_date && +tmp_end_date >= +start_date) end_date = tmp_end_date;

                    // if have information about the ending date
                    else if (!tmp_end_date && plugin.settings.direction[1] !== false && $.isArray(plugin.settings.direction))

                        // figure out the ending date
                        // use the Date object to normalize the date
                        // for example, 2011 05 33 will be transformed to 2011 06 02
                        end_date = new Date(
                            first_selectable_year,
                            first_selectable_month,
                            first_selectable_day + to_int(plugin.settings.direction[1])
                        );

                    // if a valid ending date exists
                    if (end_date) {

                        // extract the date parts
                        last_selectable_month = end_date.getMonth();
                        last_selectable_year = end_date.getFullYear();
                        last_selectable_day = end_date.getDate();

                    }

                } else if (

                    // if direction is not given as an array and the value is an integer < 0
                    (!$.isArray(plugin.settings.direction) && is_integer(plugin.settings.direction) && to_int(plugin.settings.direction) < 0) ||

                    // or direction is given as an array
                    ($.isArray(plugin.settings.direction) && (

                        // and first entry is boolean FALSE
                        plugin.settings.direction[0] === false ||
                        // or an integer < 0
                        (is_integer(plugin.settings.direction[0]) && plugin.settings.direction[0] < 0)

                    ) && (

                        // and second entry is a valid date
                        (tmp_start_date = check_date(plugin.settings.direction[1])) ||
                        // or an integer >= 0
                        (is_integer(plugin.settings.direction[1]) && plugin.settings.direction[1] >= 0)

                    ))

                ) {

                    // figure out the ending date
                    // use the Date object to normalize the date
                    // for example, 2011 05 33 will be transformed to 2011 06 02
                    end_date = new Date(
                        first_selectable_year,
                        first_selectable_month,
                        first_selectable_day + (!$.isArray(plugin.settings.direction) ? to_int(plugin.settings.direction) : to_int(plugin.settings.direction[0] === false ? 0 : plugin.settings.direction[0]))
                    );

                    // re-extract the date parts
                    last_selectable_month = end_date.getMonth();
                    last_selectable_year = end_date.getFullYear();
                    last_selectable_day = end_date.getDate();

                    // if an exact starting date was given, and the date is before the ending date, use that as a starting date
                    if (tmp_start_date && +tmp_start_date < +end_date) start_date = tmp_start_date;

                    // if have information about the starting date
                    else if (!tmp_start_date && $.isArray(plugin.settings.direction))

                        // figure out the staring date
                        // use the Date object to normalize the date
                        // for example, 2011 05 33 will be transformed to 2011 06 02
                        start_date = new Date(
                            last_selectable_year,
                            last_selectable_month,
                            last_selectable_day - to_int(plugin.settings.direction[1])
                        );

                    // if a valid starting date exists
                    if (start_date) {

                        // extract the date parts
                        first_selectable_month = start_date.getMonth();
                        first_selectable_year = start_date.getFullYear();
                        first_selectable_day = start_date.getDate();

                    }

                // if there are disabled dates
                } else if ($.isArray(plugin.settings.disabled_dates) && plugin.settings.disabled_dates.length > 0)

                    // iterate through the rules for disabling dates
                    for (var interval in disabled_dates)

                        // only if there is a rule that disables *everything*
                        if ($.inArray('*', disabled_dates[interval][0]) > -1 && $.inArray('*', disabled_dates[interval][1]) > -1 && $.inArray('*', disabled_dates[interval][2]) > -1 && $.inArray('*', disabled_dates[interval][3]) > -1) {

                            var tmpDates = [];

                            // iterate through the rules for enabling dates
                            // looking for the minimum/maximum selectable date (if it's the case)
                            $.each(enabled_dates, function() {

                                var rule = this;

                                // if the rule doesn't apply to all years
                                if (rule[2][0] !== '*')

                                    // format date and store it in our stack
                                    tmpDates.push(parseInt(
                                        rule[2][0] +
                                        (rule[1][0] === '*' ? '12' : str_pad(rule[1][0], 2)) +
                                        (rule[0][0] === '*' ? (rule[1][0] === '*' ? '31' : new Date(rule[2][0], rule[1][0], 0).getDate()) : str_pad(rule[0][0], 2)), 10));

                            });

                            // sort dates ascending
                            tmpDates.sort();

                            // if we have any rules
                            if (tmpDates.length > 0) {

                                // get date parts
                                var matches = (tmpDates[0] + '').match(/([0-9]{4})([0-9]{2})([0-9]{2})/);

                                // assign the date parts to the appropriate variables
                                first_selectable_year = parseInt(matches[1], 10);
                                first_selectable_month = parseInt(matches[2], 10) - 1;
                                first_selectable_day = parseInt(matches[3], 10);

                            }

                            // don't look further
                            break;

                        }

                // if first selectable date exists but is disabled, find the actual first selectable date
                if (is_disabled(first_selectable_year, first_selectable_month, first_selectable_day)) {

                    // loop until we find the first selectable year
                    while (is_disabled(first_selectable_year))

                        // if calendar is past-only,
                        if (!start_date) {

                            // decrement the year
                            first_selectable_year--;

                            // because we've changed years, reset the month to December
                            first_selectable_month = 11;

                        // otherwise
                        } else {

                            // increment the year
                            first_selectable_year++;

                            // because we've changed years, reset the month to January
                            first_selectable_month = 0;

                        }

                    // loop until we find the first selectable month
                    while (is_disabled(first_selectable_year, first_selectable_month)) {

                        // if calendar is past-only
                        if (!start_date) {

                            // decrement the month
                            first_selectable_month--;

                            // because we've changed months, reset the day to the last day of the month
                            first_selectable_day = new Date(first_selectable_year, first_selectable_month + 1, 0).getDate();

                        // otherwise
                        } else {

                            // increment the month
                            first_selectable_month++;

                            // because we've changed months, reset the day to the first day of the month
                            first_selectable_day = 1;

                        }

                        // if we moved to a following year
                        if (first_selectable_month > 11) {

                            // increment the year
                            first_selectable_year++;

                            // reset the month to January
                            first_selectable_month = 0;

                            // because we've changed months, reset the day to the first day of the month
                            first_selectable_day = 1;

                        // if we moved to a previous year
                        } else if (first_selectable_month < 0) {

                            // decrement the year
                            first_selectable_year--;

                            // reset the month to December
                            first_selectable_month = 11;

                            // because we've changed months, reset the day to the last day of the month
                            first_selectable_day = new Date(first_selectable_year, first_selectable_month + 1, 0).getDate();

                        }

                    }

                    // loop until we find the first selectable day
                    while (is_disabled(first_selectable_year, first_selectable_month, first_selectable_day)) {

                        // if calendar is past-only, decrement the day
                        if (!start_date) first_selectable_day--;

                        // otherwise, increment the day
                        else first_selectable_day++;

                        // use the Date object to normalize the date
                        // for example, 2011 05 33 will be transformed to 2011 06 02
                        date = new Date(first_selectable_year, first_selectable_month, first_selectable_day);

                        // re-extract date parts from the normalized date
                        // as we use them in the current loop
                        first_selectable_year = date.getFullYear();
                        first_selectable_month = date.getMonth();
                        first_selectable_day = date.getDate();

                    }

                    // use the Date object to normalize the date
                    // for example, 2011 05 33 will be transformed to 2011 06 02
                    date = new Date(first_selectable_year, first_selectable_month, first_selectable_day);

                    // re-extract date parts from the normalized date
                    // as we use them in the current loop
                    first_selectable_year = date.getFullYear();
                    first_selectable_month = date.getMonth();
                    first_selectable_day = date.getDate();

                }

                // if "start_date" is given as JavaScript Date object...
                if (plugin.settings.start_date && typeof plugin.settings.start_date === 'object' && plugin.settings.start_date instanceof Date)

                    // ...convert it the a properly formatted string
                    plugin.settings.start_date = format(plugin.settings.start_date)

                // get the default date, from the element, and check if it represents a valid date, according to the required format
                var default_date = check_date($element.val() || (plugin.settings.start_date ? plugin.settings.start_date : ''));

                // if there is a default date, date picker is in "strict" mode, and the default date is disabled
                if (default_date && plugin.settings.strict && is_disabled(default_date.getFullYear(), default_date.getMonth(), default_date.getDate()))

                    // clear the value of the parent element
                    $element.val('');

                // updates value for the date picker whose starting date depends on the selected date (if any)
                if (!update && (undefined !== start_date || undefined !== default_date))
                    update_dependent(undefined !== default_date ? default_date : start_date);

                // if date picker is not always visible in a container
                if (!(plugin.settings.always_visible instanceof jQuery)) {

                    // if we're just creating the date picker
                    if (!update) {

                        // if a calendar icon should be added to the element the plugin is attached to, create the icon now
                        if (plugin.settings.show_icon) {

                            // strangely, in Firefox 21+ (or maybe even earlier) input elements have their "display" property
                            // set to "inline" instead of "inline-block" as do all the other browsers.
                            // because this behavior brakes the positioning of the icon, we'll set the "display" property to
                            // "inline-block" before anything else;
                            if (browser.name === 'firefox' && $element.is('input[type="text"]') && $element.css('display') === 'inline') $element.css('display', 'inline-block');

                            // we create a wrapper for the parent element so that we can later position the icon
                            // also, make sure the wrapper inherits positioning properties of the target element
                            var marginTop = parseInt($element.css('marginTop'), 10) || 0,
                                marginRight = parseInt($element.css('marginRight'), 10) || 0,
                                marginBottom = parseInt($element.css('marginBottom'), 10) || 0,
                                marginLeft = parseInt($element.css('marginLeft'), 10) || 0,
                                icon_wrapper = $('<span class="Zebra_DatePicker_Icon_Wrapper"></span>').css({
                                    display:        $element.css('display'),
                                    position:       $element.css('position') === 'static' ? 'relative' : $element.css('position'),
                                    float:          $element.css('float'),
                                    top:            $element.css('top'),
                                    right:          $element.css('right'),
                                    bottom:         $element.css('bottom'),
                                    left:           $element.css('left'),
                                    marginTop:      marginTop < 0 ? marginTop : 0,
                                    marginRight:    marginRight < 0 ? marginRight : 0,
                                    marginBottom:   marginBottom < 0 ? marginBottom : 0,
                                    marginLeft:     marginLeft < 0 ? marginLeft : 0,
                                    paddingTop:     marginTop,
                                    paddingRight:   marginRight,
                                    paddingBottom:  marginBottom,
                                    paddingLeft:    marginLeft
                                });

                            // if parent element has its "display" property set to "block"
                            // the wrapper has to have its "width" set
                            if ($element.css('display') === 'block') icon_wrapper.css('width', $element.outerWidth(true));

                            // put wrapper around the element
                            // also, reset the target element's positioning properties
                            $element.wrap(icon_wrapper).css({
                                position:       'relative',
                                float:          'none',
                                top:            'auto',
                                right:          'auto',
                                bottom:         'auto',
                                left:           'auto',
                                marginTop:      0,
                                marginRight:    0,
                                marginBottom:   0,
                                marginLeft:     0
                            });

                            // create the actual calendar icon (show a disabled icon if the element is disabled)
                            icon = $('<button type="button" tabindex="-1" class="Zebra_DatePicker_Icon' + ($element.attr('disabled') === 'disabled' ? ' Zebra_DatePicker_Icon_Disabled' : '') + '"></button>');

                            // a reference to the icon, as a global property
                            plugin.icon = icon;

                            // the date picker will open when clicking both the icon and the element the plugin is attached to
                            // (or the icon only, if set so)
                            clickables = plugin.settings.open_icon_only ? icon : icon.add($element);

                        // if calendar icon is not visible, the date picker will open when clicking the element
                        } else clickables = $element;

                        // attach the "click" and, if required, the "focus" event to the clickable elements (icon and/or element)
                        clickables.on('click.Zebra_DatePicker_' + uniqueid + (plugin.settings.open_on_focus ? ' focus.Zebra_DatePicker_' + uniqueid : ''), function() {

                            // if date picker is not visible and element is not disabled
                            if (datepicker.hasClass('dp_hidden') && !$element.attr('disabled'))

                                // if not a touch-enabled device or the element is read-only, show the date picker right away
                                if (!(is_touch && !plugin.settings.readonly_element)) plugin.show();

                                // if touch-enabled device and the element is not read-only
                                else {

                                    // stop a previously started timeout, if any
                                    clearTimeout(timeout);

                                    // wait for 600 milliseconds for the virtual keyboard to appear and show the date picker afterwards
                                    timeout = setTimeout(function() {
                                        plugin.show()
                                    }, 600);

                                }

                        });

                        // attach a keydown event to the clickable elements (icon and/or element)
                        clickables.on('keydown.Zebra_DatePicker_' + uniqueid, function(e) {

                            // if "Tab" key was pressed and the date picker is visible
                            if (e.keyCode === 9 && !datepicker.hasClass('dp_hidden'))

                                // hide the date picker
                                plugin.hide();

                        });

                        // if users can manually enter dates and a pair date element exists
                        if (!plugin.settings.readonly_element && plugin.settings.pair)

                            // whenever the element looses focus
                            $element.on('blur.Zebra_DatePicker_' + uniqueid, function() {

                                var date;

                                // if a valid date was entered, update the paired date picker
                                if ((date = check_date($(this).val())) && !is_disabled(date.getFullYear(), date.getMonth(), date.getDate())) update_dependent(date);

                            });

                        // if icon exists, inject it into the DOM, right after the parent element (and inside the wrapper)
                        if (undefined !== icon) icon.insertAfter($element);

                    }

                    // if calendar icon exists
                    if (undefined !== icon) {

                        // needed when updating: remove any inline style set previously by library,
                        // so we get the right values below
                        icon.attr('style', '');

                        var

                            // get element's width and height (including margins)
                            element_width = $element.outerWidth(),
                            element_height = $element.outerHeight(),

                            // get icon's width, height and margins
                            icon_width = icon.outerWidth(),
                            icon_height = icon.outerHeight();

                        // set icon's vertical position
                        icon.css('top', (element_height - icon_height) / 2);

                        // if icon is to be placed *inside* the element
                        // position the icon accordingly
                        if (plugin.settings.inside)

                            // if icon is to be placed on the right
                            if (plugin.settings.icon_position === 'right') {

                                // place the icon to the right, respecting the element's right padding
                                icon.css('right', plugin.settings.icon_margin !== false ? plugin.settings.icon_margin : original_attributes.padding_right);

                                // also, adjust the element's right padding
                                $element.css('paddingRight', ((plugin.settings.icon_margin !== false ? plugin.settings.icon_margin : original_attributes.padding_right) * 2) + icon_width);

                            // if icon is to be placed on the left
                            } else {

                                // place the icon to the left, respecting the element's left padding
                                icon.css('left', plugin.settings.icon_margin !== false ? plugin.settings.icon_margin : original_attributes.padding_left);

                                // also, adjust the element's left padding
                                $element.css('paddingLeft', ((plugin.settings.icon_margin !== false ? plugin.settings.icon_margin : original_attributes.padding_left) * 2) + icon_width);

                            }

                        // if icon is to be placed to the right of the element
                        // position the icon accordingly
                        else icon.css('left', element_width + (plugin.settings.icon_margin !== false ? plugin.settings.icon_margin : original_attributes.padding_left));

                        // assume the datepicker is not disabled
                        icon.removeClass('Zebra_DatePicker_Icon_Disabled');

                        // if element the datepicker is attached to became disabled, disable the calendar icon, too
                        if ($element.attr('disabled') === 'disabled') icon.addClass('Zebra_DatePicker_Icon_Disabled');

                    }

                }

                // if the "Today" button is to be shown and it makes sense to be shown
                // (the "days" view is available and "today" is not a disabled date)
                show_select_today = (plugin.settings.show_select_today !== false && $.inArray('days', views) > -1 && !is_disabled(current_system_year, current_system_month, current_system_day) ? plugin.settings.show_select_today : false);

                // if we just needed to recompute the things above
                if (update) {

                    // make sure we update these strings, in case they've changed
                    $('.dp_previous', datepicker).html(plugin.settings.navigation[0]);
                    $('.dp_next', datepicker).html(plugin.settings.navigation[1]);
                    $('.dp_time_controls_increase .dp_time_control', datepicker).html(plugin.settings.navigation[2]);
                    $('.dp_time_controls_decrease .dp_time_control', datepicker).html(plugin.settings.navigation[3]);
                    $('.dp_clear', datepicker).html(plugin.settings.lang_clear_date);
                    $('.dp_today', datepicker).html(plugin.settings.show_select_today);

                    // don't go further
                    return;

                }

                // update icon/date picker position on resize and/or changing orientation
                $(window).on('resize.Zebra_DatePicker_' + uniqueid + ', orientationchange.Zebra_DatePicker_' + uniqueid, function() {

                    // hide the date picker
                    plugin.hide();

                });

                // generate the container that will hold everything
                var html = '' +
                    '<div class="Zebra_DatePicker">' +
                        '<table class="dp_header dp_actions">' +
                            '<tr>' +
                                '<td class="dp_previous">' + plugin.settings.navigation[0] + (is_iOS ? '&#xFE0E;' : '') + '</td>' +
                                '<td class="dp_caption"></td>' +
                                '<td class="dp_next">' + plugin.settings.navigation[1] + (is_iOS ? '&#xFE0E;' : '') + '</td>' +
                            '</tr>' +
                        '</table>' +
                        '<table class="dp_daypicker' + (plugin.settings.show_week_number ? ' dp_week_numbers' : '') + ' dp_body"></table>' +
                        '<table class="dp_monthpicker dp_body"></table>' +
                        '<table class="dp_yearpicker dp_body"></table>' +
                        '<table class="dp_timepicker dp_body"></table>' +
                        '<table class="dp_footer dp_actions"><tr>' +
                            '<td class="dp_today">' + show_select_today + '</td>' +
                            '<td class="dp_clear">' + plugin.settings.lang_clear_date + '</td>' +
                            '<td class="dp_view_toggler dp_icon">&nbsp;&nbsp;&nbsp;&nbsp;</td>' +
                            '<td class="dp_confirm dp_icon"></td>' +
                        '</tr></table>' +
                    '</div>';

                // create a jQuery object out of the HTML above and create a reference to it
                datepicker = $(html);

                // create references to the different parts of the date picker
                header = $('table.dp_header', datepicker);
                daypicker = $('table.dp_daypicker', datepicker);
                monthpicker = $('table.dp_monthpicker', datepicker);
                yearpicker = $('table.dp_yearpicker', datepicker);
                timepicker = $('table.dp_timepicker', datepicker);
                footer = $('table.dp_footer', datepicker);
                selecttoday = $('td.dp_today', footer);
                cleardate = $('td.dp_clear', footer);
                view_toggler = $('td.dp_view_toggler', footer);
                confirm_selection = $('td.dp_confirm', footer);

                // if date picker is not always visible in a container
                if (!(plugin.settings.always_visible instanceof jQuery))

                    // inject the container into the DOM
                    plugin.settings.container.append(datepicker);

                // otherwise, if element is not disabled
                else if (!$element.attr('disabled')) {

                    // inject the date picker into the designated container element
                    plugin.settings.always_visible.append(datepicker);

                    // and make it visible right away
                    plugin.show();

                }

                // add the mouseover/mousevents to all to the date picker's cells
                // except those that are not selectable
                datepicker
                    .on('mouseover', 'td:not(.dp_disabled)', function() {
                        $(this).addClass('dp_hover');
                    })
                    .on('mouseout', 'td:not(.dp_disabled)', function() {
                        $(this).removeClass('dp_hover');
                    });

                // prevent text selection (prevent accidental select when user clicks too fast)
                disable_text_select(datepicker);

                // event for when clicking the "previous" button
                // (directions are inverted when in RTL mode)
                $(plugin.settings.rtl ? '.dp_next' : '.dp_previous', header).on('click', function() {

                    // if view is "months"
                    // decrement year by one
                    if (view === 'months') selected_year--;

                    // if view is "years"
                    // decrement years by 12
                    else if (view === 'years') selected_year -= 12;

                    // if view is "days"
                    // decrement the month and
                    // if month is out of range
                    else if (--selected_month < 0) {

                        // go to the last month of the previous year
                        selected_month = 11;
                        selected_year--;

                    }

                    // generate the appropriate view
                    manage_views();

                });

                // if "fast_navigation" is enabled, allow clicking the upper label for quickly navigating through months and years
                if (plugin.settings.fast_navigation)

                    // attach a click event to the caption in header
                    $('.dp_caption', header).on('click', function() {

                        // if current view is "days", take the user to the next view, depending on the format
                        if (view === 'days') view = ($.inArray('months', views) > -1 ? 'months' : ($.inArray('years', views) > -1 ? 'years' : 'days'));

                        // if current view is "months", take the user to the next view, depending on the format
                        else if (view === 'months') view = ($.inArray('years', views) > -1 ? 'years' : ($.inArray('days', views) > -1 ? 'days' : 'months'));

                        // if current view is "years", take the user to the next view, depending on the format
                        else view = ($.inArray('days', views) > -1 ? 'days' : ($.inArray('months', views) > -1 ? 'months' : 'years'));

                        // generate the appropriate view
                        manage_views();

                    });

                // event for when clicking the "next" button
                // (directions are inverted when in RTL mode)
                $(plugin.settings.rtl ? '.dp_previous' : '.dp_next', header).on('click', function() {

                    // if view is "months"
                    // increment year by 1
                    if (view === 'months') selected_year++;

                    // if view is "years"
                    // increment years by 12
                    else if (view === 'years') selected_year += 12;

                    // if view is "days"
                    // increment the month and
                    // if month is out of range
                    else if (++selected_month === 12) {

                        // go to the first month of the next year
                        selected_month = 0;
                        selected_year++;

                    }

                    // generate the appropriate view
                    manage_views();

                });

                // attach a click event for the cells in the day picker
                daypicker.on('click', 'td:not(.dp_disabled)', function() {

                    var matches;

                    // if other months are selectable and currently clicked cell contains a class with the cell's date
                    if (plugin.settings.select_other_months && $(this).attr('class') && null !== (matches = $(this).attr('class').match(/date\_([0-9]{4})(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])/)))

                        // use the stored date
                        select_date(matches[1], matches[2] - 1, matches[3], 'days', $(this));

                    // put selected date in the element the plugin is attached to, and hide the date picker
                    else select_date(selected_year, selected_month, to_int($(this).html()), 'days', $(this));

                });

                // attach a click event for the cells in the month picker
                monthpicker.on('click', 'td:not(.dp_disabled)', function() {

                    // get the month we've clicked on
                    var matches = $(this).attr('class').match(/dp\_month\_([0-9]+)/);

                    // set the selected month
                    selected_month = to_int(matches[1]);

                    // if user can select only years and months
                    if ($.inArray('days', views) === -1)

                        // put selected date in the element the plugin is attached to, and hide the date picker
                        select_date(selected_year, selected_month, 1, 'months', $(this));

                    else {

                        // direct the user to the "days" view
                        view = 'days';

                        // if date picker is always visible
                        // empty the value in the text box the date picker is attached to
                        if (plugin.settings.always_visible) $element.val('');

                        // generate the appropriate view
                        manage_views();

                    }

                });

                // attach a click event for the cells in the year picker
                yearpicker.on('click', 'td:not(.dp_disabled)', function() {

                    // set the selected year
                    selected_year = to_int($(this).html());

                    // if user can select only years
                    if ($.inArray('months', views) === -1)

                        // put selected date in the element the plugin is attached to, and hide the date picker
                        select_date(selected_year, 1, 1, 'years', $(this));

                    else {

                        // direct the user to the "months" view
                        view = 'months';

                        // if date picker is always visible
                        // empty the value in the text box the date picker is attached to
                        if (plugin.settings.always_visible) $element.val('');

                        // generate the appropriate view
                        manage_views();

                    }

                });

                // function to execute when the "Today" button is clicked
                selecttoday.on('click', function(e) {

                    // date might have changed since we opened the date picker, so always use the current date
                    var date = plugin.settings.current_date !== false ? new Date(plugin.settings.current_date) : new Date();

                    e.preventDefault();

                    // select the current date
                    select_date(date.getFullYear(), date.getMonth(), date.getDate(), 'days', $('.dp_current', daypicker));

                });

                // function to execute when the "Clear" button is clicked
                cleardate.on('click', function(e) {

                    e.preventDefault();

                    // clear the element's value
                    $element.val('');

                    // reset these values
                    default_day = null; default_month = null; default_year = null;

                    // if date picker is not always visible
                    if (!plugin.settings.always_visible) {

                        // reset these values
                        selected_month = null; selected_year = null;

                    // if date picker is always visible
                    } else

                        // remove the "selected" class from all cells that have it
                        $('td.dp_selected', datepicker).removeClass('dp_selected');

                    // give the focus back to the parent element
                    $element.focus();

                    // hide the date picker
                    plugin.hide();

                    // if a callback function exists for when clearing a date
                    if (plugin.settings.onClear && typeof plugin.settings.onClear === 'function')

                        // execute the callback function and pass as argument the element the plugin is attached to
                        plugin.settings.onClear.call($element);

                });

                // function to execute when the clock/calendar button is clicked in the footer
                view_toggler.on('click', function() {

                    // if we're not in the time picker mode
                    if (view !== 'time') {

                        // switch to time picker mode
                        view = 'time';
                        manage_views();

                    // if we are already in the time picker mode,
                    // switch back to the standard view
                    // (let the click on the header's caption handle things)
                    } else $('.dp_caption', header).trigger('click');

                });

                // when the "confirm selection" button is clicked, hide the date picker
                // (visible only when in the "time" view)
                confirm_selection.on('click', function() {

                    // as users may click this before making any adjustments to time, simulate time adjustment so that
                    // a value is selected
                    $('.dp_time_controls_increase td', timepicker).trigger('click');
                    $('.dp_time_controls_decrease td', timepicker).trigger('click');

                    // if a callback function exists for when selecting a date
                    if (plugin.settings.onSelect && typeof plugin.settings.onSelect === 'function') {

                        var js_date = new Date(selected_year, selected_month, default_day,
                            (timepicker_config && timepicker_config.hours ? selected_hour + (timepicker_config.ampm && ((selected_ampm === 'pm' && selected_hour < 12) || (selected_ampm === 'am' && selected_hour === 12)) ? 12 : 0) : 0),
                            (timepicker_config && timepicker_config.minutes ? selected_minute : 0),
                            (timepicker_config && timepicker_config.seconds ? selected_second : 0)
                        );

                        // execute the callback function
                        // make "this" inside the callback function refer to the element the date picker is attached to, as a jQuery object
                        plugin.settings.onSelect.call($element, format(js_date), selected_year + '-' + str_pad(selected_month + 1, 2) + '-' + str_pad(default_day, 2) + (timepicker_config ? ' ' + str_pad(js_date.getHours(), 2) + ':' + str_pad(js_date.getMinutes(), 2) + ':' + str_pad(js_date.getSeconds(), 2) : ''), js_date);

                    }

                    plugin.hide();

                });

                // handle value increases on the time picker
                datepicker.on('click', '.dp_time_controls_increase td, .dp_time_controls_decrease td', function() {

                    var

                        // are we increasing or decreasing values?
                        increase = $(this).parent('.dp_time_controls_increase').length > 0,

                        // figure out what we're increasing (hour, minutes, seconds, ampm)
                        matches = $(this).attr('class').match(/dp\_time\_([^\s]+)/i),
                        value_container = $('.dp_time_segments .dp_time_' + matches[1] + (matches[1] !== 'ampm' ? 's' : ''), timepicker),

                        // the current value (strip the zeros in front)
                        value = value_container.text().toLowerCase(),

                        // the array with allowed values
                        lookup = timepicker_config[matches[1] + (matches[1] !== 'ampm' ? 's' : '')],

                        // the current value's position in the array of allowed values
                        current_value_position = $.inArray(matches[1] !== 'ampm' ? parseInt(value, 10) : value, lookup),

                        // the next value's position in the lookup array
                        next_value_position = current_value_position === -1 ? 0 : (increase ? (current_value_position + 1 >= lookup.length ? 0 : current_value_position + 1) : (current_value_position - 1 < 0 ? lookup.length - 1 : current_value_position - 1)),

                        default_date;

                    // increase/decrease the required value according to the values in the lookup array
                    if (matches[1] === 'hour') selected_hour = lookup[next_value_position];
                    else if (matches[1] === 'minute') selected_minute = lookup[next_value_position];
                    else if (matches[1] === 'second') selected_second = lookup[next_value_position];
                    else selected_ampm = lookup[next_value_position];

                    // if a default day is not available and the "start_date" property is set
                    if (!default_day && plugin.settings.start_date) {

                        // check if "start_date" is valid according to the format
                        default_date = check_date(plugin.settings.start_date);

                        // ...and if it is, extract the day from there
                        if (default_date) default_day = default_date.getDate();

                    }

                    // if still no value, use the first selectable day
                    if (!default_day) default_day = first_selectable_day;

                    // set the new value
                    value_container.text(str_pad(lookup[next_value_position], 2).toUpperCase());

                    // update the value in the element
                    select_date(selected_year, selected_month, default_day);

                });

                // if date picker is not always visible in a container
                if (!(plugin.settings.always_visible instanceof jQuery)) {

                    // if we dragged the screen
                    $(document).on('touchmove.Zebra_DatePicker_' + uniqueid, function() {

                        // set this flag to TRUE
                        touchmove = true;

                    });

                    // whenever anything is clicked on the page
                    $(document).on('mousedown.Zebra_DatePicker_' + uniqueid + ' touchend.Zebra_DatePicker_' + uniqueid, function(e) {

                        // if this happened on a touch-enabled device and it represents the end of finger movement instead of a tap
                        // set the "touchmove" flag to FALSE and don't go further
                        if (e.type === 'touchend' && touchmove) {

                            // we now know that this is a touch enabled device
                            is_touch = true;

                            return (touchmove = false);

                        }

                        // always set this to FALSE here
                        touchmove = false;

                        // if
                        if (

                            // date picker is visible
                            !datepicker.hasClass('dp_hidden') &&

                            (
                                // date picker opens only on interacting with the icon, icon exists, but it is not the clicked element
                                (plugin.settings.open_icon_only && plugin.icon && $(e.target).get(0) !== plugin.icon.get(0)) ||

                                // date picker doesn't open only on interacting with the icon but the clicked element it's not the icon nor the parent element
                                (!plugin.settings.open_icon_only && $(e.target).get(0) !== $element.get(0) && (!plugin.icon || $(e.target).get(0) !== plugin.icon.get(0)))

                            ) &&

                            // and the click is not inside the calendar
                            $(e.target).parents().filter('.Zebra_DatePicker').length === 0

                        // hide the date picker
                        ) plugin.hide(true);

                    });

                    // whenever a key is pressed on the page
                    $(document).on('keyup.Zebra_DatePicker_' + uniqueid, function(e) {

                        // if the date picker is visible
                        // and the pressed key is ESC
                        // hide the date picker
                        if (!datepicker.hasClass('dp_hidden') && e.which === 27) plugin.hide();

                    });

                }

                // last thing is to pre-render some of the date picker right away
                manage_views();

            },

            /**
             *  Checks if a string represents a valid date according to the format defined by the "format" property.
             *
             *  @param  string  str_date    A string representing a date, formatted accordingly to the "format" property.
             *                              For example, if "format" is "Y-m-d" the string should look like "2011-06-01"
             *
             *  @return mixed               Returns a JavaScript Date object if string represents a valid date according
             *                              formatted according to the "format" property, or FALSE otherwise.
             *
             *  @access private
             */
            check_date = function(str_date) {

                // treat argument as a string
                str_date += '';

                // if value is given
                if ($.trim(str_date) !== '') {

                    var

                        // prepare the format by removing white space from it
                        // and also escape characters that could have special meaning in a regular expression
                        format = escape_regexp(plugin.settings.format),

                        // allowed characters in date's format
                        format_chars = ['d', 'D', 'j', 'l', 'N', 'S', 'w', 'F', 'm', 'M', 'n', 'Y', 'y', 'G', 'g', 'H', 'h', 'i', 's', 'a', 'A'],

                        // "matches" will contain the characters defining the date's format
                        matches = [],

                        // "regexp" will contain the regular expression built for each of the characters used in the date's format
                        regexp = [],

                        // "position" will contain the position of the character found in the date's format
                        position = null,

                        // "segments" will contain the matches of the regular expression
                        segments = null,

                        date, i;

                    // iterate through the allowed characters in date's format
                    for (i = 0; i < format_chars.length; i++)

                        // if character is found in the date's format
                        if ((position = format.indexOf(format_chars[i])) > -1)

                            // save it, alongside the character's position
                            matches.push({
                                character: format_chars[i],
                                position: position
                            });

                    // sort characters defining the date's format based on their position, ascending
                    matches.sort(function(a, b) { return a.position - b.position; });

                    // iterate through the characters defining the date's format
                    $.each(matches, function(index, match) {

                        // add to the array of regular expressions, based on the character
                        switch (match.character) {

                            case 'd': regexp.push('0[1-9]|[12][0-9]|3[01]'); break;
                            case 'D': regexp.push('[a-z]{3}'); break;
                            case 'j': regexp.push('[1-9]|[12][0-9]|3[01]'); break;
                            case 'l': regexp.push('[a-z\u00C0-\u024F]+'); break;
                            case 'N': regexp.push('[1-7]'); break;
                            case 'S': regexp.push('st|nd|rd|th'); break;
                            case 'w': regexp.push('[0-6]'); break;
                            case 'F': regexp.push('[a-z]+'); break;
                            case 'm': regexp.push('0[1-9]|1[012]'); break;
                            case 'M': regexp.push('[a-z]{3}'); break;
                            case 'n': regexp.push('[1-9]|1[012]'); break;
                            case 'Y': regexp.push('[0-9]{4}'); break;
                            case 'y': regexp.push('[0-9]{2}'); break;
                            case 'G': regexp.push('[1-9]|1[0-9]|2[0123]'); break;
                            case 'g': regexp.push('[0-9]|1[012]'); break;
                            case 'H': regexp.push('0[0-9]|1[0-9]|2[0123]'); break;
                            case 'h': regexp.push('0[0-9]|1[012]'); break;
                            case 'i': regexp.push('0[0-9]|[12345][0-9]'); break;
                            case 's': regexp.push('0[0-9]|[12345][0-9]'); break;
                            case 'a': regexp.push('am|pm'); break;
                            case 'A': regexp.push('AM|PM'); break;

                        }

                    });

                    // if we have an array of regular expressions
                    if (regexp.length) {

                        // we will replace characters in the date's format in reversed order
                        matches.reverse();

                        // iterate through the characters in date's format
                        $.each(matches, function(index, match) {

                            // replace each character with the appropriate regular expression
                            format = format.replace(match.character, '(' + regexp[regexp.length - index - 1] + ')');

                        });

                        // the final regular expression
                        regexp = new RegExp('^' + format + '$', 'ig');

                        // if regular expression was matched
                        if ((segments = regexp.exec(str_date))) {

                            // check if date is a valid date (i.e. there's no February 31)

                            var tmpdate = new Date(),
                                original_day = 1,
                                original_month = tmpdate.getMonth() + 1,
                                original_year = tmpdate.getFullYear(),
                                original_hours = tmpdate.getHours(),
                                original_minutes = tmpdate.getMinutes(),
                                original_seconds = tmpdate.getSeconds(),
                                original_ampm,
                                english_days = ['Nedjelja', 'Ponedjeljak', 'Utorak', 'Srijeda', '&ccaron;etvrtak', 'Petak', 'Subota'],
                                english_months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
                                iterable,

                                // by default, we assume the date is valid
                                valid = true;

                            // reverse back the characters in the date's format
                            matches.reverse();

                            // iterate through the characters in the date's format
                            $.each(matches, function(index, match) {

                                // if the date is not valid, don't look further
                                if (!valid) return true;

                                // based on the character
                                switch (match.character) {

                                    case 'm':
                                    case 'n':

                                        // extract the month from the value entered by the user
                                        original_month = to_int(segments[index + 1]);

                                        break;

                                    case 'd':
                                    case 'j':

                                        // extract the day from the value entered by the user
                                        original_day = to_int(segments[index + 1]);

                                        break;

                                    case 'D':
                                    case 'l':
                                    case 'F':
                                    case 'M':

                                        // if day is given as day name, we'll check against the names in the used language
                                        if (match.character === 'D' || match.character === 'l') iterable = plugin.settings.days;

                                        // if month is given as month name, we'll check against the names in the used language
                                        else iterable = plugin.settings.months;

                                        // by default, we assume the day or month was not entered correctly
                                        valid = false;

                                        // iterate through the month/days in the used language
                                        $.each(iterable, function(key, value) {

                                            // if month/day was entered correctly, don't look further
                                            if (valid) return true;

                                            // if month/day was entered correctly
                                            if (segments[index + 1].toLowerCase() === value.substring(0, (match.character === 'D' || match.character === 'M' ? 3 : value.length)).toLowerCase()) {

                                                // extract the day/month from the value entered by the user
                                                switch (match.character) {

                                                    case 'D': segments[index + 1] = english_days[key].substring(0, 3); break;
                                                    case 'l': segments[index + 1] = english_days[key]; break;
                                                    case 'F': segments[index + 1] = english_months[key]; original_month = key + 1; break;
                                                    case 'M': segments[index + 1] = english_months[key].substring(0, 3); original_month = key + 1; break;

                                                }

                                                // day/month value is valid
                                                valid = true;

                                            }

                                        });

                                        break;

                                    case 'Y':

                                        // extract the year from the value entered by the user
                                        original_year = to_int(segments[index + 1]);

                                        break;

                                    case 'y':

                                        // extract the year from the value entered by the user
                                        original_year = '19' + to_int(segments[index + 1]);

                                        break;

                                    case 'G':
                                    case 'H':
                                    case 'g':
                                    case 'h':

                                        // extract the hours from the value entered by the user
                                        original_hours = to_int(segments[index + 1]);
                                        break;

                                    case 'i':

                                        // extract the minutes from the value entered by the user
                                        original_minutes = to_int(segments[index + 1]);
                                        break;

                                    case 's':

                                        // extract the seconds from the value entered by the user
                                        original_seconds = to_int(segments[index + 1]);
                                        break;

                                    case 'a':
                                    case 'A':

                                        // extract the seconds from the value entered by the user
                                        original_ampm = segments[index + 1].toLowerCase();
                                        break;

                                }

                            });

                            // if everything is ok so far
                            if (valid) {

                                // generate a Date object using the values entered by the user
                                // (handle also the case when original_month and/or original_day are undefined - i.e date format is "Y-m" or "Y")
                                date = new Date(original_year, (original_month || 1) - 1, original_day || 1, original_hours + (original_ampm === 'pm' && original_hours !== 12 ? 12 : (original_ampm === 'am' && original_hours === 12 ? -12 : 0)), original_minutes, original_seconds);

                                // if, after that, the date is the same as the date entered by the user
                                if (date.getFullYear() === original_year && date.getDate() === (original_day || 1) && date.getMonth() === ((original_month || 1) - 1))

                                    // return the date as JavaScript date object
                                    return date;

                            }

                        }

                    }

                    // if script gets this far, return false as something must've went wrong
                    return false;

                }

            },

            /**
             *  Prevents the possibility of selecting text on a given element. Used on the "previous" and "next" buttons
             *  where text might get accidentally selected when user quickly clicks on the buttons.
             *
             *  Code by http://chris-barr.com/index.php/entry/disable_text_selection_with_jquery/
             *
             *  @param  jQuery Element  el  A jQuery element on which to prevents text selection.
             *
             *  @return void
             *
             *  @access private
             */
            disable_text_select = function(el) {

                // if browser is Firefox
                if (browser.name === 'firefox') el.css('MozUserSelect', 'none');

                // if browser is Internet Explorer
                else if (browser.name === 'explorer') $(document).on('selectstart', el, function() { return false; });

                // for the other browsers
                else el.mousedown(function() { return false; });

            },

            /**
             *  Escapes special characters in a string, preparing it for use in a regular expression.
             *
             *  @param  string  str     The string in which special characters should be escaped.
             *
             *  @return string          Returns the string with escaped special characters.
             *
             *  @access private
             */
            escape_regexp = function(str) {

                // return string with special characters escaped
                return str.replace(/([-.,*+?^${}()|[\]\/\\])/g, '\\$1');

            },

            /**
             *  Formats a JavaScript date object to the format specified by the "format" property.
             *  Code taken from http://electricprism.com/aeron/calendar/
             *
             *  @param  date    date    A valid JavaScript date object
             *
             *  @return string          Returns a string containing the formatted date
             *
             *  @access private
             */
            format = function(date) {

                var result = '',

                    // extract parts of the date:
                    // day number, 1 - 31
                    j = date.getDate(),

                    // day of the week, 0 - 6, Sunday - Saturday
                    w = date.getDay(),

                    // the name of the day of the week Sunday - Saturday
                    l = plugin.settings.days[w],

                    // the month number, 1 - 12
                    n = date.getMonth() + 1,

                    // the month name, January - December
                    f = plugin.settings.months[n - 1],

                    // the year (as a string)
                    y = date.getFullYear() + '',

                    // the hour, 0-23
                    h = date.getHours(),

                    // the hour in 12 hours format
                    h12 = h % 12 === 0 ? 12 : h % 12,

                    // the minute, 0-59
                    m = date.getMinutes(),

                    // the second, 0-59
                    s = date.getSeconds(),

                    // am/pm
                    a = (h >= 12 ? 'pm' : 'am'),

                    i, chr;

                // iterate through the characters in the format
                for (i = 0; i < plugin.settings.format.length; i++) {

                    // extract the current character
                    chr = plugin.settings.format.charAt(i);

                    // see what character it is
                    switch (chr) {

                        // year as two digits
                        case 'y': y = y.substr(2);  // jshint ignore:line

                        // year as four digits
                        // falls through
                        case 'Y': result += y; break;

                        // month number, prefixed with 0
                        case 'm': n = str_pad(n, 2);    // jshint ignore:line

                        // month number, not prefixed with 0
                        // falls through
                        case 'n': result += n; break;

                        // month name, three letters
                        case 'M': f = ($.isArray(plugin.settings.months_abbr) && undefined !== plugin.settings.months_abbr[n - 1] ? plugin.settings.months_abbr[n - 1] : plugin.settings.months[n - 1].substr(0, 3));   // jshint ignore:line

                        // full month name
                        // falls through
                        case 'F': result += f; break;

                        // day number, prefixed with 0
                        case 'd': j = str_pad(j, 2);    // jshint ignore:line

                        // day number not prefixed with 0
                        // falls through
                        case 'j': result += j; break;

                        // day name, three letters
                        case 'D': l = ($.isArray(plugin.settings.days_abbr) && undefined !== plugin.settings.days_abbr[w] ? plugin.settings.days_abbr[w] : plugin.settings.days[w].substr(0, 3));   // jshint ignore:line

                        // full day name
                        // falls through
                        case 'l': result += l; break;

                        // ISO-8601 numeric representation of the day of the week, 1 - 7
                        case 'N': w++;  // jshint ignore:line

                        // day of the week, 0 - 6
                        // falls through
                        case 'w': result += w; break;

                        // English ordinal suffix for the day of the month, 2 characters
                        // (st, nd, rd or th (works well with j))
                        case 'S':

                            if (j % 10 === 1 && j !== 11) result += 'st';

                            else if (j % 10 === 2 && j !== 12) result += 'nd';

                            else if (j % 10 === 3 && j !== 13) result += 'rd';

                            else result += 'th';

                            break;

                        // hour in 12 hours format, without leading zeros
                        case 'g': result += h12; break;

                        // hour in 12 hours format, with leading zeros
                        case 'h': result += str_pad(h12, 2); break;

                        // hour in 24 hours format, without leading zeros
                        case 'G': result += h; break;

                        // hour in 24 hours format, with leading zeros
                        case 'H': result += str_pad(h, 2); break;

                        // minutes, with leading zeros
                        case 'i': result += str_pad(m, 2); break;

                        // seconds, with leading zeros
                        case 's': result += str_pad(s, 2); break;

                        // am/pm, lowercase
                        case 'a': result += a; break;

                        // am/pm, uppercase
                        case 'A': result += a.toUpperCase(); break;

                        // this is probably the separator
                        default: result += chr;

                    }

                }

                // return formated date
                return result;

            },

            /**
             *  Generates the day picker view, and displays it
             *
             *  @return void
             *
             *  @access private
             */
            generate_daypicker = function() {

                var

                    // get the number of days in the selected month
                    days_in_month = new Date(selected_year, selected_month + 1, 0).getDate(),

                    // get the selected month's starting day (from 0 to 6)
                    first_day = new Date(selected_year, selected_month, 1).getDay(),

                    // how many days are there in the previous month
                    days_in_previous_month = new Date(selected_year, selected_month, 0).getDate(),

                    // how many days are there to be shown from the previous month
                    days_from_previous_month = first_day - plugin.settings.first_day_of_week,

                    i, html, day, real_date, real_year, real_month, real_day, weekday, class_name, custom_class_name, is_weekend, rtl_offset;

                // the final value of how many days are there to be shown from the previous month
                days_from_previous_month = days_from_previous_month < 0 ? 7 + days_from_previous_month : days_from_previous_month;

                // manage header caption and enable/disable navigation buttons if necessary
                manage_header(plugin.settings.header_captions.days);

                // start generating the HTML
                html = '<tr>';

                // if a column featuring the number of the week is to be shown
                if (plugin.settings.show_week_number)

                    // column title
                    html += '<th>' + plugin.settings.show_week_number + '</th>';

                // name of week days
                // show the abbreviated day names (or only the first two letters of the full name if no abbreviations are specified)
                // and also, take in account the value of the "first_day_of_week" property
                for (i = 0; i < 7; i++) {

                    // the week day's number; account for RTL
                    day = (plugin.settings.first_day_of_week + (plugin.settings.rtl ? 6 - i : i)) % 7;

                    html += '<th>' + ($.isArray(plugin.settings.days_abbr) && undefined !== plugin.settings.days_abbr[day] ? plugin.settings.days_abbr[day] : plugin.settings.days[day].substr(0, 2)) + '</th>';

                }

                html += '</tr><tr>';

                // the calendar shows a total of 42 days
                for (i = 0; i < 42; i++) {

                    // we need some additional math when showing an RTL calendar
                    rtl_offset = (plugin.settings.rtl ? 6 - ((i % 7) * 2) : 0);

                    // seven days per row
                    if (i > 0 && i % 7 === 0) html += '</tr><tr>';

                    // if week number is to be shown
                    if (i % 7 === 0 && plugin.settings.show_week_number)

                        // show ISO 8601 week number
                        html += '<th>' + get_week_number(new Date(selected_year, selected_month, (i - days_from_previous_month + 1))) + '</th>';

                    // the number of the day in month
                    day = rtl_offset + (i - days_from_previous_month + 1);

                    // if dates in previous/next month can be selected, and this is one of those days
                    if (plugin.settings.select_other_months && (i < days_from_previous_month || day > days_in_month)) {

                        // use the Date object to normalize the date
                        // for example, 2011 05 33 will be transformed to 2011 06 02
                        real_date = new Date(selected_year, selected_month, day);
                        real_year = real_date.getFullYear();
                        real_month = real_date.getMonth();
                        real_day = real_date.getDate();

                        // extract normalized date parts and merge them
                        real_date = real_year + str_pad(real_month + 1, 2) + str_pad(real_day, 2);

                    }

                    // get the week day (0 to 6, Sunday to Saturday)
                    weekday = (plugin.settings.first_day_of_week + i) % 7;

                    // is day on a weekend?
                    is_weekend = ($.inArray(weekday, plugin.settings.weekend_days) > -1);

                    // if this is a day from the previous month
                    if ((plugin.settings.rtl && day < 1) || (!plugin.settings.rtl && i < days_from_previous_month))

                        html += '<td class="dp_not_in_month ' + (is_weekend ? 'dp_weekend ' : '') + (plugin.settings.select_other_months && !is_disabled(real_year, real_month, real_day) ? 'date_' + real_date : 'dp_disabled') + '">' + (plugin.settings.select_other_months || plugin.settings.show_other_months ? str_pad(rtl_offset + days_in_previous_month - days_from_previous_month + i + 1, plugin.settings.zero_pad ? 2 : 0) : '&nbsp;') + '</td>';

                    // if this is a day from the next month
                    else if (day > days_in_month)

                        html += '<td class="dp_not_in_month ' + (is_weekend ? 'dp_weekend ' : '') + (plugin.settings.select_other_months && !is_disabled(real_year, real_month, real_day) ? 'date_' + real_date : 'dp_disabled') + '">' + (plugin.settings.select_other_months || plugin.settings.show_other_months ? str_pad(day - days_in_month, plugin.settings.zero_pad ? 2 : 0) : '&nbsp;') + '</td>';

                    // if this is a day from the current month
                    else {

                        class_name = '';

                        // custom class, if any
                        custom_class_name = get_custom_class(selected_year, selected_month, day);

                        // if day is in weekend
                        if (is_weekend) class_name = ' dp_weekend';

                        // highlight the current system date
                        if (selected_month === current_system_month && selected_year === current_system_year && current_system_day === day) class_name += ' dp_current';

                        // apply custom class, if a custom class exists
                        if (custom_class_name !== '') class_name += ' ' + custom_class_name;

                        // highlight the currently selected date
                        if (selected_month === default_month && selected_year === default_year && default_day === day) class_name += ' dp_selected';

                        // if date needs to be disabled
                        if (is_disabled(selected_year, selected_month, day)) class_name += ' dp_disabled';

                        // print the day of the month (if "day" is NaN, use an empty string instead)
                        html += '<td' + (class_name !== '' ? ' class="' + $.trim(class_name) + '"' : '') + '>' + ((plugin.settings.zero_pad ? str_pad(day, 2) : day) || '&nbsp;') + '</td>';

                    }

                }

                // wrap up generating the day picker
                html += '</tr>';

                // inject the day picker into the DOM
                daypicker.html($(html));

                // if date picker is always visible
                if (plugin.settings.always_visible)

                    // cache all the cells
                    // (we need them so that we can easily remove the "dp_selected" class from all of them when user selects a date)
                    daypicker_cells = $('td:not(.dp_disabled)', daypicker);

                // make the day picker visible
                daypicker.show();

            },

            /**
             *  Generates the month picker view, and displays it
             *
             *  @return void
             *
             *  @access private
             */
            generate_monthpicker = function() {

                // manage header caption and enable/disable navigation buttons if necessary
                manage_header(plugin.settings.header_captions.months);

                // start generating the HTML
                var html = '<tr>', i, class_name, month;

                // iterate through all the months
                for (i = 0; i < 12; i++) {

                    // three month per row
                    if (i > 0 && i % 3 === 0) html += '</tr><tr>';

                    // the month, taking RTL into account
                    month = plugin.settings.rtl ? 2 + i - (2 * (i % 3)) : i;

                    class_name = 'dp_month_' + month;

                    // if month needs to be disabled
                    if (is_disabled(selected_year, month)) class_name += ' dp_disabled';

                    // else, if a date is already selected and this is that particular month, highlight it
                    else if (default_month !== false && default_month === month && selected_year === default_year) class_name += ' dp_selected';

                    // else, if this the current system month, highlight it
                    else if (current_system_month === month && current_system_year === selected_year) class_name += ' dp_current';

                    // first three letters of the month's name
                    html += '<td class="' + $.trim(class_name) + '">' + ($.isArray(plugin.settings.months_abbr) && undefined !== plugin.settings.months_abbr[month] ? plugin.settings.months_abbr[month] : plugin.settings.months[month].substr(0, 3)) + '</td>';

                }

                // wrap up
                html += '</tr>';

                // inject into the DOM
                monthpicker.html($(html));

                // if date picker is always visible
                if (plugin.settings.always_visible)

                    // cache all the cells
                    // (we need them so that we can easily remove the "dp_selected" class from all of them when user selects a month)
                    monthpicker_cells = $('td:not(.dp_disabled)', monthpicker);

                // make the month picker visible
                monthpicker.show();

            },

            /**
             *  Generates the time picker view, and displays it
             *
             *  @return void
             *
             *  @access private
             */
            generate_timepicker = function() {

                var html, condensed = (timepicker_config.hours && timepicker_config.minutes && timepicker_config.seconds && timepicker_config.ampm);

                // the HTML
                html = '<tr class="dp_time_controls_increase' + (condensed ? ' dp_time_controls_condensed' : '') + '">' +
                    (plugin.settings.rtl && timepicker_config.ampm ? '<td class="dp_time_ampm dp_time_control">' + plugin.settings.navigation[2] + '</td>' : '') +
                    (timepicker_config.hours ? '<td class="dp_time_hour dp_time_control">' + plugin.settings.navigation[2] + '</td>' : '') +
                    (timepicker_config.minutes ? '<td class="dp_time_minute dp_time_control">' + plugin.settings.navigation[2] + '</td>' : '') +
                    (timepicker_config.seconds ? '<td class="dp_time_second dp_time_control">' + plugin.settings.navigation[2] + '</td>' : '') +
                    (!plugin.settings.rtl && timepicker_config.ampm ? '<td class="dp_time_ampm dp_time_control">' + plugin.settings.navigation[2] + '</td>' : '') +
                    '</tr>';

                html += '<tr class="dp_time_segments' + (condensed ? ' dp_time_controls_condensed' : '') + '">';

                if (plugin.settings.rtl && timepicker_config.ampm) html += '<td class="dp_time_ampm dp_disabled' + (timepicker_config.hours || timepicker_config.minutes || timepicker_config.seconds ? ' dp_time_separator' : '') + '"><div>' + selected_ampm.toUpperCase() + '</div></td>';
                if (timepicker_config.hours) html += '<td class="dp_time_hours dp_disabled' + (timepicker_config.minutes || timepicker_config.seconds || (!plugin.settings.rtl && timepicker_config.ampm) ? ' dp_time_separator' : '') + '"><div>' + (timepicker_config.hour_format === 'h' || timepicker_config.hour_format === 'H' ? str_pad(selected_hour, 2) : selected_hour) + '</div></td>';
                if (timepicker_config.minutes) html += '<td class="dp_time_minutes dp_disabled' + (timepicker_config.seconds || (!plugin.settings.rtl && timepicker_config.ampm) ? ' dp_time_separator' : '') + '"><div>' + str_pad(selected_minute, 2) + '</div></td>';
                if (timepicker_config.seconds) html += '<td class="dp_time_seconds dp_disabled' + (!plugin.settings.rtl && timepicker_config.ampm ? ' dp_time_separator' : '') + '"><div>' + str_pad(selected_second, 2) + '</div></td>';
                if (!plugin.settings.rtl && timepicker_config.ampm) html += '<td class="dp_time_ampm dp_disabled">' + selected_ampm.toUpperCase() + '</td>';

                html += '</tr>';

                html += '<tr class="dp_time_controls_decrease' + (condensed ? ' dp_time_controls_condensed' : '') + '">' +
                    (plugin.settings.rtl && timepicker_config.ampm ? '<td class="dp_time_ampm dp_time_control">' + plugin.settings.navigation[3] + '</td>' : '') +
                    (timepicker_config.hours ? '<td class="dp_time_hour dp_time_control">' + plugin.settings.navigation[3] + '</td>' : '') +
                    (timepicker_config.minutes ? '<td class="dp_time_minute dp_time_control">' + plugin.settings.navigation[3] + '</td>' : '') +
                    (timepicker_config.seconds ? '<td class="dp_time_second dp_time_control">' + plugin.settings.navigation[3] + '</td>' : '') +
                    (!plugin.settings.rtl && timepicker_config.ampm ? '<td class="dp_time_ampm dp_time_control">' + plugin.settings.navigation[3] + '</td>' : '') +
                    '</tr>';

                // inject into the DOM
                timepicker.html($(html));

                // make the time picker visible
                timepicker.show();

            },

            /**
             *  Generates the year picker view, and displays it
             *
             *  @return void
             *
             *  @access private
             */
            generate_yearpicker = function() {

                // manage header caption and enable/disable navigation buttons if necessary
                manage_header(plugin.settings.header_captions.years);

                // start generating the HTML
                var html = '<tr>', i, class_name, year;

                // we're showing 12 years at a time, current year in the middle
                for (i = 0; i < 12; i++) {

                    // three years per row
                    if (i > 0 && i % 3 === 0) html += '</tr><tr>';

                    // the year, taking RTL into account
                    year = plugin.settings.rtl ? 2 + i - (2 * (i % 3)) : i;

                    class_name = '';

                    // if year needs to be disabled
                    if (is_disabled(selected_year - 7 + year)) class_name += ' dp_disabled';

                    // else, if a date is already selected and this is that particular year, highlight it
                    else if (default_year && default_year === selected_year - 7 + year) class_name += ' dp_selected';

                    // else, if this is the current system year, highlight it
                    else if (current_system_year === (selected_year - 7 + year)) class_name += ' dp_current';

                    // first three letters of the month's name
                    html += '<td' + ($.trim(class_name) !== '' ? ' class="' + $.trim(class_name) + '"' : '') + '>' + (selected_year - 7 + year) + '</td>';

                }

                // wrap up
                html += '</tr>';

                // inject into the DOM
                yearpicker.html($(html));

                // if date picker is always visible
                if (plugin.settings.always_visible)

                    // cache all the cells
                    // (we need them so that we can easily remove the "dp_selected" class from all of them when user selects a year)
                    yearpicker_cells = $('td:not(.dp_disabled)', yearpicker);

                // make the year picker visible
                yearpicker.show();

            },

            /**
             *  Return the name of a custom class to be applied to the given date.
             *
             *  @return string  The name of a custom class to be applied to the given date, or an empty string if no custom
             *                  class needs to be applied.
             *
             *  @param  integer     year    The year to check
             *  @param  integer     month   The month to check
             *  @param  integer     day     The day to check
             *
             *  @access private
             */
            get_custom_class = function(year, month, day) {

                var class_name, i, found;

                // if month is given as argument, increment it (as JavaScript uses 0 for January, 1 for February...)
                if (typeof month !== 'undefined') month = month + 1;

                // iterate through the custom classes
                for (i in custom_class_names) {

                    // the class name we're currently checking
                    class_name = custom_class_names[i]; found = false;

                    // if there are any custom classes defined
                    if ($.isArray(custom_classes[class_name]))

                        // iterate through the rules for which the custom class to be applied
                        $.each(custom_classes[class_name], function() {

                            // if a custom class needs to be applied to the date we're checking, don't look further
                            if (found) return;

                            var rule = this, weekday;

                            // if the rules apply for the current year
                            if ($.inArray(year, rule[2]) > -1 || $.inArray('*', rule[2]) > -1)

                                // if the rules apply for the current month
                                if ((typeof month !== 'undefined' && $.inArray(month, rule[1]) > -1) || $.inArray('*', rule[1]) > -1)

                                    // if the rules apply for the current day
                                    if ((typeof day !== 'undefined' && $.inArray(day, rule[0]) > -1) || $.inArray('*', rule[0]) > -1) {

                                        // if custom class is to be applied whatever the day
                                        // don't look any further
                                        if ($.inArray('*', rule[3]) > -1) return (found = class_name);

                                        // get the weekday
                                        weekday = new Date(year, month - 1, day).getDay();

                                        // if custom class is to be applied to weekday
                                        // don't look any further
                                        if ($.inArray(weekday, rule[3]) > -1) return (found = class_name);

                                    }

                        });

                    // if a custom class needs to be applied to the date we're checking, don't look further
                    if (found) return found;

                }

                // return what we've found
                return found || '';

            },

            /**
             *  Calculate the ISO 8601 week number for a given date.
             *
             *  Code is based on the algorithm at http://www.tondering.dk/claus/cal/week.php#calcweekno
             */
            get_week_number = function(date) {

                var y = date.getFullYear(),
                    m = date.getMonth() + 1,
                    d = date.getDate(),
                    a, b, c, s, e, f, g, n, w;

                /* jshint ignore:start */

                // if month jan. or feb.
                if (m < 3) {

                    a = y - 1;
                    b = (a / 4 | 0) - (a / 100 | 0) + (a / 400 | 0);
                    c = ((a - 1) / 4 | 0) - ((a - 1) / 100 | 0) + ((a - 1) / 400 | 0);
                    s = b - c;
                    e = 0;
                    f = d - 1 + 31 * (m - 1);

                // if month mar. through dec.
                } else {

                    a = y;
                    b = (a / 4 | 0) - (a / 100 | 0) + (a / 400 | 0);
                    c = ((a - 1) / 4 | 0) - ((a - 1) / 100 | 0) + ((a - 1) / 400 | 0);
                    s = b - c;
                    e = s + 1;
                    f = d + ((153 * (m - 3) + 2) / 5 | 0) + 58 + s;

                }

                g = (a + b) % 7;
                // ISO Weekday (0 is monday, 1 is tuesday etc.)
                d = (f + g - e) % 7;
                n = f + 3 - d;

                if (n < 0) w = 53 - ((g - s) / 5 | 0);

                else if (n > 364 + s) w = 1;

                else w = (n / 7 | 0) + 1;

                /* jshint ignore:end */

                return w;

            },

            /**
             *  Generates an iFrame shim in Internet Explorer 6 so that the date picker appears above select boxes.
             *
             *  @return void
             *
             *  @access private
             */
            iframeShim = function(action) {

                var zIndex, offset;

                // this is necessary only if browser is Internet Explorer 6
                if (browser.name === 'explorer' && browser.version === 6) {

                    // if the iFrame was not yet created
                    // "undefined" evaluates as FALSE
                    if (!shim) {

                        // the iFrame has to have the element's zIndex minus 1
                        zIndex = to_int(datepicker.css('zIndex')) - 1;

                        // create the iFrame
                        shim = $('<iframe>', {
                            src:            'javascript:document.write("")',
                            scrolling:      'no',
                            frameborder:    0,
                            css: {
                                zIndex:     zIndex,
                                position:   'absolute',
                                top:        -1000,
                                left:       -1000,
                                width:      datepicker.outerWidth(),
                                height:     datepicker.outerHeight(),
                                filter:     'progid:DXImageTransform.Microsoft.Alpha(opacity=0)',
                                display:    'none'
                            }
                        });

                        // inject iFrame into DOM
                        $('body').append(shim);

                    }

                    // what do we need to do
                    switch (action) {

                        // hide the iFrame?
                        case 'hide':

                            // set the iFrame's display property to "none"
                            shim.hide();

                            break;

                        // show the iFrame?
                        default:

                            // get date picker top and left position
                            offset = datepicker.offset();

                            // position the iFrame shim right underneath the date picker
                            // and set its display to "block"
                            shim.css({
                                top:        offset.top,
                                left:       offset.left,
                                display:    'block'
                            });

                    }

                }

            },

            /**
             *  Checks if, according to the restrictions of the calendar and/or the values defined by the "disabled_dates"
             *  property, a day, a month or a year needs to be disabled.
             *
             *  @param  integer     year    The year to check
             *  @param  integer     month   The month to check
             *  @param  integer     day     The day to check
             *
             *  @return boolean         Returns TRUE if the given value is not disabled or FALSE otherwise
             *
             *  @access private
             */
            is_disabled = function(year, month, day) {

                var now, len, disabled, enabled;

                // don't check bogus values
                if ((undefined === year || isNaN(year)) && (undefined === month || isNaN(month)) && (undefined === day || isNaN(day))) return false;

                // this date picker cannot handle years before 1000, so we return false in this case
                else if (year < 1000) return true;

                // if calendar has direction restrictions
                if (!(!$.isArray(plugin.settings.direction) && to_int(plugin.settings.direction) === 0)) {

                    // normalize and merge arguments then transform the result to an integer
                    now = to_int(str_concat(year, (typeof month !== 'undefined' ? str_pad(month, 2) : ''), (typeof day !== 'undefined' ? str_pad(day, 2) : '')));

                    // get the length of the argument
                    len = (now + '').length;

                    // if we're checking days
                    if (len === 8 && (

                        // day is before the first selectable date
                        (typeof start_date !== 'undefined' && now < to_int(str_concat(first_selectable_year, str_pad(first_selectable_month, 2), str_pad(first_selectable_day, 2)))) ||

                        // or day is after the last selectable date
                        (typeof end_date !== 'undefined' && now > to_int(str_concat(last_selectable_year, str_pad(last_selectable_month, 2), str_pad(last_selectable_day, 2))))

                    // day needs to be disabled
                    )) return true;

                    // if we're checking months
                    else if (len === 6 && (

                        // month is before the first selectable month
                        (typeof start_date !== 'undefined' && now < to_int(str_concat(first_selectable_year, str_pad(first_selectable_month, 2)))) ||

                        // or day is after the last selectable date
                        (typeof end_date !== 'undefined' && now > to_int(str_concat(last_selectable_year, str_pad(last_selectable_month, 2))))

                    // month needs to be disabled
                    )) return true;

                    // if we're checking years
                    else if (len === 4 && (

                        // year is before the first selectable year
                        (typeof start_date !== 'undefined' && now < first_selectable_year) ||

                        // or day is after the last selectable date
                        (typeof end_date !== 'undefined' && now > last_selectable_year)

                    // year needs to be disabled
                    )) return true;

                }

                // if month is given as argument, increment it (as JavaScript uses 0 for January, 1 for February...)
                if (typeof month !== 'undefined') month = month + 1;

                // by default, we assume the day/month/year is not enabled nor disabled
                disabled = false; enabled = false;

                // if there are rules for disabling dates
                if ($.isArray(disabled_dates) && disabled_dates.length)

                    // iterate through the rules for disabling dates
                    $.each(disabled_dates, function() {

                        // if the date is to be disabled, don't look any further
                        if (disabled) return;

                        var rule = this, weekday;

                        // if the rules apply for the current year
                        if ($.inArray(year, rule[2]) > -1 || $.inArray('*', rule[2]) > -1)

                            // if the rules apply for the current month
                            if ((typeof month !== 'undefined' && $.inArray(month, rule[1]) > -1) || $.inArray('*', rule[1]) > -1)

                                // if the rules apply for the current day
                                if ((typeof day !== 'undefined' && $.inArray(day, rule[0]) > -1) || $.inArray('*', rule[0]) > -1) {

                                    // if day is to be disabled whatever the day
                                    // don't look any further
                                    if ($.inArray('*', rule[3]) > -1) return (disabled = true);

                                    // get the weekday
                                    weekday = new Date(year, month - 1, day).getDay();

                                    // if weekday is to be disabled
                                    // don't look any further
                                    if ($.inArray(weekday, rule[3]) > -1) return (disabled = true);

                                }

                    });

                // if there are rules that explicitly enable dates
                if (enabled_dates)

                    // iterate through the rules for enabling dates
                    $.each(enabled_dates, function() {

                        // if the date is to be enabled, don't look any further
                        if (enabled) return;

                        var rule = this, weekday;

                        // if the rules apply for the current year
                        if ($.inArray(year, rule[2]) > -1 || $.inArray('*', rule[2]) > -1) {

                            // the year is enabled
                            enabled = true;

                            // if we're also checking months
                            if (typeof month !== 'undefined') {

                                // we assume the month is enabled
                                enabled = true;

                                // if the rules apply for the current month
                                if ($.inArray(month, rule[1]) > -1 || $.inArray('*', rule[1]) > -1) {

                                    // if we're also checking days
                                    if (typeof day !== 'undefined') {

                                        // we assume the day is enabled
                                        enabled = true;

                                        // if the rules apply for the current day
                                        if ($.inArray(day, rule[0]) > -1 || $.inArray('*', rule[0]) > -1) {

                                            // if day is to be enabled whatever the day
                                            // don't look any further
                                            if ($.inArray('*', rule[3]) > -1) return (enabled = true);

                                            // get the weekday
                                            weekday = new Date(year, month - 1, day).getDay();

                                            // if weekday is to be enabled
                                            // don't look any further
                                            if ($.inArray(weekday, rule[3]) > -1) return (enabled = true);

                                            // if we get this far, it means the day is not enabled
                                            enabled = false;

                                        // if day is not enabled
                                        } else enabled = false;

                                    }

                                // if month is not enabled
                                } else enabled = false;

                            }

                        }

                    });

                // if checked date is enabled, return false
                if (enabled_dates && enabled) return false;

                // if checked date is disabled return false
                else if (disabled_dates && disabled) return true;

                // if script gets this far it means that the day/month/year doesn't need to be disabled
                return false;

            },

            /**
             *  Checks whether a value is an integer number.
             *
             *  @param  mixed   value   Value to check
             *
             *  @return                 Returns TRUE if the value represents an integer number, or FALSE otherwise
             *
             *  @access private
             */
            is_integer = function(value) {

                // return TRUE if value represents an integer number, or FALSE otherwise
                return (value + '').match(/^\-?[0-9]+$/);

            },

            /**
             *  Sets the caption in the header of the date picker and enables or disables navigation buttons when necessary.
             *
             *  @param  string  caption     String that needs to be displayed in the header
             *
             *  @return void
             *
             *  @access private
             */
            manage_header = function(caption) {

                // if "selected_month" has a value
                // $.isNumeric is available only from jQuery 1.7 - thanks to birla for the fix!
                if (!isNaN(parseFloat(selected_month)) && isFinite(selected_month))

                    caption = caption.replace(/\bm\b|\bn\b|\bF\b|\bM\b/, function(match) {

                        switch (match) {

                            // month number, prefixed with 0
                            case 'm':
                                return str_pad(selected_month + 1, 2);

                            // month number, not prefixed with 0
                            case 'n':
                                return selected_month + 1;

                            // full month name
                            case 'F':
                                return plugin.settings.months[selected_month];

                            // month name, three letters
                            case 'M':
                                return ($.isArray(plugin.settings.months_abbr) && undefined !== plugin.settings.months_abbr[selected_month] ? plugin.settings.months_abbr[selected_month] : plugin.settings.months[selected_month].substr(0, 3));

                            // unknown replace
                            default:
                                return match;

                        }

                    });

                // if "selected_year" has a value
                // $.isNumeric is available only from jQuery 1.7 - thanks to birla for the fix!
                if (!isNaN(parseFloat(selected_year)) && isFinite(selected_year))

                    // replace year-related patterns
                    caption = caption

                        // year as four digits
                        .replace(/\bY\b/, selected_year)

                        // year as two digits
                        .replace(/\by\b/, (selected_year + '').substr(2))

                        // lower limit of year as two or four digits
                        .replace(/\bY1\b/i, selected_year - 7)

                        // upper limit of year as two or four digits
                        .replace(/\bY2\b/i, selected_year + 4);

                // update the caption in the header
                $('.dp_caption', header).html(caption);

            },

            /**
             *  Shows the appropriate view (days, months or years) according to the current value of the "view" property.
             *
             *  @return void
             *
             *  @access private
             */
            manage_views = function() {

                var height, elements;

                // if the day picker was not yet generated
                if (daypicker.text() === '' || view === 'days') {

                    // if the day picker was not yet generated
                    if (daypicker.text() === '') {

                        // if date picker is not always visible in a container
                        if (!(plugin.settings.always_visible instanceof jQuery))

                            // temporarily set the date picker's left outside of view
                            // so that we can later grab its width and height
                            datepicker.css('left', -1000);

                        // temporarily make the date picker visible
                        // so that we can later grab its width and height
                        datepicker.removeClass('hidden');

                        // generate the day picker
                        generate_daypicker();

                        // jQuery rounds values returned by outerWidth and outerHeight
                        // therefore, if we can get the un-rounded values, get those
                        // get the day picker's width and height
                        // (we need the second check for old Internet Explorers...)
                        if (typeof daypicker[0].getBoundingClientRect !== 'undefined' && typeof daypicker[0].getBoundingClientRect().height !== 'undefined') height = daypicker[0].getBoundingClientRect().height;

                        // if "getBoundingClientRect" is not available
                        // get the day picker's height
                        else height = daypicker.outerHeight(true);

                        // make the month picker have the same size as the day picker
                        monthpicker.css('height', height);

                        // make the year picker have the same size as the day picker
                        yearpicker.css('height', height);

                        // make the time picker have the same size as the day picker
                        timepicker.css('height', height + header.outerHeight(true));

                        // set the container's width so all the views have 100% width
                        datepicker.css('width', datepicker.outerWidth());

                        // // we have to set this now or Chrome will make the datepicker extend to the full width of the screen...
                        // $('.dp_caption', header).css('width', '100%');

                        // hide the date picker again
                        datepicker.addClass('dp_hidden');

                    // if the day picker was previously generated at least once
                    // generate the day picker
                    } else generate_daypicker();

                    // show header
                    header.show();

                    // hide the year and the month pickers
                    monthpicker.hide();
                    yearpicker.hide();

                    // hide time-picker related elements
                    timepicker.hide();
                    view_toggler.hide();
                    confirm_selection.hide();

                    // if the time picker is enabled, show the clock icon
                    if (timepicker_config) view_toggler.show().removeClass('dp_calendar');

                // if the view is "months"
                } else if (view === 'months') {

                    // generate the month picker
                    generate_monthpicker();

                    // hide the day and the year pickers
                    daypicker.hide();
                    yearpicker.hide();

                    // hide time-picker related elements
                    timepicker.hide();
                    view_toggler.hide();
                    confirm_selection.hide();

                // if the view is "years"
                } else if (view === 'years') {

                    // generate the year picker
                    generate_yearpicker();

                    // hide the day and the month pickers
                    daypicker.hide();
                    monthpicker.hide();

                    // hide time-picker related elements
                    timepicker.hide();
                    view_toggler.hide();
                    confirm_selection.hide();

                // if the view is "time"
                } else if (view === 'time') {

                    // generate the time picker
                    generate_timepicker();

                    // if the "time" view is the only available view
                    if (views.length === 1) {

                        // hide the time picker toggler button
                        view_toggler.hide();

                        // show the confirmation button
                        confirm_selection.show();

                    // if the "time" view is not the only available view
                    } else {

                        // time picker toggler button, but change the icon
                        view_toggler.show().addClass('dp_calendar');

                        // if no date is selected
                        // hide the confirmation button
                        if ($element.val() === '') confirm_selection.hide();

                        // show the confirmation button
                        else confirm_selection.show();

                    }

                    // hide the header, day, month and year pickers
                    header.hide();
                    daypicker.hide();
                    monthpicker.hide();
                    yearpicker.hide();

                }

                // if a callback function exists for when navigating through months/years
                if (view !== 'time' && plugin.settings.onChange && typeof plugin.settings.onChange === 'function' && undefined !== view) {

                    // get the "active" elements in the view (ignoring the disabled ones)
                    elements = (view === 'days' ?
                        daypicker.find('td:not(.dp_disabled)') :
                        (view === 'months' ?
                            monthpicker.find('td:not(.dp_disabled)') :
                            yearpicker.find('td:not(.dp_disabled)')));

                    // iterate through the active elements
                    // and attach a "date" data attribute to each element in the form of
                    // YYYY-MM-DD if the view is "days"
                    // YYYY-MM if the view is "months"
                    // YYYY if the view is "years"
                    // so it's easy to identify elements in the list
                    elements.each(function() {

                        var matches;

                        // if view is "days"
                        if (view === 'days')

                            // if date is from a next/previous month and is selectable
                            if ($(this).hasClass('dp_not_in_month') && !$(this).hasClass('dp_disabled')) {

                                // extract date from the attached class
                                matches = $(this).attr('class').match(/date\_([0-9]{4})(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])/);

                                // attach a "date" data attribute to each element in the form of of YYYY-MM-DD for easily identifying sought elements
                                $(this).data('date', matches[1] + '-' + matches[2] + '-' + matches[3]);

                            // if date is from the currently selected month
                            } else

                                // attach a "date" data attribute to each element in the form of of YYYY-MM-DD for easily identifying sought elements
                                $(this).data('date', selected_year + '-' + str_pad(selected_month + 1, 2) + '-' + str_pad(to_int($(this).text()), 2));

                        // if view is "months"
                        else if (view === 'months') {

                            // get the month's number for the element's class
                            matches = $(this).attr('class').match(/dp\_month\_([0-9]+)/);

                            // attach a "date" data attribute to each element in the form of of YYYY-MM for easily identifying sought elements
                            $(this).data('date', selected_year + '-' + str_pad(to_int(matches[1]) + 1, 2));

                        // if view is "years"
                        } else

                            // attach a "date" data attribute to each element in the form of of YYYY for easily identifying sought elements
                            $(this).data('date', to_int($(this).text()));

                    });

                    // execute the callback function and send as arguments the current view, the elements in the view, and
                    // the element the plugin is attached to
                    plugin.settings.onChange.call($element, view, elements);

                }

                // assume the footer is visible
                footer.show();

                // if we are in the "time" view and there are more views available
                if (view === 'time' && views.length > 1) {

                    // hide the "Today" and the "Clear" buttons
                    selecttoday.hide();
                    cleardate.hide();

                    // set the view toggler width
                    view_toggler.css('width', $element.val() === '' ? '100%' : '50%');

                // for the other cases
                } else {

                    // assume both the "Today" and "Clear" buttons are visible
                    selecttoday.show();
                    cleardate.show();

                    // if the button for clearing a previously selected date needs to be visible all the time,
                    // or the "Clear" button needs to be shown only when a date was previously selected, and now it's the case,
                    // or the date picker is always visible and the "Clear" button was not explicitly disabled
                    if (
                        plugin.settings.show_clear_date === true ||
                        (plugin.settings.show_clear_date === 0 && $element.val() !== '') ||
                        (plugin.settings.always_visible && plugin.settings.show_clear_date !== false)
                    )

                        // if the "Today" button is visible
                        if (show_select_today) {

                            // show it, and set it's width to 50% of the available space
                            selecttoday.css('width', '50%');

                            // the "Clear date" button only takes up 50% of the available space
                            cleardate.css('width', '50%');

                        // if the "Today" button is not visible
                        } else {

                            // hide the "Today" button
                            selecttoday.hide();

                            // the "Clear date" button takes up 100% of the available space
                            // unless the time picker is available, in which case take up 50% of the available space
                            cleardate.css('width', $.inArray(views, 'time') > -1 ? '50%' : '100%');

                        }

                    // otherwise
                    else {

                        // hide the "Clear" button
                        cleardate.hide();

                        // if the "Today" button is visible, it will now take up all the available space
                        if (show_select_today) selecttoday.css('width', '100%');

                        // if the "Today" button should not be visible
                        else {

                            // hide the "Today" button
                            selecttoday.hide();

                            // if there's also no timepicker view, hide the footer entirely
                            if (!timepicker_config || (view !== 'time' && view !== 'days')) footer.hide();

                        }

                    }

                }

            },

            /**
             *  Puts the specified date in the element the plugin is attached to, and hides the date picker.
             *
             *  @param  integer     year    The year
             *
             *  @param  integer     month   The month
             *
             *  @param  integer     day     The day
             *
             *  @param  string      rview   The view from where the method was called (the referrer view)
             *
             *  @param  object      cell    The element that was clicked
             *
             *  @return void
             *
             *  @access private
             */
            select_date = function(year, month, day, rview, cell) {

                var

                    // construct a new date object from the arguments
                    default_date = new Date(year, month, day,
                        (timepicker_config && timepicker_config.hours ? selected_hour + (timepicker_config.ampm ? (selected_ampm === 'pm' && selected_hour !== 12 ? 12 : (selected_ampm === 'am' && selected_hour === 12 ? -12 : 0)) : 0) : 12),
                        (timepicker_config && timepicker_config.minutes ? selected_minute : 0),
                        (timepicker_config && timepicker_config.seconds ? selected_second : 0)
                    ),

                    // pointer to the cells in the current view
                    view_cells = (rview === 'days' ? daypicker_cells : (rview === 'months' ? monthpicker_cells : yearpicker_cells)),

                    // the selected date, formatted correctly
                    selected_value = format(default_date);

                // set the currently selected and formated date as the value of the element the plugin is attached to
                $element.val(selected_value);

                // if date picker is always visible or time picker is available
                if (plugin.settings.always_visible || timepicker_config) {

                    // extract the date parts and reassign values to these variables
                    // so that everything will be correctly highlighted
                    default_month = default_date.getMonth();
                    selected_month = default_date.getMonth();
                    default_year = default_date.getFullYear();
                    selected_year = default_date.getFullYear();
                    default_day = default_date.getDate();

                    // if "cell" is available (it isn't when called from increasing/decreasing values the time picker)
                    if (cell && view_cells) {

                        // remove the "selected" class from all cells in the current view
                        view_cells.removeClass('dp_selected');

                        // add the "selected" class to the currently selected cell
                        cell.addClass('dp_selected');

                        // if we're on the "days" view and days from other months are selectable and one of those days was
                        // selected, repaint the datepicker so it will take us to the selected month
                        if (rview === 'days' && cell.hasClass('dp_not_in_month') && !cell.hasClass('dp_disabled')) plugin.show();

                    }

                }

                // if format contains time, switch to the time picker view
                if (timepicker_config) {

                    view = 'time';
                    manage_views();

                // if format doesn't contain time
                } else {

                    // move focus to the element the plugin is attached to
                    $element.focus();

                    // hide the date picker
                    plugin.hide();

                }

                // updates value for the date picker whose starting date depends on the selected date (if any)
                update_dependent(default_date);

                // if a callback function exists for when selecting a date
                // (if time picker is enabled, we'll run the callback when the user clicks on the confirmation button)
                if (!timepicker_config && plugin.settings.onSelect && typeof plugin.settings.onSelect === 'function')

                    // execute the callback function
                    // make "this" inside the callback function refer to the element the date picker is attached to
                    plugin.settings.onSelect.call($element, selected_value, year + '-' + str_pad(month + 1, 2) + '-' + str_pad(day, 2), default_date);

            },

            /**
             *  Concatenates any number of arguments and returns them as string.
             *
             *  @return string  Returns the concatenated values.
             *
             *  @access private
             */
            str_concat = function() {

                var str = '', i;

                // concatenate as string
                for (i = 0; i < arguments.length; i++) str += (arguments[i] + '');

                // return the concatenated values
                return str;

            },

            /**
             *  Left-pad a string to a certain length with zeroes.
             *
             *  @param  string  str     The string to be padded.
             *
             *  @param  integer len     The length to which the string must be padded
             *
             *  @return string          Returns the string left-padded with leading zeroes
             *
             *  @access private
             */
            str_pad = function(str, len) {

                // make sure argument is a string
                str += '';

                // pad with leading zeroes until we get to the desired length
                while (str.length < len) str = '0' + str;

                // return padded string
                return str;

            },

            /**
             *  Returns the integer representation of a string
             *
             *  @return int     Returns the integer representation of the string given as argument
             *
             *  @access private
             */
            to_int = function(str) {

                // return the integer representation of the string given as argument
                return parseInt(str, 10);

            },

            /**
             *  Updates the paired date picker (whose starting date depends on the value of the current date picker)
             *
             *  @param  date    date    A JavaScript date object representing the currently selected date
             *
             *  @return void
             *
             *  @access private
             */
            update_dependent = function(date) {

                // if the pair element exists
                if (plugin.settings.pair)

                    // iterate through the pair elements (as there may be more than just one)
                    $.each(plugin.settings.pair, function() {

                        var $pair = $(this), dp;

                        // chances are that in the beginning the pair element doesn't have the Zebra_DatePicker attached to it yet
                        // (as the "start" element is usually created before the "end" element)
                        // so we'll have to rely on "data" to send the starting date to the pair element

                        // therefore, if Zebra_DatePicker is not yet attached
                        if (!($pair.data && $pair.data('Zebra_DatePicker')))

                            // set the starting date like this
                            $pair.data('zdp_reference_date', date);

                        // if Zebra_DatePicker is attached to the pair element
                        else {

                            // reference the date picker object attached to the other element
                            dp = $pair.data('Zebra_DatePicker');

                            // update the other date picker's starting date
                            // the value depends on the original value of the "direction" attribute
                            // (also, if the pair date picker does not have a direction, set it to 1)
                            dp.update({
                                reference_date: date,
                                direction:      dp.settings.direction === 0 ? 1 : dp.settings.direction
                            });

                            // if the other date picker is always visible, update the visuals now
                            if (dp.settings.always_visible) dp.show();

                        }

                    });

            },

            // since with jQuery 1.9.0 the $.browser object was removed, we rely on this piece of code from
            // http://www.quirksmode.org/js/detect.html to detect the browser
            browser = {
                init: function() {
                    this.name = this.searchString(this.dataBrowser) || '';
                    this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || '';
                },
                searchString: function(data) {
                    var i, dataString, dataProp;

                    for (i = 0; i < data.length; i++) {
                        dataString = data[i].string;
                        dataProp = data[i].prop;
                        this.versionSearchString = data[i].versionSearch || data[i].identity;
                        if (dataString) {
                            if (dataString.indexOf(data[i].subString) !== -1)
                                return data[i].identity;
                        } else if (dataProp)
                            return data[i].identity;
                    }
                },
                searchVersion: function(dataString) {
                    var index = dataString.indexOf(this.versionSearchString);

                    if (index === -1) return;

                    return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
                },
                dataBrowser: [
                    {
                        string: navigator.userAgent,
                        subString: 'Firefox',
                        identity: 'firefox'
                    },
                    {
                        string: navigator.userAgent,
                        subString: 'MSIE',
                        identity: 'explorer',
                        versionSearch: 'MSIE'
                    }
                ]
            };

        plugin.settings = {};

        /**
         *  Clears the selected date.
         *
         *  @return void
         */
        plugin.clear_date = function() {

            $(cleardate).trigger('click');

        };

        /**
         *  Destroys the date picker.
         *
         *  @return void
         */
        plugin.destroy = function() {

            // if the calendar icon exists
            if (undefined !== plugin.icon) {

                // remove associated event handlers
                plugin.icon.off('click.Zebra_DatePicker_' + uniqueid);
                plugin.icon.off('focus.Zebra_DatePicker_' + uniqueid);
                plugin.icon.off('keydown.Zebra_DatePicker_' + uniqueid);

                // remove the icon itself
                plugin.icon.remove();

            }

            // remove all events attached to the datepicker
            // (these are the ones for increasing/decreasing values in the time picker)
            datepicker.off();

            // remove the calendar
            datepicker.remove();

            // if calendar icon was shown and the date picker was not always visible in a container,
            // also remove the wrapper used for positioning it
            if (plugin.settings.show_icon && !(plugin.settings.always_visible instanceof jQuery)) $element.unwrap();

            // remove associated event handlers from the element
            $element.off('blur.Zebra_DatePicker_' + uniqueid);
            $element.off('click.Zebra_DatePicker_' + uniqueid);
            $element.off('focus.Zebra_DatePicker_' + uniqueid);
            $element.off('keydown.Zebra_DatePicker_' + uniqueid);
            $element.off('mousedown.Zebra_DatePicker_' + uniqueid);

            // remove associated event handlers from the document
            $(document).off('keyup.Zebra_DatePicker_' + uniqueid);
            $(document).off('mousedown.Zebra_DatePicker_' + uniqueid);
            $(document).off('touchend.Zebra_DatePicker_' + uniqueid);
            $(window).off('resize.Zebra_DatePicker_' + uniqueid);
            $(window).off('orientationchange.Zebra_DatePicker_' + uniqueid);

            // remove association with the element
            $element.removeData('Zebra_DatePicker');

            // restore element's modified attributes
            $element.attr('readonly', original_attributes.readonly);
            $element.attr('style', original_attributes.style ? original_attributes.style : '');
            $element.css('paddingLeft', original_attributes.padding_left);
            $element.css('paddingRight', original_attributes.padding_right);

        };

        /**
         *  Hides the date picker.
         *
         *  @return void
         */
        plugin.hide = function(outside) {

            // unless the date picker is not already hidden AND
            // the date picker is not always visible or we clicked outside the date picker
            // (the "outside" argument is TRUE when clicking outside the date picker and the "always_visible" is set to boolean TRUE)
            if (!datepicker.hasClass('dp_hidden') && (!plugin.settings.always_visible || outside)) {

                // hide the iFrameShim in Internet Explorer 6
                iframeShim('hide');

                // hide the date picker
                datepicker.addClass('dp_hidden');

                // if a callback function exists for when hiding the date picker
                if (plugin.settings.onClose && typeof plugin.settings.onClose === 'function')

                    // execute the callback function and pass as argument the element the plugin is attached to
                    plugin.settings.onClose.call($element);

            }

        };

        /**
         *  Set the date picker's value
         *
         *  Must be a string representing a date in the format set by the "format" property, or a JavaScript date object.
         *
         *  @return void
         */
        plugin.set_date = function(date) {

            var dateObj;

            // if "date" is given as a valid Date object, convert it to the required format
            if (typeof date === 'object' && date instanceof Date) date = format(date);

            // if a valid date was entered, and date is not disabled
            if ((dateObj = check_date(date)) && !is_disabled(dateObj.getFullYear(), dateObj.getMonth(), dateObj.getDate())) {

                // set the element's value
                $element.val(date);

                // update the paired date picker (if any)
                update_dependent(dateObj);

            }

        };

        /**
         *  Shows the date picker.
         *
         *  @return void
         */
        plugin.show = function() {

            // always show the view defined in settings
            view = plugin.settings.view;

            // get the default date, from the element, and check if it represents a valid date, according to the required format
            var default_date = check_date($element.val() || (plugin.settings.start_date ? plugin.settings.start_date : '')),
                current_date;

            // if the value represents a valid date
            if (default_date) {

                // extract the date parts
                // we'll use these to highlight the default date in the date picker and as starting point to
                // what year and month to start the date picker with
                // why separate values? because selected_* will change as user navigates within the date picker
                default_month = default_date.getMonth();
                selected_month = default_date.getMonth();
                default_year = default_date.getFullYear();
                selected_year = default_date.getFullYear();
                default_day = default_date.getDate();

                // if the default date represents a disabled date
                if (is_disabled(default_year, default_month, default_day)) {

                    // if date picker is in "strict" mode, clear the value of the parent element
                    if (plugin.settings.strict) $element.val('');

                    // the calendar will start with the first selectable year/month
                    selected_month = first_selectable_month;
                    selected_year = first_selectable_year;

                }

            // if a default value is not available, or value does not represent a valid date
            } else {

                // the calendar will start with the first selectable year/month
                selected_month = first_selectable_month;
                selected_year = first_selectable_year;

            }

            // whatever the case, if time picker is enabled
            if (timepicker_config) {

                // if a default date is available, use the time from there
                if (default_date) current_date = default_date;

                // use current system time otherwise
                else current_date = new Date();

                // extract time parts from it
                selected_hour = current_date.getHours();
                selected_minute = current_date.getMinutes();
                selected_second = current_date.getSeconds();
                selected_ampm = (selected_hour >= 12 ? 'pm' : 'am');

                // if hour is in 12 hour format
                if (timepicker_config.is12hour)

                    // convert it to the correct value
                    selected_hour = (selected_hour % 12 === 0 ? 12 : selected_hour % 12);

                // make sure that the default values are withing the allowed range, if a range is defined
                if ($.isArray(plugin.settings.enabled_hours) && $.inArray(selected_hour, plugin.settings.enabled_hours) === -1) selected_hour = plugin.settings.enabled_hours[0];
                if ($.isArray(plugin.settings.enabled_minutes) && $.inArray(selected_minute, plugin.settings.enabled_minutes) === -1) selected_minute = plugin.settings.enabled_minutes[0];
                if ($.isArray(plugin.settings.enabled_seconds) && $.inArray(selected_second, plugin.settings.enabled_seconds) === -1) selected_second = plugin.settings.enabled_seconds[0];

            }

            // generate the appropriate view
            manage_views();

            // if date picker is not always visible in a container, and the calendar icon is visible
            if (!(plugin.settings.always_visible instanceof jQuery)) {

                // if date picker is to be injected into the <body>
                if (plugin.settings.container.is('body')) {

                    var

                        // get the date picker width and height
                        datepicker_width = datepicker.outerWidth(),
                        datepicker_height = datepicker.outerHeight(),

                        // compute the date picker's default left and top
                        // this will be computed relative to the icon's top-right corner (if the calendar icon exists), or
                        // relative to the element's top-right corner otherwise, to which the offsets given at initialization
                        // are added/subtracted
                        left = (undefined !== icon ? icon.offset().left + icon.outerWidth(true) : $element.offset().left + $element.outerWidth(true)) + plugin.settings.offset[0],
                        top = (undefined !== icon ? icon.offset().top : $element.offset().top) - datepicker_height + plugin.settings.offset[1],

                        // get browser window's width and height
                        window_width = $(window).width(),
                        window_height = $(window).height(),

                        // get browser window's horizontal and vertical scroll offsets
                        window_scroll_top = $(window).scrollTop(),
                        window_scroll_left = $(window).scrollLeft();

                    if (plugin.settings.default_position === 'below')
                        top = (undefined !== icon ? icon.offset().top : $element.offset().top) + plugin.settings.offset[1];

                    // if date picker is outside the viewport, adjust its position so that it is visible
                    if (left + datepicker_width > window_scroll_left + window_width) left = window_scroll_left + window_width - datepicker_width;
                    if (left < window_scroll_left) left = window_scroll_left;

                    if (top + datepicker_height > window_scroll_top + window_height) top = window_scroll_top + window_height - datepicker_height;
                    if (top < window_scroll_top) top = window_scroll_top;

                    // make the date picker visible
                    datepicker.css({
                        left:   left,
                        top:    top
                    });

                // if date picker is to be injected into a custom container element
                } else

                    datepicker.css({
                        left:   0,
                        top:    0
                    });

                // fade-in the date picker
                // for Internet Explorer < 9 show the date picker instantly or fading alters the font's weight
                datepicker.removeClass('dp_hidden');

                // show the iFrameShim in Internet Explorer 6
                iframeShim();

            // if date picker is always visible, show it
            } else datepicker.removeClass('dp_hidden');

            // if a callback function exists for when showing the date picker
            if (plugin.settings.onOpen && typeof plugin.settings.onOpen === 'function')

                // execute the callback function and pass as argument the element the plugin is attached to
                plugin.settings.onOpen.call($element);

        };

        /**
         *  Updates the configuration options given as argument
         *
         *  @param  object  values  An object containing any number of configuration options to be updated
         *
         *  @return void
         */
        plugin.update = function(values) {

            // if original direction not saved, save it now
            if (plugin.original_direction) plugin.original_direction = plugin.direction;

            // update configuration options
            plugin.settings = $.extend(plugin.settings, values);

            // reinitialize the object with the new options
            init(true);

        };

        browser.init();

        // initialize the plugin
        init();

    };

    $.fn.Zebra_DatePicker = function(options) {

        // iterate through all the elements to which we need to attach the date picker to
        return this.each(function() {

            // if element has a date picker already attached
            if (undefined !== $(this).data('Zebra_DatePicker'))

                // remove the attached date picker
                $(this).data('Zebra_DatePicker').destroy();

            // create an instance of the plugin
            var plugin = new $.Zebra_DatePicker(this, options);

            // save a reference to the newly created object
            $(this).data('Zebra_DatePicker', plugin);

        });

    };

    // this is used for setting global defaults, that will be applied to all date pickers
    $.fn.Zebra_DatePicker.defaults = {};

}));

/**
 * jquery.mask.js
 * @version: v1.14.15
 * @author: Igor Escobar
 *
 * Created by Igor Escobar on 2012-03-10. Please report any bug at github.com/igorescobar/jQuery-Mask-Plugin
 *
 * Copyright (c) 2012 Igor Escobar http://igorescobar.com
 *
 * The MIT License (http://www.opensource.org/licenses/mit-license.php)
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

/* jshint laxbreak: true */
/* jshint maxcomplexity:17 */
/* global define */

// UMD (Universal Module Definition) patterns for JavaScript modules that work everywhere.
// https://github.com/umdjs/umd/blob/master/templates/jqueryPlugin.js
(function (factory, jQuery, Zepto) {

    if (typeof define === 'function' && define.amd) {
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        module.exports = factory(require('jquery'));
    } else {
        factory(jQuery || Zepto);
    }

}(function ($) {
    'use strict';

    var Mask = function (el, mask, options) {

        var p = {
            invalid: [],
            getCaret: function () {
                try {
                    var sel,
                        pos = 0,
                        ctrl = el.get(0),
                        dSel = document.selection,
                        cSelStart = ctrl.selectionStart;

                    // IE Support
                    if (dSel && navigator.appVersion.indexOf('MSIE 10') === -1) {
                        sel = dSel.createRange();
                        sel.moveStart('character', -p.val().length);
                        pos = sel.text.length;
                    }
                    // Firefox support
                    else if (cSelStart || cSelStart === '0') {
                        pos = cSelStart;
                    }

                    return pos;
                } catch (e) {}
            },
            setCaret: function(pos) {
                try {
                    if (el.is(':focus')) {
                        var range, ctrl = el.get(0);

                        // Firefox, WebKit, etc..
                        if (ctrl.setSelectionRange) {
                            ctrl.setSelectionRange(pos, pos);
                        } else { // IE
                            range = ctrl.createTextRange();
                            range.collapse(true);
                            range.moveEnd('character', pos);
                            range.moveStart('character', pos);
                            range.select();
                        }
                    }
                } catch (e) {}
            },
            events: function() {
                el
                .on('keydown.mask', function(e) {
                    el.data('mask-keycode', e.keyCode || e.which);
                    el.data('mask-previus-value', el.val());
                    el.data('mask-previus-caret-pos', p.getCaret());
                    p.maskDigitPosMapOld = p.maskDigitPosMap;
                })
                .on($.jMaskGlobals.useInput ? 'input.mask' : 'keyup.mask', p.behaviour)
                .on('paste.mask drop.mask', function() {
                    setTimeout(function() {
                        el.keydown().keyup();
                    }, 100);
                })
                .on('change.mask', function(){
                    el.data('changed', true);
                })
                .on('blur.mask', function(){
                    if (oldValue !== p.val() && !el.data('changed')) {
                        el.trigger('change');
                    }
                    el.data('changed', false);
                })
                // it's very important that this callback remains in this position
                // otherwhise oldValue it's going to work buggy
                .on('blur.mask', function() {
                    oldValue = p.val();
                })
                // select all text on focus
                .on('focus.mask', function (e) {
                    if (options.selectOnFocus === true) {
                        $(e.target).select();
                    }
                })
                // clear the value if it not complete the mask
                .on('focusout.mask', function() {
                    if (options.clearIfNotMatch && !regexMask.test(p.val())) {
                       p.val('');
                   }
                });
            },
            getRegexMask: function() {
                var maskChunks = [], translation, pattern, optional, recursive, oRecursive, r;

                for (var i = 0; i < mask.length; i++) {
                    translation = jMask.translation[mask.charAt(i)];

                    if (translation) {

                        pattern = translation.pattern.toString().replace(/.{1}$|^.{1}/g, '');
                        optional = translation.optional;
                        recursive = translation.recursive;

                        if (recursive) {
                            maskChunks.push(mask.charAt(i));
                            oRecursive = {digit: mask.charAt(i), pattern: pattern};
                        } else {
                            maskChunks.push(!optional && !recursive ? pattern : (pattern + '?'));
                        }

                    } else {
                        maskChunks.push(mask.charAt(i).replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'));
                    }
                }

                r = maskChunks.join('');

                if (oRecursive) {
                    r = r.replace(new RegExp('(' + oRecursive.digit + '(.*' + oRecursive.digit + ')?)'), '($1)?')
                         .replace(new RegExp(oRecursive.digit, 'g'), oRecursive.pattern);
                }

                return new RegExp(r);
            },
            destroyEvents: function() {
                el.off(['input', 'keydown', 'keyup', 'paste', 'drop', 'blur', 'focusout', ''].join('.mask '));
            },
            val: function(v) {
                var isInput = el.is('input'),
                    method = isInput ? 'val' : 'text',
                    r;

                if (arguments.length > 0) {
                    if (el[method]() !== v) {
                        el[method](v);
                    }
                    r = el;
                } else {
                    r = el[method]();
                }

                return r;
            },
            calculateCaretPosition: function() {
                var oldVal = el.data('mask-previus-value') || '',
                    newVal = p.getMasked(),
                    caretPosNew = p.getCaret();
                if (oldVal !== newVal) {
                    var caretPosOld = el.data('mask-previus-caret-pos') || 0,
                        newValL = newVal.length,
                        oldValL = oldVal.length,
                        maskDigitsBeforeCaret = 0,
                        maskDigitsAfterCaret = 0,
                        maskDigitsBeforeCaretAll = 0,
                        maskDigitsBeforeCaretAllOld = 0,
                        i = 0;

                    for (i = caretPosNew; i < newValL; i++) {
                        if (!p.maskDigitPosMap[i]) {
                            break;
                        }
                        maskDigitsAfterCaret++;
                    }

                    for (i = caretPosNew - 1; i >= 0; i--) {
                        if (!p.maskDigitPosMap[i]) {
                            break;
                        }
                        maskDigitsBeforeCaret++;
                    }

                    for (i = caretPosNew - 1; i >= 0; i--) {
                        if (p.maskDigitPosMap[i]) {
                            maskDigitsBeforeCaretAll++;
                        }
                    }

                    for (i = caretPosOld - 1; i >= 0; i--) {
                        if (p.maskDigitPosMapOld[i]) {
                            maskDigitsBeforeCaretAllOld++;
                        }
                    }

                    // if the cursor is at the end keep it there
                    if (caretPosNew > oldValL) {
                      caretPosNew = newValL * 10;
                    } else if (caretPosOld >= caretPosNew && caretPosOld !== oldValL) {
                        if (!p.maskDigitPosMapOld[caretPosNew])  {
                          var caretPos = caretPosNew;
                          caretPosNew -= maskDigitsBeforeCaretAllOld - maskDigitsBeforeCaretAll;
                          caretPosNew -= maskDigitsBeforeCaret;
                          if (p.maskDigitPosMap[caretPosNew])  {
                            caretPosNew = caretPos;
                          }
                        }
                    }
                    else if (caretPosNew > caretPosOld) {
                        caretPosNew += maskDigitsBeforeCaretAll - maskDigitsBeforeCaretAllOld;
                        caretPosNew += maskDigitsAfterCaret;
                    }
                }
                return caretPosNew;
            },
            behaviour: function(e) {
                e = e || window.event;
                p.invalid = [];

                var keyCode = el.data('mask-keycode');

                if ($.inArray(keyCode, jMask.byPassKeys) === -1) {
                    var newVal = p.getMasked(),
                        caretPos = p.getCaret();

                    // this is a compensation to devices/browsers that don't compensate
                    // caret positioning the right way
                    setTimeout(function() {
                      p.setCaret(p.calculateCaretPosition());
                    }, $.jMaskGlobals.keyStrokeCompensation);

                    p.val(newVal);
                    p.setCaret(caretPos);
                    return p.callbacks(e);
                }
            },
            getMasked: function(skipMaskChars, val) {
                var buf = [],
                    value = val === undefined ? p.val() : val + '',
                    m = 0, maskLen = mask.length,
                    v = 0, valLen = value.length,
                    offset = 1, addMethod = 'push',
                    resetPos = -1,
                    maskDigitCount = 0,
                    maskDigitPosArr = [],
                    lastMaskChar,
                    check;

                if (options.reverse) {
                    addMethod = 'unshift';
                    offset = -1;
                    lastMaskChar = 0;
                    m = maskLen - 1;
                    v = valLen - 1;
                    check = function () {
                        return m > -1 && v > -1;
                    };
                } else {
                    lastMaskChar = maskLen - 1;
                    check = function () {
                        return m < maskLen && v < valLen;
                    };
                }

                var lastUntranslatedMaskChar;
                while (check()) {
                    var maskDigit = mask.charAt(m),
                        valDigit = value.charAt(v),
                        translation = jMask.translation[maskDigit];

                    if (translation) {
                        if (valDigit.match(translation.pattern)) {
                            buf[addMethod](valDigit);
                             if (translation.recursive) {
                                if (resetPos === -1) {
                                    resetPos = m;
                                } else if (m === lastMaskChar && m !== resetPos) {
                                    m = resetPos - offset;
                                }

                                if (lastMaskChar === resetPos) {
                                    m -= offset;
                                }
                            }
                            m += offset;
                        } else if (valDigit === lastUntranslatedMaskChar) {
                            // matched the last untranslated (raw) mask character that we encountered
                            // likely an insert offset the mask character from the last entry; fall
                            // through and only increment v
                            maskDigitCount--;
                            lastUntranslatedMaskChar = undefined;
                        } else if (translation.optional) {
                            m += offset;
                            v -= offset;
                        } else if (translation.fallback) {
                            buf[addMethod](translation.fallback);
                            m += offset;
                            v -= offset;
                        } else {
                          p.invalid.push({p: v, v: valDigit, e: translation.pattern});
                        }
                        v += offset;
                    } else {
                        if (!skipMaskChars) {
                            buf[addMethod](maskDigit);
                        }

                        if (valDigit === maskDigit) {
                            maskDigitPosArr.push(v);
                            v += offset;
                        } else {
                            lastUntranslatedMaskChar = maskDigit;
                            maskDigitPosArr.push(v + maskDigitCount);
                            maskDigitCount++;
                        }

                        m += offset;
                    }
                }

                var lastMaskCharDigit = mask.charAt(lastMaskChar);
                if (maskLen === valLen + 1 && !jMask.translation[lastMaskCharDigit]) {
                    buf.push(lastMaskCharDigit);
                }

                var newVal = buf.join('');
                p.mapMaskdigitPositions(newVal, maskDigitPosArr, valLen);
                return newVal;
            },
            mapMaskdigitPositions: function(newVal, maskDigitPosArr, valLen) {
              var maskDiff = options.reverse ? newVal.length - valLen : 0;
              p.maskDigitPosMap = {};
              for (var i = 0; i < maskDigitPosArr.length; i++) {
                p.maskDigitPosMap[maskDigitPosArr[i] + maskDiff] = 1;
              }
            },
            callbacks: function (e) {
                var val = p.val(),
                    changed = val !== oldValue,
                    defaultArgs = [val, e, el, options],
                    callback = function(name, criteria, args) {
                        if (typeof options[name] === 'function' && criteria) {
                            options[name].apply(this, args);
                        }
                    };

                callback('onChange', changed === true, defaultArgs);
                callback('onKeyPress', changed === true, defaultArgs);
                callback('onComplete', val.length === mask.length, defaultArgs);
                callback('onInvalid', p.invalid.length > 0, [val, e, el, p.invalid, options]);
            }
        };

        el = $(el);
        var jMask = this, oldValue = p.val(), regexMask;

        mask = typeof mask === 'function' ? mask(p.val(), undefined, el,  options) : mask;

        // public methods
        jMask.mask = mask;
        jMask.options = options;
        jMask.remove = function() {
            var caret = p.getCaret();
            if (jMask.options.placeholder) {
                el.removeAttr('placeholder');
            }
            if (el.data('mask-maxlength')) {
                el.removeAttr('maxlength');
            }
            p.destroyEvents();
            p.val(jMask.getCleanVal());
            p.setCaret(caret);
            return el;
        };

        // get value without mask
        jMask.getCleanVal = function() {
           return p.getMasked(true);
        };

        // get masked value without the value being in the input or element
        jMask.getMaskedVal = function(val) {
           return p.getMasked(false, val);
        };

       jMask.init = function(onlyMask) {
            onlyMask = onlyMask || false;
            options = options || {};

            jMask.clearIfNotMatch  = $.jMaskGlobals.clearIfNotMatch;
            jMask.byPassKeys       = $.jMaskGlobals.byPassKeys;
            jMask.translation      = $.extend({}, $.jMaskGlobals.translation, options.translation);

            jMask = $.extend(true, {}, jMask, options);

            regexMask = p.getRegexMask();

            if (onlyMask) {
                p.events();
                p.val(p.getMasked());
            } else {
                if (options.placeholder) {
                    el.attr('placeholder' , options.placeholder);
                }

                // this is necessary, otherwise if the user submit the form
                // and then press the "back" button, the autocomplete will erase
                // the data. Works fine on IE9+, FF, Opera, Safari.
                if (el.data('mask')) {
                  el.attr('autocomplete', 'off');
                }

                // detect if is necessary let the user type freely.
                // for is a lot faster than forEach.
                for (var i = 0, maxlength = true; i < mask.length; i++) {
                    var translation = jMask.translation[mask.charAt(i)];
                    if (translation && translation.recursive) {
                        maxlength = false;
                        break;
                    }
                }

                if (maxlength) {
                    el.attr('maxlength', mask.length).data('mask-maxlength', true);
                }

                p.destroyEvents();
                p.events();

                var caret = p.getCaret();
                p.val(p.getMasked());
                p.setCaret(caret);
            }
        };

        jMask.init(!el.is('input'));
    };

    $.maskWatchers = {};
    var HTMLAttributes = function () {
        var input = $(this),
            options = {},
            prefix = 'data-mask-',
            mask = input.attr('data-mask');

        if (input.attr(prefix + 'reverse')) {
            options.reverse = true;
        }

        if (input.attr(prefix + 'clearifnotmatch')) {
            options.clearIfNotMatch = true;
        }

        if (input.attr(prefix + 'selectonfocus') === 'true') {
           options.selectOnFocus = true;
        }

        if (notSameMaskObject(input, mask, options)) {
            return input.data('mask', new Mask(this, mask, options));
        }
    },
    notSameMaskObject = function(field, mask, options) {
        options = options || {};
        var maskObject = $(field).data('mask'),
            stringify = JSON.stringify,
            value = $(field).val() || $(field).text();
        try {
            if (typeof mask === 'function') {
                mask = mask(value);
            }
            return typeof maskObject !== 'object' || stringify(maskObject.options) !== stringify(options) || maskObject.mask !== mask;
        } catch (e) {}
    },
    eventSupported = function(eventName) {
        var el = document.createElement('div'), isSupported;

        eventName = 'on' + eventName;
        isSupported = (eventName in el);

        if ( !isSupported ) {
            el.setAttribute(eventName, 'return;');
            isSupported = typeof el[eventName] === 'function';
        }
        el = null;

        return isSupported;
    };

    $.fn.mask = function(mask, options) {
        options = options || {};
        var selector = this.selector,
            globals = $.jMaskGlobals,
            interval = globals.watchInterval,
            watchInputs = options.watchInputs || globals.watchInputs,
            maskFunction = function() {
                if (notSameMaskObject(this, mask, options)) {
                    return $(this).data('mask', new Mask(this, mask, options));
                }
            };

        $(this).each(maskFunction);

        if (selector && selector !== '' && watchInputs) {
            clearInterval($.maskWatchers[selector]);
            $.maskWatchers[selector] = setInterval(function(){
                $(document).find(selector).each(maskFunction);
            }, interval);
        }
        return this;
    };

    $.fn.masked = function(val) {
        return this.data('mask').getMaskedVal(val);
    };

    $.fn.unmask = function() {
        clearInterval($.maskWatchers[this.selector]);
        delete $.maskWatchers[this.selector];
        return this.each(function() {
            var dataMask = $(this).data('mask');
            if (dataMask) {
                dataMask.remove().removeData('mask');
            }
        });
    };

    $.fn.cleanVal = function() {
        return this.data('mask').getCleanVal();
    };

    $.applyDataMask = function(selector) {
        selector = selector || $.jMaskGlobals.maskElements;
        var $selector = (selector instanceof $) ? selector : $(selector);
        $selector.filter($.jMaskGlobals.dataMaskAttr).each(HTMLAttributes);
    };

    var globals = {
        maskElements: 'input,td,span,div',
        dataMaskAttr: '*[data-mask]',
        dataMask: true,
        watchInterval: 300,
        watchInputs: true,
        keyStrokeCompensation: 10,
        // old versions of chrome dont work great with input event
        useInput: !/Chrome\/[2-4][0-9]|SamsungBrowser/.test(window.navigator.userAgent) && eventSupported('input'),
        watchDataMask: false,
        byPassKeys: [9, 16, 17, 18, 36, 37, 38, 39, 40, 91],
        translation: {
            '0': {pattern: /\d/},
            '9': {pattern: /\d/, optional: true},
            '#': {pattern: /\d/, recursive: true},
            'A': {pattern: /[a-zA-Z0-9]/},
            'S': {pattern: /[a-zA-Z]/}
        }
    };

    $.jMaskGlobals = $.jMaskGlobals || {};
    globals = $.jMaskGlobals = $.extend(true, {}, globals, $.jMaskGlobals);

    // looking for inputs with data-mask attribute
    if (globals.dataMask) {
        $.applyDataMask();
    }

    setInterval(function() {
        if ($.jMaskGlobals.watchDataMask) {
            $.applyDataMask();
        }
    }, globals.watchInterval);
}, window.jQuery, window.Zepto));

const BMP_Procesi = {
    PRO_Nalozi: 10000,
    PRO_NaloziArtikli: 10001,
    RBI_Invoices:1,
    INS_Predmeti: 2,
    RBI_OB2_Zaglavlje: 3,
    SMS_Sending: 4,
    SFR_Subjekti:5,
    PIS_Obrazac8:7,
    DMS_Dokumenti: 8,
    PIS_Obrazac17: 9,
    PIS_InterniProtokol: 10,
    INS_Nadzori: 11,
    Requests:12,
    UGO_Ugovori: 13,
    SMS_Poruke: 14,
    SMS_UzorakZaglavlja: 15,
    SMS_Uzorak: 16,
    RBI_OB3_SegmentiKonta: 17,
    RBI_OstalaPlacanja: 18,
    RBI_OP_Stavke: 19,
    RBI_OB2_SegmentiKonta: 20,
    RPT_Izvjestaji: 21,
    PIS_Obrazac5: 22,
    BDG_RS_Prihodi: 23,
    PIS_Revers: 24,
    OS_InvesticijeToku: 25,
    BDG_OB5_Rashodi: 26,
    BDG_RS_Plan_Master: 27,
    BDG_RS_Plan_Detalj: 28,
    BDG_ReAl_Master: 29,
    WWW_GRA_Prigovori: 30,
    PAR_LM_LEADS: 31,
    WWW_GRA_eM_Rodjenje: 32,
    WWW_GRA_eM_Umrli: 33,
    WWW_GRA_eM_Vjencani: 34,
    WWW_GRA_Identifikacija: 35,
    CMS_HTML_Elements: 36,
    CIPS_Provjere: 37,
    WWW_Vijesti: 38,
    PAR_LM_PROSLIJEDI: 39
   
};
const BMP_Statusi = {
    KUF_POSLAN_NA_PLACANJE:14,
    INS_Predmeti_NERASPOREDJEN: 1001,
    INS_Predmeti_NA_ZAPRIMANJU: 1002,
    INS_Predmeti_ZAPRIMLJEN: 1003,
    INS_Predmeti_PRESIGNACIJA: 1004,
    INS_Predmeti_ZATVOREN:1005,
    INS_Predmeti_POSTUPAK_OBUSTAVLJEN: 1029,
    INS_Predmeti_URADJENO_RJESENJE: 1024,
    OB2_Zaglavlje_U_OBRADI: 1039,
    OB2_Zaglavlje_ZAKLJUCEN: 1040,
    OB2_Zaglavlje_STAMPAN: 1041,
    OB2_Zaglavlje_OBRISAN: 30,
    OB2_Zaglavlje_PRENESEN_U_BUDGET: 1076,
    RBI_OP_Stavke_Kreiran : 1072,
    RBI_OP_Stavke_U_REALIZACIJI : 1073,
    RBI_OP_Stavke_PROKNJIZEN : 1074,
    RBI_OP_Stavke_PLACEN: 1075,
    UGO_UNESEN : 1037,
    UGO_AKTIVAN : 1106,
    UGO_TUZBA : 1108,
    UGO_ZAVRSEN: 1107,
    //BDG_MAster
    BDG_MASTER_U_IZRADI: 1116,
    BDG_MASTER_ZAVRSEN: 1118,
    BDG_MASTER_KREIRANE_STAVKE: 1122,
    BDG_MASTER_PLANIRANJEQ1: 1123,
    BDG_MASTER_ZAVRSENQ1: 1124,
    BDG_MASTER_PLANIRANJEQ2: 1125,
    BDG_MASTER_ZAVRSENQ2: 1126,
    BDG_MASTER_PLANIRANJEQ3: 1127,
    BDG_MASTER_ZAVRSENQ3: 1128,
    BDG_MASTER_PLANIRANJEQ4: 1129,
    BDG_MASTER_ZAVRSENQ4: 1130,
    BDG_DETALJ_OTKLJUCANQ1: 1131,
    BDG_DETALJ_ZAKLJUCANQ1: 1132,
    BDG_DETALJ_OTKLJUCANQ2: 1133,
    BDG_DETALJ_ZAKLJUCANQ2: 1134,
    BDG_DETALJ_OTKLJUCANQ3: 1135,
    BDG_DETALJ_ZAKLJUCANQ3: 1136,
    BDG_DETALJ_OTKLJUCANQ4: 1137,
    BDG_DETALJ_ZAKLJUCANQ4: 1138,
    BDG_MASTER_ZAVRSENO_GODISNJE_PLANIRANJE: 1190,//javna rasprava
    BDG_UNOS_PRIJEDLOGA: 2000
};
const SMS_VrstaSlanja = {
    REDOVNO: 1,
    PO_ZAHTJEVU: 2,
    POJEDINACNO: 3
};
const BPM_Uloge = {
    Odjel_Referent: 27,
    PrimaocDP: 30,
};
const RBI_OSTALA_PLACANJA_VrstaPlacanjaID = {
    Kredit: 10
};
let currentYear = (new Date).getFullYear();
let currentMonth = (new Date).getMonth();
function TestVerzije() {
    alert("Verzija 3");
}
//defaultni text za boostrap combo box
$.fn.selectpicker.defaults = {
    selectAllText: "All",
    deselectAllText: "None",
    noneSelectedText: "---------------"
}
//extenzija za eneter ne radi za sad radi mojih evenata
$.fn.enterKey = function (fnc) {
    console.log('enter key pressed');
    return this.each(function () {
        $(this).keypress(function (ev) {
            let keycode = (ev.keyCode ? ev.keyCode : ev.which);
            if (keycode == '13') {
                fnc.call(this, ev);
            }
        })
    })
}
//popunjavanje comboboxa forme boostrap select
function Cmb(selector, url, afterSuccess, async = true, odaberitext = "odaberi...", addBackspaceEvent = true) {
    customLoadingForms = true;
    //$(selector).parent().block("<h1>učitavanje menija</h1>"); 
    return $.ajax({
        url: url,
        dataType: 'json',
        data: {},
        async: async,
        success: function (data) {
            if (data.Successed == "0") {
                let poruka = `Greška kod popunjavanja izbornika: ${selector} greška:${data.Message} `;
                $(`button[data-id="${selector.replace("#", "")}"]`).find("span.filter-option").text(data.Message);
                swal({ title: "Poruka", text: poruka, dangerMode: true, icon: "error" });
                return;
            }
           // console.log();
            // data = JSON.stringify(data);
            $(selector).empty();
            //$(selector).append(new Option('odaberi...', '',true));
            $(selector).append(`<option value="" data-hidden="true">${odaberitext}</option>`);
            if (data != '') {
                $.each(JSON.parse(data), function (i, item) {
                    $(selector).append(new Option(item.Naziv, item.Sifra));
                });
            }

            $(selector).selectpicker();
            if (afterSuccess) {
                afterSuccess();
            }
            $(selector).selectpicker("refresh");
            customLoadingForms = false;
            $(selector).unblock(); 
            if (addBackspaceEvent) {
                let id = $(selector).attr('id');
                /*console.log('id');
                console.log(id);
                alert(id);*/
                $(`button[data-id="${id}"]`).keyup(function (e) {
                    let disabled = $(selector).attr('disabled');
                    if (e.keyCode == 8 && disabled != 'disabled') {
                        $(selector).val('');
                        $(selector).selectpicker("refresh");
                        $(selector).trigger("change");
                    }

                });
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            /*console.log(xhr.responseText);
            if (xhr.responseText == 'Nemate pravo pristupa') {
                swal({ title: "Poruka", text: xhr.responseText, dangerMode: true, icon: "error" });
            }*/
            customLoadingForms = false;
            let poruka = `Greška kod popunjavanja izbornika: ${selector},greška:${thrownError},reponseText:${xhr.responseText} `;
            $(`button[data-id="${selector.replace("#", "")}"]`).find("span.filter-option").text(xhr.responseText);

            swal({ title: "Poruka", text: poruka, dangerMode: true, icon: "error" });
        }
    });
}
/*za dodavanje svih kolona s vrijednostima na opciju pored sifre i naziva*/
/*ovako doci do vrijednosti odabrane opcije  $("#cmbBookIDRBI_InvoicesEdit").find("option:selected").attr("FiscalYear")*/
/*odbrati opciju koja ima neku vrijednost kolone $("#cmbBookIDRBI_InvoicesEdit").find("option[fiscalyear=2023]").val()*/
function CmbAddColumns(selector, url, afterSuccess, async = true, odaberitext = "odaberi...",addBackspaceEvent=false) {
    customLoadingForms = true;
   
    //$(selector).parent().block("<h1>učitavanje menija</h1>"); 
    return $.ajax({
        url: url,
        dataType: 'json',
        data: {},
        async: async,
        success: function (data) {
            // data = JSON.stringify(data);
            if (data.Successed == "0") {
                let poruka = `Greška kod popunjavanja izbornika: ${selector} greška:${data.Message} `;
                $(`button[data-id="${selector.replace("#", "")}"]`).find("span.filter-option").text(data.Message);
                swal({ title: "Poruka", text: poruka, dangerMode: true, icon: "error" });
                return;
            }
            $(selector).empty();
            //$(selector).append(new Option('odaberi...', '',true));
            $(selector).append(`<option value="" data-hidden="true">${odaberitext}</option>`);
            if (data != '') {
                $.each(JSON.parse(data), function (i, item) {
                    //$(selector).append(new Option(item.Naziv, item.Sifra));
                    let Sifra = null;
                    let Naziv = null;
                    if (item.Sifra != undefined) {
                        Sifra = item.Sifra;
                    } else {
                        Sifra = item.Id;
                    }
                    if (item.Naziv != undefined) {
                        Naziv = item.Naziv;
                    } else {
                        Naziv = item.Name;
                    }
                    let OstaleKolone = ``;
                    $.each(item, function (i, n) {
                        OstaleKolone = OstaleKolone + ` ${i}="${n}"`;
                        //alert( "Name: " + i + ", Value: " + n );
                    });
                    $(selector).append(`<option value=${Sifra} ${OstaleKolone}> ${Naziv}</option>`);
                });
            }

            $(selector).selectpicker();
            if (afterSuccess) {
                afterSuccess();
            }
            $(selector).selectpicker("refresh");
            customLoadingForms = false;
            $(selector).unblock();
            if (addBackspaceEvent) {
                let id = $(selector).attr('id');
                $(`button[data-id=${id}]`).keyup(function (e) {
                    let disabled = $(selector).attr('disabled');
                    if (e.keyCode == 8 && disabled != 'disabled') {
                        $(selector).val('');
                        $(selector).selectpicker("refresh");
                        $(selector).trigger("change");
                    }

                });
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            customLoadingForms = false;
            let poruka = `Greška kod popunjavanja izbornika: ${selector},greška:${thrownError},reponseText:${xhr.responseText} `;
            $(`button[data-id="${selector.replace("#", "")}"]`).find("span.filter-option").text(xhr.responseText);
            swal({ title: "Poruka", text: poruka, dangerMode: true, icon: "error" });
        }
    });
}
function qs(key) {
    key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
    let match = location.search.match(new RegExp("[?&]" + key + "=([^&]+)(&|$)"));
    return match && decodeURIComponent(match[1].replace(/\+/g, " "));
}
function textAreaAdjust(elem) {
    $(elem).each(function () {
        this.setAttribute("style", "height:" + (this.scrollHeight) + "px;overflow-y:hidden;");
    }).on("input", function () {
        this.style.height = 0;
        this.style.height = (this.scrollHeight) + "px";
    });
   
}
function AutocompleteCMB() {
    let dataurl = `/json/GetSubjekti`;
    $('#cmbAkteri').mcautocomplete({
        maxShowItems: 10,
        showHeader: true,
        columns: [
            {
                name: 'Naziv',
                width: '200px',
                valueField: 'Naziv'
            },
            {
                name: 'Ulica',
                width: '300px',
                valueField: 'UlicaBroj'
            }],
        keypress: function (event, ui) {
            console.log(event);
        },
        select: function (event, ui) {
            //this.attr('sifra');
            this.value = (ui.item ? ui.item.Naziv : '');
            $(this).attr('sifra', ui.item.Sifra);
            return false;
        },
        focus: function (event, ui) {/*problem sa key down i focus-mjenja vrijednost samo fokusirajuci*/

            if ($('.ui-widget-content:hover').length != 0)//focus fix
                return;
            this.value = (ui.item ? ui.item.Naziv : '');
            $(this).attr('sifra', ui.item.Sifra);
            return false;
        },
        minLength: 0,
        source: function (request, response) {
            let filter = "";
            filter = $(':focus').val();
            if (filter.length < 3) {
                return;
            }
            if ($(':focus').attr('showall') == 'true') {
                filter = '';
                $(':focus').removeAttr('showall');
            }
            $.ajax({
                url: dataurl,
                dataType: 'json',
                data:
                {
                    filter: filter
                },
                success: function (data) {
                    data = JSON.stringify(data);
                    data = JSON.parse(data);
                    let result;
                    if (!data || data.length === 0) {
                    } else {
                        result = data;
                    }
                    response(JSON.parse(result));
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert(thrownError);
                }
            });
        }
    });
}
function CmbAkteri(selector, url, afterSuccess, async = true) {
    return $.ajax({
        url: url,
        dataType: 'json',
        data: {},
        async: async,
        success: function (data) {
            // data = JSON.stringify(data);
            $(selector).empty();
            //$(selector).append(new Option('odaberi...', '',true));
            $(selector).append('<option value="" data-hidden="true">odaberi...</option>');
            if (data != '') {
                $.each(JSON.parse(data), function (i, item) {
                    //$(selector).append(new Option(item.Naziv, item.Sifra));
                    $(selector).append(`<option value=${item.Sifra} TipAktera=${item.TipAktera} Interno=${item.Interno}>${item.Naziv}</option>`);
                });
            }

            $(selector).selectpicker();
            if (afterSuccess) {
                afterSuccess();
            }
            $(selector).selectpicker("refresh");
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(thrownError);
        }
    });
}
//CmbAkteri('#cmbAkter', `/json/getAkteri?ProcesID=${10}&InstancaID=${40}`);
//$('#cmbAkter option:selected').attr('interno')
function GetCurrentDateWithTIme() {
    let Datum = new Date();
    let Dan = ('0' + Datum.getDate()).slice(-2);
    let Mjesec = ('0' + (Datum.getMonth() + 1)).slice(-2);
    let Godina = Datum.getFullYear();
    formateddate = Dan + '.' + Mjesec + '.' + Godina + ' ' + ('0' + Datum.getHours()).slice(-2) + ':' + ('0' + Datum.getUTCMinutes()).slice(-2);
    return formateddate;
}
function GetCurrentDate() {
    let Datum = new Date();
    let Dan = ('0' + Datum.getDate()).slice(-2);
    let Mjesec = ('0' + (Datum.getMonth() + 1)).slice(-2);
    let Godina = Datum.getFullYear();
    formateddate = Dan + '.' + Mjesec + '.' + Godina;
    return formateddate;
}
function GetFirstDayOfCurrentYear() {
    let Datum = new Date();
    let Dan = ('0' + Datum.getDate()).slice(-2);
    let Mjesec = ('0' + (Datum.getMonth() + 1)).slice(-2);
    let Godina = Datum.getFullYear();
    formateddate =  '01.01.' + Godina;
    return formateddate;
}
function MaskDateEdit() {
    $("input.zebra").unbind("input");
    $('input.zebra').on('input', function () {
        let length = $(this).val().length;
        let val = $(this).val();
        if (length == 2) {
            $(this).val(val + '.');
        }
        else if (length == 4 && parseInt(val.substr(val.length - 1)) > 1) {
            //val.substr(val.length - 1);
            $(this).val(val.slice(0, 3) + '0' + val.substr(val.length - 1) + '.');
        }
        else if (length == 5) {
            $(this).val(val + '.');
        }
    });
}
function BootsrapFileStyleRefresh() {
    $('.filestyle').each(function () {
        let $this = $(this), options = {
            'input': $this.attr('data-input') !== 'false',
            'htmlIcon': $this.attr('data-icon'),
            'buttonBefore': $this.attr('data-buttonBefore') === 'true',
            'disabled': $this.attr('data-disabled') === 'true',
            'size': $this.attr('data-size'),
            'text': $this.attr('data-text'),
            'btnClass': $this.attr('data-btnClass'),
            'badge': $this.attr('data-badge') === 'true',
            'dragdrop': $this.attr('data-dragdrop') !== 'false',
            'badgeName': $this.attr('data-badgeName'),
            'placeholder': $this.attr('data-placeholder')
        };

        $this.filestyle(options);
    });
}
/*dinamičko učitavanje skripte */
function reload_js(name, src, refreshLoad) {
    //$(`script[tip="added"]`).remove();
    if ($(`script#${name}`).length > 0) {
        refreshLoad();
        return;
    }
    $(`script#${name}`).remove();
    $(`<script tip="added" id="${name}">`).attr('src', src).appendTo('head');
}
//prebacivanje string broja sa tačkama i zarezom u broj
function StringToNumber(value) {
    if (value == undefined) {
        return 0;
    }
    if (value == null) {
        return 0;
    }
    let r = value.toString().replaceAll(".", "");
    return r;
}
//broj u formatiran string
function NumberToString(value) {
    if (value == ''||value==undefined) {
        return value;
    }
    if (String(value).indexOf(",") >= 0) {
        value = parseFloat(value.replaceAll(".", "").replaceAll(",", "."));
    } else {
        value = parseFloat(value);
    }
   
    let r = (value).toLocaleString(
        'de-DE',
        { minimumFractionDigits: 2 }
    );
    return r;
}
//nakon napuštanja kontrole sa brojem da formatira sa tačkom i zarezom-za sve kontrole navedenog tipa
function SetFormatNumber() {
    $('input.form-control.number').on('blur', function (a) {
        let value = $(this).val();
        if (value != undefined && value != '') {
            $(this).val(NumberToString(value));
        }
    });
}
//nakon napuštanja kontrole sa brojem da formatira sa tačkom i zarezom
function SetFormatNumberForControl(control) {
    $(control).on('blur', function (a) {
        let value = $(this).val();
        if (value != undefined && value != '') {
            $(this).val(NumberToString(value));
        }
    });
}
function FormatDateTime(datum) {
    if (datum == '') {
        return '';
    }
    let Datum = new Date(parseInt((datum).toString().substr(6)));
    let Dan = ('0' + Datum.getDate()).slice(-2);
    let Mjesec = ('0' + (Datum.getMonth() + 1)).slice(-2);
    let Godina = Datum.getFullYear();
    formateddate = Dan + '.' + Mjesec + '.' + Godina + ' ' + ('0' + Datum.getHours()).slice(-2) + ':' + ('0' + Datum.getUTCMinutes()).slice(-2);
    return formateddate;
}
function FormatDateTimeZ(datum) {
    let formattedDate = new Date(datum);
    let d = formattedDate.getDate();
    let m = formattedDate.getMonth();
    m += 1;  // JavaScript months are 0-11
    let y = formattedDate.getFullYear();
    return d + "." + m + "." + y;
}
//da se u datetime editoru nemogu kucati slova i ako se klikne dole i ako je prazan da popuni sa današnjim datumom
jQuery(document).on('keydown', 'input.form-control.zebra', function (e) {
    console.log(e.originalEvent.key + '-'+ e.which);
    if ((e.which < 48 || e.which > 57) && e.keyCode !== 8 && (e.which < 97 || e.which > 105) && e.keyCode !==96) {
        e.preventDefault();
    }
    if (e.originalEvent.key == 'ArrowDown' && $(this).val() == '') {
        $(this).val(GetCurrentDate());
    }

});
$('#WarmUp').click(function () {
    testlinks();
});
$('#navBarTopFullScreen').click(function () {
    toggleFullScreen();
});
$('#navBarTopHome').click(function () {
    window.location = '/';
});

function toggleFullScreen() {
    if (!document.fullscreenElement &&    // alternative standard method
        !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement) {  // current working methods
        if (document.documentElement.requestFullscreen) {
            document.documentElement.requestFullscreen();
        } else if (document.documentElement.msRequestFullscreen) {
            document.documentElement.msRequestFullscreen();
        } else if (document.documentElement.mozRequestFullScreen) {
            document.documentElement.mozRequestFullScreen();
        } else if (document.documentElement.webkitRequestFullscreen) {
            document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
        }
    } else {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        }
    }
}
let ReloadIfNematePravaPristupa = true;
let ShowJavascriptError = true;
function testlinks() {
    ReloadIfNematePravaPristupa = false;
    ShowJavascriptError = false;
  //  jQuery.ajaxSetup({ async: false });
    $('#SPAcontainer').empty();
  //login
    testLink('/Login/index');
    testLink('/Gra_Login?OdlogujKorisnika=0');
    testLink('/ChangePassword');
    testLink('/Register');
    testLink('/Login/ForgetPassword');
   
    testLink('/Gra_SmsVerification/smsVerificationPartial');
    testLink('/Gra_EmailVerification/emailVerificationPartial');
    testLink('/Gra_ChangePersonalData/changePersonalDataPartial');
    testLink('/Gra_ChangePassword/changePasswordPartial');

    testLink('/BPM_Zadaci/Prikaz');
    //LM_LEADS
    testLink('/PAR_LM_LEADS/index');
    testLink('/LM_RazlogZatvaranja/Index');
    testLink('/LM_VrstaKampanje/Index');
    testLink('/PAR_LM_Izvori/index');
    //ADM
    testLink('/ADM/ADM_Users/index');
    testLink('/ADM_Roles/index');
    testLink('/ADM_Groups/index');
   


    testGetData('/ADM_Groups/GetData', 'GroupID');
    testGetData('/ADM_Roles/GetData', 'RoleID');
    testGetData('/ADM_Scheme/GetSchemeData');
    testGetData('/ADM_SchemePlans/GetSchemePlansData');
    testGetData('/ADM/ADM_Users/GetData', 'UserID');
    testGetData('/ADM_WorkPlace/GetWorkPlaces/GetWorkPlaces');
    testGetData('/Subjekti/GetData', 'KlijentID');

    //testGetData('/INS_Predmeti/GetData');//fali requests
    // testGetData('/PIS_Obrazac8/GetData');//fali requests
    //ostalo
    /*
        testGetData('/RBI_OB2/GetData');
    testGetData('/INS_Nadzori/GetData');
        testLink('/RBI_Invoices');
    testLink('/RBI_OB2');
    testGetData('/RBI_Invoices/GetData');
    testLink('/docunovadashboard/index?dashboardFileName=RPT_DSH_KUF_PLACENO_NE_PLACENO_PO_OJ&ViewPage=RPT_DSH_KUF_PLACENO_NE_PLACENO_PO_OJ');
   testLink('/INS_Predmeti/IndexSPA');
    testLink('/INS_Nadzori');
    testLink('/PIS_Obrazac8/IndexSPA');
    testLink('/RBI_OB2');
    testLink('/INS_Predmeti/IndexSPA');
    testLink('/INS_Nadzori');
    testLink('/PIS_Obrazac8/IndexSPA');
        testGetData('/PIS_Obrazac17/GetData');
    testGetData('/PIS_InterniProtokol/GetData');
    */
    //jQuery.ajaxSetup({ async: true });
    //portal

    testLink('/GradiskaPortal/eMailGradonacelniku');
    testLink('/GradiskaPortal/pitanjaPrivrednika');
    testLink('/GradiskaPortal/pitanjaPrivrednika');
    testLink('/HTMLCMS/edit?ShowLayout=0');
    testLink('/WWW_Vijesti/index?ShowLayout=0');
}

function testlinksGetData() {
    ReloadIfNematePravaPristupa = false;
    $('#SPAcontainer').empty();

}
let TestLinkDelay = 1;
function testLink(url) {
    window.setTimeout(function () {
        let t1 = performance.now();
        $('#SPAcontainer').block();
        $.get(url, function (data) {

            let t2 = performance.now();
            /* if (data.success != undefined) {
                 $('#SPAcontainer').append(`<div class="successfull">${url}, duration:${(t2 - t1)} ms, data.success:${data.success},<div>`);
             }
             else {
                 $('#SPAcontainer').append(`<div class="successfull">${url}, duration:${(t2 - t1)} ms<div>`);
             }*/
            $('#SPAcontainer').append(`<div class="successfull">${url}, duration:${(t2 - t1)} ms, reponse:${data.responseText}<div>`);

        }).fail(function (data) {
            $('#SPAcontainer').append(`<div class="failed">${url}, reponse:${data.responseText}<div>`);
        }).always(function (data) {
            $('#SPAcontainer').unblock();
        });
        TestLinkDelay = TestLinkDelay + 1;
    }, TestLinkDelay *1000);
   
}
function testGetData(url,id='ID') {
    let vdata = [{
        currentPage: 1,
        rowsPerPage: 9999,
        sortfield: id,
        sortorder: 'desc',
        filter: '',
    }];
    vdata = { gridparams: JSON.stringify(vdata) };
    let t1 = performance.now();
    $.ajax({
        url: url,
        dataType: 'json',
        data: vdata,
        //async: false,
        success: function (data) {
            let t2 = performance.now();
            if (data.Successed == 0) {
                $('#SPAcontainer').append(`<div class="failed">${url}, duration:${(t2 - t1)} ms<div>`);
                swal({ title: "Poruka", text: data.Message, dangerMode: true, icon: "error" });
            } else {
                $('#SPAcontainer').append(`<div class="successfull"><b>${url}</b> - 1000 records, duration:${(t2 - t1)} ms, reponse:${data}<div>`);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            let t2 = performance.now();
            $('#SPAcontainer').append(`<div class="failed">${url}, duration:${(t2 - t1)} ms, error:${xhr.responseText}<div>`);
        }
    });
}
window.onerror = function (msg, fileName, url, linenumber) {
    let errorMessage = 'Error message: ' + msg + '\nURL: ' + url + '\nLine Number: ' + linenumber + 'fileName:' + fileName;
    //alert();
    if (ShowJavascriptError) {
        swal({ title: "Greška-javascript", text: errorMessage, dangerMode: true, icon: "error" });
    } else {
        console.log(errorMessage);
    }
   
    return false;
}
/*
input[type = "file"] {
    display: none;
}

<label for="avatar" class="btn controls" style="width: 200px; padding: 5px;">
    Odaberite fajlove
</label>
    <input type="file" id="avatar" name="avatar" accept="image/png, image/jpeg" multiple capture/>
UploadFilesToAPI("#avatar",'http://localhost:82/Upload?parametar1=test')
$("#avatar").change(function () {
        UploadFilesToAPI("#avatar", 'http://localhost:82/Upload?parametar1=test')
    });
    capture za sliku sa mob
*/
function UploadFilesToAPI(inputid,url) {
    jQuery.support.cors = true;
    let fileUpload = $(inputid).get(0);
    let files = fileUpload.files;

    let formData = new FormData();

    // Looping over all files and add it to FormData object  
    let i = 1;
    for (const element of files) {
       
        //console.log('(files[i].name:' + element.name);
        formData.append('File' + i, element);
        i++;
    }

    // You can update the jquery selector to use a css class if you want
    /*$("input[type='text'").each(function (x, y) {
        formData.append($(y).attr("name"), $(y).val());
    });
    */
    console.log(formData);
    $.ajax({
        type: 'POST',
        url: url,
        data: formData,
        processData: false,
        contentType: false,
        beforeSend: function (request) {
            request.setRequestHeader("s", "s");
        },
        success: function (data) {
            alert(data);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        }
    });
}

function BlockMainContent() {
    $('#MainContent').block({ message: `<img src='/Content/Images/Loading4.gif' style='filter: invert(100%);opacity: 0.4;'/><h4>Učitavanje</h4>` })
    //$('#MainContent').block({ message: `<img src='/Content/Images/gifs/WMDx.gif'/><h4>Učitavanje</h4>` })
}
function UnBlockMainContent() {
    $('#MainContent').unblock();
}

function LatToCyr(entered_text) {
    if (currentUserPismo != 'C') {
        return entered_text;
    }
    // do all procssing in this variable -> results show in another window

    entered_text = entered_text.replace(/lj/g, 'љ');
    entered_text = entered_text.replace(/Lj/g, 'Љ');
    entered_text = entered_text.replace(/LJ/g, 'Љ');

    entered_text = entered_text.replace(/nj/g, 'њ');
    entered_text = entered_text.replace(/Nj/g, 'Њ');
    entered_text = entered_text.replace(/NJ/g, 'Њ');

    entered_text = entered_text.replace(/dž/g, 'џ');
    entered_text = entered_text.replace(/Dž/g, 'Џ');
    entered_text = entered_text.replace(/DŽ/g, 'Џ');

    entered_text = entered_text.replace(/a/g, 'а');
    entered_text = entered_text.replace(/b/g, 'б');
    entered_text = entered_text.replace(/c/g, 'ц');
    entered_text = entered_text.replace(/č/g, 'ч');
    entered_text = entered_text.replace(/ć/g, 'ћ');
    entered_text = entered_text.replace(/d/g, 'д');
    entered_text = entered_text.replace(/đ/g, 'ђ');
    entered_text = entered_text.replace(/e/g, 'е');
    entered_text = entered_text.replace(/f/g, 'ф');
    entered_text = entered_text.replace(/g/g, 'г');
    entered_text = entered_text.replace(/h/g, 'х');
    entered_text = entered_text.replace(/i/g, 'и');
    entered_text = entered_text.replace(/j/g, 'ј');
    entered_text = entered_text.replace(/k/g, 'к');
    entered_text = entered_text.replace(/l/g, 'л');
    entered_text = entered_text.replace(/m/g, 'м');
    entered_text = entered_text.replace(/n/g, 'н');
    entered_text = entered_text.replace(/o/g, 'о');
    entered_text = entered_text.replace(/p/g, 'п');
    entered_text = entered_text.replace(/r/g, 'р');
    entered_text = entered_text.replace(/s/g, 'с');
    entered_text = entered_text.replace(/š/g, 'ш');
    entered_text = entered_text.replace(/t/g, 'т');
    entered_text = entered_text.replace(/u/g, 'у');
    entered_text = entered_text.replace(/v/g, 'в');
    entered_text = entered_text.replace(/z/g, 'з');
    entered_text = entered_text.replace(/ž/g, 'ж');

    entered_text = entered_text.replace(/A/g, 'А');
    entered_text = entered_text.replace(/B/g, 'Б');
    entered_text = entered_text.replace(/C/g, 'Ц');
    entered_text = entered_text.replace(/Č/g, 'Ч');
    entered_text = entered_text.replace(/Ć/g, 'Ћ');
    entered_text = entered_text.replace(/D/g, 'Д');
    entered_text = entered_text.replace(/Đ/g, 'Ђ');
    entered_text = entered_text.replace(/E/g, 'Е');
    entered_text = entered_text.replace(/F/g, 'Ф');
    entered_text = entered_text.replace(/G/g, 'Г');
    entered_text = entered_text.replace(/H/g, 'Х');
    entered_text = entered_text.replace(/I/g, 'И');
    entered_text = entered_text.replace(/J/g, 'Ј');
    entered_text = entered_text.replace(/K/g, 'К');
    entered_text = entered_text.replace(/L/g, 'Л');
    entered_text = entered_text.replace(/M/g, 'М');
    entered_text = entered_text.replace(/N/g, 'Н');
    entered_text = entered_text.replace(/O/g, 'О');
    entered_text = entered_text.replace(/P/g, 'П');
    entered_text = entered_text.replace(/R/g, 'Р');
    entered_text = entered_text.replace(/S/g, 'С');
    entered_text = entered_text.replace(/Š/g, 'Ш');
    entered_text = entered_text.replace(/T/g, 'Т');
    entered_text = entered_text.replace(/U/g, 'У');
    entered_text = entered_text.replace(/V/g, 'В');
    entered_text = entered_text.replace(/Z/g, 'З');
    entered_text = entered_text.replace(/Ž/g, 'Ж');

    return entered_text;
}

function ClearSearch() {
    $('#menuSearch').val('');
    PretraziMeni();
}
/*function copyToClipboard2(text) {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val(text).select();
    document.execCommand("copy");
    $temp.remove();
}*/
function SPA(clickevent, url, title, scriptpath, scriptId, functiontoExecute, params = '') {

    if (clickevent.originalEvent.which == 1) {
        if (!simulateSPA) {
            window.location = url;
            return;
        }
        $('#SPAcontainer').block();
        $.get(url + "?ShowLayout=0" + params, function (data) {
            if (String(data).startsWith("<!DOCTYPE html>") || String(data).indexOf("Nemate") >= 0) {
                window.location = url;
                return;
            }
            $('#SPAcontainer').html(data);
            reload_js(scriptId, scriptpath, function () {
                functiontoExecute();
            });
            SetDMSEvents();
            SetAkteriEvents();
            BootsrapFileStyleRefresh();
            setEditSubjektiEvents();
            $('#SPAcontainer').unblock();
            $('.modal-dialog').not('.notdraggable').draggable();
        }).fail(function () {
            window.location = url;
            return;
        });
        window.history.pushState('', '', url + "?ShowLayout=1" + params);
        document.title = title;
    } else {
        window.open(url + "?ShowLayout=1" + params, "_blank");
    }
    if ($(".navbar-toggle").is(":visible")) {
        $(".navbar-toggle").click();
    }
    $('tr.newrow').find("#nimage").tooltip('destroy');
    $('tr.newrow').find('#nimage').attr('class', '');
    $('.tooltip.fade.top.in').remove();
}
$(window).on('popstate', function (a) {
    //console.log(a);
    window.location = a.currentTarget.location.href;
    return;
});
$(window).bind('beforeunload', function (a, b) {
    /*console.log(document.activeElement);
    try {
        if (document.activeElement != undefined && $(document.activeElement)!=undefined&& $(document.activeElement).attr('href').indexOf('tel') > -1) {
            return;
        }
    }
    catch (error) {
        console.error(error);
        // Expected output: ReferenceError: nonExistentFunction is not defined
        // (Note: the exact output may be browser-dependent)
    }*/
    $('#MainContent').block();
    setTimeout(function () {
        $('#MainContent').unblock();
    }, 60 * 1000);
});

const wordsMap = {
    'A': 'А', 'B': 'Б', 'V': 'В', 'G': 'Г', 'D': 'Д', 'Đ': 'Ђ',
    'E': 'Е', 'Ž': 'Ж', 'Z': 'З', 'I': 'И', 'J': 'Ј', 'K': 'К',
    'L': 'Л', 'Lj': 'Љ', 'M': 'М', 'N': 'Н', 'Nj': 'Њ', 'O': 'О',
    'P': 'П', 'R': 'Р', 'S': 'С', 'T': 'Т', 'Ć': 'Ћ', 'U': 'У',
    'F': 'Ф', 'H': 'Х', 'C': 'Ц', 'Č': 'Ч', 'Dž': 'Џ', 'Š': 'Ш',
    'a': 'а', 'b': 'б', 'v': 'в', 'g': 'г', 'd': 'д', 'đ': 'ђ',
    'e': 'е', 'ž': 'ж', 'z': 'з', 'i': 'и', 'j': 'ј', 'k': 'к',
    'l': 'л', 'lj': 'љ', 'm': 'м', 'n': 'н', 'nj': 'њ', 'o': 'о',
    'p': 'п', 'r': 'р', 's': 'с', 't': 'т', 'ć': 'ћ', 'u': 'у',
    'f': 'ф', 'h': 'х', 'c': 'ц', 'č': 'ч', 'dž': 'џ', 'š': 'ш'
};

function convertText(input) {
    //let input = document.getElementById('latinText').value;
    let result = "";


    for (let i = 0; i < input.length; i++) {
        let twoChar = input[i] + (input[i + 1]);


        if (wordsMap[twoChar]) {
            result += wordsMap[twoChar];
            i++;
        } else {
            let char = input[i];
            if (wordsMap[char]) {
                result += wordsMap[char];
            } else {
                result += char;
            }
        }

        return result;
    }


}
function latinicaToCirilica(rijec) {

    let output = "";
    for (let i = 0; i < rijec.length; i++) {
        let char = rijec[i];


        let twoChar = rijec[i] + (rijec[i + 1]);

        // Slovo lj ili Lj
        if (twoChar === "lj") {
            output += 'љ';
            i++;
        }

        else if (twoChar === "Lj" || twoChar === "LJ") {
            output += 'Љ';
            i++;
        }


        // Slovo nj ili Nj
        else if (twoChar === "nj") {
            output += 'њ';
            i++;
        }

        else if (twoChar === "Nj" || twoChar === "NJ") {
            output += 'Њ';
            i++;
        }

        // Slovo dž ili Dž
        else if (twoChar === "dž") {
            output += 'џ';
            i++;
        }

        else if (twoChar === "Dž" || twoChar === "DŽ") {
            output += 'Џ';
            i++;
        }

        // Slovo a ili A
        else if (char === 'a') {
            output += 'а';
        } else if (char === 'A') {
            output += 'А';
        }

        // Slovo b ili B
        else if (char === 'b') {
            output += 'б';
        } else if (char === 'B') {
            output += 'Б';
        }

        // Slovo c ili C
        else if (char === 'c') {
            output += 'ц';
        } else if (char === 'C') {
            output += 'Ц';
        }

        // Slovo ć ili Ć
        else if (char === 'ć') {
            output += 'ћ';
        } else if (char === 'Ć') {
            output += 'Ћ';
        }

        // Slovo č ili Č
        else if (char === 'č') {
            output += 'ч';
        } else if (char === 'Č') {
            output += 'Ч';
        }

        // Slovo d ili D
        else if (char === 'd') {
            output += 'д';
        } else if (char === 'D') {
            output += 'Д';
        }

        // Slovo đ ili Đ
        else if (char === 'đ') {
            output += 'ђ';
        } else if (char === 'Đ') {
            output += 'Ђ';
        }

        // Slovo dž ili Dž
        else if (char === 'dž') {
            output += 'џ';
        } else if (char === 'Dž') {
            output += 'Џ';
        }

        // Slovo e ili E
        else if (char === 'e') {
            output += 'е';
        } else if (char === 'E') {
            output += 'Е';
        }

        // Slovo f ili F
        else if (char === 'f') {
            output += 'ф';
        } else if (char === 'F') {
            output += 'Ф';
        }

        // Slovo g ili G
        else if (char === 'g') {
            output += 'г';
        } else if (char === 'G') {
            output += 'Г';
        }

        // Slovo h ili H
        else if (char === 'h') {
            output += 'х';
        } else if (char === 'H') {
            output += 'Х';
        }

        // Slovo i ili I
        else if (char === 'i') {
            output += 'и';
        } else if (char === 'I') {
            output += 'И';
        }

        // Slovo j ili J
        else if (char === 'j') {
            output += 'ј';
        } else if (char === 'J') {
            output += 'Ј';
        }

        // Slovo l ili L
        else if (char === 'l') {
            output += 'л';
        } else if (char === 'L') {
            output += 'Л';
        }

        // Slovo m ili M
        else if (char === 'm') {
            output += 'м';
        } else if (char === 'M') {
            output += 'М';
        }

        // Slovo n ili N
        else if (char === 'n') {
            output += 'н';
        } else if (char === 'N') {
            output += 'Н';
        }

        // Slovo o ili O
        else if (char === 'o') {
            output += 'о';
        } else if (char === 'O') {
            output += 'О';
        }

        // Slovo p ili P
        else if (char === 'p') {
            output += 'п';
        } else if (char === 'P') {
            output += 'П';
        }

        // Slovo r ili R
        else if (char === 'r') {
            output += 'р';
        } else if (char === 'R') {
            output += 'Р';
        }

        // Slovo s ili S
        else if (char === 's') {
            output += 'с';
        } else if (char === 'S') {
            output += 'С';
        }

        // Slovo š ili Š
        else if (char === 'š') {
            output += 'ш';
        } else if (char === 'Š') {
            output += 'Ш';
        }

        // Slovo t ili T
        else if (char === 't') {
            output += 'т';
        } else if (char === 'T') {
            output += 'Т';
        }

        // Slovo u ili U
        else if (char === 'u') {
            output += 'у';
        } else if (char === 'U') {
            output += 'У';
        }

        // Slovo v ili V
        else if (char === 'v') {
            output += 'в';
        } else if (char === 'V') {
            output += 'В';
        }

        // Slovo z ili Z
        else if (char === 'z') {
            output += 'з';
        } else if (char === 'Z') {
            output += 'З';
        }

        // Slovo ž ili Ž
        else if (char === 'ž') {
            output += 'ж';
        } else if (char === 'Ž') {
            output += 'Ж';
        }


        else {
            output += char;
        }
    }
    return output;
}
/// <reference path="~/Content/Danijel/DanijelLibrary.js" />
/// <reference path="~/Content/Danijel/BPM_Tracking.js" />
var bcDokumenti = new BroadcastChannel('refreshDMS_Dokumenti');
bcDokumenti.onmessage = function (ev) {
    console.log(ev.data);
    if (ev.data == "refreshDMS_Dokumenti") {
        if (tDMS_Dokumenti != null && tDMS_Dokumenti != undefined) {
            tDMS_Dokumenti.SetData();
        }
       
    }
} /* receive */
// bcDokumenti.postMessage('refreshDMS_Dokumenti');
let vcolumnModelDokumenti = [
    { name: 'extension', title: '', datatype: 'html', width: '40px', html: '' },
    { name: '', title: '', datatype: 'html', width: '60px', html: '<button class="Dokument PreuzmiDokument btn controls" onclick="PreuzmiDokument(this)"> <span class="fas fa-download"></span>Preuzmi</button>' },
    { name: '', title: '', datatype: 'html', width: '60px', html: '<button class="Dokument PregledDokument btn controls" onclick="PregledDokument(this)"> <span class="fas fa-print"></span>Pregled</button>' },
    { name: '', title: '', datatype: 'html', width: '60px', html: '<button class="Dokument IzmjeniDokument btn controls" onclick="IzmjeniDokument(this)"> <span class="fas fa-edit"></span>Izmjene</button>' },
    { name: '', title: '', datatype: 'html', width: '60px', html: '<button class="Dokument ObrisiDokument btn controls" onclick="ObrisiDokument(this)"> <span class="fas fa-trash"></span>Obriši</button>' },
    { name: '', title: '', datatype: 'html', width: '60px', html: '<button class="Dokument MetaPodaci btn controls" onclick="MetaPodaci(this)"> <span class="fas fa-edit"></span>Meta</button>' },
    { name: 'ID', title: 'ID', readonly: true, datatype: 'text', width: '100px' },
    { name: 'BrojPredmeta', title: 'Broj dokumenta', datatype: 'text', width: '150px' },
    { name: 'RedniBroj', title: 'RedniBroj', datatype: 'text', width: '70px' },
    { name: 'BrojDokumenta', title: 'Broj dokumenta', datatype: 'text', width: '170px' },
    { name: 'DatumDokumenta', title: 'Datum', datatype: 'dateedit', width: '100px' },
    { name: 'VrstaDokumentaNaziv', title: 'Vrsta dokumenta', datatype: 'text', width: '220px' },
    { name: 'OriginalniNaziv', title: 'Originalni naziv', datatype: 'text', width: '320px'},
    { name: 'Opis', title: 'Opis', datatype: 'text', width: '100%' },
    { name: 'Verzija', title: 'Verzija', datatype: 'text', width: '60px' },
    { name: 'FTPNaziv', title: 'FTPNaziv', datatype: 'text', width: '300px' },
    { name: 'ZadnjaVerzija', title: 'ZadnjaVerzija', datatype: 'text', width: '40px' },
    { name: 'StatusID', title: 'StatusID', datatype: 'text', width: '150px' },
    { name: 'StatusNaziv', title: 'Status', datatype: 'text', width: '150px' },
    { name: 'PrimalacID', title: 'PrimalacID', datatype: 'text', width: '150px' },
    { name: 'PrimalacOdjelID', title: 'PrimalacOdjelID', datatype: 'text', width: '150px' },
    { name: 'DatumStatusa', title: 'DatumStatusa', datatype: 'dateedit', width: '150px' },
    { name: 'OriginalID', title: 'OriginalID', datatype: 'text', width: '150px' },
    { name: 'ParentProcess', title: 'ParentProcess', datatype: 'text', width: '100px' },
    { name: 'ParentProcessID', title: 'ParentProcessID', datatype: 'text', width: '100px' },
    { name: 'Adresibilan', title: 'Adresibilan', datatype: 'text', width: '100px' },
    { name: 'IdeNaOdobrenje', title: 'IdeNaOdobrenje', datatype: 'text', width: '100px' },
    { name: 'Protokolisan', title: 'Protokolisan', datatype: 'text', width: '100px' },
];
let vtableOptionsDokumenti = {
    version: 2,
    dataurl: '',
    saveurl: '',
    columnModel: vcolumnModelDokumenti,
    rowsPerPage: 100,
    editable: false,
    showfooter: true,
    sortorder: 'desc',
    PKColumn: 'ID',
    sortfield: 'ID',
    PagerVisible: false,
    showFilterRow: true,
    tableCssClass: "Dokumenti",
    addValuesToRow: 1,
    onFocusChange: function (ptr) {
        trFocusedDokument = ptr;
        $("#btnDMS_Tracking,#btnDMSAkcije,#btnDMSAkteri,#btnDMSPrilozi").removeAttr("disabled");
        $('#DatumDokumenta').val($(trFocusedDokument).find('td.DatumDokumenta').attr('value'));
        $('#BrojDokumenta').val($(trFocusedDokument).attr('BrojPredmeta'));
        $('#OpisDokumenta').val($(trFocusedDokument).attr('Opis')); 
        setDMSAkcije();
    },
    onDblClick: function (ptr) {


    },
    afterSetData: function () {
         $('#tDMS_Dokumenti').children('tbody').children('tr:first').trigger('click');
        $('.zebra').Zebra_DatePicker({
            format: 'd.m.Y',
            readonly_element: false
        });
        $('.zebra').mask('00.00.0000', { placeholder: "__.__.____" });
        PrikaziStareVerzije();
        setDMSAkcije();
    }
};
let tDMS_Dokumenti = null;
let DocumentID = null;
let trFocusedDokument = null;
let ProcesID = null;
let InstancaID = null;
let DokumentAdresibilan = false;//ako je adresibilan kod kreiranja dokumenta biti će obavezno odabiranje primaoca
let DMSotpremaDokumenta = null;
let UploadDokumenta = false;
SetDMSEvents();
function SetDMSEvents(){
    $('#btnDokumentiVrstaSnimi').click(function () {
        let VrstaDokumentaID = $('#cmbVrstaDokumenta').val();
        if (VrstaDokumentaID == '') {
            swal({ title: "Poruka", text: "Vrsta dokumenta je obavezan podatak", dangerMode: true, icon: "error" });
            return;
        }
        $('.progress-bar').css('width', '0%');
        let files = $("#fileUpload").get(0).files;
        if (files.length > 0) {
            ShowUploadProgress();
            if (window.FormData !== undefined) {
                let data = new FormData();
                data.append("file" + 0, files[0]);
                for (i = 0; i < files.length; i++) {
                    data.append("file" + i, files[i]);
                }
                let fileName = files[0].name;
                let OpisDokumenta = $('#OpisDokumenta').val();
                let metaJSON = getMetaPodaci();
                let BrojDokumenta = $('#BrojDokumenta').val();
                let DatumDokumenta = $('#DatumDokumenta').val();
                $('#btnDokumentiVrstaSnimi').block({ message: '<p> Učitavanje...</p>' });
                $.ajax({
                    xhr: function () {
                        let xhr = new window.XMLHttpRequest();
                        xhr.upload.addEventListener("progress", function (evt) {
                            if (evt.lengthComputable) {
                                let percentComplete = evt.loaded / evt.total;
                                percentComplete = parseInt(percentComplete * 100);
                                $('.progress-bar').css('width', percentComplete + '%');
                                $('.progress-bar').text(percentComplete);
                            }
                        }, false);

                        return xhr;
                    },
                    type: "POST",
                    url: `/api/DMSFileUpload?ProcesID=${ProcesID}&InstancaID=${InstancaID}&OrginalniNaziv=${fileName}&VrstaDokumentaID=${VrstaDokumentaID}&Opis=${OpisDokumenta}&metaJSON=${metaJSON}&BrojDokumenta=${BrojDokumenta}&DatumDokumenta=${DatumDokumenta}`,
                    contentType: false,
                    processData: false,
                    data: data,
                    success: function (results) {
                        //alert("uploadovan");
                        $('#btnDokumentiVrstaSnimi').unblock();
                        ShowUploadControls();
                        if (tDMS_Dokumenti != null) {
                            tDMS_Dokumenti.SetData();
                        }
                        if (afterUploadDocument != null && afterUploadDocument != undefined) {
                            afterUploadDocument();
                        }
                        $('#ModalDialogDokumentiVrsta').modal('hide');
                        $("input.filestyle").val(null);

                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        $('#btnDokumentiVrstaSnimi').unblock();
                        ShowUploadControls();
                        alert(xhr.responseText);
                        console.log(xhr.responseText);
                    }
                });
            } else {
                alert("Your browser doesn't support HTML5 multiple file uploads! Please use some decent browser.");
            }
        }//*/
    });
    $('#PrikaziStareVerzije').click(function () {
        PrikaziStareVerzije();
    });
    $('#btnDMS_OtpremaDokumenta').click(function () {
        DMS_OtpremaDokumenta();
    });
    $('#cmbVrstaDokumenta').on('change', function () {
        PromjenaVrsteDokumenta();
    });
    $('#btnDokumentiVrstaSnimiMeta').click(function () {
        let ID = $(trFocusedDokument).find('td.ID').attr('value');
        let DatumDokumenta = $('#DatumDokumenta').val();
        let BrojDokumenta = $('#BrojDokumenta').val();
        let Opis = $('#OpisDokumenta').val();
        $.ajax({
            type: "POST",
            url: `/DMS_Dokumenti/UpdateMetaData?pDocumentID=${ID}&metaJSON=${getMetaPodaci()}&DatumDokumenta=${DatumDokumenta}&BrojDokumenta=${BrojDokumenta}&Opis=${Opis}`,
            contentType: false,
            processData: false,
            success: function (results) {
                $('#ModalDialogDokumentiVrsta').modal('hide');
                DocumentID = null;
                tDMS_Dokumenti.SetData();
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.responseText);
                console.log(xhr.responseText);
            }
        });
    });
    $("#btnOdustaniDokumenti").click(function () {
        if (afterPrikaziDokument != undefined) {
            afterPrikaziDokument();
        }
        $('#ModalDialogDokumenti').modal('hide');
    });
    $("#btnOdustaniDokumentiVrsta").click(function () {
        $("input.filestyle").val(null);
        $('#ModalDialogDokumentiVrsta').modal('hide');
    });
    $("#btnKreirajDokument").click(function () {
        $(".SpinTable").removeClass("focused");
        UploadDokumenta = false;
        $('#BrojDokumenta').attr("disabled", "disabled");
        DMS_KreirajDokument(ProcesID);
    });
    $("#btnDMS_Tracking").click(function () {
        let DocumentID = $(trFocusedDokument).find('td.ID').attr('value');
        PrikaziTracking(8, DocumentID);
    });
    $("#btnDMSAkteri").click(function () {
        let DocumentID = $(trFocusedDokument).find('td.ID').attr('value');
        PrikaziBPM_Akteri(8, DocumentID);
    });
    $('#btnAkteriShortcut').click(function () {
        $('#btnAkteri').trigger("click");
    });
    $("#btnDMSPrilozi").click(function () {
        let md = $(`<div id="mdPrilozi" class="modal" data-backdrop="static">`);
        $("#mdPrilozi").remove();
        let modal_dialog = $(`<div class="modal-dialog modal-lg" style="width:90%;max-width:1200px">`);
        let modal_content = $(`<div class="modal-content">`);
        let modal_header = $(`<div class="modal-header">
                <span class="iconPrilozi" style="opacity:1"></span><h6 class="modal-title">Prilozi</h6>
            </div>`);
        let modal_body = $(`
<div class="modal-body" style="padding:10px;padding-top:0px">
</div>
`);
        let container = $(`
    <div class="container" style="max-height: 500px;overflow: auto;"></div>
`);
        let modal_headerFooter = $(`
<div class="modal-header">
    <div class="row">
        <button id="btnOdustanimdPrilozi" class="btn controls" onclick="$('#mdPrilozi').modal('hide');$('.modal-backdrop.in').remove();" style="float: right; margin: 0px 5px 0px 5px;"><span class="iconOdustani"></span>Zatvori</button>
        <button id="btnCopymdPrilozi" class="btn controls" onclick="KopirajTekstPriloga()" style="float: right; margin: 0px 5px 0px 5px;"><span class="iconCopy"></span>Kopiraj prilog</button>
        <button id="btnDMSPregledDokumentSPrilozima" class="btn controls" title="Prilozi vezani za dokument" style="float: right; margin: 0px 5px 0px 5px;width:190px"><span class="iconPrint"></span> Pregled s prilozima</button>
    </div>
</div>`);
        $(md).append(modal_dialog);
        $(modal_dialog).append(modal_content);
        $(modal_content).append(modal_header);
        $(modal_content).append(modal_body);
        $(modal_content).append(modal_headerFooter);
        $(modal_body).append(container);
        $(document.body).append(md);
        let DocumentID = $(trFocusedDokument).attr("id");
        $.ajax({
            url: `/DMS_Dokumenti/GetPrilozi?ProcesID=${ProcesID}&InstancaID=${InstancaID}&DocumentID=${DocumentID}`,
            dataType: 'json',
            data: {},
            success: function (data) {
                if (data == '') {
                    return;
                }
                $.each(JSON.parse(data), function (i, item) {//loop columns
                    let NazivHTML = item["VrstaDokumentaNazivHTML"];
                    let Naziv = item["VrstaDokumentaNaziv"];
                    let ID = item["ID"];
                    let row = $('<div class="row Prilozi"></div>');
                    let label = `<div class="col-md-11">${NazivHTML}</div>`;
                    let col = $(`<div class="col-md-1"></div>`);
                    let Zakacen = item["Zakacen"];
                    let input = null;
                    let hr = $(`<hr>`);
                    input = $(`<input id="SifraDokumenta${ID}" DocumentID=${ID} Naziv="${Naziv}" MasterDocumentID=${DocumentID} type="checkbox" class="form-control DMSprilozi" ${Zakacen == 1 ? "checked" : ""}>`);
                    $(input).click(function () {
                        SnimiPrilog(this);
                    });
                    $(col).append(input);
                    $(row).append($(label));
                    $(row).append($(col));
                    $(container).append(row);
                    $(container).append(hr);
                });
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(thrownError);
            }
        });
        $("#btnDMSPregledDokumentSPrilozima").click(function () {
            let ID = $(trFocusedDokument).find('td.ID').attr('value');
            if (ID != undefined) {
                window.open('/DMS_Dokumenti/PregledDokumentSPrilozima?pDocumentID=' + ID, '_blank').focus();
            }
        });
        $("#mdPrilozi").modal('show');
    });
}
function PrikaziDokumente(procesID, instancaID, pDMSotpremaDokumenta = null) {
    afterUploadDocument = null;
    defaultVrstaDokumentaID = null;
    $('.uploadFileForm,#btnKreirajDokument,#btnDMSAkteri,#btnDMSPrilozi').show();
    $("#btnDMS_Tracking,#btnDMSAkcije,#btnDMSAkteri,#btnDMSPrilozi").attr("disabled", "disabled");
    ProcesID = procesID;
    InstancaID = instancaID;
    DMSotpremaDokumenta = pDMSotpremaDokumenta;
    tDMS_Dokumenti = null;//da se uvijek rekreira
    if (tDMS_Dokumenti == null) {
        $('#tDMS_Dokumenti').empty();
        //$('#tDMS_DokumentiContainer').find('.SpinTable.headertable').remove();
        vtableOptionsDokumenti.dataurl = `/DMS_Dokumenti/GetData?ProcesID=${procesID}&InstancaID=${InstancaID}`;
        tDMS_Dokumenti = $('#tDMS_Dokumenti').danijeltable({ tableOptions: vtableOptionsDokumenti });
    } else {
        tDMS_Dokumenti.voptions.tableOptions.dataurl = `/DMS_Dokumenti/GetData?ProcesID=${procesID}&InstancaID=${InstancaID}`;
        tDMS_Dokumenti.SetData();
    }
    //$('#ModalDialogDokumenti').modal('show');
    $('.modal-body.Dokumenti').hide();
    $('#ModalDialogDokumenti').modal('show');
    //$('.modal-body.Dokumenti').slideDown('fast');
    $('.modal-body.Dokumenti').fadeIn('slow');
    //$('.modal-body.Dokumenti').slideDown();
}
let afterPrikaziDokument = null;
let afterUploadDocument = null;
let defaultVrstaDokumentaID = null;
function PrikaziDokument(procesID, pDocumentID, pafterPrikaziDokument = null) {

    $('.uploadFileForm,#btnKreirajDokument,#btnDMSAkteri').hide();
    ProcesID = procesID;
    DocumentID = pDocumentID;
    afterPrikaziDokument = pafterPrikaziDokument;
    if (tDMS_Dokumenti == null) {
        $('#tDMS_Dokumenti').empty();
        $('#tDMS_DokumentiContainer').find('.SpinTable.headertable').remove();
        vtableOptionsDokumenti.dataurl = `/DMS_Dokumenti/GetData?DocumentID=${DocumentID}`;
        tDMS_Dokumenti = $('#tDMS_Dokumenti').danijeltable({ tableOptions: vtableOptionsDokumenti });
    } else {
        vtableOptionsDokumenti.dataurl = `/DMS_Dokumenti/GetData?DocumentID=${DocumentID}`;
        tDMS_Dokumenti.SetData();
    }
    if (!$('#PrikaziStareVerzije').is(':checked')) {
        $("#PrikaziStareVerzije").trigger("click");
    }
   
    $('#ModalDialogDokumenti').modal('show');
}
function ShowUploadControls() {
    $("#uploadControls").show();
    $("#uploadProgress").hide();
}
function ShowUploadProgress() {
    $("#uploadControls").hide();
    $("#uploadProgress").show();
}
function OnUpload() {
    UploadDokumenta = true;
    $('#DatumDokumenta').val(GetCurrentDate());
    $('#BrojDokumenta').val('');
    $('#BrojDokumenta').removeAttr("disabled");
    if (defaultVrstaDokumentaID == null) {
        Cmb('#cmbVrstaDokumenta', '/json/getDMS_Vrste_Dokumenata?ProcesID=' + ProcesID);
    } else {
        Cmb('#cmbVrstaDokumenta', `/json/getDMS_Vrste_Dokumenata?ImaSablon=0&ProcesID=${ProcesID}`, function () {
            if (defaultVrstaDokumentaID != undefined) {
                $('#cmbVrstaDokumenta').val(defaultVrstaDokumentaID);
                $('#OpisDokumenta').val($('#cmbVrstaDokumenta option:selected').text());

            } else {
                $('#cmbVrstaDokumenta').val('');
                $('#cmbSablon').attr("disabled", "");
                $('#OpisDokumenta').val('');
            }
            PromjenaVrsteDokumenta();
            $('#cmbVrstaDokumenta').selectpicker("refresh");
        });    
    }
    $('#cmbVrstaDokumenta').val('');
    $('#cmbVrstaDokumenta').selectpicker("refresh");
    $('#OpisDokumenta').val('');
    $('#btnDokumentiVrstaSnimiMeta,#btnGenerisiDokument,.row.Sablon,.row.Akter').hide();
    $('#btnDokumentiVrstaSnimi,.row.VrstaDokumenta, .row.OpisDokumenta').show();
    $('#MetaPodaci').empty();
    $('#ModalDialogDokumentiVrsta').modal('show');

}

function PreuzmiDokument(element) {
    let ID = $(element).attr("id");
    window.open('/DMS_Dokumenti/PreuzmiDokument?pDocumentID=' + ID, '_blank').focus();
}
function PregledDokument(element) {
    let ID = $(element).attr("id");
    if (ID != undefined) {
        window.open('/DMS_Dokumenti/PregledDokument?pDocumentID=' + ID, '_blank').focus();
    }
}
function IzmjeniDokument(element) {
    let ID = $(element).attr("id");
    if (ID != undefined) {
        window.open('/DMS_Dokumenti/IzmjeniDokument?pDocumentID=' + ID, '_blank').focus();
    }
}
function ObrisiDokument(element) {
    swal({
        title: "Dali ste sigurni?",
        text: "Brisanje!",
        icon: "warning",
        buttons: ["NE", "DA"],
        dangerMode: true,
    }).then(function (result) {
        if (result) {
            let ID = $(element).attr("id");
            $.ajax({
                type: "POST",
                url: "/DMS_Dokumenti/BrisanjeDokument?pDocumentID=" + ID,
                contentType: false,
                processData: false,
                success: function (results) {
                    if (results == "ok") {
                        tDMS_Dokumenti.SetData();
                    } else {
                        swal({ title: "Poruka", text: results.Message, dangerMode: true, icon: "error" });
                    }

                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert(xhr.responseText);
                }
            });
        }
    });

}
function DMS_OtpremaDokumenta() {
    //let ID = $(element).attr("documentid");
    if (DMSotpremaDokumenta == null) {
        //swal({ title: "Poruka", text: "Otprema dokumenta nije definisana za odabrani proces", dangerMode: true, icon: "error" });
    } else {
        DMSotpremaDokumenta();
    }
}
//odabir vrste dokumenta

function PromjenaVrsteDokumenta() {
    let VrstaDokumentaID = $('#cmbVrstaDokumenta').val();
    if (VrstaDokumentaID == '' || VrstaDokumentaID == null || VrstaDokumentaID == undefined) {
        $('#cmbSablon').attr("disabled", "disabled");
        return;
    }
    setMetaInput(VrstaDokumentaID);
    $('#cmbSablon').removeAttr("disabled");
    Cmb('#cmbSablon', `/json/getDMS_Sabloni?ProcesID=${ProcesID}&VrstaDokumentaID=${VrstaDokumentaID}`, function () {
        if ($("#cmbSablon")[0].options.length == 2)//1 je onaj nevidljivi tj 2 je kad ima jednu opciju
        {
            $("#cmbSablon").val($("#cmbSablon")[0].options[1].value);
            //$("#cmbSablon")
        }
    });
    $('#ModalDialogDokumentiVrsta>.modal-dialog').block();
    $.ajax({
        url: `/json/getDokumentAdresabilan?VrstaDokumentaID=${VrstaDokumentaID}`,
        dataType: 'text',
        success: function (data) {
            if (data === "True") {
                DokumentAdresibilan = true;
                $('.row.Akter').show();
                CmbAkteri('#cmbAkter', `/json/getAkteri?ProcesID=${ProcesID}&InstancaID=${InstancaID}`);
            } else {
                DokumentAdresibilan = false;
                $('.row.Akter').hide();
            }
            $('#ModalDialogDokumentiVrsta>.modal-dialog').unblock();
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(thrownError);
        }
    });
    DefaultOpisDokumenta();
}
//prikaz meta podataka sa vrjednostima za dokument
function MetaPodaci(element) {
    let DocumentID = $(element).attr("id");
    //alert(DocumentID);
    $('#btnDokumentiVrstaSnimi,#btnGenerisiDokument,.row.VrstaDokumenta, .row.Sablon, .row.Akter').hide();
    $('#btnDokumentiVrstaSnimiMeta, .row.OpisDokumenta').show();
    $('#BrojDokumenta').removeAttr("disabled");
    $('#BrojDokumenta').val(tDMS_Dokumenti.GetFocusedValue('BrojDokumenta'));
    $('#DatumDokumenta').val(tDMS_Dokumenti.GetFocusedValue('DatumDokumenta'));
    $('#OpisDokumenta').val(tDMS_Dokumenti.GetFocusedValue('Opis'));
    setMetaInputForDocument(DocumentID);
   
    $('#ModalDialogDokumentiVrsta').modal('show');
}
//kreiranje input boxova za postojeći dokument sa unešenim vrijednostima 
function setMetaInputForDocument(DocumentID) {
    $('#MetaPodaci').empty();
    let ID = $(trFocusedDokument).find('td.ID').attr('value');
    $.ajax({
        url: '/json/getDMS_Meta_Vrijednosti?DocumentID=' + ID,
        dataType: 'json',
        data: {},
        success: function (data) {
            // alert(data);
            $.each(JSON.parse(data), function (i, item) {//loop columns
                let row = $('<div class="row"></div>');
                let colInput = $('<div class="col-md-9">');
                let label = '<div class="col-md-3">' + item["Naziv"] + '</div>';
                let vinput = $('<input>');
                if (item["TipPodatka"] == 'txt') {
                    vinput = $('<input type="text" id="MetaPodatak' + item["MetaPodatakID"] + '" IdMetaPodatka=' + item["MetaPodatakID"] + ' class="form-control">');
                }
                else if (item["TipPodatka"] == 'date') {
                    vinput = $('<input id="MetaPodatak' + item["MetaPodatakID"] + '" IdMetaPodatka=' + item["MetaPodatakID"] + ' class="form-control zebra">');
                }
                else if (item["TipPodatka"] == 'number') {
                    vinput = $('<input id="MetaPodatak' + item["ID"] + '" IdMetaPodatka=' + item["ID"] + ' class="form-control number">');
                }
                $(vinput).val(item["Vrijednost"]);
                $(colInput).append($(vinput));
                //alert($(input).val());
                console.log(item["Vrijednost"]);
                $(row).append($(label));
                $(row).append($(colInput));
                $('#MetaPodaci').append($(row));

            });
            $('.zebra').Zebra_DatePicker({
                format: 'd.m.Y',
                readonly_element: false
            });
            $(".number").numeric({ decimalPlaces: 2, negative: false, decimal: "," });
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(thrownError);
        }
    });
}
//kreiranje input boxova za novi dokument na osnovu vrste dokumenta
function setMetaInput(VrstaDokumenta) {
    $('#MetaPodaci').empty();
    $.ajax({
        url: '/json/getDMS_Vrste_Dokumenata_Meta?VrstaDokumentaID=' + VrstaDokumenta,
        dataType: 'json',
        data: {},
        success: function (data) {
            if (data == '') {
                return;
            }
            $.each(JSON.parse(data), function (i, item) {//loop columns
                let row = $('<div class="row"></div>');
                let label = '<div class="col-md-3">' + item["Naziv"] + '</div>';
                let input = null;
                if (item["TipPodatka"] == 'txt') {
                    input = $('<div class="col-md-9"><input type="text" id="MetaPodatak' + item["ID"] + '" IdMetaPodatka=' + item["ID"] + ' class="form-control"></div>');
                }
                else if (item["TipPodatka"] == 'date') {
                    input = $('<div class="col-md-9"><input id="MetaPodatak' + item["ID"] + '" IdMetaPodatka=' + item["ID"] + ' class="form-control zebra"></div>');
                }
                else if (item["TipPodatka"] == 'number') {
                    input = $('<div class="col-md-9"><input id="MetaPodatak' + item["ID"] + '" IdMetaPodatka=' + item["ID"] + ' class="form-control number"></div>');
                }
                $(row).append($(label));
                $(row).append($(input));
                $('#MetaPodaci').append(row);
            });
            $('.zebra').Zebra_DatePicker({
                format: 'd.m.Y',
                readonly_element: false
            });
            $(".number").numeric({ decimalPlaces: 2, negative: false, decimal: "," });
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(thrownError);
        }
    });
}
function getMetaPodaci() {
    let metaJSON = '[';
    $("#MetaPodaci input").each(function (i, input) {
        // console.log(input);
        if (i != 0) {
            metaJSON = metaJSON + ",";
        }
        metaJSON = metaJSON + '{"id":"' + $(input).attr('idmetapodatka') + '","vrijednost":"' + $(input).val() + '"}';

    });
    metaJSON = metaJSON + ']';
    return metaJSON;
}

function DMS_KreirajDokument(pProcesID, pInstancaID,defaultVrstaDokumentaID,afterCreateDocument) {
    if (pProcesID != undefined) {
        ProcesID = pProcesID;
    }
    if (pInstancaID != undefined) {
        InstancaID = pInstancaID;
    }
    const documentTypeResponse = Cmb('#cmbVrstaDokumenta', `/json/getDMS_Vrste_Dokumenata?ImaSablon=1&ProcesID=${pProcesID}`, function () {
        if (defaultVrstaDokumentaID != undefined) {
            $('#cmbVrstaDokumenta').val(defaultVrstaDokumentaID);
            $('#OpisDokumenta').val($('#cmbVrstaDokumenta option:selected').text()); 
            
        } else {
            $('#cmbVrstaDokumenta').val('');
            $('#cmbSablon').attr("disabled", "");
            $('#OpisDokumenta').val('');
        }
        PromjenaVrsteDokumenta();
        $('#cmbVrstaDokumenta').selectpicker("refresh");
    });   

    //Check if there are document types that are connected to this process
    documentTypeResponse.then((value) => {
        const documentTypeCount = JSON.parse(value).length;
        console.log(documentTypeCount);
        if (documentTypeCount === 0)
        {
            swal({ title: "Poruka", text: "Za ovaj proces nisu ugrađeni šabloni za kreiranja dokumenata, za više informacija obratite se administratoru.", dangerMode: false, icon: "warning" });
        }
    });


    $('#btnDokumentiVrstaSnimiMeta, #btnDokumentiVrstaSnimi,.row.Akter').hide();
    $('#btnGenerisiDokument,.row.VrstaDokumenta, .row.OpisDokumenta').show();
    $('#cmbSablon').val('');
    $('#cmbSablon').selectpicker('refresh');
    $('#BrojDokumenta').val('');
    $('#DatumDokumenta').val(GetCurrentDate());
    $('#MetaPodaci').empty();
    $('.row.Sablon').show();

    $('#ModalDialogDokumentiVrsta').modal('show');
    $('#btnGenerisiDokument').unbind('click');
    $("#btnGenerisiDokument").click(function () {
        GenerisiDokument(ProcesID, InstancaID, afterCreateDocument);
    });
}
function DefaultOpisDokumenta() {
    $.ajax({
        url: `/DMS_Dokumenti/GetDefaultOpisDokumenta?ProcesID=${ProcesID}&InstancaID=${InstancaID}`,
        dataType: 'json',
        data: {},
        success: function (data) {
            data = JSON.stringify(data);
            data = JSON.parse(data);
            if (!UploadDokumenta) {
                $('#BrojDokumenta').val(data.BrojPredmeta);
                $('#OpisDokumenta').val($('#cmbVrstaDokumenta option:selected').text() + ' ' + data.OpisDokumenta);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(thrownError);
        }
    });
}
function PrikaziStareVerzije() {
    if ($('#PrikaziStareVerzije').is(':checked')) {
        $('tr[zadnjaverzija="0"]').show();
    } else {
        $('tr[zadnjaverzija="0"]').hide();
    }
   
}
function GenerisiDokument(pProcesID, pInstancaID, afterCreateDocument) {
    let ValidacionaPoruka = "";
    if ($('#cmbVrstaDokumenta').val() == '') {
        ValidacionaPoruka = ValidacionaPoruka + "Vrsta dokumenta je obavezan podatak\n";
        $("#cmbVrstaDokumenta").addClass("invalid");
    }
    if ($('#cmbSablon').val() == '') {
        ValidacionaPoruka = ValidacionaPoruka + "Šablon je obavezan podatak\n";
        $("#cmbSablon").addClass("invalid");
    }
    if (DokumentAdresibilan && $('#cmbAkter').val() == '') {
        ValidacionaPoruka = ValidacionaPoruka + "Akter je obavezan podatak\n";
        $("#cmbAkter").addClass("invalid");
    }
    if (ValidacionaPoruka != "") {
        swal({ title: "Validacija unosa", text: ValidacionaPoruka, html: true, dangerMode: true, icon: "error" });
        return;
    }
    let VrstaDokumentaID = $('#cmbVrstaDokumenta').val();
    let SablonID = $('#cmbSablon').val();
    let OpisDokumenta = $('#OpisDokumenta').val();
    let metaJSON = getMetaPodaci();
    let AkterID = $('#cmbAkter').val();
    let Interno = $('#cmbAkter option:selected').attr('interno');
    let DatumDokumenta = $('#DatumDokumenta').val();
    let DocumentIDFocus = $(trFocusedDokument).find('td.ID').attr('value');
    if (DocumentIDFocus == null || DocumentIDFocus == undefined) {
        DocumentIDFocus = 0;
    }
    $('#ModalDialogDokumentiVrsta>.modal-dialog').block();
    $.ajax({
        url: `/DMS_Dokumenti/GenerisiDokument?ProcesID=${pProcesID}&InstancaID=${pInstancaID}&VrstaDokumentaID=${VrstaDokumentaID}&SablonID=${SablonID}&Opis=${OpisDokumenta}&AkterID=${AkterID}&metaJSON=${metaJSON}&Interno=${Interno}&DatumDokumenta=${DatumDokumenta}&DocumentIDFocus=${DocumentIDFocus}`,
        dataType: 'text',
        //data: [{ gridparams: JSON.stringify(vdata),other: JSON.stringify(plugin.CustomParameters) }],
        success: function (data) {
            //alert(data);
            if (data === "ok") {
                if (tDMS_Dokumenti != null) {
                    tDMS_Dokumenti.SetData();
                }
                $('#ModalDialogDokumentiVrsta').modal('hide');
                if (afterCreateDocument != undefined) {
                    afterCreateDocument();
                }
            } else {
                swal({ title: "Poruka", text: data, dangerMode: true, icon: "error" });
            }
            $('#ModalDialogDokumentiVrsta>.modal-dialog').unblock();
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(thrownError);
            $('#ModalDialogDokumentiVrsta>.modal-dialog').unblock();
        }
    });
}
function GenerisiDokumentSaParametrima(pProcesID, pInstancaID, VrstaDokumentaID, SablonID, OpisDokumenta, AkterID,Interno, afterCreateDocument) {
    
    let metaJSON = '[]';
    $.ajax({
        url: `/DMS_Dokumenti/GenerisiDokument?ProcesID=${pProcesID}&InstancaID=${pInstancaID}&VrstaDokumentaID=${VrstaDokumentaID}&SablonID=${SablonID}&Opis=${OpisDokumenta}&AkterID=${AkterID}&metaJSON=${metaJSON}&Interno=${Interno}`,
        dataType: 'text',
        //data: [{ gridparams: JSON.stringify(vdata),other: JSON.stringify(plugin.CustomParameters) }],
        success: function (data) {
            //alert(data);
            if (data === "ok") {
                if (afterCreateDocument != undefined) {
                    afterCreateDocument();
                }
            } else {
                swal({ title: "Poruka", text: data, dangerMode: true, icon: "error" });
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(thrownError);
        }
    });
}

function setDMSAkcije() {
    if (tDMS_Dokumenti == null || tDMS_Dokumenti == undefined) {
        return;
    }
    let StatusID = tDMS_Dokumenti.GetFocusedValue('StatusID');//$(trFocusedDokument).find('td.StatusID').attr('value');
    let PrimalacID = tDMS_Dokumenti.GetFocusedValue("PrimalacID");
    if (StatusID == undefined || StatusID == '') {
        StatusID = 1;
    }
    let ZadnjaVerzija = tDMS_Dokumenti.GetFocusedValue("ZadnjaVerzija");//$(trFocusedDokument).find('td.ZadnjaVerzija').attr('value');
    if (ZadnjaVerzija == 0) {
        $("#dropDownMenuDMSAkcije").empty();
        return;
    }
    let ID = tDMS_Dokumenti.GetFocusedValue("ID");//$(trFocusedDokument).find('td.ID').attr('value');
    if (ID == null || ID == undefined) {
        ID = -1;
    }
    $.ajax({
        url: `/json/getAkcije?ProcesID=${8}&StatusID=${StatusID}&InstancaID=${ID}`,
        dataType: 'json',
        data: {},
        success: function (data) {
            $("#dropDownMenuDMSAkcije").empty();
            // alert(data);
            $.each(JSON.parse(data), function (i, item) {//loop columns
                let li = $('<li></li>');
                let Naziv = item["Naziv"];
                let Klasa = Naziv.replace(/ /g, '');
                let VrstaDokumentaID ="";// item["VrstaDokumentaID"];
                let Code = item["Code"];
                /*if (PrimalacID == '' && Code == "POSALJI_NA_ODOBRENJE") {//staro
                    return;
                }*/
                let Adresibilan=tDMS_Dokumenti.GetFocusedValue('Adresibilan');
                let IdeNaOdobrenje = tDMS_Dokumenti.GetFocusedValue('IdeNaOdobrenje');
                if (Adresibilan == 'false' && Code == "ODOBRI_ZA_SLANJE") {
                    return;
                }
                if (Adresibilan == 'true' && Code == "DMS_ODOBRI") {
                    return;
                }
                let a = $(`<a href="#" code=${Code} VrstaDokumentaID=${VrstaDokumentaID}><span class="icon${Klasa} ${Code}" ></span>${Naziv}</a>`);
                $(li).append($(a));
                $('#dropDownMenuDMSAkcije').append(li);
                if (Code == "POSALJI_NA_ODOBRENJE") {
                    $(a).click(function () {
                        POSALJI_NA_ODOBRENJE();
                    });
                }
                else if (Code == "ODOBRI_ZA_SLANJE") {
                    $(a).click(function () {
                        ODOBRI_ZA_SLANJE();
                    });
                }
                else if (Code == "DMS_ODOBRI") {
                    $(a).click(function () {
                        DMS_ODOBRI();
                    });
                }
                else if (Code == "VRATI_NA_ISPRAVKU") {
                    $(a).click(function () {
                        VRATI_NA_ISPRAVKU();
                    });
                }
                else if (Code == "POSALJI_NA_OTPREMU") {
                    $(a).click(function () {
                        POSALJI_NA_OTPREMU();
                    });
                }
                else if (Code == "DMS_PROTOKOLISI") {
                    $(a).click(function () {
                        DMS_PROTOKOLISI();
                    });
                }
            });
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(thrownError);
        }
    });
}
function SnimiPrilog(elem) {
    console.log(elem);
    let DocumentID = $(elem).attr("documentid");
    let MasterDocumentID = $(elem).attr("MasterDocumentID");
    let Checked = $(elem).is(':checked');
    $.ajax({
        type: "POST",
        url: `/DMS_Dokumenti/SnimiPrilog?ProcesID=${ProcesID}&InstancaID=${InstancaID}&DocumentID=${DocumentID}&MasterDocumentID=${MasterDocumentID}&Checked=${Checked}`,
        dataType: 'json',
        data: {},
        success: function (data) {
            if (data.Successed == 0) {
                swal({ title: "Poruka", text: results.Message, dangerMode: true, icon: "error" });
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(thrownError);
        }
    });
}
function KopirajTekstPriloga() {
    console.log("kopiranje priloga");
    let tekst = "";
    $("input.DMSprilozi:checked").each(function (i, input) {
        tekst = tekst + $(input).attr("Naziv") +"\n";


    });
    console.log(tekst);
        // Copy the text inside the text field
    copyToClipboard(tekst);
    swal({ title: "Poruka", text: "Prilog kopiran", dangerMode: true, icon: "info" });
}
function copyToClipboard(text, callback) {
    let sampleTextarea = document.createElement("textarea");
    document.body.appendChild(sampleTextarea);
    sampleTextarea.value = text; //save main text in it
    $(sampleTextarea).val(text);
    $(sampleTextarea).select(); //select textarea contenrs
    document.execCommand("copy");
    //console.log($(sampleTextarea).select());
    document.body.removeChild(sampleTextarea);
    if (callback != undefined) {
        callback();
    }
}
function copyToClipboard2(element,callback) {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val($(element).text()).select();
    document.execCommand("copy");
    $temp.remove();
    if (callback != undefined) {
        callback();
    }
}
function POSALJI_NA_ODOBRENJE() {
    $("#DokumentiKorisnici").empty();
    let filterPermisija = 'ODOBRI_ZA_SLANJE';
   /* $.ajax({
        url: `/json/GetKorisnici?filterPermisija=${filterPermisija}`,
        dataType: 'json',
        data: {},
        success: function (data) {
            if (data == '') {
                return;
            }
            $.each(JSON.parse(data), function (i, item) {//loop columns
                let Naziv = item["Naziv"];
                let Sifra = item["Sifra"];
                let row = $('<div class="row"></div>');
                let label = `<div class="col-md-9">${Naziv}</div>`;
                let input = null;
               
                input = $(`<div class="col-md-3"><input id="SifraKorisnika${Sifra}" UserID=${Sifra} type="checkbox" class="form-control"></div>`);
                $(row).append($(label));
                $(row).append($(input));
                $('#DokumentiKorisnici').append(row);
            });
            $("#btnSnimiDokumentiKorisnici").unbind('click');
            $("#btnSnimiDokumentiKorisnici").click(function () {
                POSALJI_NA_ODOBRENJE_SNIMI();
            });
            $("#NapomenaDokumentiKorisnici").val('');
            $('#mdDokumentiKorisnici').modal('show');
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(thrownError);
        }
    });
   */
    $("#btnSnimiDokumentiKorisnici").unbind('click');
    $("#btnSnimiDokumentiKorisnici").click(function () {
        POSALJI_NA_ODOBRENJE_SNIMI();
    });
    $("#NapomenaDokumentiKorisnici").val('Molim da odobrite dokument.');
    $('#mdDokumentiKorisnici').modal('show');
}
function POSALJI_NA_ODOBRENJE_SNIMI() {
    let Napomena = $("#NapomenaDokumentiKorisnici").val();
    let ValidacionaPoruka = "";
    /*if ($("#mdDokumentiKorisnici input:checked").length == 0) {
        ValidacionaPoruka = ValidacionaPoruka + "Potrebno je odabrati barem jednog korisnika\n";
    }*/
    if (Napomena == '') {
        ValidacionaPoruka = ValidacionaPoruka + "Napomena je obavezno polje\n";
        $("#NapomenaDokumentiKorisnici").addClass("invalid");
    }
    if (ValidacionaPoruka != "") {
        swal({ title: "Validacija unosa", text: ValidacionaPoruka, html: true, dangerMode: true, icon: "error" });
        return;
    }
    let DocumentID = $(trFocusedDokument).find('td.ID').attr('value');
    //let CheckedUsers = getCheckedUsers();
    let CheckedUsers = "";//ne treba uklonili smo jer cemo fiksno slati grupi
    $.ajax({
        type: "POST",
        url: `/DMS_Dokumenti/POSALJI_NA_ODOBRENJE?DocumentID=${DocumentID}&UsersID=${CheckedUsers}&Napomena=${Napomena}`,
        contentType: false,
        processData: false,
        success: function (results) {
            let icon = "success";
            if (results.Successed == 0) {
                icon = "error";
            }
            swal({ title: "Poruka", text: results.Message, dangerMode: true, icon: icon });
            tDMS_Dokumenti.SetData();
            $('#mdDokumentiKorisnici').modal('hide');
            bc.postMessage('refreshZadaci');
            bcDokumenti.postMessage('refreshDMS_Dokumenti');
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.responseText);
        }
    });
}
function getCheckedUsers() {
    let metaJSON = '[';
    $("#mdDokumentiKorisnici input:checked").each(function (i, input) {
        // console.log(input);
        if (i != 0) {
            metaJSON = metaJSON + ",";
        }
        let UserID = $(input).attr("UserID");
        metaJSON = metaJSON + `{"UserID":${UserID}}`;

    });
    metaJSON = metaJSON + ']';
    return metaJSON;
}
function ODOBRI_ZA_SLANJE() {
    $('#mdNapomena_Napomena').val('Odobravam dokument za slanje.');
    $('#mdNapomena').modal('show');
    $('#btnSnimimdNapomena').unbind('click');
    $('#btnSnimimdNapomena').click(function () {
        let DocumentID = $(trFocusedDokument).find('td.ID').attr('value');
        let Napomena = $('#mdNapomena_Napomena').val();
        $.ajax({
            type: "POST",
            url: `/DMS_Dokumenti/ODOBRI_ZA_SLANJE?DocumentID=${DocumentID}&Napomena=${Napomena}`,
            contentType: false,
            processData: false,
            success: function (results) {
                if (results.Successed == 0) {
                    swal({ title: "Poruka", text: results.Message, dangerMode: true, icon: "error" });
                    return;
                }
                swal({ title: "Poruka", text: results.Message, dangerMode: true, icon: "success" });
                tDMS_Dokumenti.SetData();
                $('#mdNapomena').modal('hide');
                bc.postMessage('refreshZadaci');
                bcDokumenti.postMessage('refreshDMS_Dokumenti');
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.responseText);
            }
        });
    });
}
function VRATI_NA_ISPRAVKU() {
    $('#mdNapomena_Napomena').val('');
    $('#mdNapomena').modal('show');
    $('#btnOdustanimdNapomena').unbind('click');
    $('#btnOdustanimdNapomena').click(function () {
        $('#mdNapomena').modal('hide');
    });
    $('#btnSnimimdNapomena').unbind('click');
    $('#btnSnimimdNapomena').click(function () {
        let DocumentID = $(trFocusedDokument).find('td.ID').attr('value');
        let Napomena = $('#mdNapomena_Napomena').val();
        if (Napomena == '') {
            swal({ title: "Poruka", text: "Napomena je obavezna", dangerMode: true, icon: "error" });
            return;
        }
        $.ajax({
            type: "POST",
            url: `/DMS_Dokumenti/VRATI_NA_ISPRAVKU?DocumentID=${DocumentID}&Napomena=${Napomena}`,
            contentType: false,
            processData: false,
            success: function (results) {
                swal({ title: "Poruka", text: results.Message, dangerMode: true, icon: "success" });
                tDMS_Dokumenti.SetData();
                $('#mdNapomena').modal('hide');
                bc.postMessage('refreshZadaci');
                bcDokumenti.postMessage('refreshDMS_Dokumenti');
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.responseText);
            }
        });
    });
}
function POSALJI_NA_OTPREMU() {
    $("#DokumentiKorisnici").empty();
    let filterPermisija = 'PIS_OTPREMI';
   /* $.ajax({
        url: `/json/GetKorisnici?filterPermisija=${filterPermisija}`,
        dataType: 'json',
        data: {},
        success: function (data) {
            if (data == '') {
                return;
            }
            $.each(JSON.parse(data), function (i, item) {//loop columns
                let Naziv = item["Naziv"];
                let Sifra = item["Sifra"];
                let row = $('<div class="row"></div>');
                let label = `<div class="col-md-9">${Naziv}</div>`;
                let input = null;

                input = $(`<div class="col-md-3"><input id="SifraKorisnika${Sifra}" UserID=${Sifra} type="checkbox" class="form-control"></div>`);
                $(row).append($(label));
                $(row).append($(input));
                $('#DokumentiKorisnici').append(row);
            });
            $("#btnSnimiDokumentiKorisnici").unbind('click');
            $("#btnSnimiDokumentiKorisnici").click(function () {
                POSALJI_NA_OTPREMU_SNIMI();
            });
            $("#NapomenaDokumentiKorisnici").val('');
            $('#mdDokumentiKorisnici').modal('show');
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(thrownError);
        }
    });*/
    $("#btnSnimiDokumentiKorisnici").unbind('click');
    $("#btnSnimiDokumentiKorisnici").click(function () {
        POSALJI_NA_OTPREMU_SNIMI();
    });
    $("#NapomenaDokumentiKorisnici").val('Molim da otpremite dokument.');
    $('#mdDokumentiKorisnici').modal('show');
}
function POSALJI_NA_OTPREMU_SNIMI() {
    let Napomena = $("#NapomenaDokumentiKorisnici").val();
    let ValidacionaPoruka = "";
    /*if ($("#mdDokumentiKorisnici input:checked").length == 0) {
        ValidacionaPoruka = ValidacionaPoruka + "Potrebno je odabrati barem jednog korisnika\n";
    }*/
    if (Napomena == '') {
        ValidacionaPoruka = ValidacionaPoruka + "Napomena je obavezno polje\n";
        $("#NapomenaDokumentiKorisnici").addClass("invalid");
    }
    if (ValidacionaPoruka != "") {
        swal({ title: "Validacija unosa", text: ValidacionaPoruka, html: true, dangerMode: true, icon: "error" });
        return;
    }
    let DocumentID = $(trFocusedDokument).find('td.ID').attr('value');
    let CheckedUsers = "";// getCheckedUsers();ne treba šaljemo zadatak grupi kurir
    $.ajax({
        type: "POST",
        url: `/DMS_Dokumenti/POSALJI_NA_OTPREMU?DocumentID=${DocumentID}&UsersID=${CheckedUsers}&Napomena=${Napomena}`,
        contentType: false,
        processData: false,
        success: function (results) {
            let icon = "success";
            if (results.Successed == 0) {
                icon = "error";
            }
            swal({ title: "Poruka", text: results.Message, dangerMode: true, icon: icon });
            tDMS_Dokumenti.SetData();
            DMS_OtpremaDokumenta();
            $('#mdDokumentiKorisnici').modal('hide');
            bc.postMessage('refreshZadaci');
            bcDokumenti.postMessage('refreshDMS_Dokumenti');
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.responseText);
        }
    });
}

function DMS_ODOBRI() {
    $('#mdNapomena_Napomena').val('Odobravam dokument.');
    $('#mdNapomena').modal('show');
    $('#btnSnimimdNapomena').unbind('click');
    $('#btnSnimimdNapomena').click(function () {
        let DocumentID = $(trFocusedDokument).find('td.ID').attr('value');
        let Napomena = $('#mdNapomena_Napomena').val();
        $.ajax({
            type: "POST",
            url: `/DMS_Dokumenti/DMS_ODOBRI?DocumentID=${DocumentID}&Napomena=${Napomena}`,
            contentType: false,
            processData: false,
            success: function (results) {
                if (results.Successed == 0) {
                    swal({ title: "Poruka", text: results.Message, dangerMode: true, icon: "error" });
                    return;
                }
                swal({ title: "Poruka", text: results.Message, dangerMode: true, icon: "success" });
                tDMS_Dokumenti.SetData();
                $('#mdNapomena').modal('hide');
                bc.postMessage('refreshZadaci');
                bcDokumenti.postMessage('refreshDMS_Dokumenti');
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.responseText);
            }
        });
    });
}
function DMS_PROTOKOLISI() {
    let DocumentID = tDMS_Dokumenti.GetFocusedValue('ID');
    $.ajax({
        type: "POST",
        url: `/DMS_Dokumenti/DMS_PROTOKOLISI?DocumentID=${DocumentID}`,
        contentType: false,
        processData: false,
        success: function (results) {
            if (results.Successed == 0) {
                swal({ title: "Poruka", text: results.Message, dangerMode: true, icon: "error" });
                return;
            }
            swal({ title: "Poruka", text: results.Message, dangerMode: true, icon: "success" });
            tDMS_Dokumenti.SetData();
            if (tPIS_Obrazac5 != undefined) {
                tPIS_Obrazac5.SetData();
            }
            bc.postMessage('refreshZadaci');
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.responseText);
        }
    });
}
/*class columnOption {
    constructor(name, title) {
        this.name = name;
        this.title = title;
    }
}*/

(function ($) {
    $.fn.danijeltable = function (options) {
        //$(tUsers.table).find('tbody').find('input').attr('readonly','')
        let plugin = this;
        let version = 1;//ne treba zasad-mjenjas verziju ako hoces da se neuzimaju snimljene postavke tj npr ako dodajes kolonu
        let currentPage = 1;
        let rowsPerPage = 10;
        let UkupanBrojStrana = 1;
        let table = null;//html tabela objekat
        let headertable = null;
        let footerdiv = null;
        let tbody = null;
        let vdata = null;
        let voptions = null;
        let keyfield = null;
        let sortorder = 'asc';
        let sortfield = '';
        let CommandFooterSet = false;
        let HeaderSet = false;
        let PagerVisible = false;
        let vSaveSettings = false;//dali snimati postavke u local storage
        let onFocusChange = null;
        let onDblClick = null;
        let showfooter = null;
        let showFilterRow = null;
        let FixedHeaderVisible = null;//netreba vise-dali je odvojena tabele sa headerom da bi napravio sticki tj da kod skrolovanja na vrhu ostaje zaglavlje tabele
        let CustomParameters = null;
        let tableCssClass = null;
        let sendGridParams = true;//staviti false ako netreba paging i slanje filtera itd
        let addValuesToRow = true;//dodavanje vrijednosti kolona u red
        let setDragableColumns = true;//reorder columns
        let focusedTr = null;
        let rowsCount = 0;
        let addnewrow = true;
        let cardView = false;
        let NemaPodatakaText = '';
        let settings = $.extend({// These are the defaults.
            selector: "",
            tableOptions: ""
        }, options);
        this.initialize = function () {
            //.log('init');
            plugin.table = this[0];
            plugin.voptions = options;
            plugin.currentPage = currentPage;
            plugin.plugin = this;
            plugin.vSaveSettings = options.tableOptions.SaveSettings;
            plugin.version = options.tableOptions.version;
            $.each(options.tableOptions.columnModel, function (i, column) {//loop columns
                if (column.key) {
                    plugin.keyfield = column.name;
                }
            });
            if (options.tableOptions.onFocusChange !== undefined) {
                plugin.onFocusChange = options.tableOptions.onFocusChange;
            }
            if (options.tableOptions.onDblClick !== undefined) {
                plugin.onDblClick = options.tableOptions.onDblClick;
            }
            if (options.tableOptions.afterSetData !== undefined) {
                plugin.afterSetData = options.tableOptions.afterSetData;
            }
            if (options.tableOptions.afterSaveData !== undefined) {
                plugin.afterSaveData = options.tableOptions.afterSaveData;
            }
            if (options.tableOptions.addValuesToRow !== undefined) {
                plugin.addValuesToRow = options.tableOptions.addValuesToRow;
            }
            if (options.tableOptions.setDragableColumns !== undefined) {
                plugin.setDragableColumns = options.tableOptions.setDragableColumns;
            } else {
                plugin.setDragableColumns = true;
            }
            if (plugin.vSaveSettings) {
                if (localStorage.getItem($(plugin.table).attr('id') + plugin.version)) {
                    options.tableOptions = jQuery.parseJSON(localStorage.getItem($(plugin.table).attr('id') + plugin.version));
                }
            }
            plugin.rowsPerPage = options.tableOptions.rowsPerPage;
            //red kolona na osnovu index
            options.tableOptions.columnModel.sort(function (a, b) {
                return a.index > b.index;
            });
            if (options.tableOptions.width !== undefined) {
                $(plugin.table).css('width', options.tableOptions.width);
                $(plugin.table).css('min-width', options.tableOptions.width);
            }
            if (options.tableOptions.sortorder !== undefined) {
                plugin.sortorder = options.tableOptions.sortorder;
            }
            if (options.tableOptions.sortfield !== undefined) {
                plugin.sortfield = options.tableOptions.sortfield;
            }
            plugin.PagerVisible = options.tableOptions.PagerVisible;
            plugin.showfooter = options.tableOptions.showfooter;
            plugin.showFilterRow = options.tableOptions.showFilterRow;
            plugin.FixedHeaderVisible = options.tableOptions.FixedHeaderVisible;
            plugin.CustomParameters = options.tableOptions.CustomParameters;
            plugin.sendGridParams = options.tableOptions.sendGridParams;
            plugin.tableCssClass = options.tableOptions.tableCssClass;
            plugin.addnewrow = options.tableOptions.addnewrow;
            plugin.cardView = options.tableOptions.cardView;
            plugin.NemaPodatakaText = options.tableOptions.NemaPodatakaText;
            //onsole.log(plugin.cardView);
            if (plugin.cardView) {
                this.SetCardView();
                return;
            }
            this.SetHeader();
            
           
            this.SetColResizable();
            this.SetDragableColumns();
           
            //this.SetPager();
            this.SetData(true);
            this.SetFooter();
            this.SetCommandFooter();
            if (plugin.PagerVisible) {
                this.SetPager();
            }
            SetKeyboardNavigation();
            return this;
        };
        this.SetHeader = function () {
            if (plugin.HeaderSet)
                return;
            $('.SpinTable.headertable.' + options.tableOptions.tableCssClass).find("thead").remove();//ukloni ako već postoji
            let thead = $('<thead>');
            if (plugin.FixedHeaderVisible) {
                $(thead).css("visibility", "collapse");
            }
            if (plugin.SetFilterRow) {
                $(thead).addClass("filtervisible");
            }
            let trheader = $('<tr class="headertr">');
            let thinfo = $('<th class="infocolumn">');
            trheader.append(thinfo);
            $.each(options.tableOptions.columnModel, function (i, column) {
                let th = $('<th>');
                th.addClass(column.name);
                th.addClass('dragable');
                th.attr('columnname', column.name);
                th.attr('index', column.index);
                th.html(column.title);
                th.attr('class', column.name);
                $(th).addClass(options.tableOptions.tableCssClass);
                if (column.width !== undefined) {
                    th.css('width', column.width);
                    th.css('min-width', column.width);
                }
                th.addClass('datatype' + column.datatype);
                trheader.append(th);
            });
            if (options.tableOptions.editable) {
                let thdelete = $('<th class="delete thdelete">');
                trheader.append(thdelete);
            }
            thead.append(trheader);
            $(plugin.table).append(thead.clone());
            let headertable = $('<table class="SpinTable headertable  ' + options.tableOptions.tableCssClass + '">');
          
            if (plugin.FixedHeaderVisible) {

                let theadFixedHeader = thead.clone();
                $(theadFixedHeader).css("visibility", "visible");
                headertable.append(theadFixedHeader);
                $(headertable).insertBefore(plugin.table);
            } else {
                $(plugin.table).addClass("headertable");
            }
            plugin.headertable = headertable;
            plugin.SetFilterRow();
            plugin.SetSort();
            plugin.HeaderSet = true;
        };
        this.SetFilterRow = function () {
            /*if (!options.tableOptions.showFilterRow) {
                return;
            }*/
            let thead = null;
            if (plugin.FixedHeaderVisible) {
                thead = $(plugin.headertable).find('thead');//ako je fixed header
            } else {
                thead = $(plugin.table).find('thead');//dodaj filter row na header tabele
            }
            let trfilter = $('<tr class="filtertr">');
            if (!options.tableOptions.showFilterRow) {
                $(trfilter).css('display', 'none');
            }
            let thinfo = $('<th class="infocolumn">');
            let clearButton = $('<span  class="clearFilter" title="Poništi filter" data-title="Poništi filter">');
            thinfo.append(clearButton);
            $(clearButton).on('click', function () {
                plugin.currentPage = 1;
                $('.filtertr input').val('');
                $('.filtertr input').attr('oldvalue', '');
                $('.filtertr input').css('background-color', 'white');
                $(plugin.table).find('div.dropdown').attr('value', '')
                $(plugin.table).find('div.checkboxfilterText').text('svi');
                plugin.SetData();
            });
            trfilter.append(thinfo);
            $.each(options.tableOptions.columnModel, function (i, column) {

                let th = $('<th>');
                th.addClass(column.name);
                th.addClass(options.tableOptions.tableCssClass);
                let vinput = $('<input>');
                let vIcon = $('<span class="filterIcon">');
                vinput.id = column.name;
                vinput.attr('class', 'form-control filtercontrol');
                vinput.attr('tabindex', i);
                vinput.attr('columnname', column.name);
                vinput.attr('oldvalue', '');
                vinput.attr('placeholder', '...kucaj za pretragu');
                vinput.attr('datatype', column.datatype);
                if (column.initialValue != undefined) {
                    vinput.val(column.initialValue);
                    $(vinput).css('background-color', '#ffeaee');
                }
                if (column.datatype == 'dateedit') {
                    vinput.addClass('zebra');
                }
                if (column.datatype == 'checkbox') {
                    //vinput.attr('type','checkbox');
                    vinput.attr('placeholder', '1/0');
                    vinput.addClass('number');
                }
                /*if (column.datatype == 'checkbox') {
                    vinput.attr('type', 'checkbox');
                }*/
                if (column.datatype != 'html' && column.datatype != 'checkbox') {
                    th.append(vIcon);
                    th.append(vinput);
                }
                else if (column.datatype == 'checkbox')
                {
                    let dropdown = $('<div>');
                    $(dropdown).attr('columnname', column.name);
                    $(dropdown).attr('value','');
                    $(dropdown).addClass('dropdown');
                    let button = $(`<button style="padding:2px;margin:0px;min-width:20px;width:100%" class="btn dropdown-toggle controls filterButton" type="button" data-toggle="dropdown">
                        <span class="iconChecked" style="float: left;"></span>
                        <div class="checkboxfilterText">svi<div>
                    </button>`);
                    //$(button).addClass('dropdown-menu');
                    let ul = $('<div>');
                    $(ul).addClass('dropdown-menu');
                    $(ul).append('<li><a value="" tekst="svi" style="padding:2px;margin:2px"><span class="iconChecked" style="float: left;margin:5px 5px 0px 0px"></span>Svi</a></li>');
                    $(ul).append('<li><a value="1" tekst="da" style="padding:2px;margin:2px"><span class="iconChecked" style="float: left;margin:5px 5px 0px 0px"></span>Da</a></li>');
                    $(ul).append('<li><a value="0" tekst="ne" style="padding:2px;margin:2px"><span class="iconUnchecked" style="float: left;margin:5px 5px 0px 0px"></span>Ne</a></li>');
                    $(ul).find("a").click(function () {
                        let value = $(this).attr('value');
                        let tekst = $(this).attr('tekst');
                        $(this).closest('div.dropdown').attr('value', value);
                        $(this).parent().parent().parent().find('div.checkboxfilterText').text(tekst);
                        plugin.SetData();
                    });
                   
                    $(dropdown).append(button);
                    $(dropdown).append(ul);
                    th.append(dropdown);
                }
                else {
                    th.addClass('nemaFiltera');
                }
                trfilter.append(th);
            });
            if (options.tableOptions.editable) {
                let thdelete = $('<th class="delete thdelete">');
                trfilter.append(thdelete);
            }
            thead.append(trfilter);
            $('.filtercontrol').on('blur', function (object) {
                if ($(object.target).val() != $(object.target).attr('oldvalue')) {
                    plugin.currentPage = 1;
                    plugin.SetData();
                    $(object.target).attr('oldvalue', $(object.target).val());
                    if ($(object.target).val() == '') {
                        $(object.target).css('background-color', 'white');
                    }
                    else {
                        $(object.target).css('background-color', '#ffeaee');
                    }
                }
            });
        };
        this.SetFooter = function () {
            return;
            /*if (!options.tableOptions.showfooter) {
                return;
            }
            let tfoot = $('<tfoot class="foot">');
            let trfooter = $('<tr class="trfooter">');
            let thinfo = $('<th class="infocolumn">');
            trfooter.append(thinfo);
            $.each(options.tableOptions.columnModel, function (i, column) {
                let th = $('<th>');
                th.addClass(column.name);
                th.attr('columnname', column.name);
                trfooter.append(th);
            });
            if (options.tableOptions.editable) {
                let thdelete = $('<th class="delete">');
                trfooter.append(thdelete);
            }
            tfoot.append(trfooter);
            $(plugin.table).append(tfoot);*/
        };
        this.SetCommandFooter = function () {
            if (plugin.CommandFooterSet)
                return;
            let footerdiv = $(`<div id="${$(plugin.table).attr('id')}" class="footerdiv ${options.tableOptions.tableCssClass}" ></div>`);
            let btnResetSettings = $(`
    <button id="btnResetTable" class="btn btn-default " title="Resetuj tabelu" style="margin-left:1px;float:left;padding: 2px 8px;">
        <span class="icon-cog3"></span> Resetuj tabelu
    </button>
`);
            $(btnResetSettings).on('click', function () {
                localStorage.removeItem($(plugin.table).attr('id') + plugin.version);
                /*$(plugin.table).empty();
                plugin.tbody = null;
                $(plugin.headertable).remove();
                plugin.HeaderSet = false;
                plugin.initialize();*/
                location.reload();
            });
            footerdiv.append(btnResetSettings);
            plugin.footerdiv = footerdiv;
            let btnToggleHidenColumns = $(`
        <span class="toggleHidenColumns" title="Prikaži sakrivene kolone"></span> 
`);
            footerdiv.append(btnToggleHidenColumns);
            $(btnToggleHidenColumns).on('click', function () {
                $(`.SpinTable.${plugin.tableCssClass} > thead > tr > th:hidden`).addClass('columnhidden');
                $(`.SpinTable.${plugin.tableCssClass} > tbody > tr > td:hidden`).addClass('columnhidden');
                $(`.SpinTable.${plugin.tableCssClass} > thead > tr > th:hidden`).css('color', 'red');
                $(`.SpinTable.${plugin.tableCssClass} > tbody > tr > td:hidden`).css('color', 'red');
                $(`.SpinTable.${plugin.tableCssClass} > thead > tr > th.columnhidden`).toggle();
                $(`.SpinTable.${plugin.tableCssClass} > tbody > tr > td.columnhidden`).toggle();
            });
            let btnRefreshData = $(`
        <span class="tableRefreshData" title="Osvježi podatke"></span> 
`);
            footerdiv.append(btnRefreshData);
            $(btnRefreshData).on('click', function () {
                plugin.SetData();
            });
            let btnShowFilterRow = $(`
        <span class="tableShowFilterRow" title="Prikaži traku za pretragu"></span> 
`);
            footerdiv.append(btnShowFilterRow);
            $(btnShowFilterRow).on('click', function () {
                let tr = $(`.SpinTable.${plugin.tableCssClass} > thead > tr.filtertr`);
                if (tr.is(":visible")) {
                    //$(tr).fadeOut(100);
                    $(tr).hide();
                    $(plugin.table).children('thead').removeClass('filtervisible');
                } else {
                    // $(tr).fadeIn(300);
                    $(tr).show();
                    $(plugin.table).children('thead').addClass('filtervisible');
                }
            });
            let btnShowDetails = $(`
        <span class="tableShowDetails" title="Prikaži zapis"></span> 
`);
            footerdiv.append(btnShowDetails);
            $(btnShowDetails).on('click', function () {
                ShowDetails(plugin);
            });
            let btnToggleEdit = $(`
        <span class="tableToggleEdit" title="Izmjena podataka"></span> 
`);
            if (options.tableOptions.saveurl!='') {
                footerdiv.append(btnToggleEdit);
            }
         
            $(btnToggleEdit).on('click', function () {
                plugin.voptions.tableOptions.editable = !plugin.voptions.tableOptions.editable;
                if (plugin.voptions.tableOptions.editable) {
                    $(plugin.table).find("th.delete").show();
                    $(plugin.table).addClass("EditMode");
                } else {
                    $(plugin.table).find("th.delete").hide();
                    $(plugin.table).removeClass("EditMode");
                }
                plugin.HeaderSet = false;
                plugin.SetHeader();
               /* plugin.SetFooter();
                plugin.SetCommandFooter();*/
                plugin.SetData();
            });
            let btnToggleStyle = $(`
        <span class="tableToggleStyle" title="Vertikalni prikaz"></span> 
`);
            footerdiv.append(btnToggleStyle);
            $(btnToggleStyle).on('click', function () {
                $(plugin.table).toggleClass('verticalTable');

            });
            let footer = $('<tfoot></tfoot>');
            let tr = $('<tr>');
            let th = $('<th colspan=999></th>');
            let InfoDiv = $(`<div class="tableinfo ${options.tableOptions.tableCssClass}"><div>`);
            footer.append(tr);
            footerdiv.append(InfoDiv);
            tr.append(th);
            th.append(footerdiv);
            if (options.tableOptions.showfooter) {
                $(plugin.table).append(footer);
            }

            plugin.CommandFooterSet = true;
        };
        this.SetSort = function () {
            if (plugin.FixedHeaderVisible) {
                //postavi klik evente na fixed header
                $(plugin.headertable).find('.headertr').find('th').on('click', function (object) {
                    plugin.currentPage = 1;
                    $(plugin.headertable).find('.headertr').find('span').remove();
                    if (plugin.sortorder == 'asc') {
                        plugin.sortorder = 'desc';
                        plugin.sortfield = $(object.target).attr('columnname');
                        $(object.target).append('<span class="sortDesc"></span>');
                    }
                    else {
                        plugin.sortorder = 'asc';
                        $(object.target).append('<span class="sortAsc"></span>');
                    }
                    plugin.SetData();
                });
            } else {
                $(plugin.table).find('.headertr').find('th').on('click', function (object) {
                    plugin.currentPage = 1;
                    $(plugin.table).find('.headertr').find('span').remove();
                    if (plugin.sortorder == 'asc') {
                        plugin.sortorder = 'desc';
                        plugin.sortfield = $(object.target).attr('columnname');
                        $(object.target).append('<span class="sortDesc"></span>');
                    }
                    else {
                        plugin.sortorder = 'asc';
                        $(object.target).append('<span class="sortAsc"></span>');
                    }
                    plugin.SetData();
                });
            }
        };
        this.SetData = function (firstload = false, afterSetData = null) {
            
            let tabindex = 1000;
            let t1 = performance.now();
             // #region Ključ fokusiranog sloga da ga ponovo fokusiramo ako ga ima nakon prikupljanja podataka
            let focusedTrKEY_VALUE = null;
            if (plugin.focusedTr != null && plugin.focusedTr != undefined && plugin.keyfield != null && plugin.keyfield != undefined) {
                focusedTrKEY_VALUE=$(plugin.focusedTr).attr(plugin.keyfield);//da fokusiramo isti slog nakon refresha
            }
             // #endregion
            if (plugin.tbody == null) {
                plugin.tbody = $('<tbody>');
                $(plugin.table).append(plugin.tbody);
            }
            else {
                plugin.tbody = $(plugin.table).find('tbody');
            }
            $(plugin.table).block();
            $(".blockUI.blockMsg.blockElement").css({ "left": "0px", "top": "0px", "width": "150px" });
            $(".blockUIicon.fas.fa-spinner.fa-spin,.blockUItext").css({ "font-size": "20px" });
            // #region Pageing i filer podaci
            let vfilter = {};
            $.each(options.tableOptions.columnModel, function (i, column) {//loop columns
                let input = $(plugin.table).find('.filtertr').find('[columnname="' + column.name + '"]');
                let val = input.val();
                if (column.datatype == 'checkbox') {
                    val = $(plugin.table).find('.filtertr').find('[columnname="' + column.name + '"]').attr('value');
                }
                if (val != '') {
                    $.extend(vfilter, { [column.name]: val });
                }
                if (column.calculatesum == 1) {
                    $(plugin.table).removeAttr(column.name + '_SUM');
                }
               
            });
            let vdata = [{
                currentPage: plugin.currentPage,
                rowsPerPage: plugin.rowsPerPage,
                sortfield: plugin.sortfield,
                sortorder: plugin.sortorder,
                filter: vfilter,
            }];
            // #endregion
            if (plugin.CustomParameters != undefined) {
                vdata.push(plugin.CustomParameters);
            }
            vdata = { gridparams: JSON.stringify(vdata) };
            if (plugin.sendGridParams === false) {
                vdata = null;
            }
            let t3 = performance.now();
            //onsole.log('SetData do ajaxa: ' + (t3 - t1) + ' ms');
            $.ajax({
                url: options.tableOptions.dataurl,
                dataType: 'json',
                data: vdata,
                //async: false,
                //data: [{ gridparams: JSON.stringify(vdata),other: JSON.stringify(plugin.CustomParameters) }],
                success: function (data) {
                    // #region Provjera da li je istekla sesija ili nema prava
                    if (String(data).indexOf('Nemate') >= 0) {
                        swal({ title: "Poruka", text: data, dangerMode: true, icon: "error" });
                        location.reload();
                        return;
                    }
                    if (data.Successed == 0) {
                        swal({ title: "Poruka", text: data.Message, dangerMode: true, icon: "error" });
                        return;
                    }
                    //#endregion
                    plugin.tbody.find('tr').remove();
                    plugin.vdata = data;
                    data = JSON.stringify(data);
                    // #region Ako nema podataka 
                    if (data != '') {
                        if (JSON.parse(data).length > 0) {
                            plugin.UkupanBrojStrana = Math.ceil(JSON.parse(data)[0]['Total'] / plugin.rowsPerPage);
                           
                        } else {
                            if (!options.tableOptions.editable) {
                                plugin.AddEmptyRow();
                            }
                            else if (options.tableOptions.editable&&plugin.addnewrow===false) {
                                plugin.AddEmptyRow();
                            }
                        }
                    }
                   //#endregion
                    $.each(JSON.parse(data), function (i, item) {//loop rows
                        let tr = document.createElement("tr");
                        tr.className = "editrow";
                        let tr_rb = i+1;
                        $(tr).attr('rb', tr_rb);
                        if (options.tableOptions.PKColumn != undefined) {
                            tr.setAttribute(options.tableOptions.PKColumn, item[options.tableOptions.PKColumn]);
                        }
                        let tdinfo = document.createElement("td");
                        tdinfo.className = "infocolumn";
                        let nimage = document.createElement("span");
                        nimage.setAttribute("id", "nimage");
                        nimage.setAttribute("data-toggle", "tooltip");
                        nimage.setAttribute("data-html", "true");
                        nimage.setAttribute("data-placement", "top");
                        tdinfo.append(nimage);
                        tr.append(tdinfo);                    
                        $.each(options.tableOptions.columnModel, function (i, column) {//loop columns
                            let td = document.createElement("td");
                            //let tabindex = parseInt(i) + (parseInt(tr_rb)*100);
                            tabindex = tabindex + 1;
                            if (options.tableOptions.addValuesToRow || options.tableOptions.addValuesToRow == undefined) {                       
                                if (column.datatype == 'dateedit') {
                                    let formateddate = '';
                                    if (item[column.name]!=undefined&&item[column.name] != '') {
                                        formateddate = $.datepicker.formatDate('dd.mm.yy', new Date(parseInt((item[column.name]).toString().substr(6))));
                                    }
                                    //td.text(formateddate);
                                    td.textContent = formateddate;
                                    //td.attr('value', formateddate);
                                    $(tr).attr(column.name, formateddate);
                                }
                                else if (column.datatype == 'number') {
                                    let val = item[column.name];
                                    if (val != undefined && val != '') {
                                        let formatedval = (val).toLocaleString(
                                            'de-DE',
                                            { minimumFractionDigits: 2 }
                                        );
                                        $(tr).attr(column.name, formatedval);

                                    } else {
                                        $(tr).attr(column.name, val);
                                    }
                                }
                                else {
                                    if (column.name.indexOf(" ") > 0) {
                                        $(tr).attr(column.name, item["'" + column.name + "'"]);
                                    } else {
                                        $(tr).attr(column.name, item[ column.name ]);
                                    }
                                }
                            }                        
                            td.className = column.name;
                            $(td).addClass(options.tableOptions.tableCssClass);
                            if (column.width !== undefined) {
                                td.style.width = column.width;
                            }
                            td.setAttribute("readonly", column.readonly);
                            
                            if (!options.tableOptions.editable) {
                                td.setAttribute("style", "padding: 2px");
                                $(td).addClass('datatype'+column.datatype);
                                if (column.datatype == 'select') {
                                    td.textContent =  item[column.lookupname];
                                    td.setAttribute("value", item[column.name]);
                                    td.setAttribute("Displayvalue", item[column.lookupname]);

                                }
                                else if (column.datatype == 'dateedit') {
                                    let formateddate = '';
                                    if (item[column.name] != undefined &&item[column.name] != '') {
                                        formateddate = $.datepicker.formatDate('dd.mm.yy', new Date(parseInt((item[column.name]).toString().substr(6))));
                                    }
                                    td.textContent = formateddate;
                                    td.setAttribute("value", formateddate);
                                }
                                else if (column.datatype == 'datetimeedit') {//ovotreba sredit
                                    let formateddate = '';
                                    if (item[column.name] != '' && item[column.name]!=undefined) {
                                        let Datum = new Date(parseInt((item[column.name]).toString().substr(6)));
                                        let Dan = ('0' + Datum.getDate()).slice(-2);
                                        let Mjesec = ('0' + ( Datum.getMonth() + 1)).slice(-2);
                                        let Godina = Datum.getFullYear();
                                        formateddate = Dan + '.' + Mjesec + '.' + Godina  + ' ' + ('0' + Datum.getHours()).slice(-2) + ':' + ('0' + Datum.getUTCMinutes()).slice(-2);
                                    }
                                    //td.text(formateddate);
                                    td.textContent = formateddate;
                                    //td.attr('value', formateddate);
                                    td.setAttribute("value", formateddate);
                                }
                                else if (column.datatype == 'number') {
                                    let val = item[column.name];
                                    if (val != undefined) {
                                        let formatedval = (val).toLocaleString(
                                            'de-DE',
                                            { minimumFractionDigits: 2 }
                                        );
                                        $(td).addClass("number");
                                        td.textContent = formatedval;
                                        
                                    }
                                    td.setAttribute("value", val);
                                    if (column.calculatesum == 1) {
                                        
                                        let Vrijednost = 0;
                                        if (item[column.name] != '') {
                                            Vrijednost = parseFloat(item[column.name]);
                                        }
                                        if ($(plugin.table).attr(column.name + '_SUM') == '' || $(plugin.table).attr(column.name + '_SUM') == undefined) {

                                            $(plugin.table).attr(column.name + '_SUM', Vrijednost);
                                        } else {
                                            let Iznos = parseFloat($(plugin.table).attr(column.name + '_SUM'));
                                            $(plugin.table).attr(column.name + '_SUM', Iznos + Vrijednost);
                                        }
                                    }
                                }
                                else if (column.datatype == 'checkbox') {
                                    let vlabelcheckcontainer = $('<label class="chkcontainer">');
                                    let vinput = $('<input type="checkbox" disabled="disabled" class="form-control tablecontrol styled" />');
                                    let vcheckmark = $('<span class="checkmark">');
                                    vinput.id = column.name;
                                    vinput.addClass('form-control checkboxcontrol control');
                                    vinput.attr('tabindex', tabindex);
                                    vinput.attr('columnname', column.name);
                                    let StatusChecked = "";
                                    if (item[column.name] == 1||item[column.name]=="true") {
                                        StatusChecked = "checked";
                                        vinput.attr("checked", '');
                                        td.setAttribute("value", "Da");
                                    } else {
                                        td.setAttribute("value", "Ne");
                                    }
                                    vinput.attr('oldvalue', StatusChecked);
                                    vinput.addClass(column.name);
                                    vlabelcheckcontainer.append($(vinput));
                                    vlabelcheckcontainer.append($(vcheckmark));
                                    $(td).append($(vlabelcheckcontainer));
                                  
                                    //$(td).append($('<input type="checkbox" class="form-control styled" />'));
                                    //tr.append(td);
                                    //plugin.tbody.append(tr);
                                }
                                else if (column.datatype == 'html') {
                                    let vhtmlelement = $(column.html);
                                    if (options.tableOptions.PKColumn != undefined) {
                                        $(vhtmlelement).attr(options.tableOptions.PKColumn, item[options.tableOptions.PKColumn]);
                                    }
                                    $(td).append(vhtmlelement);
                                }
                                else {
                                    td.textContent = item[column.name];
                                    td.setAttribute("value", item[column.name]);
                                    /*if (item[column.name] != undefined) {
                                        td.setAttribute("DuzinaSadrzaja", item[column.name].length);
                                    }*/
                                   
                                }
                                if (column.setSpan == '1') {
                                    let span = document.createElement("span");
                                    $(span).attr("columnname", column.name);
                                    $(span).attr("columnvalue", item[column.name]);
                                    td.prepend(span);
                                    
                                }
                                if (column.template != undefined) {
                                    let html = column.template;
                                    $.each(options.tableOptions.columnModel, function (i, column) {
                                        html=html.replaceAll(`{${column.name}}`, item[column.name]);
                                    });
                                    $(td).html(html);
                                } 
                                tr.append(td);
                                plugin.tbody.append(tr);
                                return;
                            }                        
                           
                            if (column.datatype == 'select') {
                                if (column.readonlyinedit) {
                                    td.textContent = item[column.lookupname];
                                    //$(td).html(`<p>${item[column.lookupname]}</p>`);
                                    td.setAttribute("value", item[column.lookupname]);
                                    tr.append(td);
                                    return;
                                }
                                let vinputgroup = $('<div class="input-group input-group-combobox">');
                                let vinput = $('<input Sifra="" class="tablecontrol" placeholder="kucaj za pretragu..." style="width:100%" type="text" />');
                                let vbutton = $('<span class="input-group-addon input-group-addon-combobox" style="cursor:pointer"><i class="caretDown"></i></span>');
                                    vinput.id = column.name;
                                    vinput.addClass('control');
                                    //vinput.attr('tabindex', i);
                                    vinput.attr('tabindex', tabindex);
                                    vinput.attr('columnname', column.name);
                                    if (column.readonly) {
                                        vinput.attr('readonly', '');
                                        vinput.attr('tabindex', -1);
                                    }
                                    vinput.attr('oldsifra', item[column.name]);
                                vinput.attr('sifra', item[column.name]);
                                if (column.DodajSifruIspred) {
                                    vinput.val(item[column.name] + '-' + item[column.lookupname]);
                                    vinput.attr('oldvalue', item[column.name] + '-' + item[column.lookupname]);
                                } else {
                                    vinput.val(item[column.lookupname]);
                                    vinput.attr('oldvalue',  item[column.lookupname]);
                                }
                                  
                                  
                                    $(vinputgroup).append($(vinput));
                                    if (options.tableOptions.editable) {
                                        vinputgroup.append(vbutton);
                                    }
                                    vinput.addClass(column.name);
                                    vinput.addClass(column.name + i);
                                    vinput.addClass('selectcontrol');
                                    $(td).append($(vinputgroup));
                                    $(tr).append($(td));
                                plugin.tbody.append(tr);
                                plugin.SetCombo('.' + column.name + tabindex, column.dataurl, column.onChange, column.additionalField, column.additionalValue, column.selectFirstIfOne,column.columns);
                                
                            }
                            else if (column.datatype == 'checkbox') {
                                let vlabelcheckcontainer = $('<label class="chkcontainer">');
                                let vinput = $('<input type="checkbox" class="form-control styled tablecontrol" />');
                                let vcheckmark = $('<span class="checkmark">');
                                vinput.id = column.name;
                                vinput.addClass('form-control checkboxcontrol control');
                                vinput.attr('tabindex', tabindex);
                                vinput.attr('columnname', column.name);
                                if (column.readonly) {
                                    vinput.attr('readonly', '');
                                    vinput.attr('tabindex', -1);
                                }
                                let StatusChecked = "";
                                if (item[column.name] == 1 || item[column.name] == "true") {
                                    StatusChecked = "checked";
                                    vinput.attr("checked", '');
                                }
                                vinput.attr('oldvalue', StatusChecked);
                                vinput.addClass(column.name);
                                $(vlabelcheckcontainer).append($(vinput));
                                $(vlabelcheckcontainer).append($(vcheckmark));
                                $(td).append($(vlabelcheckcontainer));
                                $(tr).append($(td));
                                plugin.tbody.append(tr);
                            }
                            else if (column.datatype == 'dateedit') {
                                if (column.readonly) {
                                    let formateddate = '';
                                    if (item[column.name] != '') {
                                        formateddate = $.datepicker.formatDate('dd.mm.yy', new Date(parseInt((item[column.name]).toString().substr(6))));
                                    }
                                    td.textContent = formateddate;
                                    td.setAttribute("value", formateddate);
                                    
                                    $(tr).append(td);
                                    return;
                                }
                                let vinput = $('<input type="text" class="form-control tablecontrol control styled zebra" />');
                                vinput.id = column.name;
                                vinput.attr('tabindex', tabindex);
                                vinput.attr('columnname', column.name);
                                if (column.readonly) {
                                    vinput.attr('readonly', '');
                                    vinput.attr('tabindex', -1);
                                }

                                let formateddate = '';
                                if (item[column.name] != '') {
                                    formateddate = $.datepicker.formatDate('dd.mm.yy', new Date(parseInt((item[column.name]).toString().substr(6))));
                                }
                                vinput.attr('oldvalue', formateddate);
                                vinput.val(formateddate);
                                vinput.addClass(column.name);
                                $(td).html(vinput);
                                $(tr).append(td);
                                plugin.tbody.append(tr);
                            }
                            else if (column.datatype == 'fileUpload') {
                                let vinputgroup = $(`<form action="file-echo2.php" method="post" enctype="multipart/form-data">
                                                <input class= "filestyle" id = "fileUpload`+ item["ID"] + `" type = "file"  OnDrop = "OnUpload(this)" accept=".docx" />
                                                <div id="uploadProgress" style="display:none">
                                                    <div class="progress">
                                                        <div class="progress-bar" role="progressbar" style=" height: 20px" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
                                                    </div>
                                                </div>
                                                                </form>`);
                                $(td).append($(vinputgroup));
                                tr.append(td);
                                plugin.tbody.append(tr);
                            }
                            else if (column.datatype == 'textarea'){
                                if (column.readonly) {
                                    td.textContent = item[column.name];
                                    td.setAttribute("value", item[column.name]);
                                    tr.append(td);
                                    return;
                                }
                                let vinput = $('<textarea>');
                                $(vinput).css({ border: "none" });
                                /*if (column.datatype == 'textarea') {
                                    vinput = $('<textarea onkeyup="textAreaAdjust(this)" style="heigth:1px">');
                                }*/
                                vinput.id = column.name;
                                vinput.addClass('form-control control tablecontrol');
                                vinput.attr('tabindex', tabindex);
                                vinput.attr('columnname', column.name);
                                vinput.attr('placeholder', column.title);
                                if (column.readonly) {
                                    vinput.attr('readonly', '');
                                    vinput.attr('tabindex', -1);
                                }
                                if (column.maxLength) {
                                    vinput.attr('maxLength', column.maxLength);
                                }
                                vinput.attr('oldvalue', item[column.name]);
                                vinput.val(item[column.name]);
                                $(td).append(vinput);
                                tr.append(td);
                                plugin.tbody.append(tr);
                            }
                            else if (column.datatype == 'html') {
                                let vhtmlelement = $(column.html);
                                if (options.tableOptions.PKColumn != undefined) {
                                    $(vhtmlelement).attr(options.tableOptions.PKColumn, item[options.tableOptions.PKColumn]);
                                }
                                $(td).append(vhtmlelement);
                                tr.append(td);
                            }
                            else {

                                if (column.readonly) {
                                    if (column.datatype == 'number') {
                                        td.textContent = NumberToString(String(item[column.name]));
                                    } else {
                                        td.textContent = item[column.name];
                                    }
                                   
                                    td.setAttribute("value", item[column.name]);
                                    $(td).addClass('control');
                                    $(td).attr('columnname', column.name);
                                    tr.append(td);
                                    return;
                                }
                               
                               /* //onsole.log(column.datatype);*/
                                let vinput = $('<input>');
                                /*if (column.datatype == 'textarea') {
                                    vinput = $('<textarea onkeyup="textAreaAdjust(this)" style="heigth:1px">');
                                }*/
                                vinput.id = column.name;
                                vinput.addClass('form-controltmp control tablecontrol');
                                vinput.attr('tabindex', tabindex);
                                vinput.attr('columnname', column.name);
                                vinput.attr('placeholder', column.title);
                                vinput.val(item[column.name]);
                                /*console.log(item);
                                console.log(column.name);
                                console.log(item[column.name]);*/
                                if (column.datatype == 'number' /*&& item[column.name] != ''*/) {
                                    $(vinput).numeric({ decimalPlaces: 2, negative: true, decimal: "," });
                                    $(vinput).addClass('number');
                                    let Vrijednost = NumberToString(String(item[column.name]));
                                   /* if (isNaN(Vrijednost)) {
                                        Vrijednost = '';
                                    }*/
                                    vinput.val(Vrijednost);
                                    SetFormatNumberForControl($(vinput));
                                }
                                if (column.readonly) {
                                    vinput.attr('readonly', '');
                                    vinput.attr('tabindex', -1);
                                }
                                if (column.maxLength) {
                                    vinput.attr('maxLength', column.maxLength);
                                }
                                vinput.attr('oldvalue', item[column.name]);
                               
                                $(td).append(vinput);
                                tr.append(td);
                                plugin.tbody.append(tr);
                            }
                        });          
                        if (options.tableOptions.editable) {
                            let tddelete = $('<td>');
                            tddelete.addClass('delete');
                            $(tddelete).append($(plugin.GetDeleteButton()));
                            $(tr).append($(tddelete));
                        }
                        plugin.SetEvents(tr);
                    });


                    if (options.tableOptions.editable) {
                        plugin.CreateNewRow(firstload);
                        $('.zebra').mask('00.00.0000', { placeholder: "__.__.____" });
                    }
                    else {
                        $(plugin.footerdiv).find('tbody').find('input').attr('readonly', '');
                    }
                    
                    if (JSON.parse(data)[0] != undefined) {
                        if (JSON.parse(data)[0]['Total'] != undefined) {
                            plugin.rowsCount = JSON.parse(data)[0]['Total'];
                            $(`.tableinfo.${options.tableOptions.tableCssClass}`).text(`Ukupno:${plugin.rowsCount}`);
                        }
                    } else {
                        $(`.tableinfo.${options.tableOptions.tableCssClass}`).text(`Ukupno:0`);
                        plugin.UkupanBrojStrana = 0;
                        plugin.currentPage = 1;
                    }
                    // #region Fokusiranje na isti slog ako je bio odabran i ako ga ima u podacima
                    if (focusedTrKEY_VALUE != null) {
                       
                        let rowThatWasFocusedBeforeRefresh = $(plugin.table).find("tbody").find(`tr[${plugin.keyfield}=${focusedTrKEY_VALUE}]`);
                        ////onsole.log('focusedTrKEY_VALUE != null');
                        ////onsole.log(rowThatWasFocusedBeforeRefresh.length == 0);
                        ////onsole.log(rowThatWasFocusedBeforeRefresh);
                        if (rowThatWasFocusedBeforeRefresh.length == 0) {
                            //alert($(plugin.table).find("tbody").find('tr.focused').length);
                            if ($(plugin.table).find("tbody").find('tr.focused').length == 0) {
                                plugin.focusedTr = null;
                            }
                            $(plugin.table).find("tbody").find('tr.focused').trigger("click");
                        } else {
                            rowThatWasFocusedBeforeRefresh.trigger("click");
                        }
                    }
                    //#endregion
                    plugin.UpdatePager();
                    $(`.SpinTable.${plugin.tableCssClass} > thead > tr > th.columnhidden`).hide();
                    if (plugin.afterSetData) {
                        plugin.afterSetData();
                    }
                    if (afterSetData) {
                        afterSetData();
                    }
                    $(plugin.table).unblock();
                    let t2 = performance.now();
                    //onsole.log('SetData duration: ' + (t2 - t1) + ' ms');
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    $(plugin.table).unblock();
                    swal({
                        title: "Greška kod prikupljanja podataka",
                        text: xhr.responseText,
                        icon: "warning",
                        dangerMode: true,
                    }).then(function (result) {
                        plugin.tbody.append(xhr.responseText);
                        //location.reload();
                    });
                }
            });
        };
        this.SetCardView = function (firstload = false, afterSetData = null) {

            let tabindex = 1000;
            let t1 = performance.now();
            // #region Ključ fokusiranog sloga da ga ponovo fokusiramo ako ga ima nakon prikupljanja podataka
            let focusedTrKEY_VALUE = null;
            if (plugin.focusedTr != null && plugin.focusedTr != undefined && plugin.keyfield != null && plugin.keyfield != undefined) {
                focusedTrKEY_VALUE = $(plugin.focusedTr).attr(plugin.keyfield);//da fokusiramo isti slog nakon refresha
            }
            // #endregion
            if (plugin.tbody == null) {
                plugin.tbody = $('<tbody>');
                $(plugin.table).append(plugin.tbody);
            }
            else {
                plugin.tbody = $(plugin.table).find('tbody');
            }
            $(plugin.tbody).empty();
            $(plugin.table).find('thead').hide();
            $(plugin.table).block();
            $(".blockUI.blockMsg.blockElement").css({ "left": "0px", "top": "0px", "width": "150px" });
            $(".blockUIicon.fas.fa-spinner.fa-spin,.blockUItext").css({ "font-size": "20px" });
            // #region Pageing i filer podaci
            let vfilter = {};
            $.each(options.tableOptions.columnModel, function (i, column) {//loop columns
                let input = $(plugin.table).find('.filtertr').find('[columnname="' + column.name + '"]');
                let val = input.val();
                if (column.datatype == 'checkbox') {
                    val = $(plugin.table).find('.filtertr').find('[columnname="' + column.name + '"]').attr('value');
                }
                if (val != '') {
                    $.extend(vfilter, { [column.name]: val });
                }
                if (column.calculatesum == 1) {
                    $(plugin.table).removeAttr(column.name + '_SUM');
                }

            });
            let vdata = [{
                currentPage: plugin.currentPage,
                rowsPerPage: plugin.rowsPerPage,
                sortfield: plugin.sortfield,
                sortorder: plugin.sortorder,
                filter: vfilter,
            }];
            // #endregion
            if (plugin.CustomParameters != undefined) {
                vdata.push(plugin.CustomParameters);
            }
            vdata = { gridparams: JSON.stringify(vdata) };
            if (plugin.sendGridParams === false) {
                vdata = null;
            }
            let t3 = performance.now();
            //onsole.log('SetData do ajaxa: ' + (t3 - t1) + ' ms');
            $.ajax({
                url: options.tableOptions.dataurl,
                dataType: 'json',
                data: vdata,
                //async: false,
                //data: [{ gridparams: JSON.stringify(vdata),other: JSON.stringify(plugin.CustomParameters) }],
                success: function (data) {
                    // #region Provjera da li je istekla sesija ili nema prava
                    if (String(data).indexOf('Nemate') >= 0) {
                        swal({ title: "Poruka", text: data, dangerMode: true, icon: "error" });
                        location.reload();
                        return;
                    }
                    if (data.Successed == 0) {
                        swal({ title: "Poruka", text: data.Message, dangerMode: true, icon: "error" });
                        return;
                    }
                    //#endregion
                    plugin.tbody.empty();
                    plugin.vdata = data;
                    data = JSON.stringify(data);
                    // #region Ako nema podataka 
                    if (data != '') {
                        if (JSON.parse(data).length > 0) {
                            plugin.UkupanBrojStrana = Math.ceil(JSON.parse(data)[0]['Total'] / plugin.rowsPerPage);

                        } else {
                           /* if (!options.tableOptions.editable) {
                                plugin.AddEmptyRow();
                            }
                            else if (options.tableOptions.editable && plugin.addnewrow === false) {
                                plugin.AddEmptyRow();
                            }*/
                        }
                    }
                    //#endregion
                    $.each(JSON.parse(data), function (i, item) {//loop rows
                        let divCardItem = document.createElement("div");
                        divCardItem.className = "CardItem";
                        $(divCardItem).addClass(options.tableOptions.tableCssClass);
                        let tr_rb = i + 1;
                        $(divCardItem).attr('rb', tr_rb);
                        if (options.tableOptions.PKColumn != undefined) {
                            divCardItem.setAttribute(options.tableOptions.PKColumn, item[options.tableOptions.PKColumn]);
                        }
                        $.each(options.tableOptions.columnModel, function (i, column) {//loop columns
                            let CardLabelAndData = document.createElement("div");
                            $(CardLabelAndData).addClass("CardLabelAndData");
                            $(CardLabelAndData).addClass(options.tableOptions.tableCssClass);
                            $(CardLabelAndData).addClass(column.name);
                            let CardData = document.createElement("div");
                            tabindex = tabindex + 1;
                            CardData.className = "CardData "+column.name;
                            $(CardData).addClass(options.tableOptions.tableCssClass);
                            if (column.width !== undefined) {
                                CardData.style.width = column.width;
                            }
                            CardData.setAttribute("readonly", column.readonly);
                            //CardData.setAttribute("style", "padding: 3px !important");
                            $(CardData).addClass('datatype' + column.datatype);
                            if (column.datatype == 'select') {
                                CardData.textContent = item[column.lookupname];
                                CardData.setAttribute("value", item[column.name]);
                                CardData.setAttribute("Displayvalue", item[column.lookupname]);

                            }
                            else if (column.datatype == 'dateedit') {
                                let formateddate = '';
                                if (item[column.name] != undefined && item[column.name] != '') {
                                    formateddate = $.datepicker.formatDate('dd.mm.yy', new Date(parseInt((item[column.name]).toString().substr(6))));
                                }
                                CardData.textContent = formateddate;
                                CardData.setAttribute("value", formateddate);
                            }
                            else if (column.datatype == 'datetimeedit') {//ovotreba sredit
                                let formateddate = '';
                                if (item[column.name] != '' && item[column.name] != undefined) {
                                    let Datum = new Date(parseInt((item[column.name]).toString().substr(6)));
                                    let Dan = ('0' + Datum.getDate()).slice(-2);
                                    let Mjesec = ('0' + (Datum.getMonth() + 1)).slice(-2);
                                    let Godina = Datum.getFullYear();
                                    formateddate = Dan + '.' + Mjesec + '.' + Godina + ' ' + ('0' + Datum.getHours()).slice(-2) + ':' + ('0' + Datum.getUTCMinutes()).slice(-2);
                                }
                                //td.text(formateddate);
                                CardData.textContent = formateddate;
                                //td.attr('value', formateddate);
                                CardData.setAttribute("value", formateddate);
                            }
                            else if (column.datatype == 'number') {
                                let val = item[column.name];
                                if (val != undefined) {
                                    let formatedval = (val).toLocaleString(
                                        'de-DE',
                                        { minimumFractionDigits: 2 }
                                    );
                                    $(CardData).addClass("number");
                                    CardData.textContent = formatedval;

                                }
                                CardData.setAttribute("value", val);
                                if (column.calculatesum == 1) {

                                    let Vrijednost = 0;
                                    if (item[column.name] != '') {
                                        Vrijednost = parseFloat(item[column.name]);
                                    }
                                    if ($(plugin.table).attr(column.name + '_SUM') == '' || $(plugin.table).attr(column.name + '_SUM') == undefined) {

                                        $(plugin.table).attr(column.name + '_SUM', Vrijednost);
                                    } else {
                                        let Iznos = parseFloat($(plugin.table).attr(column.name + '_SUM'));
                                        $(plugin.table).attr(column.name + '_SUM', Iznos + Vrijednost);
                                    }
                                }
                            }
                            else if (column.datatype == 'checkbox') {
                                let vlabelcheckcontainer = $('<label class="chkcontainer">');
                                let vinput = $('<input type="checkbox" disabled="disabled" class="form-control tablecontrol styled" />');
                                let vcheckmark = $('<span class="checkmark">');
                                vinput.id = column.name;
                                vinput.addClass('form-control checkboxcontrol control');
                                vinput.attr('tabindex', tabindex);
                                vinput.attr('columnname', column.name);
                                let StatusChecked = "";
                                if (item[column.name] == 1 || item[column.name] == "true") {
                                    StatusChecked = "checked";
                                    vinput.attr("checked", '');
                                    CardData.setAttribute("value", "Da");
                                } else {
                                    CardData.setAttribute("value", "Ne");
                                }
                                vinput.attr('oldvalue', StatusChecked);
                                vinput.addClass(column.name);
                                vlabelcheckcontainer.append($(vinput));
                                vlabelcheckcontainer.append($(vcheckmark));
                                $(CardData).append($(vlabelcheckcontainer));
                            }
                            else if (column.datatype == 'html') {
                                let vhtmlelement = $(column.html);
                                if (options.tableOptions.PKColumn != undefined) {
                                    $(vhtmlelement).attr(options.tableOptions.PKColumn, item[options.tableOptions.PKColumn]);
                                }
                                $(CardData).append(vhtmlelement);
                            }
                            else {
                                CardData.textContent = item[column.name];
                                CardData.setAttribute("value", item[column.name]);
                                /*if (item[column.name] != undefined) {
                                    td.setAttribute("DuzinaSadrzaja", item[column.name].length);
                                }*/

                            }
                            if (column.setSpan == '1') {
                                let span = document.createElement("span");
                                $(span).attr("columnname", column.name);
                                $(span).attr("columnvalue", item[column.name]);
                                CardData.prepend(span);

                            }
                            
                            let CardLabel = document.createElement("div");
                            CardLabel.textContent = column.title;
                            $(CardLabel).addClass("CardLabel");
                            $(CardLabel).addClass(options.tableOptions.tableCssClass);
                            $(CardLabel).addClass(column.name);
                            $(CardLabelAndData).append(CardLabel);
                            $(CardLabelAndData).append(CardData);
                            divCardItem.append(CardLabelAndData);
                            plugin.tbody.append(divCardItem);
                        });
                        //plugin.SetEvents(tr);
                    });
                    $(`.SpinTable.${plugin.tableCssClass} > thead > tr > th.columnhidden`).hide();
                    if (plugin.afterSetData) {
                        plugin.afterSetData();
                    }
                    if (afterSetData) {
                        afterSetData();
                    }
                    $(plugin.table).unblock();
                    let t2 = performance.now();
                    //onsole.log('SetData duration: ' + (t2 - t1) + ' ms');
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    $(plugin.table).unblock();
                    swal({
                        title: "Greška kod prikupljanja podataka",
                        text: xhr.responseText,
                        icon: "warning",
                        dangerMode: true,
                    }).then(function (result) {
                        plugin.tbody.append(xhr.responseText);
                        //location.reload();

                    });
                }
            });
        };
        this.SetControl = function (td, i, item, column) {
            if (!options.tableOptions.editable) {
                td.attr('style', 'padding: 3px');
                td.addClass(column.columnname);
                if (column.datatype == 'select') {
                    td.text(item[column.name] + '-' + item[column.lookupname]);
                    td.attr('value', item[column.name]);
                }
                else if (column.datatype == 'dateedit') {
                    let formateddate = '';
                    if (item[column.name] != '') {
                        formateddate = $.datepicker.formatDate('dd.mm.yy', new Date(parseInt((item[column.name]).toString().substr(6))));
                    }
                    td.text(formateddate);
                    td.attr('value', formateddate);
                }
                else {
                    td.text(item[column.name]);
                    td.attr('value', item[column.name]);
                }
            }
            else {
                if (column.datatype == 'select' ) {
                    let vinputgroup = $('<div class="input-group">');
                    let vinput = $('<input Sifra="" class="form-control tablecontrol" placeholder="kucaj za pretragu..." style="width:100%" type="text" />');
                    let vbutton = $('<span class="input-group-addon input-group-addon-combobox" style="cursor:pointer;border:none"><i class="caretDown"></i></span>');
                    vinput.id = column.name;
                    vinput.addClass('form-control control');
                    vinput.attr('tabindex', i);
                    vinput.attr('columnname', column.name);
                    if (column.readonly) {
                        vinput.attr('readonly', '');
                        vinput.attr('tabindex', -1);
                    }
                    vinput.attr('oldsifra', item[column.name]);
                    vinput.attr('sifra', item[column.name]);

                    vinput.val(item[column.name] + '-' + item[column.lookupname]);
                    vinput.attr('oldvalue', item[column.name] + '-' + item[column.lookupname]);
                    vinputgroup.append(vinput);
                    if (options.tableOptions.editable) {
                        vinputgroup.append(vbutton);
                    }
                    vinput.addClass(column.name);
                    vinput.addClass(column.name + i);
                    vinput.addClass('selectcontrol');
                    td.append(vinputgroup);

                    plugin.SetCombo('.' + column.name + i, column.dataurl, column.onChange, column.additionalField, column.additionalValue, column.selectFirstIfOne, column.columns);
                }
                else if (column.datatype == 'checkbox') {
                    let vlabelcheckcontainer = $('<label class="chkcontainer">');
                    let vinput = $('<input type="checkbox" class="form-control tablecontrol styled" />');
                    let vcheckmark = $('<span class="checkmark">');
                    vinput.id = column.name;
                    vinput.addClass('form-control checkboxcontrol control tablecontrol');
                    vinput.attr('tabindex', i);
                    vinput.attr('columnname', column.name);
                    if (column.readonly) {
                        vinput.attr('readonly', '');
                        vinput.attr('tabindex', -1);
                    }
                    let StatusChecked = "";
                    if (item[column.name] == 1) {
                        StatusChecked = "checked";
                        vinput.attr("checked", '');
                    }
                    vinput.attr('oldvalue', StatusChecked);
                    vinput.addClass(column.name);
                    vlabelcheckcontainer.append(vinput);
                    vlabelcheckcontainer.append(vcheckmark);
                    td.append(vlabelcheckcontainer);
                }
                else if (column.datatype == 'dateedit') {
                    let vinput = $('<input type="text" class="form-control control styled zebra tablecontrol" />');
                    vinput.id = column.name;
                    vinput.attr('tabindex', i);
                    vinput.attr('columnname', column.name);
                    if (column.readonly) {
                        vinput.attr('readonly', '');
                        vinput.attr('tabindex', -1);
                    }

                    let formateddate = '';
                    if (item[column.name] != '') {
                        formateddate = $.datepicker.formatDate('dd.mm.yy', new Date(parseInt((item[column.name]).toString().substr(6))));
                    }
                    vinput.attr('oldvalue', formateddate);
                    vinput.val(formateddate);
                    vinput.addClass(column.name);
                    td.append(vinput);
                }
                else {

                    let vinput = $('<input>');
                    /*if (column.datatype == 'textarea') {
                        vinput = $('<textarea onkeyup="textAreaAdjust(this)" style="heigth:1px">');
                    }*/
                    vinput.id = column.name;
                    vinput.addClass('form-controltmp control tablecontrol');
                    vinput.attr('tabindex', i);
                    vinput.attr('columnname', column.name);
                    if (column.readonly) {
                        vinput.attr('readonly', '');
                        vinput.attr('tabindex', -1);
                    }
                    vinput.attr('oldvalue', item[column.name]);
                    vinput.val(item[column.name]);
                    td.append(vinput);

                }
            }
        };
        this.SetEvents = function (ptr) {
            $(ptr).find('.control').on("focus", function (object) {
                $(ptr).removeClass('focused');
                $(ptr).addClass('focused');
                $(this).select();
            });
            $(ptr).find('.checkboxcontrol').on('change', function (object) {
                if ($(object.target).hasClass('changed')) {
                    $(object.target).removeClass('changed');
                }
                else {
                    $(object.target).addClass('changed');
                }
                if ($(object.target).prop('checked')) {
                    $(object.target).attr('checked', 'checked');
                }
                else {
                    $(object.target).removeAttr('checked');
                }
            });
            $(ptr).find('.control').on("blur", function (object) {
               
                if ($(object.target).hasClass('ui-autocomplete-input')) {
                    $(object.target).val($(object.target).attr('oldvalue'));
                }
                setTimeout(function () {
                    let focusedElement = $(':focus');
                    /*if ($('.ui-menu.ui-widget').is(':visible')) {
                        return;
                    }*/
                    let focusedTr = $(focusedElement).closest('tr');
                    let sourceTr = $(object.currentTarget).closest('tr');
                    if (sourceTr.attr("ComboShown") != undefined) {
                        sourceTr.removeAttr("ComboShown");
                        return;
                    }
                   /* console.log('focusedElement:');
                    console.log(focusedElement);
                    console.log('source:');
                    console.log(object.currentTarget);
                   
                    console.log('focusedTr:');
                    console.log(focusedTr);
                   
                    console.log('sourceTr:');
                    console.log(sourceTr);*/
                    if (focusedTr.attr('rb') === sourceTr.attr('rb')) {
                        //console.log('isti row');
                        return;
                    }
                   // console.log(focusedElement);
                    $(ptr).removeClass('focused');
                    ////onsole.log("blur");
                    if ($(document.activeElement).closest('tr').attr('rb') == $(object.target).closest('tr').attr('rb')) {
                        ////onsole.log("blur return");
                        return;
                    }
                    else {
                        if (options.tableOptions.editable) {
                            let ptr = $(object.target).closest('tr');
                            if (plugin.CheckForChanges(ptr)) {
                                ptr.attr('changed', true);
                                plugin.Save(ptr);
                                $(ptr).removeClass('focused');
                            }
                            else {
                                $(ptr).removeClass('invalidtr');
                                $(ptr).find("#nimage").attr("data-original-title", "");
                                $(ptr).find("#nimage").removeClass('fa-exclamation-triangle');
                                $(ptr).find("#nimage").tooltip('destroy');
                                $(ptr).removeAttr('changed');
                            }
                        }
                    }
                    if ($(document.activeElement).hasClass('control')) {
                        $(plugin.table).find('tr').removeClass('focused');
                        $(document.activeElement).closest('tr').addClass('focused');
                    }
                    else {
                        $(plugin.table).find('tr').removeClass('focused');
                    }
                }, 300);
            });

            //escape vraca staru vrijednost kontrole
            $(function () {
                $(ptr).find('.control').keydown(function (e) {
                  
                    // .log('keydown:' + e.keyCode );
                    if (e.keyCode == 27) {//escape
                        //.log('escape pritisnut');
                        let attr = $(this).attr('oldvalue');
                        if (typeof attr !== typeof undefined && attr !== false) {
                            $(this).val($(this).attr('oldvalue'));
                        }
                        //ako je combobox tu koristimo atribut sifru
                        let attr2 = $(this).attr('oldsifra');
                        if (typeof attr2 !== typeof undefined && attr2 !== false) {
                            $(this).attr('sifra', $(this).attr('oldsifra'));
                            $(this).val($(this).attr('oldvalue'));
                        }
                        //e.preventDefault();
                        //e.stopPropagation();
                    } 
                    if ($(e.target).hasClass('selectcontrol')) {
                        $('a.mcacAnchor>span').removeClass('focused');
                         $(`a.mcacAnchor:visible>span:contains("${$(this).val()}")`).first().addClass('focused');
                        //console.log($(this).val());
                        //$(`a.mcacAnchor:visible>span[value="${$(this).val()}"]`).first().addClass('focused');
                        
                    }
                });
            });
            $(ptr).find('.btndelete').on('click', function (object) {
                let IdValue = $(ptr).find('.control[columnname=' + plugin.keyfield + ']').val();
                swal({
                    title: "Da li ste sigurni?",
                    text: "Brisanje!",
                    icon: "warning",
                    buttons: ["NE", "DA"],
                    dangerMode: true,
                }).then(function (result) {
                    if (result) {
                        plugin.Save(ptr, true);
                    }
                });
            });
            $(ptr).on('click', function () {
                if (plugin.focusedTr == ptr) {
                    return;
                }
                //alert("aa");
                if (!$(plugin.table).hasClass('skipNavigacijaTabele')) {
                    $(".SpinTable").removeClass("focused");
                    $(plugin.table).addClass("focused");
                }
              
                $(plugin.table).find('tbody').find('tr').removeClass('focused');
                $(ptr).addClass('focused');
                if (plugin.onFocusChange != null) {
                    plugin.focusedTr = ptr;
                    plugin.onFocusChange(ptr);
                    
                }
                else {
                }
            });
            if (options.tableOptions.editable) {
                $(ptr).find('.zebra').hover(function (object) {
                    if (!$(this).hasClass('dateeditset')) {
                        $(this).Zebra_DatePicker({
                            format: 'd.m.Y',
                            readonly_element: false
                        });
                        $(this).addClass('dateeditset');
                    }
                });
                $(ptr).find('.Zebra_DatePicker_Icon').attr('tabindex', '-1');
                //$(ptr).find('.zebra').mask('00.00.0000', { placeholder: "__.__.____" });
            }
            else {
             
                $(ptr).dblclick(function () {
                    if (plugin.onDblClick != null) {
                        plugin.onDblClick(ptr);
                    }
                });
            }
        };
        this.CheckForChanges = function (ptr) {
            //.log('checkingchanges');
            //.log(ptr);
            let result = false;
            $(ptr).find('.control').each(function (a) {
                //console.log($(this).attr('readonly'));
                if ($(this).attr('readonly') != undefined) {
                    return;
                }
                if ($(this).attr('type') == 'checkbox') {
                    if ($(this).hasClass('changed')) {
                        result = true;
                    }
                }
                else if ($(this).hasClass('selectcontrol')) {
                    if ($(this).attr('sifra') != $(this).attr('oldsifra')) {
                        //onsole.log(this);
                        result = true;
                        //onsole.log($(this).attr('sifra') + ',' + $(this).val() + ',' + $(this).attr('oldvalue') );
                    }
                }
                else if ($(this).hasClass('number')) {
                    if (NumberToString($(this).val()) != NumberToString($(this).attr('oldvalue'))) {
                        //onsole.log(this);
                        result = true;
                        //onsole.log($(this).attr('sifra') + ',' + $(this).val() + ',' + $(this).attr('oldvalue') );
                    }
                }
                else {
                    //.log($(this).attr('columnname') + ',' + $(this).val() + ',' + $(this).attr('oldvalue'));
                    if ($(this).val() != $(this).attr('oldvalue')) {
                        //onsole.log(this);
                        result = true;
                        //onsole.log($(this).attr('id') + ',' + $(this).val() + ',' + $(this).attr('oldvalue') );
                    }

                }
            });
            
            return result;
        }
        this.CreateNewRow = function (setFocus = false) {
            if (!plugin.addnewrow && plugin.addnewrow!=undefined) {
                return;
            }
            $(plugin.table).find('.newrow').attr('class', 'editrow');
            //var rb = -1;
            let tr = $('<tr class="newrow" rb="-1"></tr>');
            let trinfo = $('<td class="infocolumn"><span id="nimage" class="tableIconNew" data-toggle="tooltip" data-html="true" data-placement="top"></span></td>');
            tr.append(trinfo);
            $.each(options.tableOptions.columnModel, function (i, column) {//loop columns
                let td = $('<td>');
                td.addClass(column.name);
                td.addClass(options.tableOptions.tableCssClass);
                let tabindex = i * 10000;
                td.attr('readonly', column.readonly);
                if (column.datatype == 'select') {
                    let vinputgroup = $('<div class="input-group input-group-combobox">');
                    let vinput = $('<input Sifra="" class="form-control tablecontrol" placeholder="kucaj za pretragu..." style="width:100%" type="text" />');
                    let vbutton = $('<span class="input-group-addon input-group-addon-combobox" style="cursor:pointer"><i class="caretDown"></i></span>');
                    vinput.id = column.name;
                    vinput.addClass('form-control control');
                    vinput.attr('tabindex', tabindex);
                    vinput.attr('columnname', column.name);
                    if (column.readonly) {
                        vinput.attr('readonly', '');
                        vinput.attr('tabindex', -1);
                    }
                    vinput.attr('oldsifra', '');
                    vinput.attr('sifra', '');
                    vinput.attr('oldvalue', '');
                    vinputgroup.append(vinput);
                    vinputgroup.append(vbutton);

                    vinput.addClass(column.name);
                    vinput.addClass(column.name + i);
                    vinput.addClass('selectcontrol');
                    td.append(vinputgroup);
                    tr.append(td);
                    plugin.tbody.append(tr);
                    plugin.SetCombo('.' + column.name + i, column.dataurl, column.onChange, column.additionalField, column.additionalValue, column.selectFirstIfOne, column.columns);
                }
                else if (column.datatype == 'checkbox') {
                    let vlabelcheckcontainer = $('<label class="chkcontainer">');
                    let vinput = $('<input type="checkbox" class="form-control tablecontrol styled" />');
                    let vcheckmark = $('<span class="checkmark">');
                    vinput.id = column.name;
                    vinput.addClass('form-control control');
                    vinput.attr('tabindex', tabindex);
                    vinput.attr('columnname', column.name);
                    if (column.readonly) {
                        vinput.attr('readonly', '');
                        vinput.attr('tabindex', -1);
                    }
                    let StatusChecked = "";
                    vinput.attr('oldvalue', StatusChecked);
                    vinput.addClass(column.name);
                    vinput.addClass('checkboxcontrol');
                    vlabelcheckcontainer.append(vinput);
                    vlabelcheckcontainer.append(vcheckmark);
                    td.append(vlabelcheckcontainer);
                    tr.append(td);
                    plugin.tbody.append(tr);
                }
                else if (column.datatype == 'dateedit') {
                    let vinput = $('<input type="text" class="form-control control styled zebra tablecontrol" />');
                    vinput.id = column.name;
                    vinput.attr('tabindex', tabindex);
                    vinput.attr('columnname', column.name);
                    if (column.readonly) {
                        vinput.attr('readonly', '');
                        vinput.attr('tabindex', -1);
                    }
                    vinput.attr('oldvalue', '');
                    vinput.val('');
                    vinput.addClass(column.name);
                    td.append(vinput);
                    tr.append(td);
                    plugin.tbody.append(tr);
                }
                else if (column.datatype == 'html') {
                    let vhtmlelement = $(column.html);
                    if (options.tableOptions.PKColumn != undefined) {
                        $(vhtmlelement).attr(options.tableOptions.PKColumn, item[options.tableOptions.PKColumn]);
                    }
                    $(td).append(vhtmlelement);
                    tr.append(td);
                }
                else if (column.datatype == 'textarea') {
                    if (column.readonly) {
                        tr.append(td);
                        return;
                    }
                    let vinput = $('<textarea>');
                    vinput.attr('oldvalue', '');
                    $(vinput).css({ border: "none" });
                    /*if (column.datatype == 'textarea') {
                        vinput = $('<textarea onkeyup="textAreaAdjust(this)" style="heigth:1px">');
                    }*/
                    vinput.id = column.name;
                    vinput.addClass('form-control control tablecontrol');
                    vinput.attr('tabindex', tabindex);
                    vinput.attr('columnname', column.name);
                    vinput.attr('placeholder', column.title);
                    if (column.readonly) {
                        vinput.attr('readonly', '');
                        vinput.attr('tabindex', -1);
                    }
                    if (column.maxLength) {
                        vinput.attr('maxLength', column.maxLength);
                    }
                    $(td).append(vinput);
                    tr.append(td);
                    plugin.tbody.append(tr);
                }
                else {
                    let vinput = $('<input>');
                    vinput.id = column.name;
                    vinput.attr('class', 'form-control control tablecontrol');
                    vinput.attr('tabindex', tabindex);
                    vinput.attr('columnname', column.name);
                    vinput.attr('placeholder', column.title);
                    if (column.datatype == 'number') {
                        $(vinput).numeric({ decimalPlaces: 2, negative: true, decimal: "," });
                        $(vinput).addClass('number');
                        SetFormatNumberForControl($(vinput));
                    }
                    if (column.readonly) {
                        vinput.attr('readonly', '');
                        vinput.attr('tabindex', -1);
                    }
                    if (column.maxLength) {
                        vinput.attr('maxLength', column.maxLength);
                    }
                   
                    vinput.attr('oldvalue', '');
                    if (column.defaultValue != undefined) {
                        vinput.val(column.defaultValue);
                        vinput.attr('oldvalue', column.defaultValue);
                    }
                    td.append(vinput);
                    tr.append(td);
                }
               
            });
            let tddelete = $('<td class="delete"></td>');
            tddelete.append(plugin.GetDeleteButton());
            tr.append(tddelete);
            plugin.tbody.append(tr);
            if (setFocus) {
                tr.find('.control[tabindex=1]').focus();
            }
            tr.addClass('focused');
            plugin.SetEvents(tr);
            //skroluj parent element tabele do dna
            let scroll = $(plugin.table).parent();
            scroll.animate({ scrollTop: scroll.prop("scrollHeight") });

        };
        this.Save = function (ptr, pdelete = false) {
            if (!plugin.Validate(ptr)) {
                return;
            }
            if (options.tableOptions.saveurl == "") {
                swal({ title: "Poruka", text: "Nije definisana funkcija za snimanje", dangerMode: true, icon: "error" });
                return;
            }
            let vAction = '';
            if ($(ptr).hasClass('newrow')) {
                vAction = 'new';
            }
            else {
                vAction = 'edit';
            }
            if (pdelete) {
                vAction = 'delete';
            }
            let keycolumnname = options.tableOptions.columnModel.find((o) => { return o['key'] === true }).name;
            let keycolumnvalue = $(ptr).attr(keycolumnname);
            //console.log(keycolumnvalue);
            let parametri =
            {
                __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
                pAction: vAction
            };
            $.extend(parametri, { [keycolumnname]: keycolumnvalue });
            $(ptr).find('.control').each(function (i, control) {
                //onsole.log($(control).prop("tagName"));
                let columnname = $(control).attr('columnname');
                let value = null;
                if ($(control).hasClass('selectcontrol')) {
                    value = $(control).attr('sifra');
                }
                else if ($(control).hasClass('checkboxcontrol')) {
                    if ($(control).prop('checked')) {
                        value = 1;
                    }
                    else {
                        value = 0;
                    }
                }
                else if ($(control).prop("tagName") == 'TD')
                {
                    value = $(control).attr('value');
                }
                else {
                    value = $(control).val();
                }
                if ($(control).hasClass('number')) {
                    value = StringToNumber(value);
                }
                $(ptr).attr(columnname, value);
                $.extend(parametri, { [columnname]: value });
            });
            $.ajax({
                url: options.tableOptions.saveurl,
                type: 'POST',
                data: parametri,
                success: function (data) {
                    if (data.Successed == '1') {
                        // $(ptr).find(".infocolumn").attr("class", "fas fa-check-square");
                        if (vAction == 'delete') {
                            $(ptr).remove();
                            swal({ title: "Poruka", text: data.Message, dangerMode: false, icon: "success" });
                            return;
                        }
                        plugin.AnaimirajTr(ptr);
                        $(ptr).removeAttr('changed');
                        $(ptr).removeClass('invalidtr');
                        let tooltip = $(ptr).find("#nimage.fas");
                        if (tooltip != null && tooltip != undefined) {
                            try {
                                $(tooltip).tooltip('destroy');
                            }
                            catch (err) {
                                console.log('tooltip destroy error');
                            }
                            
                        }
                        if (vAction == 'new') {
                            $.each(options.tableOptions.columnModel, function (i, column) {
                                let control = $(ptr).find('[columnname="' + column.name + '"]');
                                ////onsole.log(column.name);
                                $(ptr).attr(column.name, data[column.name]);
                                if (column.key) {
                                    //$(ptr).find('[columnname="' + column.name + '"]').val(data[column.name]);
                                    //$(ptr).find('[columnname="' + column.name + '"]').attr('oldvalue', data[column.name]);
                                    $(control).val(data[column.name]);
                                    $(control).attr('oldvalue', data[column.name]);
                                    //$(control).closest('tr').attr(column.name, data[column.name]);

                                }
                                else {
                                    $(control).attr('oldvalue', $(control).val());
                                    $(control).attr('oldsifra', $(control).attr('sifra'));
                                    //$(ptr).find('[columnname="' + column.name + '"]').attr('oldvalue', data[column.name]);
                                }
                            });
                            let maxrb = null;
                            $(plugin.table).find('tr').each(function () {
                                let value = parseFloat($(this).attr('rb'));
                                maxrb = (value > maxrb) ? value : maxrb;
                            });
                            $(ptr).attr('rb', maxrb + 1);

                            plugin.CreateNewRow(true);


                        }
                        if (vAction == 'edit') {
                            $.each(options.tableOptions.columnModel, function (i, column) {
                                let control = $(ptr).find('[columnname="' + column.name + '"]');
                                $(control).attr('oldvalue', $(control).val());
                                if (column.datatype == 'select') {
                                    $(control).attr('oldsifra', $(control).attr('sifra'));
                                }
                                if (column.datatype == 'checkbox') {
                                    $(control).removeClass('changed');
                                }
                            });
                        }
                        if (plugin.afterSaveData) {
                            plugin.afterSaveData(vAction);
                        }
                        //loader_stop2($(ptr).find('.infocolumn'));
                    } else {
                        swal({ title: "Poruka", text: data.Message, dangerMode: true, icon: "error" });
                    }
                    $(ptr).find('#nimage').attr('class', '');
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 404) {
                        swal({ title: "Poruka", text: "Nije pronađena funkcija za snimanje:" + options.tableOptions.saveurl, dangerMode: true, icon: "error" });
                    }
                    if (jqXHR.status == 500) {
                        swal({ title: "Poruka", text: "Greška kod snimanja na serveru. url:" + options.tableOptions.saveurl + ', greška:' + jqXHR.responseText, dangerMode: true, icon: "error" });
                    }
                    //onsole.log(jqXHR);
                }
            });
        };
        this.AnaimirajTr = function (ptr) {
            FlyBuyAlert('Uspješno snimljeno');
            //.log('AnaimirajTr');
            let backgroundColor = "rgb(85, 249, 0,0.0)";
            let oldBackground = $(ptr).css('background-color');
            $(ptr).find("input").css('background', 'transparent');
            $(ptr).animate({
                backgroundColor: backgroundColor
            });
            $(ptr).animate({
                backgroundColor: oldBackground
            });
        };
        this.Validate = function (ptr) {
            //alert('validiraj');
            let ValidacioniText = '';
            $.each(options.tableOptions.columnModel, function (i, column) {
                if (column.required&&column.readonly&&!$(ptr).hasClass('newrow')) {

                    let vrijednost = $(ptr).attr(column.name);
                    //.log(column.name);
                    //.log(vrijednost);
                    if (vrijednost == '' || vrijednost == undefined) {
                        ValidacioniText = ValidacioniText + column.title + ' je obavezan podatak \n';
                    }

                }
                else if (column.required) {

                    let vrijednost = $(ptr).find('[columnname="' + column.name + '"]').val();
                    //.log(column.name);
                    //.log(vrijednost);
                    if (vrijednost == '' || vrijednost == undefined) {
                        ValidacioniText = ValidacioniText + column.title + ' je obavezan podatak \n';
                    }

                }
            });
            if (ValidacioniText == '') {
                $(ptr).find(".infocolumn").attr("data-original-title", "");
                return true;
            }
            else {
                //swal({ title: "Validacija", text: ValidacioniText, dangerMode: true, icon: "error" });
                // return false;
                $(ptr).find("#nimage").attr("data-original-title", ValidacioniText);
                //$(ptr).find("#nimage").attr("data-delay", "{'show':'5000', 'hide':'3000'}");
                $('[data-toggle="tooltip"]').tooltip({ container: 'body' });
                //$('[data-toggle="tooltip"]').tooltip({ container: $(plugin.table).parent().parent()});
                $(ptr).find("#nimage").attr("class", "fas fa-exclamation-triangle");
                $(ptr).addClass("invalidtr");
                $(ptr).find("#nimage").tooltip('show');
                return false;
            }

        };
        this.SetCombo = function (selector, dataurl, onChange, additionalField, additionalValue,selectFirstIfOne,columns) {

            let orginalurl = dataurl;
            //con.sole.log('Postavljanje mcautocomplete, selector:');
            //con.sole.log(selector);
            $(selector).empty();
            if (columns == null) {
                columns = [
                    {
                        name: 'Naziv',
                        width: '100%',
                        valueField: 'Name'
                    }];
            }
            $(selector).mcautocomplete({
                maxShowItems: 10,
                showHeader: true,
                columns: columns,
                keypress: function (event, ui) {
                    //onsole.log(event);
                  
                },
                select: function (event, ui) {
                    if (ui.item.NameForValue != undefined) {
                        this.value = (ui.item ? ui.item.NameForValue : '');
                    } else {
                        this.value = (ui.item ? ui.item.Name : '');
                    }
                    if (ui.item.Id != null || ui.item.Id != undefined) {
                        $(this).attr('sifra', ui.item.Id);
                    }
                    if (ui.item.ID != null || ui.item.ID != undefined) {
                        $(this).attr('sifra', ui.item.ID);
                    }
                    if (ui.item.sifra != null || ui.item.sifra != undefined) {
                        $(this).attr('sifra', ui.item.sifra);
                    }
                    $(this).attr('oldvalue', this.value);
                    $(this).closest('tr').attr('changed', true);
                    if (onChange != undefined) {
                        onChange(ui.item);
                    }
                    return false;
                },
                focus: function (event, ui) {/*problem sa key down i focus-mjenja vrijednost samo fokusirajuci*/
                    if ($('.ui-widget-content:hover').length != 0)//focus fix
                        return;
                    if (ui.item.NameForValue != undefined) {
                        this.value = (ui.item ? ui.item.NameForValue : '');
                    } else {
                        this.value = (ui.item ? ui.item.Name : '');
                    }
                   
                    $(this).attr('sifra', ui.item.Id);
                    $(this).closest('tr').attr('changed', true);
                    return false;
                },
                minLength: 0,
                source: function (request, response) {
                    if (additionalValue != undefined) {
                        //orginalurl = dataurl + '&' + additionalField + '=' + additionalValue();
                        orginalurl = dataurl + '&'+ additionalValue();
                    }
                    let filter = "";
                    filter = $(':focus').val();
                    if ($(':focus').attr('showall') == 'true') {
                        filter = '';
                        $(':focus').removeAttr('showall');
                    }
                    //console.log(selector);
                    $('tr.focused').find(selector).parent().block({ message: 'učitavanje', fadeIn: 0, fadeOut:0 });
                    $.ajax({
                        url: orginalurl,
                        dataType: 'json',
                        data:
                        {
                            filter: filter
                        },
                        success: function (data) {
                            data = JSON.stringify(data);
                            data = JSON.parse(data);
                            let result;
                            if (!data || data.length === 0)
                            {

                            }
                            else
                            {
                                result = data;
                            }
                            //console.log(data);
                            /*console.log(JSON.parse(data).length);
                            console.log(selectFirstIfOne);
                            if (selectFirstIfOne && data.length === 1) {
                                alert('1');
                                $('tr.focused').find(selector).val(data[0]["Naziv"]);
                            }*/
                            $('tr.focused').find(selector).parent().unblock();
                            if (result.Successed == '0') {
                                swal({ title: "Poruka", text: result.Message, dangerMode: true, icon: "error" });
                                return;
                            }
                            response(JSON.parse(result));
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            $('tr.focused').find(selector).parent().unblock();
                            alert(thrownError);
                        }
                    });
                },
                //position: { my : "right top", at: "right bottom" }//
              //  position: { my: "right top", at: "right bottom", of: $(selector) }
                /*pozicija drop downa */
                //position: { my: "left+0 top-10", at: "left+0 bottom+0" }//novo
            });
            $(selector).on('change', function () {
               
                if ($(this).val() == '') {
                    $(this).attr('sifra', '');
                    $(this).attr('oldvalue', '');
                    $(this).closest('tr').attr('changed', true);
                   
                }
            });
            /*$(selector).on('keydown', function (e) {
                try { 
                $('.mcacAnchor.ui-menu-item-wrapper>span').removeClass('hovered');
                    if (e.originalEvent != undefined && e.originalEvent != null && e.originalEvent.code == "ArrowDown" || e.originalEvent.code == "ArrowUp") {
                    $(`.mcacAnchor.ui-menu-item-wrapper>span:contains("${$(this).val()}")`).addClass('hovered');
                }
                } finally {
                    //code for finally block
                }
            });*/
            /*$(selector).on('blur', function () {//ne radi
                .log(this);
                .log('text:' + $(this).val());
                .log($(this).attr('oldvalue'));
                if ($(this).val() == '')
                {
                    $(this).val($(this).attr('oldvalue'));
                    //$(this).closest('tr').attr('changed', true);
                }
            });*/
            //kad se fokusira automatski drop down
            $(selector).on('focus', function () {
               /* let e = jQuery.Event("keydown", { keyCode: 20 });
                $(this).attr('showall', 'true');
                $(this).trigger(e);*/
            });
            plugin.ComboDropDownButton();
        }
        //boostrap select
        this.SetCombo2 = function (selector, url, pval) {
            return $.ajax({
                url: url,
                dataType: 'json',
                data: {},
                success: function (data) {
                    data = JSON.stringify(data);
                    $(selector).empty();
                    $.each(JSON.parse(data), function (i, item) {
                        $(selector).append(new Option(item.Name, item.Id));
                    });
                    $(selector).val(pval);
                    $(selector).selectpicker();
                    $(selector).selectpicker("refresh");
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert(thrownError);
                }
            });
        };
        this.ComboDropDownButton = function () {
            $('.input-group-addon').unbind("click");
            $('.input-group-addon').click(function () {
                //onsole.log("cmbtest");
                //onsole.log($(this).closest("tr"));
                //$(this).closest("tr").trigger("click");
               // $(this).closest("tr").attr("ComboShown","ComboShown");
                $(this).closest('.input-group').find('input[type=text]').focus();
                let e = jQuery.Event("keydown", { keyCode: 20 });
                $(this).closest('.input-group').find('input[type=text]').attr('showall', 'true');
                $(this).closest('.input-group').find('input[type=text]').trigger(e);
            });
        }
        this.GetDeleteButton = function () {
            let deleteButton = $('<button tabindex="-1" class="btn btn-default btndelete" title="Brisanje" style="border: none;"><span class="tableDeleteIcon"></span></button>');
            return $(deleteButton);
        };
        this.SetPager = function () {
            //onsole.log('plugin.PagerSet:' + plugin.PagerSet);
            if (plugin.PagerSet == false)
                return;
            let pager = $(`
<ul class= "pagination ${options.tableOptions.tableCssClass}" style = "float: left;margin-right: 2px;">
    <li><button id="previous" tabindex="-1" class="btn btn-default  tablelbl" style="float: left;"><span class="pagerLeft" style="font-size: 20px;"></span></button></li>
    <li>
        <a style="height:27px">
            <p class="lblStrana tablelbl">Strana</p> <input id="currentPage" tabindex="-1" value="${plugin.currentPage}" class="tablelbl" type="text" />
            <div id="info" class="tablelbl" style="display: inline;"></div>
        </a>
    </li>
    <li><button id="next" tabindex="-1" class=" btn btn-default tablelbl"><span class="pagerRight" style="font-size: 20px;"></span></button></li>
    <li>
        <a style="height:27px;border-radius:0px" >
            <p class="lblPrikazi tablelbl">Prikaži</p> <input id="rowsPerPage" tabindex="-1" value="${plugin.rowsPerPage}" class="tablelbl" type="text" style="width:40px;display: inline-block;" maxlength="3" /><p class="lblZapisa tablelbl">zapisa</p> 
        </a>
    </li>
</ul>
                                                                                    `);
            // $(plugin.table).find('.footercomandcolumn').prepend(pager);
            $(plugin.footerdiv).prepend(pager);
            $(plugin.footerdiv).find('#next').on('click', function () {
                plugin.currentPage = parseInt(plugin.currentPage) + 1;
                plugin.SetData();
            });
            $(plugin.footerdiv).find('#previous').on('click', function () {
                plugin.currentPage = parseInt(plugin.currentPage) - 1;
                plugin.SetData();
            });
            $(plugin.footerdiv).find('#currentPage').on('blur', function (object) {
                plugin.currentPage = $(object.target).val();
                plugin.SetData();
            });
            $(plugin.footerdiv).find('#rowsPerPage').on('blur', function (object) {
                plugin.rowsPerPage = $(object.target).val();
                plugin.voptions.tableOptions.rowsPerPage = $(object.target).val();
                plugin.SetData();
                plugin.SaveSettings();
            });
            plugin.PagerSet = true;

        };
        this.UpdatePager = function () {
            if (plugin.currentPage == 1 || plugin.currentPage == 0) {
                $(plugin.footerdiv).find('#previous').attr('disabled', 'disabled');
            }
            else {
                $(plugin.footerdiv).find('#previous').removeAttr('disabled');
            }
            if (plugin.currentPage == plugin.UkupanBrojStrana) {
                $(plugin.footerdiv).find('#next').attr('disabled', 'disabled');
            }
            else {
                $(plugin.footerdiv).find('#next').removeAttr('disabled');
            }
            $(plugin.footerdiv).find('#info').html(' od ' + plugin.UkupanBrojStrana);
            $(plugin.footerdiv).find('#currentPage').val(plugin.currentPage);
        }
        this.SaveSettings = function () {
            if (plugin.vSaveSettings) {
                localStorage.setItem($(plugin.table).attr('id') + plugin.version, JSON.stringify(plugin.voptions.tableOptions));
            }
        };
        this.SetColResizable = function () {
            /*//onsole.log('set col resizable');
            $(plugin.table).css({ 'width': '100%' });
            $(plugin.table).colResizable({ disable: true });
            $(plugin.table).colResizable();*/
                //.log(plugin.table);
                /*if (!plugin.voptions.tableOptions.SetColResizable) {
                    return;
                }*/
           /* $.each(options.tableOptions.columnModel, function (i, column) {//loop columns
               
                if (column.resizable === true) {
                    //alert('a');
                    $(plugin.table).find('.headertr').find('th.' + column.name).resizable(
                        {
                            animate: false,
                            animateDuration:0,
                            //helper: "ui-resizable-helper",
                           // grid: 50,
                            //ghost: true,
                            autoHide: true  ,
                            handles: 'e',
                            alsoResize: "th." + column.name,
                            minWidth: 100,
                            maxWidth: 800
                        }
                    );
                }
               
            });*/
         };
        this.SetDragableColumns = function () {
            return;//treba sredit
             if (!jQuery().dragtable) {
                 //onsole.log('dragtable jQuery plugin not detected');
                 return;
             }
            if (!plugin.voptions.tableOptions.setDragableColumns) {
                //onsole.log('setDragableColumns false');
                 return;
            }
            ////onsole.log(plugin.table);
            $(plugin.table).dragtable({ excludeFooter: true, maxMovingRows: 1 });

           /* $(plugin.headertable).dragtable({
                maxMovingRows: 0,
                dragaccept: '.dragable',
                dragHandle: '.dragable',
                persistState: function (table) {
                    //onsole.log("a");
                    $(plugin.table).find('.filtertr').show();
                    table.el.find('.headertr').find('th').each(function (i) {
                        $(this).attr('index', i);
                        if ($(this).attr('columnname')) {
                            objIndex = plugin.voptions.tableOptions.columnModel.findIndex((obj => obj.name == $(this).attr('columnname')));
                            plugin.voptions.tableOptions.columnModel[objIndex].index = i;

                        }
                    });
                    plugin.SaveSettings();
                    plugin.voptions.tableOptions.columnModel.sort(function (a, b) {
                        return a.index > b.index;
                    });
                    plugin.SetData();
                    $(plugin.headertable).colResizable({ disable: true });
                    plugin.SetColResizable();
                    $(plugin.headertable).find('thead').remove();
                    $(plugin.headertable).prepend(plugin.headertable.find('thead').clone());
                }
            });*/
        };
        this.GetFocusedValue = function (columnname) {
            if (plugin.focusedTr != null && plugin.focusedTr != undefined) {
                return $(plugin.focusedTr).attr(columnname);
            } else {
                return undefined;
            }
            
        };
        this.AddEmptyRow = function (columnname) {
            let tr = document.createElement("tr");
            let td = document.createElement("td");
            $(td).attr("colspan", 999);
            $(tr).append(td);
            $(td).addClass("NemaPodataka");
            if (plugin.NemaPodatakaText == undefined) {
                plugin.NemaPodatakaText = 'Nema podataka';
            }
            $(td).html(`<span class="iconNemaPodataka"></span>${plugin.NemaPodatakaText}`);
            plugin.tbody.append(tr);

        };
        return this.initialize();
    };
}(jQuery));
function ShowDetails(table) {

    ////onsole.log($(table).find(`tr.focused`));
    let md = $(`<div id="mdTemp" class="modal" data-backdrop="static">`);
    $("#mdTemp").remove();
    let modal_dialog = $(`<div class="modal-dialog modal-lg" style="width:90%;max-width:1300px">`);
    let modal_content = $(`<div class="modal-content">`);
    let modal_header = $(`<div class="modal-header">
                <span class="tableShowDetails" style="opacity:1"></span><h6 class="modal-title">Pregled</h6>
            </div>`);
    let modal_body = $(`
<div class="modal-body" style="padding:10px;padding-top:0px;max-height: 80vh;overflow: auto;">
</div>
`);
    let container = $(`
    <div class="container"></div>
`);
    let modal_headerFooter = $(`
<div class="modal-header">
    <div class="row">
        <button id="btnOdustanimdTemp" class="btn controls" onclick="$('#mdTemp').modal('hide');" style="float: right; margin: 0px 5px 0px 5px;"><span class="iconOdustani"></span>Zatvori</button>
    </div>
</div>`);
    $(md).append(modal_dialog);
    $(modal_dialog).append(modal_content);
    $(modal_content).append(modal_header);
    $(modal_content).append(modal_body);
    $(modal_content).append(modal_headerFooter);
    $(modal_body).append(container);
    $(document.body).append(md);
    let iteration = 1;
    let row = $(`<div class="row"></div>`);
    $.each(table.voptions.tableOptions.columnModel, function (i, column) {//loop columns
        ////onsole.log(column);
        if (column.datatype == "html") {
            return;
        }
        let columnNaziv = $(`<div class="col-md-2">${column.title}</div>`);
        let columnVrijednost = $(`<div class="col-md-4"></div>`);
        let input = null;
        let value = null;
        let td = $(table).find(`tr.focused`).find(`td.${column.name}`);
        if (td.attr(`displayvalue`) != undefined) {
            value=td.attr(`displayvalue`);
        } else {
            value=td.attr(`value`);
        }
        if (value != undefined&& value.length > 50) {
            input = $(`<textarea class="form-control" disabled></textarea>`);
            columnNaziv = $(`<div class="col-md-2">${column.title}</div>`);
            columnVrijednost = $(`<div class="col-md-10"></div>`);
            iteration = iteration + 1;
        } else {
            input = $(`<input class="form-control" disabled>`);
        }
       
       
      
        if (td.is(":visible")) {
           
            if (iteration == 1) {
                container.append(row);
               
                iteration = iteration +1;
            } else {
                container.append(row);
                iteration = 1;
                $(row).unbind();
                row = $(`<div class="row"></div>`);
            }
            //if (i == 1) {
            $(row).append(columnNaziv);
            $(row).append(columnVrijednost);
            $(columnVrijednost).append(input);
            input.val(value);
            if (value.length > 50) {
                textAreaAdjust(input);
            }

        }
    });
    $("#mdTemp").modal('show');
    $("textarea").trigger("input");
    
}
function SetKeyboardNavigation() {
    $(document).unbind("keydown.NavigacijaTabele");
    $(document).bind('keydown.NavigacijaTabele', function (e) {
        if (e.originalEvent == undefined) {
            return;
        }
        if (e.originalEvent.key == "ArrowDown") {
            let nextElement = $('.SpinTable.focused tr.focused').next();
            if ($(nextElement).attr('id') == 'actionTr') {
                nextElement = $(nextElement).next();
            }
            $(nextElement).trigger('click');
        } else if (e.originalEvent.key == "ArrowUp") {
            $('.SpinTable.focused tr.focused').prev().trigger('click');
        }
    });

}
function FlyBuyAlert() {
    console.log('FlyBuyAlert');
}
jQuery(document).on('focus click', 'input', function (e) {
    $(".SpinTable").removeClass("focused");
});

/// <reference path="~/Content/Danijel/DanijelLibrary.js" />
/// <reference path="~/Content/Danijel/DMSFileManager.js" />
/// <reference path="~/Content/Danijel/BPM_Tracking.js" />
function PrikaziReport(pReportName,afterShow) {
    $.ajax({
        url: `/RPT/GetReportParameters?pReportName=${pReportName}`,
        dataType: 'json',
        success: function (data) {
            //console.log(data);
            data = JSON.stringify(data);
            if (data == '') {
                alert('nema parametara');
            }
            let md = $(`<div id="mdTemp" class="modal fade" data-backdrop="static">`);
            $("#mdTemp").remove();
            let modal_dialog = $(`<div class="modal-dialog modal-lg" style="width:90%;max-width:700px">`);
            let modal_content = $(`<div class="modal-content">`);
            let modal_header = $(`<div class="modal-header">
                <span class="iconParametri" style="opacity:1"></span><h6 class="modal-title">Parametri</h6>
            </div>`);
            let modal_body = $(`
<div class="modal-body" style="padding:10px;padding-top:0px;max-height: 80vh;overflow: show;">
</div>
`);
            let container = $(`
    <div class="container"></div>
`);
            let modal_headerFooter = $(`
<div class="modal-header">
    <div class="row">
        <div class="col-xs-4 col-md-3 col-lg-3">
            <button id="btnRPT_GRID_PRIKAZ" class="btn controls reports" onclick="PrikaziGrid('${pReportName}')" style="float: right; margin: 3px 5px 3px 5px;"><span class="iconGrid"></span>Tablarni prikaz</button>
        </div>
        <div class="col-xs-4 col-md-3 col-lg-3">
        <button id="btnRPT_OBRAZAC_PRIKAZ" class="btn controls reports" onclick="PrikaziObrazac('${pReportName}')" style="float: right; margin: 3px 5px 3px 5px;"><span class="iconIzvjestaj"></span>Obrazac</button>
        </div>
        <div class="col-xs-4 col-md-3 col-lg-3">
         <button id="btnRPT_EXCEL" class="btn controls reports" onclick="PrikaziExcel('${pReportName}')" style="float: right; margin: 3px 5px 3px 5px;"><span class="iconExcel"></span>Excel</button>
        </div>
        <div class="col-xs-12 col-md-3 col-lg-3">
            <button id="btnOdustanimdTemp" class="btn controls reports" onclick="$('#mdTemp').modal('hide');" style="float: right; margin: 3px 5px 3px 5px;"><span class="iconOdustani"></span>Zatvori</button>
        </div>
    </div>
</div>`);
            $(md).append(modal_dialog);
            $(modal_dialog).append(modal_content);
            $(modal_content).append(modal_header);
            $(modal_content).append(modal_body);
            $(modal_content).append(modal_headerFooter);
            $(modal_body).append(container);
            $(document.body).append(md);
            console.log(data);
            $.each(JSON.parse(data), function (i, item) {//loop columns
                let row = $('<div class="row"></div>');
                let colInput = $('<div class="col-md-9">');
                let label = '<div class="col-md-3">' + item["Labela"] + '</div>';
                let vinput = $('<input>');
                let ID = item["ID"];
                let Obavezan = item["Obavezan"];
                let DefaultnaVrijednost = item["DefaultnaVrijednost"];
                let Naziv = item["Naziv"];
                let Labela = item["Labela"];
                let Tip = item["Tip"];
                let Readonly = item["Readonly"];
                if (Tip == '') {
                    return false;
                }
                if (Tip == 'txt') {
                    vinput = $(`<input type="text" id="${Naziv}" Labela="${Labela}" Obavezan=${Obavezan} class="form-control">`);
                    $(colInput).append($(vinput));
                }
                else if (Tip == 'DATE') {
                    vinput = $(`
                    <input id="${Naziv}" Labela="${Labela}" Obavezan=${Obavezan} class="form-control zebra reportparameter DATE">`);
                    if (DefaultnaVrijednost == 'danas') {
                        vinput.val(GetCurrentDate());
                    } else if (DefaultnaVrijednost == 'pocetakgodine') {
                        vinput.val('01.01.'+currentYear);
                    }
                    $(colInput).append($(vinput));
                }
                else if (Tip == 'number') {
                    vinput = $(`<input id="${Naziv}" class="form-control number reportparameter">`);
                    $(colInput).append($(vinput));
                }
                else if (Tip == 'select') {
                    vinput = $(`<select id="${Naziv}" field="${Naziv.replace('@','')}" Labela="${Labela}" Obavezan=${Obavezan} class="bootstrap-select selectpicker reportparameter" data-live-search="true" data-width="100%"></select>`);
                    $(colInput).append($(vinput));
                     Cmb(vinput, `/RPT/GetCombo?ReportName=${pReportName}&FieldID=${ID}`, function () {

                    },false,"odaberi...",false);
                    //Cmb(vinput, `/RPT/GetCombo?ReportName=${pReportName}&FieldID=${ID}`,null, false);
                    if (Readonly == 1) {
                        $(vinput).attr('disabled','disabled');
                    }
                }
               
                $(row).append($(label));
                $(row).append($(colInput));
                $(container).append(row);

            });
           
            $("#mdTemp").modal('show');
            
            $('.zebra').Zebra_DatePicker({
                format: 'd.m.Y',
                readonly_element: false
            });
            $('.zebra').mask('00.00.0000', { placeholder: "__.__.____" });
            MaskDateEdit();
            $(".number").numeric({ decimalPlaces: 2, negative: false, decimal: "," });
            if (afterShow != null) {
                afterShow();
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(thrownError);
        }
    });
}
let tmdTempGrid = null;
function PrikaziGrid(pReportName, width ='auto',pafterSetdata=null) {

    let URL = `/RPT/GetData?pReportName=${pReportName}`;
    let Validacija = "";
    $('input.reportparameter,select.reportparameter').each(function (index, data) {
        console.log(this);
        let value = $(this).val();
        let ID = $(this).attr('id');
        URL = URL + `&${ID}=${value}`;
        let Obavezan = $(this).attr('Obavezan');
        let Labela = $(this).attr('Labela');
        if (Obavezan == 'true' && value == '') {
            Validacija = Validacija + Labela + " je obavezno za unos.";            
        }
    });
    if (Validacija != '') {
        swal({ title: "Poruka", text: Validacija, dangerMode: false, icon: "info" });
        return;
    }
    let md = $(`<div id="mdTempGrid" class="modal" data-backdrop="static">`);
    $("#mdTempGrid").remove();
    let modal_dialog = $(`<div class="modal-dialog modal-lg tmdTempGrid" style="width:${width};max-width:90%">`);
    let modal_content = $(`<div class="modal-content tmdTempGrid">`);
    let modal_header = $(`<div class="modal-header">
                <span class="iconGrid" style="opacity:1"></span><h6 class="modal-title">Tablerani prikaz</h6>
            </div>`);
    let modal_body = $(`
<div class="modal-body tmdTempGrid" style="padding:10px;padding-top:0px;max-height: 80vh;overflow: auto;">
</div>
`);
    let container = $(`
    <div class="container tmdTempGrid" >
     <table class="SpinTable evenoddcoloring mdTempGrid" id="tmdTempGrid"></table>
    </div>
`);
    let modal_headerFooter = $(`
<div class="modal-header">
    <div class="row">
        <div class="col-md-3">
            
        </div>
        <div class="col-md-3">
        
        </div>
        <div class="col-md-3">
        
        </div>
        <div class="col-md-3">
            <button id="btnOdustanimdTemp" class="btn controls reports" onclick="$('#mdTempGrid').modal('hide');" style="float: right; margin: 0px 5px 0px 5px;"><span class="iconOdustani"></span>Zatvori</button>
        </div>
    </div>
</div>`);
    $(md).append(modal_dialog);
    $(modal_dialog).append(modal_content);
    $(modal_content).append(modal_header);
    $(modal_content).append(modal_body);
    $(modal_content).append(modal_headerFooter);
    $(modal_body).append(container);
    $(document.body).append(md);
    $("#mdTempGrid").modal('show');
    $("#tmdTempGrid").empty();
   
    let vcolumnmdTempGrid = [
        //{ name: 'id', title: 'id', datatype: 'text', width: '40px' },

    ];
    let URLfields = `/RPT/GetReportFields?pReportName=${pReportName}`;
    $('input.reportparameter,select.reportparameter').each(function (index, data) {
        console.log(this);
        let value = $(this).val();
        let ID = $(this).attr('id');
        URLfields = URLfields + `&${ID}=${value}`;
    });
    $.ajax({
        url: URLfields,
        dataType: 'json',
        async: false,
        success: function (data) {
            console.log(data);
            if (data.Successed == '0') {
                    swal({ title: "Poruka", text: data.Message, dangerMode: false, icon: "success" });
                    return;
            }
            data = JSON.stringify(data);
            if (data == '') {
                alert('nema podataka o kolonama');
            }
            let BrojTekstualnihPolja = 0;
            $.each(JSON.parse(data), function (i, item) {//loop columns
                let Tip = item['Tip'];
                if (Tip == 'String') {
                    BrojTekstualnihPolja = BrojTekstualnihPolja + 1;
                }
            });
            $.each(JSON.parse(data), function (i, item) {//loop columns
                let Naziv = item['Naziv'];
                let Title = Naziv.replace('_',' ');
                let Tip = item['Tip'];
                let TipZaGrid = 'text';
                console.log(Tip);
                if (Tip == 'DateTime') {
                    TipZaGrid = 'dateedit';
                    vcolumnmdTempGrid.push({ name: Naziv, title: Title, datatype: TipZaGrid, width: '90px' });
                }
                else if ( Tip == 'Decimal') {
                    TipZaGrid = 'number';
                    vcolumnmdTempGrid.push({ name: Naziv, title: Title, datatype: TipZaGrid, width: '100px',calculatesum:1 });
                }
                else if (Tip == 'Int32' || Tip == 'Int64') {
                    TipZaGrid = 'int';
                    vcolumnmdTempGrid.push({ name: Naziv, title: Title, datatype: TipZaGrid, width: '40px' });
                }
                else {
                    /*vcolumnmdTempGrid.push({
                        name: Naziv, title: Title, datatype: TipZaGrid, width: `${100 / BrojTekstualnihPolja}%`
                    });*/
                    vcolumnmdTempGrid.push({
                        name: Naziv, title: Title, datatype: TipZaGrid
                    });
                }
                console.log(Tip);
                //if(Tip)

               
            });
            
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(thrownError);
        }
    });
    $.ajax({
        url: `/RPT/GetReportCSS?pReportName=${pReportName}`,
        dataType: 'text',
        async: false,
        success: function (data) {
           
            let CSS = $(`
<style>${data}</style>`
            );
            $(modal_body).append(CSS);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(thrownError);
        }
    });
    console.log(vcolumnmdTempGrid);
    let vtableOptionsdTempGrid = {
        version: 2,
        dataurl: '',
        columnModel: vcolumnmdTempGrid,
        rowsPerPage: 9999999,
        editable: false,
        showfooter: true,
        sortorder: 'desc',
        PKColumn: 'ID',
        sortfield: 'ID',
        PagerVisible: false,
        showFilterRow: false,
        FixedHeaderVisible: false,
        tableCssClass: pReportName,
        addValuesToRow: 1,
        onFocusChange: function (ptr) {

        },
        onDblClick: function (ptr) {


        },
        afterSetData: function () {
            $(tmdTempGrid).find('tfoot').empty();
            if ($(tmdTempGrid).find('th.sum').length == 0) {
                $(tmdTempGrid).find('tfoot').append('<tr><th class="sum" colspan=999 style="text-align: right;"></th></tr>');
            }
            $.each(tmdTempGrid.table.attributes, function (i, attrib) {
                let name = attrib.name;
                let value = attrib.value;
                if (name.indexOf("_sum") >= 0) {
                    let label = name.replace('_sum', ' ukupno');
                    $(tmdTempGrid).find('th.sum').append(`<div class="tableFooterSum ${pReportName} ${name}" style="text-transform: capitalize">${label}:${NumberToString(value)}</div>`);
                }

                
            });
           
            //$(tmdTempGrid).find('th.datatypetext').last().width("100%");
            if (pafterSetdata != null) {
                pafterSetdata();
            }
        }
    }
  
    vtableOptionsdTempGrid.dataurl = URL;
    tmdTempGrid = $('#tmdTempGrid').danijeltable({ tableOptions: vtableOptionsdTempGrid });
   
      
}
function PrikaziObrazac(pReportName) {
    let URL = ``;
    let Validacija = "";
    $('input.reportparameter,select.reportparameter').each(function (index, data) {
        console.log(this);
        let value = $(this).val();
        let ID = $(this).attr('id');
        ID = ID.replace('@','');
        URL = URL + `&${ID}=${value}`;
        let Obavezan = $(this).attr('Obavezan');
        let Labela = $(this).attr('Labela');
        if (Obavezan == 'true' && value == '') {
            Validacija = Validacija + Labela + " je obavezno za unos.";
        }
    });
    if (Validacija != '') {
        swal({ title: "Poruka", text: Validacija, dangerMode: false, icon: "info" });
        return;
    }
    if (pReportName == "RPT_KARTICA_UGOVORA") {
            window.open(`/UGO_Ugovori/RPT_KARTICA_UGOVORA?a=1${URL}`, '_blank');
    }
    else if (pReportName == "RPT_OB2_KARTICA_DOBAVLJACA") {
        window.open(`/RBI_Invoices/RPT_OB2_KARTICA_DOBAVLJACA?a=1${URL}`, '_blank');
    }
    else if (pReportName == "RPT_OB2_ZBIRNO_KUF") {
        window.open(`/RBI_Invoices/RPT_OB2_ZBIRNO_KUF?a=1${URL}`, '_blank');
    }
    else if (pReportName == "RPT_OP_PREGLED_OBAVEZA") {
        window.open(`/RBI_OstalaPlacanja/RPT_OP_PREGLED_OBAVEZA?a=1${URL}`, '_blank');
    }
    else if (pReportName == "RPT_OP_KARTICA_KORISNIKA") {
        window.open(`/RBI_OstalaPlacanja/RPT_OP_KARTICA_KORISNIKA?a=1${URL}`, '_blank');
    }
    else if (pReportName == "RPT_PREGLED_SALDA_PO_KONTIMA") {
        window.open(`/BDG/RPT_PREGLED_SALDA_PO_KONTIMA?a=1${URL}`, '_blank');
    }
    else if (pReportName == "RPT_ANALITICKA_KARTICA_KONTA") {
        window.open(`/BDG/RPT_ANALITICKA_KARTICA_KONTA?a=1${URL}`, '_blank');
    }
    else if (pReportName == "RPT_PREGLED_BUDZETA_PO_ID") {
        window.open(`/BDG/RPT_PREGLED_BUDZETA_PO_ID?a=1${URL}`, '_blank');
    }
    else if (pReportName == "RPT_POCETNO_STANJE") {
        window.open(`/BDG/RPT_POCETNO_STANJE?a=1${URL}`, '_blank');
    }
    else if (pReportName == "RPT_KARTICA_OS_INVESTICIJE_U_TOKU") {
        window.open(`/OS_InvesticijeToku/RPT_KARTICA_OS_INVESTICIJE_U_TOKU?a=1${URL}`, '_blank');
    }
    else if (pReportName == "RPT_OS_INVESTICIJE_U_TOKU_ZBIRNI_PREGLED") {
        window.open(`/OS_InvesticijeToku/RPT_OS_INVESTICIJE_U_TOKU_ZBIRNI_PREGLED?a=1${URL}`, '_blank');
    }
    else if (pReportName == "RPT_KARTICA_OB5") {
        window.open(`/RBI_OB5/RPT_KARTICA_OB5?a=1${URL}`, '_blank');
    }
    else if (pReportName == "RPT_OB5_ZBIRNI_PREGLED") {
        window.open(`/RBI_OB5/RPT_OB5_ZBIRNI_PREGLED?a=1${URL}`, '_blank');
    }
    else if (pReportName == "RPT_BDG_RS_PLAN") {
        window.open(`/BDG_RS_Plan_Master/RPT_BDG_RS_PLAN?a=1${URL}`, '_blank');
    }
    else {
        swal({ title: "Poruka", text: 'Nije implementiran obrazac:' + pReportName, dangerMode: false, icon: "info" });
    }
}
function PrikaziExcel(pReportName) {
    let URL = ``;
    let Validacija = "";
    $('input.reportparameter,select.reportparameter').each(function (index, data) {
        console.log(this);
        let value = $(this).val();
        let ID = $(this).attr('id');
        ID = ID.replace('@', '');
        URL = URL + `&${ID}=${value}`;
        let Obavezan = $(this).attr('Obavezan');
        let Labela = $(this).attr('Labela');
        if (Obavezan == 'true' && value == '') {
            Validacija = Validacija + Labela + " je obavezno za unos.";
        }
    });
    if (Validacija != '') {
        swal({ title: "Poruka", text: Validacija, dangerMode: false, icon: "info" });
        return;
    }
    if (pReportName == "RPT_BDG_PO_FUNC") {
        window.open(`/RPT/RPT_BDG_PO_FUNC?a=1${URL}`, '_blank');
    }
    else if (pReportName == "RPT_BDG_PO_PJ") {
        window.open(`/RPT/RPT_BDG_PO_PJ?a=1${URL}`, '_blank');
    }
    else {
        window.open(`/RPT/ExportExcel?pReportName=${pReportName}${URL}`, '_blank');
        //swal({ title: "Poruka", text: 'Nije implementiran eksport u excel:' + pReportName, dangerMode: false, icon: "info" });
    }
}
function RPT_BDG_IZVRSENJE() {
    let md = $(`<div id="mdTemp" class="modal" data-backdrop="static">`);
    $("#mdTemp").remove();
    let modal_dialog = $(`<div class="modal-dialog modal-lg" style="width:90%;max-width:700px">`);
    let modal_content = $(`<div class="modal-content">`);
    let modal_header = $(`<div class="modal-header">
                <span class="iconParametri" style="opacity:1"></span><h6 class="modal-title">Parametri</h6>
            </div>`);
    let modal_body = $(`
<div class="modal-body" style="padding:10px;padding-top:0px;max-height: 80vh;overflow: show;">
</div>
`);
    let container = $(`
    <div class="container">
     <div class="row">
        <div class="col-md-4">
            <label class="itiLabel">Datum od</label>
        </div>
        <div class="col-md-8">
        <input id="RPT_BDG_IZVRSENJEDatumOD" placeholder="datum prijema" class="form-control zebra">
        </div>
    </div>
     <div class="row">
        <div class="col-md-4">
            <label class="itiLabel">Datum do</label>
        </div>
        <div class="col-md-8">
        <input id="RPT_BDG_IZVRSENJEDatumDO" placeholder="datum prijema" class="form-control zebra">
        </div>
    </div>
     <div class="row">
        <div class="col-md-4">
            <label class="itiLabel">Organizaciona jedinica</label>
        </div>
        <div class="col-md-8">
        <select id="RPT_BDG_IZVRSENJEDepartmentID" class="bootstrap-select selectpicker" data-live-search="true" data-width="100%"></select>
        </div>
    </div>
    </div>
`);
    let modal_headerFooter = $(`
<div class="modal-header">
    <div class="row" style="margin: 0px;">
        <div class="col-md-6">
            
        </div>
        <div class="col-md-3">
        <button id="btnRPT_BDG_IZVRSENJE" class="btn controls"  style="float: right;margin: 1px;"><span class="iconIzvjestaj"></span>Obrazac</button>
        </div>
      
        <div class="col-md-3">
            <button id="btnOdustanimdTemp" class="btn controls" onclick="$('#mdTemp').modal('hide');" style="float: right; margin: 1px;"><span class="iconOdustani"></span>Zatvori</button>
        </div>
    </div>
</div>`);
    $(md).append(modal_dialog);
    $(modal_dialog).append(modal_content);
    $(modal_content).append(modal_header);
    $(modal_content).append(modal_body);
    $(modal_content).append(modal_headerFooter);
    $(modal_body).append(container);
    $(document.body).append(md);
    $('.zebra').Zebra_DatePicker({
        format: 'd.m.Y',
        readonly_element: false
    });
    $('.zebra').mask('00.00.0000', { placeholder: "__.__.____" });
    MaskDateEdit();
    $('#RPT_BDG_IZVRSENJEDatumOD').val(GetFirstDayOfCurrentYear());
    $('#RPT_BDG_IZVRSENJEDatumDO').val(GetCurrentDate());
    //Cmb('#RPT_BDG_IZVRSENJEDepartmentID', '/RBI_Invoices/GetComboDepartments?ParentID=0', null, true, "...sve organizacione jedinice");
    Cmb('#RPT_BDG_IZVRSENJEDepartmentID', '/RBI_Invoices/GetComboDepartments?ParentID=0', function () {
        if (DSH_VIDI_SVE_ORG == '1') {
            $("#RPT_BDG_IZVRSENJEDepartmentID").val('');
            $("#RPT_BDG_IZVRSENJEDepartmentID").removeAttr('disabled');
        } else {
            $("#RPT_BDG_IZVRSENJEDepartmentID").val(currentUserDeptID);
            $("#RPT_BDG_IZVRSENJEDepartmentID").attr('disabled', 'disabled');
        }
        $("#RPT_BDG_IZVRSENJEDepartmentID").selectpicker('refresh');
    }, async = true, odaberitext = "...sve organizacione jedinice");
    $('#btnRPT_BDG_IZVRSENJE').click(function () {
        let DatumOD = $('#RPT_BDG_IZVRSENJEDatumOD').val();
        let DatumDO = $('#RPT_BDG_IZVRSENJEDatumDO').val();
        let DeptID = $('#RPT_BDG_IZVRSENJEDepartmentID').val();
        window.open(`/BDG/RPT_BDG_Ostvarenje?DatumOD=${DatumOD}&DatumDO=${DatumDO}&DeptID=${DeptID}`, '_blank');
    });
    $("#mdTemp").modal('show');
}

let vcolumnModelTracking = [
    { name: 'ID', title: 'ID', key: true, readonly: true, width: '50px' },
    { name: 'ProcesID', title: 'ProcesID', width: '50px' },
    { name: 'AkcijaID', title: 'AkcijaID',  width: '50px' },
    { name: 'InstancaID', title: 'InstancaID',  width: '50px' },
    { name: 'UserID', title: 'UserID',  width: '50px' },
    { name: 'Akcija', title: 'Akcija', datatype: 'text', width: '200px' },
    { name: 'VrijemeText', title: 'Vrijeme', datatype: 'text', width: '120px' },
    { name: 'Description', title: 'Opis promjene', datatype: 'text', width: '100%' },
    { name: 'Korisnik', title: 'Korisnik', datatype: 'text', width: '200px' }

];
let vtableOptionsTracking = {
    version: 2,
    dataurl: '/json/getBPM_TRACKING',
    saveurl: '',
    columnModel: vcolumnModelTracking,
    rowsPerPage: 999,
    editable: false,
    showfooter: true,
    sortorder: 'asc',
    sortfield: 'ID',
    tableCssClass: "BPM_Tracking",
    SaveSettings: false,
    SetColResizable: true,
    ColResizable: { disabledColumns: [0] },
    SetDragableColumns: true,
    PagerVisible: true,
    showFilterRow: false,
    FixedHeaderVisible: false,
    onFocusChange: function (ptr) {
    },
    onDblClick: function (ptr) {
    }
};
let tBPM_Tracking = null;
let ProcesIDTracking = null;
let InstancaIDTracking = null;
function PrikaziTracking(pProcesID, pInstancaID) {
    if (pProcesID == null || pInstancaID == null) {
        swal({ title: "Poruka", text: "Potrebno je označiti slog za prikaz", dangerMode: true, icon: "error" });
        return;
    }
    tBPM_Tracking = null;
    ProcesIDTracking = pProcesID;
    InstancaIDTracking = pInstancaID;
    if (tBPM_Tracking == null) {
        vtableOptionsTracking.dataurl = `/json/getBPM_TRACKING?ProcesID=${ProcesIDTracking}&InstancaID=${InstancaIDTracking}`;
        $('#tBPM_Tracking').empty();
        tBPM_Tracking = $('#tBPM_Tracking').danijeltable({ tableOptions: vtableOptionsTracking });
    } else {
        tBPM_Tracking.voptions.tableOptions.dataurl = `/json/getBPM_TRACKING?ProcesID=${ProcesIDTracking}&InstancaID=${InstancaIDTracking}`;
        tBPM_Tracking.SetData();
    }
    $('#ModalDialogBPM_Tracking').modal('show');
}
let vcolumnModelBPM_Akteri = [
    { name: 'ID', title: 'ID', key: true, readonly: true, width: '50px' },
    { name: 'KlijentID', title: 'KlijentID', key: true, readonly: true, width: '50px' },
    { name: 'NazivAktera', title: 'Akter', datatype: 'text', width: '50%' },
    { name: 'UlogaID', title: 'UlogaID', datatype: 'text', width: '0px' },
    { name: 'UlogaNaziv', title: 'Uloga', datatype: 'text', width: '100px' },
    { name: 'JMB', title: 'JMB', datatype: 'text', width: '120px' },
    { name: 'UlicaBroj', title: 'Adresa', datatype: 'text', width: '50%' },
    { name: 'Telefon1', title: 'Telefon', datatype: 'text', width: '100px' },
    { name: 'IDDokumentBroj', title: 'Broj dokumenta', datatype: 'text', width: '100px' },
    { name: 'BrojRjesenja', title: 'Broj rješenja', datatype: 'text', width: '100px' },
    { name: 'DatumRjesenja', title: 'Datum rješenja', datatype: 'dateedit', width: '100px' },
    { name: 'BrisanjeAktera', title: '', datatype: 'html', html: '<button class="btn deleteAkter" title="Brisanje" style="border: none;"><span class="tableDeleteIcon"></span></button>', width: '50px' },

];
let vtableOptionsBPM_Akteri = {
    version: 2,
    dataurl: '',
    saveurl: '',
    columnModel: vcolumnModelBPM_Akteri,
    rowsPerPage: 100,
    editable: false,
    showfooter: true,
    sortorder: 'asc',
    sortfield: 'ID',
    tableCssClass: "BPM_Akteri",
    SaveSettings: false,
    SetColResizable: true,
    ColResizable: { disabledColumns: [0] },
    SetDragableColumns: true,
    PagerVisible: true,
    showFilterRow: false,
    FixedHeaderVisible: false,
    addValuesToRow:true,
    onFocusChange: function (ptr) {
        focusedTrBPM_Akteri = ptr;
        $("#btnAkteriEditAkter,#btnAkteriEditSubject").removeAttr("disabled");
    },
    onDblClick: function (ptr) {
    },
    afterSetData: function () {
        $('#tBPM_Akteri').children('tbody').children('tr:first').trigger('click');
        PostaviDeleteEvent();
        if ($("#cmbAkter") != null || $("#cmbAkter") != undefined) {//osvježi combo aktera ako postoji i ako je vidljiv
            if ($("#cmbAkter").is(':visible')) {
                CmbAkteri('#cmbAkter', `/json/getAkteri?ProcesID=${ProcesID == null ? -1 : ProcesID}&InstancaID=${InstancaID == null ? -1 : InstancaID}`);
            }
        }
        if (vshowBrojRjesenjaDatumRjesenja) {
            $('.row.BrojRjesenja.DatumRjesenja,.BPM_Akteri.BrojRjesenja,.BPM_Akteri.DatumRjesenja').show();
        }
        else {
            $('.row.BrojRjesenja.DatumRjesenja,.BPM_Akteri.BrojRjesenja,.BPM_Akteri.DatumRjesenja').hide();
        }
     
    }
};
let ProcesIDBPM_Akteri = null;
let tBPM_Akteri = null;
let BPM_InstancaIDBPM_Akteri = null;
let focusedTrBPM_Akteri = null;
let Action = 0;
let vshowBrojRjesenjaDatumRjesenja = false;
SetAkteriEvents();
function SetAkteriEvents() {
    $("#btnAkteriEditAkter,#btnAkteriEditSubject").attr("disabled","disabled");
    $("#btnOdustaniBPM_Akteri").click(function () {
        $('#ModalDialogBPM_Akteri').modal('hide');
    });
    $("#btnOdustaniBPM_AkteriEdit").click(function () {
        $('#ModalDialogBPM_AkteriEdit').modal('hide');
    });
    $("#btnAkteriEditSubject").click(function () {
        let KlijentID = $(focusedTrBPM_Akteri).find('td.KlijentID').attr('value');
        EditSubject(KlijentID, function () {
            tBPM_Akteri.SetData();
        });
    });
    $("#btnSnimiBPM_AkteriEdit").click(function () {
        $('*').removeClass('invalid');
        let ValidacionaPoruka = "";
        let AkterID = $('#cmbAkteri').attr('sifra');
        let UlogaID = $('#cmbAkteriUloge').val();
        let BrojRjesenja = $('#BrojRjesenjaModalDialogBPM_AkteriEdit').val();
        let DatumRjesenja = $('#DatumRjesenjaModalDialogBPM_AkteriEdit').val();
        if (AkterID == '' || AkterID == undefined) {
            ValidacionaPoruka = ValidacionaPoruka + "Akter je obavezan\n";
            $('#cmbAkteri').addClass("invalid");
        }
        if (UlogaID == '') {
            ValidacionaPoruka = ValidacionaPoruka + "Uloga je obavezna\n";
            $('#cmbAkteriUloge').addClass("invalid");
        }
        if (ValidacionaPoruka != "") {
            swal({ title: "Validacija unosa", text: ValidacionaPoruka, html: true, dangerMode: true, icon: "error" });
        }
        else {
            let parametri =
            {
                __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
            };
            let url = null;
            if (Action == 1) {
                url = `/BPM/BPM/DodajAktera?ProcesID=${ProcesIDBPM_Akteri}&InstancaID=${BPM_InstancaIDBPM_Akteri}&AkterID=${AkterID}&UlogaID=${UlogaID}&BrojRjesenja=${BrojRjesenja}&DatumRjesenja=${DatumRjesenja}`;
            } else {
                let ID = $(focusedTrBPM_Akteri).find('td.ID').attr('value');
                url = `/BPM/BPM/IzmjeniAktera?ID=${ID}&AkterID=${AkterID}&UlogaID=${UlogaID}&BrojRjesenja=${BrojRjesenja}&DatumRjesenja=${DatumRjesenja}`;
            }
            $.ajax({
                url: url,
                dataType: 'json',
                type: "POST",
                data: parametri,
                success: function (data) {
                    if (data.Successed == 0) {
                        swal({ title: "Poruka", text: data.Message, dangerMode: true, icon: "error" });
                    } else {
                        tBPM_Akteri.SetData();
                        $('#ModalDialogBPM_AkteriEdit').modal('hide');
                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert(thrownError);
                }
            });
        }
    });
    $("#btnAkteriAddAkter").click(function () {
        $('*').removeClass('invalid');
        //Cmb('#cmbAkteri', `/json/GetSubjekti`);
        Cmb('#cmbAkteriUloge', `/json/getAkteriUloge?ProcesID=${ProcesIDBPM_Akteri}`);
        PostaviCMB();
        $('#cmbAkteri').val('');
        $('#cmbAkteri').removeAttr('sifra');
        $('#ModalDialogBPM_AkteriEdit').modal('show');
        Action = 1;
    });
    $("#btnAkteriEditAkter").click(function () {
        $('*').removeClass('invalid');
        let KlijentID = $(focusedTrBPM_Akteri).find('td.KlijentID').attr('value');
        let UlogaID = $(focusedTrBPM_Akteri).find('td.UlogaID').attr('value');
        let NazivAktera = $(focusedTrBPM_Akteri).find('td.NazivAktera').attr('value');
        $('#BrojRjesenjaModalDialogBPM_AkteriEdit').val(tBPM_Akteri.GetFocusedValue('BrojRjesenja'));
        $('#DatumRjesenjaModalDialogBPM_AkteriEdit').val(tBPM_Akteri.GetFocusedValue('DatumRjesenja'));
        //Cmb('#cmbAkteri', `/json/GetSubjekti`);
        Cmb('#cmbAkteriUloge', `/json/getAkteriUloge?ProcesID=${ProcesIDBPM_Akteri}`, function () {
            $('#cmbAkteriUloge').val(UlogaID);
            $('#cmbAkteriUloge').selectpicker("refresh");
        });
        PostaviCMB();
        $('#cmbAkteri').val(NazivAktera);
        $('#cmbAkteri').attr('sifra', KlijentID);
        $('#ModalDialogBPM_AkteriEdit').modal('show');
        Action = 2;
    });
    $('#cmbAkteri').focus(function () {
        $('#cmbAkteri').select();
    });
    $("#btnAkteriNoviSubjekt").click(function () {
        NoviSubjekt(subjektAfterSaveDataCallback);
    });
}
function PrikaziBPM_Akteri(pProcesIDBPM_Akteri, pBPM_InstancaIDBPM_Akteri, showDeleteButton, showBrojRjesenjaDatumRjesenja=false) {
    ProcesIDBPM_Akteri = pProcesIDBPM_Akteri;
    BPM_InstancaIDBPM_Akteri = pBPM_InstancaIDBPM_Akteri;
    /*if (tBPM_Akteri == null) {
        vtableOptionsBPM_Akteri.dataurl = `/BPM/BPM/GetDataAkteri?ProcesID=${ProcesIDBPM_Akteri}&InstancaID=${BPM_InstancaIDBPM_Akteri}`;
        $('#tBPM_Akteri').empty();
        tBPM_Akteri = $('#tBPM_Akteri').danijeltable({ tableOptions: vtableOptionsBPM_Akteri });
    } else {
        tBPM_Akteri.voptions.tableOptions.dataurl = `/BPM/BPM/GetDataAkteri?ProcesID=${ProcesIDBPM_Akteri}&InstancaID=${BPM_InstancaIDBPM_Akteri}`;
        tBPM_Akteri.SetData();
    }*/
    vtableOptionsBPM_Akteri.dataurl = `/BPM/BPM/GetDataAkteri?ProcesID=${ProcesIDBPM_Akteri}&InstancaID=${BPM_InstancaIDBPM_Akteri}`;
    $('#tBPM_Akteri').empty();
    tBPM_Akteri = $('#tBPM_Akteri').danijeltable({ tableOptions: vtableOptionsBPM_Akteri });
    vshowBrojRjesenjaDatumRjesenja = showBrojRjesenjaDatumRjesenja;
    
    $('#ModalDialogBPM_Akteri').modal('show');
   

}
function subjektAfterSaveDataCallback(ID, Naziv) {
    $("#cmbAkteri").val(Naziv);
    $("#cmbAkteri").attr('sifra', ID);
}
function PostaviCMB() {
    let dataurl = `/json/GetSubjekti`;
    $('#cmbAkteri').mcautocomplete({
        maxShowItems: 10,
        showHeader: true,
        columns: [
            {
                name: 'Naziv',
                width: '200px',
                valueField: 'Naziv'
            },
            {
                name: 'Ulica',
                width: '300px',
                valueField: 'UlicaBroj'
            }        ],
        keypress: function (event, ui) {
            console.log(event);
        },
        select: function (event, ui) {
            //this.attr('sifra');
            this.value = (ui.item ? ui.item.Naziv : '');
            $(this).attr('sifra', ui.item.Sifra);
            return false;
        },
        focus: function (event, ui) {/*problem sa key down i focus-mjenja vrijednost samo fokusirajuci*/
         
            if ($('.ui-widget-content:hover').length != 0)//focus fix
                return;
            this.value = (ui.item ? ui.item.Naziv : '');
            $(this).attr('sifra', ui.item.Sifra);
            return false;
        },
        minLength: 0,
        source: function (request, response) {
            let filter = "";
            filter = $(':focus').val();
            if (filter.length < 3) {
                return;
            }
            if ($(':focus').attr('showall') == 'true') {
                filter = '';
                $(':focus').removeAttr('showall');
            }
            $.ajax({
                url: dataurl,
                dataType: 'json',
                data:
                {
                    filter: filter
                },
                success: function (data) {
                    data = JSON.stringify(data);
                    data = JSON.parse(data);
                    let result;
                    if (!data || data.length === 0) {
                    } else {
                        result = data;
                    }
                    response(JSON.parse(result));
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert(thrownError);
                }
            });
        }
    });
}
function PostaviDeleteEvent() {
    $('.deleteAkter').unbind('click');
    $('.deleteAkter').click(function () {
        let ID = $(this).closest('tr').attr('id');
        swal({
            title: "Dali ste sigurni da želite obrisati aktera?",
            text: "Brisanje!",
            icon: "warning",
            buttons: ["NE", "DA"],
            dangerMode: true,
        }).then(function (result) {
            if (result) {
                $.ajax({
                    url: `/BPM/BPM/BrisanjeAktera?ID=${ID}`,
                    dataType: 'json',
                    type: "POST",
                    success: function (data) {
                        if (data.Successed == 0) {
                            swal({ title: "Poruka", text: data.Message, dangerMode: true, icon: "error" });
                        } else {
                            tBPM_Akteri.SetData();
                        }
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert(thrownError);
                    }
                });
            }
        });
    });
}

let vActionRacuni = 0;
let vActionSubjekt = 1;
let vActionClient = 1;
let vKlijentID = null;
let subjektAfterSaveData = undefined;
let tSFR_Racuni = null;
let tSFR_PovezanaLica = null;
let vcolumnModeltSFR_Racuni = [
    { name: 'RacunID', title: 'ID', key: true, readonly: true, width: '60px' },
    { name: 'RacunBanka', title: 'Banka', required: true, width: '450px', datatype: 'select', dataurl: '/json/GetBanke', lookupname: 'RacunBankaNaziv' },
    { name: 'RacunVrsta', title: 'Vrsta', width: '150', required: true, datatype: 'select', dataurl: '/json/GetVrsteRacuna', lookupname: 'RacunVrstaNaziv' },
    { name: 'RacunBroj', title: 'Broj računa', width: '200px', required: true },
    { name: 'RacunPartija', title: 'Partija', width: '200px', required: true },
    { name: 'SistemskiBroj', title: 'Sistemski broj', width: '200px', required: false },
    { name: 'RacunAktivan', index: 6, title: 'Aktivan', required: true, datatype: 'checkbox', width: '70px' },
];
let vtableOptionstSFR_Racuni = {
    version: 2,
    dataurl: '/Subjekti/GetDataSFR_Racuni',
    saveurl: '/Subjekti/SaveSFR_Racuni',
    columnModel: vcolumnModeltSFR_Racuni,
    rowsPerPage: 100,
    editable: false,
    showfooter: false,
    sortorder: 'desc',
    sortfield: 'RacunID',
    tableCssClass: "Racuni",
    SetDragableColumns: false,
    PagerVisible: false,
    showFilterRow: false,
    onFocusChange: function (ptr) {
        PopuniPoljaIzmjeneSFR_Racuni(ptr);
    },
    onDblClick: function (ptr) {

        if (!$("#btnIzmjeniRacun").is(":disabled")) {
            $("#btnIzmjeniRacun").trigger("click");
        }
    }
};
let vcolumnModeltSFR_PovezanaLica = [
    { name: 'VezaID', title: 'ID', key: true, readonly: true, width: '60px' },
    { name: 'VrstaVeze', title: 'Vrsta veze', required: true, width: '350px', datatype: 'select', dataurl: '/json/GetVrsteVeze', lookupname: 'VrstaVezeNaziv' },
    { name: 'Klijent2', title: 'Povezano lice', width: '350px', required: true, datatype: 'select', dataurl: '/json/GetCmbSubjekti', lookupname: 'Klijent2Naziv' },
];
let vtableOptionstSFR_PovezanaLica = {
    version: 2,
    dataurl: '/Subjekti/GetDataSFR_PovezanaLica',
    saveurl: '/Subjekti/SaveSFR_PovezanaLica',
    columnModel: vcolumnModeltSFR_PovezanaLica,
    rowsPerPage: 100,
    editable: true,
    showfooter: false,
    sortorder: 'desc',
    sortfield: 'VezaID',
    tableCssClass: "SFR_PovezanaLica",
    SetDragableColumns: false,
    PagerVisible: false,
    showFilterRow: false,
    onFocusChange: function (ptr) {

    },
    onDblClick: function (ptr) {


    }
};
setEditSubjektiEvents();
function setEditSubjektiEvents() {
    $('#StranoDomace').on('change', function () {
        PostaviStranoDomace();
    });
    $('#FizickoPravno').on('change', function () {
        PostaviFizickiPravni();
    });
    $('#Entitet').on('change', function () {
        let EntitetID = $('#Entitet').val();
        PopuniGradove(EntitetID);

    });
    $('#Grad').on('change', function () {
        let GradID = $('#Grad').val();
        PopuniOpstine(GradID);
    });
    $('#Opstina').on('change', function () {
        let OpstinaID = $('#Opstina').val();
        PopuniMZ(OpstinaID);
    });
    $("#btnNoviRacun").click(function () {
        vActionRacuni = 1;
        $("#RacunBanka").val('');
        $('#RacunBanka').selectpicker("refresh");
        $("#RacunVrsta").val('1');
        $('#RacunVrsta').selectpicker("refresh");
        $("#RacunBroj").val('');
        $("#RacunPartija").val('');
        $("#SFR_RacuniSistemskiBroj").val('');
        $("#RacunAktivan").prop("checked", true);
        $('.editrowRacuni').slideDown(200);
    });
    $("#btnIzmjeniRacun").click(function () {
        if ($("#RacunBanka").val() == '') {
            swal({ title: "", text: "Odaberite račun", html: true, dangerMode: true, icon: "error" });
            return;
        }
        vActionRacuni = 2;
        $('.editrowRacuni').slideDown(200);
    });
    $("#btnSacuvajRacuni").click(function () {
        $('*').removeClass('invalid');
        let ValidacionaPoruka = "";
        if ($("#RacunBanka").val() == '') {
            ValidacionaPoruka = ValidacionaPoruka + "Banka je obavezno polje\n";
            $("#RacunBanka").addClass("invalid");
        }
        if ($("#RacunVrsta").val() == '') {
            ValidacionaPoruka = ValidacionaPoruka + "Vrsta je obavezno polje\n";
            $("#RacunVrsta").addClass("invalid");
        }
        if ($("#RacunBroj").val() == '') {
            ValidacionaPoruka = ValidacionaPoruka + "Broj računa je obavezno polje\n";
            $("#RacunBroj").addClass("invalid");
        }
        if ($("#RacunBroj").val().trim().length != 16) {
            ValidacionaPoruka = ValidacionaPoruka + "Broj računa je mora imati 16 karaktera\n";
            $("#RacunBroj").addClass("invalid");
        }
        if (ValidacionaPoruka != "") {
            swal({ title: "Validacija unosa", text: ValidacionaPoruka, html: true, dangerMode: true, icon: "error" });
        }
        else {
            //Snimi();
            if (vActionRacuni == 1) {
                let RacunAktivan = $("#RacunAktivan").prop("checked") ? "checked" : "";
                let tr = $(`
<tr class="editrow newrow">
                      <td class="infocolumn">
                      <span id="nimage" data-toggle="tooltip" data-html="true" data-placement="top"></span></td>
                      <td class="RacunID" style="padding: 3px !important" value="1"></td>
                      <td class="RacunBanka" style="padding: 3px !important" value="`+ $("#RacunBanka").val() + `">` + $("#RacunBanka  option:selected").text() + `</td>
                      <td class="RacunVrsta" style="padding: 3px !important" value="`+ $("#RacunVrsta").val() + `">` + $("#RacunVrsta  option:selected").text() + `</td>
                      <td class="RacunBroj" style="padding: 3px !important" value="`+ $("#RacunBroj").val() + `">` + $("#RacunBroj").val() + `</td>
                      <td class="RacunPartija" style="padding: 3px !important" value="`+ $("#RacunPartija").val() + `">` + $("#RacunPartija").val() + `</td>
                      <td class="SistemskiBroj" style="padding: 3px !important" value="`+ $("#SFR_RacuniSistemskiBroj").val() + `">` + $("#SFR_RacuniSistemskiBroj").val() + `</td>
                      <td class="RacunAktivan" style="padding: 3px !important">
                        <label class="chkcontainer">
                          <input type="checkbox" disabled="disabled" class="form-control styled checkboxcontrol control RacunAktivan" tabindex="5" columnname="RacunAktivan" oldvalue="" `+ RacunAktivan + `><span class="checkmark"></span>
                        </label>
                      </td>
</tr>
`)
                $(tSFR_Racuni.table).find("td.NemaPodataka").remove();
                $(tSFR_Racuni.table).append($(tr));
                tSFR_Racuni.SetEvents($(tr));
            }
            else if (vActionRacuni == 2) {
                let RacunAktivan = $("#RacunAktivan").prop("checked") ? "checked" : "";
                if (!$(tSFR_Racuni).find('tr.focused').hasClass('newrow')) {
                    $(tSFR_Racuni).find('tr.focused').addClass("updated");
                }
                $(tSFR_Racuni).find('tr.focused').find('.RacunBanka').attr('value', $("#RacunBanka").val());
                $(tSFR_Racuni).find('tr.focused').find('.RacunBanka').text($("#RacunBanka  option:selected").text());
                $(tSFR_Racuni).find('tr.focused').find('.RacunVrsta').attr('value', $("#RacunVrsta").val());
                $(tSFR_Racuni).find('tr.focused').find('.RacunVrsta').text($("#RacunVrsta  option:selected").text());
                $(tSFR_Racuni).find('tr.focused').find('.RacunBroj').attr('value', $("#RacunBroj").val());
                $(tSFR_Racuni).find('tr.focused').find('.RacunBroj').text($("#RacunBroj").val());
                $(tSFR_Racuni).find('tr.focused').find('.RacunPartija').attr('value', $("#RacunPartija").val());
                $(tSFR_Racuni).find('tr.focused').find('.RacunPartija').text($("#RacunPartija").val());
                if (RacunAktivan == "checked") {
                    $(tSFR_Racuni).find('tr.focused').find('.RacunAktivan').find('input[columnName = "RacunAktivan"]').prop("checked", true);
                } else {
                    $(tSFR_Racuni).find('tr.focused').find('.RacunAktivan').find('input[columnName = "RacunAktivan"]').prop("checked", false);
                }
                $(tSFR_Racuni).find('tr.focused').find('.SistemskiBroj').attr('value', $("#SFR_RacuniSistemskiBroj").val());
                $(tSFR_Racuni).find('tr.focused').find('.SistemskiBroj').text($("#SFR_RacuniSistemskiBroj").val());
            }
            $(tSFR_Racuni.table).find("td.NemaPodataka").remove();
            $('.editrowRacuni').slideUp(200);
        }

    });
    $("#btnOdustaniRacuni").click(function () {
        $('*').removeClass('invalid');
        $('.editrowRacuni').slideUp(200);
    });
    $("#btnSacuvajSubjekt").click(function () {
        $('*').removeClass('invalid');
        let ValidacionaPoruka = "";
        /*if ($("#JMB").val() == '') {
            ValidacionaPoruka = ValidacionaPoruka + "JMB je obavezno polje\n";
            $("#JMB").addClass("invalid");
        }
        if ($("#JMB").val().length != 13) {
            ValidacionaPoruka = ValidacionaPoruka + "JMB mora imati 13 karaktera\n";
            $("#JMB").addClass("invalid");
        }*/
        if ($("#FizickoPravno").val() == '') {
            ValidacionaPoruka = ValidacionaPoruka + "Fizički/Pravni je obavezno polje\n";
            $("button[data-id='FizickoPravno']").addClass("invalid");
        }
        if ($("#StranoDomace").val() == null) {
            ValidacionaPoruka = ValidacionaPoruka + "Strani / Domaći je obavezno polje\n";
            $("button[data-id='StranoDomace']").addClass("invalid");
        }
        let Drzava = $("#Drzava").val();
        if (Drzava == '') {
            ValidacionaPoruka = ValidacionaPoruka + "Država je obavezno polje\n";
            $("button[data-id='Drzava']").addClass("invalid");
        }
        if ($("#Entitet").val() == '' && Drzava == 1) {
            ValidacionaPoruka = ValidacionaPoruka + "Entitet je obavezno polje\n";
            $("button[data-id='Entitet']").addClass("invalid");
        }
        if ($("#Grad").val() == '' && Drzava == 1) {
            ValidacionaPoruka = ValidacionaPoruka + "Grad je obavezno polje\n";
            $("button[data-id='Grad']").addClass("invalid");
        }
        if ($("#Opstina").val() == '' && Drzava == 1) {
            ValidacionaPoruka = ValidacionaPoruka + "Opstina je obavezno polje\n";
            $("button[data-id='Opstina']").addClass("invalid");
        }
        if ($("#Ime").val() == '' && $("#FizickoPravno").val() == 'F') {
            ValidacionaPoruka = ValidacionaPoruka + "Ime je obavezno polje\n";
            $("#Ime").addClass("invalid");
        }
        if ($("#Prezime").val() == '' && $("#FizickoPravno").val() == 'F') {
            ValidacionaPoruka = ValidacionaPoruka + "Prezime je obavezno polje\n";
            $("#Prezime").addClass("invalid");
        }
        if ($("#Naziv").val() == '' && $("#FizickoPravno").val() == 'P') {
            ValidacionaPoruka = ValidacionaPoruka + "Naziv je obavezno polje\n";
            $("#Naziv").addClass("invalid");
        }
        if (ValidacionaPoruka != "") {
            swal({ title: "Validacija unosa", text: ValidacionaPoruka, html: true, dangerMode: true, icon: "error" });
        }
        else {
            if ($("#JMB").val() == '') {
                swal({
                    title: "Da li želite unijeti subjekta bez JMB?",
                    text: "JMB validacija!",
                    icon: "warning",
                    buttons: ["NE", "DA"],
                    dangerMode: true,
                }).then(function (result) {
                    if (result) {
                        SnimiSubjekt();
                    }
                });
            }
            else {
                SnimiSubjekt();
            }
           
           
            //SnimiBankovneRacune();
        }

    });
    $("#PDVObveznik").change(function () {
        PostaviPIB();
    });
    $("#JMB").change(function () {
        PostaviPIB();
    });
}
function PopuniGradove(EntitetID, GradID) {
    console.log("1")
    if (EntitetID == '') {
        $("#Grad").attr("disabled", "");
    }
    else {
        let oldval = $("#Grad").val();
        //console.log(oldval);
        Cmb('#Grad', '/json/GetGradovi?EntitetID=' + EntitetID, function () {
            $("#Grad").val(GradID);
            $("#Grad").selectpicker("refresh");
            $("#Grad").removeAttr("disabled");
        }, false);   
    }
    $("#Opstina").val('');
    $("#Opstina").selectpicker("refresh");
    $("#MZ").val('');
    $("#MZ").selectpicker("refresh");
//    $('#Grad').attr('disabled', 'disabled');
}
function PopuniOpstine(GradID, OpstinaID, selector = "#Opstina") {
   
    if (GradID == '') {
        $(selector).attr("disabled", "");
    }
    else {
        $(selector).removeAttr("disabled");
        Cmb(selector, '/json/GetOpstina?GradID=' + GradID, function () {
            $("#Opstina").val(OpstinaID);
            $("#Opstina").selectpicker("refresh");
            $("#MZ").val('');
            $("#MZ").selectpicker("refresh");
        },false);
    }
  
}
function PopuniMZ(OpstinaID, MZID, selector = "#MZ", url = '/json/GetMZ?opstinaID=') {
    console.log('MZID' + MZID);
    if (OpstinaID == '') {
        $(selector).attr("disabled", "");
    }
    else {
        $(selector).removeAttr("disabled");
        Cmb(selector, url + OpstinaID, function () {
            $(selector).val(MZID);
            $(selector).selectpicker("refresh");
        });
    }
}
function PostaviFizickiPravni() {
    if ($('#FizickoPravno').val() == 'F') {
        $('.row.FizickoLice').slideDown(200);
        $('.row.PravnoLice').slideUp(200);
    }
    else if ($('#FizickoPravno').val() == 'P') {
        $('.row.PravnoLice').slideDown(200);
        $('.row.FizickoLice').slideUp(200);
    } else {
        $('.row.FizickoLice').hide();
        $('.row.PravnoLice').hide();
    }
}
function PostaviStranoDomace() {
    if ($('#StranoDomace').val() == 'D') {
        Cmb('#Drzava', '/json/GetDrzava?Domaca=1', function () {
            $("#Drzava").val(1);
            $("#Drzava").selectpicker("refresh");
        },false);
     
        
    }
    else {
        Cmb('#Drzava', '/json/GetDrzava?Domaca=0', function () {
            $("#Drzava").val("");
            $("#Drzava").selectpicker("refresh");
        }, false);
      
      
    }
}
function PopuniPoljaIzmjeneSFR_Racuni(ptr) {
    //console.log('PopuniPoljaIzmjeneSFR_Racuni');
    $("#RacunBanka").val($(ptr).find('td.RacunBanka').attr('value'));
    $("#RacunBanka").selectpicker("refresh");
    $("#RacunVrsta").val($(ptr).find('td.RacunVrsta').attr('value'));
    $("#RacunVrsta").selectpicker("refresh");
    $("#RacunBroj").val($(ptr).find('td.RacunBroj').attr('value'));
    $("#RacunPartija").val($(ptr).find('td.RacunPartija').attr('value'));
    $("#SFR_RacuniSistemskiBroj").val($(ptr).find('td.SistemskiBroj').attr('value'));
    if ($(ptr).find('input[columnName = "RacunAktivan"]').is(":checked")) {
        $("#RacunAktivan").prop("checked", true);
    }
    else {
        $("#RacunAktivan").prop("checked", false);
    }
}
function PostaviPIB() {
    if ($("#PDVObveznik").is(':checked') && $("#FizickoPravno").val()=="P") {
        $("#PIB").val($("#JMB").val().substring(1, $("#JMB").val()));
    } else {
        $("#PIB").val('');
    }
   
}
function SnimiBankovneRacune(KlijentID) {
    $(tSFR_Racuni).find('tr.newrow').each(function () {
        let parametri = {
            __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
            pAction: 1,
            RacunID: $(this).find('td.RacunID').attr('value'),
            RacunKlijent: KlijentID,
            RacunBanka: $(this).find('td.RacunBanka').attr('value'),
            RacunVrsta: $(this).find('td.RacunVrsta').attr('value'),
            RacunBroj: $(this).find('td.RacunBroj').attr('value'),
            RacunPartija: $(this).find('td.RacunPartija').attr('value'),
            RacunAktivan: $(this).find('td.RacunAktivan').find('input[columnname="RacunAktivan"]').is(":checked"),
            SistemskiBroj: $(this).find('td.SistemskiBroj').attr('value'),
        };
        $.ajax({
            url: '/Subjekti/SnimiSFR_Racuni',
            type: 'POST',
            data: parametri,
            success: function (data) {
                if (data.Successed == '1') {

                } else {
                    swal({ title: "Poruka", text: data.Message, dangerMode: true, icon: "error" });
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(jqXHR.responseText);
            }
        });
    });
    $(tSFR_Racuni).find('tr.updated').each(function () {
        let parametri = {
            __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
            pAction: 2,
            RacunID: $(this).find('td.RacunID').attr('value'),
            RacunKlijent: $('#KlijentID').val(),
            RacunBanka: $(this).find('td.RacunBanka').attr('value'),
            RacunVrsta: $(this).find('td.RacunVrsta').attr('value'),
            RacunBroj: $(this).find('td.RacunBroj').attr('value'),
            RacunPartija: $(this).find('td.RacunPartija').attr('value'),
            RacunAktivan: $(this).find('td.RacunAktivan').find('input[columnname="RacunAktivan"]').is(":checked"),
            SistemskiBroj: $(this).find('td.SistemskiBroj').attr('value'),
        };
        $.ajax({
            url: '/Subjekti/SnimiSFR_Racuni',
            type: 'POST',
            data: parametri,
            success: function (data) {
                if (data.Successed == '1') {

                } else {
                    swal({ title: "Poruka", text: data.Message, dangerMode: true, icon: "error" });
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(jqXHR.responseText);
            }
        });
    });
}
function SnimiSubjekt() {
    let obj =
    {
        __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
        pAction: vActionSubjekt,
        KlijentID: vKlijentID,
        JMB: $('#JMB').val(),
        FizickoPravno: $('#FizickoPravno').val(),
        StranoDomace: $('#StranoDomace').val(),
        PDVObveznik: $('#PDVObveznik').is(":checked"),
        PIB: $('#PIB').val(),
        OblikOrganizovanja: $('#OblikOrganizovanja').val(),
        Naziv: $('#Naziv').val(),
        Ime: $('#Ime').val(),
        Prezime: $('#Prezime').val(),
        ImeRoditelja: $('#ImeRoditelja').val(),
        Drzava: $('#Drzava').val(),
        Entitet: $('#Entitet').val(),
        Grad: $('#Grad').val(),
        Opstina: $('#Opstina').val(),
        MZ: $('#MZ').val(),
        PTTMjesto: $('#PTTMjesto').val(),
        UlicaBroj: $('#UlicaBroj').val(),
        Telefon1: $('#Telefon1').val(),
        Telefon2: $('#Telefon2').val(),
        Mobitel: $('#Mobitel').val(),
        Fax: $('#Fax').val(),
        eMail: $('#eMail').val(),
        IDDokumentVrsta: $('#IDDokumentVrsta').val(),
        IDDokumentBroj: $('#IDDokumentBroj').val(),
        Zabiljeska: $('#Zabiljeska').val(),
        Zvanje: $('#Zvanje').val(),
        SistemskiBroj: $('#SistemskiBroj').val()
    };
    // alert('ptr:' + ptr + ',pNoviZapis:' + pNoviZapis + ',pSifraKorisnika:' + pSifraKorisnika + ',pName:' + pName + ',pLastname:' + pLastname + ',pUsername:' + pUsername + ',pEmail:' + pEmail + ',pIdGroup:' + pIdGroup +',pStatus:'+ pStatus)
    $.ajax({
        url: '/Subjekti/Snimi',
        type: 'POST',
        data: obj,
        success: function (data) {
            if (data.Successed == '1') {
                SnimiBankovneRacune(data.KlijentID);
                swal({ title: "Poruka", text: data.Message, dangerMode: false, icon: "success" });
                /*Cmb('#PrimateljID', '/json/GetSubjektiFL', function () {
                    $('#PrimateljID').val(data.KlijentID);
                });*/
                if (subjektAfterSaveData != undefined) {
                    let Naziv = "";
                    if ($("#FizickoPravno").val() == 'F') {
                        Naziv = $("#Ime").val() + " " + $("#Prezime").val();
                    } else {
                        Naziv = $("#Naziv").val();
                    }
                    subjektAfterSaveData(data.KlijentID, Naziv, $("#UlicaBroj").val() );
                }
                $('#ModalDialogSubjekt').modal('hide');
            }
            else {
                swal({ title: "Poruka", text: data.Message, dangerMode: true, icon: "error" });
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(jqXHR.responseText);
        }
    });
}
function EditSubject(pKlijentID, pafterSaveData) {
    $('.modal-title.editsubjekt').text('Izmjena subjekta');
    $("#RacunBroj").numeric({ decimalPlaces: 0, negative: false, decimal: "," });
    if (pKlijentID == null || pKlijentID == undefined || pKlijentID=='') {
        swal({ title: "Izmjena subjekta", text: "Potrebno je odabrati subjekta za izmjenu", html: true, dangerMode: true, icon: "error" });
        return;
    }
    $('#ModalDialogSubjekt').modal('show');
    $(".container.SFR_Subjekti").block();
    $("#btnrptObrazacBr4Subjekt").removeAttr('disabled');
    $("#btnrptObrazacBr4Subjekt").unbind();
    $("#btnrptObrazacBr4Subjekt").click(function () {
        window.open(`/Subjekti/rptObrazacBr4?ID=${pKlijentID}`, '_blank');
    });
    $('*').removeClass('invalid');
    $('.nav-tabs a:first').tab('show');
    vActionSubjekt = 2;//edit
    vKlijentID = pKlijentID;
    subjektAfterSaveData = pafterSaveData;
    Cmb('#FizickoPravno', '/json/GetFizickoPravno', null, false);
    Cmb('#StranoDomace', '/json/GetStranoDomace', null, false);
    Cmb('#OblikOrganizovanja', '/json/GetOblikOrganizovanja', null, false);
    Cmb('#Drzava', '/json/GetDrzava',null,false);
    Cmb('#Entitet', '/json/GetEntitet', null, false);
    Cmb('#PTTMjesto', '/json/GetPTTMjesto');
    Cmb('#IDDokumentVrsta', '/json/GetDokumentVrsta');
    Cmb('#RacunBanka', '/json/GetBanke');
    Cmb('#RacunVrsta', '/json/GetVrsteRacuna');
    PopuniPodatkeSubjekta(pKlijentID);
    $('#tSFR_Racuni').empty();
    vtableOptionstSFR_Racuni.CustomParameters = { 'KlijentID': vKlijentID };
    $('#tSFR_Racuni').find("tbody").empty();
    tSFR_Racuni = $('#tSFR_Racuni').danijeltable({ tableOptions: vtableOptionstSFR_Racuni });
    $(".SpinTable").removeClass("focused");
   
    $('.editrowRacuni').slideUp(200);
    $("#btnSacuvajSubjekt").show();


    // Disable editable fields 
    $('#JMB').removeAttr("disabled");
    $('#Ime').removeAttr("disabled");
    $('#Prezime').removeAttr("disabled");
    $('#ImeRoditelja').removeAttr("disabled");
    $('#IDDokumentBroj').removeAttr("disabled");
    $('#SistemskiBroj').removeAttr("disabled");
    $('#Zvanje').removeAttr("disabled");

    // Dropdown
    $('#FizickoPravno').removeAttr("disabled");
    $('#StranoDomace').removeAttr("disabled");
    $('#Drzava').removeAttr("disabled");
    $('#IDDokumentVrsta').removeAttr("disabled");
    $('#Entitet').removeAttr("disabled");
    $('#Grad').removeAttr("disabled");
    $('#Opstina').removeAttr("disabled");
    $('#MZ').removeAttr("disabled");
    $('#PTTMjesto').removeAttr("disabled");

    $('#FizickoPravno').selectpicker("refresh");
    $("#StranoDomace").selectpicker("refresh");
    $('#Drzava').selectpicker("refresh");
    $("#IDDokumentVrsta").selectpicker("refresh");
    $('#Entitet').selectpicker("refresh");
    $("#Grad").selectpicker("refresh");
    $('#Opstina').selectpicker("refresh");
    $("#MZ").selectpicker("refresh");
    $("#PTTMjesto").selectpicker("refresh");

    $('#UlicaBroj').removeAttr("disabled");
    $('#Mobitel').removeAttr("disabled");
    $('#eMail').removeAttr("disabled");
    $('#Telefon1').removeAttr("disabled");
    $('#Telefon2').removeAttr("disabled");
    $('#Fax').removeAttr("disabled");
    $('#Zabiljeska').removeAttr("disabled");
    $('#tabPovezanaLica').show();
    $('#tabPovezanaLica').attr('title', 'Povezana lica');
    PostaviGridPovezanaLica(pKlijentID);
    $(".container.SFR_Subjekti").unblock();
}

function PopuniPodatkeSubjekta(KlijentID) {
    $.ajax({
        url: `/Subjekti/GetSubjekt?KlijentID=${KlijentID}`,
        dataType: 'json',
        async:false,
        success: function (data) {
            data = JSON.stringify(data);
            data = JSON.parse(data);
            //alert(data[0]["KlijentID"]);
            $("#KlijentID").val(data[0]["KlijentID"]);
            $("#JMB").val(data[0]["JMB"]);
            $("#FizickoPravno").val(data[0]["FizickoPravno"]);
            $("#FizickoPravno").selectpicker("refresh");
            $("#StranoDomace").val(data[0]["StranoDomace"]);
            $("#StranoDomace").selectpicker("refresh");
            //console.log($(ptr).children('#PDVObveznik'));
            if (data[0]["PDVObveznik"]=="1") {
                $("#PDVObveznik").prop("checked", true);
            }
            else {
                $("#PDVObveznik").prop("checked", false);
            }
           
            $("#PIB").val(data[0]["PIB"]);
            $("#OblikOrganizovanja").val(data[0]["OblikOrganizovanja"]);
            $("#OblikOrganizovanja").selectpicker("refresh");
            $("#Naziv").val(data[0]["Naziv"]);
            $("#Ime").val(data[0]["Ime"]);
            $("#Prezime").val(data[0]["Prezime"]);
            $("#ImeRoditelja").val(data[0]["ImeRoditelja"]);
           
            $("#Entitet").val(data[0]["Entitet"]);
            $("#Entitet").selectpicker("refresh");
            PopuniGradove(data[0]["Entitet"], data[0]["Grad"]);
            PopuniOpstine(data[0]["Grad"], data[0]["Opstina"]);
            PopuniMZ(data[0]["Opstina"], data[0]["MZ"]);
            $("#PTTMjesto").val(data[0]["PTTMjesto"]);
            $("#PTTMjesto").selectpicker("refresh");
            $("#UlicaBroj").val(data[0]["UlicaBroj"]);
            $("#Telefon1").val(data[0]["Telefon1"]);
            $("#Telefon2").val(data[0]["Telefon2"]);
            $("#Mobitel").val(data[0]["Mobitel"]);
            $("#Fax").val(data[0]["Fax"]);
            $("#eMail").val(data[0]["eMail"]);
            $("#IDDokumentVrsta").val(data[0]["IDDokumentVrsta"]);
            $("#IDDokumentVrsta").selectpicker("refresh");
            $("#IDDokumentBroj").val(data[0]["IDDokumentBroj"]);
            $("#Zabiljeska").val(data[0]["Zabiljeska"]);
            $("#SistemskiBroj").val(data[0]["SistemskiBroj"]);
            $("#Zvanje").val(data[0]["Zvanje"]);
            PostaviFizickiPravni();
            PostaviStranoDomace();
            $("#Drzava").val(data[0]["Drzava"]);
            $("#Drzava").selectpicker("refresh");
            $(".container.SFR_Subjekti").unblock();

            // TEST 
            /*$('#Grad').attr('disabled', 'disabled');
            $('#Opstina').attr('disabled', 'disabled');
            $('#MZ').attr('disabled', 'disabled');*/
        },
        error: function (xhr, ajaxOptions, thrownError) {
            $(".container.SFR_Subjekti").unblock();
            alert(thrownError);
        }
    });
    
}
function NoviSubjekt(pafterSaveData) {
    $('.modal-title.editsubjekt').text('Novi subjekt');
    $("#RacunBroj").numeric({ decimalPlaces: 0, negative: false, decimal: "," });
    $("#btnrptObrazacBr4Subjekt").attr('disabled', 'disabled');
    subjektAfterSaveData = pafterSaveData;
    $('#ModalDialogSubjekt').modal('show');
    $(".container.SFR_Subjekti").block();
    Cmb('#FizickoPravno', '/json/GetFizickoPravno', function () {
        $("#FizickoPravno").val('F');
        $('#FizickoPravno').selectpicker("refresh");
    });
    Cmb('#StranoDomace', '/json/GetStranoDomace',null,false);
    Cmb('#OblikOrganizovanja', '/json/GetOblikOrganizovanja');
    //Cmb('#Drzava', '/json/GetDrzava');
    Cmb('#Entitet', '/json/GetEntitet', null, false);
    Cmb('#PTTMjesto', '/json/GetPTTMjesto');
    Cmb('#IDDokumentVrsta', '/json/GetDokumentVrsta');
    Cmb('#RacunBanka', '/json/GetBanke');
    Cmb('#RacunVrsta', '/json/GetVrsteRacuna');
    $('.modal-title.editsubjekt').text('Novi subjekt');
    vActionSubjekt = 1;
    $("#KlijentID").val('');
    $("#JMB").val('');

    $('.row.FizickoLice').slideDown(200);
    $("#StranoDomace").val('D');
    $('#StranoDomace').selectpicker("refresh");
    PostaviStranoDomace();
    $("#PDVObveznik").prop("checked", false);
    $("#PIB").val('');
    $("#OblikOrganizovanja").val('');
    $("#Naziv").val('');
    $("#Ime").val('');
    $("#Prezime").val('');
    $("#ImeRoditelja").val('');
    //$("#Drzava").val('');
    //$('#Drzava').selectpicker("refresh");
    $("#Entitet").val('');
    $('#Entitet').selectpicker("refresh");
    $("#Grad").val('');
    $('#Grad').selectpicker("refresh");
    if ($("#Entitet").val() == '') {
        $("#Grad").attr("disabled", "");
    } else {
        $("#Grad").removeAttr("disabled");
    }
    $("#Opstina").val('');
    $("#Opstina").selectpicker("refresh");
    if ($("#Grad").val() == '') {
        $("#Opstina").attr("disabled", "");
    } else {
        $("#Opstina").removeAttr("disabled");
    }
    $("#MZ").val('');
    $("#MZ").selectpicker("refresh");
    if ($("#Opstina").val() == '') {
        $("#MZ").attr("disabled", "");
    } else {
        $("#MZ").removeAttr("disabled");
    }
    $("#PTTMjesto").val('');
    $("#PTTMjesto").selectpicker("refresh");
    $("#UlicaBroj").val('');
    $("#Telefon1").val('');
    $("#Telefon2").val('');
    $("#Mobitel").val('');
    $("#Fax").val('');
    $("#eMail").val('');
    $("#IDDokumentVrsta").val('');
    $("#IDDokumentVrsta").selectpicker("refresh");
    $("#IDDokumentBroj").val('');
    $("#Zabiljeska").val('');
    $("#SistemskiBroj").val('');
    
    $('.editrowRacuni').slideUp(200);
    tSFR_Racuni = null;
    //$('.SpinTable.Racuni').empty();
    $('#tSFR_Racuni').find("tbody").empty();
    vtableOptionstSFR_Racuni.CustomParameters = { 'KlijentID': $('#KlijentID').val() };
    tSFR_Racuni = $('#tSFR_Racuni').danijeltable({ tableOptions: vtableOptionstSFR_Racuni });
    $('.nav-tabs a:first').tab('show');
    $(".SpinTable").removeClass("focused");
   
    $("#btnSacuvajSubjekt").show();



    // Disable editable fields 
    $('#JMB').removeAttr("disabled");
    $('#Ime').removeAttr("disabled");
    $('#Prezime').removeAttr("disabled");
    $('#ImeRoditelja').removeAttr("disabled");
    $('#IDDokumentBroj').removeAttr("disabled");
    $('#SistemskiBroj').removeAttr("disabled");
    $('#Zvanje').removeAttr("disabled");

    // Dropdown
    $('#FizickoPravno').removeAttr("disabled");
    $('#StranoDomace').removeAttr("disabled");
    $('#Drzava').removeAttr("disabled");
    $('#IDDokumentVrsta').removeAttr("disabled");
    $('#Entitet').removeAttr("disabled");
    $('#Grad').removeAttr("disabled");
    $('#Opstina').removeAttr("disabled");
    $('#MZ').removeAttr("disabled");
    $('#PTTMjesto').removeAttr("disabled");

    $('#FizickoPravno').selectpicker("refresh");
    $("#StranoDomace").selectpicker("refresh");
    $('#Drzava').selectpicker("refresh");
    $("#IDDokumentVrsta").selectpicker("refresh");
    $('#Entitet').selectpicker("refresh");
    $("#Grad").selectpicker("refresh");
    $('#Opstina').selectpicker("refresh");
    $("#MZ").selectpicker("refresh");
    $("#PTTMjesto").selectpicker("refresh");

    $('#UlicaBroj').removeAttr("disabled");
    $('#Mobitel').removeAttr("disabled");
    $('#eMail').removeAttr("disabled");
    $('#Telefon1').removeAttr("disabled");
    $('#Telefon2').removeAttr("disabled");
    $('#Fax').removeAttr("disabled");
    $('#Zabiljeska').removeAttr("disabled");
    $('#tabPovezanaLica').hide();
    $('#tabPovezanaLica').attr('title', 'Povezana lica možete unositi tek nakon snimanja novog subjekta');

    $(".container.SFR_Subjekti").unblock();
}

    // Novi/izmjeni korisnik 
function NoviKorisnik(userID, subjektID, organizacioniDioID, radnoMjestoID, ime, Email, zakljucan,password) {

    // Izmjeni
    if (userID != null) {

        $("#ADMUsersHeading").html("Izmjeni korisnika");
        $("#KorisnikID").val(UserID);
        $("#ImeNovogKorisnika").val(ime);
        $("#eMailNovogKorisnika").val(Email);
        Cmb('#SubjektID', '/json/GetSubjekti', null, false);
        $('#SubjektID').val(subjektID);
        $('#SubjektID').selectpicker('refresh');

        Cmb('#RadnoMjestoID', '/json/GetWorkPlace', null, false);
        $('#RadnoMjestoID').val(radnoMjestoID);
        $('#RadnoMjestoID').selectpicker('refresh');

        Cmb('#OrganizacioniDioID', '/json/GetOrgScheme', null, false);
        $('#OrganizacioniDioID').val(organizacioniDioID);
        $('#OrganizacioniDioID').selectpicker('refresh');

        if (zakljucan == "true") {
            $("#ZakljucanID").prop('checked', true);
            $("#JelBioZakljucan").prop('checked', true);
        }
        else {
            $("#ZakljucanID").prop('checked', false);
            $("#JelBioZakljucan").prop('checked', false);
        }
        $('#Password').val(password); 
        vActionClient = 2;
    }// Novi korisnik
    else {
        $("#ImeNovogKorisnika").val('');
        $("#eMailNovogKorisnika").val('');
        Cmb('#SubjektID', '/json/GetSubjektiPoTipuOdnosa');
        Cmb('#RadnoMjestoID', '/json/GetWorkPlace');
        Cmb('#OrganizacioniDioID', '/json/GetOrgScheme');
        vActionClient = 1;
    }
   

    $('.row.FizickoLice').slideDown(200);
    $('.nav-tabs a:first').tab('show');
    $(".SpinTable").removeClass("focused");
    $('#ModalDialogKorisnici').modal('show');
}


$("#btnSacuvajNovogKorisnika").click(function () {
    $('*').removeClass('invalid');
    let ValidacionaPoruka = "";
   
    if ($("#ImeNovogKorisnika").val() == '') {
        ValidacionaPoruka = ValidacionaPoruka + "Ime je obavezno polje\n";
        $("#ImeNovogKorisnika").addClass("invalid");
    }
    if ($("#eMailNovogKorisnika").val() == '') {
        ValidacionaPoruka = ValidacionaPoruka + "Mail adresa je obavezno polje\n";
        $("#eMailNovogKorisnika").addClass("invalid");
    }
    if ($("#OrganizacioniDioID").val() == '') {
        ValidacionaPoruka = ValidacionaPoruka + "Organizacioni dio je obavezno polje\n";
        $("button[data-id='OrganizacioniDioID']").addClass("invalid");
    }
    if ($("#SubjektID").val() == '') {
        ValidacionaPoruka = ValidacionaPoruka + "Naziv subjekta je obavezno polje\n";
        $("button[data-id='SubjektID']").addClass("invalid");
    }
    if ($("#RadnoMjestoID").val() == '') {
        ValidacionaPoruka = ValidacionaPoruka + "Radno mjesto je obavezno polje\n";
        $("button[data-id='RadnoMjestoID']").addClass("invalid");
    }
    
 
  
    if (ValidacionaPoruka != "") {
        swal({ title: "Validacija unosa", text: ValidacionaPoruka, html: true, dangerMode: true, icon: "error" });
    }
    else {
 
        SnimiKorisnika();
    }

})

function SnimiKorisnika() {
    $("#btnSacuvajNovogKorisnika").attr("disabled", "disabled");
    let obj =
    {
        __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
        pAction: vActionClient,
        KorisnikID: $('#KorisnikID').val(),
        ImeNovogKorisnika: $('#ImeNovogKorisnika').val(),
        EMailNovogKorisnika: $('#eMailNovogKorisnika').val(),
        OrganizacioniDioID: $('#OrganizacioniDioID').val(),
        SubjektID: $('#SubjektID').val(),
        RadnoMjestoID: $('#RadnoMjestoID').val(),
        Zakljucan: document.getElementById('ZakljucanID').checked,
        JelBioKorisnikZakljucan: document.getElementById('JelBioZakljucan').checked,
        OldPassword: $('#Password').val(),
    };

    $.ajax({
        url: '/ADM/ADM_Users/SnimiNovogKorisnika',
        type: 'POST',
        data: obj,
        success: function (data) {
            if (data.Successed == '1') {
          
                swal({ title: "Poruka", text: data.Message, dangerMode: false, icon: "success" });
                /*Cmb('#PrimateljID', '/json/GetSubjektiFL', function () {
                    $('#PrimateljID').val(data.KlijentID);
                });*/
                //if (subjektAfterSaveData != undefined) {
                //    let Naziv = "";
                //    if ($("#FizickoPravno").val() == 'F') {
                //        Naziv = $("#Ime").val() + " " + $("#Prezime").val();
                //    } else {
                //        Naziv = $("#Naziv").val();
                //    }
                //    subjektAfterSaveData(data.KlijentID, Naziv);
                //}
                $('#ModalDialogKorisnici').modal('hide');
                $("#btnSacuvajNovogKorisnika").removeAttr("disabled");
                tADM_Users.SetData();
            }
            else {
                swal({ title: "Poruka", text: data.Message, dangerMode: true, icon: "error" });
                $("#btnSacuvajNovogKorisnika").removeAttr("disabled");
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(jqXHR.responseText);
        }
    });
}
function PostaviGridPovezanaLica(pKlijentID) {
    vtableOptionstSFR_PovezanaLica.dataurl = `/Subjekti/GetDataSFR_PovezanaLica?Klijent1=${pKlijentID}`;
    vtableOptionstSFR_PovezanaLica.saveurl = `/Subjekti/SaveSFR_PovezanaLica?Klijent1=${pKlijentID}`;
    $('#tSFR_PovezanaLica').empty();
    $('#tSFR_PovezanaLica').find("tbody").empty();
    tSFR_PovezanaLica = $('#tSFR_PovezanaLica').danijeltable({ tableOptions: vtableOptionstSFR_PovezanaLica });
}
/*
 Drag & Drop Table Columns v.3.1.5
 for jQuery 3.x
 by Oleksandr Nikitin (a.nikitin@i.ua)
 https://github.com/alexshnur/drag-n-drop-table-columns
 */
!function(n,e){function t(n,e){return e.parentNode.insertBefore(n,e.nextSibling)}function a(){var n=navigator.userAgent.toLowerCase();return-1!==n.indexOf("msie")?parseInt(n.split("msie")[1]):!1}var r,o,d,i=null,s=null;return o=function(){function e(e,t){d=this,o=e,d.options=n.extend({},d.options,t),d.options.drag&&(9===a()&&o.find("thead tr th").each(function(){0===n(this).find(".drag-ie").length&&n(this).html(n("<a>").html(n(this).html()).attr("href","#").addClass("drag-ie"))}),r=o.find("thead tr th"),jQuery.event.addProp("dataTransfer"),[].forEach.call(r,function(e){e.setAttribute("draggable",!0),n(e).on("dragstart",d.handleDragStart),n(e).on("dragenter",d.handleDragEnter),n(e).on("dragover",d.handleDragOver),n(e).on("dragleave",d.handleDragLeave),n(e).on("drop",d.handleDrop),n(e).on("dragend",d.handleDragEnd)}))}var o;return e.prototype={options:{drag:!0,dragClass:"drag",overClass:"over",movedContainerSelector:".dnd-moved"},handleDragStart:function(e){n(this).addClass(d.options.dragClass),i=this,e.dataTransfer.effectAllowed="copy",e.dataTransfer.setData("text/html",this.id)},handleDragOver:function(n){n.preventDefault&&n.preventDefault(),n.dataTransfer.dropEffect="copy"},handleDragEnter:function(e){s=this,[].forEach.call(r,function(e){n(e).removeClass(d.options.overClass)}),n(this).addClass(d.options.overClass)},handleDragLeave:function(n){},handleDrop:function(e){e.stopPropagation&&e.stopPropagation(),i!==e&&d.moveColumns(n(i).index(),n(this).index())},handleDragEnd:function(e){var t={array:[],object:{}};[].forEach.call(r,function(e){var a=n(e).attr("data-name")||n(e).index();n(e).removeClass(d.options.overClass),t.object[a]=n(e).index(),t.array.push(n(e).index())}),"function"==typeof d.options.onDragEnd&&d.options.onDragEnd(t),n(i).removeClass(d.options.dragClass)},moveColumns:function(n,e){for(var a=o.find(d.options.movedContainerSelector),r=0;r<a.length;r++)e>n?t(a[r].children[n],a[r].children[e]):e<o.find("thead tr th").length-1&&a[r].insertBefore(a[r].children[n],a[r].children[e])}},e}(),n.fn.extend({dragableColumns:function(){var e=arguments[0];return this.each(function(){var t=n(this);new o(t,e)})}})}(window.jQuery,window);
