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

var popup;
var webexecuter = "webexecuter";

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 == "7" ) && write )
				{
					var button = $("<button type='button'>правка</button>").click( function() { openDialogEditor( $(this).parent() ); } );
					button.appendTo($this);
				}
				return $this;
		    },
		    load : function() {
		    	var $this = $(this);
		    	var paramType = $this.attr('param_type');
		    	
		    	//alert("save: $this.attr('param_id') = "+$this.attr('param_id'));
				$.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 )
							{
								//alert( "paramType = " + paramType );
								$("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 == "7" )
								{
									var s = $("select[name='paramListValue'] > option[value='0']",dialogEditor);
									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" )
								{
									for ( var i = 1; i <= data.items; i++ )
									{
										if ( data['number_'+i] )
										{
											var tr = $("<tr/>").append($("<td/>").html(""))
												.append($("<td/>").append($("<input/>").attr("size",12).attr("value",data['number_'+i][0])))
												.append($("<td/>").append($("<input/>").attr("style","width: 100%").attr("value",data['number_'+i][2])));
											$("table.paramPhoneValues tbody",dialogEditor).append(tr);
										}
									}
								}
					
							}
						} 
					);
				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);
					paramValue = i.attr("value");
					paramWrite = i.attr("paramWrite");
					// .attr("paramRead",data.paramRead);
//					$("input[name='paramStringValue']",dialogEditor).attr("value",data.paramValue).attr("paramRead",data.paramRead).attr("paramWrite",data.paramWrite);
				}
				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" )
				{
					for ( var i = 1; i <= data.items; i++ )
					{
						if ( data['number_'+i] )
						{
							var tr = $("<tr/>").append($("<td/>").html(""))
								.append($("<td/>").append($("<input/>").attr("size",12).attr("value",data['number_'+i][0])))
								.append($("<td/>").append($("<input/>").attr("style","width: 100%").attr("value",data['number_'+i][2])));
							$("table.paramPhoneValues tbody",dialogEditor).append(tr);
						}
					}
				}
				// alert( "paramValue = " + paramValue + "; paramWrite = " + paramWrite );
				if ( paramWrite == "true" )
				{
					//alert("save: $this.attr('param_id') = "+$this.attr('param_id'));
					$.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.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" ); } }, { 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( query, formId, pageIndex, pageSize )
		{
			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);
				form[0].submit();
			}
		}

		var toPage = function( query, formId, pageIndex, pageCount, pageSize )
		{
			if ( pageIndex > 0 && pageIndex < pageCount + 1 )
			{
				pageSubmit( query, formId, pageIndex, pageSize );
			}
			return false;
		};
		
		var setPageData = function( query, formId, buttonTitle, pageCount )
		{
			var pageIndex = $("div.pageIndexValue", popup).html();
			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 )
				{
					pageSubmit( query, formId, pageIndex, $("div.pageSizeValue", popup).html() );
				}
			}
			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( elem, query, formId, pageIndex, pageCount, pageSize )
		{
			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( query, formId, $(this).html(), pageCount ); } );
				}
			}
			
			showPopupMenu( elem );		

			return false;
		}
		
		var make = function()
		{
			var $this = $(this);
			var pageSize = Number($this.attr('pageSize')) || 20;
			var pageIndex = Number($this.attr('pageIndex')) || 1;
			var pageCount = Number($this.attr('pageCount')) || 1;
			var recordCount = $this.attr('recordCount');
			if( recordCount == "" ) recordCount = null; else recordCount = Number($this.attr('recordCount')) || 0; 
			var query = $this.attr('query');
			var formId = $this.attr('formId');
			
			var toFirstButton = $('<button type="button">&lt;&lt;</button>').click( function() { toPage( query, formId, pageIndex - 1 == 0 ? 0 : 1, pageCount, pageSize ) } );
			var toPrevButton = $('<button type="button">&lt;</button>').click( function() { toPage( query, formId, pageIndex - 1, pageCount, pageSize ) } );
			var mainButton = $('<button type="button" style="width: 10em;">' + pageIndex + ' из ' + pageCount + ' [' + pageSize + ']</button>').click( function() { showPagesPopup( this, query, formId, pageIndex, pageCount, pageSize ) } );
			var toNextButton = $('<button type="button">&gt;</button>').click( function() { toPage( query, formId, pageIndex + 1, pageCount, pageSize ) } );
			var toLastButton = $('<button type="button">&gt;&gt;</button>').click( function() { toPage( query, formId, pageIndex == pageCount ? 0 : pageCount, pageCount, pageSize ) } );
			
			var tmp = $('<nobr/>').appendTo($this.css('margin','0px 0px'));
			
				if ( recordCount!=null ) {
				    tmp = tmp.append($('<span style="margin-right: 1em;">Всего записей: <b>' + recordCount + '</b></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( query, formId, month, year )
		{
			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);
				form[0].submit();
			}
		}
		
		var toMonth = function( query, formId, year, month )
		{
			if ( month < 1 ) { year = year - 1; month = 12; }
			if ( month > 12 ) { year = year + 1; month = 1; }
			periodSubmit( query, formId, month, year );
			return false;
		};
		
		var showMonthYearPopup = function( elem, query, formId, year, month )
		{
			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() { toMonth( query, formId, $(this).attr('y'), $(this).parent().attr('m') ); } );
				}
			}

			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()
		{
			var year = Number($(this).attr('year'));
			var month = Number($(this).attr('month'));
			var query = $(this).attr('query');
			var formId = $(this).attr('formId');
			
			var prevButton = $('<button type="button">&lt;</button>').click( function() { toMonth( query, formId, year, month - 1 ) } );
			var mainButton = $('<button type="button" style="width: 10em;">' + months[month - 1] + ', ' + year + '</button>').click( function() { showMonthYearPopup( this, query, formId, year, month ) } );
			var nextButton = $('<button type="button">&gt;</button>').click( function() { toMonth( query, formId, year, month + 1 ) } );
			
			$('<nobr/>').appendTo($(this).css('margin','5px 0px'))
				.append($('<span>' + settings.title + '</span>'))
				.append(prevButton)
				.append(mainButton)
				.append(nextButton);
		};
		
		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 );