var $=function(id){return document.getElementById(id);}
var $n=function(id){return document.getElementsByName(name);}


String.prototype.trim = function(){return this.replace(/(^\s*)|(\s*$)/g, "");} /*去左右空格*/
String.prototype.ltrim = function(){return this.replace(/^\s*/g, "");}  /*去左空格*/
String.prototype.rtrim = function(){return this.replace(/\s*$/g, "");}  /*去右空格*/


/**判断浏览器类型*/
function isIE(){if(window.navigator.userAgent.toLowerCase().indexOf("msie")>=1){return true;}else{return false;}}
/**添加新动作，如onload等.el为window,eventType为事件,fn为函数,如addListener(window,"load",playit);*/
function addListener(el,eventType,fn){
	if(el.addEventListener){
		el.addEventListener(eventType,fn,false);
	}else if(el.attachEvent){
		el.attachEvent("on" + eventType,fn);
	}else{
		el["on"+eventType] = fn;
	}
}
/*添加到收藏夹*/
function addBookmark(){
	var title = document.getElementsByTagName("title")[0].innerHTML;
	var url = location.href;
	if(window.sidebar){try{window.sidebar.addPanel(title,url,"");}catch(e){}}
	else{window.external.AddFavorite(url,title);}
}
/**设置cookie,以秒为单位*/
function setCookie(cookieName, cookieValue) {
	var cookieStr = cookieName + "=" + escape(cookieValue) + "; path=/";
	if(arguments.length==3){
		var date=new Date();
		date.setTime(date.getTime()+arguments[2]*1000);
		cookieStr += "; expires="+date.toGMTString();
	}
	if(arguments.length==4){cookieStr += "; domain="+arguments[3];}
	document.cookie = cookieStr;
}
/**获取cookie*/
function getCookie(cookieName) {  
    var cookies = document.cookie;
    var thePart = cookieName + "=";
    var thePartLen = thePart.length;
    var i=0;
    while(i < cookies.length){
        var j = i + thePartLen;
        if(cookies.substring(i,j)==thePart) {
            var end = cookies.indexOf(";",j);
            if (end == -1){end = cookies.length;}
            return unescape(cookies.substring(j,end));
        }else{
        	i = cookies.indexOf(" ",i)+1;
        	if (i==0) {break;}
        }
    }
    return null;
}

/*复选框(全选|返选) thisObj为父(全选)的checkbox对象name，sunCbName为子checkbox对象name*/
function checkAll(thisObj,sunCbName){
	var cbs=document.getElementsByName(sunCbName);
	for(var i=0;i<cbs.length;i++){cbs[i].checked=thisObj.checked;}
}
/*复选框选中值，sunCbName复选框name，isSingle是否只能选中一个，返回对象(属性ids，values),注：操作时须判断返回值是否为null*/
function getCheckValue(sunCbName,isSingle){
	var ids='',vals='';
	var num=0,splitStr=',',objs=document.getElementsByName(sunCbName);
	for(var i=0;i<objs.length;i++){
		if(objs[i].checked){
			num++;
			if(num>1&&isSingle){alert("只能选择一个信息进行操作！");return null;}
			ids=ids+objs[i].id+splitStr;
			vals=vals+objs[i].value+splitStr;
		}
	}
	if(num==0){alert("请先选择要操作的信息！");return null;}
	ids = ids.substring(0,ids.length - 1);
	vals= vals.substring(0,vals.length - 1);
	return {'ids':ids,'values':vals};
}

/*设置复选框的值*/
function setCheckBoxesByValues(checkBoxName,values) {
	var checkBoxes = document.getElementsByName(checkBoxName);
	if(typeof(checkBoxes) != "undefined") {
		if(typeof(checkBoxes.length) != "undefined"){
			for(var i=0;i<checkBoxes.length;i++) {
				if(values.indexOf(checkBoxes[i].value)!=-1)
					checkBoxes[i].checked = true;
				else
					checkBoxes[i].checked = false;
			}
		}
	}
}

/*获取id为[textId+数字]的text值,多个已逗号隔开*/
function getTextBoxValue(textId,count){
	var str="";
	for(var i=1;i<count+1;i++){
		if(typeof(document.getElementById(textId+i)) != "undefined") {
			if(document.getElementById(textId+i).value != "undefined" && document.getElementById(textId+i).value != "")
			str += ',' + document.getElementById(textId+i).value;
		}
	}
	if(str != ""){str = str.substring(1);}
	return str;
}
/*设置id为[textId+数字]的text值,多个已逗号隔开*/
function setTextBoxValue(text,values){
	var value = values.split(",");
	if(typeof(value.length) != "undefined"){
		for(var i=0;i<value.length;i++){
			if(typeof(document.getElementById(text+(i+1)))!= "undefined") {
				document.getElementById(text+(i+1)).value = value[i];
			}
		}
	}
}

/**强制重新加载当前URL*/
function reload(){var href = location.href;location.href = randomURL(href);}
/**强制重新加载指定URL*/
function reloadURL(href){location.href = randomURL(href);}
/**添加随机数到URL上*/
function randomURL(href){
	href=href.replace(/#$/g,"");
	if(href.indexOf("?") > 0){
		var reg=/(\?|&)[0-9\.]+$/;
		if(reg.test(href)){href=href.replace(reg,"$1"+Math.random());}else{href+="&"+Math.random();}
	}else {
		href += "?" + Math.random();
	}		
	return href;
}

/**图片居中,使用:<img src="" onload="Img.setMiddle(this,100,100)"/>*/
Img={
	setMiddle:function(obj,W,H){		
		var imgObj=obj,_W,_H,image= new Image();
		if(null==W||null==H){
			W=obj.style.width!=""?obj.style.width:(obj.width+"px");
			H=obj.style.height!=""?obj.style.height:(obj.height+"px");
		}else{W+="px";H+="px"}			
		W=parseInt(W.replace('px',''));
		H=parseInt(H.replace('px',''));	
		image.src = imgObj.src;
		
		if(image.width>0 && image.height>0){
			if(image.width>W||image.height>H){	
				if(image.width/image.height >= W/H){_W = W;_H = (image.height*W)/image.width;}
				else{_H = H;_W= (image.width*H)/image.height;}
			}else{_W=image.width;_H=image.height}			
		}else{_W=W;_H=H;}
		
		var mTop= (H == _H)?0:(H - _H - 2) / 2;
		var mLeft= (W==_W)?0:(W - _W ) / 2;
		imgObj.style.width=_W+'px';
		imgObj.style.height=_H+'px';
		imgObj.style.marginTop = mTop + "px";
		imgObj.style.marginLeft = mLeft + "px";	
	},
	setGbMiddle:function(imgName){
		var imgs=document.getElementsByName(imgName);
		for(var i=0;i<imgs.length;i++){this.setMiddle(imgs[i],null,null);}
	}
}



/**图片路径生成*/
function getHashValue(id){
	var step=2,_split='/';
	var _id=id.toString();
	var len=_id.length;	
	var mul = len/step;
	var mod = len%step;		
	var dir = "";
	for(var i=0;i<mul;i++){dir = dir + _id.substring(i*step, (i+1)*step)+_split;}
	return dir;
}


/*验证码*/
function loadValidateImage(imgId){document.getElementById(imgId).src = "http://www.machine-in-china.com/buildImage?" + Math.random();}

function getMember(){
	var session=getCookie("JSESSIONID");
	if(null!=session&&session.indexOf(".")!=-1){session=session.substring(0,session.indexOf("."));}
	return getCookie("es"+session);
}

/*登录信息，在页脚进行初始化*/
function LoginInfo(loginId){
	this.loginInfo=null;    /*自定义登录消息*/
	this.loginOutInfo=null; /*自定义退出消息*/	
	this.loginId=loginId;   /*登录ID*/
	
	this._loginInfo=function(){
		var info='<a href="http://www.machine-in-china.com/trade/mycenter/home"><span style="font-weight:bold;">'+this.loginId+'</span> , welcome to member center</a>&nbsp;/&nbsp;<a title="Retirada" href="http://www.machine-in-china.com/trade/mycenter/logout">Retirada</a>';
		if(this.loginInfo!=null) info=this.loginInfo;
		return info;
	}
	this.showLoginInfo=function(infoDivId){	/*显示方法*/
		if(null!=this.loginId&&""!=this.loginId){$(infoDivId).innerHTML=this._loginInfo();}
	}
}
function addOptionEvent(){
	var selectobj = document.getElementById("select");
	var optionobj = document.getElementById("option");
	var option = optionobj.getElementsByTagName("li");
	selectobj.onclick = function(){optionobj.style.display="block";}
	
	for(i=0;i<option.length;i++){
		option[i].onclick = function(){
			var optext=this.innerHTML;
			selectobj.innerHTML=optext+"<img src=\"http://www.machine-in-china.com/images/icon2.gif\" />";
			optionobj.style.display="none"
			for(var j=0;j<option.length;j++){
				if(option[j]==this){
					if(j==0) $('searchForm').action='http://www.machine-in-china.com/search/offer/default.html';
					if(j==1) $('searchForm').action='http://www.machine-in-china.com/search/company/default.html';
				}
			}
		}
		option[i].onmouseover = function(){this.style.background="#e5e9fb";}
		option[i].onmouseout = function(){this.style.background="#fff";}
	}
	optionobj.onmouseover=function(){optionobj.style.display="block"}
	optionobj.onmouseout=function(){optionobj.style.display="none"}
}
function beforeSearch(){
	var searchWord=$("searchWord").value.trim();
	var categoryId=$("categoryId").value;
	var paramStr='?1=1';
	$("searchWord").value=searchWord;
	if(searchWord==''){
		alert("Incorpore por favor la información que usted está buscando ");
		$("searchWord").focus();
	}else{
		if(categoryId!=''){
			paramStr+='&categoryId='+categoryId;
		}
		searchWord=searchWord.substring(0,30);//自动截取前30个字符		
		paramStr+='&searchWord='+encodeURI(searchWord.trim());
		paramStr=paramStr.replace('?1=1&','?');
		location.href=$('searchForm').action+paramStr;
	}
}


function addCompanyFavorite(id,type){
	var url="http://www.machine-in-china.com/trade/mycenter/favoriteoper?id="+id+"&type="+type; 
 	window.open(url,"_blank");
}




/*登录判断*/
var winFlag=false; /*改变浏览器窗口大小使用*/
function gotoBuy(){	
	var loginMember=getMember();
	if(null!=loginMember&&''!=loginMember){
		location.href="http://www.machine-in-china.com/trade/mycenter/custommadebuylist"
	}else{
		document.getElementById("buyFrame").src="http://www.machine-in-china.com/trade/mycenter/login?viewFlag=view2";
		openBuyWindow();
	}
}
function gotoBuyDetail(url){
	var loginMember=getMember();
	if(null!=loginMember&&''!=loginMember){
		location.href=url;
	}else{
		document.getElementById("buyFrame").src="http://www.machine-in-china.com/trade/mycenter/login?viewFlag=view2";
		openBuyWindow();
	}
}
function openBuyWindow(){	
	var win = $("styleChoice_001");
	var winBg = $("styleChoiceBG_001");
	winFlag=true;
	win.style.display='block';
	winBg.style.display='block';
	var width=document.body.clientWidth;
	var height=document.body.clientHeight;
	var scrollWidth=document.body.scrollWidth;
	var windowHeight=window.screen.height;
	width=width>=scrollWidth?width:scrollWidth;
	height=height>windowHeight?height:windowHeight;
	winBg.style.width=width+'px';
	winBg.style.height=height+'px';
	win.style.left=(width-500)/2+'px';
	win.style.top='300'+'px';
	window.onresize = function (){if(winFlag){openBuyWindow();}}
}
function closeBuyWindow(){
	winFlag=false;
	var win = $("styleChoice_001");
	var winBg = $("styleChoiceBG_001");
	win.style.display='none';
	winBg.style.display='none';
	window.onresize = function (){}
}


/********* js validator method *****************/
function fill_error(objId,mes,flag){
	$(objId+'_error').innerHTML = mes;
	if(typeof(flag)!='undefined'){if(flag){$(objId+'_error').style.display="";}else{$(objId+'_error').style.display="none"}}
}
/*validator empty*/
function ckTextEmpty(objId,failMes,picFlag){
	var sucMes='',showFlag=false,objVal=$(objId).value.trim();
	if(null!=picFlag&&picFlag){showFlag=true;sucMes='<img src="../images/check_ok.gif"/>'}
	if(''==objVal){fill_error(objId,failMes,true);return false;}else{fill_error(objId,sucMes,showFlag);return true;}
}
/*validator min length*/
function ckTextMin(objId,failMes,num,picFlag){
	var sucMes='',showFlag=false,objVal=$(objId).value;
	if(null!=picFlag&&picFlag){showFlag=true;sucMes='<img src="../images/check_ok.gif"/>'}
	if(objVal.length<num){fill_error(objId,failMes,true);return false;}else{fill_error(objId,sucMes,showFlag);return true;}
}
/*validator max length*/
function ckTextMax(objId,failMes,num,picFlag){
	var sucMes='',showFlag=false,objVal=$(objId).value;
	if(null!=picFlag&&picFlag){showFlag=true;sucMes='<img src="../images/check_ok.gif"/>'}
	if(objVal.length > num){fill_error(objId,failMes,true);return false;}else{fill_error(objId,sucMes,showFlag);return true;}
}
/*validator min length and max length*/
function ckTextMinMax(objId,failMes,minNum,maxNum,picFlag){
	var sucMes='',showFlag=false,objVal=$(objId).value;
	if(null!=picFlag&&picFlag){showFlag=true;sucMes='<img src="../images/check_ok.gif"/>';}
	if(objVal.length<minNum||objVal.length>maxNum){fill_error(objId,failMes,true);return false;}else{fill_error(objId,sucMes,showFlag);return true;}
}
/*validator email*/
function ckTextEmail(objId,failMes,picFlag){
	var sucMes='',showFlag=false,objVal=$(objId).value;
	if(null!=picFlag&&picFlag){showFlag=true;sucMes='<img src="../images/check_ok.gif"/>'}
	var _exp = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+\.(.[a-zA-Z0-9_-])+/;
	if(!_exp.test(objVal)){fill_error(objId,failMes,true);return false;}else{fill_error(objId,sucMes,showFlag);return true;}
}
/*validator chinese*/
function ckTextChinese(objId,failMes,picFlag){
	var sucMes='',showFlag=false,objVal=$(objId).value,reg=/[^\x00-\xff]/g;
	if(null!=picFlag&&picFlag){showFlag=true;sucMes='<img src="../images/check_ok.gif"/>'}
	if(reg.test(objVal)){fill_error(objId,failMes,true);return false;}else{fill_error(objId,sucMes,showFlag);return true;}
}
/*validator min number*/
function ckTextMinNumber(objId,failMes,picFlag){
	var sucMes='',showFlag=false,objVal=$(objId).value;
	if(null!=picFlag&&picFlag){showFlag=true;sucMes='<img src="../images/check_ok.gif"/>'}
	if(objVal <= num){fill_error(objId,failMes,true);return false;}else{fill_error(objId,sucMes,showFlag);return true;}
}
/*validator width  regex */
function ckTextFormat(objId,regex,failMes,picFlag) {
	var sucMes='',showFlag=false,objVal=$(objId).value;
	if(null!=picFlag&&picFlag){showFlag=true;sucMes='<img src="../images/check_ok.gif"/>'}
	if(!regex.test($(objId).value)){fill_error(objId,failMes,true);return false;}else{fill_error(objId,sucMes,showFlag);return true;}
}


