//
// $Workfile:   ProductSelector.js  $
// $Revision:   1.20  $
//
// $Log:   //track01/repository/PVCS/Project Databases/Development Database/archives/Cofunds .NET/Cofunds.Web/NEWPWS/Includes/ProductSelector.js-arc  $
//
//   Rev 1.20   Sep 16 2008 11:25:34   dvalentine
//Uses the old getPPT method to create the ppt from the selected product type if in cobis screen. Logic was previously changed due to more than 10 funds requirement.
//
//   Rev 1.19   May 31 2008 15:50:44   dvalentine
//107073 - Makes sure that if the fundbasket array is null/empty, a default value is used on page load; removing the runtime error.
//
//   Rev 1.18   May 29 2008 13:24:56   dvalentine
//CR0094 - Bug spotted in KFD that cleared the fundbasket of selected funds, despite clicking on the cancel button when prompted. Looks like it worked but after trying to add another fund, the basket was cleared. Problem now rectified.
//
//   Rev 1.17   May 16 2008 12:35:52   dvalentine
//CR0094 - Functions added and changes made to facilitate more than 10 funds.
//
//   Rev 1.16   Oct 19 2007 16:01:06   rlovett
//92502 - Filter by combo text rather than value to exclude duplicates. 
//
//Filtering by value was excluding values with the same product type which excluded NPR Insured.
//
//   Rev 1.15   Jul 31 2007 10:08:54   ksandhu
//Keep previous product selected on refresh
//
//   Rev 1.14   Jul 18 2007 15:36:14   chgreaves
//Oops, hit Ctrl-X at the same time as Ctrl-S before last check-in!
//
//   Rev 1.12   Dec 05 2006 14:02:44   chgreaves
//Merge of revisions 1.11 and 1.10.1.0
//
//   Rev 1.10.1.0   Oct 30 2006 11:58:14   chgreaves
//628 - Chaged defualt selection text to be uncapitalized after first word.
//
//   Rev 1.10   Sep 05 2006 12:19:02   ksandhu
//TCL 72378 - Enable/disable KFD User details depending on portfolio selected. 
//Also renamed keyfeatures.DynamicProductList to keyfeatures.DynamicPortfolioList
//to reflect earlier change to use portfolio
//
//   Rev 1.9   Sep 03 2006 10:47:28   ksandhu
//CCR00331 - New functions used to search product/portfolio arrays for KFD All Funds functionality
//
//   Rev 1.8   Aug 02 2006 10:25:48   chgreaves
//Changed 'Product Portfolio Type' labels to 'Product'
//
//   Rev 1.7   Aug 01 2006 12:12:18   chgreaves
//Added new filter to remove ProductPortfolioTypes that do not contain any funds. This is only likely for ModelPortfolio (there's no point showing products that ultimately cannot be selected)
//
//   Rev 1.6   Jul 25 2006 10:37:28   chgreaves
//Added multicast delegate and comments
// 


//Global vars

var arrWrapper = new Array();
var arrProduct  = new Array();
var arrPPT  = new Array();

var dbMaxFunds = 0;
var autofocus = false;
var defaultMaxFundValue = 0;

function adjustFundBasketSize(basketSize)
{
    //alert('basketSize: ' + basketSize + ' and the default is: ' + defaultMaxFundValue);
    var loopMax = defaultMaxFundValue;
    
    if (basketSize !== -1)
    {
        loopMax = basketSize;
    }
      
    arrKFDFundBasket = new Array();
    
    for (var i = 0; i < loopMax; i++)
    {
        arrKFDFundBasket[i] = '';
    }
    
    return 'var arrKFDFundBasket = ' + '[' + arrKFDFundBasket.toString() + ']';
}

function getDefaultMaxFundValue(array)
{
    if (defaultMaxFundValue == 0)
    {
        defaultMaxFundValue = array.length;
    }
}

function ProductSelectorInit()
{
    
	//Checks here to see which dropdowns are available. If none are, don't bother with this and jump to fundselecion part.
	//if none of these dropdowns are shown
	if (ddlWrapper() ==null && ddlProduct()==null && ddlProductPortfolioType()==null)
	{
		PopulateFundSelectorFromValue(SelectedPPT);
	}
	else
	{

		//Filter Product/Portfolio data

		arrPPT = FilterPPTByManagementCompany();			//This should always happen (we'll always have a management company defined)

		arrPPT = FilterPPTByFunction(arrPPT);				//This should always happen (we'll always have a function)

		arrPPT = FilterPPTByIntermediaryAvailable(arrPPT);	//Should always have an intermediary;

		if (typeof(arrProductGrid)!='undefined')
			arrPPT = FilterByFundsAvailable(arrPPT);		//This will only really change with ModelPortfolio
	
		//if (ddlProductPortfolioType() != null)	//This prevents the ddlProduct getting disabled once you select a single product
		//	arrPPT = FilterPPTByPortfolioType();	

		arrProduct = FilterProductByPPT();	
		
		//Clear dropdowns
		clearDropDown(ddlProduct(),"Select product");
		clearDropDown(ddlProductPortfolioType(),"Select product");

		//Begin populating		
		PopulateProduct("");
	}
}


//Filter Functions
function FilterPPTByManagementCompany()
{
	var i=0;
	var j=0;

	var filteredArray = new Array();
	
	for (i=0;i<ProductPortfolioTypeData.length;i++)
	{
		match = false;
		for(j=0;j<ProductData.length;j++)
		{
			if ((ProductPortfolioTypeData[i][PRODUCTPORTFOLIOTYPEDATA_PRODUCTCODE]==ProductData[j][PRODUCTDATA_PRODUCTCODE]) &&
				(SelectedManagementCompanyCode == ProductData[j][PRODUCTDATA_MANAGEMENTCOMPANYCODE]) )
			{
			
				filteredArray[filteredArray.length] = ProductPortfolioTypeData[i];
				
				
			}
		
		}
			
	}

	return filteredArray;

}


function FilterPPTByFunction()
{
	var i=0;
	var j=0;

	var filteredArray = new Array();
	

	for (i=0;i<arrPPT.length;i++)
	{
		match = false;
		for(j=0;j<FunctionData.length;j++)
		{
			////alert("arrPPT[i][PRODUCTPORTFOLIOTYPEDATA_PRODUCTCODE]==FunctionData[j][FUNCTIONDATA_PRODUCTCODE]\n"			+arrPPT[i][PRODUCTPORTFOLIOTYPEDATA_PRODUCTCODE]+"\t\t--\t\t"+FunctionData[j][FUNCTIONDATA_PRODUCTCODE]			+ (arrPPT[i][PRODUCTPORTFOLIOTYPEDATA_PRODUCTCODE]==FunctionData[j][FUNCTIONDATA_PRODUCTCODE]) );
			if ((arrPPT[i][PRODUCTPORTFOLIOTYPEDATA_PRODUCTCODE]==FunctionData[j][FUNCTIONDATA_PRODUCTCODE]) &&
				(arrPPT[i][PRODUCTPORTFOLIOTYPEDATA_PORTFOLIOTYPE]==FunctionData[j][FUNCTIONDATA_PORTFOLIOTYPE]) &&
				(SelectedFunction.toUpperCase()  == FunctionData[j][FUNCTIONDATA_FUNCTIONCODE].toUpperCase()) )
			{
			
				filteredArray[filteredArray.length] = arrPPT[i];	
				
			}
		
		}
			
	}

	//alert(filteredArray.length+"\n\n"+filteredArray)
	return filteredArray;
}

function FilterPPTByIntermediaryAvailable()
{
	if (typeof(AvailableProductData)=="undefined")
		return arrPPT;
		
	var i=0;
	var j=0;

	var filteredArray = new Array();
	
	for (i=0;i<arrPPT.length;i++)
	{
		match = false;
		for(j=0;j<AvailableProductData.length;j++)
		{
			
			if ((arrPPT[i][PRODUCTPORTFOLIOTYPEDATA_PRODUCTCODE] == AvailableProductData[j][AVAILABLEPRODUCTDATA_PRODUCTCODE]) &&
				(arrPPT[i][PRODUCTPORTFOLIOTYPEDATA_PORTFOLIOTYPE] == AvailableProductData[j][AVAILABLEPRODUCTDATA_PORTFOLIOTYPE]) &&
				(AvailableProductData[j][AVAILABLEPRODUCTDATA_AVAILABLE]=="True") )
			{
						
				filteredArray[filteredArray.length] = arrPPT[i];
				
			}
		
		}
			
	}

	return filteredArray;
}

function FilterByFundsAvailable()
{
	
		
	var i=0;
	var j=0;

	var productcode;
	var portfoliotype;
	var filteredArray = new Array();
	
	for (i=0;i<arrPPT.length;i++)
	{
			for (j=0;j<arrProductGrid.length;j++)
			{
				productcode		= arrProductGrid[j][0].split("_")[0];
				portfoliotype	= arrProductGrid[j][0].split("_")[1];
				
				if (arrPPT[i][PRODUCTPORTFOLIOTYPEDATA_PORTFOLIOTYPE].toUpperCase() == portfoliotype.toUpperCase()
					&&arrPPT[i][PRODUCTPORTFOLIOTYPEDATA_PRODUCTCODE].toUpperCase() == productcode.toUpperCase()
				)
				{
				
					filteredArray[filteredArray.length] = arrPPT[i];
					
				}			
			}
	}

	return filteredArray;
}

function FilterPPTByPortfolioType()
{
	if (typeof(SelectedPortfolioType)=="undefined" || SelectedPortfolioType=="")
		return arrPPT;
	
		
	var i=0;
	var j=0;

	var filteredArray = new Array();
	
	for (i=0;i<arrPPT.length;i++)
	{
			if (arrPPT[i][PRODUCTPORTFOLIOTYPEDATA_PORTFOLIOTYPE].toUpperCase() == SelectedPortfolioType.toUpperCase())
			{	
				filteredArray[filteredArray.length] = arrPPT[i];
			}			
	}

	return filteredArray;
}


function FilterProductByPPT()
{
	var i=0;
	var j=0;

	var filteredArray = new Array();
	
	for (i=0;i<ProductData.length;i++)
	{
		match = false;
		for(j=0;j<arrPPT.length;j++)
		{
			if ((ProductData[i][PRODUCTDATA_PRODUCTCODE].toUpperCase() == arrPPT[j][PRODUCTPORTFOLIOTYPEDATA_PRODUCTCODE].toUpperCase() ))
			{
			
				filteredArray[filteredArray.length] = ProductData[i];
			
			}
		
		}
			
	}

	//alert(filteredArray.length+"\n\n"+filteredArray)
	return filteredArray;

}



function PopulateProduct(selected)
{

	var availableProduct = arrProduct;

	var ProductSelect = ddlProduct();
	var selected = '';

	if (ProductSelect != null)
	{
		Enable(ProductSelect);
	
		clearDropDown(ProductSelect,"Select product");
		
		selected = PopulateDropDownList(ProductSelect,availableProduct,PRODUCTDATA_PRODUCTNAME,PRODUCTDATA_PRODUCTCODE,SelectedProduct);
			
		if (FundSelectorDisabled) Disable(ProductSelect);
	}
	else
	{
		if (SelectedProduct!='')
		{
			selected = SelectedProduct;//if the drop down isn't present, a value should be set at compile-time
		}
		else
		{
			if(availableProduct.length == 1)
				selected = availableProduct[0][PRODUCTDATA_PRODUCTCODE];
			//else
				//alert("Error! No Product selected!\nIgnoreProduct : "+IgnoreProduct);
		}
	}	
	SelectedProduct = '';//need to get rid of it after setting, otherwise it won't change when wrapper changes!
	
	PopulateProductPortfolioType(selected);	
}

function PopulateProductPortfolioType(selected)
{

	var availableProductPortfolioTypes; 
	availableProductPortfolioTypes = getAvailableProductPortfolioTypes("");
	    
	var PPTSelect = ddlProductPortfolioType()
	var selected;
	
	if (PPTSelect != null)
	{
		
		Enable(PPTSelect);
		
		clearDropDown(PPTSelect,"Select product");

        //KSS - 
		selected = PopulatePPTDropDownList(PPTSelect,availableProductPortfolioTypes,PRODUCTPORTFOLIOTYPEDATA_PRODUCTPORTFOLIOTYPENAME,PRODUCTPORTFOLIOTYPEDATA_PRODUCTCODE,PRODUCTPORTFOLIOTYPEDATA_PORTFOLIOTYPE,selected);
		//selected = PopulatePPTDropDownList(PPTSelect,availableProductPortfolioTypes,PRODUCTPORTFOLIOTYPEDATA_PRODUCTPORTFOLIOTYPENAME,PRODUCTPORTFOLIOTYPEDATA_PRODUCTCODE,PRODUCTPORTFOLIOTYPEDATA_PORTFOLIOTYPE,PPTSelect);
		//selected = PopulateDropDownList(PPTSelect,availableProductPortfolioTypes,PRODUCTPORTFOLIOTYPEDATA_PRODUCTPORTFOLIOTYPENAME,PRODUCTPORTFOLIOTYPEDATA_PRODUCTCODE,selected);
	
		if (FundSelectorDisabled) 
			Disable(PPTSelect);
		PopulateFundSelector(selected);
	}
	else
	{
		//We don't have a dropdown, is there a pre-set value?
		if (SelectedPPT!='')
		{
			PopulateFundSelectorFromValue(SelectedPPT);
		}
		else
		{
			if(availableProductPortfolioTypes.length == 1)
			{
				selected = availableProductPortfolioTypes[0][PRODUCTPORTFOLIOTYPEDATA_PRODUCTPORTFOLIOTYPENAME];
			}
			//else
				//alert("Error! No Product Portfolio Type selected!");
			PopulateFundSelector(selected);
		}
	}
	SelectedPPT = ''; //need to get rid of it after setting, otherwise it won't change when product changes!
}

function PopulateFundSelector(selected)
{
    var position = selected.toString().indexOf("_");

    if (position >= 0)
    {
        if (selected.toUpperCase() != selectedProduct || selectedProduct == "")
        {
	        //Set the maximum funds allowed depending on product-portfoliotype
	        dbMaxFunds = getMaxFundsAllowed(selected);
    	    
	        try
	        {
	            getDefaultMaxFundValue(arrKFDFundBasket);
	        }
	        catch(err)
	        {
	            //Quick and dirty fix for when the arrKFDFundBasket object is null
	            //Only affects the initial page load
	            defaultMaxFundValue = 10;
	        }
    	    
	        adjustFundBasketSize(dbMaxFunds);
    	    
	        //Populate the fund selector part
            PopulateFundSelectorFromValue(selected);
	    }
    }
    else
    {
        var selectedPPT = getPPT(selected);
        PopulateFundSelectorFromValue(selectedPPT);
    }
}

function PopulateFundSelectorFromValue(selectedPPT)
{
	//Set it for postback
	if (txtSelectedPPT()!=null)
		txtSelectedPPT().value = selectedPPT;
		
	//calls into the fundselector.js code
	setProductType(selectedPPT);
	
	if (ddlFund()!=null && ddlFundMan()!=null)
		PopulateFundManagers(ddlFund(), ddlFundMan()); 	
}

//Gets the ProductPortfolioType composite key to look up available funds in arrProductGrid
function getPPT(selected)
{
	var ret = ''
	for (var i=0;i<arrPPT.length;i++)
	{
		if(arrPPT[i][PRODUCTPORTFOLIOTYPEDATA_PRODUCTCODE] == selected)
		{
			ret = arrPPT[i][PRODUCTPORTFOLIOTYPEDATA_PRODUCTCODE]+"_"+arrPPT[i][PRODUCTPORTFOLIOTYPEDATA_PORTFOLIOTYPE]
		}
		
	}
	return ret;
}

function getAvailableProductPortfolioTypes(selectedProductCode)
{
	if (selectedProductCode=='' && IgnoreProduct)
		return arrPPT;
		
	var availablePPTS = new Array();
	
	for (var i=0;i<arrPPT.length;i++)
	{
		if (arrPPT[i][PRODUCTPORTFOLIOTYPEDATA_PRODUCTCODE].toUpperCase()==selectedProductCode.toUpperCase())
		{
			availablePPTS[availablePPTS.length] = arrPPT[i];
		}
	}
	return availablePPTS;
}


//General function to populate a specified field with values from the array. parameters text and value are indexes in the array
function PopulateDropDownList(field, array, text, value,selected)
{
	var c=0;
	Enable(field);
	
	//currSelected = (field.selectedIndex===-1) ? '' : field.options[field.selectedIndex].value;
	var currSelected = (field.selectedIndex<2) ? selected : field.options[field.selectedIndex].value;
	var result = '';
	//populate the dropdown with the specified values
	for (var i=0;i<array.length;i++)
	{
		var c=0;
		for (;c<field.length;c++)
			if(field.options[c].text == array[i][text])
				break;
		
		if (c<field.length)
			continue;

		field.options[field.length] = new Option(array[i][text],array[i][value]);
		//if this was selected before, leave it.
		if (array[i][value]==currSelected)
		{
			field.selectedIndex = field.length - 1;
			result = currSelected;
		}
	}
	
	
	//if its the only option, set it and return the set option's value.
	if (array.length===1)
	{
		field.selectedIndex = field.length-1;
		Disable(field);
		return field.options[field.length-1].value;
	}

	//if there are no options, disable it.
	if (array.length===0)
	{
		field.selectedIndex = 0;
		Disable(field);
	}

	if (!field.disabled && autofocus) field.focus();
	
	return result;
	
}

//Function to populate a PPT field with values from the array. parameters text and value are indexes in the array
function PopulatePPTDropDownList(field, array, text, value, type, selected)
{
	var c = 0;
	Enable(field);
	var currSelected = (field.selectedIndex < 2) ? selected : field.options[field.selectedIndex].value;
	var result = '';
	
	//populate the dropdown with the specified values
	for (var i = 0; i < array.length; i++)
	{
		var c = 0;
		for (;c < field.length; c++)
		{
			if(field.options[c].text == array[i][text])
			{
				break;
			}
		}
		
		if (c < field.length)
	    {
			continue;
		}
		
        var pptString = array[i][value] + "_" + array[i][type];
		field.options[field.length] = new Option(array[i][text], pptString);
		
		//if this was selected before, leave it.
		if (array[i][value] == currSelected)
		{
			field.selectedIndex = field.length - 1;
			result = currSelected;
		}
	}
		
	//if its the only option, set it and return the set option's value.
	if (array.length === 1)
	{
		field.selectedIndex = field.length - 1;
		Disable(field);
		
		return field.options[field.length - 1].value;
	}

	//if there are no options, disable it.
	if (array.length === 0)
	{
		field.selectedIndex = 0;
		Disable(field);
	}

	if (!field.disabled && autofocus)
	{
	    field.focus();
	}
	
	return result;
}

//Custom validator functions
function ValidateWrapper(source,arguments)
{
	var ddl = ddlWrapper();
	if (ddl==null)
	{
		arguments.IsValid = true;
		return;
	}
	if(ddl.options[ddl.selectedIndex].value!="-1")
	{
		SelectedPPT = "";
		arguments.IsValid = true;
	}
	else
	{
		source.errormessage = "Please select a valid Product Group.";
		arguments.IsValid = false;
	}
	return;
}

function ValidateProduct(source,arguments)
{
	var ddl = ddlProduct();
	if (ddl==null)
	{
		arguments.IsValid = true;
		return;
	}
	if(ddl.selectedValue!="-1")
	{
		arguments.IsValid = true;
	}
	else
	{
		source.errormessage = "Please select a valid Product.";
		arguments.IsValid = false;
	}
	return;
}

function ValidateProductPortfolioType(source,arguments)
{
	var ddl = ddlProductPortfolioType();
	if (ddl==null)
	{
		arguments.IsValid = true;
		return;
	}
	if(ddl.selectedValue!="-1")
	{
		arguments.IsValid = true;
	}
	else
	{
		source.errormessage = "Please select a valid Product";
		arguments.IsValid = false;
	}
	return;
}

var ucProductSelector_PptChangedEvent = new MultiCastDelegate();

function RaisePptChangedEvent(ppt)
{
    //alert("ucProductSelector_PptChangedEvent: param: " + ppt);
	var eventArgs = new MultiCastDelegate_EventArgs(ppt);
	ucProductSelector_PptChangedEvent.RaiseEvent(eventArgs);
    //alert("typeof KFDEnableUserDetails: " + (typeof KFDEnableUserDetails));
	//Check if we're on KFD page by checking existance of KFDEnableUserDetails function
	//KFDEnableUserDetails in kfd.js and enables/disables user details depending on portfolio type
	if (typeof KFDEnableUserDetails != 'undefined'){KFDEnableUserDetails(ppt);}
}

function GetarrProductGridIndex(productcodeparm,portfoliotypeparm,servOffparm)
{
//Return index of matching product/portfolio/serviceoffering in arrProductGrid
	var intIndex = -1
	for(k=0;j<arrProductGrid.length;k++)
	{
		//Find matching product/portfolio/serviceoffering in arrProductGrid
		if ((productcodeparm==arrProductGrid[k][0].split("_")[0]) &&
			(portfoliotypeparm==arrProductGrid[k][0].split("_")[1]) &&
			(servOffparm==arrProductGrid[k][1]))
			{
				intIndex=k;
				break;
			}
	}
	
	return intIndex;
}

function getMaxFundsAllowed(selectedProductPortfolioType)
{
    //Give dbMaxFunds a default value
    var dbMaxFundValue = -1;
    var productCode;
    var portfolioType;
    var portfolioTypeSettingColumns = selectedProductPortfolioType.split("_");   
    productCode = portfolioTypeSettingColumns[0];
    portfolioType = portfolioTypeSettingColumns[1];
    
    for (var i = 0; i < ProductPortoflioTypeSettingsData.length; i++)
    {
        if (ProductPortoflioTypeSettingsData[i][PRODUCTPORTOFLIOTYPESETTINGSDATA_PORTFOLIOTYPE] == portfolioType
            && ProductPortoflioTypeSettingsData[i][PRODUCTPORTOFLIOTYPESETTINGSDATA_PRODUCTCODE] == productCode
            && ProductPortoflioTypeSettingsData[i][PRODUCTPORTOFLIOTYPESETTINGSDATA_SETTINGNAME] == "MaximumFundsAllowed")
        {
            dbMaxFundValue = ProductPortoflioTypeSettingsData[i][PRODUCTPORTOFLIOTYPESETTINGSDATA_SETTINGVALUE];
        }
    }
    
    return dbMaxFundValue;
}

function ProductCodeManagementCompanyExists(productcodeparm,managementcompanycodeparm)
{
//Check if product/managementcompany exists in ProductData
	var blnExists=false
	for(k=0;k<ProductData.length;k++)
	{
		if ( (ProductData[k][PRODUCTDATA_PRODUCTCODE]==productcodeparm) &&
			(ProductData[k][PRODUCTDATA_MANAGEMENTCOMPANYCODE]==managementcompanycodeparm) )
			{
				blnExists=true;
				break;
			}
	}
	return blnExists;
}

