
/* 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 wpfe control to size the contents to
 * @param maintainAspectRatio false to stretch to fit, true to keep ratio.
 */
function scaleElement(element, wpfe, maintainAspectRatio)
{
    var width = wpfe.clientWidth;
    var height = wpfe.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, wpfe);
}

function setScale(element, x, y, offsetX, offsetY, wpfe) {
    var renderTransform = "<TransformGroup>"
    renderTransform += "<ScaleTransform ScaleX='" + x + "' ScaleY='" + y + "'/>";
    renderTransform += "<TranslateTransform X='" + offsetX + "' Y='" + offsetY + "'/>";
    renderTransform += "</TransformGroup>";
    
    var transform = wpfe.createFromXaml(renderTransform);
    element.renderTransform = transform;
}

// called whenever the window resizes. 
// Scales the WPF/E content to fit.
function updateScale() {
    //alert("resize");
    var wpfe = document.getElementById("wpfeControl");
    scaleElement(wpfe.findName("ControlSurface"), wpfe, true);
    scaleElement(wpfe.findName("Background"), wpfe, false);
    var intro = wpfe.findName("IntroGraphics");
    var introBkg = wpfe.findName("IntroBkg");
    if (intro != null && introBkg != null) {
        scaleElement(intro, wpfe, true);
        scaleElement(introBkg, wpfe, false);
    }
}