!function(){
	var layout = $('#taobaoManage'),
		l = function(selector){
			return layout.find(selector);
		},
		goodsTitleKeyword = l('.goodsTitleKeyword'),
		goodsCatelog = l('.goodsCatelog');
		
	var onSalePage,
		inStackPage,
		commendPage;
	
	!{
		init: function(){
			var self = this;
			
			$('#menuTaobaoManage').click(function(){
				Tb.Api.authorise(function(userNickName){
					if(!userNickName){
						alert('授权失败，授权成功才能操作！');
						return false;
					}
					pur5.Pages.layoutTo(layout.attr('id'));
					$('.tabs').trigger('active', [0]);
				});
			});
			
			l('.tabs').bind('actived', function(event, index){
				onSalePage = {
					page_no: 1,
					page_size: 50
				},
				inStackPage = {
					page_no: 1,
					page_size: 50
				},
				commendPage = {
					page_no: 1,
					page_size: 50
				};
				
				goodsTitleKeyword.val('');
				goodsCatelog.val(0);
				
				self[['goods_on_sale','goods_in_stock','commended_goods'][index]]();
			});
			
			l('.searchBtn').click(function(){
				onSalePage.page_no = 1,
				inStackPage.page_no = 1,
				commendPage.page_no = 1;
				
				self[['goods_on_sale','goods_in_stock','commended_goods'][$('.tabs').triggerHandler('getIndex')]]();
			});
			
			l('.goodsCatelog').change(function(){
				onSalePage.page_no = 1,
				inStackPage.page_no = 1,
				commendPage.page_no = 1;
			});
		},
		listingAll: function(){
			l('#goods_on_sale').trigger('refresh', [{}]);
		},
		select_goods: function(){
			
		},
		getSellerCatelogs: function(scid){
			//return false;
			var self = this;
			Tb.Api.getSellercats(function(result){
				if(!result || !result.length){
					return false;
				}
				
				l('.goodsCatelog').trigger('refresh', [{
					list: result,
					defaultValue: scid,
					filter: {
						name: function(){
							return (this.parent_cid?'---':'')+this.name
						}
					}
				}]);
			});
		},
		getSelectedSellerCid: function(){
			var id = goodsCatelog.val();
			if(id == '0') id = '';
			return id;
		},
		goods_on_sale: function(){
			var self = this;
			var scid = self.getSelectedSellerCid();
			self.getSellerCatelogs(scid);
			Tb.Api.getGoodsOnSale($.extend(onSalePage,{
				q: goodsTitleKeyword.val(),
				seller_cids: scid
			}), function(result, count){
				if(!result || !result.length){
					Dialog.alert({
						content: '没有找到符合条件的宝贝'
					});
					l('#goods_on_sale').trigger('hideContextMenu');
					return false;
				}
				
				l('#goods_on_sale').trigger('refresh', [{
					list: result,
					filter: {
						pic_url: function(){
							return '<img src="' + this.pic_url + '" />'
						},
						has_showcase: function(){
							return this.has_showcase?'<span style="color:#f8b551; background-color:#67080f;">荐</span>':'';
						}
					},
					page: $.extend(onSalePage, {
						count: count
					}),
					pageAction: function(page_no){
						$.extend(onSalePage, {
							page_no: page_no
						});
						self.goods_on_sale();
					},
					selected: {
						'下 架': function(rows){
							self.deListingAll(rows);
						},
						'橱窗推荐': function(rows){
							self.addCommends(rows);
						},
						'取消橱窗推荐': function(rows){
							self.deleteCommends(rows);
						},
						'删 除': function(rows){
							self.deleteItems('goods_on_sale', rows);
						}
					},
					getRow: function(row){
						return {
							num_iid: row.attr('num_iid'),
							num: row.attr('num')
						}
					}
				}])
				.pur5UI()
				.find('.bodier table tbody tr')
				.bind('delisting', function(){
					if(!confirm('确定下架此宝贝？')) return false;
					var Row = $(this);
					self.delisting(Row.attr('num_iid'), function(success, bak){
						if(!success){
							Dialog.alert({
								content: bak || '下架失败！'
							});
							return false;
						}
						
						Dialog.alert({
							content: '下架成功！',
							style: {
								width: 180
							}
						})
						Row.remove();
					});
				})
				.bind('deleteItem', function(){
					if(!confirm('确定删除此宝贝？')) return false;
					var Row = $(this);
					self.deleteItem(Row.attr('num_iid'), function(success, bak){
						if(!success){
							Dialog.alert({
								content: bak || '删除失败！'
							});
							return false;
						}
						
						Dialog.alert({
							content: '删除成功！',
							style: {
								width: 180
							}
						})
						Row.remove();
					});
				})
				.find('span.button2')
				.filter('.detail').click(function(){
					var Row = $(this).parents('tr');
					self.getDetail(Row.attr('num_iid'), {
						button: {
							'编 辑': function(){	
								self.edit(Row.attr('num_iid'));
								return false;
							},
							'删 除': function(){
								return Row.trigger('deleteItem');
							},
							'下 架': function(){
								return Row.trigger('delisting');
							}
						}
					});
					//return false;
				})
				.end().filter('.delisting').click(function(){
					$(this).parents('tr').trigger('delisting');
					//return false;
				});
			});
		},
		goods_in_stock: function(){
			var self = this;
			var scid = self.getSelectedSellerCid();
			self.getSellerCatelogs(scid);
			Tb.Api.getGoodsInStock($.extend(inStackPage, {
				q: goodsTitleKeyword.val(),
				seller_cids: scid
			}), function(result, count){
				if(!result || !result.length){
					Dialog.alert({
						content: '没有找到符合条件的宝贝'
					});
					l('#goods_in_stock').trigger('hideContextMenu');
					return false;
				}
				l('#goods_in_stock').trigger('refresh', [{
					list: result,
					filter: {
						pic_url: function(){
							return '<img src="' + this.pic_url + '" />'
						}
					},
					page:  $.extend(inStackPage, {
						count: count
					}),
					pageAction: function(page_no){
						$.extend(inStackPage, {
							page_no: page_no
						});
						self.goods_in_stock();
					},
					selected: {
						'上 架': function(rows){
							self.listingAll(rows);
						},
						'删 除': function(rows){
							self.deleteItems('goods_in_stock', rows);
						}
					},
					getRow: function(row){
						return {
							num_iid: row.attr('num_iid'),
							num: row.attr('num')
						}
					}					
				}])
				.pur5UI()
				.find('table tbody tr')
				.bind('listing', function(){
					if(!confirm('确定上架此宝贝？')) return false
					var Row = $(this);
					self.listing(Row.attr('num_iid'), Row.attr('num'), function(success, bak){
						if(!success){
							Dialog.alert({
								content: bak || '上架失败！'
							});
							return false;
						}
						
						Dialog.alert({
							content: '上架成功！',
							style: {
								width: 180
							}
						})
						Row.remove();
					});
				})
				.bind('deleteItem', function(){
					if(!confirm('确定删除此宝贝？')) return false;
					var Row = $(this);
					self.deleteItem(Row.attr('num_iid'), function(success, bak){
						if(!success){
							Dialog.alert({
								content: bak || '删除失败！'
							});
							return false;
						}
						
						Dialog.alert({
							content: '删除成功！',
							style: {
								width: 180
							}
						})
						Row.remove();
					});
				})
				.find('span.button2')
				.filter('.detail').click(function(){
					var Row = $(this).parents('tr');
					self.getDetail(Row.attr('num_iid'), {
						button: {
							'编 辑': function(){
								self.edit(Row.attr('num_iid'));
								return false;
							},
							'删 除': function(){
								return Row.trigger('deleteItem');
							},
							'上 架': function(){
								return Row.trigger('listing');
							}
						}
					});
					//return false;
				})
				.end().filter('.listing').click(function(){
					$(this).parents('tr').trigger('listing');
					//return false;
				});
			});			
		},		
		commended_goods: function(){
			var self = this;
			var scid = self.getSelectedSellerCid();
			self.getSellerCatelogs(scid);
			Tb.Api.getGoodsOnSale($.extend(commendPage,{
				q: goodsTitleKeyword.val(),
				has_showcase: true,
				seller_cids: scid
			}), function(result, count){
				if(!result || !result.length){
					Dialog.alert({
						content: '没有找到符合条件的宝贝'
					});
					l('#goods_on_sale').trigger('hideContextMenu');
					return false;
				}
				
				l('#commended_goods').trigger('refresh', [{
					list: result,
					filter: {
						pic_url: function(){
							return '<img src="' + this.pic_url + '" />'
						}
					},
					page: $.extend(commendPage, {
						count: count
					}),
					pageAction: function(page_no){
						$.extend(commendPage, {
							page_no: page_no
						});
						self.commended_goods();
					},
					selected: {
						'取消橱窗推荐': function(rows){
							self.deleteCommends(rows);
						},
						'下 架': function(rows){
							self.deListingAll(rows);
						},
						'删 除': function(rows){
							self.deleteItems('goods_on_sale', rows);
						}
					},
					getRow: function(row){
						return {
							num_iid: row.attr('num_iid'),
							num: row.attr('num')
						}
					}
				}])
				.pur5UI()
				.find('.bodier table tbody tr')
				.bind('delisting', function(){
					if(!confirm('确定下架此宝贝？')) return false;
					var Row = $(this);
					self.delisting(Row.attr('num_iid'), function(success, bak){
						if(!success){
							Dialog.alert({
								content: bak || '下架失败！'
							});
							return false;
						}
						
						Dialog.alert({
							content: '下架成功！',
							style: {
								width: 180
							}
						})
						Row.remove();
					});
				})
				.bind('deleteItem', function(){
					if(!confirm('确定删除此宝贝？')) return false;
					var Row = $(this);
					self.deleteItem(Row.attr('num_iid'), function(success, bak){
						if(!success){
							Dialog.alert({
								content: bak || '删除失败！'
							});
							return false;
						}
						
						Dialog.alert({
							content: '删除成功！',
							style: {
								width: 180
							}
						})
						Row.remove();
					});
				})
				.find('span.button2')
				.filter('.detail').click(function(){
					var Row = $(this).parents('tr');
					self.getDetail(Row.attr('num_iid'), {
						button: {
							'编 辑': function(){
								self.edit(Row.attr('num_iid'));
								return false;
							},
							'删 除': function(){
								return Row.trigger('deleteItem');
							},
							'下 架': function(){
								return Row.trigger('delisting');
							}
						}
					});
					//return false;
				})
				.end().filter('.delisting').click(function(){
					$(this).parents('tr').trigger('delisting');
					//return false;
				});
			});
		},		
		getDetail: function(num_iid, button){
			var self = this;
			Dialog.alert({
				content: '读取宝贝详情',
				style: {
					width: 200
				}
			});
			
			Tb.Api.getItemDetail(num_iid, function(item, errorMsg){
				if(!item){
					Dialog.alert({
						content: errorMsg || '获取宝贝详情失败'
					});
				}else{
					Dialog.alert($.extend({
						title: item.title,
						content: $('.taobaoManage_itemDetail')[0].outerHTML.replace(/\$(\w+)/g, function(all, key){
							if(key == 'pic_url'){
								return '<img src="' + item[key] + '" />'
							}
							if(key == 'detail_url'){
								return '<a href="' + item[key] + '" target="_blank">宝贝浏览</a';
							}
							return item[key] || '';
						}),
						action: function($content){
							$content.find('.detail').click(function(){
								var parentSize = {
									width: parseInt($(document).width()),
									height: parseInt($(document).height())
								},	screenSize = {
									width: parseInt(screen.width*0.8),
									height: parseInt(screen.height*0.9)
								};
											
								pur5.Pages.winResize(screenSize.width, screenSize.height);
								UI.setMoveRegion(30, 0, screenSize.width, 28);
								Dialog.alert({
									title: '宝贝详情',
									content: '<iframe width="'+(screenSize.width-16)+'" height="'+(screenSize.height-84)+'" frameborder="0" application="no" src="http://item.taobao.com/item.htm?id='+num_iid+'"></iframe>',
									style: {
										border: '1px solid #ccc'
									},
									closeBtnVisible: false,
									action: function($content){
										$content.find('iframe').load(function(){
											var  Win = this.contentWindow,
												$doc = $(Win.document);
											$doc.find('.J_FlexSubmitBar').hide();
										});
									},
									button: {
										'确 定': false,
										'退 出': function(){
											pur5.Pages.winResize(parentSize.width, parentSize.height);
											UI.setMoveRegion(30, 0, parentSize.width-100, 28);
										}
									}
								});
								return false;
							});
						}
					}, button));
				}
			});
		},
		deleteItem: function(num_iid, callback){
			Tb.Api.deleteItem(num_iid, callback);
		},
		listing: function(num_iid, num, callback){
			Tb.Api.listing(num_iid, num, callback)
		},
		delisting: function(num_iid, callback){
			Tb.Api.delisting(num_iid, callback);
		},
		addCommend: function(num_iid, callback){
			Tb.Api.addCommend({
				num_iid: num_iid
			}, callback);
		},
		deleteCommend: function(num_iid, callback){
			Tb.Api.deleteCommend({
				num_iid: num_iid
			}, callback);
		},
		deleteItems: function(table, rows){
			if(!confirm('确定删除所选宝贝？')) return false;
			var self = this;			
			Progress.show('删除宝贝', '请稍等…', rows.length);
			(function(){
				var func = arguments.callee;
				if(!rows.length){
					Progress.hide();
					Dialog.alert({
						content: '所选宝贝删除完毕！',
						button: {
							'确 定': function(){
								l('.searchBtn').trigger('click');
							}
						},
						closeBtnVisible: false
					});
					return false;
				}
				
				var row = rows.shift(),
					Row = l('#'+table+' .bodier table tr[num_iid='+row.num_iid+']');
					
				Progress.val();
				self.deleteItem(Row.attr('num_iid'), function(success, bak){
					if(!success){
						Progress.hide();
						Dialog.alert({
							content: Row.attr('num_iid') + (bak || '删除失败！')
						});
						return false;
					}
					Row.remove();
					func();
				});
			})();
		},
		addCommends: function(rows){
			var self = this;			
			Progress.show('推荐宝贝到橱窗', '请稍等…', rows.length);
			(function(){
				var func = arguments.callee;
				if(!rows.length){
					Progress.hide();
					Dialog.alert({
						content: '所选宝贝推荐完毕！',
						button: {
							'确 定': function(){
								l('.searchBtn').trigger('click');
							}
						},
						closeBtnVisible: false
					});
					return false;
				}
				
				var row = rows.shift(),
					Row = l('#goods_on_sale .bodier table tr[num_iid='+row.num_iid+']');
					
				Progress.val();
				self.addCommend(Row.attr('num_iid'), function(success, msg){
					if(!success){
						Progress.hide();
						Dialog.alert({
							title: '宝贝推荐失败',
							content: Row.attr('num_iid') + (msg || '')
						});
						return false;
					}
					//Row.remove();
					func();					
				});
			})();			
		},
		deleteCommends: function(rows){
			var self = this;			
			Progress.show('取消橱窗推荐', '请稍等…', rows.length);
			(function(){
				var func = arguments.callee;
				if(!rows.length){
					Progress.hide();
					Dialog.alert({
						content: '所选宝贝取消推荐完毕！',
						button: {
							'确 定': function(){
								l('.searchBtn').trigger('click');
							}
						},
						closeBtnVisible: false
					});
					return false;
				}
				
				var row = rows.shift(),
					Row = l('#goods_on_sale .bodier table tr[num_iid='+row.num_iid+']');
					
				Progress.val();
				self.deleteCommend(Row.attr('num_iid'), function(success, msg){
					if(!success){
						Progress.hide();
						Dialog.alert({
							title: '取消推荐失败',
							content: Row.attr('num_iid') + (msg || '')
						});
						return false;
					}
					//Row.remove();
					func();
				});
			})();			
		},
		listingAll: function(rows){
			if(!confirm('确定上架所选宝贝？')) return false;
			var self = this;
			
			Progress.show('宝贝上架', '请稍等…', rows.length);
			(function(){
				var func = arguments.callee;
				if(!rows.length){
					Progress.hide();
					Dialog.alert({
						content: '所选宝贝上架完毕！',
						button: {
							'确 定': function(){
								l('.searchBtn').trigger('click');
							}
						},
						closeBtnVisible: false
					});
					return false;
				}
				
				var row = rows.shift(),
					Row = l('#goods_in_stock .bodier table tr[num_iid='+row.num_iid+']');
					
				Progress.val();
				self.listing(Row.attr('num_iid'), Row.attr('num'), function(success, bak){
					if(!success){
						Progress.hide();
						Dialog.alert({
							content: Row.attr('num_iid') + (bak || '上架失败！')
						});
						return false;
					}
					Row.remove();
					func();
				});
			})();
		},
		deListingAll: function(rows){
			if(!confirm('确定下架所选宝贝？')) return false;
			var self = this;
			
			Progress.show('宝贝下架', '请稍等…', rows.length);
			(function(){
				var func = arguments.callee;
				if(!rows.length){
					Progress.hide();
					Dialog.alert({
						content: '所选宝贝下架完毕！',
						button: {
							'确 定': function(){
								l('.searchBtn').trigger('click');
							}
						},
						closeBtnVisible: false
					});
					return false;
				}
				
				var row = rows.shift(),
					Row = l('#goods_on_sale .bodier table tr[num_iid='+row.num_iid+']');
					
				Progress.val();
				self.delisting(Row.attr('num_iid'), function(success, bak){
					if(!success){
						Progress.hide();
						Dialog.alert({
							content: Row.attr('num_iid') + (bak || '下架失败！')
						});
						return false;
					}
					Row.remove();
					func();
				});
			})();
		},
		edit: function(num_iid){
			var parentSize = {
				width: parseInt($(document).width()),
				height: parseInt($(document).height())
			},	screenSize = {
				width: parseInt(screen.width*0.8),
				height: parseInt(screen.height*0.9)
			};
						
			pur5.Pages.winResize(screenSize.width, screenSize.height);
			UI.setMoveRegion(30, 0, screenSize.width, 28);
			Dialog.alert({
				title: '编辑宝贝',
				content: '<iframe width="'+(screenSize.width-16)+'" height="'+(screenSize.height-84)+'" frameborder="0" application="no" src="http://upload.taobao.com/auction/publish/edit.htm?item_num_id='+num_iid+'"></iframe>',
				style: {
					border: '1px solid #ccc'
				},
				closeBtnVisible: false,
				action: function($content){
					$content.find('iframe').load(function(){
						var  Win = this.contentWindow,
							$doc = $(Win.document);
						$doc.find('.J_FlexSubmitBar').hide();
					});
				},
				button: {
					'确 定': false,
					'保 存': function($content){
						$content.find('iframe').contents().find('#event_submit_do_edit').click();
						return false;
					},
					'退 出': function(){
						pur5.Pages.winResize(parentSize.width, parentSize.height);
						UI.setMoveRegion(30, 0, parentSize.width-100, 28);
					}
				}
			});			
		},
		show: function(num_iid){
			var parentSize = {
				width: parseInt($(document).width()),
				height: parseInt($(document).height())
			},	screenSize = {
				width: parseInt(screen.width*0.8),
				height: parseInt(screen.height*0.9)
			};
						
			pur5.Pages.winResize(screenSize.width, screenSize.height);
			UI.setMoveRegion(30, 0, screenSize.width, 28);
			Dialog.alert({
				title: '浏览宝贝',
				content: '<iframe width="'+(screenSize.width-16)+'" height="'+(screenSize.height-84)+'" frameborder="0" application="no" src="http://item.taobao.com/item.htm?id='+num_iid+'"></iframe>',
				style: {
					border: '1px solid #ccc'
				},
				closeBtnVisible: false,
				action: function($content){
					$content.find('iframe').load(function(){
						var  Win = this.contentWindow,
							$doc = $(Win.document);
					});
				},
				button: {
					'确 定': false,
					'退 出': function(){
						pur5.Pages.winResize(parentSize.width, parentSize.height);
						UI.setMoveRegion(30, 0, parentSize.width-100, 28);
					}
				}
			});			
		}		
	}.init();
}();