﻿var displayphoto = new Image();
displayphoto.onload = onDisplayImageLoad;

var maxdimx = 300;
var maxdimy = 200;
var selectedphoto = -1;

function displayImage(obj, pth) {
	var si = obj.selectedIndex;
	var path = obj.options[si].value;
	//var pos = path.indexOf("|~|");
	//var path = path.substr(pos + 3);
	if (path.length > 0) {
		displayphoto.src = pth + "/" + path;
	}
}


function onDisplayImageLoad() {
    var pwidth = displayphoto.width;
    var pheight = displayphoto.height;

    if (pwidth <= maxdimx && pheight <= maxdimy) {
        document.preview.width = pwidth;
        document.preview.height = pheight;
    } else {
        var minwh = Math.min(maxdimx / pwidth, maxdimy / pheight);
        document.preview.width = pwidth * minwh;
        document.preview.height = pheight * minwh;
    }
    document.preview.src = displayphoto.src;
}

function setImgDimentions() {
    var images = document.getElementsByTagName('img');
  
    for (var c = 0; c < images.length; c++) {
        var img = images[c];
        if (img.id.indexOf('img_size_') != 0)
            continue;

        var arr = img.id.split('_');
        var len = arr.length;
        if (len > 3) {
            var targetHeight = parseInt(arr[len - 2]); // extracted height from id
            var targetWidth = parseInt(arr[len - 1]); // extracted width from id

            if (isNaN(targetHeight) || isNaN(targetWidth))
                continue;
        }

        var w = img.width;
        var h = img.height;
        
        if (targetHeight>= h  && targetWidth >= w)
            continue;
            
        var wRatio = targetWidth / w;
        var hRatio = targetHeight / h;

        if (wRatio > hRatio) {                       // We'll scale height
            // images' height is greater then width
            w = parseInt(w * hRatio);
            h = parseInt(h * hRatio);
        }
        else {
            // images' width is greater then height
            w = parseInt(w * wRatio);
            h = parseInt(h * wRatio);
        }

        img.width = w;
        img.height = h;
    }
}
