var months = ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'];

var popup;
var webexecuter = "webexecuter";

var uniqId = (function() {
    var i=0;
    return function() {
        return i++;
    }
})();	

jQuery(document).ready(function() {

	popup = jQuery("<div/>")
		.hide()
		.addClass("popup_menu")
		.css('position', 'absolute')
		.mouseover( function() { popup.show(); } )
		.mouseout( function() { popup.hide(); } )
		.appendTo(jQuery('body')); 
	
    jQuery('div.bgMonthAndYearWidget').bgMonthAndYearWidget();
    jQuery('div.bgPagesWidget').bgPagesWidget();
    jQuery('div.bgTableWidget').bgTableWidget();
    jQuery('div.bgBalanceInformerWidget').bgBalanceInformerWidget();
    jQuery('div.bgParameterEditorWidget').bgParameterEditorWidget();
});				

(function( $ ) {

	$.fn.bgParameterEditorWidget = function( method )
	{
		var self = this;
		var dialogEditor;

		var methods = {
		    init : function( options ) {
				var $this = $(this).css('margin','0px 5px');
				var write = Boolean($this.attr('param_write') == "true");
				
				// Костыль, пока не реализовали функцию правки для всех параметров
				var paramType = $(this).attr('param_type');
				if ( ( paramType == "1" || paramType == "3" || paramType == "5" || paramType == "7" || paramType == "9" || paramType == "11" ) && write )
				{
					$("<div>[<a href='#'>правка</a>]</div>").click( function() { openDialogEditor( $(this).parent() ); } ).appendTo($this);
				}
				return $this;
		    },
		    load : function() {
		    	var $this = $(this);
		    	var paramType = $this.attr('param_type');
		    	
				$.get( 
						webexecuter,
						{
							action: 'ContractParameter',
							module: 'contract',
							mid: 0,
							operation: 'getParameterType' + paramType,
							contractId: contractId, 
							parameterId: $this.attr('param_id'), 
							ct: 'json'
						},
						function( data )
						{
							if ( data.paramTitle )
							{
								dialogEditor = $("div#paramEditor");
								$("div.paramEditorTitle",dialogEditor).empty().html(data.paramTitle);
								if ( paramType == "1" )
								{
									$("input[name='paramStringValue']",dialogEditor).attr("value",data.paramValue).attr("paramRead",data.paramRead).attr("paramWrite",data.paramWrite);
								}
								else if ( paramType == "3" )
								{
									var paramEditors = $("div.paramEditors",dialogEditor).attr("paramRead",data.paramRead).attr("paramWrite",data.paramWrite);
									var paramEmailEditor = $("div.paramEditorValue",dialogEditor);
									for ( var i = 0; i < data.paramValue.length; i++ )
									{
										var pee = paramEmailEditor.clone().attr("index",i);
										$("input[name='paramEmailValue']",pee).attr("value",data.paramValue[i][0]);
										$("input[name='paramEmailName']",pee).attr("value",data.paramValue[i][1]);
										paramEditors.append(pee.show());
									}
									paramEditors.append(paramEmailEditor.clone().show());
								}
								else if ( paramType == "5" )
								{
									var paramEditors = $("div.paramEditorValue",dialogEditor).attr("paramRead",data.paramRead).attr("paramWrite",data.paramWrite);
									if ( data.paramValue == true )
									{
										$("input[name='paramFlagTrueValue']",dialogEditor).addClass("paramEditorButtonSelected");
									}
									if ( data.paramValue == false )
									{
										$("input[name='paramFlagFalseValue']",dialogEditor).addClass("paramEditorButtonSelected");
									}
								}
								else if ( paramType == "7" )
								{
									var s = $("select[name='paramListValue'] > option[value='0']",dialogEditor).attr("paramWrite",data.paramWrite);
									for ( var i = 0; i < data.paramValues.length; i++ )
									{
										s.before( $("<option/>").html(data.paramValues[i].title).attr("value",data.paramValues[i].id) );
									}
									if ( data.paramRead )
									{
										$("select[name='paramListValue'] > option[value='" + data.paramValue + "']",dialogEditor).attr( "selected", "true" );
										$("input[name='paramListCustomValue']").val(data.paramCustomValue);
									}
								}
								else if ( paramType == "9" )
								{
									var paramEditors = $("div.paramEditors",dialogEditor).attr("paramRead",data.paramRead).attr("paramWrite",data.paramWrite);
									var paramPhoneEditor = $("div.paramEditorValue",dialogEditor);
									for ( var i = 0; i < data.paramValue.length; i++ )
									{
										var pee = paramPhoneEditor.clone().attr("index",i);
										$("input[name='paramPhoneValue']",pee).attr("value",data.paramValue[i][0]);
										$("input[name='paramPhoneComment']",pee).attr("value",data.paramValue[i][1]);
										paramEditors.append(pee.show());
									}
									paramEditors.append(paramPhoneEditor.clone().show());
									window.prefixs = data.prefixs.split(',');
								}
								else if ( paramType == "11" )
								{
									var s = $("select[name='paramMultiListValue']",dialogEditor).attr("paramWrite",data.paramWrite);
									for ( var i = data.paramValues.length - 1; i >= 0; --i )
									{
										s.append($("<option></option>").attr("value",data.paramValues[i].id).text(data.paramValues[i].title));
									}
									if ( data.paramRead )
									{
										var values = data.paramValue;
										if ( values != null )
										{
											values = values.split(";");
											for ( var i = 0; i < values.length; ++i )
											{
												$("select[name='paramMultiListValue'] > option[value='" + values[i] + "']",dialogEditor).attr( "selected", "true" );
											}	
										}
										$("input[name='paramMultiListCustomValue']").val(data.paramCustomValue);
									}
									// Выбор значения без нажатия CTRL
									// Принцип - запоминаем в selected ранее выбранные элементы, потом вручную селектим их 
									// при каждом выборе следующего элемента  
									
									var selected = {};
									
									// Изначально добавляем в selected те элементы, которые были выбраны еще до открытия dialogEditor 
									var selectedValue = $("select[name='paramMultiListValue']").val();
									if (selectedValue != null)
									{
										for (var i = 0; i < selectedValue.length; ++i)
										{
											selected[selectedValue[i]] = "true";
										}	
									}
									
									// Селектим все ранее выбранные значения
									$("select[name='paramMultiListValue']").click( function(e) {
										var $this = $(this),
								        options = this.options,
								        option,
								        value;
								        
								        value = $this.val();
								        for (var i = 0; i < options.length; ++i) {
								        	option = options[i];
								        	if (option.value == value) {
								        		selected[value] = !selected[value];
								        	}
	
								        	option.selected = selected[option.value];
								        }
								        return false;
							      });
								}
								dialogEditor.dialog('option','position','center');
							}
						} 
					);
				return $this;
		    },
		    save : function() {
		    	var $this = $(this);
		    	var paramType = $this.attr('param_type');
		    	var paramId = $this.attr('param_id');
		    	var paramValue = '';
		    	var paramCustomValue = '';
		    	var paramWrite = 'false'; 
				if ( paramType == "1" )
				{
					var i = $("input[name='paramStringValue']",dialogEditor)[0];
					paramValue = i.value;
					paramWrite = $(i).attr("paramWrite");
				}
				else if ( paramType == "3" )
				{
					var paramEditors = $("div.paramEditors",dialogEditor); 
					paramWrite = paramEditors.attr("paramWrite");
					$.each($("div.paramEditorValue",paramEditors), function( a, b ) 
					{
						paramValue = paramValue + $(b).attr("index") + "\t" + $("input[name='paramEmailValue']",b).attr("value") + "\t" + $("input[name='paramEmailName']",b).attr("value") + " \n";
					});
				}
				else if ( paramType == "5" )
				{
					paramWrite = $("div.paramEditorValue",dialogEditor).attr("paramWrite");
					var buttonTrue = $("input[name='paramFlagTrueValue']",dialogEditor).hasClass("paramEditorButtonSelected");
					var buttonFalse = $("input[name='paramFlagFalseValue']",dialogEditor).hasClass("paramEditorButtonSelected");
					paramValue = "";
					if ( buttonTrue )
					{
						paramValue = "true";
					}
					if ( buttonFalse )
					{
						paramValue = "false";
					}
				}
				else if ( paramType == "7" )
				{
					var value = $( "select option:selected" );
					var customValue = $( "input[name*='paramListCustomValue']" );
					
					if ( value.val() != "0" )
					{
						paramValue = value.val();
					}
					else
					{
						paramCustomValue = customValue.val(); 
					}
					paramWrite = "true";
				}	
				else if ( paramType == "9" )
				{
					var paramEditors = $("div.paramEditors",dialogEditor); 
					paramWrite = paramEditors.attr("paramWrite");
					$.each($("div.paramEditorValue",paramEditors), function( a, b )
					{
						paramValue = paramValue + $(b).attr("index") + "\t" + $("input[name='paramPhoneValue']",b).attr("value") + "\t" + $("input[name='paramPhoneComment']",b).attr("value") + " \n";
					});
				}
				else if ( paramType == "11" )
				{
					var value = $( "select[name*='paramMultiListValue']" );
					var customValue = $( "input[name*='paramMultiListCustomValue']" );
					
					if ( value.val() != null )
					{
						paramValue = value.val().toString();
					}
					paramCustomValue = customValue.val(); 

					paramWrite = "true";
				}
				
				if ( paramWrite == "true" )
				{
					$.get( 
							webexecuter,
							{
								action: 'ContractParameter',
								module: 'contract',
								mid: 0,
								operation: 'updateParameterType' + paramType,
								contractId: contractId, 
								parameterId: $this.attr('param_id'),
								parameterValue: paramValue,
								parameterCustomValue: paramCustomValue,
								ct: 'json'
							},
							function( data )
							{
								$("td#param_"+data.paramType+"_"+data.paramId).html(data.paramValue);
							} 
						);
		    	}
				return $this;
		    }
		};

		var openDialogEditor = function( widget ) {
			if ( dialogEditor == undefined )
			{
				dialogEditor = $("<div id='paramEditor' title='Редактор параметра'/>").appendTo( $("body") ).dialog({ autoOpen : false, modal: true, width: 700, dialogClass: "bgbilling-dialog bgbilling-dialog-user" });
				//dialogEditor.dialog( "option", "buttons", [ { text: "Применить", click: function() { widget.bgParameterEditorWidget( "save" ); dialogEditor.dialog( "close" ); } }, { text: "Отмена", click: function() { dialogEditor.dialog( "close" ); } } ] );
			}
			//dialogEditor.empty().load( 'widget/contract/paramEditor_' + widget.attr('param_type') + '.jsp', function() { widget.bgParameterEditorWidget( "load" ); } ).dialog( "open" );
			dialogEditor.empty().load( 'widget/contract/paramEditor_' + widget.attr('param_type') + '.jsp', function() { widget.bgParameterEditorWidget( "load" ); } ).dialog( "option","buttons", [ { text: "Применить", click: function() { widget.bgParameterEditorWidget( "save" ); dialogEditor.dialog( "close" ); window.location.reload(true); } }, { text: "Отмена", click: function() { dialogEditor.dialog( "close" ); } } ] ).dialog( "open");
		};
		
		if ( methods[method] ) { return this.each( function() { methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ) ); } ); } 
		else if ( typeof method === 'object' || ! method ) { return this.each( function() { methods.init.apply( this, arguments ); } ); } 
		else { $.error( 'Метод ' +  method + ' в jQuery.bgParameterEditorWidget не существует' ); }   
	}
	
	$.fn.bgBalanceInformerWidget = function( method )
	{
		var self = this;
		
		var methods = {
		    init : function( options ) {
				var $this = $(this);
				$this.load( 'widget/contract/balanceInformer.jsp' );
				setTimeout( function() { loadData( self ); }, 1000 );
				return $this;
		    },
		    reload : function() {
		    	var $this = $(this);
				loadData( self, true );
				return $this;
		    }
		};

		var loadData = function( div, resetDelay )
		{
			var span = $('span.balanceInformerSum',$(div));
			
			$.get( 
					webexecuter,
					{
						action: 'GetBalanceInformerData',
						module: 'contract',
						mid: 0,
						contractId: contractId, 
						ct: 'json'
					},
					function( data )
					{
						if ( data.sum )
						{
							var delay = Number(span.attr('delay')) || 30;
							if ( resetDelay ) delay = 30;
							span.empty().html( data.sum + ' ' + data.currencyTitleMedium );
							setTimeout( function() { loadData( div ); }, delay * 1000 );
							span.attr('delay', 2 * delay);
						}
					} 
				);
		};
			 
		if ( methods[method] ) { return this.each( function() { methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ) ); } ); } 
		else if ( typeof method === 'object' || ! method ) { return this.each( function() { methods.init.apply( this, arguments ); } ); } 
		else { $.error( 'Метод ' +  method + ' в jQuery.bgBalanceInformerWidget не существует' ); }   
	};
	
	// *******************
	
	$.fn.bgTableWidget = function( method )
	{
		var methods = {
		    init : function( options ) {
				var $this = $(this);
				var table = $('table',this);

				var trhead = $('<tr/>').appendTo($('<thead/>').appendTo(table));
				$("col",table).each( function() { $("<td/>").append( this.title ).appendTo(trhead); } );

				$("<tbody/>").appendTo(table);
				
				return $this;
		    },
		    reload : function() {
		    	var $this = $(this);
				loadData( $this );
				return $this;
		    }
		};
		
		var loadData = function( div )
		{
			var table = $('table',div);
			var tbody = $("tbody",table).empty();

			$.get( 
					webexecuter,
					{
						action: div.attr('action'),
						module: div.attr('module'),
						mid: div.attr('moduleId'),
						operation: div.attr('operation'),
						contractId: contractId, 
						ct: 'json'
					},
					function( data )
					{
						for ( var i = 0; i < data.rows.length; i++ )
						{
							var tr = $("<tr>").appendTo(tbody);
							$("col",table).each( function() 
							{
								var type = this.getAttribute('type');
								var val = data.rows[i][this.getAttribute('name')];
								if ( type !== undefined )
								{
									if ( type == "boolean" )
									{
										var aa = $("<input type='checkbox' disabled='disabled' />");
										if ( val == true ) aa.attr('checked','checked');
										val = aa;
									}
								}
								$("<td/>").append( val ).appendTo(tr); 
							} );
						}
					} 
				);
		};
			 
		if ( methods[method] ) { return this.each( function() { methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ) ); } ); } 
		else if ( typeof method === 'object' || ! method ) { return this.each( function() { methods.init.apply( this, arguments ); } ); } 
		else { $.error( 'Метод ' +  method + ' в jQuery.bgTableWidget не существует' ); }   
	};
	
	// *******************

	$.fn.bgPagesWidget = function( options )
	{
		var settings = $.extend( {
		      'title'         : 'Страница: '
	    }, options);

		function pageSubmit( id )
		{
			let widget = $("#"+id); 
			let pageSize = Number(widget.attr('pageSize')) || 20;
			let pageIndex = Number(widget.attr('pageIndex')) || 1;
			let pageCount = Number(widget.attr('pageCount')) || 1;

		    let query = widget.attr('query');
			let formId = widget.attr('formId');
			let targetId = widget.attr('targetId');
			if ( query )
			{
				document.location = query + "&pageIndex=" + pageIndex +"&pageSize=" + pageSize;
			}
			else if ( formId )
			{
				var form = $("form#"+formId);
				var inputPageSize = $("input[name='pageSize']",form);
				var inputPageIndex = $("input[name='pageIndex']",form);
				if ( inputPageSize.length == 0 ) inputPageSize = $("<input type='hidden' name='pageSize'/>").appendTo(form);
				if ( inputPageIndex.length == 0 ) inputPageIndex = $("<input type='hidden' name='pageIndex'/>").appendTo(form);
				inputPageSize.attr('value',pageSize);
				inputPageIndex.attr('value',pageIndex);
				if ( targetId )
				{
					jQuery.ajax( webexecuter, { 
						method: "POST", 
						dataType: "html",
						processData: false,
						contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
						data: jQuery(form).serialize() }
					).done( function( data, textStatus, request ) { 
						$("#"+targetId).html( data );
						let pageInfo = JSON.parse( request.getResponseHeader('pageInfo') );
						widget.attr('pageSize',pageInfo.pageSize);
						widget.attr('pageIndex',pageInfo.pageIndex);
						widget.attr('pageCount',pageInfo.pageCount);
						widget.attr('recordCount',pageInfo.recordCount);
						$("span.recordCount",widget).html(pageInfo.recordCount);
						$("button.pageButton",widget).html(pageInfo.pageIndex + ' из ' + pageInfo.pageCount + ' [' + pageInfo.pageSize + ']');
					} );
				}
				else
				{
					form[0].submit();
				}
			}
		}

		var toPage = function( id, pageIndex )
		{
			let widget = $("#"+id); 
			let pageCount = Number(widget.attr('pageCount')) || 1;
			if ( pageIndex > 0 && pageIndex < pageCount + 1 )
			{
				widget.attr('pageIndex',pageIndex);
				pageSubmit( id );
			}
			return false;
		};
		
		var setPageData = function( id, buttonTitle, pageCount )
		{
			let widget = $("#"+id); 
			var pageIndex = $("div.pageIndexValue", popup).html();
			widget.attr('pageIndex',pageIndex);
			if ( buttonTitle == 'C' )
			{
				if ( pageIndex.length > 0 )
				{
					$("div.pageIndexValue", popup).html( pageIndex.substring( 0, pageIndex.length - 1 ) );
				}
			}
			else if ( buttonTitle == 'Ok' )
			{
				if ( pageIndex.length > 0 && Number(pageIndex) <= pageCount )
				{
					widget.attr('pageSize',$("div.pageSizeValue", popup).html());
					pageSubmit( id );
					popup.hide();
				}
			}
			else
			{
				var pageIndexValue = $("div.pageIndexValue", popup);
				if ( pageIndexValue.attr('a') == '1' )
				{
					pageIndexValue.attr('a', '0');
					pageIndexValue.html(buttonTitle);
				}
				else
				{
					pageIndexValue.html(pageIndex + buttonTitle);
				}	
			}
		};
		
		var showPagesPopup = function( id, elem )
		{
			let widget = $("#"+id); 
			let pageSize = Number(widget.attr('pageSize')) || 20;
			let pageIndex = Number(widget.attr('pageIndex')) || 1;
			let pageCount = Number(widget.attr('pageCount')) || 1;
			
			var mainTable = $("<table/>")
				.attr('cellpadding', 5)
				.appendTo(popup.empty());
			
			var mainTr = $("<tr/>")
				.appendTo(mainTable);
			
			var sizeTable = $("<table/>")
				.attr('cellpadding', 0)
				.attr('cellspacing', 0)
				.appendTo($("<td/>").appendTo(mainTr));

			$("<tr><td colspan='2' style='text-align: center;'>Размер</td></tr>")
				.appendTo(sizeTable);
			
			$("<tr><td colspan='2'><div class='pageSizeValue' style='border: 1px solid #808080; text-align: center; width: 100%; font-size: 1em; height: 1.2em;'>" + pageSize + "</div></td></tr>")
				.appendTo(sizeTable);

			var pageSizeValues = [ 10, 15, 20, 25, 30, 50, 75, 100 ];
			for ( var i = 0; i < 4; i++ )
			{
				var myTr = $("<tr/>")
					.appendTo(sizeTable);
				for ( var j = 0; j < 2; j++ )
				{
					$("<button style='width: 3em;'/>")
						.html(pageSizeValues[i*2 + j])
						.appendTo($("<td/>").appendTo(myTr))
						.click( function() { $("div.pageSizeValue", popup).html($(this).html()); $("div.pageIndexValue", popup).html(1); } );
				}
			}

			var pageTable = $("<table/>")
				.attr('cellpadding', 0)
				.attr('cellspacing', 0)
				.appendTo($("<td/>").appendTo(mainTr));

			$("<tr><td colspan='3' style='text-align: center;'>Страница</td></tr>")
				.appendTo(pageTable);

			$("<tr><td colspan='3'><div class='pageIndexValue' a='1' style='border: 1px solid #808080; text-align: center; width: 100%; font-size: 1em; height: 1.2em;'>" + pageIndex + "</div></td></tr>")
				.appendTo(pageTable);

			var pageCountValues = [ 7, 8, 9, 4, 5, 6, 1, 2, 3, 0, 'C', "Ok" ];
			for ( var i = 0; i < 4; i++ )
			{
				var myTr = $("<tr/>")
					.appendTo(pageTable);
				for ( var j = 0; j < 3; j++ )
				{
					$("<button style='width: 3em;'/>")
						.html(pageCountValues[i*3 + j])
						.appendTo($("<td/>").appendTo(myTr))
						.click( function() { setPageData( id, $(this).html(), pageCount );  } );
				}
			}
			
			showPopupMenu( elem );		

			return false;
		}
		
		var make = function()
		{
			let id = this.id;
			let widget = $(this); 
			if ( !id )
			{
				id = uniqId();
				widget.attr('id',id);
			}
		
			var pageSize = Number(widget.attr('pageSize')) || 20;
			var recordCount = widget.attr('recordCount');
			if( recordCount == "" ) recordCount = null; else recordCount = Number(widget.attr('recordCount')) || 0; 
			
			var toFirstButton = $('<button type="button">&lt;&lt;</button>').click( function() { toPage( id, 1 ) } );
			var toPrevButton = $('<button type="button">&lt;</button>').click( function() { toPage( id, (Number(widget.attr('pageIndex')) || 1) - 1 ) } );
			var mainButton = $('<button type="button" style="width: 10em;" class="pageButton">' + (Number(widget.attr('pageIndex')) || 1) + ' из ' + (Number(widget.attr('pageCount')) || 1) + ' [' + pageSize + ']</button>').click( function() { showPagesPopup( id, this ) } );
			var toNextButton = $('<button type="button">&gt;</button>').click( function() { toPage( id, (Number(widget.attr('pageIndex')) || 1) + 1 ) } );
			var toLastButton = $('<button type="button">&gt;&gt;</button>').click( function() { toPage( id, (Number(widget.attr('pageIndex')) || 1) == (Number(widget.attr('pageCount')) || 1) ? 0 : (Number(widget.attr('pageCount')) || 1) ) } );
			
			var tmp = $('<nobr/>').appendTo(widget.css('margin','0px 0px'));
			
			if ( recordCount != null ) {
			    tmp = tmp.append($('<span style="margin-right: 1em;">Всего записей: <span class="recordCount" style="font-weight: bold;">' + recordCount + '</span></span>'));
			}
			
			tmp.append($('<span>' + settings.title + '</span>'))
				.append(toFirstButton)
				.append(toPrevButton)
				.append(mainButton)
				.append(toNextButton)
				.append(toLastButton);
		};
		
		this.each( make );
	};
	
	// *******************
	
	$.fn.bgMonthAndYearWidget = function( options )
	{
		var settings = $.extend( {
		      'title'         : 'Период: '
	    }, options);

		function periodSubmit( id )
		{
			let widget = $("#"+id);
	    	let year = Number(widget.attr('year'));
	    	let month = Number(widget.attr('month'));
			let query = widget.attr('query');
			let formId = widget.attr('formId');
			let targetId = widget.attr('targetId');
			if ( query )
			{
				document.location = query + "&year=" + year +"&month=" + month;
			}
			else if ( formId )
			{
				var form = $("form#"+formId);
				var inputMonth = $("input[name='month']",form);
				var inputYear = $("input[name='year']",form);
				var inputPageIndex = $("input[name='pageIndex']",form);
				if ( inputPageIndex.length > 0 ) inputPageIndex.attr('value',1);
				if ( inputMonth.length == 0 ) inputMonth = $("<input type='hidden' name='month'/>").appendTo(form);
				if ( inputYear.length == 0 ) inputYear = $("<input type='hidden' name='year'/>").appendTo(form);
				inputMonth.attr('value',month);
				inputYear.attr('value',year);
				if ( targetId )
				{
					jQuery.ajax( webexecuter, { 
						method: "POST", 
						dataType: "html",
						processData: false,
						contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
						data: jQuery(form).serialize() }
					).done( function( data, textStatus, request ) { 
						$("#"+targetId).html( data );
						let pageId = widget.attr('pageId');						
						if ( pageId ) {
							let pageWidget = $("#"+pageId);
							let pageInfo = JSON.parse( request.getResponseHeader('pageInfo') );
							pageWidget.attr('pageSize',pageInfo.pageSize);
							pageWidget.attr('pageIndex',pageInfo.pageIndex);
							pageWidget.attr('pageCount',pageInfo.pageCount);
							pageWidget.attr('recordCount',pageInfo.recordCount);
							$("span.recordCount",pageWidget).html(pageInfo.recordCount);
							$("button.pageButton",pageWidget).html(pageInfo.pageIndex + ' из ' + pageInfo.pageCount + ' [' + pageInfo.pageSize + ']');
						}
					} );
				}
				else
				{
					form[0].submit();
				}
			}
		}
		
		var toMonth = function( id, step )
		{
			let widget = $("#"+id);
	    	let month = Number(widget.attr('month'));
	    	let year = Number(widget.attr('year'));
			month = month + step;
			if ( month < 1 ) { year = year - 1; month = 12; }
			if ( month > 12 ) { year = year + 1; month = 1; }
			$("button.mainButton",widget[0]).html( months[month - 1] + ', ' + year );
			widget.attr('month',month)
			widget.attr('year',year)
			periodSubmit( id );
			return false;
		};
		
		var showMonthYearPopup = function( id, elem )
		{
			let widget = $("#"+id);
	    	let year = Number(widget.attr('year'));

			var myTable = $("<table/>")
				.attr('cellpadding', 1)
				.appendTo(popup.empty());
		
			var myTr = $("<tr/>")
				.appendTo(myTable);

			$("<td/>")
				.append($("<button>&lt;</button>").click( function() { updateMonthYearPopup(-5); } ))
				.append($("<button>&gt;</button>").click( function() { updateMonthYearPopup(5); } ))
				.appendTo(myTr);
		
			for ( var i = 0; i < 5; i++ )
			{
				$("<td/>")
					.addClass('yearHeader')
					.html(year - 2 + i)
					.appendTo(myTr);
			}
		
			for ( var i = 0; i < 12; i++ )
			{
				var myTr = $("<tr/>").attr({m: i + 1}).appendTo(myTable);
				$("<td/>").html(months[i]).appendTo(myTr);
				for ( var j = 0; j < 5; j++ )
				{
					var bc = "#f0f0f0";
					if ( (i + j) % 2 == 0 ) { bc = "#f8f8f8"; } 
					$("<td/>").html("&nbsp;").appendTo(myTr)
						.attr({y: year - 2 + j, bc: bc})
						.addClass('yearMonth')
						.css('background-color', bc)
						.hover(
							function() { $(this).css('background-color', '#808080'); },
							function() { $(this).css('background-color', $(this).attr('bc')); }
						)
						.click( function() { $("#"+id).attr('year', $(this).attr('y') ); $("#"+id).attr('month',$(this).parent().attr('m')); toMonth( id, 0 ); popup.hide(); } );
				}
			}

			showPopupMenu( elem );		

			return false;
		}
		
		var updateMonthYearPopup = function( delta )
		{
			$("td.yearHeader", popup)
				.each(
					function() {
						$(this).html(Number($(this).html())+delta);
					}
				);
				
			$("td.yearMonth", popup)
				.each(
					function() {
						$(this).attr('y', Number($(this).attr('y'))+delta);
					}
				);
			return false;
		}
		
		var make = function()
		{
			let id = this.id;
			let widget = $(this); 
			if ( !id )
			{
				id = uniqId();
				widget.attr('id',id);
			}
	    	let month = Number(widget.attr('month'));
	    	let year = Number(widget.attr('year'));
			var prevButton = $('<button type="button">&lt;</button>').click( function() { toMonth( id, -1 ) } );
			var mainButton = $('<button type="button" class="mainButton" style="width: 10em;">' + months[month - 1] + ', ' + year + '</button>').click( function() { showMonthYearPopup( id, this ) } );
			var nextButton = $('<button type="button">&gt;</button>').click( function() { toMonth( id, 1 ) } );
			
			$('<nobr/>').appendTo($(this).css('margin','5px 0px'))
				.append($('<span>' + settings.title + '</span>'))
				.append(prevButton)
				.append(mainButton)
				.append(nextButton);
				
			let doSubmitOnLoad = widget.attr('doSubmitOnLoad');
			if ( doSubmitOnLoad && doSubmitOnLoad == "true" )
			{
				toMonth( id, 0 );
			}
		};
		
		this.each( make );
	};
	
	function showPopupMenu( tag )
	{
		var objLeft = tag.offsetLeft;
		var objTop  = tag.offsetTop;
		var objParent = tag.offsetParent;
		while ( objParent.tagName.toUpperCase() != "BODY" )
		{
			objLeft  += objParent.offsetLeft;
			objTop   += objParent.offsetTop;
			objParent = objParent.offsetParent;
		}
		var xPos=objLeft;
		var yPos=objTop + tag.offsetHeight;
		popup.css({
			'top'		: yPos + "px",
			'left'		: xPos + "px"
		}).show();
	};
	
})( jQuery );