// Global variable definitions
var FAILUREMODEINDEX;  // set in checkSelectionFailureMode(), used in runFMEAInput()
var FAILUREMODEID;
var CAUSEINDEX;  // set in checkSelectionCause(), used in runFMEAInput()
var FAILUREPATHWAYID;
var STEP = 47;  // set in getProcessStep(), used in getFailureModeSelectable() and getCauseSelectable()
var PROCESS = 1;  // set in getProcessStep(), used in runFMEAInput()
var USERID = 1;
var USERINSTID = 0;
var SEVERITYRANKING = 0;
var RADIOSORTVALUE = 1;


// This function sets the globals USERID and USERINSTID
function setUserInfo(temp_userId) {
	
	USERID=temp_userId;
	
	var strURL="qiToolBox_set_user_info.php?userid="+USERID;
	
	var req = getXMLHTTP();
	
	if (req) {
		
		req.onreadystatechange = function() {
			
			if (req.readyState == 4) {
				// only if "OK"
				if (req.status == 200) {	
				
					USERINSTID = req.responseText;
											
				} else {
					alert("There was a problem while using XMLHTTP:\n" + req.statusText);
				}
			}				
		}			
		req.open("GET", strURL, true);
		req.send(null);		
	}
}

//<!--Script for changing dropdown menu based on radio button selection-->
function getXMLHTTP() { //fuction to return the xml http object
	var xmlhttp=false;	
	try{
		xmlhttp=new XMLHttpRequest();
	}
	catch(e)	{		
		try{			
			xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(e){
			try{
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch(e1){
				xmlhttp=false;
			}
		}
	}
	 	
	return xmlhttp;
}

// jQuery scripts
////////////////////

// This function sets up the tabs
function showTabs(tab_name) {
	$( tab_name ).tabs();
}


// This function displays tabs depending on user level (1 - team member, 2 - team lead)
function tabDisplay(userLevel) {
	if (userLevel != 2) {  // show only FMEA tab
		$("#tabs-2-tab").hide();
		$("#tabs-3-tab").hide();
	}
}


// This function sets FAILUREMODEID and FAILUREPATHWAYID to 0 when the tab is changed
function changeTabEvent(tab_name) {
	$(tab_name).bind('tabsselect', function(event, ui) {
		var tabSelected = ui.index;
		if (tabSelected == 1 || tabSelected == 2) {
			FAILUREMODEID = 0;
			FAILUREPATHWAYID = 0;
		}
	});
}


// This function sets up the help dialog boxes
function showDialogBox(dialog_name) {
	$( dialog_name ).dialog();
}


// This function sets up the modal confirmation dialog boxes
function showModalDialogBox(dialog_name,option) {  // the option allows for determination of whether the dialog has two options (2) or just one (1)
	$( "#dialog:ui-dialog" ).dialog( "destroy" );
	
	if (option == 1) {
		$( dialog_name ).dialog({
			resizable: false,
			//height:140,
			modal: true,
			buttons: {
				"OK": function() {
					$( this ).dialog( "close" );
				}
			}
		});
	}
	else if (option == 2) {
		$( dialog_name ).dialog({
			resizable: false,
			width:500,
			modal: true,
			open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); },
			buttons: {
				"Save or Modify your Failure Mode List": function() {
					$( this ).dialog( "close" );
					
					$("#yourInstList li").each(function looping(index) 
					{
						var failureModeText = $(this).text();
						
						// Generate random number to pass to strURL to prevent ie from caching the result...
						var rand = Math.floor(Math.random()*1000);
	
						var strURL="qiToolBox_insert_failure_mode.php?userid="+USERID+"&processid="+PROCESS+"&processstep="+STEP+"&failuremodetext="+failureModeText+"&rand="+rand;
						
						var req = getXMLHTTP();
					
						if (req) {
							
							req.onreadystatechange = function() {
								if (req.readyState == 4) {
									// only if "OK"
									if (req.status == 200) {						
										
									} else {
										alert("There was a problem while using XMLHTTP:\n" + req.statusText);
									}
								}				
							}			
							req.open("GET", strURL, true);
							req.send(null);
						}	
					});
					
					// We also need to remove any failure modes no longer listed
					removeFailureModesFunction();
					
					// Update the failure mode selectable in the failure pathway tab (tab 2)
					setTimeout("getFailureModeYourInst()", 100);
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
			}
		});
	}
	else if (option == 3) {
		$( dialog_name ).dialog({
			resizable: false,
			width:500,
			modal: true,
			open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); },
			buttons: {
				"Save or Modify your Failure Pathway List": function() {
					$( this ).dialog( "close" );
					
					$("#yourInstListFP li").each(function looping(index) 
					{
						var failurePathwayText = $(this).text();
						
						// Generate random number to pass to strURL to prevent ie from caching the result...
						var rand = Math.floor(Math.random()*1000);
	
						var strURL="qiToolBox_insert_failure_pathway.php?userid="+USERID+"&processid="+PROCESS+"&processstep="+STEP+"&failuremodeid="+FAILUREMODEID+"&failurepathwaytext="+failurePathwayText+"&rand="+rand;
						
						var req = getXMLHTTP();
					
						if (req) {
							
							req.onreadystatechange = function() {
								if (req.readyState == 4) {
									// only if "OK"
									if (req.status == 200) {						
										
									} else {
										alert("There was a problem while using XMLHTTP:\n" + req.statusText);
									}
								}				
							}			
							req.open("GET", strURL, true);
							req.send(null);
						}
						
					});
					
					// We also need to remove any failure pathways no longer listed
					removeFailurePathwaysFunction();
					
					// Update the failure pathway selectable in the failure pathway tab (tab 2)
					setTimeout("getFailurePathwayDragDropYourInst()", 100);
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
			}
		});
	}
	else if (option == 4) {  // user should choose whether to update existing severity ranking entry (2) or to add a new severity ranking entry (3)
		
		$( dialog_name ).dialog({
			resizable: false,
			width:600,
			modal: true,
			open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); },
			buttons: {
				"Update Existing Severity Ranking": function() {
					$( this ).dialog( "close" );
					
					var severity=document.getElementById('severity');
		
					// Generate random number to pass to strURL to prevent ie from caching the result...
					var rand = Math.floor(Math.random()*1000);
	
					var strURL="qiToolBox_insert_fmea_severity.php?userid="+USERID+"&processid="+PROCESS+"&processstep="+STEP+"&failuremodeid="+FAILUREMODEID+
						"&severity="+severity.value+"&testORupdateORnew="+2+"&rand="+rand;  // pass 1 to test whether severity data already exists, 2 to update existing data, or 3 to enter new data
			
					var req = getXMLHTTP();
				
					if (req) {
						req.onreadystatechange = function() {
							if (req.readyState == 4) {
								// only if "OK"
								if (req.status == 200) {						
									
								} else {
									alert("There was a problem while using XMLHTTP:\n" + req.statusText);
								}
							}				
						}			
						req.open("GET", strURL, true);
						req.send(null);
					}
						
				},
				"Create New Severity Ranking": function() {
					$( this ).dialog( "close" );
					
					var severity=document.getElementById('severity');
		
					// Generate random number to pass to strURL to prevent ie from caching the result...
					var rand = Math.floor(Math.random()*1000);
	
					var strURL="qiToolBox_insert_fmea_severity.php?userid="+USERID+"&processid="+PROCESS+"&processstep="+STEP+"&failuremodeid="+FAILUREMODEID+
						"&severity="+severity.value+"&testORupdateORnew="+3+"&rand="+rand;  // pass 1 to test whether severity data already exists, 2 to update existing data, or 3 to enter new data
				
					var req = getXMLHTTP();
				
					if (req) {
						req.onreadystatechange = function() {
							if (req.readyState == 4) {
								// only if "OK"
								if (req.status == 200) {						
									
								} else {
									alert("There was a problem while using XMLHTTP:\n" + req.statusText);
								}
							}				
						}			
						req.open("GET", strURL, true);
						req.send(null);
					}
						
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
			}
		});
	}
	else if (option == 5) {  // user should choose whether to update existing occurrence/detect ranking entry (2) or to add a new occurrence/detect ranking entry (3)
		
		$( dialog_name ).dialog({
			resizable: false,
			width:500,
			modal: true,
			open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); },
			buttons: {
				"Update Existing Severity Ranking": function() {
					$( this ).dialog( "close" );
					
					var severity=document.getElementById('severity');
					var occurrence=document.getElementById('occurrence');
					var detectability=document.getElementById('detectability');
				
					// Generate random number to pass to strURL to prevent ie from caching the result...
					var rand = Math.floor(Math.random()*1000);
	
					var strURL="qiToolBox_insert_fmea_occurrence.php?userid="+USERID+"&processid="+PROCESS+"&processstep="+STEP+"&failuremodeid="+FAILUREMODEID+
						"&severity="+severity.value+"&failurepathwayid="+FAILUREPATHWAYID+"&occurrence="+occurrence.value+
						"&detectability="+detectability.value+"&testORupdateORnew="+2+"&rand="+rand; // pass 1 to test whether severity data already exists, 2 to update existing data, or 3 to enter new data
		
					var req = getXMLHTTP();
				
					if (req) {
						req.onreadystatechange = function() {
							if (req.readyState == 4) {
								// only if "OK"
								if (req.status == 200) {						
									
								} else {
									alert("There was a problem while using XMLHTTP:\n" + req.statusText);
								}
							}				
						}			
						req.open("GET", strURL, true);
						req.send(null);
					}
						
				},
				"Create New Severity Ranking": function() {
					$( this ).dialog( "close" );
					
					var severity=document.getElementById('severity');
					var occurrence=document.getElementById('occurrence');
					var detectability=document.getElementById('detectability');
				
					// Generate random number to pass to strURL to prevent ie from caching the result...
					var rand = Math.floor(Math.random()*1000);
	
					var strURL="qiToolBox_insert_fmea_occurrence.php?userid="+USERID+"&processid="+PROCESS+"&processstep="+STEP+"&failuremodeid="+FAILUREMODEID+
						"&severity="+severity.value+"&failurepathwayid="+FAILUREPATHWAYID+"&occurrence="+occurrence.value+
						"&detectability="+detectability.value+"&testORupdateORnew="+3+"&rand="+rand; // pass 1 to test whether severity data already exists, 2 to update existing data, or 3 to enter new data
		
					var req = getXMLHTTP();
				
					if (req) {
						req.onreadystatechange = function() {
							if (req.readyState == 4) {
								// only if "OK"
								if (req.status == 200) {						
									
								} else {
									alert("There was a problem while using XMLHTTP:\n" + req.statusText);
								}
							}				
						}			
						req.open("GET", strURL, true);
						req.send(null);
					}
						
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
			}
		});
	}
	else if (option == 6) {
		$( dialog_name ).dialog({
			resizable: false,
			//height:140,
			width:500,
			modal: true,
			open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); },
			buttons: {
				"Update Existing Severity Ranking": function() {
					$( this ).dialog( "close" );
					
					var severity=document.getElementById('severity');
		
					// Generate random number to pass to strURL to prevent ie from caching the result...
					var rand = Math.floor(Math.random()*1000);
	
					var strURL="qiToolBox_insert_fmea_severity.php?userid="+USERID+"&processid="+PROCESS+"&processstep="+STEP+"&failuremodeid="+FAILUREMODEID+
						"&severity="+severity.value+"&testORupdateORnew="+2+"&rand="+rand;  // pass 1 to test whether severity data already exists, 2 to update existing data, or 3 to enter new data
			
					var req = getXMLHTTP();
				
					if (req) {
						req.onreadystatechange = function() {
							if (req.readyState == 4) {
								// only if "OK"
								if (req.status == 200) {						
									
								} else {
									alert("There was a problem while using XMLHTTP:\n" + req.statusText);
								}
							}				
						}			
						req.open("GET", strURL, true);
						req.send(null);
					}
					
				},
				Cancel: function() {
					$( this ).dialog( "close" );
					
					document.getElementById("severity").options[SEVERITYRANKING].selected = true;
				}
			}
		});
	}
}

/////////////////////


//<!--Script for displaying selected process step-->
function getProcessStep(process,step) {		
	
	// Generate random number to pass to strURL to prevent ie from caching the result...
	var rand = Math.floor(Math.random()*1000);
	
	var strURL="qiToolBox_process_step.php?process="+process+"&step="+step+"&rand="+rand;
	
	PROCESS=process;
	STEP=step;
		
	var req = getXMLHTTP();
	
	if (req) {
		
		req.onreadystatechange = function() {
			
			if (req.readyState == 4) {
				// only if "OK"
				if (req.status == 200) {
					
					//document.getElementById('processdiv').innerHTML=req.responseText;
					//document.getElementById('processFPdiv').innerHTML=req.responseText;
					document.getElementById('processFMEAdiv').innerHTML=req.responseText;
					//document.getElementById('processFMEAdiv2').innerHTML=req.responseText;
				} else {
					alert("There was a problem while using XMLHTTP:\n" + req.statusText);
				}
			}				
		}			
		req.open("GET", strURL, true);
		req.send(null);	
	}		
}


// This function sets up the jQuery Failure Mode and Failure Pathway draggable/droppable
function setUpFMandFPDragDrop() {    
    
    /* Set-up the Failure Mode Drag/Drops*/							    
    $("#yourInstList ol").droppable({
        activeClass: "ui-state-default",
        hoverClass: "ui-state-hover",
        accept: '.globalList-item',
        drop: function(event, ui) {
            $(this).find(".placeholder").remove();
            var temp1 = ui.draggable.attr('id');
            $("<li id=\""+temp1+"\"></li>").text(ui.draggable.text())
                .addClass("yourInstList-item")
                .appendTo(this);
            $(ui.draggable).remove();
        }
    }).sortable({
        items: "li:not(.placeholder)",
        sort: function() {
            $(this).removeClass("ui-state-default");
        }
    });
    $("#globalList ul").droppable({
        drop: function(event, ui) {
            $(ui.draggable).remove();
        },
        hoverClass: "ui-state-hover",
        accept: '.yourInstList-item'
    });
    $("#garbage1").droppable({
        activeClass: "ui-state-default",
        hoverClass: "ui-state-hover",
        accept: '.yourInstList-item',
        drop: function(event, ui) {
            $(ui.draggable).remove();
        }
    });
    $("#garbage2").droppable({
        activeClass: "ui-state-default",
        hoverClass: "ui-state-hover",
        accept: '.yourInstList-item',
        drop: function(event, ui) {
            $(ui.draggable).remove();
        }
    });
    
    /* Set-up the Failure Pathway Drag/Drops*/
    $("#yourInstListFP ol").droppable({
        activeClass: "ui-state-default",
        hoverClass: "ui-state-hover",
        accept: '.globalList-item',
        drop: function(event, ui) {
            $(this).find(".placeholder").remove();
            var temp2 = ui.draggable.attr('id');
            $("<li id=\""+temp2+"\"></li>").text(ui.draggable.text())
                .addClass("yourInstList-item")
                .appendTo(this);
            $(ui.draggable).remove();
        }
    }).sortable({
        items: "li:not(.placeholder)",
        sort: function() {
            $(this).removeClass("ui-state-default");
        }
    });
    $("#globalListFP ul").droppable({
        drop: function(event, ui) {
            $(ui.draggable).remove();
        },
        hoverClass: "ui-state-hover",
        accept: '.yourInstList-item'
    });
}

// This function adds a free-text Failure Mode to yourInstList
function addFailureModeFunction(textAreaName) {
      	
      	// Catch user errors and deliver prompts
	
	if (USERID == 1) {  // if user not logged in
		showModalDialogBox("#dialog-please-login",1);
		return;
	}
	
	if (STEP == 47) {  // if user has not selected a process step
		showModalDialogBox("#dialog-please-select-step",1);
		return;
	}
	
	var value = $(textAreaName).val();
    	
    	if (value.length >= 1) {
    		$("#failureModeDragDropYourList").find(".temptemp").remove();
    		var listItem = $("<li></li>").text(value).addClass("yourInstList-item");
        	listItem.appendTo("#yourInstList ol");
        	
        } else {
        	showModalDialogBox("#dialog-freeText-failure",1); 
        }
}

// This function adds a free-text Failure Pathway to yourInstList
function addFailurePathwayFunction(textAreaName) {
									      	
      	// Catch user errors and deliver prompts
	
	if (USERID == 1) {  // if user not logged in
		showModalDialogBox("#dialog-please-login",1);
		return;
	}
	
	if (STEP == 47) {  // if user has not selected a process step
		showModalDialogBox("#dialog-please-select-step",1);
		return;
	}
	
	if (isEmpty(FAILUREMODEID) == true || FAILUREMODEID == 0) {  // if user has not selected a failure mode to analyse
		showModalDialogBox("#dialog-please-select-failure-mode",1);
		return;
	}
	
	var value = $(textAreaName).val();
	
	if (value.length >= 1) {
		$("#failurePathwayDragDropYourList").find(".temptemp").remove();
		var listItem = $("<li></li>").text(value).addClass("yourInstList-item");
        	listItem.appendTo("#yourInstListFP ol");
        } else {
        	showModalDialogBox("#dialog-freeText-pathway",1); 
        }
}
								
//<!--Script for filling jQuery Failure MODES - Global - draggable/droppable-->
function getFailureModeDragDrop() {	
	
	// Set FAILUREMODEID to 0;
	FAILUREMODEID = 0;
	
	// Catch user errors and deliver prompts
	
	if (USERID == 1) {  // if user not logged in
		showModalDialogBox("#dialog-please-login",1);
		return;
	}
	
	if (STEP == 47) {  // if user has not selected a process step
		showModalDialogBox("#dialog-please-select-step",1);
		return;
	}
	
	// Generate random number to pass to strURL to prevent ie from caching the result...
	var rand = Math.floor(Math.random()*1000);
	
	// run failure_selectable script to find 'global' Failure Modes
	var strURL="qiToolBox_failure_mode_selectable.php?userid="+1+"&userinstid="+USERINSTID+"&processid="+PROCESS+"&processstep="+STEP+"&rand="+rand;
	
	var req = getXMLHTTP();
	
	if (req) {
		
		req.onreadystatechange = function() {
			
			if (req.readyState == 4) {
				// only if "OK"
				if (req.status == 200) {	
				
					setUpFMandFPDragDrop();
									
					document.getElementById('failureModeDragDropGlobal').innerHTML=req.responseText;
					
					$("#globalList li").text(function() { 
				        	$(this).removeClass(""); 
				                $(this).addClass("globalList-item"); 
				        });
				        $("#globalList li").draggable({
					        appendTo: "body",
					        revert: "invalid"
					});
															
				} else {
					alert("There was a problem while using XMLHTTP:\n" + req.statusText);
				}
			}				
		}			
		req.open("GET", strURL, true);
		req.send(null);
		
	}
	
	// run failure_selectable script to find 'your-institution' Failure Modes
	if (USERID != 1) {
		getFailureModeYourInst();
		getFailurePathwayDragDrop();
		getFailurePathwayDragDropYourInst();
	}
}


// This function fills both the institution specific Failure Mode Drag Drops on the Failure Mode tab and the 
// institution specific Failure Mode Selectables on the Failure Pathways tab 
function getFailureModeYourInst() {
	
	// Generate random number to pass to strURL to prevent ie from caching the result...
	var rand = Math.floor(Math.random()*1000);
	
	var strURL="qiToolBox_failure_mode_selectable.php?userid="+USERID+"&userinstid="+USERINSTID+"&processid="+PROCESS+"&processstep="+STEP+"&rand="+rand;
	
	// set variable to pass to initSelectable for Failure Pathways tab
	var divtosearchFPtab = "#failuremodescssTab2 ul li";
	
	// set variable to pass to initSelectable for FMEA tab
	var divtosearchFMEAtab = "#failuremodescssTab3 ul li";
	
	var req = getXMLHTTP();
	
	if (req) {
		
		req.onreadystatechange = function() {
			
			if (req.readyState == 4) {
				// only if "OK"
				if (req.status == 200) {	
					
					document.getElementById('failureModeDragDropYourList').innerHTML=req.responseText;
					
					var listItem = $("#yourInstList li").addClass("yourInstList-item");
				        listItem.appendTo("#yourInstList ol");
				        
				        document.getElementById('failureselectableFPdiv').innerHTML=req.responseText;
					initSelectable(USERID,PROCESS,divtosearchFPtab,1);
					
					document.getElementById('failureselectablediv').innerHTML=req.responseText;
					initSelectable(USERID,PROCESS,divtosearchFMEAtab,1);
					
				} else {
					alert("There was a problem while using XMLHTTP:\n" + req.statusText);
				}
			}				
		}			
		req.open("GET", strURL, true);
		req.send(null);	
	}			
}

//<!--Script for filling jQuery Failure PATHWAYS - Global - draggable/droppable-->
function getFailurePathwayDragDrop() {	
	
	// Catch user errors and deliver prompts
	
	if (USERID == 1) {  // if user not logged in
		showModalDialogBox("#dialog-please-login",1);
		return;
	}
	
	if (STEP == 47) {  // if user has not selected a process step
		showModalDialogBox("#dialog-please-select-step",1);
		return;
	}
	
	// Generate random number to pass to strURL to prevent ie from caching the result...
	var rand = Math.floor(Math.random()*1000);
	
	// run failure_selectable script to find 'global' Failure Modes
	var strURL="qiToolBox_failure_pathway_selectable.php?userid1="+1+"&userinstid="+USERINSTID+"&processid1="+PROCESS+"&processstep1="+STEP+"&failuremodeid1="+FAILUREMODEID+"&rand="+rand;
	
	var req = getXMLHTTP();
	
	if (req) {
		
		req.onreadystatechange = function() {
			
			if (req.readyState == 4) {
				// only if "OK"
				if (req.status == 200) {	
				
					document.getElementById('failurePathwayDragDropGlobal').innerHTML=req.responseText;
					
					$("#globalListFP li").text(function() { 
				        	$(this).removeClass(""); 
				                $(this).addClass("globalList-item"); 
				        });
				        $("#globalListFP li").draggable({
					        appendTo: "body",
					        revert: "invalid"
					});
					
															
				} else {
					alert("There was a problem while using XMLHTTP:\n" + req.statusText);
				}
			}				
		}			
		req.open("GET", strURL, true);
		req.send(null);	
	}
		
}


// This function fills both the institution specific Failure Pathway Drag Drops on the Failure Pathway tab and the 
// institution specific Failure Pathway Selectables on the FMEA tab
function getFailurePathwayDragDropYourInst() {	
	
	// Generate random number to pass to strURL to prevent ie from caching the result...
	var rand = Math.floor(Math.random()*1000);
	
	var strURL="qiToolBox_failure_pathway_selectable.php?userid1="+USERID+"&userinstid="+USERINSTID+"&processid1="+PROCESS+"&processstep1="+STEP+"&failuremodeid1="+FAILUREMODEID+"&rand="+rand;
	
	var divtosearchFMEAtab = "#causescss ul li";
	
	var req = getXMLHTTP();
	
	if (req) {
		
		req.onreadystatechange = function() {
			
			if (req.readyState == 4) {
				// only if "OK"
				if (req.status == 200) {	
				
					document.getElementById('failurePathwayDragDropYourList').innerHTML=req.responseText;
					var listItem = $("#yourInstListFP li").addClass("yourInstList-item");
				        listItem.appendTo("#yourInstListFP ol");
				        
				        document.getElementById('causeselectablediv').innerHTML=req.responseText;
					initSelectable(USERID,PROCESS,divtosearchFMEAtab,2);
        										
				} else {
					alert("There was a problem while using XMLHTTP:\n" + req.statusText);
				}
			}				
		}			
		req.open("GET", strURL, true);
		req.send(null);	
	}			
}


// This function handles initialization of the jquery selectable list
function initSelectable(userId,processId,divtosearch,failureORcause)
{
	$(divtosearch).each(function looping(index) 
	{
		$(this).mouseover(function onItemOver() 
		{
			$(this).css("cursor","pointer");
		});
		
		if(failureORcause == 1) {
			$(this).click(function onItemClick() 
			{
				FAILUREMODEID = $(this).attr('id');
				
				checkSelectionFailureMode(userId,processId,divtosearch,index);
				
				getFailurePathwayDragDrop();
				getFailurePathwayDragDropYourInst();
				
				// If on FMEA page, retreive available information from the database
				if (divtosearch == "#failuremodescssTab3 ul li") {
				
					FAILUREPATHWAYID = 0;  // Reset failure pathway index when new failure mode is selected
					SEVERITYRANKING = 0;  // Reselt severity ranking when new failure mode is selected
					
					// Generate random number to pass to strURL to prevent ie from caching the result...
					var rand = Math.floor(Math.random()*1000);
	
					var strURL="qiToolBox_check_fmea_severity.php?userid="+USERID+"&processid="+PROCESS+"&processstep="+STEP+"&failuremodeid="+FAILUREMODEID+"&rand="+rand;
		
					var req = getXMLHTTP();
					
					if (req) {
						
						req.onreadystatechange = function() {
							
							if (req.readyState == 4) {
								// only if "OK"
								if (req.status == 200) {
									if (isEmpty(req.responseText) == true) {
										document.getElementById("severity").options[0].selected = true;
										document.getElementById("occurrence").options[0].selected = true;  // Reset occurrence and detectability when new failure mode is selected
										document.getElementById("detectability").options[0].selected = true;
									} else {
										SEVERITYRANKING = req.responseText;
										document.getElementById("severity").options[req.responseText].selected = true;
										document.getElementById("occurrence").options[0].selected = true;
										document.getElementById("detectability").options[0].selected = true;
									}
								} else {
									alert("There was a problem while using XMLHTTP:\n" + req.statusText);
								}
							}				
						}			
						req.open("GET", strURL, true);
						req.send(null);	
					}
				}
			});
		} else {
			$(this).click(function onItemClick() 
			{
				FAILUREPATHWAYID = $(this).attr('id');
				
				checkSelectionCause(userId,processId,divtosearch,index);
				
				// If on FMEA page, retreive available information from the database
				if (divtosearch == "#causescss ul li") {
				
					// Generate random number to pass to strURL to prevent ie from caching the result...
					var rand = Math.floor(Math.random()*1000);
	
					var strURL="qiToolBox_check_fmea_occurrence.php?userid="+USERID+"&processid="+PROCESS+"&processstep="+STEP+"&failurepathwayid="+FAILUREPATHWAYID+"&rand="+rand;
		
					var req = getXMLHTTP();
					
					if (req) {
						
						req.onreadystatechange = function() {
							
							if (req.readyState == 4) {
								// only if "OK"
								if (req.status == 200) {
									var word = req.responseText.split("+");
									document.getElementById("occurrence").options[word[0]].selected = true;
									document.getElementById("detectability").options[word[1]].selected = true;
								} else {
									alert("There was a problem while using XMLHTTP:\n" + req.statusText);
								}
							}				
						}			
						req.open("GET", strURL, true);
						req.send(null);	
					}
				}
			});
		}
	});
}


// This function handles colour animation of the Failure Modes jquery selectable list
function checkSelectionFailureMode(userId,processId,divtosearch,id)
{
	$(divtosearch).each(function looping(index) 
	{
		if(index==id)
		{
			$(this).animate( { backgroundColor: "#CCC", color: "#333" }, 500);
			
			FAILUREMODEINDEX = id + 1;
			
		}
		else
		{
			$(this).animate( { backgroundColor: "#333", color: "#CCC" }, 500);
		}
	});
}


// This function handles colour animation of the Causes jquery selectable list
function checkSelectionCause(userId,processId,divtosearch,id)
{
	$(divtosearch).each(function looping(index) 
	{
		if(index==id)
		{
			$(this).animate( { backgroundColor: "#CCC", color: "#333" }, 500);
			
			CAUSEINDEX = id + 1;
		}
		else
		{
			$(this).animate( { backgroundColor: "#333", color: "#CCC" }, 500);
		}
	});
}


// This function handles saving the users Failure Mode List to the database
function saveFailureModesFunction() {

	// Catch user errors and deliver prompts
	
	if (USERID == 1) {  // if user not logged in
		showModalDialogBox("#dialog-please-login",1);
		return;
	}
	
	if (STEP == 47) {  // if user has not selected a process step
		showModalDialogBox("#dialog-please-select-step",1);
		return;
	}
	
	// Call modal confirm dialog box - user should confirm that this action permanently changes their institution failure mode list
	showModalDialogBox("#dialog-confirm-FM",2);
	
	// strUrl, ajax, and function calls moved to showModalDialogBox	
}


// This function handles saving the users Failure Pathway List to the database
function saveFailurePathwaysFunction() {
	
	// Catch user errors and deliver prompts
	
	if (USERID == 1) {  // if user not logged in
		showModalDialogBox("#dialog-please-login",1);
		return;
	}
	
	if (STEP == 47) {  // if user has not selected a process step
		showModalDialogBox("#dialog-please-select-step",1);
		return;
	}
	
	if (isEmpty(FAILUREMODEID) == true || FAILUREMODEID == 0) {  // if user has not selected a failure mode to analyse
		showModalDialogBox("#dialog-please-select-failure-mode",1);
		return;
	}
	
	// Call modal confirm dialog box - user should confirm that this action permanently changes their institution failure mode list
	showModalDialogBox("#dialog-confirm-FP",3);
	
	// strUrl, ajax, and function calls moved to showModalDialogBox
}


// This function removes failure modes from the failure modes table if they are no longer listed at the time saveFailureModeFunciton() is called
function removeFailureModesFunction() {

	var failureModeTextArray=new Array();
	
	$("#yourInstList li").each(function looping(index) 
	{
		failureModeTextArray[index] = $(this).text()+"thisisadelimeter";	
	});
	
	// Generate random number to pass to strURL to prevent ie from caching the result...
	var rand = Math.floor(Math.random()*1000);
	
	var strURL="qiToolBox_remove_failure_mode.php?userid="+USERID+"&userinstid="+USERINSTID+"&processid="+PROCESS+"&processstep="+STEP+"&failuremodetextarray="+failureModeTextArray+"&rand="+rand;
		
	var req = getXMLHTTP();

	if (req) {
		
		req.onreadystatechange = function() {
			if (req.readyState == 4) {
				// only if "OK"
				if (req.status == 200) {						
					
				} else {
					alert("There was a problem while using XMLHTTP:\n" + req.statusText);
				}
			}				
		}			
		req.open("GET", strURL, true);
		req.send(null);
	}
	
}

// This function removes failure pathways from the failure pathways table if they are no longer listed at the time saveFailurePathwayFunciton() is called
function removeFailurePathwaysFunction() {

	// Generate random number to pass to strURL to prevent ie from caching the result...
	var rand = Math.floor(Math.random()*1000);
	
	var failurePathwayTextArray=new Array();
	
	$("#yourInstListFP li").each(function looping(index) 
	{
		failurePathwayTextArray[index] = $(this).text()+"thisisadelimeter";	
	});
	
	var strURL="qiToolBox_remove_failure_pathway.php?userid="+USERID+"&userinstid="+USERINSTID+"&processid="+PROCESS+"&processstep="+STEP+"&failuremodeid="+FAILUREMODEID+"&failurepathwaytextarray="+failurePathwayTextArray+"&rand="+rand;
		
	var req = getXMLHTTP();

	if (req) {
		
		req.onreadystatechange = function() {
			if (req.readyState == 4) {
				// only if "OK"
				if (req.status == 200) {						
					//alert("remove failure pathway function:"+req.responseText);
				} else {
					alert("There was a problem while using XMLHTTP:\n" + req.statusText);
				}
			}				
		}			
		req.open("GET", strURL, true);
		req.send(null);
	}
	
	// Update your institution list of failure pathways for selected failure mode
	//getFailurePathwayDragDropYourInst();

}

// This function handles email updates signup
function runSignUp() {		
	
	var email=document.getElementById('signup_email');
	
	var strURL="signup.php?signupemail="+email.value;
	
	var req = getXMLHTTP();
	
	if (req) {
		
		req.onreadystatechange = function() {
			if (req.readyState == 4) {
				// only if "OK"
				if (req.status == 200) {						
					document.getElementById('signupdiv').innerHTML=req.responseText;						
				} else {
					alert("There was a problem while using XMLHTTP:\n" + req.statusText);
				}
			}				
		}			
		req.open("GET", strURL, true);
		req.send(null);
	}		
}

// This function handles user login
function runLogin() {		
	
	var usr_email=document.getElementById('usr_email');
	var pwd=document.getElementById('pwd');
	
	// Check to see if 'remember me' checkbox is checked
	//var isChecked = document.getElementById("remember").checked;
	//if (isChecked) {
	//	var remember=document.getElementById("remember").value;
	//} else {
	//	remember = 0;
	//}
	var remember = 1;
		
	var strURL="login.php?usr_email="+usr_email.value+"&pwd="+pwd.value+"&remember="+remember;
	
	var req = getXMLHTTP();
	
	if (req) {
		
		req.onreadystatechange = function() {
			if (req.readyState == 4) {
				// only if "OK"
				if (req.status == 200) {
				
					if (req.responseText.charAt(0) == "*") {						
						document.getElementById('logindiv').innerHTML=req.responseText;	
					} else {
						window.location.reload();
					}					
				} else {
					alert("There was a problem while using XMLHTTP:\n" + req.statusText);
				}
			}				
		}			
		req.open("GET", strURL, true);
		req.send(null);
	}		
}

// This function handles user logout
function runLogout() {		
	
	var strURL="logout.php";
	
	var req = getXMLHTTP();
	
	if (req) {
		
		req.onreadystatechange = function() {
			if (req.readyState == 4) {
				// only if "OK"
				if (req.status == 200) {						
					//document.getElementById('logindiv').innerHTML=req.responseText;
					window.location.reload();						
				} else {
					alert("There was a problem while using XMLHTTP:\n" + req.statusText);
				}
			}				
		}			
		req.open("GET", strURL, true);
		req.send(null);
	}
			
}

// This function handles user registration
function runRegister() {		
	
	var full_name=document.getElementById('full_name');
	var country=document.getElementById('country');
	var user_name=document.getElementById('user_name');
	var usr_email=document.getElementById('usr_email_reg');
	var pwd=document.getElementById('pwd_reg');
	var pwd2=document.getElementById('pwd2_reg');
	
	var recaptcha_challenge=document.getElementById('recaptcha_challenge_field');
	var recaptcha_response=document.getElementById('recaptcha_response_field');
	
	var contribute=document.checkboxform.contribute.checked;
	
	var strURL="register.php?full_name="+full_name.value+"&country="+country.value+"&user_name="+user_name.value+"&usr_email="+usr_email.value+"&pwd="+pwd.value+"&pwd2="+pwd2.value+"&recaptcha_challenge="+recaptcha_challenge.value+"&recaptcha_response="+recaptcha_response.value+"&contribute="+contribute;
	
	var req = getXMLHTTP();
	
	if (req) {
		
		req.onreadystatechange = function() {
			if (req.readyState == 4) {
				// only if "OK"
				if (req.status == 200) {
					if (req.responseText == "#dialog-success") {
						location.href = "http://www.treatsafely.org/thankyou.php";
					} else {
						showModalDialogBox(req.responseText,1);
						Recaptcha.reload();
					}					
				} else {
					alert("There was a problem while using XMLHTTP:\n" + req.statusText);
				}
			}				
		}			
		req.open("GET", strURL, true);
		req.send(null);
	}		
}

// This function handles FMEA input functions
function runFMEAInput(userId, severityORoccurrence) {  // severityORoccurrence indicates whether user is submitting 'Severity' - 1 - or 'Occurrence and Detectability' - 2	
	
	// Catch user errors and deliver prompts
	
	if (USERID == 1) {  // if user is not logged in
		showModalDialogBox("#dialog-please-login",1);
		return;
	}
	
	if (STEP == 47) {  // if user has not selected a process step
		showModalDialogBox("#dialog-please-select-step",1);
		return;
	}
	
	if (isEmpty(FAILUREMODEID) == true || FAILUREMODEID == 0) {  // if user has not selected a failure mode to analyse
		showModalDialogBox("#dialog-please-select-failure-mode",1);
		return;
	}
	
	if (severityORoccurrence == 1) {
		
		var severity=document.getElementById('severity');
		
		// Catch user errors and deliver prompts
		
		if (severity.value < 1) {  // if user has not selected a severity ranking
			showModalDialogBox("#dialog-please-select-severity",1);
			return;
		}
		
		SEVERITYRANKING = severity.value;
	
		// Generate random number to pass to strURL to prevent ie from caching the result...
		var rand = Math.floor(Math.random()*1000);
	
		var strURL="qiToolBox_insert_fmea_severity.php?userid="+USERID+"&processid="+PROCESS+"&processstep="+STEP+"&failuremodeid="+FAILUREMODEID+
			"&severity="+severity.value+"&testORupdateORnew="+1+"&rand="+rand;  // pass 1 to test whether severity data already exists, 2 to update existing data, or 3 to enter new data
			
		var req = getXMLHTTP();
	
		if (req) {
			
			req.onreadystatechange = function() {
				if (req.readyState == 4) {
					// only if "OK"
					if (req.status == 200) {
						if (req.responseText == 1) {
							// Call modal confirm dialog box - user should choose whether to update existing severity ranking entry (2) or to create a new severity ranking entry (3)
							showModalDialogBox("#dialog-confirm-submit-severity",4);
						} else if (req.responseText == 2) {
							// Confirm successful save
							showModalDialogBox("#dialog-severity-save-success",1);
						}				
					} else {
						alert("There was a problem while using XMLHTTP:\n" + req.statusText);
					}
				}				
			}			
			req.open("GET", strURL, true);
			req.send(null);
		}
	} 
	
	if (severityORoccurrence == 2) {
		
		var severity=document.getElementById('severity');
		var occurrence=document.getElementById('occurrence');
		var detectability=document.getElementById('detectability');
	
		// Catch user errors and deliver prompts
		
		if (severity.value < 1) {  // if user has not selected a severity ranking
			showModalDialogBox("#dialog-please-select-severity",1);
			return;
		}
		
		SEVERITYRANKING = severity.value;
		
		if (occurrence.value < 1) {  // if user has not selected a severity ranking
			showModalDialogBox("#dialog-please-select-occurrence",1);
			return;
		}
		
		if (detectability.value < 1) {  // if user has not selected a severity ranking
			showModalDialogBox("#dialog-please-select-detectability",1);
			return;
		}
		
		if (isEmpty(FAILUREMODEID) == true || FAILUREPATHWAYID == 0) {  // if user has not selected a failure mode to analyse
			showModalDialogBox("#dialog-please-select-failure-pathway",1);
			return;
		}
	
		// Generate random number to pass to strURL to prevent ie from caching the result...
		var rand = Math.floor(Math.random()*1000);
	
		var strURL="qiToolBox_insert_fmea_occurrence.php?userid="+USERID+"&processid="+PROCESS+"&processstep="+STEP+"&failuremodeid="+FAILUREMODEID+
			"&severity="+severity.value+"&failurepathwayid="+FAILUREPATHWAYID+"&occurrence="+occurrence.value+
			"&detectability="+detectability.value+"&testORupdateORnew="+1+"&rand="+rand; // pass 1 to test whether severity data already exists, 2 to update existing data, or 3 to enter new data
			
		var req = getXMLHTTP();
	
		if (req) {
		
			req.onreadystatechange = function() {
				if (req.readyState == 4) {
					// only if "OK"
					if (req.status == 200) {
						if (req.responseText == 1) {
							// Call modal confirm dialog box - user should choose whether to update existing occurrence/detect ranking entry (2) or to create a new occurrence/detect ranking entry (3)
							showModalDialogBox("#dialog-confirm-submit-occur-detect",5);
						} else if (req.responseText == 2) {
							// Confirm successful save
							showModalDialogBox("#dialog-occur-detect-save-success",1);
						}
					} else {
						alert("There was a problem while using XMLHTTP:\n" + req.statusText);
					}
				}				
			}			
			req.open("GET", strURL, true);
			req.send(null);
		}
	}		
}


// This function retrieves and displays FMEA results from the FMEA Results table
function runFMEAResults(passedProcess) {

	// Catch user errors and deliver prompts
	
	if (USERID == 1) {  // if user is not logged in
		showModalDialogBox("#dialog-please-login",1);
		return;
	}
	
	// Generate random number to pass to strURL to prevent ie from caching the result...
	var rand = Math.floor(Math.random()*1000);
	
	var strURL="qiToolBox_retrieve_fmea_results.php?userid="+USERID+"&processid="+passedProcess+"&radiosortvalue="+RADIOSORTVALUE+"&rand="+rand;
			
	var req = getXMLHTTP();

	if (req) {
		
		req.onreadystatechange = function() {
			
			if (req.readyState == 4) {
				// only if "OK"
				if (req.status == 200) {	
					//alert(req.responseText);
					document.getElementById('fmeaResultsTable').innerHTML=req.responseText;
															
				} else {
					alert("There was a problem while using XMLHTTP:\n" + req.statusText);
				}
			}				
		}			
		req.open("GET", strURL, true);
		req.send(null);
		
	}

}

// This function is called when 'Display FMEA Results' button in qiToolBox-fmea-generic-trt.php is clicked, it opens a new page and posts the process number to the url
function geturl() {
	window.open('http://www.treatsafely.org/qiToolBox-fmea-results.php?proc='+PROCESS+'', '_blank');
}


// This function calls the next two functions to set the global RADIOSORTVALUE
function setGlobalRadioValue(sort_value,proc) {
	
	RADIOSORTVALUE = sort_value;
	
	runFMEAResults(proc);
}


// This function runs when the user selects a severity and checks to see if a value for Severity already exists
function checkSeveity() {
	var e = document.getElementById("severity");
	var strUser = e.options[e.selectedIndex].value;
	
	if (SEVERITYRANKING != 0 && strUser > 0) {
		// Catch user errors and deliver prompts
	
		if (USERID == 1) {  // if user is not logged in
			showModalDialogBox("#dialog-please-login",1);
			return;
		}
		
		if (STEP == 47) {  // if user has not selected a process step
			showModalDialogBox("#dialog-please-select-step",1);
			return;
		}
		
		if (isEmpty(FAILUREMODEID) == true || FAILUREMODEID == 0) {  // if user has not selected a failure mode to analyse
			showModalDialogBox("#dialog-please-select-failure-mode",1);
			return;
		}
		
		showModalDialogBox("#dialog-confirm-severity-change",6);
		return;
	}
}
					

// This function checks to see if a variable is empty
//function isEmpty(obj) {
//	for(var prop in obj) {
//		if(obj.hasOwnProperty(prop))
//			return false;
//	}
//	return true;
//}

//function isEmpty(o) {
 // var o = {};
  //for(var p in o) {
    //if (o[p] != o.constructor.prototype[p])
      //alert("false");
     // return false;
 // }
  //alert("true");
 // return true;
//}

function isEmpty(obj) {
	if (typeof obj === "undefined") {
		return true;
	}
	if (obj === "") {
		return true;
	}
	return false;
}
