var image, cropper, cropInfo;

function getImage(el) {
	cropInfo = eval(jq("#scale-selection").val());
	
	var ratio = cropInfo.crop.scaleDims[0] + ':' + cropInfo.crop.scaleDims[1];
	
	image = jQuery('#image');
	
	if(image.height() == 400) {
		var sf = cropInfo.crop.originalDims[1] / 400 
	}
	else if (image.width() == 400) {
		var sf = cropInfo.crop.originalDims[0] / 400
	}
	
	minHeight = Math.round(cropInfo.crop.scaleDims[1] / sf)
	minWidth = Math.round(cropInfo.crop.scaleDims[0] / sf)
	
	if((image.height() < minHeight) || (image.width() < minWidth)) {
		jq(el).html("This scale is too large for the chosen image");
		jq("#scales li:first").click();
	}
	else {
		setupCropper(cropInfo, ratio, sf);
	}
}

function selectEnd(img, selection) {
	jQuery("#x1").val(selection.x1);
	jQuery("#y1").val(selection.y1);
	
	jq("#x2").val(selection.x2);
	jQuery("#y2").val(selection.y2);
	
	jQuery("#scale-name").val(cropInfo.crop.scaleName);
}

function setupCropper(cropInfo, ratio, scaleFactor) {
	jQuery('#image').imgAreaSelect(
		{ 
			selectionColor: 'white',
			borderWidth: 1,
			aspectRatio: ratio,
			x1: cropInfo.crop.prevCrop.x1,
			y1: cropInfo.crop.prevCrop.y1,
			x2: cropInfo.crop.prevCrop.x2,
			y2: cropInfo.crop.prevCrop.y2,
			onSelectEnd: selectEnd,
			minWidth: Math.round(cropInfo.crop.scaleDims[0] / scaleFactor),
			minHeight: Math.round(cropInfo.crop.scaleDims[0] / scaleFactor)
		}
	);
}

function setValue(data, element) {
	jQuery("#scale-selection").val(data);
	jQuery('li.scale').removeClass("chosen");
	jQuery(element).addClass("chosen");
	jQuery("#crop-description").addClass("hiddenStructure")
	
	getImage(element); 
}

function loadFunction() {
	// getImage();
}