//the number of encounter boxes on the page
patient_counter = 0;

//just a constant
max_icd9_codes = 3;

// an array that holds the icd9 codes that are checked to make sure that no more than
// three are checked on each patient log.
icd9_list = new Array();

//Got this off the internet... It finds all elements with a particular class name (strClassName), 
//and a certain element type (strTagName) within a parent element (oElm)
function getElementsByClassName(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/\-/g, "\\-");
    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
    var oElement;
    for(var i=0; i<arrElements.length; i++){
        oElement = arrElements[i];
        if(oRegExp.test(oElement.className)){
            arrReturnElements.push(oElement);
        }
    }
    return (arrReturnElements);
}


//This function is run each time someone checks what rotation they will be logging for.
//It goes through the website and makes only the tasks that are avalable for a particular
//rotation visible.  Tasks for rotation 1 are stored in divs of class 1_tasks and so on.
function choose_rotation()
{
	elements = document.getElementsByName('task_id');
	for(i=0;i<elements.length;++i)
		elements[i].checked=false;
	
	var pel = document.getElementById('pel');
	var rotation_id;
	for(i=0; i < pel.rotation_id.length;++i)
	{
		if(pel.rotation_id[i].checked)	
		{
			rotation_id = pel.rotation_id[i].value;
			for(j=1; j<7;++j)
			{
				elements = getElementsByClassName(document, 'div', j+'_tasks');					
				for(m=0;m<elements.length;++m)
				{
					if(pel.rotation_id[i].value == j)
						elements[m].style.display = 'block';
					else
						elements[m].style.display = 'none';
				}	
			}	
		}
	}
	
	for (i=0; i < patient_counter; ++i)
	{
		element = document.getElementById('diagnosis'+i);
		if(element && rotation_id == 5)
			element.style.display = "block";
		else if (element)
			element.style.display = "none";
	}
}

//when people click the add patient button to add another patient encounter on to the page.
function add_patient()
{
	//first we create html code for the new patient to be placed on the page
	var pt = document.createElement('div');
	pt.innerHTML = get_new_pt_code(patient_counter);
	pt.id = "patient"+patient_counter;
	document.getElementById('patients').appendChild(pt); 			

	var pel = document.getElementById('pel');
	
	//then we get the default location and default task
	var default_location = -1;
	for(i=0; i<pel.location_id.length;++i)
	{
		if(pel.location_id[i].checked)
		{
			default_location = pel.location_id[i].value;
			break;
		}
	}
	var default_task = -1;
	for(i=0; i<pel.task_id.length;++i)
	{
		if(pel.task_id[i].checked)
		{
			default_task = pel.task_id[i].value;
			break;
		}
	}
	
	//then we automatically check the default location and task in the new patient we just created.
	elements = document.getElementsByName('location_id'+patient_counter);
	for(i=0; i< elements.length; ++i)
	{
		if(elements[i].value == default_location)
		{
			elements[i].checked = true;
			break;
		}
	}
	elements = document.getElementsByName('task_id'+patient_counter+'[]');
	for(i=0; i< elements.length; ++i)
	{
		if(elements[i].value == default_task)
		{
			elements[i].checked = true;
			break;
		}
	}
	
	var pel = document.getElementById('pel');
	rotation_id = -1;
	for(i=0; i < pel.rotation_id.length;++i)
	{
		if(pel.rotation_id[i].checked)	
		{
			rotation_id = pel.rotation_id[i].value;
		}
	}
	
	if(rotation_id == 5)
	{
		document.getElementById('diagnosis'+patient_counter).style.display="block";
	}
	
	//Then we just update the number of patients we have added.
	document.getElementById('patient_counter').value = patient_counter;
	++patient_counter;	
}

//This is called when someone checks an ICD 9 category and makes sure they don't add more than 3
function category_checked(element)
{
	//make new array if we havent seen this checklist before
	if(icd9_list[element.name] == undefined)
	{
		icd9_list[element.name] = new Array();
	}
	
	//if the object was checked, easy, we just add it, if not we remove it from the list
	if(element.checked)
		icd9_list[element.name].push(element);
	else
	{
		for(i=0; i < icd9_list[element.name].length; ++i)
		{
			if(icd9_list[element.name][i].value == element.value)
					icd9_list[element.name].splice(i, 1);
		}
	}
	
	//make sure there are no more boxes checked than should be
	while(icd9_list[element.name].length > max_icd9_codes)
	{
		to_uncheck = icd9_list[element.name].shift();
		to_uncheck.checked = false;
	}	
}

//Just makes the HTML code for a new patient.  It comes from hidden div with id 
// patient_template. There is a % sign that is replaced with a number.
function get_new_pt_code(number)
{
	var element = document.getElementById('patient_template');
	return element.innerHTML.replace(/%/g, number);
}

//if the user decides to remove a patient.  Pretty simple.
function remove_patient(number)
{
	var d = document.getElementById('patients');
			var olddiv = document.getElementById('patient'+number);
			d.removeChild(olddiv);
}

//When someone chooses submit.  The first thing that happens is we submit via ajax the user and password
//along with a variable called check to check if the username and password work.  If they don't we don't 
//try submitting.  If they do then we submit.  Also before all this happens we make sure all the fields are
//filled out.
function check_submit()
{
	//first create the Ajax object
	var ajaxRequest;
	var pel = document.getElementById('pel');
	document.getElementById('loading').style.display = 'block';
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				alert("Your browser broke!");
				return false;
			}
		}
	}
	
	//This whole next chunk of code makes sure all of the form fields are filled out.
	var checked = false;
	for (var j = 0; j < pel.rotation_id.length; ++j)
	{
		if(pel.rotation_id[j].checked)
			checked = true;
	}					
	if(!checked)
	{
		alert('You need to choose a rotation.');
			document.getElementById('loading').style.display = 'none';
		exit();	
	}
	for(var i = 0; i <= pel.patient_counter.value; ++i)
	{
		var additional_info = document.getElementsByName('additional_info'+i);
		if( additional_info.length > 0)
		{
			if(additional_info[0].value.length == 0)
			{
				alert('You need to fill in a patient description on one or more of your patients.');
			document.getElementById('loading').style.display = 'none';
				exit();	
			}
			var age = document.getElementsByName('pt_age'+i);
			if(age[0].value.length == 0)
			{
				alert('You need to fill in a patient age on one or more of your patients.');
			document.getElementById('loading').style.display = 'none';
				exit();	
			}
			
			var gender = document.getElementsByName('pt_gender'+i)
			checked = false;
			for (var j = 0; j < gender.length; ++j)
			{
				if(gender[j].checked)
					checked = true;
			}
			if(!checked)
			{
				alert('You need to fill in a patient gender on one or more of your patients.');
			document.getElementById('loading').style.display = 'none';
				exit();	
			}
			
			var location = document.getElementsByName('location_id'+i)
			checked = false;
			for (var j = 0; j < location.length; ++j)
			{
				if(location[j].checked)
					checked = true;
			}
			if(!checked)
			{
				alert('You need to choose a location on one or more of your patients.');
			document.getElementById('loading').style.display = 'none';
				exit();	
			}
			
			var type = document.getElementsByName('type_id'+i)
			checked = false;
			for (var j = 0; j < type.length; ++j)
			{
				if(type[j].checked)
					checked = true;
			}
			if(!checked)
			{
				alert('You need to choose a type on one or more of your patients.');
			document.getElementById('loading').style.display = 'none';
				exit();	
			}	
							
			var cat = document.getElementsByName('icd9cats'+i+'[]')
			checked = false;
			for (var j = 0; j < cat.length; ++j)
			{
				if(cat[j].checked)
					checked = true;
			}
			if(!checked)
			{
				alert('You need to choose from 1 to 3 categories on one or more of your patients.');
			document.getElementById('loading').style.display = 'none';
				exit();	
			}
			
			var type = document.getElementsByName('task_id'+i+'[]')
			checked = false;
			for (var j = 0; j < type.length; ++j)
			{
				if(type[j].checked)
					checked = true;
			}
			if(!checked)
			{
				alert('You need to choose at least 1 task on one or more of your patients.');
			document.getElementById('loading').style.display = 'none';
				exit();	
			}			
		}
	}

	//If we've gotten to this point, then the form must be filled out correctly.  This chunk of
	// code seems out of order.  It defines what happens when the first ajax request to check the
	// username and password is returned.  If the username and password were OK, then we submit the
	// form, otherwise we ask the user to try again so that we don't submit the form and loose all
	// thier information because their username and password were wrong.
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
			var response = ajaxRequest.responseText;
			document.getElementById('loading').style.display = 'none';
			if(response == 'true')
			{
				//This can take some time server side, so I don't want the user to click a bajillion times.
				document.getElementById('submit_button').disabled = true;
				pel.submit();
			}
			else
				alert('Your Username and Password Didn\'t work.  Try Again!');
		}
	}

	//This is where we post the username and password along with a variable check to let the 
	// server know we are just checking them.  If they don't work then the we just ask the user
	// to change them before submission.  Otherwise we submit
	ajaxRequest.open("POST", 'index.php', true);
	params = "user="+pel.user.value+"&pass="+pel.pass.value+"&check=true";
	//Send the proper header information along with the request
	ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	ajaxRequest.setRequestHeader("Content-length", params.length);
	ajaxRequest.setRequestHeader("Connection", "close");
	ajaxRequest.send(params);
	
	return false;
}
