
/* Used to scale objects to fit the control's size
 * If maintainAspectRatio is false, this will center the element.
 * @param element element to scale
 * @param agControl control to size the contents to
 * @param maintainAspectRatio false to stretch to fit, true to keep ratio.
 */
function scaleElement(element, agControl, maintainAspectRatio)
{
    var width = agControl.clientWidth;
    var height = agControl.clientHeight;
    
    var naturalWidth = element.width;
    var naturalHeight = element.height;
    
    var scaleRatio = naturalWidth / naturalHeight;
    var offsetX = 0;
    var offsetY = 0;
    
    if (maintainAspectRatio) {
        if (width / scaleRatio > height) {
            offsetX = (width - height * scaleRatio) / 2;
            width = height * scaleRatio;
        }
        else {
            offsetY = (height - width / scaleRatio) / 2;
            height = width / scaleRatio;
        }
    }
    
    var scaleX = width / naturalWidth;
    var scaleY = height / naturalHeight;
    
    setScale(element, scaleX, scaleY, offsetX, offsetY, agControl);
}

function setScale(element, x, y, offsetX, offsetY, agControl) {
    var renderTransform = "<TransformGroup>"
    renderTransform += "<ScaleTransform ScaleX='" + x + "' ScaleY='" + y + "'/>";
    renderTransform += "<TranslateTransform X='" + offsetX + "' Y='" + offsetY + "'/>";
    renderTransform += "</TransformGroup>";
    
    var transform = agControl.content.createFromXaml(renderTransform);
    element.renderTransform = transform;
}

    // called whenever the window resizes. 
    // Scales the WPF/E content to fit.
    function updateScale() {
        //alert("resize");
        var agControl = document.getElementById("agControl1");
        scaleElement(agControl.content.findName("ControlSurface"), agControl, true);
        scaleElement(agControl.content.findName("Background"), agControl, false);
        var intro = agControl.content.findName("IntroGraphics");
        var introBkg = agControl.content.findName("IntroBkg");
        if (intro != null && introBkg != null) {
            scaleElement(intro, agControl, true);
            scaleElement(introBkg, agControl, false);
        }
    }