// JavaScript Document
MaxTryTime = 20;	//最大尝试次数
var LoadTimes = 5;
var strLoadFail = "<DIV>Load failure!</DIV>";
var strLoading = "<DIV>Loading...</DIV>";
var strLoadTimeOut = "<DIV>Time out...</DIV>";
var imgObj;
var isLoading = false;

//整理图片大小，返回一个数组(整理后的图片尺寸)，下标0和1分别是宽和高
function FixImagesSize(MaxWidth,MaxHeight,iObj)
{
	var MaxScale = MaxWidth/MaxHeight;
	var TrueScale,ZoomScale;
	var tmpWidth,tmpHeight;
	if (typeof(iObj) == "object"){
		if(iObj.width<MaxWidth&&iObj.height<MaxHeight)return;
		TrueScale = iObj.width/iObj.height;
		if(TrueScale>MaxScale){
			ZoomScale = MaxWidth/iObj.width;
		}
		else{
			ZoomScale = MaxHeight/iObj.height;
		}
		tmpWidth = Math.round(iObj.width*ZoomScale);
		tmpHeight = Math.round(iObj.height*ZoomScale);
		iObj.width = tmpWidth;
		iObj.height = tmpHeight;
	}
	else{
		iObj.width = 0;
		iObj.height = 0;
	}
	return;
}

//放置图片
function PutImage(ImageURL,Target,MaxWidth,MaxHeight){
	if(isLoading){
		setTimeout("PutImage('" + ImageURL + "','" + Target + "'," + MaxWidth + "," + MaxHeight + ")", 250);
	}
	else{
		/*if (typeof(imgObj) != "object")*/imgObj = new Image();
		imgObj.src = ImageURL;
		CheckLoaded(ImageURL,Target,MaxWidth,MaxHeight);
	}
}

//批量添加缩略图
function BatchPutImages(arrImg,MaxWidth,MaxHeight){
	var i;
	for(i=0;i<arrImg.length;i++){
		PutImage(arrImg[i][0],arrImg[i][1],MaxWidth,MaxHeight);
	}
}

//判断是否已经加载
function CheckLoaded(ImageURL,Target,MaxWidth,MaxHeight)
{
	isLoading = true;
	var objTarget = document.getElementById(Target);
	// 对象是否已创建
	//if(typeof(objTarget)!="object")Target = eval(Target);
  if (typeof(imgObj) == "object"){
    // 是否已取得了图像的高度和宽度
    if ((imgObj.width != 0) && (imgObj.height != 0)){
      // 根据取得的图像高度和宽度设置弹出窗口的高度与宽度，并打开该窗口
			if((imgObj.width == 28) && (imgObj.height == 30)){
				objTarget.innerHTML = strLoadFail;
			}
			else{
				FixImagesSize(MaxWidth,MaxHeight,imgObj);
				objTarget.innerHTML = "<img src=" + ImageURL + " width=" + imgObj.width + " height=" + imgObj.height + " />";
//				SetDefSize();
			}
			LoadTimes = 0;
			isLoading = false;
		}
    else{
      // 因为通过 Image 对象动态装载图片，不可能立即得到图片的宽度和高度，所以每隔250毫秒重复调用检查
			if(LoadTimes > MaxTryTime){
				objTarget.innerHTML = strLoadTimeOut;
				LoadTimes = 0;
				isLoading = false;
			}
			else{
				objTarget.innerHTML = strLoading;
				LoadTimes++;
				setTimeout("CheckLoaded('" + ImageURL + "','" + Target + "'," + MaxWidth + "," + MaxHeight + ")", 250);
			}
		}
  }
}

// 当上传图片等文件时，往下拉框中填入图片路径，可根据实际需要更改此函数
function doChange(objText, objValue, objDrop){
	if (!objDrop) return;
	var str = objText.value;
	var strV = objValue.value;
	var arr = str.split("|");
	var arrV = strV.split("|");
	if(arr.length!=arrV.length)return;
	var nIndex = objDrop.selectedIndex;
	objDrop.length=0;
	for (var i=0; i<arr.length; i++){
		objDrop.options[objDrop.length] = new Option(arrV[i], arr[i]);
	}
	objDrop.selectedIndex = (nIndex+1);
}