// global context
var amendRequestId = 0,
    groupName = "",
    superUser = false,
    debug = false,
    admin = false,	//NDS admin, reviewer, etc.
    staff = false,	//read-only staff (non-NDS group)
    ndsAdmin = false,
    requestor = false,
    janitor = false,
//    roleAndGroupList = null,
    toDoTable, requestTable, requestAdminTable;
//var todoDataTableOptions = {};

$(function () {
    var userId = 5;
    var userIdMap = { "userId": userId };

    var amendActivityId; //populated when the amendment modal is shown

    //New Request success message
    //was this page loaded from a successful save at create.html?
    if (location.hash.indexOf("newrequest") > 0) {
        $('body > .container').prepend($('#newRequestSuccessTemplate').html());
        $('body > .container .newrequest-success').addClass('in')
            .find('button').click(function (e) {	//close the message
                //remove the hash (#) from the URL so this dialog doesn't come back on refresh, etc.
                removeHash();
            });
    }

    //Review success message
    //was this pages loaded from a successful review submit?
    if (location.hash.indexOf("review") > 0) {
        var urlvars = getUrlVars();
        var reviewGroup = urlvars['group'];
        reviewGroup = decodeURI(reviewGroup);	//handle any encoded spaces
        
        var msgBody = Mustache.render($('#reviewSuccessTemplate').html(), reviewGroup);

        $('body > .container').prepend(msgBody);
        $('body > .container .review-success').addClass('in')
            .find('button').click(function (e) {	//close the message
                //remove the hash (#) from the URL so this dialog doesn't come back on refresh, etc.
                removeHash();
            });

        removeHash(); //remove the hash from the URL (just using it to display the message)
    }

    
    // grab setup info from server
    $.ajax({
        url: '../dart/setup.json',
        type: 'GET',
        async: false,
        contentType: 'application/json',
        dataType:'json',
        success: function (data, textStatus, three) {
            if (textStatus === "success") {
                $('header a.active').html(data.userFullName);
                
                //var names = data.userFullName.split(",");
                //var firstname = names[1].split(" ");
                //$('body span.userFirstName').html(firstname[1]);

                userId = data.userId;
                userIdMap['userId'] = data.userId;

                requestor = data.requestor;	//requestor?
                superUser = data.superUser;	//is this the super-user role
                staff = data.staff;			//read-only staff
                admin = data.admin;			//reviewer
                ndsAdmin = data.ndsAdmin;	//is this the NDS admin role
                janitor = data.janitor;		//Administration Tool tab
                debug = data.debug;	//are we in debug mode?

                //populate the groupName (default to an empty group name)                
                if (data.groups != undefined && data.groups != null && data.groups.length > 0)	//temporarily saw "undefined" show up as the group name
                    groupName = data.groups[0];
                else
                    groupName = "";
                
                $("#reportingLink").attr("href", data.reportingLink);
                
                if (!requestor){
                	$('#dartReporting').show();
                }else{
                	$('#dartReporting').hide();
                }
                
               
               
                //
                //show/hide the Operations/Research filter
                var intermediateReviewGroup = true;	//determine if this is the read-only staff role:  for an intermediate group, don't show the filter
                if( staff == true ) {
                	if( groupName == "NDS" ) { 	// || groupName == "DART ADMIN" ) {
                		intermediateReviewGroup = false;
                	}//end if
                }//end if

//                if(!(!requestor && !superUser && admin && !ndsAdmin)){	//intermediate reviewer should not see the Operations/Research filter
                if( requestor || superUser || ndsAdmin || intermediateReviewGroup == false ) {	//intermediate reviewer should NOT see the Operations/Research filter
                    $('.table-filter').show();
                }


                if (data.admin == false && superUser == false && data.staff == false) {	//requestors do not keep the review tab, superUser keeps both tabs
                    $('li#request-administrationTab').remove(); // kill the tab

                } else {		//reviewers do not keep the request tab, superUser keeps both tabs

                    //
                    // turn off request tab if you are an administrator (only leave it if you are in debug mode)
                    if (data.admin == true || data.staff == true) {	//part of a review group
                        if (data.debug == false) {
                            $('li#requestsTab').remove(); // kill the tab
                        }
                    }//end if -- admin
                }//end else -- reviewer

                
                //
                //Remove the "janitor" Administration Tool tab if not the right role
                if( data.janitor == false ) {
                    $('li#janitorTab').remove(); // kill the Admin Tool tab
                    $('li#roleSwitcherTab').remove();
                } else {
                    //$('li#janitorTab').show();	//show the Admin Tool tab

                    //add the Admin Tool tab (workaround for IE9)
                    $('#dashboardTab').append('<li id="janitorTab" role="menuitem" ><a href="#janitor" data-toggle="tab" role="button">Administration Tool</a></li>');
                    $('#dashboardTab').append('<li id="roleSwitcherTab" role="menuitem" ><a href="#roleSwitcher" data-toggle="tab" role="button">Add/Remove Roles</a></li>');
                }//end else -- janitor

                
                //
                //super-user cannot create new requests (hide the button)
                if( superUser == true ) {
                    $('button[href="#createNewRequest"]').hide();
                }
            }

            progressIncrease('60%');
        }
    });

    

    $.ajax({
        url: '../dart/getAllRolesAndGroups.json',
        type: 'GET',
        //async: false,
        contentType: 'application/json',
        dataType:'json',
        success: function (data, textStatus, three) {
            if (textStatus === "success") {
            	if( data != null && data != undefined ) {
	            	//roleAndGroupList = data;

	                // populate the role and group combo box
	                var roleAndGroupOptions = Mustache.render($(".roleAndGroupOptionsTemplate").html(), data);
	                $("#select-role").append(roleAndGroupOptions).chosen({ no_results_text: "No group and role matched" });

            	}//end if
            }
        }
    });
    
    
    
    // createNewRequest modal shown event listener to set default field focus
    $('#createNewRequest').on('shown', function() {
        $('#new-official-name').focus();
    });
    

    // hook the continue button on the 'create new request' modal 
    $('#createNewRequest .modal-footer').on('click', 'button#continue', function (e) {
        //loader
        $('#createNewRequest .modal-footer button').hide();
        $('#createNewRequest .modal-footer .progress').show();
        var newActivityMap = { "userId": userId };
        newActivityMap['officialName'] = $('div#createNewRequest textarea#new-official-name').val();
        var selection = $('div#createNewRequest select#new-activity-type').find(':selected');
        newActivityMap['type'] = selection.val();

        // create the new activity
        $.ajax({
            url: '../dart/createActivity.json',
            type: 'POST',
            async: false,
            contentType: 'application/json',
            dataType:'json',
            data: JSON.stringify(newActivityMap),
            success: function (data, textStatus, three) {

                if (textStatus === "success") {
                    if (newActivityMap['type'] == "Research Data Access") {
                        window.location = "./create-new-project.html?id=" + data.activityId + "&rid=" + data.requestId + '&revid=0' + "&wid=0";
                    }
                    else if(newActivityMap['type'] == "Preparatory to Research Access") {
                    	window.location = "./create-new-preparatory.html?id=" + data.activityId + "&rid=" + data.requestId + '&revid=0' + "&wid=0";
                    }
                    else {
                        window.location = "./non-research-request.html?id=" + data.activityId + "&rid=" + data.requestId + '&revid=0' + "&wid=0";
                    }
                }
            }
        });

    });


    var maxLength = $("textarea#new-official-name").attr("maxlength");

    $("textarea#new-official-name").bind("keyup change", function(){checkMaxLength(this.id,  maxLength); } )

    function checkMaxLength(textareaID, maxLength) {

        var currentLengthInTextarea = $("#"+textareaID).val().length;

        if (currentLengthInTextarea > (maxLength)) {

            // Trim the field current length over the maxlength.
            $("textarea#new-official-name").val($("textarea#new-official-name").val().slice(0, maxLength));

        }
    }

    $('div.modal-footer :button.validateNewRequest').on('click', function (e) {

        var returnVal = false;
        var value = $('textarea#new-official-name').val();
        var selectValue = $('#new-activity-type').val();
        value = $.trim(value);

        if (value.length <= 0) {
            alert("You must provide an Official Name");
            returnVal = false;
        } else {
            returnVal = true;
        }

        if (selectValue == 1) {
            alert("Please select a Request Type");
            returnVal = false;
        }

        return returnVal;
    });    
    
    
    /*************** Administration Tool Modal ***************/
    
    // hook the SEARCH button on the 'Administration Tool' Tab 
    $('div.search-request :button.findRequestwithTN').on('click', function (e) {
    	
    	var returnVal = false;
        var TrackingNumber = $('input#searchtrackingNum').val();
        TrackingNumber = $.trim(TrackingNumber);
        
        if (TrackingNumber.length <= 0) {
            alert("You must provide a Tracking Number");
            //returnVal = false;
        } else {

        	$('button#reviewGroups').attr('disabled', true);	//disable the review group buttons
        	$('button#changeGroups').attr('disabled', true);
        	//$('input#changeDate').attr('disabled', true);
        	
        	$('#reviewStatusMsgContainer').html('');	//clear the review status details
        	$('#reviewStatusMsgContainer').hide();		//hide the review status details


            var trackingNumberMap = { "trackingNumber": TrackingNumber };
            //trackingNumberMap['janitor'] = 'true';
        	
            $.ajax({
                url: '../dart/getRequestProperties.json',
                type: 'POST',
                contentType: 'application/json',
                async: false,
                dataType:'json',
                data: JSON.stringify(trackingNumberMap),
                success: function (data, textStatus, three) {

                	//verify if this request exists
                	if( data.message != null && data.message != undefined ) {
                		alert("Error: " + data.message.text);

	                	$('input#changenarrativeTxt').val('');		//no narrative text, because the request doesn't exist
	                	$('input#changeofficialNameTxt').val('');	//no official name, because the request doesn't exist
	                	$('input#changeShortNameTxt').val('');

                		$('input#changenarrativeTxt').attr('disabled', true);
                		$('input#changeofficialNameTxt').attr('disabled', true);
                		$('input#changeShortNameTxt').attr('disabled', true);

	                	$("#changeNarrative").attr('disabled', true);
	                	$("#changeofficialName").attr('disabled', true);
	                	$("#changeShortName").attr('disabled', true);

                	} else {	//this request exists

	                	if ( data.amendment == true ){	//if this is not an amendment, there is no narrative text to change
	                		$('input#changenarrativeTxt').attr('disabled', false);
	                		$('button#changeNarrative').attr('disabled', false);
	                	} else {
	                		$('input#changenarrativeTxt').attr('disabled', true);
	                		$('button#changeNarrative').attr('disabled', true);
	                	}

	                	//TODO: Joyce look at this
	                	if( data.researchRequest == true ) {
	                		$("#reviewGroups").attr('disabled', false);	//does this request have intermediate reviews?
	                	}


	            		$('input#changeofficialNameTxt').attr('disabled', false);	//allow the user to update the Official Name
	            		$('button#changeofficialName').attr('disabled', false);

	            		$('input#changeShortNameTxt').attr('disabled', false);	//allow the user to update the Short Name
	            		$('button#changeShortName').attr('disabled', false);

	                	$('input#changenarrativeTxt').val(data.narrativeText);	//populate the text fields with the retrieved values
	                	$('input#changeofficialNameTxt').val(data.officialName);
	                	$('input#changeShortNameTxt').val(data.shortName);
	                	
	                	$("#changeNarrative").attr("data-id", data.requestId);	//store the requestId in the button data-id
	                	$("#changeofficialName").attr("data-id", data.requestId);
	                	$("#changeShortName").attr("data-id", data.requestId);
	                	$("#reviewGroups").attr("data-id", data.requestId);
	                	$("#changeGroups").attr("data-id", data.requestId);
	                	$("#deletefinalNDS").attr("data-id", data.requestId);
	                	
	                	$('.adminListData').hide();
	                	$('.successesChange').hide();
	                	$('button#deletefinalNDS').hide();
                	}//end else
                }
            });
        }
    });
    
    
    // hook the GO narrative text button on the 'Administration Tool' Tab 
    $('div.search-request :button.changeNarrative').on('click', function (e) {

    	var ChangenarrativeTxt = $('input#changenarrativeTxt').val();
    	ChangenarrativeTxt = $.trim(ChangenarrativeTxt);

    	 if (ChangenarrativeTxt.length <= 0) {
    		 alert("Please specify a narrative for this amendment.");
             //returnVal = false;
         } else {
        	 var changenarrativeTxtMap = { "changeNarrative": ChangenarrativeTxt };
        	 //changenarrativeTxtMap['janitor'] = 'true';
        	 changenarrativeTxtMap['requestId'] = $(this).attr("data-id");
        	 
             $.ajax({
                 url: '../dart/setNarrativeText.json',
                 type: 'POST',
                 contentType: 'application/json',
                 async: false,
                 dataType:'json',
                 data: JSON.stringify(changenarrativeTxtMap),
                 success: function (data, textStatus, three) {
                 	if( data.message != null && data.message != undefined ) {
                		alert("Error: " + data.message.text);
                	} else {

	                 	$('input#changenarrativeTxt').val(data.narrativeText);
	
	                	$('input#changenarrativeTxt').attr('disabled', true);
	                	$('button#changeNarrative').attr('disabled', true);
	                	
	                	alert("Narrative Text has been successfully changed.");
                	}//end else
                 }
             });
         }
    });
    
        
    $('div.search-request :button.changeofficialName').on('click', function (e) {
   	
    	var ChangeofficialNameTxt = $('input#changeofficialNameTxt').val();
    	ChangeofficialNameTxt = $.trim(ChangeofficialNameTxt);

    	if (ChangeofficialNameTxt.length <= 0) {
            alert("Please specify an Official Name for this study.");
        } else {
        	var changeofficialNameTxtMap = { "changeofficialName": ChangeofficialNameTxt };
        	//changeofficialNameTxtMap['janitor'] = 'true';
        	changeofficialNameTxtMap['requestId'] = $(this).attr("data-id");
       	 	
            $.ajax({
                url: '../dart/setOfficialName.json',
                type: 'POST',
                contentType: 'application/json',
                async: false,
                dataType:'json',
                data: JSON.stringify(changeofficialNameTxtMap),
                success: function (data, textStatus, three) {
                	if( data.message != null && data.message != undefined ) {
                		alert("Error: " + data.message.text);
                	} else {
	                	$('input#changeofficialNameTxt').val(data.officialName);
	                	
	                	$('input#changeofficialNameTxt').attr('disabled', true);
	                	$('button#changeofficialName').attr('disabled', true);
	                	
	                	alert("Official Name has been successfully changed.");
                	}//end else
                }
            });       	
        }
    });
    

    $('div.search-request :button.changeShortName').on('click', function (e) {
    	
    	var changeShortNameTxt = $('input#changeShortNameTxt').val();
    	changeShortNameTxt = $.trim(changeShortNameTxt);

    	if (changeShortNameTxt.length <= 0) {
            alert("Please specify a Short Name for this study.");
        } else {
        	var changeShortNameTxtMap = { "changeShortName": changeShortNameTxt };
        	changeShortNameTxtMap['requestId'] = $(this).attr("data-id");

            $.ajax({
                url: '../dart/setShortName.json',
                type: 'POST',
                contentType: 'application/json',
                async: false,
                dataType:'json',
                data: JSON.stringify(changeShortNameTxtMap),
                success: function (data, textStatus, three) {
                	if( data.message != null && data.message != undefined ) {
                		alert("Error: " + data.message.text);
                	} else {
	                	$('input#changeShortNameTxt').val(data.shortName);
	                	
	                	$('input#changeShortNameTxt').attr('disabled', true);
	                	$('button#changeShortName').attr('disabled', true);

	                	alert("Short Name has been successfully changed.");
                	}//end else
                }
            });       	
        }
    });
    
    
    $('div.show-admins :button.reviewGroups').on('click', function (e) {
    	//alert("Admin Groups.");

//TODO: wfResearch: add support for both the top-level workflow and the child workflow object
        var reqID = $(this).attr('data-id');
        var requestIdMap = { "requestId": reqID };
        
        $('button#changeGroups').attr('disabled', false);	//enable the "change" button
    	
    	// populate the list of reviews 
		$.ajax({
			url:'../dart/listAllReviewTemplates.json',
			type:'GET',
			contentType:'application/json',
			dataType:'json',
			async:false,
			success:function(data,textStatus,three) {
				if(textStatus==="success" ) {
					var adminListBody = Mustache.render($(".adminReview").html(),data);
					$('div.adminListGoesHere').html(adminListBody);
					
					adminListBody = Mustache.render($(".adminTemplateRow").html(),data);
					$('.adminListData').html(adminListBody);
				}
		
				//get the list of selected reviews
				$.ajax({
					url:'../dart/listSelectedReviewTemplates.json',
					type:'POST',
					contentType:'application/json',
					async:false,
					dataType:'json',
					data:JSON.stringify(requestIdMap),
					success:function(data,textStatus,three) {
						if(textStatus==="success" ) {
		
				     		if( data.templates != null && data.templates != undefined ) {
					    		if (data.templates.length > 0) {
					    			for (var i in data.templates) {
					    				var tempId = data.templates[i].id;
//					    				var fanalnds = data.templates[i].finalnds;
//					    				if(fanalnds == false){
					    					// find the review template row and check its checkbox
					    					$('.adminListData input[data-id='+tempId+']').attr('checked','checked');
					    					
//testing without the date change for now
//					    					$('input#changeDate').attr('disabled', false);
					    					
//					    				}
//					    				else {
//					    					$('.adminListData input[data-id='+tempId+']').attr('checked','checked').attr('disabled', true);
//					    					$('button#changeGroups').attr('disabled', true);
//					    					$('button#deletefinalNDS').attr('disabled', false).show();
//					    					$('.successesChange').hide();
//					    				}
					    			}
					    		}
				     		}//end if
						}//end success
					}
				});
				
				
				//get the state of the request and each review
				$.ajax({
					url:'../dart/validateRequestState.json',
					type:'POST',
					contentType:'application/json',
					async:false,
					dataType:'json',
					data:JSON.stringify(requestIdMap),
					success:function(data,textStatus,three) {
						if(textStatus==="success" ) {

							var error = false;
							$('#reviewStatusMsgContainer').html('');	//clear the review status details
							
							if( data.initiated == true ||  	//not yet submitted
								data.closed == true || 		//request has been closed
								data.denied == true ) {		//request has been denied
								
								error = true;

								var errorMsgContent = Mustache.render($(".errorMsgTemplate").html(), data);
								$('#reviewStatusMsgContainer').append(errorMsgContent);

							} else if( data.initialNDSCompleted == false ) {	//initial NDS review not yet completed
								error = true;

								var errorMsgContent = Mustache.render($(".errorMsgTemplate").html(), data);
								$('#reviewStatusMsgContainer').append(errorMsgContent);

							} else if( data.finalNDSCompleted == true ) {	//final NDS review already completed
								error = true;
	
								var errorMsgContent = Mustache.render($(".errorMsgTemplate").html(), data);
								$('#reviewStatusMsgContainer').append(errorMsgContent);

//TODO: might want to allow the user to remove the final NDS review

							} else if( data.finalNDSReady == true ) {	//ready for the Final NDS review (different workflow state)
								error = true;
	
								var errorMsgContent = Mustache.render($(".errorMsgTemplate").html(), data);
								$('#reviewStatusMsgContainer').append(errorMsgContent);
								
//TODO: display whether the user can change the status of the request (and warn them that all changes are final)
//TODO: might want to allow the user to add a new review group if the final NDS review has not yet been completed
							}


							//
							//display the status of each review
							var reviewStatusMsgContent = Mustache.render($(".reviewStatusMsgTemplate").html(), data);
							$('#reviewStatusMsgContainer').append(reviewStatusMsgContent);
							$('#reviewStatusMsgContainer').show();


							//display the error messages
							if( error == true ) {
								$('.adminListData input').attr('disabled','disabled');	//disable the Review Group checkboxes
								$('button#changeGroups').attr('disabled', true);	//disable the "change" button
							}//end if

						}//end success
					}
				});
			}//end success
		});

    });
    
    
    $('div.show-admins :button.changeGroups').on('click', function (e) {
    	
    	var selected = new Array();
    	$('input.adminndsReviewCheckBoxes:checked').each(function(e){
			var temp = $(this).attr('data-id');
			if (temp != null) {
				selected.push($(this).attr('data-id'));
			}							
		});    
    	 var reqID = $(this).attr('data-id');
         var requestIdMap = { "requestId": reqID };
         requestIdMap['reviewTemplates'] = selected; 

//testing without changing date for now         
//         var changeDate = $("input#changeDate").val();
//         if (changeDate != ""){         	 
//             requestIdMap['changeDate'] = changeDate;
         
	         $.ajax({
					url:'../dart/changeReviews.json',
					type:'POST',
					async:false,
					contentType:'application/json',		
					dataType:'json',
					data:JSON.stringify(requestIdMap),
					success:function(data,textStatus,three) {
						if(textStatus==="success" ) {
							$('#successesChange').val('The changes have been done successfully.');
							$('#successesChange').show();
							$('button#changeGroups').attr('disabled', true);
						}
					},
					error:function(){
						//$('lable#adminGrroupchange').val('Error');	
					}    	
	         }); 
         
//         } else {
//        	 alert("Please, setup date.");
//         }
    });


    /************************* Group and Role ****************/
    // findPeopleModal modal shown event listener to set default field focus
    $('#findPeopleModal').on('shown', function() {
    	$('#name').focus();
    });
    
    //initialize the modal
    $('.person-info').on('click', 'button[href=#findPeopleModal]', function (e) {	//regular button
        e.preventDefault();

        //
        // clear the modal of the last search info (to match the selected search results)
        clearModalOfSearchResults();
    });

    $('.person-info').on('click', 'a[href=#findPeopleModal]', function (e) {	//pencil icon
        e.preventDefault();

        //
        // clear the modal of the last search info (to match the selected search results)
        clearModalOfSearchResults();
    });


    //hook the findNow button on the 'Find People' modal
    $('.modal-body').on('click', 'button#findNow', function (e) {
        e.preventDefault();

        $('div#findPeopleModal div#resultTable .alert').hide();
        $('div#findPeopleModal div#resultTable').addClass('hide'); //hide the results table


        var personToFindVal = $('div#findPeopleModal input#name').val();
        var personToFindMap = { "key": personToFindVal };

        //if we have no search string, don't bother to query the server
        if (personToFindVal === "") {
            alert("Please enter a last name to find.");
        } else {

            $('#searchProgress').show(); //search progress bar


            //search for this person in AD
            $.ajax({
                url: '../dart/findPersons.json',
                type: 'POST',
                async: false,
                contentType: 'application/json',
                dataType:'json',
                data: JSON.stringify(personToFindMap),
                success: function (data, textStatus, three) {
                    if (textStatus === "success") {
                        if (data.persons != null) {

                            //TODO: if there are no search results, display something on the UI

                            //display the search results (currently: full name, username)
                            var personSearchResults = Mustache.render($(".findPersonOptionsTemplate").html(), data);
                            $('div#findPeopleModal table tbody').html(personSearchResults);

                            //$('div#findPeopleModal div#resultTable').fadeIn().removeClass('hide');	//show the results table
                            $('div#findPeopleModal div#resultTable').removeClass('hide'); //show the results table


                            if (data.persons.length > 0) {
                                //TODO: make the instructions the same width as the table
                                //var tableWidth = $('div#findPeopleModal table#personSortTable').width();
                                ////$('div#findPeopleModal div#resultTable .alert').removeClass('controls');
                                //$('div#findPeopleModal div#resultTable .alert').width( tableWidth );
                                ////$('div#findPeopleModal div#resultTable .alert').addClass('controls');
                                //alert("tableWidth = " + tableWidth + ", css(width) = " + $('div#findPeopleModal table#personSortTable').css('width'));
                                //alert("alert width = " + $('div#findPeopleModal div#resultTable .alert').width() + ", css(width) = " + $('div#findPeopleModal div#resultTable .alert').css('width'));

                                $('div#findPeopleModal div#resultTable .alert').fadeIn(); //show the instructions
                            } //end if

                        } //end if
                    } else {
                        //TODO: handle an error response
                    }
                }
            });


            $('#searchProgress').fadeOut(); //search progress bar

        } //end else
    });


    //clicked a row in the 'Find People' results table
    $('div#findPeopleModal table').on('click', 'tr', function (e) {
        e.preventDefault();

        var selectedRow = $(this);

        //get the selected username
        selectedPersonName = $(this).find("td#fullName").text();
        selectedPersonUsername = X(this).find("td#username").text();

        displaySelectedPersonName(); //display the selected name on the page
        
        
        //get the role and group info
        var personInfoMap = {'name':selectedPersonUsername};
        $.ajax({
            url: '../dart/findRoleAndGroup.json',
            type: 'POST',
            async: false,
            contentType: 'application/json',
            dataType:'json',
            data: JSON.stringify(personInfoMap),
            success: function (data, textStatus, three) {
                if (textStatus === "success") {

                    if( data != null && data != undefined ) {
                    	
                    	if( data.roleAndGroupList != null && data.roleAndGroupList != undefined ) {


                    		if( data.roleAndGroupList.rolesAndGroups != null && data.roleAndGroupList.rolesAndGroups != undefined && 
                    				data.roleAndGroupList.rolesAndGroups.length > 0 ) {
                    			$("#select-role").find('option[value="' + data.roleAndGroupList.rolesAndGroups[0].groupId + "_" + data.roleAndGroupList.rolesAndGroups[0].roleId + '"]').attr("selected", "selected").trigger('liszt:updated');
                    		}

                    		if( data.roleAndGroupList.janitor != null && data.roleAndGroupList.janitor != undefined && data.roleAndGroupList.janitor == true ) {
                    			$("#admin-tool").attr('checked','checked');
                    		} else {
                    			$("#admin-tool").attr('checked',false);
                    		}
                    	}
                    }


                    disableRoleSwitcherControls( false, true );	//enable the role options, disable the "change" button
                } else {
                    //TODO: handle an error response
                }
            }
        });
    });


    //clicked the cancel button -> nothing selected
    $('.modal-footer').on('click', 'button#cancel', function (e) {
        e.preventDefault();

        clearPersonNameDisplay(); //clear the selected name
        clearRoleAndGroupDisplay();	//clear the displayed role and group info

        disableRoleSwitcherControls( true, true );	//disable the role options, disable the "change" button
    });


    //create the link out of the selected person name and display it on the page
    var displaySelectedPersonName = function () {

        //display the selected person
        var selectedPersonLink = Mustache.render($('.selectPersonTemplate').html(), selectedPersonName); //display the name
        $('.displayTable td.selected-person').html(selectedPersonLink); //display the selected name on the page

        $('.displayTable td.selected-person').show(); //show the selected person link
        $('#findPeopleButtonCell').hide(); //hide the "Find People" button
    };


    //Clear out the variables holding the selected person info and update the UI
    var clearPersonNameDisplay = function () {

        selectedPersonName = "";
        selectedPersonUsername = X";

        $('.displayTable td.selected-person').hide(); //hide the selected person link
        $('#findPeopleButtonCell').show(); //show the "Find People" button
    };
    
    var clearRoleAndGroupDisplay = function () {
        $("#admin-tool").attr('checked',false);

        //$("#select-role").find('option[value="' + 0 + "_" + 0 + '"]').attr("selected", "selected").trigger('liszt:updated');
        $("#select-role").val('').trigger('liszt:updated');
    };

    //clear the modal of the last search info
    var clearModalOfSearchResults = function () {

        //
        // hide the results list
        $('div#findPeopleModal div#resultTable .alert').hide();
        $('div#findPeopleModal div#resultTable').addClass('hide'); //hide the results table

        //
        // clear the search name box
        $('div#findPeopleModal input#name').val(''); //display the selected name on the page
    };


    //update the user's role and group
    $('button#changeGroupAndRole').on('click', function (e) {
        e.preventDefault();

        //save the role and group info
        var personInfoMap = {'name':selectedPersonUsername};

        var isJanitorSelected = $("#admin-tool").is(':checked');
        personInfoMap['janitor'] = isJanitorSelected;
        
        
        var groupRoleChosenBox = $("#select-role");
        var groupRoleName = groupRoleChosenBox.val();	//group and role name
        var selectedGroupId = parseInt( groupRoleChosenBox.find('option:selected').attr('data-groupid') );	//group ID
        var selectedRoleId = parseInt( groupRoleChosenBox.find('option:selected').attr('data-roleid') );	//role ID

    	personInfoMap['groupId'] = selectedGroupId;
    	personInfoMap['roleId'] = selectedRoleId;
    	
        
        var isRequestorSelected = false;
        if( selectedGroupId == 0 && selectedRoleId == 0 ) {
        	isRequestorSelected = true;
        }//end if
        personInfoMap['requestor'] = isRequestorSelected;


        $.ajax({
            url: '../dart/saveRoleAndGroup.json',
            type: 'POST',
            async: false,
            contentType: 'application/json',
            dataType:'json',
            data: JSON.stringify(personInfoMap),
            success: function (data, textStatus, three) {
                if (textStatus === "success") {
                    if (data != null) {

                    	//display success/failure
                    	if( data.message != null && data.message != undefined ) {
                    		alert("Error:  " + data.message.text);
                    	} else {
                    		alert("Successfully updated the user's role and/or group.");
                    	}


                        clearPersonNameDisplay(); //clear the selected name
                        clearRoleAndGroupDisplay();	//clear the displayed role and group info

                        disableRoleSwitcherControls( true, true );	//disable the role options, disable the "change" button
                    } //end if
                } else {
                    //TODO: handle an error response
                }
            }
        });
    });
    
    
    $('#admin-tool').on('change', function (e) {
        e.preventDefault();
        disableRoleSwitcherControls( false, false );	//enable the "change" button
    });

    $('#select-role').on('change', function (e) {
        e.preventDefault();
        disableRoleSwitcherControls( false, false );	//enable the "change" button
    });
    
    var disableRoleSwitcherControls = function( disableOptions, disableChangeButton ) {
        $('button#changeGroupAndRole').attr('disabled', disableChangeButton);	//enable/disable the "change" button
        disableRoleSwitcherOptions( disableOptions );
    };

    var disableRoleSwitcherOptions = function( disable ) {
        $('#admin-tool').attr('disabled', disable);
        $('#select-role').attr('disabled', disable).trigger('liszt:updated');
    };
    

    /*************** Amendment Modal ***************/
    $('#amendRequestModal').on('hide', function (e) {
    	$(this).removeData('modal');	//remove the invoker info
    });
    
    $('#amendRequestModal').on('shown', function (e) {
    	$('textarea#narrative').focus();
    });
    
    $('#amendRequestModal').on('show', function (e) {

    	$('textarea#narrative').val('');	//clear out the narrative field
    	
    	//get the request to be amended
        var modal = $(this).data('modal');
        if( modal != null && modal != undefined ) {
            if( modal.options != null && modal.options != undefined ) {
                var reqID = modal.options.id;
                $('#amendRequestModal form input#requestID').val(reqID);	//request to be amended
            }
        }
        //var $trigger = $(modal.options.source);
        //var $invoker = $(e.relatedTarget);
    	
        var origRequestId = $('#amendRequestModal form input#requestID').val();
        var requestIdMap = { "requestId": origRequestId };

        // populate the user request info
        $.ajax({
            url: '../dart/getActivityInfo.json',
            type: 'POST',
            contentType: 'application/json',
            async: false,
            dataType:'json',
            data: JSON.stringify(requestIdMap),
            success: function (data, textStatus, three) {

                //TODO: we might want a simpler request handler here to only get the pieces of info that we need for the amendment
                //TODO: might want to store this somewhere in the modal itself, but for now, using a global variable				
                amendActivityId = data.activityId;
                $('#amendRequestModal form textarea#officialStudyName').val(data.officialName);	//populate the official name
                $('#amendRequestModal form input#requestType').val(data.type);	//populate the request type
            }
        });
    });


    $('#amendRequestModal').on('click', 'button#amendRequest', function (e) {
        
		//require a narrative
		var narrativeMessage = $('#amendRequestModal form textarea#narrative').val();
		if( narrativeMessage == null || narrativeMessage === "" ) {
			alert("Please enter an amendment narrative.");
		} else {

	        var rid = $('#amendRequestModal form input#requestID').val();
	        var requestIdMap = { "requestId": rid };
	        requestIdMap['narrative'] = $('#amendRequestModal form textarea#narrative').val();

	        //alert("about to call createAmendment with: " + JSON.stringify(requestIdMap));
	        //alert("amendmentActivityId = " + amendActivityId);		
	
	        $.ajax({
	            url: '../dart/createAmendment.json',
	            type: 'POST',
	            async: false,
	            contentType: 'application/json',
	            dataType:'json',
	            data: JSON.stringify(requestIdMap),
	            success: function (data, textStatus, three) {
	                if (textStatus === "success") {
	                    $('#amendRequestModal').modal('hide');
	
	                    if (data.requestId != undefined) {
	
	                        var newLocation = "./create-new-project.html";
	                        if (data.type === "Research Data Access") {
	                            newLocation = "./create-new-project.html";
	                        } else if (data.type === "Preparatory to Research Access") {
	                            newLocation = "./create-new-preparatory.html";
	                        } 
	                        else {
	                            newLocation = "./non-research-request.html";
	                        }
	
	                        //redirect to the create-new-project page with this requestId	
	                        document.location = (newLocation + "?id=" + amendActivityId + "&rid=" + data.requestId + "&revid=0" + "&wid=0");
	                    } //end if
	                }
	            }
	        });

		}//end else
    });


    /*********************** To-Do List ***********************/
    
    //TODO: not currently using this function -> at the end of the wizard, complete the tasks
    //	//
    //	// delete the Task from the To-Do Dashboard
    //	$('#dashboardContent #to-do table tbody').on('click','button.complete',function(e){
    //		//alert("clicked the complete button -- will want to launch the wizard");
    //				
    //		var tid = $(this).attr('data-id');
    //		var taskIdMap = {"taskId":tid};
    //
    //		var oTable = $('div#to-do table.dataTable').dataTable();
    //		var row = $(this).closest("tr").get(0);
    //		
    //		// complete the task
    //		$.ajax({
    //			url:'../dart/completeTask.json',
    //			type:'POST',
    //			async:false,
    //			contentType:'application/json',
    //			data:JSON.stringify(taskIdMap),
    //			success:function(data,textStatus,three) {
    //				if(textStatus==="success"){
    //					oTable.fnDeleteRow(oTable.fnGetPosition(row));
    //				}
    //			}
    //		});
    //	});


//    // populate the request aging buckets
//    $.ajax({
//        url: '../dart/getTaskAging.json',
//        type: 'POST',
//        async: false,
//        contentType: 'application/json',
//        dataType:'json',
//        data: JSON.stringify(userIdMap),
//        success: function (data, textStatus, three) {
//            if (textStatus === "success") {
//                $('div#two').text(data.day0);
//                $('div#three').text(data.day10);
//                $('div#four').text(data.day20);
//                $('div#five').text(data.day30);
//            }
//        }
//    });

    var todoDataTableOptions = {
        "iDisplayLength": 10,
        "sDom": "<'top row-fluid'<'span6'i><'span6'f>>t<'bottom row-fluid'<'span6'p><'span6 switcher'>>",
        "oLanguage": {
            "sInfo": "Showing _START_ to _END_ of _TOTAL_",
            "sInfoFiltered": "(filtered)"
        },
        "fnDrawCallback": function () {
            //hide pagination if there's only one page
            //This also fires if search results are less than one page
            if (this.fnPagingInfo().iTotalPages > 1) {
                $(this).next('.bottom').find('.dataTables_paginate').show();
            } else {
                $(this).next('.bottom').find('.dataTables_paginate').hide();
            }
        }
    };


    // populate the user to-do list
    populateToDoList(userId);	//, todoDataTableOptions);

    
    //
    //initialize the ToDo List datatable options
    //turn off sorting/searching for actions column
    todoDataTableOptions["aoColumnDefs"] = [
        { "bSortable": false, "aTargets": [6] },
        { "bSearchable": false, "aTargets": [6] }
    ];
    toDoTable = $('div#dashboardContent div#to-do .table').dataTable(todoDataTableOptions);


    $('#toDoFilterAll').on('change', function(){
        $.cookie("filterType", 1, { path: '/', expires:366 });
        setFilters();
    });

    $('#toDoFilterResearch').on('change', function(){
        $.cookie("filterType", 2, { path: '/', expires:366 });
        setFilters();
    });

    $('#toDoFilterOperations').on('change', function(){
        $.cookie("filterType", 3, { path: '/', expires:366 });
        setFilters();
    });
    
    $('#toDoFilterPreparatory').on('change', function(){
        $.cookie("filterType", 4, { path: '/', expires:366 });
        setFilters();
    });

    //	progressIncrease('100%');

    //	//TODO: might want to wait to hide the progress bar until we have also retrieved the requests
    //		$('div#dashboardContent .progress').fadeOut();
    //		$('div#dashboardContent div#to-do').addClass('in');
    //	}//end if



    //
    // populate the user request list (request tab)
    //		For requestors, super-user, or if in debug mode, populate the request tab
    var havePopulatedReviewTab = false;
    if( requestor === true || superUser === true || debug === true ) {

        $.ajax({
            url: '../dart/getAllUserRequests.json',
            type: 'POST',
            async: false,
            contentType: 'application/json',
            dataType:'json',
            data: JSON.stringify(userIdMap),
            success: function (data, textStatus, three) {
                if (textStatus === "success") {

                    //
                    //for super-user, populate both the request and the review tab (with one query)
                    if( superUser === true || ndsAdmin === true ) {

                        //
                        //Request tab (not editable unless requestor OR in debug mode)
                        if( data.requestList != null && data.requestList != undefined ) {

                            data.requestList['requestor'] = false;	//Only requestors can close or amend the requests
                            if( debug === true ) {

                                data.requestList['requestor'] = true;	//allow requests to be closed or amended if in debug mode

                            } else {	//NOT in debug mode

                                if( data.requestList.requests != null && data.requestList.requests != undefined ) {
                                    for (idx in data.requestList.requests) {	//step through the requests
                                        var currRequest = data.requestList.requests[idx];
                                        currRequest.editable = false;	//only requestors can edit the requests (unless in debug mode)
                                    }//end for
                                }//end if
                            }//end else
                        }//end if

                        populateRequestorTab( data.requestList );	//requestor tab


                        //
                        //Review tab
                        populateReviewTab( groupName, data.reviewableRequestList );	//reviewer tab
                        havePopulatedReviewTab = true;	//have now populated the review tab!
                    } else {

                        data['requestor'] = true;	//Only requestors can close or amend the requests
                        populateRequestorTab( data );	//requestor tab
                    }

                } else {
                	//alert("server error!");
                }
            },
            error: function ( jqXHR, textStatus, errorThrown ) {
            	//alert("server error! " + errorThrown)
            }
        });
    }//end if -- populate the Requestor tab


    //
    // populate the administer request list
//    if( requestor === false && superUser == false ) {	//have NOT yet populated the review tab (super-user retrieves the info for both tabs at once)
    if( havePopulatedReviewTab === false && requestor === false ) {	//have NOT yet populated the review tab (super-user retrieves the info for both tabs at once)

        $.ajax({
            url: '../dart/listUserReviewableRequests.json',
            type: 'POST',
            contentType: 'application/json',
            async: false,
            dataType:'json',
            data: JSON.stringify(userIdMap),
            success: function (data, textStatus, three) {
                if (textStatus === "success") {

                    populateReviewTab( groupName, data );

                }//end if -- success
            }
        });
    }//end if -- have not yet populated the review tab

    
    //add the event handlers to the datatables actions buttons
    $('.request-actions .closeRequest').live('click', function (e) {
        var reqID = $(this).attr('data-id');
        var requestIdMap = { "requestId": reqID };

        $.ajax({
            url: '../dart/closeRequest.json',
            type: 'POST',
            async: false,
            contentType: 'application/json',
            dataType:'json',
            data: JSON.stringify(requestIdMap),
            success: function (data, textStatus, three) {
                if (textStatus === "success") {
                    var rId = data.requestId;

                    //TODO: collapse this into the JSON response also?

                    //
                    // close requests on the Request tab
                    var reqStatusLabel = $('div#dashboardContent div#requests table tbody label[data-id="' + rId + '"]');
                    reqStatusLabel.removeClass('label-important');
                    reqStatusLabel.removeClass('label-info');
                    reqStatusLabel.removeClass('label-warning');
                    reqStatusLabel.removeClass('label-success');
                    reqStatusLabel.removeClass('label-info');
                    reqStatusLabel.removeClass('label-inverse');
                    reqStatusLabel.addClass('label-important');
                    reqStatusLabel.text('CLOSED');
                    $('div#dashboardContent div#requests table tbody div[data-id="' + rId + '"] ul').remove();

                    //
                    // close requests on the admin tab (only applicable if you are both a requestor and an admin)
                    var reviewStatusLabel = $('div#dashboardContent div#request-administration table tbody label[data-id="' + rId + '"]');
                    reviewStatusLabel.addClass('label-important');
                    reviewStatusLabel.text('CLOSED');
                    $('div#dashboardContent div#request-administration table tbody div[data-id="' + rId + '"] ul').remove();

                    //
                    // populate the user to-do list (may have closed tasks)
                    populateToDoList(userId);	//, todoDataTableOptions);
                }
            }
        });
    });
    
    //TODO: might want to use something other than live() here -- wasn't working for pagination in the datatables
    //populate the review status modal
    $('a[href=#statusModal]').live('click', function (e) {
        e.preventDefault();

        //get the requestId from the modal
        var clickLink = $(this);
        var rid = clickLink.attr('data-id');
        var wid = clickLink.attr('data-workflowid');

        var requestIdMap = { "requestId": rid };
        requestIdMap['workflowId'] = wid;	//get the status per workflow

        clickLink.find('.label').addClass('hide');	//hide the label and show the spinner
        clickLink.find('#spinner' + rid).removeClass('hide');


        var displayReviewStatus = function () {

            $.ajax({
                url: '../dart/listReviewStatus.json',
                type: 'POST',
                async: false,
                contentType: 'application/json',
                dataType:'json',
                data: JSON.stringify(requestIdMap),
                success: function (data, textStatus, three) {
                    if (textStatus === "success") {

                        if (data != null && data != undefined) {

                            //populate the template and display the review status
                            var requestStatusHeader = Mustache.render($(".requestStatusTemplate").html(), data);
                            $('div#statusModal div.modal-header h3.requestStatus').replaceWith(requestStatusHeader); //display the header

                            var reviewStatusBody = Mustache.render($(".reviewStatusTemplate").html(), data);
                            $('div#statusModal table.status-viz tbody').html(reviewStatusBody);

                            
                            $.each($('td.withdrawn'), function(index, element){             	
                            	var labelLabel = $( element ).find('label.label');       	
                            	labelLabel.addClass('label-default');	                         	
                            })

                            $.each($('td.approved'), function(index, element){
                            	var labelLabel = $( element ).find('label.label');
                            	labelLabel.addClass('label-success');
                            })

                            $.each($('td.denied'), function(index, element){
                            	var labelLabel = $( element ).find('label.label');
                            	labelLabel.addClass('label-important');
                            })

                            $.each($('td.change'), function(index, element){
                            	var labelLabel = $( element ).find('label.label');
                            	labelLabel.addClass('label-change');
                            })

                            $.each($('td.waiting'), function(index, element){
                            	var labelLabel = $( element ).find('label.label');
                            	labelLabel.addClass('label-warning');
                            })
                            
 
                            //update the review status styling
                            if (data.reviews != null && data.reviews != undefined) {

                                for (idx in data.reviews) {	//step through the reviews
                                    var review = data.reviews[idx];

                                    if (review != null && review != undefined) {

                                        var reviewRow = $('div#statusModal tr#' + review.groupNameNoSpaces); //initial and final NDS review have spaces in the name
                                        if (reviewRow != null && reviewRow != undefined) {

                                            //TODO: could update the JSON to return a boolean (for each status) and then move this to the template
                                            //update the display for the review status badge
                                            var reviewStatusLabel = reviewRow.find('label.label');

                                            //update over, over-what styles (assuming that over == > median value, over-what == median when there is an over)
                                            if (review.daysElapsed > review.medianDaysElapsed) {
                                                if (reviewRow != null && reviewRow != undefined) {
                                                    reviewRow.find('td#reviewerActual' + review.id).addClass('over'); //greater than the median value
                                                    reviewRow.find('td#reviewerMedian' + review.id).addClass('over-what');
                                                } //end if
                                            } //end if
                                            if (review.requestorDaysElapsed > review.requestorMedianDaysElapsed) {
                                                if (reviewRow != null && reviewRow != undefined) {
                                                    reviewRow.find('td#requestorActual' + review.id).addClass('over'); //greater than the median value
                                                    reviewRow.find('td#requestorMedian' + review.id).addClass('over-what');
                                                } //end if
                                            } //end if

                                        } //end if
                                    } //end if
                                } //end for
                            } //end if

                        } //end if -- data
                    }

                    //$('div#statusModal .progress').hide();
                }//end success
            });


            //hide spinner and display the label again
            clickLink.find('.label').removeClass('hide');
            clickLink.find('#spinner' + rid).addClass('hide');
        };//end displayReviewStatus
        //short delay to allow UI (spinner) to catch up (IE bug fix)
        window.setTimeout(displayReviewStatus, 100);
    });

    setFilters();
});

// populate the user to-do list
var populateToDoList = function (userId) {	//, dataTableOptions) {

    //	var initDataTables = false;

    var userIdMap = { "userId": userId };

    $.ajax({
        url: '../dart/getUserTasks.json',
        type: 'POST',
        async: false,
        contentType: 'application/json',
        dataType:'json',
        data: JSON.stringify(userIdMap),
        success: function (data, textStatus, three) {
            //			initDataTables = true;

            if (textStatus === "success") {
                var tlist = data.tasks;
                if (tlist != null) {
                    var tCount = tlist.length;
                    $('#awaitingResponse').html(tCount);

                    var todoTabBody = Mustache.render($(".todoTabTemplate").html(), tCount);	//set the # of ToDo items
                    $('ul#dashboardTab li#to-doTab').html(todoTabBody);

                    if (tlist.length > 0) {
                        $('#awaitingResponse').html(tCount);

                        $('div#dashboardContent div.alert span.alert-todo').html(tCount);

                        var tableBody = Mustache.render($(".taskRowTemplate").html(), data);
                        $('div#dashboardContent div#to-do table tbody').html(tableBody);
                    }
                    else {
                        // no tasks
                        $('#awaitingResponse').html('0');
                        $('div#to-do table tbody').html('');
                        $('div#to-do div.alert').remove();
                    }
                }
            }
            else {
                // no tasks
                $('#awaitingResponse').html('0');
                $('div#to-do table tbody').html('');
                $('div#to-do div.alert').remove();
            }

            //TODO: doesn't like it when I move this outside of the task? (might need to use async:false)		
            progressIncrease('100%');

            //			//turn off sorting/searching for actions column
            //			dataTableOptions["aoColumnDefs"] = [
            //				{ "bSortable": false, "aTargets": [ 6 ] },
            //				{ "bSearchable": false, "aTargets": [ 6 ] }
            //			]
            //			$('div#dashboardContent div#to-do .table').dataTable(dataTableOptions);

            //TODO: might want to wait to hide the progress bar until we have also retrieved the requests
            $('div#dashboardContent .progress').fadeOut();
            $('div#dashboardContent div#to-do').addClass('in');
        },
        error: function () {
            $('div#dashboardContent .progress').hide();
            $('div#to-do div.alert').removeClass('alert-info').addClass('alert-error').html('Error loading to-do list.');
            $('div#dashboardContent div#to-do').addClass('in');
        }
    });

    //	return initDataTables;
};

//populate the request tab:  data.requests
var populateRequestorTab = function( data ) {

    //create a new copy of the dataTableOptions
    var reqDataTableOptions = {
        "iDisplayLength": 10,
        "sDom": "<'top row-fluid'<'span6'i><'span6'f>>t<'bottom row-fluid'<'span6'p><'span6 switcher'>>",
        "oLanguage": {
            "sInfo": "Showing _START_ to _END_ of _TOTAL_",
            "sInfoFiltered": "(filtered)"
        },
        "fnDrawCallback": function () {
            //hide pagination if there's only one page
            //This also fires if search results are less than one page
            if (this.fnPagingInfo().iTotalPages > 1) {
                $(this).next('.bottom').find('.dataTables_paginate').show();
            } else {
                $(this).next('.bottom').find('.dataTables_paginate').hide();
            }
        }
    };

	
    var rlist = data.requests;
    if (rlist.length > 0) {
        //var tableBody = Mustache.render($(".requestRowTemplate").html(), data);
        //$('#dashboardContent #requests table tbody').html(tableBody);

//testing -- moved below (add the event handlers to the action menu items)    	
//        $('.request-actions .amendButton').on('click', function (e) {
//            var reqID = $(this).attr('data-id');
//            $('#amendRequestModal input#requestID').val(reqID);
//        });
//
//        $('.request-actions .closeRequest').on('click', function (e) {
//            var reqID = $(this).attr('data-id');
//            var requestIdMap = { "requestId": reqID };
//
//            $.ajax({
//                url: '../dart/closeRequest.json',
//                type: 'POST',
//                async: false,
//                contentType: 'application/json',
//                dataType:'json',
//                data: JSON.stringify(requestIdMap),
//                success: function (data, textStatus, three) {
//                    if (textStatus === "success") {
//                        var rId = data.requestId;
//
////TODO: collapse this into the JSON response also?
//                        //
//                        // close requests on the Request tab
//                        var reqStatusLabel = $('div#dashboardContent div#requests table tbody label[data-id="' + rId + '"]');
//                        reqStatusLabel.removeClass('label-important');
//                        reqStatusLabel.removeClass('label-info');
//                        reqStatusLabel.removeClass('label-warning');
//                        reqStatusLabel.removeClass('label-success');
//                        reqStatusLabel.removeClass('label-info');
//                        reqStatusLabel.removeClass('label-inverse');
//                        reqStatusLabel.addClass('label-important');
//                        reqStatusLabel.text('CLOSED');
//                        $('div#dashboardContent div#requests table tbody div[data-id="' + rId + '"] ul').remove();
//
//                        //
//                        // close requests on the admin tab (only applicable if you are both a requestor and an admin
//                        var reviewStatusLabel = $('div#dashboardContent div#request-administration table tbody label[data-id="' + rId + '"]');
//                        reviewStatusLabel.addClass('label-important');
//                        reviewStatusLabel.text('CLOSED');
//                        $('div#dashboardContent div#request-administration table tbody div[data-id="' + rId + '"] ul').remove();
//
//                        //
//                        // populate the user to-do list (may have closed tasks)
//                        populateToDoList(userId);	//, todoDataTableOptions);
//                    }
//                }
//            });
//        });

        // initialize the requests tab header
        var reqCount = data.requests.length,
            rowCount = reqCount;
        var requestTabBody = Mustache.render($(".requestTabTemplate").html(), reqCount);
        $('ul#dashboardTab li#requestsTab').html(requestTabBody);


//      // now fix the status labeling
//	    // Loop through all rows and add each row formatting update to the Javascript 
//        while(rowCount--) {
//        	
//	            var lblText = data.requests[rowCount].status,
//	            	rId = data.requests[rowCount].requestId;
//	            
//	            requestorTabDelayStart(lblText, rId, rowCount);
//        };
//
//        // Add dateTable creation to end of queue to wait for all row formatting to complete
//	    setTimeout(function() {


//start datatable initialization
        var dataForTable = [];
        for(idx in data.requests) {
            var currRow = data.requests[idx];
        	
            //set the values for each cell in the table
            var dataForRow = {};
            dataForRow['trackingNumber'] = {'trackingNumber':currRow.trackingNumber};
            dataForRow['activityName'] = {'activityName':currRow.activityName, 'researchRequest':currRow.researchRequest, 'preparatoryRequest':currRow.preparatoryRequest, 'operationsRequest':currRow.operationsRequest, 'activityId':currRow.activityId, 'requestId':currRow.requestId, 'reviewId':currRow.reviewId, 'workflowId':currRow.workflowId};
            dataForRow['requestType'] = {'requestType':currRow.requestType};
            dataForRow['contact'] = {'contact':currRow.contact};
            dataForRow['submitted'] = {'submitted':currRow.submitted};
//            dataForRow['status'] = {'statusList':currRow.statusList, 'requestId':currRow.requestId};
            dataForRow['status'] = {'requestId':currRow.requestId, 'workflowNameList':currRow.workflowNameList, 'workflowStatusList':currRow.workflowStatusList, 'padLeft':currRow.padLeft};
            dataForRow['actions'] = {'researchRequest':currRow.researchRequest, 'preparatoryRequest':currRow.preparatoryRequest, 'operationsRequest':currRow.operationsRequest, 'activityId':currRow.activityId, 'requestId':currRow.requestId, 'reviewId':currRow.reviewId, 'workflowId':currRow.workflowId, 'editable':currRow.editable, 'requestor':data.requestor, 'amendable':currRow.amendable};
            
            dataForTable.push(dataForRow);
        }//end for
        
        reqDataTableOptions["aaData"] = dataForTable;	//use the JSON response data instead of pre-rendering all of the contents
        reqDataTableOptions["aoColumnDefs"] = [
            { "bSortable": false, "aTargets": [6] },	//turn off sorting/searching for actions column
            { "bSearchable": false, "aTargets": [6] },
            { "mData": "trackingNumber", "aTargets": [0], 
              "mRender": function(data, type, full) {
            	  			if (type == "display") {
				  	    		var cellBody = Mustache.render($(".singleRequestRowTemplate_trackingNumber").html(), data);
				  	    		return cellBody;
				  	    	}
            	  			return data.trackingNumber;
              			}
            },
            { "mData": "activityName", "aTargets": [1], 
              "mRender": function(data, type, full) {
		    	  			if (type == "display") {
				  	    		var cellBody = Mustache.render($(".singleRequestRowTemplate_activityName").html(), data);
				  	    		return cellBody;
				  	    	}
            	  			return data.activityName;
		      			}
            },
            { "mData": "requestType", "aTargets": [2], 
              "mRender": function(data, type, full) {
		    	  			if (type == "display") {
				  	    		var cellBody = Mustache.render($(".singleRequestRowTemplate_requestType").html(), data);
				  	    		return cellBody;
				  	    	}
            	  			return data.requestType;
		      			}
            },
            { "mData": "contact", "aTargets": [3], 
              "mRender": function(data, type, full) {
		    	  			if (type == "display") {
				  	    		var cellBody = Mustache.render($(".singleRequestRowTemplate_contact").html(), data);
				  	    		return cellBody;
				  	    	}
            	  			return data.contact;
		      			}
            },
            { "mData": "submitted", "aTargets": [4], 
              "mRender": function(data, type, full) {
		    	  			if (type == "display") {
				  	    		var cellBody = Mustache.render($(".singleRequestRowTemplate_submitted").html(), data);
				  	    		return cellBody;
				  	    	}
            	  			return data.submitted;
		      			}
            },
            { "mData": "status", "aTargets": [5], 
                "mRender": function(data, type, full) {
  		    	  			if (type == "display") {
  				  	    		var cellBody = Mustache.render($(".singleRequestRowTemplate_status").html(), data);
  				  	    		return cellBody;
  				  	    	}
  		    	  			//return (JSON.stringify(data.statusList));	//return possibly multiple values
  		    	  			return (JSON.stringify(data.workflowStatusList) + JSON.stringify(data.workflowNameList));	//return possibly multiple values
  		      			}
            },
            { "mData": "actions", "aTargets": [6], 
              "mRender": function(data, type, full) {
		    	  			if (type == "display") {
				  	    		var cellBody = Mustache.render($(".singleRequestRowTemplate_actions").html(), data);
				  	    		return cellBody;
				  	    	}
		    	  			return "Actions";	//actions column not used for sorting or searching
		      			}
            }
        ];

//        reqDataTableOptions["fnRowCallback"] = function (tr, data, index) {
//        	var rowIndex = index;
//
//        	//add the event handlers to the actions
//        	var closeButtonId = "closeRequest" + data.actions.requestId;
//        	var closeButtonCtrl = $(closeButtonId);
//        	
//            //closeButtonCtrl.off('click');
//            closeButtonCtrl.on('click', function (e) {
//                var reqID = $(this).attr('data-id');
//                var requestIdMap = { "requestId": reqID };
//
//                $.ajax({
//                    url: '../dart/closeRequest.json',
//                    type: 'POST',
//                    async: false,
//                    contentType: 'application/json',
//                    dataType:'json',
//                    data: JSON.stringify(requestIdMap),
//                    success: function (data, textStatus, three) {
//                        if (textStatus === "success") {
//                            var rId = data.requestId;
//
//                            //TODO: collapse this into the JSON response also?
//
//                            //
//                            // close requests on the Request tab
//                            var reqStatusLabel = $('div#dashboardContent div#requests table tbody label[data-id="' + rId + '"]');
//                            reqStatusLabel.removeClass('label-important');
//                            reqStatusLabel.removeClass('label-info');
//                            reqStatusLabel.removeClass('label-warning');
//                            reqStatusLabel.removeClass('label-success');
//                            reqStatusLabel.removeClass('label-info');
//                            reqStatusLabel.removeClass('label-inverse');
//                            reqStatusLabel.addClass('label-important');
//                            reqStatusLabel.text('CLOSED');
//                            $('div#dashboardContent div#requests table tbody div[data-id="' + rId + '"] ul').remove();
//
//                            //
//                            // close requests on the admin tab (only applicable if you are both a requestor and an admin)
//                            var reviewStatusLabel = $('div#dashboardContent div#request-administration table tbody label[data-id="' + rId + '"]');
//                            reviewStatusLabel.addClass('label-important');
//                            reviewStatusLabel.text('CLOSED');
//                            $('div#dashboardContent div#request-administration table tbody div[data-id="' + rId + '"] ul').remove();
//
//                            //
//                            // populate the user to-do list (may have closed tasks)
//                            populateToDoList(userId);	//, todoDataTableOptions);
//                        }
//                    }
//                });
//            });
//        };

        reqDataTableOptions["bDeferRender"] = true;	//only render the visible rows
        requestTable = $('div#dashboardContent div#requests table').dataTable(reqDataTableOptions);
//end datatable initialization


        $('#requestFilterAll').on('change', function(){
            $.cookie("filterType", 1, { path: '/', expires:366 });
            setFilters();
        });

        $('#requestFilterResearch').on('change', function(){
            $.cookie("filterType", 2, { path: '/', expires:366 });
            setFilters();
        });

        $('#requestFilterOperations').on('change', function(){
            $.cookie("filterType", 3, { path: '/', expires:366 });
            setFilters();
        });
        
        $('#requestFilterPreparatory').on('change', function(){
            $.cookie("filterType", 4, { path: '/', expires:366 });
            setFilters();
        });
//	    }, reqCount + 5); // This will be added to the queue 5 seconds after the last row format update to allow time for row to finish
    }

};


//populate the review tab (administer requests):  data.requests
var populateReviewTab = function( groupName, data ) {

    //create a new copy of the dataTableOptions
    var reviewDataTableOptions = {
        "iDisplayLength": 10,
        "sDom": "<'top row-fluid'<'span6'i><'span6'f>>t<'bottom row-fluid'<'span6'p><'span6 switcher'>>",
        "oLanguage": {
            "sInfo": "Showing _START_ to _END_ of _TOTAL_",
            "sInfoFiltered": "(filtered)"
        },
        "fnDrawCallback": function () {
            //hide pagination if there's only one page
            //This also fires if search results are less than one page
            if (this.fnPagingInfo().iTotalPages > 1) {
                $(this).next('.bottom').find('.dataTables_paginate').show();
            } else {
                $(this).next('.bottom').find('.dataTables_paginate').hide();
            }
        }
    };
	
	
    var rlist = data.requests, reqCount = data.requests.length, tableRows = reqCount;

    //
    // initialize the requests tab (update the administration tab title to the group title)
    var adminGroupMap = {'groupName' : groupName};
    adminGroupMap['reqCount'] = rlist.length;

    var adminGroupTabBody = Mustache.render($(".adminGroupTabTemplate").html(), adminGroupMap);
    $('ul#dashboardTab li#request-administrationTab').html(adminGroupTabBody);


    if (rlist.length > 0) {
//        var tableBody = Mustache.render($(".administer-requestRowTemplate").html(), data);
//        $('#dashboardContent #request-administration table tbody').html(tableBody);

    	
//	    // now fix the status labeling
//	    // Loop through all rows and add each row formatting update to the Javascript queue
//	    while(tableRows--) {
//			var lblText = data.requests[tableRows].status, rId = data.requests[tableRows].requestId;
//			reviewTabDelayStart(lblText, rId, tableRows);
//	    }
//
//
//        // Add dateTable creation to end of queue to wait for all row formatting to complete
//	    setTimeout(function() {


//start datatable initialization
    var dataForTable = [];
    for(idx in data.requests) {
        var currRow = data.requests[idx];
    	
        //set the values for each cell in the table
        var dataForRow = {};
        dataForRow['trackingNumber'] = {'trackingNumber':currRow.trackingNumber};
        dataForRow['activityName'] = {'activityName':currRow.activityName, 'researchRequest':currRow.researchRequest, 'preparatoryRequest':currRow.preparatoryRequest,'operationsRequest':currRow.operationsRequest, 'activityId':currRow.activityId, 'requestId':currRow.requestId, 'reviewId':currRow.reviewId, 'workflowId':currRow.workflowId};
        dataForRow['requestType'] = {'requestType':currRow.requestType};
        dataForRow['contact'] = {'contact':currRow.contact};
        dataForRow['submitted'] = {'submitted':currRow.submitted};
//        dataForRow['status'] = {'statusList':currRow.statusList, 'requestId':currRow.requestId};
        dataForRow['status'] = {'requestId':currRow.requestId, 'workflowNameList':currRow.workflowNameList, 'workflowStatusList':currRow.workflowStatusList, 'padLeft':currRow.padLeft};
        dataForRow['actions'] = {'researchRequest':currRow.researchRequest, 'preparatoryRequest':currRow.preparatoryRequest,'operationsRequest':currRow.operationsRequest, 'activityId':currRow.activityId, 'requestId':currRow.requestId, 'reviewId':currRow.reviewId, 'workflowId':currRow.workflowId};
        
        dataForTable.push(dataForRow);
    }//end for
    
    reviewDataTableOptions["aaData"] = dataForTable;	//use the JSON response data instead of pre-rendering all of the contents
    reviewDataTableOptions["aoColumnDefs"] = [
        { "bSortable": false, "aTargets": [6] },		//turn off sorting/searching for actions column
        { "bSearchable": false, "aTargets": [6] },
        { "mData": "trackingNumber", "aTargets": [0], 
          "mRender": function(data, type, full) {
        	  			if (type == "display") {
			  	    		var cellBody = Mustache.render($(".singleRequestRowTemplate_trackingNumber").html(), data);
			  	    		return cellBody;
			  	    	}
        	  			return data.trackingNumber;
          			}
        },
        { "mData": "activityName", "aTargets": [1], 
          "mRender": function(data, type, full) {
	    	  			if (type == "display") {
			  	    		var cellBody = Mustache.render($(".singleAdminister-requestRowTemplate_activityName").html(), data);
			  	    		return cellBody;
			  	    	}
        	  			return data.activityName;
	      			}
        },
        { "mData": "requestType", "aTargets": [2], 
          "mRender": function(data, type, full) {
	    	  			if (type == "display") {
			  	    		var cellBody = Mustache.render($(".singleRequestRowTemplate_requestType").html(), data);
			  	    		return cellBody;
			  	    	}
        	  			return data.requestType;
	      			}
        },
        { "mData": "contact", "aTargets": [3], 
          "mRender": function(data, type, full) {
	    	  			if (type == "display") {
			  	    		var cellBody = Mustache.render($(".singleRequestRowTemplate_contact").html(), data);
			  	    		return cellBody;
			  	    	}
        	  			return data.contact;
	      			}
        },
        { "mData": "submitted", "aTargets": [4], 
          "mRender": function(data, type, full) {
	    	  			if (type == "display") {
			  	    		var cellBody = Mustache.render($(".singleRequestRowTemplate_submitted").html(), data);
			  	    		return cellBody;
			  	    	}
        	  			return data.submitted;
	      			}
        },
        { "mData": "status", "aTargets": [5], 
            "mRender": function(data, type, full) {
  	    	  			if (type == "display") {
  	    	  				if( superUser == true ) {
	  			  	    		var cellBody = Mustache.render($(".singleRequestRowTemplate_status").html(), data);
	  			  	    		return cellBody;
  	    	  				} else {
	  			  	    		var cellBody = Mustache.render($(".singleAdminister-requestRowTemplate_status").html(), data);	//no workflow name
	  			  	    		return cellBody;
  	    	  				}
  			  	    	}
  	    	  			//return (JSON.stringify(data.statusList));	//return possibly multiple values
  	    	  			return (JSON.stringify(data.workflowStatusList) + JSON.stringify(data.workflowNameList));	//return possibly multiple values
  	      			}
        },
        { "mData": "actions", "aTargets": [6], 
          "mRender": function(data, type, full) {
	    	  			if (type == "display") {
			  	    		var cellBody = Mustache.render($(".singleAdminister-requestRowTemplate_actions").html(), data);
			  	    		return cellBody;
			  	    	}
	    	  			return "Actions";	//actions column not used for sorting or searching
	      			}
        }
    ];
        
        reviewDataTableOptions["bDeferRender"] = true;	//only render the visible rows
        requestAdminTable = $('div#dashboardContent div#request-administration table').dataTable(reviewDataTableOptions);
//end datatable initialization

        //on page refresh start with all - related to changing roles for testing
        $.cookie("filterType", 1, { path: '/', expires:366 });
        
        $('#requestAdminFilterAll').on('change', function(){
            $.cookie("filterType", 1, { path: '/', expires:366 });
            setFilters();
        });

        $('#requestAdminFilterResearch').on('change', function(){
            $.cookie("filterType", 2, { path: '/', expires:366 });
            setFilters();
        });

        $('#requestAdminFilterOperations').on('change', function(){
            $.cookie("filterType", 3, { path: '/', expires:366 });
            setFilters();
        });
        
        $('#requestAdminFilterPreparatory').on('change', function(){
            $.cookie("filterType", 4, { path: '/', expires:366 });
            setFilters();
        });
//	    }, reqCount + 5); // This will be added to the queue 5 seconds after the last row format update to allow time for row to finish
    }
};

// Entry point for adding row formatting to the queue
function requestorTabDelayStart(lblText, rId, reqCount) {
    // Must dynamically create function definitions to add a new one to the queue and not add existing functions
    // Not doing this will just reformat the same row
    setTimeout('requestorTabDelayImpl("' + lblText + '", "' + rId + '")', reqCount);
}

// Do row formatting work
function requestorTabDelayImpl(lblText, rId) {
    if (lblText.toUpperCase() === 'INITIATED') {
        $('div#dashboardContent div#requests table tbody label[data-id="' + rId + '"]').addClass('label-inverse');
        $('div#dashboardContent div#requests table tbody label[data-id="' + rId + '"]').text('NOT SUBMITTED');
    }
    if (lblText.toUpperCase() === 'SUBMITTED') {
        $('div#dashboardContent div#requests table tbody label[data-id="' + rId + '"]').addClass('label-info');
        $('div#dashboardContent div#requests table tbody label[data-id="' + rId + '"]').text('SUBMITTED');
    }
    if (lblText.toUpperCase() === 'CHANGE REQUESTED') {
        $('div#dashboardContent div#requests table tbody label[data-id="' + rId + '"]').addClass('label-warning');
        $('div#dashboardContent div#requests table tbody label[data-id="' + rId + '"]').text('CHANGE REQUESTED');

    }
    if (lblText.toUpperCase() === 'DENIED') {
        $('div#dashboardContent div#requests table tbody label[data-id="' + rId + '"]').addClass('label-important');
        $('div#dashboardContent div#requests table tbody label[data-id="' + rId + '"]').text('DENIED');
        //$('div#dashboardContent div#requests table tbody div[data-id="'+rId+'"] ul').remove();
    }
    if (lblText.toUpperCase() === 'CLOSED') {
        $('div#dashboardContent div#requests table tbody label[data-id="' + rId + '"]').addClass('label-important');
        $('div#dashboardContent div#requests table tbody label[data-id="' + rId + '"]').text('CLOSED');
        $('div#dashboardContent div#requests table tbody div[data-id="' + rId + '"] ul').remove();
    }
    if (lblText.toUpperCase() === 'APPROVED') { // ONLY STATE YOU CAN AMEND
        $('div#dashboardContent div#requests table tbody label[data-id="' + rId + '"]').addClass('label-success');
        $('div#dashboardContent div#requests table tbody label[data-id="' + rId + '"]').text('APPROVED');
    }
    if (lblText.indexOf('%') != -1) {
        $('div#dashboardContent div#requests table tbody label[data-id="' + rId + '"]').addClass('label-info');
    }
}

//Entry point for adding row formatting to the queue
function reviewTabDelayStart(lblText, rId, reqCount) {
    // Must dynamically create function definitions to add a new one to the queue and not add existing functions
    // Not doing this will just reformat the same row
    setTimeout('reviewTabDelayImpl("' + lblText + '", "' + rId + '")', reqCount);
}

//Do row formatting work
function reviewTabDelayImpl(lblText, rId) {
    if (lblText.toUpperCase() === 'SUBMITTED') {
        $('div#dashboardContent div#request-administration table tbody label[data-id="' + rId + '"]').addClass('label-info');
        $('div#dashboardContent div#request-administration table tbody label[data-id="' + rId + '"]').text('SUBMITTED');
        $('div#dashboardContent div#request-administration table tbody a.reviewButton[data-id="' + rId + '"]').removeAttr("data-toggle");
    }
    if (lblText.toUpperCase() === 'CHANGE REQUESTED') {
        $('div#dashboardContent div#request-administration table tbody label[data-id="' + rId + '"]').addClass('label-warning');
        $('div#dashboardContent div#request-administration table tbody label[data-id="' + rId + '"]').text('CHANGE REQUESTED');
        $('div#dashboardContent div#request-administration table tbody a.reviewButton[data-id="' + rId + '"]').removeAttr("data-toggle");
    }
    if (lblText.toUpperCase() === 'DENIED') {
        $('div#dashboardContent div#request-administration table tbody label[data-id="' + rId + '"]').addClass('label-important');
        $('div#dashboardContent div#request-administration table tbody label[data-id="' + rId + '"]').text('DENIED');
        $('div#dashboardContent div#request-administration table tbody div[data-id="' + rId + '"] ul').remove();
    }
    if (lblText.toUpperCase() === 'CLOSED') {
        $('div#dashboardContent div#request-administration table tbody label[data-id="' + rId + '"]').addClass('label-important');
        $('div#dashboardContent div#request-administration table tbody label[data-id="' + rId + '"]').text('CLOSED');
        $('div#dashboardContent div#request-administration table tbody div[data-id="' + rId + '"] ul').remove();
    }
    if (lblText.toUpperCase() === 'APPROVED') {
        $('div#dashboardContent div#request-administration table tbody label[data-id="' + rId + '"]').addClass('label-success');
        $('div#dashboardContent div#request-administration table tbody label[data-id="' + rId + '"]').text('APPROVED');
    }
    if (lblText.indexOf('%') != -1) {
        $('div#dashboardContent div#request-administration table tbody label[data-id="' + rId + '"]').addClass('label-info');
        $('div#dashboardContent div#request-administration table tbody a.reviewButton[data-id="' + rId + '"]').removeAttr("data-toggle");
    }
}

var setFilters = function() {

    switch($.cookie("filterType")){
        case "1":
            $('#toDoFilterAll').prop('checked', true);
            $('#requestFilterAll').prop('checked', true);
            $('#requestAdminFilterAll').prop('checked', true);
            if(isNotNullOrUndef(toDoTable)) {
                toDoTable.fnFilter('', 3);
            }
            if(isNotNullOrUndef(requestTable)) {
                requestTable.fnFilter('', 2);
            }
            if(isNotNullOrUndef(requestAdminTable)) {
                requestAdminTable.fnFilter('', 2);
            }
            break;
        case "2":
            $('#toDoFilterResearch').prop('checked', true);
            $('#requestFilterResearch').prop('checked', true);
            $('#requestAdminFilterResearch').prop('checked', true);
            if(isNotNullOrUndef(toDoTable)) {
                toDoTable.fnFilter('Research Data Access', 3);
            }
            if(isNotNullOrUndef(requestTable)) {
                requestTable.fnFilter('Research Data Access', 2);
            }
            if(isNotNullOrUndef(requestAdminTable)) {
                requestAdminTable.fnFilter('Research Data Access', 2);
            }
            break;
        case "3":
            $('#toDoFilterOperations').prop('checked', true);
            $('#requestFilterOperations').prop('checked', true);
            $('#requestAdminFilterOperations').prop('checked', true);
            if(isNotNullOrUndef(toDoTable)) {
                toDoTable.fnFilter('Operations Data Access', 3);
            }
            if(isNotNullOrUndef(requestTable)) {
                requestTable.fnFilter('Operations Data Access', 2);
            }
            if(isNotNullOrUndef(requestAdminTable)) {
                requestAdminTable.fnFilter('Operations Data Access', 2);
            }
            break;
        case "4":
            $('#toDoFilterPreparatory').prop('checked', true);
            $('#requestFilterPreparatory').prop('checked', true);
            $('#requestAdminFilterPreparatory').prop('checked', true);
            if(isNotNullOrUndef(toDoTable)) {
                toDoTable.fnFilter('Preparatory to Research Access', 3);
            }
            if(isNotNullOrUndef(requestTable)) {
                requestTable.fnFilter('Preparatory to Research Access', 2);
            }
            if(isNotNullOrUndef(requestAdminTable)) {
                requestAdminTable.fnFilter('Preparatory to Research Access', 2);
            }
            break;
        default:
            $('#toDoFilterAll').prop('checked', true);
            $('#requestFilterAll').prop('checked', true);
            $('#toDoFilterAll').prop('checked', true);
            if(isNotNullOrUndef(toDoTable)) {
                toDoTable.fnFilter('', 3);
            }
            if(isNotNullOrUndef(requestTable)) {
                requestTable.fnFilter('', 2);
            }
            if(isNotNullOrUndef(requestAdminTable)) {
                requestAdminTable.fnFilter('', 2);
            }
            break;
    }
};

var isNotNullOrUndef = function (variable) {

    if (variable !== null && variable !== undefined) {
        return true;
    }

    return false;
};