$(document).ready(function() {
	$("#da_alert_dialog_div").dialog({bgiframe: true,
				    width: 400,
				    height: 250,
				    modal: true,
				    shadow: false,
				    autoOpen: false,
				    draggale: false,
				    resizable: false,
				    dialogClass: 'alert',
				    buttons: {
					OK: function() { $(this).dialog('close'); } 
					}
	});

	$("#da_loader_dialog_div").dialog({bgiframe: true,
				    width: 400,
				    modal: true,
				    shadow: false,
				    autoOpen: false,
				    draggale: false,
				    resizable: false
	});
});

// 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 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"});
	da_loader_open("Searching earliest open appointments.");

	//$('#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:'GET',
			data:postData,
			success: function(result){												
			//	$('#response').remove();
			//	$('#rightcolumn').append('<p id="response">'+result+'<p>');
				$('#rightcolumn_getDoctors').html(result);
				da_loader_fadeout();
				//$('#loading').fadeOut(300,function(){
				
					//$('#rightcolumn').css({opacity:1,background:""});
				//$(this).remove();
				//});
			}

	});	
}

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 fromaddress=$("#distancefrom").val();
	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={"orgid": orgId, "key_docName" : docName, "key_docPracId" : docPracId, "key_docPracIdType" : docPracIdType, "dr_specialty_id" :docSplty, "key_docVisitReason" : docVisitReason,
		"key_docInsurance" : docInsurance,	"key_docInsuranceplan" :docInsuranceplan, "key_distance" : distance,
		"key_startDate" :startDate, "key_endDate" :endDate, "key_timeRange" :timeRange, "address" : fromaddress, "user_address_lat" : fromaddressLat, "user_address_lng" : 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");
		//da_alert ("key is : " + key + " : Value is : " + filterValuesArray[key]);
	}

	da_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(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, da_select, da_selectBox_id, da_select_short) {
	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, da_select, da_selectBox_id, da_select_short);
	 }
}
 
function changePlans(planElemId,  selected, selectedPlanVal, da_select, da_selectBox_id, da_select_short) {
	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("Select Plan", -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("Select Plan", -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;

	if(da_select) {
		var select = $('select#'+planElemId);
		populate_da_select(select, da_selectBox_id, da_select_short);
	}

}

function changeDocInsuranceStatus(docInsuranceStatusDivId, insurancePlanElemId, insuranceProviderElemId, providerId, planId, insurance_right_wrong_divId, plan_right_wrong_divId) {
	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;
	}
	if(document.getElementById('insuranceProviderId')) {
		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("");

		if(insurance_right_wrong_divId) {
			document.getElementById(insurance_right_wrong_divId).className = 'answer_div wrong_answer_div';
			document.getElementById(plan_right_wrong_divId).className = 'answer_div wrong_answer_div';
		}

	} else if(planId == -1) {
		$('#'+docInsuranceStatusDivId).html("");
		if(insurance_right_wrong_divId) {
			document.getElementById(insurance_right_wrong_divId).className = 'answer_div right_answer_div';
			document.getElementById(plan_right_wrong_divId).className = 'answer_div wrong_answer_div';
		}
	} 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("<div style=position:relative;display:inline;width:25px;float:left><img align=middle style=position:relative;display:inline src="+covStatusImage+" width=24 alt='"+covStatusText+"' title='Coverage: "+covStatusText+"' /></div><div class=description style=position:relative;display:inline;width:25px;float:right >"+covStatusText+"</div>");

		if(insurance_right_wrong_divId) {
			document.getElementById(insurance_right_wrong_divId).className = 'answer_div right_answer_div';
			document.getElementById(plan_right_wrong_divId).className = 'answer_div right_answer_div';
		}
	}
}

/*
function distancefromChange(address) {	
	var geocoder = new google.maps.Geocoder();
	geocoder.geocode( { 'address': address}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			latLngPt = results[0].geometry.location;
			document.getElementById('distancefromLat').value = latLngPt.lat();
			document.getElementById('distancefromLng').value = latLngPt.lng();

			callGetDoctors("distancefrom");
		} else {
			da_alert("Please enter some valid address: Geocode was not successful for the following reason: " + status);
		}
	});
	

}
*/

function catchErrors(){ 
	if (this.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {
		da_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) 
		da_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) 
		da_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) 
		da_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) 
		da_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);
				}
				*/
			}
		}
	}
	//da_alert(resultstring[0]);
	//
	$('#rightcolumn_getDoctors').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); 
			//da_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++;
	}
	//da_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 changeVisitReason(reason_option_id, docPracId, calendar_div, calendar_pagination_div, calendar_table_div, more_div) {
	var reasonId = document.getElementById(reason_option_id).value;

	var postData = {"key_docPracId" : docPracId, "key_reasonId" : reasonId };
	$.ajax({
		url:"createDocPracBookingCalendar.php",
		type:'POST',
		data:postData,
		success: function(result){
			//var htmlStr = "<div id=calendarPagination class=mypagination></div><div id=calendarTableId class=calendarTable></div>";
			//$('#'+calendar_div).html(htmlStr);
			var resultInfo = result.split("^");
			var len = resultInfo.length;
			var numAppts = resultInfo[len-1];

			//if(numAppts > 0) {
				calendarString = resultInfo[0];
				if(docCalendarArray[docPracId]) {delete docCalendarArray[docPracId];}
				docCalendarArray[docPracId] = new Array();
				calendar = calendarString.split('@');
				for(wIndex=0; wIndex<calendar.length; wIndex++) { 
					calendar[wIndex] = calendar[wIndex].replace(/\\\'/g, "'");
					docCalendarArray[docPracId][wIndex] = calendar[wIndex];
				}
				numWeeks = docCalendarArray[docPracId].length;
				$('#'+calendar_pagination_div).pagination(numWeeks, {callback: calendarWeekSelectCB, divId: calendar_table_div, valueArray: docCalendarArray[docPracId]});
				if(document.getElementById(more_div)) {
					displayMoreButton(calendar_table_div, more_div, 141);
				}

			//} else {
				//$('#'+calendar_table_div).html('<BR>No open appointments');
				//$('#'+calendar_pagination_div).html('');
			//	numWeeks = docCalendarArray[docPracId].length;
			//	$('#'+calendar_pagination_div).pagination(numWeeks, {callback: calendarWeekSelectCB, divId: calendar_table_div, valueArray: docCalendarArray[docPracId]});
			//}

		} 
	});	
			
}

function openCalendarDialog(linkId, docPracId, docName, reasonId, startDate, endDate, startTime, endTime) {

	var body_scroll_y = document.body.scrollTop;
	var ie_browser = 0;
	if(!body_scroll_y) {
		if(document.documentElement && document.documentElement.scrollTop) {
			ie_browser = 1;
			body_scroll_y = document.documentElement.scrollTop;
		}
	}

	var position = $('#'+linkId).offset();

	var dialog_x = position.left;
	var dialog_y = position.top;

	dialog_y = dialog_y-body_scroll_y;

	$('#calendar_dialog').dialog(
			{ autoOpen: false, width: 350, modal: false }
			); 
	
	$('#calendar_dialog').dialog('option', 'width', 550); 
	$('#calendar_dialog').dialog('option', 'height', 350); 
	$('#calendar_dialog').dialog('option', 'position', [dialog_x, dialog_y]); 
	$('#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 resultInfo = result.split("^");
			var calendarString = resultInfo[0];
			var calendar = calendarString.split('@');
			for(wIndex=0; wIndex<calendar.length; wIndex++) { 
				calendar[wIndex] = calendar[wIndex].replace(/\\\'/g, "'");
				//docCalendarArray[wIndex] = calendar[wIndex];
			}

			var htmlStr = "<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></div><div id=calendarTableId class=calendarTable></div></div>"; 
			$('#calendar_dialog').html(htmlStr);
			numWeeks = calendar.length;
			$('#calendarPagination').pagination(numWeeks, {callback: calendarWeekSelectCB, divId: 'calendarTableId', valueArray: calendar})
			$('#loading').fadeOut(500,function(){
			$(this).remove();
			});
			document.body.scrollTop = body_scroll_y;
			if(ie_browser) {
				document.documentElement.scrollTop = body_scroll_y;
			}

		} 
	});	
}

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(strVisitReason == -1 || strVisitReason==undefined) {
		if(document.getElementById('dr_visit_reason_id')) { 
			strVisitReason = document.getElementById('dr_visit_reason_id').value;  
		} 
	}
	if(startAddress == -1 || startAddress == '' || startAddress==undefined) {
		if(document.getElementById('distancefrom')) { 
			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) {
		da_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) {
//			da_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)
                		{
                    		da_alert(e);
                		}
			});	
	return false;
}

function dialog_setting_docinfo (event, dialoglink,doctorPracticeId) {
      return false;
	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 open_doctor_practice_profile(event, docPracId, doc_prac_index, userId, insurancePlanId, reasonId, userAddress, userPatientFirstName, userPatientLastName) { 
	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;  
			} 
		}
	} 

	if(!doc_prac_index || doc_prac_index==undefined) {
		doc_prac_index = 0;
	}

	document.location.href ="doctor_practice_profile.php?&key_visitReason="+strVisitReason+ "&key_insurancePlanId="+ strInsurancePlan+"&key_insuranceProviderId=" + strInsuranceProvider+ "&key_userFromAddress=" + startAddress+ "&key_patientFirstName="+ patientFirstName +"&key_patientLastName=" + patientLastName +"&key_docPracId=" + docPracId+"&key_index="+doc_prac_index;
       return;	
}

/*
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 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){
	//	   da_alert("Please enter a valid email address")
		   return false
		}

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

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

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

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

		 if (str.indexOf(dot,(lat+2))==-1){
	//	    da_alert("Please enter a valid email address")
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
	//	    da_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

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) {
		da_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") {
			da_alert("Invalid characters in your zip code.  Please try again.");
			return false;
		}
		if ((hyphencount > 1) || ((field.length==10) && ""+field.charAt(5)!="-")) {
			da_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;
}

function format_phone(phone) {
	phone = stripCharsInBag(phone, validWorldPhoneChars);

	return phone;
}

//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; 

	var isPediatrician = document.getElementById('isPediatrician').value;
	isPediatrician = parseInt(isPediatrician);

	if(userId == -1) { 
		if(document.getElementById('apptRegisteredUser').checked) {
			if(!document.getElementById('apptLoginInput').value) {
				da_alert("Please enter login email"); 
				document.getElementById('apptLoginInput').focus;
				return 0;
			}
			if(!document.getElementById('apptPasswordInput').value) {
				da_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};
			da_loader_open();
			$.ajax({ 
				url:"validateUser.php", 
				type:'POST', 
				data:postData, 
				success: function(result){												
					da_loader_fadeout();
					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 != '') { 
						da_alert('Login Failed. Please check your email and password.');
						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") {
						da_alert("Login Failed. Please check your email and password.");
						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 ;
			userphone = document.getElementById('userphone').value ;

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

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

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


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

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

		if(!patientDob || !isDate(patientDob)) { 
			da_alert("Please check Patient Date of Birth");
			document.getElementById('patientdob').focus();
			return 0; 
		}
		if(!isAgeOK(patientDob, isPediatrician)) { 
			if(isPediatrician) {
				da_alert("Patient should be less than 16 years old to book an appointment of Pediatrician through DocAsap");
			} else {
				da_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('userphone').value==""){
				da_alert("Please enter your phone number along with area code");
				document.getElementById('userphone').focus();
				return false;
			}else {
				phone = document.getElementById('userphone').value;
				if(checkInternationalPhone(phone)){
					userphone = document.getElementById('userphone').value;		
				}else{
					da_alert("Please Enter a Valid Phone Number")
					document.getElementById('userphone').value="";
					document.getElementById('userphone').focus();
					return false;				
				}			

			}

			userphone = document.getElementById('userphone').value ;
			userphone = 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;

	userphone = format_phone(userphone);


	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}; 

	da_loader_open();
	$.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") { 
					da_loader_fadeout();
					da_alert(message); 
					return 0; 
				} else if(popupBox == "confirm") { 
					var res = confirm(message); 
					if(res == false) { 
						return 0; 
					} else { 
						document.getElementById('userphone').value = userphone;
						document.forms["apptConfirm"].submit(); 
					} 
				} else { 
					document.getElementById('userphone').value = userphone;
					document.forms["apptConfirm"].submit(); 
				} 
			} else {
				document.getElementById('userphone').value = userphone;
				document.forms["apptConfirm"].submit(); 
			}
		} 
	});	
	
}

function registerNewUser(){

	if (!validateNewUser ()){
		return 0;
	}

	var patientDob = document.getElementById('patientdob').value; 
	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 userphone = document.getElementById('userphone').value; 
	userphone = format_phone(userphone);

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

	da_loader_open();
	var postData = {"key_useremail" : useremail, "key_password" : userpassword, "key_userid" : userId, "key_userphone" : userphone, "key_userCode" : 0, "key_patientFirstName" : patientFirstName, "key_patientLastName" : patientLastName, "key_patientDob" : patientDob, "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") { 
					da_loader_fadeout();
					da_alert(message); 
					return 0; 
				} else if(popupBox == "confirm") { 
					var res = confirm(message); 
					if(res == false) { 
						return 0; 
					} else { 
						document.getElementById('userphone').value = userphone;
						document.forms["newUserRegistration"].submit(); 
					} 
				} else { 
					document.getElementById('userphone').value = userphone;
					document.forms["newUserRegistration"].submit(); 
				} 
			} else {
				document.getElementById('userphone').value = userphone;
				document.forms["newUserRegistration"].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){
	//	da_alert("The date format should be : mm-dd-yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
	//	da_alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
	//	da_alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
	//	da_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){
	//	da_alert("Please enter a valid date")
		return false
	}
return true
}



//THIS FUNCTION DOES THE INPUT FIELD VALIDATION
function validateNewUser () {
	//validation
	if(!validateName(document.getElementById('userfirstname').value)){
		da_alert ("Please check your first name");
		document.getElementById('userfirstname').focus ();
		return false;
	}else{
		userfirstname = document.getElementById('userfirstname').value;	
	}
	if(!validateName(document.getElementById('userlastname').value)){
		da_alert ("Please check your last name");
		document.getElementById('userlastname').focus ();
		return false;
	}else{
		userlastname = document.getElementById('userlastname').value;	
	}
	
	var patientDob = document.getElementById('patientdob').value; 


	if(!patientDob || !isDate(patientDob)) {
		da_alert("Please check Patient Date of Birth");
		document.getElementById('patientdob').focus();
		return 0; 
	}
	if(document.getElementById('isPediatrician')) {
		var isPediatrician = document.getElementById('isPediatrician').value;
		isPediatrician = parseInt(isPediatrician);
		if(!isAgeOK(patientDob, isPediatrician)) { 
			if(isPediatrician) {
				da_alert("Patient's age should be 13 or less to book an appointment of Pediatrician through DocAsap");
			} else {
				da_alert("Patient should be more than 13 years old to book an appointment through DocAsap");
			}
			document.getElementById('patientdob').focus();
			return 0; 
		}
	}
	
	//-------------get contact preferences-----------------------------
	//If contact preference is set to 'email', check if email field is filled
	if(document.getElementById('userphone').value==""){
		da_alert("Please enter your phone number along with area code");
		document.getElementById('userphone').focus();
		return false;
	}else {
		phone = document.getElementById('userphone').value;
		if(checkInternationalPhone(phone)){
			userphone = document.getElementById('userphone').value;		
		}else{
			da_alert("Please Enter a Valid Phone Number")
			document.getElementById('userphone').value="555-5555555";
			document.getElementById('userphone').focus();
			return false;				
		}			

	}


	if((document.getElementById('useremail').value)==""){
		da_alert("Please enter your email address");
		document.getElementById('useremail').focus();
		return false;
	}else {
		if (echeck(document.getElementById('useremail').value)){
			useremail=document.getElementById('useremail').value;
			//da_alert (echeck(document.getElementById('useremail').value));
		}else{
		   	da_alert("Please enter a valid email address")
			document.getElementById('useremail').value="";
			document.getElementById('useremail').focus();
			return false;
		}
	}	
	//validate password and confirm password fields
	if((document.getElementById('userpasswordid').value=="")||(document.getElementById('userconfirmpassword').value=="")){
		da_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('userpasswordid').value; 
		var c_passwd = document.getElementById('userconfirmpassword').value;
		if(!validatePassword(passwd, c_passwd)) {
			document.getElementById('userpasswordid').value="";
			document.getElementById('userconfirmpassword').value="";
			document.getElementById('userpasswordid').focus();

			return false;	
		}
	}

	if(document.getElementById('security_question_id').value==0) {
		da_alert("Please select security question");
		document.getElementById('security_question_id').focus();
		return false;
	} else if(!document.getElementById('security_question_answer_id').value ) {
		da_alert("Please add answer to your security question");
		document.getElementById('security_question_id').focus();
		return false;
	}

	if(!document.getElementById('termsCB').checked) {
		da_alert("Please read the Terms and Conditions");
		document.getElementById('termsCB').focus();
		return 0;
	}

	return true;
}

function validatePassword(password, c_password, no_da_alert) {
	if(password != c_password) {
		if(!no_da_alert) {
			da_alert ("Passwords don't match. Please try again."); 
		}
		return false;	
	}else {
		return(isUserPasswordGood(password, no_da_alert));
	}
}

function isUserPasswordGood(password, no_da_alert) {
	var wrongPsswd = 0;
	if(password.length < 8) {
		if(!no_da_alert) {
			da_alert ("Please check the password. Password should contain atleast 8 characters");
		}

		return false;	
	} 
	return true;
}

function isPasswordGood(password, no_da_alert) {
	var wrongPsswd = 0;
	if(password.length < 6) {
		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) {
		if(!no_da_alert) {
			da_alert ("Please check the password. Password should contain atleast 6 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. */

da_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) {
da_alert("Ths username contains invalid characters.");
return false;
   }
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
da_alert("Ths domain name contains invalid characters.");
return false;
   }
}

// See if "user" is valid 

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

// user is not valid

da_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) {
da_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) {
da_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) {
da_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) {
da_alert("This address is missing a hostname!");
return false;
}

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

function create_userForgotDialog(divid) {
	//var select = $('select#forgotpasswd_security_question_id');
	//make_da_select(select, 'forgotpasswd_security_question_selectBox_id', 1);

	$("#"+divid).dialog({
			autoOpen: false,
			bgiframe: true,
			modal: true,
			width: 470,
			height: 250,
			shadow: false,
			resizable: false
	});
}

function openForgotPasswordDialog() {
	var postData = {"forgot_passwd_userId" : -1};
	da_loader_open();
	$.ajax({ 
		url:'user_forgot_password.php', 
		type:'GET', 
		data:postData, 
		success: function(result) { 
			da_loader_fadeout();
			$("#forgot_dialog").html(result);
			$('#forgot_dialog').dialog('open');
		}
	});
}

function userForgotPasswordServerCall_1() {

	var loginEmail = document.getElementById("forgotpasswd_email_id").value;
	if (!loginEmail) {
		da_alert("Please enter your DocAsap login email");
		document.getElementById("forgotpasswd_email_id").focus;
		return 0;
	}

	var postData = {"key_useremail" : loginEmail, "key_security_question_id" : -1, "key_forgotpassword" : 1, "key_userCode" : 0};
	var userId;
	da_loader_open();
	$.ajax({ 
		url:'validateUser.php', 
		type:'POST', 
		data:postData, 
		success: function(result) { 
			da_loader_fadeout();
			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 == "userid") { 
					userId = message;

					postData = {"forgot_passwd_userId" : userId};
					da_loader_open();
					$.ajax({ 
						url:'user_forgot_password.php', 
						type:'GET', 
						data:postData, 
						success: function(result) { 
							da_loader_fadeout();
							$("#forgot_dialog").html(result);
						}
					});

				} else {
					da_alert(message); 
					if(popupBox == "confirm") { 
						$("#forgot_dialog").dialog('close');
					} else {
						document.getElementById("forgotpasswd_email_id").focus;
					}
					return 0; 
				}
			}
		} 
	});


}

function userForgotPasswordServerCall_2(userId, secQuesId) {
	var security_question_answer;
	security_question_answer = document.getElementById('forgotpasswd_security_question_answer_id').value;
	if (!security_question_answer) {
		da_alert("Please enter answer to your security question");
		document.getElementById("forgotpasswd_security_question_answer_id").focus;
		return 0;
	}

	var postData = {"key_userid" : userId, "key_security_question_id" : secQuesId, "key_security_question_answer" : security_question_answer, "key_forgotpassword" : 1, "key_userCode" : 0};
	da_loader_open();
	$.ajax({ 
		url:'validateUser.php', 
		type:'POST', 
		data:postData, 
		success: function(result) { 
			da_loader_fadeout();
			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 != '') { 
				da_alert(message); 
				if(popupBox == "confirm") { 
					$("#forgot_dialog").dialog('close');
				} 
				return 0; 
			}
		} 
	});
}

function da_alert(mssg) {
	if(document.getElementById('da_alert_dialog_div')) {
		var htmlStr = "<div style='float:right'><img src=images/logo.png height=25px /></div><div style='position:absolute;top:60px;text-align:center;width:95%'>"+mssg+"</div>";
		$('#da_alert_dialog_div').dialog('open');
		$('#da_alert_dialog_div').html(htmlStr);
	} else {
		alert(mssg);
	}
}

function da_loader_open(msg) {
	if(msg == undefined || !msg) {
		msg = "";
	}
	if(document.getElementById('da_loader_dialog_div')) {
		var htmlStr = "<div class=title  id=da_dialogloading><div style='float:right'><img src=images/logo.png height=25px /></div><div style='position:absolute;top:50px;text-align:center;width:95%'>"+msg+" Please Wait...<BR><BR> <img src='images/loader.gif' alt='currently loading' /></div></div>";
		$('#da_loader_dialog_div').dialog('open');
		$('#da_loader_dialog_div').html(htmlStr);
	} 
}

function da_loader_fadeout() {
	if(document.getElementById('da_loader_dialog_div')) {
		$('#da_dialogloading').fadeOut(300,function(){
			$(this).remove();
		});
		$('#da_loader_dialog_div').dialog('close');

	}
}

function isLaunchInCity(distance_service, userAddress, currentCity, specialtyId, parameters, successFunc) {

	var fromAddress = launchedCitiesArray[currentCity];
	var service_options = {
		origins: [fromAddress],
		destinations: [userAddress],
		travelMode: google.maps.TravelMode.DRIVING,
		unitSystem: google.maps.UnitSystem.IMPERIAL,
		avoidHighways: false,
		avoidTolls: false
	};

	distance_service.getDistanceMatrix(service_options,  function(response, status) {
		if (status != google.maps.DistanceMatrixStatus.OK) {
			alert('Error was: ' + status);
		} else {
			var results = response.rows[0].elements;
			var distance = results[0].distance.value; //distance in meters
			if(distance < 48280) { //1 mile = 1609.344 meters: checking for 30 miles
				var 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 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>";
				da_alert(htmlStr);

				return 0; //return from eventlistener
			}
			if(currentCity < numLaunchedCities-1) {
				currentCity++;
				isLaunchInCity(distance_service, userAddress, currentCity, specialtyId, parameters, successFunc);
			} else {
				var htmlStr = "<Div 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>";
				da_alert(htmlStr);

			}

			return 0; 
		}
	});
}

var launchedCitiesArray = new Array();
var numLaunchedCities = 0;
function isLaunched(userAddress, specialtyId, successFunc, parameters, addressLatDiv, addressLngDiv) {
	for(var city in city2SpecialityMapping) { 
		launchedCitiesArray.push(city);
		numLaunchedCities++;
	}

	var geocoder = new google.maps.Geocoder();
	geocoder.geocode( { 'address': userAddress}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			latLngPt = results[0].geometry.location;
			if(addressLatDiv && document.getElementById(addressLatDiv)) {
				document.getElementById(addressLatDiv).value = latLngPt.lat();
				document.getElementById(addressLngDiv).value = latLngPt.lng();
			}

			var currentCity = 0;
			var service = new google.maps.DistanceMatrixService();
			isLaunchInCity(service, userAddress, currentCity, specialtyId, parameters, successFunc);
		} else {
			da_alert("Please enter some valid address");
		}
	});
}


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

	var useremail = document.getElementById('useremail').value ;
	if(!useremail) { 
		da_alert("Please enter login email"); 
		document.getElementById('useremail').focus;
		return 0; 
	}
	if (!emailCheck(useremail)) {
		da_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) { 
		da_alert("Please enter cellphone number with area code"); 
		document.getElementById('userareaphone').focus;
		return 0; 
	}
	if(!checkInternationalPhone(userphone)){
		da_alert("Please enter valid cellphone number with area code"); 
		document.getElementById('userareaphone').focus;
		return 0; 
	}
	*/
	userphone = userareaphone+userphone;

	var userpassword = document.getElementById('userpasswordid').value;
	var userCpassword = document.getElementById('userconfirmpassword').value;
	if(!userpassword || userpassword != userCpassword) {
		da_alert("Please check your password");
		document.getElementById('userpasswordid').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") { 
					da_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 || name.length<2) {
		return 0;
	} else {
		return 1;
	}
}

function isAgeOK(dobStr, isPediatrician) {
	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(isPediatrician) {
		if(age>13) {
			return 0;
		} else if(age < 1) { 
			if(year < pyear) { 
				return 0;
			} else if (year == pyear) {
				if(month < pmonth) {
					return 0;
				} else if(month == pmonth) {
					if(day < pday) {
						return 0;
					}
				}
			}
		}

		return 1;
	} else {
		if(age<=13) {
			return 0;
		} else {
			return 1;
		}
	}
}

function verifyUserAccount(userId, slotId, divId) {

	var docPracIdElem = document.getElementById('docPracticeId');	
	var docPracId = docPracIdElem.value;
	var visitReasonId = document.getElementById('visitReasonId').value;
	var insurancePlanId = document.getElementById('insurancePlanId').value;
	var userFromAddress = document.getElementById('userFromAddress').value;

	var postData = {"key_userid" : userId, "key_slotid" : slotId, "key_visitReason":visitReasonId, "key_insurancePlanId": insurancePlanId, "key_userFromAddress" : userFromAddress, "key_docPracId" : docPracId};
	da_loader_open();
	$.ajax({
		url:"provide_verification_code_form.php",
		type:'GET',
		data:postData,
		success: function(result){
			da_loader_fadeout();
			$('#'+divId).html("<div class='search_heading_div font_style_h1 font_style_orange font_style_bold'>Verify your <span class=font_style_green>ACCOUNT</span></div>"+result);
			sendUserAuthenticationCode(userId, 'calling_loader_div');
			da_alert('You will receive our call shortly to provide your verfication code. Please enter the verification code to validate your account');
		}
	});
}

