﻿var PRODUCT_FAMILY_ARRAY_ID             = 0;
var PRODUCT_FAMILY_ARRAY_CARD_ID        = 1;
var PRODUCT_FAMILY_ARRAY_SENSOR         = 2;
var PRODUCT_FAMILY_ARRAY_MAG_LOW        = 3;
var PRODUCT_FAMILY_ARRAY_MAG_HIGH       = 4;
var PRODUCT_FAMILY_ARRAY_CAMERA_FORMAT  = 5;
var PRODUCT_FAMILY_ARRAY_FEATURES		= 6;
var PRODUCT_FAMILY_ARRAY_WHY_NOT		= 7;

var LENS_FAMILY_CCTV			        = 0;
var LENS_FAMILY_ZOOM                    = 1;
var LENS_FAMILY_FIXED_MAG               = 2;
var LENS_FAMILY_LARGE_FORMAT            = 3;
var LENS_FAMILY_TELECENTRIC	            = 4;
var LENS_FAMILY_FLUORESCENCE            = 5;

    /* Run database script [FeatureListGenerator] to create the feature lists below */
var productFamilies = [
	[LENS_FAMILY_CCTV, "cctv", 16, 0.000001, 1, "|C|Z|",
	    "|feature-internalFocus|feature-aperture|feature-lowLight|", ""],
	[LENS_FAMILY_ZOOM, "zoom", 30, 0, 580, "|C|E|F|",
	    "|feature-coax|feature-externalCoax|feature-ringLight|feature-internalFocus|feature-polarization|feature-motorization|feature-dic|feature-aperture|feature-detentZoom|feature-nir|", ""],
	[LENS_FAMILY_FIXED_MAG, "fixed", 11, 0.23, 91, "|C|",
	    "|feature-coax|feature-ringLight|feature-internalFocus|feature-aperture|feature-nir|", ""],
	[LENS_FAMILY_LARGE_FORMAT, "large", 90, 0.00001, 1.67, "|C|F|T|S|M|",
	    "|feature-internalFocus|feature-aperture|" , ""],
	[LENS_FAMILY_TELECENTRIC, "telecentric", 28.7, 0.04, 5, "|C|F|",
	    "|feature-coax|feature-internalFocus|feature-motorization|feature-telecentric|feature-aperture|feature-detentZoom|", ""],
	[LENS_FAMILY_FLUORESCENCE, "fluorescence", 30, 0.35, 228, "|C|F|",
	    "|feature-coax|feature-internalFocus|feature-fluorescence|feature-detentZoom|", ""]
];

var additionalFeatures = [
	"feature-coax", "feature-externalCoax", "feature-ringLight",
	"feature-internalFocus", "feature-polarization", "feature-motorization",
	"feature-fluorescence", "feature-telecentric", 
	"feature-dic", "feature-aperture", "feature-detentZoom",
	"feature-lowLight", "feature-nir"
];

var sensorHeight = '';
var sensorWidth = '';
var cameraSensorValue = 0;
var cameraMountValue = '';
var unitOfMeasure = "mm";

// Images to preload.
var images = [
	'img/QuickStrtBtn-hvr.gif',
	'img/lens-sensor.jpg',
	'img/lens-mount.jpg',
	'img/lens-camera.jpg',
	'img/lens-lens.jpg',
	'img/lens-distance.jpg',
	'img/lens-fieldofview.jpg',
	'img/card-CCTV-hvr.gif',
	'img/card-Zoom-hvr.gif',
	'img/card-Fixed-hvr.gif',
	'img/card-LgFormat-hvr.gif',
	'img/card-Telecentric-hvr.gif',
	'img/card-Fluorescence-hvr.gif',
	'img/select_rnd-hvr.gif',
	'img/return_btn-hvr.gif',
	'img/advanced_btn-hvr.gif',
	'img/return-hvr.gif',
	'img/reset-hvr.gif',
	'img/arrow_lnk-hvr.gif',
	'img/info-CCTV-back.gif',
	'img/info-CCTV-hvr.gif',
	'img/info-Zoom-actv.gif',
	'img/info-Zoom-hvr.gif',
	'img/info-Fixed-actv.gif',
	'img/info-Fixed-hvr.gif',
	'img/info-Large-actv.gif',
	'img/info-Large-hvr.gif',
	'img/info-Telecentric-actv.gif',
	'img/info-Telecentric-hvr.gif',
	'img/info-Fluorescence-actv.gif',
	'img/info-Fluorescence-hvr.gif'
];

jQuery.preloadImages = function() {
	var a = (typeof arguments[0] == 'object') ? arguments[0] : arguments;
	for (var i = a.length -1; i > 0; i--) {
		jQuery("<img>").attr("src", a[i]);
	}
}

// Run this code once the page is ready to run JavaScript.
$(document).ready(function() {
	//Firefox fix. Without this, the UOM would not show up as checked when you reload the page.
	if ($.browser.mozilla) $("form").attr("autocomplete", "off");

	// Setup hover for the measurements.
	$("#measurementsList li").hover(
		function() {
			$(this).addClass('highlight');
		},
		function() {
			$(this).removeClass('highlight');
		}
	);

	// Setup hover for the additional features.
	$("#featuresList li").hover(
		function() {
			$(this).addClass('highlight');
		},
		function() {
			$(this).removeClass('highlight');
		}
	);

	// Handle feature selections.
	$(".feature").bind("click", function(e) {
		return updateFeature(this);
	});

	// Setup hover for the product families.
	$(".productFamily").hover(
		function() {
			// Change to hover image if selectable.
			if (!$(this).hasClass('disabled')) {
				var image = $(this).find("div.title img");
				var src = image.attr("src");
				image.attr("src", src.replace("-up", "-hvr"));
			}
		},
		function() {
			// Change to up image if selectable.
			if (!$(this).hasClass('disabled')) {
				var image = $(this).find("div.title img");
				var src = image.attr("src");
				image.attr("src", src.replace("-hvr", "-up"));
			}
		}
	);


	// Setup hover for buttons (dialogs, product family, etc.).
	$(".button").hover(
		function() {
			$(this).attr('src', $(this).attr('src').replace("-up", "-hvr"));
		},
		function() {
			$(this).attr('src', $(this).attr('src').replace("-hvr", "-up"));
		}
	);

	// Setup spinner buttons.
	$('#cameraSensorLineScanUser').spinner({
		min: 0,
		stepping: .1,
		change: function() {
			updateCameraSensor();
		}
	});

	$('#cameraSensorHorizontalUser').spinner({
		min: 0,
		stepping: .1,
		change: function() {
			updateCameraSensor();
		}
	});

	$('#cameraSensorVerticalUser').spinner({
		min: 0,
		stepping: .1,
		change: function() {
			updateCameraSensor();
		}
	});

	$('#objectSizeWidth').spinner({
		min: 0,
		stepping: .1,
		change: function() {
			updateObjectImageSize();
			updateProductFamilyCards();
		}
	});

	$('#objectSizeHeight').spinner({
		min: 0,
		stepping: .1,
		change: function() {
			updateObjectImageSize();
			updateProductFamilyCards();
		}
	});

	$('#workingDistance').spinner({
		min: 0,
		stepping: .1,
		width: 22,
		change: function() {
			//			updateCameraSensor();
			updateObjectImageSize();
			updateProductFamilyCards();
		}
	});

	// Setup dialogs.
	$('#infoDialog').dialog
	(
		{
			autoOpen: false,
			draggable: true,
			width: 600,
			height: 540,
			overlay:
			{
				opacity: 0.5,
				background: "black"
			},
			bgiframe: true,
			modal: true
		}
	);

	$("#knownPixelSizeUser").keypress(function(e) {
		//if the letter is not digit then display error and don't type anything
		if (e.which != 8 && e.which != 0 && e.which != 46 && (e.which < 48 || e.which > 57)) {
			return false;
		}
	});

	$(".infoIcon").bind("click", function(e) {
		// Get the help link to load from the info icon.
		var helpLink = $('#' + $(this).attr('name'));

		// Open up help dialog.
		$('#helpDialog').dialog('open');

		// Remove "selected" class from all help links.
		$('.helpLink').removeClass('selected');

		// Add "selected" class to the help link.
		$(helpLink).addClass('selected');

		// Load the help page specified in the link.
		var contentUrl = $(helpLink).attr('href');
		$('#helpContent').load(contentUrl);
		$('#helpContent').scrollTop(0);
	});

	$('#warningDialog').dialog
	(
		{
			autoOpen: false,
			draggable: true,
			width: 400,
			height: 200,
			overlay:
			{
				opacity: 0.5,
				background: "black"
			},
			bgiframe: true,
			modal: true
		}
	);

	$('#whyNotDialog').dialog
	(
		{
			autoOpen: false,
			draggable: true,
			width: 400,
			height: 400,
			overlay:
			{
				opacity: 0.5,
				background: "black"
			},
			bgiframe: true,
			modal: true
		}
	);

	$('#optionalResolutionDialog').dialog
	(
		{
			autoOpen: false,
			draggable: true,
			width: 500,
			height: 425,
			overlay:
			{
				opacity: 0.5,
				background: "black"
			},
			bgiframe: true,
			modal: true
		}
	);

	$("#optionalResolution").bind("click", function(e) {
		$('#optionalResolutionDialog').dialog("open");
	});

	// Preload images used for hovers, etc.
	$.preloadImages(images);

	updateUnitOfMeasure();
});

// This function is called whenever the Unit of Measure radio buttons are clicked.
function updateUnitOfMeasure()
{
	if ($("#inches").is(":checked")){
		unitOfMeasure = "in";
	} else {
		unitOfMeasure = "mm";
	}

	$(".unitOfMeasure").text(unitOfMeasure);

	updateCameraSensor();
	updateObjectImageSize();
	updateProductFamilyCards();
}

// This function is called whenever the Camera Sensor dropdown value changes or a change is made to the camera sensor line scan or dimension.
function updateCameraSensor()
{
	var value = $("#cameraSensor").val();

	sensorHeight = '';
	sensorWidth = '';
	cameraSensorValue = 0;

	switch (value)
	{
		case "1":
			$('#linescan').css('display', 'none');
			$('#hxv').css('display', 'none');
			$('#otherPlaceholder').css('display', '');
			$('#objectHeight').css('display', '');
			sensorHeight = 9.6;
			sensorWidth = 12.8;
			cameraSensorValue = 16;
			break;
		case ".67":
			$('#linescan').css('display', 'none');
			$('#hxv').css('display', 'none');
			$('#otherPlaceholder').css('display', '');
			$('#objectHeight').css('display', '');
			sensorHeight = 6.6;
			sensorWidth = 8.8;
			cameraSensorValue = 11;
			break;
		case ".55":
			$('#linescan').css('display', 'none');
			$('#hxv').css('display', 'none');
			$('#otherPlaceholder').css('display', '');
			$('#objectHeight').css('display', '');
			sensorHeight = 5.32;
			sensorWidth = 7.18;
			cameraSensorValue = 8.93;
			break;
		case ".5":
			$('#linescan').css('display', 'none');
			$('#hxv').css('display', 'none');
			$('#otherPlaceholder').css('display', '');
			$('#objectHeight').css('display', '');
			sensorHeight = 4.8;
			sensorWidth = 6.4;
			cameraSensorValue = 8;
			break;
		case ".37":
			$('#linescan').css('display', 'none');
			$('#hxv').css('display', 'none');
			$('#otherPlaceholder').css('display', '');
			$('#objectHeight').css('display', '');
			sensorHeight = 4.04;
			sensorWidth = 5.37;
			cameraSensorValue = 6.72;
			break;
		case ".33":
			$('#linescan').css('display', 'none');
			$('#hxv').css('display', 'none');
			$('#otherPlaceholder').css('display', '');
			$('#objectHeight').css('display', '');
			sensorHeight = 3.6;
			sensorWidth = 4.8;
			cameraSensorValue = 6;
			break;
		case ".25":
			$('#linescan').css('display', 'none');
			$('#hxv').css('display', 'none');
			$('#otherPlaceholder').css('display', '');
			$('#objectHeight').css('display', '');
			sensorHeight = 2.4;
			sensorWidth = 3.2;
			cameraSensorValue = 4;
			break;
		case ".17":
			$('#linescan').css('display', 'none');
			$('#hxv').css('display', 'none');
			$('#otherPlaceholder').css('display', '');
			$('#objectHeight').css('display', '');
			sensorHeight = 1.8;
			sensorWidth = 2.4;
			cameraSensorValue = 3;
			break;
		case "LineScan":
			$('#linescan').css('display', '');
			$('#hxv').css('display', 'none');
			$('#otherPlaceholder').css('display', 'none');
			$('#objectHeight').css('display', 'none');
			$("#objectSizeHeight").val(0);

			var cameraSensorLineScanUser = $("#cameraSensorLineScanUser").val();

			if (cameraSensorLineScanUser != '' && cameraSensorLineScanUser != 0) {
				sensorHeight = 0;
				sensorWidth = cameraSensorLineScanUser;
				cameraSensorValue = cameraSensorLineScanUser;
			}
			break;
		case "HxV":
			$('#linescan').css('display', 'none');
			$('#hxv').css('display', '');
			$('#otherPlaceholder').css('display', 'none');
			$('#objectHeight').css('display', '');
			var cameraSensorHorizontalUser = $("#cameraSensorHorizontalUser").val();
			var cameraSensorVerticalUser = $("#cameraSensorVerticalUser").val();

			if (cameraSensorHorizontalUser != '' && cameraSensorHorizontalUser != 0 && cameraSensorVerticalUser != '' && cameraSensorVerticalUser != 0) {
				sensorHeight = cameraSensorVerticalUser;
				sensorWidth = cameraSensorHorizontalUser;
				cameraSensorValue = Math.sqrt(cameraSensorVerticalUser * cameraSensorVerticalUser + cameraSensorHorizontalUser * cameraSensorHorizontalUser);
			}
			break;
		default:
			$('#linescan').css('display', 'none');
			$('#hxv').css('display', 'none');
			$('#otherPlaceholder').css('display', '');
			$('#objectHeight').css('display', '');
			sensorHeight = '';
			sensorWidth = '';
			cameraSensorValue = 0;
			break;
	}

	if (cameraSensorValue != 0) {
		$('#diagonal').text('Diagonal = ' + (Math.round(cameraSensorValue * 100) / 100) + ' mm');
	} else {
		$('#diagonal').text('');
	}
	
	// Update object sizing.
	updateObjectImageSize();
	
	// Enable and disable product family cards based on the value selected.
	updateProductFamilyCards();
}

function updateOptionalResolution()
{
	var knownPixelSizeUser = $.trim($("#knownPixelSizeUser").val());

	if (knownPixelSizeUser.length > 0)
	{
		$("#resolution").text("Pixel Size = " + knownPixelSizeUser + "mm (" + knownPixelSizeUser * 1000 + " μ)");
	}
	else
	{
		$("#resolution").text("");
	}

	$('#knownPixelSize').val(knownPixelSizeUser);
	// Close dialog.
	$('#optionalResolutionDialog').dialog('close');
}

function updateCameraMount()
{
	cameraMountValue = $("#cameraMount").val();

	// Enable and disable product family cards based on the value selected.
	updateProductFamilyCards();
}

function updateFeature(a) {
	var warningMessage = '';
	var largestObjectDimension = calcLargestObjectDimension();
	// Enable and disable product family cards based on the value selected.
	//TODO: Need to account for this
	//	if (document.OpticalWizard.sFamily[OW_FAMILY_ZOOM_12].checked == true) {
	//		if (document.getElementById('bInternalFocus').checked == false) {
	//			document.getElementById('bInternalFocus').checked = true;
	//			noteText += 'The Ring Light option is only available with a 12X Zoom system that includes Internal Focus.<br><br>';

	//TODO: handle this
	//noteText += 'All componenets may not be available in the NIR format.<br><br>See <a href="#" onclick="loadHelpFile(\'info-feature-nir\'); return false;"><b>NIR Help</b></a> for more information.<br><br>';

	// There are some special conditions that we need to handle separately.

	switch (a.name) {
		case 'feature-coax':
			if (a.checked == true) {
				if ($('#feature-externalCoax').is(':checked')) {
					return showError('You cannot choose a configuration that includes both Coaxial Illumination and an External Coax.<br><br>Please choose one or the other.');
				}
			} else {
				if ($('#feature-polarization').is(':checked')) {
					return showError('You must choose Coaxial Illumination in order to use Polarization.<br><br>If you want to removed the Coax requirement, uncheck Polarization first.');
				} else if ($('#feature-fluorescence').is(':checked')) {
					return showError('You must choose Coaxial Illumination in order to use Fluorescence.<br><br>If you want to removed the Coax Illumination requirement, uncheck Fluorescence first.');
				} else if ($('#feature-dic').is(':checked')) {
					return showError('You must choose Coaxial Illumination in order to use DIC.<br><br>If you want to remove the Coax Illumination requirement, uncheck DIC first.');
				}
			}  // End coax / additional features check
			break;
		case 'feature-externalCoax':
			if (a.checked == true) {
				if ($('#feature-ringLight').is(':checked')) {
					return showError('You cannot choose a configuration that includes both an External Coax and a Ring Light.<br><br>If you would to use External Coax, please uncheck the Ring Light feature first.');
				}  else if ($('#feature-coax').is(':checked')) {
					return showError('You cannot choose a configuration that includes both an External Coax and Coaxial Illumination.<br><br>Please choose one or the other.');
				}

				if (largestObjectDimension > 32) {
					return showError('You cannot have a Object Size dimension over ' + DisplayDistance(32) + ' if you want to use External Coaxial Illumination.  Either reduce the Object Size Dimension or uncheck External Coaxial Illumination.');
				}

			} // End External coax / ring light check
			break;
		case 'feature-ringLight':
			if (a.checked == true && $('#feature-externalCoax').is(':checked')) {
				return showError('You cannot choose a configuration that includes both an External Coax and a Ring Light.<br><br>If you would like to use Ring Light, please uncheck the External Coax feature first.');
			} // End External coax / ring light check
			break;
		case 'feature-internalFocus':
			if (a.checked == true) {
			} else {
				if ($('#feature-dic').is(':checked')) {
					return showError('You must choose Interal Focusing in order to use DIC.<br><br>If you want to remove the Internal Focusing requirement, uncheck DIC first.');
				}
			}  // End coax / additional features check
			break;
		case 'feature-polarization':
			if (a.checked == true) {
				if ($("#cameraMount").val() != 'C' && $("#cameraMount").val() != 'F' && $("#cameraMount").val() != '') {
					return showError('Polarization is currently limited to C- or F-mount only.<br><br>Please choose the C- or F-mount option first.');
				}
				if ($('#feature-coax').is(':checked') == false) {
					$('#feature-coax').attr("checked", true);
					warningMessage += 'You must choose Coaxial Illumination in order to use Polarization.<br><br>';
				}
			} else {
				if ($('#feature-dic').attr("checked") == true) {
					return showError('You must choose Polarization in order to use DIC.<br><br>If you want to remove the Polarization requirement, uncheck DIC first.');
				} else if ($('#feature-fluorescence').attr('checked') == false) {
					$('#feature-coax').attr("checked", false);
				}
			} // End Polarization / c or f-mount check
			break;
		case 'feature-motorization':
			if (a.checked == true) {
				if ($('#feature-aperture').is(':checked')) {
					return showError('You cannot choose a configuration that includes both Aperture Control and Motorization.');
				}
				if ($('#feature-detentZoom').is(':checked')) {
					return showError('You cannot choose a configuration that includes both Detent Zoom and Motorization.');
				}
			}  // End motorization / detent / aperture check
			break;
		case 'feature-fluorescence':
			if (a.checked == true) {
				if ($('#feature-coax').is(':checked') == false) {
					$('#feature-coax').attr('checked', true)
					warningMessage += 'Coaxial Illumination is a required feature when using Fluorescense.<br><br>';
				}

				disableFeature('feature-externalCoax');
				disableFeature('feature-ringLight');
				disableFeature('feature-polarization');
				disableFeature('feature-motorization');
				disableFeature('feature-telecentric');
				disableFeature('feature-dic');
				disableFeature('feature-aperture');
				disableFeature('feature-lowLight');
				disableFeature('feature-nir');
			} else {
				if ($('#feature-polarization').attr('checked') == false) {
					$('#feature-coax').attr('checked', false)
				}
				enableFeature('feature-externalCoax');
				enableFeature('feature-ringLight');
				enableFeature('feature-polarization');
				enableFeature('feature-motorization');
				enableFeature('feature-telecentric');
				enableFeature('feature-dic');
				enableFeature('feature-aperture');
				enableFeature('feature-lowLight');
				enableFeature('feature-nir');
			}
			break;
		case 'feature-telecentric':
			if (a.checked == true) {
				disableFeature('feature-externalCoax');
				disableFeature('feature-ringLight');
				disableFeature('feature-polarization');
				disableFeature('feature-fluorescence');
				disableFeature('feature-dic');
				disableFeature('feature-lowLight');
				disableFeature('feature-nir');
			} else {
				enableFeature('feature-externalCoax');
				enableFeature('feature-ringLight');
				enableFeature('feature-polarization');
				enableFeature('feature-fluorescence');
				enableFeature('feature-dic');
				enableFeature('feature-lowLight');
				enableFeature('feature-nir');
			} // End telecentric check
			break;
		case 'feature-dic':
			if (a.checked == true) {
				if ($('#feature-coax').is(':checked') == false) {
					$('#feature-coax').attr("checked", true);
					warningMessage += 'Coaxial Illumination is a required feature when using DIC. ';
				}
				if ($('#feature-internalFocus').is(':checked') == false) {
					$('#feature-internalFocus').attr("checked", true);
					warningMessage += 'Internal Focusing is a required feature when using DIC. ';
				}
				if ($('#feature-polarization').is(':checked') == false) {
					$('#feature-polarization').attr("checked", true);
					warningMessage += 'Polarization is a required feature when using DIC. ';
				}
				disableFeature('feature-externalCoax');
				disableFeature('feature-ringLight');
				disableFeature('feature-fluorescence');
				disableFeature('feature-telecentric');
				disableFeature('feature-lowLight');
			} else {
				$('#feature-coax').attr("checked", false);
				$('#feature-internalFocus').attr("checked", false);
				$('#feature-polarization').attr("checked", false);
				enableFeature('feature-externalCoax');
				enableFeature('feature-ringLight');
				enableFeature('feature-fluorescence');
				enableFeature('feature-telecentric');
				enableFeature('feature-lowLight');
			}
			break;
		case 'feature-aperture':
			if (a.checked == true) {
				if ($('#feature-motorization').is(':checked')) {
					return showError('You cannot choose a configuration that includes both Aperture Control and Motorization.');
				}
			}
			break;
		case 'feature-detentZoom':
			if (a.checked == true) {
				if ($('#feature-motorization').is(':checked')) {
					return showError('You cannot choose a configuration that includes both Detent Zoom and Motorization.');
				}
			}
			break;
		case 'feature-lowLight':
			break;
		case 'feature-nir':
			if (a.checked == true) {
				disableFeature('feature-externalCoax');
				disableFeature('feature-ringLight');
				disableFeature('feature-polarization');
				disableFeature('feature-fluorescence');
				disableFeature('feature-telecentric');
				disableFeature('feature-dic');
				disableFeature('feature-lowLight');
				warningMessage += 'All componenets may not be available in the NIR format.<br><br>See <a href="#" onclick="loadHelpFile(\'info-feature-nir\'); return false;"><b>NIR Help</b></a> for more information.<br><br>';
			} else {
				enableFeature('feature-externalCoax');
				enableFeature('feature-ringLight');
				enableFeature('feature-polarization');
				enableFeature('feature-fluorescence');
				enableFeature('feature-telecentric');
				enableFeature('feature-dic');
				enableFeature('feature-lowLight');
			} // End NIR check
			break;
	}
	updateProductFamilyCards();
	showWarning(warningMessage + $('#featureWarningMessage').html());
}

function updateCard(cardId, enabled)
{
	if (enabled)
	{
		$("#" + cardId).removeClass("disabled");

		var image = $("#" + cardId + " div.title img");
		var src = image.attr("src");
		image.attr("src", src.replace("-na", "-up"));

		// Remove image overlay.
		$("#" + cardId + " div.graphic").find('.productFamilyImageOverlay').remove();
		
		var image = $("#" + cardId + " div.link img");
		var src = image.attr("src");
		image.attr("src", src.replace("why", "select"));
	}
	else
	{
		$("#" + cardId).addClass("disabled");

		var image = $("#" + cardId + " div.title img");
		var src = image.attr("src");
		image.attr("src", src.replace("-up", "-na"));
		
		// Add overlay to image to make it appear greyed out.
		var graphic = $("#" + cardId + " div.graphic");
		if (graphic.find('.productFamilyImageOverlay').length == 0) {
			graphic.append('<span class="productFamilyImageOverlay"></span>');
		}
		
		var image = $("#" + cardId + " div.link img");
		var src = image.attr("src");
		image.attr("src", src.replace("select", "why"));
	}
}

function cardClick(cardId)
{
	// Display why not dialog if card has been disabled based off of input.
	if ($("#" + cardId).hasClass("disabled"))
	{
		openWhyNot(cardId);
		return;
	}
	
	// Make sure user has answered all questions before allowing
	// them to move to the next step in the wizard.
	var errorMessage = '';

	if ($("#inches").is(":checked") == false && $("#millimeters").is(":checked") == false) {
		errorMessage += 'Section 1 - Unit of Measure<br>';
	}
	if ($("#cameraSensor").val() == '')
	{
		errorMessage += 'Section 2 - Camera Sensor Format<br>';
	}
	if ($("#cameraSensor").val() == 'LineScan') {
		if ($("#objectSizeWidth").val() == 0) {
			errorMessage += 'Section 3 - Object Size<br>';
		}
	} else {
		if ($("#objectSizeHeight").val() == 0 && $("#objectSizeWidth").val() == 0) {
			errorMessage += 'Section 3 - Object Size<br>';
		} else if ($("#objectSizeHeight").val() == 0 || $("#objectSizeWidth").val() == 0) {
			errorMessage += 'Section 3 - Object Size (both dimensions are required)<br>';
		}
	}
	if ($("#workingDistance").val() == 0)
	{
		errorMessage += 'Section 4 - Working Distance<br>';
	}
	if ($("#cameraMount").val() == '')
	{
		errorMessage += 'Section 5 - Camera Mount<br>';
	}
	
	if (errorMessage != '')
	{
		errorMessage = 'Please complete sections 1 - 5 before advancing to the next page of the wizard. The following sections are incomplete:<br><br>' + errorMessage;

		$('#warningMessage').html(errorMessage);
		$('#warningDialog').dialog("open");

		return;
	}

	// Goto to the next step in the wizard based on the card selected.
		
	document.forms[0]['productFamily'].value = cardId;
	document.forms[0].submit();
}

function updateProductFamilyCards()
{
	var calcMag = $('#magnification').text();
	var warningMessage = '';
	var largestObjectDimension = calcLargestObjectDimension();
	var workingDistance = ConvertDistanceToMetric(+($("#workingDistance").val()));
	var cameraMount = $("#cameraMount").val();
    for (var i in productFamilies)
	{
		var enabled = true;
		clearReason(i);

		if (cameraSensorValue != 0 && cameraSensorValue > productFamilies[i][PRODUCT_FAMILY_ARRAY_SENSOR])
		{
			enabled = false;
			addReason(i, '<li>You requested a sensor size of ' + cameraSensorValue + 'mm, but this family has a maximum sensor size of ' + productFamilies[i][PRODUCT_FAMILY_ARRAY_SENSOR] + 'mm.</li>');
		}
		if (calcMag != 0 && productFamilies[i][PRODUCT_FAMILY_ARRAY_MAG_LOW] > calcMag)
		{
			enabled = false;
			addReason(i, '<li>You requested a magnification of ' + calcMag + 'x, but that is below this family\'s low magnification restriction of ' + productFamilies[i][PRODUCT_FAMILY_ARRAY_MAG_LOW] + 'x.</li>');
		}
		if (calcMag != 0 && calcMag > productFamilies[i][PRODUCT_FAMILY_ARRAY_MAG_HIGH])
		{
			enabled = false;
			addReason(i, '<li>You requested a magnification of ' + calcMag + 'x, but that is above this family\'s high magnification restriction of ' + productFamilies[i][PRODUCT_FAMILY_ARRAY_MAG_HIGH] + 'x.</li>');
		}
		if (cameraMount != '' && productFamilies[i][PRODUCT_FAMILY_ARRAY_CAMERA_FORMAT].indexOf('|' + cameraMount + '|') == -1)
		{
			enabled = false;
			addReason(i, '<li>You requested ' + getCameraMountName(cameraMount) + ' but this family does not support that camera mount.</li>');
		}

		for (var j in additionalFeatures)
		{
			var feature = additionalFeatures[j];

			if ($('#' + feature).is(":checked")) {
				if (productFamilies[i][PRODUCT_FAMILY_ARRAY_FEATURES].indexOf('|' + feature + '|') == -1) {
					addReason(i, '<li>The ' + getFeatureName(feature) + ' feature is not supported by this family.</li>');
					enabled = false;
				}
			} else {
				//Some of the features must be checked for their card to be active
				if (feature == "feature-fluorescence" || feature == "feature-telecentric") {
					if (productFamilies[i][PRODUCT_FAMILY_ARRAY_FEATURES].indexOf('|' + feature + '|') != -1) {
						addReason(i, '<li>' + getFeatureName(feature) + ' is a required feature for this family. The wizard will not offer this family unless the cooresponding feature is selected.</li>');
						enabled = false;
					}
				}
			}
		}

		updateCard(productFamilies[i][PRODUCT_FAMILY_ARRAY_CARD_ID], enabled);
	}

	if ($('#feature-coax').is(':checked') && $('#feature-aperture').is(':checked')) {
		//Cannot have coax and aperature control with Fixed Mag
		updateCard(productFamilies[LENS_FAMILY_FIXED_MAG][PRODUCT_FAMILY_ARRAY_CARD_ID], false);
		addReason(LENS_FAMILY_FIXED_MAG, '<li>You cannot have ' + getFeatureName('feature-coax') + ' and ' + getFeatureName('feature-aperture') + ' with the Fixed Mag family.</li>');
	}

	if ($('#feature-internalFocus').is(':checked') == false && $('#feature-aperture').is(':checked') == true) {
		//Fixed must have internal focus if they want aperture.
		updateCard(productFamilies[LENS_FAMILY_FIXED_MAG][PRODUCT_FAMILY_ARRAY_CARD_ID], false);
		addReason(LENS_FAMILY_FIXED_MAG, '<li>You must have ' + getFeatureName('feature-internalFocus') + ' if you want ' + getFeatureName('feature-aperture') + ' on the Fixed Mag family.</li>');
	}

	if ($("#cameraMount").val() != 'C' && $("#cameraMount").val() != 'F' && $("#cameraMount").val() != '') {
		if ($('#feature-polarization').is(':checked')) {
			$("#cameraMount").val('');
			return showError('Polarization is currently limited to C- or F-mount only.<br><br>Please choose the C- or F-mount option first.');
		}
	}

	if ($("#cameraMount").val() == 'Z') {
		warningMessage += 'The selection of the CS-mount limits the optical solutions to CCTV lenses.<br><br>It is possible to convert a CS-mount camera to a C-mount camera with the addition of a 5mm spacer (3-6073). Subsequent selecting of the C-Mount camera in the wizard will significantly increase your choice of workable options.';

		if ($("#cameraSensor").val() != .33) {
			updateCard(productFamilies[LENS_FAMILY_CCTV][PRODUCT_FAMILY_ARRAY_CARD_ID], false);
			addReason(LENS_FAMILY_CCTV, '<li>The selection of the CS-Mount limits the optical solutions to CCTV lenses and require a 1/3&quot; format camera. The CS-Mount will not perform on any other format.</li>');
		}
	}

	var theValue = 0;
	var errorMount = '';
	var errorDiagonal = '';
	var largestObjectDimension = calcLargestObjectDimension();

	if ($("#cameraSensor").val() == 'LineScan') {
		if ($('#cameraSensorLineScanUser').val() != '' && $('#cameraSensorLineScanUser').val() != 0) {
			theValue = $('#cameraSensorLineScanUser').val();
		}
	} else if ($("#cameraSensor").val() == 'HxV') {
		if ($('#cameraSensorHorizontalUser').val() != '' && $('#cameraSensorHorizontalUser').val() != 0 && $('#cameraSensorVerticalUser').val() != '' && $('#cameraSensorVerticalUser').val() != 0) {
			theValue = Math.sqrt(Math.pow($('#cameraSensorHorizontalUser').val(), 2) + Math.pow($('#cameraSensorVerticalUser').val(), 2));
		}
	}

	if (theValue > 20 && errorMount == '') {
		errorDiagonal = 20;
		if (cameraMount == 'C' || cameraMount == 'E' || cameraMount == 'Z') {
			errorMount = cameraMount;
		} 
		
		if (theValue > 43.5 && errorMount == '') {
			errorDiagonal = 43.5;
		
			if (cameraMount == 'F' || cameraMount == 'S' || cameraMount == 'T') {
				errorMount = cameraMount;
			}
			
			if (theValue > 67 && errorMount == '') {
				errorDiagonal = 67;
				if (cameraMount == 'M') {
					errorMount = cameraMount;
				}
			}
		}
	}
	

	if (errorMount != '' && errorDiagonal != '') {
		errorMount = getCameraMountName(errorMount);
		if ($("#cameraSensor").val() == 'LineScan') {
			$('#cameraSensorLineScanUser').val('0');
			updateCameraSensor();
			return showError('You cannot have a Line Scan over ' + errorDiagonal + 'mm if you want to use the ' + errorMount + '.  Either reduce the Line Scan or choose a different Camera Mount.');
		} else {
			$('#cameraSensorHorizontalUser').val('0');
			$('#cameraSensorVerticalUser').val('0');
			updateCameraSensor();
			return showError('The values that you entered for Horizontal and Vertical Dimensions result in a Diagonal Dimension of ' + Math.floor(theValue) + 'mm. You cannot have a Diagonal Dimension over ' + errorDiagonal + 'mm if you want to use the ' + errorMount + '.  Either reduce the Dimensions or choose a different Camera Mount.');
		}
	}

	if ($('#feature-externalCoax').is(':checked')) {
		if (largestObjectDimension > 32) {
			$("#objectSizeWidth").val('0');
			$("#objectSizeHeight").val('0');
			return showError('You cannot have a Object Size dimension over ' + DisplayDistance(32) + ' if you want to use External Coaxial Illumination.  Either reduce the Object Size Dimension or uncheck External Coaxial Illumination.');
		}
	}
	
	if ($('#feature-coax').is(':checked')) {
		if (largestObjectDimension > 11) {
			updateCard(productFamilies[LENS_FAMILY_FIXED_MAG][PRODUCT_FAMILY_ARRAY_CARD_ID], false);
			addReason(LENS_FAMILY_FIXED_MAG, '<li>You cannot use ' + getFeatureName('feature-coax') + ' to illuminate an object with a diagonal larger than ' + DisplayDistance(11) + ' with this family.</li>');
			
			if (largestObjectDimension > 20.5) {
				updateCard(productFamilies[LENS_FAMILY_ZOOM][PRODUCT_FAMILY_ARRAY_CARD_ID], false);
				addReason(LENS_FAMILY_ZOOM, '<li>You cannot use ' + getFeatureName('feature-coax') + ' to illuminate an object with a diagonal larger than ' + DisplayDistance(20.5) + ' with this family.</li>');
				updateCard(productFamilies[LENS_FAMILY_FLUORESCENCE][PRODUCT_FAMILY_ARRAY_CARD_ID], false);
				addReason(LENS_FAMILY_FLUORESCENCE, '<li>You cannot use ' + getFeatureName('feature-coax') + ' to illuminate an object with a diagonal larger than ' + DisplayDistance(20.5) + ' with this family.</li>');

				if (largestObjectDimension > 50) {
					updateCard(productFamilies[LENS_FAMILY_TELECENTRIC][PRODUCT_FAMILY_ARRAY_CARD_ID], false);
					addReason(LENS_FAMILY_TELECENTRIC, '<li>You cannot use ' + getFeatureName('feature-coax') + ' to illuminate an object with a diagonal larger than ' + DisplayDistance(50) + ' with this family.</li>');
				}
			}
		}
	} // End Coax / object size check

	if ($('#feature-dic').is(':checked')) {
		if (workingDistance <= 1 || workingDistance >= 34) {
			updateCard(productFamilies[LENS_FAMILY_ZOOM][PRODUCT_FAMILY_ARRAY_CARD_ID], false);
			addReason(LENS_FAMILY_ZOOM, '<li>The Working Distance for DIC must be in the range ' + DisplayDistance(1) + ' - ' + DisplayDistance(34) + '.</li>');
		}
	} // End Working Distance DIC check

	if (workingDistance != 0) {
		if (workingDistance > 200) {
			if ($('#feature-externalCoax').is(':checked')) {
				warningMessage += 'It is not recommended to use External Coaxial Illumination for Working Distances beyond ' + DisplayDistance(200) + ' due to lack of illumination level.<br><br>';
			} else if ($('#feature-ringLight').is(':checked')) {
				warningMessage += 'It is not recommended to use a Ring Light for Working Distances beyond ' + DisplayDistance(200) + ' due to lack of illumination level.<br><br>';
			}
		} else if (workingDistance < 33) {
			if ($('#feature-externalCoax').is(':checked')) {
				warningMessage += 'It is not recommended to use External Coaxial Illumination for Working Distances under ' + DisplayDistance(33) + ' due to lack of illumination level.<br><br>';
			} else if ($('#feature-ringLight').is(':checked')) {
				warningMessage += 'It is not recommended to use a Ring Light for Working Distances under ' + DisplayDistance(33) + ' due to lack of illumination level.<br><br>';
			}
		}
	} // End Working Distance / coax check

	showWarning(warningMessage);
}

function calcLargestObjectDimension() {
	if ($("#objectSizeWidth").val() != '' && $("#objectSizeWidth").val() != 0 && $("#objectSizeWidth").val() != '' && $("#objectSizeWidth").val() != 0) {
		if (+($("#objectSizeWidth").val()) > +($("#objectSizeHeight").val())) {
			return ConvertDistanceToMetric($("#objectSizeWidth").val());
		} else {
			return ConvertDistanceToMetric($("#objectSizeHeight").val());
		}
	} else {
		return 0;
	}
}

function showWarning(warningMessage) {
	$('#featureWarningMessage').html(warningMessage);
	if (warningMessage == '') 
		$('#featureWarning').css('display', 'none');
	else		
		$('#featureWarning').css('display', 'block');

}

// Always show error messages
function showError(errorMessage) {
	if (errorMessage != '') {
		$('#warningMessage').html(errorMessage);
		$('#warningDialog').dialog("open");

		return false;
	}
}

function disableFeature(featureName) {
	$('#' + featureName).attr("checked", false);
	$('#' + featureName).attr("disabled", "disabled");
}

function enableFeature(featureName) {
	$('#' + featureName).attr("disabled", "");
}

function updateObjectImageSize()
{
	var magnification = '0.0';
	var iSensorWidthPX = 72;
	var iSensorHeightPX = 72;

	var iObjectWidth = +( ConvertDistanceToMetric($("#objectSizeWidth").val()) );
	var iObjectHeight = +(ConvertDistanceToMetric($("#objectSizeHeight").val()));
	var iIconWidth = 0;
	var iIconHeight = 0;
	var iSensorWidth = sensorWidth;
	var iSensorHeight = sensorHeight;
	var iTemp
	var iObjectWidthRecalc;
	var iObjectHeightRecalc;
	var bLineScan = ($("#cameraSensor").val() == "LineScan");
	
	// Make sure there are values specified for camera sensor and object size.
	if (iSensorWidth != '' && iSensorHeight != '') {
		//Make Width the longer side
		if (iSensorWidth < iSensorHeight) {
			iTemp = iSensorWidth;
			iSensorWidth = iSensorHeight;
			iSensorHeight = iTemp;
		}
		iSensorHeightPX = iSensorWidthPX / iSensorWidth * iSensorHeight;
	} else if (bLineScan == true && iSensorWidth != '') {
		iSensorHeightPX = 1;
	} else {
		//Default the height to the standard format dimension
		iSensorHeightPX = iSensorWidthPX / 4 * 3;
	}
	$('#objectSizeSensor').css('width', iSensorWidthPX + 'px');
	$('#objectSizeSensor').css('height', iSensorHeightPX + 'px');

	if ((iObjectWidth != '' && iObjectHeight != '') || (iObjectWidth != '' && bLineScan == true)) {
		//Make Width the longer side
		if (iObjectWidth < iObjectHeight) {
			iTemp = iObjectWidth;
			iObjectWidth = iObjectHeight;
			iObjectHeight = iTemp;
		}

		// Try to calc by fitting to width
		magnification = Math.round(iSensorWidth / iObjectWidth * 1000000) / 1000000;  // Only look at six decimal points of precision
		iObjectWidthRecalc = Math.round(iObjectWidth * magnification * 100) / 100; // Only look at two decimal points of precision
		iObjectHeightRecalc = Math.round(iObjectHeight * magnification * 100) / 100;  // Only look at two decimal points of precision

		$('#objectSizeObject').css('display', '');
		
		//Test to make sure that the mag fits
		if ((iObjectHeightRecalc > iSensorHeight || iObjectWidthRecalc > iSensorWidth) && bLineScan == false) {
			//If not, recalc mag based on height
			magnification = Math.round(iSensorHeight / iObjectHeight * 1000000) / 1000000;

			iIconHeight = iSensorHeightPX - 2;
			iIconWidth = iIconHeight / iObjectHeight * iObjectWidth;
			
			$('#objectSizeObject').css('height', iIconHeight + 'px');
			$('#objectSizeObject').css('width', iIconWidth + 'px');
			$('#objectSizeObject').css('left', (iSensorWidthPX - iIconWidth) / 2 - 1 + 'px');
			$('#objectSizeObject').css('top', '0px');

		} else {
			iIconWidth = iSensorWidthPX - 2;
			if (iObjectHeight == 0) {
				// Line Scan
				iIconHeight = 2;
			} else {
				iIconHeight = iIconWidth / iObjectWidth * iObjectHeight; 
			}
			
			$('#objectSizeObject').css('width', iIconWidth + 'px');
			$('#objectSizeObject').css('height', iIconHeight + 'px');
			$('#objectSizeObject').css('top', (iSensorHeightPX - iIconHeight) / 2 - 1 + 'px');
			$('#objectSizeObject').css('left', '0px');

		}
	} else {
		$('#objectSizeObject').css('display', 'none');
	}

	if (isNaN(magnification)) {
	    magnification = '0.0';
	}

	$('#objectSizeMagnification').val(magnification);

	// Update magnification value displayed beside object.
	$('#magnification').text(parseFloat(magnification).toFixed(4));

	updateOptionalResolution();	
}

var factor = 25.4;
function DisplayDistance(iMetricValue) {
	if (unitOfMeasure == "in")
		return parseFloat(iMetricValue / factor).toFixed(2) + " in.";
	else
		return iMetricValue + "mm";
}

function ConvertDistanceToMetric(iDistance) {
	if (unitOfMeasure == "in")
		return iDistance * factor;
	else
		return iDistance;
}

function openWhyNot(cardID) {
	loadWhyNotInfo(cardID);
	$('#whyNotDialog').dialog("open");
}

function openHelpFromWhyNot() {
	var helpLink = $('#' + $('#whyNotDialog').attr('name'));
	$('#whyNotDialog').dialog('close');	

	// Remove "selected" class from all help links.
	$('.helpLink').removeClass('selected');

	// Open up help dialog.
	$('#helpDialog').dialog('open');

	// Add "selected" class to the help link.
	$(helpLink).addClass('selected');

	//	// Load the help page specified in the link.
//	$('#helpContent').attr('innerHTML', $(helpLink).attr('innerHTML'));
	// Load the help page specified in the link.
	var contentUrl = $(helpLink).attr('href');
	$('#helpContent').load(contentUrl);
	$('#helpContent').scrollTop(0);
	$('#helpContent').scrollTop(0);

	return false;
}

function loadWhyNotInfo(cardID) {
	var helpName = '';
	var reason = '';

	switch (cardID) {
		case "cctv":
			helpName = 'info-product-family-cctv';
			break;
		case "zoom":
			helpName = "";
			break;
		case "fixed":
			helpName = "info-product-family-fixed";
			break;
		case "large":
			helpName = "info-product-family-large";
			break;
		case "telecentric":
			helpName = "info-product-family-telecentric";
			break;
		case "fluorescence":
			helpName = "info-product-family-fluorescence";
			break;
	}

	for (var i = 0; i < productFamilies.length; i++) {
		if (productFamilies[i][PRODUCT_FAMILY_ARRAY_CARD_ID] == cardID) {
			reason = productFamilies[i][PRODUCT_FAMILY_ARRAY_WHY_NOT];
			break;
		}
	}

	if (reason != '') 
		$('#whyNotReason').attr('innerHTML', 'Reason(s):<ul>' + reason + '</ul>');
	else
		$('#whyNotReason').attr('innerHTML', '');

	if (helpName != '') {
		$('#whyNotDialog').attr('name', helpName);
		$('#whyNotHelp').css('display', '');
	} else {
		$('#whyNotHelp').css('display', 'none');
	}
}


function addReason(familyID, reason) {
	productFamilies[familyID][PRODUCT_FAMILY_ARRAY_WHY_NOT] += reason;
}

function clearReason(familyID) {
	productFamilies[familyID][PRODUCT_FAMILY_ARRAY_WHY_NOT] = '';
}

function getCameraMountName(cameraMountCode) {
	switch (cameraMountCode) {
		case '':
			//Do Nothing
			break;
		case 'E':
			return 'ENG-Mount'; break;
		case 'Z':
			return 'CS-Mount'; break;
		case 'S':
			return 'SLR-Mount'; break;
		case 'M':
			return 'M72-Thread'; break;
		default:
			return cameraMountCode + '-Mount'; break;
	}
}

function getFeatureName(featureCode) {
	switch (featureCode) {
		case 'feature-coax':
			return 'Coaxial Illumination'; return;
		case 'feature-externalCoax':
			return 'External Coax'; return;
		case 'feature-ringLight':
			return 'Ring Light'; return;
		case 'feature-internalFocus': 
			return 'Internal Focusing'; return;
		case 'feature-polarization':
			return 'Polarization'; return;
		case 'feature-motorization':
			return 'Motorization'; return;
		case 'feature-fluorescence':
			return 'Fluorescence'; return;
		case 'feature-telecentric':
			return 'Telecentric'; return;
		case 'feature-dic':
			return 'DIC'; return;
		case 'feature-aperture':
			return 'Aperture Control'; return;
		case 'feature-detentZoom':
			return 'Detented Zoom'; return;
		case 'feature-lowLight':
			return 'Low Light Video'; return;
		case 'feature-nir':
			return 'NIR (Near Infrared'; return;
	}
}
