(function()
{
	//-------------------------------------------------
	//Start: 获取模板路径，并加到helper中
	var __p = $('script:last').attr('src');
	__p = __p.substr(0, __p.lastIndexOf('/js/module.js') + 1);
	_helper.addInit(__p, init);
	$('head').append('<link rel="stylesheet" href="' + __p + 'S01/' + _lang + '/css/common.css">');
	//End: 获取模板路径，并加到helper中
	//-------------------------------------------------
	
	//-------------------------------------------------
	//Start: 辅助函数
	//词典中，获取关键字对应的值
	function w(k){return _helper.dict(__p, k);}
	//获取对象名称
	function o(f){return f.toString().match(/^function (\w+)\(/)[1];}
	//获取页面变量值
	function v(p, n){return $('>section', p).data(n);}
	//End: 辅助函数
	//-------------------------------------------------

	//联动
	function linkage(element, page, callback)
	{
		var me = $(element);
		me.nextAll('select').remove();
		if (me.val() == '' || me.val() == '0')
			return;
		
		$.getJSON(page + '?Lang=' + _lang + '&ParentID=' + encodeURIComponent(element.value), function(items)
		{
			if (items.length == 0)
			{
				if (callback != null)
					callback();
				return;
			}

			var html = '<option value="">' + (page.indexOf('industry') != -1 ? w('all_sub_industry') : w('all_sub_region')) + '</option>;';
			for (var i = 0; i < items.length; i++)
				html += '<option value="' + items[i].id + '" data-inner-id="' + items[i].innerId + '" data-parent-chain="' + items[i].parentChain + '">' + items[i].name + '</option>';

			var next = me.next('select');
			if (next.length == 0)
			{
				html = '<select class="' + _lang + 'Font">' + html + '</select>';
				me.after(html);	
			}
			else
			{
				next.empty().append(html);
			}

			if (callback != null)
				callback();
		});
	}
	
	function linkageSelect(panel, data)
	{
		if (data.parentChain == null)
		{
			$.get(_helper.toAbsPanel(panel, data.parentChainPage), function(result)
			{
				data.parentChain = result;
				data.parents = result.split('.');
				linkageSelect(panel, data)
			});
	
			return;
		}
	
		data.element = $(data.element);
		if (data.parents.length == 1)
			$('[value=' + data.id + ']', data.element).attr('selected', true);
		else
			$('[data-inner-id=' + data.parents[data.index++] + ']', data.element).attr('selected', true);
		data.element.change();
	}
	
	function bindLinkage(root, page, data)
	{
		root.on('change', 'select', function(){linkage(this, page, function()
		{
			if (data == null)
				return;
	
			var last = $('select:last', root);
			if (data.index < data.parents.length)
			{
				$('[data-inner-id=' + data.parents[data.index++] + ']', last).attr('selected', true);
				last.change();
			}
			else
			{
				$('[value=' + data.id + ']', last).attr('selected', true);
				last.change();
				data = null;
			}
		});}); 
	}
	
	//-------------------------------------------------
	//Start: 初始化
	function init(instance, page, panel)
	{
		if (page == 'supplier_list')
		{
			//创建对象
			var supplier = new Supplier(instance, panel);

			//绑定事件
			$('.recycle,.delete,.recover', panel).click(supplier.update);
		}
		else if (page == 'supplier_add')
		{
			//创建对象
			var supplier = new Supplier(instance, panel);

			//绑定事件
			$('form:first', panel).submit(supplier.add);
			$('[data-operation=SelectUser]', panel).click(supplier.onSelectUserClick);
			panel.on('click', '[data-page=user_select] td a', supplier.onUserClick);			
			
			//初始化
			supplier.init();
		}
		else if (page == 'supplier_edit')
		{
			//创建对象
			var supplier = new Supplier(instance, panel);
			
			//绑定事件
			$('form:first', panel).submit(supplier.modify);
			$('[data-operation=SelectUser]', panel).click(supplier.onSelectUserClick);
			panel.on('click', '[data-page=user_select] td a', supplier.onUserClick);			
			
			//初始化
			supplier.init();
		}
		else if (page == 'supplier_addresses_list')
		{
			//创建对象
			var supplierAddresses = new SupplierAddresses(instance, panel);

			//绑定事件
			$('[data-operation=Delete]', panel).click(supplierAddresses.update);
		}
		else if (page == 'supplier_addresses_add')
		{
			//创建对象
			var supplierAddresses = new SupplierAddresses(instance, panel);

			//绑定事件
			$('form:first', panel).submit(supplierAddresses.add);
			
			//初始化
			supplierAddresses.init();
		}
		else if (page == 'supplier_addresses_edit')
		{
			//创建对象
			var supplierAddresses = new SupplierAddresses(instance, panel);
			
			//绑定事件
			$('form:first', panel).submit(supplierAddresses.modify);
			
			//初始化
			supplierAddresses.init();
		}
		else if (page == 'supplier_payment_list')
		{
			//创建对象
			var supplierPayment = new SupplierPayment(instance, panel);

			//绑定事件
			$('[data-operation=Delete]', panel).click(supplierPayment.update);
		}
		else if (page == 'supplier_payment_add')
		{
			//创建对象
			var supplierPayment = new SupplierPayment(instance, panel);

			//绑定事件
			$('form:first', panel).submit(supplierPayment.add);
		}
		else if (page == 'supplier_payment_edit')
		{
			//创建对象
			var supplierPayment = new SupplierPayment(instance, panel);
			
			//绑定事件
			$('form:first', panel).submit(supplierPayment.modify);
		}
		else if (page == 'contract_list')
		{
			//创建对象
			var contract = new Contract(instance, panel);

			//绑定事件
			panel.on('click', '[data-operation=Delete]', contract.update);
		}
		else if (page == 'contract_add')
		{
			//创建对象
			var contract = new Contract(instance, panel);

			//绑定事件
			$('form:first', panel).submit(contract.add);
			$('[data-operation=SelectSupplier]', panel).click(contract.onSelectSupplierClick);
			$('[data-operation=SelectGoods]', panel).click(contract.onSelectGoodsClick);
			panel.on('click', '.ali-grid-body:first .ali-button', contract.onDeleteGoodsClick)
				.on('click', '[data-page=supplier_select] td a', contract.onSupplierClick)
				.on('click', '[data-page=goods_select] td .ali-button', contract.onAddGoodsClick);
		}
		else if (page == 'contract_edit')
		{
			//创建对象
			var contract = new Contract(instance, panel);

			//绑定事件
			$('form:first', panel).submit(contract.modify);
			$('[data-operation=SelectSupplier]', panel).click(contract.onSelectSupplierClick);
			$('[data-operation=SelectGoods]', panel).click(contract.onSelectGoodsClick);
			panel.on('click', '.ali-grid-body:first .ali-button', contract.onDeleteGoodsClick)
				.on('click', '[data-page=supplier_select] td a', contract.onSupplierClick)
				.on('click', '[data-page=goods_select] td .ali-button', contract.onAddGoodsClick);
			
			//初始化
			contract.init();
		}
		else if (page == 'purchase_list')
		{
			//创建对象
			var purchase = new Purchase(instance, panel);

			//绑定事件
			panel.on('submit', '[data-page=accept] form:first', purchase.onAcceptSubmit)
				.on('submit', '[data-page=pay] form:first', purchase.onPaySubmit)
				.on('submit', '[data-page=refund] form:first', purchase.onRefundSubmit)
				.on('submit', '[data-page=deliver] form:first', purchase.onDeliverSubmit)
				.on('click', '[data-page=logistics_select] td a', purchase.onLogisticsClick)
				.on('click', '[data-page=deliver] [data-operation=SelectLogistics]', purchase.onSelectLogisticsClick)
				.on('click', '[data-operation=Accept]', purchase.onAcceptClick)
				.on('click', '[data-operation=Pay]', purchase.onPayClick)
				.on('click', '[data-operation=Refund]', purchase.onRefundClick)
				.on('click', '[data-operation=Deliver]', purchase.onDeliverClick);
		}
		else if (page == 'purchase_add')
		{
			//创建对象
			var purchase = new Purchase(instance, panel);

			//绑定事件
			$('form:first', panel).submit(purchase.add);
			$('[data-operation=SelectSupplier]', panel).click(purchase.onSelectSupplierClick);
			$('[data-operation=SelectContract]', panel).click(purchase.onSelectContractClick);
			$('[data-operation=SelectWarehouse]', panel).click(purchase.onSelectWarehouseClick);
			$('[data-operation=SelectGoods]', panel).click(purchase.onSelectGoodsClick);
			panel.on('click', '.ali-grid-body:first .ali-button', purchase.onDeleteGoodsClick)
				.on('blur', '.ali-grid-body:first td:nth-child(4) :text', purchase.onAmounBlur)
				.on('blur', '[name=TaxRate]', purchase.onTaxRateBlur)
				.on('blur', '[name=Freight]', purchase.onFreightBlur)
				.on('blur', '[name=PriceAdjustment]', purchase.onPriceAdjustmentBlur)
				.on('click', '[name=NeedInvoice]', purchase.onNeedInvoiceClick)
				.on('click', '[name=FreightType]', purchase.onFreightTypeClick)
				.on('click', '[data-page=supplier_select] td a', purchase.onSupplierClick)
				.on('click', '[data-page=contract_select] td a', purchase.onContractClick)
				.on('click', '[data-page=warehouse_select] td a', purchase.onWarehouseClick)
				.on('click', '[data-page=contract_goods_select] td .ali-button', purchase.onAddGoodsClick);
		}
		else if (page == 'purchase_edit')
		{
			//创建对象
			var purchase = new Purchase(instance, panel);

			//绑定事件
			$('form:first', panel).submit(purchase.add);
			$('[data-operation=SelectSupplier]', panel).click(purchase.onSelectSupplierClick);
			$('[data-operation=SelectContract]', panel).click(purchase.onSelectContractClick);
			$('[data-operation=SelectWarehouse]', panel).click(purchase.onSelectWarehouseClick);
			$('[data-operation=SelectGoods]', panel).click(purchase.onSelectGoodsClick);
			panel.on('click', '.ali-grid-body:first .ali-button', purchase.onDeleteGoodsClick)
				.on('blur', '.ali-grid-body:first td:nth-child(4) :text', purchase.onAmounBlur)
				.on('blur', '[name=TaxRate]', purchase.onTaxRateBlur)
				.on('blur', '[name=Freight]', purchase.onFreightBlur)
				.on('blur', '[name=PriceAdjustment]', purchase.onPriceAdjustmentBlur)
				.on('click', '[name=NeedInvoice]', purchase.onNeedInvoiceClick)
				.on('click', '[name=FreightType]', purchase.onFreightTypeClick)
				.on('click', '[data-page=supplier_select] td a', purchase.onSupplierClick)
				.on('click', '[data-page=contract_select] td a', purchase.onContractClick)
				.on('click', '[data-page=warehouse_select] td a', purchase.onWarehouseClick)
				.on('click', '[data-page=contract_goods_select] td .ali-button', purchase.onAddGoodsClick);
			
			//初始化
			purchase.init();
		}
	}
	//End: 初始化
	//-------------------------------------------------

	//-------------------------------------------------
	//Start: 供应商
	function Supplier(instance, panel)
	{
		var __object = o(arguments.callee);

		this.init = function()
		{
			//地区
			var regionLinkage = eval(v(panel, 'regionLinkage'));
			bindLinkage($('[data-id=region]', panel), _helper.toAbsPanel(panel, 'ajax_region.aspx'), regionLinkage);
			if (regionLinkage && regionLinkage.id != '')
				linkageSelect(panel, regionLinkage);
		};

		this.add = function()
		{
			var data = prepareData(this);
			if (data == null)
				return false;

			_helper.post({instance:instance,object:__object,operation:'Add',data:data});

			return false;
		};
		
		this.modify = function()
		{
			var data = prepareData(this);
			if (data == null)
				return false;

			var id = v(panel, 'id');
			_helper.post({instance:instance,object:__object,operation:'Modify',data:data,params:'ID=' + id});

			return false;
		};

		this.update = function()
		{
			_helper.update(instance, __object, this);
		};

		this.onSelectUserClick = function()
		{
			ali.dialog({name:'SelectUser',modal:true,appendTo:panel,width:400,height:200,resizable:false,url:_helper.toAbsPanel(panel, 'user_select.aspx'),onBeforeLoad:_helper.onDialogBeforeLoad,onShow:_helper.onDialogShow});
			return false;
		};
		
		this.onUserClick = function()
		{
			$('[name=UserName]', panel).val($(this).text());
			$('[name=UserID]', panel).val($(this).data('id'));

			ali.dialog($(this).closest('.ali-dialog-body').children(), 'close');
			
			return false;
		};
		
		function prepareData(form)
		{
			if ($.trim(form.Name.value) == '')
			{
				ali.error(w('name_empty'), $.proxy(function(){form.Name.select();}, this));
				return null;
			}
		
			if (!form.RegisteredCapital.value.match(/^\d+$/))
			{
				ali.error(w('registered_capital_incorrect'), $.proxy(function(){form.Name.select();}, this));
				return null;
			}
		
			var data = _helper.serialize(form);

			var region = $('[data-id=region] [value!=""]:selected:last', form);
			if (region.length == 1)
				data += '&RegionID=' + region.val();
			else
				data += '&RegionID=';
			
			return data;
		}
	}
	//End: 供应商
	//-------------------------------------------------

	//-------------------------------------------------
	//Start: 供应商收货地址
	function SupplierAddresses(instance, panel)
	{
		var __object = 'Supplier.Addresses';
			
		this.init = function()
		{
			//地区
			var regionLinkage = eval(v(panel, 'regionLinkage'));
			bindLinkage($('[data-id=region]', panel), _helper.toAbsPanel(panel, '../ajax_region.aspx'), regionLinkage);
			if (regionLinkage && regionLinkage.id != '')
				linkageSelect(panel, regionLinkage);
		};

		this.add = function()
		{
			var data = prepareData(this);
			if (data == null)
				return false;

			data += '&SupplierID=' + v(panel, 'supplierId');

			_helper.post({instance:instance,object:__object,operation:'Add',data:data});

			return false;
		};

		this.modify = function()
		{
			var data = prepareData(this);
			if (data == null)
				return false;

			var id = v(panel, 'id');
			_helper.post({instance:instance,object:__object,operation:'Modify',data:data,params:'ID=' + id});

			return false;
		};

		this.update = function()
		{
			var me = $(this);
			_helper.update(instance, __object, this, null, null, function()
			{
				//客户端中删除
				ali.grid($('[data-ali-widget=grid]', panel), 'deleteRow', me.closest('tr')[0].rowIndex);
			});			
		};

		function prepareData(form)
		{
			var data = _helper.serialize(form);

			var region = $('[data-id=region] [value!=""]:selected:last', form);
			if (region.length == 1)
				data += '&RegionID=' + region.val();
			else
				data += '&RegionID=';

			return data;
		}
	}
	//End: 供应商收货地址
	//-------------------------------------------------

	//-------------------------------------------------
	//Start: 供应商收款账号
	function SupplierPayment(instance, panel)
	{
		var __object = 'Supplier.Payment';
			
		this.add = function()
		{
			var data = prepareData(this);
			if (data == null)
				return false;

			data += '&SupplierID=' + v(panel, 'supplierId');

			_helper.post({instance:instance,object:__object,operation:'Add',data:data});

			return false;
		};

		this.modify = function()
		{
			var data = prepareData(this);
			if (data == null)
				return false;

			var id = v(panel, 'id');
			_helper.post({instance:instance,object:__object,operation:'Modify',data:data,params:'ID=' + id});

			return false;
		};
		
		this.update = function()
		{
			var me = $(this);
			_helper.update(instance, __object, this, null, null, function()
			{
				//客户端中删除
				ali.grid($('[data-ali-widget=grid]', panel), 'deleteRow', me.closest('tr')[0].rowIndex);
			});			
		};		

		function prepareData(form)
		{
			var data = _helper.serialize(form);

			return data;
		}
	}
	//End: 供应商收款账号
	//-------------------------------------------------

	//-------------------------------------------------
	//Start: 合同
	function Contract(instance, panel)
	{
		var __object = o(arguments.callee),
			__goods = [],
			__goodsIndex = 0;

		this.init = function()
		{
			//发货运费类型
			var deliverFreightType = $('[name=DeliverFreightType]', panel);
			deliverFreightType.val(v(panel, 'deliverFreightType'));
			ali.combo(deliverFreightType, 'activate', deliverFreightType[0].selectedIndex);

			//退货运费类型
			var returnFreightType = $('[name=ReturnFreightType]', panel);
			returnFreightType.val(v(panel, 'returnFreightType'));
			ali.combo(returnFreightType, 'activate', returnFreightType[0].selectedIndex);
			
			//商品
			$('.ali-grid-body:first tr', panel).each(function()
			{
				var goods = {};
				goods.element = $(this);
				goods.goodsNo = $(this).data('goodsNo');
				goods.goodsName = $('td:eq(0)', this).text();
				goods.goodsBarCode = $(this).data('goodsBarCode');
				goods.goodsSpec = $('td:eq(1)', this).text();
				goods.purchasePrice = $('td:eq(2)', this).text();
				goods.returnPrice = $('td:eq(3)', this).text();
				goods.memo = $(':text', this).val();
				goods.id = $(this).data('id');
				
				__goods.push(goods);
			});
		};

		this.add = function()
		{
			__goods = [];

			var data = prepareData(this);
			if (data == null)
				return false;

			var guid = _helper.post({instance:instance,object:__object,operation:'Add',data:data,silent:true});
			if (guid)
			{
				var id = _helper.post({instance:instance,object:__object,operation:'GetInnerIDFromGuid',data:data,params:'ID=' + guid,silent:true});

				uploadFile(id, guid);
			}

			return false;
		};
		
		this.modify = function()
		{
			var data = prepareData(this);
			if (data == null)
				return false;

			var id = v(panel, 'id');
			_helper.post({instance:instance,object:__object,operation:'Modify',data:data,params:'ID=' + id,silent:true});
			uploadFile(id, v(panel, 'guid'));

			return false;
		};

		this.update = function()
		{
			_helper.update(instance, __object, this);
		};

		this.onSelectSupplierClick = function()
		{
			ali.dialog({name:'Contract_SelectSupplier',modal:true,appendTo:panel,width:400,height:200,resizable:false,url:_helper.toAbsPanel(panel, '../supplier/select.aspx'),onBeforeLoad:_helper.onDialogBeforeLoad,onShow:_helper.onDialogShow});
			return false;
		};
		
		this.onSupplierClick = function()
		{
			$('[name=SupplierName]', panel).val($(this).text());
			$('[name=SupplierID]', panel).val($(this).data('id'));

			ali.dialog($(this).closest('.ali-dialog-body').children(), 'close');
			
			return false;
		};
		
		this.onSelectGoodsClick = function()
		{
			ali.dialog({name:'SelectGoods',modal:true,appendTo:panel,width:1000,height:500,resizable:false,url:_helper.toAbsPanel(panel, 'goods_select.aspx'),onBeforeLoad:_helper.onDialogBeforeLoad,onShow:_helper.onDialogShow});
			return false;
		};
		
		this.onAddGoodsClick = function()
		{
			var row = $(this).closest('tr'),
				from = row.closest('.ali-grid').prev(),
				to = $('.grid1:first', panel);
			
			//进货价介绍
			var purchasePrice = $('input:first', row);
			if (!purchasePrice.val().match(/^\d+(\.\d+)?$/))
			{
				ali.error(w('purchase_price_incorrect'), $.proxy(function(){purchasePrice.select();}, this));
				return null;
			}
			
			//退货价介绍
			var returnPrice = $('input:last', row);
			if (!returnPrice.val().match(/^\d+(\.\d+)?$/))
			{
				ali.error(w('return_price_incorrect'), $.proxy(function(){returnPrice.select();}, this));
				return null;
			}
			
			//获取当前行数据
			var newRow = ali.grid(from, 'getRow', row[0].rowIndex);

			//如果已经添加过，则退出
			var rows = $('tbody tr', to.next());
			for (var i = 0; i < rows.length; i++)
			{
				if (rows.eq(i).data('goodsNo') == newRow.GoodsNo)
					return;
			}

			//调整数据
			newRow.Memo = '<input type="text" class="ali-input">';
			newRow.Operation = '<a class="ali-button">' + w('delete') + '</a>';
			
			//添加新行
			row = ali.grid(to, 'addRow', newRow);
			ali.button($('.ali-button', row));
			
			//存储商品编号和商品条码
			row.data('goodsNo', newRow.GoodsNo);
			row.data('goodsBarCode', newRow.GoodsBarCode);
		};
		
		this.onDeleteGoodsClick = function()
		{
			ali.grid($(this).closest('.ali-grid').prev(), 'deleteRow', $(this).closest('tr')[0].rowIndex);
			return false;
		};
		
		function prepareData(form)
		{
			if ($.trim(form.SupplierID.value) == '')
			{
				ali.error(w('supplier_empty'));
				return null;
			}

			if ($.trim(form.Name.value) == '')
			{
				ali.error(w('name_empty'), $.proxy(function(){form.Name.select();}, this));
				return null;
			}
			
			//准备商品
			var goodsList = __goods;
			__goodsIndex = 0;
			__goods = [];
			
			var goodsRows = $('.ali-grid-body:first tr', panel);
			goodsRows.each(function()
			{
				var goods = {};
				goods.element = $(this);
				goods.goodsNo = $(this).data('goodsNo');
				goods.goodsName = $('td:eq(0)', this).text();
				goods.goodsBarCode = $(this).data('goodsBarCode');
				goods.goodsSpec = $('td:eq(1)', this).text();
				goods.purchasePrice = $('td:eq(2)', this).text();
				goods.returnPrice = $('td:eq(3)', this).text();
				goods.memo = $(':text', this).val();

				goods.id = $(this).data('id');
				if (!goods.id)
				{
					goods.operation = 'Add';
				}
				else
				{
					var j = 0;
					for (; j < goodsList.length; j++)
					{
						if (goods.id == goodsList[j].id && (goods.memo != goodsList[j].memo))
							break;
					}
					
					if (j < goodsList.length)
						goods.operation = 'Modify';
				}
	
				__goods.push(goods);
			});
	
			for (var i = 0; i < goodsList.length; i++)
			{
				var j = 0;
				for (; j < goodsRows.length; j++)
				{
					if (goodsList[i].id == goodsRows.eq(j).data('id'))
						break;
				}
	
				if (j >= goodsRows.length)
				{
					goodsList[i].operation = 'Delete';
					__goods.push(goodsList[i]);
				}
			}

			//构造数据
			var data = _helper.serialize(form);
			
			return data;
		}
		
		function uploadFile(id, guid)
		{
			var upload = $('[name=File]', panel);
			if (!ali.uploader(upload.next(), 'needUpload'))
			{
				setGoods(guid);
				return;
			}

			ali.uploader(upload.next(), 'upload', {status:w('uploading_contract_file'),params:'Instance=' + instance + '&Lang=' + _lang + '&Object=' + __object + '&Operation=UploadFile&ID=' + id,onComplete:function()
			{
				if (arguments[0] != 0)
				{
					ali.error(arguments[1]);
				}
				else
				{
					upload.val(arguments[1]);
					setGoods(guid);
				}
				ali.working();
			}});
		}
		
		function setGoods(guid)
		{
			if (__goodsIndex >= __goods.length)
			{
				for (var i = __goods.length - 1; i >= 0; i--)
				{
					if (__goods[i].operation == 'Delete')
						__goods.splice(i, 1);
				}
				
				ali.success(_lang_operation_success);
				ali.working();
				return;
			}

			var object = 'Contract.Goods';
			var goods = __goods[__goodsIndex];
			if (goods.operation == 'Add')
			{
				var data = 'ContractID=' + guid;
				data += '&GoodsNo=' + encodeURIComponent(goods.goodsNo);
				data += '&GoodsName=' + encodeURIComponent(goods.goodsName);
				data += '&GoodsBarCode=' + encodeURIComponent(goods.goodsBarCode);
				data += '&GoodsSpec=' + encodeURIComponent(goods.goodsSpec);
				data += '&PurchasePrice=' + encodeURIComponent(goods.purchasePrice);
				data += '&ReturnPrice=' + encodeURIComponent(goods.returnPrice);
				data += '&Memo=' + encodeURIComponent(goods.memo);
				
				goods.id = _helper.post({instance:instance,object:object,operation:'Add',data:data,silent:true});
				if (typeof(_id) != 'undefined')
					goods.element.data('id', goods.id);
			}
			else if (goods.operation == 'Modify')
			{
				var data = 'Memo=' + encodeURIComponent(goods.memo);
				
				var innerId = _helper.post({instance:instance,object:object,operation:'GetInnerIDFromGuid',params:'ID=' + goods.id,silent:true});
				_helper.post({instance:instance,object:object,operation:'Modify',data:data,params:'ID=' + innerId,silent:true});
			}
			else if (goods.operation == 'Delete')
			{
				var innerId = _helper.post({instance:instance,object:object,operation:'GetInnerIDFromGuid',params:'ID=' + goods.id,silent:true});
				_helper.post({instance:instance,object:object,operation:'Delete',params:'ID=' + innerId,silent:true});
			}
		
			__goodsIndex++;
			setGoods(guid);
		}
	}
	//End: 合同
	//-------------------------------------------------

	//-------------------------------------------------
	//Start: 采购单
	function Purchase(instance, panel)
	{
		var __object = o(arguments.callee),
			__goods = [],
			__goodsIndex = 0;

		this.init = function()
		{
			//商品
			$('.ali-grid-body:first tr', panel).each(function()
			{
				var goods = {};
				goods.element = $(this);
				goods.goodsNo = $(this).data('goodsNo');
				goods.goodsName = $(this).data('goodsName');
				goods.goodsBarCode = $(this).data('goodsBarCode');
				goods.goodsSpec = $('td:eq(2)', this).text();
				goods.price = $('td:eq(3)', this).text();
				goods.amount = $('td:eq(4) :text', this).val();
				goods.memo = $('td:eq(5) :text', this).val();
				goods.id = $(this).data('id');
				
				__goods.push(goods);
			});
			
			//运费支付类型
			var freightType = $('[name=FreightType]', panel);
			freightType.val(v(panel, 'freightType'));
			
			//更新总价
			updateSum();
		};

		this.add = function()
		{
			__goods = [];

			var data = prepareData(this);
			if (data == null)
				return false;

			var guid = _helper.post({instance:instance,object:__object,operation:'Add',data:data,silent:true});
			if (guid)
				setGoods(guid);

			return false;
		};
		
		this.modify = function()
		{
			var data = prepareData(this);
			if (data == null)
				return false;

			var id = v(panel, 'id');
			_helper.post({instance:instance,object:__object,operation:'Modify',data:data,params:'ID=' + id,silent:true});
			setGoods(v(panel, 'guid'));

			return false;
		};

		this.update = function()
		{
			_helper.update(instance, __object, this);
		};

		this.onSelectSupplierClick = function()
		{
			ali.dialog({name:'Purchase_SelectSupplier',modal:true,appendTo:panel,width:400,height:200,resizable:false,url:_helper.toAbsPanel(panel, '../supplier/select.aspx'),onBeforeLoad:_helper.onDialogBeforeLoad,onShow:_helper.onDialogShow});
			return false;
		};
		
		this.onSupplierClick = function()
		{
			$('[name=SupplierName]', panel).val($(this).text());
			$('[name=SupplierID]', panel).val($(this).data('id'));
			$('[data-col=SupplierName]', panel).text($(this).text());

			ali.dialog($(this).closest('.ali-dialog-body').children(), 'close');
			
			return false;
		};

		this.onSelectContractClick = function()
		{
			if ($('[name=SupplierID]', panel).val() == '')
			{
				ali.error(w('select_supplier_first'));
				return false;
			}
			
			ali.dialog({name:'SelectContract',modal:true,appendTo:panel,width:400,height:200,resizable:false,url:_helper.toAbsPanel(panel, '../contract/select.aspx?SupplierID=' + $('[name=SupplierID]', panel).val()),onBeforeLoad:_helper.onDialogBeforeLoad,onShow:_helper.onDialogShow});
			return false;
		};
		
		this.onContractClick = function()
		{
			$('[name=ContractName]', panel).val($(this).data('name'));
			$('[name=ContractID]', panel).val($(this).data('id'));
			$('[name=TaxRate]', panel).val($(this).data('taxRate'));

			ali.dialog($(this).closest('.ali-dialog-body').children(), 'close');
			
			return false;
		};

		this.onSelectWarehouseClick = function()
		{
			ali.dialog({name:'SelectWarehouse',modal:true,appendTo:panel,width:400,height:200,resizable:false,url:_helper.toAbsPanel(panel, 'warehouse_select.aspx'),onBeforeLoad:_helper.onDialogBeforeLoad,onShow:_helper.onDialogShow});
			return false;
		};
		
		this.onWarehouseClick = function()
		{
			$('[name=WarehouseName]', panel).val($(this).data('name'));
			$('[name=WarehouseID]', panel).val($(this).data('id'));
			$('[name=ReceiverAddress]', panel).val($(this).data('address'));
			$('[name=ReceiverPhone]', panel).val($(this).data('phone') + ' ' + $(this).data('mobile'));
			$('[name=ReceiverZip]', panel).val($(this).data('zip'));

			ali.dialog($(this).closest('.ali-dialog-body').children(), 'close');
			
			return false;
		};
		
		this.onSelectGoodsClick = function()
		{
			if ($('[name=ContractID]', panel).val() == '')
			{
				ali.error(w('select_contract_first'));
				return false;
			}
			
			ali.dialog({name:'SelectContractGoods',modal:true,appendTo:panel,width:1000,height:500,resizable:false,url:_helper.toAbsPanel(panel, 'contract_goods_select.aspx?ContractID=' + $('[name=ContractID]', panel).val()),onBeforeLoad:_helper.onDialogBeforeLoad,onShow:_helper.onDialogShow});
			return false;
		};
		
		this.onAddGoodsClick = function()
		{
			var row = $(this).closest('tr'),
				from = row.closest('.ali-grid').prev(),
				to = $('.grid1:first', panel);
			
			//获取当前行数据
			var newRow = ali.grid(from, 'getRow', row[0].rowIndex);

			//如果已经添加过，则退出
			var rows = $('tbody tr', to.next());
			for (var i = 0; i < rows.length; i++)
			{
				if (rows.eq(i).data('goodsNo') == newRow.GoodsNo)
					return;
			}

			//调整数据
			newRow.GoodsName += '(' + newRow.GoodsNo + ')';
			newRow.Amount = '<input type="text" value="1" size="4" class="ali-input">';
			newRow.Memo = '<input type="text" class="ali-input">';
			newRow.Operation = '<a class="ali-button">' + w('delete') + '</a>';
			
			//添加新行
			row = ali.grid(to, 'addRow', newRow);
			ali.button($('.ali-button', row));
			
			//存储商品编号和商品条码
			row.data('goodsName', newRow.GoodsName);
			row.data('goodsNo', newRow.GoodsNo);
			row.data('goodsBarCode', newRow.GoodsBarCode);
			
			//更新总价
			updateSum();
		};
		
		this.onDeleteGoodsClick = function()
		{
			ali.grid($(this).closest('.ali-grid').prev(), 'deleteRow', $(this).closest('tr')[0].rowIndex);
			
			//更新总价
			updateSum();

			return false;
		};

		this.onAcceptClick = function()
		{
			ali.dialog({name:'Accept',modal:true,appendTo:panel,width:500,height:200,resizable:false,url:_helper.toAbsPanel(panel, 'accept.aspx?PurchaseID=' + $(this).closest('tr').data('id')),onBeforeLoad:_helper.onDialogBeforeLoad,onShow:_helper.onDialogShow});
			return false;
		};
		
		this.onAcceptSubmit = function()
		{
			if (this.Acceptbill.value == '')
			{
				ali.error(w('acceptbill_empty'));
				return false;
			}

			var upload = $('[name=Acceptbill]', panel);
			if (!ali.uploader(upload.next(), 'needUpload'))
			{
				accept(this);
				return false;
			}
			
			var form = this;
			ali.uploader(upload.next(), 'upload', {status:w('uploading_acceptbill'),params:'Instance=' + instance + '&Lang=' + _lang + '&Object=' + __object + '&Operation=UploadAcceptbill&ID=' + $(this).data('purchaseId'),onComplete:function()
			{
				if (arguments[0] != 0)
				{
					ali.error(arguments[1]);
				}
				else
				{
					upload.val(arguments[1]);
					accept(form);
				}
				ali.working();
			}});

			return false;
		};

		this.onPayClick = function()
		{
			ali.dialog({name:'Pay',modal:true,appendTo:panel,width:500,height:200,resizable:false,url:_helper.toAbsPanel(panel, 'pay.aspx?PurchaseID=' + $(this).closest('tr').data('id')),onBeforeLoad:_helper.onDialogBeforeLoad,onShow:_helper.onDialogShow});
			return false;
		};
		
		this.onPaySubmit = function()
		{
			var data = _helper.serialize(this);

			//提交数据
			_helper.post({instance:instance,object:__object,operation:'Pay',data:data,params:'ID=' + $(this).data('purchaseId'),silent:true});

			ali.success(_lang_operation_success, $.proxy(function()
			{
				//关闭对话框
				ali.dialog($(this).closest('.ali-dialog-body').children(), 'close');

				//刷新列表
				$('.search1', panel).submit();
			}, this));

			return false;
		};

		this.onRefundClick = function()
		{
			ali.dialog({name:'Refund',modal:true,appendTo:panel,width:500,height:250,resizable:false,url:_helper.toAbsPanel(panel, 'refund.aspx?PurchaseID=' + $(this).closest('tr').data('id')),onBeforeLoad:_helper.onDialogBeforeLoad,onShow:_helper.onDialogShow});
			return false;
		};
		
		this.onRefundSubmit = function()
		{
			if (!this.RefundAmount.value.match(/^\d+(\.\d+)?$/))
			{
				ali.error(w('refund_amount_incorrect'), $.proxy(function(){this.RefundAmount.select();}, this));
				return false;
			}
			
			var data = _helper.serialize(this);

			//提交接单数据
			_helper.post({instance:instance,object:__object,operation:'Refund',data:data,params:'ID=' + $(this).data('purchaseId'),silent:true});

			ali.success(_lang_operation_success, $.proxy(function()
			{
				//关闭接单对话框
				ali.dialog($(this).closest('.ali-dialog-body').children(), 'close');

				//刷新列表
				$('.search1', panel).submit();
			}, this));

			return false;
		};

		this.onDeliverClick = function()
		{
			ali.dialog({name:'Deliver',modal:true,appendTo:panel,width:500,height:300,resizable:false,url:_helper.toAbsPanel(panel, 'deliver.aspx?PurchaseID=' + $(this).closest('tr').data('id')),onBeforeLoad:_helper.onDialogBeforeLoad,onShow:_helper.onDialogShow});
			return false;
		};
		
		this.onDeliverSubmit = function()
		{
			if (this.LogisticsID.value == '')
			{
				ali.error(w('logistics_empty'));
				return false;
			}
		
			if (this.WaybillNo.value == '')
			{
				ali.error(w('waybill_no_empty'));
				return false;
			}
		
			if (this.Waybill.value == '')
			{
				ali.error(w('waybill_empty'));
				return false;
			}
	
			if (!this.DeliverTime.value.match(/^(\d{1,4})(-|\/)(\d{1,2})(-|\/)(\d{1,2})( (\d{1,2}):(\d{1,2}):(\d{1,2}))?$/))
			{
				ali.error(w('deliver_time_incorrect'), function(){this.DeliverTime.select();}, this);
				return false;
			}

			var data = _helper.serialize(this);
				data += '&PurchaseID=' + $(this).data('purchaseGuid');

			//提交数据
			var guid = _helper.post({instance:instance,object:'Purchase.Delivery',operation:'Add',data:data,silent:true});
			var innerId = _helper.post({instance:instance,object:'Purchase.Delivery',operation:'GetInnerIDFromGuid',params:'ID=' + guid,silent:true});

			//上传发货凭据			
			var upload = $(this.Waybill);
			if (!ali.uploader(upload.next(), 'needUpload'))
			{
				deliver(this);
				return false;
			}
			
			var form = this;
			ali.uploader(upload.next(), 'upload', {status:w('uploading_waybill'),params:'Instance=' + instance + '&Lang=' + _lang + '&Object=Purchase.Delivery&Operation=UploadWaybill&ID=' + innerId,onComplete:function()
			{
				if (arguments[0] != 0)
				{
					ali.error(arguments[1]);
				}
				else
				{
					upload.val(arguments[1]);
					deliver(form);
				}
				ali.working();
			}});

			return false;
		};
		
		this.onSelectLogisticsClick = function()
		{
			ali.dialog({name:'SelectLogistics',modal:true,appendTo:panel,width:400,height:200,resizable:false,url:_helper.toAbsPanel(panel, 'logistics_select.aspx'),onBeforeLoad:_helper.onDialogBeforeLoad,onShow:_helper.onDialogShow});
			return false;
		};
		
		this.onLogisticsClick = function()
		{
			$('[name=LogisticsName]', panel).val($(this).data('name'));
			$('[name=LogisticsID]', panel).val($(this).data('id'));

			ali.dialog($(this).closest('.ali-dialog-body').children(), 'close');

			return false;
		};
		
		this.onAmounBlur = function()
		{
			if (!this.value.match(/^\d+$/))
			{
				ali.error(w('amount_must_be_number'), $.proxy(function(){this.select();}, this));
				return;
			}
			
			//更新总价
			updateSum();
		};
		
		this.onTaxRateBlur = function()
		{
			if (!this.value.match(/^\d+(\.\d+)?$/))
			{
				ali.error(w('tax_rate_incorrect'), $.proxy(function(){this.select();}, this));
				return;
			}
			
			//更新总价
			updateSum();
		};
		
		this.onFreightBlur = function()
		{
			if (!this.value.match(/^\d+(\.\d+)?$/))
			{
				ali.error(w('freight_incorrect'), $.proxy(function(){this.select();}, this));
				return;
			}
			
			//更新总价
			updateSum();
		};
		
		this.onPriceAdjustmentBlur = function()
		{
			if (!this.value.match(/^-?\d+(\.\d+)?$/))
			{
				ali.error(w('price_adjustment_incorrect'), $.proxy(function(){this.select();}, this));
				return;
			}
			
			//更新总价
			updateSum();
		};
		
		this.onNeedInvoiceClick = function()
		{
			this.form.TaxRate.disabled = this.form.InvoiceRise.disabled = this.value != 'true';
			this.form.TaxRate.value = '0';
		};
		
		this.onFreightTypeClick = function()
		{
			var freight = this.form.Freight;
			freight.disabled = this.value != 'Prepaid';
			freight.value = '0.00';
		};
		
		function prepareData(form)
		{
			//采购单号
			if ($.trim(form.No.value) == '')
			{
				ali.error(w('purchase_no_empty'), $.proxy(function(){form.No.select();}, this));
				return null;
			}

			//供应商
			if ($.trim(form.SupplierID.value) == '')
			{
				ali.error(w('supplier_empty'));
				return null;
			}

			//合同
			if ($.trim(form.ContractID.value) == '')
			{
				ali.error(w('contract_empty'));
				return null;
			}

			//仓库
			if ($.trim(form.WarehouseID.value) == '')
			{
				ali.error(w('warehouse_empty'));
				return null;
			}
			
			//税率
			if (!form.TaxRate.value.match(/^\d+(\.\d+)?$/))
			{
				ali.error(w('tax_rate_incorrect'), $.proxy(function(){form.TaxRate.select();}, this));
				return null;
			}
			
			//收货人名称
			if ($.trim(form.ReceiverName.value) == '')
			{
				ali.error(w('receiver_name_empty'), $.proxy(function(){form.ReceiverName.select();}, this));
				return null;
			}			
			
			//收货人地址
			if ($.trim(form.ReceiverAddress.value) == '')
			{
				ali.error(w('receiver_address_empty'), $.proxy(function(){form.ReceiverAddress.select();}, this));
				return null;
			}			
			
			//收货人电话
			if ($.trim(form.ReceiverPhone.value) == '')
			{
				ali.error(w('receiver_phone_empty'), $.proxy(function(){form.ReceiverPhone.select();}, this));
				return null;
			}			
			
			//收货人邮政编码
			if ($.trim(form.ReceiverZip.value) == '')
			{
				ali.error(w('receiver_zip_empty'), $.proxy(function(){form.ReceiverZip.select();}, this));
				return null;
			}			
			
			//运费
			if (!form.Freight.value.match(/^\d+(\.\d+)?$/))
			{
				ali.error(w('freight_incorrect'), $.proxy(function(){form.Freight.select();}, this));
				return null;
			}
			
			//折扣和涨价
			if (!form.PriceAdjustment.value.match(/^-?\d+(\.\d+)?$/))
			{
				ali.error(w('price_adjustment_incorrect'), $.proxy(function(){form.PriceAdjustment.select();}, this));
				return null;
			}
			
			//检查商品
			var goodsRows = $('.ali-grid-body:first tr', panel);
			if (!goodsRows.length)
			{
				ali.error(w('goods_empty'));
				return null;
			}

			//准备商品
			var goodsList = __goods;
			__goodsIndex = 0;
			__goods = [];
			
			goodsRows.each(function()
			{
				var goods = {};
				goods.element = $(this);
				goods.goodsNo = $(this).data('goodsNo');
				goods.goodsName = $(this).data('goodsName');
				goods.goodsBarCode = $(this).data('goodsBarCode');
				goods.goodsSpec = $('td:eq(1)', this).text();
				goods.price = $('td:eq(2)', this).text();
				goods.amount = $('td:eq(3) :text', this).val();
				goods.memo = $('td:eq(4) :text', this).val();

				goods.id = $(this).data('id');
				if (!goods.id)
				{
					goods.operation = 'Add';
				}
				else
				{
					var j = 0;
					for (; j < goodsList.length; j++)
					{
						if (goods.id == goodsList[j].id && (goods.amount != goodsList[j].amount || goods.memo != goodsList[j].memo))
							break;
					}
					
					if (j < goodsList.length)
						goods.operation = 'Modify';
				}
	
				__goods.push(goods);
			});
	
			for (var i = 0; i < goodsList.length; i++)
			{
				var j = 0;
				for (; j < goodsRows.length; j++)
				{
					if (goodsList[i].id == goodsRows.eq(j).data('id'))
						break;
				}
	
				if (j >= goodsRows.length)
				{
					goodsList[i].operation = 'Delete';
					__goods.push(goodsList[i]);
				}
			}

			//构造数据
			var data = _helper.serialize(form);
			
			return data;
		}
		
		function accept(form)
		{
			var data = _helper.serialize(form);

			//提交接单数据
			_helper.post({instance:instance,object:__object,operation:'Accept',data:data,params:'ID=' + $(form).data('purchaseId'),silent:true});

			ali.success(_lang_operation_success, $.proxy(function()
			{
				//关闭接单对话框
				ali.dialog($(form).closest('.ali-dialog-body').children(), 'close');
				
				//刷新列表
				$('.search1', panel).submit();
			}, this));
		}
		
		function deliver(form)
		{
			var data = _helper.serialize(form);
				data += '&DeliverMemo=' + encodeURIComponent(form.Memo.value);

			//提交接单数据
			_helper.post({instance:instance,object:__object,operation:'Deliver',data:data,params:'ID=' + $(form).data('purchaseId'),silent:true});

			ali.success(_lang_operation_success, $.proxy(function()
			{
				//关闭接单对话框
				ali.dialog($(form).closest('.ali-dialog-body').children(), 'close');
				
				//刷新列表
				$('.search1', panel).submit();
			}, this));
		}
		
		function setGoods(guid)
		{
			if (__goodsIndex >= __goods.length)
			{
				for (var i = __goods.length - 1; i >= 0; i--)
				{
					if (__goods[i].operation == 'Delete')
						__goods.splice(i, 1);
				}
				
				ali.success(_lang_operation_success);
				ali.working();
				return;
			}

			var object = 'Purchase.Detail';
			var goods = __goods[__goodsIndex];
			if (goods.operation == 'Add')
			{
				var data = 'PurchaseID=' + guid;
				data += '&GoodsNo=' + encodeURIComponent(goods.goodsNo);
				data += '&GoodsName=' + encodeURIComponent(goods.goodsName);
				data += '&GoodsBarCode=' + encodeURIComponent(goods.goodsBarCode);
				data += '&GoodsSpec=' + encodeURIComponent(goods.goodsSpec);
				data += '&Price=' + encodeURIComponent(goods.price);
				data += '&Amount=' + encodeURIComponent(goods.amount);
				data += '&Memo=' + encodeURIComponent(goods.memo);
				
				goods.id = _helper.post({instance:instance,object:object,operation:'Add',data:data,silent:true});
				if (typeof(_id) != 'undefined')
					goods.element.data('id', goods.id);
			}
			else if (goods.operation == 'Modify')
			{
				var data = 'Amount=' + encodeURIComponent(goods.amount);
				data += 'Memo=' + encodeURIComponent(goods.memo);
				
				var innerId = _helper.post({instance:instance,object:object,operation:'GetInnerIDFromGuid',params:'ID=' + goods.id,silent:true});
				_helper.post({instance:instance,object:object,operation:'Modify',data:data,params:'ID=' + innerId,silent:true});
			}
			else if (goods.operation == 'Delete')
			{
				var innerId = _helper.post({instance:instance,object:object,operation:'GetInnerIDFromGuid',params:'ID=' + goods.id,silent:true});
				_helper.post({instance:instance,object:object,operation:'Delete',params:'ID=' + innerId,silent:true});
			}
		
			__goodsIndex++;
			setGoods(guid);
		}
		
		function updateSum()
		{
			var prices = 0;
			$('.ali-grid-body:first tr', panel).each(function()
			{
				prices += parseFloat($('td:eq(2)', this).text()) * parseInt($('td:eq(3) :text', this).val());
			});
			
			var priceWithTax = prices + prices * parseFloat($('[name=TaxRate]', panel).val());
			var priceWithFreight = priceWithTax + parseFloat($('[name=Freight]', panel).val());
			var sum = priceWithFreight + parseFloat($('[name=PriceAdjustment]', panel).val());
			
			if (isNaN(sum))
			{
				$('[data-col=PriceWithFreight]', panel).text(0);
				$('[name=Sum]', panel).text(0);
			}
			else
			{
				$('[data-col=PriceWithFreight]', panel).text(priceWithFreight);
				$('[name=Sum]', panel).val(sum);
			}
		}
	}
	//End: 采购单
	//-------------------------------------------------
})();
////@ sourceURL=AliShop.PurchaseModule.js