var bi_inquiry = {
	links: [],
	clkNums: 0,
	selfClkNums: 0,
	AB_URL: ['memberinquirysuccess',
			'unimemberregister/register.htm',
			'inquirysuccess',
			'step_03_success_2'], //Active Buyer URL
	group: '',		//"D", "MD", "C", "L", "F", "M"
	userGroup: '',
	isMainland: null,
	countryCode: '',
	chance: { 
		'L1': 0,		//List - SAP
		'L2': 0,		//List - not SAP not AB
		'D1': 0, 		//Detail - SAP
		'D2': 0,		//Detail - not SAP not AB
		'MD1': 0,		//Minisite Detail - SAP
		'MD2': 0,		//Minisite Detail - not SAP not AB
		'M': 0, 		//Minisite - not SAP not AB	
		'C': 0, 		//Contact - not SAP not AB
		'F': 0, 		//AB		
		'FN1': 0		//New Add AB 1
	},
	inquiryMapURL: {
		'L1': "http://test.research.alibaba.com/index.php?sid=27828&lang=en&27828X224X1540=cookieid&27828X224X1541=URL&27828X224X1542=Query",			//List - SAP
		'L2': "http://test.research.alibaba.com/index.php?sid=75214&lang=en&75214X214X1396=cookieid&75214X214X1397=URL&75214X214X1398=Query",			//List - not SAP not AB
		'D1': "http://test.research.alibaba.com/index.php?sid=24653&lang=en&24653X217X1436=cookieid&24653X217X1437=URL&24653X217X1438=Query", 			//Detail - SAP
		'D2': "http://test.research.alibaba.com/index.php?sid=86449&lang=en&86449X220X1497=cookieid&86449X220X1498=URL&86449X220X1499=Query",			//Detail - not SAP not AB
		'MD1': "http://test.research.alibaba.com/index.php?sid=21763&lang=en&21763X233X1666=cookieid&21763X233X1667=URL&21763X233X1668=Query",			//Minisite Detail - SAP
		'MD2': "http://test.research.alibaba.com/index.php?sid=21797&lang=en&21797X236X1706=cookieid&21797X236X1707=URL&21797X236X1708=Query",			//Minisite Detail - not SAP not AB
		'M': "http://test.research.alibaba.com/index.php?sid=64793&lang=en&64793X227X1581=cookieid&64793X227X1582=URL&64793X227X1583=Query", 			//Minisite - not SAP not AB	
		'C': "http://test.research.alibaba.com/index.php?sid=16332&lang=en&16332X230X1627=cookieid&16332X230X1628=URL", 			//Contact - not SAP not AB
		'F': "http://test.research.alibaba.com/index.php?sid=77111&lang=en&77111X213X1225=cookieid&77111X213X1226=URL", 			//AB		
		'FN1': "http://test.research.alibaba.com/index.php?sid=77111&lang=en&77111X213X1225=cookieid&77111X213X1226=URL"			//New Add URL AB
	},
	getAllLinks: function() {		
		this.links = document.getElementsByTagName('a');		
	},
	noticeStr: "Before you close the page, take our survey and you could\nWin a US $50 Amazon Gift Certificate.\n\nClick \"Cancel\" to start the survey or click \"OK\" to close this page.",
	
	start: function(group) {	
		YUE.onDOMReady(bi_inquiry._start,bi_inquiry,true);			
		this.group = group;	
		try{
			clk('bi_inquiry_start_' + this.group);
		}catch(e){}
	},
	_start: function() {
		this.getAllLinks();
		this.listenUserActions();		
		if (typeof msgBox == "undefined") {			
			this.loadScript("http://style.alibaba.com/js/app/msg_box.js");
			var css,style=document.createElement('style');
			style.type='text/css';
			document.getElementsByTagName('head').item(0).appendChild(style);
			css=document.styleSheets[document.styleSheets.length-1];
			
			if(css.addRule)
			{
				css.addRule('.PopUpFrame','border:4px solid #CBE4F1;padding:7px;background:#ffffff;');
				css.addRule('.msgBoxCloseButtonImg','position:absolute;top:7px;right:7px;width:11px;height:11px;background:url(\'http://img.alibaba.com/images/eng/style/icon/close.gif\') no-repeat -2px -2px;_overflow:hidden;');
				css.addRule('.PopUpFrame h3','font:bold 13px/15px arial;color:#4888ab;position:absolute;top:7px;left:7px;z-index:1000;');
				css.addRule('.PopUpFrame iframe','background:#fff;width:100%;');
				css.addRule('.PopUpMask','position:absolute;z-index:10;left:0;top:0;background:#000;filter: Alpha(Opacity=20);');
			}else{
				css.insertRule('.PopUpFrame{border:4px solid #CBE4F1;padding:7px;background:#ffffff;}',css.cssRules.length);
				css.insertRule('.msgBoxCloseButtonImg{position:absolute;top:7px;right:7px;width:11px;height:11px;background:url(\'http://img.alibaba.com/images/eng/style/icon/close.gif\') no-repeat -2px -2px;_overflow:hidden;}',css.cssRules.length);
				css.insertRule('.PopUpFrame h3{font:bold 13px/15px arial;color:#4888ab;position:absolute;top:7px;left:7px;z-index:1000;}',css.cssRules.length);
				css.insertRule('.PopUpFrame iframe{background:#fff;width:100%;}',css.cssRules.length);
				css.insertRule('.PopUpMask{position:absolute;z-index:10;left:0;top:0;background:#000;filter: Alpha(Opacity=20);}',css.cssRules.length);
			}
		}
	},	
	listenUserActions: function() {		
		if (this.links.length > 0) {
			for (var i = 0; i < this.links.length; i++) {
				if (this.links[i].id != "new_user_close") {
					YUE.on(this.links[i], "click", function(ev, link) {						
						if (ev.button == 0) {							
							if (!(link.attributes["href"] == undefined || 
								!link.attributes["href"].specified || 
								link.href.indexOf("noLink") > -1)) {
								this.clkNums++;								
							}							
							var aTarget = link.getAttribute("target");
							if (aTarget === null || aTarget.toUpperCase() != "_BLANK") {
								this.selfClkNums++;
							}
						}
					}, this.links[i], bi_inquiry);
				}				
			}			
			
			/*
			YUE.on(document, "click", function(ev) {			
				if(ev.button == 0) {
					if(YUE.getTarget(ev).tagName.toUpperCase() == "A") {
						this.clkNums++;		
						var aTarget = YUE.getTarget(ev).getAttribute("target");			
						if (aTarget === null || aTarget.toUpperCase() != "_BLANK") {
							this.selfClkNums++;
						}
					}
				}
				
			}, bi_inquiry, true);	
			*/
		}		
		YUE.on(document, "keydown", function(ev) {				
			if(ev.keyCode == 116) {
				YUE.removeListener(window, "beforeunload");
			}
		});	
		
		YUE.on(window, "beforeunload", this._onWindowUnload,bi_inquiry,true);	
		if (YUD.get("submitbutton")) {
			YUE.on("submitbutton", "click", function() {
				YUE.removeListener(window, "beforeunload");
			});		
		}
		if (YUD.get("searchSubmit")) {
			YUE.on("searchSubmit", "click", function() {
				YUE.removeListener(window, "beforeunload");
			});		
		}
		if (YUD.get("actionButton")) {
			YUE.on("actionButton", "click", function() {
				YUE.removeListener(window, "beforeunload");
			});		
		}
		var imgButtons = document.getElementsByClassName("imageButtonA");
		if (imgButtons.length > 0) {
			YUE.on(imgButtons, "click", function() {
				YUE.removeListener(window, "beforeunload");
			});
		}
		
		var submitBtns = document.getElementsByClassName("submitBtn");
		if (submitBtns.length > 0) {
			YUE.on(submitBtns, "click", function() {
				YUE.removeListener(window, "beforeunload");
			});
		}
	},	
	isSAP: function() {
		var _index = document.referrer;
		if(_index){
			var hosts = _index.split('http://')[1].split('/')[0];			
			if(hosts.indexOf('alibaba.com') != -1){
				return false;
			}else{				
				return true;
			}
		}else{
			return true;
		}
	},	
	isAB: function() {
		for (var i = 0; i < this.AB_URL.length; i++) {
			if (document.URL.toLowerCase().indexOf(this.AB_URL[i]) != -1) {				
				return true;
			}
		}
		
		return false;
	},
	getChance: function(chance) {
		var num = Math.floor(Math.random()*100+1);	
		if (num <= chance) {
			try{
				clk('getChanceSuccess_' + this.userGroup + "_" + num);
			}catch(e){}
			return true;
		} else {
			try{
				clk('getChanceFailed_' + this.userGroup + "_" + num);
			}catch(e){}
		}
		return false;
	},
	hasShowQuestionnaire: function() {	
		var cv = YUD.getCookie("bi_inquiry");
		if (cv.charAt(0) && cv.charAt(0) != '0') {
			return true;
		} else {
			return false;
		}
	},
	userInChinaMainland: function() {
		if (this.isMainland != null) {
			return this.isMainland;									
		} else {															
			return false;											
		}
	},
	doInquiryAccordingToChance: function(chance, ev) {		
		if (this.getChance(chance)) {			
			if (this._showQuestionnaire()) {
				ev.returnValue = this.noticeStr;
			}
		} 
	},
	_onWindowUnload: function(ev) {		
		try{
			clk('beforeWindowUnload_' + this.group);
		}catch(e){}
		if (document.referrer == "") {   		
			return;
		}		
		if (this.hasShowQuestionnaire()) {				
			return;
		}	
		
		switch (this.group) {
			case "D":
			case "MD":
			case "L":
				if (this.clkNums > 0) {					
					return;
				}
				if (this.isSAP()) {				
					this.userGroup = this.group + "1";
					try{
						clk('is_sap_' + this.userGroup);
					}catch(e){}
				} else if (!this.isAB() && (!this.isSAP())) {
					if (this.group == "L") {
						return;
					}
					this.userGroup = this.group + "2";
					try{
						clk('notSapNotAB_' + this.userGroup);
					}catch(e){}
				}				
				break;			
			case "M":
				if (this.clkNums > 0) {				
					return;
				}
				if (this.isSAP() && /\/productshowimg\//.test(document.URL)) {
					this.userGroup = "MD1";
					try{
						clk('is_sap_MD1');
					}catch(e){}
				} else if(!this.isAB() && (!this.isSAP())) {
					this.userGroup = this.group;
				}
				break;
			case "C":					
				break;
			case "F":
			case "FN1":				
				break;
		}
		
		if (this.userInChinaMainland()) {			
			return;
		} 
		
		if(this.userGroup) {
			this.doInquiryAccordingToChance(this.chance[this.userGroup], ev);
		}		
	},	
	loadScript: function(url){
		var script = document.createElement("script");
		script.type = "text/javascript";
		script.src = url;
		document.body.appendChild(script);
	},
	_showQuestionnaire: function() {		
		//the params sending to the Questionnaire platform 
		var cookieId = encodeURIComponent(YUD.getCookie("ali_beacon_id")),
			lastURL = encodeURIComponent(document.referrer),
			query = encodeURIComponent(location.search.replace(/^\?/,"")),	
			beIframe = (this.inquiryMapURL[this.userGroup].indexOf("http://") > -1),
			msgBoxHeight = YUD.getViewportHeight(),
			msgBoxWidth = Math.min(YUD.getViewportWidth() - 80, 960);
			inquiryURL = this.inquiryMapURL[this.userGroup];		
		if (beIframe == true) {
			inquiryURL = inquiryURL.replace("=cookieid", "=" + cookieId);
			inquiryURL = inquiryURL.replace("=URL", "=" + lastURL);
			inquiryURL = inquiryURL.replace("=Query", "=" + query);
		}
		if(typeof msgBox == "undefined") {
			// do nothing if msgBox isUnavailable
			try{
				clk('msgBoxUnavailable_' + this.userGroup);
			}catch(e){}
			return false;
		} else {					
			if (YUD.get("AE:receiver-list")) {					//bug_fix contact.htm alibaba.com:z-index:9998
				YUD.get("AE:receiver-list").style.zIndex = 1;
			}
			if (YUD.get("companyAboutUsPicRind")) {
				var tmp = YUD.get("companyAboutUsPicRind").getElementsByTagName("span")[0];
				if (tmp) {
					tmp.style.zIndex = 1;
				}
			}
			var titleMarginLeft = msgBoxWidth / 2 - 55; 	
			var cookieValue = this.or(YUD.getCookie("bi_inquiry"),'1');
			YUD.setCookie("bi_inquiry",cookieValue, 60, "alibaba.com", "/");
			var tmpCookie = YUD.getCookie("bi_inquiry");
			if (tmpCookie != "") {				
				msgBox.xWindow(inquiryURL, [msgBoxWidth, msgBoxHeight],"<p style=\"margin-left:" + titleMarginLeft + "px;\">Buyer Survey</p>", beIframe);
				try{
					clk('cookieSetMsgBoxShow_' + this.userGroup);
				}catch(e){}
			} else {				
				try{
					if (this.userGroup == "MD1") {
						YUD.setCookie("bi_inquiry",cookieValue, 60, "", "/");
						if (YUD.getCookie("bi_inquiry") != "") {
							msgBox.xWindow(inquiryURL, [msgBoxWidth, msgBoxHeight],"<p style=\"margin-left:" + titleMarginLeft + "px;\">Buyer Survey</p>", beIframe);								
							clk('cookieSetMsgBoxShow_' + this.userGroup);
							return true;
						} else {
							if (location.host.indexOf("alibaba.com") > -1) {
								clk('cookieSetFailed_' + this.userGroup + "_ali");
							} else {
								clk('cookieSetFailed_' + this.userGroup + "_notali");
							}						
						}						
					} else {
						clk('cookieSetFailed_' + this.userGroup);
					}
					
				}catch(e){}		
				return false;
			}
			
			YUE.removeListener(window,"beforeunload");
		}
		return true;
	},

	or: function (str1, str2) {
         var as1 = str1.split(''),
            as2 = str2.split(''),
            ret = [],
            len = Math.max(as1.length, as2.length);
      
         for (var i = 0; i < len; ++i) {   
            as1[i] = ((as1[i] || 0) == 0) ? 0 : as1[i];
            as2[i] = ((as2[i] || 0) == 0) ? 0 : as2[i];            
            cur = as1[i] || as2[i];
            ret.push(cur);
         }
         return ret.join('');
    }   

};

