/* Your photo / Dit foto */

var upload_iframe_src;
var latestCrop = null;
var MIN_SIZE = 400;

var currentPicFile = '';
var currentPicID = '';
var lastReq = null;
var pathToImgDir = 'typo3conf/ext/iwshop/static/img/';
var frameWidth = new Array();
frameWidth['smal.mat.sort'] = 1.1;
frameWidth['bred.mat.sort'] = 2.5;
frameWidth['solv'] = 2.1;
frameWidth['rund.hvid'] = 1.1;

var cropUpToDate = true;

function startUploadBar(uploader) {
	g('upload_single_file_iframe').style.height = '1px';
	g('progBar').style.display = 'block';
	uploader.cancelPing = false;
	uploader.queuePing();
}

function upload_complete(uploader, imgID, imgFile, w, h) {
	uploader.stopProgressBar();
	if (min(w, h) >= MIN_SIZE) {
		$('#picture_is_bad_box').hide();
		$('#picture_is_good_box').hide();
		$('#picture_is_good_1000_box').hide();
		$('#picture_is_good_400_box').hide();
		if (min(w, h) > 1500) {
			$('#picture_is_good_box').show();
		} else if (min(w, h) >= 1000) {
			$('#picture_is_good_1000_box').show();
			$('#pic_1000_link').click();
		} else {
			$('#picture_is_good_400_box').show();
			$('#pic_400_link').click();
		}

		// $('#picture_is_good_box')
		$('#rotator').show();
		$('#btnNext').show();
		currentPicFile = imgFile;
		currentPicID = imgID;
		$('#input_userPicID').val(imgID);
		$('#input_userPicFile').val(imgFile);
		$('#input_userPicRotations').val(0);
		var wcm = Math.round(w / 1000 * 60);
		var hcm = Math.round(h / 1000 * 60);
		var maxcm = max(wcm, hcm);
		if (maxcm > 300) {
			wcm = Math.round(wcm * 300 / maxcm);
			hcm = Math.round(hcm * 300 / maxcm);
		}
		var mincm = min(wcm, hcm);
		if (mincm > 150) {
			wcm = Math.round(wcm * 150 / mincm);
			hcm = Math.round(hcm * 150 / mincm);
			maxcm = max(wcm, hcm);
			if (wcm > hcm) {
				if (wcm % 5 != 0) {
					wcm = wcm - wcm % 5;
					hcm = Math.round(hcm * wcm / maxcm);
					// maxcm == (old)wcm
					// because wcm > hcm
				}
			} else {
				if (hcm % 5 != 0) {
					hcm = hcm - hcm % 5;
					wcm = Math.round(wcm * hcm / maxcm);
					// maxcm == (old)hcm
					// because wcm <= hcm
				}
			}
		}
		$('.allowed_w').text(wcm);
		$('.allowed_h').text(hcm);

		$('#img_preview').html(
				"<img src='" + imgFile + "' alt='pic' title='' class='previewImage' id='thumb_image' />");
		// console.log("Image uploaded OK:: ID="+imgID+" :: File="+imgFile+"");
	} else {
		$('#picture_is_bad_box').show();
		$('#picture_is_good_box').hide();
		$('#picture_is_good_1000_box').hide();
		$('#picture_is_good_400_box').hide();
		$('#pic_bad_link').click();

		$('#btnNext').hide();
		$('#px_width').text(w);
		$('#px_height').text(h);
	}
	resetUploadFrame();
}

function voidUpload(uploader) {
	try {
		uploader.form().show();
		$(uploader.iframe.document).find('#progBar').hide();
	} catch (e) {
	}
}

function upload_error(uploader, msg) {
	alert(window.uploadErrorMessage || 'Upload failed!');
	resetUploadFrame();
}

function resetUploadFrame() {
	$('#progBar').hide();
	$('#upload_single_file_iframe').css('height', '40px');
	upload_iframe_src = 'typo3conf/ext/iwshop/uploader/iframe.php?dir=' + upload_dir + '&btn_name=' + btn_name ;
  $('#upload_single_file_iframe').attr('src', upload_iframe_src);
};

function clickButton(str, option) {
	if (!str) {
		str = 'Next';
	}
	btn = g('input_button');
	btn.value = str;
	if (option && g('input_frameType')) {
		g('input_frameType').value = option;
	}
	if (btn.form.onsubmit) {
		var res = btn.form.onsubmit();
		if (typeof (res) == 'undefined' || res) {
			btn.form.submit();
		}
	} else {
		btn.form.submit();
	}
}

function clickButtonCropCheck(str, option) {
	if(croppingValid()) {
		return clickButton(str, option);
	} else {
		tb_show(cropping_header, '?#TB_inline=1&width=250&height=150&inlineId=message-crop');
	}
}

function croppingValid() {
	return cropUpToDate;
}

function rotateimg() {
	rotated = g('input_userPicRotations').value * 1;
	lastReq = new AjaxRequest('typo3conf/ext/iwshop/extra/AJAX.php?rotateimg:' + currentPicID + ':'
			+ rotated + ':' + currentPicFile, 'GET', '', after_rotateimg);
	lastReq.send();
	mainImg = g('thumb_image');
	mainData = getObjectData(mainImg);
	// if(console) console.log('mainData={x:'+mainData.x+', y:'+mainData.y+',
	// w:'+mainData.w+', h:'+mainData.h+'}');
	waitImg = g('rotate_wait');
	waitData = getObjectData(waitImg);
	// if(console) console.log('waitData={x:'+waitData.x+', y:'+waitData.y+',
	// w:'+waitData.w+', h:'+waitData.h+'}');
	waitImg.style.display = 'block';
	waitImg.style.position = 'fixed';
	waitImg.style.zIndex = '1001';
	waitImg.style.top = mainData.y + (mainData.h - waitData.h) / 2 + 'px';
	waitImg.style.left = mainData.x + (mainData.w - waitData.w) / 2 + 'px';
	// if(console) console.log('Total={x:'+waitImg.style.left+',
	// y:'+waitImg.style.top+'}');
}

function after_rotateimg(XML) {
	currentPicID = getXMLvalue(XML, 'ID');
	currentPicFile = getXMLvalue(XML, 'imgFile');
	g('input_userPicID').value = currentPicID;
	g('input_userPicFile').value = currentPicFile;
	g('input_userPicRotations').value = g('input_userPicRotations').value * 1 + 1;
	g('thumb_image').src = currentPicFile;
	var tmp = $('.allowed_w:first').text();
	$('.allowed_w').text($('.allowed_h:first').text());
	$('.allowed_h').text(tmp);
	g('rotate_wait').style.display = 'none';
	// console.log("Image rotated :: ID="+currentPicID+" ::
	// File="+currentPicFile+"");
}

function imageColorite(which) {
	switch (which) {
		case 'color':
			$(g('table_original')).removeClass('shadow').addClass('glow').addClass('inuse');
			$(g('link_original')).addClass('hover').addClass('inuse');

			$(g('table_greyscale')).removeClass('inuse').removeClass('glow').addClass('shadow');
			$(g('link_greyscale')).removeClass('inuse').removeClass('hover');

			$(g('table_sepia')).removeClass('inuse').removeClass('glow').addClass('shadow');
			$(g('link_sepia')).removeClass('inuse').removeClass('hover');

			$('#thumb_image').show();
			showColorImage("thumb_image");
			$('#thumb_image').hide();
			g('input_picColorite').value = 'Original';
			break;

		case 'greyscale':
			$(g('table_greyscale')).removeClass('shadow').addClass('glow').addClass('inuse');
			$(g('link_greyscale')).addClass('hover').addClass('inuse');

			$(g('table_original')).removeClass('inuse').removeClass('glow').addClass('shadow');
			$(g('link_original')).removeClass('inuse').removeClass('hover');

			$(g('table_sepia')).removeClass('inuse').removeClass('glow').addClass('shadow');
			$(g('link_sepia')).removeClass('inuse').removeClass('hover');

			$('#thumb_image').show();
			showGreyscaleImage("thumb_image");
			$('#thumb_image').hide();
			g('input_picColorite').value = 'Greyscale';
			break;

		case 'sepia':
			$(g('table_sepia')).removeClass('shadow').addClass('glow').addClass('inuse');
			$(g('link_sepia')).addClass('hover').addClass('inuse');

			$(g('table_original')).removeClass('inuse').removeClass('glow').addClass('shadow');
			$(g('link_original')).removeClass('inuse').removeClass('hover');

			$(g('table_greyscale')).removeClass('inuse').removeClass('glow').addClass('shadow');
			$(g('link_greyscale')).removeClass('inuse').removeClass('hover');

			$('#thumb_image').show();
			showSepiaImage("thumb_image");
			$('#thumb_image').hide();
			g('input_picColorite').value = 'Sepia';
			break;

		default:
			throw new Exception("Color `" + color + "` is not a valid option");
	}
}

function hoverTable() {
	$(this).removeClass('shadow').addClass('glow');
	$(this).next().addClass('hover');
}
function hoverLink() {
	$(this).prev().removeClass('shadow').addClass('glow');
}

function unhoverTable() {
	if (!$(this).hasClass('active')) {
		$(this).removeClass('glow').addClass('shadow');
		$(this).next().removeClass('hover');
	}
}

function unhoverLink() {
	if (!$(this).hasClass('active')) {
		$(this).prev().removeClass('glow').addClass('shadow');
	}
}

function init() {
	slideImg = 'thumb_image';
	var colorite = g('input_picColorite').value;
	if (colorite == '')
		setTimeout(function() {
			imageColorite('color');
		}, 50);
	else
		setTimeout(function() {
			restoreImageColorite(colorite);
		}, 120);
	setTimeout(function() {
		jSlider.slider('moveTo', g('input_picBrightness').value);
	}, 250);
}

function resetBrightness() {
	// resetSlider(g('slider-1'));
	jSlider.slider('moveTo', 0);
}

function restoreImageColorite(color) {
	ov = g('thumb_image_fake');
	if (ov != null) {
		document.body.removeChild(ov);
		im = g('thumb_image');
		im.style.display = 'block';
		imData = getObjectData(im);
		im.style.width = imData.w + 'px';
		im.style.height = imData.h * 3 + 'px';
	}
	switch (color) {
		case 'Original':
			imageColorite('color');
			break;
		case 'Greyscale':
			imageColorite('greyscale');
			break;
		case 'Sepia':
			imageColorite('sepia');
			break;
		default:
			throw new Exception("Color `" + color + "` is not a valid option");
	}

	// if(!g('sliderImgBg')) initSlider(g('slider-1'));
	// setSliderPos(g('slider-1'), bright);
}

function chooseCropping(crop) {
	removeSelections('thumb_image');
	if (crop == 'free') {
		if (g('radio_cropping_square').checked) {
			g('radio_cropping_square').checked = false;
		}
		if (g('radio_cropping_free').checked) {
			addFreeSelect('thumb_image');
		}
	}
	if (crop == 'square') {
		if (g('radio_cropping_free').checked) {
			g('radio_cropping_free').checked = false;
		}
		if (g('radio_cropping_square').checked) {
			addSquareSelect('thumb_image');
		}
	}
	if (g('radio_cropping_free').checked || g('radio_cropping_square').checked) {
		latestCrop = getCropCoords('thumb_image');
		onCropChange(latestCrop);
	} else {
		latestCrop = null;
		resetImageSelectors();
		g('newWidth').innerHTML = g('input_width').value;
		g('newHeight').innerHTML = g('input_height').value;
	}
}

function resetCropping() {
	cropUpToDate = true;

	g('thumb_image').src = g('input_picFile').value = g('input_originalPicFile').value;
	var scale = g('input_scale').value * 1;

	var maxSize = {
	w : g('input_originalW').value * 60 / 1000,
	h : g('input_originalH').value * 60 / 1000
	};
	var validSize = validateSize(Math.round(scale * maxSize.w), Math.round(scale * maxSize.h));

	g('newWidth').innerHTML = g('input_width').value = validSize.w;
	g('newHeight').innerHTML = g('input_height').value = validSize.h;
	g('input_cropX').value = g('input_cropY').value = '0';
	g('input_cropW').value = g('input_cropH').value = '1';
	latestCrop = null;
	// setTimeout("resetImageSelectors();", 50);
	updatePrices();
}

function resetImageSelectors() {

	removeSelections('thumb_image');
	g('radio_cropping_free').checked = false;
	g('radio_cropping_square').checked = false;

	repositionDimensionArrows();
}

var doingOnceMore = false;
function repositionDimensionArrows() {

	doingOnceMore = !doingOnceMore;

	t = getObjectData(g('thumb_image'));
	hm = getObjectData(g('hMeasure'));
	hmp = getObjectData(g('hMeasure').parentNode);
	g('hMeasure').style.position = 'relative';
	g('hMeasure').style.left = t.x - hmp.x + 'px';
	g('hMeasure').style.width = t.w + 'px';

	vm = getObjectData(g('vMeasure'));
	vmp = getObjectData(g('vMeasure').parentNode);
	g('vMeasure').style.position = 'relative';
	g('vMeasure').style.top = t.y - vmp.y + 'px';
	g('vMeasure').style.height = t.h + 'px';

	if (doingOnceMore) {
		doingOnceMore = true; // this is because it gets inverted before
		// checking!
		setTimeout(repositionDimensionArrows, 500);
	}

	// if(console) console.log('Reseting image selectors :: t=', t, ' :: hm = ',
	// hm, ' :: hmp = ', hmp, ' :: vm = ', vm, ' :: vmp = ', vmp);

}

function initStep4(xpct, ypct, wpct, hpct, scale) {
	if (!scale) {
		scale = '';
	}
	w = Math.round(wpct * g('input_originalW').value);
	h = Math.round(hpct * g('input_originalH').value);
	g('input_cropW').value = wpct;
	g('input_cropH').value = hpct;
	g('input_cropX').value = xpct;
	g('input_cropY').value = ypct;
	// if(console) console.log('w='+w+' & h='+h+' & scale='+scale);
	if (w > h) {
		wcm = (scale == '') ? min(90, Math.round(w / 1000 * 60)) : Math.round(scale * w / 1000 * 60);
		scale = wcm / (w / 1000 * 60);
		hcm = Math.round(scale * h / 1000 * 60);
		g('newWidth').innerHTML = g('input_width').value = wcm; // 425;
		g('newHeight').innerHTML = g('input_height').value = hcm;
		g('input_scale').value = scale;
	} else {
		hcm = (scale == '') ? min(90, Math.round(h / 1000 * 60)) : Math.round(scale * h / 1000 * 60);
		scale = hcm / (h / 1000 * 60);
		wcm = Math.round(scale * w / 1000 * 60);
		g('newWidth').innerHTML = g('input_width').value = wcm;
		g('newHeight').innerHTML = g('input_height').value = hcm;
		g('input_scale').value = scale;
	}
	// if(console) console.log('After INIT : w='+wcm+' & h='+hcm+' &
	// scale='+scale);
	// if(console)
	// console.log('------------------------------------------------------');
	// setTimeout("resetImageSelectors();", 100);
	updatePrices();
}

function onCropChange(e) {
	cropUpToDate = false;
	t = getObjectData(g('thumb_image'));
	var i = {
	w : 0,
	h : 0
	};
	i.w = g('input_width').value;
	i.h = g('input_height').value;

	var newW = Math.round(i.w * e.w / t.w);
	var newH = Math.round(i.h * e.h / t.h);

	if (min(newW, newH) < 20) {
		var theCorner = corner;
		stopFreeSelect();
		var w = Math.round(newW < 20 ? 20 * t.w / i.w : e.w);
		var h = Math.round(newH < 20 ? 20 * t.h / i.h : e.h);
		var x = t.x + e.x;
		var y = t.y + e.y;
		if (theCorner == 'TL' || theCorner == 'L' || theCorner == 'BL' || theCorner == 'TL_X'
				|| theCorner == 'BL_X') {
			x = t.x + e.x + e.w - w;
		}
		if (theCorner == 'TL' || theCorner == 'T' || theCorner == 'TR' || theCorner == 'TL_X'
				|| theCorner == 'TR_X') {
			y = t.y + e.y + e.h - h;
		}
		setFreeSelectionTo('thumb_image', {
		x : x,
		y : y
		}, {
		x : x + w,
		y : y + h
		}, t);
		// alert(msg.smaller20); //'You cannot leave the short side smaller than
		// 20cm');
		e.w = w;
		e.h = h;
	}

	if (min(newW, newH) > 150) {
		var theCorner = corner;
		stopFreeSelect();
		var w = Math.round(newW > 150 ? 150 * t.w / i.w : e.w);
		var h = Math.round(newH > 150 ? 150 * t.h / i.h : e.h);
		var x = t.x + e.x;
		var y = t.y + e.y;
		if (theCorner == 'TL' || theCorner == 'L' || theCorner == 'BL' || theCorner == 'TL_X'
				|| theCorner == 'BL_X') {
			x = t.x + e.x + e.w - w;
		}
		if (theCorner == 'TL' || theCorner == 'T' || theCorner == 'TR' || theCorner == 'TL_X'
				|| theCorner == 'TR_X') {
			y = t.y + e.y + e.h - h;
		}
		setFreeSelectionTo('thumb_image', {
		x : x,
		y : y
		}, {
		x : x + w,
		y : y + h
		}, t);
		alert(msg.larger120);
		// alert('You cannot leave the short side larger than 120cm');
		e.w = w;
		e.h = h;
	}
	if (max(newW, newH) > 300) {
		var theCorner = corner;
		stopFreeSelect();
		var w = Math.round(newW > 300 ? 300 * t.w / i.w : e.w);
		var h = Math.round(newH > 300 ? 300 * t.h / i.h : e.h);
		var x = t.x + e.x;
		var y = t.y + e.y;
		if (theCorner == 'TL' || theCorner == 'L' || theCorner == 'BL' || theCorner == 'TL_X'
				|| theCorner == 'BL_X') {
			x = t.x + e.x + e.w - w;
		}
		if (theCorner == 'TL' || theCorner == 'T' || theCorner == 'TR' || theCorner == 'TL_X'
				|| theCorner == 'TR_X') {
			y = t.y + e.y + e.h - h;
		}
		setFreeSelectionTo('thumb_image', {
		x : x,
		y : y
		}, {
		x : x + w,
		y : y + h
		}, t);
		alert(msg.larger120);
		// alert('You cannot leave the long side larger than 300cm');
		e.w = w;
		e.h = h;
	}

	g('newWidth').innerHTML = Math.round(i.w * e.w / t.w);
	g('newHeight').innerHTML = Math.round(i.h * e.h / t.h);

	hm = getObjectData(g('hMeasure'));
	hmp = getObjectData(g('hMeasure').parentNode);
	g('hMeasure').style.position = 'relative';
	g('hMeasure').style.left = t.x + e.x - hmp.x + 'px';
	g('hMeasure').style.width = e.w + 'px';

	vm = getObjectData(g('vMeasure'));
	vmp = getObjectData(g('vMeasure').parentNode);
	// if(console) console.log('vm={x:'+vm.x+', y:'+vm.y+', w:'+vm.w+',
	// h:'+vm.h+'} && vmp={x:'+vmp.x+', y:'+vmp.y+', w:'+vmp.w+', h:'+vmp.h+'}
	// &&
	// t={x:'+t.x+', y:'+t.y+', w:'+t.w+', h:'+t.h+'} && e={x:'+e.x+',
	// y:'+e.y+',
	// w:'+e.w+', h:'+e.h+'}');
	g('vMeasure').style.position = 'relative';
	g('vMeasure').style.top = e.y + 'px';
	g('vMeasure').style.height = e.h + 'px';

	latestCrop = e;
}

function cropOnResize() {
	if (latestCrop != null) {
		d = g('thumb_image_freeselect_T');
		square = (d == null);
		removeSelections('thumb_image');
		if (square) {
			addSquareSelect('thumb_image');
		} else {
			addFreeSelect('thumb_image');
		}

		cropUpToDate = false;

		t = getObjectData(g('thumb_image'));
		// console.log('Last & current & after');
		// console.log(latestCrop);
		// console.log(getCropCoords('thumb_image'));
		setFreeSelectionTo('thumb_image', {
		x : t.x + latestCrop.x,
		y : t.y + latestCrop.y
		}, {
		x : t.x + latestCrop.x + latestCrop.w,
		y : t.y + latestCrop.y + latestCrop.h
		}, t);
		// console.log(getCropCoords('thumb_image'));
	}
}

function applyCrop() {
	if (g('thumb_image_freeselect_TL') == null) {
		return false;
	}

	var old = {
	x : g('input_cropX').value,
	y : g('input_cropY').value,
	w : g('input_cropW').value,
	h : g('input_cropH').value
	};
	var coords = getCropCoords('thumb_image');
	var img = getObjectData(g('thumb_image'));
	var c = {
	x : round(old.x * 1 + coords.x / img.w * old.w, 4),
	y : round(old.y * 1 + coords.y / img.h * old.h, 4),
	w : round((coords.w * old.w) / img.w, 4),
	h : round((old.h * coords.h) / img.h, 4)
	};
	var picID = g('input_picID').value;
	var itemID = g('input_itemID').value;
	g('input_cropX').value = c.x;
	g('input_cropY').value = c.y;
	g('input_cropW').value = c.w;
	g('input_cropH').value = c.h;
	req = new AjaxRequest('typo3conf/ext/iwshop/extra/AJAX.php?crop:' + itemID + ':' + picID + ':'
			+ c.x + ':' + c.y + ':' + c.w + ':' + c.h + ':' + g('input_picFile').value, 'GET', '',
			after_applyCrop);
	req.send();
	return true;
}

function after_applyCrop(XML) {
	g('input_picFile').value = g('thumb_image').src = getXMLvalue(XML, 'picFile');
	var scale = g('input_scale').value * 1;

	cropUpToDate = true;
	var maxSize = {
	w : Math.round(scale * g('input_originalW').value * g('input_cropW').value * 60 / 1000),
	h : Math.round(scale * g('input_originalH').value * g('input_cropH').value * 60 / 1000)
	};
	var validSize = (max(maxSize.w, maxSize.h) > 150 ? validateSize(maxSize.w, maxSize.h) : maxSize);

	g('input_width').value = g('newWidth').innerHTML = validSize.w;
	g('input_height').value = g('newHeight').innerHTML = validSize.h;
	updatePrices();
	latestCrop = null;
}

function increaseScale() {
	var w = g('input_width').value * 1;
	var h = g('input_height').value * 1;
	if (w < h) {
		recalcScaling(w, h + 5);
	} else {
		recalcScaling(w + 5, h);
	}
	updatePrices();
}

function decreaseScale() {
	var w = g('input_width').value * 1;
	var h = g('input_height').value * 1;
	if (w < h) {
		recalcScaling(w, h - 5);
	} else {
		recalcScaling(w - 5, h);
	}
	updatePrices();
}

function recalcScaling(newW, newH) {
	var w = g('input_width').value * 1;
	var h = g('input_height').value * 1;
	var scale = g('input_scale').value * 1;
	var fullW = g('input_cropW').value * g('input_originalW').value * 60 / 1000;
	var fullH = g('input_cropH').value * g('input_originalH').value * 60 / 1000;
	var nh = newH;
	var nw = newW;
	var ns;
	resetImageSelectors();
	// if(console) console.log('Initial scale='+scale);
	if (w < h) {
		ns = nh / fullH;
		nw = Math.round(ns * fullW);
		// if(console) console.log('Case w<h :: newW = '+nw+' :: newH = '+nh+'
		// ::
		// newScale = '+ns+' :: fullW='+fullW+' :: fullH='+fullH);
		if (nw > 150) {
			nw = 150;
			nh = Math.round(nw * fullH / fullW);
			// if(console) console.log('Imtermediate (w,h): ', nw, nh);
			nh = (nh % 5 == 0 ? nh : nh - nh % 5);
			ns = nh / fullH;
			nw = Math.round(ns * fullW);
			// if(console) console.log('Case w<h + ReCalc :: newW = '+nw+' ::
			// newH =
			// '+nh+' :: newScale = '+ns+' :: fullW='+fullW+' :: fullH='+fullH);
		}
		if (nw < 20) {
			nw = 20;
			nh = Math.round(nw * fullH / fullW);
			nh = (nh % 5 == 0 ? nh : (nh - nh % 5) + 5);
			ns = nh / fullH;
			nw = Math.round(ns * fullW);
			// if(console) console.log('Case w<h + ReCalc :: newW = '+nw+' ::
			// newH =
			// '+nh+' :: newScale = '+ns+' :: fullW='+fullW+' :: fullH='+fullH);
		}
		if (nh > 300) {
			nh = 300;
			ns = nh / fullH;
			nw = Math.round(ns * fullW);
			// if(console) console.log('Case w>h + ReCalc :: newW = '+nw+' ::
			// newH =
			// '+nh+' :: newScale = '+ns+' :: fullW='+fullW+' :: fullH='+fullH);
		}
	} else {
		ns = nw / fullW;
		nh = Math.round(ns * fullH);
		// if(console) console.log('Case w>h :: newW = '+nw+' :: newH = '+nh+'
		// ::
		// newScale = '+ns+' :: fullW='+fullW+' :: fullH='+fullH);
		if (nh > 150) {
			nh = 150;
			// ns = nh/fullH;
			// nw = Math.round(ns*fullW);
			nw = Math.round(nh * fullW / fullH);
			// if(console) console.log('Imtermediate (w,h): ', nw, nh);
			nw = (nw % 5 == 0 ? nw : nw - nw % 5);
			// if(console) console.log('Imtermediate2 (w,h): ', nw, nh);
			ns = nw / fullW;
			nh = Math.round(ns * fullH);
			// if(console) console.log('Post (w,h): ', nw, nh, ' :: ', fullH,
			// ns,
			// fullH*ns, Math.round(fullH*ns), ns*fullW, Math.round(ns*fullW));
			// if(console) console.log('FullW/FullH = ', fullW/fullH, ' :: nw/nh
			// = ',
			// nw/nh);
			// if(console) console.log('Case w>h + ReCalc :: newW = '+nw+' ::
			// newH =
			// '+nh+' :: newScale = '+ns+' :: fullW='+fullW+' :: fullH='+fullH);
		}
		if (nh < 20) {
			nh = 20;
			// ns = nh/fullH;
			// nw = Math.round(ns*fullW);
			nw = Math.round(nh * fullW / fullH);
			nw = (nw % 5 == 0 ? nw : nw - nw % 5 + 5);
			ns = nw / fullW;
			nh = Math.round(ns * fullH);
			// if(console) console.log('Case w>h + ReCalc :: newW = '+nw+' ::
			// newH =
			// '+nh+' :: newScale = '+ns);
		}
		if (nw > 300) {
			nw = 300;
			ns = nw / fullW;
			nh = Math.round(ns * fullH);
			// if(console) console.log('Case w<h + ReCalc :: newW = '+nw+' ::
			// newH =
			// '+nh+' :: newScale = '+ns+' :: fullW='+fullW+' :: fullH='+fullH);
		}
	}

	if (ns > 1 && min(nw, nh) > 20) {
		// if(console) console.log('scale = '+ns+' :: rescaling to 1');
		ns = 1;
		// alert('Image size does not allow larger print!');
		alert(msg.pixelLimit);
		nw = Math.round(fullW);
		nh = Math.round(fullH);
		if (nw < nh) {
			nh = (nh % 5 == 0 ? nh : nh - nh % 5);
			ns = nh / fullH;
			nw = Math.round(ns * fullW);
		} else {
			nw = (nw % 5 == 0 ? nw : nw - nw % 5);
			ns = nw / fullW;
			nh = Math.round(ns * fullH);
		}
	}
	g('input_scale').value = ns;
	g('newWidth').innerHTML = g('input_width').value = nw;
	g('newHeight').innerHTML = g('input_height').value = nh;
	// if(console) console.log('Done with increaseScale :: newW = '+nw+' :: newH
	// =
	// '+nh+' :: newScale = '+ns+' :: fullW='+fullW+' :: fullH='+fullH);
	// if(console)
	// console.log('---------------------------------------------------------------------------');
}

function framePrice(w, h, frame_type) {
	var unitprice = 0;
	if (frame_type == 'option1' || frame_type == 'option4') {
		unitprice = 75;
	}
	if (frame_type == 'option2') {
		unitprice = 78;
	}
	if (frame_type == 'option3') {
		unitprice = 175;
	}
	return Math.round(2 * (w + h) * unitprice / 100);
}

function imagePrice(w, h) {
	return Math.round(w * h * 800 / 10000 + 190);
}

function updatePrices() {
	var f = g('input_frameType').value.charAt(g('input_frameType').value.length - 1);
	var w = g('input_width').value * 1;
	var h = g('input_height').value * 1;
	// var fPrice = framePrice(w, h, frameType);
	// var iPrice = imagePrice(w, h);
	g('td_image_prod').innerHTML = products.image.split('%SIZE%').join(w + 'x' + h + ' cm');
	// g('td_image_price').innerHTML = iPrice+' DKK';
	if (f == 3)
		g('td_frame_prod').innerHTML = products.frame.split('%SIZE%').join(w + 'x' + h + ' cm');
	// g('td_frame_price').innerHTML = fPrice+' DKK';
	// g('td_total_price').innerHTML = (iPrice+fPrice)+' DKK';

	var r = new AjaxRequest('typo3conf/ext/iwshop/extra/AJAX.php?getPrice:yourphoto', 'POST', 'w='
			+ w + '&h=' + h + '&f=' + f, updatePricesLoader);
	r.send();
}

function updatePricesLoader(XML) {
	$('#td_image_price').html(getXMLvalue(XML, 'PicturePrice') + afterPriceCurrency);
	var floatPrice = getXMLvalue(XML, 'FloatFramePrice');
	if (floatPrice > 0) {
		$('#td_frame_price').html(floatPrice + afterPriceCurrency);
	}
	$('#td_total_price').html(getXMLvalue(XML, 'TotalPrice') + afterPriceCurrency);
	blinkPrices();
}

function blinkPrices() {
	g('td_image_price').style.color = 'red';
	if (g('td_frame_price')) {
		g('td_frame_price').style.color = 'red';
	}
	g('td_total_price').style.color = 'red';
	setTimeout(unblinkPrices, 500);
}

function unblinkPrices() {
	g('td_image_price').style.color = '';
	if (g('td_frame_price')) {
		g('td_frame_price').style.color = '';
	}
	g('td_total_price').style.color = '';
}

function unsetOtherChoices(o) {
	f = o.form;
	if (!o.checked) {
		o = document.createElement('input');
	}
	for ( var i = 0; i < f.elements.length; i++) {
		e = f.elements[i];
		if (e.type == 'checkbox' && e.name == o.name && e.value != o.value && e.checked) {
			e.checked = false;
		}
	}
	fixGlows(o);
	framePreview(o.value);
	updateProduct();
}

function framePreview(style) {
	var icm = {
	w : g('newWidth').innerHTML * 1,
	h : g('newHeight').innerHTML * 1
	};
	var img = getObjectData(g('thumb_image'));

	var frameW = Math.round(img.w / icm.w * frameWidth[style]);
	if (frameW < 1) {
		frameW = 1;
	}

	var pos = [ 'TL', 'T', 'TR', 'L', 'R', 'BL', 'B', 'BR' ];
	if (style == '') {
		for ( var i = 0; i < pos.length; i++) {
			g('frame' + pos[i]).style.display = 'none';
		}
	} else {
		for ( var i = 0; i < pos.length; i++) {
			o = g('frame' + pos[i]);
			o.src = pathToImgDir + 'frames/' + style + '.' + pos[i].toLowerCase() + '.jpg';
			if (pos[i] == 'T' || pos[i] == 'B') {
				o.width = img.w + 2;
				o.height = frameW;
			}
			if (pos[i] == 'L' || pos[i] == 'R') {
				o.height = img.h + 2;
				o.width = frameW;
			}
			if (pos[i].length == 2) {
				o.width = frameW;
				o.height = frameW;
			}
			o.style.display = 'block';
		}
	}
}

function fixGlows(o) {

	var elems = [ g('table.smal.mat.sort'), g('table.bred.mat.sort'), g('table.solv'), g('table.rund.hvid') ];

	for ( var i = 0; i < elems.length; i++) {
		var e = elems[i];
		if (e.id == 'table.' + o.value) {
			$(e).removeClass('shadow').addClass('glow').addClass('inuse');
		} else {
			$(e).addClass('shadow').removeClass('glow').removeClass('inuse');
		}
	}

}

function restoreFrameChoice(choice) {
	switch (choice) {
		case 'smal.mat.sort':
			g('fstyle_check1').click();
			break;
		case 'bred.mat.sort':
			g('fstyle_check2').click();
			break;
		case 'solv':
			g('fstyle_check3').click();
			break;
		case 'rund.hvid':
			g('fstyle_check4').click();
			break;
	}
}

function updateProduct() {
	var ftype = '';
	var elems = [ g('fstyle_check1'), g('fstyle_check2'), g('fstyle_check3'), g('fstyle_check4') ];
	for ( var i = 0; i < elems.length; i++) {
		var e = elems[i];
		if (e.checked) {
			switch (e.value) {
				case 'smal.mat.sort':
					ftype = ftype_trans1;
					break;
				case 'bred.mat.sort':
					ftype = ftype_trans2;
					break;
				case 'solv':
					ftype = ftype_trans3;
					break;
				case 'rund.hvid':
					ftype = ftype_trans4;
					break;
				default:
					ftype = e.value;
			}
		}
	}

	g('td_frame_prod').innerHTML = frame_prod.split('%TYPE%').join(ftype);
}

function validateSize(w, h) {
	var newW = w;
	var newH = h;

	var enlarge = true;
	var temp = 0;

	if (newW < newH) {
		if (newH > 300) {
			newW = Math.round(300 / newH * newW);
			newH = 300;
			enlarge = false;
		}
		if (newW > 150) {
			newH = Math.round(150 / newW * newH);
			newW = 150;
			enlarge = false;
		}
		if (newW < 20) {
			newH = Math.round(20 / newW * newH);
			newW = 20;
			enlarge = true;
		}

		if (newH % 5 > 0) {
			temp = newH - newH % 5 + (enlarge ? 5 : 0);
			newW = Math.round(temp / newH * newW);
			newH = temp;
		}
	} else {
		if (newW > 300) {
			newH = Math.round(300 / newW * newH);
			newW = 300;
			enlarge = false;
		}
		if (newH > 150) {
			newW = Math.round(150 / newH * newW);
			newH = 150;
			enlarge = false;
		}
		if (newH < 20) {
			newW = Math.round(20 / newH * newW);
			newH = 20;
			enlarge = true;
		}

		if (newW % 5 > 0) {
			temp = newW - newW % 5 + (enlarge ? 5 : 0);
			newH = Math.round(temp / newW * newH);
			newW = temp;
		}
	}

	return {
	w : newW,
	h : newH
	};
}

function checkFrameChoice() {
	var ok = g('fstyle_check1').checked || g('fstyle_check2').checked || g('fstyle_check3').checked
			|| g('fstyle_check4').checked;
	if (!ok) {
		alert(frameNotChosenError);
	}
	return ok;
}

