/***********************************************************
 * Document Type: JavaScript
 * Update: 2006/11/10
 * Author: Akon
 * Remark: JavaScript Common Libray
 ***********************************************************/
function getStrLength(aStr)	{
	nLen=aStr.length;
	outlen=nLen;
	for(var i=0;i<nLen;i++){
		if(aStr.charCodeAt(i)>127){
			outlen++;
		}
	}
	return outlen;
}
// --- Show Element
function Show(obj) {var o=$(obj);o.style.display = '';}

// --- Hidden Element
function Hidden(obj) {var o=$(obj);o.style.display = 'none';}

// --- Get URL Param
function GetUrlParam( paramName )
{
    var oRegex = new RegExp( '[\?&]' + paramName + '=([^&]+)', 'i' ) ;
    var oMatch = oRegex.exec( window.location.search ) ;
    if ( oMatch && oMatch.length > 1 )
        return oMatch[1] ;
    else
        return '' ;
}

// --- Select All Checkbox
/*function CheckAll(eName){
    var checks = document.getElementsByName(eName);
    var chkAll = document.getElementsByName("chkAll")
    if (chkAll.checked)
        chkAll.checked=false;
    else
        chkAll.checked=true;
    for (var i=0;i<checks.length;i++){
        checks[i].checked=chkAll.checked;
    }
}
*/
function CheckAll(va,form){
	for (var i=0;i<form.elements.length;i++){
		var e = form.elements[i];
		if(va=='all'){
			e.checked = true;
		}else{
			e.checked == true ? e.checked = false : e.checked = true;
		}
	}
}






// --- Return checkbox selected values "," separation can be used in batch operation
function getOperaValue(eName) {
    var checks = document.getElementsByName(eName);
    var res = "";
    for (var i=0;i<checks.length;i++) {
        if (checks[i].checked) {
            if (!isNaN(checks[i].value)) {
                if (!res=="") res += ",";
                res += checks[i].value;
            }
        }
    }
    return res;
}


function getAllOperaValue(eName) {
    var checks = document.getElementsByName(eName);
    var res = "";
    for (var i=0;i<checks.length;i++) {       
            if (!isNaN(checks[i].value)) {
                if (!res=="") res += ",";
                res += checks[i].value;
            }
        }
  return res;
}
// --- Batch delete operation
function batchDel(url,val) {
    if (val=="") {
        alert("请选择您要删除的记录!");
        return;
    }
    if (confirm('一旦删除将无法恢复，确认删除吗？')) self.location.href = url + val;
}

// --- Dynamic change forms ClassName
function ChangeTrClassName(ClassName,tr1,tr2) {
    if (!ClassName || !tr1 || !tr2) {return}
    var list = document.getElementsByClassName(ClassName);
    if (!list) {return}
    for (var i=0;i<list.length;i++) {
        var list_tr = list[i].getElementsByTagName("tr");
        for (var j=0;j<list_tr.length;j++){
            if (list_tr[j].className != "blank" && list_tr[j].className != "title") {
                (j%2==0)?(list_tr[j].className = tr1):(list_tr[j].className = tr2);
            }
        }
    }
}

// --- Dynamic change the background color forms
function ChangeTrColor(ClassName,tr1,tr2) {
    if (!ClassName) {return}
    var list = document.getElementsByClassName(ClassName);
    if (!list) {return}
    for (var i=0;i<list.length;i++) {
        var list_tr = list[i].getElementsByTagName("tr");
        for (var j=0;j<list_tr.length;j++){
            if (list_tr[j].className != "blank" && list_tr[j].className != "title") {
                list_tr[j].style.cursor = "default";
                list_tr[j].onmouseover = function() {this.className=tr1;};
                list_tr[j].onmouseout = function() {this.className=tr2;};
            }
        }
    }
}

// --- Automatic zooming image size by ClassName
function ReSizeImg(cName,w,h){
    var reImgs = document.getElementsByTagName("img");
    for (i=0;i<reImgs.length;i++){
        if (reImgs[i].className==cName && (reImgs[i].height>h || reImgs[i].width>w)) {
            if (reImgs[i].height==reImgs[i].width) {
                reImgs[i].height=h;reImgs[i].width=w;
            } else if (reImgs[i].height>reImgs[i].width) {
                reImgs[i].height=h;
            } else if (reImgs[i].height<reImgs[i].width){
                reImgs[i].width=w;
            }
        }
    }
}


// --- Set cookie by sName
function setCookie(sName,sValue,expireHours) {
    var cookieString = sName + "=" + escape(sValue);
    if (expireHours>0) {
         var date = new Date();
         date.setTime(date.getTime + expireHours * 3600 * 1000);
         cookieString = cookieString + "; expire=" + date.toGMTString();
    }
    document.cookie = cookieString;
}

// --- Get cookie by sName
function getCookie(sName) {
  var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++){
    var aCrumb = aCookie[i].split("=");
    if (escape(sName) == aCrumb[0])
      return unescape(aCrumb[1]);
  }
  return null;
}

// --- Delete cookie by sName
function delCookie(sName) {
  var date = new Date();
  document.cookie = sName + "= ; expires=" + date.toGMTString();
}

// --- Open upload file window
function OpenUpLoad(fName,cName,IsImage) {
    var url = "uploadfile.php?fName="+fName+"&cName="+cName+"&IsImage="+IsImage;
    window.open(url,'UploadFile','height=40,width=400,resizable=no,top=300,left=300');
}

function OpenUpLoad2(fName,cName,IsImage) {
    var url = "uploadfile.php?fName="+fName+"&cName="+cName+"&IsImage="+IsImage+"&nomkThumb=true";
    window.open(url,'UploadFile','height=40,width=400,resizable=no,top=300,left=300');
}

function isMail(mail) {
    var patrn = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
    if (!patrn.test(mail))
        return false;
    else
        return true;
}

function isBetween(value, min, max) {
    return (isNaN(value) == false  && value >= min && value <= max);
}

function isDate(value) {
    return (/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/.test(value));
}

function isEmpty(value) {
    return (/^\s*$/.test(value));
}

function isChinese(str) {
    if(escape(str).indexOf("%u")!=-1){return true;}
    return false;
}

//---Check input search
//---King add this function
//---2007-9-20
function isSearch(fm){
	if(fm.keyword.value==''){
		alert('请输入您要查询的产品名称或型号!');
		fm.searchTitle.focus();
		return false;
	}	
}

//图片出错时的默认图
function imgErr(obj,type,width,height){
	switch (type){
		case "newimg_big"://新闻默认图片
			obj.src='images/noimages_big.jpg';
			obj.width=width;
			obj.height=height;
		break;
		case "newimg_small"://新闻默认图片
			obj.src='images/noimages_small.jpg';
			obj.width=width;
			obj.height=height;
		break;
	}
}

function DrawImage(ImgID,iwidths,iheights){
    //参数(图片,允许的宽度,允许的高度)
	
	var ImgD = document.getElementById(ImgID);
    var image=new Image();
    image.src=ImgD.src;
	 if(image.width>image.height){

	 iwidth=iheights+20
	 iheight=iwidths+20
	 //ImgD.style.top="-5px"
	 //ImgD.style.left="-30px"
	 }
	 else{
	 iwidth=iwidths
	 iheight=iheights
	 //ImgD.style.top="-10px"
	 //ImgD.style.left="-10px"
	 }
	//{
    flag=true;
    if(image.width/image.height>= iwidth/iheight){
        if(image.width>iwidth){  
        ImgD.width=iwidth;
        ImgD.height=(image.height*iwidth)/image.width;
        }else{
        ImgD.width=image.width;  
        ImgD.height=image.height;
        }
        //ImgD.alt=image.width+"×"+image.height;
        }
    else{
        if(image.height>iheight){  
        ImgD.height=iheight;
        ImgD.width=(image.width*iheight)/image.height;        
        }else{
        ImgD.width=image.width;  
        ImgD.height=image.height;
        }
        //ImgD.alt=image.width+"×"+image.height;
        }
    //}
}

function setImgSize(imgID,maxWidth,maxHeight)
{
	
	var img = document.getElementById(imgID);
	if(maxWidth < 1)
	{
	    if(img.height > maxHeight)
	    {
	        img.height = maxHeight;
	    }
	    return true;
	}
	if(maxHeight < 1)
	{
	    if(img.width > maxWidth)
	    {
	        img.width = maxWidth;
	    }
	    return true;
	}
	if(img.height > maxHeight || img.width > maxWidth)
	{
	    if((img.height / maxHeight) > (img.width / maxWidth))
	    {
	        img.height = maxHeight;
	    }
	    else
	    {
	        img.width = maxWidth;
	    }
	    return true;
	}
}
function resizeImages(editor, maxW, maxH) {
	var elements = document.getElementsByTagName("img");
    for (var i=0; i < elements.length; i++) {
        if (elements[i].getAttribute("editor") == editor) {
		   elements[i].id = "fckimage_"+i;
           DrawImage(elements[i].id, maxW, maxH);
        }
    }
}

//window.onload = function(){
//	resizeImages("xiaoqing", 520, 520);
//}
//

var tgs = new Array( 'div','td','tr','p');
var szs = new Array( 'xx-small','x-small','small','medium','large','x-large','xx-large' );
var startSz = 2;
function ts( trgt,inc ) {
	if (!document.getElementById) {return;}
	var d = document,cEl = null,sz = startSz,i,j,cTags;
	sz += inc;
	if ( sz < 0 ) sz = 0;
	if ( sz > 6 ) sz = 6;
	startSz = sz;
	if ( !( cEl = d.getElementById( trgt ) ) ) cEl = d.getElementsByTagName( trgt )[ 0 ];
	cEl.style.fontSize = szs[ sz ];
	for ( i = 0 ; i < tgs.length ; i++ ) {
	cTags = cEl.getElementsByTagName( tgs[ i ] );
	for ( j = 0 ; j < cTags.length ; j++ ) cTags[ j ].style.fontSize = szs[ sz ];
	}
}


function __clear(timer){
	clearTimeout(timer);
	clearInterval(timer);
	return null;
};
function __attach_event(evt, callback) {
	if (window.addEventListener) {
		window.addEventListener(evt, callback, false);
	} else if (window.attachEvent) {
		window.attachEvent("on" + evt, callback);
	}
}
function __domReady(f) {
	if (__domReady.done) return f();
	if (__domReady.timer) {
		__domReady.ready.push(f);
	} else {
		__attach_event("load", __isDOMReady);
		__domReady.ready = [f];
		__domReady.timer = setInterval(__isDOMReady, 100);
	}
}
function __isDOMReady() {
	if (__domReady.done) return false;
	if (document && document.getElementsByTagName && document.getElementById && document.body) {
		__clear(__domReady.timer);
		__domReady.timer = null;
		for ( var i = 0; i < __domReady.ready.length; i++ ) {
			__domReady.ready[i]();
		}
		__domReady.ready = null;
		__domReady.done = true;
	}
}
__domReady(function() {
	 //
}); 

/* *
 * 添加商品到购物车 
 */
function addToCart(goodsId, parentId,flag)
{
  var goods        = new Object();
  var spec_arr     = new Array();
  var fittings_arr = new Array();
  var number       = 1;
  var formBuy      = document.forms['ECS_FORMBUY'];

  // 检查是否有商品规格 
  if (formBuy)
  {
    spec_arr = getSelectedAttributes(formBuy);

    if (formBuy.elements['number'])
    {
      number = formBuy.elements['number'].value;
    }
  }

  goods.spec     = spec_arr;
  goods.goods_id = goodsId;
  goods.number   = number;
  goods.parent   = (typeof(parentId) == "undefined") ? 0 : parseInt(parentId);
  goods.flag   = flag;

  Ajax.call('flow.php?step=add_to_cart', 'goods=' + goods.toJSONString(), addToCartResponse, 'POST', 'JSON');

}
/* *
 * 处理添加商品到购物车的反馈信息
 */
function addToCartResponse(result)
{
	
  if (result.error > 0)
  {
    // 如果需要缺货登记，跳转
    if (result.error == 2)
    {
      if (confirm(result.message))
      {
        location.href = 'user.php?act=add_booking&id=' + result.goods_id;
      }
    }
    // 没选规格，弹出属性选择框
    else if (result.error == 6)
    {
      openSpeDiv(result.message, result.goods_id);
    }
    else
    {
      alert(result.message);
    }
  }
  else
  {
    var cartInfo = document.getElementById('ECS_CARTINFO');
    var cart_url = 'flow.php?step=cart';
    if (cartInfo)
    {
      cartInfo.innerHTML = result.content;
    }

    if (result.one_step_buy == '1')
    {
      location.href = cart_url;
    }
    else
    {
      switch(result.confirm_type)
      {
        case '1' :
          if (confirm(result.message)) location.href = cart_url;
          break;
        case '2' :
          if (!confirm(result.message)) location.href = cart_url;
          break;
        case '3' :
          location.href = cart_url;
          break;
        default :
          break;
      }
    }
  }
}
function DrawImage2(ImgD,FitWidth,FitHeight){
     var image=new Image();
     image.src=ImgD.src;
     if(image.width>0 && image.height>0){
         if(image.width/image.height>= FitWidth/FitHeight){
             if(image.width>FitWidth){
                 ImgD.width=FitWidth;
                 ImgD.height=(image.height*FitWidth)/image.width;
             }else{
                 ImgD.width=image.width; 
                ImgD.height=image.height;
             }
         } else{
             if(image.height>FitHeight){
                 ImgD.height=FitHeight;
                 ImgD.width=(image.width*FitHeight)/image.height;
             }else{
                 ImgD.width=image.width; 
                ImgD.height=image.height;
             } 
        }
     }
 }
 
function isURL(str_url)
{
	var strRegex = "^((https|http|ftp|rtsp|mms)?://)" 
	+ "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@ 
	+ "(([0-9]{1,3}.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184 
	+ "|" // 允许IP和DOMAIN（域名）
	+ "([0-9a-z_!~*'()-]+.)*" // 域名- www. 
	+ "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]." // 二级域名 
	+ "[a-z]{2,6})" // first level domain- .com or .museum 
	+ "(:[0-9]{1,4})?" // 端口- :80 
	+ "((/?)|" // a slash isn't required if there is no file name 
	+ "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$"; 
	var re=new RegExp(strRegex); 
	if (re.test(str_url))
	{
		return (true); 
	}else
	{ 
		return (false); 
	}
}
