
	var map= "";
	var region = "";
	var distance = "";

	//Paginator
	var pager = new Pager('results',5);
	var tbl= ""; 
	var TabName1="Location";
	var TabName2="Information";
	var lastlinkid;

	/* The hidden field for user location input*/
	var userlocation = "search:userlocation";

	/* The hidden field name for geocode  */
	var hlatitude  = "search:hlatitude";
	var hlongitude = "search:hlongitude";

	
	/* Variables for loadLocations() */
	var el_locationBar = "locationbar";
	var el_locationXML = "search:dataXML";
	var tag_location = "location";
	var tag_latitude = "latitude";
	var tag_longitude= "longitude";
	var tag_contact = "contact";
	var el_paginator = "pagt";
	 
	var addressList = [];
	addressList[0] ="locationname";;
	addressList[1] = "address";
	addressList[2] = "city";
	addressList[3] = "zipcode";
	addressList[4] = "distance"; 
	addressList[5] = "markerImage";
	
	  
	var mesg_no_results = "There are no locations matching your search. Please try again.";
	var ipimagename = "3.gif";
	var vhcimagename = "5.gif";
	var vscimagename = "6.gif";
	var tag_url = "url";
	var tag_description = "description"; 
	var tag_subtitle = "subtitle";
	var tag_additionalinfo = "additionalinfo";
	var tag_additionalContacts = [];
	tag_additionalContacts[0] = "pharmacyrefill";
	tag_additionalContacts[1] = "clinichours";
	tag_additionalContacts[2] = "pharmacyhours";
	tag_additionalContacts[3] = "urgentcarehours"; 
	
	var tag_additionalContacts_label = [];
	tag_additionalContacts_label[0] = "Pharmacy Refill (24hrs)";
	tag_additionalContacts_label[1] = "Clinic Hours";
	tag_additionalContacts_label[2] = "Pharmacy Hours";
	tag_additionalContacts_label[3] = "Urgent Care Hours"; 
	
	
	var contact_LABEL_GENERAL = "Phone";
	var contact_LABEL_VH = "Appointment and Nurse Advice";


	
	var applicationname = "locationmap";
	var defaultState = "CA";
	var locationURL="http://www.sccgov.org/portal/site/vhp/vhpchp?path=%2Fv7%2FValley%20Health%20Plan%20%28DEP%29%2FLocations%2FVHP%20Network%20Health%20Centers";
	
	var html_additional_contact = "<div class='label-blue-pd'><b>CONTACT_TOKEN</b></div>";
	var url_token = "URL_TOKEN";
	var contact_token = "CONTACT_TOKEN";
	var main_contact_token = "MAIN_CONTACT_TOKEN";

	var html_tab1  = "<div class='label-md' ><b>locationname_TOKEN</b><br/>address_TOKEN"
		+ " <br/>city_TOKEN, defaultState_TOKEN zipcode_TOKEN"
		+ " <br/><br/> <b class='label-purple'>subtitle_TOKEN</b>"
		+ "<form name='getDirection' method='get' action='directions'>"
		+ " <br/>Start Address:<br/>"
		//+ " <br/><label for='saddr'>Start Address: </label>"
		+ " <input type='text' name='saddr' title='saddr' id='saddr' class='label-md' value= \"DEFAULT_LOCATION_TOKEN\"/>"
		+ " <input type='hidden' name='daddr' value=\"FULLADDRESS_TOKEN\"/>"
		+ " <input type='submit' value='Get Directions'  class='label-md-lk' /></div>";
	
	var html_main_contact = "<div class='label-md'>INFO_TOKEN<b>contact_LABEL_TOKEN</b><br/> MAIN_CONTACT_TOKEN<br/></div><br/>";
	
/****************************************************************************************************************************/
	/*
	 * loadLocations() - loadLocations method loads the data in the locationbar(displays 
	 * the list of locations) and the markers in the google map.
	 */	
	function loadLocations() {
		var locationXML;
		var xml;
		var markers;  
		//alert("htype ::" + document.getElementById("search:htype").value);
		//alert("hservices ::" + document.getElementById("search:hservices").value);
		//Call the servlet and get the data
		var searchUrl = '/' + applicationname + '/xml/xmlServlet?lat=' + document.getElementById(hlatitude).value + '&lng=' + document.getElementById(hlongitude).value +  '&location=' + document.getElementById(userlocation).value+ '&type=' + document.getElementById("search:htype").value + '&services=' + document.getElementById("search:hservices").value + '&radius=' + document.getElementById("search:hradius").value;
		GDownloadUrl(searchUrl, function(returndata, responseCode) {
			if(responseCode == 200) {
				xml = GXml.parse(returndata); 
				if( xml.documentElement )
					markers = xml.documentElement.getElementsByTagName(tag_location);
				if(markers != null)
				//alert("markers length :: "+ markers.length);
				getDataandMarkers(markers);	
			}else if(responseCode == -1) {
    			//alert("Data request timed out. Please try later.");
  			} else { 
    			//alert("Request resulted in error. Check XML file is retrievable.");
  			}
			
	    });
	    
	  
	} 

function showResults(){
	//alert("Request in Javascript");
	convertLocation();
}	
/*
* convertLocation() - convertLocation method converts the user entered value in the 
* input field (city, state or zip) to geocoded values and sets the geocoded value 
* in hidden field in the form. 
*/	
function convertLocation(){
  /* user input */    	
  //alert("Inside convertLocation()");
  var location = document.getElementById(userlocation).value;
  var geocoder = new GClientGeocoder();
  geocoder.getLatLng(location, function(latlng) {
	if (latlng) {
	   /* Sets the geocoded values in the hidden field */
	   document.getElementById(hlatitude).value = latlng.lat();
	   document.getElementById(hlongitude).value = latlng.lng();
	 //  alert("location, lat:: "+ location + " , " + latlng.lat());
	   loadLocations();
	 }
   });
  
}
/*
* initMap() is invoked on body onload of the results page. This function is invoked
* when we switch between the tabs(Location and Direction) as well as when the application is 
* invoked from portal. 
*/
 function initMap() {
    	var locationXML;
		var xml;
		var markers; 
		
		if(	document.getElementById(el_locationXML) != 'undefined' ){
			//returns the DOM representation of the XML 
			locationXML = document.getElementById(el_locationXML).value;
			xml = GXml.parse(locationXML); 
			if( xml.documentElement )
					markers = xml.documentElement.getElementsByTagName(tag_location);
			
		}		
		getDataandMarkers(markers);
	      
}
/*getDataandMarkers() - getDataandMarkers method loads the data in the locationbar(displays 
 * the list of locations) and the markers in the google map.
 */
function getDataandMarkers(markers){
	var mapMarkers = [];
	//locationbar displays the location list on the results page 
	var locationbar = document.getElementById(el_locationBar);
	locationbar.innerHTML = ''; 
	//clear the previous markers
	clearMap(); 
	try{
	if ( markers == null ||  markers.length == 0){
		  locationbar.innerHTML = "<div class='label-md-org'>" + mesg_no_results +"</div><br/>";
		  document.getElementById(el_paginator).innerHTML = ''; 
		  defaultMap();
	} 
	else  {
		 var tbody = createTableBody();
		 /* limiting to 60 */
		 var displaymax = markers.length;
		  if(markers.length > 60)
		 	displaymax = 60;
		 for (var i = 0; i < displaymax; i++) {
				var point = new GLatLng(parseFloat(markers[i].getElementsByTagName(tag_latitude)[0].firstChild.nodeValue),
				  parseFloat(markers[i].getElementsByTagName(tag_longitude)[0].firstChild.nodeValue));
				
				var addressObj = [];
				var fullAddress;
				if(addressList.length > 0)
					for(var j=0; j < addressList.length; j++)
						addressObj[j]  = markers[i].getElementsByTagName(addressList[j])[0].firstChild.nodeValue;
				fullAddress = addressObj[1]+ "," + addressObj[2]+ ","+ defaultState+ " " + addressObj[3]; 
					
				
				var additionalContacts = []; 
				if(tag_additionalContacts.length > 0)
					for(var j=0; j < tag_additionalContacts.length; j++)
						additionalContacts[j] = markers[i].getElementsByTagName(tag_additionalContacts[j]);
						  
				var url = markers[i].getElementsByTagName(tag_url);
				var contact = markers[i].getElementsByTagName(tag_contact);
				if(contact.length > 0){
					contact = markers[i].getElementsByTagName(tag_contact)[0].firstChild.nodeValue;
					contact = splitString(contact);
					point.contact = html_main_contact.replace(main_contact_token, contact);
					
				}
				else
					point.contact = html_main_contact.replace(main_contact_token, "");
					
				var desc = markers[i].getElementsByTagName(tag_description);
				if(desc.length > 0){
					desc = markers[i].getElementsByTagName(tag_description)[0].firstChild.nodeValue;
				}
				var subtitle = markers[i].getElementsByTagName(tag_subtitle);
				if(subtitle.length > 0){
					subtitle = markers[i].getElementsByTagName(tag_subtitle)[0].firstChild.nodeValue;
				}
				
				var additionalinfo = markers[i].getElementsByTagName(tag_additionalinfo);
				if(additionalinfo.length > 0){
					additionalinfo = markers[i].getElementsByTagName(tag_additionalinfo)[0].firstChild.nodeValue;
					var additionalinfohtml = "<b class='label-purple'>"+ additionalinfo+"</b><br/><br/>";
					point.contact = point.contact.replace("INFO_TOKEN", additionalinfohtml);
				}
				else
					point.contact = point.contact.replace("INFO_TOKEN", "");		
				if( addressObj[5] == vhcimagename || addressObj[5] == vscimagename ){
					point.contact = point.contact.replace("contact_LABEL_TOKEN", contact_LABEL_VH);
				}	
				else
					point.contact = point.contact.replace("contact_LABEL_TOKEN", contact_LABEL_GENERAL);	
			


				if(url.length > 0)
					url = markers[i].getElementsByTagName("url")[0].firstChild.nodeValue;
				
				if(additionalContacts.length > 0){
					point.contact = point.contact + "<div class='label-md'>";
					for(var j=0; j < additionalContacts.length; j++){
						if( additionalContacts[j].length > 0 ){
							var contactNode = (additionalContacts[j])[0].firstChild.nodeValue;
							contactNode = splitString(contactNode);
							point.contact = point.contact + html_additional_contact + contactNode;
							point.contact = (point.contact).replace("URL_TOKEN", URLDecode(url));
							point.contact = (point.contact).replace(contact_token, tag_additionalContacts_label[j]);
							point.contact = point.contact + "<br/>";
						}
					}
					point.contact = point.contact + "</div>";
				}
			   	point.contact = point.contact + "<br/>";
				//Settings the values to be displayed in the information window of makers.
				
			/*	if(addressObj[5] == ipimagename){
					point.location = "<div class='label-md' ><b>Independent Practice</b><br/></div>";
					point.location = point.location + html_tab1;
					alert(point.location);
				}	
				else{
					point.location  = html_tab1;
					alert(point.location);
				}*/
				
				point.location  = html_tab1;
				
				for(var j=0; j<4; j++) {
					if(j==0)
						point.location  = (point.location).replace( addressList[j]+"_TOKEN",addressObj[j]);
					else
						point.location  = (point.location).replace( addressList[j]+"_TOKEN",addressObj[j]);
				}
					
					
				point.location  = (point.location).replace("FULLADDRESS_TOKEN",fullAddress);
				point.location  = (point.location).replace("DEFAULT_LOCATION_TOKEN",document.getElementById(userlocation).value);
				point.location  = (point.location).replace("defaultState_TOKEN",defaultState); 
				if(subtitle.length > 0)
					point.location  = (point.location).replace("subtitle_TOKEN",subtitle); 
				else
					point.location  = (point.location).replace("subtitle_TOKEN",""); 
				var marker = createLocationMarker(point, addressObj[5],mapMarkers);
				mapMarkers.push(marker);
				
				//populates the location list on the results page
				var locationbarEntry = createlocationbarEntry(marker, addressObj[0], addressObj[1],addressObj[2],addressObj[3], addressObj[4],addressObj[5],desc,subtitle);
				
				//append each row to the table body
				tbody.appendChild(locationbarEntry);
			  }
			
			   locationbar.appendChild(tbl);
			   //Init the paginator
			   pager.init(); 
			   //pagt is the id of the div tag in xhtml
			   pager.showPageNav('pager', 'pagt'); 
			   pager.showPage(1);
			 
			  //displays the map
			  displayegovMap(mapMarkers);
		  
	}
	}
	catch(e){
		//Continue. do nothing.
		//alert("The following error occurred: " + e.name + " - " + e.message); 
	}


}
/**
* splitString function splits the input String (comma delimiter) and returns
* the values as table rows.
*/
function splitString(inputString){

var resultString = inputString.split(";");
var resultRow = "";
for(i = 0; i < resultString.length; i++){
	var rowData = " "+resultString[i]+ "<br/>";
	resultRow = resultRow + rowData; 
}
return resultRow;
}


/**
* createLocationMarker() - createLocationMarker method creates the location 
* marker for each point.
*/
function createLocationMarker(point, markerImage,mapMarkers ) {

	// create new GIcon to use with the marker 
	var customIcon = createCustomIcon(markerImage);
	var marker = new GMarker(point,customIcon);
	var infoTabs = [				
		new GInfoWindowTab(TabName1, point.location),
		new GInfoWindowTab(TabName2,point.contact)
	];
	var linkid = "link"+(mapMarkers.length); 
	marker.id = linkid;
	GEvent.addListener(marker, "click", function() {
		var opts = {pixelOffset:new GSize(32,5),autoScroll:true,maxHeight:150,maxWidth:220};
		marker.openInfoWindowTabsHtml(infoTabs,opts);
		//document.getElementById(linkid).style.background="#333333";
		lastlinkid=linkid;
	});
	return marker;
}

/*
* displayegovMap() - displayegovMap method the displays the google map with the location markers.
*/	
function displayegovMap(mapMarkers){

	// Find boundary points of location
	var bounds = new GLatLngBounds();
	map = new GMap2(document.getElementById("egovmap"));
	map.setCenter(new GLatLng(0,0), 0);
	
	
	for (var i=0;i < mapMarkers.length;i++)  {
	  map.addOverlay(mapMarkers[i]);
	  bounds.extend(mapMarkers[i].getPoint());
	}
	// Reset center and zoom level based on queried locations
	var mapzoomlevel = map.getBoundsZoomLevel(bounds);
	if(mapzoomlevel >  15)
		mapzoomlevel = 15;
	map.setZoom(mapzoomlevel);
	map.setCenter(bounds.getCenter());
	map.enableScrollWheelZoom();
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	GEvent.addListener(map,"infowindowclose", function() {
	        document.getElementById(lastlinkid).style.background="#333333";
	});

}

/**
* createlocationbarEntry() - createlocationbarEntry method creates each row in the location 
* list and adds the listener to each row in the location list.
* For the paginator to work, data needs to be in <table> format. 
*/  

function createlocationbarEntry(marker, locationName, address,city,zipcode, distance, markerImage,desc,subtitle) {
	
	var tr = document.createElement('tr');
	var tdimg = document.createElement('td');
	var htmlimg = "";
	// var htmlimg = "<img src='/gmap/images/icons/"+markerImage+"'/>";
	tdimg.innerHTML = htmlimg;
	tdimg.vAlign='top';
	tr.appendChild(tdimg);
	var td = document.createElement('td');
	var html = "";
	
	if(markerImage == ipimagename){
		html = "<div class='label-blue-link'>" + "Independent Practice" + "</div> ";
		if(subtitle.length > 0){
			html = html +  "<div class='label-md-pad'><b>" + subtitle + "</b></div>";
		}
		html = html +  "<div class='label-md-pad'>" + locationName + "</div>";
	}
	else{
		html = "<div class='label-blue-link'>" + locationName + "</div> ";
		
	}
	if(desc.length > 0){
		html = html +  "<div class='label-md-pad'><b>" + desc + "</b></div>";
		if(subtitle.length > 0){
			html = html +  "<div class='label-md-pad'><b>" + subtitle + "</b></div>";
		}
	}
	
	html = html +  "<div class='label-md-pad'>" + address + "</div>";
	html = html +  "<div class='label-md-pad'>" + city + ", "+ defaultState+ " "+ zipcode +"</div>";
	html = html +  "<div class='label-md-org'>~"+ distance + " miles </div><br/>" ;
	
	
	td.innerHTML = html;
	td.id = marker.id;
	td.className = "grayBox";
	td.style.cursor = 'pointer';
	td.style.marginBottom = '5px'; 
	td.style.fontSize= '10px';
	GEvent.addDomListener(td, 'click', function() {
		td.style.backgroundColor = '#666666';
		GEvent.trigger(marker, 'click');
		
	});
	  /* GEvent.addDomListener(td, 'mouseover', function() {
		        td.style.backgroundColor = '#666666';
		      });
	  GEvent.addDomListener(td, 'mouseout', function() {
		        td.style.backgroundColor = '#333333';
		    });
		   
		*/       
		      
	tr.appendChild(td);
	
	return tr;
}



/*
* createCustomIcon - function to create custom images to markers
*/
function createCustomIcon(markerImage){

// create new gicon to use with the marker 
var customIcon = new GIcon();
customIcon.image = "/"+ applicationname + "/images/icons/"+markerImage ;
customIcon.iconSize = new GSize(18, 36); 
customIcon.iconAnchor = new GPoint(10, 34); 
customIcon.infoWindowAnchor = new GPoint(10, 0);
customIcon.shadow = "";
 
return customIcon;
				
}
/**
* dirAddress of the format from: <address1> to: <address2>
*/
function loadDirections(){
var directionsPanel;
var directions;
var fromAddress = document.getElementById('search:sAddress').value;
var toAddress = document.getElementById('search:dAddress').value;
var directionAddress =  ' from: '+ fromAddress + ' to: ' + toAddress;
var dirOptions = document.getElementById('search:diroptions').value;
//Default is Driving
var dirTravelMode = G_TRAVEL_MODE_DRIVING;
if(dirOptions == "Walking"){
dirTravelMode = G_TRAVEL_MODE_WALKING; 
}
map = new GMap2(document.getElementById('egovmap'));  
directionsPanel = document.getElementById('egovdir');
directionsPanel.className="lgBox";
directionsPanel.style.fontSize= '10px';
directionsPanel.style.color= '#000000';
directions = new GDirections(map, directionsPanel);
//GEvent.addListener(directions, "load", onGDirectionsLoad);
directions.load(directionAddress, {travelMode: dirTravelMode});

}


/*
* createTableBody() - function creates the table and the table body element of the location list
* displayed in the left panel.
*/
function createTableBody(){
 tbl = document.createElement('table');
 tbl.id = 'results';
 var tbody = document.createElement('tbody');
 tbl.appendChild(tbody);
 // Heading 
 var tr = document.createElement('tr');
 var th = document.createElement('th');
 th.innerHTML = "<div class='label-md-org'>Found locations :</div>"; 
 th.colSpan ='2';
 tr.appendChild(th);
 tbody.appendChild(tr);
 return tbody;
}
/* From http://it.newinstance.it/2006/09/27/client-side-html-table-pagination-with-javascript/
*  Adds paginator to the location list
*/
function Pager(tableName, itemsPerPage) {
this.tableName = tableName;
this.itemsPerPage = itemsPerPage;
this.currentPage = 1;
this.pages = 0;
this.inited = false;

this.showRecords = function(from, to) {        
	var rows = document.getElementById(tableName).rows;
	// i starts from 1 to skip table header row
	for (var i = 1; i < rows.length; i++) {
		if (i < from || i > to)  
			rows[i].style.display = 'none';
		else
			rows[i].style.display = '';
	}
}

this.showPage = function(pageNumber) {
	if (! this.inited) {
		//alert("not inited");
		return;
	}
	var oldPageAnchor = document.getElementById('pg'+this.currentPage);
	oldPageAnchor.className = 'label-md-b';
	
	this.currentPage = pageNumber;
	var newPageAnchor = document.getElementById('pg'+this.currentPage);
	newPageAnchor.className = 'label-md-selected';
	
	var from = (pageNumber - 1) * itemsPerPage + 1;
	var to = from + itemsPerPage - 1;
	this.showRecords(from, to);
	//Added Code to hide prev and next
	var pgNext = document.getElementById('pgNext');
	var pgPrev = document.getElementById('pgPrev');
	if (this.currentPage == this.pages)
		pgNext.style.display = 'none';
	else
		pgNext.style.display = '';
	if (this.currentPage == 1)
		pgPrev.style.display = 'none';
	else
		pgPrev.style.display = '';
	
}   

this.prev = function() {
	if (this.currentPage > 1)
		this.showPage(this.currentPage - 1);
}

this.next = function() {
	if (this.currentPage < this.pages) {
		this.showPage(this.currentPage + 1);
	}
}                        

this.init = function() {
	var rows = document.getElementById(tableName).rows;
	var records = (rows.length - 1); 
	this.pages = Math.ceil(records / itemsPerPage);
	if(this.pages > 10)
		this.pages = 10;
	this.inited = true;
}

this.showPageNav = function(pagerName, positionId) {
	if (! this.inited) {
		alert("not inited");
		return;
	}
	var element = document.getElementById(positionId);
				
var pagerHtml = '<a id="pgPrev" onclick="' + pagerName + '.prev();" class="label-md-b"> &#171 Prev </a> | ';
for (var page = 1; page <= this.pages; page++) 
	pagerHtml += '<a id="pg' + page + '" class="label-md-b" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '</a> | ';
pagerHtml += '<a id="pgNext" onclick="'+pagerName+'.next();" class="label-md-b"> Next &#187;</a>';            

element.innerHTML = "<div class='orgBox'>"+pagerHtml+"</div>";
}
}

/*
* If enter key is pressed, invoke showResults() method
*/
function enableEnterKey(e){
     var key;
     if(window.event)
          key = window.event.keyCode; //IE
     else
          key = e.which; //firefox
    
     //Enter/Return Key
     if(key == 13){
 		showResults();
 		return false;
 	 }
 	return true;
}

// Clear map points
function clearMap(){
      map = new GMap2(document.getElementById("egovmap"));	     
      map.clearOverlays();
     
}

function defaultMap() {
      if (GBrowserIsCompatible()) {
	       map = new GMap2(document.getElementById("egovmap"));
	   	    map.setCenter(new GLatLng(37.315976, -121.936717), 15);
	   	    map.enableScrollWheelZoom();
	   	    map.addControl(new GLargeMapControl());
	   	    map.addControl(new GMapTypeControl());
      }
}


