﻿function showTestAppealConfirmation() {
	var elementsList = document.getElementsByTagName("input");

	var countOfCheckedElements = 0;
	
	for (var count = 0; count < elementsList.length; count++) {
		if ((elementsList[count].type == "checkbox") && (elementsList[count].id != NOT_INCLUDE_TESTAPPEAL_CONTROL_ID)) {
			if (elementsList[count].checked) {
				countOfCheckedElements++;
			}
		}
	}
	
	if (countOfCheckedElements > 0)
	{
		var dialog = $("<div />")
			.attr("title", TESTAPPEAL_TITLE)
			.html(TESTAPPEAL_CONFIRMATION)
			.appendTo($("body"))
			.dialog({
				bgiframe: true,
				modal: true,
				buttons: {
					"NO": function() {
						$(this).dialog("close");
						$(this).dialog("destroy");
					},
					"YES": function() {
						eval($("#" + AppealTestsEventReference).val());
					}
				}
			});
			
		dialog.parent().find(".ui-dialog-buttonpane > button:eq(1)").html(YES_STRING).css("padding", "0.2em 1em");
		dialog.parent().find(".ui-dialog-buttonpane > button:eq(0)").html(NO_STRING).css("padding", "0.2em 1em");
	}
};

function createMessageBox(candidate) {

	var dialog = $("<div />")
		.attr("title", CONFIRMATION_TITLE_STRING)
		.css("padding", "5px")
		.appendTo($("body"));
		
	$("<div />")
		.html(DIALOG_CAPTION_VALUE)
		.css("margin", "10px 2px")
		.appendTo(dialog);
		
	$("<div />")
		.html(candidate.name)
		.css("font-weight", "bold")
		.css("margin", "4px 2px")
		.appendTo(dialog);
		
	var candidateDataTable = $("<table><tbody><tr><td></td><td></td></tr><tr><td></td><td></td></tr><tr><td></td><td></td></tr><tr><td></td><td></td></tr></tbody></table>")
		.appendTo(dialog);
		
	candidateDataTable.find("tr:eq(0) td:eq(0)").html(BCSID_VALUE);
	candidateDataTable.find("tr:eq(0) td:eq(1)").html(candidate.bcsId);
	candidateDataTable.find("tr:eq(1) td:eq(0)").html(CERTIFICATION_VALUE);
	candidateDataTable.find("tr:eq(1) td:eq(1)").html(candidate.certification);
	candidateDataTable.find("tr:eq(2) td:eq(0)").html(SKILLCARDID_VALUE);
	candidateDataTable.find("tr:eq(2) td:eq(1)").html(candidate.skillCardId);
	candidateDataTable.find("tr:eq(3) td:eq(0)").html(REGISTRATIONDATE_VALUE);
	candidateDataTable.find("tr:eq(3) td:eq(1)").html(candidate.registrationDate);
		
	$("<div />")
		.html(DIALOG_NOTE)
		.css("margin", "4px 2px")
		.appendTo(dialog);
		
	dialog.dialog({
		bgiframe: true,
		modal: true,
		buttons: {
			"NO": function() {
				$(this).dialog("close");
				$(this).dialog("destroy");
			},
			"YES": function() {
				eval($("#" + RestoreBCSCandidateEventReferenceClientID).val());
			}
		},
		open: function() {
			$(this).parent().find('.ui-dialog-buttonpane button:eq(0)').focus();
		}
	});
	
	dialog.parent().find(".ui-dialog-buttonpane > button:eq(1)").html(YES_STRING).css("padding", "0.2em 1em");
	dialog.parent().find(".ui-dialog-buttonpane > button:eq(0)").html(NO_STRING).css("padding", "0.2em 1em");
};

function createRemainUsersDialog(json, cancel) {
	
	var dialog = $("<div id='remainUsersDialog'><div class='ui-dialog-message' /></div>")
		.attr("title", json.title)
		.appendTo($("#form1"));
		
	dialog	
		.find(".ui-dialog-message")
		.html(json.message);
		
	for(var row = 0; row < json.candidates.length; row++) {
		$("<div />")
			.addClass("ui-dialog-data")
			.html(json.candidates[row])
			.appendTo(dialog);
	};
	
	dialog.dialog({
		bgiframe: true,
		modal: true,
		buttons: {
			"Cancel" : function() {
				$(this).dialog("close");
				$(this).dialog("destroy");
			}
		},
		open: function() {
			$(this).parent().find('.ui-dialog-buttonpane button:eq(0)').focus();
		}
	});
	
	dialog.parent().find(".ui-dialog-buttonpane > button").html(cancel).css("padding", "0.2em 1em");
};
 
function createControl (candidateObject) {

	var dialogbase = $("<div />")
		.attr("title", candidateObject.strings.title)
		.appendTo($("body"));

	var table = $("<table cellpadding='3' cellspacing='5' width='100%' height='100%' />")
		.appendTo(dialogbase);
		
	var tbody = $("<tbody />").appendTo(table);
		
	createCandidateInfoSection(candidateObject.candidate, tbody);
	createEnrollmentInfoSection(candidateObject.enrollment, tbody, candidateObject.strings.confirmed);
	createAllocationSection(candidateObject, tbody);
	
	dialogbase.dialog({
		bgiframe: true,
		modal: true,
		width: 430,
		buttons: {
			"Cancel" : function() {
				$(this).dialog("close");
				$(this).dialog("destroy");
			}
		},
		open: function() {
			$(this).parent().find('.ui-dialog-buttonpane button:eq(0)').focus();
		}
	});
	
	dialogbase.parent().find(".ui-dialog-buttonpane > button").html(candidateObject.strings.buttonOk).css("padding", "0.2em 1em");
};

function createAllocationSection(candidateObject, parentElement) {

	if (candidateObject.testAllocation.testAllocations < 1) return; 
	
	createGroupRow(candidateObject.testAllocation.title, parentElement);
	
	for (var row = 0; row < candidateObject.testAllocation.testAllocations.length; row++) {
		createTextRowWithResult(
			candidateObject.testAllocation.testAllocations[row].description,
			candidateObject.testAllocation.testAllocations[row].moduleId,
			getAllocationStatus(candidateObject.testAllocation.testAllocations[row].status),
			parentElement);
			
		if (candidateObject.testAllocation.testAllocations[row].status != "Allocated") {
			parentElement.children("tr:last td:last").css("color", "red");
		};
	};
	
	$("<tr>").appendTo(parentElement);

	$("<td colspan='3'>")
		.addClass("messageInformationFields")
		.addClass("arrow")
		.html(ALLOCATION_NOTE_VALUE)
		.appendTo(parentElement.children("tr:last"));
};

function getAllocationStatus(status) {
	if (status == "Allocated") {
		return ALLOCATED_VALUE;
	} else if (status == "NotAvailable") {
		return NOT_AVAILABLE_VALUE;
	} else if (status == "NotSupported") {
		return NOT_SUPPORTED_VALUE;
	}
};

function createCandidateInfoSection(candidate, parentElement) {
	createGroupRow(candidate.title, parentElement);
	
	createTextRow(candidate.userIdTitle, candidate.userId, parentElement);
	createTextRow(candidate.firstNameTitle, candidate.firstName, parentElement);
	createTextRow(candidate.lastNameTitle, candidate.lastName, parentElement);
	createTextRow(candidate.middleNameTitle, candidate.middleName, parentElement);
};

function createEnrollmentInfoSection(enrollment, parentElement, result) {
	if (enrollment.enrollments.length < 1) return; 
	
	createGroupRow(enrollment.title, parentElement);
	
	for (var row = 0; row < enrollment.enrollments.length; row++) {
		createTextRowWithResult(
			enrollment.enrollments[row].certification,
			enrollment.enrollments[row].skillCard,
			result,
			parentElement);
	};
};

function createGroupRow(groupText, parentElement) {
	$("<tr />")
		.appendTo(parentElement);

	$("<td colspan='3' />")
		.addClass("messageInformationTitle")
		.addClass("arrow")
		.html(groupText)
		.appendTo(parentElement.children("tr:last"));
};

function createTextRow(name, value, parentElement) {
		$("<tr>")
			.appendTo(parentElement)
			
		$("<td>")
			.addClass("messageInformationFields")
			.addClass("arrow")
			.html(name)
			.appendTo(parentElement.children("tr:last"));
			
		$("<td>")
			.addClass("messageInformationFields")
			.addClass("arrow")
			.html(value)
			.appendTo(parentElement.children("tr:last"));
};

function createTextRowWithResult(name, value, result, parentElement) {
	$("<tr>")
		.appendTo(parentElement)
		
	$("<td>")
		.addClass("messageInformationFields")
		.addClass("arrow")
		.html(name)
		.appendTo(parentElement.children("tr:last"));
		
	$("<td>")
		.addClass("messageInformationFields")
		.addClass("arrow")
		.html(value)
		.appendTo(parentElement.children("tr:last"));
		
	$("<td>")
		.addClass("messageInformationFields")
		.addClass("arrow")
		.html(result)
		.appendTo(parentElement.children("tr:last"));
};

$.fn.expandMultipleDetails = function() {
	return this.each(function() {
		var content = $(this).next();
		
		if (content.attr("avaliable") == "false") return;
		
		var icon = $(this).find("span.ui-icon");

		if (!content.is(":visible")) {
			icon.removeClass("ui-icon-triangle-1-s").addClass("ui-icon-triangle-1-n");
			content.fadeIn();
		}
	});
};

$.fn.collapseMultipleDetails = function() {
	return this.each(function() {
		var content = $(this).next();
		
		if (content.attr("avaliable") == "false") return;
		
		var icon = $(this).find("span.ui-icon");
		
		if (content.is(":visible")) {
			icon.removeClass("ui-icon-triangle-1-n").addClass("ui-icon-triangle-1-s");
			content.fadeOut();
		}
	});
};

$.fn.attachExpander = function() {
	return this.each(function() {
		$(this).click(function() {
		
			var icon = $(this).find("span.ui-icon");
			var text = $(this).find('.text-content');
						
			if (text.text() == SHOW_ALL_DETAILS_VALUE) {
				$(this).parents().find(".headerRow").expandMultipleDetails();				
				text.text(HIDE_ALL_DETAILS_VALUE);
				icon.removeClass("ui-icon-triangle-1-s").addClass("ui-icon-triangle-1-n");
			} else {
				$(this).parents().find(".headerRow").collapseMultipleDetails();
				text.html(SHOW_ALL_DETAILS_VALUE);
				icon.removeClass("ui-icon-triangle-1-n").addClass("ui-icon-triangle-1-s");
			};
		});
	});
};

function create3FMultipleResultDialog(data) {

	var dialogbase = $("<div />")
		.attr("title", CONFIRMATION_TITLE_VALUE)
		.appendTo($("body"));
		
	var caption = $("<table width='100%' cellpadding='0' cellspacing='0'><tbody><tr><td/><td align='right'/></tr></tbody></table>").appendTo(dialogbase);

	$("<div />")
		.html(DIALOG_CAPTION_VALUE)
		.addClass("dialogCaption")
		.appendTo(caption.find("td:eq(0)"));
		
	$("<div><span class='ui-icon ui-icon-triangle-1-s' style='height:100%; width:12px; display:inline; text-indent:0px' /><span class='text-content' /></div>")
		.addClass("dialogCaptionRight")
		.appendTo(caption.find("td:eq(1)"))
		.attachExpander()
		.find('.text-content')
		.html(SHOW_ALL_DETAILS_VALUE);
		
	$("<br />").appendTo(dialogbase);
		
	for (var position = 0; position < data.candidates.length; position++)
	{
		var candidate = data.candidates[position];
		
		var headerRow = $("<div />").addClass("headerRow").width("100%").appendTo(dialogbase)
			.click(function() {			
				var content = $(this).next();
				var icon = $(this).find("span.ui-icon");
				if (content.attr("avaliable") == "false") return;
				
				if (content.is(":visible")) {
					icon.removeClass("ui-icon-triangle-1-n").addClass("ui-icon-triangle-1-s");
					content.hide("slide", { direction: "up" }, 1000);
				} else {
					icon.removeClass("ui-icon-triangle-1-s").addClass("ui-icon-triangle-1-n");
					content.show("slide", { direction: "up" }, 1000);
				};
			});
			
		var headerRow = $("<table cellspacing='0' width='100%'><tr> \
			<td class='rollupColumn'><span><span class='ui-icon ui-icon-triangle-1-s rollupColumn' /></span></td> \
			<td class='candidateColumn' width='100px'>" + candidate.name + "</td> \
			<td class='dataColumn' width='100px'>" + candidate.bcsId + "</td> \
			<td class='resultColumn'>" + candidate.status + "&nbsp;</td> \
			</tr></table>").appendTo(headerRow);			

		var content = $("<div />").addClass("contentRow").width("100%").appendTo(dialogbase);
		
		if (!candidate.accepted) {
			headerRow.css("color", "red");
			headerRow.find("span.ui-icon").css("background", "transparent");
		};
			
		if (candidate.qualification != '') {
			content.attr("avaliable", "true");
			
			$("<span />").addClass("rollupColumn").appendTo(content);
			$("<span />").addClass("titleColumn").html(ENROLLMENTS_VALUE).appendTo(content);
			$("<br />").appendTo(content);
			
			$("<span />").addClass("rollupColumn").appendTo(content);
			$("<span />").addClass("candidateColumn").html(candidate.qualification).appendTo(content);
			$("<span />").addClass("dataColumn").html(candidate.skillCardId).appendTo(content);
			$("<span />").addClass("resultColumn").html(candidate.enrolmentAccepted ? CONFIRMED_VALUE : REJECTED_VALUE).appendTo(content);
			$("<br />").appendTo(content);
			
			$("<span />").addClass("rollupColumn").appendTo(content);
			$("<span />").addClass("titleColumn").html(TEST_ALLOCATION_VALUE).appendTo(content);
			$("<br />").appendTo(content);
			
			if (candidate.enrolmentAccepted) {
				for (var allocationPosition = 0; allocationPosition < candidate.allocations.length; allocationPosition++)
				{
					var allocation = candidate.allocations[allocationPosition];
					
					$("<span />").addClass("rollupColumn").appendTo(content);
					$("<span />").addClass("candidateColumn").html(allocation.description).appendTo(content);
					$("<span />").addClass("dataColumn").html(allocation.moduleId).appendTo(content);
					var allocationStatus = $("<span />").addClass("resultColumn").html(getAllocationStatus(allocation.status)).appendTo(content);
					
					if (allocation.status != "Allocated") {
						allocationStatus.css("color", "Red");
					};
					
					$("<br />").appendTo(content);
				};
			} else {
				content.css("color", "red");
			};
		}
		else {
			content.attr("avaliable", "false");
		};
		
		var backgroundColor = (position % 2) ? "gridOddRow" : "gridEvenRow";
		
		headerRow.addClass(backgroundColor);
		content.addClass(backgroundColor);
		
		content.hide();
	};
	
	$("<div />")
		.html(DIALOG_NOTE_VALUE)
		.addClass("dialogNote")
		.appendTo(dialogbase);
	
	dialogbase.dialog({
		bgiframe: true,
		modal: true,
		height: 450,
		width: 600,
		autoResize: false,
		buttons: {
			"Cancel" : function() {
				$(this).dialog("close");
				$(this).dialog("destroy");
			}
		},
		open: function() {
			$(this).parent().find('.ui-dialog-buttonpane button:eq(0)').focus();
		}
	});
	
	dialogbase.parent().find(".ui-dialog-buttonpane > button").html(OK_VALUE).css("padding", "0.2em 1em");
	
	dialogbase.css("height", "350px");
	dialogbase.dialog('option', 'position', 'center');
};

function ShowPreviewClosureMessageDialog(certificationName, testTypeString, certificationId, testType, ok) {
   var dialog = $('<div width="100%" class="ui-dialog-message"></div>')
		.attr("title", PreviewClousreMessageDialogTitleFirstPart + ' "' + certificationName + '" ' + testTypeString)
		.appendTo($("body"));
			
	dialog.dialog({
		modal: true,
		minWidth: 650,
		minHeight: 170,
		width: 650,
		height: 170,
		buttons: {
			"Ok" : function() {
				$(this).dialog("close");
				$(this).dialog("destroy");
			}
		},
		open: function() {
		    var d = $(this);
		    
		    $.post('ClosureMessage.ashx?certificationid=' + certificationId+ '&testtype=' + testType , function(data){
		        d.parent().find('.ui-dialog-message').html(data);
		    });
			$(this).parent().find('.ui-dialog-buttonpane button:eq(0)').focus();
		}
	});
	
	dialog.parent().find(".ui-dialog-buttonpane > button").html(ok).css("padding", "0.2em 1em");
}
    
function ShowSetDetailsLevelDialog()
{
    var dialogBase = $('<div />').attr('title', SET_DETAILS_LEVEL_DIALOG_TITLE).appendTo($('form'));
    
    var layout = $('<table width="100%" cellpadding="0" cellspacing="0"><tbody><tr><td/></tr><tr><td/></tr><tr><td/></tr><tr><td/></tr></tbody></table>').appendTo(dialogBase);
    
    layout.find('td:eq(0)').html(LEVEL_OF_RESULT_DETAIL_COMBOBOX_TITLE);
    
    layout.find('tr:eq(0)').css('height', '20px');
    layout.find('tr:eq(1)').css('height', '20px');
    layout.find('tr:eq(2)').css('height', '20px');
    layout.find('tr:eq(3)').css('height', '358px');
    
    var comboBoxLevel = $('<select />').attr('id', 'DetailsLevelComboBox').attr('name', 'DetailsLevelComboBox').addClass('details-level-combobox').appendTo(layout.find('td:eq(1)'));
    
    var samplePictureBoxTitle = layout.find('td:eq(2)').html(SAMPLE_OF_RESULT_OF_DETAIL_TITLE);
    
    var samplePictureBox = $('<div />').addClass('details-level-sample-box').appendTo(layout.find('td:eq(3)'));
      
    var optionLevel0 = $('<option />').attr('value', 0).html(DETAIL_LEVEL_0).appendTo(comboBoxLevel);
    
    var optionLevel1 = $('<option />').attr('value', 1).html(DETAIL_LEVEL_1).appendTo(comboBoxLevel);
    
    var optionLevel2 = $('<option />').attr('value', 2).html(DETAIL_LEVEL_2).appendTo(comboBoxLevel);
    
    var optionLevel3 = $('<option />').attr('value', 3).html(DETAIL_LEVEL_3).appendTo(comboBoxLevel);
    
    var emptyOption = $('<option Selected="true" />').appendTo(comboBoxLevel);
    
    comboBoxLevel.click(function(){
        emptyOption.remove();
        $(dialogBase).parent().find('.ui-dialog-buttonpane button:eq(1)').removeAttr('disabled','disabled');
        $(dialogBase).parent().find('.ui-dialog-buttonpane button:eq(1)').removeClass('ui-state-disabled');
        comboBoxLevel.change();
    });
    
    comboBoxLevel.change(function(){
            var value = $(this).find('option:selected:eq(0)').attr('value');
            
            switch(value){
                case '0':
                    samplePictureBox
                        .removeClass('details-level-1-picture')
                        .removeClass('details-level-2-picture')
                        .removeClass('details-level-3-picture')
                        .addClass('details-level-0-picture');
                    break;
                case '1':
                    samplePictureBox
                        .removeClass('details-level-0-picture')
                        .removeClass('details-level-2-picture')
                        .removeClass('details-level-3-picture')
                        .addClass('details-level-1-picture');
                    break;
                case '2':
                    samplePictureBox
                        .removeClass('details-level-0-picture')
                        .removeClass('details-level-1-picture')
                        .removeClass('details-level-3-picture')
                        .addClass('details-level-2-picture');
                    break;
                case '3':
                    samplePictureBox
                        .removeClass('details-level-0-picture')
                        .removeClass('details-level-1-picture')
                        .removeClass('details-level-2-picture')
                        .addClass('details-level-3-picture');
                    break;
            }
        });
    
    dialogBase.dialog({
        modal: true,
        width: 275,
        resizable: false,
        buttons: {
            Cancel: function(){
                    $(this).dialog('close');
                    $(this).dialog('destroy');
                },
            Apply : function(){
                
                var detailLevel = comboBoxLevel.find('option:selected:eq(0)').attr('value');                
                               
                if(detailLevel != ''){

                    var certifications = GrabSelectedCertifications();
                    
                    if(certifications != '') {
                        
                        var form = $('form');
                    
                        AddFormValue(form, 'detaillevel', detailLevel);
                        
                        AddFormValue(form, 'certifications', certifications);
                        
                        var currentDate = new Date();
                        
                        AddFormValue(form, 'setdetailsleveldate', currentDate.toUTCString());
                                         
                        eval($('#' + ApplyDetailsLevelButtonEventHandlerId).val());
                    }
                    
                    $(this).dialog('close');
                    $(this).dialog('destroy');
                }
            }
        },
        open: function() {
			$(this).parent().find('.ui-dialog-buttonpane button:eq(0)').focus();
			$(this).parent().find('.ui-dialog-buttonpane button:eq(0)').html(SET_DETAIL_LEVEL_DIALOG_CANCEL_BUTTON);
			$(this).parent().find('.ui-dialog-buttonpane button:eq(1)').html(SET_DETAIL_LEVEL_DIALOG_APPLY_BUTTON);
		    $(this).parent().find('.ui-dialog-buttonpane button:eq(1)').attr('disabled','disabled');
            $(this).parent().find('.ui-dialog-buttonpane button:eq(1)').addClass('ui-state-disabled');
		}
    });
}

function AddFormValue(form, id, value){
    
    $("<input />")
         .attr("type", "hidden")
         .attr("enableviewstate", false)
         .attr("name", id)
		 .attr("id", id)
		 .attr("value", value)
		 .appendTo(form);			
}

function GrabSelectedCertifications() {
   
    var rows = $(".dev-grid-view span'[class*='Checked']:not(.select-all-test-result-settings)'").closest('tr');
    var certifications = '';
                    
    $(rows).each(function(){
        
        var certificationId = $(this).find('.certification-id').attr('value');
        
        var testType = $(this).find('.test-type').attr('value');
        
        certifications += certificationId + '|' + testType + ';';
    });
    
    return certifications;
}

function OnTestResultSettingsGridSelectionChanged() {

    if ($(".dev-grid-view span'[class*='Checked']").length > 0) {
        $('#' + SetDetailsLevelButtonId).enableButton();
        $('#' + SetClosureMessageButtonId).enableButton();
    }
    else {
        $('#' + SetDetailsLevelButtonId).disableButton();
        $('#' + SetClosureMessageButtonId).disableButton(); 
    }
}

function OnBeginCallBack(s, e){
}

function registerSetClosureMessageDialog(){
    $("#set-closure-message-dialog").dialog({
        title : SET_CLOSURE_MESSAGE_DIALOG_TITLE,
        autoOpen : false,
        minHeight: 321,
        minWidth : 660,
        width : 660,
        height: 321,
        resizable : false,
        modal : true,
        open : function(){
            $("#set-closure-message-dialog").css('visibility','visible');
            $("#set-closure-message-dialog").css('width','650');
            $("#set-closure-message-dialog").css('height','240');
            $(this).parent().find('.ui-dialog-buttonpane button:eq(0)').html(SET_CLOSURE_MESSAGE_DIALOG_CANCEL_BUTTON);
	   		$(this).parent().find('.ui-dialog-buttonpane button:eq(1)').html(SET_CLOSURE_MESSAGE_DIALOG_APPLY_BUTTON);
  //         ClosureMessageEditor.SetHtml('');
  //          ClosureMessageEditor.AdjustControl();
           ClosureMessageEditor.Focus();
        },
        buttons: {
            Cancel : function() {
                        $(this).dialog('close');
            },
            Apply : function() {
                        
                        var closureMessage = ClosureMessageEditor.GetHtml();
                        
                        if(closureMessage.length > 4000) {
                        
                            $('<div width="100%"></div>')
                            .html(SetClosureMessageErrorMessageBoxMessage)
                            .appendTo($("body")).dialog({
                                title: SetClosureMessageErrorMessageBoxTitle,
                                modal : true,
                                buttons: {
                                    OK: function(){
                                        $(this).dialog('close');
                                        $(this).dialog('destroy');
                                    }
                                },
                                open: function(){
                                    $(this).parent().find('.ui-dialog-buttonpane button').html(SetClosureMessageErrorMessageBoxButtonOk);
                                }
                            });
                        }
                        else{
                        
                            var certifications = GrabSelectedCertifications();
                            
                            if(certifications != ''){
                                
                                var form = $('form');
                            
                                AddFormValue(form, 'closuremessage', closureMessage);
                                AddFormValue(form, 'certifications', certifications);
                                
                                var currentDate = new Date();
                                
                                AddFormValue(form, 'setclosuremessagedate', currentDate.toUTCString());
                                
                                eval($('#' + ApplyClosureMessageButtonEventHandlerId).val());
                            
                            }
                            
                            $(this).dialog('close');
                            $(this).dialog('destroy');
                        }
                }
       }
   });
}

function ShowSetClosureMessageDialog() {
    $('#set-closure-message-dialog').dialog('open');
}

function UncheckAllCheckboxesInTestResultSettingsGrid() {
}

function InitTaskRatingSettingsTab(allowUndefinedState){
    $('.tristate').find('input').tristate({
            checkedchange: function(event, value){
        
                var label = $(this).parents('div.tristate').find('span');
                
                if(value === 'checked'){
                    label.text(TaskRatingOn);
                }
                else if(value === 'unchecked'){
                    label.text(TaskRatingOff);
                }
                else if(value === 'undefined'){
                    label.text(TaskRatingUseParentSettings);
                }
            },
            allowUndefinedState : allowUndefinedState
           });
}

function GrabSelectedModules() {

	var modules = "";

	if (SurveyPackageTreeId) {

		var moduleLinks = $("#" + SurveyPackageTreeId).find("ul").find("li.jstree-checked").find("[moduleId]");

		$(moduleLinks).each(function () {

			var packageLink = $(this).parents("li:first").parents("li:first").find("> a");

			var packageId = $(packageLink).attr("packageId");

			var moduleId = $(this).attr("moduleId");

			modules += packageId + "|" + moduleId + ";";
		});
	}

	return modules;
}

function GenerateSurveyReport() {
	var modules = GrabSelectedModules();

	if (modules != '') {

		var form = $('form');

		AddFormValue(form, 'surveySettingsReportModules', modules);
		
		var currentDate = new Date();

		AddFormValue(form, 'surveySettingsReportModulesCurrentDate', currentDate.toUTCString());
	}

	eval($("#" + GenerateButtonEventHandlerId).val());
}

function InitSurveyReportSettingsPage() {
	//"url": "../Content/Bsc/style.css",
	$("#" + SurveyPackageTreeId).jstree({ "plugins": ["themes", "html_data", "checkbox"], "themes": { "theme": "default", icons: false, dots: false} });
	$("#" + SurveyPackageTreeId).jstree("open_all");
	$("#" + SurveyPackageTreeId).jstree("check_all");

	ResizeSurveyReportSettingsPageDropDowns();

	$(window).resize(function () {
		ResizeSurveyReportSettingsPageDropDowns();
	});

}

function ResizeSurveyReportSettingsPageDropDowns() {
	var testCenter = $(".location-control-testcentre-dropdown");

	var testLab = $(".location-control-testlab-dropdown");

	var survey = $(".survey-control-survey-dropdown");

	resizeDropDowns(new Array(testCenter, testLab, survey));
}

function InitAdminListPage(candidatePasteConfirmation, candidateDeleteConfiramtion) {

	$('.button-paste').bind('click', function () { return confirm(candidatePasteConfirmation); });
	
	$('.button-delete').bind('click', function () { return confirm_deleteAll(candidateDeleteConfiramtion); });
}

function InitTaskRatingReportSettingsPage() {
	ResizeTaskRatingReportSettingsPageDropDowns();

	$(window).resize(function () {
		ResizeTaskRatingReportSettingsPageDropDowns();
	});
}

function ResizeTaskRatingReportSettingsPageDropDowns() {
	var testCenter = $(".location-control-testcentre-dropdown");

	var testLab = $(".location-control-testlab-dropdown");

	var programe = $(".programe-control-programme-dropdown");

	var exam = $(".programe-control-exam-dropdown");

	resizeDropDowns(new Array(testCenter, testLab, programe, exam));
}

function resizeDropDowns(droppdownsArray) {

	for (i = 0; i < droppdownsArray.length; i++) {
		$(droppdownsArray[i]).css("width", "auto");
	}
	
	droppdownsArray.sort(function (a, b) {
		return $(b).width() - $(a).width();
	});

	var i = 0;

	for (i = 0; i < droppdownsArray.length; i++) {

		var width = $(droppdownsArray[i]).parents("td:first").width();

		$(droppdownsArray[i]).css("width", width);	
	}
}

function InitCandidatesListPage() {

	$(".asp-grid-view-normal, .asp-grid-view-alt").dblclick(function () {
		eval($(this).find("a").attr("href"));
	});

	$(".actionButton").bind("click", function () {
		return runCandidateListAction(this);
	});

	$(".button-new-candidate").bind("click", function () {
		return true;
	});

	updateActionButton();
}

function InitTreeDefaults(treeInstance) {

	$.extend(true, $.jstree.defaults, {
		plugins: ["themes", "json_data", "ui", "types"],
		themes: {
			theme: "default",
			icons: false,
			dots: false
		},
		core: {
			animation: 0
		},
		json_data: {
			ajax: {
				url: "TreeViewHandler.ashx",
				data: function (n) {
					return {
						nodeid: n.attr ? n.attr("id") : -1,
						TreeViewAction: "GetSubnodes",
						TreeViewInstance: treeInstance
					};
				}
			},
			progressive_render: true
		},
		ui: {
			select_limit: 1,
			selected_parent_close: false
		}
	});
}

function SubscribeToCommonTreeEvents(treeViewInstance) {
	$("#treeView").bind("open_node.jstree close_node.jstree", function (event, data) {

		var target = data.args[0];

		var openedNodes = data.inst.get_container().find(".jstree-open");

		var stringOpenNodes = "";

		if (openedNodes.length > 0) {

			stringOpenNodes += "["

			$(openedNodes).each(function () {
				stringOpenNodes += $(this).attr("id") + ",";
			});

			stringOpenNodes = stringOpenNodes.substring(0, stringOpenNodes.length - 1);

			stringOpenNodes += "]";
		}

		$("#TreeViewOpenedNodeIds").val(stringOpenNodes);

		var targetType = typeof target;

		if (targetType !== "string") {

			$.post("TreeViewHandler.ashx", {
				TreeViewAction: "SaveOpenedNodes",
				TreeViewInstance: treeViewInstance,
				TreeViewOpenedNodeIds: stringOpenNodes
			});
		}
	});
}

function InitHomeTree(selectedNode, openedNodes, data) {
	InitTreeDefaults("Home");

	$("#treeView").jstree({
		"plugins": ["themes", "json_data", "ui"],
		"core": {
			initially_open: openedNodes
		},
		"ui": {
			"initially_select": [selectedNode]
		},
		json_data: {
			data : [data]
		}
	});

	$("#treeView").bind("select_node.jstree", function (event, data) {

		var target = data.args[0];

		if ($(target).is("a")) {

			var selectedNodeId = data.inst.get_selected().attr("id");

			$("#TreeViewSelectedNodeId").val(selectedNodeId);

			$.blockUI();

			__doPostBack('HomeTreeViewNodeSelected');

			return false;
		}
	});

	SubscribeToCommonTreeEvents("Home");
}

function InitCandidateMovementTree(selectedNode, openedNodes, data) {
	InitTreeDefaults("CandidateMovement");

	$("#treeView").jstree({
		"plugins": ["themes", "json_data", "ui", "types"],
		"core": {
			initially_open: openedNodes
		},
		"ui": {
			initially_select: [selectedNode]
		},
		json_data: {
			data : [data]
		},
		"types": {
			"types": {
				"default": {
					"hover_node": false,
					"select_node": false
				},
				"testlab": {
					"hover_node": true,
					"select_node": true
				}
			}
		}
	});

	$("#treeView").bind("select_node.jstree", function (event, data) {

		var target = data.args[0];

		if ($(target).is("a")) {

			var selectedNodeId = data.inst.get_selected().attr("id");

			$("#TreeViewSelectedNodeId").val(selectedNodeId);

			$.post("TreeViewHandler.ashx", {
				TreeViewInstance: "CandidateMovement",
				TreeViewAction: "SaveSelectedNode",
				TreeViewSelectedNodeId: selectedNodeId
			});
		}
	});

	SubscribeToCommonTreeEvents("CandidateMovement");
}

function InitExportResultsTree(selectedNode, openedNodes, data) {
	InitTreeDefaults("ExportResults");

	$("#treeView").jstree({
		"plugins": ["themes", "json_data", "ui", "types"],
		"core": {
			initially_open: openedNodes
		},
		"ui": {
			initially_select: [selectedNode]
		},
		json_data: {
			data : [data]
		}
	});

	$("#treeView").bind("select_node.jstree", function (event, data) {

		var target = data.args[0];

		if ($(target).is("a")) {

			var selectedNodeId = data.inst.get_selected().attr("id");

			$("#TreeViewSelectedNodeId").val(selectedNodeId);

			$.post("TreeViewHandler.ashx", {
				TreeViewAction: "SaveSelectedNode",
				TreeViewInstance: "ExportResults",
				TreeViewSelectedNodeId: selectedNodeId
			});
		}
	});

	SubscribeToCommonTreeEvents("ExportResults");
}

function InitDeleteNodePage(YesButtonEventHandlerId, YesButtonClientId) {
	$("#" + YesButtonClientId).click(function () {

		$.blockUI();

		eval($("#" + YesButtonEventHandlerId).value());

		return false;
	});
}
