/**
 * -------------------------------------
 * provider_search.js
 *
 * -------------------------------------
 */

// get a query string parameter
function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }

  return null;
}

$(document).ready(function() {
	LoadGoogleMap();
	if ($('#MedicalPractitionerSurname')) { $('#MedicalPractitionerSurname').hint() }
	if ($('#SuburbOrPostCode')) { $('#SuburbOrPostCode').hint() }
	if ($('#ProviderSurname')) { $('#ProviderSurname').hint() }
});

function fixHintText(element) {
        var jel = $('#' + element);
        if (jel) {
                if (jel.val() == '') {
                        jel.val(jel.attr('title'));
                }
        }
}

// global variables
var search_type = '';
var current_page = 1;
var row_per_page = 5;

// handle http request to remote table
function httpRequest(url, callback) {
	var httpObj = false;
	if (typeof XMLHttpRequest != 'undefined') {
		httpObj = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		try{
			httpObj = new ActiveXObject('Msxml2.XMLHTTP');
		} catch(e) {
			try{
				httpObj = new ActiveXObject('iMicrosoft.XMLHTTP');
			} catch(e) {}
		}
	}
	if (!httpObj) return;
	httpObj.onreadystatechange = function() {
		if (httpObj.readyState == 4) { // when request is complete
			if (callback) {callback(httpObj.responseText);}
		}
	};
	httpObj.open('GET', url, true);
	httpObj.send(null);
}
// fetch remote table based on url_query
function FetchSearchResult(url_query) {
	// show result table border
	$('#DisplaySearchResultHere').css('border','1px solid #e0e0e0');
	// increase marker session number to prevent old result being plotted when changing search criteria
	marker_session = marker_session + 1;
	// set mouse pointer to hour glass
	document.body.style.cursor = "wait";
	// get result and pass it on to be formatted
	httpRequest(url_query,FormatSearchResultStep1);
}
// =========== STEP 1 ===== transform remote table to multiple pages of result
function FormatSearchResultStep1(raw_result) {
	// put raw_result on document temporarily for processing
	document.getElementById('TemporaySearchResult').innerHTML = raw_result;
	// get hidden search result table
	var x = document.getElementById('SearchResult');
	// modify first column (Providers name) of TemporarySearchResult if providerDoh exist - for more info on affiliates
	var first2line;
	if (location.href.indexOf('Medical_Providers')>0) {
		for (i=1;i<=x.rows.length-1;i=i+2) {
			for (colno=0;(colno<2) && ((i+colno)<=(x.rows.length-1));colno=colno+1) {
				if (x.rows[i+colno].cells[12].innerHTML) {
					first2line = x.rows[i+colno].cells[0].innerHTML;
					x.rows[i+colno].cells[0].innerHTML = '<a href="javascript:displayMoreInfo(\'' + x.rows[i+colno].cells[12].innerHTML +
														 '\')">' + first2line.slice(0, first2line.indexOf('<')) + '</a>' + 
														 first2line.slice(first2line.indexOf('<'));
				}
			}
		}
	}
	// if search result return null pointer just show Search Result: 0
	var address_line2;
	var total_word;
	if ((x.rows.length-1)>1) {total_word='&nbsp;locations found'} else {total_word='&nbsp;location found'}
	var formatted_result = '<div id="SearchResultHeader"><div id="SearchResultTotal">Results: ' + (x.rows.length-1) + total_word +'</div><div id="PageNavigator"></div></div><table id="formatted_SearchResult" class="classformatted_SearchResult"><thead><tr><th colspan="4"></th></tr></thead><tbody>';
	for (i=1;i<=x.rows.length-1;i=i+2) {
		formatted_result = formatted_result + '<tr id="row' + (((i-1)/2)+1) + '"><td class="padding_cell"></td>';
		for (colno=0;(colno<2) && ((i+colno)<=(x.rows.length-1));colno=colno+1) {
			// start manipulating the hidden search result table for the purpose of pagination
			if (x.rows[i+colno].cells[6].innerHTML) {
				x.rows[i+colno].cells[6].innerHTML = 'Phone:&nbsp;' + x.rows[i+colno].cells[6].innerHTML + '<br/>';
			}
			if (x.rows[i+colno].cells[7].innerHTML) {
				x.rows[i+colno].cells[7].innerHTML = 'Fax:&nbsp;' + x.rows[i+colno].cells[7].innerHTML + '<br/>';
			}
			if (x.rows[i+colno].cells[8].innerHTML) {
				x.rows[i+colno].cells[8].innerHTML = 'Mobile:&nbsp;' + x.rows[i+colno].cells[8].innerHTML + '<br/>';
			}
			if (x.rows[i+colno].cells[9].innerHTML) {
				x.rows[i+colno].cells[9].innerHTML = 'Email:&nbsp;<a href="mailto:' + 
				x.rows[i+colno].cells[9].innerHTML + '">' + x.rows[i+colno].cells[9].innerHTML + '</a><br/>';
			}
			// format search result pages to be displayed
			formatted_result += '<td class="result_cell"><b>' + x.rows[i+colno].cells[0].innerHTML + '</b><br/>';
			if (x.rows[i+colno].cells[2].innerHTML) {formatted_result += x.rows[i+colno].cells[2].innerHTML + '<br />'}				
			if (x.rows[i+colno].cells[1].innerHTML) {formatted_result += x.rows[i+colno].cells[1].innerHTML + ', '}
			if (x.rows[i+colno].cells[3].innerHTML) {formatted_result += x.rows[i+colno].cells[3].innerHTML + ', '}
			formatted_result += x.rows[i+colno].cells[5].innerHTML + ' ' + x.rows[i+colno].cells[4].innerHTML + '<br/>' + 
								x.rows[i+colno].cells[6].innerHTML + x.rows[i+colno].cells[7].innerHTML + 
								x.rows[i+colno].cells[8].innerHTML + x.rows[i+colno].cells[9].innerHTML + '</td>';
		}
		if ((i+colno)==(x.rows.length) && (((x.rows.length-1)%2)==1)) {
			formatted_result = formatted_result + '<td></td><td class="padding_cell"></td></tr>';
		} else {
			formatted_result = formatted_result + '<td class="padding_cell"></td></tr>';
		}
	}
	// display the paginated page onto 'DisplaySearchResultHere' div
	DisplaySearchResult(formatted_result + '</tbody></table>');
	// reformat result text differently if 0 provider found
	if((x.rows.length-1)==0) {
		document.getElementById('SearchResultHeader').innerHTML = '<h3>No locations found.</h3>';
		replaceH3();
	} else {
		document.getElementById('SearchResultHeader').innerHTML = '<div id="SearchResultTotal">' + (x.rows.length-1) + total_word +'</div><div id="PageNavigator"></div>';
	}
	current_page = 1;
	DisplayPage(current_page);
	// only plot the map if browser support map
	if (map) {FormatSearchResultStep2()} else {document.getElementById('GoogleMapCanvas').innerHTML='<br/><b>Unfortunately your browser doesn\'t support interactive google map, however you can still view search result on the following table.</b><br/><br/>Please upgrade your browser to explore full functionality of this search page.'}
	// turn off hourglass mouse pointer
	document.body.style.cursor = "default";
	
	fixHintText('MedicalPractitionerSurname');
        fixHintText('SuburbOrPostCode');
        fixHintText('ProviderSurname');
}
// =========== STEP 2 ===== plot marker map and add location button to table
function FormatSearchResultStep2() {
	// put raw_result on document temporarily for processing
	var x = document.getElementById('SearchResult');
	var param_address;
	var param_html;
	var param_tablenameforlocationbutton;
	var param_row;
	var param_cell;
	var param_postingcacheurl;
	var delaycounter = 0;
	for (i=1;i<=x.rows.length-1;i=i+2) {
		for (colno=0;(colno<2) && ((i+colno)<=(x.rows.length-1));colno=colno+1) {
			// format how the providers details are displayed on Google Map - OpenHTMLWindow
			param_address = x.rows[i+colno].cells[1].innerHTML + ', ' +
				x.rows[i+colno].cells[3].innerHTML + ', ' + 
				x.rows[i+colno].cells[5].innerHTML + ' ' +
				x.rows[i+colno].cells[4].innerHTML;
			param_html = '<b>' + x.rows[i+colno].cells[0].innerHTML + '</b><br/>';
			if (x.rows[i+colno].cells[2].innerHTML) {param_html += x.rows[i+colno].cells[2].innerHTML + '<br />'}				
			if (x.rows[i+colno].cells[1].innerHTML) {param_html += x.rows[i+colno].cells[1].innerHTML + ', '}
			if (x.rows[i+colno].cells[3].innerHTML) {param_html += x.rows[i+colno].cells[3].innerHTML + ', '}
			param_html += x.rows[i+colno].cells[5].innerHTML + ' ' + x.rows[i+colno].cells[4].innerHTML + '<br/>' + 
						  x.rows[i+colno].cells[6].innerHTML + x.rows[i+colno].cells[7].innerHTML + 
						  x.rows[i+colno].cells[8].innerHTML + x.rows[i+colno].cells[9].innerHTML + '<br/>';
			param_tablenameforlocationbutton = 'formatted_SearchResult';
			param_row = (i+1)/2;
			param_cell = colno+1;
			param_postingcacheurl = '/HBFComApps/dispatch/geocodeCache?address=' + escape(x.rows[i+colno].cells[1].innerHTML) + 
			'&suburb=' + escape(x.rows[i+colno].cells[3].innerHTML) + '&state=' + x.rows[i+colno].cells[5].innerHTML + 
			'&postCode=' + x.rows[i+colno].cells[4].innerHTML;
			// check if there's any cached lat/long value on the table, just call AddMarker without delay
			if (x.rows[i+colno].cells[10].innerHTML && x.rows[i+colno].cells[11].innerHTML) {
				// create marker object on map and plot it - pass cached latitude and longitude from search result table 
				AddNewMarkerFromCache(escape(param_address), escape(param_html), param_tablenameforlocationbutton, 
									  param_row, param_cell, x.rows[i+colno].cells[10].innerHTML, x.rows[i+colno].cells[11].innerHTML, marker_session);
			} else {
				// create marker object on map and plot it - delay 350ms per marker plot to allow Google server to response
				delaycounter = delaycounter + 350;					
				setTimeout('AddNewMarker(\"' + escape(param_address) + '\",\"' + escape(param_html) + '\",\"' + 	
							param_tablenameforlocationbutton + '\",' + param_row +  ',' + param_cell + ',\"' +
							escape(param_postingcacheurl) + '\",' + marker_session + ')', delaycounter);
			}
		}
	}
	// display the paginated page onto 'DisplaySearchResultHere' div
	ZoomSuburbIfResultNotZero();
}
// display the formatted search result
function DisplaySearchResult(formatted_result) {
	var div = document.getElementById('DisplaySearchResultHere')
	div.innerHTML = formatted_result;
	// hide all table rows initially
	var x = document.getElementById("formatted_SearchResult");
	for (i=1; i<=x.rows.length-1; i=i+1) {
		document.getElementById('row'+i).style.display='none';
	}
}
// pagination
function DisplayPage(page_no) {
	var x = document.getElementById("formatted_SearchResult");
	var navlinks = "";
	var navlinks_pagenos = 4;
	var lastpage = Math.round(0.4+(x.rows.length-1)/row_per_page);
	// hide previous rows
	for (i=(current_page-1)*row_per_page+1; (i<=current_page*row_per_page) && (i<=x.rows.length-1); i=i+1) {
		document.getElementById('row'+i).style.display='none';
	}
	// show selected page
	for (i=(page_no-1)*row_per_page+1; (i<=page_no*row_per_page) && (i<=x.rows.length-1); i=i+1) {
		document.getElementById('row'+i).style.display='';
	}
	// generate all pagination links if search result is not zero
	current_page = page_no;
	if ((x.rows.length-1)>0) {
		if (current_page>1) {
			navlinks = '<a href="javascript:DisplayPage('+(current_page-1)+')">Previous Page</a>'
		} else {
			navlinks = 'Previous Page'
		}
		// generate prev page nos links if any
		if (lastpage-current_page<navlinks_pagenos) {
			for(j=current_page-(navlinks_pagenos-lastpage+current_page-1); j<current_page; j++) {
				if (j>=1) {
					navlinks = navlinks + '<span class="PageNos">&nbsp;&nbsp;<a href="javascript:DisplayPage('+j+')">' + j + '</a>&nbsp;&nbsp;</span>&nbsp;|&nbsp;';
				}
			}
		}
		// underline current page no
		navlinks = navlinks + '<span class="PageNos">&nbsp;&nbsp;' + current_page + '&nbsp;&nbsp;</span>';
		for(j=current_page+1; (current_page+navlinks_pagenos>j) && (j<=lastpage); j++) {
			navlinks = navlinks + '&nbsp;|&nbsp;<span class="PageNos">&nbsp;&nbsp;<a href="javascript:DisplayPage('+j+')">'+j+'</a>&nbsp;&nbsp;</span>';				
		}
		// generate next page nos links if any
		if (current_page*row_per_page < (x.rows.length-1)) {
			navlinks += '<a href="javascript:DisplayPage('+(current_page+1)+')">Next Page</a>'
		} else {
			navlinks += 'Next Page'
		}
		// show all pagination links
		document.getElementById("PageNavigator").innerHTML = navlinks;
	}
}
// ============== searching with a combination of url_query when the 'Search' button is clicked
function Search_Optical_Providers() {
	search_type = 'opticalProvider';
	var suburb = trim(document.ProviderSearchBar.SuburbOrPostCode.value);
	var postcode = suburb;
	if (document.ProviderSearchBar.SuburbOrPostCode.title != postcode) {
		resetMap();
		if (!postcode) {
			alert('Please enter suburb name OR post code');
		} else {
			if (isNaN(postcode)) {postcode=''} else {suburb=''}
			FetchSearchResult('/HBFComApps/dispatch/providerSearch?searchType=' + search_type + '&level=' +  
							  '&suburb=' + suburb + '&postCode=' + postcode);
		}
	}
}
function Search_Car_Repair_Providers() {
	search_type = 'repairProvider&repairProviderType=car';
	var category = document.ProviderSearchBar.Category.options[document.ProviderSearchBar.Category.selectedIndex].text;
	if (category.indexOf('All')==0) {category=''}
	var suburb = trim(document.ProviderSearchBar.SuburbOrPostCode.value);
	var postcode = suburb;
	if (document.ProviderSearchBar.SuburbOrPostCode.title == postcode) {
		postcode = '';
	}
	resetMap();
	if (!category && !postcode) {
		alert('Please select a category OR\nenter suburb name OR post code');
	} else {
		if (isNaN(postcode)) {postcode=''} else {suburb=''}
		FetchSearchResult('/HBFComApps/dispatch/providerSearch?searchType=' + search_type + '&repairCategory=' + 
						  category + '&suburb=' + suburb + '&postCode=' + postcode);
	}
}
function Search_Home_and_Content_Repair_Providers() {
	search_type = 'repairProvider&repairProviderType=homeAndContents';
	var category = document.ProviderSearchBar.Category.options[document.ProviderSearchBar.Category.selectedIndex].text;
	if (category.indexOf('All')==0) {category=''}
	var suburb = trim(document.ProviderSearchBar.SuburbOrPostCode.value);
	var postcode = suburb;
	resetMap();
	/*if (!category && !postcode) {
		alert('Please select a category OR\nenter suburb name OR post code');
	} else {
		if (isNaN(postcode)) {postcode=''} else {suburb=''}*/
	FetchSearchResult('/HBFComApps/dispatch/providerSearch?searchType=' + search_type + '&repairCategory=' + category + 
					  '&suburb=' + suburb + '&postCode=' + postcode);
	/*}*/
}
function Search_Covered_Dental_Practitioners() {
	search_type = 'dentalProvider';
	var servicetype = document.ProviderSearchBar.ServiceType.options[document.ProviderSearchBar.ServiceType.selectedIndex].text;		
	if (servicetype.indexOf('All')==0) {servicetype=''}		
	var providersurname = trim(document.ProviderSearchBar.ProviderSurname.value);
	if (document.ProviderSearchBar.ProviderSurname.title == providersurname) {
		providersurname = '';
	}
	var suburb = trim(document.ProviderSearchBar.SuburbOrPostCode.value);
	var postcode = suburb;
	if (document.ProviderSearchBar.SuburbOrPostCode.title == postcode) {
		postcode = '';
	}
	resetMap();
	if (!servicetype && !providersurname && !postcode) {
		alert('Please select a provider OR\nenter provider\'s surname OR\nenter suburb name OR post code');
	} else {
		if (isNaN(postcode)) {postcode=''} else {suburb=''}
		FetchSearchResult('/HBFComApps/dispatch/providerSearch?searchType=' + search_type + '&serviceType=' + escape(servicetype) + 
						  '&surname=' + providersurname + '&suburb=' + suburb + '&postCode=' + postcode);
	}
}
function Search_Covered_Medical_Gap_Practitioners() {
	search_type = 'medicalGapProvider';
	var speciality = document.ProviderSearchBar.Speciality.options[document.ProviderSearchBar.Speciality.selectedIndex].text;		
	if (speciality.indexOf('All')==0) {speciality=''}
	var medicalpractitionersurname = trim(document.ProviderSearchBar.MedicalPractitionerSurname.value);
	if (document.ProviderSearchBar.MedicalPractitionerSurname.title == medicalpractitionersurname) {
		medicalpractitionersurname = '';
	}
	var suburb = trim(document.ProviderSearchBar.SuburbOrPostCode.value);
	var postcode = suburb;
	if (document.ProviderSearchBar.SuburbOrPostCode.title == postcode) {
		postcode = '';
	}	
	resetMap();
	if (!speciality && !medicalpractitionersurname && !postcode) {
		alert('Please select a speciality OR\nenter medical practitioner\'s surname OR\nenter suburb name OR post code');
	} else {
	if (isNaN(postcode)) {postcode=''} else {suburb=''}
		FetchSearchResult('/HBFComApps/dispatch/providerSearch?searchType=' + search_type + '&speciality=' + speciality +
						  '&practitionerName=' + medicalpractitionersurname + '&suburb=' + suburb + '&postCode=' + postcode);
	}
}
// ============== common function to populate criteria keywords for search pages from search engine
function parseTable(raw_table) {
	var ResultArray = new Array();
	var StartHere = raw_table.indexOf('<TD>');
	var StopHere = raw_table.indexOf('</TD>');
	while ((StartHere>=0) && (StopHere>=0)) {
		ResultArray.push(raw_table.substring(StartHere+4,StopHere))
		StartHere = raw_table.indexOf('<TD>', StopHere);
		StopHere = raw_table.indexOf('</TD>', StartHere);
	}
	return(ResultArray);
}
function populateCriteriaKeywords(url,elementid) {
	httpRequest(url, function(raw_table) {
			var select_inputbox = document.getElementById(elementid);
			var keywords_array = parseTable(raw_table);
			for (i=0;i < keywords_array.length; i++) {
				//exclude Orthodontics
				if(keywords_array[i]!='Orthodontics'){
					select_inputbox.options[select_inputbox.options.length] = new Option(keywords_array[i]);
				}
			}
		}
	);
}
// ============== additional functions for suburb zoom and validation
function ZoomSuburbIfResultNotZero() {
	var postcode = document.ProviderSearchBar.SuburbOrPostCode.value;
	var suburb = document.ProviderSearchBar.SuburbOrPostCode.value;
	if (document.getElementById('formatted_SearchResult').rows.length > 1 && trim(postcode)!='' && trim(postcode)!='Suburb or Postcode') {
		if (postcode!='') {zoomAddress('WA ' + postcode + ' Australia',11)}
		if (suburb!='') {zoomAddress(suburb + ', WA, Australia',11)}
	}
}
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
// ============== additional function to display pop-up window for covered medical gap practitioners
function displayMoreInfo(providerDoh) {
	httpRequest('/HBFComApps/dispatch/providerSearch?searchType=medicalGapProviderDetails&providerDoh='+
				providerDoh, formatPopUpWindow);
}
function formatPopUpWindow(pop_up_content) {
	var pop_up = window.open('', '_blank', 'width=400,height=400,location=no,menubar=no,status=no,toolbar=no,scrollbars=yes,resizable=yes');
	with(pop_up.document) {
		write('<html><head>');
		write('<style>*{font: 0.9em verdana, arial; text-align:left;} th{background-color:#81BEF7; color:white; padding:3px;} td{padding:3px;} #table0{margin-top:20px;} #header{font-weight:bold; color:#81BEF7;} table caption{color:#81BEF7;} </style>');
		write('</head><body>');
		write('<div id="header">HBF fully covered medical practitioners</div>');
		write('<table id="table0"><tr><td>Medical Practitioner</td><td></td><tr><td>Principal Speciality</td><td></td><tr><td>Additional Specialities</td><td></td></table>');
		write(pop_up_content);
		write('</body></html>');
		// format header and column width
		var hidden_table = getElementById('PractitionerDetails');
		hidden_table.style.display = 'none';
		var table0 = getElementById('table0');
		table0.rows[0].cells[0].width = "150";
		table0.rows[0].cells[1].innerHTML = hidden_table.rows[1].cells[0].innerHTML;
		table0.rows[1].cells[1].innerHTML = hidden_table.rows[1].cells[1].innerHTML;
		table0.rows[2].cells[1].innerHTML = hidden_table.rows[1].cells[2].innerHTML;
		var table1 = getElementById('PracticeLocations');
		if(table1) {
			table1.createCaption();
			table1.caption.innerHTML = '<br/>Other Practice Locations';
			table1.rows[0].cells[0].innerHTML = 'Phone Number';
			table1.rows[0].cells[0].width = "150";
			table1.rows[0].cells[1].width = "230";
		}
		var table2 = getElementById('Anaesthetists');
		if(table2) {
			table2.createCaption();
			table2.caption.innerHTML = '<br/>Anaesthetists they work with';
			table2.rows[0].cells[1].innerHTML = 'Cover Type';
			table2.rows[0].cells[0].width = "150";
			table2.rows[0].cells[1].width = "230";
		}
		var table3 = getElementById('HospitalDetails');
		if(table3) {
			table3.createCaption();
			table3.caption.innerHTML = '<br/>Hospitals they work at';
			table3.rows[0].cells[0].width = "150";
			table3.rows[0].cells[1].width = "230";
		}
	}		
}