function BuildHeader()
{
	if (_page == 'sub_instance_list')
		return BuildAjaxPath(true) + '?Lang=' + _lang + '&IsRecycled=' + $('#IsRecycled').val() + '&Sort=' + $('#Sort').val() + '&Keyword=' + encodeURIComponent($('#Keyword').val()) + '&KeywordType=' + $('#KeywordType').val() + '&Page=' + _pageNumber;
	else if (_page == 'goods_list')
		return BuildAjaxPath(true) + '?Lang=' + _lang + '&IsRecycled=' + $('#IsRecycled').val() + '&IsReleased=' + $('#IsReleased').val() + '&IsHeld=' + $('#IsHeld').val() + '&IsRecommended=' + $('#IsRecommended').val() + '&CategoryID=' + $('#CategoryID').val() + '&IncludeSubCategory=' + $('#IncludeSubCategory')[0].checked + '&Sort=' + $('#Sort').val() + '&Keyword=' + encodeURIComponent($('#Keyword').val()) + '&KeywordType=' + $('#KeywordType').val() + '&ListByPicture=' + $('#ListByPicture')[0].checked + '&Page=' + _pageNumber;
	else if (_page == 'order_list')
		return BuildAjaxPath(true) + '?Lang=' + _lang + '&IsAccepted=' + $('#IsAccepted').val() + '&IsPayed=' + $('#IsPayed').val() + '&IsDelivered=' + $('#IsDelivered').val() + '&IsFinished=' + $('#IsFinished').val() + '&Sort=' + $('#Sort').val() + '&Keyword=' + encodeURIComponent($('#Keyword').val()) + '&KeywordType=' + $('#KeywordType').val() + '&Page=' + _pageNumber;
	else if (_page == 'brand_list')
		return BuildAjaxPath(true) + '?Lang=' + _lang + '&Page=' + _pageNumber;
	else if (_page == 'goods_category_list')
		return BuildAjaxPath(true) + '?Lang=' + _lang + '&IsDisplay=' + $('#IsDisplay').val() + '&IsRecommended=' + $('#IsRecommended').val() + '&IsHeld=' + $('#IsHeld').val() + '&Sort=' + $('#Sort').val();
	else if (_page == 'type_list')
		return BuildAjaxPath(true) + '?Lang=' + _lang + '&Page=' + _pageNumber;
	else
	    return BuildAjaxPath();
}

function Search()
{
	if (arguments.length > 0 && typeof(arguments[0]) != 'object')
		_pageNumber = arguments[0];
	
	SetStatusMessage(_lang_working);

	$.ajax(
	{
		url: BuildHeader(),
		data: {},
		type: 'POST',
		error: function(request)
		{
			Alert(_lang_operation_fail);
			SetStatusMessage();
		},
		success: function(data)
		{
			var list = $('#List');

			list.html(HandleFake404(data, 'text'));
			SetStatusMessage();

			if (typeof(SetupIme) == 'function')
				SetupIme();
				
			MakeButton();
		}
	});
}

function MakeButton()
{
	var buttons = '';
	var button;
	
	//回收
	button = $('#IsRecycled');
	if (button.length == 1)
	{
	    if (button[0].selectedIndex == 1)
	    {
		    buttons += '<button class="Button" id="Recycle">' + _lang_recycle + '</button>';
	    }
	    else if (button[0].selectedIndex == 2)
	    {
		    buttons += '<button class="Button" id="Delete">' + _lang_delete + '</button>';
		    buttons += '<button class="Button" id="Recover">' + _lang_recover + '</button>';
	    }
	}
	
	//发布
	button = $('#IsReleased');
	if (button.length == 1)
	{
	    if (button[0].selectedIndex == 1)
		    buttons += '<button class="Button" id="Release">' + _lang_release + '</button>';
	    else if (button[0].selectedIndex == 2)
		    buttons += '<button class="Button" id="UnRelease">' + _lang_unrelease + '</button>';
	}
	
	//置顶
	button = $('#IsHeld');
	if (button.length == 1)
	{
	    if (button[0].selectedIndex == 1)
		    buttons += '<button class="Button" id="Hold">' + _lang_hold + '</button>';
	    else if (button[0].selectedIndex == 2)
		    buttons += '<button class="Button" id="UnHold">' + _lang_unhold + '</button>';
	}
	
	//推荐
	button = $('#IsRecommended');
	if (button.length == 1)
	{
	    if (button[0].selectedIndex == 1)
		    buttons += '<button class="Button" id="Recommend">' + _lang_recommend + '</button>';
	    else if (button[0].selectedIndex == 2)
		    buttons += '<button class="Button" id="UnRecommend">' + _lang_unrecommend + '</button>';
	}
	
	//显示
	button = $('#IsDisplay');
	if (button.length == 1)
	{
	    if (button[0].selectedIndex == 1)
		    buttons += '<button class="Button" id="Display">' + _lang_display + '</button>';
	    else if (button[0].selectedIndex == 2)
		    buttons += '<button class="Button" id="UnDisplay">' + _lang_undisplay + '</button>';
	}

	//受理
	button = $("#IsAccepted");
	if (button.length == 1)
	{
	    if (button[0].selectedIndex == 1)
		    buttons += "<button class='Button' id='Delete'>" + _lang_delete + "</button>";
	}

	//完成，归档，作废
	button = $('#IsFinished');
	if (button.length == 1)
	{
	    if (button[0].selectedIndex == 1)
		{
			if ($("#IsDelivered")[0].selectedIndex == 3)
			    buttons += "<button class='Button' id='Finish'>" + _lang_finish + "</button>";
		    buttons += '<button class="Button" id="Archive">' + _lang_archive + '</button>';
		    buttons += '<button class="Button" id="Cancel">' + _lang_cancel + '</button>';
		}
	    else if (button[0].selectedIndex == 2)
		{
		    buttons += '<button class="Button" id="Archive">' + _lang_archive + '</button>';
		    buttons += '<button class="Button" id="Cancel">' + _lang_cancel + '</button>';
		}
	    else if (button[0].selectedIndex == 3 || button[0].selectedIndex == 4)
		{
		    buttons += '<button class="Button" id="Delete">' + _lang_delete + '</button>';
		}
	}

	$('#ExtraButton').html(buttons);
}

function SelectFile(type, path)
{
	var form = document.forms[0];
	switch (type)
	{
		case 'Picture':
			form.Picture.value = path;
			$('#PictureView').attr('src', path);
			break;
		case 'Thumbnail':
			form.Thumbnail.value = path;
			$('#ThumbnailView').attr('src', path);
			break;
		default:
			if (type.indexOf('MorePicture') == 0)
			{
				$('#' + type.substr(4) + 'Textbox').val(path);
				$('#' + type.substr(4) + 'View').attr('src', path);
			}
			else if (type.indexOf('SpecPicture') == 0)
			{
				$('#' + type + 'Textbox').val(path);
				$('#' + type + 'View').attr('src', path);
			}
			break;
	}	
}

//联动
function linkage(element, page, callback)
{
	var me = $(element);
	me.nextAll('select').remove();
	if (me.val() == '' || me.val() == '0')
	{
		//if (callback != null)
		//	callback();
		return;
	}
	
	SetStatusMessage(_lang_working);

	$.ajax(
	{
		url: page + '?Lang=' + _lang + '&ParentID=' + encodeURIComponent(element.value),
		type: 'GET',
		error: function(request)
		{
			Alert(_lang_operation_fail);
			SetStatusMessage();
		},
		success : function(data)
		{
			SetStatusMessage();
				
			var items = eval(data);
			if (items.length == 0)
			{
				if (callback != null)
					callback();
				return;
			}

			var html = '<option value="">' + _lang_not_set + '</option>';
			for (var i = 0; i < items.length; i++)
				html += '<option value="' + items[i].id + '" data-inner-id="' + items[i].innerId + '">' + 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(data)
{
	if (data.parentChain == null)
	{
		$.get(data.parentChainPage, function(result)
		{
			data.parentChain = result;
			data.parents = result.split('.');
			linkageSelect(data)
		});

		return;
	}

	data.element = $(data.element);
	if (data.parents.length == 1)
	{
		data.element.find('[value=' + data.id + ']').attr('selected', true);
	}
	else
	{
		data.element.find('[data-inner-id=' + data.parents[data.index++] + ']').attr('selected', true);
		data.element.change();
	}
}

//-------------------------------------------------
//Start: 栏目设置
function InstanceConfig()
{
	var __object = 'InstanceConfig',
		__base = new Base(),
		__uploadGoodsDefaultThumbnail;

	this.setBasicSettings = function()
	{
		if (!this.TypeNoDigit.value.match(/^\d+$/) || !this.GoodsNoDigit.value.match(/^\d+$/) || !this.SpecNoDigit.value.match(/^\d+$/))
		{
			Alert(_lang_sku_must_be_number);
			return false;
		}
		
		if (parseInt(this.SpecNoDigit.value) > 2)
		{
			Alert(_lang_spec_digit_lower_than_two, function(){this.SpecNoDigit.select();}, this);
			return false;
		}
		
		if (this.GoodsThumbnailFolder.value.length > 0 && this.GoodsThumbnailFolder.value.indexOf('/') != 0)
		{
			Alert(_lang_goods_thumbnail_folder_starts_slash, function(){this.GoodsThumbnailFolder.select();}, this);
			return false;
		}
		
		if (this.GoodsPictureFolder.value.length > 0 && this.GoodsPictureFolder.value.indexOf('/') != 0)
		{
			Alert(_lang_goods_picture_folder_starts_slash, function(){this.GoodsPictureFolder.select();}, this);
			return false;
		}
		
		if (this.FileFolder.value.length > 0 && this.FileFolder.value.indexOf('/') != 0)
		{
			Alert(_lang_file_folder_starts_slash, function(){this.FileFolder.select();}, this);
			return false;
		}
		
		if (this.TempFileFolder.value.length > 0 && this.TempFileFolder.value.indexOf('/') != 0)
		{
			Alert(_lang_file_temp_folder_starts_slash, function(){this.TempFileFolder.select();}, this);
			return false;
		}
		
		if (!this.GoodsThumbnailWidth.value.match(/^\d*$/))
		{
			Alert(_lang_goods_thumbnail_width_incorrect, function(){this.GoodsThumbnailWidth.select();}, this);
			return false;
		}	
		
		if (!this.GoodsThumbnailHeight.value.match(/^\d*$/))
		{
			Alert(_lang_goods_thumbnail_height_incorrect, function(){this.GoodsThumbnailHeight.select();}, this);
			return false;
		}	
		
		if (!IsAllowedType(this.GoodsDefaultThumbnail.value, this.GoodsDefaultThumbnailAllowedType.value))
		{
			Alert(_lang_type_must_be + this.GoodsDefaultThumbnailAllowedType.value, function(){this.GoodsDefaultThumbnail.select();}, this);
			return false;
		}
		
		if (!this.TaxRate.value.match(/^\d+(\.\d+)?$/))
		{
			Alert(_lang_tax_rate_incorrect, function(){this.TaxRate.select();}, this);
			return false;
		}
		
		var data = 'TypeNoDigit=' +  encodeURIComponent(this.TypeNoDigit.value);
		data += '&GoodsNoDigit=' +  encodeURIComponent(this.GoodsNoDigit.value);
		data += '&SpecNoDigit=' +  encodeURIComponent(this.SpecNoDigit.value);
		data += '&GoodsThumbnailFolder=' +  encodeURIComponent(this.GoodsThumbnailFolder.value);
		data += '&GoodsPictureFolder=' +  encodeURIComponent(this.GoodsPictureFolder.value);
		data += '&FileFolder=' +  encodeURIComponent(this.FileFolder.value);
		data += '&TempFileFolder=' +  encodeURIComponent(this.TempFileFolder.value);
		data += '&GoodsThumbnailWidth=' + this.GoodsThumbnailWidth.value;
		data += '&GoodsThumbnailHeight=' + this.GoodsThumbnailHeight.value;
		data += '&TaxRate=' + this.TaxRate.value;
		__uploadGoodsDefaultThumbnail = _uploader.NeedUpload('Goods');
		if (!__uploadGoodsDefaultThumbnail)
			data += '&GoodsDefaultThumbnail=' + encodeURIComponent(this.GoodsDefaultThumbnail.value);
		
		__base.post({object:__object,operation:'SetBasicSettings',data:data,onSuccess:uploadGoodsDefaultThumbnail});
		
		return false;	
	};
	
	function uploadGoodsDefaultThumbnail()
	{
		if (!__uploadGoodsDefaultThumbnail)
		{
			Alert(_lang_operation_success);
			SetStatusMessage();
			$(':submit')[0].disabled = false;
			return;
		}
	
		SetStatusMessage(_lang_start_upload);
		_uploader.Init({Status:_lang_uploading,Params:'Lang=' + _lang + '&Object=InstanceConfig&Operation=UploadGoodsDefaultThumbnail'});
		_uploader.Upload('Goods', function()
		{
			if (arguments[0] != 0)
				Alert(arguments[1]);
			else
				Alert(_lang_operation_success);
			SetStatusMessage();
			$(':submit')[0].disabled = false;
		});
	}

	this.createAllGoodsThumbnail = function()
	{
		var me = $(this);
		me.prop('disabled', true);
		
		__base.post({object:'Goods',operation:'CreateAllThumbnail',data:{}});
		
		return false;	
	};
	
	this.setDiscount = function()
	{
		if (this.Amount.value.match(/^\d+$/) == null || parseInt(this.Amount.value) < 1 || parseInt(this.Amount.value) > 100)
		{
			Alert(_lang_discount_incorrect);
			return;
		}
		
		var data = 'RoleID=' + this.data('id');
		data += '&Amount=' + form.Amount.value;
		
		__base.post({object:'Discount',operation:'Set',data:{}});
		
		return false;
	};
	
	this.onSkuChange = function()
	{
		if (!this.value.match(/^\d+$/))
		{
			Alert(_lang_sku_must_be_number);
			return;
		}
		
		var example = '';
		var form = this.form;
		var count;
		
		count = parseInt(form.TypeNoDigit.value);
		for (var i = 0; i < count; i++)
			example += 0;
		example += '-';

		count = parseInt(form.GoodsNoDigit.value);
		for (var i = 0; i < count; i++)
			example += 0;
		example += '-';
		
		example += '1';
		count = parseInt(form.SpecNoDigit.value);
		for (var i = 0; i < count; i++)
			example += 0;
		example += 'N';
		for (var i = 0; i < count; i++)
			example += 0;
		
		$('#example').text(example);
	};
}
//End: 栏目设置
//-------------------------------------------------

//-------------------------------------------------
//Start : 子实例
function SubInstance()
{
	var __object = 'SubInstance',
		__base = new Base();

	this.add = function()
	{
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}
		
		if (this.User.value == '' || this.User.value != $(this.User).data('name'))
		{
			Alert(_lang_select_user, function(){this.User.select();}, this);
			return false;
		}
		
		var data = 'Name=' + encodeURIComponent(this.Name.value);
		data += '&UserID=' + $(this.User).data('id');
		data += '&UserName=' + $(this.User).data('name');
		
		__base.add({object:__object,data:data});
		
		return false;
	};

	this.modify = function()
	{
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}
		
		if (this.User.value == '' || this.User.value != $(this.User).data('name'))
		{
			Alert(_lang_select_user, function(){this.User.select();}, this);
			return false;
		}
		
		var data = 'Name=' + encodeURIComponent(this.Name.value);
		data += '&UserID=' + $(this.User).data('id');
		data += '&UserName=' + $(this.User).data('name');
		
		__base.modify({object:__object,data:data});
		
		return false;
	};
	
	this.update = function(operation, id)
	{
		if (this.tagName == 'BUTTON')
			operation = this.id;

		__base.update(__object, operation, id);
	};
	
	this.check = function()
	{
		var button = $(this);
		button[0].disabled = true;
		var input = button.prev();
		
		if (input.val() == '')
		{
			Alert(_lang_user_empty);
			button[0].disabled = false;
			return;
		}

		$.ajax(
		{
			url: 'ajax_check_user.aspx?Name=' + encodeURIComponent(input.val()),
			type: 'GET',
			error: function(request)
			{
				Alert(_lang_operation_fail);
				button[0].disabled = false;
			},
			success: function(data)
			{
				var user = eval($.trim(data));
				if (user.length == 0)
				{
					Alert(_lang_user_not_exist, function(){input.val('');}, this);
				}
				else
				{
					Alert(_lang_user_founded);
					input.data('id', user[0].ID).data('name', user[0].Name);
				}
				button[0].disabled = false;
			}
		});
	};
}
//End: 子实例
//-------------------------------------------------

//-------------------------------------------------
//Start: 品牌
function Brand()
{
	var __object = 'Brand',
		__base = new Base(),
		__uploadLogo;

	this.add = function()
	{
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}
		
		if (!IsAllowedType(this.Logo.value, this.LogoAllowedType.value))
		{
			Alert(_lang_type_must_be + this.LogoAllowedType.value, function(){this.Logo.select();}, this);
			return false;
		}
		
		var pageID = this.PageID.value;
		if (pageID == '')
			pageID = '{ID}';
	
		var data = 'Name=' + encodeURIComponent(this.Name.value);
		data += '&URL=' + encodeURIComponent(this.URL.value);
		data += '&Description=' + encodeURIComponent(this.Description.value);
		data += '&PageGenerate=' + $('[name=PageGenerate]:checked').val();
		data += '&PageTemplate=' + encodeURIComponent(this.PageTemplate.value);
		data += '&PageExtension=' + encodeURIComponent(this.PageExtension.value);
		__uploadLogo = _uploader.NeedUpload('Logo');
		if (!__uploadLogo)
			data += '&Logo=' + encodeURIComponent(this.Logo.value);
	
		var guid = __base.add({object:__object,data:data,silent:true});
		if (guid)
		{
			var id = __base.post({object:__object,operation:'GetInnerIDFromGuid',params:'ID=' + guid,silent:true});
			setPageID(pageID, guid, id);
		}
		
		return false;
	};

	function setPageID(pageID, guid, id)
	{
		pageID = pageID.replace(/\{ID\}/g, id);
		pageID = pageID.replace(/\{Guid\}/g, guid);
		
		__base.post({object:__object,operation:'Modify',data:'PageID=' + pageID,params:'ID=' + id,silent:true});
		uploadLogo(id);
	}

	this.modify = function()
	{
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}
		
		if (!IsAllowedType(this.Logo.value, this.LogoAllowedType.value))
		{
			Alert(_lang_type_must_be + this.LogoAllowedType.value, function(){this.Logo.select();}, this);
			return false;
		}
		
		if (this.PageID.value == '')
		{
			Alert(_lang_pageid_empty, function(){this.PageID.select();}, this);
			return false;
		}
		
		var pageID = this.PageID.value;
		pageID = pageID.replace(/\{Guid\}/g, _guid)
		pageID = pageID.replace(/\{ID\}/g, _id)
	
		var data = 'Name=' + encodeURIComponent(this.Name.value);
		data += '&URL=' + encodeURIComponent(this.URL.value);
		data += '&Description=' + encodeURIComponent(this.Description.value);
		data += '&PageGenerate=' + $('[name=PageGenerate]:checked').val();
		data += '&PageTemplate=' + encodeURIComponent(this.PageTemplate.value);
		data += '&PageID=' + encodeURIComponent(pageID);
		data += '&PageExtension=' + encodeURIComponent(this.PageExtension.value);
		__uploadLogo = _uploader.NeedUpload('Logo');
		if (!__uploadLogo)
			data += '&Logo=' + encodeURIComponent(this.Logo.value);
	
		__base.modify({object:__object,data:data,silent:true});
		uploadLogo(_id);
		
		return false;	
	};

	function uploadLogo(id)
	{
		if (!__uploadLogo)
		{
			Alert(_lang_operation_success);
			SetStatusMessage();
			$(':submit')[0].disabled = false;
			return;
		}
	
		SetStatusMessage(_lang_start_upload);
		_uploader.Init({Status:_lang_uploading,Params:'Lang=' + _lang + '&Object=Brand&Operation=UploadLogo&ID=' + id + '&AddWaterMark=' + $('#AddWaterMark')[0].checked});
		_uploader.Upload('Logo', function()
		{
			if (arguments[0] != 0)
				Alert(arguments[1]);
			else
				Alert(_lang_operation_success);
			SetStatusMessage();
			$(':submit')[0].disabled = false;
		});
	}
	
	this.del = function(id)
	{
		__base.update(__object, 'Delete', id);
	};
}
//End: 品牌
//-------------------------------------------------

//-------------------------------------------------
//Start: 物流公司
function Logistics()
{
	var __object = 'Logistics',
		__base = new Base();

	this.add = function()
	{
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}
		
		var data = 'Name=' + encodeURIComponent(this.Name.value);
	
		__base.add({object:__object,data:data});
		
		return false;
	};

	this.modify = function()
	{
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}
	
		var data = 'Name=' + encodeURIComponent(this.Name.value);
	
		__base.modify({object:__object,data:data});
		
		return false;	
	};
	
	this.del = function(id)
	{
		__base.update(__object, 'Delete', id);
	};
}
//End: 物流公司
//-------------------------------------------------

//-------------------------------------------------
//Start: 商品类别
function GoodsCategory()
{
	var __object = 'GoodsCategory',
		__base = new Base(),
		__uploadPicture;

	this.add = function()
	{
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}
		
		if (!IsAllowedType(this.Picture.value, this.PictureAllowedType.value))
		{
			Alert(_lang_type_must_be + this.PictureAllowedType.value, function(){this.Picture.select();}, this);
			return false;
		}
		
		var pageID = this.PageID.value;
		if (pageID == '')
			pageID = '{ID}';
	
		var data = 'Name=' + encodeURIComponent(this.Name.value);
		data += '&TypeID=' + encodeURIComponent(this.TypeID.value);
		data += '&ParentID=' + encodeURIComponent(this.ParentID.value);
		data += '&MetaKeywords=' + encodeURIComponent(this.MetaKeywords.value);
		data += '&MetaDescription=' + encodeURIComponent(this.MetaDescription.value);
		data += '&PageGenerate=' + $('[name=PageGenerate]:checked').val();
		data += '&PageTemplate=' + encodeURIComponent(this.PageTemplate.value);
		data += '&PageExtension=' + encodeURIComponent(this.PageExtension.value);
		__uploadPicture = _uploader.NeedUpload('Picture');
		if (!__uploadPicture)
			data += '&Picture=' + encodeURIComponent(this.Picture.value);
		data += '&IsRecommended=' + $('#IsRecommendedYes')[0].checked;
		data += '&IsHeld=' + $('#IsHeldYes')[0].checked;
	
		var guid = __base.add({object:__object,data:data,silent:true});
		if (guid)
		{
			var id = __base.post({object:__object,operation:'GetInnerIDFromGuid',params:'ID=' + guid,silent:true});
			setPageID(pageID, guid, id);
		}
		
		return false;	
	};
	
	function setPageID(pageID, guid, id)
	{
		pageID = pageID.replace(/\{ID\}/g, id);
		pageID = pageID.replace(/\{Guid\}/g, guid);
		
		__base.post({object:__object,operation:'Modify',data:'PageID=' + pageID,params:'ID=' + id,silent:true});
		uploadPicture(id);
	}

	this.modify = function()
	{
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}
		
		if (!IsAllowedType(this.Picture.value, this.PictureAllowedType.value))
		{
			Alert(_lang_type_must_be + this.PictureAllowedType.value, function(){this.Picture.select();}, this);
			return false;
		}
		
		var pageID = this.PageID.value;
		pageID = pageID.replace(/\{Guid\}/g, _guid)
		pageID = pageID.replace(/\{ID\}/g, _id)
	
		var data = 'Name=' + encodeURIComponent(this.Name.value);
		data += '&TypeID=' + encodeURIComponent(this.TypeID.value);
		data += '&ParentID=' + encodeURIComponent(this.ParentID.value);
		data += '&MetaKeywords=' + encodeURIComponent(this.MetaKeywords.value);
		data += '&MetaDescription=' + encodeURIComponent(this.MetaDescription.value);
		data += '&PageGenerate=' + $('[name=PageGenerate]:checked').val();
		data += '&PageID=' + encodeURIComponent(pageID);
		data += '&PageTemplate=' + encodeURIComponent(this.PageTemplate.value);
		data += '&PageExtension=' + encodeURIComponent(this.PageExtension.value);
		__uploadPicture = _uploader.NeedUpload('Picture');
		if (!__uploadPicture)
			data += '&Picture=' + encodeURIComponent(this.Picture.value);
		if (_recommend == 0 || !$('#IsRecommendedYes')[0].checked)
			data += '&IsRecommended=' + $('#IsRecommendedYes')[0].checked;
		if (_hold == 0 || !$('#IsHeldYes')[0].checked)
			data += '&IsHeld=' + $('#IsHeldYes')[0].checked;
	
		__base.modify({object:__object,data:data,silent:true});
		uploadPicture(_id);
		
		return false;	
	};

	function uploadPicture(id)
	{
		if (!__uploadPicture)
		{
			Alert(_lang_operation_success);
			SetStatusMessage();
			$(':submit')[0].disabled = false;
			return;
		}
	
		SetStatusMessage(_lang_start_upload);
		_uploader.Init({Status:_lang_uploading,Params:'Lang=' + _lang + '&Object=' + __object + '&Operation=UploadPicture&ID=' + id + '&AddWaterMark=' + $('#AddWaterMark')[0].checked});
		_uploader.Upload('Picture', function()
		{
			if (arguments[0] != 0)
				Alert(arguments[1]);
			else
				Alert(_lang_operation_success);
			SetStatusMessage();
			$(':submit')[0].disabled = false;
		});
	}

	this.modifyName = function()
	{
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}
		
		var data = 'Name=' + encodeURIComponent(this.Name.value);
	
		__base.modify({object:__object,data:data,id:$(this).closest('tr').attr('ItemID')});
		
		return false;
	};
	
	this.update = function(operation, id)
	{
		if (this.tagName == 'BUTTON')
			operation = this.id;

		__base.update(__object, operation, id);
	};
		
	this.move = function(from, to)
	{
		var action = 'Move';
		var sort = $('#Sort').val();
		if (sort == '2' || sort == '3')
			action = 'MoveRecommend';
		else if (sort == '4' || sort == '5')
			action = 'MoveHold';
	
		__base.move(__object, action, from, to);
	};
	
	this.del = function(id)
	{
		__base.update(__object, 'Delete', id);
	};
}
//End: 商品类别
//-------------------------------------------------

//-------------------------------------------------
//Start: 类型
function Type()
{
	var __object = 'Type',
		__base = new Base();

	this.add = function()
	{
		//编号位数是否正确
		if (this.No.value.length != _typeNoDigit)
		{
			Alert(_lang_digit_incorrect.replace('{Digit}', _typeNoDigit), function(){this.No.select();}, this);
			return false;
		}
		
		//编号是否是数字
		if (!this.No.value.match(/^\d+$/))
		{
			Alert(_lang_all_must_be_number, function(){this.No.select();}, this);
			return false;
		}
		
		//编号是否存在
		var exist = __base.post({object:__object,operation:'IsNoExist',params:'No=' + this.No.value,silent:true});
		SetStatusMessage();
		if (exist.toLowerCase() == 'true')
		{
			Alert(_lang_no_exist, function(){this.No.select();}, this);
			return false;
		}
		
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}
		
		var data = 'No=' + encodeURIComponent(this.No.value);
		data += '&Name=' + encodeURIComponent(this.Name.value);
		data += '&Kind=' + encodeURIComponent(this.Kind.value);
	
		__base.add({object:__object,data:data});
		
		return false;
	};

	this.modify = function()
	{
		//编号位数是否正确
		if (this.No.value.length != _typeNoDigit)
		{
			Alert(_lang_digit_incorrect, function(){this.No.select();}, this);
			return false;
		}
		
		//编号是否是数字
		if (!this.No.value.match(/^\d+$/))
		{
			Alert(_lang_all_must_be_number, function(){this.No.select();}, this);
			return false;
		}
		
		//编号是否存在
		if (this.No.value != $(this.No).data('old'))
		{
			var exist = __base.post({object:__object,operation:'IsNoExist',params:'No=' + this.No.value,silent:true});
			if (exist.toLowerCase() == 'true')
			{
				Alert(_lang_no_exist, function(){this.No.select();}, this);
				return false;
			}
		}
		
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}
		
		var data = 'No=' + encodeURIComponent(this.No.value);
		data += '&Name=' + encodeURIComponent(this.Name.value);
		data += '&Kind=' + encodeURIComponent(this.Kind.value);
	
		__base.modify({object:__object,data:data});
		
		//
		$(this.No).data('old', this.No.value);
		
		return false;	
	};
	
	this.del = function(id)
	{
		__base.update(__object, 'Delete', id);
	};
}
//End: 类型
//-------------------------------------------------

//-------------------------------------------------
//Start: 属性
function Property()
{
	var __object = 'Type.Property',
		__base = new Base();

	this.add = function()
	{
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}
		
		var data = 'TypeID=' + _typeID;
		data += '&Name=' + encodeURIComponent(this.Name.value);
		data += '&Control=' + encodeURIComponent(this.Control.value);
	
		__base.add({object:__object,data:data});
		Search();
		
		return false;
	};

	this.modify = function()
	{
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}
		
		var data = 'Name=' + encodeURIComponent(this.Name.value);
	
		__base.modify({object:__object,data:data});
		
		return false;
	};

	this.modifyName = function()
	{
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}
		
		var data = 'Name=' + encodeURIComponent(this.Name.value);
	
		__base.modify({object:__object,data:data,id:$(this).closest('tr').data('id')});
		
		return false;
	};

	this.del = function(id)
	{
		__base.update(__object, 'Delete', id, false);
		$('#Row' + id).remove();
	};
	
	this.move = function(from, to)
	{
		__base.move(__object, 'Move', from, to);
	};	
}
//End: 属性
//-------------------------------------------------

//-------------------------------------------------
//Start: 属性选项
function PropertyOption()
{
	var __object = 'Type.Property.Option',
		__base = new Base();

	this.add = function()
	{
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}
		
		var data = 'PropertyID=' + _propertyID;
		data += '&Name=' + encodeURIComponent(this.Name.value);
	
		__base.add({object:__object,data:data});
		Search();
		
		return false;
	};

	this.modify = function()
	{
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}
		
		var data = 'Name=' + encodeURIComponent(this.Name.value);
	
		__base.modify({object:__object,data:data});
		
		return false;
	};

	this.modifyName = function()
	{
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}
		
		var data = 'Name=' + encodeURIComponent(this.Name.value);
	
		__base.modify({object:__object,data:data,id:$(this).closest('tr').data('id')});
		
		return false;
	};

	this.del = function(id)
	{
		__base.update(__object, 'Delete', id, false);
		$('#Row' + id).remove();
	};
	
	this.move = function(from, to)
	{
		__base.move(__object, 'Move', from, to);
	};	
}
//End: 属性选项
//-------------------------------------------------

//-------------------------------------------------
//Start: 规格
function Spec()
{
	var __object = 'Type.Spec',
		__base = new Base();

	this.add = function()
	{
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}

		//处理序号		
		var sort = 1;
		var sorts = $('[Name=Sort]');
		for (var i = 0; i < sorts.length; i++)
		{
			if (sort <= parseInt(sorts[i].value))
				sort = parseInt(sorts[i].value) + 1;
		}
		if (sort > 9)
		{
			Alert(_lang_exceeded);
			return false;
		}
		
		var data = 'TypeID=' + _typeID;
		data += '&Name=' + encodeURIComponent(this.Name.value);
		data += '&IsColor=' + this.IsColor.checked;
		data += '&CanUpload=' + this.CanUpload.checked;
		data += '&Sort=' + sort;
	
		__base.add({object:__object,data:data});
		Search();
		
		return false;
	};

	this.modify = function()
	{
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}
		
		var data = 'Name=' + encodeURIComponent(this.Name.value);
		data += '&IsColor=' + $('#IsColorYes')[0].checked;
		data += '&CanUpload=' + $('#CanUploadYes')[0].checked;
	
		__base.modify({object:__object,data:data});
		
		return false;
	};

	this.modifyName = function()
	{
		//序号必须从1到9
		if (!this.Sort.value.match(/^[1-9]$/))
		{
			Alert(_lang_sort_incorrect, function(){this.Sort.select();}, this);
			return false;
		}
		
		//序号不能重复
		var sorts = $('[Name=Sort]');
		for (var i = 0; i < sorts.length; i++)
		{
			if (sorts[i] != this.Sort && sorts[i].value == this.Sort.value)
			{
				Alert(_lang_sort_exist, function(){this.Sort.select();}, this);
				return false;
			}
		}
		
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}

		var data = 'Name=' + encodeURIComponent(this.Name.value);
		data += '&Sort=' + this.Sort.value;
	
		__base.modify({object:__object,data:data,id:$(this).closest('tr').data('id')});
		
		return false;
	};

	this.del = function(id)
	{
		__base.update(__object, 'Delete', id, false);
		$('#Row' + id).remove();
	};
	
	this.move = function(from, to)
	{
		__base.move(__object, 'Move', from, to);
	};	
}
//End: 规格
//-------------------------------------------------

//-------------------------------------------------
//Start: 规格选项
function SpecOption()
{
	var __object = 'Type.Spec.Option',
		__base = new Base();

	this.add = function()
	{
		//编号必须是数字
		if (!this.No.value.match(/^\d+$/))
		{
			Alert(_lang_no_must_be_number, function(){this.No.select();}, this);
			return false;
		}
		
		//编号位数要正确
		if (this.No.value.length != _specNoDigit)
		{
			Alert(_lang_no_digit_incorrect.replace('{Digit}', _specNoDigit), function(){this.No.select();}, this);
			return false;
		}
		
		//编号不能重复
		var nos = $('#List [name=No]');
		for (var i = 0; i < nos.length; i++)
		{
			if (nos[i].value == this.No.value)
			{
				Alert(_lang_no_exist, function(){this.No.select();}, this);
				return false;
			}
		}

		//名称不能空
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}
		
		var data = 'SpecID=' + _specID;
		data += '&No=' + this.No.value;
		data += '&Name=' + encodeURIComponent(this.Name.value);
		if (typeof(this.Color) != 'undefined')
			data += '&Color=' + encodeURIComponent(this.Color.value);
	
		__base.add({object:__object,data:data});
		Search();
		
		return false;
	};

	this.modify = function()
	{
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}
		
		var data = 'Name=' + encodeURIComponent(this.Name.value);
		if (typeof(this.Color) != 'undefined')
			data += '&Color=' + encodeURIComponent(this.Color.value);
	
		__base.modify({object:__object,data:data});
		
		return false;
	};

	this.modifyName = function()
	{
		//编号必须是数字
		if (!this.No.value.match(/^\d+$/))
		{
			Alert(_lang_no_must_be_number, function(){this.No.select();}, this);
			return false;
		}
		
		//编号位数要正确
		if (this.No.value.length != _specNoDigit)
		{
			Alert(_lang_no_digit_incorrect.replace('{Digit}', _specNoDigit), function(){this.No.select();}, this);
			return false;
		}
		
		//编号不能重复
		var nos = $('#List [name=No]');
		for (var i = 0; i < nos.length; i++)
		{
			if (nos[i] != this.No && nos[i].value == this.No.value)
			{
				Alert(_lang_no_exist, function(){this.No.select();}, this);
				return false;
			}
		}

		//名称不能空
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}
		
		var data = 'No=' + this.No.value;
		data += '&Name=' + encodeURIComponent(this.Name.value);
	
		__base.modify({object:__object,data:data,id:$(this).closest('tr').data('id')});
		
		return false;
	};

	this.del = function(id)
	{
		__base.update(__object, 'Delete', id, false);
		$('#Row' + id).remove();
	};
}
//End: 规格选项
//-------------------------------------------------

//-------------------------------------------------
//Start: 商品
function Goods()
{
	var __object = 'Goods',
		__base = new Base(),
		__userPriceIndex,
		__userPrices = [],
		__morePictureIndex,
		__morePictures = [],
		__specPictureIndex,
		__specPictures = [],
		__properties = [],
		__specs = [],
		__uploadPicture,
		__uploadThumbnail,
		__createTime;

	this.init = function()
	{
		$('#ThumbnailRow').css('display', $('#MakeThumbnail')[0].checked ? 'none' : '');
		$('#MakeThumbnail').click(function(){$('#ThumbnailRow').css('display', this.checked ? 'none' : '');});
		
		$('[name=CategoryID]').change();
		
		//初始化用户价格
		if (_userPrices.length > 0)
		{
			__userPrices = _userPrices;

			for (var i = 0; i < _userPrices.length; i++)
			{
				var checkbox = $('[value="' + _userPrices[i].roleId + '"]').prop('checked', true);
				checkbox.data('id', _userPrices[i].id);
				checkbox.closest('tr').find(':text').val(_userPrices[i].price);
			}

			$('#UserPrice').click();
		}
		
		for (var i = 0; i < _morePictures.length; i++)
		{
			if (_morePictures[i].specOptionId == '')
			{
				$('#MorePicture').click();
				var row = $('#more-picture-table tr:last');
				row.data('id', _morePictures[i].id);
				$('[id*=Textbox]', row).eq(0).val(_morePictures[i].url).end().eq(1).val(_morePictures[i].thumbnail);
				$('[id*=View]', row).attr('src', _morePictures[i].url).show();
			}
			
			//打开小图
			$(':checkbox', '#more-picture-div').prop('checked', false);
			$('p', '#more-picture-div').show();
		}
		
		//空类型编号
		no = '';
		for (var i = 0; i < _typeNoDigit; i++)
			no += 0;
		$('[name=CategoryID] option:first').data('typeNo', no);
	};

	function prepareData(form)
	{		
		//编号是否存在
		if ($(form.No).data('old') == 'undefined' || form.No.value != $(form.No).data('old'))
		{
			var exist = __base.post({object:__object,operation:'IsNoExist',params:'No=' + form.No.value,silent:true});
			SetStatusMessage();
			if (exist.toLowerCase() == 'true')
			{
				Alert(_lang_no_exist, function(){form.No.select();}, this);
				return null;
			}

			//编号位数是否正确
			if (form.No.value.length != _goodsNoDigit)
			{
				Alert(_lang_digit_incorrect.replace('{Digit}', _goodsNoDigit), function(){form.No.select();}, this);
				return null;
			}
		}
		
		if (form.Name.value == '')
		{
			Alert(_lang_name_empty, function(){form.Name.select();}, this);
			return null;
		}
		
		if (!form.Stock.value.match(/^\d+$/))
		{
			Alert(_lang_stock_incorrect, function(){form.Stock.select();}, this);
			return null;
		}
		
		if (!form.MarketPrice.value.match(/^\d+(\.\d{1,2})?$/))
		{
			Alert(_lang_market_price_incorrect, function(){form.MarketPrice.select();}, this);
			return null;
		}
		
		if (!form.SalePrice.value.match(/^\d+(\.\d{1,2})?$/))
		{
			Alert(_lang_sale_price_incorrect, function(){form.SalePrice.select();}, this);
			return null;
		}
		
		if ($('#Promote')[0].checked)
		{
			if (!form.PromotePrice.value.match(/^\d+(\.\d{1,2})?$/))
			{
				Alert(_lang_promote_price_incorrect, function(){form.PromotePrice.select();}, this);
				return null;
			}
	
			var dateTime = /^(\d{1,4})(-|\/)(\d{1,2})(-|\/)(\d{1,2})( (\d{1,2}):(\d{1,2}):(\d{1,2}))?$/;
			if (!dateTime.test(form.PromoteStart.value))
			{
				Alert(_lang_promote_start_incorrect, function(){form.PromoteStart.select();}, this);
				return null;
			}
			if (!dateTime.test(form.PromoteEnd.value))
			{
				Alert(_lang_promote_end_incorrect, function(){form.PromoteEnd.select();}, this);
				return null;
			}
		}
		
		if (!form.Weight.value.match(/^\d+(\.\d{1,3})?$/))
		{
			Alert(_lang_weight_incorrect, function(){form.Weight.select();}, this);
			return null;
		}
		
		if (!form.Volume.value.match(/^\d+(\.\d{1,3})?$/))
		{
			Alert(_lang_volume_incorrect, function(){form.Volume.select();}, this);
			return null;
		}

		//
		if (!IsAllowedType(form.Picture.value, form.PictureAllowedType.value))
		{
			Alert(_lang_picture_type_must_be + form.PictureAllowedType.value, function(){form.Picture.select();}, this);
			return null;
		}
		
		//
		if (!IsAllowedType(form.Thumbnail.value, form.PictureAllowedType.value))
		{
			Alert(_lang_picture_type_must_be + form.PictureAllowedType.value, function(){form.Thumbnail.select();}, this);
			return null;
		}

		//检查会员价
		var userPriceItems = null;
		if (typeof(form.UserPrice) != 'undefined' && form.UserPrice.checked)
		{
			var userPriceItems = $('#user-price-container :checked');
			for (var i = 0; i < userPriceItems.length; i++)
			{
				var input = userPriceItems.eq(i).closest('tr').find(':text');
				if (!input.val().match(/^\d+(\.\d{1,2})?$/))
				{
					Alert(_lang_user_price_incorrect, function(){input[0].select();}, this);
					return null;
				}
			}
		}
		
		//准备会员价
		var userPrices = __userPrices;
		__userPriceIndex = 0;
		__userPrices = [];
		if (userPriceItems)
		{
			userPriceItems.each(function()
			{
				var userPrice = {};
				userPrice.element = $(this);
				userPrice.roleId = this.value;
				userPrice.price = $(this).closest('tr').find(':text').val();

				userPrice.id = $(this).data('id');
				if (!userPrice.id)
				{
					userPrice.operation = 'Add';
				}
				else
				{
					var j = 0;
					for (; j < userPrices.length; j++)
					{
						if (userPrice.id == userPrices[j].id && (userPrice.price != userPrices[j].price))
							break;
					}
					
					if (j < userPrices.length)
						userPrice.operation = 'Modify';
				}
	
				__userPrices.push(userPrice);
			});
		}

		for (var i = 0; i < userPrices.length; i++)
		{
			var del = false;
			
			if (userPriceItems)
			{
				var j = 0;
				for (; j < userPriceItems.length; j++)
				{
					if (userPrices[i].id == userPriceItems.eq(j).data('id'))
						break;
				}
	
				if (userPriceItems && j >= userPriceItems.length)
				{
					del = true;
				}
			}
			else
			{
				del = true;
			}

			if (del)
			{
				userPrices[i].operation = 'Delete';
				__userPrices.push(userPrices[i]);
			}
		}
	
		//检查并获取更多图片
		__morePictureIndex = 0;
		__morePictures.length = 0;
		var items = $('#more-picture-div :text[name*=Picture]');
		for (var i = 0; i < items.length; i++)
		{
			if (items[i].value == '')
				continue;
				
			if (!IsAllowedType(items[i].value, form.PictureAllowedType.value))
			{
				Alert(_lang_picture_type_must_be + form.PictureAllowedType.value, function(){items[i].select();}, this);
				return null;
			}
			
			var row = items.eq(i).closest('tr');
			var index = row[0].rowIndex;
	
			var morePicture = {id:row.data('id'),url:items[i].value,pictureFormId:'Picture' + index,pictureUpload:_uploader.NeedUpload('Picture' + index),makeThumbnail:$('#MakeThumbnail' + index)[0].checked,addWaterMark:$('#AddWaterMarkToMorePicture' + index)[0].checked};
			
			if (!morePicture.makeThumbnail)
			{
				var thumbnail = items.eq(i).parent().find('p :text[name*=Thumbnail]');
				morePicture.thumbnail = thumbnail.val();
				morePicture.thumbnailFormID = 'Thumbnail' + index;
				morePicture.thumbnailUpload = _uploader.NeedUpload(morePicture.thumbnailFormID);
			}
	
			__morePictures.push(morePicture);
		}

		//获取属性
		__properties = [];
		var items = $('#property-table th :checked');
		for (var i = 0; i < items.length; i++)
		{
			var property = {id:items.eq(i).data('id'),optionIds:[],value:''};
			var control = items.eq(i).data('control');
			if (control == 'CheckBox' || control == 'Radio' || control == 'Select' || control == 'List')
			{
				items.eq(i).closest('tr').find('td :checked,td :selected').each(function()
				{
					property.optionIds.push(this.value);
				});
			}
			else
			{
				property.value = items.eq(i).closest('tr').find(':text,textarea').val();
			}
			__properties.push(property);
		}
		
		//检查并获取规格图片
		__specPictureIndex = 0;
		__specPictures.length = 0;
		var items = $('.spec-upload-table :text');
		for (var i = 0; i < items.length; i++)
		{
			if (items[i].value == '')
				continue;
				
			if (!IsAllowedType(items[i].value, form.PictureAllowedType.value))
			{
				Alert(_lang_picture_type_must_be + form.PictureAllowedType.value, function(){items[i].select();}, this);
				return null;
			}
			
			__specPictures.push({id:items.eq(i).data('id'),url:items[i].value,formId:items.eq(i).data('formId'),needUpload:_uploader.NeedUpload(items.eq(i).data('formId'))});
		}
		
		//检查并获取规格
		__specs = [];
		var items = $('#spec-price-table :checked');
		for (var i = 0; i < items.length; i++)
		{
			var inputs = items.eq(i).closest('tr').find(':text');
			
			var price = inputs[2];
			if (!price.value.match(/^\d+(\.\d{1,2})?$/))
			{
				Alert(_lang_sale_price_incorrect, function(){price.select();}, this);
				return null;
			}
			
			var promotePrice = inputs[3];
			if (!promotePrice.value.match(/^\d+(\.\d{1,2})?$/))
			{
				Alert(_lang_promote_price_incorrect, function(){promotePrice.select();}, this);
				return null;
			}
			
			var stock = inputs[4];
			if (!stock.value.match(/^\d+$/))
			{
				Alert(_lang_stock_incorrect, function(){stock.select();}, this);
				return null;
			}
			
			__specs.push({no:inputs[0].value,barCode:inputs[1].value,id:items.eq(i).data('id'),optionIds:items.eq(i).data('optionIds').split(','),stock:stock.value,price:price.value,promotePrice:promotePrice.value});
		}
		
		__createTime = new Date();
	
		SetCookie('CategoryID', form.CategoryID.value, 10*360*24*60);
		SetCookie('BrandID', form.BrandID.value, 10*360*24*60);

		var data = 'Name=' + encodeURIComponent(form.Name.value);
		data += '&No=' + form.No.value;
		data += '&BarCode=' + form.BarCode.value;

		var category = $('[name=CategoryID] :selected');
		data += '&CategoryID=' + category.val();
		data += '&CategoryName=' + encodeURIComponent(category.data('name'));
		data += '&CategoryPageGenerate=' + category.data('pageGenerate');
		data += '&CategoryPageTemplate=' + encodeURIComponent(category.data('pageTemplate'));
		data += '&CategoryPageID=' + encodeURIComponent(category.data('pageId'));
		data += '&CategoryPageExtension=' + category.data('pageExtension');

		var brand = $('[name=BrandID] :selected');
		data += '&BrandID=' + brand.val();
		data += '&BrandName=' + encodeURIComponent(brand.data('name'));
		data += '&BrandPageGenerate=' + brand.data('pageGenerate');
		data += '&BrandPageTemplate=' + brand.data('pageTemplate');
		data += '&BrandPageID=' + encodeURIComponent(brand.data('pageId'));
		data += '&BrandPageExtension=' + brand.data('pageExtension');

		data += '&Stock=' + form.Stock.value;

		data += '&Property=' + encodeURIComponent(JSON.stringify(__properties));
		data += '&SalePrice=' + form.SalePrice.value;
		data += '&MarketPrice=' + form.MarketPrice.value;

		data += '&Promote=' + $('#Promote')[0].checked;
		if ($('#Promote')[0].checked)
		{
			data += '&PromotePrice=' + form.PromotePrice.value;
			data += '&PromoteStart=' + form.PromoteStart.value;
			data += '&PromoteEnd=' + form.PromoteEnd.value;
		}

		__uploadPicture = _uploader.NeedUpload('Picture');
		if (!__uploadPicture)
			data += '&Picture=' + encodeURIComponent(form.Picture.value);

		if (form.MakeThumbnail.checked)
		{
			__uploadThumbnail = false;
		}
		else
		{
			__uploadThumbnail = _uploader.NeedUpload('Thumbnail');
			if (!__uploadThumbnail)
				data += '&Thumbnail=' + encodeURIComponent(form.Thumbnail.value);
		}

		data += '&FreightTemplateID=' + encodeURIComponent(form.FreightTemplateID.value);
		data += '&Weight=' + encodeURIComponent(form.Weight.value);
		data += '&Volume=' + encodeURIComponent(form.Volume.value);
		data += '&Spec=' + encodeURIComponent(JSON.stringify(__specs));
		data += '&Description=' + encodeURIComponent(CKEDITOR.instances[form.Description.id].getData());
		data += '&IsReleased=' + form.IsReleased.checked;
		data += '&IsRecommended=' + $('#IsRecommended')[0].checked;
		data += '&IsHeld=' + $('#IsHeld')[0].checked;
		data += '&PageGenerate=' + $('[name=PageGenerate]:checked').val();
		data += '&PageTemplate=' + encodeURIComponent(form.PageTemplate.value);
		data += '&PageExtension=' + encodeURIComponent(form.PageExtension.value);
		data += '&MetaKeywords=' + encodeURIComponent(form.MetaKeywords.value);
		data += '&MetaDescription=' + encodeURIComponent(form.MetaDescription.value);
		
		return data;
	}

	this.add = function()
	{
		var data = prepareData(this);
		if (!data)
			return false;
		
		var pageID = this.PageID.value;
		if (pageID == '')
			pageID = this.No.value;
		
		data += '&CreateTime=' + FormatDate(__createTime, 'YYYY-MM-DD hh:mm:ss.SSS');
	
		var guid = __base.add({object:__object,data:data,silent:true});
		if (guid)
		{
			var id = __base.post({object:__object,operation:'GetInnerIDFromGuid',params:'ID=' + guid,silent:true});
			setPageID(pageID, guid, id);
			
			$.get('ajax_get_unique_no.aspx', function(data){$('[name=No]').val($.trim(data));});			
		}

		return false;
	};
	
	function setPageID(pageID, guid, id)
	{
		pageID = pageID.replace(/\{Guid\}/g, guid);
		pageID = pageID.replace(/\{ID\}/g, id);
		pageID = pageID.replace(/\{YYYYMMDDhhmmss\}/g, FormatDate(__createTime, 'YYYYMMDDhhmmss'));
		pageID = pageID.replace(/\{YYYY-MM-DD\/hhmmss\}/g, FormatDate(__createTime, 'YYYY-MM-DD/hhmmss'));
		pageID = pageID.replace(/\{YYYY\/MM\/DD\/hhmmss\}/g, FormatDate(__createTime, 'YYYY/MM/DD/hhmmss'));
		pageID = pageID.replace(/\{YYYY\/MM-DD\/hhmmss\}/g, FormatDate(__createTime, 'YYYY/MM-DD/hhmmss'));
		
		__base.post({object:__object,operation:'Modify',data:'PageID=' + pageID,params:'ID=' + id,silent:true});
		setUserPrice(guid, id);
	}

	this.modify = function()
	{
		var data = prepareData(this);
		if (!data)
			return false;
	
		if (!this.HitCount.value.match(/^\d+$/))
		{
			Alert(_lang_hitcount_incorrect, function(){this.HitCount.select();}, this);
			return false;
		}
	
		if (!this.Up.value.match(/^\d+$/))
		{
			Alert(_lang_up_incorrect, function(){this.Up.select();}, this);
			return false;
		}
	
		if (!this.Down.value.match(/^\d+$/))
		{
			Alert(_lang_down_incorrect, function(){this.Down.select();}, this);
			return false;
		}
		
		if (this.PageID.value == "")
		{
			Alert(_lang_pageid_empty, function(){this.PageID.select();}, this);
			return false;
		}
		
		var pageID = this.PageID.value;
		pageID = pageID.replace(/\{Guid\}/g, _guid)
		pageID = pageID.replace(/\{ID\}/g, _id)
		pageID = pageID.replace(/\{YYYYMMDDhhmmss\}/g, FormatDate(__createTime, 'YYYYMMDDhhmmss'));
		pageID = pageID.replace(/\{YYYY-MM-DD\/hhmmss\}/g, FormatDate(__createTime, 'YYYY-MM-DD/hhmmss'));
		pageID = pageID.replace(/\{YYYY\/MM\/DD\/hhmmss\}/g, FormatDate(__createTime, 'YYYY/MM/DD/hhmmss'));
		pageID = pageID.replace(/\{YYYY\/MM-DD\/hhmmss\}/g, FormatDate(__createTime, 'YYYY/MM-DD/hhmmss'));
	
		data += '&UpdateTime=' + encodeURIComponent(this.UpdateTime.value);
		data += '&HitCount=' + this.HitCount.value;
		data += '&Up=' + this.Up.value;
		data += '&Down=' + this.Down.value;
		data += '&PageID=' + encodeURIComponent(this.PageID.value);
	
		__base.modify({object:__object,data:data,silent:true});
		setUserPrice(_guid, _id);
		
		$(this.No).data('old', this.No.value);

		return false;
	};

	function setUserPrice(guid, id)
	{
		if (__userPriceIndex >= __userPrices.length)
		{
			for (var i = __userPrices.length - 1; i >= 0; i--)
			{
				if (__userPrices[i].operation == 'Delete')
					__userPrices.splice(i, 1);
			}
			
			uploadPicture(guid, id);
			return;
		}

		var object = 'UserPrice';
		var userPrice = __userPrices[__userPriceIndex];
		if (userPrice.operation == 'Add')
		{
			var data = 'GoodsID=' + guid;
			data += '&RoleID=' + userPrice.roleId;
			data += '&Price=' + userPrice.price;
			
			var userPriceGuid = __base.post({object:object,operation:'Add',data:data,silent:true});
			if (typeof(_id) != 'undefined')
			{
				userPrice.id = __base.post({object:object,operation:'GetInnerIDFromGuid',params:'ID=' + userPriceGuid,silent:true});
				userPrice.element.data('id', userPrice.id);
			}
		}
		else if (userPrice.operation == 'Modify')
		{
			var data = 'Price=' + userPrice.price;
			
			__base.post({object:object,operation:'Modify',data:data,params:'ID=' + userPrice.id,silent:true});
		}
		else if (userPrice.operation == 'Delete')
		{
			__base.post({object:object,operation:'Delete',params:'ID=' + userPrice.id,silent:true});
		}
	
		__userPriceIndex++;
		setUserPrice(guid);
	}

	function uploadPicture(guid, id)
	{
		if (!__uploadPicture)
		{
			uploadThumbnail(guid, id);
			return;
		}
	
		_uploader.Init({Status:_lang_uploading_picture,Params:'Lang=' + _lang + '&Object=' + __object + '&Operation=UploadPicture&ID=' + id + '&MakeThumbnail=' + $('#MakeThumbnail')[0].checked + '&AddWaterMark=' + $('#AddWaterMarkToPicture')[0].checked});
		_uploader.Upload('Picture', function()
		{
			if (arguments[0] != 0)
			{
				Alert(arguments[1]);
				SetStatusMessage();
				$(':submit')[0].disabled = false;
			}
			else
			{
				$('#PictureTextbox').val(arguments[1]);
				$('#PictureView').attr('src', arguments[1]);
				uploadThumbnail(guid, id);
			}
		});
	}

	function uploadThumbnail(guid, id)
	{
		if (!__uploadThumbnail)
		{
			addMorePicture(guid);
			return;
		}
	
		_uploader.Init({Status:_lang_uploading_thumbnail,Params:'Lang=' + _lang + '&Object=' + __object + '&Operation=UploadThumbnail&ID=' + id + '&AddWaterMark=' + $('#AddWaterMarkToThumbnail')[0].checked});
		_uploader.Upload('Thumbnail', function()
		{
			if (arguments[0] != 0)
			{
				Alert(arguments[1]);
				SetStatusMessage();
				$(':submit')[0].disabled = false;
			}
			else
			{
				$('#ThumbnailTextbox').val(arguments[1]);
				$('#ThumbnailView').attr('src', arguments[1]);
				
				addMorePicture(guid);
			}
		});
	}

	function addMorePicture(guid)
	{
		if (__morePictureIndex >= __morePictures.length)
		{
			addSpecPicture(guid);
			return;
		}
		
		var o = __morePictures[__morePictureIndex++];
		
		var data = 'GoodsID=' + guid;
		if (!o.pictureUpload)
			data += '&URL=' + encodeURIComponent(o.url);
		if (o.thumbnail && !o.thumbnailUpload)
			data += '&Thumbnail=' + encodeURIComponent(o.thumbnail);
		
		if (o.id)
		{
			if (!o.pictureUpload || !o.thumbnailUpload)
				__base.modify({object:'Goods.Pictures',data:data,id:o.id,silent:true});
			uploadMorePicture(guid, o.id, o);
		}
		else
		{
			var result = __base.add({object:'Goods.Pictures',data:data,silent:true});
			if (result)
			{
				var id = __base.post({object:'Goods.Pictures',operation:'GetInnerIDFromGuid',params:'ID=' + result,silent:true});
				uploadMorePicture(guid, id, o);
			}
		}
	}
	
	function uploadMorePicture(guid, id, o)
	{
		if (!o.pictureUpload)
		{
			uploadMoreThumbnail(guid, id, o);
			return;
		}
		
		_uploader.Init({Status:_lang_uploading_more_picture,Params:'Lang=' + _lang + '&Object=Goods.Pictures&Operation=UploadPicture&ID=' + id + '&MakeThumbnail=' + o.makeThumbnail + '&AddWaterMark=' + o.addWaterMark});
		_uploader.Upload(o.pictureFormId, function()
		{
			if (arguments[0] != 0)
			{
				Alert(arguments[1]);
				SetStatusMessage();
				$(':submit')[0].disabled = false;
			}
			else
			{
				$('#' + o.pictureFormId + 'Textbox').val(arguments[1]);
				$('#' + o.pictureFormId + 'View').attr('src', arguments[1]);
				
				uploadMoreThumbnail(guid, id, o);
			}
		});
	}
	
	function uploadMoreThumbnail(guid, id, o)
	{
		if (!o.thumbnailUpload)
		{
			addMorePicture(guid);
			return;
		}
		
		_uploader.Init({Status:_lang_uploading_more_picture,Params:'Lang=' + _lang + '&Object=Goods.Pictures&Operation=UploadThumbnail&ID=' + id});
		_uploader.Upload(o.thumbnailFormId, function()
		{
			if (arguments[0] != 0)
			{
				Alert(arguments[1]);
				SetStatusMessage();
				$(':submit')[0].disabled = false;
			}
			else
			{
				$('#' + o.thumbnailFormId + 'Textbox').val(arguments[1]);
				$('#' + o.thumbnailFormId + 'View').attr('src', arguments[1]);
				
				addMorePicture(guid);
			}
		});
	}
	
	function addSpecPicture(guid)
	{
		if (__specPictureIndex >= __specPictures.length)
		{
			Alert(_lang_operation_success);
			SetStatusMessage();
			$(':submit')[0].disabled = false;
			return;
		}
		
		var o = __specPictures[__specPictureIndex++];
		
		var data = 'GoodsID=' + guid;
		data += '&SpecOptionID=' + o.id;
		if (!o.needUpload)
			data += '&URL=' + encodeURIComponent(o.url);
		
		var result = __base.add({object:'Goods.Pictures',data:data,silent:true});
		if (result)
		{
			var id = __base.post({object:'Goods.Pictures',operation:'GetInnerIDFromGuid',params:'ID=' + result,silent:true});
			uploadSpecPicture(guid, id, o);
		}
	}
	
	function uploadSpecPicture(guid, id, o)
	{
		if (!o.needUpload)
		{
			addSpecPicture(guid);
			return;
		}
		
		_uploader.Init({Status:_lang_uploading_spec_picture,Params:'Lang=' + _lang + '&Object=Goods.Pictures&Operation=UploadPicture&ID=' + id + '&MakeThumbnail=true'});
		_uploader.Upload(o.formId, function()
		{
			if (arguments[0] != 0)
			{
				Alert(arguments[1]);
				SetStatusMessage();
				$(':submit')[0].disabled = false;
			}
			else
			{
				$('#' + o.formId + 'Textbox').val(arguments[1]);
				$('#' + o.formId + 'View').attr('src', arguments[1]);
				
				addSpecPicture(guid);
			}
		});
	}
	
	this.onPromoteClick = function()
	{
		var form = this.form;
		if (this.checked)
		{
			form.PromotePrice.disabled = false;
			form.PromoteStart.disabled = false;
			form.PromoteEnd.disabled = false;
			form.PromoteStart.value = FormatDate(new Date(), 'YYYY-MM-DD');
			form.PromoteEnd.value = FormatDate(new Date(), 'YYYY-MM-DD');
		}
		else
		{
			form.PromotePrice.disabled = true;
			form.PromoteStart.disabled = true;
			form.PromoteEnd.disabled = true;
		}
	};
	
	this.onUserPriceClick = function()
	{
		$('#user-price-container').toggle();
		/*
		var form = this.form;
		
		var userPriceTable = $('#user-price-container table');
		if (userPriceTable.length)
		{
			this.checked ? userPriceTable.show() : userPriceTable.hide();
		}
		else
		{
			$('#user-price-container').load('ajax_user_price.aspx?SalePrice=' + $('[name=SalePrice]').val(), function()
			{
				if (_userPrices)
				{
					for (var i = 0; i < _userPrices.length; i++)
					{
						var checkbox = $('#user-price-container [value="' + _userPrices[i].roleId + '"]')
						checkbox.prop('checked', true);
						checkbox.closest('tr').find(':text').val(_userPrices[i].price);
					}
					_userPrices = null;
				}
			});
		}
		*/
	};

	this.selectPicture = function()
	{
		__base.showDialog({fileBrowse:true,type:'Picture',listByPicture:true,root:_pictureRoot});
	};

	this.selectThumbnail = function()
	{
		__base.showDialog({fileBrowse:true,type:'Thumbnail',listByPicture:true,root:_thumbnailRoot});
	};

	this.selectMorePicture = function()
	{
		__base.showDialog({fileBrowse:true,type:$(this).data('selectPicture'),listByPicture:true,root:_pictureRoot});
	};

	this.selectMoreThumbnail = function()
	{
		__base.showDialog({fileBrowse:true,type:$(this).data('selectThumbnail'),listByPicture:true,root:_thumbnailRoot});
	};

	this.selectSpecPicture = function()
	{
		__base.showDialog({fileBrowse:true,type:$(this).data('selectPicture'),listByPicture:true,root:_pictureRoot});
	};

	this.addMorePictureRow = function()
	{
		var cell1Html = '<input type="button" value="' + _lang_delete + '">';
		var cell2Html = _lang_picture + '<input id="Picture<!--Index-->Textbox" type="text" name="MorePicture<!--Index-->" size="55" class="Text" />\
						 <input id="Picture<!--Index-->Browse" type="button" value="' + _lang_browse + '" />\
						 <input type="button" value="' + _lang_select + '..." data-select-picture="MorePicture<!--Index-->" />\
						 <img height="22" id="Picture<!--Index-->View" style="vertical-align:bottom" />\
						 <input type="checkbox" id="MakeThumbnail<!--Index-->" checked /><label for="MakeThumbnail<!--Index-->">' + _lang_generate_thumbnail + '</label>\
						 <input type="checkbox" id="AddWaterMarkToMorePicture<!--Index-->" /><label for="AddWaterMarkToMorePicture<!--Index-->">' + _lang_water_print + '</label><p>' +
						 _lang_thumbnail + '<input id="Thumbnail<!--Index-->Textbox" type="text" name="MoreThumbnail<!--Index-->" size="55" class="Text" />\
						 <input id="Thumbnail<!--Index-->Browse" type="button" value="' + _lang_browse + '" />\
						 <input type="button" value="' + _lang_select + '..." data-select-thumbnail="MoreThumbnail<!--Index-->" /></p>';
		
		var morePictureTable = $('#more-picture-table');
		if (!morePictureTable.length)
		{
			morePictureTable = $('<table id="more-picture-table" border="0" cellpadding="4" cellspacing="1"></table>');
			$('#more-picture-div').html(morePictureTable);
		}
	
		var index = $('tr', morePictureTable).length;
		var html = '<tr><th width="40">' + cell1Html.replace(/<!--Index-->/g, index) + '</th><td>' + cell2Html.replace(/<!--Index-->/g, index) + '</td></tr>';
		morePictureTable.append(html);
		
		_uploader.Add('Picture' + index, 'Picture' + index + 'Textbox', 'Picture' + index + 'Browse');
		_uploader.Add('Thumbnail' + index, 'Thumbnail' + index + 'Textbox', 'Thumbnail' + index + 'Browse');
	};
	
	this.delMorePictureRow = function()
	{
		var id = $(this).closest('tr').data('id');
		$(this).closest('tr').remove();
		
		if (id)
			__base.post({object:'Goods.Pictures',operation:'Delete',params:'ID=' + id});
	};
	
	this.onCategoryIDChange = function()
	{
		var typeId = $(':selected', this).data('typeId');
		if (typeId == '')
		{
			$('#property-row').hide().find('>td').html('');
			$('#spec-row').hide().find('>td').html('');
		}
		else
		{
			//获取类型编号
			$.get('ajax_get_type_no.aspx?Lang=' + _lang + '&TypeID=' + typeId, function(data)
			{
				$('[name=CategoryID] :selected').data('typeNo', $.trim(data));
			});
			
			//获取属性
			$.getJSON('ajax_property.aspx?Lang=' + _lang + '&TypeID=' + typeId, function(properties)
			{
				var html = '<table id="property-table" cellspacing="1" cellpadding="4" border="0" class="sub-table">';
				for (var i = 0; i < properties.length; i++)
				{
					html += '<tr><th class="' + _lang + 'Font"><label><input type="checkbox" data-id="' + properties[i].id + '" data-control="' + properties[i].control + '">' + properties[i].name + '</label> : </th><td>';
					if (properties[i].control == 'Text')
					{
						html += '<input type="text" size="50" class="' + _lang + 'Font">';
					}
					else if (properties[i].control == 'TextArea')
					{
						html += '<textarea cols="50" rows="5" class="' + _lang + 'Font"></textarea>';
					}
					else if (properties[i].control == 'Select')
					{
						html += '<select class="' + _lang + 'Font">';
						html += '<option value=""></option>';
						for (var j = 0; j < properties[i].options.length; j++)
						{
							html += '<option value="' + properties[i].options[j].id + '">' + properties[i].options[j].name + '</option>';
						}
						html += '</select>';
					}
					else if (properties[i].control == 'List')
					{
						html += '<select size="4" class="' + _lang + 'Font">';
						html += '<option value=""></option>';
						for (var j = 0; j < properties[i].options.length; j++)
						{
							html += '<option value="' + properties[i].options[j].id + '">' + properties[i].options[j].name + '</option>';
						}
						html += '</select>';
					}
					else if (properties[i].control == 'CheckBox')
					{
						for (var j = 0; j < properties[i].options.length; j++)
						{
							html += '<label><input type="checkbox" value="' + properties[i].options[j].id + '">' + properties[i].options[j].name + '</label>';
						}
					}
					else if (properties[i].control == 'Radio')
					{
						for (var j = 0; j < properties[i].options.length; j++)
						{
							html += '<label><input type="radio" name="p' + i + '" value="' + properties[i].options[j].id + '"' + (j == 0 ? ' checked' : '') + '>' + properties[i].options[j].name + '</label>';
						}
					}
					html += '</td></tr>';
				}
				html += '</table>';
				$('#property-row').show().find('>td').html(html);
				
				//设置值
				if (typeof(_properties) == 'undefined')
				{
					$('#property-table th :checkbox').prop('checked', true);
				}
				else
				{
					for (var i = 0; i < _properties.length; i++)
					{
						var check = $('#property-table [data-id="' + _properties[i].id + '"]').prop('checked', true);
						if (_properties[i].value != '')
						{
							check.closest('tr').find(':text,textarea').val(_properties[i].value);
						}
						else
						{
							for (var j = 0; j < _properties[i].optionIds.length; j++)
							{
								var tag = $('#property-table [value="' + _properties[i].optionIds[j] + '"]');
								if (tag[0].tagName == 'OPTION')
									tag.prop('selected', true);
								else
									tag.prop('checked', true);
							}
						}
					}
				}
				_properties = undefined;
			});
			
			//获取规格
			$.getJSON('ajax_spec.aspx?Lang=' + _lang + '&TypeID=' + typeId, function(specs)
			{
				//规格列表
				var html = '<table id="spec-table" cellspacing="1" cellpadding="4" border="0" class="sub-table">';
				for (var i = 0; i < specs.length; i++)
				{
					html += '<tr data-index="' + i + '" data-id="' + specs[i].id + '" data-sort="' + specs[i].sort + '" data-name="' + specs[i].name + '" data-can-upload="' + specs[i].canUpload + '"><th class="' + _lang + 'Font">' + specs[i].name + '</th><td>';
					for (var j = 0; j < specs[i].options.length; j++)
					{
						var color = '';
						if (specs[i].isColor)
							color = '<input type="button" class="spec-color" style="background:' + specs[i].options[j].color + '">';
						html += '<label><input type="checkbox" value="' + specs[i].options[j].id + '" data-index="' + j + '" data-no="' + specs[i].options[j].no + '" data-name="' + specs[i].options[j].name + '">' + color + specs[i].options[j].name + '</label>';
					}
					html += '</td></tr>';
				}
				html += '</table>';
				$('#spec-row').show().find('>td').html(html);
				
				//设置值
				if (typeof(_specs) != 'undefined')
				{
					var specTable = $('#spec-table');
					for (var i = 0; i < _specs.length; i++)
					{
						for (var j = 0; j < _specs[i].optionIds.length; j++)
						{
							var checkbox = $('[value="' + _specs[i].optionIds[j] + '"]', specTable)[0];
							if (!checkbox.checked)
								checkbox.click();
						}
					}
					
					for (var i = 0; i < _specs.length; i++)
					{
						var checkbox = $('#spec-price-table [data-option-ids="' + _specs[i].optionIds.join(',') + '"]');
						checkbox.data('id', _specs[i].id)[0].click();
						checkbox.closest('tr').find(':text:eq(0)').val(_specs[i].no).end().find(':text:eq(1)').val(_specs[i].barCode).end().find(':text:eq(2)').val(_specs[i].price).end().find(':text:eq(3)').val(_specs[i].promotePrice).end().find(':text:eq(4)').val(_specs[i].stock);
					}
				}
				_specs = undefined;
			});
		}
	};
	
	this.onSpecOptionClick = function()
	{
		var row = $(this).closest('tr');
		if (row.data('canUpload'))
		{
			var html;
			var table = $('.spec-upload-table[data-index=' + row.data('index') + ']');
			if (!table.length)
			{
				html = '<table cellspacing="1" cellpadding="4" border="0" class="sub-table spec-upload-table" data-index="' + row.data('index') + '">';
				html += '<thead><th>' + row.data('name') + '</th><th>' + _lang_select + '</th></thead><tbody></tbody>';
				html += '</table>';
				table = $(html);
				$('#spec-table').after(table);
			}
			
			if (this.checked)
			{
				var suffix = row.data('index') + '-' + $(this).data('index');
				html = '<tr data-index="' + $(this).data('index') + '"><td>' + $(this).data('name') + '</td><td><input id="SpecPicture' + suffix + 'Textbox" type="text" size="55" class="Text" data-id="' + this.value + '" data-form-id="SpecPicture' + suffix + '" />\
					 <input id="SpecPicture' + suffix + 'Browse" type="button" value="' + _lang_browse + '" />\
					 <input type="button" value="' + _lang_select + '..." data-select-picture="SpecPicture' + suffix + '" />\
					 <img height="22" id="SpecPicture' + suffix + 'View" style="vertical-align:bottom" /></td></tr>';
				$('tbody', table).append(html);
			
				_uploader.Add('SpecPicture' + suffix, 'SpecPicture' + suffix + 'Textbox', 'SpecPicture' + suffix + 'Browse');
				
				if (_morePictures)
				{
					for (var i = 0; i < _morePictures.length; i++)
					{
						if (_morePictures[i].specOptionId == this.value)
							$('#SpecPicture' + suffix + 'Textbox').val(_morePictures[i].url);
					}
				}
			}
			else
			{
				$('[data-index=' + $(this).data('index') + ']', table).remove();
				if (table.find('tbody tr').length == 0)
					table.remove();
			}
		}
		
		//构造价格表
		var specs = [];
		$('#spec-table tr').each(function()
		{
			var spec = $(this);
			$(':checked', this).each(function(i)
			{
				if (i == 0)
					specs.push({id:spec.data('id'),sort:spec.data('sort'),name:spec.data('name'),options:[]});
				
				specs[specs.length - 1].options.push({id:this.value,no:$(this).data('no'),name:$(this).data('name')});
			});
		});
		
		$('#spec-price-table').remove();
		if (specs.length)
		{
			//构造头部
			var html = '<table id="spec-price-table" cellspacing="1" cellpadding="4" border="0" class="sub-table"><thead><tr>';
			for (var i = 0; i < specs.length; i++)
			{
				html += '<th>' + specs[i].name + '</th>';
			}
			html += '<th>' + _lang_no + '</th><th>' + _lang_bar_code + '</th><th>' + _lang_price + '</th><th>' + _lang_promote_price + '</th><th>' + _lang_stock + '</th><th>' + _lang_select + '</th></tr></thead><tbody>';
			
			//计算count和skip，设置index
			var count = 1;
			for (var i = specs.length - 1; i >= 0; i--)
			{
				specs[i].index = 0;
				specs[i].skip = count;
				count *= specs[i].options.length;
			}
			
			//构造列表
			for (var i = 0; i < count; i++)
			{
				var optionsIds = '';
				var specNo = '';

				html += '<tr>';
				for (var j = 0; j < specs.length; j++)
				{
					if (i % specs[j].skip == 0)
					{
						if (specs[j].index >= specs[j].options.length)
							specs[j].index = 0;
						html += '<td rowspan="' + specs[j].skip + '">' + specs[j].options[specs[j].index].name + '</td>';
						specs[j].index++;
					}
					
					if (optionsIds != '')
						optionsIds += ',';
					optionsIds += specs[j].options[specs[j].index - 1].id;
					
					//
					specNo += specs[j].sort + '' + specs[j].options[specs[j].index - 1].no;
				}
				
				//生成编号
				var no = $('[name=CategoryID] :selected').data('typeNo') + $('[name=No]').val() + specNo;
				
				html += '<td><input type="text" value="' + no + '" disabled></td><td><input type="text" disabled></td><td><input type="text" disabled></td><td><input type="text" disabled></td><td><input type="text" disabled></td><td><input type="checkbox" data-id="' + newGuid() + '" data-option-ids="' + optionsIds + '"></td></tr>';
			}
			
			html += '</tbody></table>';
			$('#spec-row>td').append(html);
			
			//商品货号和库存不能改
			$('[name=No]').prop('disabled', true);
			//$('[name=Stock]').val(0).prop('disabled', true);
		}
		else
		{
			//商品货号可以改
			$('[name=No]').prop('disabled', false);
		}
	};
	
	this.onPropertyTableClick = function()
	{
		$(this).closest('tr').find('td input,td textarea,td select').prop('disabled', !this.checked);
	};
	
	this.onSpecPriceTableClick = function()
	{
		$(this).closest('tr').find(':text').prop('disabled', !this.checked);
	};
	
	this.update = function(operation, id)
	{
		if (this.tagName == 'BUTTON')
			operation = this.id;

		__base.update(__object, operation, id);
	};
	
	this.replace = function()
	{
		if (this.From.type == 'text' && this.From.value == '')
		{
			Alert(_lang_from_empty, function(){this.From.select();}, this);
			return false;
		}
		
		var data = 'Property=' + this.Property.value;
		data += '&From=' + encodeURIComponent(this.From.value);
		data += '&To=' + encodeURIComponent(this.To.value);
		
		__base.post({object:__object,operation:'Replace',data:data});
		
		return false;
	};
	
	this.onPropertyChange = function()
	{
		switch (this.value)
		{
			case 'CategoryID':
			
				$.getJSON('ajax_goods_category.aspx', function(categories)
				{
					var from = '<select name="From" class="' + _lang + 'Font">';
					var to = '<select name="To" class="' + _lang + 'Font">';
					for (var i = 0; i < categories.length; i++)
					{
						var option = '<option value="' + categories[i].id + '">' + categories[i].name + '</option>';
						from += option;
						to += option;
					}
					from += '</select>';
					to += '</select>';
					
					$('#FromTd').html(from);
					$('#ToTd').html(to);
				});
				break;
			case 'Name':
			case 'Description':
				$('#FromTd').html('<input type="text" name="From" class="Text ' + _lang + 'Font">');
				$('#ToTd').html('<input type="text" name="To" class="Text ' + _lang + 'Font">');
				break;
			default:
				$('#FromTd').html('<input type="text" name="From" size="40" class="Text">');
				$('#ToTd').html('<input type="text" name="To" size="40" class="Text">');
				break;
		}
	};
}
//End: 商品
//-------------------------------------------------

//-------------------------------------------------
//Start: 地区
function Region()
{
	var __object = 'Region',
		__base = new Base();

	this.add = function()
	{
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}
		
		var data = 'Name=' + encodeURIComponent(this.Name.value);
		data += '&ParentID=' + encodeURIComponent(this.ParentID.value);
		data += '&IsCity=' + $('[name=IsCity]:checked').val();
	
		__base.add({object:__object,data:data});
		
		return false;	
	};

	this.modify = function()
	{
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}
		
		var data = 'Name=' + encodeURIComponent(this.Name.value);
		data += '&ParentID=' + encodeURIComponent(this.ParentID.value);
		data += '&IsCity=' + $('[name=IsCity]:checked').val();
	
		__base.modify({object:__object,data:data});
		
		return false;	
	};

	this.modifyName = function()
	{
		if (this.Name.value == '')
		{
			Alert(_lang_name_empty, function(){this.Name.select();}, this);
			return false;
		}
		
		var data = 'Name=' + encodeURIComponent(this.Name.value);
	
		__base.modify({object:__object,data:data,id:$(this).closest('tr').attr('ItemID')});
		
		return false;
	};
		
	this.move = function(from, to)
	{
		__base.move(__object, 'Move', from, to);
	};
	
	this.del = function(id)
	{
		__base.update(__object, 'Delete', id);
	};
}
//End: 地区
//-------------------------------------------------

//-------------------------------------------------
//Start: 订单
function Order()
{
	var __object = 'Order',
		__base = new Base();

	this.modify = function()
	{
		if (!this.PriceAdjustment.value.match(/^-?\d+(\.\d+)?$/))
		{
			Alert(_lang_price_adjustment_incorrect, function(){this.PriceAdjustment.select();}, this);
			return false;
		}
		
		var data = 'PriceAdjustment=' + this.PriceAdjustment.value;
		data += '&AdminMemo=' + encodeURIComponent(this.AdminMemo.value);
		data += '&Sum=' + $('#sum').text();
	
		__base.modify({object:__object,data:data});
	};

	this.update = function(operation, id)
	{
		if (this.tagName == 'BUTTON')
			operation = this.id;

		__base.update(__object, operation, id);
	};
	
	this.onPriceAdjustmentKeyUp = function()
	{
		if (!this.value.match(/^-?\d+(\.\d+)?$/))
		{
			this.value = '0.00';
			return;
		}
		
		var old = parseFloat($('#sum').data('old'));
		$('#sum').text((old + parseFloat(this.value)).toFixed(2));
		return false;
	};

	this.onAcceptClick = function()
	{
		var id = $(this).closest('tr')[0].id;
		Confirm(_lang_confirm_accept, function(returnValue){if (returnValue)accept(id);}, this);
	};
	
	var accept = function(id)
	{
		__base.post({object:'Order',operation:'Accept',params:'ID=' + id,hasList:true});
	};
	
	this.onPayClick = function()
	{
		var id = $(this).closest('tr')[0].id;
		__base.showDialog({url:'pay.aspx?Lang=' + _lang + '&ID=' + id,width:600,height:400,callback:pay});
	};
	
	var pay = function()
	{
		var win = window;
		with (pay.prototype.dialog)
		{
			if (!this.Amount.value.match(/^\d+(\.\d+)?$/))
			{
				Alert(_lang_amount_incorrect, function(){this.Amount.select();}, this);
				return false;
			}
			
			if (parseFloat(this.Amount.value) <= 0)
			{
				Alert(_lang_amount_less_than_zero, function(){this.Amount.select();}, this);
				return false;
			}
			
			if (parseFloat(this.Amount.value) > parseFloat($.trim($('#Money', this).text())))
			{
				Alert(_lang_amount_greater_than_money, function(){this.Amount.select();}, this);
				return false;
			}
			
			if (parseFloat(this.Amount.value) > parseFloat($.trim($('#NeedPay', this).text().replace(',', ''))))
			{
				Alert(_lang_amount_greater_than_sum, function(){this.Amount.select();}, this);
				return false;
			}
			
			var dateTime = /^(\d{1,4})(-|\/)(\d{1,2})(-|\/)(\d{1,2})( (\d{1,2}):(\d{1,2}):(\d{1,2}))?$/;
			if (!dateTime.test(this.PayTime.value))
			{
				Alert(_lang_time_incorrect, function(){this.PayTime.select();}, this);
				return false;
			}
			
			var data = 'Amount=' + this.Amount.value;
			data += '&PayTime=' + this.PayTime.value;
			data += '&PayMemo=' + encodeURIComponent(this.PayMemo.value);
			
			(new Base()).post({object:'Order',operation:'Pay',data:data,params:'&ID=' + _id,onSuccess:function()
			{
				Alert(_lang_operation_success, function(){close();}, this);
				win.Search();
			}});
		}

		return false;
	};
	
	this.onRefundClick = function()
	{
		var id = $(this).closest('tr')[0].id;
		__base.showDialog({url:'refund.aspx?Lang=' + _lang + '&ID=' + id,width:600,height:300,callback:refund});
	};
	
	var refund = function()
	{
		var win = window;
		with (refund.prototype.dialog)
		{
			if (!this.Amount.value.match(/^\d+(\.\d+)?$/))
			{
				Alert(_lang_amount_incorrect, function(){this.Amount.select();}, this);
				return false;
			}
			
			if (parseFloat(this.Amount.value) <= 0)
			{
				Alert(_lang_amount_less_than_zero, function(){this.Amount.select();}, this);
				return false;
			}
			
			if (parseFloat(this.Amount.value) > parseFloat($.trim($('#HasPayed', this).text().replace(',', ''))))
			{
				Alert(_lang_amount_greater_than_sum, function(){this.Amount.select();}, this);
				return false;
			}
			
			var dateTime = /^(\d{1,4})(-|\/)(\d{1,2})(-|\/)(\d{1,2})( (\d{1,2}):(\d{1,2}):(\d{1,2}))?$/;
			if (!dateTime.test(this.RefundTime.value))
			{
				Alert(_lang_time_incorrect, function(){this.RefundTime.select();}, this);
				return false;
			}
			
			var data = 'Amount=' + this.Amount.value;
			data += '&RefundTime=' + this.RefundTime.value;
			data += '&RefundMemo=' + encodeURIComponent(this.RefundMemo.value);
			
			(new Base()).post({object:'Order',operation:'Refund',data:data,params:'&ID=' + _id,onSuccess:function()
			{
				Alert(_lang_operation_success, function(){close();}, this);
				win.Search();
			}});
		}

		return false;
	};
	
	this.onDeliverClick = function()
	{
		var id = $(this).closest('tr')[0].id;
		__base.showDialog({url:'deliver.aspx?Lang=' + _lang + '&ID=' + id,width:600,height:400,callback:deliver});
	};
	
	function deliver()
	{
		var win = window;
		with (deliver.prototype.dialog)
		{
			//检查物流公司
			if (this.LogisticsID.selectedIndex == -1)
			{
				Alert(_lang_logistics_empty, function(){this.LogisticsID.select();}, this);
				return false;
			}
			
			//检查发货时间
			var dateTime = /^(\d{1,4})(-|\/)(\d{1,2})(-|\/)(\d{1,2})( (\d{1,2}):(\d{1,2}):(\d{1,2}))?$/;
			if (!dateTime.test(this.DeliverTime.value))
			{
				Alert(_lang_time_incorrect, function(){this.DeliverTime.select();}, this);
				return false;
			}

			//准备发货单数据
			var data = 'LogisticsID=' + encodeURIComponent(this.LogisticsID.value);
			data += '&LogisticsName=' + encodeURIComponent($(this.LogisticsID).text());
			data += '&WaybillNo=' + encodeURIComponent(this.WaybillNo.value);
			data += '&DeliverTime=' + this.DeliverTime.value;
			data += '&DeliverMemo=' + encodeURIComponent(this.DeliverMemo.value);
			data += '&IsAll=true';
			data += '&OrderID=' + _guid;
			
			//提交发货单
			(new Base()).post({object:'Order.Delivery',operation:'Add',data:data,silent:true});
			
			//准备数据
			var data = '&DeliverTime=' + this.DeliverTime.value;
			data += '&DeliverMemo=' + encodeURIComponent(this.DeliverMemo.value);
			
			(new Base()).post({object:'Order',operation:'Deliver',data:data,params:'&ID=' + _id,onSuccess:function()
			{
				Alert(_lang_operation_success, function(){close();}, this);
				win.Search();
			}});
		}

		return false;
	}
	
	this.onReturnClick = function()
	{
		var id = $(this).closest('tr')[0].id;
		__base.showDialog({url:'return.aspx?Lang=' + _lang + '&ID=' + id,width:600,height:300,callback:returnOrder});
	};
	
	var returnOrder = function()
	{
		var win = window;
		with (returnOrder.prototype.dialog)
		{
			var dateTime = /^(\d{1,4})(-|\/)(\d{1,2})(-|\/)(\d{1,2})( (\d{1,2}):(\d{1,2}):(\d{1,2}))?$/;
			if (!dateTime.test(this.ReturnTime.value))
			{
				Alert(_lang_time_incorrect, function(){this.ReturnTime.select();}, this);
				return false;
			}
			
			var data = 'ReturnTime=' + this.ReturnTime.value;
			data += '&ReturnMemo=' + encodeURIComponent(this.ReturnMemo.value);
			
			(new Base()).post({object:'Order',operation:'Return',data:data,params:'&ID=' + _id,onSuccess:function()
			{
				Alert(_lang_operation_success, function(){close();}, this);
				win.Search();
			}});
		}

		return false;
	};
}
//End: 订单
//-------------------------------------------------

//-------------------------------------------------
//#region 运费模板
function FreightTemplate()
{
	var __object = 'FreightTemplate',
		__base = new Base();

	function prepareData(form)
	{
		//名称不能空
		if (form.Name.value == '')
		{
			Alert(_lang_name_empty, function(){form.Name.select();}, this);
			return null;
		}
		
		//必须选择货物所在地
		var region = $('#region [value!=""]:selected:last', form);
		if (region.length == '')
		{
			Alert(_lang_region_empty);
			return null;
		}
		
		//买家承担（自定义）时，必须选择运送方式
		var isBuyerCustom = $('[value=BuyerCustom]').prop('checked');
		var express = $('[value=Express]');
		var ems = $('[value=EMS]');
		var post = $('[value=Post]');
		if (isBuyerCustom && (!express.prop('checked') && !ems.prop('checked') && !post.prop('checked')))
		{
			Alert(_lang_deliver_method_empty);
			return null;
		}
		
		//检查运送方式
		var expressJson = {};
		var emsJson = {};
		var postJson = {};
		if (isBuyerCustom)
		{
			for (var d = 0; d < 3; d++)
			{
				var method, json;
				if (d == 0)
				{
					method = express;
					json = expressJson;
				}
				else if (d == 1)
				{
					method = ems;
					json = emsJson;
				}
				else
				{
					method = post;
					json = postJson;
				}
				
				if (!method.prop('checked'))
					continue;

				var table = method.parent().next();
				var caption = table.find('caption');
	
				var start = $('[data-name=Start]', caption);
				if (!start.val().match(/\d+/))
				{
					Alert(_lang_start_incorrect, function(){start[0].select();}, this);
					return null;
				}
	
				var startFee = $('[data-name=StartFee]', caption);
				if (!startFee.val().match(/\d+/))
				{
					Alert(_lang_start_fee_incorrect, function(){startFee[0].select();}, this);
					return null;
				}
	
				var plus = $('[data-name=Plus]', caption);
				if (!plus.val().match(/\d+/))
				{
					Alert(_lang_plus_incorrect, function(){plus[0].select();}, this);
					return null;
				}
				
				var plusFee = $('[data-name=PlusFee]', caption);
				if (!plusFee.val().match(/\d+/))
				{
					Alert(_lang_plus_fee_incorrect, function(){plusFee[0].select();}, this);
					return null;
				}
				
				json.defaultValue = {start:parseInt(start.val()),startFee:parseInt(startFee.val()),plus:parseInt(plus.val()),plusFee:parseInt(plusFee.val())}
				json.regions = [];
				
				var rows = table.find('tbody tr');
				for (var i = 0; i < rows.length; i++)
				{
					var row = rows.eq(i);
					
					var regions = $('th div span', row);
					if (regions.length == 0)
					{
						Alert(_lang_deliver_region_empty);
						return null;
					}
		
					start = $('[data-name=Start]', row);
					if (!start.val().match(/\d+/))
					{
						Alert(_lang_start_incorrect, function(){start[0].select();}, this);
						return null;
					}
		
					startFee = $('[data-name=StartFee]', row);
					if (!startFee.val().match(/\d+/))
					{
						Alert(_lang_start_fee_incorrect, function(){startFee[0].select();}, this);
						return null;
					}
		
					plus = $('[data-name=Plus]', row);
					if (!plus.val().match(/\d+/))
					{
						Alert(_lang_plus_incorrect, function(){plus[0].select();}, this);
						return null;
					}
					
					plusFee = $('[data-name=PlusFee]', row);
					if (!plusFee.val().match(/\d+/))
					{
						Alert(_lang_plus_fee_incorrect, function(){plusFee[0].select();}, this);
						return null;
					}

					json.regions.push({ids:[],start:parseInt(start.val()),startFee:parseInt(startFee.val()),plus:parseInt(plus.val()),plusFee:parseInt(plusFee.val())});
					regions.each(function(){json.regions[json.regions.length - 1].ids.push($(this).data('id'));});
				}
			}
		}
		
		var data = $(form).serialize();
		data += '&RegionID=' + region.val();
		data += '&Express=' + encodeURIComponent(JSON.stringify(expressJson));
		data += '&EMS=' + encodeURIComponent(JSON.stringify(emsJson));
		data += '&Post=' + encodeURIComponent(JSON.stringify(postJson));
		
		return data;
	}

	this.add = function()
	{
		var data = prepareData(this);
		if (!data)
			return false;
		
		__base.add({object:__object,data:data});
		
		return false;
	};

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

		__base.modify({object:__object,data:data});
		
		return false;
	};
	
	this.update = function(operation, id)
	{
		if (this.tagName == 'BUTTON')
			operation = this.id;

		__base.update(__object, operation, id);
	};	

	this.onDeliverClick = function()
	{
		$(this).parent().next().toggle();		
	};
	
	this.onAddDeliverClick = function()
	{
		var tbody = $(this).closest('table').find('tbody');
		var html = '<tr><td><input type="checkbox" name="Sel"></td><th><a href="" data-operation="SelectRegion" id="' + ali.util.formatDate(new Date(), 'ssSSS') + '">' + _lang_select_region + '</a></th><td><input type="text" data-name="Start" value="1"></td><td><input type="text" data-name="StartFee"></td><td><input type="text" data-name="Plus" value="1"></td><td><input type="text" data-name="PlusFee"></td><td><a href="" data-operation="Delete">' + _lang_delete + '</a></td></tr>';
		tbody.append(html);

		return false;
	};
	
	this.onSelectRegionClick = function()
	{
		var region = $('#region-dialog');
		var selected = $(this).next();
		$(':checkbox', region).prop('checked', false);
		$('dd', region).hide();
		if (selected.length != 0)
		{
			selected.find('span').each(function()
			{
				$('[value="' + $(this).data('id') + '"]', region).prop('checked', true).parent().parent().show();
			});
		}

		region.data('id', this.id).dialog({width:750,height:300,position:{my:'left top',at:'right top',of:this}});
		return false;
	};
	
	this.onToggleButtonClick = function()
	{
		$(this).closest('dt').next().toggle();
	};
	
	this.onRegionClick = function()
	{
		var parent = $(this).parent().parent();
		if (parent[0].tagName == 'TH' || parent[0].tagName == 'DT')
		{
			parent.next().find(':checkbox').prop('checked', $(this).prop('checked'));
		}
		
		//
		var selectRegion = $('#' + $('#region-dialog').data('id'));
		var selected = selectRegion.next();
		if (selected.length == 0)
		{
			selected = $('<div/>');
			selectRegion.after(selected);
		}

		html = '';
		$(this).closest('table').find('[data-is-city=True]:checked').each(function()
		{
			html += '<span data-id="' + this.value + '">' + $(this).parent().text() + '</span>';
		});
		selected.html(html);
	};
	
	this.onBearClick = function()
	{
		if (this.value == 'BuyerCustom')
			$(this).closest('tr').nextAll().show();
		else
			$(this).closest('tr').nextAll().hide();
	};
	
	this.onMethodClick = function()
	{
		$('.deliver b,#batch-dialog b').text($(this).parent().find('b').data('unit'));
	};
	
	this.onSelectAllClick = function()
	{
		$(this).closest('thead').next().find('td:nth-child(1) :checkbox').prop('checked', this.checked);
	};
	
	this.onBatchDeleteClick = function()
	{
		$(this).closest('table').find('tbody td:nth-child(1) :checked').each(function()
		{
			$(this).closest('tr').remove();
		});
		
		return false;
	};
	
	this.onBatchOperationClick = function()
	{
		$('#batch-dialog').data('id', $(this).data('id')).dialog({width:600,height:100,resizable:false,position:{my:'center top',at:'center bottom',of:this}});
		return false;
	};
	
	this.onBatchDialogOkClick = function()
	{
		var dialog = $('#batch-dialog');
		
		var start = $('[data-name=Start]', dialog);
		if (!start.val().match(/\d+/))
		{
			Alert(_lang_start_incorrect, function(){start[0].select();}, this);
			return;
		}
		
		var startFee = $('[data-name=StartFee]', dialog);
		if (!startFee.val().match(/\d+/))
		{
			Alert(_lang_start_fee_incorrect, function(){startFee[0].select();}, this);
			return;
		}
		
		var plus = $('[data-name=Plus]', dialog);
		if (!plus.val().match(/\d+/))
		{
			Alert(_lang_plus_incorrect, function(){plus[0].select();}, this);
			return;
		}
		
		var plusFee = $('[data-name=PlusFee]', dialog);
		if (!plusFee.val().match(/\d+/))
		{
			Alert(_lang_plus_fee_incorrect, function(){plusFee[0].select();}, this);
			return;
		}
		
		$('.deliver:eq(' + dialog.data('id') + ') tbody td:nth-child(1) :checked').each(function()
		{
			var row = $(this).closest('tr');
			$('[data-name=Start]', row).val(start.val());
			$('[data-name=StartFee]', row).val(startFee.val());
			$('[data-name=Plus]', row).val(plus.val());
			$('[data-name=PlusFee]', row).val(plusFee.val());
		});
	};
	
	this.onDeleteClick = function()
	{
		$(this).closest('tr').remove();
		
		return false;
	};
	
	this.regionCallback = function()
	{
		if (_regionLinkageData == null)
			return;

		var last = $('#region select:last');
		if (_regionLinkageData.index < _regionLinkageData.parents.length)
		{
			last.find('[data-inner-id=' + _regionLinkageData.parents[_regionLinkageData.index++] + ']').attr('selected', true);
			last.change();
		}
		else if (_regionLinkageData != null)
		{
			last.find('[value=' + _regionLinkageData.id + ']').attr('selected', true);
			last.change();
			_regionLinkageData = null;
		}
	};	
}
//#endregion
//-------------------------------------------------

(function()
{
	if (typeof(_page) == 'undefined')
		return;
	
	if (_page == 'sub_instance_add')
	{
		var subInstance = new SubInstance();
		
		$('form:first').submit(subInstance.add);
		$('#check').click(subInstance.check);
	}
	else if (_page == 'sub_instance_edit')
	{
		var subInstance = new SubInstance();
		
		$('form:first').submit(subInstance.modify);
		$('#check').click(subInstance.check);
	}
	else if (_page == 'sub_instance_list')
	{
		var subInstance = new SubInstance();
		
		MakeButton();

		$('#IsRecycled,#Sort').change(Search);
		$('body').on('click', '#Recycle,#Delete,#Recover', subInstance.update);
		$('#Keyword').keydown(function(e){if(e.keyCode == 13){Search(1);e.preventDefault();}});
		$('#Search').click(function(){Search(1);});
		$('#SelectAll').click(function(){$(':checkbox[name=Sel]').each(function(){this.checked = true;});});
		$('#ReverseSelect').click(function(){$(':checkbox[name=Sel]').each(function(){this.checked = !this.checked;});});
	}
	else if (_page == 'sub_instance_select')
	{
		window.dialogArguments.prototype.dialog = window;
		$('#List').on('click', 'a', window.dialogArguments);
	}
	else if (_page == 'config_basic')
	{
		var instanceConfig = new InstanceConfig();
		
		_uploader.Init({WebPath:_webPath});
		_uploader.Add('Goods', 'GoodsTextbox', 'GoodsBrowse');

		$('form:first').submit(instanceConfig.setBasicSettings);
		$('#CreateAllGoodsThumbnail').click(instanceConfig.createAllGoodsThumbnail);
		$('#GoodsTextbox').change(function(){$('#GoodsDefaultThumbnailView').attr('src', this.value)});
		$('[name=TypeNoDigit],[name=GoodsNoDigit],[name=SpecNoDigit]').change(instanceConfig.onSkuChange).change();
	}
	else if (_page == 'config_discount')
	{
		var instanceConfig = new InstanceConfig();
		$('form').submit(instanceConfig.setDiscount);
	}
	else if (_page == 'brand_list')
	{
		var brand = new Brand();

		$('#List').on('click', 'td:last-child a', function()
		{
			var id = $(this).closest('tr').attr('id');
			Confirm(_lang_confirm_delete, function(returnValue){if (returnValue)brand.del(id);}, this);
			return false;
		});
	}
	else if (_page == 'brand_add')
	{
		var brand = new Brand();

		_uploader.Init({WebPath:_webPath});
		_uploader.Add('Logo', 'LogoTextbox', 'LogoBrowse');
		
		$('form:first').submit(brand.add);
		$('#LogoTextbox').change(function(){$('#LogoView').attr('src', this.value)});
		$('#PageIDCandidate').change(PageIDCandidate_OnChange);
	}
	else if (_page == 'brand_edit')
	{
		var brand = new Brand();

		$('[name=PageGenerate][value="' + _pageGenerate + '"]')[0].checked = true;

		_uploader.Init({WebPath:_webPath});
		_uploader.Add('Logo', 'LogoTextbox', 'LogoBrowse');
		
		$('form:first').submit(brand.modify);
		$('#LogoTextbox').change(function(){$('#LogoView').attr('src', this.value)});
		$('#PageIDCandidate').change(PageIDCandidate_OnChange);
	}
	else if (_page == 'logistics_list')
	{
		var logistics = new Logistics();

		$('#List').on('click', 'td:last-child a', function()
		{
			var id = $(this).closest('tr').attr('id');
			Confirm(_lang_confirm_delete, function(returnValue){if (returnValue)logistics.del(id);}, this);
			return false;
		});
	}
	else if (_page == 'logistics_add')
	{
		var logistics = new Logistics();

		$('form:first').submit(logistics.add);
	}
	else if (_page == 'logistics_edit')
	{
		var logistics = new Logistics();

		$('form:first').submit(logistics.modify);
	}
	else if (_page == 'goods_category_add')
	{
		var goodsCategory = new GoodsCategory();

		_uploader.Init({WebPath:_webPath});
		_uploader.Add('Picture', 'PictureTextbox', 'PictureBrowse');
		
		$('form:first').submit(goodsCategory.add);
		$('#PictureTextbox').change(function(){$('#PictureView').attr('src', this.value)});
		$('#PageIDCandidate').change(PageIDCandidate_OnChange);
	}
	else if (_page == 'goods_category_edit')
	{
		var goodsCategory = new GoodsCategory();

		$('[name=PageGenerate][value="' + _pageGenerate + '"]')[0].checked = true;

		_uploader.Init({WebPath:_webPath});
		_uploader.Add('Picture', 'PictureTextbox', 'PictureBrowse');
		
		$('form:first').submit(goodsCategory.modify);
		$('#PictureTextbox').change(function(){$('#PictureView').attr('src', this.value)});
		$('#PageIDCandidate').change(PageIDCandidate_OnChange);
	}
	else if (_page == 'goods_category_list')
	{
		var goodsCategory = new GoodsCategory();

	    MakeButton();

		InitMove(null, 'Move', null, goodsCategory.move);

		$('#IsDisplay,#IsRecommended,#IsHeld,#Sort').change(Search);
		$('form').submit(goodsCategory.modifyName);
		$('[sort]').mouseover(function(){this.className += ' Move_MouseOver';}).mouseout(function(){this.className='Move';});

		$('#List').on('click', 'td:last-child a', function()
		{
			var id = $(this).closest('tr').attr('ItemID');
			Confirm(_lang_confirm_delete, function(returnValue){if (returnValue)goodsCategory.del(id);}, this);
			return false;
		});
	}
	else if (_page == 'type_add')
	{
		var type = new Type();

		$('form').submit(type.add);
		
		//自动编码
		var no = '';
		var count = _typeNoDigit - _maxTypeInnerId.toString().length;
		if (_typeNoDigit < 0)
		{
			Alert(_lang_digit_not_enough);
			$(':submit').prop('disabled', true);
		}
		for (var i = 0; i < count; i++)
		{
			no += '0';
		}
		no += _maxTypeInnerId;
		$('[name=No]').val(no);
	}
	else if (_page == 'type_edit')
	{
		var type = new Type();

		$('form').submit(type.modify);
		
		$('[name=Kind]').val(_kind);
	}
	else if (_page == 'type_list')
	{
		var type = new Type();

		$('#List').on('click', 'td:last-child a', function()
		{
			var id = $(this).closest('tr').attr('id');
			Confirm(_lang_confirm_delete, function(returnValue){if (returnValue)type.del(id);}, this);
			return false;
		});
	}
	else if (_page == 'property_list')
	{
		var property = new Property();

		InitMove(null, 'Move', null, property.move);

		$('.ToolBar form').submit(property.add);		
		$('tr form').submit(property.modifyName);
		$('[sort]').mouseover(function(){this.className += ' Move_MouseOver';}).mouseout(function(){this.className='Move';});

		$('#List').on('click', 'td:last-child a', function()
		{
			var id = $(this).closest('tr').data('id');
			Confirm(_lang_confirm_delete, function(returnValue){if (returnValue)property.del(id);}, this);
			return false;
		});
	}
	else if (_page == 'property_edit')
	{
		var property = new Property();

		$('form').submit(property.modify);
	}
	else if (_page == 'property_option_list')
	{
		var propertyOption = new PropertyOption();

		InitMove(null, 'Move', null, propertyOption.move);

		$('.ToolBar form').submit(propertyOption.add);		
		$('tr form').submit(propertyOption.modifyName);
		$('[sort]').mouseover(function(){this.className += ' Move_MouseOver';}).mouseout(function(){this.className='Move';});

		$('#List').on('click', 'td:last-child a', function()
		{
			var id = $(this).closest('tr').data('id');
			Confirm(_lang_confirm_delete, function(returnValue){if (returnValue)propertyOption.del(id);}, this);
			return false;
		});
	}
	else if (_page == 'property_option_edit')
	{
		var propertyOption = new PropertyOption();

		$('form').submit(propertyOption.modify);
	}
	else if (_page == 'spec_list')
	{
		var spec = new Spec();

		$('.ToolBar form').submit(spec.add);		
		$('#List').on('submit', 'form', spec.modifyName)
				.on('click', 'td:last-child a', function()
				{
					var id = $(this).closest('tr').data('id');
					Confirm(_lang_confirm_delete, function(returnValue){if (returnValue)spec.del(id);}, this);
					return false;
				});
	}
	else if (_page == 'spec_edit')
	{
		var spec = new Spec();

		$('form').submit(spec.modify);
	}
	else if (_page == 'spec_option_list')
	{
		var specOption = new SpecOption();

		//事件绑定
		$('.ToolBar form').submit(specOption.add);

		$('#List').on('submit', 'form', specOption.modifyName)
				.on('click', 'td:last-child a', function()
				{
					var id = $(this).closest('tr').data('id');
					Confirm(_lang_confirm_delete, function(returnValue){if (returnValue)specOption.del(id);}, this);
					return false;
				});
		
		$('.color-selector').ColorPicker(
		{
			onShow: function(colpkr)
			{
				if (!$(colpkr).is(':visible'))
					$(colpkr).slideDown('fast');
				return false;
			},
			onHide: function(colpkr)
			{
				$(colpkr).slideUp('fast');
				return false;
			},
			onChange: function(hsb, hex, rgb)
			{
				$('.color-selector').val('#' + hex).find('a').css('backgroundColor', '#' + hex);
			}
		});
		
		//初始化编号
		var no = 1;
		$('#List [name=No]').each(function()
		{
			if (no <= parseInt(this.value))
				no = parseInt(this.value) + 1;
		});
		var count = _specNoDigit - no.toString().length;
		for (var i = 0; i < count; i++)
		{
			no = '0' + no;
		}
		$('[name=No]:first').val(no);
	}
	else if (_page == 'spec_option_edit')
	{
		var specOption = new SpecOption();

		$('form').submit(specOption.modify);
		
		$('.color-selector').ColorPicker(
		{
			onShow: function(colpkr)
			{
				if (!$(colpkr).is(':visible'))
					$(colpkr).slideDown('fast');
				return false;
			},
			onHide: function(colpkr)
			{
				$(colpkr).slideUp('fast');
				return false;
			},
			onChange: function(hsb, hex, rgb)
			{
				$('.color-selector').val('#' + hex).find('a').css('backgroundColor', '#' + hex);
			}
		});
	}
	else if (_page == 'goods_list')
	{
		var goods = new Goods();

		MakeButton();
		
		InitMove(null, 'Move', null, goods.move);
		
	    if (GetCookie('ListByPicture').toLowerCase() == 'true')
		    $('#ListByPicture')[0].checked = true;	
	    else
		    $('#ListByPicture')[0].checked = false;
	
		$('[sort]').mouseover(function(){this.className += ' Move_MouseOver';}).mouseout(function(){this.className='Move';});

		$('#IsRecycled,#IsReleased,#IsHeld,#IsRecommended,#CategoryID,#Sort').change(Search);
		$('#IncludeSubCategory').click(Search);
		$('#Keyword').keydown(function(e){if(e.keyCode == 13){Search(1);e.preventDefault();}});
		$('#Search').click(function(){Search(1);});
		$('#SelectAll').click(function(){$(':checkbox[name=Sel]').each(function(){this.checked = true;});});
		$('#ReverseSelect').click(function(){$(':checkbox[name=Sel]').each(function(){this.checked = !this.checked;});});
		$('body').on('click', '#Recycle,#Delete,#Recover,#Release,#UnRelease,#Recommend,#UnRecommend,#Hold,#UnHold', goods.update);
		
		$('#ListByPicture').click(function()
		{
	        SetCookie('ListByPicture', $('#ListByPicture')[0].checked, 10*360*24*60);
	        Search();
		});
	}
	else if (_page == 'goods_add')
	{
		var goods = new Goods();
		
		//上传绑定
		_uploader.Init({WebPath:_webPath});
		_uploader.Add('Picture', 'PictureTextbox', 'PictureBrowse');
		_uploader.Add('Thumbnail', 'ThumbnailTextbox', 'ThumbnailBrowse');

		//事件绑定
		$('form:first').submit(goods.add);
		$('[name=CategoryID]').change(goods.onCategoryIDChange);
		$('#Promote').click(goods.onPromoteClick);
		$('#UserPrice').click(goods.onUserPriceClick);
		$('#PictureSelect').click(goods.selectPicture);
		$('#ThumbnailSelect').click(goods.selectThumbnail);
		$('#MorePicture').click(goods.addMorePictureRow);
		$('#PageIDCandidate').change(PageIDCandidate_OnChange);
		$('body').on('click', '#property-table :checkbox', goods.onPropertyTableClick)
				.on('click', '#more-picture-table th input', goods.delMorePictureRow)
				.on('click', '#more-picture-table [data-select-picture]', goods.selectMorePicture)
				.on('click', '#more-picture-table [data-select-thumbnail]', goods.selectMoreThumbnail)
				.on('click', '#spec-row [data-select-picture]', goods.selectSpecPicture)
				.on('click', '#spec-table :checkbox', goods.onSpecOptionClick)
				.on('click', '#spec-price-table :checkbox', goods.onSpecPriceTableClick);
		$('#more-picture-div').on('click', '[id*=MakeThumbnail]', function(){$(this).parent().find('p').toggle();});

		//初始化		
		$('[name=CategoryID]').val(GetCookie('CategoryID')).change();
		$('[name=BrandID]').val(GetCookie('BrandID'));

		var makeThumbnail = $('#MakeThumbnail')[0];
		if (GetCookie('MakeThumbnail') == 'false')
			makeThumbnail.checked = false;
		else
			makeThumbnail.checked = true;
		$('#ThumbnailRow').css('display', makeThumbnail.checked ? 'none' : '');
		$('#MakeThumbnail').click(function(){$('#ThumbnailRow').css('display', this.checked ? 'none' : '');});
		
		//商品自动编号
		$.get('ajax_get_unique_no.aspx', function(data){$('[name=No]').val($.trim(data));});
		
		//空类型编号
		no = '';
		for (var i = 0; i < _typeNoDigit; i++)
			no += 0;
		$('[name=CategoryID] option:first').data('typeNo', no);
	}
	else if (_page == 'goods_edit')
	{
		var goods = new Goods();
		
		_uploader.Init({WebPath:_webPath});
		_uploader.Add('Picture', 'PictureTextbox', 'PictureBrowse');
		_uploader.Add('Thumbnail', 'ThumbnailTextbox', 'ThumbnailBrowse');

		$('form:first').submit(goods.modify);
		$('[name=CategoryID]').change(goods.onCategoryIDChange);
		$('#Promote').click(goods.onPromoteClick);
		$('#UserPrice').click(goods.onUserPriceClick);
		$('#PictureSelect').click(goods.selectPicture);
		$('#ThumbnailSelect').click(goods.selectThumbnail);
		$('#MorePicture').click(goods.addMorePictureRow);
		$('#PageIDCandidate').change(PageIDCandidate_OnChange);
		$('body').on('click', '#property-table :checkbox', goods.onPropertyTableClick);
		$('body').on('click', '#more-picture-table th input', goods.delMorePictureRow);
		$('body').on('click', '#more-picture-table [data-select-picture]', goods.selectMorePicture);
		$('body').on('click', '#more-picture-table [data-select-thumbnail]', goods.selectMoreThumbnail);
		$('body').on('click', '#spec-row [data-select-picture]', goods.selectSpecPicture);
		$('body').on('click', '#spec-table :checkbox', goods.onSpecOptionClick);
		$('body').on('click', '#spec-price-table :checkbox', goods.onSpecPriceTableClick);
		$('#Now').click(function(){$('[name=UpdateTime]').val(FormatDate(new Date(), 'YYYY-MM-DD hh:mm:ss'));return false;});
		
		$('#more-picture-div').on('click', '[id*=MakeThumbnail]', function(){$(this).parent().find('p').toggle();});

		//初始化数据
		goods.init();
	}
	else if (_page == 'goods_replace')
	{
		var goods = new Goods();
		
		$('form').submit(goods.replace);
		$('[name=Property]').change(goods.onPropertyChange);
	}
	else if (_page == 'region_add')
	{
		var region = new Region();

		$('form:first').submit(region.add);
	}
	else if (_page == 'region_edit')
	{
		var region = new Region();

		$('form:first').submit(region.modify);
	}
	else if (_page == 'region_list')
	{
		var region = new Region();

		InitMove(null, 'Move', null, region.move);

		$('#IsDisplay,#IsRecommended,#IsHeld,#Sort').change(Search);
		$('form').submit(region.modifyName);
		$('[sort]').mouseover(function(){this.className += ' Move_MouseOver';}).mouseout(function(){this.className='Move';});

		$('#List').on('click', 'td:last-child a', function()
		{
			var id = $(this).closest('tr').attr('ItemID');
			Confirm(_lang_confirm_delete, function(returnValue){if (returnValue)region.del(id);}, this);
			return false;
		});
	}
	else if (_page == 'order_edit')
	{
		var order = new Order();

		$('form:first').submit(order.modify);
		$('[name=PriceAdjustment]').keyup(order.onPriceAdjustmentKeyUp);
	}
	else if(_page == 'order_list')
	{
		var order = new Order();
		
		$('#IsAccepted,#IsPayed,#IsDelivered,#IsFinished,#Sort').change(Search);
		$('body').on('click', '#Finish,#Archive,#Cancel,#Delete', order.update);
		$('#Keyword').keydown(function(e){if(e.keyCode == 13){Search(1);e.preventDefault();}});
		$('#Search').click(function(){Search(1);});
		$('#SelectAll').click(function(){$(':checkbox[name=Sel]').each(function(){this.checked = true;});});
		$('#ReverseSelect').click(function(){$(':checkbox[name=Sel]').each(function(){this.checked = !this.checked;});});

		var list = $('#List');
		list.on('click', '[data-action=Accept]', order.onAcceptClick);
		list.on('click', '[data-action=Pay]', order.onPayClick);
		list.on('click', '[data-action=Refund]', order.onRefundClick);
		list.on('click', '[data-action=Deliver]', order.onDeliverClick);
		list.on('click', '[data-action=Return]', order.onReturnClick);
	}
	else if (_page == 'order_pay')
	{
		window.dialogArguments.prototype.dialog = window;
		$('form').submit(window.dialogArguments);
	}
	else if (_page == 'order_refund')
	{
		window.dialogArguments.prototype.dialog = window;
		$('form').submit(window.dialogArguments);
	}
	else if (_page == 'order_deliver')
	{
		window.dialogArguments.prototype.dialog = window;
		$('form').submit(window.dialogArguments);
	}
	else if (_page == 'order_return')
	{
		window.dialogArguments.prototype.dialog = window;
		$('form').submit(window.dialogArguments);
	}
	else if (_page == 'freight_template_add')
	{
		var freightTemplate = new FreightTemplate();

		$('form:first').submit(freightTemplate.add);
		$('[value=Express],[value=EMS],[value=Post]').click(freightTemplate.onDeliverClick);
		$('[data-operation=AddDeliver]').click(freightTemplate.onAddDeliverClick);
		$('.deliver').on('click', '[data-operation=SelectRegion]', freightTemplate.onSelectRegionClick);
		$('#region-dialog dt button').click(freightTemplate.onToggleButtonClick);
		$('#region-dialog :checkbox').click(freightTemplate.onRegionClick);
		$('[name=Bear]').click(freightTemplate.onBearClick);
		$('[name=Method]').click(freightTemplate.onMethodClick);
		$('.deliver thead th:nth-child(1) :checkbox').click(freightTemplate.onSelectAllClick);
		$('[data-operation=BatchDelete]').click(freightTemplate.onBatchDeleteClick);
		$('[data-operation=BatchOperation]').click(freightTemplate.onBatchOperationClick);
		$('.deliver').on('click', '[data-operation=Delete]', freightTemplate.onDeleteClick);
		$('#batch-dialog button').click(freightTemplate.onBatchDialogOkClick);
		
		//所属地区联动
		$('#region').on('change', 'select', function(){linkage(this, 'ajax_region.aspx');}); 
	}
	else if (_page == 'freight_template_edit')
	{
		var freightTemplate = new FreightTemplate();

		//#region 事件绑定
		$('form:first').submit(freightTemplate.modify);
		$('[value=Express],[value=EMS],[value=Post]').click(freightTemplate.onDeliverClick);
		$('[data-operation=AddDeliver]').click(freightTemplate.onAddDeliverClick);
		$('.deliver').on('click', '[data-operation=SelectRegion]', freightTemplate.onSelectRegionClick);
		$('#region-dialog dt button').click(freightTemplate.onToggleButtonClick);
		$('#region-dialog :checkbox').click(freightTemplate.onRegionClick);
		$('[name=Bear]').click(freightTemplate.onBearClick);
		$('[name=Method]').click(freightTemplate.onMethodClick);
		$('.deliver thead th:nth-child(1) :checkbox').click(freightTemplate.onSelectAllClick);
		$('[data-operation=BatchDelete]').click(freightTemplate.onBatchDeleteClick);
		$('[data-operation=BatchOperation]').click(freightTemplate.onBatchOperationClick);
		$('.deliver').on('click', '[data-operation=Delete]', freightTemplate.onDeleteClick);
		$('#batch-dialog button').click(freightTemplate.onBatchDialogOkClick);
		//#endregion
		
		//#region 初始化
		//根据承担方式，处理下面的选项
		$('[name=Bear]:checked').click();
		
		//所属地区联动
		$('#region').on('change', 'select', function(){linkage(this, 'ajax_region.aspx', freightTemplate.regionCallback);}); 
		if (_regionLinkageData.id != '')
			linkageSelect(_regionLinkageData);
		
		//运送方式
		for (var i = 0; i < 3; i++)
		{
			var json;
			if (i == 0)
				json = _express;
			else if (i == 1)
				json = _ems;
			else
				json = _post;
			
			//如果没有设置，则下一个
			if (!json.defaultValue)
				continue;
			
			var table = $('.deliver:eq(' + i + ')');
			
			//选择运送方式
			table.prev().find(':checkbox').prop('checked', true);
			
			//显示列表
			table.show();

			//默认运费
			var caption = $('caption', table);
			$('[data-name=Start]', caption).val(json.defaultValue.start);
			$('[data-name=StartFee]', caption).val(json.defaultValue.startFee);
			$('[data-name=Plus]', caption).val(json.defaultValue.plus);
			$('[data-name=PlusFee]', caption).val(json.defaultValue.plusFee);
			
			for (var j = 0; j < json.regions.length; j++)
			{
				//添加一行
				$('[data-operation=AddDeliver]', table).click();
				
				//获取最后一行
				var row = $('tbody tr:last', table);
				
				//形成地区
				var regions = '<div>';
				for (var k = 0; k < json.regions[j].ids.length; k++)
				{
					var region = $('#region-dialog [value="' + json.regions[j].ids[k] + '"]');
					regions += '<span data-id="' + json.regions[j].ids[k] + '">' + region.parent().text() + '</span>';
				}
				regions += '</div>';
				$('th', row).append(regions);
				
				//
				$('[data-name=Start]', row).val(json.regions[j].start);
				$('[data-name=StartFee]', row).val(json.regions[j].startFee);
				$('[data-name=Plus]', row).val(json.regions[j].plus);
				$('[data-name=PlusFee]', row).val(json.regions[j].plusFee);
			}
		}
		//#endregion
	}
	else if (_page == 'freight_template_list')
	{
		var freightTemplate = new FreightTemplate();

		$('body').on('click', '[data-operation=Delete]', function()
		{
			var id = $(this).closest('tr').data('id');
			Confirm(_lang_confirm_delete, function(returnValue){if (returnValue)freightTemplate.update('Delete', id);}, this);
			return false;
		});
	}
})();