AE.namespace('AE.run');
if(!AE.run.detailPOA) {

AE.run.detailPOA = function() {

	this.config = {
		target				:'',			// 
		actionUrl			:''				// urlַ
	};
};

AE.run.detailPOA.prototype = {

	init: function(customConfig) {
		this.config = YL.merge(this.config, customConfig || {});
		var _self = this,
			config = _self.config,
			obj = get(config.target);
			
		_self.isGs = config.target == "slider-gs" ? 1 :0;
		_self.loadCss('http://style.aliexpress.com/css/4v/wholesale/seller/slider.css');
		_self.loadJs('http://style.aliexpress.com/js/5v/app/slidebox/slidebox.js');

		YAHOO.util.Connect.asyncRequest("GET", config.actionUrl, {
			success:function(data){_self.showProductList(data.responseText, obj, _self);},
			failure:function(data){},
			timeout:5000
		}, null);
	},

	/**
	 * 为展示的产品添加曝光统计
	 * @param {Object} ids
	 */
	showStat : function(ids){
		var _self = this;
		if(!dmtrack || !ids) return;
		var url = "http://stat.alibaba.com/bt/aliexpress_show.html",
			//根据初始化容器判断当前页面类型，fm为 slider-fm（统计的page为102），gs为slider-gs（统计的page为103）
			params = {
				Page : _self.isGs ? "103" : "102" ,
				Object_type :"offer",
				ObjectID : ids ,
				rec_id : _self.isGs ? "3003" : "3005" ,
				user_id : '' ,
				isMember : ''
			};
		 dmtrack.clickstat(url,params);
	},
	/**
	 * 为产品绑定点击统计
	 */
	liveClickStat : function(){
		var _self = this;
		var statItems = YUD.getElementsByClassName("stat-item");
		YUE.on(statItems,"mousedown",function(e){
			YUE.stopPropagation(e);
			var productId = this.getAttribute("productId");
			if(!dmtrack || !productId)return;
			var url = "http://stat.alibaba.com/bt/aliexpress_click.html",
				params = {
					Page :  _self.isGs ? "103" : "102",
					Object_type: "offer",
					ObjectID : productId ,
					rec_id : _self.isGs ? "3003" : "3005",
					user_id : '' ,				
					isMember :''
				};
			dmtrack.clickstat(url,params);
		});
	},
	showProductList: function(jsonStr, obj, _self) {
		if(jsonStr == '{}' || jsonStr == '' || jsonStr == null){
			obj.style.display = 'none';
			return;
		}
		var json = eval('(' + jsonStr + ')');
		var items = '',
			productIds = '';
		if(json && json.products && json.products.length > 0) {
			for(var i=0; i<json.products.length; i++) {
				items += _self.buildItem(json, i);
				productIds += json.products[i].productId + ",";
			} 

			var black = 'G2 G4 G12 G15 ';
			var isBlack = (json.template != null) && (black.split(json.template + ' ').length > 1);

			obj.style.display = 'none';
			obj.innerHTML = _self.buildHeader(json, isBlack) + items + _self.buildFooter(json, isBlack) + _self.buildHotProductDetail() + _self.buildAliexpressDetail();
			_self.bindAliexpress();
			_self.bindHotProduct();
			_self.showStat(productIds);
			_self.liveClickStat();

			YUE.onDOMReady(function(){
				var count = 5;
				if(obj.id == 'slider-gs'){
					count = 4;
				}
				(new AE.app.Slidebox()).init({
					slideboxId				:'related-product-slide',
					containerClassName		:'pnl-slide-container',
					prevClassName			:'lnk-prev',
					nextClassName			:'lnk-next',
					prevDisabledClassName	:'lnk-prev-disabled',
					nextDisabledClassName	:'lnk-next-disabled',
					slideCount				:count,
					time					:200
				});
			});

			obj.style.display = 'block';
		}
	},

	loadCss: function(file){
		var head = document.getElementsByTagName('head').item(0);
		css = document.createElement('link');
		css.href = file;
		css.rel = 'stylesheet';
		css.type = 'text/css';
		head.appendChild(css);
	},
	
	loadJs: function(js_url){
		var head = document.getElementsByTagName('head').item(0);
		js = document.createElement('script');
		js.src = js_url;
		js.type = 'text/javascript';
		head.appendChild(js);
	},

	buildHeader: function(json, isBlack) {
		var header = '';

		if(isBlack) {
			header += '<div id="related-products" class="related black-template clearfix">'
					+ '<div id="aliexpress-caption" class="aliexpress-caption">Buy related wholesale products directly on <a class="aliexpress-link" target="_blank" href="http://www.aliexpress.com"><img border="0" src="http://img.alibaba.com/images/eng/wholesale/icon/aliexpress_logo.png" alt="AliExpress" /></a></div>';
		} else {
			header += '<div id="related-products" class="related clearfix">'
					+ '<div id="aliexpress-caption" class="aliexpress-caption">Buy related wholesale products directly on <a class="aliexpress-link" target="_blank" href="http://www.aliexpress.com"><img border="0" src="http://img.alibaba.com/images/eng/wholesale/icon/aliexpress_logo.gif" alt="AliExpress" /></a></div>'
		}

		header +=			'<div id="related-product-slide" class="product-slide">'
				+				'<div class="pnl-slide">'
				+ 					'<div class="pnl-slide-container">'
				+						'<ul>';

		return header;
	},
	
	buildFooter: function(json, isBlack) {
		var footer = 					'</ul>'
					+ 				'</div>'
					+ 			'</div>'
					+			'<a class="lnk-prev">Preview</a>'
					+			'<a class="lnk-next">Next</a>'
					+		'</div>'
					+	'</div>';

		var blackClass = '';
		if(isBlack) {
			blackClass = 'black-store-panel';
		}

		// if wholesale store is exist, more link, show it.
		if(json.type == 'gs' && json.storeUrl) {
			footer +=	'<div class="store-panel ' + blackClass + '"><a href="../Qingdao Luckall Hardware Co_, Ltd_ - Rigging, hardware, chain.files/' + json.storeUrl + '">View supplier\'s wholesale store</a></div>';
		} else if(json.type == 'fm' && json.storeUrl) {
			footer +=	'<div class="store-panel ' + blackClass + '"><a href="../Qingdao Luckall Hardware Co_, Ltd_ - Rigging, hardware, chain.files/' + json.storeUrl + '">View all wholesale products</a></div>';
		}

		// attached area
		footer +=		'<div class="attached clearfix">'
				+			'<div class="aliexpress-comment"></div>'
				+			'<div class="escrow-comment escrow-comment-' + json.type + '">Secure your payments online. <a rel="nofollow" class="learn-more" href="http://escrow.aliexpress.com/" target="_blank">Learn more</a></div>'
				+		'</div>';
		
		footer +=	'</div>';

		return footer;
	},

	buildItem: function(json, index) {
		var item =	'<li>';

		item += 		'<div class="pnl-thumb">'
			+					'<a class="lnk-thumb stat-item" productId="'+ json.products[index].productId  +'" href="../Qingdao Luckall Hardware Co_, Ltd_ - Rigging, hardware, chain.files/' + json.products[index].detailUrl + '" target="_blank" rel="nofollow"><img src="' + ((!json.products[index].imgUrl) ? ('http://img.alibaba.com/navigation/minisite/no_photo_detail.gif') : ('http://img.alibaba.com' + json.products[index].imgUrl)) + '" title="' + json.products[index].notHightLightSubject + '" /></a>'
			+			'</div>'

			+	'<div class="product-name">';

			if(json.products[index].hotProduct) {
				item += '<img class="hotproduct-icon" alt="" src="http://img.alibaba.com/images/eng/wholesale/icon/hotproduct_20x20.gif" />'
			}

		item +=			'<a class="stat-item" productId="'+ json.products[index].productId +'" href="../Qingdao Luckall Hardware Co_, Ltd_ - Rigging, hardware, chain.files/' + json.products[index].detailUrl + '" title="' + json.products[index].notHightLightSubject + '" target="_blank" rel="nofollow">' + json.products[index].subject + '</a>'
				+	'</div>'

			+			'<div class="price">US $' + json.products[index].priceRange;

		if(json.products[index].unit && json.products[index].unit.length > 0) {
			item +=			'<span class="unit"> / ' + json.products[index].unit + '</span>';
		}
		item += 		'</div>';

		if(json.products[index].num){
			item +=		'<div class="count">' + json.products[index].num + ' / lot</div>';
		}

		if(json.products[index].sold && parseInt(json.products[index].sold, 10) > 0) {
			item += '<div class="sold">'
				+		'Recently Sold: ' + json.products[index].sold
				+	'</div>';
		}

		item +=		'</li>';
		return item;
	},

	buildHotProductDetail: function() {
		return '<div id="hotproduct-icon-detail" class="over-tip" style="display:none;"><div class="arrow"></div><div class="tip-popup-content"><div><strong>Top-Rated Products</strong><ul><li>Top Feedback</li><li>Top Quality</li><li>Top Delivery</li></ul></div></div></div> ';
	},

	buildAliexpressDetail: function() {
		return '<div id="aliexpress-detail" class="over-tip" style="display:none;"><div class="arrow"></div><div class="tip-popup-content"><div><strong>AliExpress, your one-stop-shop for wholesale products online.</strong><ul><li>High resell value</li><li>Escrow Buyer Protection</li><li>Sample orders start at a item</li></ul></div></div></div> ';
	},

	bindHotProduct: function() {
		var excursion = [3, 20];
		if(AE.bom.isIE6){
			excursion = [-7, 20];
		}

		var poa = get('poa');
		var tip = get('hotproduct-icon-detail');
		var hotIcons = YUD.getElementsByClassName('hotproduct-icon', 'img', poa);
		for(var i=0, len=hotIcons.length; i<len; i++) {
			var hotIcon = hotIcons[i];
			var hotTip = tip.cloneNode(true);
			hotTip.removeAttribute('id');
			tip.parentNode.insertBefore(hotTip, tip);

			// 初始化人气宝贝 tab icon 的 overshow
			(new AE.widget.overShow()).init({
				targetId: hotIcon,
				positionId: false,
				contentId: hotTip,
				showDelayTime: 200,
				hiddenDelayTime: 200,
				excursion: excursion,
				needMask: false,
				needXY: true,
				closeBtnClass: 'close-button'
			});
		}
	},

	bindAliexpress: function() {
		var icon = get('aliexpress-caption');
		var tip = get('aliexpress-detail');
		(new AE.widget.overShow()).init({
			targetId: icon,
			positionId: false,
			contentId: tip,
			showDelayTime: 200,
			hiddenDelayTime: 200,
			excursion: ['right', 20],
			needMask: false,
			needXY: true,
			closeBtnClass: 'close-button'
		});
	}
};
}

