var digits = 3;        // количество цифр после запятой в результатах
var voltage1Min = 0;   // минимальное значение напряжения питания
var voltage1Max = 250; // максимальное значение напряжения питания
var voltage2Min = 0;   // минимальное значение прямого напряжения светодиода
var voltage2Max = 250; // максимальное значение прямого напряжения светодиода
var currentMin = 1;    // минимальное значение тока через светодиод
var currentMax = 500;  // максимальное значение тока через светодиод 
var ledcountMin = 2;   // минимальное значение числа диодов (для последовательного или параллельного соединений)
var ledcountMax = 32;  // максимальное значение числа диодов

var correction = Math.pow(10, digits);
var mode = 1;

var img = new Array();
img[1] =  new Image();
img[2] =  new Image();
img[3] =  new Image();
img[1].src = $('img').src;
img[2].src = 'images/img_2.gif';
img[3].src = 'images/img_3.gif';

$('ledcountCell').style.display = 'none';

// служебные функции
function $(id) { return document.getElementById(id); }
function _round(val) { return Math.round(val * correction) / correction; }
function isNumeric(sText)
{
	var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;

	for (i = 0; i < sText.length && IsNumber == true; i++) { 
		Char = sText.charAt(i);
		if (ValidChars.indexOf(Char) == -1) { IsNumber = false; }
	}
	return IsNumber;
}

function setImg(num) {
	mode = num;
	$('img').src = img[mode].src;

	if (mode == 1) { $('ledcountCell').style.display = 'none'; }
	else if (mode == 2) { $('ledcountCell').style.display = ''; }
	else if (mode == 3) { $('ledcountCell').style.display = ''; }
}

function standardResistance(resistance)
// определение стандартного значения резистора
{
	var	unit_correction = 1;
	var result = new Array();

	while (resistance > 8.2) {
		unit_correction *= 10;
		resistance /= 10;
	}
	if (resistance < 1.0) resistance = 1.0;
	else if (resistance < 1.2) resistance = 1.2;
	else if (resistance < 1.5) resistance = 1.5;
	else if (resistance < 1.8) resistance = 1.8;
	else if (resistance < 2.2) resistance = 2.2;
	else if (resistance < 2.7) resistance = 2.7;
	else if (resistance < 3.3) resistance = 3.3;
	else if (resistance < 3.9) resistance = 3.9;
	else if (resistance < 4.7) resistance = 4.7;
	else if (resistance < 5.6) resistance = 5.6;
	else if (resistance < 6.8) resistance = 6.8;
	else resistance = 8.2;

  if (unit_correction >= 1000000) {
	 result['unit'] = 'mOm';
	 unit_correction /= 1000000;
  } else if (unit_correction >= 1000) {
	 result['unit'] = 'kOm';
	 unit_correction /= 1000;
  } else result['unit'] = 'Om';

  result['resistance'] = _round(resistance * unit_correction);
  return result;
}

function validate()
// валидация полей
{
	var error = '';
	$('voltage1').value = $('voltage1').value.replace(/\s/g, '');
	$('voltage2').value = $('voltage2').value.replace(/\s/g, '');
	$('current1').value = $('current1').value.replace(/\s/g, '');
	$('ledcount').value = $('ledcount').value.replace(/\s/g, '');
	$('voltage1').value = $('voltage1').value.replace(/,/, '.');
	$('voltage2').value = $('voltage2').value.replace(/,/, '.');
	$('current1').value = $('current1').value.replace(/,/, '.');

	if (mode == 2 || mode == 3) {
		if (!isNumeric($('ledcount').value) || $('ledcount').value < ledcountMin || $('ledcount').value > ledcountMax) {
			error = 'The number of LED — number of ' + ledcountMin + ' before ' + ledcountMax + '\n' + error;
			$('ledcount').focus();
		}
	}
	if (!isNumeric($('current1').value) || $('current1').value < currentMin || $('current1').value > currentMax) {
		error = 'Through LED current number of ' + currentMin + ' to ' + currentMax + '\n' + error;
		$('current1').focus();
	}
	if (!isNumeric($('voltage2').value) || $('voltage2').value < voltage2Min || $('voltage2').value > voltage2Max) {
		error = 'Direct-LED voltage of ' + voltage2Min + '  to  ' + voltage2Max + '\n' + error;
		$('voltage2').focus();
	}
	if (!isNumeric($('voltage1').value) || $('voltage1').value < voltage1Min || $('voltage1').value > voltage1Max) {
		error = 'Power is the number of ' + voltage1Min + ' to ' + voltage1Max + '\n' + error;
		$('voltage1').focus();
	}
	if (error != '') {
		alert(error);
		return false;
	} else { return true; }
}

function calculate()
// расчет резистора
{
	if (validate()) {

	var voltage1 = eval($('voltage1').value);
	var voltage2 = eval($('voltage2').value);
	var current1 = eval($('current1').value) / 1000; // сразу в амперы
	var ledcount = Math.floor(eval($('ledcount').value));

	var resistance1;
	var resistance2;
	var rating1;
	var rating2;

	if (mode == 1)	{
	// один светодиод
		resistance1 = (voltage1 - voltage2) / current1;
		rating1 = (voltage1 - voltage2) * current1;
	} else if (mode == 2) {
	// последовательное соединение
		resistance1 = (voltage1 - voltage2 * ledcount) / current1;
		rating1 = (voltage1 - voltage2 * ledcount) * current1;
	} else if (mode == 3) {
	// параллельное соединение
		resistance1 = (voltage1 - voltage2) / current1;
		rating1 = (voltage1 - voltage2) * current1;
	}

	resistance2 = standardResistance(resistance1);
	rating2 = rating1 + voltage2 * current1;

	$('resistance1').value = _round(resistance1);
	$('resistance2').value = resistance2['resistance'];
	$('resistance2_unit').innerHTML = resistance2['unit'];
	$('rating1').value = _round(rating1);
	$('rating2').value = _round(rating2);
	
	if (resistance1 < 0) { $('result_message').innerHTML = 'Stress is not enough power to power LED. <br/> Reduce the number or check the voltage of the diode.';
	} else { $('result_message').innerHTML = '' } 
	
	} else {
		$('resistance1').value = '—';
		$('resistance2').value = '—';
		$('resistance2_unit').innerHTML = 'Ом';
		$('rating1').value = '—';
		$('rating2').value = '—';
	}
}
