function loadPopUp( pServlet, pLanguage, x ) {

    var screenHeight = (screen.availHeight / 2) - 190;
    var screenWidth  = (screen.availWidth  / 2) - 225;

    var region = x;
    if (navigator.appName == "Netscape") {
        doc = window.open( pServlet + "?" + pLanguage + "/REGION/COUNTRY_LIST/" + region,"BF","scrollbars=1,resizable=0,height=380,width=450,left=" + screenWidth + ",top=" + screenHeight );
    } else {
        doc = window.open( pServlet + "?" + pLanguage + "/REGION/COUNTRY_LIST/" + region,"BF","scrollbars=yes,resizable=false,height=380,width=450,left=" + screenWidth + ",top=" + screenHeight );
    }
  }

function scrollToTop () {
	var objDiv = document.getElementById('mainBody');
	objDiv.scrollTop = 0;
}

 function clearField( pId, pCompare ) {
	var wObj = 	document.getElementById( pId );
	if ( wObj.value == pCompare ) {
		wObj.value='';
	}
}

function helpBox(pElementId,e, pHideSelect) {
var is_ie6 = (
	window.external &&
	typeof window.XMLHttpRequest == "undefined");

    if (is_ie6 == true) {
    	if (!document.getElementsByTagName) return;

      	if (document.getElementsByTagName){
     	  var selects = document.getElementsByTagName("select");
      		for (var i=0; i<selects.length; i++) {
      			var select = selects[i];
       			if (selects[i].className == 'selectHide2' ) {
        			selects[i].style.display = 'none';
        		}
       			if ( pHideSelect == true ) {
       				if (selects[i].className == 'selectHide' ) {
	        			selects[i].style.display = 'none';
	        		}
	        	}
    		}
    	}
  	}

  	var posx = 0;
    var posy = 0;
    if(!e) var e = window.event;
    if(e.pageX || e.pageY) {
      posx = e.pageX;
      posy = e.pageY;
    } else if(e.clientX || e.clientY) {
        if (document.documentElement && document.documentElement.scrollTop) {
		   	scrollx = document.documentElement.scrollLeft;
		   	scrolly = document.documentElement.scrollTop;
		}
		else {
       		scrollx = document.body.scrollLeft;
       		scrolly = document.body.scrollTop;
   		}
          posx = e.clientX + scrollx;
          posy = e.clientY + scrolly;
	}

    var divPops = document.getElementsByTagName("div");
    for (var i=0; i< divPops.length; i++)
    {	var divPop = divPops[i];
           if (divPop.className =="whatsNew" || divPop.className =="whatsNew topBubble2"){

          	divPop.style.display = 'none';
    	}
    }

    var state  = document.getElementById(pElementId).style.display;
    if(document.getElementById)
    	{
      		if (state=='none') {
        			state = 'block';
      		} else {
        		 state = 'none';
      		}
		}
	if (document.documentElement.offsetWidth < posx + parseInt(document.getElementById(pElementId).style.width ))
	{
		var diff= posx - parseInt(document.getElementById(pElementId).style.width);
		document.getElementById(pElementId).className="whatsNew" + " " + "topBubble2" ;
		document.getElementById(pElementId).style.left=(diff) + 'px';
		document.getElementById(pElementId).style.top=(posy) + -50 + 'px';
		document.getElementById(pElementId).style.display=state;
	}
	else
	{

		document.getElementById(pElementId).className="whatsNew";
		document.getElementById(pElementId).style.top=(posy) + -50 + 'px';
		document.getElementById(pElementId).style.left=(posx) + 'px';
    	document.getElementById(pElementId).style.display=state;
	}
}

function closeIt(pElementId) {

	var state = document.getElementById(pElementId).style.display ;
	if ( state  == 'block') {
			state= 'none';
    }
    document.getElementById(pElementId).style.display= state;

	if (document.getElementsByTagName){
		var selects = document.getElementsByTagName("select");
		for (var i=0; i<selects.length; i++) {
			var select = selects[i];
			if (selects[i].className == 'selectHide2' || selects[i].className == 'selectHide' ) {
				selects[i].style.display = 'block';
			}
    	}
	}
}

function openCollapse( pListId, pImgId ) {
	var wList = document.getElementById(pListId);
	var wImage = document.getElementById(pImgId);
	if ( wList.style.display=="none" ) {
		wList.style.display="block";
		wImage.src="/cgi/[LBL_LANG]/img/selectBox_arrow.gif";
	} else {
		wList.style.display="none";
		wImage.src="/cgi/[LBL_LANG]/img/selectBox_arrow_down.gif";
	}
}

function collapseRecentSearchHistory( pListId, pImgId ) {
	var wList = document.getElementById(pListId);
	var wImage = document.getElementById(pImgId);
	if ( wList.style.display=="block" ) {
		wList.style.display="none";
		wImage.src="/cgi/[LBL_LANG]/img/selectBox_arrow_down.gif";
	}
}

function openCollapseSM( pListId, pImgId ) {
	var wList = document.getElementById(pListId);
	var wImage = document.getElementById(pImgId);
	if ( wList.style.display=="none" ) {
		wList.style.display="block";
		wImage.src="/cgi/[LBL_LANG]/img/selectBoxSM_arrow.gif";
	} else {
		wList.style.display="none";
		wImage.src="/cgi/[LBL_LANG]/img/selectBoxSM_arrow_down.gif";
	}
}

function toggleDiv( pListId, pImgId ){
	var wList = document.getElementById(pListId);
	var wImage = document.getElementById(pImgId);
	wList.style.display="none";
	wImage.src="/cgi/[LBL_LANG]/img/selectBox_arrow_down.gif";
}

function toggleDivSM( pListId, pImgId ){
	var wList = document.getElementById(pListId);
	var wImage = document.getElementById(pImgId);
	wList.style.display="none";
	wImage.src="/cgi/[LBL_LANG]/img/selectBoxSM_arrow_down.gif";
}

function reinitializeInput( pInputId, pNewValue ) {
    var wInput = document.getElementById(pInputId);

    if( wInput != null ) {
        wInput.value = pNewValue;
    }
}


function HideSee (wichOne , divTab, divContent)
{
    if (wichOne == 1)
        {

        document.getElementById(divContent).style.display = 'block';
           document.getElementById(divTab).className = "swap2";
        document.getElementById('divMulti').className = "swap4" ;
        document.getElementById('multiSearchContentId').style.display = 'none';


        }
     else if (wichOne == 2)
        {

            document.getElementById(divContent).style.display = 'block';

            document.getElementById(divTab).className = "swap1";
           document.getElementById('divSingle').className = "swap3";
            document.getElementById('SearchContentId').style.display = 'none';

        }

    }

function prepWwPreviewColors() {
	var wTarget = new Array("prev_genBckColor","prev_headerBckColor","prev_fontBckColor","prev_buttonBckColor");
	var wSource = new Array("WwClientSettings.BackgroundColor","WwClientSettings.TblHeaderBackgroundColor","WwClientSettings.FontColor","WwClientSettings.ButtonBackgroundColor");
	for(var i=0;i<wTarget.length;i++){
		document.getElementById(wTarget[i]).style.backgroundColor=document.getElementById(wSource[i]).value;
	}
}

function initWwFontFaceOptions( pSelectInputId ) {
    var selObj = document.getElementById(pSelectInputId);

    for( i=0; i < selObj.options.length; i++ ) {
       var selText = selObj.options[i].text;
       selObj.options[i].style.fontFamily = selText;
    }
}

function changeWwPreviewFont( pSelectInputId ) {
    var selObj = document.getElementById(pSelectInputId);
    var selText = selObj.options[selObj.selectedIndex].text;
    selObj.style.fontFamily = selText;

}

/**
*Used fo the Advanced Filters
**/
function onAdvFiltersLoad( pSelectedRegionGroup, pLi, pDiv) {

    openClose(pLi, pDiv);

    if( pSelectedRegionGroup != null && pSelectedRegionGroup != '' ) {
        var wListId = pSelectedRegionGroup.substr(0,pSelectedRegionGroup.indexOf('-'));
        var wImgId = pSelectedRegionGroup.substr(pSelectedRegionGroup.indexOf('-')+1);
        openCollapseRegion( wListId, wImgId);
    }
}

function openCollapseRegion( pListId, pImgId ) {
        //document.getElementById('selectedRegionGroup').value='plus${regionGroup.code}-imgplus${itemCount}';
        //collapseAll('regionGroup', 'imgplus', 'plus${regionGroup.code}', 'imgplus${itemCount}');
        //openCollapseRegion('plus${regionGroup.code}','imgplus${itemCount}')

		var wList = document.getElementById(pListId);
		var wImage = document.getElementById(pImgId);

		if ( wList.style.display=="none" ) {
			wList.style.display="block";
			wImage.src="/cgi/en/img/blueMinusSign.gif";
		} else {
			wList.style.display="none";
			wImage.src="/cgi/en/img/bluePlusSign.gif";
			
			document.getElementById("selectedRegionGroup").value = "";
		}
}

function collapseAll( pListName, pImgName, pCurrentListId, pCurrentImgId ) {
       
        var wRegionGroups = document.getElementById('regionsSelection').getElementsByTagName(pListName);
        var wImgPlus = document.getElementsByName(pImgName);
        for( var i=0; i<wRegionGroups.length; i++) {
           
            if((wRegionGroups[i].id)!= pCurrentListId) {
             
                wRegionGroups[i].style.display ='none';                
            }
         
        }

        for( var i=0; i<wImgPlus.length; i++) {
            if(wImgPlus[i].id != pCurrentImgId) {
                wImgPlus[i].src="/cgi/en/img/bluePlusSign.gif";
            }
        }
        
}

function openClose(pLi,pDiv)
{

		var ul = document.getElementById("filterOptions");
		var lists = ul.getElementsByTagName("li");
		var divParent = document.getElementById("changeDiv");
		var divsChild = divParent.getElementsByTagName("div");


	for (var i=0; i<lists.length; i++)
	{
	 var list = lists[i];

	 list.className = 'bkcNone';

	}

	for (var i =0; i< divsChild.length; i++)
		{
		var divChild = divsChild[i];
		if(divChild.className == "subTree1"){ divChild.style.display = 'none'; }

		}

	document.getElementById(pDiv).style.display ='block';
	document.getElementById(pLi).className = 'selected';

}

function displayContent( pController, pDivName ) {

    var loader = new ContentLoader( pController, pDivName, '' );
	loader.start();
}


function initializeAndSubmitForm( pFormId, pController, pTargetIFrame ) {
    initializeForm( pFormId, pController, pTargetIFrame )
    document.forms[pFormId].submit();
}

function initializeForm( pFormId, pInitialAction, pTarget ) {
    if(document.forms[pFormId] != null) {
        document.forms[pFormId].action = pInitialAction;
        document.forms[pFormId].target = pTarget;
    }
}


function onLoadIFrameDisplayAdvFilters( pEvent, pTargetDivId, pIFrameId ) {
    var iframe = pIFrameId ;
	var targetElement = pTargetDivId ;
	if (getIFrameDocument(iframe).body.innerHTML != ''){
		cleanup(targetElement);
		createHtml(targetElement, getIFrameDocument(iframe).body.innerHTML );
		cleanup(iframe);
		//alert(document.getElementById('advFiltersOpen').value);
        //if(document.getElementById('advFiltersOpen').value != 'true') {
		    deactivateDivPopUp();
		    displayDivValueInDivPopUp( pTargetDivId, null, false, false, '532px', '400px', '200px', '300px', pEvent );
		//}


		cleanup(targetElement);
		cleanup(iframe);
	}
}

function checkUncheckChildrens( pParentId, pChildPrefixId, pChildrenCount ) {

	var pListChkBox = document.getElementById( pParentId );
	var pCheckedStatus = false;

	if( pListChkBox.checked ) {
		pCheckedStatus = true;
	}
	for ( var j = 0; j < pChildrenCount; j++ ) {
		var pChildElId = pChildPrefixId + j;
		var pChildEl = document.getElementById( pChildElId );
		pChildEl.checked = pCheckedStatus

	}
}

function checkUncheckParent( pParentId, pChildPrefixId, pChlidrenCount ) {

    var wSelectedChildrenCount = 0
    for ( var j = 0; j < pChlidrenCount; j++ ) {
		var pChildElId = pChildPrefixId + j;
		var pChildEl = document.getElementById( pChildElId );
		if( pChildEl.checked  ){
		    wSelectedChildrenCount++
		}
	}
	var pParentChkBox = document.getElementById( pParentId );
	if( wSelectedChildrenCount > 0  ) {
	    pParentChkBox.checked = true;
	} else {
	    pParentChkBox.checked = false;
	}
}

/*
function onLoadIFrameAdvFilters( pIFrameId, pEvent, pDivId ) {

	var iframe = pIFrameId ;
	if (getIFrameDocument(iframe).body.innerHTML != ''){
		cleanup(pDivId);
		createHtml(pDivId, getIFrameDocument(iframe).body.innerHTML );
		cleanup(iframe);
	}

}
*/
function clearAll(pController,pDivName) {
    var wUrl = pController + '?SearchCriteria_originalFullPartNumber=' +
                    document.formAdvFilters.SearchCriteria_originalFullPartNumber.value +
                    '&SearchCriteria_MfgCode=' +
                    document.formAdvFilters.SearchCriteria_MfgCode.value +
                    '&SearchCriteria_quantity=' +
                    document.formAdvFilters.SearchCriteria_quantity.value +
                    '&SearchCriteria_dateCode=' +
                    document.formAdvFilters.SearchCriteria_dateCode.value +
                    '&SearchCriteria_Price=' +
                    document.formAdvFilters.SearchCriteria_Price.value +
                    '&isPriorityOnSearchBox=true' +
                    '&isMultiRegionMode=true';

    var loader = new ContentLoader( wUrl, pDivName, '' );
    loader.start();
}
/*
function setMyBuyRegion(pController,pDivName) {

    var wUrl = pController + '?SearchCriteria_originalFullPartNumber=' +
                    document.formAdvFilters.SearchCriteria_originalFullPartNumber.value +
                    '&SearchCriteria_MfgCode=' +
                    document.formAdvFilters.SearchCriteria_MfgCode.value +
                    '&SearchCriteria_quantity=' +
                    document.formAdvFilters.SearchCriteria_quantity.value +
                    '&SearchCriteria_dateCode=' +
                    document.formAdvFilters.SearchCriteria_dateCode.value +
                    '&SearchCriteria_Price=' +
                    document.formAdvFilters.SearchCriteria_Price.value +
                    '&isPriorityOnSearchBox=true&RegionId=SELECTED_ONLY';

    var loader = new ContentLoader( wUrl, pDivName, '' );
    loader.start();
}
*/

/*
 * Author : http://www-128.ibm.com/developerworks/web/library/wa-ie2mozgd/
 */
function getIFrameDocument(aID){
	 var rv = null;

	 // if contentDocument exists, W3C compliant (Mozilla)
	 if (document.getElementById(aID).contentDocument){
	   rv = document.getElementById(aID).contentDocument;
	 } else {
	   // IE
	   rv = document.frames[aID].document;
	 }

	 return rv;
}

function bfCollapseExpand(ulId, imgId)
{
   var img = document.getElementById(imgId);
   var ul = document.getElementById(ulId);
        if ( ul.style.display == 'block' )
		    {
		    ul.style.display = 'none';
		    img.className ="imgPlus";
		    }
     else if ( ul.style.display =='none' )
		    {
		       ul.style.display ='block';
		       img.className ="imgMinus";
		    }
		}

function openCollapseList(pItemId,pImgId,pCollapseImg,pOpenImg) {
 var wItem = document.getElementById(pItemId);
 var wImgs = document.getElementsByTagName("img");
 for ( i=0;i<wImgs.length;i++ ) {
  if ( wImgs[i].id == pImgId ) {
   if (wItem.style.display == 'none' ) {
    wImgs[i].src=pCollapseImg;
   } else {
    wImgs[i].src=pOpenImg;
   }
  }
 }
 
 if (wItem.style.display == 'none' ) {
  wItem.style.display = 'block';
 } else {
  wItem.style.display = 'none';
 }
}

function toggleTab (wichOne, divTab, divContent)
{
    if (wichOne == 1)
        {
            document.getElementById(divContent).style.display = 'block';
            document.getElementById(divTab).className = "tabs1"
            document.getElementById('Assign').className = "tabs2" ;
            document.getElementById('box2').style.display = 'none';
        }
     else if (wichOne == 2)
        {
            document.getElementById(divContent).style.display = 'block';
            document.getElementById(divTab).className = "tabs1";
            document.getElementById('uAccountBox').className = "tabs2";
            document.getElementById('box1').style.display = 'none';
        }

    }


  function toggleIt(wichOne, divTab, divContent,alink)
{
    if (wichOne == 1 )
        {
            document.getElementById('newRating').style.display = 'block';
            document.getElementById('ReqForRating').style.display = 'none';
            document.getElementById('searchResults').style.display = 'none';
            document.getElementById(divTab).className = 'part1';
            document.getElementById('ratingTabs2').className = 'part3';
                if (! (document.getElementById(alink).className =='Btndisabled'))
                    {
                        document.getElementById('ratingTabs3').className = 'part3';
                    }

        }
     else if (wichOne == 2)
        {
            document.getElementById(divContent).style.display = 'block';
            document.getElementById('searchResults').style.display = 'none';
            document.getElementById(divTab).className = "part2";
            document.getElementById('ratingTabs1').className = "part3";
            document.getElementById('newRating').style.display = 'none';
                if (!(document.getElementById(alink).className =='Btndisabled'))

                    {

                    document.getElementById('ratingTabs3').className = 'part3';
                    }
         }

     else if(wichOne == 3 || (document.getElementById(alink).className !='Btndisabled'))
         {
            document.getElementById('ratingTabs3').style.display = 'block';
            document.getElementById(divContent).style.display = 'block';
            document.getElementById('newRating').style.display = 'none';
            document.getElementById('ReqForRating').style.display = 'none';
            document.getElementById('ratingTabs1').className = "part3";
            document.getElementById('ratingTabs2').className = "part3";
            document.getElementById('ratingTabs3').className = "part2";


         }


    }

    function checkDisable(link){
    if(document.getElementById(link).className == 'Btndisabled')
        {
            document.getElementById(link).className = 'enable';
            document.getElementById('btnDisabled').style.display = 'none';
            document.getElementById('searchResults').style.display ='block';
            document.getElementById('newRating').style.display ='none';
           document.getElementById('ReqForRating').style.display ='none';
          document.getElementById('ratingTabs1').className ='part3';
          document.getElementById('ratingTabs2').className ='part3';
          document.getElementById('ratingTabs3').className ='part2';

        }

}
/*************BF-Account*Light*Box************/
var PageInfo = {
   getPageSizeWithScroll:
   function (){
    if (window.innerHeight && window.scrollMaxY) {// Firefox
     yWithScroll = window.innerHeight + window.scrollMaxY;
     xWithScroll = window.innerWidth + window.scrollMaxX;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
     yWithScroll = document.body.scrollHeight;
     xWithScroll = document.body.scrollWidth;
    } else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
     yWithScroll = document.body.offsetHeight;
     xWithScroll = document.body.offsetWidth;
    }
    arrayPageSizeWithScroll = new Array(xWithScroll,yWithScroll);
    return arrayPageSizeWithScroll;
   },
 
   getViewPortSize:
   function (){
    var xViewPort = self.innerWidth || (document.documentElement.clientWidth || document.body.clientWidth);
    var yViewPort = self.innerHeight || (document.documentElement.clientHeight || document.body.clientHeight);
    arrayViewPortSize = new Array(xViewPort,yViewPort);
    return arrayViewPortSize;
   },
 
   getPageCornerCoord:
   function (){
    var pageSizeWithScroll = this.getPageSizeWithScroll()
    var xCornerCoord = pageSizeWithScroll[0] - pageSizeWithScroll[0] + document.body.scrollLeft + document.documentElement.scrollLeft;
    var yCornerCoord = pageSizeWithScroll[1] - pageSizeWithScroll[1] + document.body.scrollTop + document.documentElement.scrollTop;
    arrayPageCornerCoord = new Array(xCornerCoord,yCornerCoord);
    return arrayPageCornerCoord;
   }
};

function divCloseit(pElementId)
{
    document.getElementById('greyBox').style.display = 'none';
    document.getElementById(pElementId).style.display = 'none';
}

function copyIFrameToDivPopUp( pIFrameId, pElementId ){
	var iFrameInnerHtml = getIFrameDocument(pIFrameId).body.innerHTML; 
	cleanup(pElementId);
	if ( iFrameInnerHtml != ''){
		createHtml(pElementId, iFrameInnerHtml );
		iFrameInnerHtml = ''
	}
}

function divPopUpFrame( pIFrameId, pElementId, pHeight, pWidth ) {
	copyIFrameToDivPopUp( pIFrameId, pElementId );
	hideElementByTag( 'select', true );
	divPopUp( pElementId, pHeight, pWidth );
}

function closeIFramePopUp( pElementId ) {
	hideElementByTag( 'select', false );
	getIFrameDocument('iFrameMembersSearch').body.innerHTML = ''
    closeIt( pElementId );
}

function hideElementByTag( pElemTag, pHide ) {
    if (document.getElementsByTagName){
        var selects = document.getElementsByTagName( pElemTag );
      	for (var i=0; i<selects.length; i++) {
      		var select = selects[i];
       		if ( pHide == true ) {
       		    selects[i].style.visibility = 'hidden';
        	} else {
        	    selects[i].style.visibility = 'visible';
        	}
    	}
    }
}

function divPopUp(pElementId, pHeight, pWidth) {
	var state = document.getElementById('greyBox').style.display;
    var divWidth;
    var divHeight;
    
    if (document.getElementById(pElementId)) {
    	if (state == 'none') {
        state = 'block';
        } else {
        state = 'none';
        }

           if (pWidth > 0) {
    	     divHeight = pHeight;
    	     divWidth = pWidth; 
    	    } else {
                 divHeight = 337;
    	         divWidth = 535;
    	    }
           
    	 //For a div with a flash inside the div
           
    	 if (document.getElementById('clBox')) {
    	     document.getElementById(pElementId).innerHTML = document.getElementById('clBox').innerHTML; 
    	 }
    	 
         document.getElementById(pElementId).style.left = (PageInfo.getPageCornerCoord()[0] + ((PageInfo.getViewPortSize()[0] - divWidth)/2))+'px';
		 document.getElementById(pElementId).style.top = (PageInfo.getPageCornerCoord()[1] + ((PageInfo.getViewPortSize()[1] - divHeight)/2))+'px';
		 document.getElementById(pElementId).style.display = state;
		 document.getElementById('greyBox').style.display = state;
		 document.getElementById('greyBox').style.height = PageInfo.getPageSizeWithScroll()[1] + 'px';
		 if (parseInt(document.getElementById('greyBox').style.height) < 600) {
	           document.getElementById('greyBox').style.height = 100 + '%';
	     }		 
    }
}

function openWindow( pURL, pWidth, pHeight, pScrollbars ) {
    if (typeof pScrollbars == "undefined") {
        pScrollbars = "no";
    }
    popWin = window.open( "", "Agreement", "width=" + pWidth + ",height=" +  pHeight + ",dependent=yes,scrollbars=" + pScrollbars + ",resizable=1" );
    popWin.location.replace( pURL );
    popWin.moveTo(0,0);
    popWin.focus();
}


function updateSortingData(gridDataStore){
    var size = gridDataStore.getTotalCount();
    for ( i = 0; i < size; i++) {
        var record = gridDataStore.getAt(i);
        var rowIndex = gridDataStore.indexOf(record);
        record.set('Order', rowIndex + 1);
	}
}

function roundToHalf(value) {
   var converted = parseFloat(value); // Make sure we have a number
   var decimal = (converted - parseInt(converted, 10));
   decimal = Math.round(decimal * 100);
   if (decimal == 50) { return (parseInt(converted, 10)+0.5); }   
   if ( (decimal >= 25) && (decimal < 75) ) {
      return (parseInt(converted, 10)+0.5);   
   } else if (decimal >= 75 ) {
      return (parseInt(converted, 10)+1);
   } else {
      return parseInt(converted,10);
   }
}



function displayGlobalStars(pSpanName, pGlobalAvg) { //alert('Global ::: ' + pSpanName +":::"+ pGlobalAvg);
    setStarClass(""+roundToHalf(pGlobalAvg), 1, pSpanName);
}

function displayStars(pSpanName, pAvg) { //alert(pSpanName +':: '+ pAvg);
   setStarClass(""+roundToHalf(pAvg), 1, pSpanName);
}

function setStarClass(pAvg, pIndex, pSpanName) {

        //var i = 1;
        //alert("INIT "+pScore +" ::: "+ pIndex + "####" + pSpanName);
        var wElementId = pSpanName+''+pIndex;
    if(pIndex <= 5) {
        if(pAvg >=1) {
        //alert(">=1");

        //alert("ElementId: "+wElementId);
        //alert(document.getElementById(wElementId).className);
            document.getElementById(wElementId).className="fullStar";
            setStarClass(pAvg-1, pIndex+1, pSpanName);
        }
        else if(pAvg > 0 && pAvg < 1) {
        //alert("pScore > 0 && pScore < 1");
            document.getElementById(wElementId).className="halfStar";
            setStarClass(pAvg-1, pIndex+1, pSpanName);
        }
    }
}

function validateMaxCharacters(pInputField, pCountfield, pMaxLimit) {
	var wInputField = document.getElementById( pInputField );
	var wCountfield = document.getElementById( pCountfield );
	var wInputFieldValueLength = wInputField.value.length;
	if(wInputFieldValueLength > pMaxLimit) {
		// if too long...trim it!
		wInputField.value = wInputField.value.substring(0, pMaxLimit);
		// otherwise, update 'characters left' counter
	} else {
	    var wRemainingCharactersCount = (wInputField.value.length);
		wCountfield.innerHTML = "" + wRemainingCharactersCount + " / " + pMaxLimit;
	}
}

function showandTell(divtoShow){

   var state = document.getElementById(divtoShow).style.display;
   var state2 = document.getElementById('no0').style.display;
    if(state =='none')
       {
       state = 'block';
       state2 = 'none'; }
     else
      {
      state ='none';
      state2 = 'block';
      }
      document.getElementById(divtoShow).style.display = state;
      document.getElementById('no0').style.display = state2;
 }

 function mouseOutOver(divtoShow){

   var state = document.getElementById(divtoShow).style.display;

    if(state =='none')
       {

        state = 'block';
    }
     else
      {
          state ='none';
      }
      document.getElementById(divtoShow).style.display = state;

 }
 function displayTextareaMessage(pId, pVisible) {
	
	if( document.getElementById(pId) != null ) {
    	if (pVisible == true) {
    		 document.getElementById(pId).style.display = 'block';
    	}
    	 else 
    	 	{
    	 		document.getElementById(pId).style.display = 'none';
    	 	}
    }
 }

 
 
 function setMaxLength() {
	 	var existingCounter = document.getElementById('textareacounter');
	 	if ( existingCounter == null) {
	 
	 		var x = document.getElementsByTagName('textarea');
	 		var counter = document.createElement('div');
	 		counter.id='textareacounter';
	 		counter.className = 'counter';
	 		for (var i=0;i<x.length;i++) {
	 			if (x[i].getAttribute('maxlength')) {
	 				var counterClone = counter.cloneNode(true);
	 				counterClone.relatedElement = x[i];
	 				counterClone.innerHTML = '<span>0</span>'+'<span>/'+x[i].getAttribute('maxlength')+'</span>';
	 				x[i].parentNode.insertBefore(counterClone,x[i].nextSibling);
	 				x[i].relatedElement = counterClone.getElementsByTagName('span')[0];
	 				x[i].onkeyup = x[i].onchange = checkMaxLength2;
	 				x[i].onkeyup();
	 			}
	 		}
	 	}
	}

	 function setMaxFeed() {
		
		var x = document.getElementsByTagName('textarea');
		var counter = document.createElement('div');
		
		for (var i=0;i<x.length;i++) {
			if (x[i].getAttribute('tabindex')) {
				counter.className = 'counter' + ' ' + 'chr'+ i;
				var counterClone = counter.cloneNode(true);
				counterClone.relatedElement = x[i];
				counterClone.innerHTML = '<span>0</span>'+'<span>/'+x[i].getAttribute('tabindex')+'</span>'+'<span class="fNormal">&#160;{Character Limit}</span>';
				x[i].parentNode.insertBefore(counterClone,x[i].nextSibling);
				x[i].relatedElement = counterClone.getElementsByTagName('span')[0];
				var txtError = 'testMessage'+ i;
				x[i].onkeyup = x[i].onchange = function(){checkMaxLength(txtError,this); };
				x[i].onkeyup();
			}
		}
	}
	
	
	function checkMaxLength(textError, textarea ) 
	{
		var tm = textarea;
		var maxLength = tm.getAttribute('tabindex');
		var currentLength = tm.value.length;
		if (currentLength > maxLength) {
     		tm.relatedElement.className = 'toomuch';
			displayTextareaMessage(textError, true);
		}
		else 
			{
				tm.relatedElement.className = '';
				displayTextareaMessage(textError, false);
			}
	  tm.relatedElement.firstChild.nodeValue = currentLength;
		// not innerHTML
	}

	function checkMaxLength2() 
	{
		var maxLength = this.getAttribute('maxlength');
		var currentLength = this.value.length;
		if (currentLength > maxLength) {
			this.relatedElement.className = 'toomuch';
			displayTextareaMessage('textareMessage', true);
		}
		else {
			this.relatedElement.className = '';
			displayTextareaMessage('textareMessage', false);
		}
		this.relatedElement.firstChild.nodeValue = currentLength;
		// not innerHTML
	}
	function findPos(obj) 
	{
	var curleft = curtop = 0;
	if (obj.offsetParent)
	  {
	    do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
			}while (obj = obj.offsetParent);
	      return [curleft,curtop];
	       }	
		}
	
	
	function popUpDivRegion(divToShow, tdEscrow, tdPref)
	{
	    var div = document.getElementById(divToShow);
        var tdEscrowColor = document.getElementById(tdEscrow);
	    var tdPrefColor = document.getElementById(tdPref); 
        tdEscrowColor.style.backgroundColor = tdEscrowColor.parentNode.style.backgroundColor;
        tdPrefColor.style.backgroundColor = tdEscrowColor.parentNode.style.backgroundColor;
	     if( document.getElementById('bubbeTbl').style.display =='none')
	        { 
	           document.getElementById('bubbeTbl').innerHTML = "<span class='bubleStyle'>" + div.innerHTML + "</span>"; 
	          tdEscrowColor.style.backgroundColor = '#DFE8F6';
	          tdPrefColor.style.backgroundColor = '#DFE8F6';  
	           tab1 = new Array();
	           tab1 = eval(findPos(tdEscrowColor));
	           document.getElementById('bubbeTbl').style.left = tab1[0] - 99 + "px";
	           document.getElementById('bubbeTbl').style.top = tab1[1] + 20 + "px";
	           document.getElementById('bubbeTbl').style.display='block';
	         }
	}
	function popUpDivRating(tdStar,aWhiteSpace,starValue)
	{
	    var pStar = document.getElementById(tdStar);
	    var paWhiteSpace = document.getElementById(aWhiteSpace);
 		
 		if (starValue != null && starValue != '')
 		{
		     if( document.getElementById('ratingChart_' + starValue).style.display =='none' && starValue != null)
		        { 
		        	paWhiteSpace.style.backgroundColor = '#fffae3';  
		        	pStar.style.backgroundColor = '#fffae3';  
		           	tab1 = new Array();
		           	tab1 = eval(findPos(pStar));
		            document.getElementById('ratingChart_' + starValue).style.left = tab1[0] + 80 + 'px' ;
		            document.getElementById('ratingChart_' + starValue).style.top = tab1[1] - 110 + 'px';
		            document.getElementById('ratingChart_' + starValue).style.display='block';
		         }
		     else
		      	{
			      	paWhiteSpace.style.backgroundColor = '#ffffff';
			      	pStar.style.backgroundColor = '#ffffff';  
			      	document.getElementById('ratingChart_' + starValue).style.display ='none';
		      	}   
		 }
		 else
		 {
	      	if( document.getElementById('ratingChart').style.display =='none' )
		        { 
		        	paWhiteSpace.style.backgroundColor = '#fffae3';  
		        	pStar.style.backgroundColor = '#fffae3';  
		           	tab1 = new Array();
		           	tab1 = eval(findPos(pStar));
		            document.getElementById('ratingChart').style.left = tab1[0] + 80 + 'px' ;
		            document.getElementById('ratingChart').style.top = tab1[1] - 110 + 'px';
		            document.getElementById('ratingChart').style.display='block';
		         }
		     else
		      	{
		      		paWhiteSpace.style.backgroundColor = '#ffffff';
		      		pStar.style.backgroundColor = '#ffffff';  
		      		document.getElementById('ratingChart').style.display ='none';
		      	}   
		 }
	}
	 
	function popUpDivDetails(td1,td2,title,details,posy)
	{
		pTd1 = document.getElementById(td1);
		pTd2 = document.getElementById(td2);
		pTitle = document.getElementById(title);
		pDetails = document.getElementById(details);
		tab1 = new Array();
        tab1 = eval(findPos(pTd1));
        wCatDetailPopup = document.getElementById('catDetails');	
        wCatDetailPopup.style.left = tab1[0] + 25 + 'px';
        wCatDetailPopup.style.top = tab1[1] - posy + 'px';
        var wCatTitle = document.getElementById('catTitle');
        wCatTitle.innerHTML = pTitle.innerHTML;
		document.getElementById('catDetail').innerHTML = pDetails.innerHTML;
				
		if( wCatDetailPopup.style.display == 'none' ) {
			wCatDetailPopup.style.display='';
			pTd1.style.backgroundColor = '#fffae3';
        	pTd2.style.backgroundColor = '#fffae3';
		}
	}
	
	function hideDivDetails(td1,td2) {
	    wCatDetailPopup = document.getElementById('catDetails');
	    wTd1 = document.getElementById(td1);
		wTd2 = document.getElementById(td2);
		wCatDetailPopup.style.display='none';
		wTd1.style.backgroundColor = 'transparent';
        wTd2.style.backgroundColor = 'transparent';
	}
	
	function showHideRatingLegend(pIdToShow,pCellId,pGroupText,pHiddenRating,e) {
		var wVendorRatingPopup = document.getElementById(pIdToShow);
		var wX, wY = 0;
		// Get x,y coords of mouse
		if ( document.captureEvents ) {
			wX = e.pageX;
			wY = e.pageY;
		} else if ( window.event.clientX ) {
			wX = window.event.clientX+document.documentElement.scrollLeft;
			wY = window.event.clientY+document.documentElement.scrollTop;
		}

		var scrX = Number(wX);
		var scrY = Number(wY);
		var tp = parseInt(scrY);
		var lt = parseInt(scrX);
		
		if ( parseInt(document.documentElement.clientWidth+document.documentElement.scrollLeft) < parseInt(wVendorRatingPopup.offsetWidth+lt) ) {
			wVendorRatingPopup.style.left = parseInt(lt-(wVendorRatingPopup.offsetWidth+10))+'px';
		} else {
			wVendorRatingPopup.style.left = parseInt(lt+20)+'px';
		}
		if ( parseInt(document.documentElement.clientHeight+document.documentElement.scrollTop) < parseInt(wVendorRatingPopup.offsetHeight+tp) ) {
			wVendorRatingPopup.style.top = parseInt(tp-(wVendorRatingPopup.offsetHeight+10)-150)+'px';
		} else {
			wVendorRatingPopup.style.top = parseInt(tp-130)+'px';
		}
		
		var wGroupText = document.getElementById('ratingCat');
		wGroupText.innerHTML = pGroupText + "<br /><strong>Rated " + document.getElementById(pHiddenRating).value + "</strong>";
		
		if ( wVendorRatingPopup.style.display=='none') {
			wVendorRatingPopup.style.display='';
			document.getElementById(pCellId).style.backgroundColor='#fffae3';
		} else {
			wVendorRatingPopup.style.display='none';
			document.getElementById(pCellId).style.backgroundColor='transparent';
		}
	} 
	 
	function popUpFlush( divtoShow, tdescrow, tdPref)
	{   
	   var td1 = document.getElementById(tdescrow);    
	   var td2 = document.getElementById(tdPref); 
      	
	   document.getElementById('bubbeTbl').style.left = '';
	   document.getElementById('bubbeTbl').style.top = '';
	   
	    
	if(document.getElementById('bubbeTbl').style.display == 'block')
	     {
	           td1.style.backgroundColor = td1.parentNode.style.backgroundColor;
	           td2.style.backgroundColor = td1.parentNode.style.backgroundColor;  
	           document.getElementById('bubbeTbl').innerHTML = '';
               document.getElementById('bubbeTbl').style.display = 'none';
	           
	      }
	}
	
	function popUpDivSimple(divShowDesc,tdShowDesc)
	{
	     
	   var divShow = document.getElementById(divShowDesc);
       var tdPos = document.getElementById(tdShowDesc);	   
        if(document.getElementById('bubbeTbl2').style.display == 'none')
	        {
	           tab1 = new Array();
	           tab1 = eval(findPos(tdPos));
               document.getElementById('bubbeTbl2').style.left = tab1[0] + "px";
               document.getElementById('bubbeTbl2').style.top = tab1[1] + 15 + "px";
               document.getElementById('bubbeTbl2').style.display='block';
               document.getElementById('bubbeTbl2').innerHTML = divShow.innerHTML + '<div class="bottom"></div>'; 
             }
	}
	function popUpSpFlush(divShowDesc,td)
	{    
	
	    document.getElementById('bubbeTbl2').style.left = '';
	    document.getElementById('bubbeTbl2').style.top = '';
	   var div1 = document.getElementById(divShowDesc);
	    if(document.getElementById('bubbeTbl2').style.display == 'block')
	         {
	           document.getElementById('bubbeTbl2').style.display = 'none';
	              if(div1)
	             {
	                   
	                   document.getElementById('bubbeTbl2').innerHTML = '';
	                   div1.style.display = 'none';
	               }
	               
	           } 
	}
	
	function showInfo(infoText)
	
	{
	   var chck =document.getElementById('chkUseMergedPart');
	   var info = document.getElementById(infoText).innerHTML;
	  if ( document.getElementById('bubbeTbl2').style.display == 'none')
	    {
	        document.getElementById('bubbeTbl2').innerHTML = '<div class="top left">' + info + '</div><div class="bottom"></div>';
	        document.getElementById('bubbeTbl2').style.display = 'block';
	        tab1 = new Array();
	        tab1 = eval(findPos(chck ));
	        document.getElementById('bubbeTbl2').style.left = tab1[0]+ 80 + "px";
            document.getElementById('bubbeTbl2').style.top = tab1[1] - 70 + "px";
	    }
	    else if(document.getElementById('bubbeTbl2').style.display == 'block')
	        {
	          document.getElementById('bubbeTbl2').style.display = 'none';
	        }
	   
	}

	/**************************
	 *       GENERIC AJAX
	 **************************/

	/*
	 * Create Html
	 *
	 * Author : Simon Vaillancourt
	 */
	function createHtml(elementId, html){
	 var content = document.getElementById(elementId);
	 content.appendChild(toDOM(html));
	}

	/*
	 * Copy a DOM fragment received
	 * as a string to the HTML.
	 *
	 * Author : Simon Vaillancourt
	 */
	function toDOM(HTMLstring){
	 var d = document.createElement('div');
	 d.innerHTML = HTMLstring.replace(/\r|\n|\r\n/g, "");
	 var docFrag = document.createDocumentFragment();
	 while (d.firstChild) {
	  docFrag.appendChild(d.firstChild)
	 };
	 return docFrag;
	}

	/*
	 * Remove the children of a node
	 *
	 * Author : Simon Vaillancourt
	 */
	function cleanup(elementId){
	 var content = document.getElementById(elementId);
	 var child = content.firstChild;
	 while( child != null ){
	  content.removeChild(child);
	  child = content.firstChild;
	 }
	}

    /*
	 * Returns an object that allows
	 * us to make the requests.
	 *
	 * Author : Simon Vaillancourt
	 */
	function getRequest(){
	 var http;
	 var browser = navigator.appName;
	 if(browser == "Microsoft Internet Explorer"){
	  http = new ActiveXObject("Microsoft.XMLHTTP");
	 }else{
	  http = new XMLHttpRequest();
	 }
	 return http;
	}

	var ContentLoader = function(url, id, options){
         this.url = url;
         this.id = id;
	 this.init = false;
	 this.xmlHttp = false;
	 this.xml = false;
	 this.text = '';
	 this.done = false;
	 this.browser = '';
	 this.responseType = 'text'; //'text' or 'xml'
	 this.callback1 = function(){};
	 this.callback2 = function(){};
	 this.callback3 = function(){};
	 this.callback4 = function(){
		document.getElementById(this.id).innerHTML = this.text;
	 };
	 if (typeof options != 'undefined' ){
		if (typeof options.responseType != 'undefined' ){
			this.responseType = options.responseType;
		}
		if (typeof options.callback1 != 'undefined' ){
			this.callback1 = options.callback1;
		}
		if (typeof options.callback2 != 'undefined' ){
			this.callback2 = options.callback2;
		}
                if (typeof options.callback3 != 'undefined' ){
			this.callback3 = options.callback3;
		}
                if (typeof options.callback4 != 'undefined' ){
			this.callback4 = options.callback4;
		}
	 }
	 this.setup();
   };
ContentLoader.prototype.isIe = function(){
	if( this.browser.indexOf("ie") >= 0 ){
		return true;
	}else{
		return false;
	}
};
ContentLoader.prototype.setup = function(){
	if (typeof XMLHttpRequest!='undefined')
	{
	     this.xmlHttp = new XMLHttpRequest();
	     if(document.all){
	       this.browser = 'ie'+parseFloat(navigator.appVersion.split('MSIE')[1]);
	     }else{
	       this.browser = 'mozilla';
	     }
	}
	if (!this.xmlHttp && window.ActiveXObject)
	{
	    this.browser = 'ie'+parseFloat(navigator.appVersion.split('MSIE')[1]);
	    try
	    {
		this.xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
	    } catch (e) {
		try
		{
			this.xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e) { this.xmlHttp = false; }
	    }
	}
	var str = this.url;
	//alert(this.browser);
	if( this.isIe() ){
	  if( str.indexOf("?") >= 0 ){
	   this.url+="&millis"+new Date().getTime()+"="+new Date().getTime();
	  }else{
	   this.url+="?millis"+new Date().getTime()+"="+new Date().getTime();
	  }
	}
	//alert(this.url);
       if (this.xmlHttp) this.init = true;
};
ContentLoader.handler = function( o ){
		var obj = o;

		if (obj.xmlHttp.readyState == 1)
		{obj.callback1();
		}else if (obj.xmlHttp.readyState == 2)
		{obj.callback2();
		}else if (obj.xmlHttp.readyState == 3)
		{obj.callback3();
		}else if (obj.xmlHttp.readyState == 4)
		{	if (obj.xmlHttp.status == 200 || obj.xmlHttp.status == 0) {
				if( obj.responseType == 'text' ){
					obj.text = obj.xmlHttp.responseText;
				}else if( obj.responseType == 'xml' ){
					obj.xml = obj.xmlHttp.responseXML;
				}
				obj.done = true;
			}else{ 
				obj.text = obj.xmlHttp.status; 
			}
			obj.callback4();
		}
};
ContentLoader.prototype.start = function(pFunction){
		if (!this.init) return false;
		var me = this;
		try{
			this.xmlHttp.onreadystatechange = function() { 
				ContentLoader.handler(me, pFunction);
			}
			this.xmlHttp.open( 'GET', this.url, true );
			this.xmlHttp.send(null);
		}catch(e){
			this.init = false;
		}
};

/*
*	Ajax suggestion box controls
*
*	Author: St�phane Fortin
*
*	20/11/2007
*
*	See HOW-TO EXAMPLE at end of file
*	
*	TODO: 	Some work if we want to go back to a multi-column popup
*				- Trap right/left key
*				- New css
*
*			Add possibility to have more than one control per page.
*			
*	
*/

	//Key codes for keyboard key press event
	var DOWN_KEY_CODE = 40;
	var UP_KEY_CODE = 38;
	var PAGE_DOWN_KEY_CODE = 34;
	var PAGE_UP_KEY_CODE = 33;
	var ENTER_KEY_CODE = 13;
			
	//CSS classes
	var CLASS_INPUT_SUGGESTION_BOX_COLUMN = "InputSuggestionBoxListColumn";
	var CLASS_INPUT_SUGGESTION_BOX_LAST_COLUMN = "InputSuggestionBoxListLastColumn";
	var CLASS_INPUT_SUGGESTION_BOX_VALUE = "InputSuggestionBoxListValue";
	var CLASS_INPUT_SUGGESTION_BOX_SELECTED_VALUE = "InputSuggestionBoxListSelectedValue";
	
	//Default values constants
	var NB_VISIBLE_SUGGESTION_VALUES_UNDEFINED = -1;
	var MAX_ITEM_PER_COLUMN_PARAM_INFINITE_VALUE = -1;
	var NO_SELECTED_ITEM = -1;
	var SUGGESTION_BOX_HIDE_DELAY_FROM_USER_ACTION = 500;
	
	var xmlHttp;
	var inputSuggestionBoxContainerObj;
	var inputSuggestionBoxListObj;
	var fieldToFillObj;
	var cacheResults;
	var nbVisibleSuggestionValues;
	var maxItemsPerColumn;
	var controllerForData;
	var controllerParams = "";
	var targetDataElementNameInControllerOutput = "";
	var displayDelay = 0;
	var isSuggestionBoxVisible = false;
	var suggestionBoxControlsHaveFocus = false;
	var closeBoxDisplay = false;
	var selectedItemIndex = NO_SELECTED_ITEM;
	var selectedItemIndexInNbVisibleSuggestionValues = NO_SELECTED_ITEM;
	var nbCurrentItemSuggested = 0;
	var pixelToSkipOnUpDownArrow = null;
	var pixelToSkipOnPageUpPageDown = null;

	var currentTimerId = null;
	var currentPausedInputValue = null;

	var lastActionByKeyboard = false;
	
	/*
	*	Main method.  Receive objects to use and drives the synchronization of the suggestion box
	*	by dispatching the request client-side (if results are cache) and server side (for new results)
	*
	*
	*	pControllerForData 	Controller to call to get data
	*	
	*	pControllerParams 	Parameters passed to controller
	*
	*	pTargetDataElementNameInControllerOutput	Element name where to fetch the data.  All elements in document with
	*												the name specified will be counted as values. 
	*
	*	pInputSuggestionBoxContainerObj	Input Suggestion box container object
	*
	*	pInputSuggestionBoxListObj		Input Suggestion Box list object
	*
	*	pFieldToFillObj		Field to feed with selected data
	*
	*	pNbVisibleSuggestionValues	Number of values seen inside the suggestion box when poped (css dependent).  Used to know how many record to skip
	*								on pageUp/pageDown key press and know when to begin scrolling results in list on up/down key press.
	*	
	*	pMaxItemsPerColumn	Max entries by column (CSS styles dependent a.k.a. no float:left = 1 column only)
	*
	*	pDisplayDelay		Delay before starting the auto-completion process
	*
	*	pEvent				Event fired object
	* 
	*/
	function refreshSuggestionBox( pControllerForData, pControllerParams, pTargetDataElementNameInControllerOutput, pInputSuggestionBoxContainerObj, pInputSuggestionBoxListObj, pFieldToFillObj, pNbVisibleSuggestionValues, pMaxItemsPerColumn, pDisplayDelay, pPixelToSkipOnUpDownArrow, pPixelToSkipOnPageUpPageDown, pEvent ){
	
		if( !userMovedInSuggestionBoxWithKeyboard( pEvent ) ){
			selectedItemIndex = NO_SELECTED_ITEM;
			selectedItemIndexInNbVisibleSuggestionValues = NO_SELECTED_ITEM;
		 	initializeSuggestionBoxControl( pControllerForData, pControllerParams, pTargetDataElementNameInControllerOutput, pInputSuggestionBoxContainerObj, pInputSuggestionBoxListObj, pFieldToFillObj, pNbVisibleSuggestionValues, pMaxItemsPerColumn, pDisplayDelay, pPixelToSkipOnUpDownArrow, pPixelToSkipOnPageUpPageDown );
			
		 	//If suggestion box is visible and user has enter character to be more precise 
		 	if( isSuggestionBoxVisible && pFieldToFillObj.value != null && pFieldToFillObj.value.length > 1 ){
		 		dispatchToAppropriateDataLoadingProcess();
		 	}else{
		 		switchSuggestionBoxDisplay(false);
		 	
				currentPausedInputValue = null;
				
				//If a timer was existent, refresh the displayDelay time (since user added or removed a char in input)
				if( currentTimerId != null ){
					clearTimeout( currentTimerId );
					currentTimerId = null;
				}
		
				currentTimerId = setTimeout( 'dispatchToAppropriateDataLoadingProcess()', displayDelay);
				currentPausedInputValue = fieldToFillObj.value;
			}
		}else{
			controlSelectionByUserInput( pEvent );
		}
		
	} 			
	
/*********************************************
*********************************************	
 	Data fetching methods	
*********************************************	
********************************************/	
	
	/*
	*	Data loading process dispatcher.  To server if new data must be loaded or in memory
	*	if data already loaded.
	*
	*/	
	function dispatchToAppropriateDataLoadingProcess(){
	 	var wInputValue = fieldToFillObj.value;
	 	var wInputValueFirstChar = fieldToFillObj.value.charAt(0);
		
		//Clean old results
		clearSuggestionBox();	
			 	
	 	//If user has started typing in input box
	 	if( wInputValue.length > 0 ){
			var wResultArray = cacheResults[wInputValueFirstChar];
			
			//If existent values for corresponding first char
			if( wResultArray != null ){
		 		buildSuggestionBoxContent( wResultArray );
			}else{
		 		prepareAjaxCallToServer();
			}
		}
	}
	
	/*
	*	Prepare call to server 
	*
	*/
	function prepareAjaxCallToServer( ){
		if( xmlHttp == null ){
			alert("Your browser does not support AJAX!");
			return;
		}
					
		//Prepare input param and call server to refresh list
		try{
			if( fieldToFillObj.value != '' ){
				var wInputParam = controllerParams;
		    	//xmlHttp.open("GET", controllerForData + '?' + escape(wInputParam), true);
		    	xmlHttp.open("GET", controllerForData + '?' + wInputParam, true);
				xmlHttp.onreadystatechange=loadDataFromServerAndDispatchToBuildSuggestionBoxContent;
		    	xmlHttp.send(null);
		    }
		}catch( e ){
			//alert(e);
		}
	}
	
	/*
	*	Synchronize suggestion box entries and call prepare suggestion method (reason why it is call in here
	*	is because method called on xmlHttp.onreadystatechange event does not wait for operation to complete
	*	before calling next line code in prepareAjaxCallToServer() method ) . 
	*
	*/			
	function loadDataFromServerAndDispatchToBuildSuggestionBoxContent(){

	  if(xmlHttp.readyState==4)
	    {
	    	if( xmlHttp.responseXML != null && xmlHttp.responseXML.documentElement != null){
				var xmlDoc = xmlHttp.responseXML.documentElement;
				var wResultArray;
				var wColumnObj;
				
				if( targetDataElementNameInControllerOutput != null && targetDataElementNameInControllerOutput.length > 0 ){
					var wDataToDisplayNodes = xmlDoc.getElementsByTagName( targetDataElementNameInControllerOutput );
	
					if( wDataToDisplayNodes.length > 0 ){
						cacheResults[fieldToFillObj.value.charAt(0)]= new Array();
						wResultArray = cacheResults[fieldToFillObj.value.charAt(0)];
	
						//Iterate through results
						for( var i = 0; i < wDataToDisplayNodes.length; i++ ){
							//Add result to corresponding array and in suggestion box
							wResultArray[i] = wDataToDisplayNodes[i].firstChild.nodeValue;
						}
	
						//Must be call here because method called on xmlHttp.onreadystatechange event does not wait 
						//for operation to complete before calling next line code in prepareAjaxCallToServer() method.
					    buildSuggestionBoxContent( wResultArray );
					}
				}else{
					//alert('Impossible to fetch data.  Cause: target data element name was not specified.')				
				}
			}
	    }
	}	
	
/**************************************************************
**************************************************************	
 	Suggestion box generation and visibility control methods	
**************************************************************
**************************************************************/
		
	/*
	*	Build results table from client-side cache
	*
	*/
	function buildSuggestionBoxContent( pResultsArray ){
		var wStartsWithValueLowerCase = fieldToFillObj.value.toLowerCase();
		var wColumnObj;
		var wLastValue = "";
		nbCurrentItemSuggested = 0;
		
		//Find corresponding results
		for( var i = 0; i < pResultsArray.length; i ++ ){
			var wValue = pResultsArray[i];

			//Create column if first result or if number of item in one column is reached and there are still other results to process
			if( nbCurrentItemSuggested == 0 || ( maxItemsPerColumn != MAX_ITEM_PER_COLUMN_PARAM_INFINITE_VALUE && (nbCurrentItemSuggested % maxItemsPerColumn == 0)) ){
				wColumnObj = document.createElement("div");
				wColumnObj.className = CLASS_INPUT_SUGGESTION_BOX_COLUMN;
				inputSuggestionBoxListObj.appendChild( wColumnObj );
			}
			
			//If current value matches the startsWith param
			if( pResultsArray[i].toLowerCase().indexOf(wStartsWithValueLowerCase)== 0 ){
				wLastValue = pResultsArray[i];
				
				// Remove extra info
				var wIndexStartExtraInfo = wLastValue.indexOf( " " );
		
        		if ( wIndexStartExtraInfo != -1 ) {
            		wLastValue = wLastValue.substring( 0, wIndexStartExtraInfo );
        		}
				
				addSuggestionBoxEntry( pResultsArray[i], fieldToFillObj.value, wColumnObj, nbCurrentItemSuggested );
				nbCurrentItemSuggested++;
			}	
		}

		//Mark last column with another css class
		wColumnObj.className = CLASS_INPUT_SUGGESTION_BOX_LAST_COLUMN;

		//if only one suggestion and characters are already all entered input box
		if( suggestionBoxControlsHaveFocus && (( nbCurrentItemSuggested > 1 && fieldToFillObj.value == currentPausedInputValue ) ||
			( nbCurrentItemSuggested == 1 && fieldToFillObj.value.toLowerCase() != wLastValue.toLowerCase() ))  ){
			switchSuggestionBoxDisplay(true);
		}else{

			//If no entry found or if one entry and matches completely value entered in input box 
			if( nbCurrentItemSuggested == 0 || 
			( nbCurrentItemSuggested == 1 && fieldToFillObj.value.toLowerCase() == wLastValue.toLowerCase() ) ){  
				switchSuggestionBoxDisplay(false);
			}
		}
		
	}
	/*
	*	Add an entry in the suggestion list
	*
	*/
	function addSuggestionBoxEntry( pValue, pStartsWithValue, pColumnElement, pIndex ){
		var wParagraphElement = document.createElement("p");
		wParagraphElement.innerHTML = prepareDisplayValue( pValue, pStartsWithValue );
		
		wParagraphElement.className = CLASS_INPUT_SUGGESTION_BOX_VALUE;
		addEvent( wParagraphElement, 'click', function(){switchSuggestionBoxDisplay(false);} );
		addEvent( wParagraphElement, 'mouseover', function(){
																if( !lastActionByKeyboard ){
																	fieldToFillObj.value = pValue ;
															 		wParagraphElement.className = CLASS_INPUT_SUGGESTION_BOX_SELECTED_VALUE;
															 		this.id='SelectedSuggestion';
															 		switchListSelectedElement( selectedItemIndex, pIndex );
															 		selectedItemIndex = pIndex;
															 	}
															 } );
		pColumnElement.appendChild(wParagraphElement);
	}
	
	/*
	*	Prepare value that will be displayed to user.
	*
	*	Highlight corresponding letters to user input. 
	*
	*/
	function prepareDisplayValue( pValue, pStartsWithValue ){
		var wOutputValue = new StringBuffer();
		wOutputValue.append("<b>");
		for( var i = 0; i < pStartsWithValue.length; i++ ){
			var wChar;
			if( pValue.toLowerCase().charAt(i) == pStartsWithValue.toLowerCase().charAt(i) ){
				wChar = pValue.charAt(i);
			}else{
				if( pValue.toUpperCase().charAt(i) == pStartsWithValue.toUpperCase().charAt(i) ){
					wChar = pValue.charAt(i);
				}
			}
			 
			wOutputValue.append(wChar);
		}
	
		wOutputValue.append( "</b>" + pValue.substring(pStartsWithValue.length) );
		return wOutputValue.toString();
	}
	
	/*
	*	Remove all suggestions
	*
	*/
	function clearSuggestionBox(){
		if( inputSuggestionBoxListObj.firstChild ){
			while (inputSuggestionBoxListObj.firstChild) {
				inputSuggestionBoxListObj.removeChild(inputSuggestionBoxListObj.firstChild);
			}
		}	
		selectedItemIndex = NO_SELECTED_ITEM;
		selectedItemIndexInNbVisibleSuggestionValues = NO_SELECTED_ITEM;
	}
		
	/*
	*	Swith visibility with delay, user driven
	*
	*/
	function switchSuggestionBoxDisplay( pSetVisible ){
		if( pSetVisible ){
			closeBoxDisplay = false;
			setTimeout('displaySuggestionBox()', SUGGESTION_BOX_HIDE_DELAY_FROM_USER_ACTION );
			isSuggestionBoxVisible = true;
		}else{
			closeBoxDisplay = true;
			setTimeout('hideSuggestionBox()', SUGGESTION_BOX_HIDE_DELAY_FROM_USER_ACTION );
			isSuggestionBoxVisible = false;
		}
	}

	function displaySuggestionBox(){
		if( inputSuggestionBoxContainerObj != null && inputSuggestionBoxContainerObj.style.display != 'block' ){
			inputSuggestionBoxContainerObj.style.display = 'block';
			inputSuggestionBoxContainerObj.scrollTop = 0;
			isSuggestionBoxVisible = true;
		}
	}
			
	function hideSuggestionBox(){
		if( closeBoxDisplay && inputSuggestionBoxContainerObj != null && inputSuggestionBoxContainerObj.style.display != 'none' ){
			inputSuggestionBoxContainerObj.style.display = 'none';
			isSuggestionBoxVisible = false;
			selectedItemIndex = NO_SELECTED_ITEM;
			selectedItemIndexInNbVisibleSuggestionValues = NO_SELECTED_ITEM;
		}
	}
	
	function setSuggestionBoxControlsHaveFocusFlag( pFlag ){
		suggestionBoxControlsHaveFocus = pFlag;
	}


/*********************************************
*********************************************	
 	Suggestion selection by keyboard methods	
*********************************************	
*********************************************/	
	
	/*
	*	Check if event has been triggered by down/up arrow keys or pageup/pageDown keys
	*
	*/
	function userMovedInSuggestionBoxWithKeyboard( pEvent ){
		if( pEvent.keyCode == DOWN_KEY_CODE || 
			pEvent.keyCode == UP_KEY_CODE || 
			pEvent.keyCode == PAGE_DOWN_KEY_CODE || 
			pEvent.keyCode == PAGE_UP_KEY_CODE){
			return true;
		}
		
		return false;
	}
	
	/*
	*	Change selected suggestion and scroll down/up list
	*
	*/
	function controlSelectionByUserInput( pEvent ){

		if( isSuggestionBoxVisible ){
			lastActionByKeyboard = true;
			var wCurrentTop = inputSuggestionBoxContainerObj.scrollTop;
			var wElements = inputSuggestionBoxListObj.getElementsByTagName('p');

			if( selectedItemIndex == -1 ){
				inputSuggestionBoxContainerObj.scrollTop = 0;
			}
			
			//Select new entry in list and Scroll list
			switch( pEvent.keyCode ){

				//Down arrow
				case DOWN_KEY_CODE:
					if( !(selectedItemIndex + 1 > wElements.length - 1) ){//if enough entry to move one down
						switchListSelectedElement( selectedItemIndex, selectedItemIndex + 1 );
						
						//if selected line is not the last line visible in the box
						if( selectedItemIndexInNbVisibleSuggestionValues < nbVisibleSuggestionValues ){
							selectedItemIndexInNbVisibleSuggestionValues++;
						}
	
						//if newly selected entry must scroll page
						if( selectedItemIndex >= nbVisibleSuggestionValues ){//if newly selected entry must scroll page
							inputSuggestionBoxContainerObj.scrollTop = wCurrentTop + pixelToSkipOnUpDownArrow;
						}
					}									
					break;
					
				//Up arrow
				case UP_KEY_CODE:
					if( !(selectedItemIndex - 1 < 0) ){//if enough entry to move one up
						switchListSelectedElement( selectedItemIndex, selectedItemIndex - 1 );
	
	
						//if selected line is not the first line visible in the box
						if( selectedItemIndexInNbVisibleSuggestionValues > 0 ){
							selectedItemIndexInNbVisibleSuggestionValues--;
						}
						
						//More entry available above
						if( selectedItemIndex <= (wElements.length - 1) - nbVisibleSuggestionValues ){
							inputSuggestionBoxContainerObj.scrollTop = wCurrentTop - pixelToSkipOnUpDownArrow;
						}
					}								
					break;
					
				//Page Down
				case PAGE_DOWN_KEY_CODE:
					if( selectedItemIndex > NO_SELECTED_ITEM ){//if list has a selected entry
						if( !(selectedItemIndex + nbVisibleSuggestionValues > wElements.length - 1) ){//if enough entry to do a complete page down
							switchListSelectedElement( selectedItemIndex, selectedItemIndex + nbVisibleSuggestionValues );				
						}else{
							switchListSelectedElement( selectedItemIndex, wElements.length - 1 );				
						}				
						inputSuggestionBoxContainerObj.scrollTop = wCurrentTop + pixelToSkipOnPageUpPageDown ;
					}
					break;			
				
				//Page up	
				case PAGE_UP_KEY_CODE:
					if( selectedItemIndex > NO_SELECTED_ITEM ){//if list has a selected entry
						if( !(selectedItemIndex - nbVisibleSuggestionValues < 0) ){//if enough entry to do a complete page up
							switchListSelectedElement( selectedItemIndex, selectedItemIndex - nbVisibleSuggestionValues );
						}else{
							switchListSelectedElement( selectedItemIndex, 0 );
						}
						inputSuggestionBoxContainerObj.scrollTop = wCurrentTop - pixelToSkipOnPageUpPageDown;
					}						
					break;
			}	
		}
	}
	
	/*
	*	Switch selected element in list
	*
	*/
	function switchListSelectedElement( pOldIndex, pNewIndex ){
		var wElements = inputSuggestionBoxListObj.getElementsByTagName('p');	
		if( pOldIndex > NO_SELECTED_ITEM ){
			wElements[pOldIndex].id = null;
			wElements[pOldIndex].className = CLASS_INPUT_SUGGESTION_BOX_VALUE;
		}
		setSelectedElement( wElements, pNewIndex );
	}	
	
	/*
	*	Set Selected Element in list
	*
	*/	
	function setSelectedElement( pElementList, pIndexToSelect ){
		pElementList[pIndexToSelect].id = 'SelectedSuggestion';
		pElementList[pIndexToSelect].className = CLASS_INPUT_SUGGESTION_BOX_SELECTED_VALUE;
		selectedItemIndex = pIndexToSelect;
		
		//Changed selected value (and remove bold tags)
		var wValue = pElementList[pIndexToSelect].innerHTML;
		wValue = wValue.replace(/<[\/]{0,1}(B|b)[^><]*>/g,'');
		
		var wIndexStartExtraInfo = wValue.indexOf( " " );
		
		if ( wIndexStartExtraInfo != -1 ) {
    		wValue = wValue.substring( 0, wIndexStartExtraInfo );
		}
		
		fieldToFillObj.value = wValue;
	}	
	
	/*
	*	Keep track of last action on list has been fired by which input
	*/
	function setLastActionByKeyboard( pBoolean ){
		lastActionByKeyboard = pBoolean;
	}


/*********************************************
*********************************************	
 	Initialize method
*********************************************	
*********************************************/	

	/*
	*	Initialize method.  ** MUST BE CALLED **
	*/
	function initializeSuggestionBoxControl( pControllerForData, pControllerParams, pTargetDataElementNameInControllerOutput, pInputSuggestionBoxContainerObj, pInputSuggestionBoxListObj, pFieldToFillObj, pNbVisibleSuggestionValues, pMaxItemsPerColumn, pDisplayDelay, pPixelToSkipOnUpDownArrow, pPixelToSkipOnPageUpPageDown ){
		if( inputSuggestionBoxContainerObj == null ){
			inputSuggestionBoxContainerObj = pInputSuggestionBoxContainerObj;
		}

		if( inputSuggestionBoxListObj == null ){
			inputSuggestionBoxListObj = pInputSuggestionBoxListObj;
		}
		
		if( fieldToFillObj == null ){
			fieldToFillObj = pFieldToFillObj;
		}

		if( xmlHttp == null ){		
		 	xmlHttp = getXmlHttpObject(); 
		}
		
		if( cacheResults == null ){
			cacheResults = new Array();
		}
		
		if( nbVisibleSuggestionValues == null ){
			if( pNbVisibleSuggestionValues != null ){
				nbVisibleSuggestionValues = pNbVisibleSuggestionValues;
			}else{
				nbVisibleSuggestionValues = NB_VISIBLE_SUGGESTION_VALUES_UNDEFINED;
			}
		}
		
		if( maxItemsPerColumn == null ){
			if( pMaxItemsPerColumn != null ){
				maxItemsPerColumn = pMaxItemsPerColumn;
			}else{
				maxItemsPerColumn = MAX_ITEM_PER_COLUMN_PARAM_INFINITE_VALUE;
			}
		}		
		
		if( controllerForData == null ){
			if( pControllerForData != null ){
				controllerForData = pControllerForData;
			} 
		}
		
		if( pControllerParams != null ){
			controllerParams = pControllerParams;
		}

		if( pTargetDataElementNameInControllerOutput != null ){
			targetDataElementNameInControllerOutput = pTargetDataElementNameInControllerOutput;
		}
		
		
		if( pDisplayDelay != null){
			displayDelay = pDisplayDelay;
		}

		if( pixelToSkipOnUpDownArrow == null ){
			pixelToSkipOnUpDownArrow = pPixelToSkipOnUpDownArrow;
		}
				
		if( pixelToSkipOnPageUpPageDown == null){
			pixelToSkipOnPageUpPageDown = pPixelToSkipOnPageUpPageDown;
		}
	}
		
/*********************************************
*********************************************	
 	Different utilities	
*********************************************	
*********************************************/	
	
	/*
	*	Get ajax main object
	*
	*/			
	function getXmlHttpObject(){
		var xmlHttp;
		
		try// Firefox, Opera 8.0+, Safari
		{        
		    xmlHttp=new XMLHttpRequest();
		}catch (e){    // Internet Explorer    
			try
			{      
			   	xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");    
			}catch (e){      
			    try
			    {        
			      	xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			    }catch (e){       
			      	alert("Your browser does not support AJAX!");        
			      	return false;        
			    }      
			}  
		}
		return xmlHttp;  
	}
	
	
	/*
	*	Simulate String buffer object
	*/

	function StringBuffer() { 
		this.buffer = []; 
	} 
		
	StringBuffer.prototype.append = function(string) { 
		this.buffer.push(string); 
		return this; 
	} 

	StringBuffer.prototype.toString = function(){ 
		return this.buffer.join(""); 
	}

	/*
	*	Add event method to work with multiple browser
	*/
	function addEvent( obj, type, fn ) { 
	  if ( obj.attachEvent ) { 
	    obj['e'+type+fn] = fn; 
	    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}; 
	    obj.attachEvent( 'on'+type, obj[type+fn] ); 
	  } else {
	    obj.addEventListener( type, fn, false );
	  } 
	} 

	/*
	*	return false if key code refers to ENTER key on keyboard
	*/
	function cancelSubmitOnEnterKeyPressAndCloseSuggestionList( pEvent ){
		if( pEvent.keyCode == ENTER_KEY_CODE ){
			switchSuggestionBoxDisplay(false);
		}
			
		return !(pEvent.keyCode == ENTER_KEY_CODE);
	} 

    function setComplaintCoReported( pIndex ) {
        var wCoNameId = 'co_name_' + pIndex;
        var wCoNoId = 'co_no_' + pIndex;
	    var wClientNameObj = document.getElementById( wCoNameId );
	    var wClientNoObj = document.getElementById( wCoNoId );
        document.getElementById( 'REPORTED_CO_NAME' ).value = document.getElementById( wCoNameId ).value;
        document.getElementById( 'REPORTED_CO_ID' ).value = document.getElementById( wCoNoId ).value;
    }
    
    function setSelectedCoToMemberSearch( pIndex, pOldCoNameElId, pCoNameElId, pCoNoElId ) {
        var wSelCoNameEl = 'co_name_' + pIndex;
        var wSelCoNoEl = 'co_no_' + pIndex;
        document.getElementById( pCoNameElId ).value = document.getElementById( wSelCoNameEl ).value;
        try {
        	document.getElementById( pCoNameElId ).onchange();
        } catch(err){}
        
        if ( document.getElementById( pOldCoNameElId ) != null ) {
        	document.getElementById( pOldCoNameElId ).value = document.getElementById( wSelCoNameEl ).value;
        }        
        
        document.getElementById( pCoNoElId ).value = document.getElementById( wSelCoNoEl ).value;
    }
    
    function displayRating(){
        if( document.getElementById('ratingExclusivity') != null ) {  
            document.getElementById('ratingExclusivity').style.display = 'block';
        }
    }
    
    function hideRating(){
        if( document.getElementById('ratingExclusivity') != null ) { 
            document.getElementById('ratingExclusivity').style.display = 'none';
        }
    }
    
    function initVendorRating( pIssuerTypeCodeId, pIsEditable ) {

		var wIsBuyerRole = false;
		if( pIsEditable == true ) {
		    if( document.getElementById(pIssuerTypeCodeId).checked ) {
		        wIsBuyerRole = true;
		    } 
		} else if( document.getElementById( pIssuerTypeCodeId ).value == 'BUYER' ){
		    wIsBuyerRole = true; 
		}

		if( wIsBuyerRole ) {
			displayRating('ratingExclusivity');
			if( pIsEditable == true ) {
    			setRating('ratingNumber_1','rating1', document.getElementById('ratingNumber_1').value ,5);
    			setRating('ratingNumber_2','rating2', document.getElementById('ratingNumber_2').value ,5);
    			setRating('ratingNumber_3','rating3', document.getElementById('ratingNumber_3').value ,5);
    			setRating('ratingNumber_4','rating4', document.getElementById('ratingNumber_4').value ,5);
    			setRating('ratingNumber_5','rating5', document.getElementById('ratingNumber_5').value ,5);
    			averageStar();
    		}
		} else {
			hideRating('ratingExclusivity');
		}
	}
    

/*
*	HOW-TO EXAMPLE:
*
*		1. Link java script methods and css files (styles could need to be redefine)
*			<link href="/cgi/en/css/InputSuggestionBoxControl.css" rel="stylesheet" type="text/css"/>
*			<xsl:comment><![CDATA[[if IE 7]><link href="/cgi/en/css/InputSuggestionBoxControl_ie7.css" type="text/css" rel="stylesheet" media="all"/><![endif]]]></xsl:comment>
*			<xsl:comment><![CDATA[[if lte IE 6]><link href="/cgi/en/css/InputSuggestionBoxControl_ie6.css" type="text/css" rel="stylesheet" media="all"/><![endif]]]></xsl:comment>
*			<script type="text/javascript" language="JavaScript" src="/cgi/en/Js/InputSuggestionBoxControl.js"/>
*
*		2. First create a text box and add/edit events to pass working parameters (see param descriptions in refreshSuggestionBox() method header)
*	
*				<input class="txt" type="text" id="LineItem.OriginalManufacturerCode" 
*					name="LineItem.OriginalManufacturerCode" size="23" autocomplete="off"
*					value="{LineItem/OriginalManufacturerCode}" tabindex="3"
*					onkeyup="refreshSuggestionBox( '/cgi/en/manufacturer.list',
*						'/SearchCriteria.StartsWith=' + this.value.substring(0, 1),	
*						'LongName',					
*						findObject('InputSuggestionBox'),
*						findObject('InputSuggestionBoxEntryList'),
*						findObject('LineItem.OriginalManufacturerCode'), 
*						9, null,
*						1000,						
*						22, 198,
*						event);" 
*					onblur="switchSuggestionBoxDisplay(false)"
*					onkeypress="return cancelSubmitOnEnterKeyPressAndCloseSuggestionList( event )"/>
*
*		3. Add these div where you want the popup to show
*				<!-- Popup list containing results  -->                    
*				<div id="InputSuggestionBox" class="InputSuggestionBoxInventory" 
*					onblur="javascript:switchSuggestionBoxDisplay(false);" 
*					onfocus="javascript:switchSuggestionBoxDisplay(true);"
*					onmousemove="setLastActionByKeyboard(false)">
*					<div id="InputSuggestionBoxEntryList"/>
*				</div>
*
*		4. To complete, create css stylesheets
*/
	
 
    /***********************************************************************************************
	
	Copyright (c) 2005 - Alf Magne Kalleland post@dhtmlgoodies.com
	
	UPDATE LOG:
	
	March, 10th, 2006 : Added support for a message while large image is loading
	
	Get this and other scripts at www.dhtmlgoodies.com

	You can use this script freely as long as this copyright message is kept intact.

	***********************************************************************************************/ 
   	
   	/******************ClientBioGraphyBody********************************************************/
   			function editNote() 
		{
			document.getElementById('editNote').style.display='none';
			document.getElementById('linkSave').style.display='inline';
			document.getElementById('contactNote').readOnly=false;
			document.getElementById('contactNote').className = 'txtArea';
			
		}
		
		function cancelEditNote() {
			document.getElementById('editNote').style.display ='inline';
			document.getElementById('linkSave').style.display='none';
			document.getElementById('contactNote').readOnly=true;
		}

       	function setFormAction() {
       		
       		var pParam = "";
       		if(document.formContactNote.formAction != null) {
       			pParam = document.formContactNote.formAction.value;
       		}
       	
       		var controller = "";
       		if(pParam = 'add') {
       			controller = "/cgi/en/client.bio.create.note";
       		} else if( pParam = 'edit' ) {
       			controller = "/cgi/en/client.bio.attach.note";
       		}
       		document.formContactNote.action = controller;
       	}
       	function callFuncAddNote() 
       	  {
       		 document.getElementById('formAction').value='add'; 
       		 setFormAction(); 
       		 document.getElementById('formContactNote').submit();
       		 window.location.reload();
       	  }
       	  
       	 function callSaveNote()
       	 {
       	 	document.getElementById('formAction').value='edit'; 
       	 	setFormAction(); 
       	 	
       	 	if (document.getElementById('linkSave').style.display =='none')
       	 		{ document.getElementById('contactNote').className = 'txtArea editMode'; }
       	 	if (document.getElementById('editNote').style.display =='none')
       	 		{ document.getElementById('contactNote').className = 'txtArea'; }
       	 	        document.getElementById('formContactNote').submit();
       	 	        window.location.reload();
       	 	        
       	}
       	function toggleNote(pImg,pNote) {
			var wImg = document.getElementById(pImg);
			var wNote = document.getElementById(pNote);
			
			if ( wNote.style.display=='none' ) {
				wImg.src='/cgi/en/img/rate-hide-note.png'
				wNote.style.display='';
			} else {
				wImg.src='/cgi/en/img/rate-add-note.png'
				wNote.style.display='none';
			}
		}
       	function callAjaxWithController ( pController, pDivId ) {
			if( pController != null ){
				var wContentLoader = new ContentLoader( pController, pDivId, "" );
				wContentLoader.start();
			}
		}
       	
		function postAjaxWithController ( pController, pDivId, pFormId ) {
			var formObject = document.getElementById(pFormId);

			var callback = 
				{ 
				success: function(o) { document.getElementById(pDivId).innerHTML = o.responseText; }, 
				failure: function(o) { document.getElementById(pDivId).innerHTML = o.responseText; }
				}; 
				
			YAHOO.util.Connect.setForm(formObject); 
			var cObj = YAHOO.util.Connect.asyncRequest('POST', pController, callback); 
		}
		
		function openPrintVersion(pDiv)
      {
		var content = document.getElementById(pDiv);
		OpenWindow=window.open("", "newwin", "height=700, width=601,top=0,left=0,screenX=0,screenY=0,toolbar=no,scrollbars=yes,menubar=no");
		OpenWindow.document.write("<title>The Broker Forum Feedback Terms &amp; Conditions</title>");
		OpenWindow.document.write("<style type='text/css'>");
		OpenWindow.document.write("h1{font: bold 18px arial; border-bottom:1px solid #cccccc; padding: 0 0 10px 20px; margin: 30px 0 0 34px;} body{font:11px arial; margin:0px;} .bckTop { background-color:#efefef; height:22px; }.print { background: url('/cgi/en/img/printIcon.gif') no-repeat top left ; display:block; float:left; width:100px; padding: 0 0 3px 24px; margin:0 0 0 17px; } .close { display:block; background: url('/cgi/en/img/btnXRouge.gif') no-repeat top left ; width:14px; height:14px; float:right; margin:3px 7px 0 0; }  ");
		OpenWindow.document.write("#termandCond{padding: 0 0 0 32px;}")
		OpenWindow.document.write("</style>"); 
		OpenWindow.document.write("<body onload='window.print()'>");
		OpenWindow.document.write("<div class='bckTop'><a href='javascript:window.print()' class='print'>Print</a><a href='javascript:window.close();' class='close'></a></div><h1>The Broker Forum Feedback Terms & Conditions</h1>");
		OpenWindow.document.write(content.innerHTML);
		OpenWindow.document.write("</body>");
		OpenWindow.document.write("</html>");
		OpenWindow.document.close();
	}
		 
	function switchBtn()
   	{
	   	if(document.getElementById('btnAction').style.display == 'none')
   		{
   			document.getElementById('btn').style.display = 'none';
   			document.getElementById('btnAction').style.display = 'inline';
   		
   		}
	   	else {
   			document.getElementById('btn').style.display = 'inline';
   			document.getElementById('btnAction').style.display = 'none';
   		} 
   	}
	
	function displayNote( pController, pDivId, pAction, pFormId ) {
		if(pFormId != null) {
			var formObject = document.getElementById(pFormId);
			YAHOO.util.Connect.setForm(formObject);
		}
   		
   		var callback = 
		{ 
		success: function(o) { 
			document.getElementById(pDivId).innerHTML = o.responseText;
			setMaxLength();
			}, 
		failure: function(o) { document.getElementById(pDivId).innerHTML = o.responseText; }
		}; 
		var cObj = YAHOO.util.Connect.asyncRequest(pAction, pController, callback); 
	}
	
	/**Slideshow for TBF Verified Pictures in Company Profile **/
/***********************************************************************************************
	
	Copyright (c) 2005 - Alf Magne Kalleland post@dhtmlgoodies.com
	
	UPDATE LOG:
	
	March, 10th, 2006 : Added support for a message while large image is loading
	
	Get this and other scripts at www.dhtmlgoodies.com
	
	You can use this script freely as long as this copyright message is kept intact.
	
	***********************************************************************************************/ 
   	
	var displayWaitMessage=false;	// Display a please wait message while images are loading?
  	
   		
	var activeImage = false;
	var imageGalleryLeftPos = false;
	var imageGalleryWidth = false;
	var imageGalleryObj = false;
	var maxGalleryXPos = false;
	var slideSpeed = 0;
	var imageGalleryCaptions = new Array();
	
	function startSlide(e) {
		if(document.all)e = event;
		var id = this.id;
		if(this.id=='arrow_right'){
			slideSpeedMultiply = Math.floor((e.clientX - this.offsetLeft) / 5);
			slideSpeed = -1*slideSpeedMultiply;
			slideSpeed = Math.max(-10,slideSpeed);
		}else{			
			slideSpeedMultiply = 10 - Math.floor((e.clientX - this.offsetLeft) / 5);
			slideSpeed = 1*slideSpeedMultiply;
			slideSpeed = Math.min(10,slideSpeed);
			if(slideSpeed<0)slideSpeed=10;
		}
	}
	
	function releaseSlide()	{
		var id = this.id;
		slideSpeed=0;
	}
		
	function gallerySlide()	{
	
		if(slideSpeed!=0){
			var leftPos = imageGalleryObj.offsetLeft;
			leftPos = leftPos/1 + slideSpeed;
			if(leftPos>maxGalleryXPos){
				leftPos = maxGalleryXPos;
				slideSpeed = 0;
				
			}
			if(leftPos<minGalleryXPos){
				leftPos = minGalleryXPos;
				slideSpeed=0;
			}
			
			imageGalleryObj.style.left = leftPos + 'px';
		}
		setTimeout('gallerySlide()',20);
	}
	
	function showImage() {
	
		if(activeImage){
			activeImage.style.border = '1px solid #ccc';
		}	

		this.style.border = '1px solid #698fbe';	
		activeImage = this;	
	}
	
	function initSlideShow()	{
		document.getElementById('arrow_left').onmousemove = startSlide;
		document.getElementById('arrow_left').onmouseout = releaseSlide;
		document.getElementById('arrow_right').onmousemove = startSlide;
		document.getElementById('arrow_right').onmouseout = releaseSlide;
		
		imageGalleryObj = document.getElementById('theImages');
		imageGalleryLeftPos = imageGalleryObj.offsetLeft;
		imageGalleryWidth = document.getElementById('galleryContainer').offsetWidth - 15;
		maxGalleryXPos = imageGalleryObj.offsetLeft; 
		minGalleryXPos = imageGalleryWidth - document.getElementById('slideEnd').offsetLeft;
		var slideshowImages = imageGalleryObj.getElementsByTagName('img');
		for(var no=0;no<slideshowImages.length;no++){
			slideshowImages[no].onmouseover = showImage;
			slideshowImages[no].onmouseout = removeOpacity;
		}
		
		gallerySlide();
	}
	
	function showPreview(imagePath,imageIndex) {

		document.getElementById('imageId').innerHTML = imageIndex;
		
		var subImages = document.getElementById('previewPane').getElementsByTagName('img');
		if(subImages.length==0){
			var img = document.createElement('img');
			document.getElementById('previewPane').appendChild(img);
		}else{
		     img = subImages[0];
    		img.src = imagePath;
    	}
	}
	
	function removeOpacity()	{
	
		this.style.filter = 'alpha(opacity=100)';
		this.style.opacity = 1;	
		activeImage = this;	
	}

	function trim(str) {
	    if( !str || typeof str != 'string' ) {
	        return '';
	    }
	    return str.replace(/^\s+|\s+$/g,"");
    }
 
    function ltrim(str) {
	    if( !str || typeof str != 'string' ) {
	        return '';
	    }
	    return str.replace(new RegExp("/^[" + chars + "]+", "/g"), "");
    }
 
    function rtrim(str, chars) {
	    if( !str || typeof str != 'string' ) {
	        return '';
	    }
	    return str.replace(new RegExp("[" + chars + "]+$", "/g"), "");
    }


    function displayTextAreaCharCount(textareaId, counterId, limit) {
    	
    	if ($("#" + textareaId).length > 0) {
    		
    		var textareaValue = $("#" + textareaId).val();
    		
    		$("#" + counterId).text(textareaValue.length);
    		if (textareaValue.length > limit) {
    			$("#" + counterId).css({ color: "#F46", fontWeight: "bold" });
    		} else {
    			$("#" + counterId).css({ color: "", fontWeight: "" });
    		}
    		
    	}
    		
    }
    