var Global_Default_TPR_UUID = "ECHA-f7b3c65d-0346-49a3-818c-2af09d06f7e7"

var Global_SubstancesCount = 0;
var Global_PhaseInCount = 0;
var Global_NonPhaseInCount = 0;
var Global_SubThresholdSubstancesCount = 0;
var Global_UnselectedSubstancesCount = 0;
var Global_RegisteredSubstancesCount = 0;
var Global_AuthorisationSubstancesCount = 0;


function ResetUUIDValue()
{
	var UUIDNode =	document.getElementById("blands_uuid_input")
	UUIDNode.value = Global_Default_TPR_UUID
	var TrueStatus1 = CheckUUID(UUIDNode)
}

function IsUUIDChar(Char)
{
	return ( 
			((Char.charCodeAt(0) >= 48) && (Char.charCodeAt(0) <= 57)) ||
			((Char.charCodeAt(0) >= 65) && (Char.charCodeAt(0) <= 70)) ||
			((Char.charCodeAt(0) >= 97) && (Char.charCodeAt(0) <= 102)) 
		  );

}

function IsLeadChar(Char)
{
	var LeadChars="ECHAIUC5"
	return ( 
			(LeadChars.indexOf(Char.toUpperCase()) != -1)
		  );

}

function CheckFormUUIDNode(Node)
{
	var TrueStatus = true
	var Char="";
	var Block1 =""
	var Block2 =""
	var Block3 =""
	var Block4 =""
	var Block5 =""
	var Block6 =""
	var Overflow =""
		
	Node.value = Node.value.replace(/\s+|-/g, '')
	Node.value = TrimString(Node.value)
	if (Node.value == "") return TrueStatus
	
	for (var j=1; j<= Node.value.length; ++j)
	{
		Char = Node.value.charAt(j-1);
		
		if ((j>= 1) && (j<=4) && IsLeadChar(Char) )
		{
				Block1 += Char
		} else if (
					IsUUIDChar(Char) ||
					(Char == "-")
				)
		{
			
			if ((j>= 5) && (j<=12))
			{
				Block2 += Char
			} else if ((j>= 13) && (j<=16))
			{
				Block3 += Char
			} else if ((j>= 17) && (j<=20))
			{
				Block4 += Char
			} else if ((j>= 21) && (j<=24)) 
			{
				Block5 += Char
			} else if ((j>= 25) && (j<=36))
			{
				Block6 += Char
			} else 
			{
				Overflow += Char
			} 
			
		}
		else 
		{
			TrueStatus = false
		}
	}
	
	Block1 = UpperCase(Block1)
	Block2 = LowerCase(Block2)
	Block3 = LowerCase(Block3)
	Block4 = LowerCase(Block4)
	Block5 = LowerCase(Block5)
	Block6 = LowerCase(Block6)

	Node.value = Block1 + '-' + Block2 + '-' + Block3 + '-' + Block4 + '-' + Block5 + '-' + Block6
	Node.value = Node.value.replace(/--/g, '')
	Node.value = Node.value.replace(/-$/g, '')
	if (
		(Block1 != "ECHA") &&
		(Block1 != "IUC5") 
		)
	{
		TrueStatus = false ; return TrueStatus;
	}
	
	if (Block1.length != 4) {TrueStatus = false; return TrueStatus;}
	if (Block2.length != 8) {TrueStatus = false; return TrueStatus;}
	if (Block3.length != 4) {TrueStatus = false; return TrueStatus;}
	if (Block4.length != 4) {TrueStatus = false; return TrueStatus;}
	if (Block5.length != 4) {TrueStatus = false; return TrueStatus;}
	if (Block6.length != 12) {TrueStatus = false; return TrueStatus;}
	if (Overflow.length != 0) {TrueStatus = false; return TrueStatus;}
		
	return TrueStatus
}

function CheckUUID(UUIDNode, ColorMode, OKColor, MinChars)
{
	ColorMode = (ColorMode) ? ColorMode : 3 ;
	OKColor = (OKColor) ? OKColor : "#FFB720" ;
	MinChars = (MinChars) ? MinChars : 41
	//var UUIDNode =	document.getElementById("blands_uuid_input") 
	
	var TrueStatus1 = CheckFormUUIDNode(UUIDNode)
	if (TrueStatus1 == false)
	{
		UUIDNode.focus();
		FormCheckthisInputNode(UUIDNode, ColorMode, OKColor, UUIDNode.value.length +1)  // flag error
	}
	else
	{
		FormCheckthisInputNode(UUIDNode, ColorMode, OKColor, UUIDNode.value.length)  // Accept input
	}
	
	return (TrueStatus1) 
}



function UpdateUUID(TextNode) 
{
	var UUIDNode =	document.getElementById("blands_uuid_input") 
	var PromptValue = window.prompt(GetMessage("TPR_UUID_Number"), UUIDNode.value);
	if (PromptValue || PromptValue == "")
	{
		UUIDNode.value = TrimString(PromptValue)
		var TrueStatus1 = CheckFormUUIDNode(UUIDNode)
		while (TrueStatus1 == false)
		{
			var PromptValue2 = window.prompt(GetMessage("Erroneous_UUID"), UUIDNode.value);
			if (PromptValue2 || PromptValue2 == "")
			{
				UUIDNode.value = TrimString(PromptValue2)
				TrueStatus1 = CheckFormUUIDNode(UUIDNode)
			}
			else
			{
				UUIDNode.value =""  // exit
				TrueStatus1 = true
			}

		}
	
	}
	
	if (UUIDNode.value == "") 
	{
		UUIDNode.value = Global_Default_TPR_UUID
	}
	//FormCheckthisInputNode(UUIDNode, 3, "#FFB720", UUIDNode.value.length)  // Accept input
	CheckUUID(UUIDNode)
}


function GenerateXmlFiles(Form, DisplayWIN, Action)
{
	if (Form)
	{ 
	 var OKStatus = CheckBulkModeMaxSubstances()
	 
	 if (! OKStatus)
	 {
		 return // Abandon
	 }
	 //alert(document.getElementById("blands_pre_reg_limitation").value)
	 
	 FormCompactCPTable(Form, 'ContactPersonList');
	 Form.onsubmit = OnSubmitXMLProcess;
	 Form.target = DisplayWIN;
	 Form.action = Action
	 
	 if (! MakeXMLFiles(Form, DisplayWIN))
	 {  // Failed
	 }
	 
	 
	}
	else
	{
		alert("Form not found");
	}
	
}


function OnSubmitXMLProcess()
{
	var Status = true;
	var Form = document.forms['BlandsForm'];
	if (!Form) { Form = document.BlandsForm;}	
	
	var RecipientsEmailNode = document.getElementById('blands_excel_file_recipients');
	var EmailNode = document.getElementById('emails');

	UpdateCPRowCount(Form, 'ContactPersonList');
	UpdateRowCount(Form, 'SubstanceList');
	UpdateAttachedFilesInfo(Form, 'Attached_Files');
	UpdateUserTimeStamp(Form);
	
	
/* */
	
	if (CheckExcelRecipientsEmailInputs(RecipientsEmailNode) == false)
	{
		Status = false;
	}
	else
	{
		if (RecipientsEmailNode.value.length == 0)
		{
			RecipientsEmailNode.style.background="red";	
			RecipientsEmailNode.focus();
			Status = false;
			Status = true;  // Keep going ...
		}
	}

	if (CheckUserEmailInputs(EmailNode, 0) == false)
	{
		Status = false;
	}
	else
	{
		if (EmailNode.value.length == 0)
		{
			EmailNode.style.background="red";	
			Status = false;
			EmailNode.focus();
		}
	}
	
	if (CheckAllContactInformation() == false)
	{
		Status = false;
	}
/* */

	if (CheckAllCPStatus(Form, "ContactPersonList") == false)
	{
		Status = false;
	}

    if (!Status)
	{
	 	var Member= document.getElementById("company");
	   	if (Member) { Member.focus(); }
		var Error_Message = GetMessage("XML_Error") + "\n" +
			"\n  " + GetMessage('Company') +
			"\n  " + GetMessage('Company_Address') +
			"\n  " + GetMessage('Company_City') +
			"\n  " + GetMessage('Company_Country') +
			"\n  " + GetMessage('First_Name') +
			"\n  " + GetMessage('Last_Name') +
			"\n  " + GetMessage('Telephone') +
			"\n  " + GetMessage('Email') +
			"\n  " 
		alert(Error_Message);
	}



	if (GetSubstancesStatistics(Form, 'SubstanceList') == false)
	{
		Status = false;
	}
	
	//// LAST IN FUNCTION
	if (Status == true)
	{
		var CurrentLanguage = GetLanguage();
		
		if (CurrentLanguage != "English")
		{
			FlipBrieflyLanguageToEnglish(CurrentLanguage);
		}
		
	}
	else
	{
	}
	
	return Status;
}



function GetSubstancesStatistics(Form, Table_ID) 
{
	if (Form)
	{
		var row = document.getElementById(Table_ID).rows.item(0);  // 1st row
		var MaxRow = row.parentNode.rows.length;
		Global_SubstancesCount = 0;
		Global_PhaseInCount = 0;
		Global_NonPhaseInCount = 0;
		Global_SubThresholdSubstancesCount = 0;
		Global_UnselectedSubstancesCount = 0;
		Global_RegisteredSubstancesCount = 0;
		Global_AuthorisationSubstancesCount = 0;
	
		for (var RowNumber = 1; RowNumber <= MaxRow ; ++RowNumber)
		{	
			if (FormHasEmptyInputs(Form, RowNumber)) {continue}
  			var RowMember = GetFormMember(Form, 'blands_input_row__', RowNumber);
			if (RowMember) // Row exists
			{
  				var CASMember = GetFormMember(Form, 'blands_input_cas_number__', RowNumber);
  				var EINECSMember = GetFormMember(Form, 'blands_input_einecs_number__', RowNumber);
				var SubstanceNameMember = GetFormMember(Form, 'blands_input_substance_name__', RowNumber);
				var TonnageMember= GetFormMember(Form, 'blands_input_tonnage__', RowNumber);
				var RegYearMember = GetFormMember(Form, 'blands_input_registration_year__', RowNumber);
				var Int_CurrentSelectedRegYear = isNaN(parseInt(RegYearMember.value)) ? 0: parseInt(RegYearMember.value);
				var Int_Tonnage =  isNaN(parseInt(TonnageMember.value)) ? 0: parseInt(TonnageMember.value);
				var Int_CurrentYear = GetThisYear();
				
				++Global_SubstancesCount;
				
				if (RegYearMember.selectedIndex == 19)
				{
				 	++Global_RegisteredSubstancesCount
				}
				else  if (RegYearMember.selectedIndex == 21)
				{
					++Global_AuthorisationSubstancesCount
				}
				
				if ( /*(TrimString(CASMember.value) != "") && */ (TrimString(EINECSMember.value) == "") && (Int_Tonnage > 0) && (RegYearMember.selectedIndex != 19))
				{
					++Global_NonPhaseInCount
				} else if ( (TrimString(EINECSMember.value) != "") && (Int_Tonnage > 0) && (RegYearMember.selectedIndex != 19) && (RegYearMember.selectedIndex != 21))
				{
					++Global_PhaseInCount
				} else if ((Int_Tonnage < 1))
				{
					if (TonnageMember.value != "")
					{
						if (
							(RegYearMember.selectedIndex != 21)     // authorisation
							&& (RegYearMember.selectedIndex != 20)  // exemption
							)
						{
							++Global_SubThresholdSubstancesCount	
						}
					}
					else
					{
						++Global_UnselectedSubstancesCount
					}
				}
				
				

			} else
			{
				//alert ("ROW: " + RowNumber + " does not exist !");
			}
		}
		
		//alert("Total Substance(s): " + Global_SubstancesCount + "\nTotal Phase-in: " + Global_PhaseInCount+ "\nTotal Authorisation: " + Global_AuthorisationSubstancesCount + "\nTotal Non phase-in: " + Global_NonPhaseInCount + "\nTotal Sub-Threshold (< T/y): " + Global_SubThresholdSubstancesCount + "\nTotal Unselected: " + Global_UnselectedSubstancesCount)
		
		var Message1 = GetMessage("Substances_Stats")+ "\n\n  " + GetMessage("Stats_Total_Substances") + Global_SubstancesCount + "\n  " + GetMessage("Stats_Total_Phase_In") + Global_PhaseInCount + "\n  " + GetMessage("Stats_Total_Authorisation") + Global_AuthorisationSubstancesCount + "\n  " + GetMessage("Stats_Total_Non_Phase_In") + Global_NonPhaseInCount + "\n  " + GetMessage("Stats_Total_Sub_Threshold") + Global_SubThresholdSubstancesCount + "\n  " + GetMessage("Stats_Total_Unselected") + Global_UnselectedSubstancesCount+ "\n  " + GetMessage("Stats_Total_Registered") + Global_RegisteredSubstancesCount
		if (Global_SubThresholdSubstancesCount > 0)
		{
			var Message2 = "\n\n" + GetMessage("Force_Threshold")
			if (confirm(Message1+Message2))
			{
				ForceSubstancesThreshold(Form, Table_ID);
				return true  // OK
			}
		}
		
		if (Global_PhaseInCount + Global_NonPhaseInCount == 0)
		{
			var Message2 = "\n\n" + GetMessage("No_Candidate_Substance")
			alert(Message1+Message2)
			return false  // Error
		}
		return true  // OK
	}
	return false
}



function ForceSubstancesThreshold(Form, Table_ID) 
{
	if (Form)
	{
		var row = document.getElementById(Table_ID).rows.item(0);  // 1st row
		var MaxRow = row.parentNode.rows.length;
	
		for (var RowNumber = 1; RowNumber <= MaxRow ; ++RowNumber)
		{	
			if (FormHasEmptyInputs(Form, RowNumber)) {continue}
  			var RowMember = GetFormMember(Form, 'blands_input_row__', RowNumber);
			if (RowMember) // Row exists
			{
				var TonnageMember= GetFormMember(Form, 'blands_input_tonnage__', RowNumber);
				var Int_Tonnage =  isNaN(parseInt(TonnageMember.value)) ? 0: parseInt(TonnageMember.value);
				
				if ((Int_Tonnage < 1))
				{
					if (TonnageMember.value != "")
					{
						TonnageMember.selectedIndex = 2;  // [1-10]T/y
						FormPresetRegistrationYear(Form, RowNumber);
					}
				}

			} else
			{
				//alert ("ROW: " + RowNumber + " does not exist !");
			}
		}
	}
}



function CheckBulkModeMaxSubstances() 
{
	var TrueStatus1 = false
	var BulkPreRegSubstanceLimitationNode =	document.getElementById("blands_echa_pre_reg_limitation") 
	var UserBulkPreRegSubstanceLimitationNode =	document.getElementById("blands_pre_reg_limitation")
	
	if (UserBulkPreRegSubstanceLimitationNode.value == "") {UserBulkPreRegSubstanceLimitationNode.value = BulkPreRegSubstanceLimitationNode.value}
	
	var DteDuJ = new Date() ;
	var DteFin = new Date(2008,11,2); // yyyy,mm-1,dd   - 1st December 2008 DEADLINE for REACH-IT BULK Mode Submissions
	if (DteDuJ >= DteFin) {UserBulkPreRegSubstanceLimitationNode.value = '0';}

	var INT_ECHABulkLimitation = parseInt(document.getElementById("blands_echa_pre_reg_limitation").value) // 500 substances
	if (isNaN(INT_ECHABulkLimitation) || (INT_ECHABulkLimitation == 0)) { return true }
	
	var PromptValue = window.prompt(GetMessage("BULK_Substance_Breakdown") + "\n" + GetMessage("BULK_Current_Max_Substance") + UserBulkPreRegSubstanceLimitationNode.value+ GetMessage("BULK_Max_Substance"), UserBulkPreRegSubstanceLimitationNode.value);
	PromptValue = TrimString(PromptValue)
	if (PromptValue || PromptValue == "")
	{
		TrueStatus1 = CheckMaxSubstanceValidity(PromptValue)
		while (TrueStatus1 == false)
		{
			PromptValue = window.prompt(GetMessage("BULK_Substance_Breakdown") + "\n" + GetMessage("BULK_Current_Max_Substance") + UserBulkPreRegSubstanceLimitationNode.value + GetMessage("BULK_Max_Substance"), UserBulkPreRegSubstanceLimitationNode.value);
			PromptValue = TrimString(PromptValue)
			if (PromptValue || PromptValue == "")
			{
				TrueStatus1 = CheckMaxSubstanceValidity(PromptValue)
			}
			else
			{
				return false  // Abandon
			}

		}
	
	 UserBulkPreRegSubstanceLimitationNode.value = "" + parseInt(PromptValue)
	 return true
	}
	else
	{
		return false  // Abandon
	}

}


function CheckMaxSubstanceValidity(PromptValue)
{
	var TrueStatus1 = false
	var INT_BulkLimitation = parseInt(document.getElementById("blands_echa_pre_reg_limitation").value) // 500 substances
	var INT_MaxSubstances = parseInt(PromptValue)
	if (isNaN(INT_MaxSubstances))
	{
		TrueStatus1 = false
	}
	else
	{
		if ((INT_MaxSubstances < 0) || (INT_MaxSubstances > INT_BulkLimitation))
		{
			TrueStatus1 = false
		}
		else
		{
			TrueStatus1 = true
		}
	}
	return TrueStatus1
}
