function setCookies(name,value,times)
{
   var exp   = new Date();     //new Date("December 31, 9998");
   exp.setTime(exp.getTime() + times*1000);
   document.cookie = name + "="+ escape(value) +";expires="+ exp.toGMTString();
}

function getCookies(name)
{
   var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
   if(arr != null) return unescape(arr[2]); return null;
}
//if login, show username
function bindingUserName(otherPageName) {
	bindingUserName1(otherPageName);
	setInterval('bindingUserName2("'+otherPageName+'")',30000);
}

function bindingUserName2(otherPageName){
	var currbuyerid = '';
	if(null != document.getElementById('currbuyerid'))
		currbuyerid = document.getElementById('currbuyerid').value;
	if(getCookies('sendRefreshBuyer' + currbuyerid) != null){
		return;
	}
	setCookies('sendRefreshBuyer' + currbuyerid, 'asdjfkljsa', 30);
	bindingUserName1(otherPageName);
	return false;
}

function bindingUserName1(otherPageName){
	jQuery.ajax({
		   url: otherPageName, 
		   dataType : "html",
		   cache: false,
           type: 'GET', // 设置请求类型为 ‘POST’，默认为 ‘GET’
           error: function(XMLHttpRequest, textStatus, errorThrown) {
           		
           },
           success: function(data) {
                getUserName(data);
           }
     });
}

function getUserName(reply){
	var replyArray = reply.split('|');
	document.getElementById('loginbar').innerHTML = replyArray[0];
	
	if(replyArray != null && replyArray.length > 1){
		if(replyArray[1] != ''){
			document.getElementById('buyerCartCount').innerHTML = replyArray[1];
		}
	}
	var iminfo = replyArray[2];
	if("" != iminfo && "null" != iminfo && document.getElementById('currbuyerid')){
		var currbuyerid = document.getElementById('currbuyerid').value;
		if(currbuyerid == ''){
			return;
		}
		var talkcookie = 'LinkChinaIMCK' + currbuyerid;
		var openDMaskCookie = 'openDMaskCookie' + currbuyerid;
		
		if(getCookies(talkcookie) != null){
			return;
		}
		
		if(getCookies(openDMaskCookie) != null) {
			return;
		}
		
		//setCookies(talkcookie, 'abcdefg', 60);
		var openwin = window.open('/imopen--' + iminfo);
		if(!openwin){
			var split = iminfo.split("--");
			var username = split[1];
			if(username == ""){
				username = split[3];
			}
			
			openDMask(username, '/imopen--' + iminfo);
		}
	}
}

function hiddenclockinfo(){
	var info = document.getElementById('IMNoticeBar');
	info.display = false;
}
//keywords from search engine
function searchassistant(inputobj,e){
	if(!e) e = window.event;
	if(e.keyCode == 40 || e.keyCode == 38 || e.keyCode == 13) return;
	
	jQuery.ajax({
		   url: '../../keywordsSimple.do?keywords='+inputobj.value, 
		   dataType : "html",
		   cache: false,
           type: 'GET', // 设置请求类型为 ‘POST’，默认为 ‘GET’
           error: function(XMLHttpRequest, textStatus, errorThrown) {
           		
           },
           success: function(data) {
                getAssistantWords(data);
           }
     });
   
	return false;
}

function getAssistantWords(result){
	if(result==null || result == ''){
		dropdownKeywords(document.getElementById('searchproductname'),null);
		return;
	}
	
	//replace the ' simble
	result = result.replace(/\'/g,"");
	
	var objarray = result.split("||");
   	if(objarray != null){
   		var keywordsList = new Array();
    	for(i=0;i<objarray.length;i++){
   			var temp = objarray[i].split("@@");
			keywordsList[i] = [temp[0],temp[1]];    		
   		}
   		
   		dropdownKeywords(document.getElementById('searchproductname'),keywordsList);
   	}
}

function replacevalid(searchproductname){
	if(searchproductname == null || searchproductname == ''){
		return '';
	}

	//replace - to wholesale-05
	searchproductname = searchproductname.replace(/\-/g,"wholesale-05");

	//replace & to wholesale-01
	searchproductname = searchproductname.replace(/\&/g,"wholesale-01");
	
	//replace % to wholesale-02
	searchproductname = searchproductname.replace(/\%/g,"wholesale-02");
	
	//replace # to wholesale-03
	searchproductname = searchproductname.replace(/\#/g,"wholesale-03");
	
	//replace + to wholesale-04
	searchproductname = searchproductname.replace(/\+/g,"wholesale-04");
	
	//replace \ to wholesale-07
	searchproductname = searchproductname.replace(/\\/g,"wholesale-07");

	//replace wholesale to wholesale-06
	searchproductname = searchproductname.replace(/\wholesale/g,"wholesale-06");
	
	//replace ' ' to -
	searchproductname = searchproductname.replace(/\s/g,'-');
	return searchproductname;
}

function changeDoToUrlBase(searchproductname,searchcatalogid){
	searchproductname = replacevalid(searchproductname);
	
	var url = '/buy/' + searchproductname + '/' + searchcatalogid + '--40-1--';
		url += getPriceStart() + '-';
		url += getPriceEnd() + '-';
		url += isFreeShipping() + '-';
		url += getCatalogPropertyValue() + '.html';
	document.location.href = url;
}
/** 用于获取当前类目下的属性选项搜索*/
function getCatalogPropertyValue() {
	var options = document.getElementsByName('catalogPropertyValue');
	
	if(options == undefined) {
		return '';
	}
		
	var str = '';
	
	for(var i=0; i<options.length; i++){
		
		if(options[i].checked){
			
			str += options[i].value + ',';
		}
	}
	if(str == '' || str.length == 0) {
		str = '';
	}
	
	return str;
}
/** 获取showonly区域的 freeshiping复选框是否选中*/
function isFreeShipping() {
	
	var only = document.getElementsByName("onlyFreeShipping");
	
	if(only == undefined) {
		return '';
	}
	
	for(i = 0 ; i < only.length ; i++) {
	
		if(only[i].checked == true) {
			return only[i].value;
		}
	}
	
	return '';
}

/** 获取showonly区域价格区间 起始价格*/
function getPriceStart() {
	
	var priceStart = document.getElementById('onlyPriceStart');
	
	if(priceStart == undefined) {
		
		return '';
	}
	
	return priceStart.value;
	
}
/** 获取showonly区域价格区间 结束价格*/
function getPriceEnd() {
	
	var priceEnd = document.getElementById('onlyPriceEnd');
	
	if(priceEnd == undefined) {
		
		return '';
	}
	
	return priceEnd.value;
}

//change .do to url
function changeDoToUrl(e){
	if(!e) var e = window.event;
	if(e.keyCode == 13) submitSearchKeyWords();
}

var PLEASE_ENTER_KEYWORDS = "Please enter the keywords";

function submitSearchKeyWords(){
	var searchproductname = document.getElementById('searchproductname');
	var searchcatalogid = document.getElementById('searchcatalogid').value;
	if (searchproductname.value.trim() == ''){
		searchproductname.value = PLEASE_ENTER_KEYWORDS;
		searchproductname.style.color = '#999';
		return;
	} else if (searchproductname.value.trim() == PLEASE_ENTER_KEYWORDS){
		searchproductname.value = PLEASE_ENTER_KEYWORDS;
		searchproductname.style.color = '#999';
		return;
	}
		
		changeDoToUrlBase(searchproductname.value,searchcatalogid);
}

function changeDoToUrlfooter(){
	var searchproductname = document.getElementById('searchproductnamefooter').value;
	var searchcatalogid = document.getElementById('searchcatalogidfooter').value;
	
	changeDoToUrlBase(searchproductname,searchcatalogid);
}

function cart(){
	window.location.href='/buyerCart.do';
}

function leaveMsg (){
	window.open('/leaveMessageInsert.do','leaveMsg','status=yes,resizable=yes,width=610,height=430');
}

function clearSearchInform(obj){
	if (obj.value.trim() == PLEASE_ENTER_KEYWORDS){
		obj.value = '';
		obj.style.color = '#000';
	}
	
}
function showSearchInform(obj){
	if (obj.value.trim() == '') {
		obj.value = PLEASE_ENTER_KEYWORDS;
		obj.style.color = '#999';
	}
}
String.prototype.trim = function(){ 
	return this.replace(/(^\s*)|(\s*$)/g, ""); 
}
var isIE6Browsercart = false;
function recoIeBrowsercart(){
	var browser=navigator.appName;
	var b_version=navigator.appVersion;
	var version=b_version.split(";");
	var trim_Version=version[1].replace(/[ ]/g,"");
	if(browser=="Microsoft Internet Explorer" && trim_Version=="MSIE6.0")
	{
		isIE6Browsercart = true;
	} else {
		isIE6Browsercart = false;
	}
}
recoIeBrowsercart();

var ifrmFlagcart = 0;
function bindingProductList(otherPageName) {
	jQuery.ajax({
		   url: otherPageName, 
		   dataType : "html",
		   cache: false,
           type: 'GET', // 设置请求类型为 ‘POST’，默认为 ‘GET’
           error: function(XMLHttpRequest, textStatus, errorThrown) {
           		
           },
           success: function(data) {
                getProductList(data);
           }
     });
	return false;
}

var indexflag = 0;
function getProductList(reply){
	document.getElementById('miniShoppingCartCon').innerHTML = reply;
//	var tab = document.getElementById('shoppingcartid');
	var obj = document.getElementById("miniShoppingCart");
	if(isIE6Browsercart){
		if(ifrmFlagcart == 0){
			var ifrm = document.createElement("iframe");
			ifrmFlagcart = 1;
			ifrm.id = 'miniShoppingCartid';
			obj.appendChild(ifrm);
		}
	}
	document.getElementById("miniShoppingCart").style.display="block";
	indexflag = 1;
//	tab.className = "act";
}

var s;
function indexshowMessage(){
	if(indexflag == 0){
		s=window.setTimeout("indexshow();",500);
	}else{
		window.clearTimeout(s);
	}
}

function indexshow(){
	var cartCount = document.getElementById('cartCount').innerHTML;
	if(cartCount != "0"){
		bindingProductList("/buyerCartProducts.do");
	}else{
		return false;
	}
}

function indexhiddenMessage(){
    s=window.setTimeout("indexhidden();",1000);
}

function indexhidden(){
	
//	var tab = document.getElementById('tagCategories');
	var obj = document.getElementById("miniShoppingCart");
//	tab.className = "";
    document.getElementById("miniShoppingCart").style.display="none";
    indexflag = 0;
    if(isIE6Browsercart){
		if(ifrmFlagcart == 1 && document.getElementById("miniShoppingCartid")){
			var ifrm = document.getElementById("miniShoppingCartid");
			obj.removeChild(ifrm);
			ifrmFlagcart = 0;
		}	
	}
}

function checkInputPrice(priceText) {
	str = priceText.value;
	for (var i = (str.length - 1) * 1; i >= 0; i--) {
		if (!isFloat(str)) {
			var ilen = str.length;
			str = str.substring(0, ilen - 1);
		} else {
			var dotindex = str.indexOf(".");
			if (dotindex > 0) {
				if (str.length - dotindex > 3) {
					var ilen = str.length;
					str = str.substring(0, ilen - 1);
				}
			}
			break;
		}
	}
	priceText.value = str;
}

//判断是否是浮点数
function isFloat(s)
{
	var patrn =/^([1-9]\d*)$|(0)$/;
	var patrn1=/^([0-9]\d*)$/
	
	var dotindex=s.indexOf(".");
	if(dotindex>0)
	{
		var bs=s.substring(0,dotindex);
		if (!patrn.exec(bs)) 
			return false;
		if(dotindex==s.length-1){
			return true;
		}else{
			var es = s.substring(dotindex+1);
			if (!patrn1.exec(es)) 
				return false;
			else
				return true;
		}
	}
	if (!patrn.exec(s)) 
		return false;
	else
		return true;
}

var playing = 0;
var currfocus = 1;
var flag = 0;
var tempTitle = document.title;
   function indexTitleFlash(stat){
   	if(currfocus == 1){
   		return;
   	}
   	if(stat == 1){
   		if(playing == 1){
   			return;
   		}
   		playing = 1;
   	}
	if(flag % 2 == 0){
		document.title = "LinkChina WebIM";
	}else{
		document.title = "New Message";
	}
	flag ++;
	if(playing == 1 && currfocus == 0){
		setTimeout("indexTitleFlash(0)", 400);
	}else{
		callimFocus();
	}
   }
   function callimFocus(){
	   	currfocus = 1;
	   	playing = 0;
	   	document.title = tempTitle;
  }

var mask_D_width = 480;
var ediD = false;
var firsDshow = 0;
var fixedDX = 0;
var panlD, mskD = null;
function initDetector(dynamicWidth) {
	

	if(ediD == false) return;
	
	var panlD = document.getElementById("detector_container");
	var mskD = document.getElementById("detector_mask");
	if(dynamicWidth > 0){
		//alert("B: dynamicWidth == " + dynamicWidth);
		panlD.style.width = dynamicWidth + "px";	
	} else {
		//alert("C: " + dynamicWidth );
		panlD.style.width = "480px";	
	}
	mskD.style.position = "absolute";
	mskD.style.left = "0px";
	mskD.style.top = "0px";
	mskD.style.background = "#000";
	mskD.style.zIndex = 20;
	
	panlD.style.position = "absolute";	
	panlD.style.zIndex = 21;
	//panlD.style.border = "1px solid #ff3";
	panlD.style.width = "480px";
	panlD.style.height = "150px";
	panlD.style.left = "0px";
	panlD.style.top = "0px";

	panlD.style.display = "block";
	mskD.style.display = "block";
	
	if (!document.all){
		var w = parseInt(window.innerWidth);//窗口可见宽度
		var h = parseInt(window.innerHeight);//窗口可见高度
		var x = parseInt(window.pageXOffset);//页面滚动的宽度
		var y = parseInt(window.pageYOffset);//页面滚动的高度
    }else{
		var w = parseInt(document.documentElement.clientWidth);//窗口可见宽度
		var h = parseInt(document.documentElement.clientHeight);//窗口可见高度
		var x = parseInt(document.documentElement.scrollLeft);//页面滚动的宽度
		var y = parseInt(document.documentElement.scrollTop);//页面滚动的高度
    }
	//document.title = "w: ," + w + ", h:" + h + ", x:" + x + ", y:" + y;
	
	
	
	var m_w = (w - parseInt(panlD.offsetWidth)) / 2;
	
	var panlD_h = parseInt(panlD.offsetHeight);
	var body_h = parseInt(document.body.offsetHeight);
	
	var real_H = findMax(h, panlD_h, body_h);
	if(real_H <= panlD_h) {
		//real_H = real_H + 60;
		real_H = real_H;
	}
	
	mskD.style.left = "0px";
	mskD.style.top = "0px";
		if(dynamicWidth>w || panlD_h>h){
			if(fixedDX == 0){
				panlD.style.top = y + "px";
				panlD.style.left = x+ "px";	
/*			if(y <80){
				document.body.style.paddingTop = 30 + "px";	
			}else{
				document.body.style.paddingTop = 0 + "px";	
			}*/
				fixedDX++;

			}
		}else {
			panlD.style.left = (m_w <= 0) ? "0px" : m_w + "px";
			panlD.style.top = y + (h - panlD_h)/2 + "px";
			//panlD.style.top = y + 3 + "px";
/*			if(y <80){
				document.body.style.paddingTop = 30 + "px";	
			}else{
				document.body.style.paddingTop = 0 + "px";	
			}*/
			fixedDX = 0;
		}
	mskD.style.width = (w < dynamicWidth) ? dynamicWidth + 40 + "px" : w + "px";
	//mskD.style.width = (w < parseInt(panlD.offsetWidth)) ? parseInt(panlD.offsetWidth) + "px" : w + "px";
	mskD.style.height = real_H + "px"; //如果实际高度大于检测到的高度,则以实际高度为准
	
	
	

	//alert("scroll go top from here!");
	
	
/*
	if(firsDshow == 0){
		panlD.style.top = y + 20 + "px";//别下沉!	
	}
*/

	var final_panlD_h = panlD_h + y + 2;
	if(final_panlD_h >= real_H) {
		mskD.style.height = final_panlD_h + "px";
	}
	
	firsDshow++;
}

function findMax (a, b, c) {
	if(a>b) {
		if(a > c){
			return a;
		} else {
			return c;
		}
	} else {
		if(b > c){
			return b;
		} else {
			return c;
		}
	}
}



function openDMask(username, link, url, mw, transp) {
	if(mw == undefined) {
		mw = 480;
	}
	mask_D_width = mw;
	if(!document.getElementById("detector_container")){
		panlD = document.createElement("div");
		panlD.id = "detector_container";
		document.body.appendChild(panlD);
	}
	
	if(!document.getElementById("detector_mask")){
		mskD = document.createElement("div");
		mskD.id = "detector_mask";
		document.body.appendChild(mskD);
	}
	//var url = encodeURI(url);
	if(document.all){
		var selectObj = document.all.tags("SELECT");
		if(selectObj.length > 0) {
			for (i = 0; i < selectObj.length; ++i){
				if(selectObj[i].nodeName == "SELECT" ){
					selectObj[i].style.visibility = "hidden";
				}
			}
		}
	}
	if(!transp) transp = 40;
	if(document.all){
		mskD.style.filter = "alpha(opacity="+transp+")";
	} else {
		mskD.style.opacity = transp / 100;
	}

	ediD = true;
	if(document.getElementById("imPlayer") != undefined && document.getElementById("imPlayer") != null){
	
		if(typeof(document.getElementById("imPlayer")).toLowerCase() == "object" && document.getElementById("imPlayer").innerHTML != ""){
			document.getElementById("imPlayer").innerHTML = "";
			var chld = document.getElementById("imPlayer");
			document.body.removeChild(chld);
		}
	}
	
	var embedRingTone = '<div id="imPlayer" style="visibility:hidden:width:1px;height:1px;">'
	+'<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="1" height="1" id="ringtone" align="middle">'
	+'<param name="allowScriptAccess" value="sameDomain" />'
	+'<param name="allowFullScreen" value="false" />'
	+'<param name="movie" value="http://image.linkchina.com/im/ringtone.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" />	<embed src="http://image.linkchina.com/im/ringtone.swf" quality="high" bgcolor="#ffffff" width="1" height="1" name="ringtone" align="middle" allowscriptaccess="sameDomain" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />'
	+'</object>'
	+'</div>';
	
	panlD.innerHTML = '<div id="IMNoticeBar"><div><div><img src="http://image.linkchina.com/buyer/icon_close.gif" alt="close" title="close" class="close" onclick="closeDMask(\'' + link + '\')" /><p>Notice</p><br/>Due to the basic set up problem of your browser, ' + username + '\'s message has been blocked. Please click <a href="#" class="shamrock" onclick="closeDMask(\'' + link + '\');">Open LinkChina WebIM</a> link to get the information.&nbsp;&nbsp;&nbsp;<span class="shamrock close" onclick="closeDMask(\'' + link + '\')">&lt;&nbsp;Close&nbsp;&gt;'+embedRingTone+'</span></div></div></div>';
	setTimeout("initDetector("+mask_D_width+")",50);
	
	//闪烁
	currfocus = 0;
	indexTitleFlash(1);
	
	var currbuyerid = document.getElementById('currbuyerid').value;
	
	//写cookie ,用于30秒 刷新时判断 当前蒙板存在状态 不在继续window.open()
	setCookies('openDMaskCookie' + currbuyerid, 'aaaaa', 35);
	setInterval('DMaskCookie()',30000);
	//panlD.style.top = (h - parseInt(panlD.offsetHeight)) / 2 + "px";
}

function DMaskCookie() {
	var currbuyerid = document.getElementById('currbuyerid').value;
	var openDMaskCookie = 'openDMaskCookie' + currbuyerid;
	
	if(getCookies(openDMaskCookie) != null) {
		setCookies(openDMaskCookie, 'aaaaa', 35);
	}
}

function closeDMask(link) { 
	callimFocus();
	var currbuyerid = document.getElementById('currbuyerid').value;
	
	//将cookie值 设置为空
	setCookies('openDMaskCookie' + currbuyerid, '', 1);
	if(link == undefined){
		return;	
	}
	//if(document.all){
		//stop();
	//}
	window.open(link);
	var panlD = document.getElementById("detector_container");
	var mskD = document.getElementById("detector_mask");
	if(document.all){
		var selectObj = document.all.tags("SELECT");
		if(selectObj.length > 0) {
			for (i = 0; i < selectObj.length; ++i){
				if(selectObj[i].nodeName == "SELECT" ){
					selectObj[i].style.visibility = "visible";
				}
			}
		}
	}
	panlD.style.display = "none";
	mskD.style.display = "none";
	
	ediD = false;
	mask_D_width = 0;
	panlD.innerHTML = "";
	panlD, mskD = null;
/*	if(parseInt(document.body.style.paddingTop) > 0){
		document.body.style.paddingTop = "0px";
	}*/
	
}

function stop(e) {

	if (!e) e = window.event;
	(e.stopPropagation) ? e.stopPropagation() : e.cancelBubble = true;
	(e.preventDefault) ? e.preventDefault() : e.returnValue = false;
	return false;

}

window.onresize = function(){
	if(ediD) initDetector(mask_D_width);

}
window.onscroll = function(){
	if(ediD) initDetector(mask_D_width);

}