var firstImg=  $("#picUrl").val();

var ic;
var h;
var w=400;
var imgWidth, imgHeight;
var zoomRate;

$("<img style='visibility:hidden;position:absolute;left:0;top:0' src='"+ firstImg +"'/>").appendTo("body").load(function(){
	var $img = $(this);
	imgWidth = $img.width();
	imgHeight = $img.height();
	h = parseInt(400*imgHeight/imgWidth);
	zoomRate = w/imgWidth;
	
	$("#bgDiv").css("height",h);
	$("#viewDiv").css("height",h);
	$("#loading").hide();
	$("#container").show();
	
	ic = new ImgCropper("bgDiv", "dragDiv", firstImg, {
		Width: w, Height: h, Color: "#000",
		Resize: true,
		Scale : true,
		Right: "rRight", Left: "rLeft", Up:	"rUp", Down: "rDown",
		RightDown: "rRightDown", LeftDown: "rLeftDown", RightUp: "rRightUp", LeftUp: "rLeftUp",
		Preview: "viewDiv", viewWidth: w, viewHeight: h
	});
	
	changeRatio(defaultRatio.width,defaultRatio.height);
});



function changeRatio(ww,hh){
	ic.Ratio = ww/hh;
	if(ic.Ratio>=imgWidth/imgHeight){
		dwidth = w;
		dheight = w/ic.Ratio;
	}else{
		dheight = h;
		dwidth = h*ic.Ratio;
	}
	
	var css = {'left':parseInt((w-dwidth)/2),'top':parseInt((h-dheight)/2),'width':dwidth-2,'height':dheight-2};
	$("#dragDiv").css(css);
	console.log("drag size:"+ css.left +','+css.top+','+css.width+','+css.height);
	ic.SetPos();
	ic.Ratio = ww /hh;
	ic.Init();
	
}


$i("idColor").onclick = function(){
	if(ic.Color == "#000"){
		ic.Color = "#fff";
		this.value = "黑色背景";
	}else{
		ic.Color = "#000";
		this.value = "白色背景";
	}
	ic.Init();
}

function getRealPos(){
	var p = ic.GetPos();
	if(w != imgWidth){
		if(p.Top>0){
			p.Top = parseInt(p.Top/zoomRate);
		}
		if(p.Left>0){
			p.Left = parseInt(p.Left/zoomRate);
		}
		if(p.Width==w){
			p.Width = imgWidth;
		}else{
			p.Width = parseInt(p.Width/zoomRate);
		}
		if(p.Height==h){
			p.Height = imgHeight;
		}else{
			p.Height = parseInt(p.Height/zoomRate);
		}
	}
	return p;
}

$("#crop").click(function(){
	var pos = getRealPos();
	$("#Pic_x").val(pos.Left);
	$("#Pic_y").val(pos.Top);
	$("#Pic_w").val(pos.Width);
	$("#Pic_h").val(pos.Height);
	return true;
});

