//*******************************************************************************
//
// Hpyertac Configurator
//
// This file contains javascript functions called by FRAME_MODULES.HTM
// 
// Modification History:
//
// 7/12/04 : Creation by T.DUBUIS
//
//*******************************************************************************


//**********************************************************
// Returns true if upper frame loaded is modules frame
//**********************************************************
function CurrentFrameIsModules ()
{
	if ( parent.wizard_frame.document.forms[0].next_frame.value == "frame_frame.asp" )
		return(true);
	else
		return(false);
}

//**********************************************************
// Returns true if upper frame loaded is modules frame
//**********************************************************
function clear_combination ()
{

if ( ! CurrentFrameIsModules() )
{
	window.status = "Button has no effect within current context";
	return;
}

	parent.ctrl_board.ctrl_board.pitches.value = "0";
	parent.ctrl_board.ctrl_board.modules_combination.value = "";
	parent.ctrl_board.ctrl_board.nb_modules.value = "1";
	check_modules_combination();

}



//**********************************************************
// Called when frame "modules" is loaded
//**********************************************************
function init_frame_modules ()
{
	restore_memorised_values();
	check_modules_combination();

}

//**********************************************************
// Increment or decrement nb modules values
//**********************************************************
function inc_nb_mods ( inc_value )
{

if ( ! CurrentFrameIsModules() )
{
	window.status = "Button has no effect within current context";
	return;
}

	var nb_modules = convInt(parent.ctrl_board.ctrl_board.nb_modules.value);

	nb_modules += convInt(inc_value);

	if ( nb_modules < 1 ){ nb_modules = 1; }

	parent.ctrl_board.ctrl_board.nb_modules.value= nb_modules;


}

//**********************************************************
// Add selected module to combination
//**********************************************************
function add_modules ( )
{

if ( ! CurrentFrameIsModules() )
{
	window.status = "Button has no effect within current context";
	return;
}


	var nb_modules = convInt(parent.ctrl_board.ctrl_board.nb_modules.value);
	var pitches = convInt(parent.ctrl_board.ctrl_board.pitches.value);
	var modules_combination = parent.ctrl_board.ctrl_board.modules_combination.value;

	if ( nb_modules < 1 || nb_modules > 300 ){
		alert("ERROR: Number of modules out of range (min=1 and max=300) " );
		parent.ctrl_board.ctrl_board.nb_modules.value= "1";
		return;
	}

	var selected_module = getHtmlEltValue("modules","MODULE","wizard_frame");
	if( selected_module == "" ){
		alert("ERROR: please select a module" );
		return;
	}

	if ( parent.ctrl_board.modules_width[selected_module] == null )
	{
		alert("ERROR: Unknown Module type:"+selected_module );
		return;
	}

	pitches +=  convInt(parent.ctrl_board.modules_width[selected_module])*nb_modules;
	parent.ctrl_board.ctrl_board.pitches.value = pitches;
	modules_combination += "/" + nb_modules + selected_module;
	parent.ctrl_board.ctrl_board.modules_combination.value = modules_combination;
	check_modules_combination();

}
//**********************************************************
// Called when modules combination field is modified manualy
// It checks the syntax, and update pitches field
// combination looks like this: "/5PFR/10TFD/"
//**********************************************************
function check_modules_combination()
{
	var modules_combination = parent.ctrl_board.ctrl_board.modules_combination.value;
	var combination_array = modules_combination.split(/\//);
	var pitches = 0;
	var new_combination = "";
	var error_detected = false;


	modules_combination = modules_combination.toUpperCase();
	if ( modules_combination != "" )
	{

		for ( var i = 0; i< combination_array.length; i++)
		{
			// An error may have been already detected ie: **34FGH**
			if ( combination_array[i].match(/^\*\*/) )
			{
				alert("ERROR: Please fix module combination:"+combination_array[i]+"(Ex: 12PFD)");
				new_combination += "/"+combination_array[i];
				error_detected = true;
			}
			else
			{
				// Extract digits
				var nb = combination_array[i].match(/^(\d+)(.+)$/);
				if ( ! nb ) 
				{
					alert("ERROR: Bad syntax in module combination:"+combination_array[i]+"(Ex: 12PFD)");
					new_combination += "/**"+combination_array[i]+"**";
					error_detected = true;
				}
				else
				{
					// Checks Module desination
					if ( parent.ctrl_board.modules_width[nb[2]] == null )
					{
						alert("ERROR: Unknown Module type:"+nb[2]+" in combination:"+combination_array[i] );           
						new_combination += "/**"+combination_array[i]+"**";
						error_detected = true;
					}
					else
					{
						pitches += convInt(nb[1])*parent.ctrl_board.modules_width[nb[2]];
						new_combination += "/"+combination_array[i];
					}
				}
			}
		}
		if  (error_detected)
		{
			parent.wizard_frame.document.forms[0].frame_status.value = "Bad modules combination";
		}
		else
		{
			parent.wizard_frame.document.forms[0].frame_status.value = "OK";
		}
	}
	else
	{
		parent.wizard_frame.document.forms[0].frame_status.value = "Add Modules";
	}

	// Check pitches is an integer
	if ( (pitches - parseInt(pitches)) != 0 ) {
		parent.wizard_frame.document.forms[0].frame_status.value = "ERROR: Number of pitches must be an Integer. Change number of modules";
	}

	parent.ctrl_board.ctrl_board.modules_combination.value = new_combination;
	parent.ctrl_board.ctrl_board.pitches.value = pitches;


	return(!error_detected);

}

//**********************************************************
// Called when frame "frame definition" is loaded
// It create a select list with frames that are long
// enough given the module combination.
//**********************************************************
function init_frame_frame()
{
	// retrieve values from ctrl_board frame
	var modules_combination = parent.ctrl_board.ctrl_board.modules_combination.value;
	var pitches = convInt(parent.ctrl_board.ctrl_board.pitches.value);

	// Save current selected option:
	var current_ref = getHtmlEltValue("frames_form","frame_select","wizard_frame");

	// Create pointer to Option List in HTML page
	eval( "var select_obj = parent.wizard_frame.frames_form.frame_select");
	if ( select_obj == null )
	{
		alert(" init_frame_frame():Can not Initialize to HTML select object");
		return(false)
	}
	
	


	var item_count = 0;
	var current_index = 0;
	var fr_type_selected = "";
	var short_frame_list = parent.ctrl_board.ctrl_board.short_frame_list.checked;
	
	
	select_obj.options[item_count].text = "-SELECT-";
	select_obj.options[item_count++].value = "";

	// Go thru the array of frames, and keep only those with enough pitches
	for ( var j = 0 ; j < parent.ctrl_board.frames_designation.length ; j ++ )
	{
		// Modified on 31/05/06: Makes the list shorter : Keep only the first  that suit
		var cr_fr_designation = parent.ctrl_board.frames_designation[j];
		var cr_fr_pitches = parent.ctrl_board.frames_pitches[cr_fr_designation];
		// Designation looks like HJY_23 --> extract type="HJY"
		var cr_fr_type = cr_fr_designation.substring(0,cr_fr_designation.indexOf("_"));
		
		if ( cr_fr_pitches >= pitches && ( fr_type_selected != cr_fr_type || ! short_frame_list ) )
		{
			// Only this frame will be kept in the list 
			fr_type_selected = cr_fr_type;
			
			if ( item_count >= select_obj.options.length )
			{
				select_obj.options[item_count] = new Option(parent.ctrl_board.frames_designation[j], parent.ctrl_board.frames_designation[j], false, false);
			}
			else
			{
				select_obj.options[item_count].text = parent.ctrl_board.frames_designation[j];
				select_obj.options[item_count].value = parent.ctrl_board.frames_designation[j];
			}
			
			item_count ++;
		}
	}

	select_obj.options.length = item_count;
	
	if ( item_count == 1 )
	{
		alert("ERRROR: Could not find Frames that can suit the Modules combination:"+pitches )
		select_obj.selectedIndex = 0;
	}
	else 	if ( item_count == 2 )
	{
		// In case of only one reference available, it is selected.
		//alert("ATTENTION: Après recherche dans les compatibilités,\nIl n'y a qu'une seule reference disponible pour l'option :["+mod_option.toUpperCase()+"], Elle est validée." )
		select_obj.selectedIndex = 1;
	}         

	select_frame();

	return(true);

}

//**********************************************************
// Called when user select PLug or Receptacle button
// If user as selected a frame: OK
//**********************************************************
function select_plug_recept()
{
	// get value of selected frame
	var selected_frame = getHtmlEltValue("frames_form","frame_select","wizard_frame");

	if  ( parent.ctrl_board.frames_pitches[selected_frame] == null ) {
		set_frame_status("Please select a frame ");
	}
	else {
		set_frame_status("OK");
	}
}


//**********************************************************
// Called when frame has been selected
// It shows parameters of frame, and split de Module combination
//**********************************************************
function select_frame()
{

	// get value of selected frame
	var selected_frame = getHtmlEltValue("frames_form","frame_select","wizard_frame");

	// Extract first letters ie: HB_7 --> HB
	var frame_name = selected_frame.match(/(.+)_/);

	if  ( parent.ctrl_board.frames_pitches[selected_frame] == null ) {
		// Clear all fields
		setHtmlEltValue("frames_form","pitches","","wizard_frame");
		setHtmlEltValue("frames_form","rows","","wizard_frame");
		setHtmlEltValue("frames_form","areas","","wizard_frame");
		setHtmlEltValue("frames_form","frame_length","","wizard_frame");
		setHtmlEltValue("frames_form","remark","","wizard_frame");
		//       parent.wizard_frame.document.images[1].src="./images/frame_select.gif";
		parent.wizard_frame.document.images[0].src="./images/frame_select.gif";
	}
	else {
		setHtmlEltValue("frames_form","pitches",parent.ctrl_board.frames_pitches[selected_frame],"wizard_frame");
		setHtmlEltValue("frames_form","areas",parent.ctrl_board.frames_areas[selected_frame],"wizard_frame");
		setHtmlEltValue("frames_form","rows",parent.ctrl_board.frames_rows[selected_frame],"wizard_frame");
		setHtmlEltValue("frames_form","frame_length",parent.ctrl_board.frames_length[selected_frame],"wizard_frame");
		setHtmlEltValue("frames_form","remark",parent.ctrl_board.frames_remark[selected_frame],"wizard_frame");
		//       parent.wizard_frame.document.images[1].src="./images/frame_"+frame_name[1]+".gif";
		parent.wizard_frame.document.images[0].src="./images/frame_"+frame_name[1]+".jpg";

		// Enable disable plug/Recpetacle button
		var frames_form = parent.wizard_frame.document.frames_form;
		frames_form.plug_receptacle[0].checked = false;
		if ( parent.ctrl_board.frames_plug_recept[selected_frame].match(/P/) )
		{
			frames_form.plug_receptacle[0].disabled = false;
		}
		else {
			frames_form.plug_receptacle[0].disabled = true;
		}
		
		frames_form.plug_receptacle[1].checked = false;
		if ( parent.ctrl_board.frames_plug_recept[selected_frame].match(/R/) )
		{
			frames_form.plug_receptacle[1].disabled = false;
		}
		else {
			frames_form.plug_receptacle[1].disabled = true;
		} 

	}

	// Compute combinations for each areas of the plug/receptacle
	if ( fill_areas() )
	{
		if  ( parent.ctrl_board.frames_pitches[selected_frame] == null ) {
			set_frame_status("Please select a frame ");
		}
		else {
			set_frame_status("Please select Plug or Receptacle");
		}
	}
	else
	set_frame_status("Please select a frame ");
}

//**********************************************************
// Split the combination in each area
//**********************************************************
function fill_areas()
{

	if ( !check_modules_combination() ) {
		return(false);
	}

	// get value of selected frame
	var selected_frame = getHtmlEltValue("frames_form","frame_select","wizard_frame");

	// Clear all fields
	setHtmlEltValue("frames_form","R1G_FILLRATE","","wizard_frame");
	setHtmlEltValue("frames_form","R1G_COMBINATION","","wizard_frame");
	setHtmlEltValue("frames_form","R2G_FILLRATE","","wizard_frame");
	setHtmlEltValue("frames_form","R2G_COMBINATION","","wizard_frame");
	setHtmlEltValue("frames_form","R1D_FILLRATE","","wizard_frame");
	setHtmlEltValue("frames_form","R1D_COMBINATION","","wizard_frame");
	setHtmlEltValue("frames_form","R2D_FILLRATE","","wizard_frame");
	setHtmlEltValue("frames_form","R2D_COMBINATION","","wizard_frame");

	// Case no frame has been selected
	if  ( parent.ctrl_board.frames_pitches[selected_frame] == null ) {
		// alert("Select af frame");
		return(false);
	}

	var nb_rows = convInt(getHtmlEltValue("frames_form","rows","wizard_frame"));
	var nb_areas = convInt(getHtmlEltValue("frames_form","areas","wizard_frame"));
	var nb_pitches = convInt(getHtmlEltValue("frames_form","pitches","wizard_frame"));

	var modules_combination = getHtmlEltValue("ctrl_board","modules_combination","ctrl_board");
	var combination_array = modules_combination.split(/\//);
	var area_idx = 0;
	var area_length = nb_pitches/nb_areas;

	var area_combination = new Array();
	var area_pitches = new Array();


	// Arrays init
	for ( var i = 0; i < 4; i++)
	{
		area_pitches[i] = parseFloat(0);
		area_combination[i] = "";
	}   


	// Go thru combination and fill all areas
	for ( var i = 0; i< combination_array.length; i++)
	{
		// Extract digits, and module name
		var nb = combination_array[i].match(/^(\d+)(.+)$/);
		var module_name =  nb[2];
		var module_count = convInt(nb[1]);
		// Warning Module width may be no integer !! (2.5 pitches for instance)
		var module_width = parseFloat(parent.ctrl_board.modules_width[module_name]);

		
		var current_area = area_idx;
		for ( var j = 0 ; j<module_count ; j++)
		{
			if ( parseFloat(area_length)-(parseFloat(area_pitches[area_idx])+module_width) >= 0  )
			{
				// Continue with the same area
				area_pitches[area_idx] = parseFloat(area_pitches[area_idx])+module_width;
			}
			else
			{
				// Current area is not necessarely full but can not accept current module
				// Continue with next area
				if ( j > 0 )
				{
					area_combination[area_idx] += "/"+j+module_name;
					module_count -= j;
					j=0
				}

				// Before closing current area, Check current area has an integer number of modules
				if ( (area_pitches[area_idx] - parseInt(area_pitches[area_idx])) != 0 )
				{
					alert("ERROR: This module combination can not be used with this frame (Because of half pitches modules)");
					
					// Reset Frame selection
					setHtmlEltValue("frames_form","frame_select","-SELECT-","wizard_frame");
					//parent.wizard_frame.frames_form.frame_select.selected_index=0;
					return(false);		
				}
				
				// Continue with next area
				area_idx++;

				// make sure we can go to the next one ...
				if ( area_idx >= nb_areas )
				{
					alert("ERROR: This module combination can not be used with this frame.\nCombination could not be split between areas.");
					
					// Reset Frame selection
					setHtmlEltValue("frames_form","frame_select","-SELECT-","wizard_frame");
					//parent.wizard_frame.frames_form.frame_select.selected_index=0;
					return(false);		
				}
				

				area_pitches[area_idx] = module_width;
			}
		}

		area_combination[area_idx] += "/"+j+module_name;  

	}



	// Checks if areas are completed
	var nb_ph_added = 0;
	
	
	for ( var i = 0; i< nb_areas; i++)
	{        
		var fullfill_ok = false;
		if ( i == 0 )
		{
			if ( (area_pitches[i] < area_length) )
			{
				fullfill_ok = true;
			}             
		}

		// Second area: may be right for one row, right for 4 areas
		if ( i == 1 && (nb_rows == 1 || nb_areas == 4) )
		{
			if ( (area_pitches[i] < area_length)  )
			{
				fullfill_ok = true;
			}             
		}

		// Second area: may be left if 2 rows and only 2 areas
		if ( i == 1 && nb_rows == 2 && nb_areas == 2)
		{
			if ( (area_pitches[i] < area_length) )
			{
				fullfill_ok = true;
			}             
		}

		// For third and forth area it must be case 4 areas
		if ( i == 2 )
		{
			if ( (area_pitches[i] < area_length)  )
			{
				fullfill_ok = true;
			}             
		}

		if ( i == 3 )
		{
			if ( (area_pitches[i] < area_length) )
			{
				fullfill_ok = true;
			}             
		}

		if ( fullfill_ok )
		{
			nb_ph_added += convInt(area_length-area_pitches[i]);
			area_combination[i] += "/" + convInt(area_length-area_pitches[i]) + "PH"; 
			area_pitches[i]= area_length;
		}
		
	}

	if ( nb_ph_added > 0 ) 
		alert("WARNING: ["+nb_ph_added+"] empty modules (PH) were added to fullfill the areas");
		
	// Display values in right fields
	for ( var i = 0; i< nb_areas; i++)
	{
		if ( i == 0 )
		{
			setHtmlEltValue("frames_form","R1G_FILLRATE",area_pitches[i]+"/"+area_length,"wizard_frame");
			setHtmlEltValue("frames_form","R1G_COMBINATION",area_combination[i],"wizard_frame");
		}

		// Second area: may be right for one row
		if ( i == 1 && (nb_rows == 1 || nb_areas == 4) )
		{
			setHtmlEltValue("frames_form","R1D_FILLRATE",area_pitches[i]+"/"+area_length,"wizard_frame");
			setHtmlEltValue("frames_form","R1D_COMBINATION",area_combination[i],"wizard_frame");
		}

		// Second area: may be left if 2 rows and only 2 areas
		if ( i == 1 && nb_rows == 2 && nb_areas == 2)
		{
			setHtmlEltValue("frames_form","R2G_FILLRATE",area_pitches[i]+"/"+area_length,"wizard_frame");
			setHtmlEltValue("frames_form","R2G_COMBINATION",area_combination[i],"wizard_frame");
		}

		// For third and forth area it must be case 4 areas
		if ( i == 2 )
		{
			setHtmlEltValue("frames_form","R2G_FILLRATE",area_pitches[i]+"/"+area_length,"wizard_frame");
			setHtmlEltValue("frames_form","R2G_COMBINATION",area_combination[i],"wizard_frame");
		}

		if ( i == 3 )
		{
			setHtmlEltValue("frames_form","R2D_FILLRATE",area_pitches[i]+"/"+area_length,"wizard_frame");
			setHtmlEltValue("frames_form","R2D_COMBINATION",area_combination[i],"wizard_frame");
		}

	}

	return(true);


}

