// image for nav
function newImage(arg) {
if (document.images) {
	rslt = new Image();
	rslt.src = arg;
	return rslt;}}
function changeImagesArray(array) {
    if (preloadFlag == true) {
	    var d = document; var img; var i;
	    for (i=0;i<array.length;i+=2) {
		    img = null; var n = array[i];
		    if (d.images) {
			    if (d.layers) {img = findElement(n,0);}
			    else {img = d.images[n];}
		    }
		    if (!img && d.getElementById) {img = d.getElementById(n);}
		    if (!img && d.getElementsByName) {
			    var elms = d.getElementsByName(n);
			    if (elms) {
				    for (j=0;j<elms.length;j++) {
					    if (elms[j].src) {img = elms[j]; break;}
				    }}}
		    if (img) {img.src = array[i+1];}
	    }}}
function changeImages() {changeImagesArray(changeImages.arguments);}			
var preloadFlag = false;
function preloadImages() {
    if (document.images) {
	    pre_nav_home_over = newImage('http://www.medpages.co.za/mphtml/v2/images/nav_home_over.png');
	    pre_nav_search_over = newImage('http://www.medpages.co.za/mphtml/v2/images/nav_search_over.png');
	    pre_nav_getlisted_over = newImage('http://www.medpages.co.za/mphtml/v2/images/nav_getlisted_over.png');
	    pre_nav_products_over = newImage('http://www.medpages.co.za/mphtml/v2/images/nav_products_over.png');
	    pre_nav_about_over = newImage('http://www.medpages.co.za/mphtml/v2/images/nav_about_over.png');
	    pre_nav_contact_over = newImage('http://www.medpages.co.za/mphtml/v2/images/nav_contact_over.png');
	    preloadFlag = true;
    }}
// general utility methods and definitions - consolidated file
nn=(document.layers)?true:false;
ie=(document.all)?true:false;
function checkKeyDownDefaultFormSubmit(e) {
	   var evt=(e)?e:(window.event)?window.event:null;
	   if(evt){
		 var key=(evt.charCode)?evt.charCode:
			((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
		if(key=="13") document.forms[0].submit();
	   }
}
// ------------------ definitions ----------------- 
var SEARCHBY_NAME = 1;
var SEARCHBY_PRACTICE_NUMBER = 2;
var SEARCHBY_COUNCIL_NUMBER  = 3;
var SEARCHBY_MEDPAGES_CODE   = 4;
var SEARCHBY_SUBURB = 5;
var SEARCHBY_BRICK  = 6;
var SEARCHBY_TELEPHONE = 7;
var SEARCHBY_EMAIL = 8;
var SEARCHBY_DISTRIBUTOR_NUMBER = 9;
var SEARCHBY_COUNCIL_NUMBER_PROMPT = 'e.g. 0400211MP';
var WIDE_SEARCH_LIST_WIDTH = 450;
var SEARCH_INPUT_WIDTH = 220;
var SEARCH_INPUT_SIZE = 33;
var IMAGE_PATH = "nx01/";
// ------------------------  general method to handle exceptions --------------
window.onerror = handleErr;
function handleErr(msg,url,lineno) {
 var l_currentURL = ''
 l_currentURL = window.location.host;
 var l_exception  = "There was an exception on this page.\n\n"
 l_exception += "Exception: " + msg + "\n\n"
 l_exception += "Click OK! to continue.\n\n"
 
 // action
 var l_url = 'http://' + l_currentURL + "/jsexception.php?msg=" + msg + '&url=' + url + '&lineno=' + lineno;
 try {
   var l_ajax = new ajaxrpc();
   l_ajax.get(l_url, "", "jsexception_feedback",0, "jsexception_error");
   l_ajax = "";	
 }
  catch(e) {
    alert(l_exception);
    return true
 }
 //alert(l_exception + "\n\n Sent to server:  msg: " + msg + "\n URL: " + url + "\n lineno: " + lineno)
 return true
}
//--------------------------------------------------------------------//
function jsexception_feedback(l_data) {
   var l_exception  = "There was an exception on this page.\n\n";
   l_exception += "Details logged.(" + l_data + ").\n\n"
   l_exception += "Click OK! to continue.\n\n"
   //alert(l_exception);
   l_exception='';
}
function jsexception_error(l_data) {
   alert('jsexception_error: ' + l_data)
}
// ------------------- utility methods ---------------------------------------
var getById=function (ctlname) {
   return (document.getElementById(ctlname));   
};
var selected_listvalue=function (ctlselect) {
    var l_result = 0;
	if (document.getElementById(ctlselect)  != null) {
	   l_result = document.getElementById(ctlselect).value
	}
	return (l_result);
};
var selected_listtext=function (ctlselect) {
    var l_result =''; var l_index=0;
	if (document.getElementById(ctlselect)  != null) {
	   l_index   = document.getElementById(ctlselect).options.selectedIndex;
	   l_result = document.getElementById(ctlselect).options[l_index].text;
	}
	return (l_result);
}; 
var check_ctl_exists=function (ctlName) {
  // return true / false if ctl exists
  // leave form param for backward compatibility
  return (document.getElementsByName(ctlName).length != 0)? 1:0;
};   
var isNumberstring=function (theField) {
   inStr =theField;
   inLen =inStr.length;
   if(inLen==0) return (false);
   var refstring="1234567890";
   for (count=0; count <  inLen; count++)  {
       var TempChar=  inStr.substring (count, count+1)
        if (refstring.indexOf (TempChar, 0)==-1)        
             return false;
        }
   return (true);
};
var isShowing=function(d) {
   return (getById(d).style.display == "block")?1:0;
};
var toggleDisplay=function (d,blnValue) {
    if (blnValue == 1 || blnValue == true) {
	   ShowContent(d);
	} else {
	  HideContent(d); 
	}
}
var HideContent=function (d) {
    getById(d).style.display = "none";
};
var ShowContent=function (d) {
    getById(d).style.display = "block"; 
};
var ReverseContentDisplay=function (d) {
   if(getById(d).style.display == "none") { 
      getById(d).style.display = "block"; 
   } else { 
	  getById(d).style.display = "none"; 
   }
};
var add_Item=function (sval,stext, toCtrl) {
	var i;
	var j;
	var itemexists;
	var nextitem;
	// add item : value & text value in parameters
	// search toCtrl to see if duplicate exists
	j = 0;
	itemexists = false;
	while ((j < toCtrl.options.length) && (!(itemexists))) {
		if (toCtrl.options[j].value == sval) {
			itemexists = true;
		}
		j++;
	}
	if (!(itemexists)) {
		// add the item
		nextitem = toCtrl.options.length;
		toCtrl.options[nextitem] = new Option(stext);
		toCtrl.options[nextitem].value = sval;			    	
	}
};
var remove_AllItems=function (fromCtrl) {
   fromCtrl.options.length = 0;
};
var do_select=function (ctlselect,l_newval){
   var lCtlID = document.getElementById(ctlselect);
   if ( lCtlID != null) {lCtlID.value = l_newval;}
};
var trim=function(str) {
    return (str.replace(/(^\s+|\s+$)/g,''));
};
var startPopEvent=function (PopUrl,win_width, win_height) {
  var desktop=window.open(PopUrl,"_blank","toolbar=no,location=yes,status=yes,menubar=no,scrollbars=yes,width=" + win_width + ",height=" + win_height + ",resizable");
};
var toggleProgress=function (d,l_bln) {
    // requires searchfdefs.js
    // display / hide animated progress icon in div or span 
	if (document.getElementById(d) != null) {
	   document.getElementById(d).innerHTML = (l_bln)? '<img src="' + IMAGE_PATH + 'images/progress.gif"/>':''
    }
};
// --------------------------------  ajax rpc ------------------------------
function ajaxrpc() {
  this.xmlhttp=null;
  this.callBackFunction=function(){};
  this.errorCallBackFunction=function(){};
  this.shouldDebug =0;
  // ------------------------------ public methods --------------------------
  this.get = function(url, urlVars, callbackFunction, expectingXML, errorCallBackFunction,callingContext) {
     //alert('In GET') 
    this.errorCallBackFunction=errorCallBackFunction; 
	this._callServer(url, urlVars, callbackFunction, expectingXML,
                    callingContext, "GET", null, null, null);
  };
  this.postVars =
    function(url, bodyVars, optionalURLVars, callbackFunction, expectingXML,
             errorCallBackFunction, callingContext) {
      this.errorCallBackFunction=errorCallBackFunction; 			 
      this._callServer(url, optionalURLVars, callbackFunction, expectingXML,
                      callingContext, "POST", bodyVars, null, null);
  };
  // creates http object, does rpc, execs callback function 
  this._callServer = function(url, urlVars, callbackFunction, expectingXML,
                       callingContext, requestMethod, bodyVars,
                       explicitBodyType, explicitBody) {
    if (urlVars==null) {urlVars = new Array();}
	_debug("_callServer() called. About to request URL\n"
                + "url: [" + url + "]\n"
                + "callback function: [" + callbackFunction + "]\n"
                + "treat response as xml?: [" + expectingXML + "]\n"
                + "Request method?: [" + requestMethod + "]\n"
                + "calling context: [" + callingContext + "]\n"
                + "explicit body type: [" + explicitBodyType + "]\n"
                + "explicit body: [" + explicitBody + "]\n"
                + "urlVars: [" + urlVars + "]\n"
                + "bodyVars: [" + bodyVars + "]"
              );
   // create xml object
   this.xmlhttp = _createXMLHttpRequest();   
   this.callbackFunction = callbackFunction;
   // use in call back
   var self = this;
     //alert('B4 call OPEN: requestMethod: ' + requestMethod + ' url: ' + url);
   this.xmlhttp.open(requestMethod, url, true);
     //alert('after call OPEN')
   this.xmlhttp.onreadystatechange = function() {
		if (self.xmlhttp.readyState < 4 ) return;
		if (self.xmlhttp.readyState == 4) {
		     var content = expectingXML ? self.xmlhttp.responseXML : self.xmlhttp.responseText;
			  // call the call back function, pass data			  
			  eval(self.callbackFunction  + '(content)');
		}
	};
    // check for a GET / POST - TODO: prep vars for POST  
    if (requestMethod=="GET" || requestMethod=="HEAD" || requestMethod=="DELETE") {
       _debug("Body-less request to URL " + url);
       this.xmlhttp.send(null);
       return;
    }
    if (requestMethod=="POST" || requestMethod=="PUT" || requestMethod=="OPTIONS" || requestMethod=="TRACE") {
        bodyType = null;
        body = null;
       if (explicitBodyType==null) { // It's a form
         bodyType = 'application/x-www-form-urlencoded; charset=UTF-8';
         body = bodyVars;   //this._createHTTPVarSpec(bodyVars);
       } else {
         bodyType = explicitBodyType;
         body = explicitBody;
       }
       this._debug("Content-Type: [" + bodyType + "]\nBody: [" + body + "].");
       this.xmlhttp.setRequestHeader('Content-Type',  bodyType);
       this.xmlhttp.send(body);
       return;
    }
    _debug("ERROR: Unknown Request Method: " + requestMethod);
 }
 // create http object
 _createXMLHttpRequest = function () {
    if (window.XMLHttpRequest) {
      return new XMLHttpRequest();
    } else if (window.ActiveXObject) {
      return new ActiveXObject('Microsoft.XMLHTTP')
    } else {
      this._error("Could not create XMLHttpRequest on this browser");
      return null;
    }
  };  
  _debug = function(message) {
      if (this.shouldDebug) {
        alert("AjaxJS Message:\n\n" + message);
      }
  };
  _error = function(message) {
      if (this.shouldDebug) {
        alert("AjaxJS ERROR:\n\n" + message);
      }
  }
};
// ------------------------ end ajax --------------------------------
function validate_received_content(l_starttag, l_endtag, l_input) {
   var l_result=0;
   // convert to lower case
   l_input = l_input.toLowerCase(); 
   // check that start and end tag exist in string
   l_result = ((l_input.substring(0,(l_starttag.length))==l_starttag))? 1:0;
   // check for closing tag
   if (l_result ==1 ) l_result= ( (l_input.substring(l_input.length-(l_endtag.length),l_input.length) == l_endtag) )? 1:0;
   return (l_result);
}
// all callback fns must validate content, call this method and reset content on failure
function do_notify_ajax_retrieval_failed(l_userproperty, l_pagemethod) {
   // notify user using default messge
   // l_ajaxDataRetrievalFailed
   alert(do_get_ajax_failed_message(l_userproperty));
   // attempt to log error
   void handleErr('Ajax data retrieval failed: ' + l_userproperty,l_pagemethod);
}
function do_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);
}   