// borrowed directly from Alpha (KH)

// leds and meanings array output via script
var alternates=Array();
var flash=Array();
	
function closealtdiv() {document.getElementById('alternatediv').style.display='none';}
function altern8(img,color,pairing)
{
if (leds[img][3]=='')
  {
  leds[img][3]=pairing;
  leds[pairing][3]=img;
  document.getElementById('led' + img).src="/custom/images/leds/" + color + "f" + "_offon.gif";
  }
else
  {
  document.getElementById('led' + img).src="/custom/images/leds/" + color + "f" + "_onoff.gif";
  leds[img][3]='';
  leds[pairing][3]='';
  }
rebuild();
}
	  
function changeLED(img,color,state)
{
if (state=='f')
  {
  if (leds[img][1]!='f')
    {
    leds[img][1]=state;
    // clear any alt states
    for (ref in leds)
      {
	  if (leds[ref][1]=='f') {document.getElementById('led' + ref).src="/custom/images/leds/" + leds[ref][2] + "f" + "_onoff.gif";}
	  leds[ref][3]='';
	  }
	if (flash.length>0)
  	  {
	  var localflash=flash.slice();
	  var p=localflash.pop();
	  document.getElementById('alt' + p).innerHTML='';
	  document.getElementById('alt' + img).innerHTML='<input type="checkbox" id="altcb' + img + '" onclick="altern8(\'' + img + '\',\'' + color + '\',\'' + p + '\')" />tick box if this light is alternating with light ' + leds[p][0];
	  }
	flash.push(img);
	}
  }
else
  {
  leds[img][1]=state;
  if (detectItem(flash,img))
    {		  
    leds[img][3]='';
	var localflash=flash.slice();
	document.getElementById('alt' + localflash.pop()).innerHTML='';
	removeItem(flash,img);
	if (flash.length>1)
	  {
	  var localflash=flash.slice();
	  var p=localflash.pop(); var pp=localflash.pop();
	  document.getElementById('alt' + p).innerHTML='<input type="checkbox" id="altcb' + p + '" onclick="altern8(\'' + p + '\',\'' + color + '\')" />tick box if this light is alternating with light ' + leds[pp][0];
	  }
    }
	document.getElementById('alt' + img).innerHTML='';
  }
img=document.getElementById('led' + img);
img.src="/custom/images/leds/" + color + state + (state=='f'?'_onoff':'') + ".gif";
rebuild();
}
	  
function rebuild()
{
var message='';
var activeleds=Array();
var alternatestemp='';
var matrix=Array();
for (ref in leds)
  {
  if (leds[ref][1]!='')
    {
	if (leds[ref][3]=='') {activeleds.push(ref + leds[ref][1]);}
	else {alternatestemp+=(alternatestemp?',':'') + ref + leds[ref][1];}
	}
  }		
// create matrix of all possible permuations and combinations of active leds
var combinations=Array();
var permutations=Array();
if (activeleds.length>0)
  {
  combinations=combine(activeleds);
  for(r=0;r<combinations.length;r++)
    {
	if (combinations[r].toString().match(','))
  	  {
	  permutations=permute(combinations[r].toString().split(','));
	  for(y=0;y<permutations.length;y++) {matrix.push(permutations[y]);}
	  }
	else
   	  { 
	  matrix.push(combinations[r]);
	  }
    permutations.length=0;
    }
  }
  
if (alternatestemp!='') {matrix.push('[' + alternatestemp + ']');}
// now search, match and remove
for (var z=matrix.length; z>=0; z--)
  {
  for(x=0;x<meanings.length;x+=3)
	{
	if (meanings[x]==matrix[z])
	  {
	  var arr=Array(); var solution='<a href=\'/?contact_us&amp;n=helpline&amp;e=' + escape('I have used the virtual control panel tool on your website and correctly matched the light indicators showing on my own boiler.\n\nModel: ' + document.getElementById('currentmodel').value + '\n\nControl panel lights status: ' + getMeaning(meanings[x]) + '\n\nPossible cause: ' + meanings[x+1] + '\n\nPlease contact me via e-mail or telephone regarding this issue') + '\' title=\'Submit an online Call Centre request form\'>Please contact the help desk</a>';
	  if (meanings[x+2]!='') {solution=meanings[x+2];}
	  message+='<li class=\'indication\'><strong>' + meanings[x+1] + '</strong> <span>(' + getMeaning(meanings[x]) + ')</span><ul><li class=\'remedy\'>' + solution + '</li></ul></li>';
	  if (matrix[z].toString().match(',')) {arr=matrix[z].toString().split(',');} else {arr.push(matrix[z]);}
      for(y=0;y<matrix.length;y++) {for(var i in arr) {if (arr[i]==matrix[y]) {matrix[y]='';}}}
	  }
    }
  }
if (!message) {if (matrix.length>0) {message='<em>no recognised indication</em>';} else {message='No lights on at all? Check your electricity supply.';} } else {message='<ul class=\'troubleshooter\'>' + message + '</ul>';}
document.getElementById('solution').innerHTML=message;
gifReload();
}

function getMeaning(ledstring)
{
var output=''; var templeds=Array();
var alternatingflag=false;
if (ledstring.match(/^\[.+\]$/)) {alternatingflag=true;}
if (ledstring.match(','))
  {
  if (alternatingflag) {t=Array(); t=ledstring.match(/^\[(.+)\]$/); ledstring=t[1];}
  templeds=ledstring.split(',');
  }
else
  {
  templeds[0]=ledstring;
  }
var temp=Array(); var ledcount=0;
for(q=0;q<templeds.length;q++)
  {
  temp=templeds[q].split('');
  switch(temp[1])
    {
	case "f":
	state="Flashing";
	break;
	case "c":
  	state="Illuminated";
	break;
	case "fs":
	state="Strobing";
	break;
	default:
	state="Off";
	}
  output+=(output?' and ':'') + (ledcount?state.toLowerCase():state) + (alternatingflag?' (alternating)':'') + ' ' + leds[temp[0]][2] + ' ' + leds[temp[0]][0];
  ledcount++;
  }
output=output + ' indicator' + (ledcount>1?'s':'');
return output;
}
	  
function gifReload()
{
// reload all gifs in an attempt to syncronise any flashing
var now = new Date(); var time = now.getTime();
for (var reference in leds) {var eimg=document.images['led' + reference]; eimg.src = eimg.src + "?" + time;}
}
	  
combine = function(a)
{
var fn = function(n, src, got, all)
  {
  if (n == 0) {if (got.length > 0) {all[all.length] = got;} return;}
  for (var j = 0; j < src.length; j++) {fn(n - 1, src.slice(j + 1), got.concat([src[j]]), all);}
  return;
  }
var all = [];
for (var i=0; i < a.length; i++)
  {
  if (a[i]!='') {fn(i, a, [], all);}
  }
all.push(a);
return all;
};

permute = function(v, m)
{
for(var p = -1, j, k, f, r, l = v.length, q = 1, i = l + 1; --i; q *= i);
for(x = [new Array(l), new Array(l), new Array(l), new Array(l)], j = q, k = l + 1, i = -1; ++i < l; x[2][i] = i, x[1][i] = x[0][i] = j /= --k);
for(r = new Array(q); ++p < q;)
for(r[p] = new Array(l), i = -1; ++i < l; !--x[1][i] && (x[1][i] = x[0][i], x[2][i] = (x[2][i] + 1) % l), r[p][i] = m ? x[3][i] : v[x[3][i]])
for(x[3][i] = x[2][i], f = 0; !f; f = !f)
for(j = i; j; x[3][--j] == x[2][i] && (x[3][i] = x[2][i] = (x[2][i] + 1) % l, f = 1));
return r;
};
	 
function detectItem(originalArray, itemToDetect)
{
var j=0;
while (j < originalArray.length) {if (originalArray[j] == itemToDetect) {return true;} else {j++;}}
return false;
}
	
function removeItem(originalArray, itemToRemove)
{
var j=0;
while (j<originalArray.length)
  {
  if (originalArray[j]==itemToRemove) {originalArray.splice(j, 1);}
  else {j++;}
  }
return originalArray;
}
