function initializePage(){

	//FILL DROPDOWNS
	var optionField = document.getElementById('dr_specialty_id');
	optionField.options.length=0; 
	for (var ctr = 0; ctr < launchedSpecialityArray.length; ctr++) { 
		var spId = launchedSpecialityArray[ctr][0];
		var spName = launchedSpecialityArray[ctr][1];
		optionField.options[ctr]=new Option(spName, spId, false, false);
	}

	optionField = document.getElementById('dr_visit_reason_id');
	optionField.options.length=0; 
	var dentistVisitReasons = reasonsForVisit[1];
	for (var ctr = 0; ctr < dentistVisitReasons.length; ctr++) { 
		var reason = dentistVisitReasons[ctr];
		var reasonId = reason[0];
		var reasonDesc = reason[1];
		optionField.options[ctr]=new Option(reasonDesc, reasonId, false, false);
	}
	optionField = document.getElementById('insurance_id');
	optionField.options.length=0; 
	for (var ctr = 0; ctr < dentistInsuranceProviders.length; ctr++) { 
		optionField.options[ctr]=new Option(dentistInsuranceProviders[ctr][1], dentistInsuranceProviders[ctr][0], false, false); 
	}

	optionField = document.getElementById('plan_id');
	optionField.options.length=1; 
	optionField.options[0] = new Option("I'll fill this out later", -1, false, false); 

	//Create array of filter element values;
	//elementValues = retrieveSearchPageElementValues()

	//document.getElementById('distancefrom').value = '19103';
	//distancefromChange(document.getElementById('distancefrom').value);

	//Call Ajax function to post the values to DB
	//callAjax("default","getDoctors.php",elementValues);

}

function dialog_setting (type,dialoglink,linkid,tdcount,trcount,pgcount) {

	$(dialoglink).dialog({
		autoOpen: false,
		width: 350
	});

	if (type=='map') {
		//initialize_map('JFK' ,'PHL',tdcount,trcount);
	}
	// Dialog Link
	$(linkid).click(function(e){
	/*
	if(tdcount == 0) {
	 left=e.pageX;
	} else if (tdcount == 1) {
	 left=e.pageX-300;
	} else if (tdcount == 2) {
	 left=e.pageX-500;
	} else {
	 left=e.pageX-600;
	}
	if(trcount == 0) {
	 top=e.pageY;
	} else if (trcount == 1) {
	 top=e.pageY-50;
	} else if (trcount == 2) {
	 top=e.pageY-300;
	} else {
	 top=e.pageY-500;
	}
	*/
	  
	  //$(dialoglink).dialog('option', 'position', [left,top]);
	  $(dialoglink).dialog('option', 'width', 350);
	  $(dialoglink).dialog('option', 'height', 250);
	  $(dialoglink).dialog('open');
	  return false;
	});
}

function callAjax(elementType, postUrl, postData){
	//call the jquery ajax function
	//$('#rightcolumn').css({opacity:.4,background:"#FFFFFF"});
        $('#loader_dialog').dialog('open');
	$('#loader_dialog').html('<div class=title  id="dialogloading"> <BR><BR>Searching earliest open appointments. Please Wait...<BR> <img src="images/loader.gif" alt="currently loading" /></div>'); 

	//$('#rightcolumn').before('<div class=title  id="loading"> <BR><BR>Loading, Please Wait...<BR> <img src="images/loader.gif" alt="currently loading"></div>');
	$.ajax({
			url:postUrl,
			type:'POST',
			data:postData,
			success: function(result){												
			//	$('#response').remove();
			//	$('#rightcolumn').append('<p id="response">'+result+'<p>');
				$('#rightcolumn').html(result);
				//$('#loading').fadeOut(300,function(){
				
					//$('#rightcolumn').css({opacity:1,background:""});
				//$(this).remove();
				//});
				$('#dialogloading').fadeOut(300,function(){
					$(this).remove();
				});
				$('#loader_dialog').dialog('close');
			}

			});	
}

function retrieveSearchPageElementValues(){
	//RETRIEVE ELEMENT VALUES
	var orgId=$("#orgid").val();
	var docName=$("#doctorname").val();
	var docSplty=$("#dr_specialty_id").val();
	var docVisitReason=$("#dr_visit_reason_id").val();
	var docInsurance=$("#insurance_id").val();
	var docInsuranceplan=$("#plan_id").val();
	var distance=$("#distance").val();
	distance = distance.split("<")[1].split(" ")[1];
	var startDate=$("#startdatepicker").val();
	//var endDate=$("#enddatepicker").val();
	var endDate="12/31/2030";
	var timeRange=$("#timerange").val();
	var mon = 0;
	if (document.getElementById('mon').checked) {
		mon = 1;
	}
	var tue = 0;
	if (document.getElementById('tue').checked) {
		tue = 1;
	}
	var wed = 0;
	if (document.getElementById('wed').checked) {
		wed = 1;
	}
	var thr = 0;
	if (document.getElementById('thr').checked) {
		thr = 1;
	}
	var fri = 0;
	if (document.getElementById('fri').checked) {
		fri = 1;
	}
	var sat = 0;
	if (document.getElementById('sat').checked) {
		sat = 1;
	}
	var sun = 0;
	if (document.getElementById('sun').checked) {
		sun = 1;
	}
	var fromaddressLat=$("#distancefromLat").val();
	var fromaddressLng=$("#distancefromLng").val();
	if(docName) {
		var docPracId=$("#docPracId").val();
		var docPracIdType=$("#docPracIdType").val();
	} else {
		var docPracId = -1;
	}
	var defaultValue="test";


	//Assign default Values if empty
	if(!docName){
		docName=defaultValue;
	}
	if(!docSplty){
		docSplty=defaultValue;
	}
	if(!docVisitReason){
		docVisitReason=defaultValue;
	}
	if(!docInsurance){
		docInsurance=defaultValue;
	}
	if(!docInsuranceplan){
		docInsuranceplan=defaultValue;
	}
	if(!distance){
		distance=defaultValue;
	}
	if(!startDate){
		startDate=defaultValue;
	}
	if(!endDate){
		endDate=defaultValue;
	}
	if(!timeRange){
		timeRange=defaultValue;
	}
	if(!fromaddressLat){
		fromaddressLat=350;
	}
	if(!fromaddressLng){
		fromaddressLng=350;
	}

	//Generate an array of key value pairs of filter element values			
	filterValuesArray={"key_orgid": orgId, "key_docName" : docName, "key_docPracId" : docPracId, "key_docPracIdType" : docPracIdType, "key_docSplty" :docSplty, "key_docVisitReason" : docVisitReason,
		"key_docInsurance" : docInsurance,	"key_docInsuranceplan" :docInsuranceplan, "key_distance" : distance,
		"key_startDate" :startDate, "key_endDate" :endDate, "key_timeRange" :timeRange, "key_fromaddressLat" : fromaddressLat, "key_fromaddressLng" : fromaddressLng, "key_mon" : mon, "key_tue" : tue, "key_wed":wed, "key_thr":thr, "key_fri":fri, "key_sat":sat, "key_sun":sun};
	

/*	//Test for printing array values
	for (key in filterValuesArray)
	{
		//document.write("For the key " + key + " element value is " + filterValuesArray[key]+"\n");
		//alert ("key is : " + key + " : Value is : " + filterValuesArray[key]);
	}

	alert ("Loaded Filter Element Values into Array"); 
*/
	//$('#doctorname').val('');
	//$('#docPracId').val(-1);
	//$('#docPracIdType').val('');
	setTimeout("$('#suggestions').hide();", 200);

	return filterValuesArray;
}

function callGetDoctors(elemid) {
	param = [elemid];
	var specialtyId=$("#dr_specialty_id").val();
	var address=$("#distancefrom").val();
	isLaunched("loader_dialog", address, specialtyId,callGetDoctorsInternal,param);
}

function callGetDoctorsInternal(elemid) {
	var elementValues = retrieveSearchPageElementValues(); 
	callAjax(elemid,"getDoctors.php",elementValues);
}

function changeReasonsForVisit( selected) {		       
	var newReasons = reasonsForVisit[selected]; 
	var len = newReasons.length;
	var optionField = document.getElementById('dr_visit_reason_id');
	optionField.options.length=0; 
	for (var ctr = 0; ctr < newReasons.length; ctr++) { 
		var reason = newReasons[ctr];
		var reasonId = reason[0];
		var reasonDesc = reason[1];
		optionField.options[ctr]=new Option(reasonDesc, reasonId, false, false);
	} 
}

function changeInsuranceProvider(insuranceElemId, planElemId, selected, page, mInsuranceId, mInsurancePlanId, dInsuranceId, dInsurancePlanId) {
	if(!mInsuranceId && mInsuranceId!=0) {
		mInsuranceId = -1;
	}
	if(!mInsurancePlanId && mInsurancePlanId!=0) {
		mInsurancePlanId = -1;
	}
	if(!dInsuranceId && dInsuranceId!=0) {
		dInsuranceId = -1;
	}
	if(!dInsurancePlanId && dInsurancePlanId!=0) {
		dInsurancePlanId = -1;
	}
	var optionField = document.getElementById(insuranceElemId);
	optionField.options.length=0; 
	var selectedIndex = 0;
	var planId = -1;
	var insuranceId = -1;
	 if(selected == 1) {
		for (var ctr = 0; ctr < dentistInsuranceProviders.length; ctr++) { 
			optionField.options[ctr]=new Option(dentistInsuranceProviders[ctr][1], dentistInsuranceProviders[ctr][0], false, false); 
			if(dInsuranceId == dentistInsuranceProviders[ctr][0]) {
				selectedIndex = ctr;
			}
		}
		optionField.selectedIndex = selectedIndex;
		planId = dInsurancePlanId;
		insuranceId = dInsuranceId;
	 } else {
		for (var ctr = 0; ctr <generalInsuranceProviders.length; ctr++) { 
			optionField.options[ctr]=new Option(generalInsuranceProviders[ctr][1], generalInsuranceProviders[ctr][0], false, false); 
			if(mInsuranceId == generalInsuranceProviders[ctr][0]) {
				selectedIndex = ctr;
			}
		}
		optionField.selectedIndex = selectedIndex;
		planId = mInsurancePlanId;
		insuranceId = mInsuranceId;
	 } 
	 if(page != "home") { 
		 changePlans(planElemId, insuranceId, planId);
	 }
}
 
function changePlans(planElemId,  selected, selectedPlanVal) {
	if(!selectedPlanVal && selectedPlanVal!=0) {
		selectedPlanVal = -1;
	}
	var optionField = document.getElementById(planElemId);
	selectedPlanIndex = 0;
	if (selected == -1) { 
		optionField.options.length=1; 
		optionField.options[0] = new Option("", -1, false, false); 
	} 
	else if (selected == -2) { 
		optionField.options.length=1; 
		optionField.options[0] = new Option("", -2, false, false); 
	} 
	else { 
		optionField.options.length=0; 
		var newPlans =insurancePlanNames[selected]; 
		optionField.options[0] = new Option("", -1, false, false); 
		//var defaultPlan = insurancePlanDefault[selected]; 
		for (var ctr = 0; ctr < newPlans.length; ctr++) { 
			//optionField.options[ctr]=new Option(newPlans[ctr], newPlans[ctr], false, newOptions[ctr]==defaultPlan); 
			var planInfo = newPlans[ctr];
			var planId = planInfo[0];
			var planName = planInfo[1];
			optionField.options[ctr+1]=new Option(planName, planId, false, false);
			if(selectedPlanVal==planId) {
				selectedPlanIndex = ctr+1;
			}
		} 
	} 
	optionField.selectedIndex = selectedPlanIndex;

}

function changeDocInsuranceStatus(docInsuranceStatusDivId, insurancePlanElemId, insuranceProviderElemId, providerId, planId) {
	var insInfoProvided = 0;
	if(providerId==undefined) { 
		providerId = $("#"+insuranceProviderElemId).val(); 
		planId = $("#"+insurancePlanElemId).val(); 
	} else {
		insInfoProvided = 1;
		var optionField = document.getElementById(insuranceProviderElemId);
		for(var i=0; i<optionField.options.length; i++) {
			if(optionField.options[i].value == providerId) {
				optionField.selectedIndex = i; 
				changePlans(insurancePlanElemId, providerId, planId);
			}
		}
	}

	var optionField = document.getElementById(insuranceProviderElemId);
	var providerName = optionField.options[optionField.selectedIndex].text
	optionField = document.getElementById(insurancePlanElemId);
	var planName = optionField.options[optionField.selectedIndex].text
	if(providerId == -2) {
		planId = providerId;
		planName = providerName;
	}
	document.getElementById('insuranceProviderId').value = providerId;
	document.getElementById('insurancePlanId').value = planId;
	document.getElementById('insuranceProviderName').value = providerName;
	document.getElementById('insurancePlanName').value = planName;

	optionField = document.getElementById('insurance_id');
	if(optionField) { 
		for(var i=0; i<optionField.options.length; i++) { 
			if(optionField.options[i].value == providerId) { 
				optionField.selectedIndex = i; 
				changePlans('plan_id', providerId, planId);
			}
		}
	}

	if(planId == -1 || insInfoProvided) {
		dontChangeInsPlan = 0;
	} else {
		dontChangeInsPlan = 1;
	}


	if(providerId == -1) {
		$('#'+docInsuranceStatusDivId).html("Select Insurance");
	} else if(planId == -1) {
		$('#'+docInsuranceStatusDivId).html("Select Insurance Plan");
	} else {
		var covStatus = docInsuranceInfoArray[planId];
		var covStatusText;
		var covStatusImage;
		if(!covStatus) { 
			covStatusText = "Unknown";
			covStatusImage = "/images/ico/help.ico";
		} else {
			covStatusText = covStatus[0]; 
			covStatusImage = covStatus[1];
		}
		$('#'+docInsuranceStatusDivId).html("<img align=middle src="+covStatusImage+" width=24 alt='"+covStatusText+"' title='Coverage: "+covStatusText+"' /><span class=description>"+covStatusText+"</span>");
	}
}


function distancefromChange(address) {	
	var gdir = new GDirections();
	GEvent.addListener(gdir, "error", catchErrors);
	var dist;
	var eventListener = GEvent.addListener(gdir, "load", function() { 
			var geocoder = new GClientGeocoder(); 
			var latLngPt; 
			GEvent.addListener(geocoder, "getLatLng", catchErrors); 
			geocoder.getLatLng(  address,  function(pt) { 
				if(!pt) {
					alert("Please enter some valid address");
				} else {
					latLngPt = pt;
					document.getElementById('distancefromLat').value = latLngPt.lat();
					document.getElementById('distancefromLng').value = latLngPt.lng();

					callGetDoctors("distancefrom");
					//elementValues=retrieveSearchPageElementValues();
					//callAjax("distancefrom","getDoctors.php",elementValues);
				}  
				delete geocoder;
			}); 

			delete gdir; 
			return; 
	}); 

	var refAddress = "19104";
	var direction_query = "from:&apos;" + address +"&apos; to:&apos;"+ refAddress+"&apos;"; 
	gdir.load(direction_query);

}

function catchErrors(){ 
	if (this.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {
		alert("Please check the address. No corresponding geographic location could be found for the specified address."); 
	} else if (this.getStatus().code == G_GEO_SERVER_ERROR) 
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + this.getStatus().code); 
	else if (this.getStatus().code == G_GEO_MISSING_QUERY) 
		alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + this.getStatus().code); 
	else if (this.getStatus().code == G_GEO_BAD_KEY) 
		alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + this.getStatus().code); 
	else if (this.getStatus().code == G_GEO_BAD_REQUEST) 
		alert("A directions request could not be successfully parsed.\n Error code: " + this.getStatus().code);
}


/*
function dialog_setting_waitlist (dialoglink,linkid) {
    $(dialoglink).dialog({
        autoOpen: false,
        width: 350
    });
    // Dialog Link
    $(linkid).click(function(e){
      //$(dialoglink).dialog('option', 'position', [left,top]);
      $(dialoglink).dialog('option', 'width', 250);
      $(dialoglink).dialog('option', 'height', 600);
      $(dialoglink).load("leftcolumn_dialog.php");
      $(dialoglink).dialog('open');
    });
}
*/


var __last_page_index=0
function pageselectCallback (page_index, jq) {
	
	for(var i = 0; i<6; i++) {
		if($('#calendarTable'+i).length > 0) {
			var id="calendarTable"+i; 
			var elem = document.getElementById(id);
			elem.parentNode.removeChild(elem);
		}
		if($('#calendarPagination'+i).length > 0) {
			var id="calendarPagination"+i; 
			var elem = document.getElementById(id);
			elem.parentNode.removeChild(elem);
		}
		if($('#calendarDialog'+i).length > 0) {
			var id="calendarDialog"+i; 
			var elem = document.getElementById(id);
      			$('#calendarDialog'+i).dialog('destroy');
			elem.parentNode.removeChild(elem);
		}
		if($('#dist'+i).length > 0) {
			var id="dist"+i; 
			var elem = document.getElementById(id);
			elem.parentNode.removeChild(elem);
		}
		/*
		if($('#FAtimeSlotDialog'+i+'1').length > 0) {
			var id="FAtimeSlotDialog"+i+'1'; 
			var elem = document.getElementById(id);
			elem.parentNode.removeChild(elem);
		}
		if($('#FAtimeSlotDialog'+i+'2').length > 0) {
			var id="FAtimeSlotDialog"+i+'2'; 
			var elem = document.getElementById(id);
			elem.parentNode.removeChild(elem);
		}
		if($('#FAtimeSlotDialog'+i+'3').length > 0) {
			var id="FAtimeSlotDialog"+i+'3'; 
			var elem = document.getElementById(id);
			elem.parentNode.removeChild(elem);
		}
		if($('#FAtimeSlotDialog'+i+'4').length > 0) {
			var id="FAtimeSlotDialog"+i+'4'; 
			var elem = document.getElementById(id);
			elem.parentNode.removeChild(elem);
		}
		*/
		if($('#profileDialog'+i).length > 0) {
			var id="profileDialog"+i; 
			var elem = document.getElementById(id);
			elem.parentNode.removeChild(elem);
		}
		if($('#numSlots'+i).length > 0) {
			var id="numSlots"+i; 
			var numSlots = document.getElementById(id);
			for(j=0; j<numSlots; j++) {
				/*
				if($('#timeSlotDialog'+i+j).length > 0) {
					var slotId = "timeSlotDialog"+i+j;
					var elem = document.getElementById(id);
					elem.parentNode.removeChild(elem);
				}
				*/
			}
		}
	}
	//alert(resultstring[0]);
	//
	$('#rightcolumn').html(resultstring[page_index]);
	//$('#rightcolumn').src = ("renderSearchRightPage.php"+resultstring[0]);
	//document.getElementById('rightcolumn').src = "renderSearchRightPage.php"+resultstring[0];
	var userAddress = document.getElementById('distancefrom').value;
	var startDocIndex = page_index*6;
	var index = 0;
	for(var i = startDocIndex; i<startDocIndex+6; i++) {
		if($('#dist'+index).length > 0) { 
			docDistDiv = document.getElementById('dist'+index); 
			//alert("getDist called ua:" + userAddress + " da:" + doctorsArray[i]['address']);
			getDistance('dist'+index, doctorsArray[i]['name'], userAddress, doctorsArray[i]['address']);
		}
		index++
	}

	index = 0;
	for(var i = startDocIndex; i<startDocIndex+6; i++) {
		var docCalendarstring = allDocsCalendarstring[i];
		if(docCalendarstring) { 
			if(onePageDocsCalendarstring[index] && onePageDocsCalendarstring[index].length > 0) { 
				delete onePageDocsCalendarstring[index]; 
			}
			onePageDocsCalendarstring[index] = new Array();
			for(var wi=0;wi<docCalendarstring.length;wi++) {
				onePageDocsCalendarstring[index][wi] = docCalendarstring[wi];
			}
		}
		index++;
	}
	//alert(document.getElementById("calendarTable0"));
}

/*
function openCalendarDialog(calendarDialogId, calendarTableId, docIndexOnPage, docName) {
    $('#'+calendarDialogId).dialog({
        autoOpen: false,
	buttons: {
		Close: function() { $(this).dialog('close'); } 
	},
        width: 350
    });

      var calendarArray = onePageDocsCalendarstring[docIndexOnPage];
      var numWeeks = calendarArray.length;

      $('#'+calendarDialogId).dialog('option', 'width', 550);
      $('#'+calendarDialogId).dialog('option', 'height', 250); 
      $('#'+calendarDialogId).dialog('open');

      var calendarTableId = "calendarTable"+docIndexOnPage;
      var calendarPaginationId = "calendarPagination"+docIndexOnPage;

      var htmlStr = "<div><div class=doctor-name>"+docName+" &nbsp;&nbsp;&nbsp;Calendar</div><BR><div id="+calendarPaginationId+" class=mypagination style='float:right'></div><BR><div id="+calendarTableId+">"+calendarArray[0]+"</div></div>";

      $('#'+calendarDialogId).html(htmlStr);

      if(docIndexOnPage == 0) { 
	      $("#"+calendarPaginationId).pagination(numWeeks, {callback: calendarPageSelectCB0});
      } else if(docIndexOnPage == 1) {
	      $('#'+calendarPaginationId).pagination(numWeeks, {callback: calendarPageSelectCB1});
      } else if(docIndexOnPage == 2) {
	      $('#'+calendarPaginationId).pagination(numWeeks, {callback: calendarPageSelectCB2});
      } else if(docIndexOnPage == 3) {
	      $('#'+calendarPaginationId).pagination(numWeeks, {callback: calendarPageSelectCB3});
      } else if(docIndexOnPage == 4) {
	      $('#'+calendarPaginationId).pagination(numWeeks, {callback: calendarPageSelectCB4});
      } else if(docIndexOnPage == 5) {
	      $('#'+calendarPaginationId).pagination(numWeeks, {callback: calendarPageSelectCB5});
      } 


      return false;
}
*/
function closeReviewDialog() {
	$('#review_dialog').dialog('close');
}
function openReviewDialog(docPracId) {
	
	$('#review_dialog').dialog('option', 'width', 500); 
	$('#review_dialog').dialog('option', 'height', 400); 
	$('#review_dialog').dialog('open');
	

	var postData = {"key_docPracId" : docPracId}; 
	$.ajax({
		url:"createDocPracReview.php",
		type:'POST',
		data:postData,
		success: function(result){												
			$('#response').remove(); 
			var htmlStr = result; 
			$('#review_dialog').html(htmlStr);
		} 
	});	
}

function openCalendarDialog(docPracId, docName, reasonId, startDate, endDate, startTime, endTime) {
	$('#calendar_dialog').dialog(
			{ autoOpen: false, width: 350, modal: false }
			); 
	
	$('#calendar_dialog').dialog('option', 'width', 550); 
	$('#calendar_dialog').dialog('option', 'height', 300); 
	$('#calendar_dialog').dialog('open');
	

	var postData = {"key_docPracId" : docPracId, "key_reasonId" : reasonId, "key_startDate" : startDate, "key_endDate" : endDate, "key_startTime": startTime, "key_endTime" : endTime}; 
	$.ajax({
		url:"createDocPracBookingCalendar.php",
		type:'POST',
		data:postData,
		success: function(result){												
			$('#response').remove(); 
			var htmlStr = result+"<div><div class=doctor-name>"+docName+" &nbsp;&nbsp;&nbsp;Full Open Calendar <BR><span class=title style='color:#FF9900;background-color:#FFFFFF;height:25;text-align:left'> Click time below to book appointment, INSTANTLY and FREE </span></div><BR><BR><div id=calendarPagination class=mypagination style='float:right'></div><BR><BR><div id=calendarTable></div></div>"; 
			$('#calendar_dialog').html(htmlStr);
			numWeeks = docCalendarArray.length;
			$('#calendarPagination').pagination(numWeeks, {callback: calendarWeekSelectCB, divId: 'calendarTable', valueArray: docCalendarArray})
			$('#loading').fadeOut(500,function(){
			$(this).remove();
			});
		} 
	});	
}

function calendarPageSelectCB0(weekIndex, jq) {
	$('#calendarTable0').html(onePageDocsCalendarstring[0][weekIndex]);
}
function calendarPageSelectCB1(weekIndex, jq) {
	$('#calendarTable1').html(onePageDocsCalendarstring[1][weekIndex]);
}
function calendarPageSelectCB2(weekIndex, jq) {
	$('#calendarTable2').html(onePageDocsCalendarstring[2][weekIndex]);
}
function calendarPageSelectCB3(weekIndex, jq) {
	$('#calendarTable3').html(onePageDocsCalendarstring[3][weekIndex]);
}
function calendarPageSelectCB4(weekIndex, jq) {
	$('#calendarTable4').html(onePageDocsCalendarstring[4][weekIndex]);
}
function calendarPageSelectCB5(weekIndex, jq) {
	$('#calendarTable5').html(onePageDocsCalendarstring[5][weekIndex]);
}

function calendarWeekSelectCB(wi, js, divId, calArray) {
	$('#'+divId).html(calArray[wi]);
}

function updateDocCalendar(docPracId, reasonId) {
	var calendar = docCalendarArray[reasonId];
	var numWeeks = calendar.length;
	if(numWeeks == 0) {
		var htmlStr = "<div class=description style=color:red>No open appointments</div>";
		calendar[0] = htmlStr;
		$('#docCalPagination'+docPracId).pagination(1, {callback: calendarWeekSelectCB, divId: 'docCalendar'+docPracId, valueArray: calendar})
	} else { 
		$('#docCalPagination'+docPracId).pagination(numWeeks, {callback: calendarWeekSelectCB, divId: 'docCalendar'+docPracId, valueArray: calendar})
	}
}

function dialog_onclickconfirmation(event, timeSlotId, userId, insurancePlanId, reasonId, userAddress, userPatientFirstName, userPatientLastName, docPracId) { 
	if(event.preventDefault) 
	{
		event.preventDefault(); 	
	} else {
		event.returnValue = false;
	}

	var strInsurancePlan = insurancePlanId;
	var strInsuranceProvider = -1;
	var strVisitReason = reasonId;
	var startAddress = userAddress;
	var patientFirstName = userPatientFirstName;
	var patientLastName = userPatientLastName;
	if(strInsurancePlan == -1 || strInsurancePlan==undefined) {
		if(document.getElementById('plan_id')) { 
			strInsurancePlan = document.getElementById('plan_id').value;	
			strInsuranceProvider = document.getElementById('insurance_id').value;	
			if(document.getElementById('dr_visit_reason_id')) { 
				strVisitReason = document.getElementById('dr_visit_reason_id').value;  
				startAddress = document.getElementById('distancefrom').value;  
			} 
		}
	} 
	document.location.href ="/secureConfirmation.php?key_slotId="+timeSlotId + "&key_visitReason="+strVisitReason+ "&key_insurancePlanId="+ strInsurancePlan+"&key_insuranceProviderId=" + strInsuranceProvider+ "&key_userFromAddress=" + startAddress+ "&key_patientFirstName="+ patientFirstName +"&key_patientLastName=" + patientLastName +"&key_docPracId=" + docPracId;
       return;	

	/*
	if(strInsurancePlan==-1) {
		alert("Please first provide your insurance details\nin the filter results section before booking an appointment");
		$('#insurance_id').focus();

		return 0;
	}
	*/
//	if(typeof( window[ 'docInsurancePlanIdArray' ] )!=undefined && strInsurancePlan!=-2) {
//		var found = 0;
//		for(var i=0;i<docInsurancePlanIdArray.length;i++) {
//			if(docInsurancePlanIdArray[i] == strInsurancePlan) {
//				found = 1;
//			}
//		}
//		if(!found) {
//			alert("The insurance you have entered is not accepted by the doctor");
//			$('#insurance_id').focus();
//			return 0;
//		}
//	}



	//if($('#apptforself').length > 0) { 
	//	var id='apptforself'; 
	//	var elem = document.getElementById(id); 
	//	elem.parentNode.removeChild(elem); 
	//}
	
	$('#confirmationdiv').dialog(
			{ autoOpen: false, width: 350, modal: true }
			); 
	if(document.getElementById('insurance_id')) { 
		$('#confirmationdiv').bind('dialogbeforeclose', function(event, ui) { 
			callGetDoctorsInternal(); 
		});
	}
	
	$('#confirmationdiv').dialog('option', 'width', 650); 
	$('#confirmationdiv').dialog('option', 'height', 550); 
	$('#confirmationdiv').dialog('open'); 
	var postData = {"key_slotId" : timeSlotId, "key_visitReason" : strVisitReason, "key_insurancePlanId" : strInsurancePlan, "key_insuranceProviderId" : strInsuranceProvider, "key_userFromAddress" : startAddress, "key_patientFirstName": patientFirstName, "key_patientLastName" : patientLastName, "key_docPracId" : docPracId}; 
	$.ajax({
			url:"confirmationPage.php",
			type:'GET',
			data:postData,
			success: function(result){												
				$('#response').remove();
				$('#confirmationdiv').html(result);
				$('#loading').fadeOut(500,function(){
				$(this).remove();
				});
			}, 
			error: function (data, status, e)
                		{
                    		alert(e);
                		}
			});	
	return false;
}

function dialog_setting_docinfo (event, dialoglink,doctorPracticeId) {
	if(event.preventDefault) 
	{
		event.preventDefault(); 	
	} else {
		event.returnValue = false;
	}
    // Dialog Link
      //$(dialoglink).dialog('option', 'position', [left,top]);
      $('#'+dialoglink).dialog('option', 'width', 700);
      $('#'+dialoglink).dialog('option', 'height', 500); 
      $('#'+dialoglink).dialog('open');
      var postData = {"key_docPracId" : doctorPracticeId};
      $('#'+dialoglink).append('<img src="images/loader.gif" alt="currently loading" id="loading">');
      $.ajax({
			url:"docprofile_dialog.php",
			type:'GET',
			data:postData,
			success: function(result){												
				$('#response').remove();
				$('#'+dialoglink).html(result);

				$('#loading').fadeOut(300,function(){
				$(this).remove();
				});
			}

			});	
      return false;


}

/*
function patientdetailshide(){
	if(document.getElementById('apptforself').checked){
		if(document.getElementById('patientdob')) {
			userdob = document.getElementById('patientdob').value;
		}
		var patientfirstname = "";
		var patientlastname = "";
		var patientdob = "";
		document.getElementById('patientfirstname').disabled = false;
		document.getElementById('patientlastname').disabled = false;
		if(document.getElementById('patientfirstnameOptions')) { 
			document.getElementById('patientfirstnameOptions').disabled = false;
			patientfirstname = document.getElementById('patientfirstnameOptions').options[0].value;
			document.getElementById('patientfirstnameOptions').selectedIndex = 0;
		}
		if(document.getElementById('patientlastnameOptions')) { 
			document.getElementById('patientlastnameOptions').disabled = false;
			patientlastname = document.getElementById('patientlastnameOptions').options[0].value;
			document.getElementById('patientlastnameOptions').selectedIndex = 0;
		}
		document.getElementById('patientfirstname').value = patientfirstname;
		document.getElementById('patientlastname').value = patientlastname;
		if(patientName2DobArray[patientfirstname + ' ' + patientlastname]) {
			document.getElementById('patientdob').value = patientName2DobArray[patientfirstname + ' ' + patientlastname];
		}

	}else{
		if(document.getElementById('patientdob')) {
			document.getElementById('patientdob').value = userdob;
		}
		document.getElementById('patientfirstname').value = document.getElementById('userfirstname').value;
		document.getElementById('patientlastname').value = document.getElementById('userlastname').value;
		patientfirstname = document.getElementById('userfirstname').value;
		patientlastname = document.getElementById('userlastname').value;

		document.getElementById('patientfirstname').disabled = true;
		document.getElementById('patientlastname').disabled = true;
		if(document.getElementById('patientfirstnameOptions')) { 
			document.getElementById('patientfirstnameOptions').disabled = true;
		}
		if(document.getElementById('patientlastnameOptions')) { 
			document.getElementById('patientlastnameOptions').disabled = true;
		}
	}	
	if(!dontChangeInsPlan) { 
		var insInfo = patientName2InsArray[patientfirstname + ' ' + patientlastname];
		var insProviderId = insInfo[0];
		var insPlanId = insInfo[1];
		changeDocInsuranceStatus('docInsuranceStatusDiv', 'appt_plan_id', 'appt_insurance_id', insProviderId, insPlanId);
	}


}

function updatePatientName() {
	if(!document.getElementById('apptforself').checked){
		document.getElementById('patientfirstname').value = document.getElementById('userfirstname').value;
		document.getElementById('patientlastname').value = document.getElementById('userlastname').value;
	}
}
*/


function showHideApptLoginRegisterDiv() {
	if(document.getElementById('apptRegisteredUser').checked) {
		$('.apptLoginDiv').show();
		$('.apptDetailsDiv').hide();
	} else {
		$('.apptDetailsDiv').show();
		$('.apptLoginDiv').hide();
	}
}

function confirmApptSetPatientName(inputElemId, value, pFirstNameElemId, pLastNameElemId, pDobElemId) {
	document.getElementById(inputElemId).value = value;
	var firstName;
	var lastName;
	if(document.getElementById(pFirstNameElemId) && document.getElementById(pLastNameElemId) && document.getElementById(pDobElemId)) {
		firstName = document.getElementById(pFirstNameElemId).value;
		lastName = document.getElementById(pLastNameElemId).value;
		if(patientName2DobArray[firstName + ' ' + lastName]) {
			document.getElementById(pDobElemId).value = patientName2DobArray[firstName + ' ' + lastName];
		}
	}
	if(!dontChangeInsPlan) { 
		var insInfo = patientName2InsArray[firstName + ' ' + lastName];
		var insProviderId = insInfo[0];
		var insPlanId = insInfo[1];
		changeDocInsuranceStatus('docInsuranceStatusDiv', 'appt_plan_id', 'appt_insurance_id', insProviderId, insPlanId);
	}

}

function echeck(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   alert("Please enter a valid email address")
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   alert("Please enter a valid email address")
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    alert("Please enter a valid email address")
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    alert("Please enter a valid email address")
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    alert("Please enter a valid email address")
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    alert("Please enter a valid email address")
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    alert("Please enter a valid email address")
		    return false
		 }

 		 return true					
	}



/**
 * DHTML phone number validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */

//START : PHONE NUMBER VALIDATION

// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;

function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function trim(s)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not a whitespace, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (c != " ") returnString += c;
    }
    return returnString;
}

function stripCharsInBag(s, bag)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function checkInternationalPhone(strPhone){
	var bracket=3
	strPhone=trim(strPhone)
	if(strPhone.indexOf("+")>1) return false
	if(strPhone.indexOf("-")!=-1)bracket=bracket+1
	if(strPhone.indexOf("(")!=-1 && strPhone.indexOf("(")>bracket)return false
	var brchr=strPhone.indexOf("(")
	if(strPhone.indexOf("(")!=-1 && strPhone.charAt(brchr+2)!=")")return false
	if(strPhone.indexOf("(")==-1 && strPhone.indexOf(")")!=-1)return false
	s=stripCharsInBag(strPhone,validWorldPhoneChars);
	return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

function validateZIP(field) {
	var valid = "0123456789-";
	var hyphencount = 0;

	if (field.length!=5 && field.length!=10) {
		alert("Please enter your 5 digit or 5 digit+4 zip code.");
		return false;
	}
	for (var i=0; i < field.length; i++) {
		temp = "" + field.substring(i, i+1);
		if (temp == "-") hyphencount++;
		if (valid.indexOf(temp) == "-1") {
			alert("Invalid characters in your zip code.  Please try again.");
			return false;
		}
		if ((hyphencount > 1) || ((field.length==10) && ""+field.charAt(5)!="-")) {
			alert("The hyphen character should be used with a properly formatted 5 digit+four zip code, like '12345-6789'.   Please try again.");
			return false;
   		}
	}
	return true;
}

//END : PHONE NUMBER VALID
//THIS FUNCTION IS CALLED FOR A SUBMIT TO DB
function submitConfirmationToDB(slotId){
//	if(!document.getElementById('apptforself').checked) {
//	       document.getElementById('patientfirstname').value = "";
//	       document.getElementById('patientlastname').value = "";
//	}	       

	var userId = document.getElementById('userId').value;
	var useremail;
	var userphone;
	var userpassword;
	var patientFirstName = -1;
	var patientLastName = -1;
	var patientDob = document.getElementById('patientdob').value; 


	if(userId == -1) { 
		if(document.getElementById('apptRegisteredUser').checked) {
			if(!document.getElementById('apptLoginInput').value) {
				alert("Please enter login email"); 
				document.getElementById('apptLoginInput').focus;
				return 0;
			}
			if(!document.getElementById('apptPasswordInput').value) {
				alert("Please enter password"); 
				document.getElementById('apptPasswordInput').focus;
				return 0;
			}
			useremail = document.getElementById('apptLoginInput').value;
			userpassword = document.getElementById('apptPasswordInput').value;

			var slotId = document.getElementById('slotId').value;
			var docPracIdElem = document.getElementById('docPracticeId');	
			var docPracId = docPracIdElem.value;
			var visitReasonId = document.getElementById('visitReasonId').value;
			var insurancePlanId = document.getElementById('insurancePlanId').value;
			var insuranceProviderId = document.getElementById('insuranceProviderId').value;
			var userFromAddress = document.getElementById('userFromAddress').value;
			//document.location.href ="/secureConfirmation.php?key_slotId="+slotId + "&key_visitReason="+visitReasonId+ "&key_insurancePlanId="+ insurancePlanId+"&key_insuranceProviderId=" +insuranceProviderId+ "&key_userFromAddress=" + userFromAddress+ "&key_useremail="+ useremail +"&key_userpassword=" + userpassword +"&key_docPracId=" + docPracId;
			var postData = {"key_slotId" : slotId, "key_visitReason" : visitReasonId, "key_insurancePlanId" : insurancePlanId, "key_insuranceProviderId" : insuranceProviderId, "key_userFromAddress" : userFromAddress, "key_useremail" : useremail, "key_userpassword" : userpassword, "key_docPracId" : docPracId};
			var postData = {"key_useremail" : useremail, "key_password" : userpassword, "key_login": 1};
			$.ajax({ 
				url:"validateUser.php", 
				type:'POST', 
				data:postData, 
				success: function(result){												
					var resultInfo = result.split("|");
					var message = resultInfo[0];
					var messageInfo = message.split("^");
					message = messageInfo[1];
					var popupBox = resultInfo[1];
					var popupBoxInfo = popupBox.split("^");
					popupBox = popupBoxInfo[1];
					if(message != '') { 
						alert('Login Failed');
						document.getElementById('apptLoginInput').focus;
					} else {
						document.location.href ="/secureConfirmation.php?key_slotId="+slotId + "&key_visitReason="+visitReasonId+ "&key_insurancePlanId="+ insurancePlanId+"&key_insuranceProviderId=" +insuranceProviderId+ "&key_userFromAddress=" + userFromAddress+ "&key_docPracId=" + docPracId;
					}
				} 
			});	
       			return false;	


			var postData = {"key_slotId" : slotId, "key_visitReason" : visitReasonId, "key_insurancePlanId" : insurancePlanId, "key_insuranceProviderId" : insuranceProviderId, "key_userFromAddress" : userFromAddress, "key_useremail" : useremail, "key_userpassword" : userpassword, "key_docPracId" : docPracId};
        		$('#modalDialog').dialog('open');
			$('#modalDialog').html('<div class=title  id="dialogloading"> <BR><BR>Please Wait...<BR> <img src="images/loader.gif" alt="currently loading" /></div>'); 
			$.ajax({ 
				url:"confirmationPage.php", 
				type:'GET', 
				data:postData, 
				success: function(result){												
					$('#modalDialog').dialog('close');
					if(result == "login failed") {
						alert("Login Failed");
						document.getElementById('apptLoginInput').focus;
						return 0;
					} else {

						$('#response').remove(); 
						$('#confirmationdiv').html(result); 
						$('#confirmationdiv').bind('dialogbeforeclose', function(event, ui) {
							callGetDoctorsInternal(); 
						});
						 
					}
				} 
			});	
			
			return false;
		} else { 
			var userfirstname;
			var userlastname;
			useremail = document.getElementById('useremail').value ;
			userareaphone = document.getElementById('userareaphone').value ;
			userphone = document.getElementById('userphone').value ;
			userphone = userareaphone+userphone;

			var insuranceProviderId = document.getElementById('appt_insurance_id').value ;
			if(insuranceProviderId == -1) {
				alert("Please fill insurance details");
				document.getElementById('appt_insurance_id').focus();
				return 0; 
			}

			var insurancePlanId = document.getElementById('appt_plan_id').value ;
			if(insurancePlanId == -1) {
				alert("Please fill insurance plan");
				document.getElementById('appt_plan_id').focus();
				return 0; 
			}

			//set default values for checkbox. ('both' option)	
			if (!validateConfirmationForm ()){
				return 0;
			}

			if(!patientDob || !isDate(patientDob)) {
				alert("Please check Patient Date of Birth");
				document.getElementById('patientdob').focus();
				return 0; 
			}
			if(!isAgeOK(patientDob)) { 
				alert("Patient should be more than 14 years old and less than 80 years old to book an appointment through DocAsap");
				document.getElementById('patientdob').focus();
				return 0; 
			}

		}
	} else {
		var insuranceProviderId = document.getElementById('appt_insurance_id').value ;
		if(insuranceProviderId == -1) {
			alert("Please fill insurance details");
			document.getElementById('appt_insurance_id').focus();
			return 0; 
		}

		var insurancePlanId = document.getElementById('appt_plan_id').value ;
		if(insurancePlanId == -1) {
			alert("Please fill insurance plan");
			document.getElementById('appt_plan_id').focus();
			return 0; 
		}

		if(!patientDob || !isDate(patientDob)) { 
			alert("Please check Patient Date of Birth");
			document.getElementById('patientdob').focus();
			return 0; 
		}
		if(!isAgeOK(patientDob)) { 
			alert("Patient should be more than 14 years old and less than 80 years old to book an appointment through DocAsap");
			document.getElementById('patientdob').focus();
			return 0; 
		}
		if(document.getElementById('userphone')) {
			if((document.getElementById('userareaphone').value)=="" || document.getElementById('userphone').value==""){
				alert("Please enter your phone number along with area code");
				document.getElementById('userareaphone').focus();
				return false;
			}else {
				phone = document.getElementById('userareaphone').value+document.getElementById('userphone').value;
				if(checkInternationalPhone(phone)){
					userphone = document.getElementById('userphone').value;		
				}else{
					alert("Please Enter a Valid Phone Number")
					document.getElementById('userareaphone').value="";
					document.getElementById('userphone').value="";
					document.getElementById('userareaphone').focus();
					return false;				
				}			

			}

			userareaphone = document.getElementById('userareaphone').value ;
			userphone = document.getElementById('userphone').value ;
			userphone = userareaphone+userphone;
		}
	}

	var pos1=patientDob.indexOf(dtCh)
	var pos2=patientDob.indexOf(dtCh,pos1+1)
	var strMonth=patientDob.substring(0,pos1)
	var strDay=patientDob.substring(pos1+1,pos2)
	var strYear=patientDob.substring(pos2+1)
	patientDob = strYear+dtCh+strMonth+dtCh+strDay;


	var postData = {"key_useremail" : useremail, "key_password" : userpassword, "key_userid" : userId, "key_slotid" : slotId, "key_userphone" : userphone, "key_userCode" : 0, "key_patientFirstName" : patientFirstName, "key_patientLastName" : patientLastName, "key_patientDob" : patientDob}; 
        $('#modalDialog').dialog('open');
	$('#modalDialog').html('<div class=title  id="dialogloading"> <BR><BR>Please Wait...<BR> <img src="images/loader.gif" alt="currently loading" /></div>'); 
	$.ajax({ 
		url:'validateUser.php', 
		type:'POST', 
		data:postData, 
		success: function(result) { 
			var resultInfo = result.split("|");
			var message = resultInfo[0];
			var messageInfo = message.split("^");
			message = messageInfo[1];
			var popupBox = resultInfo[1];
			var popupBoxInfo = popupBox.split("^");
			popupBox = popupBoxInfo[1];
			if(message != '') { 
				if(popupBox == "alert") { 
					$('#modalDialog').dialog('close');
					alert(message); 
					return 0; 
				} else if(popupBox == "confirm") { 
					var res = confirm(message); 
					if(res == false) { 
						return 0; 
					} else { 
						document.forms["apptConfirm"].submit(); 
					} 
				} else { 
					document.forms["apptConfirm"].submit(); 
				} 
			} else {
				document.forms["apptConfirm"].submit(); 
			}
		} 
	});	
	
}

var dtCh= "-";
var minYear=1900;
var maxYear=2100;

function daysInFebruary (year){ 
	// February has 29 days in any year evenly divisible by four, 
	// EXCEPT for centurial years which are not also divisible by 400.  
	return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) { 
	for (var i = 1; i <= n; i++) { 
		this[i] = 31; 
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29} 
	} 
	return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : mm-dd-yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}



//THIS FUNCTION DOES THE INPUT FIELD VALIDATION
function validateConfirmationForm () {
	//validation
	if(!validateName(document.getElementById('userfirstname').value)){
		alert ("Please check your first name");
		document.getElementById('userfirstname').focus ();
		return false;
	}else{
		userfirstname = document.getElementById('userfirstname').value;	
	}
	if(!validateName(document.getElementById('userlastname').value)){
		alert ("Please check your last name");
		document.getElementById('userlastname').focus ();
		return false;
	}else{
		userlastname = document.getElementById('userlastname').value;	
	}
	
	
	//-------------get contact preferences-----------------------------
	//If contact preference is set to 'email', check if email field is filled
	if((document.getElementById('useremail').value)==""){
		alert("Please enter your email address");
		document.getElementById('useremail').focus();
		return false;
	}else {
		if (echeck(document.getElementById('useremail').value)){
			useremail=document.getElementById('useremail').value;
			//alert (echeck(document.getElementById('useremail').value));
		}else{
			document.getElementById('useremail').value="";
			document.getElementById('useremail').focus();
			return false;
		}
	}	
	if((document.getElementById('userareaphone').value)=="" || document.getElementById('userphone').value==""){
		alert("Please enter your phone number along with area code");
		document.getElementById('userareaphone').focus();
		return false;
	}else {
		phone = document.getElementById('userareaphone').value+document.getElementById('userphone').value;
		if(checkInternationalPhone(phone)){
			userphone = document.getElementById('userphone').value;		
		}else{
			alert("Please Enter a Valid Phone Number")
			document.getElementById('userareaphone').value="";
			document.getElementById('userphone').value="";
			document.getElementById('userareaphone').focus();
			return false;				
		}			

	}


	//validate password and confirm password fields
	if((document.getElementById('userpassword').value=="")||(document.getElementById('userconfirmpassword').value=="")){
		alert("Please enter your password details");
/*
		//set focus to the empty field
		if(document.getElementById('userpassword').value==""){
			document.getElementById('userpassword').focus();
		}
		if(document.getElementById('userconfirmpassword').value=""){
			document.getElementById('userconfirmpassword').focus();
		}
		*/
		return false;
	} else { 
		var passwd = document.getElementById('userpassword').value; 
		var c_passwd = document.getElementById('userconfirmpassword').value;
		if(!validatePassword(passwd, c_passwd)) {
			document.getElementById('userpassword').value="";
			document.getElementById('userconfirmpassword').value="";
			document.getElementById('userpassword').focus();

			return false;	
		}
	}
	return true;
}

function validatePassword(password, c_password) {
	if(password != c_password) {
		alert ("Passwords don't match. Please try again."); 
		return false;	
	}else {
		//Check the password
		var wrongPsswd = 0;
		if(password.length < 8) {
			wrongPsswd = 1;
		} else {
			var count = 0;
			if(password.match(/[0-9]/)) {
				count++;
			}
			if(password.match(/[a-z]/)) {
				count++;
			}
			if(password.match(/[A-Z]/)) {
				count++;
			}
			if(password.match(/[\W_]/)) {
				count++;
			}
			if(count < 3) {
				wrongPsswd = 1;
			}
		}
		if(wrongPsswd) {
			alert ("Please check the password. Password should contain atleast 8 characters and should be composed of at least three of the following characteristics (using all four is encouraged): 1. At least one numeric character (0-9), 2. At least one lower case character (a-z), 3. At least one upper case character (A-Z), 4. At least one non-alphanumeric character (~, @, #, $, %, ^, &, *, (, ), -, =, +, ?, [, ],..)");

			return false;	
		}
	}
	return true;
}

function emailCheck (emailStr) {

/* The following variable tells the rest of the function whether or not
to verify that the address ends in a two-letter country or well-known
TLD.  1 means check it, 0 means don't. */

var checkTLD=1;

/* The following is the list of known TLDs that an e-mail address must end with. */

var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

/* The following pattern is used to check if the entered e-mail address
fits the user@domain format.  It also is used to separate the username
from the domain. */

var emailPat=/^(.+)@(.+)$/;

/* The following string represents the pattern for matching all special
characters.  We don't want to allow special characters in the address. 
These characters include ( ) < > @ , ; : \ " . [ ] */

var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

/* The following string represents the range of characters allowed in a 
username or domainname.  It really states which chars aren't allowed.*/

var validChars="\[^\\s" + specialChars + "\]";

/* The following pattern applies if the "user" is a quoted string (in
which case, there are no rules about which characters are allowed
and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
is a legal e-mail address. */

var quotedUser="(\"[^\"]*\")";

/* The following pattern applies for domains that are IP addresses,
rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
e-mail address. NOTE: The square brackets are required. */

var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

/* The following string represents an atom (basically a series of non-special characters.) */

var atom=validChars + '+';

/* The following string represents one word in the typical username.
For example, in john.doe@somewhere.com, john and doe are words.
Basically, a word is either an atom or quoted string. */

var word="(" + atom + "|" + quotedUser + ")";

// The following pattern describes the structure of the user

var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

/* The following pattern describes the structure of a normal symbolic
domain, as opposed to ipDomainPat, shown above. */

var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

/* Finally, let's start trying to figure out if the supplied address is valid. */

/* Begin with the coarse pattern to simply break up user@domain into
different pieces that are easy to analyze. */

var matchArray=emailStr.match(emailPat);

if (matchArray==null) {

/* Too many/few @'s or something; basically, this address doesn't
even fit the general mould of a valid e-mail address. */

alert("Email address seems incorrect (check @ and .'s)");
return false;
}
var user=matchArray[1];
var domain=matchArray[2];

// Start by checking that only basic ASCII characters are in the strings (0-127).

for (i=0; i<user.length; i++) {
if (user.charCodeAt(i)>127) {
alert("Ths username contains invalid characters.");
return false;
   }
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
alert("Ths domain name contains invalid characters.");
return false;
   }
}

// See if "user" is valid 

if (user.match(userPat)==null) {

// user is not valid

alert("The username doesn't seem to be valid.");
return false;
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
host name) make sure the IP address is valid. */

var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {

// this is an IP address

for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {
alert("Destination IP address is invalid!");
return false;
   }
}
return true;
}

// Domain is symbolic name.  Check if it's valid.
 
var atomPat=new RegExp("^" + atom + "$");
var domArr=domain.split(".");
var len=domArr.length;
for (i=0;i<len;i++) {
if (domArr[i].search(atomPat)==-1) {
alert("The domain name does not seem to be valid.");
return false;
   }
}

/* domain name seems valid, but now make sure that it ends in a
known top-level domain (like com, edu, gov) or a two-letter word,
representing country (uk, nl), and that there's a hostname preceding 
the domain or country. */

if (checkTLD && domArr[domArr.length-1].length!=2 && 
domArr[domArr.length-1].search(knownDomsPat)==-1) {
alert("The address must end in a well-known domain or two letter " + "country.");
return false;
}

// Make sure there's a host name preceding the domain.

if (len<2) {
alert("This address is missing a hostname!");
return false;
}

// If we've gotten this far, everything's valid!
return true;
}

function userForgotPasswordServerCall() {
	var loginEmail = document.getElementById("emailaddress").value;
	if (!emailCheck(loginEmail)) {
		return 0;
	}
	var postData = {"key_useremail" : loginEmail, "key_forgotpassword" : 1, "key_userCode" : 0};
	$.ajax({ 
		url:'validateUser.php', 
		type:'POST', 
		data:postData, 
		success: function(result) { 
			var resultInfo = result.split("|");
			var message = resultInfo[0];
			var messageInfo = message.split("^");
			message = messageInfo[1];
			var popupBox = resultInfo[1];
			var popupBoxInfo = popupBox.split("^");
			popupBox = popupBoxInfo[1];
			if(message != '') { 
				if(popupBox == "alert") { 
					alert(message); 
					$("#forgot_dialog").dialog('close');
					return 0; 
				} else if(popupBox == "confirm") { 
					var res = confirm(message); 
					if(res == false) { 
						return 0; 
					} else { 
						return 1;
					} 
				} else { 
					return 0;
				} 
			}
		} 
	});
}
function userForgotPassword() {
	var forgotpasswordhtml;
	forgotpasswordhtml ="<table><tr><td colspan=3 class=bolded align=center>Please enter your email address<HR><BR><BR></td></tr>";
	forgotpasswordhtml +="<tr><td class=title>Email: </td><td class=description><input class=description id=emailaddress></td>";
	forgotpasswordhtml +="<td style='background:orange'><a class=title href=# onClick=userForgotPasswordServerCall()>&nbsp;Submit&nbsp;</a></td></tr></table>";
			     
	$("#forgot_dialog").dialog('open');
	$("#forgot_dialog").html(forgotpasswordhtml);
	
		
}

function isLaunched(msgDivId, userAddress, specialtyId, successFunc, parameters) {
	var gdir = new GDirections();
	GEvent.addListener(gdir, "error", handleErrors);

	var launchedCitiesArray = new Array();
	var numLaunchedCities = 0;
	for(var city in city2SpecialityMapping) { 
		launchedCitiesArray.push(city);
		numLaunchedCities++;
	}

	var currentCity = 0;

	var isLaunch = 0;
	var isCityLaunch = 0;
	var isSpLaunch = 0;


	var eventListener = GEvent.addListener(gdir, "load", function() { 
		var distarray = gdir.getDistance().html.split("&"); 
		var dist = distarray[0].replace(",","");
		if(dist < 30) {
			isCityLaunch = 1;
			city = launchedCitiesArray[currentCity];
			//Check for sp launch
			for(var index in city2SpecialityMapping[city]) {
				spId = city2SpecialityMapping[city][index];
				if(spId == specialtyId) {
					argumentsList = "";
					for(var parameter in parameters) {
						argumentsList=argumentsList+","+parameter;
					}
					successFunc(argumentsList);
					return 1;
				}
			}

			var spName = specialityArray[specialtyId];
			
			var htmlStr = "<div><img src=/images/docasap_logo.jpg></div><Div class=doctor-name style='text-align:left'><BR>Thanks for using DocAsap. We have not yet launched '"+spName+"' near "+userAddress+".<BR><BR>We are quickly expanding into new specialities in the coming months. Till then, please stay tuned with our progress at <a href=http://blog.docasap.com style='color:orange'>Our Blog</a></div>";

		        $('#'+msgDivId).dialog('open');
			$('#'+msgDivId).html(htmlStr);	

			return 0; //return from eventlistener
		}

		if(currentCity < numLaunchedCities-1) {
			currentCity++;
			var dir_query = "from:&apos;" + launchedCitiesArray[currentCity] +"&apos; to:&apos;"+ userAddress+"&apos;"; 
			gdir.load(dir_query);
		} else {
			var htmlStr = "<div><img src=/images/docasap_logo.jpg></div><Div class=doctor-name style='text-align:left'><BR>Thanks for using DocAsap. Our services are currently not available at "+userAddress+".<BR><BR>We are quickly expanding into new cities in the coming months. Till then, please stay tuned with our progress at <a href=http://blog.docasap.com style='color:orange'>Our Blog</a></div>";

		         $('#'+msgDivId).dialog('open');
			 $('#'+msgDivId).html(htmlStr);	
		}

		return 0; 
	}); 


	var direction_query = "from:&apos;" + launchedCitiesArray[0] +"&apos; to:&apos;"+ userAddress+"&apos;"; 
	gdir.load(direction_query);


}

function submitUserRegistration() { 
	var userfirstname = document.getElementById('userfirstname').value ;
	var userlastname = document.getElementById('userlastname').value ;
	if(!validateName(userfirstname)) { 
		alert("Please check first name"); 
		document.getElementById('userfirstname').focus;
		return 0; 
	}
	if(!validateName(userlastname)) { 
		alert("Please check last name"); 
		document.getElementById('userlastname').focus;
		return 0; 
	}

	var useremail = document.getElementById('useremail').value ;
	if(!useremail) { 
		alert("Please enter login email"); 
		document.getElementById('useremail').focus;
		return 0; 
	}
	if (!emailCheck(useremail)) {
		alert("Please enter valid email"); 
		document.getElementById('useremail').focus;
		return 0;
	}

	var userareaphone = document.getElementById('userareaphone').value ;
	var userphone = document.getElementById('userphone').value ;
	/*
	if(!userareaphone || !userphone) { 
		alert("Please enter cellphone number with area code"); 
		document.getElementById('userareaphone').focus;
		return 0; 
	}
	if(!checkInternationalPhone(userphone)){
		alert("Please enter valid cellphone number with area code"); 
		document.getElementById('userareaphone').focus;
		return 0; 
	}
	*/
	userphone = userareaphone+userphone;

	var userpassword = document.getElementById('userpassword').value;
	var userCpassword = document.getElementById('userconfirmpassword').value;
	if(!userpassword || userpassword != userCpassword) {
		alert("Please check your password");
		document.getElementById('userpassword').focus;
		return 0; 
	}

	if(userphone) {
		var postData = {"key_useremail" : useremail, "key_userid" : -1, "key_userphone" : userphone, "key_no_appointment" : 1}; 
	} else {
		var postData = {"key_useremail" : useremail, "key_userid" : -1, "key_no_appointment" : 1}; 
	}
	$.ajax({ 
		url:'validateUser.php', 
		type:'POST', 
		data:postData, 
		success: function(result) { 
			var resultInfo = result.split("|");
			var message = resultInfo[0];
			var messageInfo = message.split("^");
			message = messageInfo[1];
			var popupBox = resultInfo[1];
			var popupBoxInfo = popupBox.split("^");
			popupBox = popupBoxInfo[1];
			if(message != '') { 
				if(popupBox == "alert") { 
					alert(message); 
					return 0; 
				} else if(popupBox == "confirm") { 
					var res = confirm(message); 
					if(res == false) { 
						return 0; 
					} else { 
						document.forms["registerForm"].submit(); 
					} 
				} else { 
					document.forms["registerForm"].submit(); 
				} 
			} else {
				document.forms["registerForm"].submit(); 
			}
		} 
	});	
}

function validateName(name) {
	if(!/^[a-zA-Z ]+$/.test(name) || name.length>20) {
		return 0;
	} else {
		return 1;
	}
}

function isAgeOK(dobStr) {
	var daysInMonth = DaysArray(12);
	var pos1=dobStr.indexOf(dtCh);
	var pos2=dobStr.indexOf(dtCh,pos1+1);
	var strMonth=dobStr.substring(0,pos1);
	var strDay=dobStr.substring(pos1+1,pos2);
	var strYear=dobStr.substring(pos2+1);
	strYr=strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1);
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1);
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);
	}
	pmonth=parseInt(strMonth);
	pday=parseInt(strDay);
	pyear=parseInt(strYr);

	today=new Date(); 
	year = today.getFullYear() ; 
	month = today.getMonth(); 
	day = today.getDate(); 

	var age;	
	if ( month < pmonth ){ 
		age = year - pyear - 1; 
	} else if ( month > pmonth ){ 
		age = year - pyear; 
	} else if ( month == pmonth ){ 
		if ( day < pday ){ 
			age = year - pyear - 1; 
		} else if ( day > pday ){ 
			age = year - pyear; 
		} else if ( day == pday ){ 
			age = year - pyear; 
		} 
	}

	if(age<14 || age>80) {
		return 0;
	} else {
		return 1;
	}
}
	
