var isCPSNTCycler = '';
var isCPSQuant = '';
var isCPSInvent = '';
var isCPSCust = '';	
function processCustomPlating(){
	Ext.get('delayjsonloading').addCls('dispNone');
	Ext.get('delayjsonloading').removeCls('dispBlck');
	outputList.removeAll(true);
	updateExperimentInfo("isCustomPlatingCalc",true);
	
	Ext.get('openarrayinstrumentdiv').update("");
	
	var isCPSoamiRNA = getExperimentInfo("isCPSoamiRNA");
	
	/*if ( isCPSoamiRNA ){
		Ext.get('overview').update( getExperimentInfo("noofcsptargets") + " of Custom/MTO &nbsp; &nbsp;" + getExperimentInfo("noofsamples") + " samples &nbsp; &nbsp;" + getExperimentInfo("noofreplicates") + " replicates ");
		
		Ext.get('detailoverview').update("<span class='spinCont' id='csnomtragets' >"+getExperimentInfo("noofcsptargets")+"</span> " + " Custom/MTO Assays "+"<span id='nomsamples' class='spinCont'>"+  getExperimentInfo("noofsamples") +"</span> " + " samples  " +"<span id='nomplicat' class='spinCont'>"+ getExperimentInfo("noofreplicates") +"</span> " + " replicates <input type='button' id='editInputBtCPS' class='editDet' value='Edit' onclick='editInputsCPS();' />");
	} else */
	/*if( getExperimentInfo("csPlatingAssayVal") == "Cast PCR"){ 
		Ext.get('overview').update(getExperimentInfo("noofinvptargets") + " INV Assays  &nbsp; &nbsp;" + getExperimentInfo("noofsamples") + " samples &nbsp; &nbsp;" + getExperimentInfo("noofreplicates") + " replicates ");
		
		Ext.get('detailoverview').update("<span class='spinCont' id='noofinvptargets' >"+getExperimentInfo("noofinvptargets")+"</span> " + " INV Assays "+ "<span id='nomsamples' class='spinCont'>"+  getExperimentInfo("noofsamples") +"</span> " + " samples  " +"<span id='nomplicat' class='spinCont'>"+ getExperimentInfo("noofreplicates") +"</span> " + " replicates <input type='button' id='editInputBtCPS' class='editDet' value='Edit' onclick='editInputsCPS();' />");
	} else {*/
		Ext.get('overview').update(getExperimentInfo("noofinvptargets") + " Assays  &nbsp; &nbsp;" + getExperimentInfo("noofsamples") + " samples &nbsp; &nbsp;" + getExperimentInfo("noofreplicates") + " replicates ");
		
		Ext.get('detailoverview').update("<span class='spinCont' id='noofinvptargets' >"+getExperimentInfo("noofinvptargets")+"</span> " + " Assays "+"<span id='nomsamples' class='spinCont'>"+  getExperimentInfo("noofsamples") +"</span> " + " samples  " +"<span id='nomplicat' class='spinCont'>"+ getExperimentInfo("noofreplicates") +"</span> " + " replicates <input type='button' id='editInputBtCPS' class='editDet' value='Edit' onclick='editInputsCPS();' />");
	//}
	
	
	 /*Ext.get('summ_cust_tubes').update('N/A');
	 Ext.get('summ_cust_plates').update('N/A');
	 Ext.get('summ_fixed_plates').update('N/A');
	 Ext.get('summ_cust_cards').update('N/A');
	 Ext.get('summ_fixed_cards').update('N/A');
	 Ext.get('summ_cust_openarray').update('N/A');
	 Ext.get('summ_fixed_openarray').update('N/A');
	 Ext.get('summ_cust_chips').update('N/A');
	 Ext.get('summ_fixed_chips').update('N/A');*/
	 
	//if (getExperimentInfo("csPlatingAssayVal") == "Gene Expression") {
	/*
	
	*/
	initRequiredFunction();
	//};
	listHtml = "";
	outputList.each(function (e) {
		composeOutPutHtmls(e);
		//composeOutPutHtmlCPS(e);
	});
	
	listHtml += "<div style='margin-left:31px;padding-top:20px;'><span style='float:left;margin:1px 3px 0 0;'>Note :</span> <p style='float:left;width:465px;line-height:18px;'> <span style='display:block;'>Pricing provided is an estimate for North America customers only. Pricing will be different for different countries. </span> <span style='display:block;'>Contact custom plating group (customplating@thermofisher.com) for quotes.</span></p><div style='clear:both;'></div></div>";
	
	Ext.fly('tab2cont').dom.innerHTML = listHtml;
	//var typeCSPSortArray = Array("plate");
	//composeOutPutHtmlByTypeList(typeCSPSortArray, false);
	
}


/* Edit input values in details page*/
function editInputsCPS(){
	 Ext.get('detailoverview').addCls('hidden');
     Ext.get('detailoverview').removeCls('visible');
	 
	Ext.get('editinputsCPS').addCls('visible');
    Ext.get('editinputsCPS').removeCls('hidden');
	 
	//var nomtragets = getExperimentInfo("noofcsptargets"); Madhu asked to remove this on 06-10-2015
	var nomsamples = getExperimentInfo("noofsamples");
	var nomplicat = getExperimentInfo("noofreplicates");
	var isCPSoamiRNA = getExperimentInfo("isCPSoamiRNA");
	/*if ( isCPSoamiRNA ){
		$("#spn_inv_assays").hide();
		$("#spn_custmto_assays").show();
	} else */
	if( getExperimentInfo("csPlatingAssayVal") == "Cast PCR"){
		$("#spn_inv_assays").show();
		$("#no_of_invassays").val($("#noofinvptargets").html());
		$("#spn_custmto_assays").hide();
	} else {
		$("#spn_inv_assays").show();
		$("#spn_custmto_assays").show();
		$("#no_of_invassays").val($("#noofinvptargets").html());
		$("#no_of_custmtoassays").val($("#csnomtragets").html());
	}
	
	$("#no_of_custmtoassays").val($("#csnomtragets").html());
	$("#no_of_samplescps_3").val($("#nomsamples").html());
	$("#no_of_replicatescps_3").val($("#nomplicat").html());
		
	$("#editInputBtCPS").hide();
	$("#submitEditedInputCPS").show();	
	$("#CPSinputcntrls").show();
	
	$( ".editInputSpinner" ).spinner({ min: 0, max: 10000, step: 1});	
}

function submitEditInputsCPS(){	
	Ext.get('editinputsCPS').addCls('hidden');
    Ext.get('editinputsCPS').removeCls('visible');
	
	Ext.get('detailoverview').addCls('visible');
    Ext.get('detailoverview').removeCls('hidden');
	 
	
	$(".editInputSpinner" ).spinner("destroy" );
	$("#submitEditedInputCPS").hide();
	$("#editInputBtCPS").show();	
	var isCPSoamiRNA = getExperimentInfo("isCPSoamiRNA");
	/*if ( !isCPSoamiRNA ){
		$("#noofinvptargets").html($("#no_of_invassays").val());
	} */
	$("#noofinvptargets").html($("#no_of_invassays").val());
	$("#csnomtragets").html($( "#no_of_custmtoassays" ).val());
	$("#nomsamples").html($( "#no_of_samplescps_3" ).val());
	$("#nomplicat").html($( "#no_of_replicatescps_3" ).val());
	
	//var noofcsptargets = Number($( "#no_of_custmtoassays" ).val()); Madhu asked to remove this on 06-10-2015
	var noofinvptargets = Number($( "#no_of_invassays" ).val());
	var cspnooftargets = noofinvptargets ;// +noofcsptargets ;
	//updateExperimentInfo("noofcsptargets", Number($( "#no_of_custmtoassays" ).val())); Madhu asked to remove this on 06-10-2015
	updateExperimentInfo("noofinvptargets", Number($( "#no_of_invassays" ).val()));	
	updateExperimentInfo("noofsamples", Number($( "#no_of_samplescps_3" ).val()));
	updateExperimentInfo("noofreplicates", Number($( "#no_of_replicatescps_3" ).val()));	
	updateExperimentInfo("nooftargets", cspnooftargets);
	updateExperimentInfo("type", getExperimentInfo("csPlatingAssayVal"));

	
	//updateExperimentInfo("isOtherFormat", "NO");
	//if(currentpno === "111"){
	//	currentpno = getExperimentInfo("currFmPno");
	//}
	var rec = outputList.findRecord('pno', currentpno, 0, false, false, true);
	var isValid = true;
	var ai = 1;
	
	var functionName  = rec.get('fnName');
	outputList.removeAll();
	/*if(outputList.findExact('pno',currentpno) != -1){
		outputList.removeAt(outputList.findExact('pno',currentpno));
	}*/
	
	initRequiredFunction();	
	eval( '('+functionName+'())' );
	
	if(outputList.findExact('pno',currentpno) != -1){
		showDetails(currentpno);
		Ext.get('editinputsCPS').addCls('hidden');
		Ext.get('editinputsCPS').removeCls('visible');
		
		Ext.get('detailoverview').addCls('visible');
		Ext.get('detailoverview').removeCls('hidden');
		 
		$("#submitEditedInputCPS").hide();
		$("#editInputBtCPS").show();	
		$("#cpserrtarget").html("");
	}else{
		outputList.add(rec);
		showDetails(currentpno);
		Ext.get('editinputsCPS').addCls('visible');
		Ext.get('editinputsCPS').removeCls('hidden');
		
		Ext.get('detailoverview').addCls('hidden');
		Ext.get('detailoverview').removeCls('visible');
		$( ".editInputSpinner" ).spinner({ min: 0, max: 10000, step: 1});
		$("#cpserrtarget").html("Invalid Target value");
		$("#submitEditedInputCPS").show();
		
	}
}


function addCPSmiRNAOA(){	
	//var nooftargets = getExperimentInfo("noofcsptargets");
	var nooftargets = getExperimentInfo("nooftargets");
	var noofsamples = getExperimentInfo("noofsamples");
	var noofreplicates = getExperimentInfo("noofreplicates");
	var noofreactions = noofsamples * noofreplicates;
	var InstrumentType = getExperimentInfo('openarrayinstrument');
	var assayType = getExperimentInfo('assayType');
	
	if(isCPSCust){
		//var title = "TaqMan<sup>&reg;</sup>&nbsp;OpenArray<sup>&reg;</sup>&nbsp; Custom miRNA assays";
		var title = "TaqMan<sup>&reg;</sup>&nbsp;OpenArray<sup>&reg;</sup>&nbsp;Custom Format with Custom miRNA assays";
	} else {
		//var title = "TaqMan<sup>&reg;</sup>&nbsp;OpenArray<sup>&reg;</sup>&nbsp; Inventoried miRNA assays";
		var title = "TaqMan<sup>&reg;</sup>&nbsp;OpenArray<sup>&reg;</sup>&nbsp;Custom Format with Inventoried miRNA assays";
	}
	if(getExperimentInfo('openarrayinstrument') == "QuantStudio"){
		title = title +" (QS)";
	} else {
		title = title +" (NT)";
	}
	//var formatObject = isCPSCust ? findApproximateCPSmiRNAOaCUSRec(assayType,noofrxns) : findApproximateCPSmiRNAOaRec(assayType,noofrxns);
	
	if(isCPSCust && isCPSQuant){
		var spno = 203;
	} else if(isCPSInvent && isCPSQuant){
		var spno = 204;
	} else if(isCPSCust && isCPSNTCycler){
		var spno = 205;
	} else if(isCPSInvent && isCPSNTCycler){
		var spno = 206;
	}
	
	var specie = "Human";
	var formatObject = findApproximateCPSmiRNAOaRec(nooftargets, assayType, noofreactions, InstrumentType);
	var formatObj = findApproximateOpenMirnaRecord(getExperimentInfo(specie));
	//console.log(formatObject);
	var partNumber = formatObject.get('partnumber');
	var description = formatObject.get('Description');
	var format = description;
	var qty = noofreactions/formatObject.get('Samples Plate'); 
	noofreactions = noofreactions * formatObject.get('Assays Plate'); //Lini asked to use formula from GE for no rxns on 24-03-2016
	//var qty = noofreactions/formatObject.get('Samples Plate');
	var noofunits = Math.ceil(qty/10);
	var regionObj = formatObject.regions();	
	var assayCostPerUnit = regionObj.findRecord('region', region + "-" + currency).get('price');	
	var discountno = 0;
	var volDiscount = getOpenArrayDiscoutValue("product", noofunits,format, true)
	var volumeDiscount = getExperimentInfo("cpsDiscountValue");
	var costWithVolDisc = noofunits * assayCostPerUnit * (1 - (volumeDiscount / 100));
	var plateperc = 0; //(Ext.get('plateperc').dom.value).split('%')[0];
	var preamprtperc = 0; //(Ext.get('preamprtperc').dom.value).split('%')[0];
	var accessoriesperc = 0; //(Ext.get('accessoriesperc').dom.value).split('%')[0];
	var accessperc = 0;
	var masterperc = 0;
	var totalAssayCost = costWithVolDisc * (1 - (plateperc / 100));
	var assayCostPerReaction = totalAssayCost/noofreactions;
	var assayCostPerSample = totalAssayCost / noofsamples * 10;
	var isPreamp = true;
	var totalReactions = getExperimentInfo('noofreplicates') * getExperimentInfo('noofsamples');
	//var totalCost = totalAssayCost;
	var optimizationCostPerReaction = 0;
	
	
	/* MM starts*/
	
	var mvolume = (getExperimentInfo('noofsamples') * getExperimentInfo('noofreplicates')) * 45;
	var mmxObj = accessories.findRecord('partnumber',"4462159");
	var mmxObj1 = accessories.findRecord('partnumber',"4462164");
	var mastermix = "";
	mastermix = mmxObj.get('product');
	var mastermix1 = mmxObj1.get('product');
	var mmxPartNumber = mmxObj.get('partnumber');
	var mmxPartNumber1 = mmxObj1.get('partnumber');
	var Totmnoofunits = mvolume / 1000;
	var mnoofunits = Math.ceil(Totmnoofunits / 1.5);	
	var mnoofunits1 = Math.ceil(Totmnoofunits / 5);
	var masterMixCostPerUnit = pricelist.findRecord('partnumber', mmxPartNumber).regions().findRecord('region',
			region + "-" + currency).get('price');
	var masterMixCostPerUnit1 = pricelist.findRecord('partnumber', mmxPartNumber1).regions().findRecord('region',
			region + "-" + currency).get('price');

	var totalMasterMixCost = masterMixCostPerUnit * mnoofunits
			* (1 - (masterperc / 100));
	var totalMasterMixCost1 = masterMixCostPerUnit1 * mnoofunits1
			* (1 - (masterperc / 100));
	
	//To get Combination of 1.5 and 5 ML MasterMix
	/*var tempmnoofunits = Totmnoofunits / 1.5;
	var tempmnoofunits1 = Totmnoofunits / 5;
	
	if(tempmnoofunits1 > 1){
	
		var temp = mnoofunits1 - 1;
		
		var temp1 = Totmnoofunits - (temp * 5);
		var temp2 = Math.ceil(temp1 / 1.5);
		
		var temp3 = masterMixCostPerUnit1 * temp * (1 - (masterperc / 100));
		var temp4 = masterMixCostPerUnit * temp2 * (1 - (masterperc / 100));
		
		var temp5 = temp3 + temp4;
		//alert(totalMasterMixCost1 +' = temp5 : ' + temp5);
		
		if(temp5 < totalMasterMixCost1){
			mnoofunits = temp2;
			mnoofunits1 = temp;
			totalMasterMixCost = temp4;
			totalMasterMixCost1 = temp3;
		}else{
			mnoofunits1 = mnoofunits1;
			mnoofunits = 0;
			totalMasterMixCost1 = totalMasterMixCost1;
		}
	}else{
		if(totalMasterMixCost1 < totalMasterMixCost){
			mnoofunits = 0;
			totalMasterMixCost = 0;
			mnoofunits1 = mnoofunits1;
		}else{
			mnoofunits1 = 0;
			totalMasterMixCost1 = 0;
			mnoofunits = mnoofunits;
		}
	}*/
	var mvolume = (150 * noofunits * 10)/1000 ; // Lini asked to change the value 157 to 150 on 04-06-2014
	
	if(mvolume >= 3)
	{
		if(mvolume <=5)
		{
			var mnoofunits = 0;
			var mnoofunits1 = 1;		
		}else{
			var remvol = (mvolume % 5);
			var mnoofunits = Math.ceil((remvol / 1.5));
			var mnoofunits1 = Math.floor((mvolume / 5));
		

		}

	}else
	{
		var mnoofunits = Math.ceil((mvolume / 1.5));
		var mnoofunits1 = 0;
	}
	/* MM combination ends*/
	var masterMixCostPerReaction = (totalMasterMixCost + totalMasterMixCost1) / noofreactions;
	var masterMixCostPerReaction1 = totalMasterMixCost1 / noofreactions;
	
	/* MM Ends*/
	
	/* RT starts */
	var reqnoofunits = getExperimentInfo('noofsamples')* getExperimentInfo('noofsubarrays')/ 3;
	var isMin = (min == 1 ? 1 : (Math.ceil(reqnoofunits) < min ? 0 : 1));
	var rt_tools = $('input[name=rt_tools]:radio:checked').val();
	/*if(rt_tools == "Megaplex"){ */
		var rtObj = mirnaRT.findRecord('productname', 'TaqMan® MicroRNA Reverse Transcription Kit, 200 rxns');
		var rtObj1 = mirnaRT.findRecord('productname', 'TaqMan® MicroRNA Reverse Transcription Kit, 1000 rxns');
		var rtProduct = rtObj.get('productname');
		var rtProduct1 = rtObj1.get('productname');	
		var rtPartNumber = rtObj.get('partnumber');
		var rtPartNumber1 = rtObj1.get('partnumber');
		var rtCostPerUnit = pricelist.findRecord('partnumber', rtObj.get('partnumber')).regions().findRecord(
				'region', region + "-" + currency).get('price');
		//CSPINST 1 : Added on 14/08/2015 based Lini instruction - changed the calc for RT-NO-UNITS(here noofsamples = samples * replicates)
		
		//As per Necip - removing replicates in calculation on 9 Nov 2015
		//var rtNoOfReactions = getExperimentInfo('noofsamples') * getExperimentInfo('noofreplicates');
		var rtNoOfReactions = getExperimentInfo('noofsamples');
		
		/* Commented 14/08/2015 based - CSPINST 1 
		var preamp_rxn_size = Number($('input[name=preamp_rxn_size]:radio:checked').val());
		preamp_rxn_size = Math.ceil((1000/preamp_rxn_size)*0.25*1.125);
		//var rtNoOfUnits = Math.ceil((formatObj.get('rtkitperunit') * reqnoofunits) % 5);
		var rtNoOfUnits = Math.floor(noofsamples/preamp_rxn_size);
		console.log("noofsamples -"+noofsamples+ "--"+"preamp_rxn_size - "+preamp_rxn_size);*/
		
		//Added on 14/08/2015 based - CSPINST 1
		var rt_tools = $('input[name=rt_tools]:radio:checked').val();
		if(getExperimentInfo("noofcsptargets") != 0){
		   if(rt_tools == "Megaplex"){
				var kit200Rxn = 65;
				var kit1000Rxn = 332;
		   } else {
				var kit200Rxn = 42;
				var kit1000Rxn = 214;
		   }
		}else{
		   var kit200Rxn = 65;
		   var kit1000Rxn = 332;
		}
		var rtNoOfUnits = Math.ceil(rtNoOfReactions/kit200Rxn);
		var totalRTCost = rtCostPerUnit * rtNoOfUnits * (1 - (preamprtperc / 100));
		var rtCostPerReaction = totalRTCost / noofreactions;

		var rtCostPerUnit1 = pricelist.findRecord('partnumber', rtObj1.get('partnumber')).regions().findRecord(
				'region', region + "-" + currency).get('price');
		//var rtNoOfReactions1 = getExperimentInfo('noofsamples') * getExperimentInfo('noofreplicates');
		var rtNoOfReactions1 = getExperimentInfo('noofsamples');
		/* Commented 14/08/2015 based - CSPINST 1 
		var rtNoOfUnits1 = Math.floor((formatObj.get('rtkitperunit') * reqnoofunits) / 5);*/
		//Added on 14/08/2015 based - CSPINST 1
		var rtNoOfUnits1 = Math.ceil( rtNoOfReactions1/kit1000Rxn );
		var totalRTCost1 = rtCostPerUnit1 * rtNoOfUnits1 * (1 - (preamprtperc / 100));
		var rtCostPerReaction1 = totalRTCost1 / noofreactions;
		//Added on 14/08/2015 based - CSPINST 1
		
		/*if( totalRTCost <= totalRTCost1 ){
			rtNoOfUnits1 = 0;
			totalRTCost1 = 0;
		}else if( totalRTCost1 < totalRTCost){
			rtNoOfUnits = 0;
			totalRTCost = 0;		
		}*/
		
		// combination of 200 rxn and 1000 rxn starts
		var tempmnoofunits = rtNoOfUnits ;
		var tempmnoofunits1 = rtNoOfUnits1 ;
					
		var totalRTCost = rtCostPerUnit * rtNoOfUnits * (1 - (preamprtperc / 100));
		var totalRTCost1 = rtCostPerUnit1 * rtNoOfUnits1 * (1 - (preamprtperc / 100));
		
		if(tempmnoofunits1 > 1){
			var temp = Math.floor(rtNoOfReactions/kit1000Rxn);
			var tempReaction = (rtNoOfReactions - (temp * kit1000Rxn ));
			var temp2 =  Math.ceil(tempReaction/kit200Rxn);
			/*var temp = rtNoOfUnits1 - 1;						
			var temp1 = rtNoOfUnits;
			var temp2 = rtNoOfUnits1;
			*/
			var temp3 = rtCostPerUnit1 * temp * (1 - (preamprtperc / 100));
			var temp4 = rtCostPerUnit * temp2 * (1 - (preamprtperc / 100));
			
			var temp5 = temp3 + temp4;
						
			if(temp5 < totalRTCost1){
				rtNoOfUnits = temp2;
				rtNoOfUnits1 = temp;
				totalRTCost = temp4;
				totalRTCost1 = temp3;
			}else{
				rtNoOfUnits1 = rtNoOfUnits1;
				rtNoOfUnits = 0;
				totalRTCost1 = totalRTCost1;
			}
		}else{
			if(totalRTCost1 < totalRTCost){
				rtNoOfUnits = 0;
				totalRTCost = 0;
				rtNoOfUnits1 = rtNoOfUnits1;
			}else{
				rtNoOfUnits1 = 0;
				totalRTCost1 = 0;
				rtNoOfUnits = rtNoOfUnits;
			}
		}
		
		// combination of 200 rxn and 1000 rxn ends
		
	/*} else {*/
		var preampprimerpools = "TaqMan® OpenArray Custom PreAmp Pools";
		var preampprimerpoolpartnumber = 4485255;
		var preprimerpoolspriceperunit = Number(pricelist.findRecord('partnumber', preampprimerpoolpartnumber).regions().findRecord(
				'region', region + "-" + currency).get('price'));
		var preamp_rxn_size = Number($('input[name=preamp_rxn_size]:radio:checked').val());
		preamp_rxn_size = Math.ceil( 1000/( preamp_rxn_size * 0.25 * 1.125 ) );		
		//var rtNoOfUnits = Math.ceil((formatObj.get('rtkitperunit') * reqnoofunits) % 5);
		
		
		//var preampprimerpoolsnoofunits = Math.ceil( Number(noofsamples * noofreplicates)/preamp_rxn_size);
		
		//As per Necip - removing replicates in calculation on 9 Nov 2015
		var preampprimerpoolsnoofunits = Math.ceil( Number(noofsamples)/preamp_rxn_size);		
		var totalpreampprimerpoolspricecost = preprimerpoolspriceperunit * preampprimerpoolsnoofunits * (1 - (preamprtperc / 100));		
		var preampprimerpoolsreaction = totalpreampprimerpoolspricecost / noofreactions;
		var preampprimerpoolspricepersample = totalpreampprimerpoolspricecost/getExperimentInfo('noofsamples');
		
		
		/*
		Comment on 07/08/2015 this one is replaced with above code.
		var rtProduct = "TaqMan® OpenArray Custom PreAmp Pools";
		var rtProduct1 = "";
		var rtPartNumber = 4485255;
		var rtPartNumber1 = "";
		var rtCostPerUnit = 0;
		var rtNoOfReactions = getExperimentInfo('noofsamples');
		var preamp_rxn_size = Number($('input[name=preamp_rxn_size]:radio:checked').val());
		preamp_rxn_size = Math.ceil( 1000/( preamp_rxn_size * 0.25 * 1.125 ) );		
		//var rtNoOfUnits = Math.ceil((formatObj.get('rtkitperunit') * reqnoofunits) % 5);
		var rtNoOfUnits = Math.ceil( Number(noofsamples * noofreplicates)/preamp_rxn_size);
		var totalRTCost = rtCostPerUnit * rtNoOfUnits * (1 - (preamprtperc / 100));
		var rtCostPerReaction = totalRTCost / noofreactions;
		var rtNoOfReactions1 = getExperimentInfo('noofsamples');
		var rtNoOfUnits1 = 0;
		var rtCostPerUnit1 = pricelist.findRecord('partnumber', rtPartNumber).regions().findRecord(
				'region', region + "-" + currency).get('price');
		var totalRTCost1 = rtCostPerUnit1 * rtNoOfUnits1 * (1 - (preamprtperc / 100));
		var rtCostPerReaction1 = totalRTCost1 / noofreactions;*/
	//}
	/* RT ends*/
	
	/* Preamp starts */	
	var preAmpObj = mirnaPreAmp.findRecord('productname','TaqMan® PreAmp Master Mix - 1mL');
	var preAmpProduct = preAmpObj.get('productname');
	var preAmpPartNumber = preAmpObj.get('partnumber');
	var preAmpCostPerUnit = pricelist.findRecord('partnumber', preAmpObj.get('partnumber')).regions().findRecord(
			'region', region + "-" + currency).get('price');
	var preAmpNoOfReactions = getExperimentInfo('noofsamples');
	var preAmpNoOfUnits = Math.ceil( 1000/ ( Number($('input[name=preamp_rxn_size]:radio:checked').val())  * 0.50 * 1.125 ) );
	
	//As per Necip - removing replicates in calculation on Nov 9,2015
	//preAmpNoOfUnits = Math.ceil( ( noofsamples * noofreplicates ) / preAmpNoOfUnits );
	preAmpNoOfUnits = Math.ceil( ( noofsamples ) / preAmpNoOfUnits );
	
	var totalPreAmpCost = preAmpCostPerUnit * preAmpNoOfUnits * (1 - (preamprtperc / 100));	
	var preAmpCostPerSample = totalPreAmpCost / preAmpNoOfReactions;
	//Changed to noofreactions
	var preAmpCostPerReaction = totalPreAmpCost / noofreactions;
	
	var preAmpObj1 = mirnaPreAmp.findRecord('productname','TaqMan® PreAmp Master Mix - 5mL');
	var preAmpProduct1 = preAmpObj1.get('productname');
	var preAmpPartNumber1 = preAmpObj1.get('partnumber');
	var preAmpCostPerUnit1 = pricelist.findRecord('partnumber', preAmpObj1.get('partnumber')).regions().findRecord(
			'region', region + "-" + currency).get('price');
	var preAmpNoOfReactions1 = getExperimentInfo('noofsamples');
	var preAmpNoOfUnits1 = Math.ceil( 5000/ ( Number($('input[name=preamp_rxn_size]:radio:checked').val())  * 0.50 * 1.125 ) );
	
	//As per Necip - removing replicates in calculation on Nov 9,2015
	//preAmpNoOfUnits1 = Math.ceil( ( noofsamples * noofreplicates ) / preAmpNoOfUnits1 );
	preAmpNoOfUnits1 = Math.ceil( ( noofsamples ) / preAmpNoOfUnits1 );
	
	var totalPreAmpCost1 = preAmpCostPerUnit1 * preAmpNoOfUnits1 * (1 - (preamprtperc / 100));	
	var preAmpCostPerSample1 = totalPreAmpCost1 / preAmpNoOfReactions1;
	//Changed to noofreactions
	var preAmpCostPerReaction1 = totalPreAmpCost1 / noofreactions;
	
	if( totalPreAmpCost < totalPreAmpCost1 ){
		preAmpNoOfUnits1 = 0;
		preAmpCostPerSample1 = 0;
		preAmpNoOfReactions1 = 0;
	}else{
		preAmpNoOfUnits = preAmpNoOfUnits1;
		preAmpCostPerSample = preAmpCostPerSample1;
		preAmpNoOfReactions = preAmpNoOfReactions1;
		preAmpProduct = preAmpProduct1;
		preAmpPartNumber = preAmpPartNumber1;
		preAmpNoOfUnits1 = 0;
		preAmpCostPerSample1 = 0;
		preAmpNoOfReactions1 = 0;
	}
	
	/* Preamp ends */
	
	var openArray384Obj = accessories.findRecord('product', 'OpenArray® 384-well Sample Plates');
	var acc1PartNumber = openArray384Obj.get('partnumber');	
	/*var openArray384WellSamplePlatesUnits = Math.ceil(formatObj.get('openarraysampleplatesperunit')
			* reqnoofunits) < openArray384Obj.get('min') ? openArray384Obj.get('min') : Math.ceil(formatObj.get('openarraysampleplatesperunit') * reqnoofunits);*/
			
	//var openArray384WellSamplePlatesUnits = Math.ceil(0.125	* reqnoofunits) < openArray384Obj.get('min') ? openArray384Obj.get('min') : Math.ceil(0.125 * reqnoofunits);
	var openArray384WellSamplePlatesUnits =   Math.ceil( noofunits * 0.125 );
	var openArray384WellSamplePlatesCost = pricelist.findRecord('partnumber',
			acc1PartNumber).regions().findRecord('region',
					region + "-" + currency).get('price')
			* openArray384WellSamplePlatesUnits;
	

	//var openArrayAccuFillSystemTipsUnits = Math.ceil((formatObj.get('openarraytipsperunit') * reqnoofunits) % 10);
	var openArrayAccuFillSystemTipsUnits = Math.ceil(noofunits * 1.25);

	
	var acc2PartNumber = mirnaAccessories.findRecord('productname','OpenArray® AccuFill® System Tips').get('partnumber');

	var openArrayAccuFillSystemTipsCost = pricelist.findRecord('partnumber',
			acc2PartNumber).regions().findRecord('region',
					region + "-" + currency).get('price')
			* openArrayAccuFillSystemTipsUnits;

	var acc3PartNumber = mirnaAccessories.findRecord('productname','OpenArray® AccuFill® System Tips, 10 pack').get('partnumber');

	//var openArrayAccuFillSystemTips10PackUnits = Math.floor((formatObj.get('openarraytipsperunit') * reqnoofunits) / 10);
	var openArrayAccuFillSystemTips10PackUnits = Math.ceil((noofunits * 1.25) / 10);
	
	var openArrayAccuFillSystemTips10PackCost = pricelist.findRecord('partnumber',
			acc3PartNumber).regions().findRecord('region',
					region + "-" + currency).get('price')
			* openArrayAccuFillSystemTips10PackUnits;
	
	if( openArrayAccuFillSystemTipsCost < openArrayAccuFillSystemTips10PackCost ){
		openArrayAccuFillSystemTips10PackUnits = 0;
		openArrayAccuFillSystemTipsCost = openArrayAccuFillSystemTipsCost;	
	}else{		
		openArrayAccuFillSystemTipsUnits = openArrayAccuFillSystemTips10PackUnits;
		openArrayAccuFillSystemTips10PackUnits = 0;
		openArrayAccuFillSystemTipsCost = openArrayAccuFillSystemTips10PackCost;
	}
	
	if(isCPSQuant){		
		var acc4PartNumber = mirnaAccessories.findRecord('productname','QuantStudio 12K Flex OpenArray® Accessories Kit').get('partnumber');
		var realtimePCRname = "TaqMan® OpenArray® QuantStudio 12K Flex OpenArray® Accessories Kit";
		var openArrayRealTimePCRAccessoriesKitUnits = 0;
	}else{		
		var acc4PartNumber = mirnaAccessories.findRecord('productname',	'OpenArray® Real-Time PCR Accessories Kit').get('partnumber');
		var realtimePCRname = "TaqMan® OpenArray® Real-Time PCR Accessories Kit";
		var openArrayRealTimePCRAccessoriesKitUnits = Math.ceil(1	* noofunits);
	}
	
   
	//var openArrayRealTimePCRAccessoriesKitUnits = Math.ceil(formatObj.get('accessorieskitperunit')	* reqnoofunits);
	//var openArrayRealTimePCRAccessoriesKitUnits = Math.ceil(1	* noofunits);
	var openArrayRealTimePCRAccessoriesKitCost = pricelist.findRecord('partnumber',
			acc4PartNumber).regions().findRecord('region',
					region + "-" + currency).get('price')
			* openArrayRealTimePCRAccessoriesKitUnits;
	
	//var megaplexPrimerPoolsHumanUnits = isPreamp ? Math.ceil(formatObj.get('primerpoolsperunit') * reqnoofunits) : 0;
	
	// 1 kit is for 50 samples.
	//var megaplexPrimerPoolsHumanUnits = Math.ceil( ( noofsamples * noofreplicates ) / 50 );
	
	//As per Necip - removing replicates in calculation on Nov 9,2015
	var megaplexPrimerPoolsHumanUnits = Math.ceil( noofsamples / 50 );
	
	var species = specie;
	species = (species == "Rat" || species == "Mouse") ? "Rodent" : species;
	
	
	var acc5PartNumber = (species == "Human" ? accessories.findRecord('product', 'Megaplex® Primer Pools, Human').get('partnumber'): accessories.findRecord('product','Megaplex® Primer Pools, Rodent').get('partnumber'));
					
	var rt_tools = $('input[name=rt_tools]:radio:checked').val();
	if(rt_tools == "Megaplex"){
		acc5PartNumber = 4444750;
		var assay5costperUnts =  pricelist.findRecord('partnumber',	acc5PartNumber).regions().findRecord('region',region + "-" + currency).get('price');
	} else {
		acc5PartNumber = 'A25630'; //450008;
		var assay5costperUnts = 0;
	}
	
	var megaplexPrimerPoolsHumanCost = assay5costperUnts * megaplexPrimerPoolsHumanUnits
			* (1 - (parseFloat(accessoriesperc) / 100));
	
	
	var rtPrimerPoolsObj = getRTPrimerPools(specie,	getExperimentInfo('noofreplicates')
					* getExperimentInfo('noofsamples'),(format.indexOf("A+B") != -1 ? "Pool Set v3.0" : "Pool B v3.0"));
	var rtPrimerPools = rtPrimerPoolsObj.get('productname');
	
	//As per Necip - removing replicates in calculation on 9 Nov 2015
	//var rtPrimerPoolsNoOfUnits = isPreamp ? 0 : Math.ceil(getExperimentInfo('noofreplicates') * getExperimentInfo('noofsamples')/ rtPrimerPoolsObj.get('reactions'));
	var rtPrimerPoolsNoOfUnits = isPreamp ? 0 : Math.ceil(getExperimentInfo('noofsamples')/ rtPrimerPoolsObj.get('reactions'));
	
	var rtPrimerPoolsPartNumber = rtPrimerPoolsObj.get('partnumber');
	
	var rtPrimerPoolsPricePerUnit = pricelist.findRecord('partnumber',
			rtPrimerPoolsPartNumber).regions().findRecord('region',
			region + "-" + currency).get('price');
	var totalRtPrimerPoolsPriceCost = rtPrimerPoolsPricePerUnit
			* rtPrimerPoolsNoOfUnits * (1 - (preamprtperc / 100));
	;

	var openArray384WellSamplePlatesCostWithDisc = openArray384WellSamplePlatesCost * (1 - (accessperc / 100));
	//var openArrayAccuFillSystemTips10CostWithDisc = openArrayAccuFillSystemTips10PackCost * (1 - (accessperc / 100));
	var openArrayAccuFillSystemTipsCostWithDisc	  = openArrayAccuFillSystemTipsCost * (1 - (accessperc / 100));
	var openArrayRealTimePCRAccessoriesKitCostCostWithDisc	  = openArrayRealTimePCRAccessoriesKitCost * (1 - (accessperc / 100));

	/*var accessoriescost = openArray384WellSamplePlatesCostWithDisc
			+ openArrayAccuFillSystemTipsCostWithDisc
			+ openArrayAccuFillSystemTips10CostWithDisc
			+ openArrayRealTimePCRAccessoriesKitCostCostWithDisc
			+ megaplexPrimerPoolsHumanCost + totalRtPrimerPoolsPriceCost;*/
			
	var accessoriescost = openArray384WellSamplePlatesCostWithDisc
			+ openArrayAccuFillSystemTipsCostWithDisc
			+ openArrayRealTimePCRAccessoriesKitCostCostWithDisc
			+ megaplexPrimerPoolsHumanCost + totalRtPrimerPoolsPriceCost;

	var totalAccessoriescost = accessoriescost;

	var accessoriesCostPerReaction = totalAccessoriescost / noofreactions;

	var totalCostPerReaction = assayCostPerReaction + masterMixCostPerReaction
			+ rtCostPerReaction + rtCostPerReaction1 + preAmpCostPerReaction
			+ accessoriesCostPerReaction + preampprimerpoolsreaction;
	/*console.log("assayCostPerReaction - "+assayCostPerReaction);
	console.log("masterMixCostPerReaction - "+masterMixCostPerReaction);
	console.log("rtCostPerReaction - "+rtCostPerReaction);
	console.log("rtCostPerReaction1 - "+rtCostPerReaction1);
	console.log("preAmpCostPerReaction - "+preAmpCostPerReaction);
	console.log("accessoriesCostPerReaction - "+accessoriesCostPerReaction);
	console.log("preampprimerpoolsreaction - "+preampprimerpoolsreaction);*/
	
	var mmixCostPerSample = totalMasterMixCost	/ getExperimentInfo('noofsamples');
	var mmixCostPerSample1 = totalMasterMixCost1 / getExperimentInfo('noofsamples');
	var assayCostPerSample = totalAssayCost / getExperimentInfo('noofsamples');
	var rtCostPerSample = totalRTCost / getExperimentInfo('noofsamples');
	var rtCostPerSample1 = totalRTCost1 / getExperimentInfo('noofsamples');
	
	var acc1CostPerSample = openArray384WellSamplePlatesCostWithDisc / getExperimentInfo('noofsamples');
	var acc2CostPerSample = openArrayAccuFillSystemTipsCostWithDisc / getExperimentInfo('noofsamples');
	//var acc3CostPerSample = openArrayAccuFillSystemTips10CostWithDisc / getExperimentInfo('noofsamples');
	var acc4CostPerSample = openArrayRealTimePCRAccessoriesKitCostCostWithDisc / getExperimentInfo('noofsamples');
	var acc5CostPerSample = megaplexPrimerPoolsHumanCost / getExperimentInfo('noofsamples');
			
	var rtPrimerPoolsPerSample = totalRtPrimerPoolsPriceCost / getExperimentInfo('noofsamples');		
	var accessoriesCostPerSample = acc1CostPerSample + acc2CostPerSample + acc4CostPerSample + acc5CostPerSample ;
	var totalCostPerSample = assayCostPerSample + mmixCostPerSample
			+ rtCostPerSample + rtCostPerSample1 + preAmpCostPerSample
			+ accessoriesCostPerSample+mmixCostPerSample1+rtPrimerPoolsPerSample + preampprimerpoolspricepersample;
	
	/*console.log("----------------------------------");
	console.log("assayCostPerSample - "+assayCostPerSample);
	console.log("mmixCostPerSample - "+mmixCostPerSample);
	console.log("rtCostPerSample - "+rtCostPerSample);
	console.log("rtCostPerSample1 - "+rtCostPerSample1);
	console.log("preAmpCostPerSample - "+preAmpCostPerSample);
	console.log("accessoriesCostPerSample - "+accessoriesCostPerSample);
	console.log("mmixCostPerSample1 - "+mmixCostPerSample1);
	console.log("rtPrimerPoolsPerSample - "+rtPrimerPoolsPerSample);
	console.log("preampprimerpoolspricepersample - "+preampprimerpoolspricepersample);
	console.log("----------------------------------");*/
	
	var totalCostPreDisc = costWithVolDisc
			+ (masterMixCostPerUnit * mnoofunits) + totalPreAmpCost
			+ totalRTCost + totalRTCost1 + accessoriescost + totalpreampprimerpoolspricecost;
	var totalDiscount = 100 - (totalCost * 100 / totalCostPreDisc);
	

	var noOfHours = 0;
	var oType = getExperimentInfo('openarrayinstrument') == "QuantStudio" ? "GEandMirnaQS"
			: "GEandMirnaNT";
	var tRec = openarrayruntimes.findRecord('type', oType);
	noOfHours = Math.ceil(Math.ceil((reqnoofunits)
			/ tRec.get('noofplatesperrun'))
			* tRec.get('totalmin') / 60);

	var totalCost = totalAssayCost + totalMasterMixCost + totalRTCost
			+ totalRTCost1 + totalPreAmpCost + totalAccessoriescost + totalMasterMixCost1;
			
	/*console.log("####################################");
	console.log("totalAssayCost - "+totalAssayCost);
	console.log("totalMasterMixCost - "+totalMasterMixCost);
	console.log("totalRTCost - "+totalRTCost);
	console.log("totalRTCost1 - "+totalRTCost1);
	console.log("totalPreAmpCost - "+totalPreAmpCost);
	console.log("totalAccessoriescost - "+totalAccessoriescost);
	console.log("totalMasterMixCost1 - "+totalMasterMixCost1);
	console.log("####################################");*/
	
	var totalReactions = (getExperimentInfo('nooftargets') * getExperimentInfo('noofreplicates') * getExperimentInfo('noofsamples'));		
	
	var totalCostPerReaction = totalCost /noofreactions ;
	
	var productUrl = "";
	if(species == "Rodent") {
		productUrl = "http://products.invitrogen.com/ivgn/product/4461105";
	} else {
		productUrl = "http://products.invitrogen.com/ivgn/product/4470201";
	}
	
	//var totalCostPerReaction = assayCostPerReaction + optimizationCostPerReaction;
	//var totalCostPerSample = assayCostPerSample;
	//var totalCostPreDisc = costWithVolDisc;
	//var totalDiscount = 100 - (totalCost * 100 / totalCostPreDisc)
	
	if (getExperimentInfo('ulMethod') == "96 Well Plates"){		
			var hours = Math.ceil((40 * 1.2 * noofunits)/60);
	}else{
			var hours = Math.ceil((75 * 1.2 * noofunits)/60);
	}
	
	//var productUrl = "#";
	var imageType = "";
	if(isCPSNTCycler){
		imageType = "openarray-ntcycler-fixed";
	}
	
	/*if(isCPSInvent){
		preAmpNoOfUnits = 0;
		rtNoOfUnits = 0;
		megaplexPrimerPoolsHumanUnits = 0;
	}*/
	
	outputList.add({
		pno : spno,
		title : title,
		partnumber : partNumber,
		format : format.replace(/�/gi, '<sup>&reg;</sup>&nbsp;'),
		rtproduct : rtProduct.replace(/�/gi, '<sup>&reg;</sup>&nbsp;'),
		rtproduct1 : rtProduct1.replace(/�/gi,'<sup>&reg;</sup>&nbsp;'),
		preampproduct : preAmpProduct.replace(/�/gi,'<sup>&reg;</sup>&nbsp;'),
		rtnoofunits : rtNoOfUnits,
		rtnoofunits1 : rtNoOfUnits1,
		rtpartnumber : rtPartNumber,
		rtpartnumber1 : rtPartNumber1,
		rtcostperunit : roundNumber(rtCostPerUnit, 2),
		rtcostperunit1 : roundNumber(rtCostPerUnit1, 2),
		rtcostpersample : 0,
		rtcostpersample1 : 0,
		totalrtcost : roundNumber(totalRTCost, 2),
		totalrtcost1 : roundNumber(totalRTCost1, 2),
		preamppartnumber : preAmpPartNumber,
		preampnoofunits : preAmpNoOfUnits,
		preampcostperunit : roundNumber(preAmpCostPerUnit, 2),
		preampcostpersample : 0,
		totalpreampcost : roundNumber(totalPreAmpCost, 2),
		realtimePCRname:realtimePCRname,	
		noofunits : noofunits,
		noofreactions : noofreactions,
		mastermix : mastermix.replace(/�/gi, '<sup>&reg;</sup>&nbsp;'),
		mastermix1 : mastermix1.replace(/�/gi,'<sup>&reg;</sup>&nbsp;'),
		mnoofunits : mnoofunits,
		mnoofunits1 : mnoofunits1,
		totalcost : roundNumber(totalCost, 2),
		volumediscount : volumeDiscount,
		mvolumediscount : 0,
		mastermixdisc : masterperc,
		accessoriesdisc : accessperc,
		assayscost : roundNumber(costWithVolDisc, 2),
		assayscostperunit : roundNumber(assayCostPerUnit, 2),
		assayscostwithvoldisc : roundNumber(totalAssayCost, 2),
		assaycostpersample : 0,
		mastermixvol : 0,
		mastermixcostperunit : roundNumber(masterMixCostPerUnit, 2),
		mastermixcostperunit1 : roundNumber(masterMixCostPerUnit1, 2),
		mastermixcostwithvoldisc : roundNumber((masterMixCostPerUnit * mnoofunits), 2),
		mastermixcostwithvoldisc1 : roundNumber((masterMixCostPerUnit1 * mnoofunits1), 2),
		mastermixcostwithdisc : roundNumber(totalMasterMixCost, 2),
		mastermixcostwithdisc1 : roundNumber(totalMasterMixCost1, 2),
		mastermixcost : roundNumber((masterMixCostPerUnit * mnoofunits), 2),
		mastermixcost1 : roundNumber((masterMixCostPerUnit1 * mnoofunits1), 2),
		noofhours : noOfHours,
		rtcostperreaction : 0,
		rtcostperreaction1 : 0,
		preampcostperreaction : 0,
		assaycostperreaction : 0,
		mastermixcostperreaction : 0,
		mastermixcostperreaction1 : 0,
		accessoriescostperreaction : 0,
		optimizationcostperreaction : 0,
		totalcostperreaction : roundNumber(totalCostPerReaction, 2),
		producturl : productUrl,
		openarray384wellsampleplatescost : openArray384WellSamplePlatesCost,
		openarrayaccufillsystemtipscost : openArrayAccuFillSystemTipsCost,
		openarrayaccufillsystemtips10packcost : openArrayAccuFillSystemTips10PackCost,
		openarray384wellsampleplatesunits : openArray384WellSamplePlatesUnits,
		openarrayaccufillsystemtipsunits : openArrayAccuFillSystemTipsUnits,
		openarrayaccufillsystemtips10packunits : openArrayAccuFillSystemTips10PackUnits,
		openarrayrealtimepcraccessorieskitunits : openArrayRealTimePCRAccessoriesKitUnits,
		openarrayrealtimepcraccessorieskitcost : openArrayRealTimePCRAccessoriesKitCost,
		megaplexprimerpoolshumanunits : megaplexPrimerPoolsHumanUnits,
		megaplexprimerpoolshumancost : roundNumber(megaplexPrimerPoolsHumanCost, 2),
		rtprimerpools : rtPrimerPools,
		rtprimerpoolsnoofunits : rtPrimerPoolsNoOfUnits,
		rtprimerpoolpartnumber : rtPrimerPoolsPartNumber,
		rtprimerpoolspriceperunit : rtPrimerPoolsPricePerUnit,
		totalrtprimerpoolspricecost : totalRtPrimerPoolsPriceCost,
		totalcostpersample : roundNumber(totalCostPerSample, 2),
		accessoriescost : roundNumber(accessoriescost, 2),
		accessoriescostwithdisc : roundNumber(totalAccessoriescost, 2),
		assaycostpersample : 0,
		accessoriescostpersample : 0,
		mmxcostpersample : 0,
		mmxcostpersample1 : 0,
		totalcostpredisc : roundNumber(totalCostPreDisc, 2),
		totaldiscount : roundNumber(totalDiscount, 2),
		noofhours : hours,
		assaycostperreaction : 0,	
		producturl : productUrl,
		type : 'plate-custom',
		accessory1partnumber : acc1PartNumber,
		accessory2partnumber : acc2PartNumber,
		accessory3partnumber : acc3PartNumber,
		accessory4partnumber : acc4PartNumber,
		accessory5partnumber : acc5PartNumber,
		assay5costperUnts : assay5costperUnts,
		mastermixpartnumber : mmxPartNumber,
		mastermixpartnumber1 : mmxPartNumber1,
		preampprimerpools : preampprimerpools,
		preprimerpoolpartnumber : preampprimerpoolpartnumber,
		preprimerpoolspriceperunit : preprimerpoolspriceperunit,
		preampprimerpoolsnoofunits : preampprimerpoolsnoofunits,
		totalpreampprimerpoolspricecost : totalpreampprimerpoolspricecost,
		preampprimerpoolsreaction : preampprimerpoolsreaction,
		preampprimerpoolspricepersample : preampprimerpoolspricepersample,
		reqnoofunits : reqnoofunits,
		type : 'openarray-fixed',
		min : min,
		ismin : isMin,
		imageType:imageType,
		fnName:'addCPSmiRNAOA'
	});
}

function findApproximateCPSmiRNAOaCUSRec(type,rxn){
	var recordIndex = 0;
    var minQty = 0;
    var count = 0;
    CustomPlatingmiRNAOA.each(function (e) {
        var partNumber = e.get('partnumber');
        var regionObj = e.regions();
        if (e.get('Type') == type) {
            var qty = rxn/e.get('Samples Plate');
			//var totalqty = Math.ceil(qty/10);
           // var mprice = totalqty * regionObj.findRecord('region', region + "-" + currency).get('price');
			//console.log( e.get('Description') +" = "+mprice);
            if (minQty == 0) {
                minQty = e.get('PackType');
                recordIndex = count;
            }
            if ( minQty < minQty ) {
                price = mprice;
                recordIndex = count;
            }
        } 
        count++;
    });
    return CustomPlatingmiRNAOA.getAt(recordIndex);
}

function findApproximateOpenMirnaRecord(species) {
	species = (species == "Rat" || species == "Mouse") ? "Rodent" : species;
	var recordIndex = 0;
	var count = 0;
	mirnaAssay.each(function(record) {
		if (record.get('species') == species && record.get('producttype') == "OpenArray") {
			recordIndex = count;
			return false; // a record with this data exists

		}
		count++;
	});

	return mirnaAssay.getAt(recordIndex);
}

function findApproximateCPSmiRNAOaRec(nooftargets, type, rxn, InstrumentType){
	var recordIndex = 0;
    var minQty = 0;
    var count = 0;
	if (nooftargets <= 18) {
		nooftargets = 18;
	} else if (nooftargets >= 19 && nooftargets <= 56) {
		nooftargets = 56;
	} else if (nooftargets >= 57 && nooftargets <= 112) {
		nooftargets = 112;
	} else if (nooftargets >= 113 && nooftargets <= 168) {
		nooftargets = 168;
	} else if (nooftargets >= 169) {
		nooftargets = 224;
	}
    CustomPlatingmiRNAOA.each(function (e) {
        var partNumber = e.get('partnumber');
        var regionObj = e.regions();
        if (e.get('Type') == type && e.get('InstrumentType') == InstrumentType && e.get('Assays Plate') == nooftargets) {  				
					recordIndex = count;				
        } 
        count++;
    });
    return CustomPlatingmiRNAOA.getAt(recordIndex);
}

function addCSPTAP() {
	if(	(getExperimentInfo("ulMethod") == "96 Well Plates" ) && (getExperimentInfo('nooftargets') > 96) ){
		Ext.get('emessage').removeCls('hidden');
		updateContMessage()
		return;
	}else if( (getExperimentInfo("ulMethod") == "384 Well Plates" ) && (getExperimentInfo('nooftargets') > 384)){
		Ext.get('emessage').removeCls('hidden');
		updateContMessage()
		return;
		
	}
	var regionPrice = 0;
	Ext.get('emessage').addCls('hidden');
	
	if(getExperimentInfo('ulMethod') == "96 Well Plates"){
		var title = "Custom TaqMan<sup>&reg;</sup>&nbsp;Array 96-well Plates";
	} else {
		var title = "Custom TaqMan<sup>&reg;</sup>&nbsp;Array 384-well Plates";
	}
	var formatObj = findApproximateCSPTapRecord('nooftargets',	getExperimentInfo('nooftargets') - 1);
	var formatNo = formatObj.get('tapformat');
	
	
	var pinRec = platesCardsModel.findRecord('description', formatObj.get('tapname'));
	//var partNumber = pinRec.get('partnumber');
	//Added on 28/01/2015 based on Lini 
	if(getExperimentInfo("noofinvptargets") == 0){
		var partNumber = 4398986;
	}else{
		var partNumber = 4398985;
	}
	var description = formatObj.get('tapname');
	var format = description;
	var noofreplicates = formatObj.get('numberoftapreplicates');
	var noofsamples = formatObj.get('numberofsamplesperplate');
	var noofreaction = (getExperimentInfo('nooftargets')) * (getExperimentInfo('noofsamples') * getExperimentInfo('noofreplicates'));
	
	if(getExperimentInfo('ulMethod') == "96 Well Plates"){
		var spno = 201;
		var rxnQtyT = 96;
	}else{
		var spno = 202;
		var rxnQtyT = 384;
	}
	
	var reqnoofunits =  Math.ceil(noofreaction / rxnQtyT);
	if( getExperimentInfo("csPlatingAssayVal") != "Cast PCR"){
		var cspObj = findCustomPlatingAssays(noofreaction, getExperimentInfo('ulMethod'), rxnQtyT, "Custom/MTO assay", "Custom/MTO assay", false);
	}
	
	var cspINVAssayObj = findCustomPlatingAssays(noofreaction, getExperimentInfo('ulMethod'), rxnQtyT, "INV assays", "pre-designed assay", false);
	
	if( getExperimentInfo("csPlatingAssayVal") != "Cast PCR"){
		var minQtyObj = findCustomPlatingAssays(noofreaction, getExperimentInfo('ulMethod'), rxnQtyT, "Custom/MTO assay", "Custom/MTO assay", true);
	}else{
		var minQtyObj = findCustomPlatingAssays(noofreaction, getExperimentInfo('ulMethod'), rxnQtyT, "INV assays", "pre-designed assay", true);
	}
	
	/*if( getExperimentInfo("csPlatingAssayVal") != "Cast PCR"){
	var cspObj = cspObjArray[0];
	var cspINVAssayObj = cspObjArray[1];
	var minQtyObj = cspObjArray[2];
	}else{
		var cspObj = cspObjArray[0];
		var cspINVAssayObj = cspObjArray[1];
		var minQtyObj = cspObjArray[3];
	}*/
	
	//var noofunits = cspObj.get("Qty");
	//var reqnoofunits = cspObj.get("Qty");
	
	var min = Number(minQtyObj.get('Qty'));
	var isMin = reqnoofunits < min ? 0 : 1;
	var noofunits = reqnoofunits < min ? min : reqnoofunits;
	var cspCusCostPerUnit =	0;
	if( getExperimentInfo("csPlatingAssayVal") != "Cast PCR"){
		var cspCUSAssayPrice = parseFloat(cspObj.Regions().findRecord("region",region+"-"+currency).get('price'));
		//cspCusCostPerUnit = (getExperimentInfo("noofcsptargets")/getExperimentInfo('nooftargets')) *  cspCUSAssayPrice;
		cspCusCostPerUnit = (getExperimentInfo("noofinvptargets")/getExperimentInfo('nooftargets')) *  cspCUSAssayPrice;
	}
	var cspInvCostPerUnit = 0;
	var cspINVAssayPrice =	parseFloat(cspINVAssayObj.Regions().findRecord("region",region+"-"+currency).get('price'));
	cspInvCostPerUnit = (getExperimentInfo("noofinvptargets")/getExperimentInfo('nooftargets')) * cspINVAssayPrice;
	
	var assayCostPerUnit = cspCusCostPerUnit + cspInvCostPerUnit;
	var discountno = 0;
	var volumeDiscount = 0;
	var costWithVolDisc = noofunits * assayCostPerUnit * (1 - (volumeDiscount / 100));
	var plateperc = 0; //(Ext.get('plateperc').dom.value).split('%')[0];
	var totalAssayCost = costWithVolDisc * (1 - (plateperc / 100));
	var assayCostPerReaction = totalAssayCost/noofreaction;
	var assayCostPerSample = totalAssayCost / getExperimentInfo('noofsamples');
	
	/* Master Mix */
	if(getExperimentInfo('ulMethod') == "96 Well Plates"){
		var mvolume = (noofreaction*10)/1000;
	}else{
		var mvolume = (noofreaction*5)/1000;
	}
	var mastermixObj = findOptimumGeneMicroMMXTubeRecord(mvolume);
	var mastermix = mastermixObj.get('product');
	var mastermixPartNumber = mastermixObj.get('partnumber');
	var mnoofunits = Math.ceil(mvolume / mastermixObj.get('volume'));
	var masterMixCostPerUnit = pricelist.findRecord('partnumber', mastermixPartNumber).regions().findRecord('region', region + "-" + currency).get('price');
	var masterperc = (Ext.get('masterperc').dom.value).split('%')[0];
	var totalMasterMixCost = masterMixCostPerUnit * mnoofunits * (1 - (masterperc / 100));
	var masterMixCostPerReaction = totalMasterMixCost/totalReactions;
	var mmixCostPerSample = totalMasterMixCost / getExperimentInfo('noofsamples');
	/* End Master Mix*/
	
	if (getExperimentInfo('ulMethod') == "96 Well Plates"){		
			var hours = Math.ceil((40 * 1.2 * noofunits)/60);
	}else{
			var hours = Math.ceil((75 * 1.2 * noofunits)/60);
	}
	var totalReactions = getExperimentInfo('nooftargets') * getExperimentInfo('noofreplicates') * getExperimentInfo('noofsamples');
	var totalCost = totalAssayCost + totalMasterMixCost;
	var optimizationCostPerReaction = 0;
	var totalCostPerReaction = assayCostPerReaction + masterMixCostPerReaction + optimizationCostPerReaction;
	var totalCostPerSample = assayCostPerSample + mmixCostPerSample;
	var totalCostPreDisc = costWithVolDisc + (masterMixCostPerUnit * mnoofunits);
	var totalDiscount = 100 - (totalCost * 100 / totalCostPreDisc);
	
	var productUrl = "";
	if (getExperimentInfo('type') == "Gene Expression") {
		productUrl = "http://www.lifetechnologies.com/us/en/home/life-science/pcr/real-time-pcr/real-time-pcr-assays/taqman-gene-expression/96-well-taqman-gene-expression-assays/custom-taqman-arrayplates.html";
	} else {
		productUrl = "#";
	}
	
	outputList.add({
		pno : spno,
		title : title,
		partnumber : partNumber,
		format : format.replace(/�/gi, '<sup>&reg;</sup>&nbsp;'),
		noofunits : noofunits,
		noofreactions : totalReactions,
		mastermix : mastermix.replace(/�/gi, '<sup>&reg;</sup>&nbsp;'),
		mnoofunits : mnoofunits,
		totalcost : roundNumber(totalCost, 2),
		volumediscount : volumeDiscount,
		mvolumediscount : masterperc,
		assayscost : roundNumber(costWithVolDisc, 2),
		assayscostperunit : roundNumber(assayCostPerUnit, 2),
		assayscostwithvoldisc : roundNumber(totalAssayCost, 2),
		mastermixvol : roundNumber(mvolume, 2),
		mastermixcostperunit : roundNumber(masterMixCostPerUnit, 2),
		mastermixdisc : masterperc,
		mastermixcostwithdisc : roundNumber(totalMasterMixCost, 2),
		mastermixcostpredisc : roundNumber((masterMixCostPerUnit * mnoofunits),
				2),
		mastermixcost : roundNumber(masterMixCostPerUnit * mnoofunits, 2),
		mmxcostpersample : roundNumber(mmixCostPerSample, 2),
		assaycostpersample : roundNumber(assayCostPerSample, 2),
		totalcostpredisc : roundNumber(totalCostPreDisc, 2),
		totaldiscount : roundNumber(totalDiscount, 2),
		noofhours : hours,
		mastermixpartnumber : mastermixPartNumber,
		assaycostperreaction : roundNumber(assayCostPerReaction, 2),
		mastermixcostperreaction : roundNumber(masterMixCostPerReaction, 2),
		optimizationcostperreaction : roundNumber(optimizationCostPerReaction,
				2),
		totalcostperreaction : roundNumber(totalCostPerReaction, 2),
		totalcostpersample : roundNumber(totalCostPerSample, 2),
		producturl : productUrl,
		reqnoofunits : reqnoofunits,
		type : 'plate-custom',
		min : min,
		ismin : isMin,
		fnName:'addCSPTAP'
	});
}
function findCustomPlatingAssays( rxn, ulMethodType, rxnType, selType, selType1, isMin  ){

	var returnArray = [];
	var totQty = rxn / rxnType;
	var minQtyObj = null;
	var minInvQtyObj = null;
	var selCusObj = null;
	var selCusFormat = 0;
	var selINVObj = null;
	var selINVFormat = 0; 
	
	var cusmtoLastIndexRec = null;
	var invLastIndexRec = null;
	var cusmtoMinLastIndex = 0;
	var invMinLastIndex = 0;
	var nLastQtyRecIndex = 0;
	var nLastRecIndex = 0;
	var nPriceAtRec = 0;
	var lastMinQty = null;
	var selLastObj = null;
	var selLastIndxObj = null;
	
	//CustomPlatingRec.get(4);
	CustomPlatingRec.each(function(e){
		if(getExperimentInfo("csPlatingAssayVal") == e.get("Assay") && ulMethodType == e.get("PlateType") 
			&& (e.get("Assay Format").indexOf(selType) != -1 || e.get("Assay Format").indexOf(selType1) != -1 ) ){
				if(  getExperimentInfo("nooftargets") <= Number(e.get("Format")) && ( Number(e.get("Format")) < selCusFormat  || selCusFormat == 0) ){
					var customObj = e.QtyPrice();
					var cusCountMin = 0;
					var selCusQty = 0;
					//nPriceAtRec = 0;
					customObj.each(function(e1){
						var priceCheck = Number(e1.Regions().findRecord("region",region+"-"+currency).get('price'));
						if( priceCheck != 0 ){
							selCusFormat = Number(e.get("Format"));
							//nPriceAtRec = priceCheck;
							if( cusCountMin == 0 ){
								minQtyObj = e1;
							}
							if( totQty <= Number(e1.get("Qty")) && ( Number(e1.get("Qty")) < selCusQty  || selCusQty == 0) ){
								selCusQty = Number(e1.get("Qty"));
								selCusObj = e1;
							}else{
								selLastObj = e1;
							}
							cusCountMin ++;
							//nLastQtyRecIndex ++;
						}
					});
					/*if( nPriceAtRec != 0 ){
						nLastRecIndex ++;
					}*/
				}else{
					var customObj = e.QtyPrice();
					var countMin = 0
					var selQty = 0;
					customObj.each(function(e1){
						var priceCheck = Number(e1.Regions().findRecord("region",region+"-"+currency).get('price'));
						if( priceCheck != 0 ){
							if( countMin == 0 ){
								lastMinQty = e1;
							}
							if( totQty <= Number(e1.get("Qty")) && ( Number(e1.get("Qty")) < selQty  || selQty == 0) ){
								selQty = Number(e1.get("Qty"));
								selLastObj = e1;
							}else{
								selLastIndxObj = e1;
							}
							countMin ++;
						}
					});
				}
		}
		/*if(getExperimentInfo("csPlatingAssayVal") == e.get("Assay") && ulMethodType == e.get("PlateType") 
			&& ( e.get("Assay Format").indexOf("INV assays") != -1  || e.get("Assay Format").indexOf("pre-designed assay") != -1 ) ){
				if(  getExperimentInfo("nooftargets") <= Number(e.get("Format")) && ( Number(e.get("Format")) < selINVFormat  || selINVFormat == 0) ){
					var customObj = e.QtyPrice();
					var selINVQty = 0;
					var cusCountMin = 0;
					selINVFormat = Number(e.get("Format"));
					customObj.each(function(e1){
						var priceCheck = Number(e1.Regions().findRecord("region",region+"-"+currency).get('price'));
						if( priceCheck != 0 ){
							if( cusCountMin == 0 ){
								minInvQtyObj = e1;
							}
							if( totQty <= Number(e1.get("Qty")) && ( Number(e1.get("Qty")) < selINVQty  || selINVQty == 0) ){
								selINVQty = Number(e1.get("Qty"));
								selINVObj = e1;
							}else{
								invLastIndexRec = e1;
							}
							cusCountMin ++;
						}
					});
				}
		}*/
	});
	
	if( selCusObj == null ){
		//var selRec =  CustomPlatingRec.getAt( nLastRecIndex );
		//var selQtyRec = selRec.QtyPrice();
		//selCusObj = selQtyRec.getAt( nLastQtyRecIndex );
		if( selLastObj == null ){
			selCusObj = selLastIndxObj;
		}else{
			selCusObj = selLastObj;
		}
		minQtyObj = lastMinQty;
		//console.log(selCusObj);
	}
	if( isMin ){
		return minQtyObj;
	}else{
		return selCusObj;
	}
	/*console.log()
	if(selCusObj == null){
		selCusObj = cusmtoLastIndexRec;
	}
	if(selINVObj == null){
		selINVObj = invLastIndexRec;
		//minInvQtyObj = invLastIndexRec[1];
	}
	console.log("Returned " + selINVObj);
	returnArray.push(selCusObj);
	returnArray.push(selINVObj);
	returnArray.push(minQtyObj);
	returnArray.push(minInvQtyObj);*/
	return returnArray;
}
function toGetLastQuantity(QtyPrice, totQty){
	var selINVQty = 0;
	var cusCountMin = 0;
	var minInvQtyObj = null;
	var selINVObj = null;
	var returnArray = [];
	var lastIndex = 0;
	QtyPrice.each(function(e1){
		var priceCheck = Number(e1.Regions().findRecord("region",region+"-"+currency).get('price'));
		if( priceCheck != 0 ){
			if( cusCountMin == 0 ){
				minInvQtyObj = e1;
			}
			//console.log(e1.get("Qty"));
			if( totQty <= Number(e1.get("Qty")) && ( Number(e1.get("Qty")) < selINVQty  || selINVQty == 0) ){
				selINVQty = Number(e1.get("Qty"));
				selINVObj = e1;
			}
			cusCountMin ++;
			//console.log(totQty);
			//console.log(e1);
		}
	});
	//console.log("Return : " + selINVObj)
	returnArray.push(selINVObj);
	returnArray.push(minInvQtyObj);
}
/*
function findCustomPlatingAssays( rxn, ulMethodType, rxnType){
	var temp = ulMethodType;
	var selCusFormat = 0;
	var selObj = null;
	var count = 0;
	var lastIndex = false;
	var returnArray = [];
	var tempQty = rxn / rxnType;
	var minQtyObj = null;
	CustomPlatingRec.each(function(e){
		if(getExperimentInfo("csPlatingAssayVal") == e.get("Assay") && temp == e.get("PlateType")){
			var customObj = e.CustomAssayPlate();
			var invAssayObj = e.INVAssayPlate();
			customObj.each(function(e1){
				count ++;
				if( customObj.count() === count && selCusFormat == 0){
					lastIndex = true;
				}
				if( ( getExperimentInfo("nooftargets") <= e1.get("Format") || lastIndex ) && ( ( e1.get("Format") < selCusFormat ) || (selCusFormat == 0) ) ){
					var selCusQty = 0;
					var customqtyObj = e1.qtyprice();
					var cusCountMin = 0;
					customqtyObj.each(function(e2){
						if( e2.get("price") != 0 || e2.get("price") != 'N/A' ){
							selCusFormat = e1.get("Format");
							
						if( cusCountMin == 0 ){
						   minQtyObj =  e2;
						}
						cusCountMin ++;
						if( tempQty <= e2.get("qty") && ( ( e2.get("qty") < selCusQty ) || (selCusQty == 0) ) ){
							selCusQty = e2.get("qty");
							selObj = e2;
						}
						}
					});
				}
			});
			returnArray.push(selObj);
			count = 0;
			selCusFormat = 0;
			selObj = null;
			lastIndex = 0;
			invAssayObj.each(function(e1){
				count ++;
				if( invAssayObj.count() === count && selCusFormat == 0){
					lastIndex = true;
				}
				if( ( getExperimentInfo("nooftargets") <= e1.get("Format") || lastIndex ) && ( ( e1.get("Format") < selCusFormat ) || (selCusFormat == 0) ) ){
					var selCusQty = 0;
					
					var invqtyObj = e1.qtyprice();
					invqtyObj.each(function(e2){
						if( e2.get("price") != 0 || e2.get("price") != 'N/A' ){
							selCusFormat = e1.get("Format");
						
						if( tempQty <= e2.get("qty") && ( ( e2.get("qty") < selCusQty ) || (selCusQty == 0) ) ){
							selCusQty = e2.get("qty");
							selObj = e2;
							}
						}
					});
				}
			});
			returnArray.push(selObj);
			returnArray.push(minQtyObj);
		}
	});
	//console.log(selObj);
	return returnArray;
}
*/
function findApproximateCSPTapRecord(name, value) {
	var record = null;
	var prevRecord = null;
	if (value >= 96)
		return tacTapHelper.findRecord('tapformat', '96');
	tacTapHelper.each(function(e) {
		if (e.get(name) == value) {
			record = e;
			return false;
		} else if (e.get(name) > value) {
			if (prevRecord != null)
				record = prevRecord;
			else
				record = e;
			return false;
		}
		prevRecord = e;
	});
	return record;
}

function checkCustomAssays(){
	if($("#customAssay").is(':checked')){
		updateExperimentInfo('assayType',"Custom");
		isCPSInvent = false;
		isCPSCust = true;
		addCPSmiRNAOA();
	} else {
		updateExperimentInfo('assayType',"Inventoried");
		isCPSInvent = true;
		isCPSCust = false;
		addCPSmiRNAOA();
	}
}
function initRequiredFunction(){
	var isCPSoamiRNA = getExperimentInfo("isCPSoamiRNA");
	if ( isCPSoamiRNA ){
		updateExperimentInfo('openarrayinstrument',"QuantStudio");	
		isCPSNTCycler = false;
		isCPSQuant = true;
		
				
		/*if(getExperimentInfo("noofcsptargets") != 0){			
			updateExperimentInfo('assayType',"Custom")
			isCPSInvent = false;
			isCPSCust = true;
			addCPSmiRNAOA();
		}
		if( getExperimentInfo("noofinvptargets") != 0 && getExperimentInfo("noofcsptargets") == 0){
			updateExperimentInfo('assayType',"Inventoried");
			isCPSInvent = true;
			isCPSCust = false;
			addCPSmiRNAOA();
		}*/
		
		if($("#customAssay").is(':checked')){
			updateExperimentInfo('assayType',"Custom");
			isCPSInvent = false;
			isCPSCust = true;
			addCPSmiRNAOA();
		} else {
			updateExperimentInfo('assayType',"Inventoried");
			isCPSInvent = true;
			isCPSCust = false;
			addCPSmiRNAOA();
		}
		
		updateExperimentInfo('openarrayinstrument',"NTCycler")
		isCPSNTCycler = true;
		isCPSQuant = false;
		
		/*if(getExperimentInfo("noofcsptargets") != 0){
			updateExperimentInfo('assayType',"Custom")
			isCPSInvent = false;
			isCPSCust = true;
			addCPSmiRNAOA();
		}
		if( getExperimentInfo("noofinvptargets") != 0 && getExperimentInfo("noofcsptargets") == 0){
			updateExperimentInfo('assayType',"Inventoried");
			isCPSInvent = true;
			isCPSCust = false;
			addCPSmiRNAOA();
		}*/
		
		if($("#customAssay").is(':checked')){
			updateExperimentInfo('assayType',"Custom");
			isCPSInvent = false;
			isCPSCust = true;
			addCPSmiRNAOA();
		} else {
			updateExperimentInfo('assayType',"Inventoried");
			isCPSInvent = true;
			isCPSCust = false;
			addCPSmiRNAOA();
		}
		
	} else {
		updateExperimentInfo("ulMethod","96 Well Plates");
		addCSPTAP();
		updateExperimentInfo("ulMethod","384 Well Plates");
		addCSPTAP();
	}
	
}