// global var used within functions
var l_loadingmessage = "Loading ...";
var l_redirect_message = "Please login as a valid session cannot be located.";
// mputils.js 
//  AND  (blnJSloaded == 1)
function handle_searchfor_change() {
  // get currently seclted searchbyid;
  var l_searchbyid = getById('searchbyid').value;
  fillCategories(0);
  fillSearchBy(l_searchbyid);
  check_getBrickList();
  check_searchby();  // would have enabled controls if searchby was not MPcode / brick
  void reset_geocontrols_searchby_change();
}
// general search and utility related methods
function fillListFromArray(l_rectypecode,l_divname, l_ctl, l_arrVals, l_selectedid, l_itemone) {
   // fill relative to params
   var divname      = getById(l_divname);
   var icount       = l_arrVals.length;      
   var vtemp        = remove_AllItems(l_ctl);
   // add first item ALL :  new Option(text, value, defaultSelected, selected)
   if (l_itemone ==1) {
     l_ctl.options[0] = new Option("All", 0, 0, true);
   }
   for (var icounter =0; icounter < icount; icounter++) {
	 if (l_arrVals[icounter].rectypecode == l_rectypecode) {	   
		var stemp = l_arrVals[icounter].description;
		if ( (stemp.substr(0,1)) !== "<") {
		   // add the item
		      //alert('l_ctl: ' + l_ctl.name + ' l_arrVals[icounter].id: ' + l_arrVals[icounter].id + ' l_selectedid: ' + l_selectedid);
		   var nextitem = l_ctl.options.length;
		   if (l_arrVals[icounter].id == l_selectedid) {
		         //alert('l_ctl: ' + l_ctl.name + ' l_arrVals[icounter].id: ' + l_arrVals[icounter].id + ' l_selectedid: ' + l_selectedid);
   		      l_ctl.options[nextitem] = new Option(stemp, l_arrVals[icounter].id,false,true);
		   } else {
  		       l_ctl.options[nextitem] = new Option(stemp, l_arrVals[icounter].id,false ,false);
		   }
        }
	 }
   }
}
function fillSearchBy(l_selectedid) {
    var l_rectypecode = getById('searchforid').value; 
	var l_ctltofill = getById('searchbyid'); 
	var l_currentselcteditemid = 0; 
	if (!l_selectedid) l_selectedid = l_currentselcteditemid;
    if (l_rectypecode == 1) {
   	  void fillListFromArray(1,'searchby',l_ctltofill , arrOSearchBy, l_selectedid);
    } else {
	  void fillListFromArray(2,'searchby', l_ctltofill, arrPSearchBy, l_selectedid);
	}  
}
function fillCategories(l_selectedid) {
   var l_rectypecode = getById('searchforid').value; 
   var l_ctltofill   = getById('categorycode');
   void fillListFromArray(l_rectypecode, 'divcategories', l_ctltofill, arrCategories, l_selectedid, 1)
   // refill services
   void getServicesList(0);
   void check_searchby();
}
function getServicesList(l_preselectcode) {
	 // called from handle_onload(), onChange() of Category list
	 l_blnSearchListLoadInProgress = 1; // reset on  AJAX complete NO disable of seach list by checkSearchBy()
     var l_recordtypecode = getById('searchforid').value;
	 var l_categorycode = getById('categorycode').value;
	 var l_url ="index.php?module=searchcategoryservices&categorycode=" + l_categorycode + "&servicecode=" + l_preselectcode;
	 // if categorycode == 0 / ALL
	 if (l_categorycode == 0) {
	    void getRecordTypeServicesList(l_recordtypecode, l_preselectcode); 
	 } else {
	    if (blnJSloaded)  getServicesXML(l_url, ''); 
	 }   
 }
 // retrieve full list for person/org
 function getRecordTypeServicesList(l_recordtypecode, l_preselectcode) {
	 // called from handle_onload(), onChange() of Search For list
	 var l_categorycode = 0;
	 if (getById('categorycode') != null) {
	   var l_categorycode = getById('categorycode').value;
	 }
	 var l_url ="index.php?module=searchrecordcategoryservices&recordtypecode=" + l_recordtypecode + "&servicecode=" + l_preselectcode;
	 if ((l_allserviceslist == '') || (js_allpeopleserviceslist =='')|| (js_allserviceslist=='')) { 
          if (getById('divservices') != null) getRecordTypeServicesXML(l_url, ''); 
     } else {
	    // if categorycode == 0 / ALL
		if (l_categorycode == 0) {
	       // reassign to var based on: searchfor orgs OR people
		   l_allserviceslist = (getById('searchforid').value == 2 )? js_allpeopleserviceslist:js_allserviceslist;
  		   getById('divservices').innerHTML = l_allserviceslist;  
	    } else {
           if (getById('divservices') != null) getRecordTypeServicesXML(l_url, ''); 
		}
	 }
 }
function check_searchby() {
   // reset / hide input box based on seachbyid
   // assign a user prompt fora COUNCILE NO search
   // check for l_blnSearchListLoadInProgress: do not enable LIST controls while this is in progress
    void setServicesLabel();
   // get current value
   var l_searchvaluecontent = ''; 
   if (getById('searchvalue') != null) {l_searchvaluecontent = getById('searchvalue').value;}
   if (getById('searchbyid').value == SEARCHBY_BRICK) {
	   // enable list controls
	   void disable_list_ctl(document.frmSearch,'select-one',0);
       // disable geo controls
       disable_geoControls(1); 
	   void check_getBrickList();
   } else if (getById('searchbyid').value ==SEARCHBY_MEDPAGES_CODE)  {
  	    // disable all except for and by disable_for_MPCodeSearch(1);
         void disable_list_ctl(document.frmSearch,'select-one',1);
		 void resetCriteriaInput(l_searchvaluecontent, '#000000'); 
   } else {
	   // enable list ctls, reset  text for council no search
 	    disable_geoControls(0); 
 	    void disable_list_ctl(document.frmSearch,'select-one',0);
        void resetCriteriaInput(l_searchvaluecontent, '#000000'); 	  
   }
   // reassess need to disable certain geo lists 
   void reset_geocontrols_searchby_change() 
}
function resetCriteriaInput(l_text, l_style) {
    if (getById("searchvalue") == null) {
       var l_content = '<input type="text" id="searchvalue" name="searchvalue" style="color:"' + l_style + ' size="' + SEARCH_INPUT_SIZE + '" value="' + l_text + '" maxlength="50" class="inputSearchValue">';
       getById('divcriteria').innerHTML = l_content;
	 } else {
	   var l_element = getById("searchvalue");
	   l_element.style.color =  l_style;  
	   l_element.value =  l_text;  
     }
 } 
function disable_geoControls(l_blnEnable) {
    // is searchtypeid MP still selected
    if (getById('selsearchtypeid') != null ) {
	   getById('selsearchtypeid').disabled = l_blnEnable;
	   if (getById('selsearchtypeid').value < 0 ) {
	      // disable MP area ctls 
          if (getById('countryid') !==null)  getById('countryid').disabled =  l_blnEnable;
          if (getById('regioncode') !==null) document.getElementById('regioncode').disabled =  l_blnEnable;
          if (document.getElementById('subregioncode') !==null) document.getElementById('subregioncode').disabled =  l_blnEnable;
	   } else {
          if (document.getElementById('sraregionid') !==null) document.getElementById('sraregionid').disabled =  l_blnEnable;
	      if (document.getElementById('sraterritoryid') !==null) document.getElementById('sraterritoryid').disabled =  l_blnEnable;
          if (document.getElementById('srareportingareaid') !==null) document.getElementById('srareportingareaid').disabled =  l_blnEnable;
	   }
    }
 }
 function disable_for_MPCodeSearch(l_blnEnable) {
	if (getById('ratinglistid') !==null) getById('ratinglistid').disabled =  l_blnEnable;
	if (getById('ratingitemid') !==null) getById('ratingitemid').disabled =  l_blnEnable;
	if (getById('categorycode') !==null) getById('categorycode').disabled =  l_blnEnable;
    if (getById('servicecode') !==null) getById('servicecode').disabled =  l_blnEnable;
    if (getById('selsearchtypeid') != null ) getById('selsearchtypeid').disabled = l_blnEnable;
    // disable MP are ctls 
    if (getById('countryid') !==null) getById('countryid').disabled =  l_blnEnable;
    if (getById('regioncode') !==null) getById('regioncode').disabled =  l_blnEnable;
    if (getById('subregioncode') !==null) getById('subregioncode').disabled =  l_blnEnable;
    if (getById('sraregionid') !==null) getById('sraregionid').disabled =  l_blnEnable;
	if (getById('sraterritoryid') !==null) getById('sraterritoryid').disabled =  l_blnEnable;
    if (getById('srareportingareaid') !==null) getById('srareportingareaid').disabled =  l_blnEnable;
 }
 function disable_list_ctl(f,ctlType,blnenable) {
  // loop thru from controls
   for (i=0;i < f.length;i++) {
       stemp = f.elements[i].name;
     if ((f.elements[i].type == ctlType)) { 
	    if (f.elements[i].name != 'searchbyid') {
		  if (f.elements[i].name != 'searchforid') {
		    // AJAX on complete will reset this
			if (l_blnSearchListLoadComplete ==1) f.elements[i].disabled = blnenable
	      }
		}  
	 } 
   }  
}   
function setServicesLabel() {
   var l_rectypecode = getById('searchforid').value; 
  // if (getById('lblservicecode') !==null) {
  getById('lblservicecode').innerHTML = (l_rectypecode == 2)? "Speciality:":"Service:";
  // } 
}
function check_getBrickList() {
  // was search by brick selected? then call get brick list
 var l_searchvaluecontent = ''; 
 if (getById('searchvalue') != null) { 
       l_searchvaluecontent = getById('searchvalue').value;
 }
 if (getById('searchbyid').value == SEARCHBY_BRICK) {
      // disable geo controls
         disable_geoControls(1); 
      if (l_bricklist == '') {
	    void getBrickList();
	  } else {
	   getById('divcriteria').innerHTML = l_bricklist;        
	  }	
  } else { 	  
     // enable list ctls, reset  text for council no search
     disable_geoControls(0); 
	 // reset input box
	  void resetCriteriaInput(l_searchvaluecontent, '#000000'); 
  }
 }
// ********************************************************** 
// methods that do final AJAX calls in searchRPC.js
// ensure that boolean flag is true (blnJSloaded == 1)
//
// *********************************************************
function getBrickList() {
     var l_url ="index.php?module=bricklist";
	 getById('divcriteria').innerHTML = "Loading ..."; 
	 if (blnJSloaded) getBrickListXML(l_url, ''); 
 }
function getRatingItemsList(l_preselectcode) {
	 // called from handle_onload(), onChange() of Rating list
	 var f = document.frmSearch;
	 if ( getById('ratinglistid') != null) {
	    var l_ratinglistid = getById('ratinglistid').value;
	    var l_url ="index.php?module=ratinglistitems&ratinglistid=" + l_ratinglistid + "&ratingitemid=" + l_preselectcode;
	    if (blnJSloaded) getRatingItemsXML(l_url, ''); 
	}
 }
 function getSubRegionList() {
  // ajax call to build region list
  var l_regioncode = getById('regioncode').value;
  resetSubRegionListToAll();  
  if (l_regioncode > 0) {
     var l_url ="index.php?module=searchsubregions&regioncode=" + l_regioncode;
     if (blnJSloaded) getSubRegionListXML(l_url, ''); 
  }	
}
function resetSubRegionListToAll() {
   var l_subregionlist  = '<select id="subregioncode" name="subregioncode" class="wideSearchSelect" style="width:' + WIDE_SEARCH_LIST_WIDTH + 'px;"><option value="0">All</option></select>';
   if (getById('divsubregioncode') !==null) getById('divsubregioncode').innerHTML = l_subregionlist;  
   if (getById('subregioncode') !==null) getById('subregioncode').disabled =true;
    // var l_regioncode = getById('regioncode').value;
    // if (getById('subregioncode') !==null) getById('subregioncode').disabled = (l_regioncode > 0)? false:true; 
}
function getRegionList(l_countryid) {
  //var l_countryid = selected_listvalue (document.frmSearch.countryid);
  var l_url ="index.php?module=searchregions&countryid=" + l_countryid;
  void resetRegionListToAll();
  void resetSubRegionListToAll(); 
  if (l_countryid > 0) {
      // if (blnJSloaded) 
	  if (getById('regioncode') != null) getRegionListXML(l_url, ''); 
  }
}
function resetRegionListToAll() {
   var l_regionlist  = '<select id="regioncode" name="regioncode" class="wideSearchSelect" style="width:' + WIDE_SEARCH_LIST_WIDTH + 'px;"><option value="0">All</option></select>';
   if (getById('divregioncode') !==null) getById('divregioncode').innerHTML = l_regionlist; 
   if (getById('regioncode') !==null) getById('regioncode').disabled = true; 
}
function check_getCountryList(l_preselectcode) {
    // was searchtypeid MEDpages selected
	if (getById('selsearchtypeid') != null ) {
        if (getById('selsearchtypeid').value < 0) {
		  // reset subregion
		  if (l_countrylist == '') {
		    void getCountryList(l_preselectcode);
		  } else {
		    var divname = getById('divcountryid');
		    divname.innerHTML = l_countrylist;        
		  }	
	   } 
	}	
 }
 function getCountryList(l_preselectcode) {
	 var l_url ="index.php?module=searchcountries&countryid=" + l_preselectcode;
	 void resetRegionListToAll();
     void resetSubRegionListToAll(); 
	 if (blnJSloaded) getCountryListXML(l_url, ''); 
 }
function resetCountryListToAll() {
    var l_temp_countrylist  = '<select id="countryid" name="countryid" class="wideSearchSelect" style="width:' + WIDE_SEARCH_LIST_WIDTH + 'px;"><option value="0">All</option></select>';
    var divname = getById('divcountryid');
	divname.innerHTML = l_temp_countrylist;  
}
function getSRARegionList(l_sradivisionid) {
  // ajax call to build region list
  var l_url ="index.php?module=searchsraregions&sradivisionid=" + l_sradivisionid;
  void resetSRARegionListToAll();
  // building in XML/XSL: refresh from onLoad
  void resetTerritoryListToAll(); 
  void resetReportingAreaListToAll();
  // Jul 2007 - change; 
  if (getById('sraregionid') != null) getSRARegionListXML(l_url, ''); 
}
function resetSRARegionListToAll() {
    var l_sraregionlist  = '<select id="sraregionid" name="sraregionid" class="wideSearchSelect" style="width:' + WIDE_SEARCH_LIST_WIDTH + 'px;"><option value="0">All</option></select>';
    var divname = getById('divcountryid');
	divname.innerHTML = l_sraregionlist;  
 }
function getSRATerritoryList() {
  // ajax call to build territory list
  var l_sraregionid =0;
  if (getById('sraregionid') != null) {
     l_sraregionid = getById('sraregionid').value;
  }
  void resetTerritoryListToAll();  
  void resetReportingAreaListToAll();
    //alert('In getSRATerritoryList () l_sraregionid: ' + l_sraregionid + ' blnJSloaded: ' + blnJSloaded);
  if (l_sraregionid > 0) {
     var l_url ="index.php?module=searchsraterritories&sraregionid=" + l_sraregionid;
     if (blnJSloaded) getSRATerritoryListXML(l_url, ''); 
  }	 
}
function resetTerritoryListToAll() {
    var l_territorylist  = '<select id="sraterritoryid"  name="sraterritoryid" class="wideSearchSelect" style="width:' + WIDE_SEARCH_LIST_WIDTH + 'px;"><option value="0">All</option></select>';
    getById('divregioncode').innerHTML = l_territorylist;  
    if (getById('sraterritoryid') !==null) getById('sraterritoryid').disabled = true; 
}
function getSRAReportingAreaList() {
  // ajax call to build territory list
  var l_sraterritoryid = getById('sraterritoryid').value;
  if (l_sraterritoryid > 0) {
     var l_url ="index.php?module=searchsrareportingarea&sraterritoryid=" + l_sraterritoryid;
     if (blnJSloaded) getSRAReportingAreaListXML(l_url, ''); 
  } else {
    void resetReportingAreaListToAll();  
  }	 
}
function resetReportingAreaListToAll() {
    var l_reportingarealist  = '<select id="srareportingareaid" name="srareportingareaid" class="wideSearchSelect" style="width:' + WIDE_SEARCH_LIST_WIDTH + 'px;"><option value="0">All</option></select>';
    var divname = getById('divsubregioncode');
	divname.innerHTML = l_reportingarealist;  
    if (getById('srareportingareaid') !==null) getById('srareportingareaid').disabled = true; 
}
function reset_geocontrols_searchby_change() {
 // if country is ALL, regions , subregions are reset to ALL
 // if regions is all subregions is reset
 // sra: If regions is ALL territrry and rpt area are reset
 //      if territory is ALL rpt area is reset
   if (getById('selsearchtypeid') != null ) {
       if (getById('selsearchtypeid').value < 0 ) {
	      // MP area ctls 
          if (getById('countryid') !==null )  {
		     if (getById('countryid').value== 0 ) {
                // disable regioncode list
			   if (getById('regioncode') !==null) getById('regioncode').disabled=true;
			 }
		  }	 
          if (getById('regioncode') !==null) {
		     if (getById('regioncode').value == 0 ) { 
                // disable subregioncode list
			   if (getById('subregioncode') !==null) getById('subregioncode').disabled=true; 
			 } else {
			   if (getById('subregioncode') !==null) getById('subregioncode').disabled=false; 
			 }
		  }
	    // SRA 
	   } else {
          if (getById('sraregionid') !==null)  {
		     if (getById('sraregionid').value == 0 ) {
			     if (getById('sraterritoryid') !==null) getById('sraterritoryid').disabled=true;
			 }
		  }
		  if (getById('sraterritoryid') !==null) {
		     if (getById('sraterritoryid').value == 0 ) { 
			     if (getById('srareportingareaid') !==null) getById('srareportingareaid').disabled=true;
             }
          }
	   }
    }
 }	
 function checkSearchSubmit(f) {
  // cannot search for all items in list boxes and not supply criteria
  var a=0;var b=0; var c=0;var d=0;var e=0;var l_blncontinue=1;
  // msut check a record status box
  var l_msg = ''
  var l_minAllowed=2;
  l_msg = check_checkboxes(f);
  if (l_msg !='') {
     alert(l_msg);
     l_blncontinue=0;
  } 
  if (l_blncontinue==1) {  
	  // was searchtypeid MEDpages selected  
	  if (getById('selsearchtypeid') != null ) {
	       if (getById('selsearchtypeid').value < 0 ) {
	        // MP area ctls 
	          if (getById('regioncode') !==null) a=getById('regioncode').value;
	          if (getById('subregioncode') !==null ) b=getById('subregioncode').value;
		    // SRA 
		   } else {
	          if (getById('sraregionid') !==null) a=getById('sraregionid').value;
			  if (getById('sraterritoryid') !==null) b=getById('sraterritoryid').value; 
	       }
	   }  
	   // check category, service, ratinigtemid  
	   if (getById('categorycode') !==null) c=getById('categorycode').value;
	   if (getById('servicecode') !==null) d=getById('servicecode').value; 
	   if (getById('ratingitemid') !==null) e=getById('ratingitemid').value; 
	   
	  if ((a==0) && (b==0) && (c==0) && (d==0) && (e==0)) {
	    if (getById('searchvalue') != null ) {
		   l_minAllowed =get_min_criteria_count(getById('searchbyid').value);
		  if ( (trim(f.searchvalue.value).length < l_minAllowed ) || (trim(f.searchvalue.value)=="") ) {
			   l_blncontinue=0;
		       alert (get_min_criteria_msg(getById('searchbyid').value));
		       f.searchvalue.focus();
	        }
		}
	  }
  }
  // do submit
  if (l_blncontinue==1) f.submit();
 } 
 function check_checkboxes (f) {
  // return possible feedback message
   var l_checkboxmsg = '';
   if ( !(f.recordstatuscode_1.checked) && !(f.recordstatuscode_2.checked) && !(f.recordstatuscode_3.checked)  ) {
	  l_checkboxmsg = "You need to tick at least one of Verified, Updating or Closed. Otherwise your search will return no results.\n\n";
	  l_checkboxmsg += "Verified shows records that are verified by MEDpages as accurate and up to date.\n\n";
	  l_checkboxmsg += "Updating shows records that MEDpages is in the process of verifying and updating.\n\n";
	  l_checkboxmsg += "Closed shows records that once existed but MEDpages has confirmed that they now no longer exist (e.g. practitioner no longer practising, or clinic has closed down).\n\n";
   }
   return (l_checkboxmsg);
 }
 function get_min_criteria_count(l_searchbyid) {
  var l_result='';
  if ((l_searchbyid == SEARCHBY_NAME) || (l_searchbyid == SEARCHBY_PRACTICE_NUMBER) ||
      (l_searchbyid == SEARCHBY_SUBURB) || ( l_searchbyid== SEARCHBY_TELEPHONE) ) {
     l_result = 3;
  } else if ((l_searchbyid == SEARCHBY_COUNCIL_NUMBER) || (l_searchbyid == SEARCHBY_EMAIL)) {
     l_result = 2;
  } else {
     // SEARCHBY_MEDPAGES_CODE, SEARCHBY_DISTRIBUTOR_NUMBER
     l_result = 1; 
  }
  return (l_result);
 }
 function get_min_criteria_msg(l_searchbyid) {
   var l_result =''; var l_min =''; var l_txt='';var l_chars;
   // count of min chars required
   l_min = get_min_criteria_count(l_searchbyid);
   // description of searchby
   l_txt = (selected_listtext('searchbyid'));
   l_chars = (l_min > 1)? "characters":"character";
   l_result = "When searching by everything please enter at least " + l_min + " " + l_chars + " for searching by " + l_txt + ".";
   return (l_result);
}
// ---------------  XML RPC   --------------------------------
function reset_list_for_loading(l_value, l_newtext, l_listname) {
    // clear contents and add new item
    var l_listid = getById(l_listname);
	if (l_listid !=null) {
	   // reset contents
       l_listid.options.length = 0;
       // add item : new Option(text, value, defaultSelected, selected)
	   l_listid.options[0] = new Option(l_newtext, l_value, l_value, true);
	}
}
function getRatingItemsXML(l_action, pagetitle) {
    toggleProgress('ratingprogress',true);
    reset_list_for_loading(0, l_loadingmessage, 'ratingitemid');
	if (getById('ratingitemid') !==null) getById('ratingitemid').disabled = true;
    var ajaxRating = new ajaxrpc();
    ajaxRating.get(l_action, "", 'assignRemoteData_Rating',0, 'assignErrorData_Rating');
}
function assignRemoteData_Rating(l_data) {
	void check_for_expired_result(l_data);
	// strip other values and retain select start to end tags only
	var l_positionSelect    = l_data.indexOf('<select',0);
    var l_positionEndSelect = l_data.indexOf('</select>',l_positionSelect);
    var selStringOnly       = l_data.substring (l_positionSelect, l_positionEndSelect+9)
    if (validate_selectList(selStringOnly)==0) {
	    reset_list_for_loading(0, "All", 'ratingitemid');
	    assignErrorData_Rating();
		return;
	}	
 	// assign received data, toggle progress indicator
	getById('divratingitems').innerHTML = selStringOnly;
    toggleProgress('ratingprogress',false);
    if (getById('ratingitemid') !==null)  getById('ratingitemid').disabled = false;
}
function assignErrorData_Rating(l_error) {
    //getById('ratingerror').innerHTML = l_error;
    toggleProgress('ratingprogress',false);
	if (getById('ratingitemid') !==null)  getById('ratingitemid').disabled = false;
	notify_ajax_retrieval_failed("Rating List", "search:assignErrorData_Rating()");
}
function getBrickListXML(l_action, pagetitle) {
    toggleProgress('divcriteriaprogress',true);
    var ajax = new ajaxrpc();
    ajax.get(l_action, "", 'assignRemoteData_Brick',0, 'assignErrorData_Brick');
}
function assignRemoteData_Brick(l_data) {
   void check_for_expired_result(l_data);
   var l_positionSelect    = l_data.indexOf('<select',0);
   var l_positionEndSelect = l_data.indexOf('</select>',l_positionSelect);
   var l_listonly          = l_data.substring (l_positionSelect, l_positionEndSelect+9)
   if (validate_selectList(l_listonly)==0) {
	    reset_list_for_loading(0, "All", 'brickid');
	    assignErrorData_Brick("Brick list retrieval failed, please retry.");
		return;
   }
   // assign to global var
   l_bricklist = l_listonly;
   // is search by brick still selected
   if (getById('searchbyid').value ==  SEARCHBY_BRICK) {
	  getById('divcriteria').innerHTML = l_listonly;        
   }   
   toggleProgress('divcriteriaprogress',false);
   void check_searchby();
}
function assignErrorData_Brick(l_error) {
	//getById('divcriteriaerror').innerHTML = l_error;
    toggleProgress('divcriteriaprogress',false);
	if (getById('brickid') !==null)  getById('brickid').disabled = false;
	if (getById('divcriteria') !==null)getById('divcriteria').innerHTML = "Failed to load Brick List."; 
	notify_ajax_retrieval_failed("Brick List", "search:assignErrorData_Brick()");
    // change searchby index
	getById('searchbyid').options.selectedIndex=0;
	void check_searchby();
}
function getServicesXML(l_action, pagetitle) {
    toggleProgress('divservicesprogress',true);
	// reset contents
	reset_list_for_loading(0, l_loadingmessage, 'servicecode');
	if (getById('servicecode') !==null)  getById('servicecode').disabled = true;
    var ajax = new ajaxrpc();
    ajax.get(l_action, "", 'assignRemoteData_Services',0, 'assignErrorData_Services');
}
// full people / org list
function getRecordTypeServicesXML(l_action, pagetitle) {
	toggleProgress('divservicesprogress',true);
	// reset contents
	l_blnSearchListLoadComplete='';
	reset_list_for_loading(0, l_loadingmessage, 'servicecode');
	if (getById('servicecode') !==null)  getById('servicecode').disabled = true;
    var ajax = new ajaxrpc();
    ajax.get(l_action, "", 'assignRemoteData_Services',0, 'assignErrorData_Services');
}
function assignRemoteData_Services(l_data) {
    // handle assign to global var: must be relative to category ?
    void check_for_expired_result(l_data);
    var l_valreceived = l_data;
  	// strip other values and retain select start to end tags only
	var l_positionSelect    = l_valreceived.indexOf('<select',0);
    var l_positionEndSelect = l_valreceived.indexOf('</select>',l_positionSelect);
    var selStringOnly       = l_valreceived.substring (l_positionSelect, l_positionEndSelect+9)
    // validate
	if (validate_selectList(selStringOnly)==0) {
	    reset_list_for_loading(0, "All", 'servicecode');
	    assignErrorData_Services();
		return;
	}	
	// assign to global var if categorycode == all
	var l_categorycode = getById('categorycode').value;
	if (l_categorycode == 0) {
	   l_allserviceslist = selStringOnly;
	   // 17 Jul 2007: assign to globsal var for re-use
	   if (getById('searchforid') != null) {
	      (getById('searchforid').value==2)? (js_allpeopleserviceslist=l_allserviceslist):(js_allserviceslist=l_allserviceslist);
       }
	}    	   
    getById('divservices').innerHTML = selStringOnly;        
    toggleProgress('divservicesprogress',false); 
    if (getById('servicecode') !==null)  getById('servicecode').disabled = false;
    l_blnSearchListLoadComplete=1;
	// remove any possible previous error
	getById('divserviceserror').innerHTML = "";
}
function assignErrorData_Services(l_error) {
	//getById('divserviceserror').innerHTML = "<span class='errorColor'>" + l_error + "</span>";
	toggleProgress('divservicesprogress',false);
	if (getById('servicecode') !==null)  getById('servicecode').disabled = false;
	notify_ajax_retrieval_failed("Services List", "search:assignErrorData_Services()");
}
function getSubRegionListXML(l_action, pagetitle) {
    // do loading msg
    toggleProgress('divsubregionprogress',true);
	reset_list_for_loading(0, l_loadingmessage, 'subregioncode');
	if (getById('subregioncode') !==null)  getById('subregioncode').disabled = true;
    var ajax = new ajaxrpc();
    ajax.get(l_action, "", 'assignRemoteData_SubRegions',0, 'assignErrorData_SubRegions');
}
function assignRemoteData_SubRegions(l_data) {
      void check_for_expired_result(l_data);
      var l_valreceived = l_data;
	   // strip other values and retain select start to end tags only
	   var l_positionSelect    = l_valreceived.indexOf('<select',0);
       var l_positionEndSelect = l_valreceived.indexOf('</select>',l_positionSelect);
       // assign to global var
	   var l_subregionlist       = l_valreceived.substring (l_positionSelect, l_positionEndSelect+9)
       // validate
	   if (validate_selectList(l_subregionlist)==0) {
	      reset_list_for_loading(0, "All", 'subregioncode');
	      assignErrorData_SubRegions();
		  l_subregionlist="";
		  return;
	   }
	   // is searchtypeid MP still selected
 	   if (getById('selsearchtypeid') != null ) {
          if (getById('selsearchtypeid').value < 0 ) {
	         getById('divsubregioncode').innerHTML = l_subregionlist;        
          }
	   } else {
	      // non sra user 
		   if (getById('searchtypeid') != null) {
	          if (getById('searchtypeid').value = "-1") getById('divsubregioncode').innerHTML = l_subregionlist;
	      } 
	   }	    		   
       toggleProgress('divsubregionprogress',false);
       if (getById('subregioncode') !==null)  getById('subregioncode').disabled = false;
}
function assignErrorData_SubRegions(l_error) {
	// getById('divsubregionerror').innerHTML = l_error;
    toggleProgress('divsubregionprogress',false);
	if (getById('subregioncode') !==null)  getById('subregioncode').disabled = false;
	notify_ajax_retrieval_failed("Subregion List", "search:assignErrorData_SubRegions()");
}
function getRegionListXML(l_action, pagetitle) {
    toggleProgress('divregionprogress',true);
	reset_list_for_loading(0, l_loadingmessage, 'regioncode');
	if (getById('regioncode') !==null)  getById('regioncode').disabled = true;
    var ajax = new ajaxrpc();
    ajax.get(l_action, "", 'assignRemoteData_Regions',0, 'assignErrorData_Regions');
}
function assignRemoteData_Regions(l_data) {
       // alert('assignRemoteData_Regions(l_data): ' + l_data)
	   void check_for_expired_result(l_data);
       var l_valreceived = l_data;
	   l_valreceived.indexOf('<select',0);
	   // strip other values and retain select start to end tags only
	   var l_positionSelect    = l_valreceived.indexOf('<select',0);
       var l_positionEndSelect = l_valreceived.indexOf('</select>',l_positionSelect);
       var selStringOnly =l_valreceived.substring (l_positionSelect, l_positionEndSelect+9);
	   // validate
	   if (validate_selectList(selStringOnly)==0) {
	      reset_list_for_loading(0, "All", 'regioncode');
	      assignErrorData_Regions();
		  return;
	   }
	   // assign to global var
	   var l_regionlist       = selStringOnly;
	   //alert('Region list Received: ' + l_data);
	   // is searchtypeid MP still selected
	   if (getById('selsearchtypeid') != null) {
          if (getById('selsearchtypeid').value < 0 ) {
	         getById('divregioncode').innerHTML = l_regionlist;        
	      }
	   } else {
	      // non sra user 
		   if (getById('searchtypeid') != null) {
	          if (document.frmSearch.searchtypeid.value = "-1") {
			      getById('divregioncode').innerHTML = l_regionlist;
		      }		  
	      } 
	   }	    	   
      toggleProgress('divregionprogress',false);
	  if (getById('regioncode') !==null)  getById('regioncode').disabled = false;
	  // 18 Jun: commented out as need to disable subregion list 
	  // void check_searchby();
}
function assignErrorData_Regions(l_error) {
   //getById('divregionerror').innerHTML = l_error;
   toggleProgress('divregionprogress',false);
   if (getById('regioncode') !==null) getById('regioncode').disabled = false;
   notify_ajax_retrieval_failed("Regions List", "search:assignErrorData_Regions()");
}
function getCountryListXML(l_action, pagetitle) {
    toggleProgress('divcountryprogress',true);
    var ajax = new ajaxrpc();
    ajax.get(l_action, "", 'assignRemoteData_Country',0, 'assignErrorData_Country');
}
function assignRemoteData_Country(l_data) {
       void check_for_expired_result(l_data);
       var l_valreceived = l_data;
	   // strip other values and retain select start to end tags only
	   var l_positionSelect    = l_valreceived.indexOf('<select',0);
       var l_positionEndSelect = l_valreceived.indexOf('</select>',l_positionSelect);
       var selStringOnly =l_valreceived.substring (l_positionSelect, l_positionEndSelect+9);
       // assign to global var
	    // validate
	   if (validate_selectList(selStringOnly)==0) {
	      reset_list_for_loading(0, "All", 'countryid');
	      assignErrorData_Country();
		  return;
	   }
	   // assign to global var
	   l_countrylist=selStringOnly; 
	   var divname = document.getElementById('divcountryid');
	   // is searchtypeid MP still selected
	   if (getById('selsearchtypeid') != null ) {
    	   if (getById('selsearchtypeid').value < 0 ) {
	          divname.innerHTML = l_countrylist;        
	       }
	   } 	   
       toggleProgress('divcountryprogress',false);
}
function assignErrorData_Country(l_error) {
	//getById('divcountryerror').innerHTML = l_error;
    toggleProgress('divcountryprogress',false);
	if (getById('countryid') !==null)  getById('countryid').disabled = false;
    var l_title = "";
	if (getById('selsearchtypeid') != null) {
          if (getById('selsearchtypeid').value > 0 ) {
		     l_title ="SRA Region List"
	      } else {
		     l_title ="Country List";
		  }	  
	}	  
	notify_ajax_retrieval_failed(l_title, "search:assignErrorData_Country()");

}
function getSRARegionListXML(l_action, pagetitle) {
    toggleProgress('divcountryprogress',true);
	reset_list_for_loading(0, l_loadingmessage, 'sraregionid');
	if (getById('sraregionid') !==null)  getById('sraregionid').disabled = true;
    var ajax = new ajaxrpc();
    ajax.get(l_action, "", 'assignRemoteData_SRARegions',0, 'assignErrorData_Country');
}
function assignRemoteData_SRARegions(l_data) {
       void check_for_expired_result(l_data);
       var l_valreceived = l_data;
	   // strip other values and retain select start to end tags only
	   var l_positionSelect    = l_valreceived.indexOf('<select',0);
       var l_positionEndSelect = l_valreceived.indexOf('</select>',l_positionSelect);
       var selStringOnly = l_valreceived.substring (l_positionSelect, l_positionEndSelect+9);
	   // validate
	   if (validate_selectList(selStringOnly)==0) {
	      reset_list_for_loading(0, "All", 'sraregionid');
	      assignErrorData_Country();
		  return;
	   }
       // assign to global var
	   var l_sraregionlist = selStringOnly; 
	   var divname = document.getElementById('divcountryid');
	   // is searchtypeid MP still selected
	   if (getById('selsearchtypeid') != null) {
          if (getById('selsearchtypeid').value > 0 ) {
	         divname.innerHTML = l_sraregionlist;        
	      }
	   }	    	   
       toggleProgress('divcountryprogress',false);
	   if (getById('sraregionid') !==null) {
	      // enale sra region list
	      getById('sraregionid').disabled = false;
          // enable territory list if region is not ALL
          if (getById('sraregionid').value > 0) {
		     // enable sra territory list
	         if (getById('sraterritoryid') !==null)  getById('sraterritoryid').disabled = false;
    	  }
	   }
}
function getSRATerritoryListXML(l_action, pagetitle) {
    toggleProgress('divregionprogress',true);
	reset_list_for_loading(0, l_loadingmessage, 'sraterritoryid');
	if (getById('sraterritoryid') !==null)  getById('sraterritoryid').disabled = true;
    var ajax = new ajaxrpc();
    ajax.get(l_action, "", 'assignRemoteData_SRATerritory',0, 'assignErrorData_SRATerritory');
}
function assignRemoteData_SRATerritory(l_data) {
    void check_for_expired_result(l_data);
    var l_valreceived = l_data;
	// strip other values and retain select start to end tags only
	var l_positionSelect    = l_valreceived.indexOf('<select',0);
    var l_positionEndSelect = l_valreceived.indexOf('</select>',l_positionSelect);
	var selStringOnly       = l_valreceived.substring (l_positionSelect, l_positionEndSelect+9);
	// validate
	if (validate_selectList(selStringOnly)==0) {
	    reset_list_for_loading(0, "All", 'sraterritoryid');
	    assignErrorData_SRATerritory();
	    return;
    }
    // assign to global var
	var l_territorylist = selStringOnly ;
	// is searchtypeid SRA still selected
 	if (getById('selsearchtypeid') != null) {
        if (getById('selsearchtypeid').value > 0 ) {
	       getById('divregioncode').innerHTML = l_territorylist;        
        }
	} 	   
    toggleProgress('divregionprogress',false);
    if (getById('sraterritoryid') !==null)  getById('sraterritoryid').disabled = false;
}
function assignErrorData_SRATerritory(l_error) {
   //getById('divregionerror').innerHTML = l_error;
   toggleProgress('divregionprogress',false);
   if (getById('sraterritoryid') !==null) getById('sraterritoryid').disabled = false;
   notify_ajax_retrieval_failed("SRA Territory List", "search:assignErrorData_SRATerritory()");
}
function getSRAReportingAreaListXML(l_action, pagetitle) {
    toggleProgress('divsubregionprogress',true);
	reset_list_for_loading(0, l_loadingmessage, 'srareportingareaid');
	if (getById('srareportingareaid') !==null)  getById('srareportingareaid').disabled = true;
    var ajax = new ajaxrpc();
    ajax.get(l_action, "", 'assignRemoteData_SRARptArea',0, 'assignErrorData_SRARptArea');
}
function assignRemoteData_SRARptArea(l_data) {
    void check_for_expired_result(l_data);
    var l_valreceived = l_data;
	// strip other values and retain select start to end tags only
	var l_positionSelect    = l_valreceived.indexOf('<select',0);
    var l_positionEndSelect = l_valreceived.indexOf('</select>',l_positionSelect);
    var selStringOnly       = l_valreceived.substring (l_positionSelect, l_positionEndSelect+9);
   	// validate
	if (validate_selectList(selStringOnly)==0) {
	    reset_list_for_loading(0, "All", 'srareportingareaid');
	    assignErrorData_SRARptArea();
	    return;
    }
	// assign to global var
	var l_reportingarealist = selStringOnly;
	// is searchtypeid SRA still selected
 	if (getById('selsearchtypeid') != null) {
       if (getById('selsearchtypeid').value > 0 ) {
	       getById('divsubregioncode').innerHTML = l_reportingarealist;        
       }
	} 	   
    toggleProgress('divsubregionprogress',false);
	if (getById('srareportingareaid') !==null)  getById('srareportingareaid').disabled = false;
}
function assignErrorData_SRARptArea(l_error) {
	// getById('divsubregionerror').innerHTML = l_error;
    toggleProgress('divsubregionprogress',false);
	if (getById('srareportingareaid') !==null)  getById('srareportingareaid').disabled = false;
	notify_ajax_retrieval_failed("SRA Reporting Area List", "search:assignErrorData_SRARptArea()");
}

// redirect to login if necessary
function check_for_expired_result(l_content) {
   var l_expired_message = 'This section of the Site is reserved for logged in users';
   var l_result =  l_content.indexOf(l_expired_message,0);
   if (l_result > 0) location.href = "index.php?module=home&loginmessage=" + l_redirect_message;
}
function validate_selectList(l_input) {
   var l_result=0;
   // convert to lower case
   l_input = l_input.toLowerCase(); 
   // check that select list exists in string
   // must start with <select and end with </select>
   l_result = ((l_input.substring(0,7)=="<select"))? 1:0;
   // check for closing tag
   if (l_result ==1 ) l_result= ( (l_input.substring(l_input.length-9,l_input.length) == "</select>") )? 1:0;
   return (l_result);
}
// all callback fns must validate content, call this method and reset content on failure
function notify_ajax_retrieval_failed(l_userproperty, l_pagemethod) {
   // notify user using default messge
   // l_ajaxDataRetrievalFailed
   alert(get_ajax_failed_message(l_userproperty));
   // attempt to log error
   void handleErr('Ajax data retrieval failed: ' + l_userproperty,l_pagemethod);
}
function get_ajax_failed_message(l_userproperty) {
  var l_ajaxDataRetrievalFailed = "MEDpages Data retrieval failed - " + l_userproperty + ".\n\n This may be due to: \n\n - your Browser not allowing AJAX (Asynchronous JavaScript and XML)\n - a slow or intermittent connection to the Internet.\n\n Please retry by refreshing the page.";
  return (l_ajaxDataRetrievalFailed);
}