/*
	Pt. trateazaBusinessException si afiseazaCustomMessage, variantele vechi
*/
function changeButtonLabel( buttonId, newLabel )
{
	document.getElementById( buttonId + '_table' ).title = newLabel;
	document.getElementById( buttonId + '_label' ).innerHTML = newLabel;
}

// Deschide o fereastra pentru afisarea erorilor
function openErrorPopup(messageKey)
{
	var wsw = window.screen.width;
	var wsh = window.screen.height;

	var	winW = wsw / 2.3;
	var	winH = wsh / 3;

	var winRef = open( '/ael/common-v2/messageErrorPopup.jsp?messageKey='+messageKey,
			'errorPopup',
			'scrollbars=1,resizable=1,width=' + winW + ',height=' + 250 +
			',left=' + ( wsw / 2 - winW/2 ) + ',top=200' );
}

// transmite mesajele de eroare ca parametri pt. messagePopup.jsp, afisata in dialog
function showErrorDialog( errorMessage, errorDetails )
{
	window.showModalDialog( "/ael/common-v2/messagePopup.jsp?errorClass=" + encodeURI( errorDetails.substr( 0, 1000 ) )
				+ "&errorMessage=" + encodeURI( errorMessage.substr( 0, 1000 ) ),
				'errorPopup',
				'dialogHeight:250px; edge:sunken; help:no; status:no; unadorned:yes' );
}

// transmite mesajul ca parametru pt. messagePopup.jsp, afisata in dialog
function showMsgDialog( messageTxt )
{
	//se afiseaza un mesaj
	window.showModalDialog( "/ael/common-v2/messagePopup.jsp?messageDiv=" + encodeURI( messageTxt.substr( 0, 1000 ) ),
		'errorPopup',
		'dialogHeight:250px; edge:sunken; help:no; status:no; unadorned:yes' );
}

/*
	Pt. trateazaBusinessException si afiseazaCustomMessage, variantele noi, cu mesajele pe sesiune
*/
// afiseaza messagePopupSes.jsp in dialog, aceasta urmind sa ia mesajele de eroare de pe sesiune
// parametrul withException : = true daca este apelata din trateazaBusinessException, altfel = false
function showErrorDialogSes( withException )
{
	window.showModalDialog( "/ael/common-v2/messagePopupSes.jsp?withException=" + withException,
				'errorPopup',
				'dialogWidth:700px; dialogHeight:300px; edge:sunken; help:no; status:no; unadorned:yes; resizable:yes' );
}
//

function trim_string( s )
{
	var ichar, icount;
	var strValue = s;
	ichar = strValue.length - 1;
	icount = -1;
	while ( ( strValue.charAt( ichar ) == ' ' || strValue.charCodeAt( ichar ) == 13 || strValue.charCodeAt( ichar ) == 10 ) && ichar > icount )
		--ichar;
	if ( ichar != ( strValue.length - 1 ) )
		strValue = strValue.slice( 0, ichar + 1 );
	ichar = 0;
	icount = strValue.length - 1;
	while ( ( strValue.charAt( ichar ) == ' ' || strValue.charCodeAt( ichar ) == 13 || strValue.charCodeAt( ichar ) == 10 ) && ichar < icount )
	++ichar;
	if ( ichar != 0 )
		strValue = strValue.slice( ichar, strValue.length );
	return strValue;
}

function isEmpty( theElement )
{
		s = theElement.value;
        if ( s == null || trim_string( s ) == "" || s.length == 0 )
            return true;
        return false;
}

function isValidName( folderName )
{	// Caractere interzise in numele directorului
	if ( folderName.indexOf('\\') != -1 ||
		 folderName.indexOf('/') != -1 ||
		 folderName.indexOf(':') != -1 ||
		 folderName.indexOf('*') != -1 ||
		 folderName.indexOf('?') != -1 ||
		 folderName.indexOf('"') != -1 ||
		 folderName.indexOf('<') != -1 ||
		 folderName.indexOf('>') != -1 ||
		 folderName.indexOf('|') != -1 )
	{
		return false;
	}
	else
		return true;
}

function isNotSelected( theElement )
{	s = theElement.selectedIndex;
	if( s == 0 || s == -1 )
		return true;
	return false;
}

//folosit pt. LOV-urile cu multiple selection
function isNotMultipleSelected( theElement )
{	s = theElement.selectedIndex;
	if( s == -1 )
		return true;
	return false;
}

var CNPDate = null;
var NDate = null;
var noValidate = false;
var currentDate = new Date();
var currentYear = currentDate.getFullYear();

function validareCNP( CNP, ziNastere, lunaNastere, anNastere )
{
	if( noValidate == true )
		return true;
	var errorMsg = "";
	var alertMsg = "";
	var errorFlag = false;
	var idx1 = -1;
	var idx2 = -1;
	if( testEmpty( CNP.value ) ){
		errorMsg += "  - CNP necompletat\n";
		if( idx1 == -1 ) idx1 = 5;
	}else{
		if( CNP.value.length < 13 ){
			errorMsg += "  - Lungimea CNP nu este de 13 caractere\n";
			if( idx1 == -1 ) idx1 = 5;
		}
		else if( !testNatural( CNP.value, false ) ){
			errorMsg += "  - CNP nu este un numar valid\n";
			if( idx1 == -1 ) idx1 = 5;
		}else{
			if( ( CNP.value.charAt( 0 ) != '1' ) && ( CNP.value.charAt( 0 ) != '2') &&
				( CNP.value.charAt( 0 ) != '3' ) && ( CNP.value.charAt( 0 ) != '4') &&
				( CNP.value.charAt( 0 ) != '7' ) && ( CNP.value.charAt( 0 ) != '8'))
			{
				alertMsg += "  - Prima cifra din CNP nu este una din valorile { 1, 2, 3, 4, 7, 8 } \n";
				if( idx2 == -1 ) idx2 = 5;
//			}else if( document.forms[ 0].elevCNP.value.charAt( 0 ) != ( document.forms[0].sex.selectedIndex + 1 ) ){
//				alertMsg += "  - Sexul candidatului diferit fata de CNP\n";
//				if( idx2 == -1 ) idx2 = 5;
			}
			var anCnp =  CNP.value.substring( 1,3 );
			/*pentru copii nascuti in 200...prima cifra (cea care indica sexul este 7 sau 8 )*/
			if(  CNP.value.charAt( 0 ) == '7' ||  CNP.value.charAt( 0 ) == '8' )
					anCnp = "20" + anCnp;
			else
					anCnp = "19" + anCnp;

			if( !testDate( CNP.value.substring( 5, 7 ),
					CNP.value.substring( 3, 5 ),
					anCnp ) ){
				alertMsg += "  - Data nasterii din CNP invalida\n";
				if( idx2 == -1 ) idx2 = 5;
			}else{
				CNPDate = new Date();
				CNPDate.setFullYear( anCnp );
				CNPDate.setDate( CNP.value.substring( 5, 7 ) );
				CNPDate.setMonth( CNP.value.substring( 3, 5 ) - 1 );
			}
		}
	}

	if( testEmpty( ziNastere.value ) || testEmpty( lunaNastere.value ) || testEmpty( anNastere.value ) )
	{
		alertMsg += "  - Data nasterii necompletata\n";
		if( idx1 == -1 ) idx1 = 10;
	}else if( !testDate0( ziNastere.value, lunaNastere.value - 1, anNastere.value ) )
	{
		errorMsg += "  - Data nasterii invalida\n";
		if( idx1 == -1 ) idx1 = 10;
//	}else if( ( currentYear - anNastere.value  < 1 ) ||
//		( currentYear - anNastere.value  > 50 ) ){
//			errorMsg += "  - Varsta nu este intre 1 si 150 ani\n";
//			if( idx1 == -1 ) idx1 = 12;
	}else if( CNPDate != null ){
		NDate = new Date();
		NDate.setFullYear( anNastere.value );
		NDate.setDate( ziNastere.value );
		NDate.setMonth( lunaNastere.value - 1 );
		//alert( NDate );
		if( ( NDate.getDate() != CNPDate.getDate() ) || ( NDate.getMonth() != CNPDate.getMonth() ) || ( NDate.getFullYear() != CNPDate.getFullYear() ) ){
			alertMsg += "  - Data nasterii diferita fata de CNP\n";
			if( idx2 == -1 ) idx2 = 10;
		}
	}

	// final : mesaje de eroare si avertizare
	if( errorMsg != "" ){
		alert( "Corectati urmatoarele erori:\n\n" + errorMsg );
//		event.returnValue = false;
		return false;
	//	document.forms[0].elements[ idx1 ].focus();
	}else if( alertMsg != "" )
		if( confirm( "Au fost depistate urmatoarele neconcordante:\n\n" + alertMsg + "\nDoriti sa continuati?" ) ){
//			document.forms[0].mai.disabled = false;
//			document.forms[0].mad.disabled = false;
			return true;
		}else{
		//	document.forms[0].elements[ idx2 ].focus();
//			event.returnValue = false;
			return false;
		}
	else{
//		document.forms[0].mai.disabled = false;
//		document.forms[0].mad.disabled = false;
		return true;
	}
}

function testDate( zi, luna, an )// luna in baza 1
{
	var DOMonth = new Array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
	var lDOMonth = new Array( 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
	var zz, ll, aaaa, mm;

	if( !testNatural( zi, false ) || !testNatural( luna, false ) || !testNatural( an, false ) )
		return false;
	if( ( zi.length == 2 ) && ( zi.charAt( 0 ) == '0') ) zi = zi.substr( 1 );
	if( ( luna.length == 2 ) && ( luna.charAt( 0 ) == '0') ) luna = luna.substr( 1 );

	zz = parseInt( zi, 10 );
	ll = parseInt( luna, 10 );
	aaaa = parseInt( an, 10 );
	if( ( aaaa % 4 ) == 0 ){
		if( ( aaaa % 100 ) == 0 && ( aaaa % 400 ) != 0 )
			nrZile = DOMonth[ ll - 1 ];
		else
			nrZile = lDOMonth[ ll - 1 ];
	}
	else
		nrZile = DOMonth[ ll - 1 ];
//	alert( zz + ":" + ll + ":" + aaaa + ":" + nrZile);

	if( ( zz < 0 ) || ( ll < 0 ) || ( aaaa < 0 ) || ( ll > 12) || ( zz > nrZile ) )
		return false;
	return true;
}

function testDate0( zi, luna, an ) // luna in baza 0
{
	var DOMonth = new Array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
	var lDOMonth = new Array( 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
	var zz, ll, aaaa, mm;

	if( !testNatural( zi, false ) || !testNatural( luna, false ) || !testNatural( an, false ) )
		return false;
	if( ( zi.length == 2 ) && ( zi.charAt( 0 ) == '0') ) zi = zi.substr( 1 );
	if( ( luna.length == 2 ) && ( luna.charAt( 0 ) == '0') ) luna = luna.substr( 1 );

	zz = parseInt( zi, 10 );
	ll = parseInt( luna, 10 ) + 1;
	aaaa = parseInt( an, 10 );
	if( ( aaaa % 4 ) == 0 ){
		if( ( aaaa % 100 ) == 0 && ( aaaa % 400 ) != 0 )
			nrZile = DOMonth[ ll - 1 ];
		else
			nrZile = lDOMonth[ ll - 1 ];
	}
	else
		nrZile = DOMonth[ ll - 1 ];
//	alert( zz + ":" + ll + ":" + aaaa + ":" + nrZile);

	if( ( zz < 0 ) || ( ll < 0 ) || ( aaaa < 0 ) || ( ll > 12) || ( zz > nrZile ) )
		return false;
	return true;
}

function testNatural( sir, spaces )
{
	var returnValue = true;
	if( sir.length == 0 ) returnValue = false;
	for( i = 0; i < sir.length; i++){
		if( ( sir.charAt( i ) == ' ' ) && ( spaces == false ) ){
			returnValue = false;
			break;
		}else if( ( sir.charAt( i ) != ' ' ) && ( ( sir.charAt( i ) < '0' ) || ( sir.charAt( i ) > '9' ) ) ){
			returnValue = false;
			break;
		}
	}
	return returnValue;
}

function testEmpty( sir )
{
	returnValue = true;
	for( i = 0; i < sir.length; i++ )
		if( sir.charAt( i ) != ' ' ){
			returnValue = false;
			break;
		}

	return returnValue;
}

function CNPOnBlur( CNP, ZiNastere, LunaNastere, AnNastere, anInceput )
{
//		document.forms[0].sex.selectedIndex = 0;
//	if( document.forms[0].CNP.value.charAt( 0 ) == '2')
//		document.forms[0].sex.selectedIndex = 1;
	if( CNP.value.length == 13 )
	{
		ZiNastere.value = CNP.value.substring( 5, 7 );
		LunaNastere.value = CNP.value.substring( 3, 5 );

		var an = parseFloat( "19" + CNP.value.substring( 1, 3 ) );
		if( parseInt( CNP.value.charAt( 0 ) ) >= 7 )
			an = parseFloat( "20" + CNP.value.substring( 1, 3 ) );
		AnNastere.value = an;
	}
}

function isGoodIEVersion()
{
	//return false;
	//var isOK = false;
	if( window.clientInformation.userAgent.indexOf( "MSIE " ) > 0 )
		if( window.clientInformation.appName == "Microsoft Internet Explorer" )
		{
			var version = window.clientInformation.appVersion;
			if( version.indexOf( "5.5" ) > 0 )
			{
				//return version;
				return true;
			}
			if( version.indexOf( "6.0" ) > 0 )
			{
				//return version;
				return true;
			}
		}
	return false;
}

function isPositiveIntegerNumber( theElementValue )		// daca e intreg > 0 -> true
{
	if( typeof theElementValue == "undefined" )
		return false;
	else if( isNaN( Math.abs( theElementValue ) ) )
		return false;
	else
	{
		if( Math.round( theElementValue ) - theElementValue != 0 )
			return false;
		else if( theElementValue <= 0 )
			return false;
	}
	return true;
}

function isPositiveIntegerNumberZ( theElementValue )	// daca e intreg >= 0 -> true
{
	if( typeof theElementValue == "undefined" )
		return false;
	else if( isNaN( Math.abs( theElementValue ) ) )
		return false;
	else
	{
		if( Math.round( theElementValue ) - theElementValue != 0 )
			return false;
		else if( theElementValue < 0 )
			return false;
	}
	return true;
}

function trim( s )
{
	while( s.substring(0, 1) == ' ' )
	{
		s = s.substring(1, s.length);
	}
	while( s.substring(s.length - 1, s.length) == ' ' )
	{
		s = s.substring(0, s.length - 1);
	}

	return s;
}

// Process all transfers between the select objects
/*
*@param noMaxim = nu se va permite depasirea a noMaxim valori
*@errorMsg  = mesajul de eroare in cazul depasirii
*/
function transferSelectSelect( sourceList, destinationList, noMaxim, errorMsg )
{
	var destinationIndex = destinationList.selectedIndex;
	if( destinationIndex < 0 )
		destinationIndex = 0;

	for( var i = 0; i < sourceList.length; i++ )
	{
		var child = sourceList.options[ i ];
		if( child.selected == true )
		{
			/*daca sunt noMaxim inregistrari in destinatie, aruncam eroare si iesim din for*/
			if( noMaxim != undefined && destinationList.length == noMaxim )
			{
				alert( errorMsg );
				break;
			}
			sourceList.removeChild( child );
			i--;
			destinationList.options[ destinationList.length ] = new Option( child.text, child.value );
		}
	}
}

//Transfera o valoare dintr-un input intr-un select; daca valoarea exista se da un mesaj de eroare
function transferInputSelect( sourceInput, destinationList, errorMessage, noMaxim, errorMsg )
{
	var valueNoSpaces = trim( sourceInput.value );
	if(  valueNoSpaces == '' )
		return;

	if( noMaxim != undefined && destinationList.length >= noMaxim )
	{
		alert( errorMsg );
		return;
	}


	found = false;
	//Cautam in lista daca mai exista acelasi text deja introdus
	for( var i = 0; i < destinationList.length; i++ )
	{
		if( valueNoSpaces == destinationList.options[ i ].text )
		{
			found = true
		}
	}
	if( found )
	{
		alert( errorMessage );
	}
	else
	{
		destinationList.options[ destinationList.length ] = new Option( valueNoSpaces, valueNoSpaces );
		sourceInput.value = '';
	}

	sourceInput.focus();
}

//Transfera o valoare dintr-un select intr-un input
function transferSelectInput( sourceList, destinationInput )
{
	for( var i = 0; i < sourceList.length; i++ )
	{
		var child = sourceList.options[ i ];
		if( child.selected == true )
		{
			sourceList.removeChild( child );
			i--;
			destinationInput.value = child.text;
		}
	}
}

function getXmlHttpRequest()
{
	var request = false;
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	// JScript gives us Conditional compilation, we can cope with old IE versions.
	// and security blocked creation of the objects.
	try {
		request = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			request = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E)	{
			request = false;
		}
	}
	@end @*/
	if( !request && ( typeof( XMLHttpRequest ) != "undefined" ) )
	{
		request = new XMLHttpRequest();
	}

	return request;
}
/**
** pune focus pe elementul cu id-ul 'idElement'
*@param idElement  id-ul elementului pe care dorim sa facem focus
*/
function setFocusToElement( idElement )
{
	var ref= document.getElementById( idElement );
	if( ref != undefined && ref.disabled != true )
		ref.focus();
}

function onMouseOver( object )
{
	object.style.backgroundColor= eval ('customBgColor');
	object.style.borderWidth='1px';
	object.style.borderStyle='solid';
	object.style.borderColor='#909090';
}
function onMouseOut( object )
{
	object.style.backgroundColor='#FFFFFF';
	object.style.borderWidth='1px';
	object.style.borderStyle='solid';
	object.style.borderColor='white';
}
function goBackTo( url )
{
	location.href = url;
}

var screenCover;
var messageDiv;
var callbackCode;
var defaultMessageTitle;
var defaultCloseLabel;
var defaultCloseTitle;
var messageDomCreated;
var runCalbackOnlyOnce = true;

function initDivs()
{
	screenCover = document.getElementById("screenCover");
	messageDiv = document.getElementById("messageDiv");
	defaultMessageTitle = document.getElementById("msgTitle").innerHTML;
	defaultCloseLabel = document.getElementById("msgCloseButton_label").innerHTML;
	defaultCloseTitle = document.getElementById("msgCloseButton_table").title;
}

function createMessage( messageHtml, titleHtml, callbackCodeToRun, closeLabelHtml )
{
	if( screenCover == undefined || messageDiv == undefined )
		initDivs();
	document.getElementById("msgBody").innerHTML = messageHtml;
	if( titleHtml == undefined || titleHtml == null )
		document.getElementById("msgTitle").innerHTML = defaultMessageTitle;
	else
		document.getElementById("msgTitle").innerHTML = titleHtml;
	if( closeLabelHtml == undefined || closeLabelHtml == null )
	{
		document.getElementById("msgCloseButton_span").innerHTML = defaultCloseLabel;
		document.getElementById("msgCloseButton_table").title = defaultCloseTitle;
	}
	else
	{
		document.getElementById("msgCloseButton_span").innerHTML = closeLabelHtml;
		document.getElementById("msgCloseButton_table").title = closeLabelHtml;
	}
	callbackCode = callbackCodeToRun;
}

function createMessage2( messageId, titleText, callbackCodeToRun, closeLabelText )
{
	if( screenCover == undefined || messageDiv == undefined )
		initDivs();

	var messageContentContainer = $(document.getElementById("msgBody"));
	messageContentContainer.update('');
	var messageContent = document.getElementById(messageId);
	messageContentContainer.appendChild( messageContent );
	messageDomCreated = messageContent;
	messageContent.style.display = "block";

	if( titleText == undefined || titleText == null )
		document.getElementById("msgTitle").innerHTML = titleText;
	else
		document.getElementById("msgTitle").innerHTML = titleText;

	if( closeLabelText == undefined || closeLabelText == null )
	{
		document.getElementById("msgCloseButton_span").innerHTML = defaultCloseLabel;
		document.getElementById("msgCloseButton_table").title = defaultCloseTitle;
	}
	else
	{
		document.getElementById("msgCloseButton_span").innerHTML = closeLabelText;
		document.getElementById("msgCloseButton_table").title = closeLabelText;
	}
	callbackCode = callbackCodeToRun;
}

function displayMessage()
{
	screenCover.style.display = "block";
	messageDiv.style.display = "block";
}

function showMessage2( messageId, titleText, callbackCodeToRun, closeLabelText, runCalbackOnlyOnce_param )
{
	runCalbackOnlyOnce = runCalbackOnlyOnce_param;
	if( !messageDomCreated )
	{
		createMessage2(messageId, titleText, callbackCodeToRun, closeLabelText);
	}
	displayMessage();
}

function showMessage( messageHtml, titleHtml, callbackCodeToRun, closeLabelHtml )
{
	createMessage(messageHtml, titleHtml, callbackCodeToRun, closeLabelHtml);
	displayMessage();
}

function hideMessage()
{
	if( screenCover == undefined || messageDiv == undefined )
		initDivs();
	if( callbackCode != undefined && callbackCode != null )
	{
		try
		{
			eval(callbackCode);
		}
		catch( e )
		{ log("Error in hideMessage callback code: " + e + " - " + e.description); }
	}
	screenCover.style.display = "none";
	messageDiv.style.display = "none";
	if( runCalbackOnlyOnce )
	{
		callbackCode = undefined;
	}
}

document.onkeydown = function anonymous( event )
{
	var pressedKeyCode;
	if( window.event )
		pressedKeyCode = window.event.keyCode;
	else
		pressedKeyCode = event.keyCode;
	if( pressedKeyCode == 27 )
	{
		hideMessage();
	}
	if( document.libraryOnkeydown )
		libraryOnkeydown();
}

//functie care imi limiteaza numarul de caractere care se vor introduce intr-un textarea
function textCounter( field, maxlimit, messageAlert )
{
	if (field.value.length > maxlimit) // if too long...trim it!
		{
			alert( messageAlert + " (" + maxlimit+ ")" ); //afisez un mesaj de eroare
			field.value = field.value.substring(0, maxlimit);
		}
}

//functie care imi limiteaza numarul de caractere care se vor introduce intr-un textarea (dintr-un div)
function textCounterDiv( field, maxlimit, messageAlert )
{
	if (field.innerHTML.length > maxlimit) // if too long...trim it!
	{
		alert( messageAlert + " (" + maxlimit+ ")" ); //afisez un mesaj de eroare
		field.innerHTML = field.innerHTML.substring(0, maxlimit);
	}
}
