﻿var DefaultWidth = 10.4;
var PrevWidth = -1;
var PrevHeight = -1;
var OrigProportion;

var PriceBySquareInch;

var IsContentLoaded = false;
var InitComplete = false;

function BodyInit()
{
    IsContentLoaded = true;
    if (!InitComplete) init();
}

function init()
{
    if (!IsContentLoaded ) return;
    InitComplete = true;
    
    var image=document.getElementById('imgDecal');
    OrigProportion = image.height/image.width;
    
    if (document.getElementById('tbWidth').value==-1)
    {
        var Width = DefaultWidth;
        document.getElementById('tbWidth').value = Width;
    }
    
    PriceBySquareInch = document.getElementById('hiddenPriceBySquareInch').value;
    DimChange('width');
}

function ResizeImage(height, width)
{
    var image = document.getElementById('imgDecal');
    var Height = height/width*image.width;
    var OrigWidth = image.width;
    image.height = Height;
    image.width = OrigWidth;
}

function DimChange(sender)
{
    var Width = document.getElementById('tbWidth').value;
    var Height = document.getElementById('tbHeight').value;
    
    //Validate 
    if (isNaN(Width)||isNaN(Height))
    {
        alert('Not a number!');
        document.getElementById('tbWidth').value = PrevWidth;
        document.getElementById('tbHeight').value = PrevHeight;
        return;
    }
    
    //Saving proportions
    if (document.getElementById('cbMaintainProportions').checked)
    {
        if (sender=='width') 
            Height = Math.round(100*Width*OrigProportion)/100;
        else if (sender='height')
            Width = Math.round(100*Height/OrigProportion)/100;
    }
    ResizeImage(Height,Width);
    //Save dimensions
    PrevWidth = Width;
    PrevHeight = Height;
    
    document.getElementById('tbWidth').value = Width;
    document.getElementById('tbHeight').value = Height;
    
    document.getElementById('labelWidth').innerHTML = Width + '"';
    document.getElementById('labelHeight').innerHTML = Height + '"';
    
    //Price
    var Price = CalcPrice(Width,Height,PriceBySquareInch);
    document.getElementById('inputPrice').value = '$' + Math.round(Price*100)/100;
}

function CalcPrice(width, height, priceBySqInch)
{
    return width*height*priceBySqInch;
}

function MaintainCheckedChange(cb)
{
    if (cb.checked)
        DimChange('width');
}