
/* Global variables */
var ChartingColors = "";
var unitCodeChangeable = true;
var ageStatus = "show5yrs";
var instrumentAges = "";


/* Tab and corresponding table to make visible */
function ChangeTabs(tab)
{
	document.getElementById('PriceInc').className = (tab == 'Income' ? 'tabOn' : 'tabOff');
	document.getElementById('PriceAcc').className = (tab == 'Accumulation' ? 'tabOn' : 'tabOff');
	
	document.getElementById('tabInc').className = (tab == 'Income' ? 'tab act' : 'tab');
	document.getElementById('tabAcc').className = (tab == 'Accumulation' ? 'tab act' : 'tab');
	document.getElementById('unittype').value = (tab == 'Income' ? 'Inc' : 'Acc'); 
}

/* For retaining month dropdown and tab selection */
function RetainDropdowns(id)
{
    if(id != "")
    {
        var selectValue = getQueryValue(id);
        RetainSelection(id, selectValue);
        
        var t = new Date;
        //selectValue = (getQueryValue("Month") == '') ? t.getMonth()+1 : getQueryValue("Month");
        selectValue = (getQueryValue("Month") == '') ? '1' : getQueryValue("Month");
        RetainSelection('Month', selectValue);
    }
    var unitType = getQueryValue("unittype");
    if(unitType.indexOf("Inc") >= 0)
    {
        ChangeTabs("Income");
    }
    else if(unitType.indexOf("Acc") >= 0)
    {
        ChangeTabs("Accumulation");
    }
}

/* To make given value as selectedvalue for specifed dropdown*/
function RetainSelection(selectid, selectValue)
{
	var selectCtrl = document.getElementById(selectid);
	for (i=0; i < selectCtrl.options.length; i++) 
	{
		if (selectCtrl.options[i].value == selectValue) 
		{
			selectCtrl.selectedIndex = i;
		}
	}
}

/* Redirect to specified url with current tab selection */
function RedirectToPage(url)
{
    if(document.getElementById("PriceInc").className == "tabOn")
    {
        window.location = url + "?unittype=Inc"
    }
    else
    {
        window.location = url + "?unittype=Acc"
    }
}

/* Methods to be called at pageload */
function InitializeData()
{
    var defaultCode = getValue('hdDefaultCode');
    //GetElementById("ddTimeScale").selectedIndex = 1;
    loadTimeValues('Y', 'slctTimevalue');
    CreateHeader(true);
    LoadFundValues(false);
    if(defaultCode != "")
    {
        addToChart(defaultCode, false);
    }
    RetainSelection("Unit", defaultCode);
    LoadFundValues(true);
}

/* Loading units from hidden variable and units change event makes it sector loading for corresponding unit */
function LoadFundValues(isLoadSector)
{
    var AllFunds = GetElementById('hdFundList').value;
	var menuFunds = GetElementById('Unit');
	var menuSectors = GetElementById('Sector');
	menuSectors.options.length = 0;

	var slctIndex = 0, i, fundcount = 0;
	var dataArr = new Array();
	var optioncategory = new Array();
	var options;
	
	dataArr = AllFunds.split(";");
	
	for (i=0; i<dataArr.length; i++) 
	{
		options = dataArr[i];
		optionCollection = options.split("!");
		
		var fundOption = optionCollection[0].split(",");
        var fundName = fundOption[0];
        var fundValue = fundOption[1];
        
        if(!isLoadSector)
        {
            var chkflag = true;
	        for(var opt=0; opt<menuFunds.options.length; opt++)
	        {
		        if(menuFunds.options[opt].value == fundValue)
		        {
			        chkflag = false;
		        }
	        }
	        if(chkflag == true && fundName != '' && fundValue != '')
	        {
		        menuFunds.options.add(new Option(fundName, fundValue.replace('#','')), 0);
	        }
	    }
	    else if(fundValue != undefined)
	    {
	        var img = GetElementById("ChartImg");
	        var currSrc = img.src;
	        var allCodes = parseURL(currSrc, "codes");
	        var unitValue = getValue("Unit");
	        unitValue = unitValue.replace('#','');
	        var codeArray = allCodes.split(",");
	        
	        var isCodeFound = false;
	        for(var l=0; l<codeArray.length; l++)
	        {
	            if(codeArray[l] == unitValue)
	            {
	                isCodeFound = true;
	            }
	        }

	        if(!isCodeFound && codeArray[0] != "")
	        {
	            GetElementById("Sector").disabled = true;
	        }
	        else if(isCodeFound && codeArray.length == 1)
	        {
	            GetElementById("Sector").disabled = false;
	        }
	        
	        if(fundValue.replace('#','') == getValue('Unit') && getValue('Unit') != "" && optionCollection[1] != null)
	        {
	            var sectorOption = optionCollection[1].split(",");
                var sectorName = sectorOption[0];
                var sectorValue = sectorOption[1];
                var chkflag = true;
                
	            for(var opt=0; opt<menuSectors.options.length; opt++)
	            {
		            if(menuSectors.options[opt].value == sectorValue)
		            {
			            chkflag = false;
		            }
	            }
	            if(chkflag == true && sectorName != '' && sectorValue != '')
	            {
	                var img = GetElementById("ChartImg");
	                var currSrc = img.src;
	                var sectorCode = parseURL(currSrc, "sector");
	                if(sectorCode.indexOf(sectorValue) >= 0)
	                {
	                    unitCodeChangeable = true;
	                }
		            menuSectors.options.add(new Option(sectorName, sectorValue.replace('#','')), 0);
	            }
	        }
	    }
	}
	if(!isLoadSector)
	{
	    menuFunds.options.add(new Option("Choose a Fund", ""), 0);
        menuFunds.selectedIndex = 0;
    }
    if(menuSectors.options.length == 0)
    {
        menuSectors.options.add(new Option("Choose a Sector", ""), 0);
        menuSectors.selectedIndex = 0;
    }
}


/* 
	Adds a code to the chart, will only add a chart code to the IMG if the 
	code has not already been selected.
*/
function addToChart(code, isSector)
{
    if(code != '')
    {
	    //Get a reference to the ChartBuilder.aspx image area
	    var img = GetElementById("ChartImg");
	    var currSrc = img.src;
	    var newSrc;				
    	
	    //"codes" refers to the codes used for the image
	    var allCodes = parseURL(currSrc, "codes");
	    var hiddenCodes = parseURL(currSrc, "hide");
	    var span = parseURL(currSrc, "span");
	    var sectorCode = parseURL(currSrc, "sector");

	    var arrAllCodes = new Array();
    	
	    //Retrieve a comma delimited list of all codes
	    if (allCodes != "")
	    {
		    arrAllCodes = allCodes.split(",");
	    }
	    var len = arrAllCodes.length;		
    	
	    var isNotPresent = true;
	    for(j=0; j<len; j++)
	    {
		    if(arrAllCodes[j] == code)
		    {
			    isNotPresent = false;
		    }
	    }

	    var codeAddedToChart = false;
	    
	    //If the code is not already on the graph, then it needs to be added
	    if (isNotPresent && code != '')
	    {
		    //Add the code to the array
		    if(isSector && sectorCode == '' && GetElementById("Sector").disabled == false)
		    {
		        sectorCode = code;
		        codeAddedToChart = true;
		        if(allCodes != '')
		        {
		            GetElementById("Sector").disabled = true;
		        }
		        GetElementById("Unit").disabled = true;
		    }
		    else if(!isSector && GetElementById("Unit").disabled == false)
		    {
		        if(unitCodeChangeable)
		        {
		            arrAllCodes[len] = code;
		            codeAddedToChart = true;
		            if(len >= 0 && sectorCode != '')
		            {
		                GetElementById("Unit").disabled = true;
		            }
		        }
		        else
		        {
		            alert("Instrument cannot be added for different sector");
		        }
		        if(len >= 1 || sectorCode != '')
		        {
		            GetElementById("Sector").disabled = true;
		        }
		    }
		    else if(sectorCode != code && code != '')
		    {
		        alert("Instrument cannot be added for different sector");
		    }

		    // Verify instrument Ages for column show/hide
		    if(codeAddedToChart)
		    {
		        var verifyAge = getValue("hdVerifyAge");
	            var ageArr = verifyAge.split(",");
	            var currAgeStatus = "show5yrs";
	            if(!isSector)
	            {
	                var selectIndex = GetElementById("Unit").selectedIndex-1;
	                if(selectIndex > -1)
	                {
	                    currAgeStatus = ageArr[GetElementById("Unit").selectedIndex-1];
	                }
	            }
	            instrumentAges += (instrumentAges != "") ? "," +code+ "~" +currAgeStatus : code+ "~" +currAgeStatus;
	            var instrAgeArr = instrumentAges.split(",");

	            var isToHide5yrs = false;
	            for(var k=0; k<instrAgeArr.length; k++)
	            {
	                var ageCodeArr = instrAgeArr[k].split("~");
	                if(ageCodeArr[1] == "hide5yrs")
	                {
	                    isToHide5yrs = true;
	                }
	            }
	            ageStatus = (isToHide5yrs) ? "hide5yrs" : "show5yrs";
	        }
			
		    //Concatenate array elements into a single string
		    var strCodes = arrAllCodes.join();
			
		    //Add new codes to the IMG tag source
		    newSrc = "chartbuilder.aspx?codes=" + strCodes + "&hide=" + hiddenCodes + "&span=" + span + "&sector=" + sectorCode;
		    img.src = newSrc;

		    UpdatePerfTable(strCodes, sectorCode);
	    }
	    else 
	    {
		    //No changes were needed to the graph
		    img.src=currSrc;
	    }
	}
}

/* Update performance table triggered at add-to-chart or remove-from-chart */
function UpdatePerfTable(strCodes, sectorCode)
{
    var arrAllCodes = strCodes.split(",");
    if (GetElementById('PerfTables', false) != null)
    {
        var updateCodes = "";
        var sectorValueCode; 
        for(var l=0; l<arrAllCodes.length; l++)
        {
            var updateCodeArr = arrAllCodes[l].split("@");
            if(updateCodeArr[0] != "" && updateCodeArr[1] != "")
            {
                if(ChartingColors.indexOf(updateCodeArr[1]) < 0)
                {
                    ChartingColors += (ChartingColors != "") ? "," + updateCodeArr[1] : updateCodeArr[1];
                }
                updateCodes += (updateCodes == "") ? updateCodeArr[0] : "," + updateCodeArr[0];
            }
        }
        if(sectorCode != "")
        {
            sectorValueCode = sectorCode.split("@");
            if(sectorValueCode[0] != "")
            {
                updateCodes += (updateCodes == "") ? sectorValueCode[0] : "," + sectorValueCode[0];
            }
        }        
	    cws.LoadPerformance(updatePerformanceTables, updateCodes);
    }
}

/* Changing span value at chart */
function UpdateSpan()
{
    var img = GetElementById("ChartImg");
    var currSrc = img.src;
    
    var allCodes = parseURL(currSrc, "codes");
    var hiddenCodes = parseURL(currSrc, "hide");
    var sectorCode = parseURL(currSrc, "sector");
    var span = getValue('slctTimevalue');
    ChartUpdate(allCodes, hiddenCodes, span, sectorCode);
}

/* Making show/hide of code in chart */
function ChangeChart(code)
{
    var img = GetElementById("ChartImg");
    var currSrc = img.src;
    
    var allCodes = parseURL(currSrc, "codes");
    var hiddenCodes = parseURL(currSrc, "hide");
    var sectorCode = parseURL(currSrc, "sector");
    var span = parseURL(currSrc, "span");
    
    var ctrl = GetElementById("cb" + code);
    var aHideCodes = hiddenCodes.split(",");
    
    var alreadyHidden = false;
    for(var i=0; i<aHideCodes.length; i++)
    {
        if(aHideCodes[i] == code)
        {
            alreadyHidden = true;
        }
    }
    if(!alreadyHidden && ctrl.checked == false)
    {
        hiddenCodes += (hiddenCodes != "") ? "," + code : code;
    }
    
    else if(ctrl.checked)
    {
        var hCodeArr = hiddenCodes.split(",");
        for(var i=0; i<hCodeArr.length; i++)
        {
            if(hCodeArr[i] == code)
            {
                hCodeArr.splice(i, 1);
            }
        }
        hiddenCodes = hCodeArr.join();
    }
    ChartUpdate(allCodes, hiddenCodes, span, sectorCode);
}

/* Removing instrument from the chart and performance table */
function RemoveCode(code)
{
    var img = GetElementById("ChartImg");
    var currSrc = img.src;
    var allCodes = parseURL(currSrc, "codes");
    var hiddenCodes = parseURL(currSrc, "hide");
    var sectorCode = parseURL(currSrc, "sector");
    var span = parseURL(currSrc, "span");
    var aCodeArr = allCodes.split(",");
    var aHCodeArr = hiddenCodes.split(",");
    
    for(var i=0; i<aCodeArr.length; i++)
    {
        var codeTempArr = aCodeArr[i].split("@");
        if(codeTempArr[0] == code)
        {
            var aColors = ChartingColors.split(",");
            for(var j=0; j<aColors.length; j++)
            {
                if(aColors[j] == codeTempArr[1])
                {
                    aColors.splice(j, 1);
                    GetElementById("Unit").disabled = false;
                    if(sectorCode != "")
                    {
                        unitCodeChangeable = false;
                    }
                }
            }
            ChartingColors = aColors.join();
            aCodeArr.splice(i, 1);
        }
    }
    for(var i=0; i<aHCodeArr.length; i++)
    {
        if(aHCodeArr[i].indexOf(code + "@") >= 0)
        {
            aHCodeArr.splice(i, 1);
        }
    }
    if(sectorCode.indexOf(code) >= 0)
    {
        if(aCodeArr.length > 1)
        {
            GetElementById("Sector").disabled = true;
        }
        else
        {
            GetElementById("Sector").disabled = false;
        }
        GetElementById("Unit").disabled = false;
        sectorCode = "";
    }
    if(aCodeArr.length == 1 && sectorCode == "")
    {
        RetainSelection("Unit", aCodeArr[0]);
        LoadFundValues(true);
        GetElementById("Sector").disabled = false;
    }
    if(allCodes == "" && sectorCode == "")
    {
        GetElementById("Unit").disabled = false;
        GetElementById("Sector").disabled = false;
        unitCodeChangeable = true;
    }
    if(sectorCode != "" && aCodeArr.length == 0)
    {
        GetElementById("Unit").disabled = false;
    }
    
    // Verify instrument age for 5yr perf show/hide
    var instrAgeArr = instrumentAges.split(",");
    var isToHide5yrs = false;
    for(var k=0; k<instrAgeArr.length; k++)
    {
        var ageCodeArr = instrAgeArr[k].split("~");
        if(ageCodeArr[0].indexOf(code+"@") >= 0)
        {
            instrAgeArr.splice(k, 1);
        }
    }
    instrumentAges = instrAgeArr.join();
    instrAgeArr = instrumentAges.split(",");
    for(var k=0; k<instrAgeArr.length; k++)
    {
        var ageCodeArr = instrAgeArr[k].split("~");
        if(ageCodeArr[1] == "hide5yrs")
        {
            isToHide5yrs = true;
        }
    }
    ageStatus = (isToHide5yrs) ? "hide5yrs" : "show5yrs";
    // End instrument age
    
    allCodes = aCodeArr.join();
    hiddenCodes = aHCodeArr.join();
    ChartUpdate(allCodes, hiddenCodes, span, sectorCode);
    UpdatePerfTable(allCodes, sectorCode);
}

/* Update chart with specifed codes, hiddencodes and span */
function ChartUpdate(allCodes, hideCodes, span, sector)
{
	GetElementById("ChartImg").src = "chartbuilder.aspx?codes=" + allCodes + "&hide=" + hideCodes + "&span=" + span + "&sector=" + sector;		
}


/* 
	Parse the URL and retrieve a list of all codes, the hide flag and how many
	months to span the performance data over. Only used for the performance chart
	querystring.
*/
function parseURL(url,r){
	
	var strReturn = "";
				
	var aUrl = url.split("?");					
	var scriptName = aUrl[0];
	
	var allCodes="";
	var hideCodes="";
	var span = "";
	var sector = "";
	
	var qStr = new Array();
	var qCodes = new Array();
	var qHide = new Array();
	var qSpan = new Array();
	var qSector = new Array();
					
	if (aUrl.length > 1){
	
		qStr = aUrl[1].split("&");
		
		qCodes = qStr[0].split("=");
			allCodes = qCodes[1];
		
		if (qStr.length > 1){						
			qHide = qStr[1].split("=");	
			hideCodes = qHide[1];				
		}
		
		if (qStr.length > 2){
			qSpan = qStr[2].split("=");
			span = qSpan[1];
		}
		
		if (qStr.length > 3){
			qSector = qStr[3].split("=");
			sector = qSector[1];
		}
	}
	
	switch(r){
		case "script":
			strReturn = scriptName;
			break;
		case "codes":
			strReturn =  allCodes;
			break;
		case "hide":
			strReturn =  hideCodes;
			break;
		case "span":
			strReturn =  span;
			break;
		case "sector":
			strReturn =  sector;
			break;
	}
	
	return strReturn;
}	



/// Paging
function GoToPage(pageNo){
	document.forms["MainForm"].pageNo.value = pageNo;
	document.forms["MainForm"].submit();	
}


/// Loading a url in new window with specified height & width
function loadFlt(url, height, width, scrollbars)
{
	var browser = navigator.appName + " " + navigator.appVersion; 
    	var Newwindow = window.open(url,"choose","resizable=no,height=" + height + ",status=yes,width=" + width + ",scrollbars=" + scrollbars + ",top=20,left=250");
	
      	if ( browser.substring(0, 8) =="Netscape") 
      	{ 
        	Newwindow.creator = self; 
      	}
        else 
		{
          	if (Newwindow.opener == null) 
          	{
			Newwindow.opener = self;
			} 
      	} 
}

/// For show / hide the advanced search option
function showhide(id)
{ 
	if (document.getElementById)
	{ 
		obj = document.getElementById(id); 
		if (obj.style.display == "none")
		{ 
			obj.style.display = ""; 
		}
		else
		{ 
			obj.style.display = "none"; 
		} 
	} 
} 

/// Navigate on page index
function SetPageIndex(index)
{
	document.getElementById('PgIndex').value=index;
	document.MainForm.submit();
}

/// Maintaining table and advanced options - visibility
function RetainTab(isShortlistPage)
{
	var tab='';
	tab=getQueryValue('CurrentTab');
	if(tab == '')
	{
		contrl = document.getElementById('CurrentTab');
		if(contrl != null)
		{
			tab = document.getElementById('CurrentTab').value;
		}
	}
	if(tab != '')
	{
		ChangeTabs(tab);
	}
	if(!isShortlistPage)
	{
		var advancesearch='';
		advancesearch=getQueryValue('AdvanceSearch');
		if(advancesearch == '')
		{
			advancesearch = document.getElementById('AdvanceSearch').value;
		}
		if(advancesearch == '1')
		{
			showhide('advanceOption','yes');
		}
	}
}

function URLEncode(value)
{
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = value;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for
	return encoded;
}

function URLDecode(encoded)
{
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;
}

/// To get querystring value from url
function getQueryValue(name) 
{
	var url = document.URL;
	i = url.indexOf(name += '=')
	j = url.indexOf('&', i);
	if(-1 == j) 
	{
		j = url.length;
	}
	if(-1 != i) 
	{
		return url.substring(i + name.length, j);
	}
	else
	{
		return '';
	}
}

/// For Checking in table checkboxes
function ChkBoxSelection()
{
	var elements = document.getElementsByTagName("INPUT");
	for(i=0;i<elements.length;i++)
	{
		if(IsCheckBox(elements[i]) == true && elements[i].id == "ChkFund")
		{
			elements[i].checked = true;
		}
	}
}

/// Checking the control for checkbox
function IsCheckBox(chk)
{
	return (chk.type == 'checkbox');
}

/// Storing the shortlisted fund's typecode in cookie
function ShortListed()
{
	var tabvalue = document.getElementById('CurrentTab').value;
	var elements = document.getElementsByTagName("INPUT");
	var shortlist='';
	shortlist=GetCookie('FPUser');
	var array = new Array();
	array = shortlist.split(',');

	if(array.length>24)
	{
		alert('Maximum (25) Funds have been shortlisted.');
	}
	else
	{
		for(var i=0;i<elements.length;i++)
		{
			if(IsCheckBox(elements[i]) && elements[i].name==tabvalue)
			{
				if(elements[i].checked==true)
				{
					if(shortlist.indexOf(elements[i].value)<0)
					{
						shortlist = (shortlist != '' ? shortlist+',' : '');
						shortlist += elements[i].value;
					}
				}
			}
		}
		SetCookie('FPUser',shortlist);
		shortlist=GetCookie('FPUser');
		array = shortlist.split(',');
		if(shortlist != '')
		{
			document.getElementById('lblshortlist').innerText = "[" + array.length + " Fund(s) totally shortlisted]";
		}
	}
}

/// Clearing All Shortlisted Funds By Clearing Cookie
function ClearAllShorlisted()
{
	SetCookie('FPUser','');
	document.location.href='pricetable.aspx';
}

/// To Get specified Cookie value
function GetCookie(name) 
{
    var start = document.cookie.indexOf(name+"=");
    var len = start+name.length+1;
    if ((!start) && (name != document.cookie.substring(0,name.length))) return '';
    if (start == -1) return '';
    var end = document.cookie.indexOf(";",len);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len,end));
}

/// To Set specified cookie
function SetCookie(name,value,expires,path,domain,secure)
{
    document.cookie = name + "=" +escape(value) +
        ( (expires) ? ";expires=" + expires.toGMTString() : "") +
        ( (path) ? ";path=" + path : "") + 
        ( (domain) ? ";domain=" + domain : "") +
        ( (secure) ? ";secure" : "");
}

/// Storing sort field and direction of sorting
function Sort(field)
{
	var array = new Array();
	array = field.split(' ');
	if(array.length > 1)
	{
		array[1] = ((array[1] == 'asc')? 'desc' : 'asc');
		field = array[0] + ' ' + array[1];
		document.MainForm.SortField.value = array[0];
		document.MainForm.SortDirection.value = array[1];
	}
	
	document.MainForm.submit();
}

// Adding Additional funds outside FriendsProvident
function AddFunds()
{
	var fundarray='';
	var fundnamearray='';
	var selectedindex=document.MainForm.fund.selectedIndex;
	
	fundarray = document.getElementById('fundsarray').value;
	fundnamearray = document.getElementById('fundsnamearray').value;
	if(document.getElementById('fund').selectedValue != '')
	{
		if(fundarray.indexOf(document.MainForm.fund.options[selectedindex].value)<0)
		{
			if(fundarray != '')
			{
				fundarray += ',';
				fundnamearray += ',';
			}
			fundarray += document.MainForm.fund.options[selectedindex].value;
			fundnamearray += document.MainForm.fund.options[selectedindex].text;
		}
	}
	document.getElementById('fundsarray').value = fundarray;
	document.getElementById('fundsnamearray').value = fundnamearray;
	
	document.MainForm.submit();
}

// Remove particular Additional funds in comparison funds
function RemoveSelectedFund(fundtypecode)
{
	var fundarray = document.getElementById('fundsarray').value;
	var fundnamearray = document.getElementById('fundsnamearray').value;
	var farray = new Array();
	var fnarray = new Array();
	farray = fundarray.split(',');
	fnarray = fundnamearray.split(',');
	fundarray = '';
	fundnamearray = '';
	
	for(var i=0;i<farray.length;i++)
	{
		if(farray[i] != fundtypecode)
		{
			if(fundarray != '')
			{
				fundarray += ',';
				fundnamearray += ',';
			}
			fundarray += farray[i];
			fundnamearray += fnarray[i];
		}
	}
	
	document.getElementById('fundsarray').value = fundarray;
	document.getElementById('fundsnamearray').value = fundnamearray;
	document.MainForm.submit();
}

// default filter values
function ClearFilters()
{
	document.MainForm.Manager.selectedIndex = 0;
	document.MainForm.Yield.selectedIndex = 0;
	document.MainForm.submit();
}

// Storing value in hidden control & Submitting form
function SetHiddenValueAndSubmit(controlid,value)
{
	document.getElementById(controlid).value = value;
	document.MainForm.submit();
}

// To Calculate Portfolio Weight
function CalcPortfolioPercentage()
{
	var elements = document.getElementsByTagName("INPUT");
	var totalpercentage = 0;
	for(var l=0;l<elements.length;l++)
	{
		if((IsTextBox(elements[l]) == true) && (elements[l].name == 'PortfolioPercentage') && (elements[l].value != ''))
		{
			if(checkNumeric(elements[l],0,100) == true)
			{
				totalpercentage += eval(elements[l].value);
			}
		}
	}
	document.getElementById('total').value = eval(totalpercentage);
}

// Return true if argument is input textbox
function IsTextBox(txt)
{
	return (txt.type == 'text');
}

// To Check Numeric value in text input
function checkNumeric(objName,minval, maxval)
{
	var numberfield = objName;
	if (chkNumeric(objName,minval,maxval) == false)
	{
		numberfield.select();
		numberfield.focus();
		return false;
	}
	else
	{
		return true;
	}
}

function chkNumeric(objName,minval,maxval)
{
	// only allow 0-9 be entered, plus any values passed
	var checkOK = "0123456789" + ".";
	var checkStr = objName;
	var allValid = true;
	var decPoints = 0;
	var allNum = "";
	document.getElementById('ValidValues').value = '0';
	
	for (i = 0;  i < checkStr.value.length;  i++)
	{
		ch = checkStr.value.charAt(i);
		for (j = 0;  j < checkOK.length;  j++)
			if (ch == checkOK.charAt(j))
			break;
		if (j == checkOK.length)
		{
			allValid = false;
			break;
		}
		if (ch != ",")
			allNum += ch;
	}
	if (!allValid)
	{	
		alert("Invalid Entry");
		return (false);
	}

	// set the minimum and maximum
	var chkVal = allNum;
	var prsVal = parseInt(allNum);
	if (chkVal != "" && !(prsVal > minval && prsVal <= maxval))
	{
		alert("Invalid Range");
		return (false);
	}
	document.getElementById('ValidValues').value = '1';
	return (true);
}

