/************************************
 file: utils.js
 Some javascript routine function
 Created by Chen Yonghong
 2001-09-21
 function list
*************************************/

/*
trim(str) - return string stripped space at start and end
checkFloat(number) - number is a string
checkPositiveFloat(number) 
checkInteger(number) 
hasSpecialChar(source, str) - check special char
isCapital(str) - is capital
checkMoney(value) - check money 16,6 if valid return true
checkMoneyN(value) - check money 16,6 if valid return true   allow negative
checkPositiveInteger(number) 
checkCode(code) - if special char contained except alpha and digits, return false
checkIdentityNo(identity) - check chinese format identity no.
compareDate(sFrom,sTo) - if(sFrom<=sTo) return true, sFrom and sTo must in yyyy-mm-dd
checkDate(sDate) - sDate must be yyyy-mm-dd format, return false if invalid.
checkDay(year,month,day) - 
addItem(objSrcList,objTgtList) - add an item from source list to target list
removeItem(objTgtList) - remove current item from a list, do nothing if no item selected
getValue(objList) - get value of current item from a list.
changeDateOption(objThis,objm,objd,objy) - handling date select list value
checkRange(x,min,max) - if  min <= x <= max return true
*/
function trim(string1)// strip space at start and end
{
	var s1=string1
	var i=0,j=s1.length
	while(s1.substring(i,i+1)==" "){i++}
	while(s1.substring(j-1,j)==" "){j--}
	if(i<j)	s1=s1.substring(i,j)
	else s1=""
	return s1
}

// These function will check number format, 
// note it will exclude numbers in special format ,
// for example: 4.5E6
function checkFloat(float1) 
{
	regExp1  = /[^-?\d\.]/
	regExp2 = /^-?\.\d*$/
	regExp3 = /^-?\d*\.$/
	if(isNaN(float1) ||
	    regExp1.exec(float1) ||
	    regExp2.exec(float1) ||
	    regExp3.exec(float1))
		return false
	return true
	
}


function checkPositiveFloat(pfloat1) 
{
    pfloat1 +=""
 	return checkFloat(pfloat1) && pfloat1.indexOf('-')==-1
}

function checkInteger(int1) 
{
    int1 += ""
	return checkFloat(int1+"") && Math.floor(int1)==int1 && int1.indexOf(".")==-1
}

function checkPositiveInteger(pint1)
{
    pint1 += ""
    return checkInteger(pint1) && pint1.indexOf('-')==-1
}

function checkEmail(email)
{
	//regExp=/^((\w)+\.?)?(\w)+\@((\w)+\.)+(\w)+$/
	//RegExp=/^((\w)+-+\.?)?(\w)+\@((\w)+\.)+(\w)+$/
	RegExp=/^((\w)+[-|_|\.])?(\w)+\@((\w)+\.)+(\w)+$/
	if(RegExp.exec(email))
		return true
	return false
}

// special char not allowed except alphabetics and digits
function checkCode(code)
{
    if(trim(code)=="") return true
	regExp=/^[\w_]+$/
	if(regExp.exec(code))
		return true
	return false
	
}

// check special char
function hasSpecialChar(source)
{
    var str = "<\""
    for(i=0;i<str.length;i++)
    {
        if(source.indexOf(str.charAt(i))>-1)
        {
            return true
        }
    }
    return false
}

function isCapital(str)
{
    regExp = /[a-z]+/
    return !regExp.exec(str)
}

function isUsernameValidate(str)
{
    regExp = /[a-z]+[A-Z]+[0-9]/
    return !regExp.exec(str)
}

function getCheckedNum(objCheck)
{
    var	num = 0;
    if (typeof objCheck =="undefined") return 0
    if(typeof objCheck[0]=="undefined")
    {
        if(objCheck.checked) num++;
    }else{
        for (i=0;i<objCheck.length;i++) {
            if(objCheck[i].checked) num++;
        }
    }
    return num;
}

// Check Chinese identity card no.
function checkIdentityNo(identity)
{
	var id = identity
	if(id=="") return true
	var passed = false
	regExp1=/^\d{15}$/
	regExp2=/^\d{17}\w{1}$/
	if(regExp1.exec(id))
		passed = true
	if(!passed &&  regExp2.exec(id))
		passed = true
	return passed
}

function compareDate(Date1,Date2){
	// date formated as yyyy-mm-dd; date1 is expectd earlier than date2
	// tDate -- to date formated as yyyy-mm-dd
	if(Date1==''||Date2=='') return true
	var aFDate=Date1.split("-")
	var aTDate=Date2.split("-")

	var fY=aFDate[0]
	var fM=aFDate[1]-1
	var fD=aFDate[2]   

	var tY=aTDate[0]
	var tM=aTDate[1]-1
	var tD=aTDate[2]

	var FDate = new Date(fY,fM,fD)   
	var TDate = new Date(tY,tM,tD)

	return FDate<=TDate
}

function getValue(obj){//get selected value
	// obj -- list object
	return obj.options[obj.selectedIndex].value
}

function getText(obj){//get selected text
	// obj -- list object
	return obj[obj.selectedIndex].text
}

function addItem(objSrcList,objTgtList)
{
    
	if (objSrcList.selectedIndex<0)
		return
	var sourceID   = getValue(objSrcList)
	var sourceDesc = getText(objSrcList)
	if (typeof sourceID=="undefined" || sourceID=="") {
		return false
    }
    
	var i = objTgtList.length;
	var bExist=false;
	for (var j=0;j<i;j++)
		if (objTgtList.options[j].value==sourceID)
			bExist=true // item focus in source list existed in target list
	if (!bExist)
		objTgtList.options[i] = new Option(sourceDesc, sourceID);

	return
}
 
function removeItem(objTgtList){
	var i=objTgtList.selectedIndex 
	if (i>=0)
		objTgtList.options[i] = null;
}


function checkDate(sDate)
{
    //Returns true if value is a date format or is NULL
    //otherwise returns false	
    if (sDate == '') return true
    if (sDate.length!=10) return false
	var aDate=sDate.split("-")
    if(aDate.length>3) return false
	var sYear=aDate[0]
	var sMonth=aDate[1]
	var sDay=aDate[2]   
	

	if (!checkPositiveInteger(sMonth)) //check month
		return false
	else
	if (!checkRange(sMonth, 1, 12)) //check month
		return false
	else
	if (!checkPositiveInteger(sYear)) //check year
		return false
	else
	if (!checkRange(sYear, 1000, 9999)) //check year
		return false
	else
	if (!checkPositiveInteger(sDay)) //check day
		return false
	else
	if (!checkDay(sYear, sMonth, sDay)) // check day
		return false
	else
		return true
 }


function checkDay(checkYear, checkMonth, checkDay)
{
	maxDay = 31;
	if (checkMonth == 4 || checkMonth == 6 || checkMonth == 9 || checkMonth == 11)
		maxDay = 30;
	else
    	if (checkMonth == 2)
    	{
    		if (checkYear % 4 > 0)
    			maxDay =28;
    		else
        		if (checkYear % 100 == 0 && checkYear % 400 > 0)
        			maxDay = 28;
        		else
        			maxDay = 29;
    	}
	return checkRange(checkDay, 1, maxDay); //check day
}




function numberRange(number, min_value, max_value)
{
    if (min_value != null)
	{
        if (number < min_value)
		return false
	}
    if (max_value != null)
	{
	if (number > max_value)
		return false
	}
    return true
}

function checkRange(number, min_value, max_value)
{
    //if value is in range then return true else return false
    if (number.length == 0)
        return false
    if (!checkFloat(number))
	    return false
    else
	    return numberRange(number, min_value, max_value)
    return true
}

// handle month, day, year drop down list
// validate date value when one drop list changed
// Modified by Richard Chen 2000-02-15
function changeDateOption(objThis,objm,objd,objy)
{
	// objm -- form list, Month
	// objd -- form list, Day
	// objy -- form list, Year    
	var haveEmpty=(objThis.options[0].value=='')
   
	//clear all fields if user set a field to blank intentionally
	if (getValue(objThis)==''){
   		objm.selectedIndex=0
   		objd.selectedIndex=0
   		objy.selectedIndex=0
		return
	}
	var m=getValue(objm)
	var d=getValue(objd)
	var y=getValue(objy)
	var today= new Date()	    
	if (m=='')
		m=1
	if (y=='')
		y=today.getFullYear()
	if (d=='') 
		d=1
	objd.length=28
	var validDay=parseInt(objd.options[objd.length-1].value)+1
	for (n=validDay; n<=31;n++){
		if (checkDay(y,m,n))
			objd.options[objd.length]=new Option(n,n)
	}


	if (!checkDay(y,m,d)){
		objd.selectedIndex=objd.length-1
	}
	else   
		for (n=0; n<objd.length;n++)
			if (d==objd.options[n].value)
				objd.selectedIndex=n

	for (n=0; n<objm.length;n++)
		if (m==objm.options[n].value)
			objm.selectedIndex=n

	for (n=0; n<objy.length;n++)
		if (y==objy.options[n].value)
			objy.selectedIndex=n
}

function checkMoney(number)
{
    if(isNaN(number)) return false
    if(number<0) return false
    return checkMoneyN(Math.abs(number))
}

function checkMoneyN(number) // check money 16,2
{
 regExp = /^\-?\d{1,16}\.?\d{0,2}$/
 if(regExp.exec(number) && number <10000000000)
     return checkFloat(number)
 return false
}

//检查回复留言是否合法！
function checkwriteback(str) //add leo
{
     var str1 = trim(str);
     if(str1.length < 1)
     {
        return false;
     }
     if( str1.length >= 3
        && str1.charAt(str1.length-3) == 'R' 
        && str1.charAt(str1.length-2) == 'e'
        && str1.charAt(str1.length-1) == ':')
     {
        return false;
     }
     return true;
}

function resizeImg(){
    var aArg = resizeImg.arguments;  
    var nArg = aArg.length;
    if (nArg == 0){ return; }
    
    var objImage = aArg[0];
    var objTmpImage = getImageObject(objImage.src);
    var nOldWidth = objTmpImage.width;
    var nOldHeight = objTmpImage.height;
    if(nOldWidth == 0 || nOldHeight == 0){ return; }

    if(nArg > 1){
        nNewWidth = parseInt(aArg[1]);
    }else{
        nNewWidth = objImage.width;
    }
    if(nArg > 2){
        nNewHeight = parseInt(aArg[2]);
    }else{
        nNewHeight = objImage.height;
    }
    var nTmpWidth = nOldWidth * nNewHeight / nOldHeight;
    var nTmpHeight = nOldHeight * nNewWidth / nOldWidth;

    if(nNewWidth == 0){
        nNewWidth = nTmpWidth;
    }
    if(nNewHeight == 0){
        nNewHeight = nTmpHeight;
    }
    if(nOldWidth > nNewWidth){
        if(nOldHeight > nNewHeight){
            if ((nOldWidth / nOldHeight) > (nNewWidth / nNewHeight)){
                nNewHeight = nTmpHeight;
            }else{
                nNewWidth = nTmpWidth;
            }
        }else{
            nNewHeight = nTmpHeight;
        }
    }else{
        if(nOldHeight > nNewHeight){
            nNewWidth = nTmpWidth;
        }else{
            if(nArg >3){
                var enlarge = aArg[3];
            }else{
                var enlarge = false;
            }
            if(enlarge){
                if((nOldWidth / nOldHeight) > (nNewWidth / nNewHeight)){
                    nNewHeight = nTmpHeight;
                }else{
                    nNewWidth = nTmpWidth;
                }
            }else{
                nNewWidth = nOldWidth;
                nNewHeight = nOldHeight;
            }
        }
    }
    objImage.width = Math.round(nNewWidth);
    objImage.height = Math.round(nNewHeight);
}

/*
function resizeImg(sControlName, nWidth, nHeight, bLessThanResize) {
    var objImage = sControlName;
    var objTmpImage = getImageObject(objImage.src);
    var nOldWidth = objTmpImage.width;
    var nOldHeight = objTmpImage.height;
    if(nOldWidth == 0 || nOldHeight == 0){ return; }

    nNewWidth = parseInt(nWidth);
    nNewHeight = parseInt(nHeight);
    
    var nTmpWidth = nOldWidth * nNewHeight / nOldHeight;
    var nTmpHeight = nOldHeight * nNewWidth / nOldWidth;

    if(nNewWidth == 0){
        nNewWidth = nTmpWidth;
    }
    if(nNewHeight == 0){
        nNewHeight = nTmpHeight;
    }
    if(nOldWidth > nNewWidth){
        if(nOldHeight > nNewHeight){
            if ((nOldWidth / nOldHeight) > (nNewWidth / nNewHeight)){
                nNewHeight = nTmpHeight;
            }else{
                nNewWidth = nTmpWidth;
            }
        }else{
            nNewHeight = nTmpHeight;
        }
    }else{
        if(nOldHeight > nNewHeight){
            nNewWidth = nTmpWidth;
        }else{
            if((nOldWidth / nOldHeight) > (nNewWidth / nNewHeight)){
                nNewHeight = nTmpHeight;
            }else{
                nNewWidth = nTmpWidth;
            }
        }
    }
    objImage.width = Math.round(nNewWidth);
    objImage.height = Math.round(nNewHeight);
}
*/

function getImageObject(url){
	var objimg = new Image();
	objimg.src = url;
	return objimg;
}

function resizeImg(sControlName, nWidth, nHeight, bLessThanResize) {
        var nNewWidth
        var nNewHeight

        //高度和宽度均未指定，则不做处理
		if (('undefined' == typeof(nWidth) && 'undefined' == typeof(nHeight))) {
			return;
        }
		
		//判断 sControlName 是对象还是字符串
		if("string"==typeof(sControlName)){
			imgResize = document.getElementById(sControlName);
		}else if("object"==typeof(sControlName)){
			imgResize = sControlName;
		}
		//未取到对象则退出
		if ('undefined' == typeof(imgResize)) {
			return;
        }
        
        //缺省在原图小于指定宽度时不做处理
		if ('undefined' == typeof(bLessThanResize)) {
			bLessThanResize = false;
        }
        

        //取原始宽度和高度
        nOldWidth = imgResize.width;
        nOldHeight = imgResize.height;
        if (0 == nOldWidth || 0 == nOldHeight) {
            return;
        }
		if(nWidth == "" || nWidth == 0 || nHeight == "" || nHeight == 0){
			 nNewWidth = nWidth;
			nNewHeight = nHeight;
			if ('undefined' == typeof(nHeight) || 0 == nHeight) {
				//未指定高度
				if (!bLessThanResize && nOldWidth < nNewWidth) {
					//如果现有图像宽度小于当前图像宽度，且未指定该种情形下强制转换，则不做处理直接退出
					return;
				}
				//如果未指定高度，则按给定的宽度和原有尺寸的比例计算新高度的值
				nNewHeight = nOldHeight * (nWidth / nOldWidth);
			} else if ('undefined' == typeof(nWidth) || 0 == nWidth) {
				//未指定宽度
				if (!bLessThanResize && nOldHeight < nNewHeight) {
					//如果现有图像高度小于当前图像高度，且未指定该种情形下强制转换，则不做处理直接退出
					return;
				}
				//如果未指定宽度，则按给定的高度和原有尺寸的比例计算新宽度的值
				nNewWidth = nOldWidth * (nHeight / nOldHeight);
			}
		}else{
			nNewWidth = 0;
			nNewHeight = 0;
			//原图宽高 比例
			oldRatio = nOldWidth/nOldHeight;
			//用户指定 宽高比例
			newRatio = nWidth/nHeight;
			
			if(oldRatio < newRatio){
			// 以原图 高度 为基础 进行 压缩
				if(!bLessThanResize && nOldHeight <= nHeight){
					// 原图高度小于指定高度，且当前 不指定 强行放大
					nNewHeight = nOldHeight;
					nNewWidth = nNewHeight * oldRatio;
				}else{
					nNewHeight = nHeight;
					nNewWidth = nNewHeight * oldRatio;
				}
			}else{
			// 以原图 宽度 为基础 进行 压缩
				if(!bLessThanResize && nOldWidth <= nWidth){
					// 原图高度小于指定宽度，且当前 不指定 强行放大
					nNewWidth = nOldWidth;
					nNewHeight = nNewWidth / oldRatio;
				}else{
					nNewWidth = nWidth;
					nNewHeight = nNewWidth / oldRatio;
				}
			}
        }
        
        imgResize.width = Math.round(nNewWidth);
        imgResize.height = Math.round(nNewHeight);
    }