var focusForm = true;
var calendarMonth = true;
var calendarDay = false;
var sbox = false;

if (useShadowbox) { 
	Shadowbox.loadSkin('classic', site_root+'/js/shadowbox/skin');
	Shadowbox.loadLanguage('en', site_root+'/js/shadowbox/lang');
	//Shadowbox.loadPlayer(['img', 'swf', 'flv', 'qt', 'wmp', 'iframe', 'html'], site_root+'/js/shadowbox/player');
	Shadowbox.loadPlayer(['html','iframe'], site_root+'/js/shadowbox/player');
}

if (useWindows) {
	var defaultOptions = {
		
		className:		"mac_os_x", 
		title:			"Window Title", 
		width:			350, 
		height:			350, 
		destroyOnClose:	true, 
		recenterAuto:	false,
		draggable:		false,
		resizable:		false,
		closable:		false,
		maximizable:	false,
		minimizable:	false
	}
}

Event.observe(window, 'load', function() {
	if (useShadowbox) {
		Shadowbox.init({
			skipSetup:		true,
			onClose:		function() {if(typeof shadowboxReturn == 'function') {shadowboxReturn();}}//,
		//	initialHeight:	350,
		//	initialWidth:	350
		});
	}
	
	frms = $$("form");
	if(frms.length && focusForm) {
		frms[0].focusFirstElement();
	}
	//if ($$("form")) {
		//alert($$("form"));
	//	$$("form").first().focusFirstElement();
	//}
});

function closeShadowbox() {
	if (this.parent.Shadowbox) {
		this.parent.Shadowbox.close();
	} else if (Shadowbox) {
		Shadowbox.close();	
	}
}

function changePatient() {
	patientid = $F('patient');
	if (patientid == "new") {
		$('calendar_day_new_patient').show();
		$('calendar_day_existing_patient').hide();
	} else if (patientid > 0) {
		$('calendar_day_new_patient').hide();
		$('calendar_day_existing_patient').show();
	} else {
		$('calendar_day_new_patient').hide();
		$('calendar_day_existing_patient').hide();	
	}
}

function changemonth(newMonth, admin, slot_length, container) {
	calendarMonth = newMonth;
	container = container ? container : "calendar-month";
	//alert("here");
	$('loading').show();
	url = site_root + '/calendar/update_calendar/' + newMonth + '/' + admin + '/' + slot_length;
	new Ajax.Updater(container, url, {
		onComplete: function() {
			$('loading').hide();	
		}
	});
}

function changedate(newDay, admin, slot_length, container) {
	calendarDay = newDay;
	rslt = true;
	if ($P.function_exists("changedate_local")) {
		rslt = changedate_local(newDay, admin, slot_length, container);
	}
	
	if (rslt) {
		
		container = container ? container : "calendar-day";
		
		$('loading').show();
		
		$$(".selected-date").invoke('removeClassName', 'selected-date');
		$$("#date_" + newDay).invoke('addClassName', "selected-date");
		
		url = site_root + '/calendar/update_day_calendar/' + newDay + '/' + admin;
	
		new Ajax.Updater(container, url, {
			onComplete: function() {
				if (admin == 'true') {
					//Event.observe('last_name', 'keyup', updatePatientLiveSearch);
					//Event.observe('first_name', 'keyup', updatePatientLiveSearch);
					//updatePatientLiveSearch();
					changeAppointmentLength(newDay, 'slotlength', true);
				}
				$('loading').hide();
			}
		});
	}
}

function confirmation(type) {
	switch(type) {
		case "delete patient":	
			str = "Are you sure you would like to delete this patient?";
			break;
		default:
			str = "Are you sure?";
	}
	return confirm(str);
}

function deletePatient(patient_id) {
	if (confirmation('delete patient')) {
 		alert(patient_id);
	}
}

function viewPatient(patient_id) {
	//alert(patient_id);
	/*
	Shadowbox.open({
		player:     'html',
		title:      'Welcome',
		content:    '<div id="welcome-msg">Welcome to my website!</div>',
		height:     350,
		width:      350
	});
	*/
	Shadowbox.open({
		player:     'iframe',
		title:      'Patient',
		content:     site_root + '/admin/patients/view/' + patient_id + "/true/",
		onClose:	function() {alert("here");}
	});

}


function filterPatientTable(arg) {
	
	var relookup = false;
	if (typeof(arg) == "number") {
		page = (arg > 0 ? arg : 1);
		relookup = true;
	} else if(typeof(arg) == "object") {
		page = 1;
		if ((arg.keyCode >= 48 && arg.keyCode <= 90) || (arg.keyCode >= 96 && arg.keyCode <= 111) || (arg.keyCode >= 186 && arg.keyCode <= 222) || arg.keyCode == 8 || arg.keyCode == 32) {
			relookup = true;
		}
		//alert(arg.keyCode);	
	} else {
		page = 1;
		relookup = true;	
	}
	if (relookup) {
		$('loading').show();
		//$('debug').innerHTML = $F('first_name') + " " + $F('last_name');	
		url = site_root + '/patients/find_patients/' + page;
		new Ajax.Request(url, {
			method: 'post',
			onlyLatestOfClass: 'patientLive',
			parameters: {
				"data[Patient][first_name]" : $F('PatientFirstName'),
				"data[Patient][last_name]" : $F('PatientLastName'),
				"data[Patient][email_address]" : $F('PatientEmailAddress'),
				"data[Patient][street_1]" : $F('PatientStreet1'),
				"data[Patient][street_2]" : $F('PatientStreet2'),
				"data[Patient][city]" : $F('PatientCity'),
				"data[Patient][state]" : $F('PatientState'),
				"data[Patient][zip]" : $F('PatientZip'),
				"data[Patient][phone_1]" : $F('PatientPhone1'),
				"data[Patient][phone_2]" : $F('PatientPhone2')
			},
			onSuccess: function(transport) {
				//$('calendar_day_patient_list').innerHTML = "<ul>";
				//patients  = transport.responseText;
				//patients = transport.responseText.isJSON();//$('calendar_day_patient_list').innerHTML = transport.responseText;
				//alert(patients);
				if (transport.responseText) {
					
					str = transport.responseText;
					str = str.substr(0, str.lastIndexOf('!--') - 1);
					//alert(str);
					
					//str = '[{"foundCount":2,"patients":[{"Patient":{"last_name":"Slosarek","first_name":"Mark","city":"Fort Atkinson","id":"2"}}],"page":"1","pages":1,"limit":"10000","start":1,"end":2,"compact":"1"}]';
					//rslt = eval(str);
				
					patient_out = eval(str);
					
					patient_out = patient_out[0];
					patients = patient_out['patients'];
					
					pages_str = "";
					if(patient_out.pages == 1) {
						pages_str = "Showing " + patient_out.foundCount + (patient_out.foundCount == 1 ? " Patient" : " Patients");
					} else {
						pages_str = "<span>Page: ";
						for(pg=1; pg<=patient_out.pages; pg++) {
							if (pg == patient_out.page) {
								pages_str += pg + " ";
							} else {
								pages_str += "<a href=\"#\" onclick=\"filterPatientTable(" + pg + ");return false\">" + pg + "</a> ";
							}
						}
						pages_str += "</span>";
					
						pages_str += "Showing Patients " + patient_out.start + " through " + patient_out.end + " of " + patient_out.foundCount + " Patients";
						
					}
					
					$$('.patient_pagination').each(function(elmt) {
						elmt.innerHTML = pages_str;
					});
					
					//$('patient_table_data').replace("<tr><td colspan=\"8\">Content</td></tr>");
					//alert("here");
					//$('patient_table_data').innerHTML = "";
					
					ptable_data = "<tbody id=\"patient_table_data\">";
					
					patients.each(function(patient) {
						var onclick = " onclick=\"viewPatient(" + patient.Patient.id + ")\"";
						str = ""; 
						str += "<tr>";
						str += "<td class=\"show_merge checkcol\"><input type=\"checkbox\" name=\"data[Patients][id][]\" id=\"patient_" + patient.Patient.id + "\" value=\"" + patient.Patient.id + "\" /></td>";
						str += "<td" + onclick + ">" + patient.Patient.last_name + "&nbsp;</td>";
						str += "<td" + onclick + ">" + patient.Patient.first_name + "&nbsp;</td>";
						str += "<td" + onclick + ">" + patient.Patient.email_address + "&nbsp;</td>";
						str += "<td" + onclick + ">" + patient.Patient.street_1 + "&nbsp;</td>";
						str += "<td" + onclick + ">" + patient.Patient.street_2 + "&nbsp;</td>";
						str += "<td" + onclick + ">" + patient.Patient.city + "&nbsp;</td>";
						str += "<td" + onclick + ">" + patient.Patient.state + "&nbsp;</td>";
						str += "<td" + onclick + ">" + patient.Patient.zip + "&nbsp;</td>";
						str += "<td" + onclick + ">" + (patient.Patient.phone_1 == "--" ? "" : patient.Patient.phone_1) + "&nbsp;</td>";
						str += "<td" + onclick + ">" + (patient.Patient.phone_2 == "--" ? "" : patient.Patient.phone_2) + "&nbsp;</td>";
						str += "<td" + onclick + ">" + (patient.Patient.established_patient == 1 ? "Yes" : "No") + "&nbsp;</td>";
						//str += "<td><a href=\"" + site_root + "/admin/patients/delete/" + patient.Patient.id + "\" onclick=\"deletePatient(" + patient.Patient.id + "); return false\">Delete</a></td>";
						
						//str += "<td>".$html->link("Delete", "/admin/patients/delete/".$patient['Patient']['id'], array("onclick"=>"deletePatient(".$patient['Patient']['id'].")"), "Are you sure you would like to delete ths patient?")."</td>";
						str += "</tr>";
						//$('debug').innerHTML += "<li>" + patient.Patient.last_name + ", " + patient.Patient.first_name + "</li>";
						//$('patient_table_data').innerHTML += str;
						ptable_data += str;
					});
					
					ptable_data += "</tbody>";
					
					$('patient_table_data').replace(ptable_data);
					
					//$('patient_table_data').innerHTML = str;
					//$('calendar_day_patient_list').innerHTML += "</ul>";
					
					$('loading').hide();
				}
			}
		});
	}
}

function updatePatientLiveSearch(container, linkUrl, linkAction) {
	$('loading').show();
	container = (container ? container : "calendar_day_patient_list");
	
	url = site_root + '/patients/find_patients/1/10000/1/0/1';
	new Ajax.Request(url, {
		method: 'post',
		onlyLatestOfClass: 'patientLive',
		parameters: {
			"data[Patient][first_name]" : $F('first_name'),
			"data[Patient][last_name]" : $F('last_name')	
		},
		onSuccess: function(transport) {
			//$('calendar_day_patient_list').innerHTML = "<ul>";
			//patients  = transport.responseText;
			//patients = transport.responseText.isJSON();//$('calendar_day_patient_list').innerHTML = transport.responseText;
			//alert(patients);
			if (transport.responseText) {
			
				//$("debug").innerHTML = transport.responseText;
			
				//str = "'"+transport.responseText+"'";
				//str = "{"+transport.responseText+"}";
				str = transport.responseText;
				str = str.substr(0, str.lastIndexOf('!--') - 1);
				//alert(str);
				
				//str = '[{"foundCount":2,"patients":[{"Patient":{"last_name":"Slosarek","first_name":"Mark","city":"Fort Atkinson","id":"2"}}],"page":"1","pages":1,"limit":"10000","start":1,"end":2,"compact":"1"}]';
				rslt = eval(str);
				//rslt = str.evalJSON();
				
				//alert(rslt);
				
				
				
				rslt = rslt[0];
				
				//alert(rslt);
				
				patients = rslt.patients;
				
				$(container).innerHTML = "";
				patients.each(function(patient) {
					if(patient.Patient.last_name ||  patient.Patient.first_name) {
						var str = "";
						str += "<li id=\"patient_" + patient.Patient.id + "\">";
						if (linkUrl || linkAction) {
							linkActionT = linkAction.replace(/_id_/, patient.Patient.id);
							linkUrl = (linkUrl ? linkUrl : "#");
							linkAction = (linkAction ? linkAction : "");
							str += "<a href=\"" + linkUrl + "\" onclick=\"" + linkActionT + "\">";
						}
						str += patient.Patient.last_name + ", " + patient.Patient.first_name;
						if (patient.Patient.city) {
							str += " (" + patient.Patient.city + ")";
						}
						if (linkUrl || linkAction) {
							str += "</a>";
						}
						str += "</li>";
						$(container).insert(str);
						
					}
					//$('debug').innerHTML += "<li>" + patient.Patient.last_name + ", " + patient.Patient.first_name + "</li>";
				});
				//$('calendar_day_patient_list').innerHTML += "</ul>";
				$('loading').hide();
			}
			
		}
	});
	
}

function showAddTimes() {
	
	if (useShadowbox) {
		Shadowbox.open({
			player:			'html',
			title:			'Welcome',
			content:		$('addTimesForm').innerHTML,
			height:			350,
			width:			350	
		});
	}
	
	if (useWindows) {
		wOptions = defaultOptions;
		wOptions.title = "Sample";
		wOptions.closable = true;
		wOptions.height = 150;
		wOptions.width = 250;
		
		win = new Window(wOptions);
		win.getContent().update($('addTimesForm').innerHTML);
		win.showCenter();
	}

}

function addTimes() {
	//var frm = $('TimeslotAddForm');
	params = Form.serialize("TimeslotAddForm", true);
	//$("debug").innerHTML = Object.toJSON(params);
	
	url = site_root + "/timeslots/make/";
	new Ajax.Request(url, {
		method: 'post',
		parameters: params,
		onSuccess: function(transport) {
			
			changemonth(calendarMonth, 'true', 20);
			changedate(calendarDay, 'true', 20);
			//$("debug").innerHTML = transport.responseText;
			
			/*avail_slots = eval(transport.responseText);
			
			$("timeslots").innerHTML = "";
			
			if (avail_slots.length > 0) {
				avail_slots.each(function(elmt) {
				if (display) {
					$("timeslots").innerHTML += "<li>" + $P.date('g:i A', elmt.Timeslot.start_ts) + " - " + $P.date("g:i A", elmt.Timeslot.end_ts) + "</li>";
				} else {
					$("timeslots").innerHTML += "<li><label><input type=\"radio\" name=\"data[Timeslot][timeslot_id]\" id=\"TimeslotTimeslotId\" value=\"" + elmt.Timeslot.ids + "\">" + $P.date('g:i A', elmt.Timeslot.start_ts) + " - " + $P.date("g:i A", elmt.Timeslot.end_ts) + "</label></li>";	
				}
				});
			} else {
				$("timeslots").innerHTML += "<li>No Available Appointments</li>";
			}
			//$("timeslots").innerHTML += transport.responseText;
			*/
		}
	});
}

var currentTs = "";

function changeAppointmentLength(ts, slField, display) {
	currentTs = ts;
	
	slField = slField ? slField : "slotlength";
	aptLength = $F(slField);
	
	url = site_root + "/timeslots/get_avail/" + ts + "/" + aptLength + "/1";
	
	new Ajax.Request(url, 
		{
			method: 'get',
			onSuccess: function(transport) {
				
				str = transport.responseText;
				str = str.substr(0, str.lastIndexOf('!--') - 1);
				
				avail_slots = eval(str);
				
				//alert(here);
				
				$("timeslots").innerHTML = "";
				
				if (avail_slots.length > 0) {
					avail_slots.each(function(elmt) {
					if (display) {
						$("timeslots").innerHTML += "<li><a href=\"#\" onclick=\"deleteTimeslot('" + elmt.Timeslot.id + "');return false\">" + $P.date('g:i A', elmt.Timeslot.start_ts) + " - " + $P.date("g:i A", elmt.Timeslot.end_ts) + "</a></li>";
					} else {
						$("timeslots").innerHTML += "<li><label><input type=\"radio\" name=\"data[Timeslot][timeslot_id]\" id=\"TimeslotTimeslotId\" value=\"" + elmt.Timeslot.ids + "\">" + $P.date('g:i A', elmt.Timeslot.start_ts) + " - " + $P.date("g:i A", elmt.Timeslot.end_ts) + "</label></li>";	
					}
					});
				} else {
					$("timeslots").innerHTML += "<li>No Available Appointments</li>";
				}
				//$("timeslots").innerHTML += transport.responseText;
			}
		}
	);

}

function deleteTimeslot(timeslot_id) {
	if (confirm("Are you sure you would like to delete this timeslot?")) {
		url = site_root + "/timeslots/delete/" + timeslot_id;
		
		new Ajax.Request(url, 
			{
				method: 'get',
				onSuccess: function(transport) {
					
					//changeAppointmentLength(currentTs);
					changemonth(calendarMonth, 'true', 20);
					changedate(calendarDay, 'true', 20);
				}
			}
		);
	}
}

function setNewPatientTimeSlots() {
	url = site_root + "/days/set_value/" + calendarDay + "/" + $F("TimeslotNew");
		
	new Ajax.Request(url, 
		{
			method: 'get',
			onSuccess: function(transport) {
				
			}
		}
	);
}

function loadingStr(txt) {
	txt = (txt ? txt : "Loading...");
	str = "<span class=\"loading_str\"><img src=\"" + site_root + "/img/ajax-loader-small.gif\" alt=\"\" /> " + txt + "</span>";
	return str;
}