var changeCount = 0;

// call this whenever the heading input is changed
function headingChange(preview, heading, delay) {
	if (delay == null) delay = 500;
	changeCount++;
	updateMaxLength(heading);
	if (delay < 1) {
		updateTagPreview(changeCount, preview, heading);
	} else {
		setTimeout("updateTagPreview("+changeCount+", '"+preview+"', '"+heading+"')", delay);
	}
}

// update the maxlength attribute of the heading input based on the width of the heading on the tag
function updateMaxLength(heading) {
	var headingValue = document.getElementById(heading).value;
	var width = dotWidth(headingValue);
	var maxLength;
	if (width <= (525-29)) {
		document.getElementById(heading).setAttribute('maxLength', 64);
	} else if (width <= 525) {
		document.getElementById(heading).setAttribute('maxLength', headingValue.length);
	} else {
		do {
			headingValue = headingValue.substr(0, headingValue.length-1);
		} while (dotWidth(headingValue.substr(0, headingValue.length-1)) > (525-29))
		document.getElementById(heading).value = headingValue;
		document.getElementById(heading).setAttribute('maxLength', headingValue.length);
	}
}

// compute the width of a heading string in printer dots
function dotWidth(headingValue) {
	var widths = new Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9,9,14,14,14,26,18,9,9,9,14,26,9,26,9,9,14,14,14,14,14,14,14,14,14,14,9,9,29,26,29,13,26,16,16,16,17,15,15,17,18,8,13,16,14,22,18,17,16,17,17,16,15,18,16,24,16,16,15,9,9,9,15,15,9,13,15,13,15,14,8,15,15,8,8,13,8,22,15,14,15,15,10,12,8,15,13,19,13,13,11,15,15,15,29,0);
	var width = 0;
	for (var i = 0; i < headingValue.length; i++) {
		var c = headingValue.charCodeAt(i);
		if (c >= 0 && c < widths.length) width += widths[c];
	}
	return width;
}

// update the tag preview
function updateTagPreview(callerChangeCount, preview, heading) {
	if (callerChangeCount == changeCount) {
		var headingValue = document.getElementById(heading).value;
		if (document.getElementById(heading).disabled) headingValue = '';
		document.getElementById(preview).src = 'http://www.intelliscanner.com/scripts/asset_tag_preview/tag.php?heading='+encodeURIComponent(headingValue);
	}
}
