﻿function CheckSCIDandPasswordFilling(textBoxSCID, textBoxPassword, buttonID)
{
	var textBoxSCIDText = document.getElementById(textBoxSCID.id).value;
	var textBoxPasswordText = document.getElementById(textBoxPassword.id).value;
	if ((textBoxSCIDText == "") || (textBoxPasswordText == ""))
		$("#" + buttonID.id).disableButton();
	else
		$("#" + buttonID.id).enableButton();
};

function getByIdentifier(id) {
	return $("#" + id);
}

function SetButtonState(removeExpiredCertificationButtonID, convertSkillCardButtonID, txtBoxCertifID, textBoxStatusID) {

	var certificationStatusText = getByIdentifier(textBoxStatusID).val();;
	var certificationNameText = getByIdentifier(txtBoxCertifID).val();
	var removeExpiredButton = getByIdentifier(removeExpiredCertificationButtonID);
	var convertSkillCardButton = getByIdentifier(convertSkillCardButtonID);
	
	if (removeExpiredButton.length > 0) {
		if (certificationStatusText == CERTIFICATION_EXPIRED_STRING) {
			removeExpiredButton.removeAttr("disabled");
		}
		else {
			removeExpiredButton.attr("disabled", "disabled");
		}
	}
	
	if (convertSkillCardButton.length > 0) {
	
		if (certificationStatusText == CERTIFICATION_COMPLETED_STRING) {
			convertSkillCardButton.attr("disabled", "disabled");
			
			for (var i = 0; i < COMPLETED_CERTIFICATIONS_CAN_CONVERTED.length; i++) {
				if (COMPLETED_CERTIFICATIONS_CAN_CONVERTED[i] == certificationNameText) {
					convertSkillCardButton.removeAttr("disabled");
				}
			}
		}
		else {
			convertSkillCardButton.attr("disabled", "disabled");
			
			for (var i = 0; i < CERTIFICATIONS_CAN_CONVERTED.length; i++) {
				if (CERTIFICATIONS_CAN_CONVERTED[i] == certificationNameText) {
					convertSkillCardButton.removeAttr("disabled");
				}
			}
		}
	}
};

function UpdateLayout(objectSender, buttonID, nonIncludeID, criteria, invert, buttonID2, criteria2)
{
	var elementsList = document.getElementsByTagName("input");

	var countOfCheckedElements = 0;
	
	for (var count = 0; count < elementsList.length; count++) {
		if ((elementsList[count].type == "checkbox") && (elementsList[count].id != nonIncludeID.id)) {
			if (elementsList[count].checked) {
				countOfCheckedElements++;
			}
		}	
	}
	
	if (invert == true)
	{
		if (countOfCheckedElements > criteria)
			$("#" + buttonID.id).enableButton();
		else
			$("#" + buttonID.id).disableButton();
	}
	else
	{
		if ((countOfCheckedElements > criteria) || (countOfCheckedElements == 0))
			$("#" + buttonID.id).disableButton();
		else
			$("#" + buttonID.id).enableButton();
	}
	
	if ( typeof(buttonID2) != 'undefined' )
	{
		if (countOfCheckedElements > criteria2)
			$("#" + buttonID2.id).enableButton();
		else
			$("#" + buttonID2.id).disableButton();
	}
	
}

function confirm_delete ( confirmation, name ) {
	if ( name == 'undefined' )
		var str = confirmation;
	else
		var str = confirmation + name +" ?";

	return confirm ( str );
};

function confirm_deleteAll ( confirmation ) {
	return confirm( confirmation );
};

function ShowImportDetails ( txt ) {
	alert(txt);
};

function doSomething() { 
	alert("Enter Notes");
};

function setEnterKey ( btnName ) {
	if ( event.keyCode == 13 ) {
		event.cancelBubble = true;
		event.returnValue = false;
		document.getElementById( btnName ).click();
	}
};

function ForbidChars()
{
    if ((event.keyCode == 47)       // /
        || (event.keyCode == 92)    // \       
        || (event.keyCode == 124)   // |
        || (event.keyCode == 34)    // "
        || (event.keyCode == 63)    // ?
        || (event.keyCode == 42)    // *
        || (event.keyCode == 60)    // <
        || (event.keyCode == 62)    // >
        || (event.keyCode == 58))   // :
    {
        event.cancelBubble = true;
	    event.returnValue = false;
    }
};


function increment ( textboxID, span ) {
	var textbox = $("#" + textboxID);

	if (parseInt( textbox.val() ) < parseInt( textbox.attr("maxValue"))) {
		textbox.val(parseInt(textbox.val()) + span);
	}
};

function decrement ( textboxID, span ) {
	var textbox = $("#" + textboxID);

	if (parseInt(textbox.val()) > parseInt( textbox.attr("minValue"))) {
		textbox.val(parseInt(textbox.val()) - span);
	}
};

/****************************************
*	DOM methods							*
****************************************/

//Get a style property (name) of a specific element (element)
function getStyle( element, name ) {
	//If property exists in style[], then it's been set recently (and is current)
	if ( element.style[ name ] )
		return element.style[ name ];
		
	//Otherwise, try to use IE's method
	else if ( element.currentStyle )
		return element.currentStyle[ name ];
		
	//Or the W3C's method, if it exists
	else if ( document.defaultView && document.defaultView.getComputedStyle ) {
		name = name.replace(/([A-Z])/g,"-$1");
		name = name.toLowerCase();
		
		var s = document.defaultView.getComputedStyle( element, "" );
		return s && s.getPropertyValue( name );
	}
	
	//Otherwise, we're using some other browser
	else
		return null;
};

//Find the X (Horizontal, Left) position of an element
function pageX( element ) {
	//See if we're at the root element, or not
	return element.offsetParent ?
		//If we can still go up, add the current offset and recurse upwards
		element.offsetLeft + pageX( element.offsetParent ) :
		
		//Otherwise, just get current offset
		element.offsetLeft;
};

//Find the Y (Vertical, Top) position of an element
function pageY( element ) {
	//See if we're at the root element, or not
	return element.offsetParent ?
		//if we can still go up, add the current offset and recurse upwards
		element.offsetTop + pageY( element.offsetParent ) :
		//Otherwise, just get the current offset
		element.offsetTop;
};

//Find the left position of an element
function posX( element ) {
	//Get the computed style and get the number out of value
	return parseInt( getStyle( element, "left" ) );
};

//Find the top position of an element
function posY ( element ) {
	//Get the computed style and get the number out of value
	return parseInt( getStyle( element, "top" ) );
};

//A function for setting the horizontal position of an element
function setX( element, position ) {
	//Set the 'left' CSS property, using pixel units
	element.style.left = position + "px";
};

//A function for setting the vertical position of an element
function setY( element, position ) {
	//Set the 'top' CSS property, using pixel units
	element.style.top = position + "px";
};

//Disable text selection for target
function disableSelection( target ) {
	//If IE
	if ( typeof target.onselectstart != "undefined" )
		target.onselectstart = function() { return false; };
	//if Firefox
	else if (typeof target.style.MozUserSelect != "undefined" )
		target.style.MozUserSelect = "none";
	//if Opera
	else
		target.onmousedown = function() { return false; };
		
	target.style.cursor = "default"
}

function createTable () {
	var table = document.createElement("table");	
	return table;
};

function createCell ( className, innerText, collSpan ) {

	var tableCell = document.createElement("td");
	tableCell.className = className;
	tableCell.innerText = innerText;
	
	if ( collSpan != null )
		tableCell.colSpan = collSpan;
	
	return tableCell
};


/*************************************************************
*	Method using by Ajax Tree (Default, Candidatemovement)   *
*************************************************************/
function getElementsByClassName(oElm, strTagName, strClassName) {
	var arrElements = (strTagName == "*" && oElm.all)?  oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for( var i = 0; i < arrElements.length; i++ ) {
		oElement = arrElements[i];
		if (oRegExp.test(oElement.className)) {
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
};

function checkChild( obj ) {
	if (obj != null)
		if (obj.hasChildNodes != null)
			return true;
	
	return false;
};

function createDOMElementTextNode( caption ) {
	var DOMElement = document.createTextNode( caption );
	return DOMElement;
};

function createDOMElementTable() {
	var DOMElement = document.createElement( 'table' );
    DOMElement.border = '0';
    DOMElement.cellPadding = '0';
    DOMElement.cellSpacing = '2';
    DOMElement.width = '100%';
    return DOMElement;
};

function createDOMElement( element, cssClass, eventParams, elementID ) {
	var DOMElement = document.createElement(element);
	
	if ( cssClass != null )
		DOMElement.className = cssClass;
		
	if ( eventParams != null )
		DOMElement.onclick = function() {doPostBack(eventParams);}
		
	if ( elementID != null )
		DOMElement.setAttribute( 'id', elementID );
		
	return DOMElement;
};

function getChildAttribute( object, child, attribute ) {
	return object.childNodes[child].getAttribute(attribute);
};

function getChildNodesLength( object ) {
	if ( object.hasChild() ) {
		return object.childNodes.length;
	}
	return 0;
};

function getNodeDivForReFormat( nodeObject ) {
	return nodeObject.parentNode.parentNode.lastChild.lastChild;
};

function getNodeImageDivForReFormat( nodeObject ) {
	return nodeObject.parentNode.parentNode.firstChild.firstChild;	
};

function getParentNodeForToggle( nodeObject ) {
	return nodeObject.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
};

function getNodeDivForToggle( nodeObject ) {
	return nodeObject.parentNode;
};

function getChildNodeForToggle( nodeObject ) {
	return nodeObject.parentNode.parentNode.parentNode.lastChild.lastChild;
};

function runCandidateListAction(actionButton) {

	var actions = $(actionButton).prev();
	
	switch (actions.val()) {
		case "None":
			return false;
		
		case "Delete":
			return confirm_deleteAll(confirmationDeleteCandidates);
		
		case "Paste":
			return confirm(confirmationMoveCandidate);
			
		case "Update3FCandidate":
			if ($(".hierarhyLeftPanel input[id$=CheckBoxAddTime]:checked").length > 15) {
				return showConfirmationDialog(UPDATE_MULTIPLE_TITLE_STRING, UPDATE_MULTIPLE_STRING, NO_STRING, YES_STRING, UpdateBCSCandidateEventReferenceClientID);
			}
			
			return;
	};

	return true;
};

function updateActionButton() {
	actionButton = $(".actionButton:first");
	actionButtonBottom = $(".actionButton:last");

	switch($("select.actionsDropDown").val()) {
		case "None":
			enableControl(actionButton, false);
			enableControl(actionButtonBottom, false);
			break;
		
		case "Export":
			enableControl(actionButton, (getSelectedUsers() > 0 && isTrue(actionButton.attr("allowExport"))));
			enableControl(actionButtonBottom, (getSelectedUsers() > 0 && isTrue(actionButton.attr("allowExport"))));
			break;
			
		case "Import":
			enableControl(actionButton, isTrue(actionButton.attr("allowImport")));
			enableControl(actionButtonBottom, isTrue(actionButton.attr("allowImport")));
			break;
			
		case "Delete":
			enableControl(actionButton, (getSelectedUsers() > 0 && isTrue(actionButton.attr("allowDelete"))));
			enableControl(actionButtonBottom, (getSelectedUsers() > 0 && isTrue(actionButton.attr("allowDelete"))));
			break;
			
		case "Cut":
			enableControl(actionButton, (getSelectedUsers() > 0 && isTrue(actionButton.attr("allowMove"))));
			enableControl(actionButtonBottom, (getSelectedUsers() > 0 && isTrue(actionButton.attr("allowMove"))));
			break;
			
		case "Paste":
			enableControl(actionButton, isTrue(actionButton.attr("allowPaste")));
			enableControl(actionButtonBottom, isTrue(actionButton.attr("allowPaste")));
			break;
			
		case "SetTimeRange":
			enableControl(actionButton, (getSelectedUsers() > 0 && isTrue(actionButton.attr("allowSetTimeRange"))));
			enableControl(actionButtonBottom, (getSelectedUsers() > 0 && isTrue(actionButton.attr("allowSetTimeRange"))));
			break;
			
		case "TestAllocation":
			enableControl(actionButton, (getSelectedUsers() > 0 && isTrue(actionButton.attr("allowTestAllocation"))));
			enableControl(actionButtonBottom, (getSelectedUsers() > 0 && isTrue(actionButton.attr("allowTestAllocation"))));
			break;
			
		case "TestAppeal":
			enableControl(actionButton, (getSelectedUsers() == 1 && isTrue(actionButton.attr("allowTestAppeal"))));
			enableControl(actionButtonBottom, (getSelectedUsers() == 1 && isTrue(actionButton.attr("allowTestAppeal"))));
			break;
			
		case "Get3FCandidates":
			enableControl(actionButton, isTrue(actionButton.attr("allowGet3FCandidates")));
			enableControl(actionButtonBottom, isTrue(actionButton.attr("allowGet3FCandidates")));
			break;
			
		case "Update3FCandidate":
			enableControl(actionButton, getSelectedUsers() >= 1 && isTrue(actionButton.attr("allowUpdate3FCandidates")));
			enableControl(actionButtonBottom, getSelectedUsers() >= 1 && isTrue(actionButton.attr("allowUpdate3FCandidates")));
			break;
	};
};

function isTrue(value) {
	return (value.toLowerCase() == "true");
};

function getSelectedUsers() {
	return ($(".asp-grid-view-normal, .asp-grid-view-alt").find(":checkbox:checked").length);
};

function enableControl(control, enable) {
	if (enable) {
		$(control).enableButton();
	}
	else {
		$(control).disableButton();
	};
};

function onChangeQualificationTypeDropDown(element) {
	var packagesTable = $(element).parents(".get3FCandidate").find(".packages");
	var validators = packagesTable.find("tr > td > span[id*=validatorSelectPackage]");
	
	if ($(element).val() == "-1" || $(element).val() == "NONE") {
		packagesTable.parent().hide();
		validators.each(function() { $(this).attr("validationGroup", "0"); });
	}
	
	Page_IsValid = true;
	Page_BlockSubmit = false;
};

function showConfirmationDialog(title, content, no, yes, postpack) {
	var confirmation = $("<div />")
		.attr("title", title)
		.html(content)
		.appendTo($("body"));
	
	confirmation.dialog({
		bgiframe: true,
		modal: true,
		width: 430,
		buttons: {
			"Cancel" : function() {
				$(this).dialog("close");
				$(this).dialog("destroy");	
			},
			"Ok" : function() {
				$(this).dialog("close");
				$(this).dialog("destroy");
				eval($("#" + postpack).val());
			}
		},
		open: function() {
			$(this).parents('.ui-dialog-buttonpane button:eq(1)').focus();
		},
		close: function() {
			$(this).dialog("destroy");
		}
	});
	
	confirmation.parent().find(".ui-dialog-buttonpane button:eq(0)").html(no);
	confirmation.parent().find(".ui-dialog-buttonpane button:eq(1)").html(yes);
	
	return false;
}

function getBCS3FCandidate(element) {

	var packagesTable = $(element).parents(".get3FCandidate").find(".packages");
		
	if (!packagesTable.is(":visible"))
	{
		eval($("#" + GetBCSCandidateEventReferenceClientID).val());
		return;
	}
		
	if (packagesTable.find(":selected").val() == -1)
	{
		eval($("#" + GetBCSCandidateEventReferenceClientID).val());
		return;
	}
		
	var confirmation = $("<div />")
		.attr("title", TEST_ALLOCATION_TITLE_STRING)
		.html(TEST_ALLOCATION_CONFIRMATION_STRING)
		.appendTo($("body"));
	
	confirmation.dialog({
		bgiframe: true,
		modal: true,
		width: 430,
		buttons: {
			"Cancel" : function() {
				$(this).dialog("close");
				$(this).dialog("destroy");	
			},
			"Ok" : function() {
				$(this).dialog("close");
				$(this).dialog("destroy");
				eval($("#" + GetBCSCandidateEventReferenceClientID).val());
			}
		},
		open: function() {
			$(this).parents('.ui-dialog-buttonpane button:eq(1)').focus();
		}
	});
	
	confirmation.parent().find(".ui-dialog-buttonpane button:eq(0)").html(NO_STRING);
	confirmation.parent().find(".ui-dialog-buttonpane button:eq(1)").html(YES_STRING);
};

/*************************************************************
*	Session timeout countdown                                *
*************************************************************/
function onLoad_SessionExpiredConfirmation() {
	var sessionTimeout = sessionExpirationTimeout;
	var countdown = sessionExpirationCountdown;
	var confirmationTimeout = sessionExpirationTimeout - sessionExpirationCountdown;

	timeId = setTimeout("showSessionExpiredConfirmation(" + sessionExpirationCountdown + ");", confirmationTimeout);
}

function showSessionExpiredConfirmation(countdown) {
	// create div, dialog based on
	$("<div id='sessionTimeoutConfirmation' />")
		.attr({
			title: SESSION_EXPIRATION_DIALOG_TITLE
			})
		.append(SESSION_EXPIRATION_DIALOG_MESSAGE10)
		.append("<div id='divCountdown' style='display:inline;' />")
		.append(SESSION_EXPIRATION_DIALOG_MESSAGE11)
		.append(SESSION_EXPIRATION_DIALOG_CONTINUE_BUTTON)
		.append(SESSION_EXPIRATION_DIALOG_MESSAGE12)
		.appendTo("body");
	// create dialog
	var buttons = {}; // workaround for button label from variable
	buttons[SESSION_EXPIRATION_DIALOG_CONTINUE_BUTTON] = onSessionExpiredButtonContinue;
	$("#sessionTimeoutConfirmation")
		.dialog({ 
			bgiframe: true,
			autoOpen: false,
			closeOnEscape: false,
			modal: true,
			width: 400,
			buttons: buttons,
			open: function()  { onSessionExpiredConfirmationOpened(countdown); },
			close: function() { onSessionExpiredConfirmationClosed(); }
		})
		.dialog("open");
	// setup first tick
	setTimeout("updateSessionExpiredConfirmation(" + countdown + ");", 1000);
}

function onSessionExpiredConfirmationOpened(countdown) {
	// remove Close icon in Titlebar
	$("#sessionTimeoutConfirmation").parents(".ui-dialog:first").find(".ui-dialog-titlebar-close").remove();
	// set initial value for countdown
	$("#divCountdown").text( convertMilliseconds(countdown) );
}

function onSessionExpiredConfirmationClosed() {
	// destroy dialog and remove div
	$("#sessionTimeoutConfirmation").dialog("destroy").remove();
}

function updateSessionExpiredConfirmation(countdown) {
	if ($("#sessionTimeoutConfirmation").size() > 0) {
		// decrement for 1 sec
		countdown -= 1000;
		
		if (countdown <= 0) {
			// workaround to button label from variable
			var buttons = {}; 
			buttons[SESSION_EXPIRATION_DIALOG_GOTO_BUTTON] = onSessionExpiredButtonGoto;
			// change message and button
			$("#sessionTimeoutConfirmation")
				.empty()
				.append(SESSION_EXPIRATION_DIALOG_MESSAGE20)
				.append(SESSION_EXPIRATION_DIALOG_GOTO_BUTTON)
				.append(SESSION_EXPIRATION_DIALOG_MESSAGE21)
				.dialog("option", "buttons", buttons);
		}
		else {
			// update countdown value
			$("#divCountdown").text( convertMilliseconds(countdown) );
			// setup next tick
			setTimeout("updateSessionExpiredConfirmation(" + countdown + ");", 1000);
		}
	}
}

function onSessionExpiredButtonContinue() {
	$(this).dialog("close");
	// request page to restore session
	$.get("SessionAlive.ashx");
	// initialize
	onLoad_SessionExpiredConfirmation();
}

function onSessionExpiredButtonGoto() {
	$(this).dialog("close");
	// reload - code behind jumps to root, as session is expired
	try {
		window.location = "Default.aspx";
	} catch(e) {
		// exception if user pressed cancel button
	}
}

function convertMilliseconds(ms) {
	var minutes = parseInt("" + ms / 1000 / 60);
	var seconds = parseInt("" + ms / 1000 - minutes * 60);
	if (seconds < 10)
		seconds = "0" + seconds;
	return minutes + ":" + seconds;
}

function beforeAjaxRequest(sender, args) {
	var get3FCandidateButton = $("input.[id$=getBCSCandidate]");
	
	if (get3FCandidateButton.length > 0) {
		get3FCandidateButton.attr("disabled", "disabled");
	}
}

function afterAjaxRequest(sender, args) {
	var get3FCandidateButton = $("input.[id$=getBCSCandidate]");
	
	if (get3FCandidateButton.length > 0)
	{
		get3FCandidateButton.removeAttr("disabled");
	}
	
	var select = $(".get3FCandidate").find("select[id$=qualificationType]");

	if (select.val() != "-1" && select.val() != "NONE") {
		var packagesTable = $(".get3FCandidate").find("table.packages");
		var validators = packagesTable.find("tr > td > span[id*=validatorSelectPackage]");
		packagesTable.parent().show();
		validators.each(function() { $(this).attr("validationGroup", "9"); });
	}
}

function InitLoginPage() {
	$(document).ready(function () {
		var currentDateTime = new Date();
		$("#ClientTimeZoneOffset").val(-currentDateTime.getTimezoneOffset());
	});
}
