/**
 * @author Maurice
 */


var userID = -1;
var dateAdms = null;
var selectedURL = null;			
var selectedDB = null;
var loadMask = null;
var userRole = -1;
var loginPopup = null;

function ShowLogin()
{
	ClearSession();

	if (loginPopup == null) 
	{
		loginPopup = new Ext.Window({
			id: 'popup',
			width: 360,
			height: 160,
			resizable: false,
			frame: false,
			closable: false,
			html: '<div class="Popup">' +
			'<div class="PopupHeader"><div style="padding-top:2px;">Login</div></div>' +
			'<div class="PopupContent">' +
			'<table cellspacing=0 cellpadding=0 border=0 align="center">' +
			'<tr>' +
			'<td class="PopupColumnLabel">Email:</td><td><div id="divEmail" /></td>' +
			'</tr>' +
			'<tr>' +
			'<td class="PopupColumnLabel">Password:</td><td><div id="divPassword" /></td>' +
			'</tr>' +
			'</table>' +
			'</div>' +
			'<div class="PopupFooter">' +
			'<input id="btnLogin" class="PopupButton" type="button" value="Login" />' +
			'<input id="btnCancel" class="PopupButton" type="button" value="Cancel" />' +
			'</div>' +
			'</div>'
		
		});
		
		
		
		
		loginPopup.show(document.body);
		
		
		
		var txtEmail = new Ext.form.TextField({
			id: 'txtEmail',
			//vtype: 'email',
			renderTo: 'divEmail'
		});
		
		var txtPassword = new Ext.form.TextField({
			id: 'txtPassword',
			inputType: 'password',
			renderTo: 'divPassword'
		});
		
		
		Ext.get('btnLogin').on("click", function()
		{
			ShowLoader();
			Ext.Ajax.request({
					url: phpURL + 'Login.php',
				    disableCaching: true,
					//scriptTag: true,
					method: 'post',
					params: 
					{ 
						email: Ext.get("txtEmail").getValue(),
						password: Ext.get("txtPassword").getValue()
					},
					success: GrantAccess,
					timeout: 15000,
					failure: function() 
					{
						HideLoader();
						Ext.MessageBox.confirm('Confirm', 'Error loading data.  Attempt to reload?', ReloadLoginPage);
					}
				});
		});
		
		Ext.get('btnCancel').on("click", function()
		{
			loginPopup.hide();
			window.location.href = 'Unauthorized.html';
		});
	}
	else
	{
		loginPopup.show(document.body);
	}			
	
	setTimeout("Ext.get('txtEmail').dom.focus()",1000);

}




function RestartSetup()
{
	window.location.href = "CAPHCAdmin.html";
}



function GrantAccess(response)
{			
		
	var jsonObj = Ext.util.JSON.decode( response.responseText );
	
	if (jsonObj != null) 
	{
		if ( jsonObj.results.length == 0 )
		{
			Ext.MessageBox.show({
			           title: 'Login',
			           msg: 'Error logging in.  The email and/or password does not exist.',
			           buttons: Ext.MessageBox.OK,
					   icon: Ext.MessageBox.INFO
			       });
		}
		else
		{
			userRole = jsonObj.results[0].USER_ROLE;
			
			SetSession();
			
			loginPopup.hide();
			
			GetSession();
		}
	}	
	
	HideLoader();
}


function WriteContentToFile(url, content)
			{
				var f = air.File.applicationDirectory.resolvePath(url);				
                var fs = new air.FileStream();
                fs.open(f, air.FileMode.WRITE);
                
				fs.writeUTFBytes(content);
                fs.close();
            		
			}
			
			
			function ReadContentFromFile(url)
			{
			    var f = air.File.applicationDirectory.resolvePath(url);
				
                var fs = new air.FileStream();
                fs.open(f, air.FileMode.READ);
                var content = fs.readUTFBytes(fs.bytesAvailable);
                fs.close();
                
                return content;
            }


/*
function ClearSession()
{
	var tempMainDirectory = air.File.applicationDirectory.nativePath;
	
	WriteContentToFile(tempMainDirectory + "\\Session.cfg", "userRole==-1");				
}


function SetSession()
{
	var tempMainDirectory = air.File.applicationDirectory.nativePath;
	
	WriteContentToFile(tempMainDirectory + "\\Session.cfg", "userRole==" + userRole);				
}


function GetSession()
{
	var tempMainDirectory = air.File.applicationDirectory.nativePath;
	var content = ReadContentFromFile( tempMainDirectory + "\\Session.cfg");
	var lines = content.split('\r\n');
	
	for (var i = 0; i < lines.length; i++) 
	{
		var pairs = lines[i].split('==');
		
		if (pairs.length != 2) 
			continue;
				
		if (pairs[0] == 'userRole') 
			userRole = pairs[1];
	}
}
*/


function ClearSession()
{
	Ext.util.Cookies.set("userRole", -1);
	Ext.util.Cookies.set("userID", -1);				
	Ext.util.Cookies.set("dateAdms", "");
	//Ext.util.Cookies.set("selectedURL", "");
	Ext.util.Cookies.set("nselectedDB", "");
}


function SetSession()
{
	//if ( !selectedURL || selectedURL == null )
	//	selectedURL = '';
	
	Ext.util.Cookies.set("userRole", userRole);
	Ext.util.Cookies.set("userID", userID);				
	Ext.util.Cookies.set("dateAdms", dateAdms);
	//Ext.util.Cookies.set("selectedURL", selectedURL);
	Ext.util.Cookies.set("nselectedDB", selectedDB);
	 	
}


function GetSession()
{
	userRole = Ext.util.Cookies.get("userRole");
	userID = Ext.util.Cookies.get("userID");				
	dateAdms = Ext.util.Cookies.get("dateAdms");
	//selectedURL = Ext.util.Cookies.get("selectedURL");
	selectedDB = Ext.util.Cookies.get("nselectedDB");
}




/*
function SetSessionVar(key, val)
{
    var bytes = new air.ByteArray();

    bytes.writeUTFBytes(val);
	
	alert ( air.EncryptedLocalStore );
		alert ( air.EncryptedLocalStore.setItem );
    air.EncryptedLocalStore.setItem(key, bytes);
	
	alert( 'done' );
}


function GetSessionVar(key)
{
    var storedValue = air.EncryptedLocalStore.getItem(key);
    air.trace(storedValue.readUTFBytes(storedValue.length)); 
    air.EncryptedLocalStore.removeItem(key);	
}
*/

function ShowLoader()
{
	loadMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
	if ( loadMask )
		loadMask.show();
}

function HideLoader()
{
	if ( loadMask )
		loadMask.hide();
}


function ReloadLoginPage(btn)
{
	if ( btn == "yes" )
		window.location.href = window.location.href;
	else
		window.location.href = 'Unauthorized.html';
}

function ReloadPage(btn)
{
	if ( btn == "yes" )
		window.location.href = window.location.href;
}


 
 
var DATE_FORMAT_MYSQL = "Y-m-d";



function InitializeSettings()
{
	document.title = appTitle + ' ' + appVersion;
}


function CreateComboBox()
{	
	
}


function GetFormattedDate(dateObj)
{
	if (Date.formatFunctions && Date.formatFunctions.length > 0) 
	{
		return dateObj.format("Y-n-j");
	}
	else 
	{
		return dateObj.getFullYear() + '-' + (dateObj.getMonth() + 1) + '-' + dateObj.getDate();
	}
}


/*
function GetText(txtID, val)
{
    if (val != '') 
        document.getElementById(txtID).value = val;
    else 
        document.getElementById(txtID).value = 'N/A';
}
*/

function GetText(txtArea, val)
{
	if ( !txtArea )
		return;
	
    if (val != '') 
        txtArea.setValue(val);
    else 
        txtArea.setValue('N/A');
}


/**
 * Gets the URL parameters
 */
function GetParams()
{
	// separating the GET parameters from the current URL
	var getParams = document.URL.split("?");
	if ( getParams.length > 1)
	// transforming the GET parameters into a dictionnary
	var params = Ext.urlDecode(getParams[1]);
	return params;
}


/**
 * Toggles the provided div (given ID)
 * It sets the display, to the opposite, or the override value
 * @param {Object} divID
 * @param {Object} overrideValue
 */
function ToggleDiv(divID, overrideValue)
{
	
	var div = document.getElementById(divID);
	if ( div )
	{
		if (overrideValue) 
		{
			if (overrideValue == 'show') 
				div.style.display = 'block';
			else 
				div.style.display = 'none';
		}
		else 
		{
			if (div.style.display == 'none') 
				div.style.display = 'block';
			else 
				div.style.display = 'none';
		}
	}
}




function ConvertDate(date) 
{ 
    if (Ext.isAir) 
    { 
        return date.getFullYear() + '-' + (date.getMonth() + 1) + "-" + date.getDate(); 
    } 
    else 
    { 
        return date.format('Y-n-j');
    } 
}




/**
 * Given a datetime from mySQL, converts it into a regular Javascript Date Object
 * @param {Object} timestamp
 */
function ConvertMYSQLDate(timestamp) {
	if ( !timestamp )
		return null;
    //function parses mysql datetime string and returns javascript Date object
    //input has to be in this format: 2007-06-05 15:26:02
    var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
    var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
    return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
  }




function GetDateFormat(dateObj)
{
	if (dateObj.getValue() != '') 
	{
		return dateObj.getValue().format(DATE_FORMAT_MYSQL);		
	}
	else 
		return '';
}



var tplNavigation = new Ext.XTemplate('<tpl for="."><div class="x-combo-list-item">{name}</div></tpl>');

function CreateNavigation()
{
	GetSession();
	
	var dataArray = new Array();
	if ( userRole == 1 )
	{
		// ADMIN
		dataArray.push(["TrigTool_ChartSelect.html?chartType=1", "Trigger Tool"]);
		dataArray.push(["ChartSelect.html?chartType=0", "Physician Tool"]);
		dataArray.push(["ReportSelector.html", "Reports"]);		
	}
	else if ( userRole == 2 )
	{
		// Nurse (Trig Tool)
		dataArray.push(["TrigTool_ChartSelect.html?chartType=1", "Trigger Tool"]);
	}
	else if ( userRole == 3 )
	{
		// Physician
		dataArray.push(["ChartSelect.html?chartType=0", "Physician Tool"]);
	}
	else if ( userRole == 4 )
	{
		// Reports
		dataArray.push(["ReportSelector.html", "Reports"]);		
	}
		
	 // simple array store
    var store = new Ext.data.SimpleStore({
        fields: ['url', 'name'],
        data : dataArray
    });
	
	var comboNavigation = new Ext.form.ComboBox
	({
		store:store,
		tpl: tplNavigation,
		displayField:'name',
		valueField:'url',
	    typeAhead: true,
		triggerAction: 'all',
	    renderTo:'cboNavigation',
		allowBlank:false,
		selectOnFocus: true,
		anchor:'100%',
	    forceSelection:true,
		mode: 'local',
		listAlign:'b-t',
		listeners:
		{
			"select": NavigateTo
		}
		
	});
	
	//comboNavigation.render();
}



/**
 * Using ComboBox Select & Navigation, the Record MUST have a 'url' property
 * @param {Object} combo
 * @param {Object} record
 * @param {Object} index
 */
function NavigateTo(combo, record, index)
{
	window.location.href = record.data.url;	
}




function InitSession()
{
	if (Ext.isAir) 
	{
		//var f = air.File.applicationDirectory.resolvePath("state.cfg");
		var fp = new Ext.air.FileProvider({
			 file: 'state.cfg',
			 defaultState: {}
		});
		Ext.state.Manager.setProvider(fp);
	}
	else 
	{
		var cp = new Ext.state.CookieProvider();
		Ext.state.Manager.setProvider(cp);
	}
}

function ClearSession()
{
	Ext.state.Manager.clear("chartType");
	Ext.state.Manager.clear("id");
}

function SessionGet(key)
{
	alert( key );
	alert( Ext.state.Manager.get(key) );
	return Ext.state.Manager.get(key);
}

function SessionSet(key, val)
{
	Ext.state.Manager.set(key, val);
}



/**
 * Creates the Bottom Left corner item that
 * shows the MRID and date of admission
 * @param {String} mrid
 * @param {Date} dateAdmission
 */
function CreateChartInfo(mrid, dateAdmission)
{	
	//var chartInfo = 'MRID:  ' + mrid + '<br />Admit Date:  ' + dateAdmission.format('Y-n-j');
	var chartInfo = 'MRID:  ' + mrid + '<br />Admit Date:  ' + ConvertDate(dateAdmission);
	Ext.get('divChartInfo').dom.innerHTML = chartInfo;
}


/**
 * Takes a KeyID (usually 'mrid date', and creates the bottom corner info based on it
 * @param {String} keyID
 */
function CreateChartInfoByKey(keyID)
{	
	var pos = keyID.lastIndexOf(" ");
	if (pos > 0) {
		var mrid = keyID.substring(0, pos);
		var dateAdmission = keyID.substring(pos + 1);
		
		//CreateChartInfo(mrid, dateAdmission);
		
		var chartInfo = 'MRID:  ' + mrid + '<br />Admit Date:  ' + dateAdmission;
		Ext.get('divChartInfo').dom.innerHTML = chartInfo;
	}
	else
	{
		var chartInfo = 'MRID:  ' + keyID + '<br />Admit Date:  ' + dateAdms;
		Ext.get('divChartInfo').dom.innerHTML = chartInfo;
	}
}

/*
function CreateChartInfoByKey(keyID)
{	
	var pos = keyID.lastIndexOf(" ");
	var mrid = keyID.substring(0, pos);
	var dateAdmission = keyID.substring(pos+1);	
	
	//CreateChartInfo(mrid, dateAdmission);
	
	var chartInfo = 'MRID:  ' + mrid + '<br />Admit Date:  ' + dateAdmission;
	Ext.get('divChartInfo').dom.innerHTML = chartInfo;
}
*/








			function GetPrevModule(startingIndex, keyID, chartType)
			{
				Ext.Ajax.request({
					url: phpURL + 'GetModules.php?keyID=' + keyID,				
					startingIndex: startingIndex,
					keyID: keyID,
					chartType: chartType,
					success: LoadPrevModule
				});
			}
			
			function LoadPrevModule( response, options )
			{
				var startAt = options.startingIndex;
				
				var keyID = options.keyID;
				var chartType = options.chartType;
				
				var jsonObj = Ext.util.JSON.decode( response.responseText );				
				if (jsonObj != null) 
				{

					var moduleCare = jsonObj.results[0].HAS_MODULE_CARE;
					var	moduleMedication = jsonObj.results[0].HAS_MODULE_MEDICATION;
					var	moduleLab = jsonObj.results[0].HAS_MODULE_LAB;
					var	moduleSurgical = jsonObj.results[0].HAS_MODULE_SURGICAL;
					var	moduleICU = jsonObj.results[0].HAS_MODULE_ICU;
					var	moduleOther = jsonObj.results[0].HAS_MODULE_OTHER;
					var	noTrigger = jsonObj.results[0].NO_TRIGGER;


					if ( moduleOther == 1 && startAt >= 7 )
						window.location.href = 'ModuleOther.html?key=' + keyID + '&chartType=' + chartType;
					
					else if ( moduleICU == 1 && startAt >= 6 )
						window.location.href = 'ModuleICU.html?key=' + keyID + '&chartType=' + chartType;
						
					else if ( moduleSurgical == 1 && startAt >= 5 )
						window.location.href = 'ModuleSurgery2.html?key=' + keyID + '&chartType=' + chartType;
						
					else if ( moduleLab == 1 && startAt >= 4 )
						window.location.href = 'ModuleLab5.html?key=' + keyID + '&chartType=' + chartType;
					
					else if ( moduleMedication == 1 && startAt >= 3 )
						window.location.href = 'ModuleMedication1.html?key=' + keyID + '&chartType=' + chartType;
										
					else if ( moduleCare == 1 && startAt >= 2 )
						window.location.href = 'ModuleCare6.html?key=' + keyID + '&chartType=' + chartType;
				
					else 																						
						window.location.href = 'FunctionMenu.html?key=' + keyID + '&chartType=' + chartType;
				}				
			}

			function GetNextModule(startingIndex, keyID, chartType)
			{
				Ext.Ajax.request({
					url: phpURL + 'GetModules.php?keyID=' + keyID,				
					startingIndex: startingIndex,
					keyID: keyID,
					chartType: chartType,
					success: LoadNextModule
				});
			}
			
			function LoadNextModule( response, options )
			{
				var startAt = options["startingIndex"];
				var keyID = options.keyID;
				var chartType = options.chartType;
				
				var jsonObj = Ext.util.JSON.decode( response.responseText );				
				if (jsonObj != null) 
				{

					var moduleCare = jsonObj.results[0].HAS_MODULE_CARE;
					var	moduleMedication = jsonObj.results[0].HAS_MODULE_MEDICATION;
					var	moduleLab = jsonObj.results[0].HAS_MODULE_LAB;
					var	moduleSurgical = jsonObj.results[0].HAS_MODULE_SURGICAL;
					var	moduleICU = jsonObj.results[0].HAS_MODULE_ICU;
					var	moduleOther = jsonObj.results[0].HAS_MODULE_OTHER;
					var	noTrigger = jsonObj.results[0].NO_TRIGGER;

					
					
					if ( moduleCare == 1 && startAt == 0 )
						window.location.href = 'ModuleCare1.html?key=' + keyID + '&chartType=' + chartType;
						
					else if ( moduleMedication == 1 && startAt <= 1 )
						window.location.href = 'ModuleMedication1.html?key=' + keyID + '&chartType=' + chartType;
						
					else if ( moduleLab == 1 && startAt <= 2 )
						window.location.href = 'ModuleLab1.html?key=' + keyID + '&chartType=' + chartType;
						
					else if ( moduleSurgical == 1 && startAt <= 3 )
						window.location.href = 'ModuleSurgery1.html?key=' + keyID + '&chartType=' + chartType;
						
					else if ( moduleICU == 1 && startAt <= 4 )
						window.location.href = 'ModuleICU.html?key=' + keyID + '&chartType=' + chartType;
						
					else if ( moduleOther == 1 && startAt <= 5 )
						window.location.href = 'ModuleOther.html?key=' + keyID + '&chartType=' + chartType;
						
					else 
						window.location.href = 'TrigTool_Complete.html?key=' + keyID + '&chartType=' + chartType;		
						
																										
				}				
			}

			
			
			
			
			
			function GetNextAE(startingIndex, keyID, injuryID, chartType)
			{
				Ext.Ajax.request({
					url: phpURL + 'GetAEs.php?injuryID=' + injuryID,				
					startingIndex: startingIndex,
					keyID: keyID,
					injuryID: injuryID,
					chartType: chartType,
					success: LoadNextAE
				});
			}
			
			
			function LoadNextAE( response, options )
			{
				var startAt = options["startingIndex"];
				var keyID = options.keyID;
				var injuryID = options.injuryID;
				var chartType = options.chartType;
				
				var jsonObj = Ext.util.JSON.decode( response.responseText );				
				if (jsonObj != null) 
				{

					var	aeDiagnostic = jsonObj.results[0].ERROR_DIAGNOSTIC;
					var aeSurgical = jsonObj.results[0].ERROR_SURGICAL;
					var	aeFractures = jsonObj.results[0].ERROR_FRACTURE;
					var aeAnaesthesia = jsonObj.results[0].ERROR_ANAESTHESIA;
					var	aeMedical = jsonObj.results[0].ERROR_MEDICAL_PROCEDURE;
					var	aeDrug = jsonObj.results[0].ERROR_DRUG;
					var	aeFluid = jsonObj.results[0].ERROR_FLUID;					
					var	aeNotCovered = jsonObj.results[0].ERROR_NOT_COVERED;
					var	aeOCM = jsonObj.results[0].ERROR_OTHER;
					
					
					if ( aeDiagnostic == 1 && startAt == 0 )
						window.location.href = 'AE_Diagnostic1.html?key=' + keyID + '&chartType=' + chartType + '&injuryID=' + injuryID;
						
					else if ( aeSurgical == 1 && startAt <= 1 )
						window.location.href = 'AE_Surgical1.html?key=' + keyID + '&chartType=' + chartType + '&injuryID=' + injuryID;
						
					else if ( aeFractures == 1 && startAt <= 2 )
						window.location.href = 'AE_Fractures1.html?key=' + keyID + '&chartType=' + chartType + '&injuryID=' + injuryID;
						
					else if ( aeAnaesthesia == 1 && startAt <= 3 )
						window.location.href = 'AE_Anaesthesia1.html?key=' + keyID + '&chartType=' + chartType + '&injuryID=' + injuryID;
						
					else if ( aeMedical == 1 && startAt <= 4 )
						window.location.href = 'AE_MedicalProcedure1.html?key=' + keyID + '&chartType=' + chartType + '&injuryID=' + injuryID;
						
					else if ( aeDrug == 1 && startAt <= 5 )
						window.location.href = 'AE_Drug1.html?key=' + keyID + '&chartType=' + chartType + '&injuryID=' + injuryID;

					else if ( aeFluid == 1 && startAt <= 6 )
						window.location.href = 'AE_Fluid1.html?key=' + keyID + '&chartType=' + chartType + '&injuryID=' + injuryID;

					else if ( aeNotCovered == 1 && startAt <= 7 )
						window.location.href = 'AE_RISNCE1.html?key=' + keyID + '&chartType=' + chartType + '&injuryID=' + injuryID;

					else if ( aeOCM == 1 && startAt <= 8 )
						window.location.href = 'AE_OCM1.html?key=' + keyID + '&chartType=' + chartType + '&injuryID=' + injuryID;

					else if ( startAt <= 9 )
						window.location.href = 'AE_Preventability1.html?key=' + keyID + '&chartType=' + chartType + '&injuryID=' + injuryID;

						
					else
					{
						//window.location.href = 'PhysRev_Complete.html?key=' + keyID + '&chartType=' + chartType + '&injuryID=' + injuryID;						
						//window.location.href = 'PhysRev_Outcome1.html?key=' + keyID + '&chartType=' + chartType;
						 CheckShouldComplete(startAt, keyID, injuryID, chartType);
					}																					
				}				
			}
			
			
			function CheckShouldComplete(startingIndex, keyID, injuryID, chartType)
			{
				Ext.Ajax.request({
					url: phpURL + 'CheckUnreviewed.php?keyID=' + keyID,				
					startingIndex: startingIndex,
					keyID: keyID,
					injuryID: injuryID,
					chartType: chartType,
					success: ShouldComplete
				});
			}
			
			
			function ShouldComplete(response, options)
			{
				// Three Parts (Causation2.html, SuspectedInjuries.html & common.js)
				var startAt = options["startingIndex"];
				var keyID = options.keyID;
				var injuryID = options.injuryID;
				var chartType = options.chartType;
				window.location.href = 'PhysRev_SuspectedInjuries.html?key=' + keyID + '&chartType=' + chartType;
										
				/*
				var startAt = options["startingIndex"];
				var keyID = options.keyID;
				var injuryID = options.injuryID;
				var chartType = options.chartType;
				
				var jsonObj = Ext.util.JSON.decode(response.responseText);
				if (jsonObj != null) 
				{
					var numUnreviewed = jsonObj.results[0].NUM_UNREVIEWED;	
					if ( numUnreviewed == 0 )
						window.location.href = 'PhysRev_Outcomes1.html?key=' + keyID + '&chartType=' + chartType;
					else
						window.location.href = 'PhysRev_SuspectedInjuries.html?key=' + keyID + '&chartType=' + chartType;
				}
				*/
			}
			
			
			
			function GetPrevAE(startingIndex, keyID, injuryID, chartType)
			{
				Ext.Ajax.request({
					url: phpURL + 'GetAEs.php?injuryID=' + injuryID,				
					startingIndex: startingIndex,
					keyID: keyID,
					injuryID: injuryID,
					chartType: chartType,
					success: LoadPrevAE
				});
			}
			
			function LoadPrevAE( response, options )
			{
				var startAt = options.startingIndex;
				var injuryID = options.injuryID;
				var keyID = options.keyID;
				var chartType = options.chartType;
				
				var jsonObj = Ext.util.JSON.decode( response.responseText );				
				if (jsonObj != null) 
				{

					var	aeDiagnostic = jsonObj.results[0].ERROR_DIAGNOSTIC;
					var aeSurgical = jsonObj.results[0].ERROR_SURGICAL;
					var	aeFractures = jsonObj.results[0].ERROR_FRACTURE;
					var aeAnaesthesia = jsonObj.results[0].ERROR_ANAESTHESIA;
					var	aeMedical = jsonObj.results[0].ERROR_MEDICAL_PROCEDURE;
					var	aeDrug = jsonObj.results[0].ERROR_DRUG;
					var	aeFluid = jsonObj.results[0].ERROR_FLUID;					
					var	aeNotCovered = jsonObj.results[0].ERROR_NOT_COVERED;
					var	aeOCM = jsonObj.results[0].ERROR_OTHER;

					
					if ( startAt >= 11 )
						window.location.href = 'AE_Preventability1.html?key=' + keyID + '&chartType=' + chartType + '&injuryID=' + injuryID;

					else if ( aeOCM == 1 && startAt >= 10 )
						window.location.href = 'AE_OCM1.html?key=' + keyID + '&chartType=' + chartType + '&injuryID=' + injuryID;
						
					else if ( aeNotCovered == 1 && startAt >= 9 )
						window.location.href = 'AE_RISNCE1.html?key=' + keyID + '&chartType=' + chartType + '&injuryID=' + injuryID;

					else if ( aeFluid == 1 && startAt >= 8 )
						window.location.href = 'AE_Fluid1.html?key=' + keyID + '&chartType=' + chartType + '&injuryID=' + injuryID;

					else if ( location == 1 && startAt >= 7 )
						window.location.href = 'AE_Drug1.html?key=' + keyID + '&chartType=' + chartType + '&injuryID=' + injuryID;
					
					else if ( aeMedical == 1 && startAt >= 6 )
						window.location.href = 'AE_MedicalProcedure1.html?key=' + keyID + '&chartType=' + chartType + '&injuryID=' + injuryID;
						
					else if ( aeAnaesthesia == 1 && startAt >= 5 )
						window.location.href = 'AE_Anaesthesia1.html?key=' + keyID + '&chartType=' + chartType + '&injuryID=' + injuryID;
						
					else if ( aeFractures == 1 && startAt >= 4 )
						window.location.href = 'AE_Fractures1.html?key=' + keyID + '&chartType=' + chartType + '&injuryID=' + injuryID;
					
					else if ( aeSurgical == 1 && startAt >= 3 )
						window.location.href = 'AE_Surgical1.html?key=' + keyID + '&chartType=' + chartType + '&injuryID=' + injuryID;
										
					else if ( aeDiagnostic == 1 && startAt >= 2 )
						window.location.href = 'AE_Diagnostic1.html?key=' + keyID + '&chartType=' + chartType + '&injuryID=' + injuryID;
				
					else 																						
						//window.location.href = 'PhysRev_Complete.html?key=' + keyID + '&chartType=' + chartType + '&injuryID=' + injuryID;
						window.location.href = 'PhysRev_Classification.html?key=' + keyID + '&chartType=' + chartType + '&injuryID=' + injuryID;
				}				
			}

			

/*********************************************************************************
 * 
 * MANDATORY CHECKBOXES METHOD
 * 
 *********************************************************************************/

function GetCheckbox(chkName)
{
	var chkBoxes = Ext.select('*[name=' + chkName + ']');
	if (chkBoxes && chkBoxes.elements && chkBoxes.elements.length > 0) 
	{
		for ( var i = 0; i < chkBoxes.elements.length; i++ )
		{
			if ( chkBoxes.elements[i].checked )
				return true;
		}
		
		return false;
	}
	else
	{
		return true;
	}
	
	
}			
						
/*********************************************************************************
 * 
 * PRINTING
 * 
 *********************************************************************************/

function doPrintAir() 
{
	window.print();
//    var pjob = new window.runtime.flash.printing.PrintJob;
//    if ( pjob.start() )
//    {
//        var poptions = new window.runtime.flash.printing.PrintJobOptions;
//        poptions.printAsBitmap = true;
//        try
//        {
//            pjob.addPage(window.htmlLoader, null, poptions);
//            pjob.send();
//        }
//        catch (err)
//        {
//            alert("exception: " + err);
//        }
//    }
//    else
//    {
//        alert("PrintJob couldn't start");
//    }
}
//comment the line below if you do not want to mess with existing
//window.print
//window.print = doPrintAir;





/*!
 * Ext JS Library 3.0.0
 * Copyright(c) 2006-2009 Ext JS, LLC
 * licensing@extjs.com
 * http://www.extjs.com/license
 */
/**
 * @class Ext.util.Cookies
 * Utility class for managing and interacting with cookies.
 * @singleton
 */
Ext.util.Cookies = {
    /**
     * Create a cookie with the specified name and value. Additional settings
     * for the cookie may be optionally specified (for example: expiration,
     * access restriction, SSL).
     * @param {Object} name
     * @param {Object} value
     * @param {Object} expires (Optional) Specify an expiration date the
     * cookie is to persist until.  Note that the specified Date object will
     * be converted to Greenwich Mean Time (GMT). 
     * @param {String} path (Optional) Setting a path on the cookie restricts
     * access to pages that match that path. Defaults to all pages (<tt>'/'</tt>). 
     * @param {String} domain (Optional) Setting a domain restricts access to
     * pages on a given domain (typically used to allow cookie access across
     * subdomains). For example, "extjs.com" will create a cookie that can be
     * accessed from any subdomain of extjs.com, including www.extjs.com,
     * support.extjs.com, etc.
     * @param {Boolean} secure (Optional) Specify true to indicate that the cookie
     * should only be accessible via SSL on a page using the HTTPS protocol.
     * Defaults to <tt>false</tt>. Note that this will only work if the page
     * calling this code uses the HTTPS protocol, otherwise the cookie will be
     * created with default options.
     */
    set : function(name, value){
        var argv = arguments;
        var argc = arguments.length;
        var expires = (argc > 2) ? argv[2] : null;
        var path = (argc > 3) ? argv[3] : '/';
        var domain = (argc > 4) ? argv[4] : null;
        var secure = (argc > 5) ? argv[5] : false;
        document.cookie = name + "=" + escape(value) + ((expires === null) ? "" : ("; expires=" + expires.toGMTString())) + ((path === null) ? "" : ("; path=" + path)) + ((domain === null) ? "" : ("; domain=" + domain)) + ((secure === true) ? "; secure" : "");
    },

    /**
     * Retrieves cookies that are accessible by the current page. If a cookie
     * does not exist, <code>get()</code> returns <tt>null</tt>.  The following
     * example retrieves the cookie called "valid" and stores the String value
     * in the variable <tt>validStatus</tt>.
     * <pre><code>
     * var validStatus = Ext.util.Cookies.get("valid");
     * </code></pre>
     * @param {Object} name The name of the cookie to get
     * @return {Mixed} Returns the cookie value for the specified name;
     * null if the cookie name does not exist.
     */
    get : function(name){
        var arg = name + "=";
        var alen = arg.length;
        var clen = document.cookie.length;
        var i = 0;
        var j = 0;
        while(i < clen){
            j = i + alen;
            if(document.cookie.substring(i, j) == arg){
                return Ext.util.Cookies.getCookieVal(j);
            }
            i = document.cookie.indexOf(" ", i) + 1;
            if(i === 0){
                break;
            }
        }
        return null;
    },

    /**
     * Removes a cookie with the provided name from the browser
     * if found.
     * @param {Object} name The name of the cookie to remove
     */
    clear : function(name){
        if(Ext.util.Cookies.get(name)){
            document.cookie = name + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
        }
    },
    /**
     * @private
     */
    getCookieVal : function(offset){
        var endstr = document.cookie.indexOf(";", offset);
        if(endstr == -1){
            endstr = document.cookie.length;
        }
        return unescape(document.cookie.substring(offset, endstr));
    }
};


function CheckForNull(v)
{
	if ( v == null  || v == 'null' )
		return '';
	else
		return v;
}
