// Customizable variables
var DefaultDateFormat = 'MM/DD/YYYY'; // If no date format is supplied, this will be used instead
var HideWait = 2; // Number of seconds before the calendar will disappear
var Y2kPivotPoint = 76; // 2-digit years before this point will be created in the 21st century
var UnselectedMonthText = ''; // Text to display in the 1st month list item when the date isn't required
var FontSize = 11; // In pixels
var FontFamily = 'Tahoma';
var CellWidth = 18;
var CellHeight = 18;
var ImageURL = '/images/calenderIcon.png';
var NextURL = '/images/next.png';
var PrevURL = '/images/prev.png';
var BGImageURL= '/images/whitepixel.png';
var CalBGColor = 'white';
var TopRowBGColor = '#ECF1F9';
var DayBGColor = '#ECF1F9';
var DateName;
var tmpDT = new Date();
var curTime = getDblChar(tmpDT.getHours()) +  ":" + getDblChar(tmpDT.getMinutes()); // This variable will maintain the time picked in the clock
var globalDisTime = false; // This will maintain the status whether to display time or not
var selectedHour = getDblChar(tmpDT.getHours());   
var selectedMinute = getDblChar(tmpDT.getMinutes() - tmpDT.getMinutes()%5);
var currentDay;

// Global variables
var curDay;
var ObjName;
var ZCounter = 10;
var Today = new Date();
var WeekDays = new Array('S','M','T','W','T','F','S');
var MonthDays = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var MonthNames = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
var styleContent ="";

// Write out the stylesheet definition for the calendar
with (document) {
   styleContent ='<style>';
   styleContent+='td.calendarDateInput {letter-spacing:normal;line-height:normal;font-family:' + FontFamily + ',Sans-Serif;font-size:' + FontSize + 'px;}';
   styleContent+='select.calendarDateInput {letter-spacing:.06em;font-family:Verdana,Sans-Serif;font-size:11px;}';
   styleContent+='input.calendarDateInput {letter-spacing:.06em;font-family:Verdana,Sans-Serif;font-size:11px;}';
   styleContent+='</style>';
}

// Only allows certain keys to be used in the date field
function YearDigitsOnly(e) {
   var KeyCode = (e.keyCode) ? e.keyCode : e.which;
   return ((KeyCode == 8) // backspace
        || (KeyCode == 9) // tab
        || (KeyCode == 37) // left arrow
        || (KeyCode == 39) // right arrow
        || (KeyCode == 46) // delete
        || ((KeyCode > 47) && (KeyCode < 58)) // 0 - 9
   );
}

// Function to get the Hours and minutes with two characters
function getDblChar(val) {
   if(val.toString().length==1) {
      val = "0" + val;
      return val;
   }
   else return val;
}

// Gets the absolute pixel position of the supplied element
function GetTagPixels(StartTag, Direction) {
   var PixelAmt = (Direction == 'LEFT') ? StartTag.offsetLeft : StartTag.offsetTop;
   while ((StartTag.tagName != 'BODY') && (StartTag.tagName != 'HTML')) {
      StartTag = StartTag.offsetParent;
      PixelAmt += (Direction == 'LEFT') ? StartTag.offsetLeft : StartTag.offsetTop;
   }
   return PixelAmt;
}

// Is the specified select-list behind the calendar?
function BehindCal(SelectList, CalLeftX, CalRightX, CalTopY, CalBottomY, ListTopY) {
   var ListLeftX = GetTagPixels(SelectList, 'LEFT');
   var ListRightX = ListLeftX + SelectList.offsetWidth;
   var ListBottomY = ListTopY + SelectList.offsetHeight;
   return (((ListTopY < CalBottomY) && (ListBottomY > CalTopY)) && ((ListLeftX < CalRightX) && (ListRightX > CalLeftX)));
}

// For IE, hides any select-lists that are behind the calendar
function FixSelectLists(Over) {
   if (navigator.appName == 'Microsoft Internet Explorer') {
      var CalDiv = this.getCalendar();
      var CalLeftX = CalDiv.offsetLeft;
      var CalRightX = CalLeftX + CalDiv.offsetWidth;
      var CalTopY = CalDiv.offsetTop;
      var CalBottomY = CalTopY + (CellHeight * 9);
      var FoundCalInput = false;
      formLoop :
      for (var j=this.formNumber;j<document.forms.length;j++) {
      if(j != -1)
      {
         for (var i=0;i<document.forms[j].elements.length;i++) {
            if (document.forms[j].elements[i].type == 'string') {
               if ((document.forms[j].elements[i].type == 'hidden') && (document.forms[j].elements[i].name == this.hiddenFieldName)) {
                  FoundCalInput = true;
                  i += 3; // 3 elements between the 1st hidden field and the last year input field
               }
               if (FoundCalInput) {
                  if (document.forms[j].elements[i].type.substr(0,6) == 'select') {
                     ListTopY = GetTagPixels(document.forms[j].elements[i], 'TOP');
                     if (ListTopY < CalBottomY) {
                        if (BehindCal(document.forms[j].elements[i], CalLeftX, CalRightX, CalTopY, CalBottomY, ListTopY)) {
                          if(document.forms[j].elements[i].id == DateName + "_YearID")
									{
										document.forms[j].elements[i].style.visibility = (!Over) ? 'hidden' : 'visible';
									}
									if(!document.forms[j].elements[i].id == DateName + "_YearID")
									{
										document.forms[j].elements[i].style.visibility = (Over) ? 'hidden' : 'visible';
									}
                        }
                     }
                     else break formLoop;
                  }
               }
            }
         }
      }
    }
   }
}

// Displays a message in the status bar when hovering over the calendar days
function DayCellHover(Cell, Over, Color, HoveredDay) {
   Cell.style.backgroundColor = (Over) ? DayBGColor : Color;
   if (Over) {
      if ((this.yearValue == Today.getFullYear()) && (this.monthIndex == Today.getMonth()) && (HoveredDay == Today.getDate())) self.status = 'Click to select today';
      else {
         var Suffix = HoveredDay.toString();
         switch (Suffix.substr(Suffix.length - 1, 1)) {
            case '1' : Suffix += (HoveredDay == 11) ? 'th' : 'st'; break;
            case '2' : Suffix += (HoveredDay == 12) ? 'th' : 'nd'; break;
            case '3' : Suffix += (HoveredDay == 13) ? 'th' : 'rd'; break;
            default : Suffix += 'th'; break;
         }
         self.status = 'Click to select ' + this.monthName + ' ' + Suffix;
      }
   }
   else self.status = '';
   return true;
}

// Sets the form elements after a day has been picked from the calendar
function PickDisplayDay(ClickedDay) {
   this.show();
   var MonthList = this.getMonthList();
   var DayList = this.getDayList();
   var YearField = this.getYearField();
   FixDayList(DayList, GetDayCount(this.displayed.yearValue, this.displayed.monthIndex));
   // Select the month and day in the lists
   for (var i=0;i<MonthList.length;i++) {
      if (MonthList.options[i].value == this.displayed.monthIndex) MonthList.options[i].selected = true;
   }
   for (var j=1;j<=DayList.length;j++) {
      if (j == ClickedDay) DayList.options[j-1].selected = true;
   }
   this.setPicked(this.displayed.yearValue, this.displayed.monthIndex, ClickedDay);
   // Change the year, if necessary
   YearField.value = this.picked.yearPad;
   YearField.defaultValue = YearField.value;
}

// Builds the HTML for the calendar days
function BuildCalendarDays() {
var dayExceed=false;
   var Rows = 5;
   if (((this.displayed.dayCount == 31) && (this.displayed.firstDay > 4)) || ((this.displayed.dayCount == 30) && (this.displayed.firstDay == 6))) Rows = 6;
   else if ((this.displayed.dayCount == 28) && (this.displayed.firstDay == 0)) Rows = 4;
   var HTML = '<table width="' + (CellWidth * 7) + 'px" cellspacing="0" cellpadding="1" style="cursor:default;z-index:5000;">';
   for (var j=0;j<Rows;j++) {
      HTML += '<tr>';
      for (var i=1;i<=7;i++) {
         Day = (j * 7) + (i - this.displayed.firstDay);
         if ((Day >= 1) && (Day <= this.displayed.dayCount)) {
            if ((this.displayed.yearValue == this.picked.yearValue) && (this.displayed.monthIndex == this.picked.monthIndex) && (Day == this.picked.day)) {
               TextStyle = 'color:black;font-weight:bold;'
               currentDay=Day;
               BackColor = DayBGColor;
            }
            else {
               TextStyle = 'color:black;'
               BackColor = CalBGColor;
            }
            if ((this.displayed.yearValue == Today.getFullYear()) && (this.displayed.monthIndex == Today.getMonth()) && (Day == Today.getDate())) 
            {
					TextStyle += 'border:1px solid #a7c7e7;padding:0px;';
				}
				if((this.displayed.yearValue == Today.getFullYear()) && (this.displayed.monthIndex == Today.getMonth()) && (parseInt(Day - 1) == Today.getDate()))
				{
					dayExceed=true;
				}
				if(!dayExceed)
				{
					HTML += '<td align="center" class="calendarDateInput" style="cursor:default;height:' + CellHeight + 'px;width:' + CellWidth + 'px;' + TextStyle + ';background-color:' + BackColor + '" onClick="' + this.objName + '.pickDay(' + Day + ');' + this.objName + '.followUP();" onMouseOver="return ' + this.objName + '.displayed.dayHover(this,true,\'' + BackColor + '\',' + Day + ')" onMouseOut="return ' + this.objName + '.displayed.dayHover(this,false,\'white\')">' + Day + '</td>';
				}
				else
				{
					HTML += '<td align="center" class="calendarDateInput" style="cursor:default;height:' + CellHeight + 'px;width:' + CellWidth + 'px;' + TextStyle + ';background-color:#A5A5A5">' + Day + '</td>';
				}
         }
         else HTML += '<td class="calendarDateInput" style="height:' + CellHeight + 'px">&nbsp;</td>';
      }
      HTML += '</tr>';
   }
   return HTML += '</table>';
}

// It will record the change in the time select box
function Time_Change(val)
{
   if(this.globalDisTime)
   {
	  if (val=="get")
	  {
		 selectedHour = document.getElementById("Hour_ID").options[document.getElementById("Hour_ID").selectedIndex].value;   
		 selectedMinute = document.getElementById("Minute_ID").options[document.getElementById("Minute_ID").selectedIndex].value;
	  }
	  else	if (val=="set") // To set the time
	  {
		 document.getElementById("Hour_ID").value = selectedHour ;   
   		 document.getElementById("Minute_ID").value = selectedMinute;
	  }
	  curTime = selectedHour + ":" + selectedMinute;
   }
}

// Determines which century to use (20th or 21st) when dealing with 2-digit years
function GetGoodYear(YearDigits) {
   if (YearDigits.length == 4) return YearDigits;
   else {
      var Millennium = (YearDigits < Y2kPivotPoint) ? 2000 : 1900;
      return Millennium + parseInt(YearDigits,10);
   }
}

// Returns the number of days in a month (handles leap-years)
function GetDayCount(SomeYear, SomeMonth) {
   return ((SomeMonth == 1) && ((SomeYear % 400 == 0) || ((SomeYear % 4 == 0) && (SomeYear % 100 != 0)))) ? 29 : MonthDays[SomeMonth];
}

// Highlights the buttons
function VirtualButton(Cell, ButtonDown) {
   if (ButtonDown) {
      Cell.style.borderLeft = 'buttonshadow 1px solid';
      Cell.style.borderTop = 'buttonshadow 1px solid';
      Cell.style.borderBottom = 'buttonhighlight 1px solid';
      Cell.style.borderRight = 'buttonhighlight 1px solid';
   }
   else {
      Cell.style.borderLeft = 'buttonhighlight 1px solid';
      Cell.style.borderTop = 'buttonhighlight 1px solid';
      Cell.style.borderBottom = 'buttonshadow 1px solid';
      Cell.style.borderRight = 'buttonshadow 1px solid';
   }
}

// Mouse-over for the previous/next month buttons
function NeighborHover(Cell, Over, DateObj) {
   if (Over) {
      VirtualButton(Cell, false);
      self.status = 'Click to view ' + DateObj.fullName;
   }
   else {
      Cell.style.border = 'buttonface 1px solid';
      self.status = '';
   }
   return true;
}

// Adds/removes days from the day list, depending on the month/year
function FixDayList(DayList, NewDays) {
   var DayPick = DayList.selectedIndex + 1;
   if (NewDays != DayList.length) {
      var OldSize = DayList.length;
      for (var k=Math.min(NewDays,OldSize);k<Math.max(NewDays,OldSize);k++) {
         (k >= NewDays) ? DayList.options[NewDays] = null : DayList.options[k] = new Option(k+1, k+1);
      }
      DayPick = Math.min(DayPick, NewDays);
      DayList.options[DayPick-1].selected = true;
   }
   return DayPick;
}

// Resets the year to its previous valid value when something invalid is entered
function FixYearInput(YearField) {
   var YearRE = new RegExp('\\d{' + YearField.value.length + '}');
   if (!YearRE.test(YearField.selectedvalue)) YearField.value = YearField.value;
}

// Displays a message in the status bar when hovering over the calendar icon
function CalIconHover(Over) {
   var Message = (this.isShowing()) ? 'hide' : 'show';
   self.status = (Over) ? 'Click to ' + Message + ' the calendar' : '';
   return true;
}

// Starts the timer over from scratch
function CalTimerReset() {
   eval('clearTimeout(' + this.timerID + ')');
   eval(this.timerID + '=setTimeout(\'' + this.objName + '.show()\',' + (HideWait * 1000) + ')');
}

// The timer for the calendar
function DoTimer(CancelTimer) {
   if (CancelTimer) eval('clearTimeout(' + this.timerID + ')');
   else {
      eval(this.timerID + '=null');
      this.resetTimer();
   }
}

// Show or hide the calendar
function ShowCalendar() {
   if (this.isShowing()) {
	  
      var StopTimer = true;      
      var frameId=document.getElementById(this.hiddenFieldName + "_IFrame");
      frameId.style.visibility='hidden'; 
      //var position= getPosition(farmeLeft.id);    
      this.getCalendar().style.zIndex = --ZCounter;
      this.getCalendar().style.visibility = 'hidden';
      this.fixSelects(false);
   }
   else {
      var StopTimer = false;
      this.fixSelects(true);      
      this.getCalendar().style.zIndex = ++ZCounter;    
      var browsType=window.navigator.userAgent;
      document.getElementById(this.hiddenFieldName + "_IFrame").style.zIndex=0;  
      var frameId=document.getElementById(this.hiddenFieldName + "_IFrame");      
      if(browsType.indexOf("MSIE 6.0")>=0) {
		frameId.style.visibility='visible'; 
		var farmeLeft=document.getElementById(this.hiddenFieldName + "_ID").offsetLeft;
        var farmeTop=document.getElementById(this.hiddenFieldName + "_ID").offsetTop;
        frameId.style.left=farmeLeft;
        frameId.style.top=farmeTop;
      }      
      this.getCalendar().style.visibility = 'visible';
   }
   this.handleTimer(StopTimer);
   self.status = '';
}

// Hides the input elements when the "blank" month is selected
function SetElementStatus(Hide) {
   this.getDayList().style.visibility = (Hide) ? 'hidden' : 'visible';
   this.getYearField().style.visibility = (Hide) ? 'hidden' : 'visible';
   this.getCalendarLink().style.visibility = (Hide) ? 'hidden' : 'visible';
}

// Sets the date, based on the month selected
function CheckMonthChange(MonthList) {
   var DayList = this.getDayList();
   if (MonthList.options[MonthList.selectedIndex].value == '') {
      DayList.selectedIndex = 0;
      this.hideElements(true);
      this.setHidden('');
   }
   else {
      this.hideElements(false);
      if (this.isShowing()) {
         this.resetTimer(); // Gives the user more time to view the calendar with the newly-selected month
         this.getCalendar().style.zIndex = ++ZCounter; // Make sure this calendar is on top of any other calendars
      }
      var DayPick = FixDayList(DayList, GetDayCount(this.picked.yearValue, MonthList.options[MonthList.selectedIndex].value));
      this.setPicked(this.picked.yearValue, MonthList.options[MonthList.selectedIndex].value, DayPick);
   }
}

// Sets the date, based on the day selected
function CheckDayChange(DayList) {
   if (this.isShowing()) this.show();
   this.setPicked(this.picked.yearValue, this.picked.monthIndex, DayList.selectedIndex+1);
}

// Changes the date when a valid year has been entered
function CheckYearInput(YearField) {
   if ( (YearField.defaultValue != YearField.value)) {
      if (this.isShowing()) {
         this.resetTimer(); // Gives the user more time to view the calendar with the newly-entered year
         this.getCalendar().style.zIndex = ++ZCounter; // Make sure this calendar is on top of any other calendars
      }
      var NewYear = GetGoodYear(YearField.value);
      var MonthList = this.getMonthList();
      var NewDay = FixDayList(this.getDayList(), GetDayCount(NewYear, this.picked.monthIndex));
      this.setPicked(NewYear, this.picked.monthIndex, NewDay);
   }
}

// Holds characteristics about a date
function dateObject() {
   if (Function.call) { // Used when 'call' method of the Function object is supported
      var ParentObject = this;
      var ArgumentStart = 0;
   }
   else { // Used with 'call' method of the Function object is NOT supported
      var ParentObject = arguments[0];
      var ArgumentStart = 1;
   }
   ParentObject.date = (arguments.length == (ArgumentStart+1)) ? new Date(arguments[ArgumentStart+0]) : new Date(arguments[ArgumentStart+0], arguments[ArgumentStart+1], arguments[ArgumentStart+2]);
	ParentObject.yearValue = ParentObject.date.getFullYear();
   ParentObject.monthIndex = ParentObject.date.getMonth();
   ParentObject.monthName = MonthNames[ParentObject.monthIndex];
   ParentObject.fullName = ParentObject.monthName + ' ' + ParentObject.yearValue;
   ParentObject.day = ParentObject.date.getDate();
   ParentObject.dayCount = GetDayCount(ParentObject.yearValue, ParentObject.monthIndex);
   var FirstDate = new Date(ParentObject.yearValue, ParentObject.monthIndex, 1);
   ParentObject.firstDay = FirstDate.getDay();
}

// Keeps track of the date that goes into the hidden field
function storedMonthObject(DateFormat, DateYear, DateMonth, DateDay) {
   (Function.call) ? dateObject.call(this, DateYear, DateMonth, DateDay) : dateObject(this, DateYear, DateMonth, DateDay);
   this.yearPad = this.yearValue.toString();
   this.monthPad = (this.monthIndex < 9) ? '0' + String(this.monthIndex + 1) : this.monthIndex + 1;
   this.dayPad = (this.day < 10) ? '0' + this.day.toString() : this.day;
   this.monthShort = this.monthName.substr(0,3).toUpperCase();
   // Formats the year with 2 digits instead of 4
   if (DateFormat.indexOf('YYYY') == -1) this.yearPad = this.yearPad.substr(2);
   // Define the date-part delimiter
   if (DateFormat.indexOf('/') >= 0) var Delimiter = '/';
   else if (DateFormat.indexOf('-') >= 0) var Delimiter = '-';
   else var Delimiter = '';
   // Determine the order of the months and days
   if (/DD?.?((MON)|(MM?M?))/.test(DateFormat)) {
      this.formatted = this.dayPad + Delimiter;
      this.formatted += (RegExp.$1.length == 3) ? this.monthShort : this.monthPad;
   }
   else if (/((MON)|(MM?M?))?.?DD?/.test(DateFormat)) {
      this.formatted = (RegExp.$1.length == 3) ? this.monthShort : this.monthPad;
      this.formatted += Delimiter + this.dayPad;
   }
   // Either prepend or append the year to the formatted date
   this.formatted = (DateFormat.substr(0,2) == 'YY') ? this.yearPad + Delimiter + this.formatted : this.formatted + Delimiter + this.yearPad;
}

// Object for the current displayed month
function displayMonthObject(ParentObject, DateYear, DateMonth, DateDay) {
   (Function.call) ? dateObject.call(this, DateYear, DateMonth, DateDay) : dateObject(this, DateYear, DateMonth, DateDay);
   this.displayID = ParentObject.hiddenFieldName + '_Current_ID';
   this.getDisplay = new Function('return document.getElementById(this.displayID)');
   this.dayHover = DayCellHover;
   this.goCurrent = new Function(ParentObject.objName + '.getCalendar().style.zIndex=++ZCounter;' + ParentObject.objName + '.setDisplayed(Today.getFullYear(),Today.getMonth());');
   if (ParentObject.formNumber >= 0) this.getDisplay().innerHTML = this.fullName.substring(0,this.fullName.length-4);
}

// Object for the previous/next buttons
function neighborMonthObject(ParentObject, IDText, DateMS) {
     (Function.call) ? dateObject.call(this, DateMS) : dateObject(this, DateMS);
   this.buttonID = ParentObject.hiddenFieldName + '_' + IDText + '_ID';
   this.hover = new Function('C','O','NeighborHover(C,O,this)');
   this.getButton = new Function('return document.getElementById(this.buttonID)');
   this.go = new Function(ParentObject.objName + '.getCalendar().style.zIndex=++ZCounter;' + ParentObject.objName + '.setDisplayed(this.yearValue,this.monthIndex);');
   if (ParentObject.formNumber >= 0) this.getButton().title = this.monthName;
   
}

// Sets the currently-displayed month object
function SetDisplayedMonth(DispYear, DispMonth) {

		var TodayDate=new Date();
		var diffDays=days_between(TodayDate,new Date(parseInt(DispYear),parseInt(DispMonth),parseInt(curDay)));
		
		
		ChangeYear(DispYear,this.hiddenFieldName);
					
		this.displayed = new displayMonthObject(this, DispYear, DispMonth, 1);
		if(parseInt(diffDays) >= 0 && parseInt(diffDays) < 14667)
		{
			this.previous = new neighborMonthObject(this, 'Previous', this.displayed.date.getTime() - 86400000);
			this.next = new neighborMonthObject(this, 'Next', this.displayed.date.getTime() + (86400000 * (this.displayed.dayCount + 1)));
			this.picked.monthIndex = DispMonth;
		}
		else
		{
			this.displayed = new displayMonthObject(this, TodayDate.getFullYear(),TodayDate.getMonth(),TodayDate.getDay());
			ChangeYear(TodayDate.getFullYear());
			//this.previous = new neighborMonthObject(this, 'Previous', this.displayed.date.getTime() - 86400000);
			//this.next = new neighborMonthObject(this, 'Next', this.displayed.date.getTime() + (86400000 * (this.displayed.dayCount + 1)));
			this.picked.monthIndex = TodayDate.getMonth();
		}
		
		
		//if (this.formNumber >= 0) 
		if(this.getDayTable() != null)
		{
			 this.getDayTable().innerHTML="";
			 this.getDayTable().innerHTML = this.buildCalendar();
			 this.getMonthDisplay().innerHTML =  MonthNames[parseInt(this.picked.monthIndex)];
		}
}

// Sets the current selected date
function SetPickedMonth(PickedYear, PickedMonth, PickedDay) {
	
	//Loading Values for further.
	curDay=PickedDay;		
		
	this.picked = new storedMonthObject(this.format, PickedYear, PickedMonth, PickedDay);
	this.setHidden(this.picked.formatted);
	if(document.getElementById(ObjName+"_YearID"))
	{
		document.getElementById(ObjName+"_YearID").value=PickedYear;
	}
  var ele=document.getElementById(this.displayName);

/////////////////////////////////////// Display Date here //////////////////////////////////////////////////////

   if(ele!=null)
   { 
	   if(ele.tagName=='INPUT')
	   {
			document.getElementById(this.displayName).value=this.picked.formatted;
	   }
	   else
	   {
		   var TimeShow = (globalDisTime && this.displayName == "TZCSpanDate")? (" " + curTime):"";		 		   
		   if(this.displayName == "TZCSpanDate") 
		   {
			   var str = String(this.picked.formatted);
		 	   var dandt = new Date(str.substring(7,11),getMonthNum(str.substring(3,6))-1,str.substring(0,2));
			   document.getElementById(this.displayName).innerHTML=dandt.toDateString() + TimeShow;
			   cntPkdTime("Picked");
		   }
		   else
		   {
			   document.getElementById(this.displayName).innerHTML=this.picked.formatted + TimeShow;
			   if(this.displayName == "CalcDateL" || this.displayName == "ExDate1L" || this.displayName == "ExDate2L") CalculatorAjax();
		   }			 
	   }
	}
   this.setDisplayed(PickedYear, PickedMonth);
}

// The calendar object
function calendarObject(DateName, DateFormat, DefaultDate,DisplayName) {

   /* Properties */
   this.displayName=DisplayName;
   this.hiddenFieldName = DateName;
   ObjName = DateName;
   this.monthListID = DateName + '_Month_ID';
   this.dayListID = DateName + '_Day_ID';
   this.yearFieldID = DateName + '_Year_ID';
   this.monthDisplayID = DateName + '_Current_ID';
   this.calendarID = DateName + '_ID';
   this.dayTableID = DateName + '_DayTable_ID';
   this.calendarLinkID = this.calendarID + '_Link';
   this.timerID = this.calendarID + '_Timer';
   this.objName = DateName + '_Object';
   this.format = DateFormat;
   this.formNumber = -1;
   this.picked = null;
   this.displayed = null;
   this.previous = null;
   this.next = null;

   /* Methods */
   this.setPicked = SetPickedMonth;
   this.setDisplayed = SetDisplayedMonth;
   this.checkYear = CheckYearInput;
   this.fixYear = FixYearInput;
   this.changeMonth = CheckMonthChange;
   this.changeDay = CheckDayChange;
   this.resetTimer = CalTimerReset;
   this.hideElements = SetElementStatus;
   this.show = ShowCalendar;
   this.handleTimer = DoTimer;
   this.iconHover = CalIconHover;
   this.buildCalendar = BuildCalendarDays;
   this.pickDay = PickDisplayDay;
   this.fixSelects = FixSelectLists;
   this.setHidden = new Function('D','if (this.formNumber >= 0) this.getHiddenField().value=D');
   // Returns a reference to these elements
   
   this.getHiddenField = new Function('return document.forms[this.formNumber].elements[this.hiddenFieldName]');
   this.getMonthList = new Function('return document.getElementById(this.monthListID)');
   this.getDayList = new Function('return document.getElementById(this.dayListID)');
   this.getYearField = new Function('return document.getElementById(this.yearFieldID)');
   this.getCalendar = new Function('return document.getElementById(this.calendarID)');
   this.getDayTable = new Function('return document.getElementById(this.dayTableID)');
   this.getCalendarLink = new Function('return document.getElementById(this.calendarLinkID)');
   this.getMonthDisplay = new Function('return document.getElementById(this.monthDisplayID)');
   this.isShowing = new Function('return !(this.getCalendar().style.visibility != \'visible\')');
   
   this.followUP = new Function(typeof followUpMethod != "undefined"?followUpMethod:'');
   
   /* Constructor */
   // Functions used only by the constructor
   function getMonthIndex(MonthAbbr) { // Returns the index (0-11) of the supplied month abbreviation
      for (var MonPos=0;MonPos<MonthNames.length;MonPos++) {
         if (MonthNames[MonPos].substr(0,3).toUpperCase() == MonthAbbr.toUpperCase()) break;
      }
      return MonPos;
   }
   function SetGoodDate(CalObj, Notify) { // Notifies the user about their bad default date, and sets the current system date
      CalObj.setPicked(Today.getFullYear(), Today.getMonth(), Today.getDate());
      if (Notify) 
      {
        //alert('WARNING: The supplied date is not in valid \'' + DateFormat + '\' format: ' + DefaultDate + '.\nTherefore, the current system date will be used instead: ' + CalObj.picked.formatted);
      }
   }
   // Main part of the constructor
   if (DefaultDate != '') {
      if ((this.format == 'YYYYMMDD') && (/^(\d{4})(\d{2})(\d{2})$/.test(DefaultDate))) this.setPicked(RegExp.$1, parseInt(RegExp.$2,10)-1, RegExp.$3);
      else {
         // Get the year
         if ((this.format.substr(0,2) == 'YY') && (/^(\d{2,4})(-|\/)/.test(DefaultDate))) { // Year is at the beginning
            var YearPart = GetGoodYear(RegExp.$1);
            // Determine the order of the months and days
            if (/(-|\/)(\w{1,3})(-|\/)(\w{1,3})$/.test(DefaultDate)) {
               var MidPart = RegExp.$2;
               var EndPart = RegExp.$4;
               if (/D$/.test(this.format)) { // Ends with days
                  var DayPart = EndPart;
                  var MonthPart = MidPart;
               }
               else {
                  var DayPart = MidPart;
                  var MonthPart = EndPart;
               }
               MonthPart = (/\d{1,2}/i.test(MonthPart)) ? parseInt(MonthPart,10)-1 : getMonthIndex(MonthPart);
               this.setPicked(YearPart, MonthPart, DayPart);
            }
            else SetGoodDate(this, true);
         }
         else if (/(-|\/)(\d{2,4})$/.test(DefaultDate)) { // Year is at the end
            var YearPart = GetGoodYear(RegExp.$2);
            // Determine the order of the months and days
            if (/^(\w{1,3})(-|\/)(\w{1,3})(-|\/)/.test(DefaultDate)) {
               if (this.format.substr(0,1) == 'D') { // Starts with days
                  var DayPart = RegExp.$1;
                  var MonthPart = RegExp.$3;
               }
               else { // Starts with months
                  var MonthPart = RegExp.$1;
                  var DayPart = RegExp.$3;
               }
               MonthPart = (/\d{1,2}/i.test(MonthPart)) ? parseInt(MonthPart,10)-1 : getMonthIndex(MonthPart);
               this.setPicked(YearPart, MonthPart, DayPart);
            }
            else SetGoodDate(this, true);
         }
         else SetGoodDate(this, true);
      }
   }
}

// Main function that creates the form elements
function DateInput(DateName, Required, DateFormat,DisplayName, DefaultDate,DisplayTime) {  
	if(DateName == '')
	{
		DateName="Valid"+DisplayName;
	}    
   if(DisplayTime)
   {  
	  
	  this.globalDisTime=DisplayTime;
   }
   else
   {
	  this.globalDisTime=false;
   }
   
   var DateContent="";
   
   if (arguments.length == 0) DateContent+=('<span style="color:red;font-size:' + FontSize + 'px;font-family:' + FontFamily + ';">ERROR: Missing required parameter in call to \'DateInput\': [name of hidden date field].</span>');
   else {
      // Handle DateFormat
      if (arguments.length < 3) { // The format wasn't passed in, so use default
         DateFormat = DefaultDateFormat;
         if (arguments.length < 2) Required = false;
      }
      else if (/^(Y{2,4}(-|\/)?)?((MON)|(MM?M?)|(DD?))(-|\/)?((MON)|(MM?M?)|(DD?))((-|\/)Y{2,4})?$/i.test(DateFormat)) DateFormat = DateFormat.toUpperCase();
      else { // Passed-in DateFormat was invalid, use default format instead
         var AlertMessage = 'WARNING: The supplied date format for the \'' + DateName + '\' field is not valid: ' + DateFormat + '\nTherefore, the default date format will be used instead: ' + DefaultDateFormat;
         DateFormat = DefaultDateFormat;
         if (arguments.length == 4) { // DefaultDate was passed in with an invalid date format
            var CurrentDate = new storedMonthObject(DateFormat, Today.getFullYear(), Today.getMonth(), Today.getDate());
            AlertMessage += '\n\nThe supplied date (' + DefaultDate + ') cannot be interpreted with the invalid format.\nTherefore, the current system date will be used instead: ' + CurrentDate.formatted;
            DefaultDate = CurrentDate.formatted;
         }
         alert(AlertMessage);
      }
      // Define the current date if it wasn't set already
      if (!CurrentDate) var CurrentDate = new storedMonthObject(DateFormat, Today.getFullYear(), Today.getMonth(), Today.getDay());
      // Handle DefaultDate
      if (arguments.length < 4) { // The date wasn't passed in
         DefaultDate = (Required) ? CurrentDate.formatted : ''; // If required, use today's date
      }
      // Creates the calendar object!
      eval(DateName + '_Object=new calendarObject(\'' + DateName + '\',\'' + DateFormat + '\',\'' + DefaultDate +'\',\'' + DisplayName + '\')');
      // Determine initial viewable state of day, year, and calendar icon
      if ((Required) || (arguments.length == 4)) {
         var InitialStatus = '';
         var InitialDate = eval(DateName + '_Object.picked.formatted');
      }
      else {
         var InitialStatus = ' style="visibility:hidden"';
         var InitialDate = '';
         eval(DateName + '_Object.setPicked(' + Today.getFullYear() + ',' + Today.getMonth() + ',' + Today.getDay() + ')');
      }
      
		if(DefaultDate == '' || DefaultDate == '01-Jan-001')
      {
			var ele=document.getElementById(DisplayName);
			eval(DateName + '_Object.setPicked(' + Today.getFullYear() + ',' + Today.getMonth() + ',' + Today.getDay() + ')');
			if(ele!=null)
			{ 
				if(ele.tagName=='INPUT')
				{
					ele.value='';
				}
				else
				{
					ele.innerHTML='';
				}
			}
		}
      // Create the form elements
      
      with (document) {
			DateContent+='<input type="hidden" name="' + DateName + '" value="' + InitialDate + '">';
			
			// Find this form number
         for (var f=0;f<forms.length;f++) {
            for (var e=0;e<forms[f].elements.length;e++) {
               if (typeof forms[f].elements[e].type == 'string') {
                  if ((forms[f].elements[e].type == 'hidden') && (forms[f].elements[e].name == DateName)) {
                     eval(DateName + '_Object.formNumber='+f);
                     break;
                  }
               }
            }
         }
        DateContent +=' <iframe id="' + DateName +'_IFrame"  src="" frameborder="0" scrolling="no" style="width:' + parseInt(parseInt(CellWidth * 8)+2) + 'px;visibility:hidden;position:absolute;"></iframe>';
         DateContent+='<table cellpadding="0" cellspacing="2"><tr>' + String.fromCharCode(13) + '<td valign="middle" style="visibility:hidden; position:absolute;z-index:25000;" >';
         DateContent+='<select class="calendarDateInput" id="' + DateName + '_Month_ID" onChange="' + DateName + '_Object.changeMonth(this)">';
         if (!Required) {
            var NoneSelected = (DefaultDate == '') ? ' selected' : '';
            DateContent+='<option value=""' + NoneSelected + '>' + UnselectedMonthText + '</option>';
         }
         for (var i=0;i<12;i++) {
            MonthSelected = ((DefaultDate != '') && (eval(DateName + '_Object.picked.monthIndex') == i)) ? ' selected' : '';
            DateContent+='<option value="' + i + '"' + MonthSelected + '>' + MonthNames[i].substr(0,3) + '</option>';
         }
         DateContent+='</select>' + String.fromCharCode(13) + '</td>' + String.fromCharCode(13) + '<td valign="middle" style="visibility:hidden; position:absolute;">';
         DateContent+='<select' + InitialStatus + ' class="calendarDateInput" id="' + DateName + '_Day_ID" onChange="' + DateName + '_Object.changeDay(this)">';
         for (var j=1;j<=eval(DateName + '_Object.picked.dayCount');j++) {
            DaySelected = ((DefaultDate != '') && (eval(DateName + '_Object.picked.day') == j)) ? ' selected' : '';
            DateContent+='<option' + DaySelected + '>' + j + '</option>';
         }
         DateContent+='</select>' + String.fromCharCode(13) + '</td>' + String.fromCharCode(13) + '<td valign="middle" style="visibility:hidden; position:absolute;">';
         DateContent+='<input' + InitialStatus + ' class="calendarDateInput" type="text" id="' + DateName + '_Year_ID" size="' + eval(DateName + '_Object.picked.yearPad.length') + '" maxlength="' + eval(DateName + '_Object.picked.yearPad.length') + '" title="Year" value="' + eval(DateName + '_Object.picked.yearPad') + '" onKeyPress="return YearDigitsOnly(window.event)" onKeyUp="' + DateName + '_Object.checkYear(this)" onBlur="' + DateName + '_Object.fixYear(this)">';
         DateContent+='<td valign="middle">' + String.fromCharCode(13) + '<a' + InitialStatus + ' id="' + DateName + '_ID_Link" href="javascript:' + DateName + '_Object.show()" onMouseOver="return ' + DateName + '_Object.iconHover(true)" onMouseOut="return ' + DateName + '_Object.iconHover(false)"><img src="' + ImageURL + '" align="left" title="Calendar" border="0"></a>&nbsp;';
         DateContent+='<span id="' + DateName + '_ID" style="position:absolute;visibility:hidden;z-index:25000;width:' + (CellWidth * 8) + 'px;background-color:' + CalBGColor + ';border:1px solid #a7c7e7;" onMouseOver="' + DateName + '_Object.handleTimer(true)" onMouseOut="' + DateName + '_Object.handleTimer(false)">';
			
			var monName = MonthNames[parseInt(eval(DateName + '_Object.picked.monthPad'))-1];
         monName = (monName == null ? MonthNames[Today.getMonth()]:MonthNames[parseInt(eval(DateName + '_Object.picked.monthPad'))-1]) ;
         
         DateContent+='<table width="' + (CellWidth * 8) + 'px" cellspacing="0" cellpadding="1" style="background-color:white;z-index:25000;">' + String.fromCharCode(13) + '<tr style="background-color:' + TopRowBGColor + ';">';
         DateContent+='<td id="' + DateName + '_Previous_ID" style="cursor:default" align="center" class="calendarDateInput" style="height:' + CellHeight + 'px" onClick="' + DateName + '_Object.previous.go();" onMouseDown="VirtualButton(this,true)" onMouseUp="VirtualButton(this,false)" onMouseOver="return ' + DateName + '_Object.previous.hover(this,true)" onMouseOut="return ' + DateName + '_Object.previous.hover(this,false)" title="' + eval(DateName + '_Object.previous.monthName') + '"><img src="' + PrevURL + '"></td>';
         DateContent+='<td style="cursor:pointer" align="center" class="calendarDateInput" style="height:' + CellHeight + 'px" colspan="5" onMouseOver="self.status=\'Click to view ' + CurrentDate.fullName + '\';return true;" onMouseOut="self.status=\'\';return true;" title="Show Current Month"><div><span id="' + DateName + '_Current_ID" onClick="' + DateName + '_Object.displayed.goCurrent();" style="font-size:9px;">' + monName + '</span>' + DisplayYear(DateName) +'</div></td>';
         DateContent+='<td id="' + DateName + '_Next_ID" style="cursor:default" align="center" class="calendarDateInput" style="height:' + CellHeight + 'px" onClick="' + DateName + '_Object.next.go()" onMouseDown="VirtualButton(this,true)" onMouseUp="VirtualButton(this,false)" onMouseOver="return ' + DateName + '_Object.next.hover(this,true)" onMouseOut="return ' + DateName + '_Object.next.hover(this,false)" title="' + eval(DateName + '_Object.next.monthName') + '"><img src="' + NextURL + '"></td></tr>' + String.fromCharCode(13) + '<tr>';
         for (var w=0;w<7;w++) DateContent+='<td width="' + CellWidth + 'px" align="center" class="calendarDateInput" style="height:' + CellHeight + 'px;width:' + CellWidth + 'px;font-weight:bold;border-top:1px solid #a7c7e7;border-bottom:1px solid #a7c7e7;">' + WeekDays[w] + '</td>';
         DateContent+='</tr>' + String.fromCharCode(13) + '</table>' + String.fromCharCode(13) + '<span id="' + DateName + '_DayTable_ID">' + eval(DateName + '_Object.buildCalendar()') + '</span>';
         //DateContent+=(String.fromCharCode(13) + '</span>');
         
         if(this.globalDisTime)
		 {  
			var HTML1='';
		   HTML1 = '<span class="calendarDateInput"><table cellspacing="0" border="0" cellpadding="1"><tr><td style="text-align:right;">Time</td><td style="text-align:left;"><select id="Hour_ID" style="font-size:9px; height:15px; width:40px;" onChange=Time_Change("get");>';
		   for(h=0;h<24;h++)
		   {
				if(selectedHour==h)
					HTML1 += '<option value="' + getDblChar(h) + '" selected>'+ getDblChar(h) + '</option>';
				else
					HTML1 += '<option value="' + getDblChar(h) + '">'+ getDblChar(h) + '</option>';
		   }   
		   HTML1 += '</select>';
            
		   HTML1 += '<strong>:</strong><select id="Minute_ID" style="font-size:9px; height:15px; width:40px;" onChange=Time_Change("get");>';
		   for(h=0;h<60;h=h+5)
		   {
				if(selectedMinute==h)
					HTML1 += '<option value="' + getDblChar(h) + '" selected>'+ getDblChar(h) + '</option>';
				else
					HTML1 += '<option value="' + getDblChar(h) + '">'+ getDblChar(h) + '</option>';
		   }   
		   HTML1 += '</select></td><td><button id="Go" onClick="return goBtnClick()"><span class="buttonLeft"><span class="buttonRight">Go</span></span></button></td></tr></table></span>';

		   DateContent+=HTML1;
		 }
		 
		 DateContent+='</td></span></td>' + String.fromCharCode(13) + '</tr>';
		 
		
         // Completion of calander
         DateContent+=String.fromCharCode(13) + '</table></div>';
         
         DateContent+='<script>Time_Change("set");</script>';
        
      }
   }
   return DateContent+styleContent;
}


function displayFrame(varl)
{
	//alert(varl);
	var frameid=document.getElementById(varl + '_IFrame');	
	var testVar=document.getElementById(varl + '_ID');
	//iframevar.style.left= testVar.style.left;

}
function DisplayYear(dn)
{
	var ObjName=dn;
	var YrContent="";
	var yrVal=eval(dn + '_Object.picked.yearPad');
	var curYear;
	if(yrVal != '')
	{
		curYear=yrVal
	}
	else
	{
		curYear = Today.getFullYear();
	}
	YrContent += '<select id="'+ dn +'_YearID" title="Select Year" style="font-size:9px; height:15px; width:48px;" onchange="' + dn + '_Object.checkYear(this)">';
	for (var i=curYear-40; i<= curYear; i++)
	{
		if(i == curYear)
		{
			YrContent += '<option value="' + i + '" selected>' + i + '</option>';
		}
		else
		{
			YrContent += '<option value="' + i + '">' + i + '</option>';
		}
	}
	YrContent+='</select>';
	return YrContent;

}
function ChangeYear(yearVal,dn)
{
	if(document.getElementById(dn + "_YearID"))
	{
		document.getElementById(dn + "_YearID").value=yearVal;	
	}
}

function days_between(date1, date2) {

    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24;

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime();
    var date2_ms = date2.getTime();

    // Calculate the difference in milliseconds
    var difference_ms = date1_ms - date2_ms;
    
    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY);

}

function goBtnClick(){
orderDT_Object.pickDay(currentDay);
return false;
}var userId = GetCookie("TN_UserId");
var univCode=GetCookie("TN_Holding");
/* Menu bar */
function SetActiveMenu() 
{
    var url = document.URL;
    var divMain = $("mainMenu");
    if(divMain)
    {
        for(var i=0; i<divMain.childNodes.length; i++)
        {
            if(divMain.childNodes[i].href)
            {
					var urlTempPath = url.substring(0, url.indexOf(".aspx"));
					if(urlTempPath == "" && url.indexOf(".aspx") < 0) {
						 urlTempPath = url;
					}
                var urlPath = urlTempPath.substring(0,urlTempPath.lastIndexOf("/")+1);
                var hrefPath = divMain.childNodes[i].href.substring(0, divMain.childNodes[i].href.lastIndexOf("/")+1);
                if(url.indexOf("/Home.aspx") >= 0 && url.indexOf("/Login.aspx") < 0)
                {
						urlPath += "Investments/";
                }
                
                var divId = divMain.childNodes[i].id;
                var subMenu = $("sub"+divId);
                if(subMenu)
                {
						 var child = subMenu;
						 var displayChild = child.style;
						 if(!child.style)
						 {
							displayChild = child;
						 }
						 if(hrefPath.toUpperCase() == urlPath.toUpperCase() || IsUrlBelongsToMenu(divMain.childNodes[i], urlPath))
						 {
							divMain.childNodes[i].className = "selected";

							displayChild.display = "block";
							var currSub = $("currSubmenu");
							if(currSub)
							{
								currSub.value = child.id;
								var secondLvl = child.getElementsByTagName("LI");
								var selSecondLvl = 0;
								if(default2ndLevel != '')
								{
									var lvl2 = $(default2ndLevel)
									if(lvl2)
									{
										lvl2.className += " selected";
									}
								}
								else
								{
									for(var k=0;k<secondLvl.length;k++)
									{
										if(secondLvl[k])
										{
											var anchor = secondLvl[k].getElementsByTagName("A");
											for(var l=0;l<secondLvl.length;l++)
											{
												var isPerfPage = 0;
												if(url.toUpperCase().indexOf("/INVESTMENTS/")>=0) isPerfPage = 1;
												if(typeof(anchor[l])!='undefined' 
													&& url.toUpperCase().indexOf(anchor[l].href.toUpperCase())>=0 )
												{
													if(isPerfPage == 1)
													{
														var anchHref = anchor[l].href.toUpperCase();
														anchHref = "HTTP://"+getHostname(url).toUpperCase()+anchHref.substring(anchHref.indexOf("/INVESTMENTS/"),anchHref.length);
														var urlHref = url.toUpperCase();
														if(urlHref.indexOf("?")>0) urlHref = urlHref.substring(0,urlHref.indexOf("?"))
														if (anchHref != urlHref+"?UNIV="+getQueryValue("univ").toUpperCase()) {
															continue;
														}
													}
													anchor[0].className += " selected";
													selSecondLvl = 1;
													break;
												}
											}
											if(selSecondLvl == 1)
												break;
										}
									}
								}
							}
						 }
						 else
						 {
							  displayChild.display = "none";
						 }
                }
            }
        }
    }
}

function getHostname(url) {
	var re = new RegExp('^(?:f|ht)tp(?:s)?\://([^/]+)', 'im');
	return url.match(re)[1].toString();
}

function IsUrlBelongsToMenu(menu, urlPath)
{
    if(menu.id.toUpperCase() == "TOOLS")
    {
        if(urlPath.toUpperCase().indexOf("/PSCAN") >= 0 
        || urlPath.toUpperCase().indexOf("/RSS") >= 0)
        {
            return true;
        }
    }
    if(menu.id.toUpperCase() == "INVESTMENTS")
    {
        if(urlPath.toUpperCase().indexOf("/FACTSHEETS") >= 0
			|| urlPath.toUpperCase().indexOf("/GENERAL") >= 0
			|| urlPath.toUpperCase().indexOf("/INVESTMENTS") >= 0)
        {
            return true;
        }
    }   
    if(menu.id.toUpperCase() == "EDUCATION")
    {
        if(urlPath.toUpperCase().indexOf("/GLOSSARIES") >= 0
        	|| urlPath.toUpperCase().indexOf("/MASTERCLASS") >= 0)
        {
            return true;
        }
    }   
    return false;
}

function portSubmit(page)
{
    document.masterForm.action=page;
    document.masterForm.submit();
}
	 
function ChangeCurrency(currency)
{
    SetCookie("TN_Currency", currency, 123231);
    document.masterForm.submit();
}

function SetActiveCurrency(currency)
{
 if(emailSiteCode!="TNUK")
 {
    var srcFile = "";
    var mnuSrc = "";
    var title = "";
    switch(currency.toUpperCase())
    {
        case "LOCAL":
        case "":
            srcFile = "currencyMaster";
            mnuSrc = "Local";
            title = "Fund Currency";
            break;
        case "GB":
        case "GBP":
            srcFile = "currencyPound";
            mnuSrc = "Pound";
            title = "UK Pound";
            break;
        case "US":
        case "USD":
            srcFile = "currencyDollar";
            mnuSrc = "Dollar";
            title = "US Dollar";
            break;
        case "EU":
        case "EUR":
            srcFile = "currencyEuro";
            mnuSrc = "Euro";
            title = "Euro Currency";
            break;
        case "HK":
        case "HKD":
            srcFile = "currencyEuro";
            mnuSrc = "HKDollar";
            title = "HK Dollar";
            break;   
        case "SG":
        case "SGD":
            srcFile = "currencySG";
            mnuSrc = "SGDollar";
            title = "SG Dollar";
            break;  
        case "IN":
        case "INR":
            srcFile = "currencyRupees";
            mnuSrc = "Rupees";
            title = "IN Rupee";
            break; 
    }
    var leftCurrentCurr = $('currentCurrency');
    if(leftCurrentCurr)
    {
		leftCurrentCurr.src = "/images/"+srcFile+".png";
		leftCurrentCurr.title = title;
    }
    var mnuCurrentCurr = $('mnuCurrentCurrency');
    if(mnuCurrentCurr)
    {
		mnuCurrentCurr.src = "/images/curMenu/"+mnuSrc+"Icon.png";
		mnuCurrentCurr.title = title;
		var rdo = $("rdo"+mnuSrc);
		if(rdo)
		{
			rdo.checked = true;
		}
    }
   }
}

function LaunchPop(urlpop, width, height)
{
	newWindow = window.open(urlpop,"popup","scrollbars,height="+height+",width="+width+",location=0,status=0");
	newWindow.focus();
}


/* * *		Factsheet Functions     * * */

function GroupFile()
{
    var mngCode = $('managerCode').value
    var universeCode = $('universeCode').value
    document.location = "GroupFactSheet.aspx?managerCode=" + mngCode + "&univ="+universeCode;
}

function FSPageTransistion()
{
	var pagetype = getQueryValue("pagetype");
	if(pagetype=='') pagetype='overview';
	pagetype = pagetype.toUpperCase();
	if($('tab1'))$('tab1').className = (pagetype == 'OVERVIEW' ? 'selected' : '');
    if($('tab2'))$('tab2').className = (pagetype == 'PERFORMANCE' ? 'selected' : '');
    if($('tab3'))$('tab3').className = (pagetype == 'RATIOS' ? 'selected' : '');
    if($('tab4'))$('tab4').className = (pagetype == 'PORTFOLIOBREAKDOWN' ? 'selected' : '');
    if($('tab5'))$('tab5').className = (pagetype == 'DIVIDENDS' ? 'selected' : '');
    if($('tab6'))$('tab6').className = (pagetype == 'MGMTINFO' ? 'selected' : '');
    if(SiteCode=='TNUK')
    {
        $('tab7').className = (pagetype == 'WRAPPER' ? 'selected' : '');
    }
    //$('tab1').className = (pagetype != 'PERFORMANCE' && pagetype != 'RATIOS' && pagetype != 'PORTFOLIOBREAKDOWN' && pagetype != 'DIVIDENDS' && pagetype != 'MGMTINFO'&& pagetype != 'WRAPPER' && pagetype == 'OVERVIEW') ? 'selected' : '';
}
function ITFSPageTransistion()
{
	var pagetype = getQueryValue("pagetype");
	pagetype = pagetype.toUpperCase();
    if($('tab2'))$('tab2').className = (pagetype == 'PERFORMANCE' ? 'selected' : '');  
    if($('tab3'))$('tab3').className = (pagetype == 'DIVIDENDS' ? 'selected' : '');
    if($('tab4'))$('tab4').className = (pagetype == 'PORTFOLIOBREAKDOWN' ? 'selected' : '');
    if($('tab5'))$('tab5').className = (pagetype == 'ANALYSIS' ? 'selected' : '');
    if($('tab6'))$('tab6').className = (pagetype == 'LIFE' ? 'selected' : '');
    if($('tab7'))$('tab7').className = (pagetype == 'PENSION' ? 'selected' : '');    
    if($('tab1'))$('tab1').className = (pagetype != 'PERFORMANCE' && pagetype != 'RATIOS'&& pagetype != 'ANALYSIS' && pagetype != 'PORTFOLIOBREAKDOWN' && pagetype != 'DIVIDENDS' && pagetype != 'MGMTINFO' && pagetype != 'PENSION' && pagetype != 'LIFE') ? 'selected' : '';
}

function CFPPageTransistion()
{
	var pagetype = getQueryValue("pagetype");
	pagetype = pagetype.toUpperCase();
    if($('tab2'))$('tab2').className = (pagetype == 'VIEW' ? 'selected' : '');  
    if($('tab1'))$('tab1').className = (pagetype != 'VIEW') ? 'selected' : '';
}

function ChangeSpan(typeCode, unitname, benchmarkcode, benchmarkname)
{
	var imgChart = $("chartImg");
	var timeSpan = $("timeSpan");
	if(imgChart)
	{
		imgChart.src = "ChartBuilder.aspx?chart=3&typeCode="+typeCode+"&unitname="+unitname+"&benchmarkcode="+benchmarkcode+"&benchmarkname="+benchmarkname+"&span="+timeSpan.value+"&w=375&h=240";
	}
}

function ChangeSpanValue(typeCode, unitname, benchmarkcode, benchmarkname)
{
	var imgChart = $("fundChart");
	var timeSpan = $("chartperiod");
	if(imgChart)
	{
		imgChart.src = "/Factsheets/ChartBuilder.aspx?chart=3&typeCode="+typeCode+"&unitname="+unitname+"&benchmarkcode="+benchmarkcode+"&benchmarkname="+benchmarkname+"&span="+timeSpan.value+"&h=210&w=310";
	}
}
function ChangeSpanWidth(typeCode, unitname, benchmarkcode, benchmarkname,width)
{
	var imgChart = $("fundChart");
	var timeSpan = $("chartperiod");
	if(imgChart)
	{
		imgChart.src = "/Factsheets/ChartBuilder.aspx?chart=3&typeCode="+typeCode+"&unitname="+unitname+"&benchmarkcode="+benchmarkcode+"&benchmarkname="+benchmarkname+"&span="+timeSpan.value+"&h=250&w="+width;
	}
}
function ChangeDiscPreSpan(unitcode,span)
{
  var imgChart = $("Img6");
  if(span!="" && imgChart)
  {
  imgChart.src = "/Webservices/Charting.asmx/GetDiscountPremiumChart?width=650&height=250&unitCode="+unitcode+"&span="+span;
  }
}
function ChangeUnit(code)
{
	$("citicode").value = code;
	document.masterForm.submit();
}


function getOptionIndex(selectCtrlID, value) 
{
	var select = $(selectCtrlID);
	for (var i = 0; i < select.options.length; i++) {
	  if (select.options[i].value == value) 
		return i;
	}
	return -1;
}

function LoadSectorsByAssetClass(univ, assetClassCtrl)
{
 var universe=univ;
 if(assetClassCtrl)
 {
	 var assetClass = assetClassCtrl.options[assetClassCtrl.selectedIndex].text;

	 // Loading Sectors
	 var Sector=TrustnetX.Controls.CustomisedTable.LoadSectorsByAssetClass(universe, assetClass);
	 Sector=Sector.value;
	 var sectorDDCtrl=$(ctrlId+"_"+"Sector");
	 if(sectorDDCtrl)
	 {
		 var initialOptionText = sectorDDCtrl.options[0].text;
		 var initialOptionValue = sectorDDCtrl.options[0].value;
	 
		 sectorDDCtrl.options.length=0;
		 var optionElement=document.createElement("option");
		 optionElement.text = initialOptionText;
		 optionElement.value = initialOptionValue;
		 sectorDDCtrl.options.add(optionElement);
		 if(Sector)
		 {
			 for(i=0;i<Sector.length;i++)
			 {
				optionElement=document.createElement("option");
				optionElement.text=Sector[i].SectorName;
				optionElement.value=Sector[i].SectorClassCode;
				sectorDDCtrl.options.add(optionElement);
			 }
		 }
	}
 }
}

function GetSectorsIfValid(univ, sectorDDId, selectedValue)
{
	var hdnSectorValid = $('hdnTQSectUnAvail');
	if(hdnSectorValid) {
		var sectorUnAvailArr = hdnSectorValid.value.split(',');
		if(IsStringFoundInArray(sectorUnAvailArr, univ)) {
			$(sectorDDId).value = "";
			$(sectorDDId).disabled = true;
			$('TQCrownRating').value = "";
			$('TQCrownRating').disabled = true;
		}
		else {
			LoadSectorsByUniv(univ, sectorDDId, selectedValue);
			$('TQCrownRating').disabled = false;
		}
		//Universe Value Assigned while selecting radio button in TopQuartile Page
	    univValue=univ;
	}
}

function AssetSectorChange(univCode)
{
   var assetClassCtrl = $(ctrlId+"_AssetClass");
	if(assetClassCtrl)
	{
		var sectorDD = $(ctrlId+"_Sector");
		
		
		LoadSectorsByAssetClass(univCode, assetClassCtrl);
		var hdnsector = $(ctrlId+"_CurrentSector");
		
		if(sectorDD && hdnsector) {
			for (i=0; i < sectorDD.options.length; i++){  
				if(sectorDD.options[i].value == hdnsector.value) {
					sectorDD.selectedIndex = i;
				}
			}
		}
	}
}

function DeHighlightRows(typecodes)
{
	var cookieType = Mode;
	var basketOverriden = false;
	 var overrideBasketElem = $('overrideBasketCookie');
	 if(overrideBasketElem) {
		if(overrideBasketElem.value != "") {
			basketCookieName = overrideBasketElem.value;
			basketOverriden = true;
		}
	 }
   var Title="basket";    
	 switch(cookieType.toUpperCase())
	 {
		   case "PORT":
			  Title="Portfolio '"+portName+"'"
			  break;
		   case "WATCH":
			  Title="Watchlist";
			  break;
		   default:
			  if(basketOverriden){
				 Title=basketCookieName;
			  }
			  else {
				 Title="basket";
			  }
			  break;
	 } 
    var elements = document.getElementsByTagName("TR");
    var typecodeArr = typecodes.split(',');
    for(var i=0;i<elements.length;i++)
	{
	    if(IsStringFoundInArray(typecodeArr, elements[i].id))
	    {
			var imgTags = elements[i].getElementsByTagName('IMG');
			for(var j=0;j<imgTags.length;j++)
			{
				if(imgTags[j].src.indexOf("/icons/removeIco.png") >= 0)
				{
					imgTags[j].src = "/icons/icon_plus.png";					
					imgTags[j].title = "add to "+Title;
					imgTags[j].width = "16";
					imgTags[j].height = "15";
				}
			}
	      elements[i].className = elements[i].className.replace("selected", "");
	    }
	}
	elements = document.getElementsByTagName("DIV");
	for(var i=0;i<elements.length;i++)
	{
	    if(IsStringFoundInArray(typecodeArr, elements[i].id))
	    {
			var imgTag = $("Img-"+elements[i].id);
			if(imgTag)
			{
				if(imgTag.src.indexOf("/icons/removeIco.png") >= 0)
				{
					imgTag.src = "/icons/icon_plus.png";
					imgTag.title = "add to "+Title;
					imgTag.width = "16";
					imgTag.height = "15";
				}
			}
			var divTag = $("span-"+elements[i].id);
			if(divTag)
			{
			    if(divTag.innerHTML.indexOf('equity') > 0)
			    {
			        divTag.innerHTML = "Add this equity to basket";
			    }
			    else
			    {
				    divTag.innerHTML = "Add this unit to basket";
				}
			}
			elements[i].className = elements[i].className.replace("bold", "");
	    }
	}
}

function retainSelectedVal(typeCode)
{
	var value = GetCookie("TN_RetainSelected");
//	if(value=='')
//	{
//	value = GetCookie("shortlisted");
//	}
	var spliter =((value != '')?',':'');
	value +=  spliter + typeCode;
	SetCookie("TN_RetainSelected", value);
}
	 

function DeleteFromShortlist(typecode, cookieName)
{
	 var value = GetCookie(cookieName);
//	 if(value=='' && cookieName=="TN_RetainSelected")
//	 {
//	  value = GetCookie("shortlisted")	
//	 }
	 var newShortList = '';
	 var spliter ='';

	var farray = new Array();
	farray = value.split(',');
	for(var i=0; i< farray.length; i++)
	{
		if(farray[i] != typecode)
		{
			 newShortList += spliter + farray[i];
			 spliter = ',';
		}
	}   
	if(cookieName=="TN_RetainSelected")
	{
    SetCookie(cookieName, newShortList);
    }else{
     SetCookie(cookieName, newShortList, 123231);
    }
}


function DeleteFromDB(typecode, TypeCodes)
{
	 var value = TypeCodes;
	 var newShortList = '';
	 var spliter ='';

	var farray = new Array();
	farray = value.split(',');	
	for(var i=0; i< farray.length; i++)
	{
		if(farray[i] != typecode)
		{
			 newShortList += spliter + farray[i];
			 spliter = ',';
		}
	}   
   
   PorttypeCodes=newShortList;   
   WatchtypeCodes=newShortList;
}


function SetCookie( name, value, expires, path, domain, secure ) 
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	/*
	if the expires variable is set, make the correct 
	expires time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : ";path=/" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

/// 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));
}

// this deletes the cookie when called
function DeleteCookie(name, path, domain)
{
   if (GetCookie(name))
   {
      document.cookie = name + "=" + 
         (path ? ";path=" + path : ";path=/") +
         (domain ? ";domain=" + domain : "") +
         ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
   } 
}

// Function to set the selected values in dropdown.
function setSelect(sbox, value) {
	if(sbox != null && sbox.options != null)
	{
		for (i = 0 ; i < sbox.options.length; i++) {
			if (sbox.options[i].value == value) {
				sbox.selectedIndex = i;
				return;
			}
		}
	}
}

function IsStringFoundInArray(array, stringValue)
{
    var found = false;
    if(stringValue != '')
    {
		 for(var i=0; i< array.length; i++)
		 {
			  if(array[i] == stringValue)
			  {
					found = true;
					break;
			  }
		 }
	 }
    return found;
}

function HideTooltip()
{
    $("Popup_Sortlist").style.display="none";
}

function findPosX(obj)
{
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
}

function findPosY(obj)
{
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
}


/// 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 '';
	}
}



//Function for Fund Comaprision page


function checkTypeCode(url,min, max, parameters)
{
//	var typeCode=GetCookie("TN_RetainSelected");
//	var SortListedtypeCode=GetCookie("shortlisted");
//	if(typeCode=='')
//	{
//	typeCode=SortListedtypeCode;
//	SetCookie("TN_RetainSelected", SortListedtypeCode);
//	}
	
	
	var typeCode=GetCookie("TN_RetainSelected");
	var element = document.getElementsByName("ckShortList");
	if(typeCode=='' && element.length==0)
	{
	    typeCode = GetCookie("shortlisted");
	     SetCookie("TN_RetainSelected", typeCode);
	}    
    
	var SortListedtypeCode = GetCookie("shortlisted");
	if(SortListedtypeCode=='')typeCode='';
	
	if(SortListedtypeCode!='')
	{
	var length = 0; 
	if(typeCode == null || typeCode == '')
	{
		//alert('No funds selected for comparison to add funds go to performance page and click the green color plus button.');
		var imageUrl='<img src="images/icon_plus.png"/>';
		alert('Select 2 or more funds for fund comparison. Add funds in Basket using "Green Plus Icon" wherever you see it next to a fund.');
	}
	else
	{
			var farray = new Array();
			farray = typeCode.split(',');
			length = farray.length;
			if(length<2)
			{
				//alert('Atleast select 2 funds for comparison to add funds go to performance page and click the green color plus button.');
				alert('Select 2 or more funds for fund comparison. Add funds in Basket using "Green Plus Icon" wherever you see it next to a fund.');
			}
			if(length>4)
			{
				alert('Selected funds should be less than or equal to 4');
				document.masterForm.action="/Tools/Tools.aspx";
				//document.masterForm.submit();
			}
			if(length>=min && length<=max){
				document.masterForm.action=url;
				document.masterForm.submit();
			}
	}
	}else
	{
		//alert('No Funds in Basket. To add funds in Basket using "Green Plus Icon" wherever you see it next to a fund.');
		alert('There are no funds in your basket. To add funds to your basket use the "Green Plus Icon" wherever you see it next to a fund.');
	}
}

// Function to trim the given string
function TrimAString(str)
{ 
	while(str.charAt(0) == (" "))		
	{ str = str.substring(1);	}
	
	while(str.charAt(str.length-1) == " " )
	{ str = str.substring(0,str.length-1);	}

	return str;
}

//Check Registor Details
function CheckDetails(chk)
{
	
    var userName,userPwd,userPwd2     
    Password=$("Password");
    userPwd2=$("userPwd2");      
	var Email=$("EmailAddress");  	 
	var elements=document.getElementsByName('Register'); 	
	var  values="";
	var keys="";
	var ids="";	
	var err="You must enter values for mandatory (*) fields.";		 
	if(elements.length!=0)
	{
		for(var i=0;i<elements.length;i++)
		{	 	       
			if(elements[i].tagName=="INPUT")
			{
				if(elements[i].value=="")
				{		
					var idName="span"+elements[i].id;														  
					$(idName).style.visibility="visible"; 		
					$("errMsg").innerHTML=err;
					ids="error";  					    
				}
			   else
			   {
					if(elements[i].type=="text")
					{
						values +=elements[i].value+",";	
						keys+=elements[i].id+",";			 				    
						$("span"+elements[i].id).style.visibility="hidden"; 
					}    
				}	
			}
		
			if(elements[i].tagName=="SELECT")
			{
				var rowEle = document.getElementById("tbl" + elements[i].id);
				if(rowEle.style.display!='none')
				{	 
					if(elements[i].options[elements[i].selectedIndex].value=="" && elements[i].id != "")
					{	
						var Expatriot=$("Expatriate");	
						if(Expatriot!=null)
						{	
							if(Expatriot.value=="Yes")
							{
								$("span"+elements[i].id).style.visibility="visible"; 
								$("errMsg").innerHTML=err;		     
								ids="error";
							}
							else
							{				 
								if(elements[i].id!='Country of residence')
								{
									$("span"+elements[i].id).style.visibility="visible"; 
									$("errMsg").innerHTML=err;		     
									ids="error";
								}
							}				   
						}
						else
						{
							$("span"+elements[i].id).style.visibility="visible"; 
							$("errMsg").innerHTML=err;		     
							ids="error";
						}
					}
					else
					{
						if(elements[i].id=='Referred by')
						{
							var optionVal = elements[i].options[elements[i].selectedIndex].value;
							if(optionVal=='Others')
							{
								var eleRefByOthersTxt = $('ReferredByOthers');
								if(eleRefByOthersTxt)
								{
									values = values + eleRefByOthersTxt.value + ",";
								}
								else
								{
									values = values + optionVal + ",";
								}
							}
							else
							{
								values = values + optionVal + ",";
							}
						}
						else
						{
							values=values+elements[i].options[elements[i].selectedIndex].value+",";
						}
						
						keys+=elements[i].id+",";
						$("span"+elements[i].id).style.visibility="hidden";
					}
				}
			}
			 //$("values").value=values;	
			 //$("keys").value=keys;
		}
		if($("TrustnetResearch"))
		{
			if($("TrustnetResearch").checked==true)
			{
				values += "1,";
				keys += "Trustnet Research,";
			}
			else
			{
				values += "0,";
				keys += "Trustnet Research,";
			}
		}
			
		if($("TrustnetUpdates"))
		{
			if($("TrustnetUpdates").checked==true)
			{
				values += "1,";
				keys += "Trustnet Updates,";
			}
			else
			{
				values += "0,";
				keys += "Trustnet Updates,";
			}
		}
		
		$("values").value=values;	
		$("keys").value=keys;
	}
	  
	if(Email.value=="")
	{
		$("spanEmail").style.visibility="visible";
		$("errMsg").innerHTML=err;
		ids="error";   
	}
	else
	{
		if(validateEmail(Email)==false)
		{
			ids="error";
			Email.value=Email.value
			//err="** Invalid E-mail ID"
			$("errMsg").innerHTML=err;
			$("EmailAddress").focus();
		}
		else
		{
			$("spanEmail").style.visibility="hidden";
		}
	}
	if(Password.value=="" && chk=="add")
	{
		$("spanPassword").style.visibility="visible";
		$("errMsg").innerHTML=err;
		ids="error";   
	}
	else
	{
		if(Password.value!=userPwd2.value)
		{
			ids="error";  
		   $("errMsg").innerHTML="Password and Confirm password should be same.";
		   $("spanuserPwd2").style.visibility="visible"; 
		   $("userPwd2").focus();
		}
		else
		{
			$("spanuserPwd2").style.visibility="hidden";
		}
		$("spanPassword").style.visibility="hidden";
	}
	if(chk=="add" && ids=="")
	{	    
		document.masterForm.submit();
	}
	else if(chk!="add" && ids=="")
	{
		document.masterForm.action="/Tools/Profile.aspx?type=1&boolLogin=register"
	   document.masterForm.submit();
	}
}

function CheckReferredByValue(refByVal)
{
	var eleRefByRow = $('ReferredByOthersRow');
	
	if(refByVal=='Others')
	{
		eleRefByRow.style.display='block';
	}
	else
	{
		eleRefByRow.style.display='none';
	}
}

function LoadCountry()
	{
	var Expatriot=$("Expatriate");
	
	if(Expatriot!=null)
	{	
	if(Expatriot.value=="Yes")
	{	
	$("tblCountry of residence").style.visibility="visible";
	$("tblCountry of residence").style.display="";	
	}else{
	$("tblCountry of residence").style.visibility="hidden";
	$("tblCountry of residence").style.display="none";
	$("tblCountry of residence").style.position="relative";
	}
	}
}

//Check Email ID
function echeck(str) {
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   $("errMsg").innerHTML="** Invalid E-mail ID";
		   return false
		}
		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   $("errMsg").innerHTML="** Invalid E-mail ID";
		   return false
		}
		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    $("errMsg").innerHTML="** Invalid E-mail ID";
		    return false
		}
		if (str.indexOf(at,(lat+1))!=-1){
		    $("errMsg").innerHTML="** Invalid E-mail ID";
		    return false
		 }
		if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    $("errMsg").innerHTML="** Invalid E-mail ID";
		    return false
		 }
		if (str.indexOf(dot,(lat+2))==-1){
		    $("errMsg").innerHTML="** Invalid E-mail ID";
		    return false
		 }		
		 if (str.indexOf(" ")!=-1){
		    $("errMsg").innerHTML="** Invalid E-mail ID";
		    return false
		 }
 		 return true					
}
	
//Check Login Details
function  CheckLogin()
{
     var Email,userPwd
     Email=$("EmailAddress").value;     
     userPwd=$("userPwd").value;     
     if(Email=="" && userPwd=="")
         {
            $("errMsg").innerHTML="Please type your e-mail address and Password";
            $("EmailAddress").focus();
            return false;
         }
     else if(Email=="")
         {
            $("errMsg").innerHTML="Please type your e-mail address";
            $("Email").focus();
            return false;
         }
     else if(userPwd==""){
            $("errMsg").innerHTML="Please type your Password";
            $("userPwd").focus();
            return false;
        }
     else if (validateEmail($("EmailAddress"))==false){     
		    Email=""
		    $("EmailAddress").focus();
		    return false;
	     }	    
	 else{
	 //   document.masterForm.action="PortfolioLogin.aspx?requiredLogin=true";
        document.masterForm.submit();         
        }
}

//Load Change Event
function onChange(){
	  document.masterForm.submit(); 
}

//Change Holding Link
function addHold()
{
if(code!=''){
 document.masterForm.action="/Investments/Perf.aspx?univ=E"
 document.masterForm.submit();
 }
}
  
//Get All Valution Totals And quantity
function addItems(page,val)
{
  var elements=document.getElementsByName("quantity");
  var elementPD=document.getElementsByName("PD");
  var elementBalance=document.getElementsByName("balance");  
  var elementRename=document.getElementsByTagName("INPUT");
  var quantity="";
  var balance="";  
  var elementCost=document.getElementsByName("Cost");
  var cost="";
  var err="";
  var PDCost="";
  var spliter="";
  var names="";
  var rdnCid="";
  var cName="";
for(var i=0;i<elementRename.length;i++)
{

    if(elementRename[i].name=="Rename")
    {         
    cName=elementRename[i].value;
    names=names+cName.replace(",","#@#")+",";
    rdnCid=rdnCid+elementRename[i].id+",";       
    }
} 

  

 for(var i=0;i<elementBalance.length;i++)
  { 
  
    if (elementBalance[i].value == "")
	{	
		elementBalance[i].select();
		elementBalance[i].focus();
		err="error";
		return false;	
	}
    if (chkNumeric(elementBalance[i]) == false)
	{	
		elementBalance[i].select();
		elementBalance[i].focus();
		err="error";	
		return false;
	}
	if(i==(elementBalance.length-1))
	{
	balance+=elementBalance[i].value;
	}else{
    balance+=elementBalance[i].value+",";
   }
 }
 
  
 
 $("hdnBalance").value=balance;
 if($("hdnRenames"))$("hdnRenames").value=names;
 if($("rdnCid"))$("rdnCid").value=rdnCid;  

 if(err=="")
 {
   if(val=="y"){
    document.masterForm.action=page+"?type=1";
   }else{
   document.masterForm.action=page;
 }
 document.masterForm.submit();
 }
}
    
//Key Press Event
function onSearchKeyPress(e, str) {
	var key;
	if (window.event) {
		key = window.event.keyCode; //ie
	}
	else {
		key = e.which; //ff
	}
	if (key == 13) {	
	   if(str.id=="EmailAddress" || str.id=="userPwd"){
	   CheckLogin();
	   }
//	   else if(str.id=="txtPassword")
//	   {
//	   CheckUser(); 
//	   }
	   else 
	   {
	    return false;
	   }
	}
}

//Key Press Event for simple text search
function onSearchTextKeyPress(e,keyword) 
{
    var key;
     
    if (window.event) {
        key = window.event.keyCode; //ie
    }
    else {
        key = e.which; //ff
    }
    if (key == 13) { 
       if((keyword.id=="strText" && keyword.value!="")||(keyword.id=="keyword" && keyword.value!=""))searchSubmit(keyword.value);else return false;
       
    }
 }
        
 //submit to simple text search        
 function searchSubmit(keyword)
 {
	if(keyword != "" && keyword.length >=3)
	{
		var scope = $('scope');
		var searchArticles = $('rdoArticles');
		var pageNo="";
		if(document.getElementById('PageNo'))
			pageNo="&PageNo="+ document.getElementById('PageNo').value

		if(!ValidateString(keyword))
		{
			alert('Invalid input, please provide valid input.');
			return false;
		}
		if(typeof(scope)!='undefined' && scope != null && typeof(searchArticles)!='undefined')
		{
			if(searchArticles.checked)
			{
				window.location='/Tools/Search.aspx?keyword='+URLencode(keyword)+'&scope='+ URLencode(scope.value) +'&on=a'+pageNo;
			}
			else
			{
				window.location='/Tools/Search.aspx?keyword='+URLencode(keyword)+'&scope='+scope.value+'&on=f';
			}
		}
		else if(typeof(scope)!='undefined' && scope != null)
		{
			window.location='/Tools/Search.aspx?keyword='+URLencode(keyword)+'&scope='+scope.value;
		}
		else
		{
			window.location='/Tools/Search.aspx?keyword='+URLencode(keyword);
		}
	}
	else
	{
		alert("Value should not be empty and should be more than four letters");
		return false;
	}
 }
 
 function ValidateString(n)
 {
	if(n.indexOf("&#") > -1 || n.indexOf("<") > -1 || n.indexOf("!") > -1 || n.indexOf("/") > -1 || n.indexOf("__") > -1)
	{
		return false;
	}
	return true;
 }
 
 function URLencode(n)
 {
	var encoded = "";
	
	var len=n.length;
	for(;;)
	{
		n=n.replace('%25','%');
		n=n.replace('%20',' ');
		if(n.length == len)
		{
			break;
		}
		else
		{
			len=n.length;
		}
	}
	
	n=n.replace("%2520"," ");
	n=n.replace("%20"," ");
    var HEX = "0123456789ABCDEF";
    var UNSAFECHARS = '<>"#%{}|^~[];/?:@=&\'';

    for (var i = 0; i < n.length; i++ ) {

    	var ch = n.charAt(i);

    	if (ch == " ") {
		encoded += "+";	// x-www-urlencoded, rather than %20
    	}
    	else if (UNSAFECHARS.indexOf(ch) != -1) {
			var charCode = ch.charCodeAt(0);
			encoded += "%";
            encoded += HEX.charAt((charCode >> 4) & 0xF);
            encoded += HEX.charAt(charCode & 0xF);
			}
		else{
			//it�s safe
			encoded += ch;
    	}
    } // for
   
    return encoded;
}
 
 function NumericCount(id,e)
 {
 var keycode= (e.keyCode) ? e.keyCode : e.which;
 if((keycode>= 48 && keycode<=57 ))
 {
 var value= id.value.split("."); 
 if(value[0].length>12)
 {
 return false;
 }
 }
 return true;
 }
 
 // print any page

 function printMe() 
 { 

   var windowWidth='850';

   var windowHeight='850';

   

    var centerWidth = (window.screen.width - windowWidth) / 2;

    var centerHeight = (window.screen.height - windowHeight) / 2;

    

    var url="";

    if(window.location.href.indexOf('?')>-1)
    {
        url=window.location.href+"&print=true";

    }
    else
    {
        url=window.location.href+"?print=true";

    }

     $('masterForm').action=url;
     $('masterForm').target="_blank";

     $('masterForm').submit();
     
     $('masterForm').action="";
     $('masterForm').target="";


   // newWindow = window.open(url, 'Print', 'scrollbars=1,resizable=1,width=' + windowWidth + ',height=' + windowHeight + ',left=' + centerWidth + ',top=' + centerHeight);
   //newWindow.focus(); 
   

    return;

  }

    



    function addLoadEvent(func) { 
	  var oldonload = window.onload; 
	  if (typeof window.onload != 'function') { 
	    window.onload = func; 
	  } else { 
	    window.onload = function() { 
	      oldonload(); 
	      func(); 
        } 
	  } 
	} 
	 
 //print this popup page
  function printThis()
  {
	  var portControl= document.getElementById('selectPortfolio');
	  if(portControl)
	  {
		 var w =portControl.selectedIndex;	   
		 var pName=portControl.options[w].text;  	  
		 var pText=document.getElementById("PortText");
		 if(pText)pText.innerHTML="<b>Portfolio Name : "+pName+"</b>";		 
	  }
	  for(var i = 0; (linkelement = document.getElementsByTagName("link")[i]); i++)
      { 
        if(linkelement.getAttribute("rel").indexOf("style") != -1 &&  linkelement.media == "print")
        { linkelement.media='All';
        }
      }

      var topMnu = $('topBG');
      if (topMnu) {

        var currency=$("mnuCurrentCurrency");
        
        var logo=null;
        
        if(logoName!=null&&logoName!='')
        {
            logo=document.createElement("IMG");
            logo.alt=emailSiteName;
            logo.title=emailSiteName;
            logo.border="0";
            logo.src="/images/"+logoName;
            
            if(emailSiteCode=="TNO")
            {
                logo.style.width="189px";
                logo.style.height="108px";
            }
            else if(emailSiteCode=="TNHK")
            {
                logo.style.width="220px";
                logo.style.height="91px";
            }
            else if(emailSiteCode=="TNIN")
            {
                logo.style.width="217px";
                logo.style.height="85px";
            }
            else if(emailSiteCode=="TNSG")
            {
                logo.style.width="223px";
                logo.style.height="82px";
            }
            else if(emailSiteCode=="TNUK")
            {
                logo.style.width="172px";
                logo.style.height="50px";
            }
            else if(emailSiteCode=="TNME")
            {
                logo.style.width="136px";
                logo.style.height="100px";
            }            
        }
        else
        {
          logo=document.createTextNode('  ');             
        }

        //TNHK_Logo.png
        //TN_Global.jpg
        
        var logoDiv=document.createElement("DIV");
        logoDiv.appendChild(logo);
        logoDiv.className='headerLogoPrint';        
        topMnu.style.display = 'none';
        
			var main = $('main');
			var footer = $('footer');
			var headDiv = document.createElement("DIV");
			
			
			//******************************************
			// Code for UK print preview starts here
			//******************************************
			if(emailSiteCode=="TNUK")
			{
				var userId=GetCookie("TN_UserId");
				/*
					ifIFA				-	False
					isWhileLable	-	True i.e., domain name other than www.trustnet.com
				*/
				if(isIFAUser == 0 && isWhiteLabel=="Yes" && isUniqueLogo=="No")
				{
					var ifaLogo=null;
					ifaLogo=document.createElement("IMG");
					ifaLogo.alt="";
					ifaLogo.title="";
					ifaLogo.border="0";
					ifaLogo.src="/images/" + wlLogoName;
					
					var oTbl=document.createElement("Table");
					var oTR= oTbl.insertRow(0);
					var oTDL= oTR.insertCell(0);
					var oTDR= oTR.insertCell(1);
					oTDL.style.width=ifaLogo.style.width;
					oTDL.appendChild(ifaLogo);
					
					var tnLogo=document.createElement("IMG");
					tnLogo.alt=emailSiteName;
					tnLogo.title=emailSiteName;
					tnLogo.border="0";
					tnLogo.src="/images/TN_Logo.png";
					
					var tnLogoDiv=document.createElement("DIV");
					tnLogoDiv.style.width="100%";
					tnLogoDiv.style.styleFloat="right";
					tnLogoDiv.style.cssFloat="right";
					tnLogoDiv.style.textAlign="right";
					tnLogoDiv.appendChild(tnLogo);
					
					oTDR.appendChild(tnLogoDiv);
               oTDR.style.textAlign="right";
					oTDR.style.styleFloat="right";
					
					if(!$('rightColumnHome') && !(document.URL.indexOf("/Factsheet.aspx?")>0) && !(document.URL.indexOf("/Tools.aspx")>0))
					{
						headDiv.style.width="980px";
						main.style.width="980px";
						if (footer) 
						{
							footer.style.width="980px";
						}
					}
					else
					{
						if (footer) 
						{
							if($('rightColumnHome')) footer.className = 'footerPrint';
							else footer.className = 'footerPrintBig';
						}
					}
					headDiv.appendChild(oTbl);
				}
				/* 
					UserId			-	Exist
					isIFA				-	True
					IFAFile			-	Exist
					isWhiteLabel	-	No i.e., the domain name is www.trustnet.com
				*/
				else if(userId != "" && isIFAUser == 1 && isIFAFileExist == "Yes")
				{
					var ifaLogo=null;
					ifaLogo=document.createElement("IMG");
					ifaLogo.alt="";
					ifaLogo.title="";
					ifaLogo.border="0";
					ifaLogo.src="/Tools/LogoBuilder.aspx?UserId=" +	userId;

					var oTbl=document.createElement("Table");
					var oTR= oTbl.insertRow(0);
					var oTDL= oTR.insertCell(0);
					var oTDM= oTR.insertCell(1);
					var oTDR= oTR.insertCell(2);
					var dt = new Date();
					//oTDL.style.width="210px";
					oTDL.style.width=ifaLogo.style.width;
					oTDL.appendChild(ifaLogo);
					oTDM.innerHTML=dt.toDateString() + "<br />" + ifaUserName + "<br />" + ifaUserEmail;
					logoDiv.style.width="100%";
					logoDiv.style.styleFloat="right";
					logoDiv.style.cssFloat="right";
					logoDiv.style.textAlign="right";					
					oTDR.appendChild(logoDiv);
               oTDR.style.textAlign="right";
					oTDR.style.styleFloat="right";
               
               if(!$('rightColumnHome') && !(document.URL.indexOf("/Factsheet.aspx?")>0) && !(document.URL.indexOf("/Tools.aspx")>0))
					{
						headDiv.style.width="980px";
						main.style.width="980px";
						if (footer) 
						{
							footer.style.width="980px";
						}
					}
					else
					{
						if (footer) 
						{
							if($('rightColumnHome')) footer.className = 'footerPrint';
							else footer.className = 'footerPrintBig';
						}
					}
					headDiv.appendChild(oTbl);
				}
				else
				{
					headDiv.appendChild(logoDiv);
					if (footer) 
					{
						if($('rightColumnHome')) footer.className = 'footerPrint';
						else footer.className = 'footerPrintBig';
					}
				}
			}
			else
			{
				headDiv.appendChild(logoDiv);				
				if (footer) 
				{
					if($('rightColumnHome')) footer.className = 'footerPrint';
					else footer.className = 'footerPrintBig';
				}
			}
			//******************************************
			// Code for UK print preview ends here
			//******************************************
        
        // Currency Div starts here        
        var curr='';        
        if(currency!=null)
        { 
			curr=currency.title;
        }
         
        var currImg='';
        var currImgWidth='66px';
        var currImgHeight='71px';
        
 
        switch(curr)
        {
            case 'Fund Currency': currImg='fundCurForPrint.jpg'; break;
            case 'UK Pound': currImg='poundForPrint.jpg'; break;
            case 'Euro Currency': currImg='euroForPrint.jpg'; break;
            case 'US Dollar': currImg='dollarForPrint.jpg'; break;
            case 'HK Dollar': currImg='HKDollarForPrint.jpg'; currImgHeight='64px'; break;
            case 'SG Dollar': currImg='SGDollarForPrint.jpg'; currImgHeight='64px'; break;
            default : currImg=''; break;
        }     
            
            var txtCurrDiv=document.createElement("DIV");
            var txtCurr=document.createElement("H1");
            
            var printCurr=null;
            
            if(currImg!='')
            {
                printCurr=document.createElement("IMG");
                printCurr.title=curr;
                printCurr.border="0";
                printCurr.src="/images/"+currImg;
                printCurr.style.width=currImgWidth;
                printCurr.style.height=currImgHeight;
                
                txtCurr.appendChild(document.createTextNode('All Performance figures are rebased to '+curr+'  '));
            }
            else
            {
                printCurr=document.createTextNode('  ');
                txtCurr.appendChild(document.createTextNode('  '));
            }
            
            txtCurrDiv.appendChild(txtCurr);
            txtCurrDiv.className='headerCurrPrintText';
            
           
            var currDiv=document.createElement("DIV");
            
            var currPrintDiv=document.createElement("DIV");
            currPrintDiv.className='headerCurrPrint';
            currPrintDiv.appendChild(printCurr);
            currDiv.appendChild(currPrintDiv);
            
            currDiv.appendChild(txtCurrDiv);
            currDiv.className='headerCurr';
            
            if(currImg=='')
            {   currDiv.style.height='58px';
            }
            
            if(emailSiteCode!="TNUK")
            {
					headDiv.appendChild(currDiv);    
				}
          // Currency Div ends here
        
           if($('rightColumnHome'))headDiv.className='headerPrint';
           else headDiv.className='headerPrintBig';
         
           main.insertBefore(headDiv,$('leftNav'));
           
           if($('ChartingMain')&&window.navigator.userAgent.indexOf("IE")==-1)
           {    main.insertBefore($('ChartingMain'),$('leftNav'));
           }
      }

        var leftColn = $('leftColumn');
        if (leftColn) {
            leftColn.style.display = 'none';
        }

		var quickSearch = $('QuickSearchStyle');
		if(quickSearch){
			quickSearch.style.display = 'none';
		}
        
        var articleRating=$('articleRating');
        if(articleRating)
        {
            articleRating.style.display='none';
        }
        
        var articleComment=$('articleComment');
        if(articleComment)
        {
            articleComment.style.display='none';
        }
        
        var rightColn = $('rightColumnHome');
        if (rightColn) {
            rightColn.style.display = 'none';
        }

        if($("userTypePopUp")) {
            closeInvestorSelector();
        }

        var topSearch=$("topSearchRow");
        if(topSearch) {
            topSearch.style.display = 'none';
        }

        var mainDiv=$('MainDiv');
        if(mainDiv){   
			mainDiv.style.display='none';
        }

      var calc=$('Calculator');
      if(calc) {   calc.style.display='none'; }

      var modeWindowDiv=$('ModeWindowDiv');
      if(modeWindowDiv) {
          modeWindowDiv.style.display='none';
      }

      var exRateCalc=$('ExRateCalc')
      if(exRateCalc) {
          exRateCalc.style.display='none';
      }

      var col=getElementsByClassName("rightColumnBig");
      if(col) {
        for(var i=0;i<col.length;i++) {
           if(col[i].style){ 
				col[i].style.display = 'none';
           }
        }
    }

   

    if (window.print) 
    { 
        if($('ChartingMain'))
        {
          if($('ChartImg').complete)
          {  
            window.print();
          }
          else
          {
              $('ChartImg').onload=function()
              {
                window.print();
              };
          
          }
            
        }
        else
        {  window.print();
         }   
    }
    
 }              
     

  //Get elements by class name  
  function getElementsByClassName(classname, node) 
  {

     if(!node)
     { node = document.getElementsByTagName("body")[0];

      }

     var a = [];

     var re = new RegExp('\\b' + classname + '\\b');

     if(node)
     {
         var els = node.getElementsByTagName("*");

         for(var i=0,j=els.length; i<j; i++)
         { 
           if(re.test(els[i].className))
           { a.push(els[i]);

           }

         }

     }

     return a;
  }
  

  if(getQueryValue('print')=='true')
  { 
      addLoadEvent(printThis); 
   }
 



//Check Numeric Values
function chkNumeric(objName)
{
	var checkOK = "0123456789. ";
	checkOK=checkOK;
	var checkStr = objName;
	var allValid = true;
	var decPoints = 0;
	var allNum = "";

    var counter=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 (ch == '.' )
		{
		 counter++;
		}
	}
	if(counter>1)
	{
	allValid = false;
	}
	if (!allValid)
	{	
		//alertsay = "Please enter only numeric values"
		//alertsay = alertsay +" in the "+ checkStr.name + " field."
		//alert(alertsay);
		return (false);
	}
}

function chkNumericMinus(objName)
{
	var checkOK = "0123456789.- ";	
	checkOK=checkOK;
	var checkStr = objName;
	var allValid = true;
	var decPoints = 0;
	var allNum = "";
   


   var counter=0;
    var counter1=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 (ch == '-')
		{
		counter++;
		}
		if (ch == '.'  )
		{
		counter1++;
		}
	}
	if(counter>1)
	{
	allValid = false;
	}
	if(counter1>1)
	{
	allValid = false;
	}
	if (!allValid)
	{	
		alertsay = "Please enter only numeric values"
		//alertsay = alertsay +" in the "+ checkStr.name + " field."
		alert(alertsay);
		return (false);
	}
}


//Check Numeric Values
function chkNumericPercent(objName)
{
	var checkOK = "0123456789.% ";
	checkOK=checkOK;
	var checkStr = objName;
	var allValid = true;
	var decPoints = 0;
	var allNum = "";
    var counter=0;
       var counter1=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 (ch == '%')
		{
		counter++;
		}
		if(ch == '.')
		{
		counter1++;
		}
	}
	if(counter>1)
	{
	allValid = false;
	}
	if(counter1>1)
	{
	allValid = false;
	}
	if (!allValid)
	{	
		alertsay = "Please enter only numeric values"
		//alertsay = alertsay +" in the "+ checkStr.name + " field."
		alert(alertsay);
		return (false);
	}
}

//Loading Shortlisted Values.
 function GetShortlistedItems()
 {
	var shortListedItems= new Array();
	var value = GetCookie("shortlisted");
	var cookieType = Mode;
	if($("NoOfShortListedItems")!=null)
	{
		if(value!=""){
		shortListedItems=value.split(',');		
		$("NoOfShortListedItems").innerHTML="("+shortListedItems.length+")";		
		}else{
		$("NoOfShortListedItems").innerHTML="(0)";	
		}
	}
	
 }
 
	
// Function will be triggred when any changes happened to the User Controls.
// Controls include Sector analysis, Top Risers and Fallers, Top Rated Fund and Sector Correlation
function onControlChange(ctrlName, universeCode, durationCode, previousUniverse, sortOrder, ddID)	{

		var eleFilterCode = $("hdn" + ctrlName + "FilterCode");
		var elePreviousUniv = $("hdn" + ctrlName + "PreviousUniverse");
		var eleUnivCode = $("hdn" + ctrlName + "UniverseCode");
		var eleDurationCode = $("hdn" + ctrlName + "DurationCode");
		var eleScroll = $("hdn" + ctrlName + "Scroll");
		var eleSortOrder = $("hdn" + ctrlName + "SortOrder");
		var eleYearCode = $("hdn" + ctrlName + "YearCode");		
		var eleCode = $("hdn" + ctrlName + "Code");	
		
		if(ctrlName!='SA') { 
		   if($(ddID) != null) {
			  eleFilterCode.value = $(ddID).value;		
		   }
		}
		else {
		   eleFilterCode.value = "";
		}
		if(ctrlName=='FM')
		{
		 eleCode.value=universeCode;
		}
		if(elePreviousUniv) {
			elePreviousUniv.value = previousUniverse;
		}
		
		if(eleUnivCode) {
			eleUnivCode.value = universeCode;
		}
		
		if(eleDurationCode) {
			eleDurationCode.value = durationCode;
		}
		
		if(eleScroll) {
			eleScroll.value = "1";			
		}	
		if(ctrlName=='SQ') { 	
		if(eleYearCode)
		{
		eleYearCode.value = durationCode;
		}
		}
		if(ctrlName!='TRF')	{
			if(eleSortOrder) 
			   eleSortOrder.value = sortOrder;		
		}
		var url = RemoveQueryString("ctr",document.URL)
		if(url.indexOf('?') > 0) {
			url += '&ctr='+ctrlName;
		}
		else {
			url += '?ctr='+ctrlName;
		}
		document.forms[0].action = url;
		document.forms[0].submit();
}

function RemoveQueryString(inpQueryStr,docUrl) {
	var index	 = docUrl.indexOf('?');
	var queryStr = (index != -1) ? docUrl.substring(docUrl.indexOf('?')+1) : '';
	var queryArr = queryStr.split('&');
	
	var url = docUrl.substring(0, (index == -1) ? docUrl.length : index);
	for(var i=0; i<queryArr.length; i++) {
		var qryParam = queryArr[i].split('=');
		if (qryParam[0] != inpQueryStr && qryParam[0] != '') {
			url += (url.indexOf('?') > 0) ? '&' + queryArr[i] : '?'+queryArr[i];
		}
	}
	return url;
}

/* * * * * * * * * Script for the page ShortList.ascx starts here * * * * * * * * */
var typeCodes = "";
var typeCodesNew = "";

// Function to clear all
function clearAll() {
	if($("emptyBasket")!=null && $("basketList")!=null ){
	$("emptyBasket").style.display = "block";
	$("basketList").style.display = "none";
	}
	var typecodes = GetCookie("shortlisted");
	DeHighlightRows(typecodes);
	DeleteCookie("shortlisted");
	DeleteCookie("TN_RetainSelected");
	GetShortlistedItems();
	return false;
}

//Function DeleteShortList
function delFromShortList(rowId, typecode) {
	removeRow(rowId, typecode);
	DeleteFromShortlist(typecode, "shortlisted");
	var valueNew = GetCookie("shortlisted");
		  GetShortlistedItems();
	DeleteFromShortlist(typecode, "TN_RetainSelected");
	
} 

//function to select all or deselect all
function selectChkbox(value) {
	var element = document.getElementsByName("ckShortList");
	var length = element.length;
	var selected = "";
	var spliter = "";
	
	for(var i=0; i < length; i++) {
		
		if(element[i].id != "ckShortList")
		{
			element[i].checked = value;
			selected += spliter + element[i].id;
			spliter = ",";
		}
	}
	
	if(value) {
		SetCookie("TN_RetainSelected", selected);
	} else {
		SetCookie("TN_RetainSelected", "");
	}
	return false;
}

// Function to remove row
function removeRow(rowId, typecode) {
	var elements = $("tableShortList");
	var len = elements.rows.length;
	var fundCount = 1;
	var unitCount = 0;
	
	for(var i = 0; i < len; i++) {
		
		currRow = elements.rows[i];
		
		if( currRow.id == rowId) 
		{
			currRow.style.display = "none";
			
			if(currRow.cells[1].id == "ckShortList" )
			{
				currCell = currRow.cells[1];
				checkBox =   currCell.getElementsByTagName("INPUT"); 
				var checkBoxId = checkBox[0].id;
				DeleteFromShortlist(checkBoxId, "TN_RetainSelected");
				DeleteFromShortlist(checkBoxId, "shortlisted");
				var valueNew = GetCookie("shortlisted");
				GetShortlistedItems();
				
			}
			
			
		}
		else if(currRow.cells[0].id == "fundCount" && currRow.style.display != "none" ) 
		{
			currRow.cells[0].innerHTML = fundCount + ".";
			fundCount++;
		} 
		else if(currRow.cells[1].id == "ckShortList"  && currRow.style.display != "none" ) 
		{
			unitCount++;	

		}
	}

	if(fundCount == 1) {
		clearAll();
	} else {
	
		var varUnit = (unitCount == 1)?"unit":"units";
		var varFund = (fundCount == 2)?"fund":"funds";
		$("showCount").innerHTML = "Showing " + unitCount +" " + varUnit + " of " + (fundCount - 1) + " "+ varFund;
	}
}

// Function for Next Page. 
	function showNextHome(page, Max, Min, title, parameters)
	{
		
		 typeCodes = GetCookie("TN_RetainSelected");
		 if(typeCodes=='')
		 {
		  typeCodes = GetCookie("shortlisted");
		 }
		 typeCodeArray=typeCodes.split(',');

		 if(typeCodeArray.length>=Min && typeCodeArray[0]!="")
		 {
			if((typeCodeArray.length>Max))
			{
				alert("You cant carry more than "+ Max +" values to "+ title);
			}
			else
			{
				window.location = page + "?typeCode=" + typeCodes + parameters;
			}
		 }
		 else
		 {
			if(title=="Multiplot" && Min<=1)
			{
			   window.location = page + "?typeCode=NUKX";
			}
			else
			{
			   //alert('No Funds in Basket. To add funds in Basket using "Green Plus Icon" wherever you see it next to a fund.');
			   alert('There are no funds in your basket. To add funds to your basket use the "Green Plus Icon" wherever you see it next to a fund.');
			}
		 }
	}
	
// Function for Next Page. 
function showNext(page, Max, Min, title, parameters) {

	typeCodes = shortList();
	var codes = GetCookie("shortlisted");
	var userId=GetCookie("TN_UserId");
	if(codes=='')typeCodes='';
	if(title=='DirectPortfolio')
	{
	typeCodes=codes;
	}
	if(codes == "" && title=='Portfolio' && userId=="")
	{	    
	    window.location ='/Tools/Portfolio/PortfolioLogin.aspx';
	}
	else if(codes != "" || title =="Multiplot") {	
		if(minValidation(Min)) {
			if(!maxValidate(Max)) {
				alert("You cant carry more than " + Max + " values to " + title);
			}
			window.location = page + "?typeCode=" + typeCodesNew + parameters;
		}
		else 
		{
			if(Min != 0)
			{			
				alert("You need atleast " + Min + " funds to see " + title);
			}
			else
			{
				window.location = page;
			}
		}
	} else {	
		//alert('No Funds in Basket. To add funds in Basket using "Green Plus Icon" wherever you see it next to a fund.');
		alert('There are no funds in your basket. To add funds to your basket use the "Green Plus Icon" wherever you see it next to a fund.');
	}
}

// Function for maxmum count validation
function maxValidate(count) {
	var typeCode = typeCodes.split(",");
	var len = typeCode.length;
	typeCodesNew  = "";
	var spliter = "";
	if(len > count) {
		for(var i = 0; i < count; i++) {
			typeCodesNew += spliter + typeCode[i];
			spliter = ",";
		}
		return false;
	} else {
		typeCodesNew = typeCode;
		return true;
	}
}

// Function for Minimum validation
function minValidation(count) {

	var typeCode = typeCodes.split(",");
	var len = typeCode.length;
	if(len < count || typeCodes == "") {
		return false;
	}
	
	return true;
}

// Getting the Selected Checkbox in ',' Separated Pair.
function shortList() {
	var element = document.getElementsByName("ckShortList");
	var typeCodes = "";
	var spliter = "";
	var len = element.length;
	for(var i=0; i< len; i++) {
		if(element[i].checked) {
			typeCodes += spliter + element[i].id;
			spliter = ",";
		}
	}
//	if(typeCodes=='' && element.length==0)
//	{
//	 typeCodes=GetCookie("shortlisted");   
//	}
	return typeCodes;
}

// Function to stored the selected checkbox values
// To retain.
function retainSelected(checked, typeCode) {
	var value = GetCookie("TN_RetainSelected");
	//if(value=='')value = GetCookie("shortlisted");
	var spliter =((value != "")?",":"");

	if(checked == true) {
		value +=  spliter + typeCode;
	} else {
		spliter = "";
		var typeCodes = new Array();
		typeCodes = value.split(",");
		var newCodes = "";
		for(var i = 0; i < typeCodes.length; i++) {
			if(typeCodes[i] != typeCode) {
				newCodes  +=  spliter + typeCodes[i];
				spliter = ",";
			}
		}
		value = newCodes;
	}

	SetCookie("TN_RetainSelected", value);
}

function Login()
{
	var userId=GetCookie("TN_UserId");
	if(userId == "") {			
		document.masterForm.action="/Tools/Portfolio/PortfolioLogin.aspx";
		document.masterForm.submit();
	}else{	
		document.masterForm.action="/Tools/Portfolio/PortfolioLogin.aspx?ch_logon=1";
		document.masterForm.submit();
	}
}

/* * * * * * * * * Script for the page ShortList.ascx ends here * * * * * * * * */

/* * * * * * * * * Script for User Pop-up starts here * * * * * * * * */

function setUser(selectedUT, page) {
	UpdateUserCookieByIPFn(selectedUT);
   SetCookie("invtype_client", selectedUT, 365);
	SetCookie("invtype", selectedUT, 365);
	$("invtype").value = selectedUT;
	closeInvestorSelector();
}

function UpdateUserCookieByIPFn(cookieVal)
{
	UpdateUserCookieByIPinDB('','invtype',cookieVal);
}

function closeInvestorSelector() {
	$("userTypePopUp").style.visibility = "hidden";
	$("investorSelectorIFrame").style.visibility = "hidden";
	return void(0);
}

function setTopPosition() {
	var elementTop = document.documentElement.scrollTop + (document.documentElement.clientHeight / 4);
	var elementLeft = document.documentElement.scrollLeft + (document.documentElement.clientWidth / 4) - 40;

	if (navigator.appName.indexOf("Microsoft") == -1) {
		$("userTypePopUp").style.top = elementTop + "px";
		$("investorSelectorIFrame").style.top = elementTop + "px";
		
		$("userTypePopUp").style.left = elementLeft + "px";
		$("investorSelectorIFrame").style.left = elementLeft + "px";
	} else {
		$("userTypePopUp").style.top = elementTop;
		$("investorSelectorIFrame").style.top = elementTop;
		
		$("userTypePopUp").style.left = elementLeft;
		$("investorSelectorIFrame").style.left = elementLeft;
	}
	
	if($("userTypePopUp").style.visibility == "visible") {
		setTimeout("setTopPosition()", 10);
	}
}

/* * * * * * * * * Script for User Pop-up ends here * * * * * * * * */

    
    // Customized go to page function
	function GoToPage(ctrlId, pageNo)
	{
		if($(ctrlId+"_pageNo"))
		{
			$(ctrlId+"_pageNo").value = pageNo;
		}
		document.masterForm.submit();
	}
	
	// Customized table sort function
	function Sort(ctrlId, sortedColumn)
    {
		 var isSameColumn = 0;
		 var columnEleID = $(ctrlId+"_sortedColumn");
	    if(columnEleID)
	    {
			 if(columnEleID.value == sortedColumn)
				isSameColumn=1;
		    columnEleID.value = sortedColumn;
	    }
	    var element = $(ctrlId+"_sortedDirection");
	    if(element)
	    {
			 var oppValue = (element.value.toUpperCase() == "ASC") ? "Desc" : "Asc";
		    element.value = (isSameColumn==1) ? oppValue : element.value;
	    }
	    //GoToPage(ctrlId,1);
	    SubmitControl(ctrlId)
    }
    
    function Sort(ctrlId, sortedColumn, defaultSortDirection)
    {
		 var isSameColumn = 0;
		 var columnEleID = $(ctrlId+"_sortedColumn");
	    if(columnEleID)
	    {
			 if(columnEleID.value == sortedColumn)
				isSameColumn=1;
		    columnEleID.value = sortedColumn;
	    }
	    var element = $(ctrlId+"_sortedDirection");
	    if(element)
	    {
			 var oppValue = (element.value.toUpperCase() == "ASC") ? "Desc" : "Asc";
			 defaultSortDirection = (typeof(defaultSortDirection)=='undefined') ? element.value : defaultSortDirection;
		    element.value = (isSameColumn==1) ? oppValue : defaultSortDirection;
	    }
	    //GoToPage(ctrlId,1);
	    SubmitControl(ctrlId)
    }
	
	// Filter submit
	function SubmitControl(ctrlId)
	{
		var index	 = document.URL.indexOf('?');
		var queryStr = (index != -1) ? document.URL.substring(document.URL.indexOf('?')+1) : '';
		var queryArr = queryStr.split("&");
		var url = document.URL.substring(0, (index == -1) ? document.URL.length : index);
		for(var i=0; i<queryArr.length; i++)
		{
			var qryParam = queryArr[i].split("=");
			var selectCtrls = $(ctrlId+"_selectCtrls");
			if(selectCtrls && qryParam[0] != ctrlId+"_sortedColumn" && qryParam[0] != ctrlId+"_sortedDirection" && qryParam[0] != "AddnFlt" && qryParam[0] != "Pf_Geoarea")
			{
				var pageCtrl = ctrlId+"_pageNo";
				if(selectCtrls.value.indexOf(qryParam[0]) < 0 && qryParam[0].toUpperCase() != pageCtrl.toUpperCase())
				{
					url += (url.indexOf("?") >= 0) ? "&" + queryArr[i] : "?"+queryArr[i];
				}
			}
			if(qryParam[0] == "AddnFlt")
			{
				var addnFilterQry = '';
				var addnQuery = qryParam[1].split("+AND+")
				for(var j=0;j<addnQuery.length;j++)
				{
					if( (addnQuery[j].indexOf('Fund.AssetClass')<0 && addnQuery[j].indexOf('Fund.FundInvestmentFocusList.InvestmentFocus')<0) )
					{
						addnFilterQry = (addnFilterQry.length > 0) ? '+AND+'+addnQuery[j] : addnQuery[j];
					}
				}
				url += (url.indexOf("?") >= 0) ? "&AddnFlt="+addnFilterQry : "?AddnFlt="+addnFilterQry;
			}
		}
		//$(ctrlId+"_pageNo").value=1;
		var selectFlt;
		var filters = $(ctrlId+'_selectCtrls');
		if(filters)
		{ 
			selectFlt = filters.value.split(',');
			for(var i=0;i<selectFlt.length;i++)
			{
				var selectCtrl = $(selectFlt[i]);
				if(selectCtrl && selectCtrl.value != "")
				{
					var textvalue = selectCtrl.id+"="+selectCtrl.value;
					url += (url.indexOf("?") >= 0) ? "&" + textvalue : "?"+textvalue;
				}
			}
		}
		var sort = $(ctrlId+'_sortedColumn')
		if(sort)
		{
			var textvalue = sort.id+"="+sort.value;
			url += (url.indexOf("?") >= 0) ? "&" + textvalue : "?"+textvalue;
		}
		sort = $(ctrlId+'_sortedDirection')
		if(sort)
		{
			var textvalue = sort.id+"="+sort.value;
			url += (url.indexOf("?") >= 0) ? "&" + textvalue : "?"+textvalue;
		}
		//window.location = url;
		
		//Code add for take hidden field values while submit page instead of window.location
        document.masterForm.action = url;
        document.masterForm.submit();
	}

	
   //change tab for factsheets	
   function ChangeTab(tab, page, tabCode)
   {
       $('pageno').value = page;
       $('CurrTab').value = tab;
       $('tabCode').value = tabCode;
       
       document.masterForm.submit();
   } 
   
    
    //Top Search dropdown change event
    function LoadGroupList() 
    {
      var universe = $("universe").options[$("universe").selectedIndex].value;
      
           
      document.forms[0].submit();
     }
	
    //Top Search goto Group Factsheet page
    function postGroup() 
    {
        var universe = $("universe").options[$("universe").selectedIndex].value;
        var group = $("group").options[$("group").selectedIndex].value;
        var URL = "/Factsheets/GroupFactSheet.aspx?managerCode="+group + "&univ=" + universe;
      
        document.location.href =URL;
        
    }
    
    //LoginControl in menubar
    
    
    
function AddDynamicInput()
{
	if($('divPass').innerHTML=="Password" && $('divUser').innerHTML=="Username/email")
	{

	$('ctl00_MenubarHome_beforeLoginRowhidden').style.display='block';
	$('ctl00_MenubarHome_beforeLoginRow1').style.display='none';
	   if(document.all)
	   {
	   $('txtUser').className='menuinputIE';
	   $('txtPass').className='menuinputIE';
	   if(window.navigator.userAgent.indexOf("MSIE 6.0")>=0)
	   {
	   currencyMenu.style.width='269px';
	   currencyMenu.style.height='56px';
	   currencyMenu.style.overflow='hidden';
	   }
	  
	   }
	   $('txtUser').focus();
	   
	}
}

function checkkey(txt,e)
{
    if(txt.id=="txtUser" || txt.id=="txtPass")
    {
    if(e.keyCode==13)
    {
      if(LoginCheckMenu())
       return true;
       else
       return false;
    }
    }
    else
    {
    return false;
    }
}
function CheckEmailAscii(objEmail,eMailEvent)
{
    if(objEmail.id=="txtForgotEmail")
    {	
	    if(eMailEvent.keyCode==13)
	    {			
		    CheckEmailEmpty();		
	    }
		    return true;		
    }
    return false;
}
function CheckEmailEmpty()
{	
	var emailId=$('txtForgotEmail');
	   if(emailId.value==null || emailId.value=="")
		{
			alert('Please Enter your Email ID(username)');
			emailId.focus();
			return false; 
		}  
		else if (echeck(emailId.value)==false){
			emailId.value="";
			emailId.focus();
			return false
		} 
		else
		{		
		document.masterForm.action='/Tools/Portfolio/ForgotPassword.aspx?flag=forgot';
		document.masterForm.submit(); 	 	
		}
}
//Script for forgotten Details
function checkForgottemEmail(objEmail,eMailEvent)
{	
	if(objEmail.id=="txtForgotEmail")
	{	
		if(eMailEvent.keyCode==13)
		{			
			sendEmail();		
		}			
	}
}
function sendEmail()
{	
	var emailId=$('txtForgotEmail');
	if(emailId.value==null || emailId.value=="")
		{
			alert('Please Enter your Email ID');
			emailId.focus();
			return false; 
		}   
		if (echeck(emailId.value)==false){
			emailId.value="";
			emailId.focus();
			return false
		}
		else
		{		
		document.masterForm.action='/Tools/Portfolio/ForgotPassword.aspx?flag=forgot';
		document.forms[0].submit(); 		
		}
}
//End of Script
function validateEmail(field)
{
var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
str = field.value;
if(str!=null){
       if(SiteCode=='TNUK')
       {
         return true;
       } 
      else if(str.match(emailRegEx))
       {
         return true;
       }
      else
       {
       alert('Please enter a valid email address.');
       field.focus();
       return false;
       }
  }
}

function LoginCheckMenu()
{

if($('ctl00_MenubarHome_beforeLoginRowhidden').style.display=='block')
{
var user=$('txtUser');
var pass=$('txtPass');
if(user.value!="")
{
   if(validateEmail(user))
   {
    if(pass.value!="")
    {
    $('boolLogin').value="login";
    document.masterForm.submit();
    }
    else
    {
     pass.focus();
     alert("Enter password");
     return false;
    }
   }
}
else
{
alert("Enter UserName");
user.focus();
return false;
}
}
//else
//{
//alert("Enter your email");
//return false;
//}

}
function LogoutMenu()
{
$('boolLogin').value="logout";
document.masterForm.submit();
}

function findiframeposition()
{
	if(window.navigator.userAgent.indexOf("MSIE 6.0")>=0)
	{
	  var position=getPosition("setperf");
	   //alert(position.x);
	   var st = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
	   var st1 = Math.max(document.body.scrollLeft,document.documentElement.scrollLeft);
	   if(position.x<927)
	   {
			if($("loginSubmenu"))
			{
				loginSubmenu.style.left=position.x-6;
				loginSubmenu.style.top=position.y+29;
				$('CurrencyMenuFrame').style.left=position.x-6;
			}
	   }
	   else
	   {
			if($("loginSubmenu"))
			{
				loginSubmenu.style.left='922px';
				$('CurrencyMenuFrame').style.left='922px';
				loginSubmenu.style.top='216px';
			}
	   }
	}
} 
function changestyle()
{

	var logged=$('boolLogin').value;
	var hidCount=0;
	var browsertype=window.navigator.userAgent;
	if(window.isOpera)
	{
	  $('txtUser').style.marginLeft='7px';
	  $('txtUser').style.border='0px';
	  $('txtPass').style.marginLeft='7px';
	  $('txtPass').style.border='0px';
	}
	var pos=getPosition("setperf"); 
	var top=document.body.clientTop?document.body.clientTop:0;
	top=top+parseInt(pos.y)+18;
	 if(browsertype.indexOf("Safari")>=0)
	 {
	 $('tdEmailL').style.width='70px';
	 $('tdEmailL').style.border='0px';
	 
	 }
      if(browsertype.indexOf("MSIE 6.0")>=0){
      currencyMenu.style.width="253px";
      $('subMenu').style.width="680px";}
       if(logged=="login")
          {
			if(document.all || browsertype.indexOf("Safari")>=0 )
			{
			   if($('loginSubmenuList'))
			   {
					var len=$('loginSubmenuList').children.length;
					for(i=1;i<=len;i++)
					{
					 var listid="listdynamic"+i;
					 var listElement = $(listid);
					 if(listElement)
						listElement.className=listElement.className+"IE";
					}
			   }

			  if(browsertype.indexOf("MSIE 7.0")>=0)
			  {
				 if($('CurrencyMenuFrame'))
				 {
					 if(emailSiteCode!="TNUK")
					 {
					  $('mnuCurrentCurrency').style.paddingBottom='2px';
					 }
					 var position=getPosition("CurrencyMenuFrame");
					 $('CurrencyMenuFrame').style.top=position.y-4;
					 $('CurrencyMenuFrame').style.left=position.x+8;
			    }
			  }     
			   if(browsertype.indexOf("MSIE 6.0")>=0)
			   {   
			   var position=getPosition("CurrencyMenuFrame");
			   
			   if($("loginSubmenu"))
				{
					loginSubmenu.style.left=position.x;
					loginSubmenu.style.top=position.y+8;
	//			   if(emailSiteCode=="TNME")
	//			   {
	//			   loginSubmenu.style.left=position.x+20;
	//			   loginSubmenu.style.top=position.y+10;
					loginSubmenu.style.marginTop="-14px";
					loginSubmenu.style.marginLeft="3px";
	//			   }
					currencyMenu.style.width="253px";
					$('subMenu').style.width="680px";
					$('CurrencyMenuFrame').style.top=position.y;
					$('CurrencyMenuFrame').style.width="253px";
					loginSubmenu.style.width="187px";
					loginSubmenu.style.styleFloat="none";
					loginSubmenu.style.zIndex="99999";
					loginSubmenu.style.position="absolute";
					loginSubmenuList.style.marginRight="0px";
					loginSubmenuList.style.styleFloat="none";
			   }
			   for(i=1;i<=len;i++)
			   {
			    var listid="listdynamic"+i;
			    var listElement = $(listid);
			      if(listElement)
			       {
					listElement.style.marginLeft="-15px";
					listElement.style.width="160px";
				   }
			   }
			    
			   } 	
			}
			else
			{ 
			  
			  $('mnuCurrentCurrency').style.paddingBottom='2px'; 
			  if($('CurrencyMenuFrame'))
				$('CurrencyMenuFrame').style.top=top+19+"px";
			  
			}
         }
}
function CreateIframe()
{
         if(window.navigator.userAgent.indexOf("MSIE 6.0")>=0)
         {
            var objcurrencyMenu=$('currencyMenu');
			var ele = document.createElement('iframe');
			ele.tabIndex = '-1';
			ele.src = 'javascript:false;';
			objcurrencyMenu.appendChild(ele);
			ele.style.top="198px";
			ele.style.height="198px";
			ele.style.width="184px";
			ele.style.marginRight="100px";
			ele.style.left="922px";
			ele.style.position="absolute";
			ele.style.className='mainLoginDiv';
			}	
}
function RemoveIframe()
{  
   if(window.navigator.userAgent.indexOf("MSIE 6.0")>=0)
         {
        var objcurrencyMenu=$('currencyMenu');
        var layers = objcurrencyMenu.getElementsByTagName('iframe');
	     while(layers.length > 0)
	      {
		layers[0].parentNode.removeChild(layers[0]);
	      }
	     }
}

//End of login menu control


//Basket Box

function AddToWatchList(typecode)
{
		//var value = GetCookie(userId+"watch");	
		var count=$("NoOfWatchlistItems");		
        var isCodeRemoved = false;       
		 if(WatchtypeCodes != "")
		 {
		  var farray = new Array();
		  farray = WatchtypeCodes.split(',');		  
        if(!IsStringFoundInArray(farray, typecode))
        {
            WatchtypeCodes += ","+typecode;      
        }
        else
        {
			DeleteFromShortlist(typecode, userValue+"watch");
			DeleteFromDB(typecode,WatchtypeCodes);
			//SetCookie(userId+"watch",WatchtypeCodes,123231);
			//DeleteFromShortlist(typecode, "TN_RetainSelected");			
			isCodeRemoved = true;
        }
    }
    else
    {
        WatchtypeCodes = typecode;    
    }
    if(!isCodeRemoved)
    {
		SetCookie(userValue+"watch", WatchtypeCodes, 123231);		
		AddWatchlistFundDisplay(userValue,univValue,typecode,SiteCode);
		count.innerHTML=parseInt(count.innerHTML)+1;
	    //retainSelectedVal(typecode);
    BasketPopup('visible',typecode,'Watchlist');	
    }
    else
    {	
        RemoveWatchlistFundDisplay(userValue,typecode,SiteCode);
        DeHighlightRows(typecode);        
        count.innerHTML=parseInt(count.innerHTML)-1;	
        if($('curPopup')!=null)
		{
			   var currentPopup=$('curPopup').value;
			  var basket= $('BasketPopup'+currentPopup)
			  if(basket!=null)
			  {
			   basket.style.visibility='hidden';
			   $("BasketPopupFrame").style.visibility='hidden';  
			  }	
		}
    }	
	HighLightSelectedRows();
}
	 
function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return  scrOfY ;
} 

function AddToPortfolio(typecode)
{
	   //var value = GetCookie(userId+"portfolio"); 
	  // value=PorttypeCodes;
	   var count=$("NoOfPortfolioItems");		    
       var isCodeRemoved = false;     
	   if(PorttypeCodes != "")
	   {
        var farray = new Array();
        farray = PorttypeCodes.split(',');     
		
        if(!IsStringFoundInArray(farray, typecode))
        {
            PorttypeCodes += ","+typecode;            	            
           
        }
        else
        {    	
			DeleteFromShortlist(typecode, userValue+"portfolio");	
			DeleteFromDB(typecode,PorttypeCodes);
			//SetCookie(userId+"portfolio",PorttypeCodes,123231);
			//DeleteFromShortlist(typecode, userId+"portfolio");
			isCodeRemoved = true;
        }
    }
    else
    {				
        PorttypeCodes = typecode;                      
    }
    if(!isCodeRemoved)
    {	  
      AddPortfolioFundDisplay(pId,userValue,univValue,typecode);
	  SetCookie(userValue+"portfolio", PorttypeCodes, 123231);		 
	  count.innerHTML=parseInt(count.innerHTML)+1;
	  BasketPopup('visible',typecode,'Portfolio',portNameLong);	    
    }
    else
    {   
      RemovePortfolioFundDisplay(pId,userValue,typecode); 
	  DeHighlightRows(typecode);
	  count.innerHTML=parseInt(count.innerHTML)-1;
	   if($('curPopup')!=null)
	   {
	       var currentPopup=$('curPopup').value;
		   var basket= $('BasketPopup'+currentPopup)
		   if(basket!=null)
		   {
		    basket.style.visibility='hidden';
		    $("BasketPopupFrame").style.visibility='hidden';  
	    }
		}
    }
	HighLightSelectedRows();
}
	 

function clearPortfolio()
{	
   var typecodes = GetCookie(userValue+"portfolio");  
   DeHighlightRows(typecodes);
   DeleteCookie(userValue+"portfolio");	
   GetPortfolioItems(userValue+'portfolio');	
}
	 
	
function clearWatchlist()
 {	   
	var typecodes = GetCookie(userValue+"watch");
	var ele=$("WatchlistbasketBox");
    ele.style.display="none";
	DeHighlightRows(typecodes);
	DeleteCookie(userValue+"watch");	
	GetPortfolioItems(userValue+'watch');				
 }
	 
	 //Loading Shortlisted Values.
 function GetPortfolioItems(cookie)
 {
	var shortListedItems= new Array();
	var value = GetCookie(cookie);	
	if(cookie==userValue+"watch"){		
      $("NoOfWatchlistItems").innerHTML="(0)";	
    }else{
     $("NoOfPortfolioItems").innerHTML="(0)";	
    }
 }
 
	 // Function for Next Page. 
function showNextPortfolio(page,cookie,Max, Min, title, parameters)
{

	//typeCodes = shortList();
	typeCodes = GetCookie(userId+cookie);		
	if(typeCodes != "" || title =="Multiplot") {	
		 if(minValidation(Min)) {
			if(!maxValidate(Max)) {
				alert("You cant carry more than " + Max + " values to " + title);
			}
			//if(title!='DirectPortfolio')
			//{			
			//DeleteCookie(cookie);
				
		    SetCookie("TN_Mode", "General", 123231);
		    SetCookie(userId+cookie, "", 123231);
		     
			document.masterForm.action = page + "?typeCode=" + typeCodes + parameters;
			document.masterForm.submit();
		}
		else 
		{
			if(Min != 0)
			{			
				alert("You need atleast " + Min + " funds to see " + title);
			}
			else
			{
				window.location = page;
			}
		}
	} else {
		//alert('No Funds in Basket. To add funds in Basket using "Green Plus Icon" wherever you see it next to a fund.');
		alert('There are no funds in your basket. To add funds to your basket use the "Green Plus Icon" wherever you see it next to a fund.');
	}
}

function clearBasket()
{
	   clearAll();
	   return;
}

//function OpenMode()
//{
//  var wnd = $("ModebasketDiv");		  
//  var postion=getPosition("BasketHead");	
//  wnd.style.position="absolute";
//  wnd.style.display = "block";
//  wnd.style.visibility = "visible";	  	  
//  //clearTimeout(CTO);
////  CTO = setTimeout("Hide()",5000);	  
//  var left=postion.x+133+"px";
//  wnd.style.left =left;
//  wnd.style.top =postion.y+13+"px";	   			
//  if($("hdnmode")!=null)
//  {	
//	var id=$("hdnmode").value;	
//	var rdoMode = $(id);
//	if(rdoMode)
//	  rdoMode.checked=true;
//  }  
//}
//function ModeShade(ctl)
//{
//	ctl.style.background="#a7c7e7";
//}

//// Remove Shading while Cursor Out for mode window.
//function ModeReShade(ctl)
//{
//	ctl.style.background="";
//}

function AutoHide(e)
{

                var logged=$('boolLogin').value;
                if(logged=="login")
                {
                 
					if(document.all)
					{
					   if(event.srcElement.tagName!="HTML")
					   {
					   if(event.srcElement.parentElement!=null){
						var tagn=event.srcElement.parentElement.id;
						      
							  if(event.srcElement.id=="setperf" || event.srcElement.id=="loginSubmenu" ||tagn=="loginSubmenu" || tagn=="loginSubmenuList" ||tagn=="listdynamic1" ||tagn=="listdynamic2" ||tagn=="listdynamic3" 
							   || tagn=="listdynamic4" || tagn=="listdynamic5" ||tagn=="rdofundCurrency" ||tagn=="rdopoundCurrency" ||tagn=="rdoeuroCurrency" ||tagn=="rdodollarCurrency" ||tagn=="rdoHKDCurrency" ||tagn=="rdoSGDCurrency" ||tagn=="rdorupeesCurrency"
							  ||event.srcElement.id=="rdoHKDollar"||event.srcElement.id=="rdoSGDollar" ||event.srcElement.id=="rdoLocal" ||event.srcElement.id=="rdoLocal" ||event.srcElement.id=="rdoDollar" || event.srcElement.id=="rdoEuro"||event.srcElement.id=="rdoPound" ||event.srcElement.id=="rdoRupees" )
								{
								 
								  $('loginSubmenu').style.display='block';$('CurrencyMenuFrame').style.visibility='visible';
								 findiframeposition();
								}
								else
								{
								
								try
								{
								$('loginSubmenu').style.display='none';$('CurrencyMenuFrame').style.visibility='hidden';
								}
								catch(e)
								{
								}
								}
							}
						}
					}
				}				
// var postion=getPosition("userLeftBox");	
// var left=postion.x+125;
// 
// var top=postion.y-20;
// var x=0;
// var y=0;
// var y1=getScrollXY();	 
// if (IE) { // grab the x-y pos.s if browser is IE
//   x = event.clientX;
//   y = event.clientY+y1;
// }
// else {  // grab the x-y pos.s if browser is NS
//   x = e.pageX;
//   y = e.pageY;
// }
// 

// if(x<(left) ||  x>(left+140) ) 
// {
// Hide();
// }
// if( y<(top) || y>(top+110))
// {
// Hide();
// }
}

function ChangeModeBasket()
{   
	 var element=document.getElementsByName("BMode");
	 var value="";
	 for(var i=0;i<element.length;i++){   
	   if(element[i].checked){
		  value=element[i].value;   		  
		  $("hdnmode").value=element[i].id;		  		 
	   }
    }     
	 SetCookie("TN_Mode", value, 123231);
	 document.masterForm.submit();
}
	 
function CloseMode()
{
 SetCookie("TN_Mode", "General");
 document.masterForm.submit();
}	 

function Hide()
{
	 var wnds = $("ModebasketDiv");	 
	 wnds.style.visibility = "hidden";
}	


function DiplayBasket()
{
   var mode = GetCookie("TN_Mode");
   if(mode == "")
   {
	SetCookie("TN_Mode", "General", 123231);
   }
	if($("NoOfShortListedItems")!=null){		
        var value = GetCookie("shortlisted");
		var farray = new Array();
		farray = value.split(',');	
		if(value!="")
		{	
		$("NoOfShortListedItems").innerHTML="("+farray.length+")";     
		}else{
		$("NoOfShortListedItems").innerHTML="(0)";  
		}
	 }      
    
}

//Portfolio

function MatrixChange()
{
	$("hdnRow").value=$("Row").value;
	$("hdnColumn").value=$("Column").value;		 
	document.masterForm.submit();		 
}		 
function deleteReport(portID,delReport,delFrequency)
{
	$("delportID").value=portID;
	$("delReport").value=delReport;
	$("delFrequency").value=delFrequency;
	document.masterForm.submit(); 
}	
function onChangeFund(page)
{

var elementValue=document.getElementsByName("value");
var element=$("Currency");
var elementFund=document.getElementsByName("selectFunds");
var elementAlert=document.getElementsByName("selectAlerts");
var elementprice=document.getElementsByName("pricevalue");

var values="";
var valuepercent="";
var valuesPrice="";
var alerts="";
var typeCodes="";
var Currency;
for(var i=0;i<elementValue.length;i++)
{
	if (chkNumericMinus(elementValue[i]) == false || elementValue[i].value=="" )
	{
		 return false;
	}
	else{
		 if(i==(elementValue.length-1))
		 {
		 values+=elementValue[i].value;
		 }else{
		 values+=elementValue[i].value+",";
		 }
   }
}

for(var i=0;i<elementprice.length;i++)
{
   if (chkNumericMinus(elementprice[i]) == false || elementprice[i].value=="")
	{
		 return false;
	}
	else{
		 if(i==(elementprice.length-1))
		 {
		 valuesPrice+=elementprice[i].value;
		 }else{
		 valuesPrice+=elementprice[i].value+",";
		 }
   }
}


for(var i=0;i<elementFund.length;i++)
{
   if(i==(elementFund.length-1))
   {
   typeCodes+=elementFund[i].options[elementFund[i].selectedIndex].value;
   }else{
   typeCodes+=elementFund[i].options[elementFund[i].selectedIndex].value+",";
   }
}

for(var i=0;i<elementAlert.length;i++)
{
   if(i==(elementAlert.length-1))
   {
   alerts+=elementAlert[i].options[elementAlert[i].selectedIndex].value;
   }else{
   alerts+=elementAlert[i].options[elementAlert[i].selectedIndex].value+",";
   }
}
   $("alert").value=alerts;
   if(element)Currency=element.options[element.selectedIndex].value;
   $("values").value=values;
   $("pricevalues").value=valuesPrice;
   $("hdnCurrency").value=Currency;
   $("typecode").value=typeCodes;

   if(page=='add')
   {
   document.masterForm.action="portfoliosAlert.aspx?type=1"
   }
   else if(page=='addprice'){
   document.masterForm.action="portfoliosAlert.aspx?type=2"
   }
   document.masterForm.submit();
   }

function delFundsList(hdnDelete1)
{
  var confirmmessage = "Are you sure you want to delete?";
  var cancelmessage = "Action Cancelled";
  if (confirm(confirmmessage)) {
  $("hdnDelete").value=hdnDelete1;
  document.masterForm.submit(); 
  }
}

function delFundPriceList(hdnDelete)
{
  $("priceDelete").value=hdnDelete;
  document.masterForm.submit(); 
}

function onChangeValue()
{
  var valuePercent=document.getElementsByName("valuePercents");  
	if (chkNumericPercent(valuePercent[0]) == false)
	   {
		 return false;
	   }
	else{
		  var value=valuePercent[0].value.split("%");		  		  		  
		  var currentValue=$("CurrentValue").innerHTML.replace(',','');  
		  var condition=$("selectType");
		  var result=parseInt(+(parseFloat(value)* parseFloat(currentValue))/100);
				if(value!=""){  
		  if(condition.value=='>=')
		  {  
		  $("value").value=CORE((parseFloat(currentValue)+result),2);
		  }else{
		  $("value").value=CORE((parseFloat(currentValue)-result),2);
		  }		  
       }
     }
}
 
function onChangePriceValue()
{
  var valuePercent=document.getElementsByName("pricePercentValues");  
  var condition=document.getElementsByName("selectCondition");
  var pricevalue=document.getElementsByName("pricevalue");
 // var Totalvalue=document.getElementsByName("PriceTotalValue");
   
  for(var i=0;i<valuePercent.length;i++)
   {
	if (chkNumericPercent(valuePercent[i]) == false)
	   {
		 return false;
	   }
    else{ 
		  var value=valuePercent[i].value.split("%");
		  var currentValue= $("Curr"+i).innerHTML.replace(',','');    
		  var result=parseInt((parseFloat(value)* parseFloat(currentValue))/100);
		  if(value!="")
		  {  
		  if(condition[i].value=='>=')
		  {
		  pricevalue[i].value=CORE((parseFloat(currentValue)+result),2);
		  }else{  
			   pricevalue[i].value=CORE((parseFloat(currentValue)-result),2);
		  }
          }
        }
   }
} 
	 
function onChangeFundAlert(page)
{
var element=document.getElementsByName("selectFunds");
var elementAlert=document.getElementsByName("selectAlerts");
var elementValue=document.getElementsByName("value");
var typeCodes="";
var alerts="";
var values="";
   for(var i=0;i<element.length;i++)
   {
	   if(i==(element.length-1))
	   {
	   typeCodes+=element[i].options[element[i].selectedIndex].value;
	   }else{
	   typeCodes+=element[i].options[element[i].selectedIndex].value+",";
	   }
   }
   for(var i=0;i<elementAlert.length;i++)
   {
	  if(i==(elementAlert.length-1))
	  {
	  alerts+=elementAlert[i].options[elementAlert[i].selectedIndex].value;
	  }else{
	  alerts+=elementAlert[i].options[elementAlert[i].selectedIndex].value+",";
	  }
   }
   for(var i=0;i<elementValue.length;i++)
   {
   if (chkNumericMinus(elementValue[i]) == false || elementValue[i].value=="" )
	{
		 return false;
	}
	else{
	  if(i==(elementValue.length-1))
	  {
	  values+=elementValue[i].value;
	  }else{
	  values+=elementValue[i].value+",";
	  }
	  }
   }
   $("values").value=values;
   $("typecode").value=typeCodes;
   $("alert").value=alerts;
   if(page=='add')
   {
   document.masterForm.action="alerts.aspx?type=1"
   }
   document.masterForm.submit();
}

function delFundPriceListAlert(hdnDelete)
{
  $("priceDelete").value=hdnDelete;
  document.masterForm.submit(); 
}

function onChangePriceValueAlert()
{
  var valuePercent=document.getElementsByName("pricePercentValues");  
  var condition=document.getElementsByName("selectType");
  var pricevalue=document.getElementsByName("value");
  //var Totalvalue=document.getElementsByName("PriceTotalValue");
   
  for(var i=0;i<valuePercent.length;i++)
   {
	  if (chkNumericPercent(valuePercent[i]) == false)
	  {
	   return false;
	  }
	  else
	  { 
		var value=valuePercent[i].value.split("%");
		var currentValue=$("Curr"+i).innerHTML.replace(',','');    
		var result=((parseFloat(value)* parseFloat(currentValue))/100);  
		if(value!="")
		{
		  if(condition[i].value=='>=')
		  {
		  var target=parseFloat(currentValue)+result;
		  pricevalue[i].value=CORE(target,2);
		  }else{  
		  var target=parseFloat(currentValue)-result;
		  pricevalue[i].value=CORE(target,2);
		  }
	     }
	   }
    }
}
  
  function CORE(X, N) { // X to String with N decimal places
  var int = Math.floor(X), frc = ((X-int)+1.0) * Math.pow(10, N)
  frc = String(IntFrc(frc,N)) // Put chosen rounding algorithm here
  return (int + +(frc.charAt(0)=="2")) + '.' + frc.substring(1)
   }

function IntFrc(frc,CaseNo) { // often for X > -0.5e-N
  with (Math) switch (CaseNo) {
    case 0 : // Trunc
      return floor(frc)
    case 1 : // Round
      return round(frc)
    case 2 : // Alternate Round
      if (frc%1 >= 0.5) frc++ ; return frc | 0
    case 3 : // Simple Bankers'
      return frc%1 != 0.5 ? round(frc) : 2*round(frc/2)
    case 4 : // Better Bankers'
      return NearHalf(frc) ? 2*round(frc/2) : round(frc)
    case 5 : // Double-round
      if (NearHalf(frc)) frc = round(2*frc)/2 ; return round(frc)
    case 6 : // Ceil
      return ceil(frc)
    case 7 : // Statistical
      return (frc + random()) | 0
    default : return " TypeError" } }


  
function getPosition(elementId)
 {
   var element = $(elementId);
   var left = 0;
   var top = 0;
   var width = 0; 
   var height = 0;
     
   if (element != null)
   {
       // Try because sometimes errors on offsetParent after DOM changes.
       try
       {
            width= element.offsetWidth;
            height= element.offsetHeight;
            while (element.offsetParent)              {
               // While we haven't got the top element in the DOM hierarchy
               // Add the offsetLeft
               left += element.offsetLeft;
               // If my parent scrolls, then subtract the left scroll position
               if (element.offsetParent.scrollLeft) {left -= element.offsetParent.scrollLeft; }               
               // Add the offsetTop
               top += element.offsetTop;
               // If my parent scrolls, then subtract the top scroll position
               if (element.offsetParent.scrollTop) { top -= element.offsetParent.scrollTop; }
               // Grab
               element = element.offsetParent;
              }
       }

       catch (e)
       {
              // Do nothing
       }
	
	  // Add the top element left offset and the windows left scroll and subtract the body's client left position.
	 left += element.offsetLeft + document.body.scrollLeft - (document.body.clientLeft?document.body.clientLeft:0);



	 // Add the top element topoffset and the windows topscroll and subtract the body's client top position.

	 top += element.offsetTop + document.body.scrollTop - (document.body.clientTop?document.body.clientTop:0);
	 
	  }

   return {x:left, y:top , w:width , h:height};
 }
 
 
 // Function to load sectors based on universe and assetclass
function qsLoadSector(val)
{		
   var selUnivEleID = $("qsUniverseDD");
   var assetClassCtrl = $("qsAssetClassDD");
   
   // Skip this code when both the element doesn't exit
   if(assetClassCtrl && selUnivEleID)
   {
	  // Assigning values of the dropdown boxes to a local variable
	  var assetClass = assetClassCtrl.options[assetClassCtrl.selectedIndex].text;
	  var universe=selUnivEleID[selUnivEleID.selectedIndex].value;
	  var isSecRequired = universe.substring(universe.toString().indexOf(":")+1,universe.toString().length);
	  universe=universe.substring(0,universe.toString().indexOf(":"));
	  var sectorDDCtrl=$("qsSectorsDD");
	  
	  if(isSecRequired=="True")
	  {
		 // To Load Sectors in a local variable using Ajax Pro Method
		 var Sector=TrustnetX.Controls.QSearch.LoadSectorsByAssetClass(universe, assetClass);	  
		 Sector=Sector.value;		 
   	  
		 // Skip this code when this element doesn't exit	  
		 if(sectorDDCtrl)
		 {
			sectorDDCtrl.disabled=false;
			sectorDDCtrl.options.length=0;
			var optionElement=document.createElement("option");
			optionElement.text="All Sectors";
			optionElement.value="";
			sectorDDCtrl.options.add(optionElement);
   		 
			// Skip this code when Sector array is null
			if(Sector)
			{
			   // Loop to add all the Sectors in Sector Dropdown box
			   for(i=0;i<Sector.length;i++)
			   {
				  if(Sector[i]!=null) {
					 optionElement=document.createElement("option");
					 optionElement.text=Sector[i].SectorName;
					 optionElement.value=Sector[i].SectorClassCode;
					 sectorDDCtrl.options.add(optionElement);
				  }
			   }
			}
		 }
	  }
	  else
	  {
		 sectorDDCtrl.value="";
		 sectorDDCtrl.disabled=true;		 
	  }
	  
	  // To load managers based on universe
	  if(val=="univ")
	  {	  
		 qsLoadManangers(universe);
		 qsLoadDomiciles(universe);
	  }
   }
}   


// Function to load Managers based on the universe code
function qsLoadManangers(univ)
{
   var universe=univ;
   
   // Skip this code when this element doesn't exit   
   if($("qsManagerDD"))
   {
	  // To Load Manager in a local variable using Ajax Pro Method
	  var Manager=TrustnetX.Controls.QSearch.LoadManagersByUniverse(universe);
	  Manager=Manager.value;
	  
	  // If no manager loaded then skip
	  if(Manager!=null)
	  {		 
		 var selectmanagers=$("qsManagerDD");
		 selectmanagers.options.length=0;
		 var ele=document.createElement("option");
		 ele.text= "All Managers";
		 ele.value="";
		 selectmanagers.options.add(ele);
		 
		 // Loop to add all Managers in the Manager Dropdown box
		 for(i=0;i<Manager.length;i++)
		 {
			if(Manager[i]!=null){
			   var ele=document.createElement("option");
			   ele.text=Manager[i].ManagerName;
			   ele.value=Manager[i].ManagerCode;
			   selectmanagers.options.add(ele);
			}
		 }
	  } 
   }       
}


// Function to load Domicile based on the universe code
function qsLoadDomiciles(univ)
{
   var universe=univ;
   
   // Skip this code when this element doesn't exit   
   if($("qsDomicileDD"))
   {
	  // To Load Domicile in a local variable using Ajax Pro Method
	  var Domicile=TrustnetX.Controls.QSearch.LoadDomocilesByUniverse(universe);
	  Domicile=Domicile.value;
	  
	  // If no Domicile loaded then skip
	  if(Domicile!=null)
	  {		 
		 var selectdomicile=$("qsDomicileDD");
		 selectdomicile.options.length=0;
		 var ele=document.createElement("option");
		 ele.text= "All Domiciles";
		 ele.value="";
		 selectdomicile.options.add(ele);
		 
		 // Loop to add all Domicile in the Domicile Dropdown box
		 for(i=0;i<Domicile.length;i++)
		 {
			var ele=document.createElement("option");
			ele.text=Domicile[i].DomicileName;
			ele.value=Domicile[i].DomicileCode;
			selectdomicile.options.add(ele);
		 }
	  } 
   }       
}


// Function executes when Go button in the quick search is click
function qsGoButton_Click()
{
   // Assigning the elements in the local variable
   var selUnivEleID = $("qsUniverseDD");
   var selACEleID = $("qsAssetClassDD");
   var selSectorEleID = $("qsSectorsDD");
   var selDomicileEleID = $("qsDomicileDD");
   var selManagerEleID = $("qsManagerDD");
   
   
   // Skip this code when both the element doesn't exit
   if(selUnivEleID)
   {
	  // Extracting universe code from universe dropdown
	  var universe=selUnivEleID[selUnivEleID.selectedIndex].value;
	  universe=universe.substring(0,universe.toString().indexOf(":"));
	  
		var qsURL = "/Investments/Perf.aspx?univ=" + universe + "&";
		qsURL += UpdateQSQryStr("Pf_AssetClass",selACEleID[selACEleID.selectedIndex].value);
		qsURL += UpdateQSQryStr("Pf_Sector",selSectorEleID[selSectorEleID.selectedIndex].value);
		qsURL += UpdateQSQryStr("Pf_Domicile",selDomicileEleID[selDomicileEleID.selectedIndex].value);
		qsURL += UpdateQSQryStr("Pf_Manager",selManagerEleID[selManagerEleID.selectedIndex].value);
		qsURL = qsURL.substring(0,qsURL.toString().length-1);
	  
	   window.location = qsURL;
	  // Assigning the values of the dropdown box to the hidden variables 
	  /*$("Pf_AssetClass").value=selACEleID[selACEleID.selectedIndex].value;
	  $("Pf_Sector").value=selSectorEleID[selSectorEleID.selectedIndex].value;
	  $("Pf_Domicile").value=selDomicileEleID[selDomicileEleID.selectedIndex].value;
	  $("Pf_Manager").value=selManagerEleID[selManagerEleID.selectedIndex].value;

	  // Submitting the form using Post method
	  document.forms[0].action="/Investments/Perf.aspx?univ=" + universe;
	  document.forms[0].submit();*/
   }
}

// To update quicksearch querystring parameters
function UpdateQSQryStr(str,val)
{
	if(val=="")
	{
		return "";
	}
	else
	{
		return str + "=" + val + "&";
	}
}


/// Checking the control for checkbox
function IsCheckBox(chk)
{
    return (chk.type == 'checkbox');
}

/// Checking the control for radio button
function IsRadio(chk)
{
   return (chk.type == 'radio');
}

function LoadSectorsByUniv(univ, sectorDDId, selectedValue)
{
	// To Load Sectors for universe using Ajax Pro Method
	var Sectors=TrustnetX.Tools.TopQuartiles.LoadSectorsByUniv(univ);	  
	Sectors = Sectors.value;
	var sectorDD = $(sectorDDId);
	if(sectorDD)
	{
		sectorDD.disabled=false;
		sectorDD.options.length=0;
		var optionElement=document.createElement("option");
		optionElement.text="All Sectors";
		optionElement.value="";
		sectorDD.options.add(optionElement);
	 
		// Skip this code when Sector array is null
		if(Sectors)
		{
		   // Loop to add all the Sectors in Sector Dropdown box
		   var selectedIndex = 0;
		   for(i=0;i<Sectors.length;i++)
		   {
			  if(Sectors[i]!=null) {
				 optionElement=document.createElement("option");
				 optionElement.text=Sectors[i].SectorName;
				 optionElement.value=Sectors[i].SectorClassCode;
				 sectorDD.options.add(optionElement);
				 if(Sectors[i].SectorClassCode == selectedValue)
					selectedIndex = i;
			  }
		   }
		   if(selectedValue!="")
		   sectorDD.value = selectedValue;
		}
	}
}
function btnTQSearch_Click()
{
	var sectorDD = $('TQSector');
	var crownDD = $('TQCrownRating');
	var loadUnits = $('hdnTQLoadUnits');
	loadUnits.value = 1;
	if(sectorDD)
	{
		$('hdnTQSector').value = sectorDD.options[sectorDD.selectedIndex].value;
	}
	if(crownDD)
	{
		$('hdnTQCrownRating').value = crownDD.options[crownDD.selectedIndex].value;
	}
	SelectTopQuartileColumns();
}
function SelectTopQuartileColumns()
{
    var radioIds = "";
    var columnIds = "";
    var isOthrThanMandatorySel = false;
    var elements = document.getElementsByTagName("INPUT");
    var univCode="";
	for(var i=0;i<elements.length;i++)
    {
       if(IsCheckBox(elements[i]))
	    {
	        if(elements[i].checked == true)
	        {
	            columnIds += (columnIds.length > 0) ? ","+elements[i].id : elements[i].id;
	        }
	    }
	    if(IsRadio(elements[i]))
	    {
	        if(elements[i].checked == true)
	        {
	            if(elements[i].name.indexOf("FundRadio")>=0)
	            {
	            radioIds += (radioIds.length > 0) ? ","+elements[i].id : elements[i].id;
	            univCode=$(elements[i].id).value;
	            }
	            if(elements[i].name.indexOf("radioquartile")>=0)
	            {
	            radioIds += (radioIds.length > 0) ? ","+elements[i].id : elements[i].id;
	            }
	        }
	    }
	}
	if($('TQCrownRating').value == "")
	{
		columnIds = columnIds.replace("Crown","");
	}
	else
	{
		columnIds += (columnIds.length > 0) ? ",Crown" : "Crown";
	}
	
	SetCookie("CustTopQuartile_CC_"+univCode+"_"+requestFile, columnIds,123231);
	document.masterForm.RadioColumns.value=radioIds;
	document.masterForm.submit();
 }

	
/**************** Key Asset control ****************/	
function loadIndicesKAC()
{
    var indicesName = ["SBWGU","Citi World Government Bond Index- all maturities",
					"CRSHDG","Credit Suisse Tremont Hedge Fund Index",
					"ASX","FTSE All Share",
					"LIB3MGBP","LIBOR GBP 3m",
					"M990100","MSCI THE WORLD INDEX",
					"M891800","MSCI EM (EMERGING MARKETS)",
					"IPDAP","IPD UK all property"];
					
    var assetClass = $('keyAssetClass').value.replace('@GB','');
    for(i=0; i<indicesName.length; i=i+2)
    {
	  if (indicesName[i]==assetClass)
	  {
		 $('spanIndicesName').innerHTML = indicesName[i+1];
	  }
    }
}

function changeSpanKeyAsset(){ 
	
    var assetClass = $('keyAssetClass').value;
    var assetSpan = $('keyAssetSpan').value;	 
	$('hdnassetClass').value=$('keyAssetClass').value;
	$('hdnkeyAssetSpan').value=$('keyAssetSpan').value;	
	var imageSource = "/Tools/ChartBuilder.aspx?width=320&height=122&color=CE1010&codes=N" + assetClass + "&span=" + assetSpan;
	var imgObj = $("keyAssetChart");
	if (imgObj) {
		imgObj.src = imageSource;
	}	
	loadIndicesKAC();
}
/************** End Key Asset control ******************/

/************** Start of Index Performance control ******************/
function IndexPerfChange(){
	
	// Declaring shortname for required elements
	var eSelectIP = document.getElementById('IndexPerfDD');
	var eSelectSpan = document.getElementById('IndexPerfSpan');
	var eSpanIPName = document.getElementById('spnIndexPerfName');
	var eImageChart = document.getElementById('IndexPerfChart');		
	
	var span = eSelectSpan.value;
	var indexCode = eSelectIP.value;
	var indexName = eSelectIP.options[eSelectIP.selectedIndex].text;
	eSpanIPName.innerHTML = indexName;
	eImageChart.src = "/Tools/ChartBuilder.aspx?width=320&height=122&color=CE1010&codes=N" + indexCode + "&span=" + span;
}
/************** End of Index Performance control ******************/



/************** Foreign Exchange control ******************/

var curTitleArray = new Array();
var newCurCookie = new Array();
var arrGICookie = new Array();	    		
var curCookie = GetCookie("TN_ForEx");	
newCurCookie = curCookie.split(',');
arrGICookie = GetCookie("TN_GIBar").split(',');
var curDirectionStatus = "Up";

function assignCURTypeCode(typecode) {
	curTitleArray = typecode.split(',');
}
    
// Function to display or hide Global Indices Popup
function getCurPopup(val) {
  if(val=="True") {
	 $("curPopup").style.visibility='visible';
	 $("curIFrame").style.visibility='visible';
  }
  else if(val=="False") {
	 $("curPopup").style.visibility='hidden';
	 $("curIFrame").style.visibility='hidden';
	 updateCur_Cookie();
	 document.forms[0].submit(); 
  }
  else {
	 $("curPopup").style.visibility='hidden';
	 $("curIFrame").style.visibility='hidden';		 
  }
}

// Function to update Foreign Exchange cookie values
function updateCur_Cookie() {
  var prevCookie = GetCookie("TN_ForEx");	  

  if(prevCookie==null) {
	 SetCookie("TN_ForEx", null, 123231);
  }
  else {		 
	 var k=0;
	 var newCookieValue='';
	 for(j=0;j<curTitleArray.length;j++) {	
		if($(curTitleArray[j] + "_Chk")) {		
			if($(curTitleArray[j] + "_Chk").checked) {
				if(k>0) { 
				  newCookieValue += ","; 
				}
				newCookieValue += curTitleArray[j];
				k++;
			}
		}			
	 }
	 SetCookie("TN_ForEx", newCookieValue, 123231);		 
  }	 
}

// It will change the charts based on the time span
function changeCurrencyChart(val) {	  
  for(i=0;i<newCurCookie.length;i++) {
	 var curAry = new Array();
	 //curAry = newCurCookie[i].split('/');
	 curAry = newCurCookie[i].split(':');
	 var imgObj = $(newCurCookie[i]);
	 if(imgObj)	 {
		imgObj.src = "/Currencies/chartbuilder.aspx?height=110&width=145&hide=1&format=NoCopyright&yformat=0.0&xformat=MMM yy&color=" + strFEBMColorCode + "&currency1=" + curAry[0] + "&currency2=" + curAry[1] + "&span=" + val;
	 }
  }	  
} 

// On Clicking the chart it will navigate to charting page
function onCurClick(Title) {	  	  
  var sel = $("CurrencySpanVal")[$("CurrencySpanVal").selectedIndex].value;
  var curAry = new Array();
  //curAry = Title.split('/');
  curAry = Title.split(':');
  window.location="/Currencies/CurrencyHistory.aspx?SourceT=" + curAry[0] + curAry[1] + "&spanddl=" + sel;		 		 
} 

// It will decide to display or hide the outer border
function updateCurOuterDiv() {
  var eleOuterDiv = $("curOuterDiv");
  var eleInnerDiv = $("curInnerDiv");
  var eleScrollUp = $("curScrollUp");
  var eleScrollDown = $("curScrollDown");
  
  if (newCurCookie.length > 5-arrGICookie.length)
  {
	 var ht =  5 - arrGICookie.length;
	 if(newCurCookie.length>1) {
		eleOuterDiv.style.border = 'solid 1px #A7C7E7';
		eleOuterDiv.style.height = ((ht<=0)?imgHeight:ht*imgHeight) + "px" ;
		eleScrollDown.style.visibility='visible';
		eleScrollUp.style.visibility='visible';
		moveCurChart(true);
	 }
	 else {
		eleOuterDiv.style.border = 'none 0px white';
		eleOuterDiv.style.height = imgHeight + "px";
		eleScrollDown.style.visibility='hidden';
		eleScrollUp.style.visibility='hidden';		 
		moveCurChart(false);
	 }
  }
  else
  {
	 eleOuterDiv.style.border = 'none 0px white';
	 eleOuterDiv.style.height = eleInnerDiv.getElementsByTagName('img').length * imgHeight + "px";
	 eleScrollDown.style.visibility='hidden';
	 eleScrollUp.style.visibility='hidden';
	 moveCurChart(false);
  }
}	   
	
// It will execute when up and down scrolls clicked based on the parameter passed
function curScroll(direction, state) { 	  
  if(state=="Start" && direction=='') {		 
	 direction=curDirectionStatus;
  }
  else if(direction!='') {
	 curDirectionStatus = direction;
  }
  $("hdnCurDirection").value = direction;
}

// Function to keep the charts moving always
function moveCurChart(srlval) {
  var eleHdn = $("hdnCurDirection");
  var eleInnerDiv = $("curInnerDiv");
  var inEleHeight = newCurCookie.length * imgHeight;
  var jump = 5;
  var scrollFETimer = 0;	  
  	  
  if(eleHdn.value=="Up") {
	 for(i=0;i<newCurCookie.length;i++) {
		var eleChart = $(newCurCookie[i] + "_div");
		if(eleChart){
			var chartHeight = eleChart.style.top;
			chartHeight = parseInt(chartHeight.replace('px','')) - parseInt(jump);
			eleChart.style.top = chartHeight + "px";
			if(chartHeight<-imgHeight) {
			   eleChart.style.top = parseInt(inEleHeight) - parseInt(imgHeight) + "px";
			}
		}
	 }
  }
  else if(eleHdn.value=="Down") {		 
	 for(i=0;i<newCurCookie.length;i++) {
		var eleChart = $(newCurCookie[i] + "_div");
		if(eleChart){
			var chartHeight = eleChart.style.top;
			chartHeight = parseInt(chartHeight.replace('px','')) + parseInt(jump);
			eleChart.style.top = chartHeight + "px";
			if(chartHeight > (parseInt(inEleHeight) - parseInt(imgHeight))) {
			   eleChart.style.top = -(parseInt(imgHeight)) + "px";			   
			}
		}
	 }  
  }
  if(srlval) {
	scrollFETimer = setTimeout('moveCurChart(true)',300);
  }
  else {
	clearTimeout(scrollFETimer);
  }
}
/************** End Foreign Exchange control ******************/


/************** Advertisement Script ******************/

function OAS_NORMAL(pos){
	document.write(OAS_NORMAL_STR(pos))	
}

function OAS_NORMAL_STR(pos){
	var str = "";
	str += ('<a href="'+OAS_url+'click_nx.ads\/'+OAS_sitepage+'\/1'+OAS_rns+'@'+OAS_listpos+'!'+pos+OAS_query+'" rel="external">');
	str += ('<img src="'+OAS_url+'adstream_nx.ads\/'+OAS_sitepage+'\/1'+OAS_rns+'@'+OAS_listpos+'!'+pos+OAS_query+'" alt="advert" \/><\/a>');
	return str;
}

function OAS_AD(pos){
	if(OAS_listpos!=''){
		if (OAS_version>=11 && typeof(OAS_RICH_STR)!='undefined'){
			var width = 730;
			var height = 92;
			var nocomment = "";
			nocomment = "&nocomment=1";

			switch(pos) {
				case "Top":
					width = 728; height = 90;
					break;
				case "Top2":
					width = 120; height = 60;
					break;
				case "Right":
					width = 140; height = 840;
					break;
				case "Position1":
					width = 300; height = 250;
					break;
				case "Top3":
					width = 150; height = 30;
					break;
				case "x03":
					width = 5; height = 5;
					break;
				case "BottomLeft":
					width = 155; height = 470;
					break;
				case "Left1":
					width = 155; height = 160;
					break;
					
			}
			var str = OAS_RICH_STR(pos);
			if (str) {
				document.write('<iframe style="width: '+width+'px;height: '+height+'px; padding: 0" marginheight="0" marginwidth="0" scrolling="no" frameborder="0" src="\/functions\/IframeAd.aspx?pos='+pos+nocomment+'"><\/iframe>')
			}
		}
		else if (OAS_version>=11 && typeof(OAS_RICH)!='undefined'){
			OAS_RICH(pos);
		}
		else{
			OAS_NORMAL(pos);
		}
	}
}

function OAS_AD_STR(pos){
	if(OAS_listpos!=''){
		if (OAS_version>=11 && typeof(OAS_RICH_STR)!='undefined'){
			return OAS_RICH_STR(pos);
		}else{
			return OAS_NORMAL_STR(pos);
		}
	}
}

function advPosition() {
	if(OAS_listpos!=''){
		OAS_version=11;
		if(navigator.userAgent.indexOf('Mozilla/3')!=-1){
			OAS_version=10;
		}else{
			var surl = OAS_url+'adstream_mjx.ads\/'+OAS_sitepage+'\/1'+OAS_rns+'@'+OAS_listpos+OAS_query;

			if (iframead) {
				document.write('<sc'+'ript language="javascript1.1" src="\/functions/OasStr.aspx?adstr='+escape(surl)+'"><\/scr'+'ipt>');
			}
			else {
				document.write('<sc'+'ript language="javascript1.1" src="'+surl+'"><\/scr'+'ipt>');
			}		
		}
	}
}

/************** End of Advertisement script *********/
// Function to load sectors based on universe and assetclass
function qsNewLoadSector(val)
{		
  
   var selUnivEleID = $("qsUniverseDD");
   var assetClassCtrl = $("qsAssetClassDD");
   
   // Skip this code when both the element doesn't exit
   if(assetClassCtrl && selUnivEleID)
   {
	  // Assigning values of the dropdown boxes to a local variable
	  var assetClass = assetClassCtrl.options[assetClassCtrl.selectedIndex].value;
	  var universe=selUnivEleID[selUnivEleID.selectedIndex].value;
	  var isSecRequired = universe.substring(universe.toString().indexOf(":")+1,universe.toString().length);
	  universe=universe.substring(0,universe.toString().indexOf(":"));
	  var sectorDDCtrl=$("qsSectorsDD");
	  
	  if(isSecRequired=="True")
	  {
		 if(val=='univ')
		 {
		  LoadFilterBusObjectLoad('Sectors',universe,'LoadByUniverse',universe,'Name','SectorClassCode','','Name asc');
		 }
		 else
		 {
		 LoadSectorByAssetClassLoad(assetClass,universe,'Name','SectorClassCode',null,'Name asc');	
		 }
		 
	  }
	  else
	  {
		 sectorDDCtrl.value="";
		 sectorDDCtrl.disabled=true;		 
	  }
	  if(val=="univ")
	  {	  
		 
		   LoadFilterBusObjectLoad('Managers',universe,'LoadByUniverse',"'"+universe+"'",'Name','ManagerCode','','Name asc');
		   LoadFilterBusObjectLoad('Domiciles',universe,'LoadByUniverse',"'"+universe+"'",'DomicileName','DomicileCode','','DomicileName asc');
		
	  }
   }
}   

 

/////////////////////// ***************************** Dragging Object ******************************** //////////////////

///Drag Object.
// This will Drag object corresponding to the Cursor Movement.
function $(v) 
{ 
	return(document.getElementById(v)); 
}

function agent(v) 
{ 
	return(Math.max(navigator.userAgent.toLowerCase().indexOf(v),0)); 
}

function xy(e,v) 
{ 
	return(v?(agent('msie')?event.clientY+document.body.scrollTop:e.pageY):(agent('msie')?event.clientX+document.body.scrollTop:e.pageX)); 
} 

function dragOBJ(d,e,ifid,trid) 
{ 	
	function drag(e) 
	{ 
		if(!stop) 
		{ 
			d.style.top=(tX=xy(e,1)+oY-eY+'px'); 
			d.style.left=(tY=xy(e)+oX-eX+'px'); 
			ifid.style.top=(tX=xy(e,1)+oY-eY+'px'); 
			ifid.style.left=(tY=xy(e)+oX-eX+'px');
			
			StableHeader(trid);
		} 
	} 	
	var oX=parseInt(d.style.left),oY=parseInt(d.style.top),eX=xy(e),eY=xy(e,1),tX,tY,stop; 	
	document.onmousemove=drag; document.onmouseup=function()
	{ 
		stop=1; 
		StableHeader(trid);
		document.onmousemove=''; 
		document.onmouseup=''; 
	}; 
}


function StableHeader(titleEle)
{
	if(titleEle)
	{
		//var titleEle = $("CalcTitleTR");
		titleEle.style.background="url(/Images/bgMainMenuActive.gif)  repeat-x";
		titleEle.style.cursor='move'; 
	}
}


// This function is to enable and display popup window
function enablePopup(id) {	
	switch (id)
	{
		case "FooterTZCDiv":
			if(!$("TimeZoneDiv")) {
				CalDayLightTimeLoad();
				$("FooterTZCDiv").innerHTML=loadTimeZoneConverter();
			}
			showTZC();
			break;
		case "FooterMailDiv":
			if(!$("MailDiv")) {
				$("FooterMailDiv").innerHTML=EmailContent();				
			}
			showMailDiv('logDiv');
			// $("txtTo").value="[enter the email address of the person you'd like to send this page to]";
         $("txtComment").value="[I thought you might interested in this page]";             
			break;
		case "FooterCalDiv":
			if(!$("CalcMainDiv")) {
				$("FooterCalDiv").innerHTML=CalculatorContent();
			}
			ShowCalc();
			break;
		default:				
	}       
}

/////////////////////// ------------------------------------------------------------------------------ ////////////////////

function LoadPresetColumns(columnIds)
{
	SetCookie(ctrlId+ "_CC_"+cust_universe+"_"+requestfile, columnIds, 11111);
	document.masterForm.submit();
}


function postValues(ctrl,tabName,duration)
{
  var tab=$("ffcType");
  var dur=$("ffcDuration");
  tab.value=tabName;
  dur.value=duration;
  
  document.forms[0].submit();
  
}

function changeValues(ctrl,tabName,duration)
{
  var chart=$("chartFeatured");
  var dur=$("ffcDuration");
  
  
  var span=36;
  if(duration=='36M')
  {
   span=36;
  }
  else if(duration=='12M')
  {
   span=12;
  }
  else if(duration=='60M')
  {
   span=60;
  }
  
  
 if(ctrl=='ffc')
 {
    chart.src='/Tools/ChartBuilder.aspx?width=320&height=122&codes=FITWTAN&span='+span+'&color=CE1010';
    
    var list_item=$('ffc_li_'+duration);
    
    if(list_item)
    {
        list_item.className='selected';

        switch(duration)
        {
          case '12M':  
          $('ffc_li_36M').className='';
          $('ffc_li_60M').className='';
          break;
          
          case '60M':  
          $('ffc_li_12M').className='';
          $('ffc_li_36M').className='';
          break;
          
          default:  
          $('ffc_li_12M').className='';
          $('ffc_li_60M').className='';
          break;
        
        }

    } 
  
  }
  
}

function OnSplitViewChange(val)
{
$('hdnView').value=val;
document.masterForm.submit();
}
function OpenSplitCapital(val)
{
SetCookie("SCA_CC_T_SplitCapitalAnalytics",val,123231);
window.open("/Investments/SplitCapitalAnalytics.aspx?univ=T","_self");
}

function ToolDiscPerf(univ)
{
SetCookie('Pf_CC_'+univ+'_perf','Fundname,P0t12m,P12t24m,P24t36m,P36t48m,P48t60m','11111');
document.masterForm.action='/Investments/Perf.aspx?univ='+univ+'';
document.masterForm.submit();
}
function btnSubmit_Click()
{
	if($('txtEmailAddress').value!="")
	{
		if(validateEmail($('txtEmailAddress')))
		{
		document.masterForm.submit();
		}
	}
	else
	{
	alert("Please enter your email address");
	$('txtEmailAddress').focus();
	}
}
function leftNavHide(id) 
{

 var value=GetCookie('LeftNav');
 
 if ($(id).style.display == 'none')
 {   
    var farray = new Array();
	farray = value.split(',');           
	if(!IsStringFoundInArray(farray, id))
	{
	 value += ","+id;	
	}
	else
	{
	 DeleteFromShortlist(id,'LeftNav');
	 value=GetCookie('LeftNav');
	}
	SetCookie('LeftNav',value,123231);
	$(id).style.display = 'block';	 
	$('btn' + id).src = '/images/icon_hide.png';
 } 
 else 
 {
	DeleteFromShortlist(id,'LeftNav');
	value=GetCookie('LeftNav');
	SetCookie('LeftNav',value,12345);
	$(id).style.display = 'none';	  
	$('btn' + id).src = '/images/icon_view.png';
 }
 return false;
}

function ShowAllLefNav()
{
   var value=GetCookie('LeftNav');
   var farray = new Array();
   farray = value.split(',');
   //alert(value);
   for(var i=0;i<farray.length;i++)
   {
	  if(farray[i]!='')
	  {
		if ($(farray[i]).style.display == 'none')
		{
		$(farray[i]).style.display = 'block';	 
		$('btn' + farray[i]).src = '/images/icon_hide.png';
		} 
		else 
		{
		$(farray[i]).style.display = 'none';	  
		$('btn' + farray[i]).src = '/images/icon_view.png';
		}
	  }
   }
}

function GoToPerf(id)
{
 var univ=$(id).value;
 if(univ == "VCT")
 {
	window.open("/Investments/VCTPerf.aspx","_self");
 }
 else
 {
	window.open("/Investments/Perf.aspx?univ="+univ+"","_self");
 }
}

////////////////////////////////// Functions for Basket in checkstatus control ////////////////

	 function ShowBasketHelp(DivID)
		{
			$(DivID).style.visibility="visible";
			$(DivID).style.zIndex = "2000";
			MinimizeBasketHelpWindow('BasketHelpContent');
			return false;
		}
		
		function HideBasketHelp(DivID)
		{
			$(DivID).style.visibility="hidden";
			$('BasketHelpContent').style.visibility="hidden";
		}
		
		//Minimize Window is the function to Minimise Currency Gadjet Window.
		//To Minimise Current Window to Bottom.
		function MinimizeBasketHelpWindow(divID)
		{
			//Code here for Minimising Div.
			if($(divID).style.visibility == 'visible')
			{
				$(divID).style.visibility = 'hidden';
				$("BasketMinimizeL").innerHTML = "<img src='/images/shape_square.png' style='border:#FFFFFF solid 1px; height:16px;' alt='Maximize' />";
				$("BasketMinimizeL").style.verticalAlign = "bottom";
				$("BasketMinimizeL").title ="Maximize";
				$("HelpBasket").style.height = '21px';
			}
			else
			{
				$(divID).style.visibility = 'visible';
				$("BasketMinimizeL").innerHTML = "&nbsp;_&nbsp;";
				$("BasketMinimizeL").style.border="0px";
				$("BasketMinimizeL").title = "Minimize";
				$("HelpBasket").style.height = '';
			}
			
		}

		//Make shading while Cursor Moves.

		function Shade(ctl)
		{
			ctl.style.background="#1A5083";
		}

		// Remove Shading while Cursor Out.
		function RShade(ctl)
		{
			ctl.style.background="";
		}
		
////////////////////// Menu bar input controls ////////////////////////////

function SetAutoComplete(ctrlid, on_off) {
	if($(ctrlid))
	{
		var f = $(ctrlid);
		f.setAttribute("autocomplete", on_off);
	}
} 
 function save()
    {
    var element=document.getElementsByName("Default");   
    var elementRename=document.getElementsByTagName("INPUT"); 
    var elementCurrency=document.getElementsByName("changeCurrency");   
    var names="";
    var rdnPid="";
    var msg="";
    var CurrencyPid="";
    for(var i=0;i<element.length;i++){
    if(element[i].type=="radio"){    
    if(element[i].checked){
    $("rdnDefault").value=element[i].id;   
    }else{  
    msg++;
    }    
    }
    }
     for(var i=0;i<elementRename.length;i++){
    if(elementRename[i].name=="Rename"){              
    names=names+elementRename[i].value+",";
    rdnPid=rdnPid+elementRename[i].id+",";       
    } 
    }     
    for(var i=0;i<elementCurrency.length;i++){   
    CurrencyPid=CurrencyPid+elementCurrency[i].id+",";
    }
    $("hdnRenames").value=names;
    $("rdnPid").value=rdnPid; 
    $("CurrencyPid").value=CurrencyPid;  
      
    if((msg+1)!=element.length){
    alert('Please select Default Portfolio');  
    }else{
	  document.masterForm.action="ManagePortfolio.aspx";
     document.masterForm.submit();
    }
    }
  function delFundsList1(rdnDelDefault)
  {
  $("rdnDelDefault").value=rdnDelDefault;
  document.masterForm.submit(); 
  }
  function addReport(portID)
  {
  $("portID").value=portID;
  document.masterForm.submit(); 
  }
 
  
 function editFundsList(editText,id,idL)
  {  
  if(document.getElementById(idL)!=null){
   var editElement=$(editText);  
   var editLink =$(idL);      
   var ele=document.createElement("input");
   ele.setAttribute("id", id);
   ele.setAttribute("name", "Rename");  
   ele.onchange=function(){ loadCashValue(id,id,'Rename Cash');};
   //"javascript:loadCashValue('"+id+"'); PortfolioPopup('visible','curr"+id+"');"
   //editText.appendChild(ele);
   editLink.parentNode.replaceChild(ele, editLink);
   ele.focus();
   }   
  } 
  
  
  function loadResult(univ)
  {  
    var typecodes=document.getElementsByName("selectFunds");
    var typeCode="";
    var splitter="";
   for(var i=0;i<typecodes.length;i++)
   { 
   typeCode=typeCode+splitter+typecodes[i].value;
   splitter=",";
   }

   var Result=TrustnetX.Portfolio.PortfoliosAlert.LoadResult(typeCode,univ);
  
	  if(Result!=null)
	  {					 
			 //var Prcies=document.getElementsByName("Curr");			  
			 Result=Result.value;  	
	 		 for(var i=0;i<typecodes.length;i++)
			 {
			 for(var j=0;j<Result.length;j++)
			 {			 
			 if(typecodes[i].value!="" && Result[j].typeCode==typecodes[i].value){			 			 
			 var selectPrice=$("alert"+i);
			 selectPrice.options.length=0;
			 //selectPrice[count].value=Result[count].Name;
			  var ele=document.createElement("option");
			  ele.text=Result[j].Name;
			  ele.value=Result[j].Name;
			  selectPrice.options.add(ele);	
			  if(univ=="T")
			  {
			  var ele=document.createElement("option");			  
			  ele.text="Discount";
			  ele.value="Discount";
			  selectPrice.options.add(ele);
			  var ele1=document.createElement("option");		
			  ele1.text="% Pricechange";
			  ele1.value="% Pricechange";
			  selectPrice.options.add(ele1);
			  }
			  else if(univ=="Warrants")
			  {
			  var ele=document.createElement("option");			  
			  ele.text="Discount";
			  ele.value="Discount";
			  selectPrice.options.add(ele);
			  var ele1=document.createElement("option");		
			  ele1.text="% Pricechange";
			  ele1.value="% Pricechange";
			  selectPrice.options.add(ele1);
			  } 
			  else if(univ=="Equities")
			  {			 
			  var ele1=document.createElement("option");		
			  ele1.text="% Pricechange";
			  ele1.value="% Pricechange";
			  selectPrice.options.add(ele1);
			  }
			  else
			  {			 
			  if(Result[j].Name=="Bid")
			  {
			  var ele=document.createElement("option");
			  ele.text="Offer";
			  ele.value="Offer";
			  selectPrice.options.add(ele);
			  var ele1=document.createElement("option");
			  ele1.text="% Pricechange";
			  ele1.value="% Pricechange";
			  selectPrice.options.add(ele1);
			  }			  
			  else if(Result[j].Name=="Mid")
			  {
			  var ele=document.createElement("option");			 
			  ele.text="% Pricechange";
			  ele.value="% Pricechange";
			  selectPrice.options.add(ele);
			  }		
			  }	  
			  $("Curr"+i).innerHTML=Result[j].Price;
			  selectPrice.value=Result[j].Name;			 
			 
			  }	
			  }	
		   }
	   }        
      }
      
   function loadPriceResult()
   {
    var typecodes=document.getElementsByName("selectFunds");
    var typeCode="";
    var splitter="";
   for(var i=0;i<typecodes.length;i++)
   { 
   typeCode=typeCode+splitter+typecodes[i].value;
   splitter=",";
   }
   var count=0;
   var selectPrice=document.getElementsByName("selectAlerts"); 
    for(var j=0;j<selectPrice.length;j++)
	{	
	if(selectPrice[j].value!="" && typecodes[j].value!=""){		  
	  var Result=TrustnetX.Portfolio.PortfoliosAlert.LoadPriceResult(typecodes[j].value,selectPrice[j].value);    
	  if(Result!=null)
	  {			 
			  Result=Result.value; 				
			  //selectPrice[j].value=selectPrice[j].value;		  		  
			  document.getElementById("Curr"+j).innerHTML=Result[0].Price;			 
			  count++
		 	
		}	   }  
	   }      
      }
      
function loadWatchResult(univ)
   {
    var typecodes=document.getElementsByName("selectFunds");
    var typeCode="";
    var splitter="";
   for(var i=0;i<typecodes.length;i++)
   { 
   typeCode=typeCode+splitter+typecodes[i].value;
   splitter=",";
   }
   var Result=TrustnetX.Alerts.LoadResult(typeCode,univ);   
	  if(Result!=null)
	  {					 
			 //var Prcies=document.getElementsByName("Curr");			  
			 Result=Result.value;  	
	 		 for(var i=0;i<typecodes.length;i++)
			 {
			 for(var j=0;j<Result.length;j++)
			 {			 
			 if(typecodes[i].value!="" && Result[j].typeCode==typecodes[i].value){			 			 
			 var selectPrice=$("alert"+i);
			 selectPrice.options.length=0;
			 //selectPrice[count].value=Result[count].Name;
			  var ele=document.createElement("option");
			  ele.text=Result[j].Name;
			  ele.value=Result[j].Name;
			  selectPrice.options.add(ele);	
			  if(univ=="T")
			  {
			  var ele=document.createElement("option");			  
			  ele.text="Discount";
			  ele.value="Discount";
			  selectPrice.options.add(ele);
			  var ele1=document.createElement("option");		
			  ele1.text="% Pricechange";
			  ele1.value="% Pricechange";
			  selectPrice.options.add(ele1);
			  }
			  else if(univ=="Warrants")
			  {
			  var ele=document.createElement("option");			  
			  ele.text="Discount";
			  ele.value="Discount";
			  selectPrice.options.add(ele);
			  var ele1=document.createElement("option");		
			  ele1.text="% Pricechange";
			  ele1.value="% Pricechange";
			  selectPrice.options.add(ele1);
			  } 
			  else if(univ=="Equities")
			  {			 
			  var ele1=document.createElement("option");		
			  ele1.text="% Pricechange";
			  ele1.value="% Pricechange";
			  selectPrice.options.add(ele1);
			  }
			  else
			  {			 
			  if(Result[j].Name=="Bid")
			  {
			  var ele=document.createElement("option");
			  ele.text="Offer";
			  ele.value="Offer";
			  selectPrice.options.add(ele);
			  var ele1=document.createElement("option");
			  ele1.text="% Pricechange";
			  ele1.value="% Pricechange";
			  selectPrice.options.add(ele1);
			  }			  
			  else if(Result[j].Name=="Mid")
			  {
			  var ele=document.createElement("option");			 
			  ele.text="% Pricechange";
			  ele.value="% Pricechange";
			  selectPrice.options.add(ele);
			  }		
			  }	  
			  $("Curr"+i).innerHTML=Result[j].Price;
			  selectPrice.value=Result[j].Name;			 
			 
			  }	
			  }	
		   }
	   }    
      }
      
  function loadWatchPriceResult()
  {
    var typecodes=document.getElementsByName("selectFunds");
    var typeCode="";
    var splitter="";
    for(var i=0;i<typecodes.length;i++)
    { 
    typeCode=typeCode+splitter+typecodes[i].value;
    splitter=",";
    }
   var count=0;
   var selectPrice=document.getElementsByName("selectAlerts"); 
   for(var j=0;j<selectPrice.length;j++)
	{	
		 if(selectPrice[j].value!="" && typecodes[j].value!="")
		 {		  
			   var Result=TrustnetX.Alerts.LoadPriceResult(typecodes[j].value,selectPrice[j].value);    
			   if(Result!=null)
			   {			 
				   Result=Result.value; 				
				  // selectPrice[j].value=selectPrice[j].value;		  		  
				   $("Curr"+j).innerHTML=Result[0].Price;			 
				   count++
         		 	
			   }
		}   
	}      
 }

function HideMenu(e,listid,parent)
{
	var tagn=(document.all)?event.srcElement.parentElement.id:e.target.parentNode.id;
	var tagid=(document.all)?event.srcElement.id:e.target.id;
	tagid=tagid==""?tagn:tagid;
	var flag=false;
	var x =  $(listid).childNodes;
	for(var i = 0; i < x.length;i++)
	{
	var tab = x[i];
	var ang = tab.childNodes;
		if(tagid==(ang.id)&& ang.id!="")
		{
		flag=true;
		break;
		}
		for(var d = 0;d<ang.length;d++)
		{
		var chi = ang[d];
			if(tagid==(chi.id) && chi.id!="")
			{
			flag=true;
			break;
			}

		}
	}
	if(flag==true || tagid==parent )
	{
	 $(listid).style.display='block';
	}
	else
	{
	 $(listid).style.display='none';
	}
}

function Navigate(id,scope,type)
{
	var val=$(id).value;

	if($('scope'))
	{
		if($(scope))
		{
			$('scope').value=$(scope).value;
		}
		else
		{
			$('scope').value="all";
		}
	}
	$(type).checked=true;
	searchSubmit($(id).value);
	return true;
}

function OnSearchEnter(e,id,scope,type)
{
	if(e.keyCode == 13)
	{
		Navigate(id,scope,type)
	}
}

function SetSelectedValue()
{
	var browserVersion=navigator.userAgent;
    
   var keyDD=document.getElementById('keyStrategyDD');
   var selValue=document.getElementById('keyStrategyLbl').innerHTML.toLowerCase(); 
	selValue=selValue.replace('-',' ');
	for(i=0;i<keyDD.length;i++)
	{
		if(keyDD.options[i].text.toLowerCase()==selValue)
		{
			keyDD.selectedIndex=i
		}
	}
}

/*  Smart navigation  */
function SmartScroller_GetCoords() {
	var scrollX, scrollY;
	if (document.all) {
		if (!document.documentElement.scrollLeft)
			scrollX = document.body.scrollLeft;
		else
			scrollX = document.documentElement.scrollLeft;
		if (!document.documentElement.scrollTop)
			scrollY = document.body.scrollTop;
		else
			scrollY = document.documentElement.scrollTop; 
	}
	else {
		scrollX = window.pageXOffset; scrollY = window.pageYOffset; 
	}
	 $('scrollLeft').value = scrollX;
	 $('scrollTop').value = scrollY;
}

function SmartScroller_Scroll() {
	var x =  $('scrollLeft').value;
	var y =  $('scrollTop').value;
	window.scrollTo(x, y); 
}

/*  End smart navigation  */

function ChangeFontSize(divName, size) 
{
   var eleContent =  $(divName);
   if(eleContent)
   {
		eleContent.style.fontSize = size;
   }
}

function BasketPopup(visibleType,typeCode,popupType,portfolioName)
{
    if(typeCode!=null && typeCode!='')
    {
        FundByType(typeCode);
    }
    if(visibleType=="visible")
    {
        $("FooterBasketDiv").innerHTML=BasketPopupContent(getPosition(typeCode),popupType,typeCode,portfolioName);
        $('curPopup').value=typeCode;
        setTimeout("CloseBasket('"+typeCode+"')",4000);
    }
    else
    {
        CloseBasket(typeCode);
    }
}

function SetBasketVisibility(r)
{
    var row = $("td_TypeName");
    if(row && r!=null)
    {
        row.innerHTML =r.FundName;
    }
}


function CloseBasket(typeCode)
{
    if($('isBasketClose')!=null && $('isBasketClose').value=='true')
    {
       if($("BasketPopup"+typeCode+"")!=null)
       { 
        $("BasketPopup"+typeCode+"").style.visibility='hidden';  
        $("BasketPopupFrame").style.visibility='hidden';  
       }
    }
}

function ClosePortfolio(id)
{
    if($('isPortfolioClose')!=null && $('isPortfolioClose').value=='true')
    {
       if($("PortfolioPopup"+id+"")!=null)
       { 
        $("PortfolioPopup"+id+"").style.visibility='hidden';  
        $("PortfolioPopupFrame").style.visibility='hidden';  
       }
    }
}

//Region for Article Comment and Recpatcha functions

function ChangeRecaptchaImg()
{
 var recapImgDiv =  $('recaptcha_image');
 recapImgDiv.style.width = "250px";
 var recapEle = recapImgDiv.getElementsByTagName('IMG');
 for(var l=0;l<recapEle.length;l++)
 {
    if(typeof(recapEle[l])!='undefined')
    {
	    recapEle[l].style.width = "250px";
    }
 }
}
function ChangeCaptchaMode()
{
 var label = $("lblResponse");
 var recapMode =  $('Captchamode');
 if(recapMode.src.indexOf('recaptcha_volume') != -1)
 {
     Recaptcha.switch_type("audio");
     recapMode.src = "/icons/recaptcha_text.jpg";
     if(label) label.innerHTML = "Enter the eight numbers: ";
 }
 else
 {
     Recaptcha.switch_type("image");
     recapMode.src = "/icons/recaptcha_volume.jpg";
     if(label) label.innerHTML = "Enter either word above: ";
 }
}

function getCommentValue(id)
{
  var userId=GetCookie("TN_UserId")             
  if(userId=='')
  {
     ShowLogInDiv();
  }
  else
  {
	 var comment= $(id).value;
	 var maxValue=2000; 				    
	 comment= comment.replace(/^[\s]+/,'').replace(/[\s]+$/,'').replace(/[\s]{2,}/,' ');						     
	 if(comment.length>maxValue)
	 {
		  alert('Too much data in the text box!you can enter upto 2000 characters');
		  return false;
	 }
	 else
	 {
		  comment= encodeMyHtml(comment); 
		  //document.getElementById(id).value=''; 			        		    
		  if(comment!="")
		  {	        
			  //Recaptcha.ajax_verify(validateCaptcha);
			  
			  var response = Recaptcha.get_response();
			  var challenge = Recaptcha.get_challenge();
			  var isValidCaptcha = TrustnetX.Controls.ArticleComment.ValidateRecaptcha(RequestIp, challenge, response, MachineLocation);
			  isValidCaptcha = isValidCaptcha.value;
			  if(isValidCaptcha.indexOf("true") != -1)
			  {
				   $(id).value=''; 								  
				   $('commentText').value=comment; 				    
				  var url=document.URL;
				  if(url.indexOf('#') != -1)
				  {
						url=url.substring(0,url.indexOf('#'));
				  }
				  url=url+'&sValue=1';
				  
			    //Check Comment Alert
			    if(document.getElementById('commentAlert').checked)
                {
                    document.getElementById('mailAlert').value=true;      
                }
                else
                {
                    document.getElementById('mailAlert').value=false;      
                }
				document.masterForm.action=url;
				document.masterForm.submit();
			  }
			  else
			  {
						 alert('The security code you entered did not match. Please try again.');
					Recaptcha.reload();
					 $('recaptcha_error').style.display = 'block';
			  }
		  }else
		  {
			  alert('Please enter the comment');				
		  }	
		}
  }
}
   			    	
function encodeMyHtml(comment) {
	contents=new String(comment);
	contents=contents.replace(/</g,'&lt;');
	contents=contents.replace(/>/g,'&gt;');            
	return contents;
} 

function validateCaptcha(data)
{
  if (data['is_correct']) 
  { 
  alert("correct");
  } 
  else 
  { 
     alert('The security code you entered did not match. Please try again.'); 
     Recaptcha.reload('r'); 
     return false; 
  } 
}

//  Function to show Alias Name information box
function ShowAliasNameInformation(DivID)
{    if($(DivID).style.visibility=='hidden')
     {
	     $(DivID).style.visibility="visible";
	     $("AliasNameIFrame").style.visibility="visible";
	     $(DivID).style.zIndex = "2000";
	 }else
	 {
	     $(DivID).style.visibility="hidden";
	     $("AliasNameIFrame").style.visibility="hidden";	    
	 }
	return false;
}

//  Function to hide Alias Name information box		
function HideAliasNameInformation(DivID)
{
	 $(DivID).style.visibility="hidden";
	 $("AliasNameIFrame").style.visibility="hidden";	
}


//Function to create Login div while posting comment
function CreateLogInDiv()
{  
    var refUrl=referUrl;      
    refUrl =refUrl.replace('&','%26');               
    var strDiv="";   
    strDiv+='<div style="visibility:hidden;width:390px;left:450px;Z-index=1000;position: absolute;height:auto;background-color:#fff;" id="loginDiv" >';   
    strDiv+='<table cellpadding="0" cellspacing="0" style="border:solid 1px #5A8FBC;background-color:#fff;">';
    strDiv+='<tr style="height: 23px; cursor:move;  background: url(/images/bgMainMenuActive.gif) repeat-x;"><td style="width: 100%;text-align: left; border-bottom: solid 1px #a7c7e7;padding-left: 6px;color:#fff;"><b>Login</b></td><td align="right" style="border-bottom: solid 1px #a7c7e7;padding-right:6px;"><a href="javascript:ClosLogDiv();" alt="close" style="color:#fff;">&nbsp;<b>X</b>&nbsp;</a></td></tr>';
    strDiv+='<tr>';
    strDiv+='<td align="center" colspan="2" style="padding:3px;"><img src="/images/Login_image.png" alt="Lock" /></td></tr>';
    strDiv+='<tr><td colspan="2" style="font-size:15px;padding-bottom:10px;color:#1A5083;" align="center"><b>Sorry, you must be logged in to use this feature</b></td></tr>';
     strDiv+='<tr><td style="padding-left:40px; width:190px;"><table border="0" cellpadding="0" cellspacing="0"><tr><td style="width:30%"><img src="/images/icon_lock.png" alt="login" /></td><td style="width:50%"><span style="font-weight:bold;color:#1A5083;font-size:14px;float:left"><a href="/Tools/Portfolio/PortfolioLogin.aspx?url='+refUrl+'">Login</a></span></td></tr></table></td>';
    strDiv+='<td style="padding-right:40px;width:190px;"><table border="0" cellpadding="0" cellspacing="0"><tr><td style="width:30%"><img src="/images/Register.png" alt="register" /></td><td style="width:50%"><span style="font-weight:bold;color:#1A5083;font-size:14px;"><a href="/Tools/Portfolio/PortfolioRegister.aspx">Register</a></span></td></tr></table></td></tr>';        
     strDiv+='</table>';     
     strDiv+='</div>';
     return strDiv;   
}

//Functio to close the Login Div
function ClosLogDiv()
{
      $('loginDiv').style.visibility='hidden';
}

//Display LoginDiv While unlogged user posting comment
function ShowLogInDiv()
{
    var pos;
    var top;
    var left;
    var browserName=window.navigator.userAgent;
    pos=getPosition("readerimg");
    if(pos.x==0 && pos.y==0)
    {
        pos=getPosition("txtComment");
        top=parseInt(pos.y);
        left=parseInt(pos.x);
          $("FooterMailDiv").innerHTML=CreateLogInDiv();
        if(browserName.indexOf("MSIE 7.0")>=0)
        {	
	        $('loginDiv').style.top=top;
	         $('loginDiv').style.left=left+60;				    
        }else if(browserName.indexOf("MSIE 6.0")>=0) 
        {
	         $('loginDiv').style.top=top+10;			    	 
	         $('loginDiv').style.left=left+60;
        } else
        {
	        $('loginDiv').style.top=(top+10)+"px";
	        $('loginDiv').style.left=(left+60)+"px";			  
        }
        
    }else
    {
        top=parseInt(pos.y);
        left=parseInt(pos.x);
          $("FooterMailDiv").innerHTML=CreateLogInDiv();
        if(browserName.indexOf("MSIE 7.0")>=0)
        {	
	        $('loginDiv').style.top=top+50;
	         $('loginDiv').style.left=left-150;				    
        }else if(browserName.indexOf("MSIE 6.0")>=0) 
        {
	         $('loginDiv').style.top=top+50;			    	 
	         $('loginDiv').style.left=left-150;
        } else
        {
	        $('loginDiv').style.top=(top+50)+"px";
	        $('loginDiv').style.left=(left-150)+"px";			  
        }
    }       
    $('loginDiv').style.visibility='visible';   
}

//Function for Feedback div in LPwrapper control
function CreateFeedBackDiv()
{
    var divHtml='<div id="feedbackDiv" style="visibility:hidden;left:632px;top:681px;Z-index=1000;position: absolute;width:150px;background-color:#A50500;">';
    divHtml+='<table border="0" cellpadding="2" cellspacing="0">';
    divHtml+='<tr><td style="padding-left:25px;font-weight:bold;"><a href="javascript:SendFeedBack(\'A\');" style="color:#FFFFFF;">Very useful</a></td></tr>';
    divHtml+='<tr><td style="padding-left:25px;font-weight:bold;"><a href="javascript:SendFeedBack(\'B\');" style="color:#FFFFFF;">Quite useful</a></td></tr>';
    divHtml+='<tr><td style="padding-left:25px;font-weight:bold;"><a href="javascript:SendFeedBack(\'C\');" style="color:#FFFFFF;">I`m indifferent</a></td></tr>';
    divHtml+='<tr><td style="padding-left:25px;font-weight:bold;"><a href="javascript:SendFeedBack(\'D\');" style="color:#FFFFFF;">Not very useful</a></td></tr>';
    divHtml+='<tr><td style="padding-left:25px;font-weight:bold;"><a href="javascript:SendFeedBack(\'E\');" style="color:#FFFFFF;">Useless</a></td></tr>';
    divHtml+='</table></div>';
    
    return divHtml;
}

 function SendFeedBack(rateValue)
{
   var upDateStatus=TrustnetX.Controls.TNUK.LPWrapperControl.UpDateFeedBack(feedBackUserId,rateValue,ipAddress);				    				    
   if(upDateStatus)
   {
      $('feedbackDiv').style.visibility='hidden';      
      $('feedback').style.display='none';
      $('feedReply').style.display='block';
   }
}

function ShowFeedBackDiv()
{    
    if($('feedbackDiv')==null)
    {
        $("FooterMailDiv").innerHTML=CreateFeedBackDiv();
    }
     if($('feedbackDiv').style.visibility=='hidden')
      {        
        var pos;
        var top;
        var left;
        var browserName=window.navigator.userAgent;
       
        pos=getPosition("feedback");
        top=parseInt(pos.y);
        left=parseInt(pos.x);          
        if(browserName.indexOf("MSIE 7.0")>=0)
        {	
            $('feedbackDiv').style.top=top+20;
            $('feedbackDiv').style.left=left+3;				    
        }else if(browserName.indexOf("MSIE 6.0")>=0) 
        {
             $('feedbackDiv').style.top=top+20;			    	 
             $('feedbackDiv').style.left=left+3;
        } else
        {
            $('feedbackDiv').style.top=top+20+"px";
            $('feedbackDiv').style.left=left+3+"px";			  
        }   
        $('feedbackDiv').style.visibility='visible';
      }else if($('feedbackDiv').style.visibility='visible')
      {
         $('feedbackDiv').style.visibility='hidden';
      }    
}

function CloseFeedBackDiv()
{
    if($('feedbackDiv').style.visibility='visible')
      {
         $('feedbackDiv').style.visibility='hidden';
      }    
}

//Function to create popup div for hints
function CreatePopUpDiv(divId)
{   
    var displayText=""; 
    var displayTitle="";          
    if(divId=="peerDiv")
    {
        displayText="For every fund managed by a fund manager, we take its sector average, and combine them over the periods that each of the funds has been managed. The calculation is achieved by constructing an artificial portfolio, as if you had bought and sold all of the sector averages relating to the manager`s funds during the period he/she has managed them. The weighting of each sector relating to each fund is equal, but is halved if the related fund is co-managed. Any periods where we have no record of fund manager performance is treated as a flat period.";
        displayTitle="Peer group composite";
    }else if(divId=="verdictDiv")
    {
        displayText="The Trustnet Verdict is a programmatically driven word generator which uses a number of key quantitive variables to create a verdict. As with the Alpha Manager Ratings, the variables are - alpha over the manager&lsquo;s career, length of track record, outperformance over a number of periods, and performance in up- and down-markets. Note that the periods used may not exactly correspond to the calendar annual periods shown in the Factsheet. The Verdict is entirely mechanical and quant-driven, so does not represent any judgment or opinion or recommendation on Trustnet&lsquo;s part.";
        displayTitle="Trustnet verdict";
    }else if(divId=="alphaRollingDiv")
    {
        displayText="Why do we use Alpha? Because alpha is what a fund manager generates over and above the market returns, once the market effects on performance have been removed. It reflects the ability of the manager to stockpick.";
        displayTitle="Rolling Alpha Quartile";
    }else if(divId=="contributionChartDiv")
    {
        displayText="Contribution tells you the amount of performance contribution each holding has made to the overall portfolio performance, over a given time period. This contribution is determined by the performance of the fund and the weight of the fund in the portfolio.";
        displayTitle="Contribution chart";
    }else if(divId=="houseStyleDiv")
    {
        displayText="To what extent are the fund managers at this group free to run money without restriction from position limits, risk or other top down controls.";
        displayTitle="House style";
    }
    
    var strDiv="";   
    strDiv+='<div style="visibility:hidden;width:390px;left:450px;Z-index=1500;position: absolute;height:auto;background-color:#fff;" id="'+divId+'" >';   
    strDiv+='<table cellpadding="0" cellspacing="0" style="border:solid 1px #5A8FBC;background-color:#fff;">';
    strDiv+='<tr style="height: 23px; cursor:move;  background: url(/images/bgMainMenuActive.gif) repeat-x;"><td style="width: 100%;text-align: left; border-bottom: solid 1px #a7c7e7;padding-left: 6px;color:#fff;"><b>'+displayTitle+'</b></td><td align="right" style="border-bottom: solid 1px #a7c7e7;padding-right:6px;"><a href="javascript:ClosPopUpDiv(\''+divId+'\');" alt="close" style="color:#fff;">&nbsp;<b>X</b>&nbsp;</a></td></tr>';
    strDiv+='<tr>';
     strDiv+='<td style="padding-left:5px;">'+displayText+'</td></tr>';
     strDiv+='</table>';     
     strDiv+='</div>';     
     return strDiv;   
}

//Display popup div for hints
function ShowPopUpDiv(id,divId)
{
    var pos;
    var top;
    var left;
    var browserName=window.navigator.userAgent;
    pos=getPosition(id);
    if(pos.x==0 && pos.y==0)
    {
        pos=getPosition("txtComment");
        top=parseInt(pos.y);
        left=parseInt(pos.x);
          $("FooterMailDiv").innerHTML=CreatePopUpDiv(divId);
        if(browserName.indexOf("MSIE 7.0")>=0)
        {	
	        $(divId).style.top=top;
	         $(divId).style.left=left;				    
        }else if(browserName.indexOf("MSIE 6.0")>=0) 
        {
	         $(divId).style.top=top;			    	 
	         $(divId).style.left=left;
        } else
        {
	        $(divId).style.top=top+"px";
	        $(divId).style.left=left+"px";			  
        }
        
    }else
    {
        top=parseInt(pos.y);
        left=parseInt(pos.x);
          $("FooterMailDiv").innerHTML=CreatePopUpDiv(divId);
        if(browserName.indexOf("MSIE 7.0")>=0)
        {	
	        $(divId).style.top=top;
	         $(divId).style.left=left;				    
        }else if(browserName.indexOf("MSIE 6.0")>=0) 
        {
	         $(divId).style.top=top;			    	 
	         $(divId).style.left=left;
        } else
        {
	        $(divId).style.top=top+"px";
	        $(divId).style.left=left+"px";			  
        }
    }       
    $(divId).style.visibility='visible';   
}

//Function to close the Popup Div
function ClosPopUpDiv(divId)
{
     $(divId).style.visibility='hidden';
}

function PortfolioPopupContent(pos,id,dispText)
{
    var backUrl='';
    var posTop=pos.y;
    var posLeft=pos.x+pos.w+5;
    var windowWidth=window.innerWidth;
    var windowHeight=window.innerHeight;
    if(windowWidth==null || windowWidth==0)
    {
        windowWidth=document.documentElement.clientWidth;
    }
    if(windowHeight==null || windowHeight==0)
    {
        windowHeight=document.documentElement.clientHeight;
    }
    if((posLeft+99)>windowWidth)
    {
        posLeft=posLeft-125;
    }
    posLeft=posLeft-80;
    posTop=posTop+25;
    var popupContent='<iframe id="PortfolioPopupFrame" src="" height="40" frameborder="0" scrolling="no" style="z-index:2000;width: 99px;  visibility: visible;position: absolute; top: '+posTop+'px; left: '+posLeft+'px;" ></iframe>';
    popupContent+='<div id="PortfolioPopup'+id+'" name="PortfolioPopup" style="z-index:2000;visibility: visible; background-repeat: repeat-y; background-image: url(/Images/table_middle_transparent.gif); top: '+posTop+'px; position: absolute; width: 99px; left: '+posLeft+'px;" onmouseover="javascript:$(\'isPortfolioClose\').value=\'false\';" onmouseout="javascript:$(\'isPortfolioClose\').value=\'true\';setTimeout(\'CloseBasket(\\\''+id+'\\\')\',2000); ">';
    popupContent+='<div style="background-image: url(/Images/table_top_transparant1.gif); background-repeat: no-repeat; background-position: left top;width:99px;">';
    popupContent+='<div style="padding:  0px 0px 0px 0px; background-image: url(/Images/table_bottom_transparent1.gif); background-repeat: no-repeat; background-position: left bottom;width:99px;">'
    popupContent+='<table cellpadding="0" cellspacing="0" border="0" width="100%">';
    popupContent+='<tbody>';
    popupContent+='<tr style="height: 10px;">';
    popupContent+='<td style="padding-left: 6px; border-bottom: #a7c7e7 1px solid; text-align: left">';
    popupContent+='<b style="color:#006BBC; font-size:12px;">'+dispText+'</b>';
    popupContent+='</td>';
    popupContent+='<td align="right" style="padding-right: 4px; padding-left: 0px; padding-bottom: 0px; margin: 5px 0px; width: 20%; padding-top: 0px; border-bottom: #a7c7e7 1px solid; text-align: right">';
    popupContent+='<b onclick="javascript:$(\'isPortfolioClose\').value=\'true\';ClosePortfolio(\''+id+'\');" title="Close" id="BCloseL" style="cursor: pointer; font-size: 16px; color: #006BBC;">X</b>';    
    popupContent+='</td>';
    popupContent+='</tr>';
    popupContent+='<tr height="20">';
    popupContent+='<td colspan="2" align="center" id="">';
    
    popupContent+='<b><span id="td_TypeName">Saved</span></b><br/>';
    popupContent+='</td>';
    popupContent+='</tr>';        
    popupContent+='</tbody>';
    popupContent+='</table>';
    popupContent+='<input type="hidden" id="isPortfolioClose" name="isBasketClose" value="true" />';
    
    popupContent+='</div>';
    popupContent+='</div>';
    popupContent+='</div>';
    return popupContent;    
}


function PortfolioPopup(visibleType,id,dispText)
{    
    if(visibleType=="visible")
    {
        $("FooterPortfolioDiv").innerHTML=PortfolioPopupContent(getPosition(id),id,dispText);        
        setTimeout("ClosePortfolio('"+id+"')",2000);
    }
    else
    {
        ClosePortfolio(id);
    }
}


function UpdateFundList(id,univ,isCost,text,eleId,dispText)
   { 	
    var typecode=id.substring(4,id.length);      
     clearInterval(x);
	var quantity= $("quantity"+typecode).value;
	var rowGuid= $("quantity"+typecode).name.replace("Quantity","");
	
	//var pid=port.value;	
	var CostValue= $("PD"+typecode);
	var pCost=CostValue.value;
	var fundcurrency= $("curr"+typecode).innerHTML;
	var currency='GBP';
	var hdnCost= $("hdnPD"+typecode).value;
	
	if(quantity=='')quantity=0;	
	if(pCost=='')pCost=0;	
	 var costV='';
	 if(isCost==1)
	 {
	 costV='1';
	 }
	 else
	 {
	  costV='0';
	 }
	 var pDate='';
	 if( $("cost"+typecode+"_"+univ))
	 {
	  pDate= $("cost"+typecode+"_"+univ).value;		 
	 }	

	 var isValid=true;
	 if(chkNumeric(CostValue) == false || chkNumeric( $("quantity"+typecode))==false)
	 {
	  quantity='0'
	  pCost ='0';
	  isValid=false;
	 }
	  if(quantity=='.')
	  {
	  quantity='0'
	  isValid=false;
	  }
	  if(CostValue.value=='.')
	  {	   	  
	   	  pCost ='0';
	   	  isValid=false;
	  }	  
	 
	if(isValid)
	{	    
	 PortfolioUpdateFundList(typecode,pDate,quantity,fundcurrency,currency,costV,pCost,rowGuid,port,userValue);  
	}
	PortfolioPopup('visible',eleId,dispText);
	//document.getElementById("update"+typecode).style.display="none";
	$("tr"+typecode).className= $("tr"+typecode).className.replace("Red");
	clearInterval(x);
}

function UpdateCashList(id,eleId,dispText)
{
  var typecode=id;
  window.clearInterval(x);
  var quantity= $("balance"+typecode).value;
  //var rowGuid=document.getElementById("quantity"+typecode).name.replace("Quantity","");	
  //var pid=port.value;	
  var name='';
  if( $(typecode)) name= $(typecode).value;
  if(name=='') name= $('name'+typecode).innerHTML;	
  var isValid=true;
  if(chkNumeric( $("balance"+typecode)) == false || quantity=='.' )
  {
  quantity='0'	  
  isValid=false;
  }
  if(isValid)
  {
	var fundcurrency= $("curr"+typecode).options[ $("curr"+typecode).selectedIndex].text;
	var AccType= $("acc"+typecode).options[ $("acc"+typecode).selectedIndex].text;
	var currency='GBP';
    CashUpdateList(typecode,quantity,fundcurrency,currency,AccType,name,port,userValue); 				
  }	 
   PortfolioPopup('visible',eleId,"Cash");
  // document.getElementById("update"+typecode).style.display="none";
   $("tr"+typecode).className= $("tr"+typecode).className.replace("Red");
   window.clearInterval(x);
}

function Doc_Resize()
{
	placeAdPositions();
	PlaceRegisterScreen();
}
	
function PlaceRegisterScreen()
{
	if($('regBlock'))
	{
		var isMainDiv = 0;
		var pos = getPosition('main');
		var top = parseInt(pos.y);
		var left = parseInt(pos.x) + 160;
		var width = overlayWidth;

		if($('QuickSearchStyle')) { top += 90; }
      
      var regBlockStyle = ($('regBlock').style) ? $('regBlock').style : $('regBlock');
		regBlockStyle.left = left + "px";
		regBlockStyle.top = top + "px";
		
		if($('contentPage'))
			regBlockStyle.height = $('contentPage').offsetHeight + "px";
		if($('main'))
			regBlockStyle.height = $('main').offsetHeight + "px";
		
		var regScreenStyle = ($('regScreen').style) ? $('regScreen').style : $('regScreen');
		regScreenStyle.left = left + "px";
		regScreenStyle.top = (top + 55) + "px";
		
		if(width != '' && width != '0')
		{
			regBlockStyle.width = width + "px";
			regScreenStyle.width = width + "px";
		}
	}
}

function getIEVersion()
{
   var rv = -1; // Return value assumes failure.
   if (navigator.appName == 'Microsoft Internet Explorer')
   {
      var ua = navigator.userAgent;
      var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
      if (re.exec(ua) != null)
         rv = parseFloat( RegExp.$1 );
   }
   return rv;
}


function moveAdToPositionX(pos) {
   var box = "adPos_" + pos;
   var container = "adContainer_" + pos;
   var src = $(container);
   var dest = $(box);
   if(src && dest) {
		src.style.width = dest.offsetWidth;
		src.style.textAlign = (pos == "Top") ? "Right" : (pos == "Top3" ? "Center" : "");
		src.style.display = "inline";
		src.className="noPrint";
		if(pos == "Position1") {
			dest.style.width=src.offsetWidth+"px";
			dest.style.width="300px";
			
		}
        
        var ver = getIEVersion();
        if ( ver<= -1 || ver>= 8.0 )
        {
            var position = getPosition(box);
	        src.style.position = "absolute";
	        src.style.left = parseInt(position.x)+"px";
	        var top= parseInt(position.y);
	        if(pos=="TopRight")
	        {
	            top+=50;
	        }
	        src.style.top = top+"px";
            dest.style.height = src.offsetHeight+"px";
        }
        
        dest.replaceChild(src,dest.childNodes[0]);
		var eyeDiv = $("eyeDiv");
		if(eyeDiv){
			eyeDiv.className += eyeDiv.className.indexOf("noPrint") >= 0 ? "" : "noPrint";			
		}
   }
}

function moveAdPos(pos,box,container) {
   var src = $(container);
   var dest = $(box);
      
   if(src && dest) {
      var position = getPosition(box);
      src.style.left = parseInt(position.x)+"px";
          var top=parseInt(position.y);
	        if(pos=="TopRight")
	        {
	            top+=50;
	        }
      src.style.top = top+"px";
      dest.style.height = src.offsetHeight+"px";
      if(pos == "Position1") {
	        dest.style.width=src.offsetWidth+"px";
	        dest.style.width="300px";
	        
      }      
   }
}

function placeAdPositions() {
	if(OAS_listpos && OAS_listpos != "") {
		var arrAdPos = new Array()
		arrAdPos = OAS_listpos.split(',');
		for(var i=0; i<arrAdPos.length; i++) {
			var pos = arrAdPos[i];
			if(pos != "") {
				moveAdPos(pos,"adPos_" + pos,"adContainer_" + pos);
			}
		}
	}
}

function floatingAds(div, position) {
	div.style.left = parseInt(position.x)+"px";
	div.style.top = parseInt(position.y)+"px";
}


/************** Tabbed basket popup function starts here ***************/

function AddFundToBasket(typecode)
{
	var basketCookieName = "shortlisted";
	var basketOverriden = false;
	var overrideBasketElem = $('overrideBasketCookie');

	if(overrideBasketElem && overrideBasketElem.value != "") 
	{
		basketCookieName = overrideBasketElem.value;
		basketOverriden = true;
	}

   var value = GetCookie(basketCookieName);
	var count=$("NoOfShortListedItems");
	var isCodeRemoved = false;
	   
   if(value != "")
   {
	   var farray = new Array();
	   farray = value.split(',');

	   if(!IsStringFoundInArray(farray, typecode))
	   {
		  value += ","+typecode;			
		  if(count!=null && !basketOverriden){
			count.innerHTML="("+((parseInt(farray.length))+1)+")";              
		  }
	   }
	   else
	   {
		   DeleteFromShortlist(typecode, basketCookieName);
		   if(!basketOverriden){
				DeleteFromShortlist(typecode, "TN_RetainSelected");
			}
		   value = GetCookie(basketCookieName);			
		   if((farray.length-1)!=0){
				if(count!=null && !basketOverriden){
					count.innerHTML="("+(farray.length-1)+")";	
				}		   
		   }
		   else{
				if(count!=null && !basketOverriden){
					count.innerHTML="(0)";
				}
		   }
		   isCodeRemoved = true;
	   }
   }
   else
   {
	   value = typecode;
	   if(count != null && !basketOverriden){
			count.innerHTML="(1)";
	   }
   }
   
   if(!isCodeRemoved)
   {
	   SetCookie(basketCookieName, value, 123231);
	   retainSelectedVal(typecode);
   }
   else
   {
	   DeHighlightRows(typecode);
   }
   	
	HighLightSelectedRows();
}

function AddFundToPortfolio(typecode,addOrRemoveFund)
{
   var count=$("NoOfPortfolioItems");

	var eleBasketPId = $('basketDD');
	var selectBoxPId = $('basketDD') ? $('basketDD').options[$('basketDD').selectedIndex].value : '';
	var isCodeRemoved = false;
	if(selectBoxPId=='') selectBoxPId=pId;
	if(addOrRemoveFund=='add')
	{
		PorttypeCodes += (PorttypeCodes != "") ? ","+typecode : typecode;
		AddPortfolioFundDisplay(selectBoxPId,userValue,univValue,typecode);
		SetCookie(userValue+"portfolio", PorttypeCodes, 123231);
		if(count && selectBoxPId==pId)
			count.innerHTML=parseInt(count.innerHTML)+1;
	}
	else if(addOrRemoveFund=='remove')
	{
		DeleteFromShortlist(typecode, userValue+"portfolio");	
		DeleteFromDB(typecode,PorttypeCodes);
		RemovePortfolioFundDisplay(selectBoxPId,userValue,typecode);
		if(count && selectBoxPId==pId)
			count.innerHTML=parseInt(count.innerHTML)-1;
	}
	HighLightSelectedRows();
}

function AddFundToWatchList(typecode,addOrRemoveFund)
{
	var count=$("NoOfWatchlistItems");
	if(addOrRemoveFund=='add')
	{
		WatchtypeCodes += (WatchtypeCodes != "") ? ","+typecode : typecode;
		SetCookie(userValue+"watch", WatchtypeCodes, 123231);		
		AddWatchlistFundDisplay(userValue,univValue,typecode,SiteCode);
		if(count)
			count.innerHTML=parseInt(count.innerHTML)+1;
	}
	else if(addOrRemoveFund=='remove')
	{
		DeleteFromShortlist(typecode, userValue+"watch");
		DeleteFromDB(typecode,WatchtypeCodes);
		RemoveWatchlistFundDisplay(userValue,typecode,SiteCode);
		if(count)
			count.innerHTML=parseInt(count.innerHTML)-1;
	}
	HighLightSelectedRows();
}

function HighLightSelectedRows()
{
	var basketCookieName = "shortlisted";
	var basketOverriden = false;
	var overrideBasketElem = $('overrideBasketCookie');

	if(overrideBasketElem) 
	{
		if(overrideBasketElem.value != "") 
		{
			basketCookieName = overrideBasketElem.value;
			basketOverriden = true;
		}
	}
	
	var typecodelist = GetCookie(basketCookieName);
	if(userId!='')
	{
		if(Mode.toUpperCase()=='PORT')
		{
			typecodelist = ',' + GetCookie(userId+"portfolio") + ',' + PorttypeCodes;
		}
		else if(Mode.toUpperCase()=='WATCH')
		{
			typecodelist = ',' + GetCookie(userId+"watch") + ',' + WatchtypeCodes;
		}
	}
	
	HighLightRows(typecodelist);
}

function CheckAndReturnUniv(paramUniv)
{
	var retUniv='';	
	if(paramUniv!='' && paramUniv.length>0)
	{
		var alphane = paramUniv;
		for(var j=0; j<alphane.length; j++)
		{
			var alphaa = alphane.charAt(j);
			var hh = alphaa.charCodeAt(0);
			if((hh > 64 && hh<91) || (hh > 96 && hh<123))
			{
				retUniv+=alphaa;
			}
 		}
	}
	return retUniv;
}

var PopUpTypeCode='';
var IsTypeCodeInPort=false;
function AddtoShortlist(typeCode)
{
	//PortfolioByUserId(userId);
	
	// This code is to set univValue in search page
	var docURL = document.URL;
	if(univValue=='' && docURL.toLowerCase().indexOf('search.aspx')>0)
	{
		var rowElement = $(typeCode);
		if(rowElement)
		{
			var rowInnerHTML = rowElement.innerHTML;
			var currentOccurance = rowInnerHTML.indexOf('univ=');
			var tempUniv = rowInnerHTML.substring(currentOccurance+5, currentOccurance+7);
			univValue=CheckAndReturnUniv(tempUniv);
		}	
	}
	
	// Common variables for all basket function 
	PopUpTypeCode = typeCode;
	IsTypeCodeInPort=false;
	
	var basketCookieName = "shortlisted";
	var basketOverriden = false;
	var overrideBasketElem = $('overrideBasketCookie');

	if(overrideBasketElem) 
	{
		if(overrideBasketElem.value != "") 
		{
			basketCookieName = overrideBasketElem.value;
			basketOverriden = true;
		}
	}
	
	var portvalue=Mode.toUpperCase();
   var value = GetCookie(basketCookieName);
	var count=$("NoOfShortListedItems");	

	if(portvalue == "PORT")
	{	
		IsTypeCodeInPort=CheckForPortTypeCode(typeCode);
		if(pId!='')
		{	
			if(IsTypeCodeInPort)
			{
				AddFundToPortfolio(typeCode,'remove');
				DisplayBasketPopUp(typeCode,'p','visible');
				ChangePortfolioRow('remove');
			}
			else
			{
				AddFundToPortfolio(typeCode,'add');
				DisplayBasketPopUp(typeCode,'p','visible');
				ChangePortfolioRow('add');
			}
		}
		else
		{	
			DisplayBasketPopUp(typeCode,'p','visible');
		}
   }
	else if(portvalue == "WATCH")
	{
		 if(!IsCodeExistInShortlist(typeCode, userId+'watch'))
		 {
			AddFundToWatchList(typeCode,'add');
	 		//ChangeBasketButtonCaption('watchlist',typeCode,'remove');
		 }
		 else
		 {	
			AddFundToWatchList(typeCode,'remove');
			//ChangeBasketButtonCaption('watchlist',typeCode,'add');
		 }		
		
		//ChangeBasketButtonCaption('watchlist',typeCode,'remove');
		DisplayBasketPopUp(typeCode,'w','visible');
	}
   else
   {
		AddFundToBasket(typeCode);
		DisplayBasketPopUp(typeCode,portvalue=='PRODUCTSEARCH'? 'ps' : 's','visible');
   }
   HighLightSelectedRows(portvalue);
}

function CheckForPortTypeCode(typeCode)
{
	return PorttypeCodes.indexOf(typeCode)>=0 ? true : false;
}

function DisplayBasketPopUp(typeCode, popupType, visibleType)
{		
   if(typeCode!=null && typeCode!='')
   {
       FundByType(typeCode);
   }
    
	if(visibleType=="visible")
   {
		$("FooterBasketDiv").innerHTML=BasketPopupContent(getPosition(typeCode),popupType,typeCode);
      $('curPopup').value=typeCode;
      
      // loading portfolio using webservice for basket dropdown
		PortfolioByUserId(userId);
      
      // Setting default tab
      switch(Mode.toUpperCase())
      {
			case "PORT":
			ChangeBasketTab('Portfolio',typeCode);
			break;
			
			case "WATCH":
			ChangeBasketTab('Watchlist',typeCode);
			break;
			
			default:
			ChangeBasketTab('Basket',typeCode);
			break;      
      }
      //ChangeBasketTab('Basket',typeCode);
				
      //setTimeout("CloseBasket('"+typeCode+"')",4000);
    }
    else
    {
        CloseBasket(typeCode);
    }
}

function CheckForPortfolioRow(lValue)
{
	var portfolioDD=$("basketDD");
	var portfolioRow1 = $("trSelectRow1");
	var portfolioRow2 = $("trSelectRow2");
	var portfolioRow3 = $("trSelectRow3");
	var portfolioRow4 = $("trSelectRow4");	
	
	if(portfolioDD && portfolioDD.options != null && portfolioDD.options[0]!=null &&  portfolioDD.options[0].value!='' && portfolioDD.options[0].text!='Select')
	{
		if(portfolioRow1)
			portfolioRow1.style.display='block';
		if(portfolioRow2)
			portfolioRow2.style.display='block';
		if(portfolioRow3)
			portfolioRow3.style.display='none';
		if(portfolioRow4)
			portfolioRow4.style.display='none';
	}
	else if(typeof(lValue)!='undefined' && lValue=='ws')
	{
		if(portfolioRow1)
			portfolioRow1.style.display='none';
		if(portfolioRow2)
			portfolioRow2.style.display='none';
		if(portfolioRow3)
			portfolioRow3.style.display='block';
		if(portfolioRow4)
			portfolioRow4.style.display='none';
	}
	
//	var selectBoxPId = $('basketDD') ? $('basketDD').options[$('basketDD').selectedIndex].value : '';
//	if(selectBoxPId!='' && lValue=='ws')
//	{
//		CheckTypeCodeInPortfolio(selectBoxPId,PopUpTypeCode);
//		//PopUpTypeCode='';
//	}
}

function IsCodeExistInShortlist(typeCode, cookieName)
{
   var value = GetCookie(cookieName);
	if(value!=null && value!='' && value.indexOf(typeCode)>=0)
	{
		return true;
	}
	else
	{
		return false;
	}
}

function ChangeBasketButtonCaption(tabName, typeCode, displayStatus)
{
	switch(tabName)
	{
		case 'basket':
		case 'product':
			var eleAddRow = $('basketAddRow');
			var eleRemoveRow = $('basketRemoveRow');
	
			if(displayStatus=='add')
			{
				eleAddRow.style.display='block';
				eleRemoveRow.style.display='none';
			}
			else if(displayStatus=='remove')
			{
				eleRemoveRow.style.display='block';
				eleAddRow.style.display='none';	
			}
			else
			{
				eleAddRow.style.display='block';
				eleRemoveRow.style.display='none';
			}
			break;
		case 'portfolio':
			var elePortfolioAddRow = $('portfolioAddRow');
			var elePortfolioRemoveRow = $('portfolioRemoveRow');
			if(displayStatus=='remove')
			{	
				if(elePortfolioAddRow)
					elePortfolioAddRow.style.display='none';
				if(elePortfolioRemoveRow)
					elePortfolioRemoveRow.style.display='block';
			}
			else
			{
				if(elePortfolioAddRow)
					elePortfolioAddRow.style.display='block';
				if(elePortfolioRemoveRow)
					elePortfolioRemoveRow.style.display='none';	
			}
		case 'watchlist':
			var eleAddRow = $('watchlistAddRow');
			var eleRemoveRow = $('watchlistRemoveRow');
	
			if(displayStatus=='add')
			{
				eleAddRow.style.display='block';
				eleRemoveRow.style.display='none';
			}
			else if(displayStatus=='remove')
			{
				eleRemoveRow.style.display='block';
				eleAddRow.style.display='none';	
			}
			else
			{
				eleAddRow.style.display='block';
				eleRemoveRow.style.display='none';
			}
			break;
		default:
			break;
	}
}

function ChangePortfolioRow(updateStatus)
{
	var elePortfolioAddRow = $('portfolioAddRow');	
	var elePortfolioRemoveRow = $('portfolioRemoveRow');
	var elePortfolioCancelRow = $('portfolioCancelRow');
	
	if(updateStatus=='add')
	{
		elePortfolioAddRow.style.display='none';
		elePortfolioCancelRow.style.display='none';
		elePortfolioRemoveRow.style.display='block';

	}
	else if(updateStatus=='remove')
	{
		elePortfolioRemoveRow.style.display='none';
		elePortfolioCancelRow.style.display='none';
		elePortfolioAddRow.style.display='block';		
	}
	else if(updateStatus=='add multiple')
	{
		elePortfolioCancelRow.style.display='block';
		elePortfolioAddRow.style.display='none';
		elePortfolioRemoveRow.style.display='none';
	}
}

function IsTypeCodeInPortfolio(r)
{
	var elePortfolioAddRow = $('portfolioAddRow');
	var elePortfolioRemoveRow = $('portfolioRemoveRow');
	if(r)
	{	
		if(elePortfolioAddRow)
			elePortfolioAddRow.style.display='none';
		if(elePortfolioRemoveRow)
			elePortfolioRemoveRow.style.display='block';
	}
	else
	{
		if(elePortfolioAddRow)
			elePortfolioAddRow.style.display='block';
		if(elePortfolioRemoveRow)
			elePortfolioRemoveRow.style.display='none';	
	}
	IsTypeCodeInPort=r;
}

function HighLightRows(typecodes)
{
	var basketOverriden = false;
	var overrideBasketElem = $('overrideBasketCookie');
	if(overrideBasketElem) {
		if(overrideBasketElem.value != "") {
			basketCookieName = overrideBasketElem.value;
			basketOverriden = true;
		}
	}
	if(typecodes != "")
	{	
	   var Title="basket";    
		var elements = document.getElementsByTagName("TR");
		var typecodeArr = typecodes.split(',');

		for(var i=0;i<elements.length;i++)
		{
			if(!IsStringFoundInArray(typecodeArr, elements[i].id) && (elements[i].className.indexOf("selected") >= 0))
			{
				elements[i].className = elements[i].className.replace("selected","");
				var imgTags = elements[i].getElementsByTagName('IMG');
				for(var j=0;j<imgTags.length;j++)
				{
					if(imgTags[j].src.indexOf("/icons/removeIco.png") >= 0)
					{
						imgTags[j].src = "/icons/icon_plus.png";
						imgTags[j].title = "add to "+Title;
						imgTags[j].width = "16";
						imgTags[j].height = "15";
					}
				}
			}
			if(IsStringFoundInArray(typecodeArr, elements[i].id) && elements[i].className.indexOf(" selected") < 0)
			{
				var imgTags = elements[i].getElementsByTagName('IMG');
				for(var j=0;j<imgTags.length;j++)
				{
					if(imgTags[j].src.indexOf("/icons/icon_plus.png") >= 0)
					{
						imgTags[j].src = "/icons/removeIco.png";
						imgTags[j].title = "remove from "+Title;
						imgTags[j].width = "14";
						imgTags[j].height = "14";
					}
				}
				elements[i].className += " selected";
			}
		}
		elements = document.getElementsByTagName("DIV");
		for(var i=0;i<elements.length;i++)
		{
			if(!IsStringFoundInArray(typecodeArr, elements[i].id) && (elements[i].className.indexOf("bold") >= 0))
			{
				elements[i].className = elements[i].className.replace("bold","");
				var imgTag = $("Img-"+elements[i].id);
				if(imgTag)
				{
					if(imgTag.src.indexOf("/icons/removeIco.png") >= 0)
					{
						imgTag.src = "/icons/icon_plus.png";
						imgTag.title = "add to "+Title;
						imgTag.width = "16";
						imgTag.height = "15";
					}
				}
				var divTag = $("span-"+elements[i].id);
				if(divTag)
				{
				    if(divTag.innerHTML.indexOf('equity') > 0)
				    {
				        divTag.innerHTML = "Add this equity from basket";
				    }
				    else
				    {
					    divTag.innerHTML = "Add this unit to basket";
					}
				}
			}
			if(IsStringFoundInArray(typecodeArr, elements[i].id) && elements[i].className.indexOf(" bold") < 0)
			{
				var imgTag = $("Img-"+elements[i].id);
				if(imgTag)
				{
					if(imgTag.src.indexOf("/icons/icon_plus.png") >= 0)
					{
						imgTag.src = "/icons/removeIco.png";
						imgTag.title = "remove from "+Title;
						imgTag.width = "14";
						imgTag.height = "14";
					}
				}
				var divTag = $("span-"+elements[i].id);
				if(divTag)
				{
				    if(divTag.innerHTML.indexOf('equity') > 0)
				    {
				        divTag.innerHTML = "Remove this equity from basket";
				    }
				    else
				    {
					    divTag.innerHTML = "Remove this unit from basket";
					}
				}
				elements[i].className += " bold";
			}
		}
	}
}

function BasketPopupContent(pos,popupType,typeCode)
{
    var posTop=pos.y;
    var posLeft=pos.x+pos.w+5;
    var windowWidth=window.innerWidth;
    var windowHeight=window.innerHeight;

    if(windowWidth==null || windowWidth==0)
    {
        windowWidth=document.documentElement.clientWidth;
    }

    if(windowHeight==null || windowHeight==0)
    {
        windowHeight=document.documentElement.clientHeight;
    }

    if((posLeft+220)>windowWidth)
    {
        posLeft=posLeft-245;
    }
         
    var popupContent='<iframe id="BasketPopupFrame" src="" height="100" frameborder="0" scrolling="no" style="z-index:2000;width: 220px;  visibility: visible;position: absolute; top: '+posTop+'px; left: '+posLeft+'px;" ></iframe>';
    //popupContent+='<div id="BasketPopup'+typeCode+'" name="BasketPopup" style="z-index:2000;visibility: visible; background-repeat: repeat-y; background-image: url(/Images/newBasketMiddle.gif); top: '+posTop+'px; position: absolute; width: 220px; left: '+posLeft+'px;" onmouseover="javascript:$(\'isBasketClose\').value=\'false\';" onmouseout="javascript:$(\'isBasketClose\').value=\'true\';setTimeout(\'CloseBasket(\\\''+typeCode+'\\\')\',4000);">';
    popupContent+='<div id="BasketPopup'+typeCode+'" name="BasketPopup" style="z-index:2000;visibility: visible; background-repeat: repeat-y; background-image: url(/Images/newBasketMiddle.gif); top: '+posTop+'px; position: absolute; width: 220px; left: '+posLeft+'px;" onmouseover="javascript:$(\'isBasketClose\').value=\'false\';">';
    popupContent+='<div style="background-image: url(/Images/newBasketTop.gif); background-repeat: no-repeat; background-position: left top;">';
    
    if(SiteCode=='TNUK')
    {
        popupContent+='<div style="padding:  0px 16px 20px 10px; ">'
    }
    else
    {
        popupContent+='<div style="padding:  0px 16px 20px 10px; background-image: url(/Images/newBasketBottom.gif); background-repeat: no-repeat; background-position: left bottom;">'
    }
    
    popupContent+='<table cellpadding="0" cellspacing="0" border="0" width="100%">';
    popupContent+='<tbody>';
    popupContent+='<tr style="height: 23px;">';
    popupContent+='<td style="padding-left: 6px; border-bottom: #a7c7e7 1px solid;" colspan="3">';
    popupContent+='<b style="color:#006BBC; font-size:12px;float:left; valign=\'middle\'">Add to</b>';
    popupContent+='<b onclick="javascript:$(\'isBasketClose\').value=\'true\';CloseBasket(\''+typeCode+'\');" title="Close" id="BCloseL" style="cursor: pointer; font-size: 16px; color: #006BBC;float:right">X</b>';    
    popupContent+='</td>';
    popupContent+='</tr>';
        
    if(userId!='')
    {
		 if (popupType=='ps')
		 {	
			popupContent+='<tr height="20" align="center" style="cursor:pointer;">';
			popupContent+='<td id="tabBasket" style="border-bottom: #a7c7e7 1px solid;border-right: #a7c7e7 1px solid;">';
			popupContent+='<b onclick="javascript:ChangeBasketTab(\'Basket\',\''+typeCode+'\');">Product</b>';
			popupContent+='</td>';
		 }
		 else
		 {
		 	popupContent+='<tr height="20" align="center" style="cursor:pointer;">';
			popupContent+='<td id="tabBasket" style="border-bottom: #a7c7e7 1px solid;border-right: #a7c7e7 1px solid;">';
			popupContent+='<b onclick="javascript:ChangeBasketTab(\'Basket\',\''+typeCode+'\');">Basket</b>';
			popupContent+='</td>';		 
		 }
		 popupContent+='<td id="tabPortfolio" style="border-bottom: #a7c7e7 1px solid;border-right: #a7c7e7 1px solid;">';
		 popupContent+='<b onclick="javascript:ChangeBasketTab(\'Portfolio\',\''+typeCode+'\');">Portfolio</b>';
		 popupContent+='</td>';
		 popupContent+='<td id="tabWatchlist" style="border-bottom: #a7c7e7 1px solid;">';
		 popupContent+='<b onclick="javascript:ChangeBasketTab(\'Watchlist\',\''+typeCode+'\');">Watchlist</b>';
		 popupContent+='</td>';
		 popupContent+='</tr>';
    }
    else
    {
		 popupContent+='<tr height="20" align="center" style="cursor:pointer;">';
		 popupContent+='<td id="tabBasket" style="border-bottom: #a7c7e7 1px solid;">';
		 popupContent+='<b onclick="javascript:ChangeBasketTab(\'Basket\',\''+typeCode+'\');">Basket</b>';
		 popupContent+='</td>';
		 popupContent+='<td id="tabPortfolio" style="border-bottom: #a7c7e7 1px solid;">  ';		 
		 popupContent+='</td>';
		 popupContent+='<td id="tabWatchlist" style="border-bottom: #a7c7e7 1px solid;">    ';
		 popupContent+='</td>';
		 popupContent+='</tr>';
    }
    
    popupContent+='<tr height="25">';
    popupContent+='<td colspan="3" align="center" style="vertical-align:bottom;">';
    popupContent+='<b><span id="td_TypeName">Loading..</span></b>';
    popupContent+='</td>';
    popupContent+='</tr>';
    popupContent+='<tr>';
    popupContent+='<td colspan="3" align="center">';
    
    // Basket tab content starts here
    popupContent+='<table id="tblBasket"  style="display: block;">';
    popupContent+='<tr>';
    popupContent+='<td>';
    //popupContent+=portName;
    popupContent+=' ';
    popupContent+='</td>';
    popupContent+='</tr>';
    popupContent+='<tr height="20" align="center" >';
    popupContent+='<td align="center" style="text-align:centre;">';

	 if (popupType=='ps')
	 {	
		popupContent+='<div id=\'basketAddRow\' style="width: 100%;display: none;">';
		popupContent+='<a href="javascript:AddFundToBasket(\''+typeCode+'\',\'add\');UpdateBasket();ChangeBasketButtonCaption(\'product\',\''+typeCode+'\',\'remove\');" style="text-decoration: underline;"><b>Add</b></a>';
		popupContent+='&nbsp;			             &nbsp;';
		popupContent+='<a href="javascript:$(\'isBasketClose\').value=\'true\';CloseBasket(\''+typeCode+'\');" style="text-decoration: underline;"><b>Cancel</b></a>';
		popupContent+='</div>';
		
		popupContent+='<div id=\'basketRemoveRow\' style="width: 100%;display: none;">';
		popupContent+='<a id=\'basketAddlink\' name=\'basketAddlink\' href="javascript:AddFundToBasket(\''+typeCode+'\');ChangeBasketButtonCaption(\'product\',\''+typeCode+'\',\'add\');" style="text-decoration: underline;"><b>Remove</b></a>';
		popupContent+='&nbsp;			             &nbsp;';
		popupContent+='<a href="javascript:$(\'isBasketClose\').value=\'true\';CloseBasket(\''+typeCode+'\');" style="text-decoration: underline;"><b>Cancel</b></a>';
		popupContent+='</div>';
	 }
	 else
	 {
		 //popupContent+='<td align="center" style="text-align:centre;">';
		 popupContent+='<div id=\'basketAddRow\' style="width: 100%;display: none;">';
		 popupContent+='<a id=\'basketAddlink\' name=\'basketAddlink\' href="javascript:AddFundToBasket(\''+typeCode+'\');ChangeBasketButtonCaption(\'basket\',\''+typeCode+'\',\'remove\');" style="text-decoration: underline;"><b>Add</b></a>';
		 popupContent+='&nbsp;			             &nbsp;';
		 popupContent+='<a href="javascript:$(\'isBasketClose\').value=\'true\';CloseBasket(\''+typeCode+'\');" style="text-decoration: underline;"><b>Cancel</b></a>';
		 popupContent+='</div>';
			
		 popupContent+='<div id=\'basketRemoveRow\' style="width: 100%;display: none;">';
		 popupContent+='<a id=\'basketAddlink\' name=\'basketAddlink\' href="javascript:AddFundToBasket(\''+typeCode+'\');ChangeBasketButtonCaption(\'basket\',\''+typeCode+'\',\'add\');" style="text-decoration: underline;"><b>Remove</b></a>';
		 popupContent+='&nbsp;			             &nbsp;';
		 popupContent+='<a href="javascript:$(\'isBasketClose\').value=\'true\';CloseBasket(\''+typeCode+'\');" style="text-decoration: underline;"><b>Cancel</b></a>';
		 popupContent+='</div>';
		 //popupContent+='</td>';
	 }
	     
    popupContent+='</td>';
    popupContent+='</tr>';
    
    popupContent+='<tr height="20">';
	 popupContent+='<td align="center">';
    popupContent+='<a href="/Tools/Tools.aspx" style="text-decoration: underline;"><b>Back to Tools</b></a>';    
    popupContent+='</td>';
    popupContent+='</tr>';
    popupContent+='</table>';

	 // Portfolio tab content starts here
	 popupContent+='<table id="tblPortfolio"  style="height: 60px; display: none;">';

	 // If portfolio exist display the below two rows
	 popupContent+='<tr id=\'trSelectRow1\' style="display: none;">';
	 popupContent+='<td>';
	 popupContent += '<select id="basketDD" name="basketDD" style="width:144px;" onchange="javascript:ChangeBasketTab(\'Portfolio\',\''+typeCode+'\');"><option value="">Select</option></select>';
	 popupContent+='</td>';
	 popupContent+='</tr>';

 
	 if (popupType=='ProductSearch')
	 {
	 	popupContent+='<tr id=\'trSelectRow2\' height="20" style="display: none;">';
		popupContent+='<td align="center">';
		popupContent+='<a href="javascript:AddFundToPortfolio(\''+typeCode+'\',\'add\');UpdateBasket();$(\'isBasketClose\').value=\'true\';CloseBasket(\''+typeCode+'\');" style="text-decoration: underline;"><b>Cancel</b></a>';
		popupContent+='</td>';
		popupContent+='</tr>';
	 }
	 else
	 {
	 	popupContent+='<tr id=\'trSelectRow2\' height="20" style="display: none;">';
		popupContent+='<td align="center">';
		//	Add and Cancel button
		popupContent+='<div id=\'portfolioAddRow\'  style="width: 100%;display: none;">';
		popupContent+='<a href="javascript:AddFundToPortfolio(\''+typeCode+'\',\'add\');ChangePortfolioRow(\'add\');" style="text-decoration: underline;"><b>Add</b></a>';
		popupContent+='&nbsp;                  &nbsp;';
		popupContent+='<a href="javascript:$(\'isBasketClose\').value=\'true\';CloseBasket(\''+typeCode+'\');" style="text-decoration: underline;"><b>Cancel</b></a>';
		popupContent+='</div>';
		//	Remove and Add multiple button 
		popupContent+='<div id=\'portfolioRemoveRow\'  style="width: 100%;display: none;">';
		popupContent+='<a href="javascript:AddFundToPortfolio(\''+typeCode+'\',\'remove\');ChangePortfolioRow(\'remove\');" style="text-decoration: underline;"><b>Remove</b></a>';
		popupContent+='&nbsp;                  &nbsp;';
		popupContent+='<a href="javascript:AddFundToPortfolio(\''+typeCode+'\',\'add\');ChangePortfolioRow(\'add multiple\');" style="text-decoration: underline;"><b>Add Multiple</b></a>';
		popupContent+='</div>';
		// Remove and Cancel button
		popupContent+='<div id=\'portfolioCancelRow\'  style="width: 100%;display: none;">';
		popupContent+='<a href="javascript:AddFundToPortfolio(\''+typeCode+'\',\'remove\');ChangePortfolioRow(\'remove\');" style="text-decoration: underline;"><b>Remove</b></a>';
		popupContent+='&nbsp;                  &nbsp;';
		popupContent+='<a href="javascript:$(\'isBasketClose\').value=\'true\';CloseBasket(\''+typeCode+'\');" style="text-decoration: underline;"><b>Cancel</b></a>';
		popupContent+='</div>';
		popupContent+='</td>';
		popupContent+='</tr>';
	 }
	
   // If no portfolio exist display this block.
	popupContent+='<tr id=\'trSelectRow3\' height="20"  style="display: none;" >';
	popupContent+='<td align="center">';
	popupContent+='No portfolio exist. <a href="/Tools/Portfolio/ManagePortfolio.aspx" style="text-decoration: underline;">Click here</a> to create a new portfolio.';
	popupContent+='</td>';
	popupContent+='</tr>';

	popupContent+='<tr id=\'trSelectRow4\' height="20"  style="display: block;" >';
	popupContent+='<td align="center">';
	popupContent+='Loading Portfolio...';
	popupContent+='</td>';
	popupContent+='</tr>';
		 
	popupContent+='<tr height="20">';
	popupContent+='<td align="center">';
   popupContent+='<a href="/Tools/Portfolio/Valuation.aspx" style="text-decoration: underline;"><b>Back to Portfolio</b></a>';    
   popupContent+='</td>';
   popupContent+='</tr>';
   popupContent+='</table>';
    
   // Watchlist tab content starts here
   popupContent+='<table id="tblWatchlist"  style="display: none;">';
   popupContent+='<tr>';
   popupContent+='<td> ';
   popupContent+='</td>';
   popupContent+='</tr>';
   popupContent+='<tr height="20">';
   popupContent+='<td align="center">';

   popupContent+='<div id=\'watchlistAddRow\' style="width: 100%;display: none;">';
   popupContent+='<a id=\'watchListAddLink\' href="javascript:AddFundToWatchList(\''+typeCode+'\',\'add\');ChangeBasketButtonCaption(\'watchlist\',\''+typeCode+'\',\'remove\');" style="text-decoration: underline;"><b>Add</b></a>';
   popupContent+='&nbsp;			             &nbsp;';
	popupContent+='<a href="javascript:$(\'isBasketClose\').value=\'true\';CloseBasket(\''+typeCode+'\');" style="text-decoration: underline;"><b>Cancel</b></a>';
   popupContent+='</div>';
    
   popupContent+='<div id=\'watchlistRemoveRow\' style="width: 100%;display: none;">';
   popupContent+='<a id=\'watchListAddLink\' href="javascript:AddFundToWatchList(\''+typeCode+'\',\'remove\');ChangeBasketButtonCaption(\'watchlist\',\''+typeCode+'\',\'add\');" style="text-decoration: underline;"><b>Remove</b></a>';
   popupContent+='&nbsp;			             &nbsp;';
	popupContent+='<a href="javascript:$(\'isBasketClose\').value=\'true\';CloseBasket(\''+typeCode+'\');" style="text-decoration: underline;"><b>Cancel</b></a>';
   popupContent+='</div>';
    
   popupContent+='</td>';
   popupContent+='</tr>';
   popupContent+='<tr height="20">';
   popupContent+='<td align="center">';
   popupContent+='<a href="/Tools/Portfolio/Watchlist.aspx" style="text-decoration: underline;"><b>Back to Watchlist</b></a>';    
   popupContent+='</td>';
   popupContent+='</tr>';
   popupContent+='</table>';

    
   popupContent+='</td>';
   popupContent+='</tr>';
   popupContent+='</tbody>';
   popupContent+='</table>';
   popupContent+='<input type="hidden" id="isBasketClose" name="isBasketClose" value="true" />';
   popupContent+='<input type="hidden" id="curPopup" name="curPopup" value="" />';
   popupContent+='</div>';
   popupContent+='</div>';
   
   if(SiteCode=='TNUK')
   {
       popupContent+='<div>';
       popupContent+='<table border="0" cellspacing="0" cellpadding="0" style="width:217px;margin-bottom:-2px;">';
       popupContent+='<tr>';
       popupContent+='<td>';
       popupContent+='<img src="/images/invesco_ad_curve_bottom.gif" alt="" style="width:217px;"/>';
       popupContent+='</td>';
       popupContent+='</tr>';
       popupContent+='<tr>';
       popupContent+='<td>';
       popupContent+='<h3 style="width:216px;margin:0px;background-image: url(/Images/invesco_ad_heading_bg.gif);background-repeat: repeat-x; background-position: left top;text-align:center;color:white;font-size:14px;padding-top:2px;padding-bottom:2px;">Visit <a style="color:white;font-size:14px;" href="/General/Redirect.aspx?url=http%3A%2F%2Fbs.serving-sys.com%2FBurstingPipe%2FadServer.bs%3Fcn%3Dtf%26c%3D20%26mc%3Dclick%26pli%3D1618089%26PluID%3D0%26ord%3D%25%25REALRAND%25%25" target="_blank">microsite</a> to view funds<br/> in this sector</h3>';
       popupContent+='</td>';
       popupContent+='</tr>';
       popupContent+='<tr>';
       popupContent+='<td>';
       popupContent+='<a href="/General/Redirect.aspx?url=http%3A%2F%2Fbs.serving-sys.com%2FBurstingPipe%2FadServer.bs%3Fcn%3Dtf%26c%3D20%26mc%3Dclick%26pli%3D1618083%26PluID%3D0%26ord%3D%25%25REALRAND%25%25" target="_blank"><img src="/images/invesco_ad.png" alt="" /></a>';
       popupContent+='</td>';
       popupContent+='</tr>';        
       popupContent+='</table>';
   }
   popupContent+='</div>';
   popupContent+='</div>';
   return popupContent;
}

function ChangeBasketTab(type,typeCode)
{
    if(type=='ProductSearch')
    {
       type='Basket'; 
    }
    
    var types=new Array('Basket','Portfolio','Watchlist');
    for(var i=0;i<3;i++)
    {
         var tblElement=document.getElementById('tbl'+types[i]);
         var tabElement=document.getElementById('tab'+types[i]);
         if(type==types[i])
         {
            tblElement.style.display='block';
            tabElement.style.color='#006BBC';
         }
         else
         {
            tblElement.style.display='none';
            tabElement.style.color='#000000';
         }
    }
    
	 if(type=='Portfolio')
    {
		if(Mode.toUpperCase()!='PORT')
		{
			CheckForPortfolioRow();
		}
			//SelectCurrentPortfolio();
			var selectBoxPId = $('basketDD') && $('basketDD').selectedIndex!=-1 ? $('basketDD').options[$('basketDD').selectedIndex].value : '';
			if(selectBoxPId!='')
				CheckTypeCodeInPortfolio(selectBoxPId,typeCode);
		
    }
    
    if(type=='Basket')
    {
		var basketCookieName='shortlisted';
		var basketOverriden = false;
		var overrideBasketElem = $('overrideBasketCookie');
		if(overrideBasketElem) {
			if(overrideBasketElem.value != "") {
				basketCookieName = overrideBasketElem.value;
				basketOverriden = true;
			}
		}
		
		if(basketCookieName=='productSearch')
		{
			if(!IsCodeExistInShortlist(typeCode,basketCookieName))
			{
				ChangeBasketButtonCaption('product',typeCode,'add');
			}
			else
			{
				ChangeBasketButtonCaption('product',typeCode,'remove');
			}
		}
		else
		{
			if(!IsCodeExistInShortlist(typeCode,'shortlisted'))
			{
				ChangeBasketButtonCaption('basket',typeCode,'add');
			}
			else
			{
				ChangeBasketButtonCaption('basket',typeCode,'remove');
			}
		}
    }
    if(type=='Watchlist')
    {
		 if(!IsCodeExistInShortlist(typeCode, userId+'watch'))
		 {
	 		ChangeBasketButtonCaption('watchlist',typeCode,'add');
		 }
		 else
		 {	
			ChangeBasketButtonCaption('watchlist',typeCode,'remove');
		 }	
	 }
}

// Webservice method
function PopulateBasketPortfolio(UserPortfolio)
{
	if(UserPortfolio!=null && UserPortfolio!='')
   {
		var portfolioDD=$("basketDD");
           
		// Skip this code when this element doesn't exit	  
		if(portfolioDD)
		{
			portfolioDD.options.length=0;

			for(i=0;i<UserPortfolio.length;i++)
			{
				if(UserPortfolio[i]!=null) 
				{
					var optionElement=document.createElement("option");				 
					if(typeof UserPortfolio[i].PortfolioName !='undefined')
					{
					   if(UserPortfolio[i].PortfolioName!=null && UserPortfolio[i].PortfolioName!='')
						{
							optionElement.text=UserPortfolio[i].PortfolioName;
							optionElement.value=UserPortfolio[i].PortfolioId;
							portfolioDD.options.add(optionElement);
						}
					}
				}
			}
			if(Mode.toUpperCase()=='PORT')
			{
				//CheckForPortfolioRow('ws');
				SelectCurrentPortfolio();
				var selectBoxPId = $('basketDD') ? $('basketDD').options[$('basketDD').selectedIndex].value : '';
				if(selectBoxPId!='')
				{
					//CheckTypeCodeInPortfolio(selectBoxPId,PopUpTypeCode);
					PopUpTypeCode='';
					//CheckTypeCodeInPortfolio(selectBoxPId,'');
				}
			}
		}
		CheckForPortfolioRow('ws');
		//SelectCurrentPortfolio();
	}
}

function SelectCurrentPortfolio()
{
	var elePortDropDown = $('basketDD');
	if(elePortDropDown && pId!='')
	{
		for(i=0;i<elePortDropDown.options.length;i++) 
		{
			if(elePortDropDown.options[i].value==pId) 
			{
				elePortDropDown.options[i].selected = 'selected';
				break;				   
			}
		} 
	}
}

function GetInvCookie(name) {

    if(document.cookie.length==0)
    {   return '';
    } 
    
    var a=document.cookie.match('(^|;) ?'+name+'=([^;]*)(;|$)'); 
    if(a){
    return (unescape(a[2]));
    } 
    else {
    return '';
    } 
}

/********************ContactUs Email*************************/

function RequireCountry()
	{
		if(document.getElementById("CountryCB").value == "Other")
		{
			document.getElementById("CountryT").style.visibility="Visible";
		}
		else	
		{
			document.getElementById("CountryT").style.visibility="hidden";
		}
	}
	function SendContactEmail()
	{		
	    var logUserName=$('logeduserName').value;
	    var commentValue=$('CommentsTA').value;
	    commentValue=commentValue.LTrim();
	    commentValue=commentValue.RTrim();
	    var commnetText=Encodehtml(commentValue);
	    var countryName=$('countryName').value;
        var investorType=$('investorName').value;  
        if(investorType=='')
        {
           investorType=$('investorType').value; 
        } 
        var referedUrl=$('referedUrl').value;   
        var userAgent=navigator.userAgent;
	    var cookieValue=document.cookie;	
	    var designSource=$("mailtemplate").innerHTML;
	    var telePhone = $("Telephone").value;
	    var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	    var email;
	    var uName;
	    if(logUserName=='')
	    {
	        email=$('EmailT').value; 
	        uName=$('NameT').value; 
	        uName=uName.LTrim();
	        uName=uName.RTrim();
	        	    
	        if(email=='')
	        {
	            $('emailId').style.visibility='visible'; 
	            $('mandatory').style.visibility='visible'; 	              
	        }else
	        {	                	                
	                if(!email.match(emailRegEx))
	                {
	                    $('emailId').style.visibility='visible';
	                     $('mandatory').style.visibility='visible'; 
	                    alert('Enter vallid email');
	                    return false;
	                }
	                else
	                {
	                    $('emailId').style.visibility='hidden';
	                     $('mandatory').style.visibility='hidden'; 
	                }
	        }
	        if(countryName=='')
	        {
	            $('country').style.visibility='visible'; 
	            $('mandatory').style.visibility='visible'; 
	            return false;
	            
	        }else
	        {
	            $('country').style.visibility='hidden'; 
	            $('mandatory').style.visibility='hidden';
	        }
	      }
	      else
	      {
	         uName=logUserName;         
	         email=$('userEmail').value;  
	      }  
            if(commnetText=='')
	        {		    			
		        alert("Please enter your comment");			
		        return false;
	        }
	        else if(commnetText.length>4000)
	        {
	            alert("your comment limit is 4000 characters");
		        return false;
	        }
		    else
		    {				
			    $("SendT").value="1";
			    
			    $("btnSend").className = 'buttonNone';			    
			    $('sendStatus').style.visibility='visible'; 
			    $('CommentsTA').value='';
		        $('Telephone').value=''; 			          
		        $('sendStatus').innerHTML="Your feedback has been sent to our email address helpdesk@financialexpress.net";			    			    
		       TrustnetX.About.Contact.SendFeedBackMail(uName,email,countryName,investorType,commnetText,referedUrl,userAgent,cookieValue,telePhone,CallBack);			                    			        
		    }    	
	}
	
	function CallBack(res)
	{
	
	}
	
//	function EnableDisableElement(chValue,elementIds)
//	{
//	    var elementArray=new Array();
//	     elementArray=elementIds.split(',');
//	     for(var i=0;i<elementArray.length;i++)
//	     {
//	        var visibleStatus='hidden';	        
//	        if(chValue=='')
//	        {
//	            visibleStatus='visible';
//	            
//	            if(i>0 && i==elementArray.length-1)
//	            return false;
//	        }
//	        	        
//	        $(elementArray[i]).style.visibility=visibleStatus;
//	     } 
//	}
	
	function ValidateComments(str) {
       if(!ValidateString(str))
		{
			alert('Invalid input, please provide valid input.');
			return false;
		}
		return true;
	} 
     
     function  GetOptionValue(selectId)
     {
         if(document.getElementById(selectId) != null) {
            if(selectId=='countryresidence')
            {               
              document.getElementById('countryName').value=document.getElementById(selectId).value;                
            }else if(selectId=='investorType')
            {
                document.getElementById('investorName').value=document.getElementById(selectId).value;
            }            
         }
     }   
     function Encodehtml(text) {
        
        var textneu = text.replace(/&/g,"&amp;");
        textneu = textneu.replace(/</g,"&lt;");
        textneu = textneu.replace(/>/g,"&gt;");
        textneu = textneu.replace(/\r\n/g,"<br>");
        textneu = textneu.replace(/\n/g,"<br>");
        textneu = textneu.replace(/\r/g,"<br>");
        return(textneu);
    }  
    
       
 // trim blank space at the beginning
 String.prototype.LTrim = function()
 {
 return this.replace(/(^\s*)/g, "");
 }
  
 // trim blank space at the end
 String.prototype.RTrim = function()
 {
 return this.replace(/(\s*$)/g, "");}
 
 //Portfolio Focus function
 function FocusElement(id)
 {
    var idValue=$(id).value;
    if(idValue==0)
    {
       //$(id).select();
       $(id).value='';
    }else
    {
        $(id).focus();
    }    
}       

/************************End contactUs*****************************/

/************************ START POLL ******************************/


function  ShowHidePoll()
{    
    var choiceId=getCheckedValue(document.forms['masterForm'].elements['btnRadio']);
    if(choiceId=='')
    {
        alert('Please choose any one choice');
    }
    else if(pollEnable==1)
    {
       pollEnable=0;
      document.body.style.cursor = 'wait';
      $('pollImg').style.cursor = 'wait';
          var pws = new PortfolioWebService();
          pws.UpdatePollChoice(GetUpdateValues,QuestionId,choiceId);
       SetCookie("TN_Poll", QuestionId,1232);
    }
}
function GetUpdateValues(result)
{
document.body.style.cursor = 'default';
$('pollImg').style.cursor = 'default';
pollChoice=result;	   
var pollString='';
var totalVotes=0;
$('AfterPoll').innerHTML='';

for(i=0;i<pollChoice.length;i++)
{
   totalVotes+=pollChoice[i].SuggestedTotal;   
}	  

if($('AfterPoll').firstChild!=null)
{
    $('AfterPoll').firstChild.nodeValue = '';
}

outerTable=document.createElement("table"); 
outerTable.setAttribute("border","0");
outerTable.setAttribute("cellpadding","0");
outerTable.setAttribute("cellspacing","0");

outerTablebody = document.createElement("tbody");
outerCurrent_row = document.createElement("tr");                
outerCurrent_cell = document.createElement("td");
//outerCurrent_cell.setAttribute("style","padding-right:3px;");

for(i=0;i<pollChoice.length;i++)
{	       
var suggestTotal=pollChoice[i].SuggestedTotal;
var percentage=(suggestTotal/totalVotes)*100;
var imgWidth=(90*suggestTotal)/totalVotes;
var noOfVotes='';

    if(suggestTotal==0){
        imgWidth=0;
        noOfVotes='Nil';
    }else{
        if(suggestTotal>1){noOfVotes=suggestTotal+' votes';}
        else{noOfVotes=suggestTotal+' vote';}
    }
    	    
    myTable=document.createElement("table"); 
    myTable.setAttribute("border","0");
    myTable.setAttribute("cellpadding","0");
    myTable.setAttribute("cellspacing","0");
    
    mytablebody = document.createElement("tbody"); 	                  
    mycurrent_row = document.createElement("tr");                
    mycurrent_cell = document.createElement("td");
    mycurrent_cell.setAttribute("style","padding-left:5px;");
    
    myDiv=document.createElement("div");                
    myDiv.setAttribute("title",noOfVotes);
    if(imgWidth==0){
        myDiv.setAttribute("style","float:left;");               
    }else{
        myDiv.setAttribute("class","pollDiv");
        myDiv.setAttribute("style","width:"+imgWidth+"px;");               
    }
    mycurrent_cell.appendChild(myDiv); 
    
    mySpan=document.createElement("div");
    var roundValue=''+Math.round(percentage)+'%';
    currenttext = document.createTextNode(roundValue);
    mySpan.appendChild(currenttext);
    mySpan.setAttribute("style","padding-left:5px;color:#000000;font-weight:bold;");               
    mycurrent_cell.appendChild(mySpan);                 
                                                                                                                         
    mycurrent_row.appendChild(mycurrent_cell);  
    mytablebody.appendChild(mycurrent_row);

    mycurrent_row1 = document.createElement("tr");
    mycurrent_cell1 = document.createElement("td");
    mycurrent_cell1.setAttribute("class","smallTxt");                   
    currenttext = document.createTextNode(pollChoice[i].ChoiceText);
    mycurrent_cell1.appendChild(currenttext);   
    mycurrent_row1.appendChild(mycurrent_cell1);                                                
    mytablebody.appendChild(mycurrent_row1);    
    myTable.appendChild(mytablebody);
    
    outerCurrent_cell.appendChild(myTable);
    
    borderDiv=document.createElement("div");
    borderDiv.setAttribute("class","topbottomBorder");
    outerCurrent_cell.appendChild(borderDiv);
    
    outerCurrent_row.appendChild(outerCurrent_cell);
    outerTablebody.appendChild(outerCurrent_row);
    outerTable.appendChild(outerTablebody);
    
}	   	             
    total_row=document.createElement("tr");
    total_cell=document.createElement("td");
    total_cell.setAttribute("style","font-weight:bold;padding-left:5px;");
    var totalText='';
    if(totalVotes>0 && totalVotes==1)
    {
        totalText=totalVotes+' vote';
    }else if(totalVotes>0 && totalVotes>1)
    {
        totalText=totalVotes+' votes';
    }
    totalText = document.createTextNode(totalText);
    total_cell.appendChild(totalText);  
    total_row.appendChild(total_cell); 
    outerTablebody.appendChild(total_row);
    outerTable.appendChild(outerTablebody);
    
    OuterBorderDiv=document.createElement("div");
    OuterBorderDiv.setAttribute("class","topbottomBorder");     
    
    $('AfterPoll').appendChild(OuterBorderDiv);
    $('AfterPoll').appendChild(outerTable);
        	    	    	   
    $('BeforePoll').className='displayNone';
    $('AfterPoll').className='displayBlock';
}

function getCheckedValue(radioObj) {
    if(!radioObj)
	    return "";
    var radioLength = radioObj.length;
    if(radioLength == undefined)
	    if(radioObj.checked)
		    return radioObj.value;
	    else
		    return "";
    for(var i = 0; i < radioLength; i++) {
	    if(radioObj[i].checked) {
		    return radioObj[i].value;
	    }
    }
    return "";
}

/************************ END POLL ********************************/

function OpenResearchPage(paramArticleId){
	window.location = "/News/Research.aspx?id=" + paramArticleId;
}

function ChangeHoverRegion(ele, action) {	
	ele.style.backgroundColor = (action=='in') ? '#ecf1f9' : '#FFFFFF';
}

/********************* ANNUITY SEARCH *******************************/
function AssignSpouseGender(genderId){
    var element=$(genderId);
    var spouseGender='Female';
    var gender=element.options[element.selectedIndex].value;
    if(gender=='F'){
        spouseGender='Male';}	        
    $('lblGender').innerHTML=spouseGender;	     
}
	    
function EnableJoint(id){
    var enable=$(id).checked;
    if(enable){
        $('SpouseDetail').style.display='block';	            
    }else{
        $('SpouseDetail').style.display='none';            	            
    }
}
	    
function SearchAnnuity(){	    
    var leadGender=$('ddlGender').options[$('ddlGender').selectedIndex].value;       
    var leadAge=$('txtLeadAge').value;
    var profit=$('ddlProfit').value;
     if(profit=='')
    profit=$('ddlProfit').options[$('ddlProfit').selectedIndex].value;
    
    var product=$('ddlProduct').value;
    if(product=='')
    product=$('ddlProduct').options[$('ddlProduct').selectedIndex].value;
    
    var isJoint=$('ckJoint').checked;
    var spouseAge='';
    var reduction='';
    var impairment=$('ddlImpairment').value;
    if(impairment=='')
    impairment=$('ddlImpairment').options[$('ddlImpairment').selectedIndex].value;
    
    var escalation=$('ddlEscalation').value;
    if(escalation=='')
    escalation=$('ddlEscalation').options[$('ddlEscalation').selectedIndex].value;
    
    var guarantee=$('ddlGuarantee').value;
    if(guarantee=='')
    guarantee=$('ddlGuarantee').options[$('ddlGuarantee').selectedIndex].value;
    
    var purchaseprice=$('txtPurchasePrice').value;	        	        	        
   	        	        
    if(isJoint)
    {
        spouseAge=$('txtSpouseAge').value; 
        reduction=$('ddlReduction').value; 
        
        if(reduction=='')
            reduction=$('ddlReduction').options[$('ddlReduction').selectedIndex].value;
            
        if(spouseAge<35 || spouseAge>90 || isNaN(spouseAge) || spouseAge=='')
        {
            alert('Your spouse age should be in 35 to 90');  
            $('txtSpouseAge').focus();
         }
        else if(leadAge<35 || leadAge>90 || leadAge=='' || isNaN(leadAge))
        {
            alert('Your age should be in 35 to 90');  
            $('txtLeadAge').focus();
        }
        else if(purchaseprice=='' || purchaseprice<5000 || purchaseprice>999999 || isNaN(purchaseprice))
        {
            alert('Purchase price should be in range from 5000 to 999999');  
             $('txtPurchasePrice').focus();
        }
        else
        {                 
            var url=document.URL;   
            if(url.indexOf("?")>0){
                url=url.substring(0,url.indexOf("?"));  
            }                    
            url+="?lGender="+leadGender+"&lAge="+leadAge+"&profit="+profit+"&product="+product+"&joint="+isJoint+"&sAge="+spouseAge+"&reduction="+reduction+"&impair="+impairment+"&escalation="+escalation+"&guarantee="+guarantee+"&pPrice="+purchaseprice;                                              
            document.masterForm.action=url+"&search=1";
            document.masterForm.submit();
         }
    }else{	            
        if(leadAge<35 || leadAge>90 || leadAge=='' || isNaN(leadAge)){
            alert('Your age should be in 35 to 90');  
            $('txtLeadAge').focus();
         }
        else if(purchaseprice=='' || purchaseprice<5000 || purchaseprice>999999 || isNaN(purchaseprice)){
            alert('Purchase price should be in 5000 to 999999');  
            $('txtPurchasePrice').focus();
        }
        else{	                
            var url=document.URL;   
            if(url.indexOf("?")>0)
            {
                url=url.substring(0,url.indexOf("?"));                          
            }     
            url+="?lGender="+leadGender+"&lAge="+leadAge+"&profit="+profit+"&product="+product+"&joint="+isJoint+"&sAge="+spouseAge+"&reduction="+reduction+"&impair="+impairment+"&escalation="+escalation+"&guarantee="+guarantee+"&pPrice="+purchaseprice;                       
            document.masterForm.action=url+"&search=1";
            document.masterForm.submit();	           	           	        	        
        }
    }
}
/********************* END ANNUITY SEARCH *******************************/



/***********************PRINT ICON ON FACTSHEET************************/
 
 function ShowPrintIcon()
 {
 var userId=GetCookie("TN_UserId")             
  if(userId=='')
  {
     var pos;
    var top;
    var left;
    var browserName=window.navigator.userAgent;
    pos=getPosition("printIcon");            
    top=parseInt(pos.y);
    left=parseInt(pos.x);
      $("FooterMailDiv").innerHTML=CreateLogInDiv();
    if(browserName.indexOf("MSIE 7.0")>=0)
    {	
        $('loginDiv').style.top=top;
         $('loginDiv').style.left=left;				    
    }else if(browserName.indexOf("MSIE 6.0")>=0) 
    {
         $('loginDiv').style.top=top+10;			    	 
         $('loginDiv').style.left=left;
    } else
    {
        $('loginDiv').style.top=(top+10)+"px";
        $('loginDiv').style.left=(left)+"px";			  
    }
            
    $('loginDiv').style.visibility='visible';
  }
  else
  {
        var url=document.URL;   
        url+=(url.indexOf("?")>0)?"&print=true":"?print=true"       
        document.masterForm.action=url;
        document.masterForm.submit();	  
            
  }
}
/***********************END******************************************/


/************* Tabbed basket popup function ends here *************/

/************* New approach basket code starts here	**************/

/*
var PopUpTypeCode='';
var PopUpSelecteTab='General';
//var IsTypeCodeInPort=false;
function AddtoShortlist(typeCode)
{
	// This code is to set univValue in search.aspx page
	var docURL = document.URL;
	if(univValue=='' && docURL.toLowerCase().indexOf('search.aspx')>0)
	{
		var rowElement = $(typeCode);
		if(rowElement)
		{
			var rowInnerHTML = rowElement.innerHTML;
			var currentOccurance = rowInnerHTML.indexOf('univ=');
			var tempUniv = rowInnerHTML.substring(currentOccurance+5, currentOccurance+7);
			univValue=CheckAndReturnUniv(tempUniv);
		}
	}

	// Common variables for all basket function 
	PopUpTypeCode = typeCode;
	
	var eleWatchlistDetails = $('completeWatchlistDetail');
	if(eleWatchlistDetails && eleWatchlistDetails.value=='')
	{
		WatchlistByUserId(userId);
	}
	
	var elePortfolioDetails = $('completePortfolioDetail');			
	if(elePortfolioDetails && elePortfolioDetails.value=='')
	{
		PortfolioByUserId(userId);
	}
	
	var portvalue=GetSelectedBasketTab();
	switch(portvalue)
	{
		case "PORT":
			if(pId!='' && !IsTypeCodeInHdnPortfolio(pId,typeCode))
			{
				AddFundToPortfolio(typeCode,'add');
			}
			else if(pId!='' && IsTypeCodeInHdnPortfolio(pId,typeCode))
			{
				AddFundToPortfolio(typeCode,'remove');
			}
			DisplayBasketPopUp(typeCode,'p','visible');
			HighLightSelectedRows('PORT');
			break;
			
		case "WATCH":
			AddFundToWatchList(typeCode, !IsTypeCodeInHdnWatchList(typeCode) && WatchtypeCodes.indexOf(typeCode)<0 ?  'add': 'remove');
			DisplayBasketPopUp(typeCode,'w','visible');
			HighLightSelectedRows('WATCH');
			break;
			
		default:
			AddFundToBasket(typeCode);
			DisplayBasketPopUp(typeCode,'s','visible');
			HighLightSelectedRows('GENERAL');
			break;
	}
}

function GetSelectedBasketTab()
{
	var selectedTab='GENERAL';
	var basketCookieValue = GetCookie("TN_Mode").toUpperCase();
	if(basketCookieValue!='' && basketCookieValue!=null)
	{
		if(basketCookieValue=='PORT')
		{
			var portCookieValue = GetCookie("TN_Portfolio");
			
			if(portCookieValue!='' && portCookieValue!=null)
			{
				pId=portCookieValue;
			}
		}
		else
		{
			pId='';
		}
		selectedTab=basketCookieValue;
	}
	return selectedTab;
}

function SetDefaultBasketTab(basketValue)
{	
	if(basketValue=='PORT')
	{
		var selectBoxPId = $('basketDD') ? $('basketDD').options[$('basketDD').selectedIndex].value : '';
		if(selectBoxPId!='')
		{
			SetCookie("TN_Portfolio", selectBoxPId);
		}
	}
	SetCookie("TN_Mode", basketValue);
}

function IsTypeCodeInHdnPortfolio(paramPortId, typeCode)
{
	var portRowValue = GetHdnPortfolioRowById(paramPortId);
	var portTCode = GetHdnPortfolioValue(portRowValue, 'typecodes');
	return (portTCode!='' && typeof(portTCode)!='undefined' && portTCode.indexOf(typeCode)>=0) ? true : false;
}

function IsDuplicateTypeCodeInHdnPort(paramPortId, typeCode)
{
	var noOfOccurance = 0;
	var portRowValue = GetHdnPortfolioRowById(paramPortId);
	var portTCode = GetHdnPortfolioValue(portRowValue, 'typecodes');
	
	if (portTCode!='' && typeof(portTCode)!='undefined' && portTCode.indexOf(typeCode)>=0)
	{	
		var codeArray = portTCode.split('~');
		for(cnt=0; cnt<codeArray.length; cnt++)
		{
			if(codeArray[cnt]!='' && codeArray[cnt]==typeCode)
			{
				noOfOccurance++;
			}
		}
	}

	return (noOfOccurance>1) ? true : false;
}

function IsPortfolioExist()
{
	var elePortfolioDetails = $('completePortfolioDetail');
	var portStatus = false;
		
	if(elePortfolioDetails && elePortfolioDetails.value!='')
	{
		var portList = elePortfolioDetails.value.split(',');
		for(i=0; i<portList.length; i++)
		{
			var tempPortId = GetHdnPortfolioValue(portList[i],'id');
			if(tempPortId != '')
			{
				portStatus=true;
				break;
			}
		}
	}
	return portStatus;
}

function GetHdnPortfolioValue(paramPortRow, rValue)
{
	var portDetail = paramPortRow.split('|');
	var returnValue = '';
	
	if(portDetail.length>0)
	{
		switch(rValue)
		{
			case 'id':
				returnValue = portDetail[0];	// Portfolio Id from hidden variable
				break;
			case 'name':
				returnValue = portDetail[1];	// Portfolio Name from hidden variable
				break;
			case 'typecodes':
				returnValue = portDetail[2];	// Portfolio Typecodes from hidden variable
				break;
			default:
				var rowCodes = portDetail[2].split('~');
				var typeCodeCount = 0;
				for(codeCnt=0; codeCnt<rowCodes.length; codeCnt++)
				{
					if(rowCodes[codeCnt]!='')
						typeCodeCount++;
				}
				returnValue = typeCodeCount;	// Portfolio Count from hidden variable
				break;
		}
	}
	return returnValue;
}

function GetHdnPortfolioRowById(paramPortId)
{
	var elePortfolioDetails = $('completePortfolioDetail');
	var rowValue = '';
		
	if(elePortfolioDetails && elePortfolioDetails.value!='')
	{
		var portList = elePortfolioDetails.value.split(',');
		for(i=0; i<portList.length; i++)
		{
			if(portList[i].indexOf(paramPortId)>=0)
			{
				rowValue=portList[i];
				break;
			}
		}
	}
	return rowValue;
}

function AddTypeCodeInHdnPortfolio(paramPortId, typeCode)
{
	var elePortfolioDetails = $('completePortfolioDetail');
	var tempPortDetails = '';
	
	if(elePortfolioDetails && elePortfolioDetails.value!='')
	{
		var portList = elePortfolioDetails.value.split(',');
		for(i=0; i<portList.length; i++)
		{
			var tempPortId = GetHdnPortfolioValue(portList[i],'id');
			if(tempPortId == paramPortId)
			{
				var tempPortName = GetHdnPortfolioValue(portList[i],'name');
				var tempPortCodes = GetHdnPortfolioValue(portList[i],'typecodes');
				tempPortCodes += '~' + typeCode;
				var tempPortCount = GetHdnPortfolioValue(portList[i],'count');
				tempPortCount++;
				tempPortDetails += tempPortId + '|' + tempPortName + '|' + tempPortCodes + '|' + tempPortCount + ',';
			}
			else if(tempPortId != '')
			{
				tempPortDetails += portList[i] + ',';
			}
		}
	}
	elePortfolioDetails.value = tempPortDetails;
}

function DeleteTypeCodeFromHdnPortfolio(paramPortId, typeCode)
{
	var elePortfolioDetails = $('completePortfolioDetail');
	var tempPortDetails = '';
	
	if(elePortfolioDetails && elePortfolioDetails.value!='')
	{
		var portList = elePortfolioDetails.value.split(',');
		for(i=0; i<portList.length; i++)
		{
			var tempPortId = GetHdnPortfolioValue(portList[i],'id');
			if(tempPortId == paramPortId)
			{
				var tempPortName = GetHdnPortfolioValue(portList[i],'name');
				var tempPortCodes = GetHdnPortfolioValue(portList[i],'typecodes');				
				//var indexCount = tempPortCodes.indexOf(typeCode);
				tempPortCodes = RemoveSubstring(tempPortCodes, typeCode);
				var tempPortCount = GetHdnPortfolioValue(tempPortId + '|' + tempPortName + '|' + tempPortCodes + '|','count');
				//if(indexCount>=0)
				//	tempPortCount--;
				tempPortDetails += tempPortId + '|' + tempPortName + '|' + tempPortCodes + '|' + tempPortCount + ',';
			}
			else if(tempPortId != '')
			{
				tempPortDetails += portList[i] + ',';
			}
		}
	}
	elePortfolioDetails.value = tempPortDetails;
}

function RemoveSubstring(s, t) 
{
  var indexCount = s.indexOf(t);
  var returnValue = "";
  if (indexCount == -1) return s;
  returnValue += s.substring(0,indexCount) + RemoveSubstring(s.substring(indexCount + t.length), t);
  return returnValue;
}

function PopulateBasketPortfolio(val)
{
	var elePortfolioDetails = $('completePortfolioDetail');
	var portfolioDD=$("basketDD");
	
	if(elePortfolioDetails && val!='' && portfolioDD)
	{
		elePortfolioDetails.value = val;
		var portList = elePortfolioDetails.value.split(',');
		
		if(portList!='' && portList!=null)
			portfolioDD.options.length=0;
		
		for(i=0; i<portList.length; i++)
		{
			var tempPortId = GetHdnPortfolioValue(portList[i],'id');
			var tempPortName = GetHdnPortfolioValue(portList[i],'name');
			
			if(tempPortId!='' && tempPortName!='')
			{
				var optionElement=document.createElement("option");
				optionElement.text=tempPortName;
				optionElement.value=tempPortId;
				portfolioDD.options.add(optionElement);				
			}
			tempPortId = tempPortName = '';
		}
	}
	CheckForPortfolioRow();
	SelectCurrentPortfolio();
	PortfolioSelectOnChange(PopUpTypeCode);
	
//	if(GetSelectedBasketTab()=='PORT')
//		HighLightSelectedRows('PORT');
}

function LoadHiddenWatchList(wListVal)
{	
	var eleWatchlistDetails = $('completeWatchlistDetail');
	if(eleWatchlistDetails)
	{
		eleWatchlistDetails.value = wListVal;
	}
	UpdateWatchlistCount();
	
//	if(GetSelectedBasketTab()=='WATCH')
//		HighLightSelectedRows('WATCH');
}

function SelectCurrentPortfolio()
{
	var elePortDropDown = $('basketDD');
	if(elePortDropDown && pId!='')
	{
		for(i=0;i<elePortDropDown.options.length;i++) 
		{
			if(elePortDropDown.options[i].value==pId) 
			{
				elePortDropDown.options[i].selected = 'selected';
				break;				   
			}
		} 
	}
}

function DisplayBasketPopUp(typeCode, popupType, visibleType)
{		
   if(typeCode!=null && typeCode!='')
   {
       FundByType(typeCode);
   }
    
	if(visibleType=="visible")
   {
		$("FooterBasketDiv").innerHTML=BasketPopupContent(getPosition(typeCode),popupType,typeCode);
      $('curPopup').value=typeCode;
      
      // loading portfolio using webservice for basket dropdown
      var elePortfolioDetails = $('completePortfolioDetail');
      if(elePortfolioDetails && elePortfolioDetails.value=='')
      {
			PortfolioByUserId(userId,typeCode);
		}
		
		var eleWatchlistDetails = $('completeWatchlistDetail');
		if(eleWatchlistDetails && eleWatchlistDetails.value=='')
		{
			WatchlistByUserId(userId);
		}
      
      // Setting default tab
      switch(popupType)
      {
			case "p":
			ChangeBasketTab('Portfolio',typeCode);
			break;
			
			case "w":
			ChangeBasketTab('Watchlist',typeCode);
			break;
			
			default:
			ChangeBasketTab('Basket',typeCode);
			break;
      }
      //setTimeout("CloseBasket('"+typeCode+"')",4000);
    }
    else
    {
        CloseBasket(typeCode);
    }
}


function ChangeBasketTab(type,typeCode)
{
    var types=new Array('Basket','Portfolio','Watchlist');
    for(var i=0;i<3;i++)
    {
         var tblElement=document.getElementById('tbl'+types[i]);
         var tabElement=document.getElementById('tab'+types[i]);
         var divElement=document.getElementById('div'+types[i]+'Default');
         
         if(type==types[i])
         {
            tblElement.style.display='block';
            tabElement.style.color='#006BBC';
            divElement.style.display='block';
         }
         else
         {
            tblElement.style.display='none';
            tabElement.style.color='#000000';
            divElement.style.display='none';
         }
    }
    
    switch(type)
    {
		case 'Portfolio':			
			var elePortfolioDetails = $('completePortfolioDetail');
			PopulateBasketPortfolio(elePortfolioDetails.value);
			HighLightSelectedRows('PORT');
			break;
			
		case 'Watchlist':
			var eleWatchlistDetails = $('completeWatchlistDetail');
			if(eleWatchlistDetails && eleWatchlistDetails.value=='')
			{
				WatchlistByUserId(userId);
			}
			
			if(!IsTypeCodeInHdnWatchList(typeCode))
			{
				ChangeBasketButtonCaption('watchlist',typeCode,'add');
			}
			else
			{
				ChangeBasketButtonCaption('watchlist',typeCode,'remove');
			}
			UpdateWatchlistCount();
			HighLightSelectedRows('WATCH');
			break;
			
		case 'Basket':
			if(!IsCodeExistInShortlist(typeCode,'shortlisted'))
			{
				ChangeBasketButtonCaption('basket',typeCode,'add');
			}
			else
			{
				ChangeBasketButtonCaption('basket',typeCode,'remove');
			}
			HighLightSelectedRows('GENERAL');
			break;
    }
}
 
function IsTypeCodeInHdnWatchList(paramTypeCode)
{
	var codeStatus = false;
	var eleWatchlistDetails = $('completeWatchlistDetail');
	if(eleWatchlistDetails && eleWatchlistDetails.value!='' && eleWatchlistDetails.value!=null && eleWatchlistDetails.value.indexOf(paramTypeCode)>=0)
	{
		codeStatus = true;
	}
	return codeStatus;
}

function PortfolioSelectOnChange(typeCode)
{
	var selectBoxPId = $('basketDD') ? $('basketDD').options[$('basketDD').selectedIndex].value : '';
	if(selectBoxPId!='')
	{
		ChangeBasketButtonCaption('portfolio',typeCode, (IsTypeCodeInHdnPortfolio(selectBoxPId,typeCode)) ? 'add' : 'remove');
		UpdateBasketPortCount(selectBoxPId);
	}
}

function UpdateBasketPortCount(paramPortId)
{
	var eleSpanCount = $('spanPortCount');		
	if(eleSpanCount && paramPortId!='')
	{
		eleSpanCount.innerHTML = ' &nbsp; ' + GetHdnPortfolioValue(GetHdnPortfolioRowById(paramPortId), 'count');
	}
	else if(eleSpanCount)
	{
		eleSpanCount.innerHTML = '';
	}
}


function BasketPopupContent(pos,popupType,typeCode)
{
    var posTop=pos.y;
    var posLeft=pos.x+pos.w+5;
    var windowWidth=window.innerWidth;
    var windowHeight=window.innerHeight;

    if(windowWidth==null || windowWidth==0)
    {
        windowWidth=document.documentElement.clientWidth;
    }

    if(windowHeight==null || windowHeight==0)
    {
        windowHeight=document.documentElement.clientHeight;
    }

    if((posLeft+220)>windowWidth)
    {
        posLeft=posLeft-245;
    }
        
    var popupContent='<iframe id="BasketPopupFrame" src="" height="100" frameborder="0" scrolling="no" style="z-index:2000;width: 220px;  visibility: visible;position: absolute; top: '+posTop+'px; left: '+posLeft+'px;" ></iframe>';
    popupContent+='<div id="BasketPopup'+typeCode+'" name="BasketPopup" style="z-index:2000;visibility: visible; background-repeat: repeat-y; background-image: url(/Images/newBasketMiddle.gif); top: '+posTop+'px; position: absolute; width: 220px; left: '+posLeft+'px;" onmouseover="javascript:$(\'isBasketClose\').value=\'false\';" onmouseout="javascript:$(\'isBasketClose\').value=\'true\';">';
    popupContent+='<div style="background-image: url(/Images/newBasketTop.gif); background-repeat: no-repeat; background-position: left top;">';
    popupContent+='<div style="padding:  0px 16px 20px 10px; background-image: url(/Images/newBasketBottom.gif); background-repeat: no-repeat; background-position: left bottom;">'
    popupContent+='<table cellpadding="0" cellspacing="0" border="0" width="100%">';
    popupContent+='<tbody>';
    popupContent+='<tr style="height: 23px;">';
    popupContent+='<td style="padding-left: 6px; border-bottom: #a7c7e7 1px solid;" colspan="3">';
    popupContent+='<b style="color:#006BBC; font-size:12px;float:left; valign=\'middle\'">Add to</b>';
    popupContent+='<b onclick="javascript:$(\'isBasketClose\').value=\'true\';CloseBasket(\''+typeCode+'\');" title="Close" id="BCloseL" style="cursor: pointer; font-size: 16px; color: #006BBC;float:right">X</b>';    
    popupContent+='</td>';
    popupContent+='</tr>';
        
    if(userId!='')
    {
		 popupContent+='<tr height="20" align="center" style="cursor:pointer;">';
		 popupContent+='<td id="tabBasket" style="border-bottom: #a7c7e7 1px solid;border-right: #a7c7e7 1px solid;">';
		 popupContent+='<b onclick="javascript:ChangeBasketTab(\'Basket\',\''+typeCode+'\');">Basket</b>';
		 popupContent+='</td>';
		 popupContent+='<td id="tabPortfolio" style="border-bottom: #a7c7e7 1px solid;border-right: #a7c7e7 1px solid;">';
		 popupContent+='<b onclick="javascript:ChangeBasketTab(\'Portfolio\',\''+typeCode+'\');">Portfolio</b>';
		 popupContent+='</td>';
		 popupContent+='<td id="tabWatchlist" style="border-bottom: #a7c7e7 1px solid;">';
		 popupContent+='<b onclick="javascript:ChangeBasketTab(\'Watchlist\',\''+typeCode+'\');">Watchlist</b>';
		 popupContent+='</td>';
		 popupContent+='</tr>';
		 
		 // set selection mode
		 popupContent+='<tr align="center" style="padding-bottom:4px;">';		 
		 popupContent+='<td align="center" colspan="3">';
		 popupContent+='<div id="divBasketDefault" style="width: 100%; display: none;"><a href="javascript:SetDefaultBasketTab(\'GENERAL\');" style="text-decoration: underline;">Set as default selection mode</a>&nbsp;<span style="cursor:hand;color:blue;" title="By default holdings will be added directly on the first click"><b>?</b></span></div>';
		 popupContent+='<div id="divPortfolioDefault" style="width: 100%; display: none;"><a href="javascript:SetDefaultBasketTab(\'PORT\');" style="text-decoration: underline;">Set as default selection mode</a>&nbsp;<span style="cursor:hand;color:blue;" title="By default holdings will be added directly on the first click"><b>?</b></span></div>';
		 popupContent+='<div id="divWatchlistDefault" style="width: 100%; display: none;"><a href="javascript:SetDefaultBasketTab(\'WATCH\');" style="text-decoration: underline;">Set as default selection mode</a>&nbsp;<span style="cursor:hand;color:blue;" title="By default holdings will be added directly on the first click"><b>?</b></span></div>';
		 popupContent+='</td>';
		 popupContent+='</tr>';
    }
    else
    {
		 popupContent+='<tr height="20" align="center" style="cursor:pointer;">';
		 popupContent+='<td id="tabBasket" style="border-bottom: #a7c7e7 1px solid;">';
		 popupContent+='<b onclick="javascript:ChangeBasketTab(\'Basket\',\''+typeCode+'\');">Basket</b>';
		 popupContent+='</td>';
		 popupContent+='<td id="tabPortfolio" style="border-bottom: #a7c7e7 1px solid;">  ';		 
		 popupContent+='</td>';
		 popupContent+='<td id="tabWatchlist" style="border-bottom: #a7c7e7 1px solid;">    ';
		 popupContent+='</td>';
		 popupContent+='</tr>';
    }
    
    popupContent+='<tr height="25">';
    popupContent+='<td colspan="3" align="center" style="vertical-align:bottom;">';
    popupContent+='<b><span id="td_TypeName">Loading..</span></b>';
    popupContent+='</td>';
    popupContent+='</tr>';
    popupContent+='<tr>';
    popupContent+='<td colspan="3" align="center">';
    
    // Basket tab content starts here
    popupContent+='<table id="tblBasket"  style="display: block;">';
    popupContent+='<tr>';
    popupContent+='<td>';
    //popupContent+=portName;
    popupContent+=' ';
    popupContent+='</td>';
    popupContent+='</tr>';
    popupContent+='<tr height="20" align="center" >';
    popupContent+='<td align="center" style="text-align:centre;">';

	 popupContent+='<div id=\'basketAddRow\' style="width: 100%;display: none;">';
	 popupContent+='<a id=\'basketAddlink\' name=\'basketAddlink\' href="javascript:AddFundToBasket(\''+typeCode+'\');ChangeBasketButtonCaption(\'basket\',\''+typeCode+'\',\'remove\');" style="text-decoration: underline;"><b>Add</b></a>';
	 popupContent+='&nbsp;			             &nbsp;';
	 popupContent+='<a href="javascript:$(\'isBasketClose\').value=\'true\';CloseBasket(\''+typeCode+'\');" style="text-decoration: underline;"><b>Cancel</b></a>';
	 popupContent+='</div>';
		
	 popupContent+='<div id=\'basketRemoveRow\' style="width: 100%;display: none;">';
	 popupContent+='<a id=\'basketAddlink\' name=\'basketAddlink\' href="javascript:AddFundToBasket(\''+typeCode+'\');ChangeBasketButtonCaption(\'basket\',\''+typeCode+'\',\'add\');" style="text-decoration: underline;"><b>Remove</b></a>';
	 popupContent+='&nbsp;			             &nbsp;';
	 popupContent+='<a href="javascript:$(\'isBasketClose\').value=\'true\';CloseBasket(\''+typeCode+'\');" style="text-decoration: underline;"><b>Cancel</b></a>';
	 popupContent+='</div>';
	     
    popupContent+='</td>';
    popupContent+='</tr>';
    
    popupContent+='<tr height="20">';
	 popupContent+='<td align="center">';
    popupContent+='<a href="/Tools/Tools.aspx" style="text-decoration: underline;"><b>Back to Tools</b></a>';    
    popupContent+='</td>';
    popupContent+='</tr>';
    popupContent+='</table>';

	 // Portfolio tab content starts here
	 popupContent+='<table id="tblPortfolio"  style="height: 80px; display: none;">';

	 // If portfolio exist display the below two rows
	 popupContent+='<tr id=\'trSelectRow1\' style="display: none;">';
	 popupContent+='<td>';
	 popupContent += '<select id="basketDD" name="basketDD" style="width:144px;" onchange="javascript:PortfolioSelectOnChange(\''+typeCode+'\');HighLightSelectedRows(\'PORT\');"><option value="" selected>Select</option></select>';
	 //popupContent+='<span id=\'spanPortCount\'></span>';	 
	 popupContent+='</td>';
	 popupContent+='</tr>';

 
//	 if (popupType=='ProductSearch')
//	 {
//	 	popupContent+='<tr id=\'trSelectRow2\' height="20" style="display: none;">';
//		popupContent+='<td align="center">';
//		popupContent+='<a href="javascript:AddFundToPortfolio(\''+typeCode+'\',\'add\');UpdateBasket();$(\'isBasketClose\').value=\'true\';CloseBasket(\''+typeCode+'\');" style="text-decoration: underline;"><b>Cancel</b></a>';
//		popupContent+='</td>';
//		popupContent+='</tr>';
//	 }
//	 else
//	 {
	 	popupContent+='<tr id=\'trSelectRow2\' height="30" style="display: none;">';
		popupContent+='<td align="center">';
		popupContent+='No. of Holdings: <span id=\'spanPortCount\'></span>';
		popupContent+='<br/>';
		//	Add and Cancel button
		popupContent+='<div id=\'portfolioAddRow\'  style="width: 100%;display: none;">';
		popupContent+='<a href="javascript:AddFundToPortfolio(\''+typeCode+'\',\'add\');" style="text-decoration: underline;"><b>Add</b></a>';
		popupContent+='&nbsp;                  &nbsp;';
		popupContent+='<a href="javascript:$(\'isBasketClose\').value=\'true\';CloseBasket(\''+typeCode+'\');" style="text-decoration: underline;"><b>Cancel</b></a>';
		popupContent+='</div>';
		//	Remove and Add multiple button 
		popupContent+='<div id=\'portfolioRemoveRow\'  style="width: 100%;display: none;">';
		popupContent+='<a href="javascript:AddFundToPortfolio(\''+typeCode+'\',\'remove\');" style="text-decoration: underline;"><b>Remove</b></a>';
		popupContent+='&nbsp;                  &nbsp;';
		popupContent+='<a href="javascript:AddFundToPortfolio(\''+typeCode+'\',\'add multiple\');" style="text-decoration: underline;"><b>Add Multiple</b></a>';
		popupContent+='</div>';
		// Remove and Cancel button
		popupContent+='<div id=\'portfolioCancelRow\'  style="width: 100%;display: none;">';
		popupContent+='<a href="javascript:AddFundToPortfolio(\''+typeCode+'\',\'remove\');" style="text-decoration: underline;"><b>Remove</b></a>';
		popupContent+='&nbsp;                  &nbsp;';
		popupContent+='<a href="javascript:$(\'isBasketClose\').value=\'true\';CloseBasket(\''+typeCode+'\');" style="text-decoration: underline;"><b>Cancel</b></a>';
		popupContent+='</div>';		
		popupContent+='</td>';
		popupContent+='</tr>';

//	 }
	
   // If no portfolio exist display this block.
	popupContent+='<tr id=\'trSelectRow3\' height="20"  style="display: none;" >';
	popupContent+='<td align="center">';
	popupContent+='No portfolio exist. <a href="/Tools/Portfolio/ManagePortfolio.aspx" style="text-decoration: underline;">Click here</a> to create a new portfolio.';
	popupContent+='</td>';
	popupContent+='</tr>';
		 
	popupContent+='<tr height="20">';
	popupContent+='<td align="center">';
   popupContent+='<a href="/Tools/Portfolio/Valuation.aspx" style="text-decoration: underline;"><b>Back to Portfolio</b></a>';    
   popupContent+='</td>';
   popupContent+='</tr>';
   popupContent+='</table>';
    
   // Watchlist tab content starts here
   popupContent+='<table id="tblWatchlist"  style="display: none;">';
   popupContent+='<tr>';
   popupContent+='<td> ';
   popupContent+='</td>';
   popupContent+='</tr>';
   popupContent+='<tr height="20">';
   popupContent+='<td align="center">';
   popupContent+='No. of Holdings: <span id=\'spanWatchListCount\'></span>';
	popupContent+='<br/>';

   popupContent+='<div id=\'watchlistAddRow\' style="width: 100%;display: none;">';
   popupContent+='<a id=\'watchListAddLink\' href="javascript:AddFundToWatchList(\''+typeCode+'\',\'add\');ChangeBasketButtonCaption(\'watchlist\',\''+typeCode+'\',\'remove\');" style="text-decoration: underline;"><b>Add</b></a>';
   popupContent+='&nbsp;			             &nbsp;';
	popupContent+='<a href="javascript:$(\'isBasketClose\').value=\'true\';CloseBasket(\''+typeCode+'\');" style="text-decoration: underline;"><b>Cancel</b></a>';
   popupContent+='</div>';
    
   popupContent+='<div id=\'watchlistRemoveRow\' style="width: 100%;display: none;">';
   popupContent+='<a id=\'watchListAddLink\' href="javascript:AddFundToWatchList(\''+typeCode+'\',\'remove\');ChangeBasketButtonCaption(\'watchlist\',\''+typeCode+'\',\'add\');" style="text-decoration: underline;"><b>Remove</b></a>';
   popupContent+='&nbsp;			             &nbsp;';
	popupContent+='<a href="javascript:$(\'isBasketClose\').value=\'true\';CloseBasket(\''+typeCode+'\');" style="text-decoration: underline;"><b>Cancel</b></a>';
   popupContent+='</div>';
    
   popupContent+='</td>';
   popupContent+='</tr>';
   popupContent+='<tr height="20">';
   popupContent+='<td align="center">';
   popupContent+='<a href="/Tools/Portfolio/Watchlist.aspx" style="text-decoration: underline;"><b>Back to Watchlist</b></a>';    
   popupContent+='</td>';
   popupContent+='</tr>';
   popupContent+='</table>';

    
   popupContent+='</td>';
   popupContent+='</tr>';
   popupContent+='</tbody>';
   popupContent+='</table>';
   popupContent+='<input type="hidden" id="isBasketClose" name="isBasketClose" value="true" />';
   popupContent+='<input type="hidden" id="curPopup" name="curPopup" value="" />';
   popupContent+='</div>';
   popupContent+='</div>';
   popupContent+='</div>';
   return popupContent;
}

function ReplaceAllStrInst( str, replacements ) 
{
    for ( i = 0; i < replacements.length; i++ ) 
    {
        var idx = str.indexOf( replacements[i][0] );
        while ( idx > -1 ) 
        {
            str = str.replace( replacements[i][0], replacements[i][1] ); 
            idx = str.indexOf( replacements[i][0] );
        }
    }
    return str;
}

function HighLightSelectedRows(highlightType)
{
	var typecodelist='';
	var codeType = (typeof(highlightType)=='undefined') ? Mode.toUpperCase():highlightType;
	
	switch(codeType)
	{
		case "WATCH":
			var eleWatchlistDetails = $('completeWatchlistDetail');
			if(eleWatchlistDetails && eleWatchlistDetails.value !='')
			{
				typecodelist=eleWatchlistDetails.value;
			}
			else
			{
				typecodelist = WatchtypeCodes;
			}
			break;
		case "PORT":
			var eleBasketPId = $('basketDD');
			var selectBoxPId = eleBasketPId ? eleBasketPId.options[eleBasketPId.selectedIndex].value : '';
			if(selectBoxPId!=null && selectBoxPId!='')
			{	
				typecodelist = ReplaceAllStrInst(GetHdnPortfolioValue(GetHdnPortfolioRowById(selectBoxPId), 'typecodes'), [["~", ","]] );
			}
			else
			{
				typecodelist =PorttypeCodes;
			}
			break;
		default:
			typecodelist = GetCookie("shortlisted");
			break;
	}
	HighLightRows(typecodelist);
}

function HighLightRows(typecodes)
{
	var basketOverriden = false;
	var overrideBasketElem = $('overrideBasketCookie');
	if(overrideBasketElem) {
		if(overrideBasketElem.value != "") {
			basketCookieName = overrideBasketElem.value;
			basketOverriden = true;
		}
	}
	if(typecodes != "")
	{	
	   var Title="basket";    
		var elements = document.getElementsByTagName("TR");
		var typecodeArr = typecodes.split(',');

		for(var i=0;i<elements.length;i++)
		{
			if(!IsStringFoundInArray(typecodeArr, elements[i].id) && (elements[i].className.indexOf("selected") >= 0))
			{
				elements[i].className = elements[i].className.replace("selected","");
				var imgTags = elements[i].getElementsByTagName('IMG');
				for(var j=0;j<imgTags.length;j++)
				{
					if(imgTags[j].src.indexOf("/icons/removeIco.png") >= 0)
					{
						imgTags[j].src = "/icons/icon_plus.png";
						imgTags[j].title = "add to "+Title;
						imgTags[j].width = "16";
						imgTags[j].height = "15";
					}
				}
			}
			if(IsStringFoundInArray(typecodeArr, elements[i].id) && elements[i].className.indexOf(" selected") < 0)
			{
				var imgTags = elements[i].getElementsByTagName('IMG');
				for(var j=0;j<imgTags.length;j++)
				{
					if(imgTags[j].src.indexOf("/icons/icon_plus.png") >= 0)
					{
						imgTags[j].src = "/icons/removeIco.png";
						imgTags[j].title = "remove from "+Title;
						imgTags[j].width = "14";
						imgTags[j].height = "14";
					}
				}
				elements[i].className += " selected";
			}
		}
		elements = document.getElementsByTagName("DIV");
		for(var i=0;i<elements.length;i++)
		{
			if(!IsStringFoundInArray(typecodeArr, elements[i].id) && (elements[i].className.indexOf("bold") >= 0))
			{
				elements[i].className = elements[i].className.replace("bold","");
				var imgTag = $("Img-"+elements[i].id);
				if(imgTag)
				{
					if(imgTag.src.indexOf("/icons/removeIco.png") >= 0)
					{
						imgTag.src = "/icons/icon_plus.png";
						imgTag.title = "add to "+Title;
						imgTag.width = "16";
						imgTag.height = "15";
					}
				}
				var divTag = $("span-"+elements[i].id);
				if(divTag)
				{
				    if(divTag.innerHTML.indexOf('equity') > 0)
				    {
				        divTag.innerHTML = "Add this equity from basket";
				    }
				    else
				    {
					    divTag.innerHTML = "Add this unit to basket";
					}
				}
			}
			if(IsStringFoundInArray(typecodeArr, elements[i].id) && elements[i].className.indexOf(" bold") < 0)
			{
				var imgTag = $("Img-"+elements[i].id);
				if(imgTag)
				{
					if(imgTag.src.indexOf("/icons/icon_plus.png") >= 0)
					{
						imgTag.src = "/icons/removeIco.png";
						imgTag.title = "remove from "+Title;
						imgTag.width = "14";
						imgTag.height = "14";
					}
				}
				var divTag = $("span-"+elements[i].id);
				if(divTag)
				{
				    if(divTag.innerHTML.indexOf('equity') > 0)
				    {
				        divTag.innerHTML = "Remove this equity from basket";
				    }
				    else
				    {
					    divTag.innerHTML = "Remove this unit from basket";
					}
				}
				elements[i].className += " bold";
			}
		}
	}
}

function ChangeBasketButtonCaption(tabName, typeCode, displayStatus)
{
	switch(tabName)
	{
		case 'basket':
			var eleAddRow = $('basketAddRow');
			var eleRemoveRow = $('basketRemoveRow');
	
			if(displayStatus=='add')
			{
				eleAddRow.style.display='block';
				eleRemoveRow.style.display='none';
			}
			else if(displayStatus=='remove')
			{
				eleRemoveRow.style.display='block';
				eleAddRow.style.display='none';	
			}
			else
			{
				eleAddRow.style.display='block';
				eleRemoveRow.style.display='none';
			}
			break;
		case 'portfolio':
			var elePortfolioAddRow = $('portfolioAddRow');
			var elePortfolioRemoveRow = $('portfolioRemoveRow');
			if(displayStatus=='add')
			{	
				if(elePortfolioAddRow)
					elePortfolioAddRow.style.display='none';
				if(elePortfolioRemoveRow)
					elePortfolioRemoveRow.style.display='block';
			}
			else
			{
				if(elePortfolioAddRow)
					elePortfolioAddRow.style.display='block';
				if(elePortfolioRemoveRow)
					elePortfolioRemoveRow.style.display='none';	
			}
			break;
		case 'watchlist':
			var eleAddRow = $('watchlistAddRow');
			var eleRemoveRow = $('watchlistRemoveRow');
	
			if(displayStatus=='add')
			{
				eleAddRow.style.display='block';
				eleRemoveRow.style.display='none';
			}
			else if(displayStatus=='remove')
			{
				eleRemoveRow.style.display='block';
				eleAddRow.style.display='none';	
			}
			else
			{
				eleAddRow.style.display='block';
				eleRemoveRow.style.display='none';
			}
			break;
	}
}

function CheckForPortfolioRow()
{
	var portfolioDD=$("basketDD");
	var portfolioRow1 = $("trSelectRow1");
	var portfolioRow2 = $("trSelectRow2");
	var portfolioRow3 = $("trSelectRow3");

	if(IsPortfolioExist())
	{
		if(portfolioRow1)
			portfolioRow1.style.display='block';
		if(portfolioRow2)
			portfolioRow2.style.display='block';
		if(portfolioRow3)
			portfolioRow3.style.display='none';
	}
	else
	{
		if(portfolioRow1)
			portfolioRow1.style.display='none';
		if(portfolioRow2)
			portfolioRow2.style.display='none';
		if(portfolioRow3)
			portfolioRow3.style.display='block';
	}
}


function IsCodeExistInShortlist(typeCode, cookieName)
{
   var value = GetCookie(cookieName);
	if(value!=null && value!='' && value.indexOf(typeCode)>=0)
	{
		return true;
	}
	else
	{
		return false;
	}
}

function AddFundToBasket(typecode)
{
	var basketCookieName = "shortlisted";
	var basketOverriden = false;
	var overrideBasketElem = $('overrideBasketCookie');

	if(overrideBasketElem && overrideBasketElem.value != "") 
	{
		basketCookieName = overrideBasketElem.value;
		basketOverriden = true;
	}

   var value = GetCookie(basketCookieName);
	var count=$("NoOfShortListedItems");
	var isCodeRemoved = false;
	   
   if(value != "")
   {
	   var farray = new Array();
	   farray = value.split(',');

	   if(!IsStringFoundInArray(farray, typecode))
	   {
		  value += ","+typecode;			
		  if(count!=null && !basketOverriden){
			count.innerHTML="("+((parseInt(farray.length))+1)+")";              
		  }
	   }
	   else
	   {
		   DeleteFromShortlist(typecode, basketCookieName);
		   if(!basketOverriden){
				DeleteFromShortlist(typecode, "TN_RetainSelected");
			}
		   value = GetCookie(basketCookieName);			
		   if((farray.length-1)!=0){
				if(count!=null && !basketOverriden){
					count.innerHTML="("+(farray.length-1)+")";	
				}		   
		   }
		   else{
				if(count!=null && !basketOverriden){
					count.innerHTML="(0)";
				}
		   }
		   isCodeRemoved = true;
	   }
   }
   else
   {
	   value = typecode;
	   if(count != null && !basketOverriden){
			count.innerHTML="(1)";
	   }
   }
   
   if(!isCodeRemoved)
   {
	   SetCookie(basketCookieName, value, 123231);
	   retainSelectedVal(typecode);
   }
   else
   {
	   DeHighlightRows(typecode);
   }
   	
	//HighLightSelectedRows();
	HighLightSelectedRows('GENERAL');
}

function UpdateWatchlistTypeCode(parmTypeCode, updateStatus)
{
	var eleWatchlistDetails = $('completeWatchlistDetail');
	if(eleWatchlistDetails)
	{
		if(updateStatus=='remove')
		{
			eleWatchlistDetails.value = RemoveSubstring(eleWatchlistDetails.value, parmTypeCode);
		}
		else
		{
			eleWatchlistDetails.value += ',' + parmTypeCode;
		}
	}
	UpdateWatchlistCount();
}

function UpdateWatchlistCount()
{
	var watchlistCount=0;
	var eleWatchlistDetails = $('completeWatchlistDetail');
	if(eleWatchlistDetails)
	{
		var wListCodes = eleWatchlistDetails.value.split(',');
		if(wListCodes!=null && wListCodes.length)
		{
			for(lCnt=0;lCnt<wListCodes.length;lCnt++)
			{
				if(wListCodes[lCnt]!='')
				{
					watchlistCount++;
				}
			}
		}
	}
	var eleWatchHolding = $('spanWatchListCount');
	if(eleWatchHolding)
	{
		eleWatchHolding.innerHTML=watchlistCount;
	}
		
	var eleLeftNavWatchCnt = $('NoOfWatchlistItems');
	if(eleLeftNavWatchCnt)
	{
		eleLeftNavWatchCnt.innerHTML=watchlistCount;
	}
	//return watchlistCount;
}


function AddFundToPortfolio(typecode,addOrRemoveFund)
{
   var count=$("NoOfPortfolioItems");

	var eleBasketPId = $('basketDD');
	var selectBoxPId = $('basketDD') ? $('basketDD').options[$('basketDD').selectedIndex].value : '';
	var isCodeRemoved = false;
	
	if(addOrRemoveFund=='add' || addOrRemoveFund=='add multiple')
	{
		PorttypeCodes += (PorttypeCodes != "") ? ","+typecode : typecode;
		AddPortfolioFundDisplay(selectBoxPId,userValue,univValue,typecode);
		SetCookie(userValue+"portfolio", PorttypeCodes, 123231);
		if(count && selectBoxPId==pId)
			count.innerHTML=parseInt(count.innerHTML)+1;
		// Adding typecode in hidden variable
		AddTypeCodeInHdnPortfolio(selectBoxPId, typecode);
		ChangePortfolioRow(addOrRemoveFund=='add'? 'add' : 'add multiple');
	}
	else if(addOrRemoveFund=='remove')
	{
		// Condition to check for duplicate occurance		
		if(IsDuplicateTypeCodeInHdnPort(selectBoxPId,typecode))
		{	
			var statusMsg='This portfolio contain dupulicate of this holding. Do you want to delete it individually?';
			if(confirm(statusMsg))
			{
				SubmitFormThroughBasket('/Tools/Portfolio/Valuation.aspx?selectPortfolio='+selectBoxPId);
			}
		}
		else
		{
			DeleteFromShortlist(typecode, userValue+"portfolio");	
			DeleteFromDB(typecode,PorttypeCodes);
			RemovePortfolioFundDisplay(selectBoxPId,userValue,typecode);
			if(count && selectBoxPId==pId)
				count.innerHTML=parseInt(count.innerHTML)-1;
			// Delete typecode from hidden variable
			DeleteTypeCodeFromHdnPortfolio(selectBoxPId, typecode);
			ChangePortfolioRow('remove');
		}
	}
	UpdateBasketPortCount(selectBoxPId);
	HighLightSelectedRows('PORT');
}

function SubmitFormThroughBasket(page)
{
    document.masterForm.action=page;
    document.masterForm.submit();
}


function AddFundToWatchList(typecode,addOrRemoveFund)
{
	var count=$("NoOfWatchlistItems");
	if(addOrRemoveFund=='add')
	{
		WatchtypeCodes += (WatchtypeCodes != "") ? ","+typecode : typecode;
		SetCookie(userValue+"watch", WatchtypeCodes, 123231);		
		AddWatchlistFundDisplay(userValue,univValue,typecode,SiteCode);
		if(count)
			count.innerHTML=parseInt(count.innerHTML)+1;
		UpdateWatchlistTypeCode(typecode,'add');
	}
	else if(addOrRemoveFund=='remove')
	{
		DeleteFromShortlist(typecode, userValue+"watch");
		DeleteFromDB(typecode,WatchtypeCodes);
		RemoveWatchlistFundDisplay(userValue,typecode,SiteCode);
		if(count)
			count.innerHTML=parseInt(count.innerHTML)-1;
		UpdateWatchlistTypeCode(typecode,'remove');
	}
	HighLightSelectedRows('WATCH');
}


function ChangePortfolioRow(updateStatus)
{
	var elePortfolioAddRow = $('portfolioAddRow');	
	var elePortfolioRemoveRow = $('portfolioRemoveRow');
	var elePortfolioCancelRow = $('portfolioCancelRow');
	//var eleNoOfHoldingsRow = $('noOfHoldingsRow');
	
	if(elePortfolioAddRow && elePortfolioCancelRow && elePortfolioRemoveRow)
	{
		if(updateStatus=='add')
		{
			elePortfolioAddRow.style.display='none';
			elePortfolioCancelRow.style.display='none';
			elePortfolioRemoveRow.style.display='block';
		}
		else if(updateStatus=='remove')
		{
			elePortfolioRemoveRow.style.display='none';
			elePortfolioCancelRow.style.display='none';
			elePortfolioAddRow.style.display='block';		
		}
		else if(updateStatus=='add multiple')
		{
			elePortfolioCancelRow.style.display='block';
			elePortfolioAddRow.style.display='none';
			elePortfolioRemoveRow.style.display='none';
		}
	}
}
*/
/************* New approach basket code ends here	**************/

//v1.7
// Flash Player Version Detection
// Detect Client Browser type
// Copyright 2005-2007 Adobe Systems Incorporated.  All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			
			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful. 
			
			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)		
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}
	
	return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;
	
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");			
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}	
	return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '';
  if (isIE && isWin && !isOpera)
  {
    str += '<object ';
    for (var i in objAttrs)
    {
      str += i + '="' + objAttrs[i] + '" ';
    }
    str += '>';
    for (var i in params)
    {
      str += '<param name="' + i + '" value="' + params[i] + '" /> ';
    }
    str += '</object>';
  }
  else
  {
    str += '<embed ';
    for (var i in embedAttrs)
    {
      str += i + '="' + embedAttrs[i] + '" ';
    }
    str += '> </embed>';
  }

  document.write(str);
}

function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
      case "id":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}

///////////////////////  Menu bar //////////////////////////////
function SetActiveMenu()
{
	 var url = document.URL;
	 if(requestActUrl != '')
	 {
		url = requestActUrl;
	 }
    var divMain = $("mainMenu");
    if(divMain)
    {
        for(var i=0; i<divMain.childNodes.length; i++)
        {
            if(divMain.childNodes[i].href)
            {
				var urlTempPath = url.substring(0, url.indexOf(".aspx"));
				if(urlTempPath == "" && url.indexOf(".aspx") < 0) {
					 urlTempPath = url;
				}
                var urlPath = urlTempPath.substring(0,urlTempPath.lastIndexOf("/")+1);
                var hrefPath = divMain.childNodes[i].href.substring(0, divMain.childNodes[i].href.lastIndexOf("/")+1);
                if(url.indexOf("/Home.aspx") >= 0 && url.indexOf("/Login.aspx") < 0 && url.indexOf("/Managers/") < 0)
                {
						urlPath += "Investments/";
                }
                if(url.indexOf("/Investments/") >= 0 && url.indexOf("/Managers/") >= 0)
                {
						urlPath = urlPath.replace("Investments/","");
                }

                var divId = divMain.childNodes[i].id;
                var subMenu = $("sub"+divId);
                if(subMenu)
                {
						 var child = subMenu;
						 var displayChild = child.style;
						 if(!child.style)
						 {
							displayChild = child;
						 }
						 if(hrefPath.toUpperCase() == urlPath.toUpperCase() || IsTNUrlBelongsToMenu(divMain.childNodes[i], urlPath))
						 {
							   divMain.childNodes[i].className = "selected";
	                    
								displayChild.display = "block";
								var currSub = $("currSubmenu");
								if(currSub)
								{
									currSub.value = child.id;
									var secondLvl = child.getElementsByTagName("LI");
									var selSecondLvl = 0;
									if(default2ndLevel != '')
									{
										var lvl2 = $(default2ndLevel)
										if(lvl2)
										{
											lvl2.className += " selected";
										}
									}
									else
									{
										for(var k=0;k<secondLvl.length;k++)
										{
											if(secondLvl[k])
											{
												var anchor = secondLvl[k].getElementsByTagName("A");
												for(var l=0;l<secondLvl.length;l++)
												{
													if(typeof(anchor[l])!='undefined' && (url.toUpperCase().indexOf(anchor[l].href.toUpperCase())>=0) )
													{
														anchor[0].className += " selected";
														selSecondLvl = 1;
														break;
													}
												}
												if(selSecondLvl == 1)
													break;
											}
										}
									}
								}
						 }
						 else
						 {
							  displayChild.display = "none";
						 }
                }
            }
        }
    }
	function IsTNUrlBelongsToMenu(menu, urlPath)
	{
		 if(menu.id.toUpperCase() == "TOOLS")
		 {
			  if(urlPath.toUpperCase().indexOf("/PSCAN") >= 0
				|| urlPath.toUpperCase().indexOf("/CURRENCIES") >= 0
				|| urlPath.toUpperCase().indexOf("/FUNDPROFILER") >= 0
				|| urlPath.toUpperCase().indexOf("/PENSIONCALCULATOR") >= 0
				|| urlPath.toUpperCase().indexOf("/RSS") >= 0)
			  {
					return true;
			  }
		 }
		 if(menu.id.toUpperCase() == "INVESTMENTS")
		 {
			  if((urlPath.toUpperCase().indexOf("/FACTSHEETS") >= 0 && urlPath.toUpperCase().indexOf("/MANAGERS") < 0)
				|| (urlPath.toUpperCase().indexOf("/GENERAL") >= 0 && urlPath.toUpperCase().indexOf("/MANAGERS") < 0)
				|| urlPath.toUpperCase().indexOf("/HELP") >= 0
				|| urlPath.toUpperCase().indexOf("/INVESTMENTS") >= 0)
			  {
					return true;
			  }
		 }   
		 if(menu.id.toUpperCase() == "EDUCATION")
		 {
			  if(urlPath.toUpperCase().indexOf("/GLOSSARIES") >= 0
        		|| urlPath.toUpperCase().indexOf("/MASTERCLASS") >= 0)
			  {
					return true;
			  }
		 }   
		 if(menu.id.toUpperCase() == "NEWS")
		 {
			  if(urlPath.toUpperCase().indexOf("/KEYSTRATEGIES") >= 0
        		|| urlPath.toUpperCase().indexOf("/ABSOLUTERETURN/") >= 0
        		|| urlPath.toUpperCase().indexOf("/AWARDS") >= 0)
			  {
					return true;
			  }
		 }   
//		 if(menu.id.toUpperCase() == "COMMUNITY")
//		 {
//			  if(urlPath.toUpperCase().indexOf("/COMMUNITY") >= 0
//        		|| urlPath.toUpperCase().indexOf("/ADMIN") >= 0)
//			  {
//					return true;
//			  }
//		 }
		 if(menu.id.toUpperCase() == "MANAGERS")
		 {
			  if(urlPath.toUpperCase().indexOf("/MANAGERS") >= 0
				|| urlPath.toUpperCase().indexOf("/ALPHAMANAGERS/") >= 0
				|| urlPath.toUpperCase().indexOf("/ALPHAMANAGER/") >= 0)
			  {
					return true;
			  }
		 }
		 return false;
	}
}

///////////////////////  Quick search //////////////////////////////

function ChangeUKQS(univ, evnt)
{	
	univ=univ.substring(0,univ.toString().indexOf(":"));
	
	var tdUniverse = document.getElementById("tdUniverseDD");
	var tdSectors	= document.getElementById("tdSectorsDD");	
	var tdDomicile = document.getElementById("tdDomicileDD");
	var tdAssetClass= document.getElementById("tdAssetClassDD");
	var tdManager = document.getElementById("tdManagerDD");
	
	var eDomicile = document.getElementById("qsDomicileDD");	
	var eManager = document.getElementById("qsManagerDD");
	var eAssetClass= document.getElementById("qsAssetClassDD");
	var eSectors	= document.getElementById("qsSectorsDD");
	var eUnits	= document.getElementById("qsUnitsDD");
	var eUniverse	= document.getElementById("qsUniverseDD");	
	
	switch(univ)
	{
		case "U":
			eSectors.style.visibility='visible';
			eUnits.style.visibility='visible';
			eUnits.style.width='80px';
			tdUniverse.style.width='146px';
			eUniverse.style.width='144px';
			tdAssetClass.style.width='146px';
			eAssetClass.style.width='144px';
			tdSectors.style.width='180px';
			eSectors.style.width='178px';
			tdDomicile.style.width='180px';
			eDomicile.style.width='178px';
			eManager.style.width='98%';
			//tdManager.style.width='68%';
			break;
		case "T":
			eSectors.style.visibility='visible';
			eUnits.style.visibility='visible';
			eUnits.style.width='80px';
			tdUniverse.style.width='146px';
			eUniverse.style.width='144px';
			tdAssetClass.style.width='146px';
			eAssetClass.style.width='144px';
			tdSectors.style.width='180px';
			eSectors.style.width='178px';
			tdDomicile.style.width='180px';
			eDomicile.style.width='178px';
			eManager.style.width='98%';
			//tdManager.style.width='68%';
			break;
		case "P":
			eSectors.style.visibility='visible';
			eUnits.style.visibility='hidden';
			tdUniverse.style.width='146px';
			eUniverse.style.width='144px';
			tdAssetClass.style.width='146px';
			eAssetClass.style.width='144px';
			tdSectors.style.width='180px';
			eSectors.style.width='178px';
			tdDomicile.style.width='180px';
			eDomicile.style.width='178px';
			eManager.style.width='98%';
			//tdManager.style.width='68%';
			break;
		case "N":
			eSectors.style.visibility='visible';
			eUnits.style.visibility='hidden';
			tdUniverse.style.width='146px';
			eUniverse.style.width='144px';
			tdAssetClass.style.width='146px';
			eAssetClass.style.width='144px';
			tdSectors.style.width='180px';
			eSectors.style.width='178px';
			tdDomicile.style.width='180px';
			eDomicile.style.width='178px';
			eManager.style.width='98%';
			//tdManager.style.width='68%';
			break;
		case "VCT":
			eSectors.style.visibility='hidden';
			eUnits.style.visibility='hidden';			
			tdUniverse.style.width='180px';
			eUniverse.style.width='178px';
			tdAssetClass.style.width='180px';
			eAssetClass.style.width='178px';
			tdSectors.style.width='146px';
			eSectors.style.width='144px';	
			tdDomicile.style.width='146px';
			eDomicile.style.width='144px';
			eManager.style.width='98%';
			//tdManager.style.width='68%';
			break;		
		default: // B & E
			eSectors.style.visibility='visible';
			eUnits.style.visibility='hidden';
			tdUniverse.style.width='146px';
			eUniverse.style.width='144px';
			tdAssetClass.style.width='146px';
			eAssetClass.style.width='144px';
			tdSectors.style.width='180px';
			eSectors.style.width='178px';
			tdDomicile.style.width='180px';
			eDomicile.style.width='178px';
			eManager.style.width='98%';
			//tdManager.style.width='68%';
			break;
	}
	tdManager.style.width='22%';
	//LoadingUKText('qsManagerDD');	LoadingUKText('qsDomicileDD'); LoadingUKText('qsSectorsDD'); setTimeout('UKQSLoadSector(\'univ\')',0); LoadingUKText('qsAssetClassDD'); setTimeout('UKQSLoadAssetClass(\'univ\')',0);
	if(evnt=="Change")
	{
		LoadingUKText('qsManagerDD');
		LoadingUKText('qsDomicileDD');
		if(univ!="VCT")
		{
			LoadingUKText('qsSectorsDD');
		}
		setTimeout('UKQSLoadSector(\'univ\')',0);
		
		LoadingUKText('qsAssetClassDD'); 
		setTimeout('UKQSLoadAssetClass(\'univ\')',0);
	}
}

function LoadingUKText(id)
{
	var selectFund=document.getElementById(id);
   if(selectFund.style.visibility='visible')
   {
		selectFund.options.length=0;   
		var ele=document.createElement("option");
		ele.text="Loading...";
		ele.value="-1";
		selectFund.options.add(ele);
	}
}

function ClearQSDropDown(ddId) 
{			
	var theDropDown = document.getElementById(ddId);
	var numberOfOptions = theDropDown.options.length;
	for (i=0; i<numberOfOptions; i++) 
	{				 //Note: Always remove(0) and NOT remove(i)				 
		theDropDown.remove(0)			
	}		
}
   
function PopulateSectors(Sector)
{
    
    var sectorDDCtrl=$("qsSectorsDD");
    
       
	 // Skip this code when this element doesn't exit	  
	 if(sectorDDCtrl)
	 {
		sectorDDCtrl.disabled=false;
		sectorDDCtrl.options.length=0;
		var optionElement=document.createElement("option");

		optionElement.text="All Sectors";
		optionElement.value="";
		sectorDDCtrl.options.add(optionElement);
	 
		// Skip this code when Sector array is null
		if(Sector)
		{
			// Loop to add all the Sectors in Sector Dropdown box
			for(i=0;i<Sector.length;i++)
			{
			  if(Sector[i]!=null) {
				 optionElement=document.createElement("option");
				 
				 if(typeof Sector[i].SectorName !='undefined')
				 {
				     optionElement.text=Sector[i].SectorName;
				     optionElement.value=Sector[i].SectorClassCode;
				     sectorDDCtrl.options.add(optionElement);
				 }
			  }
			}
		}
	 }
}    
   function PopulateAssetClass(AssetClass)
   {
     	  
		  // If no asset class loaded then skip
		  if(AssetClass!=null)
		  {		 
			 var selectAssetClass=$("qsAssetClassDD");
			 selectAssetClass.options.length=0;
			 var ele=document.createElement("option");
			 ele.text= "All Fund Focuses";
			 ele.value="A:";
			 selectAssetClass.options.add(ele);
			 
			 // Loop to add all Managers in the Manager Dropdown box
			 for(i=0;i<AssetClass.length;i++)
			 {
				if(AssetClass[i]!=null)
				{
					var ele=document.createElement("option");
					
					if(typeof AssetClass[i].Name !='undefined')
				    {
					    if(AssetClass[i].Code=="0")
					    {
					        ele.text='';
					    }
					    else
					    {
					        ele.text=AssetClass[i].Name;
					    }
					    ele.value=AssetClass[i].Code;
					    selectAssetClass.options.add(ele);
					}
				}
			 }
		  }
		  else
		  {
				var selectAssetClass=$("qsAssetClassDD");
				selectAssetClass.options.length=0;
				var ele=document.createElement("option");
				ele.text= "All Fund Focuses";
				ele.value="A:";
				selectAssetClass.options.add(ele);
		  }
   }
   
   function PopulateManager(Manager)
   {
   	  // If no manager loaded then skip
	  if(Manager!=null)
	  {		 
		 var selectmanagers=$("qsManagerDD");
		 selectmanagers.options.length=0;
		 var ele=document.createElement("option");
		 ele.text= "All Managers";
		 ele.value="";
		 selectmanagers.options.add(ele);
		 
		 // Loop to add all Managers in the Manager Dropdown box
		 for(i=0;i<Manager.length;i++)
		 {
			if(Manager[i]!=null){
			   var ele=document.createElement("option");
			   
			   if(typeof Manager[i].ManagerName !='undefined')
			   {
			       ele.text=Manager[i].ManagerName;
			       ele.value=Manager[i].ManagerCode;
			       selectmanagers.options.add(ele);
			   }
			}
		 }
	  } 
   }
   function PopulateDomiciles(Domicile)
   {
   	// If no Domicile loaded then skip
			if(Domicile!=null)
			{		 
				var selectdomicile=$("qsDomicileDD");
				selectdomicile.options.length=0;
				var ele=document.createElement("option");
				ele.text= "All Domiciles";
				ele.value="";
				selectdomicile.options.add(ele);
			 
				// Loop to add all Domicile in the Domicile Dropdown box
				for(i=0;i<Domicile.length;i++)
				{
					var ele=document.createElement("option");
					
					if(typeof Domicile[i].DomicileName !='undefined')
			        {
					    ele.text=Domicile[i].DomicileName;
					    ele.value=Domicile[i].DomicileCode;
					    selectdomicile.options.add(ele);
					}
				}
			}	
   }
   function PopulateGeoarea(Geoarea)
   {
   // If no Domicile loaded then skip
			if(Geoarea!=null)
			{		 
				var selectGeoarea=$("qsDomicileDD");
				selectGeoarea.options.length=0;
				var ele=document.createElement("option");
				ele.text= "All Geographies";
				ele.value="";
				selectGeoarea.options.add(ele);
			 
				// Loop to add all Geoarea in the Domicile Dropdown box
				for(i=0;i<Geoarea.length;i++)
				{
					if(Geoarea[i]!=null)
					{					
						var ele=document.createElement("option");
						if(typeof Geoarea[i].GeoareaName!='undefined')
						{
						    ele.text=Geoarea[i].GeoareaName;
						    ele.value=Geoarea[i].GeoareaCode;
						    selectGeoarea.options.add(ele);
						}
					}
				}
			}		
   }
   
  function PopulateVCTQSObjects(vctSectorObj)
  {
        var assetclassDDCtrl=$("qsAssetClassDD");
    
	    if(vctSectorObj)
	    {
		    ClearQSDropDown("qsAssetClassDD");
		    //sectorDDCtrl.style.visibility='hidden';
		    for(i=0; i < vctSectorObj.length; i++)
		    {
		      if(vctSectorObj[i]!=null) {
			     var optionElement=document.createElement("option");
			     
			     if(typeof vctSectorObj[i].Name!='undefined')
				 {
			      optionElement.text=vctSectorObj[i].Name;
			      optionElement.value=vctSectorObj[i].Code;
			      assetclassDDCtrl.options.add(optionElement);
			     }
		      }
		    }
	    }
  } 
  
  function PopulateVCTQSObjectsManager(vctManagerObj)
  {
  
        var managerDDCtrl=$("qsManagerDD");
  
	    if(vctManagerObj)
	    {
		    ClearQSDropDown("qsManagerDD");
		    for(i=0; i < vctManagerObj.length; i++)
		    {
		      if(vctManagerObj[i]!=null) {
			     var optionElement=document.createElement("option");
			     
			     if(typeof vctManagerObj[i].Name!='undefined')
				 {
			     optionElement.text=vctManagerObj[i].Name;
			     optionElement.value=vctManagerObj[i].Code;
			     managerDDCtrl.options.add(optionElement);
			     }
		      }
		    }
	    }
  }
  
  function PopulateVCTQSObjectsGeoAreas(vctGeoareasObj)
  {
    var domicileDDCtrl=$("qsDomicileDD");
			
    if(vctGeoareasObj)
    {
	    ClearQSDropDown("qsDomicileDD");
	    for(i=0; i < vctGeoareasObj.length; i++)
	    {
	      if(vctGeoareasObj[i]!=null) {
		     var optionElement=document.createElement("option");
		     
		        if(typeof vctGeoareasObj[i].Name!='undefined')
				 {
		         optionElement.text=vctGeoareasObj[i].Name;
		         optionElement.value=vctGeoareasObj[i].Code;
		         // Domicile ctrl is used for Geoareas
		         domicileDDCtrl.options.add(optionElement);
		     }
	      }
	    }
    }

  
  }
   
// Function to load sectors based on universe and assetclass
function UKQSLoadSector(val)
{		
   var selUnivEleID = $("qsUniverseDD");
   var assetClassCtrl = $("qsAssetClassDD");
   
   // Skip this code when both the element doesn't exit
   if(assetClassCtrl && selUnivEleID)
   {
	  // Assigning values of the dropdown boxes to a local variable
	  var assetClass = assetClassCtrl.options[assetClassCtrl.selectedIndex].text;
	  var universe=selUnivEleID[selUnivEleID.selectedIndex].value;
	  var isSecRequired = universe.substring(universe.toString().indexOf(":")+1,universe.toString().length);
	  universe=universe.substring(0,universe.toString().indexOf(":"));
	  var sectorDDCtrl=$("qsSectorsDD");
	  
	  if(universe != "VCT")
	  {
		  if(isSecRequired=="True")
		  {
	            //Loading by webservice
	            SectorsByAssetClassQS(universe, "All");
	            
		  }
		  else
		  {
			 sectorDDCtrl.value="";
			 sectorDDCtrl.disabled=true;		 
		  }
		  
		  // To load managers and domicile or geoarea based on universe
		  if(val=="univ")
		  {	  
			 UKQSLoadManangers(universe);
			 if(universe!="U" && universe!="T" && universe!="P" && universe!="N")
			 {
				UKQSLoadDomiciles(universe,"Domicile");
			 }
			 else
			 {
				UKQSLoadDomiciles(universe,"Geoarea");
			 }
		  }
		}		
		else if(universe == "VCT")
		{
			 // Code to load all VCT drop down
			 var sectorDDCtrl=$("qsSectorsDD");
			 var managerDDCtrl=$("qsManagerDD");
			 var assetclassDDCtrl=$("qsAssetClassDD");
			 var domicileDDCtrl=$("qsDomicileDD");
			 
			 // Load Sectors in Assetclass Dropdown box
			 if(assetclassDDCtrl)
			 {
				//Load by web service
			    VCTQSObjects(PopulateVCTQSObjects,universe, "sector");
	        
			 }
			 
			 // Load Manager Dropdown box
			 if(managerDDCtrl)
			 {
			    //Load by web service
			    VCTQSObjects(PopulateVCTQSObjectsManager,universe,"manager");
			 }
			 
			 // Load Geoareas Dropdown box
			 if(domicileDDCtrl)
			 {
			    //Load by webservice	  
                VCTQSObjects(PopulateVCTQSObjectsGeoAreas,universe,"geoareas");
			 }
		}
   }
}  


// Function to load AssetClass and Investment Focus based on the universe code
function UKQSLoadAssetClass(univ)
{
   // var universe=univ.substring(0,univ.toString().indexOf(":"));
   var selUnivEleID = $("qsUniverseDD");
   var universe=selUnivEleID[selUnivEleID.selectedIndex].value;
	//var isSecRequired = universe.substring(universe.toString().indexOf(":")+1,universe.toString().length);
	universe=universe.substring(0,universe.toString().indexOf(":"));
  
   if(universe!="VCT")
   {  
		// Skip this code when this element doesn't exit
		if($("qsAssetClassDD"))
		{	

		    //Load by webservice
		    AssetClassByUniverseQS(universe);
	
		}
	}     
} 


// Function to load Managers based on the universe code
function UKQSLoadManangers(univ)
{
   var universe=univ;
   
   // Skip this code when this element doesn't exit   
   if($("qsManagerDD"))
   {
      //Load by webservice
	  ManagersByUniverseQS(universe);
	  
   }       
}


// Function to load Domicile based on the universe code
function UKQSLoadDomiciles(univ,content)
{
   var universe=univ;
   
   // Skip this code when this element doesn't exit   
   if($("qsDomicileDD"))
   {
		if(content=="Geoarea")
		{
			//Load by webservice
			GeoareaByUniverseQS(universe);
					  
			
		}
		else 
		{
		    //Load by webservice
			DomicilesByUniverseQS(universe);
		  
		    	
		} 
   }       
}

// Function executes when Go button in the quick search for UK is click
function UKQSGoButton()
{
   // Assigning the elements in the local variable
   var selUnivEleID = $("qsUniverseDD");
   var selACEleID = $("qsAssetClassDD");
   var selSectorEleID = $("qsSectorsDD");
   var selDomicileEleID = $("qsDomicileDD");
   var selManagerEleID = $("qsManagerDD");
   var selUnitsEleID = $("qsUnitsDD");
   var selCategoryEleID = $("qsCaterogyDD");
   
   // variable to hold combobox values
   var strSector = "";
   var strAssetclass = "";
   var strManager = "";
   var strDomicile = "";
   var strCategory ="";
   var strUnits = "";
   var strGeoarea = "";
   var ukQSURL = "/Investments/Perf.aspx?"
   
   
   // Skip this code when the element doesn't exit
   if(selUnivEleID)
   {
		// Extracting universe code from universe dropdown
		var universe=selUnivEleID[selUnivEleID.selectedIndex].value;
		universe=universe.substring(0,universe.toString().indexOf(":"));
	  
		// Assigning the values of the dropdown box to local variables 
		strAssetclass = selACEleID[selACEleID.selectedIndex].value;
		if(universe!="VCT")
		{
			strSector = selSectorEleID[selSectorEleID.selectedIndex].value;
		}
		strManager = selManagerEleID[selManagerEleID.selectedIndex].value;
	  
		switch(universe)
		{
			case "U":
				// For Geoarea
				strGeoarea = selDomicileEleID[selDomicileEleID.selectedIndex].value;
				// For Unit Type
				strUnits = selUnitsEleID[selUnitsEleID.selectedIndex].value;
				break;
			case "T":
				// For Geoarea
				strGeoarea = selDomicileEleID[selDomicileEleID.selectedIndex].value;
				// For Unit Type
				strUnits = selUnitsEleID[selUnitsEleID.selectedIndex].value;
				break;
			case "P":
				// For Geoarea
				strGeoarea = selDomicileEleID[selDomicileEleID.selectedIndex].value;
				break;
			case "N":
				// For Geoarea
				strGeoarea = selDomicileEleID[selDomicileEleID.selectedIndex].value;
				break;
			case "VCT":
				// For Geoarea
				strGeoarea = selDomicileEleID[selDomicileEleID.selectedIndex].value;
				break;
			default: // B & E
				strDomicile = selDomicileEleID[selDomicileEleID.selectedIndex].value;
				break;
		}
		
		// Appending URL for performance page
		if(universe!="VCT")
		{
			ukQSURL += UpdateUKQryStr("univ",universe);		
			if(strAssetclass!="A:" && strAssetclass!="I:")
			{	
				if(universe=="B" || universe=="E")				
				{
							//var AssetClassPref=strAssetclass;
							//var isSecRequired = universe.substring(universe.toString().indexOf(":")+1,universe.toString().length);
							var AssetClassPref = strAssetclass.substring(strAssetclass.toString().indexOf(":")+1,strAssetclass.toString().length);
							//AssetClassPref=strAssetclass.substring(0,strAssetclass.toString().indexOf(":"));
							ukQSURL += UpdateUKQryStr("Pf_AssetClass",AssetClassPref);
				}
				else
				{		
					ukQSURL += UpdateUKQryStr("Pf_AssetClass",strAssetclass);
				}
			}
			ukQSURL += UpdateUKQryStr("Pf_Sector",strSector);
			ukQSURL += UpdateUKQryStr("Pf_Manager",strManager);	
			//ukQSURL += UpdateUKQryStr("Pf_Category",strCategory);
			ukQSURL += UpdateUKQryStr("Pf_IncAcc",strUnits);
			if(universe!="U" && universe!="T" && universe!="P" && universe!="N")
			{
				ukQSURL += UpdateUKQryStr("Pf_Domicile",strDomicile);
			}
			else
			{			
				ukQSURL += UpdateUKQryStr("Pf_Geoarea",strGeoarea);		
			}
			// To remove '&' symbol present at the end of the URL
			ukQSURL = ukQSURL.substring(0,ukQSURL.toString().length-1);
		}
		else if(universe=="VCT")
		{
			//"/Investments/VCTPerf.aspx?univ=VCT&VCTPf_Sector=T:VGP&VCTPf_sortedColumn=NameLong&VCTPf_sortedDirection=Asc"
			ukQSURL = "/Investments/VCTPerf.aspx?";
			ukQSURL += UpdateUKQryStr("VCTPf_Sector",strAssetclass);
			ukQSURL += UpdateUKQryStr("VCTPf_Manager",strManager);
			ukQSURL += UpdateUKQryStr("VCTPf_Geoarea",strGeoarea);
			ukQSURL = ukQSURL.substring(0,ukQSURL.toString().length-1);
		}
		
		
		
		//-- Submitting the form using Post method bcz 
		//-- window.loc.. is not working in Moz..
		//alert(ukQSURL);
        //document.forms[0].action = ukQSURL
        //document.forms[0].submit();		
	    window.location = ukQSURL;
	}
}

function PopulateManagerSF(Manager)
{
	  // If no manager loaded then skip
  if(Manager!=null)
  {		 
	 var selectmanagers=$("ManagerDDOption");
	 selectmanagers.options.length=0;
	 var ele=document.createElement("option");
	 ele.text= "Select Manager..";
	 ele.value="";
	 selectmanagers.options.add(ele);
	 
	 // Loop to add all Managers in the Manager Dropdown box
	 for(i=0;i<Manager.length;i++)
	 {
		if(Manager[i]!=null){
		   var ele=document.createElement("option");
		   
		   if(typeof Manager[i].ManagerName !='undefined')
		   {
		       ele.text=Manager[i].ManagerName;
		       ele.value=Manager[i].ManagerCode;
		       selectmanagers.options.add(ele);
		   }
		}
	 }
  } 
}

  function PopulateVCTSFManager(vctManagerObj)
  {
  
        var managerDDCtrl=$("ManagerDDOption");
  
	    if(vctManagerObj)
	    {
		    ClearQSDropDown("ManagerDDOption");
		    for(i=0; i < vctManagerObj.length; i++)
		    {
		      if(vctManagerObj[i]!=null) {
			     var optionElement=document.createElement("option");
			     
			    if(typeof vctManagerObj[i].Name!='undefined')
				 {
					if(vctManagerObj[i].Name=="All Managers")
					{
						optionElement.text="Select Manager..";
					}
					else
					{
						optionElement.text=vctManagerObj[i].Name;
					}
					optionElement.value=vctManagerObj[i].Code;
					managerDDCtrl.options.add(optionElement);
			     }
		      }
		    }
	    }
  }
 
function PopulateSPSFManager(spManagerObject)
{  
	var managerDDCtrl=$("ManagerDDOption");

   if(spManagerObject)
   {
	   ClearQSDropDown("ManagerDDOption");
	   var selectmanagers=$("ManagerDDOption");
		selectmanagers.options.length=0;
		var ele=document.createElement("option");
		ele.text= "Select Manager..";
		ele.value="";
		selectmanagers.options.add(ele);
	 
	   for(i=0; i < spManagerObject.length; i++)
	   {
	      if(spManagerObject[i]!=null) {
		     var ele=document.createElement("option");
		     
		    if(typeof spManagerObject[i].Name!='undefined')
			 {
				ele.text=spManagerObject[i].Name;
				ele.value=spManagerObject[i].Code;
				managerDDCtrl.options.add(ele);
		     }
	      }
	    }
    }
}
 
function UKSFLoadManangers(univ)
{
   var universe=univ;
   
   LoadingUKText('ManagerDDOption');		
   if(univ!='VCT' && univ!='SP')
   {
		// Skip this code when this element doesn't exit   
		if($("ManagerDDOption"))
		{
			//Load by webservice
			setTimeout('',2);
			ManagersByUniverseSF(universe);
		}
	}
	else if(univ=='VCT')
	{
		if($("ManagerDDOption"))
		{
			setTimeout('',2);
			VCTQSObjects(PopulateVCTSFManager,universe,"manager");
		}
	}
	else if(univ=='SP')
	{
		if($("ManagerDDOption"))
		{
			setTimeout('',2);
			SPSFObjects(PopulateSPSFManager,universe,"manager");
		}
	}
}
 
// To select the top value in the given DD
function SelectTopOnDD(obj)
{
	if(obj.value=="0")
	{
		obj.selectedIndex=0;
	}
}

// To update quicksearch querystring parameters
function UpdateUKQryStr(str,val)
{
	if(val=="")
	{
		return "";
	}
	else
	{
		return str + "=" + val + "&";
	}
}


/*  Investor type pop-up  

function InvestorSelectorPopUp(visibleType)
{
	if(visibleType == "visible")
	{
		var userTypePopUpContent = "<div id=\"userTypePopUp\" class=\"landing\" style=\"visibility:"+ visibleType +"\">";
		userTypePopUpContent += "<a href=\"javascript:closeInvestorSelector();void(0)\"><img style=\"float: right; width: 18px; height: 19px; margin: 5px\" src=\"/images/icon_close.png\" alt=\"Close\" /></a>";
		userTypePopUpContent += "<div style=\"width: 1px; height: 100px\">&nbsp;</div>"
		userTypePopUpContent += "<br /><a style=\"margin: 0 0 0 60px\" href=\"javascript:setUser('investor','');void(0)\">I am a private investor without an IFA &raquo;</a>";
		userTypePopUpContent += "<br /><a style=\"margin: 0 0 0 60px\" href=\"javascript:setUser('investor_ifa','');void(0)\">I am a private investor with an IFA &raquo;</a>";
		userTypePopUpContent += "<br /><a style=\"margin: 0 0 0 60px\" href=\"javascript:setUser('adviser','');void(0)\">I am an IFA &raquo;</a>";
		userTypePopUpContent += "<br /><a style=\"margin: 0 0 0 60px\" href=\"javascript:setUser('fundmanager','');void(0)\">I am a retail fund manager &raquo;</a>";
		userTypePopUpContent += "<br /><a style=\"margin: 0 0 0 60px\" href=\"javascript:setUser('marketpro','');void(0)\">I am a market professional &raquo;</a>";
		userTypePopUpContent += "<br /><a style=\"margin: 0 0 0 60px\" href=\"javascript:setUser('institutional','');void(0)\">I am an institutional investor &raquo;</a>";
		userTypePopUpContent += "<br /><div style=\"width: 1px; height: 10px\">&nbsp;</div>";
		userTypePopUpContent += "<span style=\"float: left\"><a href=\"/Help/ContactUs.aspx?text=investorPopup\">Been here before? Click here if you experience any problems.</a></span>";
		userTypePopUpContent += "<br /><div style=\"width: 1px; height: 10px\">&nbsp;</div>";
		userTypePopUpContent += "<span style=\"float: left\"><a href=\"/Education/PrivacyPolicy.aspx\" style=\"float:left\">Why are you asking me this? &raquo;</a></span>";
		userTypePopUpContent += "<span style=\"float: right\"><a href=\"javascript:closeInvestorSelector();void(0)\">Close this window &raquo;</a></span>";
		userTypePopUpContent +="</div>";
		document.getElementById("InvestorSelector").innerHTML=userTypePopUpContent;
	}
	document.getElementById("investorSelectorIFrame").style.visibility = visibleType;
}
*/

/*  Investor type pop-up  */
function InvestorSelectorPopUp(visibleType)
{
	if(visibleType == "visible")
	{
		var userTypePopUpContent = "<div id=\"userTypePopUp\" style=\"visibility:"+ visibleType +"\">";
		userTypePopUpContent +="<div id=\"description\">";
        userTypePopUpContent +="<p>We realise this may be irritating, but occasionally we must ask who you are to make sure our content is suitable for our audience.</p>";
        userTypePopUpContent +="<p>Click the button next to the user type which describes you best. Once that's done you should not see this popup again.</p>";
        userTypePopUpContent +="</div>";
        userTypePopUpContent +="<div id=\"types\">";    
        userTypePopUpContent +="<p><label><input type=\"radio\" value=\"radio\" id=\"radio1\" name=\"radio\" onclick=\"setUser('adviser','')\"/>I am a financial adviser</label></p>";
        userTypePopUpContent +="<p><label><input type=\"radio\" value=\"radio\" id=\"radio2\" name=\"radio\" onclick=\"setUser('investor','')\"/>I am a private investor without a financial adviser</label></p>";
        userTypePopUpContent +="<p><label><input type=\"radio\" value=\"radio\" id=\"radio3\" name=\"radio\" onclick=\"setUser('investor_ifa','')\"/>I am a private investor with a financial adviser</label></p>";
        userTypePopUpContent +="<p><label><input type=\"radio\" value=\"radio\" id=\"radio4\" name=\"radio\" onclick=\"setUser('fundmanager','')\"/>I am a discretionary fund manager</label></p>";
        userTypePopUpContent +="<p><label><input type=\"radio\" value=\"radio\" id=\"radio5\" name=\"radio\" onclick=\"setUser('marketpro','')\"/>I am a market professional</label></p>";       
        userTypePopUpContent +="<p><label><input type=\"radio\" value=\"radio\" id=\"radio6\" name=\"radio\" onclick=\"setUser('institutional','')\"/>I am an institutional investor</label></p>";
        userTypePopUpContent +="<p><label><input type=\"radio\" value=\"radio\" id=\"radio7\" name=\"radio\" onclick=\"setUser('journalist','')\"/>I am a journalist</label></p>";        
                
        userTypePopUpContent +="</div>";
        userTypePopUpContent +="<div id=\"links\"><a href=\"/Help/ContactUs.aspx?text=investorpopup\">You shouldn't see this pop-up more than once,<br/>  click here to report it if you do >></a></div>";
		userTypePopUpContent +="</div>";
		document.getElementById("InvestorSelector").innerHTML=userTypePopUpContent;
	}
	document.getElementById("investorSelectorIFrame").style.visibility = visibleType;
}

/*  Pension search  */

function GoPensionSearch()
{
    DeleteCookie('productSearch');
    window.location.href='/Investments/ProductSearch.aspx?univ=P&Step=1';
}

// Function to trim the given string
function TrimString(str)
{ 
	while(str.charAt(0) == (" "))		
	{ str = str.substring(1);	}
	
	while(str.charAt(str.length-1) == " " )
	{ str = str.substring(0,str.length-1);	}

	return str;
}function EmailContent()
{
	var strBuilder="";		
	strBuilder+='<iframe id="MailIFrame" onload="DisableSelectMail(\'MailIFrame\');" src="" frameborder="0" scrolling="no" style="width:600px;position: absolute;visibility: hidden; top: 203px;left: 505px;border: solid 1px #red;height:170px;"></iframe>'; 		
	strBuilder += '<div id="MailDiv"   onmousedown=EmailZindex(); style="width: 600px;Z-index=1000; position: absolute; visibility: hidden; top: 203px;left: 505px; border: solid 2px #a7c7e7;" >';
	strBuilder += '<table cellpadding="0" cellspacing="0" border="0" width="100%">';
	strBuilder += '<tr id="trHeadMail" title="Email - Double Click here to Minimize/Expand this window" style="height: 23px; cursor:move;  background: url(/images/bgMainMenuActive.gif) repeat-x;" onmousedown="dragMailBox(document.getElementById(\'MailDiv\'),event,document.getElementById(\'MailIFrame\')); return false;" ondblclick="">';
	strBuilder += '<td id="idSelect" style="width: 35%;text-align: left; border-bottom: solid 1px #a7c7e7;padding-left: 6px;">';
	strBuilder += '<b style="color:White; font-size:12px;">Send this link to a friend</b></td>';
	strBuilder += '<td style="text-align: right;width: 65%; padding: 0px 0px 0px 0px;margin: 5px 0px 5px 0px; border-bottom: solid 1px #a7c7e7;">';
	strBuilder += '<b id="idMin" style="cursor:pointer; font-size:16px; color:White;" title ="Minimize" onmouseover="ShadeMail(this)" onmouseout="RShadeMail(this)" onclick="MinimizeMailWindow(\'Email\');">';
	strBuilder += '&nbsp;_&nbsp;';
	strBuilder += '</b> <img id="idMax" src="/images/shape_square.png" title="Maximize" alt="Maximize" style="display:none;vertical-align:middle;border:solid 1px white;width:12px;height:12pxcursor:hand;cursor:pointer;" onclick="MinimizeMailWindow(\'Email\');"/>';
	strBuilder += '<b style="cursor:pointer; vertical-align:middle; font-size:16px; color:White;" id="CloseL" title="Close" onmouseover="ShadeMail(this)" onmouseout="RShadeMail(this)" onclick="HideDiv();">';
	strBuilder += '&nbsp;X&nbsp;';
	strBuilder += '</b></td></tr></table>';
	strBuilder += '<div id="Email" style="visibility:hidden; background-color:White;">';
	strBuilder+='<table border="0" cellpadding="0" celspacing="0">'; 
	strBuilder +='<tr>';
	strBuilder +='<td style="width:150px;text-align:right;padding-right:5px;vertical-align:top;color:#2F6496;">'; 
	strBuilder+='<b>Send To:</b>';
	strBuilder+='</td>';
	strBuilder +='<td>';
	strBuilder+='<input type="text" id="txtTo" name="txtTo" value="" style="width:450px;height:16px;"/>';  
	strBuilder+='</td>';
	strBuilder +='</tr>';
	strBuilder+='<tr>'; 
	strBuilder +='<td style="text-align:right;padding-right:5px;vertical-align:top;color:#2F6496;">';
	strBuilder +='<b>Comment :</b>'; 
	strBuilder+='</td>';
	strBuilder +='<td>';
	strBuilder+='<textarea id="txtComment" name="txtComment" value="" style="width:450px;height:80px;"></textarea>';  
	strBuilder+='</td>';
	strBuilder +='</tr>';
	strBuilder +='<tr>';
	strBuilder +='<td colspan="2" align="center">';
	strBuilder +='<button id="button" style="width:90px;cursor:hand;BORDER:0px; background-color: #fff;" onclick="javascript:PopupMail();return false;"><span style="DISPLAY: block; PADDING-LEFT: 4px;COLOR:#fff; FONT-WEIGHT: bold; BACKGROUND: url(/images/buttonBlue.png) no-repeat left 0px; LINE-HEIGHT: 17px; HEIGHT: 19px"><span id="emailright" style="PADDING-RIGHT: 4px; DISPLAY: block; FONT-WEIGHT: bold; BACKGROUND: url(/images/buttonBlue.png) no-repeat right 0px; LINE-HEIGHT: 17px; HEIGHT: 19px; TEXT-ALIGN: center;COLOR:#fff;">Send mail</span></span></button>';
	strBuilder +='</td>';
	strBuilder +='</tr>';
	strBuilder += '</table>';	
	strBuilder += '</div>';	
	strBuilder += '</div>';	
	return strBuilder;
}

function EmailZindex()
{	
	var id=document.getElementById('MailDiv');	
	var eid=document.getElementById('TimeZoneDiv');	
	var cid=document.getElementById('CalcMainDiv');	
	document.getElementById('trHeadMail').style.background="url(/images/bgMainMenuActive.gif) repeat-x";	
	if(eid)eid.style.zIndex="100";
	if(cid)cid.style.zIndex="100";	
	if(id)id.style.zIndex="2000";	
	document.getElementById('trHeadMail').style.background="url(/images/bgMainMenuActive.gif) repeat-x";	
}

var userEmailId=GetCookie("TN_UserId");
function showMailDiv(idValue)
{	
	//document.getElementById("EmailDiv").innerHTML = EmailContent();
			
	if(userEmailId!='')
	{
		var browsertype=window.navigator.userAgent;
		if(idValue!='shareDiv')
		{		
		var pos;
		if($('setperf')==null)
		{
		pos=getPosition("setprofile");
		}
		else
		{
		 pos=getPosition("setperf"); 
		}
		var top=document.body.clientTop?document.body.clientTop:0;
		top=top+parseInt(pos.y)+22;
		if(browsertype.indexOf("MSIE 7.0")>=0)
		{	
			document.getElementById('MailDiv').style.top=top;
			document.getElementById('MailIFrame').style.top=top;
		}else if(browsertype.indexOf("MSIE 6.0")>=0) 
		{
			 document.getElementById('MailDiv').style.top=top-71;
			 document.getElementById('MailIFrame').style.top=top-71;	 
		} else
		{
			document.getElementById('MailDiv').style.top=top+"px";
			document.getElementById('MailIFrame').style.top=top+"px";
		}
		document.getElementById('MailDiv').style.visibility='visible';
		document.getElementById('Email').style.visibility='visible';
		document.getElementById('MailIFrame').style.visibility='';	
		document.getElementById('MailIFrame').style.height='170px';
		document.getElementById('MailDiv').style.left='505px';
		document.getElementById('MailIFrame').style.left='505px';
		document.getElementById('MailDiv').style.zIndex="1000";				
		document.getElementById("MailDiv").style.height = '170px';
		document.getElementById("Email").style.height = '146px';				
		document.getElementById("idMin").style.display = '';
		document.getElementById("idMax").style.display = 'none';	
		EmailZindex();
		document.getElementById('trHeadMail').style.background="url(/images/bgMainMenuActive.gif) repeat-x";
		}else if(idValue=='shareDiv')
		{
			var pos;
			pos=getPosition("shareDiv");
			var top=document.body.clientTop?document.body.clientTop:0;
			top=top+parseInt(pos.y)+32;
			$("FooterMailDiv").innerHTML=EmailContent();
			if(browsertype.indexOf("MSIE 7.0")>=0)
			{	
				document.getElementById('MailDiv').style.top=top;
				document.getElementById('MailIFrame').style.top=top;
			}else if(browsertype.indexOf("MSIE 6.0")>=0) 
			{
				 document.getElementById('MailDiv').style.top=top-71;
				 document.getElementById('MailIFrame').style.top=top-71;	 
			} else
			{
				document.getElementById('MailDiv').style.top=top+"px";
				document.getElementById('MailIFrame').style.top=top+"px";
			}
			document.getElementById('MailDiv').style.visibility='visible';
			document.getElementById('Email').style.visibility='visible';
			document.getElementById('MailIFrame').style.visibility='';	
			document.getElementById('MailIFrame').style.height='170px';
			document.getElementById('MailDiv').style.left='300px';
			document.getElementById('MailIFrame').style.left='300px';
			document.getElementById('MailDiv').style.zIndex="1000";				
			document.getElementById("MailDiv").style.height = '170px';
			document.getElementById("Email").style.height = '146px';				
			document.getElementById("idMin").style.display = '';
			document.getElementById("idMax").style.display = 'none';	
			EmailZindex();
			document.getElementById('trHeadMail').style.background="url(/images/bgMainMenuActive.gif) repeat-x";	
		}		
	}else
	{
		alert('Please Login');
	}
}

function HideDiv()
{
	document.getElementById('MailDiv').style.visibility='hidden';
	document.getElementById('Email').style.visibility='hidden';
	document.getElementById('MailIFrame').style.visibility='hidden';
}

function DisableSelectMail(id) 
{	
	document.getElementById(id).onselectstart = function() {return false;} // ie
	document.getElementById(id).onmousedown = function() {return false;} // mozilla
	
}
function getValues()
{
	var recepient=document.getElementById('txtTo').value;
	var comment=document.getElementById('txtComment').value;
	var url=location.href;	
}


//Global Variables for Email.
var AgainOpn=false;
var strMemory="0";
var PrimaryNo=parseFloat("0");
var CurrentOpn="";
var OpnSelected=false;

//Minimize Window is the function to Minimise Currency Gadjet Window.
//To Minimise Current Window to Bottom.
//<params> Div Id  </params>
function MinimizeMailWindow(divID)
{
	//Code here for Minimising Div.
	if(document.getElementById(divID).style.visibility == 'visible')
	{	
		document.getElementById(divID).style.visibility = 'hidden';
		document.getElementById("MailDiv").style.height = '21px';		
		document.getElementById("Email").style.height = '21px';		
		document.getElementById("MailIFrame").style.height = '21px';
		document.getElementById("idMin").style.display = 'none';
		document.getElementById("idMax").style.display = '';			
	}
	else
	{
		document.getElementById(divID).style.visibility = 'visible';
		document.getElementById("MailDiv").style.height = '170px';
		document.getElementById("Email").style.height = '146px';		
		document.getElementById("MailIFrame").style.height = '170px';
		document.getElementById("idMin").style.display = '';
		document.getElementById("idMax").style.display = 'none';								
	}	
}

///Drag Object.
// This will Drag object corresponding to the Cursor Movement.
function $(s) 
{ 
	return(document.getElementById(s)); 
}

function Mailagent(s) 
{ 
	return(Math.max(navigator.userAgent.toLowerCase().indexOf(s),0)); 
}

function xy(e,s) 
{ 
	return(s?(Mailagent('msie')?event.clientY+document.body.scrollTop:e.pageY):(Mailagent('msie')?event.clientX+document.body.scrollTop:e.pageX)); 
} 
//document.getElementById('trHeadMail');
function dragMailBox(d,e,ifid) 
{ 		
	function drag(e) 
	{ 
		document.getElementById('trHeadMail').style.background="url(/images/bgMainMenuActive.gif) repeat-x";
		if(!stop) 
		{ 
			d.style.top=(tX=xy(e,1)+oY-eY+'px'); 
			d.style.left=(tY=xy(e)+oX-eX+'px'); 
			ifid.style.top=(tX=xy(e,1)+oY-eY+'px'); 
			ifid.style.left=(tY=xy(e)+oX-eX+'px'); 
			//alert(document.getElementById('MailDiv').style.top+','+document.getElementById('MailDiv').style.left);
			//controlDrag(d,ifid);
		} 
	} 	
	var oX=parseInt(d.style.left),oY=parseInt(d.style.top),eX=xy(e),eY=xy(e,1),tX,tY,stop; 	
	document.onmousemove=drag; document.onmouseup=function()
	{ 
		stop=0; 
		document.getElementById('trHeadMail').style.background="url(/images/bgMainMenuActive.gif) repeat-x";
		document.onmousemove=''; 
		document.onmouseup=''; 
	}; 
}

//Make shading while Cursor Moves.

function ShadeMail(ctl)
{
	ctl.style.background="#1A5083";
}

// Remove Shading while Cursor Out.
function RShadeMail(ctl)
{
	ctl.style.background="";	
}

function PopupMail()
{				
	if(ValidateForm()==true){
	var to=document.getElementById('txtTo').value; 
	var Message=document.getElementById('txtComment').value; 
	var url=location.href; 
	var logUserName=document.getElementById('logeduserName').value;
	
	var test=FinancialExpress.EmailComponent.EmailCreator.sendPopupMail(to,Message,url,logUserName,emailSiteCode+','+emailSitemailid+','+emailDomain+','+emailSiteName+','+siteUserEmail);	
	document.getElementById('txtTo').value=''; 
	document.getElementById('txtComment').value=''; 
	document.getElementById('MailDiv').style.visibility='hidden';
	document.getElementById('Email').style.visibility='hidden';	
	document.getElementById('MailIFrame').style.visibility='hidden';	
	}
}


function echeck(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)

	 if (str.indexOf(at)==-1){
		   alert("Invalid E-mail ID");
		   return false;
		}

	 if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   alert("Invalid E-mail ID");
		   return false;
		}

	 if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    alert("Invalid E-mail ID");
		    return false;
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    alert("Invalid E-mail ID");
		    return false;
		 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    alert("Invalid E-mail ID");
		    return false;
		 }

	 if (str.indexOf(dot,(lat+2))==-1){
		    alert("Invalid E-mail ID");
		    return false;
		 }

		if(str.indexOf(" ")!=-1){
		    alert("Invalid E-mail ID");
		    return false;
		 }
 		 return true
	}
	function ValidateForm(){	
	if(document.getElementById('MailDiv').style.visibility=="visible")
	{
		var emailID=document.getElementById('txtTo');			
		if ((emailID.value==null)||(emailID.value=="")){
			alert("Please Enter your Email ID")
			emailID.focus()
			return false
		}
		if (echeck(emailID.value)==false){
			emailID.value=""
			emailID.focus()
			return false
		}
		return true
	}
 }
 


function controlDrag(d,ifid)
{			
	var totalLeft=parseInt(d.style.left.replace('px',''))+600;	
	var totalTop=parseInt(d.style.top.replace('px',''))+d.style.height.replace('px','');		
	var pageWidth =window.screen.width;		
	var pageHeight=window.screen.height;
	
	if(totalLeft>(pageWidth-1))
	{	
		if(d.style.top.replace('px','')<0 || (d.style.top<"0px"))
		{			
			if (navigator.appName.indexOf("Microsoft") == -1) {
				d.style.left=pageWidth-605+"px";
				ifid.style.left=pageWidth-605+"px";
			}							
				d.style.left=pageWidth-605;
				ifid.style.left=pageWidth-605;
				
			d.style.top=0;
			ifid.style.top=0;
			if (navigator.appName.indexOf("Microsoft") == -1) {
			 d.style.top=0+"px";
			 ifid.style.top=0+"px";			
			 }
		}else if(totalTop>(pageHeight))
		{
			if (navigator.appName.indexOf("Microsoft") == -1) {
				d.style.left=pageWidth-605+"px";
				ifid.style.left=pageWidth-605+"px";
			}							
				d.style.left=pageWidth-605;
				ifid.style.left=pageWidth-605;
			if (navigator.appName.indexOf("Microsoft") == -1) {
				var topmoz=pageHeight -d.style.height.replace('px','');
				d.style.top=topmoz+"px";
				ifid.style.top=topmoz+"px";
			}
			d.style.top=pageHeight-d.style.height.replace('px','');	
			ifid.style.top=pageHeight-d.style.height.replace('px','');				 
		}else
		{
			if (navigator.appName.indexOf("Microsoft") == -1) {
				d.style.left=pageWidth-605+"px";
				ifid.style.left=pageWidth-605+"px";
			}							
			d.style.left=pageWidth-605;
			ifid.style.left=pageWidth-605;		
		}
	}	
	else if(d.style.left.replace('px','')<0|| (d.style.left<'0px'))
	{	
		if(d.style.top.replace('px','')<0 || (d.style.top<"0px"))
		{					
			d.style.left=0;	
			ifid.style.left=0;	
			if (navigator.appName.indexOf("Microsoft") == -1) {
			 d.style.left=0+"px";
			 ifid.style.left=0+"px";
			}	
			d.style.top=0;
			ifid.style.top=0;
			if (navigator.appName.indexOf("Microsoft") == -1) {
			 d.style.top=0+"px";
			 ifid.style.top=0+"px";
			 }
		}else if(totalTop>(pageHeight))
		{
			d.style.left=0;	
			ifid.style.left=0;	
			if (navigator.appName.indexOf("Microsoft") == -1) {
			 d.style.left=0+"px";
			 ifid.style.left=0+"px";
			}	
			if (navigator.appName.indexOf("Microsoft") == -1) {
				var topmoz=pageHeight -d.style.height.replace('px','');
			d.style.top=topmoz+"px";
			ifid.style.top=topmoz+"px";
			}
			d.style.top=pageHeight-d.style.height.replace('px','');			
			ifid.style.top=pageHeight-d.style.height.replace('px','');			
		}
		else
		{						
			d.style.left=0;
			ifid.style.left=0;	
			if (navigator.appName.indexOf("Microsoft") == -1) {
			 d.style.left=0+"px";
			 ifid.style.left=0+"px";
			}	
		}			
	}	
	else if(totalTop>(pageHeight))
	{					
		if (navigator.appName.indexOf("Microsoft") == -1) {
			var topmoz=pageHeight -d.style.height.replace('px','');
			d.style.top=topmoz+"px";
			ifid.style.top=topmoz+"px";
		}
		d.style.top=pageHeight-d.style.height.replace('px','');
		ifid.style.top=pageHeight-d.style.height.replace('px','');		
	}	
	else if(d.style.top.replace('px','')<0 || (d.style.top<"0px"))
	{
		d.style.top=0;
		ifid.style.top=0;
		if (navigator.appName.indexOf("Microsoft") == -1) {
		 d.style.top=0+"px";
		 ifid.style.top=0+"px";
		}	
	}				
}/* SpryMenuBar.js - Revision: Spry Preview Release 1.4 */

// Copyright (c) 2006. Adobe Systems Incorporated.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//   * Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//   * Neither the name of Adobe Systems Incorporated nor the names of its
//     contributors may be used to endorse or promote products derived from this
//     software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

/*******************************************************************************

 SpryMenuBar.js
 This file handles the JavaScript for Spry Menu Bar.  You should have no need
 to edit this file.  Some highlights of the MenuBar object is that timers are
 used to keep submenus from showing up until the user has hovered over the parent
 menu item for some time, as well as a timer for when they leave a submenu to keep
 showing that submenu until the timer fires.

 *******************************************************************************/

var Spry;
if(!Spry)
{
	Spry = {};
}
if(!Spry.Widget)
{
	Spry.Widget = {};
}

// Constructor for Menu Bar
// element should be an ID of an unordered list (<ul> tag)
// preloadImage1 and preloadImage2 are images for the rollover state of a menu
Spry.Widget.MenuBar = function(element, opts)
{
	this.init(element, opts);
};

Spry.Widget.MenuBar.prototype.init = function(element, opts)
{
	this.element = this.getElement(element);

	// represents the current (sub)menu we are operating on
	this.currMenu = null;

	var isie = (typeof document.all != 'undefined' && typeof window.opera == 'undefined' && navigator.vendor != 'KDE');
	if(typeof document.getElementById == 'undefined' || (navigator.vendor == 'Apple Computer, Inc.' && typeof window.XMLHttpRequest == 'undefined') || (isie && typeof document.uniqueID == 'undefined'))
	{
		// bail on older unsupported browsers
		return;
	}

	// load hover images now
	if(opts)
	{
		for(var k in opts)
		{
			var rollover = new Image;
			rollover.src = opts[k];
		}
	}

	if(this.element)
	{
		this.currMenu = this.element;
		var items = this.element.getElementsByTagName('li');
		for(var i=0; i<items.length; i++)
		{
			this.initialize(items[i], element, isie);
			if(isie)
			{
				this.addClassName(items[i], "MenuBarItemIE");
				items[i].style.position = "static";
			}
		}
		if(isie)
		{
			if(this.hasClassName(this.element, "MenuBarVertical"))
			{
				this.element.style.position = "relative";
			}
			var linkitems = this.element.getElementsByTagName('a');
			for(var i=0; i<linkitems.length; i++)
			{
				linkitems[i].style.position = "relative";
			}
		}
	}
};

Spry.Widget.MenuBar.prototype.getElement = function(ele)
{
	if (ele && typeof ele == "string")
		return document.getElementById(ele);
	return ele;
};

Spry.Widget.MenuBar.prototype.hasClassName = function(ele, className)
{
	if (!ele || !className || !ele.className || ele.className.search(new RegExp("\\b" + className + "\\b")) == -1)
	{
		return false;
	}
	return true;
};

Spry.Widget.MenuBar.prototype.addClassName = function(ele, className)
{
	if (!ele || !className || this.hasClassName(ele, className))
		return;
	ele.className += (ele.className ? " " : "") + className;
};

Spry.Widget.MenuBar.prototype.removeClassName = function(ele, className)
{
	if (!ele || !className || !this.hasClassName(ele, className))
		return;
	ele.className = ele.className.replace(new RegExp("\\s*\\b" + className + "\\b", "g"), "");
};

// addEventListener for Menu Bar
// attach an event to a tag without creating obtrusive HTML code
Spry.Widget.MenuBar.prototype.addEventListener = function(element, eventType, handler, capture)
{
	try
	{
		if (element.addEventListener)
		{
			element.addEventListener(eventType, handler, capture);
		}
		else if (element.attachEvent)
		{
			element.attachEvent('on' + eventType, handler);
		}
	}
	catch (e) {}
};

// createIframeLayer for Menu Bar
// creates an IFRAME underneath a menu so that it will show above form controls and ActiveX
Spry.Widget.MenuBar.prototype.createIframeLayer = function(menu)
{
	var layer = document.createElement('iframe');
	layer.tabIndex = '-1';
	layer.src = 'javascript:false;';
	menu.parentNode.appendChild(layer);
	
	layer.style.left = menu.offsetLeft + 'px';
	layer.style.top = menu.offsetTop + 'px';
	layer.style.width = menu.offsetWidth + 'px';
	layer.style.height = menu.offsetHeight + 'px';
};

// removeIframeLayer for Menu Bar
// removes an IFRAME underneath a menu to reveal any form controls and ActiveX
Spry.Widget.MenuBar.prototype.removeIframeLayer =  function(menu)
{
	var layers = menu.parentNode.getElementsByTagName('iframe');
	while(layers.length > 0)
	{
		layers[0].parentNode.removeChild(layers[0]);
	}
};

// clearMenus for Menu Bar
// root is the top level unordered list (<ul> tag)
Spry.Widget.MenuBar.prototype.clearMenus = function(root)
{
	var menus = root.getElementsByTagName('ul');
	for(var i=0; i<menus.length; i++)
	{
		this.hideSubmenu(menus[i]);
	}
	this.removeClassName(this.element, "MenuBarActive");
};

// bubbledTextEvent for Menu Bar
// identify bubbled up text events in Safari so we can ignore them
Spry.Widget.MenuBar.prototype.bubbledTextEvent = function()
{
	return (navigator.vendor == 'Apple Computer, Inc.' && (event.target == event.relatedTarget.parentNode || (event.eventPhase == 3 && event.target.parentNode == event.relatedTarget)));
};

// showSubmenu for Menu Bar
// set the proper CSS class on this menu to show it
Spry.Widget.MenuBar.prototype.showSubmenu = function(menu)
{
	if(this.currMenu)
	{
		this.clearMenus(this.currMenu);
		this.currMenu = null;
	}
	
	if(menu)
	{
		this.addClassName(menu, "MenuBarSubmenuVisible");
		if(window.navigator.userAgent.indexOf("MSIE 6.0")>=0)
		{
			if(typeof document.all != 'undefined' && typeof window.opera == 'undefined' && navigator.vendor != 'KDE')
			{
				if(!this.hasClassName(this.element, "MenuBarHorizontal") || menu.parentNode.parentNode != this.element)
				{
					menu.style.top = menu.parentNode.offsetTop + 'px';
				}
			}
			if(typeof document.uniqueID != "undefined")
			{
				this.createIframeLayer(menu);
			}
        }
	}
	this.addClassName(this.element, "MenuBarActive");
};

// hideSubmenu for Menu Bar
// remove the proper CSS class on this menu to hide it
Spry.Widget.MenuBar.prototype.hideSubmenu = function(menu)
{
	if(menu)
	{
		this.removeClassName(menu, "MenuBarSubmenuVisible");
		if(typeof document.all != 'undefined' && typeof window.opera == 'undefined' && navigator.vendor != 'KDE')
		{
			menu.style.top = '';
			menu.style.left = '';
		}
		this.removeIframeLayer(menu);
	}
};

// initialize for Menu Bar
// create event listeners for the Menu Bar widget so we can properly
// show and hide submenus
Spry.Widget.MenuBar.prototype.initialize = function(listitem, element, isie)
{
	var opentime, closetime;
	var link = listitem.getElementsByTagName('a')[0];
	var submenus = listitem.getElementsByTagName('ul');
	var menu = (submenus.length > 0 ? submenus[0] : null);

	var hasSubMenu = false;
	if(menu)
	{
		this.addClassName(link, "MenuBarItemSubmenu");
		hasSubMenu = true;
	}

	if(!isie)
	{
		// define a simple function that comes standard in IE to determine
		// if a node is within another node
		listitem.contains = function(testNode)
		{
			// this refers to the list item
			if(testNode == null)
			{
				return false;
			}
			if(testNode == this)
			{
				return true;
			}
			else
			{
				return this.contains(testNode.parentNode);
			}
		};
	}
	
	// need to save this for scope further down
	var self = this;

	this.addEventListener(listitem, 'mouseover', function(e)
	{
		if(self.bubbledTextEvent())
		{
			// ignore bubbled text events
			return;
		}
		clearTimeout(closetime);
		if(self.currMenu == listitem)
		{
			self.currMenu = null;
		}
		// show menu highlighting
		self.addClassName(link, hasSubMenu ? "MenuBarItemSubmenuHover" : "MenuBarItemHover");
		if(menu && !self.hasClassName(menu, "MenuBarSubmenuVisible"))
		{
			opentime = window.setTimeout(function(){self.showSubmenu(menu);}, 0.01);
		}
	}, false);

	this.addEventListener(listitem, 'mouseout', function(e)
	{
		if(self.bubbledTextEvent())
		{
			// ignore bubbled text events
			return;
		}

		var related = (typeof e.relatedTarget != 'undefined' ? e.relatedTarget : e.toElement);
		if(!listitem.contains(related))
		{
			clearTimeout(opentime);
			self.currMenu = listitem;

			// remove menu highlighting
			self.removeClassName(link, hasSubMenu ? "MenuBarItemSubmenuHover" : "MenuBarItemHover");
			if(menu)
			{
				closetime = window.setTimeout(function(){self.hideSubmenu(menu);}, 80);
			}
		}
	}, false);
};

function AutoSuggest(elem,chkRadio)
{
    this.debug=false;
    
    this.searchType = "";
    this.suggestType="";
    this.suggestDivID = "";
    this.hiddenID="";
    this.enabledRadio=chkRadio;
	this.listClick=null; 
	
	var me = this;

	this.elem = elem;

	this.suggestion = new suggestions();
	
	this.inputText = null; 

	this.highlighted = -1;
	 
	this.requesting=false; 
	this.submission_state=false;
	this.div = (this.suggestDivID=="")?$("autosuggest"):$(this.suggestDivID);
    
	var TAB = 9;
	var ESC = 27;
	var KEYUP = 38;
	var KEYLEFT = 37;
	var KEYRIGHT = 39;
	var KEYDN = 40;
	var ENTER = 13;
    var SHIFT = 16;
	
	elem.setAttribute("autocomplete","off");
    
	if(!elem.id)
	{
		var id = "autosuggest" + idCounter;
		idCounter++;

		elem.id = id;
	}


    elem.onkeypress = function(ev)
	{
	 
		var key = me.getKeyCode(ev);

		switch(key)
		{
			case ENTER: 	
			me.cancelEvent(ev);
			return false;
			break;
		}
	}
	
    elem.onblur = function(ev)
	{
	    if(this.value == '' && typeof  me.defaultText !='undefined') 
	    { 
	        this.value = me.defaultText; 
	        
	        if(me.hiddenID && typeof me.hiddenID !='undefined')
	        {
	          $(me.hiddenID).value='';
	           
	           if(me.searchType=='sector')
			   {
				   $(me.includeSectorID).style.visibility='hidden';
			    }
	        }
	    }
	    
	   // me.blurTimeout(1000);   
	   
	}
	

	elem.onkeydown = function(ev)
	{
		var key = me.getKeyCode(ev);

		switch(key)
		{
			case TAB:
			
			if(me.highlighted > -1)
            {  
                if(me.suggestType=="hidden")
                {
			        $(me.hiddenID).value=me.suggestion.list[me.highlighted].Code;
				    me.elem.value=me.suggestion.list[me.highlighted].Name;
				}
				else
				{
			        me.useSuggestion();
			    }
			}
			
			break;

			case ESC:
			if(!me.requesting)
			{   me.hideDiv();
			  
			}
			me.cancelEvent(ev);
			break;

			case KEYUP:
			if (me.highlighted > -1)
			{
				me.highlighted--;
			}
			me.changeHighlight(key);
			break;

			case KEYDN:
			
			if (me.highlighted < (me.suggestion.list.length - 1))
			{
				me.highlighted++;			
    
			}
			
			me.changeHighlight(key);
			
			break;
			 
			case ENTER:
			
			if(me.highlighted > -1)
            {  
                if(me.suggestType!="hidden")
                {        
                     if(typeof me.controlType!='undefined' && me.controlType=="listbox")
	                 {  me.elem.value=me.suggestion.list[me.highlighted].Name;
	                 }
	                    
	                    
				     if(me.searchType.toUpperCase() == "MANAGER") 
				     {   
					    GotoManagerFactsheet(me.suggestion.list[me.highlighted].Code,me.suggestion.list[me.highlighted].Univ);
				     }
				     else if(me.searchType.toUpperCase() == "GROUP") 
				     {
					    GotoGroupFactsheet(me.suggestion.list[me.highlighted].Code,me.suggestion.list[me.highlighted].Univ);
				     }
				     else 
				     {
					    GotoFundFactsheet(me.suggestion.list[me.highlighted].Code,me.suggestion.list[me.highlighted].Univ);
				     }
				      me.submission_state=true;
				 }
				 else
				 {
				    $(me.hiddenID).value=me.suggestion.list[me.highlighted].Code;
				    me.elem.value=me.suggestion.list[me.highlighted].Name;
				    
				    if(me.searchType=='sector')
				    {
				        $(me.includeSectorID).style.visibility='';
				        $(me.bindedHidMgr).value='';
				        $(me.bindedTxtMgr).value='Enter manager name';
				    }
				 }
				 			    
			    me.hideDiv();
			   
            }
            else if(elem.value.length>0&&me.suggestType!="hidden"&&me.controlType!="listbox")
            { 
                var txtSearch=escape(me.elem.value.urlEncode());
                
                if(!ValidateString(txtSearch))
		        {		         
			        alert('Invalid input, please provide valid input.');
			        return false;
		        }
		        else
		        {
                    searchSubmit(txtSearch);
                    me.submission_state=true;
                }
            }
           
            me.cancelEvent(ev);
            
            break;
		}
	};
	
 

	elem.onkeyup = function(ev) 
	{
		var key = me.getKeyCode(ev);
		if(this.enabledRadio==null || this.enabledRadio.checked)
		{
		    switch(key)
		    {
		        case TAB:
		        case ESC:
		        case KEYUP:
		        case KEYDN:
		        case KEYRIGHT:
		        case KEYLEFT:
		        case SHIFT:
		        case ENTER:
		            return;
    		
		        default:
               
			        if (!me.requesting&&this.value != me.inputText && (this.value.length > 2||(this.value.length>0&&me.controlType=='listbox')))
			        {
        	               	
			               if(typeof me.listClick == 'object' && me.searchType=='fund')
			               {
			                    if(me.searchType=="fund" && $(me.hiddenGroupID).value=="")
                                {
                                    alert("Please select a group");
                                    return;
                                }
                                
			                    me.inputText = this.value;
			                    var temp=me.searchType;                                
                                
                                if(!me.hiddenGroupID || $(me.hiddenGroupID).value=="")
                                {            
                                    me.searchType="fundbyuniverse";   
                                    me.requesting=true;         
                                    me.swiftLoad(me.inputText);
                                }
                                else
                                {
                                    me.searchType="fundbygroup";   
                                    me.requesting=true;         
                                    me.swiftLoad($(me.hiddenGroupID).value+'||'+me.inputText);
                                }                            
                                
                                me.searchType=temp;
                            }
                            else if(typeof me.listClick == 'object' && me.searchType=='manager' && me.hiddenSectorID && $(me.hiddenSectorID).value!="" )			           
                            {
                                 me.inputText = this.value;
			                     var temp=me.searchType;                                                                
                                 me.searchType="managerbysector";   
                                 me.requesting=true;         
                                 me.swiftLoad($(me.hiddenSectorID).value+'||'+me.inputText);
                                 me.searchType=temp;
                            }
                            else
                            {
                               me.inputText = this.value;
        		               me.requesting=true;
			                   me.swiftLoad(me.inputText);	
                            }
			               
			               	             
    		       
			        }
			        else if(!me.requesting&&this.value == me.inputText && (this.value.length > 2||(this.value.length>0&&me.controlType=='listbox')))
			        {
			            me.showDiv();
			        }
			        else
			        {
			            if(this.value.length<3)
			            { 
			                me.suggestion.keyword='';
			                me.suggestion.list.length=0;
			            }
    			       
				        me.hideDiv();
			        }
		        }
		   }
	};
	
    this.clickTimeout=function(ms,keyword)
	{
	    var _self = this;
	    
	    if(keyword=='')
        {   
            setTimeout(function(ms){_self.clickShow(keyword);}, ms);       
        }
        else
        {
            setTimeout(function(ms){_self.clickShowManager(keyword);}, ms);       
        }
    
	};
	
	this.clickShow=function(keyword)
	{ 
	    me.requesting=true;
        me.swiftLoad(keyword);
     }
    
    this.clickShowManager=function(keyword)
	{ 
	    var temp=me.searchType;
	    me.searchType="managerbysector"; 
	    me.requesting=true;
        me.swiftLoad(keyword);
        me.searchType=temp;
        
     }
          
	
	this.setListButton=function(obj)
	{
	 
        me.listClick=obj;
        me.listClick.onclick=function(ev)
        {
            //setTimeout("$('" + me.elem.id + "').value='loading...';",0);
            me.elem.value='loading...';      
            me.clickTimeout(100,'');                  
            //alert(me.elem.value);
            
        }
        
      }
      
    this.setGroupListButton=function(obj)
	{
	 
        this.listClick=obj;
        this.listClick.onclick=function(ev)
        { 
            if(me.searchType=="fund" && $(me.hiddenGroupID).value=="")
            {
                alert("Please select a group");
                return;
            }
            
            var temp=me.searchType;
            me.elem.value='loading...';
            
            if($(me.hiddenGroupID).value=="")
            {            
                me.searchType="fundbyuniverse";   
                me.requesting=true;         
                me.swiftLoad('xxx');
            }
            else
            {
                me.searchType="fundbygroup";   
                me.requesting=true;         
                me.swiftLoad($(me.hiddenGroupID).value);
            }
            
            
            me.searchType=temp;
            me.cancelEvent(ev);
        }
        
        this.listClick.onkeydown = function(ev)
	    {
		    var key = me.getKeyCode(ev);

		    switch(key)
		    {
			    case ESC:
			    if(!me.requesting)
			    {   me.hideDiv();
    			  
			    }
			    me.cancelEvent(ev);
			    break;
		    }
		}	
    }
      
    this.setSectorListButton=function(obj)
	{
	 
        this.listClick=obj;
        this.listClick.onclick=function(ev)
        { 
            
            me.elem.value='loading...';
            
            if($(me.hiddenSectorID).value!="")
            {     
                me.clickTimeout(100,$(me.hiddenSectorID).value);      
            }
            else
            {              
                me.clickTimeout(100,'');      
            }            
            
         
        }
        
        this.listClick.onkeydown = function(ev)
	    {
		    var key = me.getKeyCode(ev);

		    switch(key)
		    {
			    case ESC:
			    if(!me.requesting)
			    {   me.hideDiv();
    			  
			    }
			    me.cancelEvent(ev);
			    break;
		    }
		}	
    }  
      
    this.swiftLoad=function(txt)
    {
     
        var a=document.createElement("script");
        a.setAttribute("id","sugg_funds");
        var searchQuery = (me.searchType != "") ? "&type="+me.searchType : "";
        a.src="/Tools/Suggest.aspx?q="+encodeURIComponent(txt)+searchQuery;
        var b=$("sugg_funds"),d=document.getElementsByTagName("head")[0];
        if(b)d.removeChild(b);
        d.appendChild(a);
        me.requestLoadTimeout(50);
    }
  
    this.requestLoadTimeout=function(ms)
	{
	    var _self = this;
        var t=setTimeout(function(ms){_self.requestLoadTimeout(ms);}, ms);
        
        if(typeof sF=='object')
        {  
           me.doSuggestion(sF);
           clearTimeout(t);         
        }
    
	};
	
	this.requestTimeout=function(ms,txt)
	{
	
	  if(!me.submission_state)
	  {
	      var _self = this;
          setTimeout(function(ms){_self.deferRequest(''+txt+'');}, ms);
       }
	};
     
     
    this.deferRequest=function(txt)
    {
       if(!me.requesting&&me.inputText==txt)
       {  
           if(!me.submission_state)
           {                
               me.requesting=true;               
               me.swiftLoad(me.inputText);
    		}    
		}	
    };
    
    this.doSuggestion=function(res)
    {
        me.requesting=false;
        
        var result=[];
        
        if(typeof res == 'object')
        {   result=res;
        
        }
        else
        {
          if(me.debug)
          { 
            alert('response not in correct format ');
            
          }
          return;
        }  
       
        
        me.suggestion.list=result.slice();
		me.suggestion.keyword=me.inputText;
		
		delete sF;
		 
		
		if(!me.submission_state && me.suggestion.list.length>0&&(me.enabledRadio==null || me.enabledRadio.checked))
		{   
		    me.createDiv();
		    me.positionDiv();
		    me.showDiv();
		    
		    if(me.elem.value=='loading...')
            {   setTimeout("$('" + me.elem.id + "').value='';",0);
                me.elem.value='';
            }
		}
		else
	    {   
		    me.hideDiv();
	    }

        
        
    };

  
  
	this.blurTimeout=function(ms)
	{	
	    var _self = this;
        setTimeout(function(ms){_self.hideDiv();}, ms);
      
	};
      
 
	this.useSuggestion = function()
	{
		if (this.highlighted > -1)
		{
		    this.elem.value = this.suggestion.list[this.highlighted].Name;
			this.hideDiv();
			setTimeout("$('" + this.elem.id + "').focus()",0);
		}
	};


	this.showDiv = function()
	{
		this.div.style.display = 'block';
	};


	this.hideDiv = function()
	{
		this.div.style.display = 'none';
		this.highlighted = -1;
	};

	  
    this.changeHighlight = function()
    {
        if(typeof me.controlType!='undefined' && me.controlType=="listbox")
	    {   
	         var lis = this.div.getElementsByTagName('SELECT');
	         if(lis.length>0)
	         {  
                 for(var i=0;i<lis[0].options.length;i++)
                 {
                     var li = lis[0].options[i];
                     
                     if (this.highlighted == i)
                     {  
                        li.selected=true; 
                                          
                     }
                     else
                     {
                        li.selected=false;
                     }
                  }  
              }
	    }
	    else
	    {
             var lis = this.div.getElementsByTagName('LI');
             for(var i=0;i<lis.length;i++)
             {
                var li = lis[i];
     
                 if (this.highlighted == i)
                 {                
                    li.className = "selected";
                    
                    if(i>18)
                    {   
                        this.div.scrollTop=i*10;
                    }
                    else
                    {   
                        this.div.scrollTop=0;  
                    }
                 }
                 else
                 {
                    li.className = "";
                 }
             }
         }
     };

	this.positionDiv = function()
	{
		var el = this.elem;
		var x = 0;
		var y = el.offsetHeight;
	
		while (el.offsetParent && el.tagName.toUpperCase() != 'BODY')
		{
			x += el.offsetLeft;
			y += el.offsetTop;
			el = el.offsetParent;
		}

		x += el.offsetLeft;
		y += el.offsetTop;

  
		this.div.style.left = x + 'px';
		this.div.style.top = y + 'px';
	};   
    
    
	this.createDiv = function()
	{
		var ul = document.createElement('ul');
      	this.div = (this.suggestDivID=="")?$("autosuggest"):$(this.suggestDivID);
        
        var selectList=null; 
        if(typeof me.controlType!='undefined' && me.controlType=="listbox")
	    {
	    
	        if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
	        { 
                var ieversion=new Number(RegExp.$1) 
                if (ieversion<7)
                {
                    selectList=document.createElement('<select multiple=\"multiple\"></select>');    
                }
                else
                {
                    selectList=document.createElement('SELECT');    
                }
      
             }
             else
             {
                selectList=document.createElement('SELECT');    
             }
	    
            //alert('its a list');
           //selectList=document.createElement('SELECT');    
           //selectList.setAttribute("type","select-multiple");
           
           if(me.suggestion.list.length>15)
           { selectList.setAttribute("size","15");
           }
           else
           { selectList.setAttribute("size",me.suggestion.list.length);
           }
           selectList.setAttribute("multiple","true");
            //alert(selectList.type);
            
           	selectList.onkeydown = function(ev)
	        {
		        var key = me.getKeyCode(ev);

		        switch(key)
		        {
			        case TAB:me.hideDiv(); break;
			     }
			} 
            
           selectList.onchange = function(ev)
           {
                if(this.selectedIndex>-1)
                {
                      me.highlighted=this.selectedIndex;
                      var code=this.options[this.selectedIndex].value;
                      var name=this.options[this.selectedIndex].text;
                      var univ='U';
                      
                      
                          if(me.suggestType!="hidden")
	                      {   me.elem.value=name;
	                            if(me.searchType.toUpperCase() == "MANAGER") {
        			                
			                        window.location="/Managers/ManagerFactsheet.aspx?personCode="+code+"&univ="+univ;
	                            }
	                            else if(me.searchType.toUpperCase() == "GROUP") {
			                        window.location="/Factsheets/ManagerGroup.aspx?managerCode="+code+"&univ="+univ;
	                            }
	                            else {
			                        window.location="/Factsheets/Factsheet.aspx?fundCode="+code+"&univ="+univ;
	                            }
	                        }
	                        else
	                        {
	                            $(me.hiddenID).value=code;
	                            me.elem.value=name;
	                            $(me.div.id).style.display='none';		
	                 
	                            if(me.searchType=='sector')
				                {
				                    $(me.includeSectorID).style.visibility='';
				                    $(me.bindedHidMgr).value='';
				                    $(me.bindedTxtMgr).value='Enter manager name';
				                }	            
            			        
	                         }
                    } 
               
              } //end onchange event
              
//        selectList.onmouseover = function(ev)
//		{
//		    //alert(window.event.fromElement.tagName);
//		    var target = me.getEventSource(ev);		    
//		    //alert(target.tagName);
//            while (target.parentNode && target.tagName.toUpperCase() != 'OPTION')
//	        {
//		        target = target.parentNode;
//	        }
//		
//	        var lis = me.div.getElementsByTagName('OPTION');    			
//	        
//	        for (i in lis)
//	        {
//		        var li = lis[i];
//		        if(li == target)
//		        {
//			        me.highlighted = i;
//			        break;
//		        }
//		        
//	        }	        
//	        
//	        me.changeHighlight();
//     
//		 }//end onmouseover event
              
              
        }//end if list control
        

	    for (var j=0;j<me.suggestion.list.length;j++)
		{   
		    var word = me.suggestion.list[j].Name;
		    var code = me.suggestion.list[j].Code;
		    var univ = me.suggestion.list[j].Univ;
		    
	        if(typeof word=='string')
	        {
	        
	            if(typeof me.controlType =='undefined')
	            {    
			        var li = document.createElement('li');
			        var a = document.createElement('a');
			        li.setAttribute('id',this.div.id+'_li_'+j);
            
			        if(this.suggestType!="hidden")
			        {
			            if(me.searchType.toUpperCase() == "MANAGER") {
					        a.href="/Managers/ManagerFactsheet.aspx?personCode="+code+"&univ="+univ;
			            }
			            else if(me.searchType.toUpperCase() == "GROUP") {
					        a.href="/Factsheets/ManagerGroup.aspx?managerCode="+code+"&univ="+univ;
			            }
			            else {
					        a.href="/Factsheets/Factsheet.aspx?fundCode="+code+"&univ="+univ;
			            }
			        }
			        else
			        {
			            a.href="javascript:$('"+this.hiddenID+"').value='"+code+"';$('"+this.elem.id+"').value='"+word+"';$('"+this.div.id+"').style.display='none';void(0);";
    			        
			         }
    			   
			        var rSpan = document.createElement('div');
    			    
			        rSpan.className='rSpan';
			        rSpan.innerHTML=word;
    			    
    		        a.appendChild(rSpan);
    			    
			        li.appendChild(a);
        	    
//        	        li.appendChild(rSpan);
        	        
			        if (me.highlighted == j)
			        {
				        li.className = "selected";
			        }
        	
			        ul.appendChild(li);
			    }
			    else if(me.controlType=="listbox")
			    {
			        //inside loop
			        var item=new Option(word,code);		        
	                //item.attachEvent('onmouseover',function(){alert('d');}); 
			        selectList.options.add(item);
					
			    
			    }
			}//end if word
			
		}//end for
		
		if(typeof me.controlType!='undefined' && me.controlType=="listbox")
	    {
	        this.div.replaceChild(selectList,this.div.childNodes[0]);	        
	        me.highlighted=-1;
         }
        else
        {	
		    this.div.replaceChild(ul,this.div.childNodes[0]);
		}      

		
		
        this.div.onblur = function(ev)
	    {
	        me.blurTimeout(100);   
    	   
	    }

        document.onclick=function(e)
        {               
            var e=e? e : window.event;
            var ref=e.target? e.target : e.srcElement;

            if(ref!=me.listClick)
            { 
                if(me.elem.value == '' && typeof  me.defaultText !='undefined'&& ref!=me.elem) 
	            { 
	                me.elem.value = me.defaultText; 
	                
	                if(me.hiddenID && typeof me.hiddenID !='undefined')
	                {
	                    $(me.hiddenID).value='';
	                    
	                     if(me.searchType=='sector')
				         {
				            $(me.includeSectorID).style.visibility='hidden';
				            
				         }
	                }
	            }
                me.hideDiv();
              
             }
           
        } 
        
        document.onkeypress=function(e)
        {               
            
           	var key = null;
           	
           	if(e)			//Moz
		    {
			    key= e.keyCode;
		    }
		    if(window.event)	//IE
		    {
			    key=window.event.keyCode;
		    }
				
           	switch(key)
		    {   case ESC:
		        if(me.elem.value == '' && typeof  me.defaultText !='undefined') 
	            { 
	                me.elem.value = me.defaultText; 
	                
	                if(me.hiddenID && typeof me.hiddenID !='undefined')
	                {
	                    $(me.hiddenID).value='';
	                     if(me.searchType=='sector')
				         {
				            $(me.includeSectorID).style.visibility='hidden';
				         }
	                }
	            }
		        me.hideDiv();
		        break;
		    }
        }    

        
    	
	
		ul.onmouseover = function(ev)
		{
		    var target = me.getEventSource(ev);
		    
		    try
		    {  		    
                while (target.parentNode && target.tagName.toUpperCase() != 'LI')
	            {
		            target = target.parentNode;
	            }
    		        
	            var lis = me.div.getElementsByTagName('LI');    			
    	
	            for (var i=0;i<lis.length;i++)
	            {
		            var li = lis[i];
		            if(li == target)
		            {
			            me.highlighted = i;
			            break;
		            }
	            }
		        
	            me.changeHighlight();  		       
	            
	         }
	         catch(e)
	         {}
		};


//		ul.onclick = function(ev)
//		{
		
//			me.useSuggestion();
//			
//		
//			searchSubmit(escape(me.elem.value.urlEncode()));
//			me.submission_state=true;
//			
//			me.hideDiv();
//			me.cancelEvent(ev);
//			return false;
//		};
	
		this.div.className="suggestion_list";
		this.div.style.position = 'absolute';
		this.div.style.zIndex = 100;
		
		if(me.suggestion.list.length>18&&me.controlType!="listbox")
		{
		    this.div.className += " suggestScroll";
		}
		else
		{
		    this.div.className += " suggestNoscroll";
		}

	};

	this.mouseOverTimeout=function(ms)
	{	
	    var _self = this;
        setTimeout
        (
            function(ms)
            {             
               _self.changeHighlight();
            }
         , ms);
      
	}; 

	this.getKeyCode = function(ev)
	{
		if(ev)			//Moz
		{
			return ev.keyCode;
		}
		if(window.event)	//IE
		{
			return window.event.keyCode;
		}
	};

	this.getEventSource = function(ev)
	{
		if(ev)			//Moz
		{
			return ev.target;
		}
	
		if(window.event)	//IE
		{
			return window.event.srcElement;
		}
	};

	this.cancelEvent = function(ev)
	{
		if(ev)			//Moz
		{
			ev.preventDefault();
			ev.stopPropagation();
		}
		if(window.event)	//IE
		{
			window.event.returnValue = false;
			event.cancel = true;
		}
	}
	
	function suggestions()
	{
	   this.list=[];
	   this.keyword='';
	}	   
	
}

	
	
	
 String.prototype.urlEncode = function () 
 {
        var text = this.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < text.length; n++) {

            var c = text.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
  }

function GotoFundFactsheet(fundCode,univCode)
{
   if(fundCode!=""&&univCode!="")
   { 
     window.location="/Factsheets/Factsheet.aspx?fundCode="+fundCode+"&univ="+univCode;
   }
}

function GotoManagerFactsheet(personCode,univCode)
{   
   if(personCode!="")
   {
     window.location="/Managers/ManagerFactsheet.aspx?personCode="+personCode+"&univ="+univCode;
     
   }
   
   
}

function GotoGroupFactsheet(managerCode,univCode)
{
   if(managerCode!="")
   {
     window.location="/Factsheets/ManagerGroup.aspx?managerCode="+managerCode+"&univ="+univCode;
   }
}


var idCounter = 0;

/*###################################################################

Revision history:

Date      | By | Description
----------+----+------------------------------------------
14-Mar-07   RP   Created.

####################################################################*/

//####################################################################
// These variables can safely be modified by client scripts as required
//####################################################################

// if true, helpful debug alerts will be be displayed.
var DebugAlert = false; 

// notifies every time a web service is executed. DebugAlert must be true.
var DebugAlertOnWebServiceExec = false; 

// notifies what parameters are used for a web service. Both above variables must be true.
var DebugAlertShowParamsOnExec = false;

// if true, alerts will be sent to a DIV element rather than the alert box.
var UseDebugPanel = true;

// If true, then no style data will be allocated to the DebugPanel. UseDebugPanel must be set to true.
// This means the client should define CSS class definitions for div.DebugPanel, div.DebugEntry, div.DebugHeading
var DebugPanelUseCustomStyle = false; 



//####################################################################
// ChartingWebService definition and methods
//####################################################################
function ChartingWebService()
{
	 this.WebServiceUrl ='http://'+serverName+'/WebServices/charting.asmx';
}
function TNXWebService()
{
	 this.WebServiceUrl ='http://'+serverName+'/WebServices/BusinessObjLoader.asmx';
}
function PortfolioWebService()
{
	 this.WebServiceUrl ='http://'+serverName+'/WebServices/BusinessObjLoader.asmx';
}
function LoadSectorQs(r)
{
 	LoadOptionList(r, 'qsSectorsDD', 'Sectors');
}
function LoadDomicilesQs(r)
{
 	LoadOptionList(r, 'qsDomicileDD', 'Domiciles');
}
function LoadManagersQs(r)
{
 	LoadOptionList(r, 'qsManagerDD', 'Managers');
}

function LoadFilterBusObjectLoad(busCollObjName,univCode,loadMethod,param,nameProperty,codeProperty,filter,sort)
{
var pws = new PortfolioWebService();
if(busCollObjName=="Sectors")
pws.LoadFilterBusObjects(LoadSectorQs,busCollObjName,univCode,loadMethod,param,nameProperty,codeProperty,filter,sort);
if(busCollObjName=="Domiciles")
pws.LoadBusObjAdoQS(LoadDomicilesQs,busCollObjName,univCode,nameProperty,codeProperty,filter,sort);
if(busCollObjName=="Managers")
pws.LoadFilterBusObjects(LoadManagersQs,busCollObjName,univCode,loadMethod,param,nameProperty,codeProperty,filter,sort);
}

function CalDayLightTimeLoad()
{
var pws = new PortfolioWebService();
pws.CalDayLightTime(LoadDayLightData);
}

function LoadSectorByAssetClassLoad(assetClassCode,univCode,nameProperty,codeProperty,filter,sort)
{
var pws = new PortfolioWebService();
pws.LoadSectorByAssetClassQs(LoadSectorQs,assetClassCode,univCode,nameProperty,codeProperty,filter,sort);
}

function AddPortfolioFundDisplay(portfolioId, userId, univCode, typeCode)
{
var pws = new PortfolioWebService();
pws.AddPortfolioFund(UserCount,portfolioId, userId, univCode, typeCode);
}

function PortfolioUpdateFundList(typecode,pDate,quantity,fundcurrency,currency,costV,pCost,rowGuid,port,userId)
{
var pws = new PortfolioWebService();
pws.UpdatePortfolioFund(UserCount,typecode,pDate,quantity,fundcurrency,currency,costV,pCost,rowGuid,port,userId);
}

 
function CashUpdateList(typecode,quantity,fundcurrency,currency,AccType,name,port,userId)
{
var pws = new PortfolioWebService();
pws.UpdateCash(UserCount,typecode,quantity,fundcurrency,currency,AccType,name,port,userId);
}

function AddPortfolioFundDisplay(portfolioId, userId, univCode, typeCode)
{
var pws = new PortfolioWebService();
pws.AddPortfolioFund(UserCount,portfolioId, userId, univCode, typeCode);
}

function RemovePortfolioFundDisplay(portfolioId, userId,typeCode)
{
var pws = new PortfolioWebService();
pws.RemovePortfolioFund(UserCount,portfolioId, userId, typeCode);
}

function AddWatchlistFundDisplay(userId, univCode, typeCode,SiteCode)
{
var pws = new PortfolioWebService();
pws.AddWatchlistFund(UserCount,userId, univCode, typeCode,SiteCode);
}

function RemoveWatchlistFundDisplay(userId, univCode, typeCode,SiteCode)
{
var pws = new PortfolioWebService();
pws.RemoveWatchlistFund(UserCount,userId, univCode, typeCode,SiteCode);
}

function CheckLoginUserDetails(email,password)
{
var pws = new PortfolioWebService();
pws.CheckUserLogIn(UserDetails,email, password);
}

function UserDetails(r)
{
    if(r!="0")
    {
		if(allowPop && allowPop == "true")
		{
			window.open('http://www.trustnet.com/?uId='+r,'_blank');
		}
	   else
	   {
			window.location.href = "/?uId="+r;
	   }
    }else
    {
        alert("!Invalid UserDetails");
    }
}

function FundByType(typeCode)
{
var pws = new PortfolioWebService();
pws.LoadFundByType(SetBasketVisibility,typeCode);
}

function CheckTypeCodeInPortfolio(portfolioId, typeCode)
{
var pws = new PortfolioWebService();
pws.IsTypeCodeExistInPortfolio(IsTypeCodeInPortfolio,portfolioId, typeCode);
}


function PortfolioByUserId(userId)
{
var pws = new PortfolioWebService();
pws.LoadPortfolioByUserId(PopulateBasketPortfolio,userId);
}

function WatchlistByUserId(userId)
{
var pws = new PortfolioWebService();
pws.LoadWatchlistByUserId(LoadHiddenWatchList,userId);
}

function FundByTypeCode(typeCode)
{
var pws = new PortfolioWebService();
pws.LoadFundByTypes(SetProdSearchBaseket,typeCode);
 
}

function UpdateUserCookieByIPinDB(userId,cookieName,cookieValue)
{
	var pws = new PortfolioWebService();
	pws.UpdateUserCookieDB(UpdateUserCookieByIPFn,userId,cookieName,cookieValue);
}

function SectorsByAssetClassQS(universe, filter)
{
    var pws = new PortfolioWebService();
    pws.LoadSectorsByAssetClassQS(PopulateSectors,universe, filter);

}

function AssetClassByUniverseQS(universe )
{
    var pws = new PortfolioWebService();
    pws.LoadAssetClassByUniverseQS(PopulateAssetClass,universe );

}

function ManagersByUniverseQS(universe )
{
    var pws = new PortfolioWebService();
    pws.LoadManagersByUniverseQS(PopulateManager,universe);

}

function DomicilesByUniverseQS(universe )
{
    var pws = new PortfolioWebService();
    pws.LoadDomicilesByUniverseQS(PopulateDomiciles,universe );

}

function GeoareaByUniverseQS(universe )
{
    var pws = new PortfolioWebService();
    pws.LoadGeoareaByUniverseQS(PopulateGeoarea,universe );

}

function VCTQSObjects(delegate,universe, filter)
{
    var pws = new PortfolioWebService();
    pws.LoadVCTQSObjects(delegate,universe, filter);

}

function SPSFObjects(delegate,universe, filter)
{
    var pws = new PortfolioWebService();
    pws.LoadSPSFManagers(delegate,universe, filter);
}



function UserCount(r)
{   
   return r;
}

function ManagersByUniverseSF(universe)
{
    var pws = new PortfolioWebService();
    pws.LoadManagersByUniverseSF(PopulateManagerSF,universe);

}


PortfolioWebService.prototype.LoadSectorsByAssetClassQS=function(delegateFunc,universe, filter)
{
    var p = new WSParameters();
    p.Add('universeCode',universe);
    p.Add('assetClassName',filter);
    this.Invoke('LoadSectorsByAssetClassQS', p,delegateFunc);
}

PortfolioWebService.prototype.LoadAssetClassByUniverseQS=function(delegateFunc,universe)
{
    var p = new WSParameters();
    p.Add('universeCode',universe);    
    this.Invoke('LoadAssetClassByUniverseQS', p,delegateFunc);
}

TNXWebService.prototype.LoadSectorsByUniverse=function(delegateFunc,universe)
{
    var p = new WSParameters();
    p.Add('busCollObjName','Sector');
    p.Add('univCode',universe);
    p.Add('nameProperty','NameLong');
    p.Add('codeProperty','SectorClassCode');
    p.Add('filter','');
    p.Add('sort','NameLong');
    this.Invoke('LoadBusObjAdo', p,delegateFunc);
}


PortfolioWebService.prototype.UpdatePollChoice=function(delegateFunc,pollId,pollChoiceId)
{
    var p = new WSParameters();
    p.Add('pollId',pollId);
    p.Add('pollChoiceId',pollChoiceId);   
    this.Invoke('UpdatePollChoice', p,delegateFunc);
}

PortfolioWebService.prototype.LoadManagersByUniverseQS=function(delegateFunc,universe)
{
    var p = new WSParameters();
    p.Add('universeCode',universe);
    p.Add('includeAll',false);
    this.Invoke('LoadManagersByUniverseQS', p,delegateFunc);
}

PortfolioWebService.prototype.LoadDomicilesByUniverseQS=function(delegateFunc,universe)
{
    var p = new WSParameters();
    p.Add('universeCode',universe);    
    this.Invoke('LoadDomicilesByUniverseQS', p,delegateFunc);
}

PortfolioWebService.prototype.LoadGeoareaByUniverseQS=function(delegateFunc,universe)
{
    var p = new WSParameters();
    p.Add('universeCode',universe);    
    this.Invoke('LoadGeoareaByUniverseQS', p,delegateFunc);
}



PortfolioWebService.prototype.LoadVCTQSObjects=function(delegateFunc,universe, filter)
{
    var p = new WSParameters();
    p.Add('universeCode',universe);
    p.Add('returnValue',filter);
    this.Invoke('LoadVCTQSObjects', p,delegateFunc);
}

PortfolioWebService.prototype.LoadSPSFManagers=function(delegateFunc,universe)
{
    var p = new WSParameters();
    p.Add('universeCode',universe);
    this.Invoke('LoadSPSFManagers', p,delegateFunc);
}

PortfolioWebService.prototype.LoadManagersByUniverseSF=function(delegateFunc,universe)
{
    var p = new WSParameters();
    p.Add('universeCode',universe);
    p.Add('includeAll',true);
    this.Invoke('LoadManagersByUniverseQS', p,delegateFunc);
}

ChartingWebService.prototype.LoadPerformance = function(delegateFunc, typeCodes, periodType, priceType, methodType, sort, filter)
{
	var p = new WSParameters();

	if (periodType == null) periodType = '';
	if (priceType == null) priceType = 'TR';
	if (methodType == null) methodType = 1;

	p.Add('TypeCodes', typeCodes);
	p.Add('PeriodType', periodType);
	p.Add('PriceType', priceType);
	p.Add('MethodType', methodType);
	
	this.AddStdParams(p, sort, filter);
	this.Invoke('Performance', p, delegateFunc);
}

PortfolioWebService.prototype.AddPortfolioFund= function(delegateFunc,portfolioId, userId, univCode, typeCode)
{
	var p = new WSParameters();

	p.Add('portfolioId', portfolioId);
	p.Add('userId', userId);
	p.Add('univCode', univCode);
	p.Add('typeCode', typeCode);
	this.Invoke('AddPortfolio', p,delegateFunc);
}

PortfolioWebService.prototype.UpdatePortfolioFund= function(delegateFunc,typecode,pDate,quantity,fundcurrency,currency,costV,pCost,rowGuid,port,userId)
{
	var p = new WSParameters();

	p.Add('typecode', typecode);
	p.Add('purchaseDate', pDate);
	p.Add('Quantity', quantity);
	p.Add('fundCurrency', fundcurrency);	
	p.Add('Currency', currency);
	p.Add('isCost', costV);
	p.Add('pCost', pCost);
	p.Add('rowGuid', rowGuid);
	p.Add('pid', port);
	p.Add('userid', userId);
	this.Invoke('UpdatePortfolioFund', p,delegateFunc);
}

PortfolioWebService.prototype.UpdateCash= function(delegateFunc,typecode,quantity,fundcurrency,currency,AccType,name,port,userId)
{
	var p = new WSParameters();
	p.Add('cid', typecode);	
	p.Add('Quantity', quantity);
	p.Add('fundCurrency', fundcurrency);
	p.Add('Currency', currency);
	p.Add('accType', AccType);
	p.Add('accName', name);	
	p.Add('pid', port);
	p.Add('userid', userId);
	this.Invoke('UpdateCash', p,delegateFunc);
}

PortfolioWebService.prototype.CheckUserLogIn=function (delegateFunc,emailId,password)
{
    var p = new WSParameters();
    p.Add('emailId',emailId);
    p.Add('password',password);
    this.Invoke('CheckUserLogIn',p,delegateFunc);
//    var pws = new PortfolioWebService();
//    pws.CheckUserLogIn(emailId,password);
} 

PortfolioWebService.prototype.CalDayLightTime= function(delegateFunc)
{
	var p = new WSParameters();

    this.Invoke('CalCulateDayLightTime',p,delegateFunc);
}
PortfolioWebService.prototype.LoadFilterBusObjects= function(delegateFunc,busCollObjName,univCode,loadMethod,param,nameProperty,codeProperty,filter,sort)
{
	var p = new WSParameters();

    if (param == null) param = '';
    if (filter == null) filter = '';
    
	p.Add('busCollObjName', busCollObjName);
	p.Add('univCode', univCode);
	p.Add('loadMethod', loadMethod);
	p.Add('parameter', param);
	p.Add('nameProperty', nameProperty);
	p.Add('codeProperty', codeProperty);
	p.Add('filter', filter);
	p.Add('sort', sort);
	this.Invoke('LoadFilterBusObject', p,delegateFunc);
}
PortfolioWebService.prototype.LoadFilterBusObjectByUnivGroup= function(delegateFunc,busCollObjName,univGroupCode,parameterType,parameterValue,filter)
{
	var p = new WSParameters();

	if (filter == null) filter = '';
   if (parameterType == null) parameterType = '';
   if (parameterValue == null) parameterValue = '';
    
	p.Add('busCollObjName', busCollObjName);
	p.Add('univGroupCode', univGroupCode);
	p.Add('parameterType', parameterType);
	p.Add('parameterValue', parameterValue);
	p.Add('filter', filter);
	this.Invoke('LoadFilterBusObjectByUnivGroup', p,delegateFunc);
}

PortfolioWebService.prototype.LoadChartFilterBusObjectByUnivGroup= function(delegateFunc,busCollObjName,univGroupCode,parameterType,parameterValue,filter)
{
	var p = new WSParameters();

	if (filter == null) filter = '';
   if (parameterType == null) parameterType = '';
   if (parameterValue == null) parameterValue = '';
    
	p.Add('busCollObjName', busCollObjName);
	p.Add('univGroupCode', univGroupCode);
	p.Add('parameterType', parameterType);
	p.Add('parameterValue', parameterValue);
	p.Add('filter', filter);
	this.Invoke('LoadChartFilterBusObjectByUnivGroup', p,delegateFunc);
}

PortfolioWebService.prototype.LoadBusObjAdoQS= function(delegateFunc,busCollObjName,univCode,nameProperty,codeProperty,filter,sort)
{
	var p = new WSParameters();

    if (filter == null) filter = '';
    
	p.Add('busCollObjName', busCollObjName);
	p.Add('univCode', univCode);
	p.Add('nameProperty', nameProperty);
	p.Add('codeProperty', codeProperty);
	p.Add('filter', filter);
	p.Add('sort', sort);
	this.Invoke('LoadBusObjAdo', p,delegateFunc);
}
PortfolioWebService.prototype.LoadSectorByAssetClassQs= function(delegateFunc,assetClassCode,univCode,nameProperty,codeProperty,filter,sort)
{
	var p = new WSParameters();

    if (assetClassCode == null) assetClassCode = '';
    if (filter == null) filter = '';
    
	p.Add('assetClassCode', assetClassCode);
	p.Add('univCode', univCode);
	p.Add('nameProperty', nameProperty);
	p.Add('codeProperty', codeProperty);
	p.Add('filter', filter);
	p.Add('sort', sort);
	this.Invoke('LoadSectorByAssetClass', p,delegateFunc);
}

PortfolioWebService.prototype.RemovePortfolioFund= function(delegateFunc,portfolioId, userId,  typeCode)
{
	var p = new WSParameters();

	p.Add('portfolioId', portfolioId);
	p.Add('userId', userId);	
	p.Add('typeCode', typeCode);

	this.Invoke('RemovePortfolio', p,delegateFunc);
}

PortfolioWebService.prototype.AddWatchlistFund= function(delegateFunc,userId,univCode,typeCode)
{
	var p = new WSParameters();
	p.Add('userId', userId);	
	p.Add('univCode', univCode);
	p.Add('typeCode', typeCode);   
	p.Add('SiteCode', SiteCode);
	this.Invoke('AddWatchlist', p,delegateFunc);
}

PortfolioWebService.prototype.RemoveWatchlistFund= function(delegateFunc,userId,  typeCode,SiteCode)
{
	var p = new WSParameters();
	
	p.Add('userId', userId);	
	p.Add('typeCode', typeCode);
    p.Add('SiteCode', SiteCode);

	this.Invoke('RemoveWatchlist', p,delegateFunc);
}

PortfolioWebService.prototype.LoadManagerPersons= function(delegateFunc,univCode,loadBy,parameter,nameProperty,codeProperty,filter,sort)
{
	var p = new WSParameters();
	if (parameter == null) return;
	if (filter == null) filter = '';
    
	p.Add('univCode', univCode);
	p.Add('loadMethod', loadBy);
	p.Add('parameter', parameter);
	p.Add('nameProperty', nameProperty);
	p.Add('codeProperty', codeProperty);
	p.Add('filter', filter);
	p.Add('sort', sort);
	this.Invoke('LoadManagerPersons', p,delegateFunc);
}

PortfolioWebService.prototype.LoadFundByType=function(delegateFunc,typeCode)
{
    var p = new WSParameters();
    p.Add('typeCode',typeCode);
    this.Invoke('LoadFundByTypeCode', p,delegateFunc);
}
PortfolioWebService.prototype.LoadPortfolioByUserId=function(delegateFunc,userId)
{
    var p = new WSParameters();
    p.Add('userId',userId);
    this.Invoke('LoadPortfolioByUserId', p,delegateFunc);
}

PortfolioWebService.prototype.LoadWatchlistByUserId=function(delegateFunc,userId)
{
    var p = new WSParameters();
    p.Add('userId',userId);
    this.Invoke('LoadWatchlistByUserId', p,delegateFunc);
}

PortfolioWebService.prototype.IsTypeCodeExistInPortfolio=function(delegateFunc,portfolioId,typeCode)
{
    var p = new WSParameters();
    p.Add('portfolioId',portfolioId);
    p.Add('typeCode',typeCode);
    this.Invoke('IsTypeCodeExistInPortfolio', p,delegateFunc);
}

PortfolioWebService.prototype.LoadFundByTypes=function(delegateFunc,typeCode)
{
    var p = new WSParameters();
    p.Add('typeCode',typeCode);
    this.Invoke('LoadFundByTypeCodes', p,delegateFunc);
}

PortfolioWebService.prototype.UpdateUserCookieDB=function(delegateFunc,userId,cookieName,cookieValue)
{
    var p = new WSParameters();
    p.Add('userId',userId);
    p.Add('cookieName',cookieName);
    p.Add('cookieValue',cookieValue);
    this.Invoke('UpdateUserCookie', p,delegateFunc);
}

// Parameters are as follows:
//   calcType .......... one from [MinMax, MinMean]
//   statisticalType ... e.g. Alpha, Beta, etc.
//   period ............ period over which to make calculations, in months.
//   offset ............ how many months ago should the latest data point be?
//   step .............. in months (interval between data points).
//   number ............ number of data points to return.
//
// Example:
//   LoadRollingDiscreteRange(null, 'MinMax', 'FFISS', 'NASX', 'Alpha', 36, 0, 1, 12)
ChartingWebService.prototype.LoadRollingDiscreteRange = function(delegateFunc, calcType, typeCodes, benchmarkCode, statisticalType, period, offset, step, number)
{
	var p = new WSParameters();

	p.Add('CalcType', typeCodes);
	p.Add('TypeCodes', typeCodes);
	p.Add('BenchmarkCode', benchmarkCode);
	p.Add('StatisticalType', statisticalType);
	p.Add('Period', period);
	p.Add('Offset', offset);
	p.Add('Step', step);
	p.Add('Number', number);

	this.Invoke('GetRollingDiscrete', p, delegateFunc);
}


// Parameters are as follows:
//   statisticalType ... e.g. Alpha, Beta, etc.
//   period ............ period over which to make calculations, in months.
//   offset ............ how many months ago should the latest data point be?
//   step .............. in months (interval between data points).
//   number ............ number of data points to return.
//
// Example:
//   LoadRollingDiscrete(null, 'FFISS', 'NASX', 'Alpha', 36, 0, 1, 12)
ChartingWebService.prototype.LoadRollingDiscrete = function(delegateFunc, typeCodes, benchmarkCode, statisticalType, period, offset, step, number)
{
	var p = new WSParameters();

	p.Add('TypeCodes', typeCodes);
	p.Add('BenchmarkCode', benchmarkCode);
	p.Add('StatisticalType', statisticalType);
	p.Add('Period', period);
	p.Add('Offset', offset);
	p.Add('Step', step);
	p.Add('Number', number);

	this.Invoke('GetRollingDiscrete', p, delegateFunc);
}


ChartingWebService.prototype.LoadEquities = function(delegateFunc, sort, filter)
{
	var p = new WSParameters();
	if (sort == null) sort = 'Name';
	this.AddStdParams(p, sort, filter);
	this.Invoke('Equities', p, delegateFunc);
}

ChartingWebService.prototype.LoadInstruments = function(delegateFunc, typeCodes, sort, filter)
{
	var p = new WSParameters();
	p.Add('TypeCodes', typeCodes);
	if (sort == null) sort = 'Name';
	this.AddStdParams(p, sort, filter);
	this.Invoke('Instruments', p, delegateFunc);
}

ChartingWebService.prototype.LoadUnitsByManagerCode = function(delegateFunc, categories, managerCodes, sort, filter)
{
	var p = new WSParameters();
	p.Add('Categories', categories);
	p.Add('ManagerCodes', managerCodes);
	if (sort == null) sort = 'Name';
	this.AddStdParams(p, sort, filter);
	this.Invoke('Units_ByManagerCode', p, delegateFunc);
}

ChartingWebService.prototype.LoadUnitsBySectorClassCode = function(delegateFunc, categories, sectorClassCodes, sort, filter)
{
	var p = new WSParameters();
	p.Add('Categories', categories);
	p.Add('SectorClassCodes', sectorClassCodes);
	if (sort == null) sort = 'Name';
	this.AddStdParams(p, sort, filter);
	this.Invoke('Units_BySectorClassCode', p, delegateFunc);
}

ChartingWebService.prototype.LoadUnitsByFundCode = function(delegateFunc, fundCodes, sort, filter)
{
	var p = new WSParameters();
	p.Add('FundCodes', fundCodes);
	if (sort == null) sort = 'Name';
	this.AddStdParams(p, sort, filter);
	this.Invoke('Units_ByFundCode', p, delegateFunc);
}

ChartingWebService.prototype.LoadFundsByManagerCode = function(delegateFunc, categories, managerCodes, sort, filter)
{
	var p = new WSParameters();
	p.Add('Categories', categories);
	p.Add('ManagerCodes', managerCodes);
	if (sort == null) sort = 'Name';
	this.AddStdParams(p, sort, filter);
	this.Invoke('Funds_ByManagerCode', p, delegateFunc);
}

ChartingWebService.prototype.LoadFundsBySectorClassCode = function(delegateFunc, categories, sectorClassCodes, sort, filter)
{
	var p = new WSParameters();
	p.Add('Categories', categories);
	p.Add('SectorClassCodes', sectorClassCodes);
	if (sort == null) sort = 'Name';
	this.AddStdParams(p, sort, filter);
	this.Invoke('Funds_BySectorClassCode', p, delegateFunc);
}

ChartingWebService.prototype.LoadManagers = function(delegateFunc, categories, sort, filter)
{
	var p = new WSParameters();
	
	if (filter == null) filter = '';
	if (sort == null) sort = 'Name';

	// Due to case-sensitivity, and the fact that the Managers method has different case 
	// parameters from the standard, it has to be done the long way.
	p.Add('categories', categories);
	p.Add('pageNo', 1);
	p.Add('pageSize', 0);
	p.Add('filter', filter);
	p.Add('sort', sort);

	this.Invoke('Managers', p, delegateFunc);
}

ChartingWebService.prototype.LoadSectors = function(delegateFunc, categories, officialSectors, sort, filter)
{
	var p = new WSParameters();
	var webMethod = officialSectors ? 'OfficialSectors' : 'Sectors';
	if (sort == null) sort = 'Name';
	if (officialSectors != true)
	{
		officialSectors = false;
	}
	p.Add('Categories', categories);
	this.AddStdParams(p, sort, filter);
	this.Invoke(webMethod, p, delegateFunc);
}

ChartingWebService.prototype.LoadIndices = function(delegateFunc, sort, filter)
{
	var p = new WSParameters();
	if (sort == null) sort = 'Name';
	this.AddStdParams(p, sort, filter);
	this.Invoke('Indices', p, delegateFunc);
}

// This method has not been tested.
ChartingWebService.prototype.LoadStochasticFanByAssetCodes = function(delegateFunc, assetCodes, percentiles, timePeriods, allowForInflation)
{
	var p = new WSParameters();
	p.Add('assetCodes', assetCodes);
	p.Add('percentiles', percentiles);
	p.Add('timePeriods', timePeriods);
	p.Add('allowForInflation', allowForInflation);
	this.Invoke('GetStochasticFan_ByAssetCodes', p, delegateFunc);
}

// This method has not been tested.
ChartingWebService.prototype.LoadStochasticFanByTypeCodes = function(delegateFunc, typeCodes, percentiles, timePeriods, allowForInflation)
{
	var p = new WSParameters();
	p.Add('typeCodes', typeCodes);
	p.Add('percentiles', percentiles);
	p.Add('timePeriods', timePeriods);
	p.Add('allowForInflation', allowForInflation);
	this.Invoke('GetStochasticFan_ByTypeCodes', p, delegateFunc);
}

ChartingWebService.prototype.AddStdParams = function(p, sort, filter)
{
	if (filter == null) filter = '';
	if (sort == null) sort = '';
	p.Add('PageNo', 1);
	p.Add('PageSize', 0);
	p.Add('Filter', filter);
	p.Add('Sort', sort);
}

ChartingWebService.prototype.Invoke = function(webMethod, params, delegateFunc)
{
	if (delegateFunc == null) 
	{
		delegateFunc = LoadServiceTest;
		if (webMethod.indexOf('GetRollingDiscrete') == 0)
		{
			delegateFunc = LoadServiceTestString;
		}
	}
	Debug(params.Length == 0, 'Invoke method: params is empty for method "' + webMethod + '"');
	if (DebugAlertOnWebServiceExec)
	{
		var msg = 'Executing ' + webMethod + ' method';
		if (DebugAlertShowParamsOnExec)
		{
			msg += ' with parameters:\n' + params.ToString();
		}
		Debug(true, msg);
	}

	try
	{
		SOAPClient.invoke(this.WebServiceUrl, webMethod, params.ToSoap(), true, delegateFunc);
	}
	catch (ex)
	{
		Debug(true, 'Error invoking web service.\nUrl: ' + this.WebServiceUrl + '\nMethod: ' + webMethod + '\nParameters: ' + params.ToString() + '\nException: ' + ex);
	}
}

PortfolioWebService.prototype.Invoke = function(webMethod, params, delegateFunc)
{

	Debug(params.Length == 0, 'Invoke method: params is empty for method "' + webMethod + '"');
	if (DebugAlertOnWebServiceExec)
	{
		var msg = 'Executing ' + webMethod + ' method';
		if (DebugAlertShowParamsOnExec)
		{
			msg += ' with parameters:\n' + params.ToString();
		}
		Debug(true, msg);
	}

	try
	{
		SOAPClient.invoke(this.WebServiceUrl, webMethod, params.ToSoap(), true, delegateFunc);
	}
	catch (ex)
	{
		Debug(true, 'Error invoking web service.\nUrl: ' + this.WebServiceUrl + '\nMethod: ' + webMethod + '\nParameters: ' + params.ToString() + '\nException: ' + ex);
	}
}

//####################################################################
// Parameters collection
//####################################################################
function WSParameters()
{
	this.names = new Array();
	this.values = new Array();
}

WSParameters.prototype.Add = function(name, value)
{
	this.names[this.names.length] = name;
	this.values[this.values.length] = value;
}

WSParameters.prototype.Length = function()
{
	return this.names.length;
}

WSParameters.prototype.ToString = function(separator)
{
	var res = '', sep = '';
	if (separator == null) separator = '\n';
	for (var i = 0; i < this.names.length; i++)
	{
		res += sep + this.names[i] + '="' + this.values[i] + '"';
		sep = separator;
	}
	return res;
}

WSParameters.prototype.ToSoap = function()
{
	var p = new SOAPClientParameters();
	for (var i = 0; i <this.names.length; i++)
	{
		p.add(this.names[i], this.values[i]);
	}
	return p;
}

//####################################################################
// Helper functions below this point 
//####################################################################

function GetElementById(id, msgOnFail)
{
	if (msgOnFail == null) msgOnFail = true;
	var element = document.getElementById(id);
	Debug(element == null && msgOnFail, "Unable to locate element with id='" + id + "'");
	return element;
}


// This method can be safely run in client scripts. 
// Use instead of alert(message).
function Debug(condition, message)
{
	var href = document.location.href.toLowerCase();
	var urlDebug = href.indexOf('debugalert=1') > -1 || href.indexOf('debugalert=y') > -1;

	if (!(condition && (DebugAlert || urlDebug))) return;

	var div = null;	
	var doAlert = true;

	if (UseDebugPanel)
	{
		try
		{
			div = GetDebugPanel(); // this may fail if the document hasn't loaded fully.
			doAlert = false;
		}
		catch (e) { }
	}
	
	if (!doAlert)
	{
		div.Write(message);
	}
	else
	{
		alert(message);
	}
}

// This function is used to populate drop-down boxes.
// Parameters:
//   xmlResult ....... the parameter result from the web service.
//   selectControl ... either the id of an element in the document or the element itselft. Must be a <SELECT>.
//   itemPlural ...... a string denoting the type of item, e.g. 'funds', 'indices', etc.
function LoadOptionList(xmlResult, selectControl, itemPlural)
{
	var data = null;
	var sc = selectControl;
	
	if (sc != null && sc.options == null)
	{
		sc = GetElementById(sc);
	}

	sc.options.length = 0;

	if (xmlResult == null || xmlResult.Items == null)
	{
		return;
	}
	
	data = xmlResult.Items;
    if(selectControl.indexOf("qs")>=0)
	sc.options.add(new Option("All "+itemPlural,''), 0);
	else
	InfoFirstItem(sc, data.length, itemPlural);
	for (var i = 0; i < data.length; i++)
	{
		sc.options.add(new Option(data[i].Name, data[i].Code), sc.options.length);
	}
}

// This function can be over-ridden with a custom function as required.
function InfoFirstItem(selectControl, itemCount, itemPlural)
{
	var text = null;
	if (itemCount > 1)
	{
		text = itemCount + " " + itemPlural + " found...";
	}
	else if (itemCount < 1)
	{
		text = "0 " + itemPlural + " found!";
	}
	
	if (text != null)
	{
		selectControl.options.add(new Option(text, ""), 0)
	}
}

//####################################################################
// Test functions below this point
//####################################################################

// Used to test web service result set when result is not a string.
// If the delegate provided by a service is set to null, then either this function or the one below
// will be called. Ensure that DebugAlert is set to true to get a result.
function LoadServiceTest(r)
{
	Debug(r == null, 'LoadServiceTest: parameter "r" was unexpectedly null');
	var data = r.Items;
	if (data == null) data = r.PerfItems;
	Debug(data == null, 'LoadServiceTest: parameter "r" does not contain required property. Must contain either "Items" or "PerfItems".');
	Debug(true, 'LoadServiceTest: data.length is ' + data.length);
}

// Used to test web service result set when result is a string.
function LoadServiceTestString(r)
{
	Debug(r == null, 'LoadServiceTest: parameter "r" was unexpectedly null');
	Debug(true, 'LoadServiceTestString:\n' + r);
}

function TestSuite()
{
	var cws = new ChartingWebService();
	
	Debug(true, 'Tests are asynchronous and may not appear in order.');
	
	Debug(true, 'Testing LoadPerformance...');
	cws.LoadPerformance(null, 'FFISS,FTSENVA');
	
	Debug(true, 'Testing LoadInstruments...');
	cws.LoadInstruments(null, 'FFISS,FTSENVA');
	
	Debug(true, 'Testing LoadUnitsBySectorClassCode...');
	cws.LoadUnitsBySectorClassCode(null, 'OIC', 'U:UG');
	
	Debug(true, 'Testing LoadPerformance...');
	cws.LoadUnitsByManagerCode(null, 'OIC', 'FIDE');
	
	Debug(true, 'Testing LoadSectors...');
	cws.LoadSectors(null, 'OIC', false);

	Debug(true, 'Testing LoadSectors...');
	cws.LoadSectors(null, 'OIC', true);
	
	Debug(true, 'Testing LoadRollingDiscrete...');
	cws.LoadRollingDiscrete(null, 'FFISS', 'NASX', 'Alpha', 36, 0, 1, 12);
	
	Debug(true, 'Testing LoadRollingDiscreteRange...');
	cws.LoadRollingDiscreteRange(null, 'MinMax', 'FFISS', 'NASX', 'Alpha', 36, 0, 1, 12)
	
	Debug(true, 'Testing LoadEquities...');
	cws.LoadEquities(null, "Code LIKE 'EE%' OR Code LIKE 'F%'");
	
	Debug(true, 'Testing LoadIndices...');
	cws.LoadIndices(null, "Source='FTET' OR Source='FTVU' OR Source='MISC'");
}

//####################################################################
// Functions and methods below should not be called directly by client scripts.
// They are called via the Debug function as required.
//####################################################################

function GetDebugPanel()
{
	var div = document.getElementById('DebugPanel');
	if (div == null) 
	{
		div = new DebugPanel();
	}
	else
	{
		div = div.PanelRef;
	}
	return div;
}


function DebugPanel()
{
	var body = document.getElementsByTagName('BODY')[0];
	var div = document.createElement('DIV');
	var hdgStyle = ''
	
	div.id = 'DebugPanel';
	div.className = 'DebugPanel';
	if (!DebugPanelUseCustomStyle)
	{
		div.style.position = 'absolute';
		div.style.width = '350px';
		div.style.left = (document.body.clientWidth - 370) + 'px';
		div.style.top = '20px';
		div.style.fontFamily = 'Arial, Verdana, Sans-Serif';
		div.style.fontSize = '12px';
		div.style.display = 'block';
		div.style.border = 'solid 1px black';
		div.style.backgroundColor = '#E0E0FF';
		div.style.padding = '2px';
		hdgStyle = ' style="font-weight:bold; border-bottom: solid 1px black;"'
	}
	div.innerHTML = '<div class="DebugHeading"' + hdgStyle + '>Debug Window</div>';
	
	body.insertBefore(div, null);	
	
	this.Div = div;
	div.PanelRef = this;
}


DebugPanel.prototype.Write = function(message)
{
	var div = document.createElement('DIV');
	this.Div.insertBefore(div, null);
	div.className = 'DebugEntry';
	if (!DebugPanelUseCustomStyle)
	{
		div.style.borderBottom = 'solid 1px black';
	}
	div.innerText = message;
}

//#################################################################### 
/*****************************************************************************\

 Javascript "SOAP Client" library

 @version: 1.5 - 2006.05.23
 @author: Alan Machado
 @description: Major modifications and buffering to increase performance. Also allow for wsdl attributes
               
 @author: Matteo Casati - http://www.guru4.net/

\*****************************************************************************/

function StringBuffer() { 
   this.buffer = []; 
 } 

 StringBuffer.prototype.append = function append(str) { 
 
   this.buffer[this.buffer.length] = str; 
   return this; 
 }; 

 StringBuffer.prototype.toString = function toString() { 
   return this.buffer.join(""); 
 }; 
 
  StringBuffer.prototype.clear = function clear() { 
   this.buffer.length = 0; 
   return this.buffer
 }; 

function SOAPClientParameters()
{
	var _pl = new Array();
	var _buf = new StringBuffer();
	this.add = function(name, value) 
	{
		_pl[name] = value; 
		return this; 
	}
	
	this.toXml = function(wsdl)
	{
		_buf.clear();
		for(var p in _pl)
			if (p.substring(0,1) != "_")
				_buf.append(SOAPClientParameters._serialize(p,_pl[p],wsdl));
		return _buf.toString();	
	}
}

SOAPClientParameters._serialize = function(parentName, o,wsdl)
{
    var _buf = new StringBuffer();
    var isAttributes = false;
    
    switch(typeof(o))
    {
		  case "undefined":
				o = "";
        case "string":
            _buf.append(o.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")); break;
        case "number":
        case "boolean":
            _buf.append(o.toString()); break;
        case "object":
            // Date
            if(o.constructor.toString().indexOf("function Date()") > -1)
            {
                var year = o.getFullYear().toString();
                var month = (o.getMonth() + 1).toString(); month = (month.length == 1) ? "0" + month : month;
                var date = o.getDate().toString(); date = (date.length == 1) ? "0" + date : date;
                var hours = o.getHours().toString(); hours = (hours.length == 1) ? "0" + hours : hours;
                var minutes = o.getMinutes().toString(); minutes = (minutes.length == 1) ? "0" + minutes : minutes;
                var seconds = o.getSeconds().toString(); seconds = (seconds.length == 1) ? "0" + seconds : seconds;
                var milliseconds = o.getMilliseconds().toString();
                var tzminutes = Math.abs(o.getTimezoneOffset());
                var tzhours = 0;
                while(tzminutes >= 60)
                {
                    tzhours++;
                    tzminutes -= 60;
                }
                tzminutes = (tzminutes.toString().length == 1) ? "0" + tzminutes.toString() : tzminutes.toString();
                tzhours = (tzhours.toString().length == 1) ? "0" + tzhours.toString() : tzhours.toString();
                var timezone = ((o.getTimezoneOffset() < 0) ? "+" : "-") + tzhours + ":" + tzminutes;
                _buf.append(year + "-" + month + "-" + date + "T" + hours + ":" + minutes + ":" + seconds + "." + milliseconds + timezone);
            }
            // Array
            else if(o.constructor.toString().indexOf("function Array()") > -1)
            {
                for(var p in o)
                {
                    if(!isNaN(p))   // linear array
                    {
                        (/function\s+(\w*)\s*\(/ig).exec(o[p].constructor.toString());
                        var type = RegExp.$1;
                        switch(type)
                        {
                            case "":
                                type = typeof(o[p]);
                            case "String":
                                type = "string"; break;
                            case "Number":
                                type = "int"; break;
                            case "Boolean":
                                type = "bool"; break;
                            case "Date":
                                type = "DateTime"; break;
                        }
                        _buf.append(SOAPClientParameters._serialize(type,o[p],wsdl));
                    }
                    else    // associative array
                        _buf.append(SOAPClientParameters._serialize(p,o[p],wsdl));
                }
            }
            // Object or custom function
            else
            {
				 	 str = ""
                for(var p in o)
                {
						if (p.substring(0,1) != "_")
						{
							if (SOAPClient._isAttributeTypeWsdl(p,wsdl))
							{
								isAttributes = true;
								_buf.append(p + "=\"" + SOAPClientParameters._serialize("",o[p],wsdl) + "\" ")
							}
							else
							{
								_buf.append(SOAPClientParameters._serialize(p,o[p],wsdl))
							}                
						}
					 }
				}	
            break;
        default:
				return "";
            //throw new Error(500, "SOAPClientParameters: type '" + typeof(o) + "' is not supported");
    }

	if (parentName == "") return _buf.toString();
	
	return addNodeStr(parentName,_buf.toString(),isAttributes);
}


function addNodeStr(elname,str,attributes)
{
	if (attributes == true)
		return "<" + elname + " " + str +  " />"
	else
		return "<" + elname + ">" + str + "</" + elname + ">"
}


function SOAPClient() {}

SOAPClient.invoke = function(url, method, parameters, async, callback)
{
	if(async)
		SOAPClient._loadWsdl(url, method, parameters, async, callback);
	else
		return SOAPClient._loadWsdl(url, method, parameters, async, callback);
}

// private: wsdl cache
SOAPClient_cacheWsdl = new Array();

// private: invoke async
SOAPClient._loadWsdl = function(url, method, parameters, async, callback)
{
	// load from cache?
	var wsdl = SOAPClient_cacheWsdl[url];
	if(wsdl + "" != "" && wsdl + "" != "undefined")
		return SOAPClient._sendSoapRequest(url, method, parameters, async, callback, wsdl);
	// get wsdl
	var xmlHttp = SOAPClient._getXmlHttp();
	xmlHttp.open("GET", url + "?wsdl", async);
	if(async) 
	{
		xmlHttp.onreadystatechange = function() 
		{
			if(xmlHttp.readyState == 4)
				SOAPClient._onLoadWsdl(url, method, parameters, async, callback, xmlHttp);
		}
	}
	xmlHttp.send(null);
	if (!async)
		return SOAPClient._onLoadWsdl(url, method, parameters, async, callback, xmlHttp);
}
SOAPClient._onLoadWsdl = function(url, method, parameters, async, callback, req)
{
	var wsdl = req.responseXML;
	SOAPClient_cacheWsdl[url] = wsdl;	// save a copy in cache
	return SOAPClient._sendSoapRequest(url, method, parameters, async, callback, wsdl);
}
SOAPClient._sendSoapRequest = function(url, method, parameters, async, callback, wsdl)
{
	// get namespace
	var ns = (wsdl.documentElement.attributes["targetNamespace"] + "" == "undefined") ? wsdl.documentElement.attributes.getNamedItem("targetNamespace").nodeValue : wsdl.documentElement.attributes["targetNamespace"].value;
	// build SOAP request

	var sr = 
				"<?xml version=\"1.0\" encoding=\"utf-16\"?>" +
				"<soap:Envelope " +
				"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
				"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
				"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
				"<soap:Body>" +
				"<" + method + " xmlns=\"" + ns + "\">" +
				parameters.toXml(wsdl) +
				"</" + method + "></soap:Body></soap:Envelope>";
	// send request

	var xmlHttp = SOAPClient._getXmlHttp();
	xmlHttp.open("POST", url, async);
	var soapaction = ((ns.lastIndexOf("/") != ns.length - 1) ? ns + "/" : ns) + method;
	xmlHttp.setRequestHeader("SOAPAction", soapaction);
	xmlHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
	if(async) 
	{
		xmlHttp.onreadystatechange = function() 
		{
			if(xmlHttp.readyState == 4)
				SOAPClient._onSendSoapRequest(method, async, callback, wsdl, xmlHttp);
		}
	}
	xmlHttp.send(sr);
	if (!async)
		return SOAPClient._onSendSoapRequest(method, async, callback, wsdl, xmlHttp);
}
SOAPClient._onSendSoapRequest = function(method, async, callback, wsdl, req)
{
	var o = null;
	var nd = SOAPClient._getElementsByTagName(req.responseXML, method + "Result");
	if(nd.length == 0)
	{
		if(req.responseXML.getElementsByTagName("faultcode").length > 0)
			throw new Error(500, req.responseXML.getElementsByTagName("faultstring")[0].childNodes[0].nodeValue);
	}
	else
		o = SOAPClient._soapresult2object(nd[0], wsdl);
	if(callback)
		callback(o, req.responseXML);
	if(!async)
		return o;		
}

// private: utils
SOAPClient._getElementsByTagName = function(document, tagName)
{
	try
	{
		// trying to get node omitting any namespaces (latest versions of MSXML.XMLDocument)
		return document.selectNodes(".//*[local-name()=\""+ tagName +"\"]");
	}
	catch (ex) {}
	// old XML parser support
	return document.getElementsByTagName(tagName);
}

SOAPClient._soapresult2object = function(node, wsdl)
{
	return SOAPClient._node2object(node, wsdl);
}
SOAPClient._node2object = function(node, wsdl)
{
 // var obj = new Object()

/* Node Types
	ELEMENT_NODE = 1 
	ATTRIBUTE_NODE = 2 
	TEXT_NODE = 3 
	CDATA_SECTION_NODE = 4 
	ENTITY_REFERENCE_NODE = 5 
	ENTITY_NODE = 6 
	PROCESSING_INSTRUCTION_NODE = 7 
	COMMENT_NODE = 8 
	DOCUMENT_NODE = 9 
	DOCUMENT_TYPE_NODE = 10 
	DOCUMENT_FRAGMENT_NODE = 11 
	NOTATION_NODE = 12 
*/
	// null node
	if(node == null)
		return null;
	if(node.nodeType == 2) 
		return SOAPClient._extractValue(node.nodeName,node.nodeValue, wsdl);
	if(node.nodeType == 3 || node.nodeType == 4)
	{
		return SOAPClient._extractValue(node.parentNode.nodeName,node.nodeValue, wsdl);
	}
	
	var obj = eval("new function "+node.nodeName+"(){}");
		
	// leaf node
	if (node.childNodes.length == 1 && (node.childNodes[0].nodeType == 3 || node.childNodes[0].nodeType == 4))
		obj = SOAPClient._node2object(node.childNodes[0], wsdl);
		
	var isarray = SOAPClient._getDataTypeFromWsdl(node.nodeName, wsdl).toLowerCase().indexOf("arrayof") != -1;
	// object node
	if(!isarray)
	{
		for(var i = 0; i < node.childNodes.length; i++)
		{
			var p = SOAPClient._node2object(node.childNodes[i], wsdl);
			obj[node.childNodes[i].nodeName] = p;
		}

	}
	// list node
	else
	{
		// create node ref
		var arr = new Array();
		for(var i = 0; i < node.childNodes.length; i++)
			arr[arr.length] = SOAPClient._node2object(node.childNodes[i], wsdl);
		return arr;
	}
			// attributes and no text
	if(node.attributes != null)
	{
		for(var i = 0; i < node.attributes.length; i++)
		{
			var p = SOAPClient._node2object(node.attributes[i], wsdl);
			obj[node.attributes[i].nodeName] = p;
		}
	}
	return obj;
}


SOAPClient._extractValue = function(nodeName,nodeValue, wsdl)
{
	var value = nodeValue;
	switch(SOAPClient._getDataTypeFromWsdl(nodeName, wsdl).toLowerCase())
	{
		default:
		case "s:string":			
			return (value != null) ? value + "" : "";
		case "s:boolean":
			return value+"" == "true";
		case "s:int":
		case "s:long":
			return (value != null) ? parseInt(value + "", 10) : 0;
		case "s:double":
			return (value != null) ? parseFloat(value + "") : 0;
		case "s:datetime":
			if(value == null)
				return null;
			else
			{
				value = value + "";
				value = value.substring(0, value.lastIndexOf("."));
				value = value.replace(/T/gi," ");
				value = value.replace(/-/gi,"/");
				var d = new Date();
				d.setTime(Date.parse(value));										
				return d;				
			}
	}
}

var wsdlNodeBuff = []
SOAPClient._getDataTypeFromWsdl = function(elementname, wsdl)
{
   if (wsdlNodeBuff[elementname] == null)
   {
		wsdlNodeBuff[elementname] = getWsdlNode(elementname,wsdl)
	}
	
	node = wsdlNodeBuff[elementname]

	if (node == null)
	{
		return "";
	}

	type = node.attributes.getNamedItem("type").nodeValue; // IE
	if (type == "")
		type = node.attributes["type"].value; // MOZ
	return type
	
}

SOAPClient._isAttributeTypeWsdl = function(elementname, wsdl)
{
   if (wsdlNodeBuff[elementname] == null)
   {
		wsdlNodeBuff[elementname] = getWsdlNode(elementname,wsdl)
	}
	
	node = wsdlNodeBuff[elementname]

	if (node == null)
	{
		return false;
	}

	return (node.nodeName.indexOf("attribute") >= 0); 
	
}

function getWsdlNode(elementname, wsdl)
{
		
	var el = wsdl.getElementsByTagName("s:element");	// IE
	if(el.length == 0)
	{
		el = wsdl.getElementsByTagName("element");	// MOZ
	}
	
	var result;
	for(var i = 0; i < el.length; i++)
	{
		if(isRequiredWsdl(el[i],elementname))
			return el[i];
	}

	var el = wsdl.getElementsByTagName("s:attribute");	// IE
	if(el.length == 0)
		el = wsdl.getElementsByTagName("attribute");	// MOZ
	
	for(var i = 0; i < el.length; i++)
	{
		if(isRequiredWsdl(el[i],elementname))
			return el[i];
	}
	
	return null;	
	
}

function isRequiredWsdl(el,elname)
{
	if(el.attributes["name"] + "" == "undefined")	// IE
	{
		if(el.attributes.getNamedItem("name") != null && el.attributes.getNamedItem("name").nodeValue == elname && el.attributes.getNamedItem("type") != null) 
		{
			return  true;
		}
	}
	else // MOZ
	{
		if(el.attributes["name"] != null && el.attributes["name"].value == elname && el.attributes["type"] != null)
		{
			return true;
		}
	}
	return false;
}

function IsRequiredElement(el,elname)
{
	if(el.attributes["name"] + "" == "undefined")	// IE
	{
		if(el.attributes.getNamedItem("name") != null && el.attributes.getNamedItem("name").nodeValue == elname && el.attributes.getNamedItem("type") != null) 
		{
			return  el.attributes.getNamedItem("type").nodeValue;
		}
	}
	else // moz
	{
		if(el.attributes["name"] != null && el.attributes["name"].value == elname && el.attributes["type"] != null)
		{
			return el.attributes["type"].value;
		}
	}
	
	return "";
}

// private: xmlhttp factory
SOAPClient._getXmlHttp = function() 
{
	try
	{
		if(window.XMLHttpRequest) 
		{
			var req = new XMLHttpRequest();
			// some versions of Moz do not support the readyState property and the onreadystate event so we patch it!
			if(req.readyState == null) 
			{
				req.readyState = 1;
				req.addEventListener("load", 
									function() 
									{
										req.readyState = 4;
										if(typeof req.onreadystatechange == "function")
											req.onreadystatechange();
									},
									false);
			}
			return req;
		}
		if(window.ActiveXObject) 
			return new ActiveXObject(SOAPClient._getXmlHttpProgID());
	}
	catch (ex) {}
	throw new Error("Your browser does not support XmlHttp objects");
}
SOAPClient._getXmlHttpProgID = function()
{
	if(SOAPClient._getXmlHttpProgID.progid)
		return SOAPClient._getXmlHttpProgID.progid;
	var progids = ["Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
	var o;
	for(var i = 0; i < progids.length; i++)
	{
		try
		{
			o = new ActiveXObject(progids[i]);
			return SOAPClient._getXmlHttpProgID.progid = progids[i];
		}
		catch (ex) {};
	}
	throw new Error("Could not find an installed XML parser");
}
