// JavaScript Document

// Some controls...
// This script expects an array of options called []
// ['specific'] = 0 or 1
// ['vehicle']  = 0 or 1

var spidfrmnames = new Array();
var partnames = new Array();
var timers = new Array();
var alog   = '';

function AL(txt)
{
	var currentTime = new Date();
	alog += currentTime.getTime() + ': ' + txt + "\n";
}

function SL()
{
	AL('SL Called');
	alert(alog);
	alog = '';
}

function KeyUp(i)
{
	AL('KeyUp('+i+')');
	// Start a countdown to when the lookup will begin. If they press another
	// key before the countdown completes, reset the countdown again.

	if (timers[i] != '')
	{
		// Already is a timer in operation for this part - reset it
		AL("Clearing timer " + i);
		clearTimeout(timers[i]);
	}
	else
	{
		AL("Time " + i + " is already clear");
	}
	
	// Regardless, start a new one now? Only if the value in the box has changed since we last
	// recorded it surely
	try 
	{
		pn = document.getElementById('part'+i+'name').value;
		if (pn != partnames[i])
		{
			AL("Setting timeout " + i);
			timers[i] = setTimeout('gotTimeout('+i+');',500);
		}
	}
	catch (err)
	{
		AL("Caught this - " + err);
	}
}

function gotTimeout(i)
{
	AL('gotTimeout('+i+')');
	timers[i] = '';
	CheckName(i);
}

function CheckName(i)
{
	AL('CheckName('+i+')');

	try 
	{
		pno = document.getElementById('part'+i+'name');
	
		// First see if it has changed. If it has, we need to re-populate the suggestion box
		testvalue = trim(pno.value);
		if (testvalue != partnames[i])
		{
			// It's changed! Record what it is now
			partnames[i] = pno.value;
			
			numsuggestions = 0;
			
			// Populate the suggestion box?
			if (testvalue != '') // must have at least one letter hey!
			{
				// Any specific or specific aka we recognise in the name?
				// If so, strip it out and set that as the selected option
				// in the specific option dropdown box - visible or not
				
				// We want a FULL match, and then a space otherwise we aint calling it a match
				
				// Also, we may find a match, but there may be a longer match - we should
				// always go for the longer one
			
				// Repopulate the suggestion box now
				numsuggestions = SetSuggestions(i,testvalue);
			}
		}
		
		// If it's blank, ensure both suggestions and cats are hidden
		if (testvalue == '')
		{
			he('trpart'+i+'suggestions');
			
			// Also hide the bit offering a link
			if (ploptions['isdealer'])
			{
				he('trpart'+i+'cfmatchmsg');
			}
		}
		else if  (numsuggestions == 0)
		{
			if (ploptions['showallifnomatch'])
			{
				// Load up ALL suggestions then, and show them...
				SetSuggestions(i,'');
				se('trpart'+i+'suggestions');
				// Also show the bit offering a link
				if (ploptions['isdealer'])
				{
					se('trpart'+i+'cfmatchmsg');
				}
			}
			else
			{
				he('trpart'+i+'suggestions');
				// Also hide the bit offering a link
				if (ploptions['isdealer'])
				{
					he('trpart'+i+'cfmatchmsg');
				}
			}
		}
		else
		{
			if (ploptions['dss'] != 1)
			{
				se('trpart'+i+'suggestions');
				// Also show the bit offering a link
				if (ploptions['isdealer'])
				{
					se('trpart'+i+'cfmatchmsg');
				}
			}
		}
	
		if (ploptions['specific'])
		{
			// hide the specific, AND set its value to un-selected!
			try
			{
				he('trpart'+i+'specific');
				spo = document.getElementById('part'+i+'specific');
				spo.selectedIndex = 0;
				try
				{
					psoc = document.getElementById('PSOC'+i);
					psoc.value = 0;
				}
				catch (err)
				{
					//alert(err);
				}
			}
			catch (err)
			{
			}
		}
	}
	catch (err)
	{
	}
}

function SetSuggestions(i,value)
{
	AL('SetSuggestions('+i+','+value+')');

	try 
	{
		// Keep track of which prods we've already added
		donepids = new Array();
		numselections = 0;
		
		// Remove all items in the select box first
		sgo = document.getElementById('part'+i+'suggestion');
		while (sgo.options.length > 0) { sgo.remove(0); }
		
		// And as we're doing this, we MUST remove all options from the specifics
		// AND hide that section - DID TRY THIS BUT IT STOPS THE SPECIFICS FROM SHOWING
		//he('part'+i+'specific');
		
		if (value == '')
		{
		}
		else
		{
			// Read back the values off the server
			data = Ajax('/ajax/suggestions.php?q='+testvalue);
			if (data != '')
			{
				// Parse the data
				pts  = data.split('$$$');
				vals = pts[0].split('|');
				spidfrmnames[i] = pts[1];
				for (p = 0; p<vals.length; p+=2)
				{
					// Add an slct option now. Is it the selected option?
					if ((vals[p] > 0) && (vals[p+1] != ''))
					{
						AddSlctOption(sgo,vals[p],vals[p+1]);
						numselections++;
					}
				}
			}
			
			// If num selections is zero and ploptions[isdealer], show the no matches link
			if ((numselections <= 0) && ploptions['isdealer'])
			{
				AL('Showing the no match message...');
				se('part'+i+'nomatchmsg');
			}
			else
			{
				AL('Num selections more than zero it is: ' + numselections);
				if (ploptions['isdealer'])
				{
					// Hide the top one, show the bottom one...
					AL('Hiding the no match message...');
					he('part'+i+'nomatchmsg');
				}
			}
		}
	}
	catch (err)
	{
		numselections = 0;
	}
	
	return numselections;
}

function CheckSuggestion(i)
{
	AL('CheckSuggestion('+i+')');
	
	try
	{
		sgo = document.getElementById('part'+i+'suggestion');
		
		// A suggestion selected?
		if ((sgo[sgo.selectedIndex].value != '-') && (sgo[sgo.selectedIndex].value != ''))
		{
			// Make sure the specific row is showing. First, populate it appropriately...
			if (ploptions['specific'])
			{
				numspecifics = SetSpecifics(i,sgo[sgo.selectedIndex].value);
				if (numspecifics > 0)
				{
					se('trpart'+i+'specific');
					CheckSpecific(i);
					
					// If we can find the object on the page which is the (3) next to
					// the vehicle selector, then ensure now that it IS showing (3)
					// but only need to do this if fsv is set as an option
					if (ploptions['fsv'])
					{
						try
						{
							icon3 = document.getElementById('icon3green');
							if (icon3)
							{
								icon3.src = "../../mgimages/icon3green.gif";
							}
							icon4 = document.getElementById('icon4green');
							if (icon4)
							{
								icon4.src = "../../mgimages/icon4green.gif";
							}
						}
						catch (err) 
						{
						}
					}
				}
				else if (ploptions['vehicle'])
				{
					se('trpart'+i+'vehicle');
					
					AL('In Check suggestion, about to test fsv');
					
					if (ploptions['fsv'])
					{
						AL('In Check suggestion, showing the vehicles now...');		
						
						// Make sure icon3green is showing a 2! there are no specifics!!
						if (ploptions['fsv'])
						{
							try
							{
								icon3 = document.getElementById('icon3green');
								if (icon3)
								{
									icon3.src = "../../mgimages/icon2green.gif";
								}
								icon4 = document.getElementById('icon4green');
								if (icon4)
								{
									icon4.src = "../../mgimages/icon3green.gif";
								}
							}
							catch (err) 
							{
							}
						}
						
						se('trvehiclemodels');
					}
				}
			}
			he('trpart'+i+'suggestions');
			// Also hide the bit offering a link
			if (ploptions['isdealer'])
			{
				he('trpart'+i+'cfmatchmsg');
			}
			pno = document.getElementById('part'+i+'name');
			pno.value = sgo[sgo.selectedIndex].text;
			partnames[i] = sgo[sgo.selectedIndex].text;
		}
	}
	catch (err) 
	{ 
		AL('Check Suggestion caught this ' + err); 
	}
}

// These funcs used when pre-loading the form with data...
function SetSuggestionById(i,val)
{
	AL('SetSuggestionById('+i+','+val+')');
	try 
	{
		sgo = document.getElementById('part'+i+'suggestion');
		
		for (j=0; j < sgo.length; j++)
		{
			// This has to work for numbers, and texts because it
			// sometimes looks at lists, sometimes at select boxes
			if (sgo[j].value.toLowerCase() == val)
			{
				sgo.selectedIndex = j;
				CheckSuggestion(i);
				break;
			}
		}
	}
	catch (err)
	{
		AL("Got error in SetSuggestionById " + err);
	}
}
function SetSuggestionByText(i,val)
{
	AL('SetSuggestionById('+i+','+val+')');

	try 
	{
		sgo = document.getElementById('part'+i+'suggestion');
		
		for (j=0; j < sgo.length; j++)
		{
			// This has to work for numbers, and texts because it
			// sometimes looks at lists, sometimes at select boxes
			if ((sgo[j].value.toLowerCase() == val.toLowerCase()) || (sgo[j].text.toLowerCase() == val.toLowerCase()))
			{
				AL("got this far again!");
				sgo.selectedIndex = j;
				CheckSuggestion(i);
				break;
			}
		}
	}
	catch (err)
	{
		AL("Got error in SetSuggestionByText " + err);
	}
}


// This func used when pre-loading the form with data...

function SetSpecific(i,val)
{
	AL('SetSpecific('+i+')');

	try 
	{
		spo = document.getElementById('part'+i+'specific');
		for (j=0; j < spo.length; j++)
		{
			if (spo[j].value == val)
			{
				spo.selectedIndex = j;
				CheckSpecific(i);
				AL('Back from CheckSpecific');
				break;
			}
		}
	}
	catch (err)
	{
	}
}

function CheckSpecific(i)
{
	AL('CheckSpecific('+i+') started...');

	try
	{
		// When the suggestions blurs, do we have a selection any longer?
		// if fsv is true then the vehicle section is forced to show
		// this is used when a dealer already has a default vehicle option
		
		// Take care in the situation where there are NO specifics!
		if (ploptions['vehicle'] && ploptions['specific'])
		{
			AL('In CheckSpecific('+i+') Getting spo...');
	
			spo = document.getElementById('part'+i+'specific');
	
			AL('In CheckSpecific('+i+') Got spo...');
	
			if (spo)
			{
				AL('In CheckSpecific('+i+') spo seems valid');
				AL('In CheckSpecific('+i+') spo has value ' + spo[spo.selectedIndex].value);
				AL('In CheckSpecific('+i+') spo has length ' + spo.length);
				
				if  (
						(
							(spo[spo.selectedIndex].value != '-') 
							&& 
							(spo[spo.selectedIndex].value != '')
						)
						||
						(
							spo.length == 0
						)
						||
						(
							(spo.length == 1)
							&&
							(spo[spo.selectedIndex].value == '-')
						)					
					)
				{
					AL('In CheckSpecific('+i+') Note 1.1');
					
					// Show the vehicle row then
					se('trpart'+i+'vehicle');
		
					AL('In CheckSpecific('+i+') Note 1.2');
					
					// If fsv is set then also show the vehicle models now
					if (ploptions['fsv'])
					{
						AL('In CheckSpecific('+i+') Note 2.1');
						se('trvehiclemodels');
						//AL('In CheckSpecific('+i+') Note 2.2');
						//se('trvehiclemodels');
					}
					
					AL('In CheckSpecific('+i+') Note 2.3');
				}
				else
				{
					AL('In CheckSpecific('+i+') Note 3.0');
		
					he('trpart'+i+'vehicle');
					he('trvehiclemodels');
				}
			}
			else
			{
				AL('In CheckSpecific('+i+') But spo seems to be invalid!');
			}
		}
		else
		{
			AL('In CheckSpecific('+i+') No ploptions set for this.');
		}
	}
	catch (err)
	{
	}
}

function SetSpecifics(i, prodid)
{
	AL('SetSpecifics('+i+')');

	try 
	{
		// Go through the entire sp array and add ALL items which have this prod ID
		// value is the specific ID
		// Remove all items in the select box first
		spo = document.getElementById('part'+i+'specific');
		while (spo.options.length > 1) { spo.remove(1); }
		
		preslctidx = -1; curridx = 1; numspecifics = 0;
		
		// Do an ajax call to get the specifics...
		if (ploptions['isusa'])
		{
			data = Ajax('/ajax/specifics.php?q='+prodid+'&usa=1');
		}
		else
		{
			data = Ajax('/ajax/specifics.php?q='+prodid);
		}
		spids = data.split('|');
		
		for (spi=0; spi < spids.length; spi+=2)
		{
			if ((spids[spi] > 0) && (spids[spi+1] != ''))
			{
				// Add this one then
				AddSlctOption(spo, spids[spi], spids[spi+1]);
				if (spids[spi] == spidfrmnames[i])
				{
					preslctidx = curridx;
				}
				curridx++;
				numspecifics++;
			}
		}
		
		try
		{
			psoc = document.getElementById("PSOC"+i);
			if (psoc)
			{
				psoc.value = numspecifics;
			}
		}
		catch (err)
		{
		}
		
		// Got one pre-specified by name?
		if (preslctidx != -1)
		{
			spo.selectedIndex = preslctidx;
			
			// We've now pre-selected a subcat. So, we should NOW show the vehicle selector
			if (ploptions['vehicle'])
			{
				se('trpart'+i+'vehicle');
			}
		}
	}
	catch (err)
	{
		numspecifics = 0;
	}
	
	// No specifics? Then hide this
	return numspecifics;
}


