﻿function addTitle(myJobTitle,myManagerialLevelId,myFieldId,mySubFieldId,myExperienceId)
{
	jobTitle[jobTitle.length] = new Array();
	jobTitle[jobTitle.length - 1][idxJT_id] = "-1";
	jobTitle[jobTitle.length - 1][idxJT_text] = myJobTitle;
	jobTitle[jobTitle.length - 1][idxJT_experience] = myExperienceId;
	jobTitle[jobTitle.length - 1][idxJT_field] = myFieldId;
	jobTitle[jobTitle.length - 1][idxJT_subfield] = mySubFieldId;
	jobTitle[jobTitle.length - 1][idxJT_managerial] = myManagerialLevelId;

	calculateSumExperience();
	modalHide();
}

function cantFindJobtitle_popUp()
{
	modalShow(cantFindJobTitleLiteral, 'EmploymentHistory_Add.aspx', 600, 400)
}

function addJobTitle( idx )
{
	if( arrSearchJobTitle[idx][0] == -1 )
	{
		cantFindJobtitle_popUp();
		hideMenu();	
	}
	else
	{
		var exists = false;
		if(jobTitle.length-1 >= 0)
		{
			if (exists)
			{
				alert('Job title already selected.');
			}
			else
			{
				var d = getObj('RegistrationSearchBox');
				d.parentNode.removeChild(d);
			
				reg.addRow( arrSearchJobTitle[idx][0], arrSearchJobTitle[idx][1], 0, -1, -1, -1 );	
				hideMenu();		
			}
		}
		else
		{
			var d = getObj('RegistrationSearchBox')
			d.parentNode.removeChild(d);
		
			reg.addRow( arrSearchJobTitle[idx][0], arrSearchJobTitle[idx][1] );	
			hideMenu();		
		}
	}		
}

function addAnotherJobTitle()
{
	if(getObj('RegistrationRowAdd') != null)
	{
		getObj('RegistrationRowAdd').className = '';
		getObj('RegistrationRowAdd').innerHTML = strAddAnother;
	}
}

function doOnKeyPress( obj )
{
	var firstChar = obj.value.substr(0,1).toLowerCase();
	workSearch = obj.value.toLowerCase();		
	
	if(firstChar != '')
		populateSelect( null, 'AllJobTitlesByFirstLetter', null, firstChar , "MEX", doAfterType, null, null, 'a_' + firstChar )
}

function doAfterType( obj )
{
	if( workSearch.length == 1 )
		arrSearchJobTitle = copyAssociativeArray( obj );
	else
		arrSearchJobTitle = copyArray( obj, workSearch );

	search.Build_Search( arrSearchJobTitle, true );
}	

function copyAssociativeArray( obj )
{
	var newArray = new Array();
	    
	for(var i in obj)
	{			
		for(var j in obj[i])
		{
			newArray[newArray.length] = obj[i][j];				
		}
	}
	
	newArray.sort( function(a,b){ return( (a[2] > b[2])?1:0) } );
	
	return newArray;
}

function copyArray( obj, workSearch )
{
	var arrData = obj[ workSearch.substr(1,1) ];
	
	var newArray = new Array();
		    
	for(var j in arrData)
	{
		if( workSearch.length > 2 )
		{
			if( arrData[j][1].toLowerCase().indexOf(workSearch.toLowerCase()) == 0 )
				newArray[newArray.length] = arrData[j];				
		}
		else
			newArray[newArray.length] = arrData[j];				
	}
	
	return newArray;
}

function buildInputList(objArrMain, inputType, objContainer, onClickFunction, objValues, isMandatoryField)
{
	var HTMLtable = '';
	var maxLengthForRow = 23;
	var rowTextLength = 0;

	if (objValues != null)
		objValues = ',' + objValues.toString() + ',';

	for (var i = 0; i < objArrMain.length; i++)
	{
		var isChecked = "";

		if (objValues != null && objValues.toString().indexOf(',' + objArrMain[i][0] + ',') > -1)
			isChecked = ' checked ';

		HTMLtable += '<input type="' + inputType + '" name="' + inputType + objContainer + '" id="' + inputType + objContainer + i.toString() + '"' + ((typeof (isMandatoryField) != 'undefined') ? ' isMandatoryField="' + isMandatoryField + '"' : ' ') + ' value="' + objArrMain[i][0] + '"' + ((typeof (onClickFunction) != 'undefined' && onClickFunction != null) ? ' onClick="' + onClickFunction + 'Click(this)" ' : ' ') + isChecked + '/>';
		HTMLtable += '<label for="' + inputType + objContainer + i.toString() + '">' + objArrMain[i][1] + '</label>';

		rowTextLength += objArrMain[i][1].length;
		if (rowTextLength > maxLengthForRow)
		{
			HTMLtable += '<BR/>';
			rowTextLength = 0;
		}
	}

	$('#' + objContainer).html(HTMLtable);
	hints_prepareInputs2Radios();
}

function editField(txtAnchor, txtObject, txtClass, divToShow)
{
	var obj = $('#' + txtObject);
	var objAnchor = $(txtAnchor);

	if (obj.hasClass(txtClass))
	{
		obj.removeClass(txtClass);
		obj.attr("disabled", "disabled");
		obj.attr("readonly", "readonly");

		if (!divToShow)
			objAnchor.parent().show();
	}
	else
	{
		obj.addClass(txtClass);
		obj.removeAttr("disabled");
		obj.removeAttr("readonly");

		objAnchor.parent().hide();
	}

	if (divToShow)
	{
		objAnchor.parent().hide();
		($('#' + divToShow)).show();
	}

}

//=============== Add Another Button Function ================
function addAnother(anAddButtonId, ulModel, maxAdd, autocompleteHandleFunction, titleObjectId, helpToolTip)
{
	var nodeModel = $('#' + ulModel);
	
	if (nodeModel.length == 1)
	{
		if (isNaN(nodeModel.attr('AddedCount')))
		{
			nodeModel.attr('AddedCount', '1');
		}

		//Variables
		var addedCount = nodeModel.attr('AddedCount');
		var cloneModelId = nodeModel[0].id + addedCount;
		var cloneModel = changeNodeIds(nodeModel.clone(), addedCount); //Clone the model and chanche IDs
		var multiLevelDropDown = cloneModel.find('#MultiLevelDropDown > select');
		var hlpFieldName = multiLevelDropDown.attr('hlpFieldName');

		//Reset Values
		cloneModel = resetValues(cloneModel);

		//Remove the values for multiLevelDropDown
		cloneModel.find('#M_' + hlpFieldName + 'Tree2 > *').remove();

		//Add titles
		cloneModel.find("ul[id^='" + titleObjectId + "']").show();

		//Restore the default value of the multiLevelDropDown
		if (multiLevelDropDown.children("option").length == 1)
		{
			multiLevelDropDown[0].value = -1;

			multiLevelDropDown.children("option")[0].text = multiLevelDropDown.attr('defaultselect');
			multiLevelDropDown.children("option")[0].value = -1;
		}

		//Hide Validator
		cloneModel.find('.validator').hide();

		//Hide OnlyOnFirst
		cloneModel.find('*[showOnlyOnFirst]').hide();

		//Get the HTML
		var cloneModelHTML = cloneModel.html();

		//Replace MultiLevelDropDown		
		if (hlpFieldName != null)
		{
			var multiLevelDropDownName = ($(cloneModel).find(':input[hlpFieldName]')[0].name).replace(new RegExp(hlpFieldName, "g"), hlpFieldName + addedCount);

			cloneModelHTML = cloneModelHTML.replace(new RegExp(hlpFieldName, "g"), hlpFieldName + addedCount);

			cloneModelHTML = cloneModelHTML.replace(multiLevelDropDownName, $(cloneModel).find(':input[hlpFieldName]')[0].name);
		}

		//Change Radio Names
		var cloneModelHTML = changeRadioNames(cloneModel, cloneModelHTML, addedCount);

		//Build the new HTML Node
		var model = "<" + nodeModel[0].tagName + " id=" + cloneModelId + ">" + cloneModelHTML + "</" + nodeModel[0].tagName + ">";

		//Add the node after the Model Node
		var allULnodes = $('#' + ulModel).parent().children("ul[id^='" + ulModel + "']");
		$(allULnodes[allULnodes.length - 1]).after(model);

		//Add efect
		$('#' + cloneModelId).hide();
		$('#' + cloneModelId).show("fast");

		//Hide the 'ADD' button
		if (maxAdd > 0 && Number(addedCount) >= maxAdd - 1)
		{
			if ($('#' + anAddButtonId).parent().parent().length == 1)
			{
				$('#' + anAddButtonId).parent().parent().css('visibility', 'hidden');
			}
		}

		//Add DropDown Tree events
		if ($(cloneModel).find(':input[hlpFieldName]').length == 1)
		{
			CreateDropDownObject($(cloneModel).find(':input[hlpFieldName]')[0].id);
		}

		//Add Autocomplete
		addAutocompleteHandler(autocompleteHandleFunction, cloneModelId, addedCount);

		//Save the added count in model node. Must be the last action in the function
		nodeModel.attr('AddedCount', (Number(addedCount) + 1).toString());

		//Add Validator if needed
		//$('#' + cloneModelId).find('.validator').each
		$('#' + cloneModelId).find('SPAN[errormessage],SPAN[controltovalidate],SPAN[display]').each
		(
			function(index, node)
			{
				if ($(this).length == 1)
				{
					var val_field = $('#' + cloneModelId).find(':input[id^="' + $(this).attr('controltovalidate') + '"]');

					var clientvalidationfunction = null;
					if (val_field.length == 1)
					{
						$(this).attr('controltovalidate', val_field[0].id);

						//clientvalidationfunction = nodeModel.find('span[controltovalidate]')[index].id + ".clientvalidationfunction";
						clientvalidationfunction = $(this)[0].id + ".clientvalidationfunction";
					}

					var evaluationfunction = nodeModel.find('span[errormessage],span[controltovalidate],span[display]')[index].id + ".evaluationfunction";

					if (typeof (eval(evaluationfunction)) == 'function')
					{
						var strEvalValidator = "Page_Validators[Page_Validators.length] = document.getElementById(\"" + $(this)[0].id + "\");" +
														"document." + $(this)[0].id + " = document.all ? document.all[\"" + $(this)[0].id + "\"] : document.getElementById(\"" + $(this)[0].id + "\");" +
														((val_field.length == 1) ? "" + $(this)[0].id + ".controltovalidate = \"" + val_field[0].id + "\";" : "") +
														"" + $(this)[0].id + ".evaluationfunction = " + evaluationfunction + ";" +
														"" + $(this)[0].id + ".initialvalue = \"\";" +
														(typeof (eval(clientvalidationfunction) == 'undefined') ? "" : "" + $(this)[0].id + ".clientvalidationfunction = " + eval(clientvalidationfunction) + ";") +
														"if (typeof (ValidatorOnLoad) == \"function\"){ValidatorOnLoad();}";
						eval(strEvalValidator);
					}
				}
			}
		)

		//Add event ddlDegree
		$('select[name=ddlDegreeId]').change(function()
		{
			CheckSelection(this);
		});

		//Add icon tooltip
       $('#' + cloneModelId).find(':span[id$=GIF' + addedCount + ']').each
       (
            function(index, node) {
                var obj = node.id;
                setTooltipGif(obj.replace("GIF" + addedCount, ""), 70, addedCount);
            }
        )
//       var collection = $('#' + cloneModelId).find(':span[id$=GIF' + addedCount + ']');
//       for (index in collection) {
//           var value = collection[index];
//          
//       }

//		if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent))
//		{
//			var ffversion = new Number(RegExp.$1);
//			$('#' + cloneModelId).find('SPAN.validator').each //,SPAN[id*="RmCustomValidator]"
//			(
//			function(index, node)
//			{
//				if ($(this).length == 1)
//				{
//					//match ctl00_MasterContentPlaceHolder_THE-CONTROL-ID-HERE_RmCustomValidator1
//					//FIND it within INPUT and SELECT retreive the id and add the attribute controltovalidate to this
//					var validatorId = $(this)[0].id;
//					var spliter1 = validatorId.split("_");

////					if (spliter1.length == 4)
////						start = spliter1[2];
//					var controlToValidate = "";
//					var clientvalidationfunction = null;
//					$("script:contains('CDATA'):contains('" + validatorId + ".controltovalidate')").each(function()
//					{
//						var pos1 = $(this).text().indexOf(validatorId + ".controltovalidate");
//						controlToValidate = $(this).text().substring(pos1);
//						controlToValidate = controlToValidate.substring(0, controlToValidate.indexOf(";"));
//						controlToValidate = controlToValidate.split("=")[1].trim();
//						controlToValidate = controlToValidate.replace("\"", "").replace("\"", "");
//					});
//					if (controlToValidate.length > 0)
//					{
//						$(this).attr('controltovalidate', controlToValidate);
//						clientvalidationfunction = validatorId + ".clientvalidationfunction";

//						var val_field = $('select[id^="' + controlToValidate + '"]');
//						
//						var clientvalidationcall = clientvalidationfunction +"=\""+ controlToValidate+"\";";
//						$('<script type="text/javascript">\n//<![CDATA[' + clientvalidationcall + '//]]></script>').appendTo(document.body);
//						
//						var evaluationfunction = nodeModel.find('SPAN.validator')[index].id + ".evaluationfunction";
//						//alert(evaluationfunction.length);
//						if (typeof (eval(evaluationfunction)) == 'function')
//						{
//							var strEvalValidator = "Page_Validators[Page_Validators.length] = document.getElementById(\"" + $(this)[0].id + "\");" +
//														"document." + $(this)[0].id + " = document.all ? document.all[\"" + $(this)[0].id + "\"] : document.getElementById(\"" + $(this)[0].id + "\");" +
//														((val_field.length == 1) ? "" + $(this)[0].id + ".controltovalidate = \"" + val_field[0].id + "\";" : "") +
//														"" + $(this)[0].id + ".evaluationfunction = " + evaluationfunction + ";" +
//														"" + $(this)[0].id + ".initialvalue = \"\";" +
//														(typeof (eval(clientvalidationfunction) == 'undefined') ? "" : "" + $(this)[0].id + ".clientvalidationfunction = " + eval(clientvalidationfunction) + ";") +
//														"if (typeof (ValidatorOnLoad) == \"function\"){ValidatorOnLoad();}";
//							//alert(strEvalValidator);
//							eval(strEvalValidator);
//						}

//					}
//				}
//			}
//		)}	
	}
}

function removeAnother(anRemoveButton, ulModel, titleObjectId)
{
	var nodeModel = $('#' + ulModel);
	var addedCount = (Number(nodeModel.attr('AddedCount')) - 1);
	var parentNode = nodeModel.parent().children("ul[id^='" + ulModel + "']");
	
	if (parentNode.length > 1)
	{
		var node2Del = null;
		if (ulModel != null && titleObjectId != null)
		{
			node2Del = $(anRemoveButton).parents("ul[id^='" + ulModel + "']");
			
			//Show the 'ADD' button
			nodeModel.nextAll('.button_reg').show();
			nodeModel.nextAll('.button_reg').css('visibility', 'visible');
		}
		else
		{
			node2Del = $(anRemoveButton).parent().parent();
		}

		if (node2Del.length == 1)
		{
			//Rename the node and delete the selected one
			node2Del.hide("medium", function()
			{
				if ($(this)[0].id == ulModel)
				{
					$(this)[0].id = 'temporary';

					parentNode[1].id = ulModel;

					//Is case we delete the model node, it'll shown the hiden nodes in the second node
					$(parentNode[1]).find('*[showOnlyOnFirst]').show();
				}

				$(this).remove();
			});


			//Save the added count in model node. Must be the last action in the function
			nodeModel.attr('AddedCount', addedCount.toString());

			//Get the node in order to remove the ASP.NET validator. Remove Validator
			node2Del.find('span[errormessage],span[controltovalidate],span[display]').each
			(
				function(index, node)
				{
					if ($(this).length == 1)
					{
						for (var x = 0; x < Page_Validators.length; x++)
						{
							if (Page_Validators[x] == $(this)[0])
							{
								Page_Validators.splice(x, 1);
								break;
							}
						}
					}
				}
			)
		}			
	}	
}

function changeNodeIds(obj, suffix)
{
	obj.children().each
	(
		function(index, node)
		{
			if (node.nodeName != 'OPTION' && (node.getAttribute('isReplaceIDs') == null || node.getAttribute('isReplaceIDs').toLowerCase() != 'false'))
			{
				if (node.id && node.id != null && node.id != '')
				{
					node.id = node.id + suffix;
				}

				if (node.hasChildNodes())
				{
					changeNodeIds($(node), suffix);
				}
			}
			else
			{
				var spanError = $(node).find('span[errormessage],span[controltovalidate],span[display]');

				if (spanError.length == 1)
				{
					spanError[0].id = spanError[0].id + suffix;
				}
			}
		}
	);

	return obj;
}

function changeRadioNames(cloneModel, HTML, suffix)
{
	var arrRadio = new Array();

	//Add to radio Array
	cloneModel.find(':radio').each
	(
		function(index, node)
		{
			var radioName = $(this)[0].name;

			var isInArr = false;

			for (var x = 0; x < arrRadio.length; x++)
			{
				if (radioName == arrRadio[x])
				{
					isInArr = true;
					break;
				}
			}

			if (!isInArr)
			{
				arrRadio[arrRadio.length] = radioName;
			}
		}
	)

	//Replace the radio
	for (var x = 0; x < arrRadio.length; x++)
	{
		HTML = HTML.replace(new RegExp(arrRadio[x], "g"), arrRadio[x] + suffix);
	}

	return HTML;
}

function resetValues(obj)
{
	obj.children().each
	(
		function(index, node)
		{
			if (node.nodeName == 'SELECT')
			{
				node.selectedIndex = 0;
			}
			else if (node.type == 'radio' || node.type == 'checkbox')
			{
				node.checked = false;
			}
			else if (node.nodeName == 'INPUT' && node.type != 'button')
			{
				node.value = "";
				if(typeof (node.defaultValue) != 'undefined')
					node.defaultValue = "";
			}

			if (node.hasChildNodes())
			{
				resetValues($(node));
			}
		}
	);

	return obj;
}

function addAutocompleteHandler(autocompleteHandleFunction, cloneModelId, suffix)
{
	if (typeof (autocompleteHandleFunction) != 'undefined')
	{
		autocompleteHandleFunction("#" + cloneModelId, suffix);
	}
}
//=============== Add Another Button Function ================

//===================== AutoComplete =========================
function prepareJobTitleAutocomplete(ulObject, suffix)
{
	$(ulObject).find("input[id$='_txtJobTitleText" + suffix + "']")
		.autocomplete("../Common/GenericHandlers/AutoCompleteJobTitle.ashx",
		{
			minChars: 3,
			width: 287,
			matchContains: true,
			autoFill: false,
			max: 15,
			delay: 200,
			selectFirst: false,
			extraParams: { langId: langId }
		});
	//.result(function(event, data, formatted)
	//{
	//if (data)
	//{
	//var ulParent = $(this).parents('ul')

	//Select JobFields
	//				ulParent.find("#txtJobTitleId" + suffix)[0].value = data[5];

	//Set SubField
	//				var subFieldDropDown = ulParent.find("select[id$='SubFieldIIDs_DropDownList']");
	//				subFieldDropDown[0].options[0].value = data[4];
	//				subFieldDropDown[0].options[0].text = data[1];

	//Set the dropDown object
	//				eval('this.igtree_' + subFieldDropDown.attr('hlpFieldName') + 'Tree2_cs = [{}, { ' + data[4] + ': 0 }, { ' + data[3] + ': 0}];');

	//Select Managerial Level
	//				ulParent.find('div:#ManagerialLevelId :radio').each
	//				(
	//					function(index, node)
	//					{
	//						if (node.value == data[2])
	//						{
	//							node.checked = true;
	//						}
	//					}
	//				);
	//}
	//});
}

function prepareInstituteAutocomplete(ulObject, suffix)
{
	$(ulObject).find("input[id$='_txtInstituteName" + suffix + "']")
		.autocomplete("../Common/GenericHandlers/AutoCompleteInstituteName.ashx",
		{
			minChars: 3,
			width: 287,
			matchContains: true,
			autoFill: false,
			max: 15,
			delay: 200,
			selectFirst: false,
			extraParams: { langId: langId }
		})
		.result(function(event, data, formatted)
		{
			if (data)
			{
				var ulParent = $(this).parents('ul')
				ulParent.find("#txtInstituteNameId" + suffix)[0].value = data[1];
			}
		});
}

function prepareSkillAutocomplete(ulObject, suffix)
{
	$(ulObject).find("input[id$='_txtSkillDesc" + suffix + "']")
		.autocomplete("../Common/GenericHandlers/AutoCompleteSkill.ashx",
		{
			minChars: 3,
			width: 243,
			matchContains: true,
			autoFill: false,
			max: 15,
			delay: 200,
			selectFirst: false,
			extraParams: { langId: langId, selectedSkills: function() { var Ids = ""; for (var x = 0; x < document.getElementsByName('txtSkillId').length; x++) { Ids += document.getElementsByName('txtSkillId')[x].value + ","; } return Ids; } }
		})
		.result(function(event, data, formatted)
		{
			if (data)
			{
				var ulParent = $(this).parents('ul');
				ulParent.find("#txtSkillId" + suffix)[0].value = data[1];
			}
		});
	$(ulObject).find("input[id$='_txtSkillDesc" + suffix + "']")
		.keypress(function(event)
		{
			clearHiddenId(event, this, "#txtSkillId" + suffix);			
		});
}

function prepareLanguageAutocomplete(ulObject, suffix)
{
	$(ulObject).find("input[id$='_txtLanguageDesc" + suffix + "']")
		.autocomplete("../Common/GenericHandlers/AutoCompleteLanguage.ashx",
		{
			minChars: 3,
			width: 287,
			matchContains: true,
			autoFill: true,
			max: 15,
			delay: 200,
			selectFirst: true,
			mustMatch: true,
			extraParams: { langId: langId }
		})
		.result(function(event, data, formatted)
		{
			if (data)
			{
				var ulParent = $(this).parents('ul')
				ulParent.find("#txtLanguageId" + suffix)[0].value = data[1];
			}
		});
}

function prepareCompanyNameAutocomplete(ulObject, suffix)
{
	$(ulObject).find("input[id$='_txtCompanyName" + suffix + "']")
		.autocomplete("../Common/GenericHandlers/AutoCompleteCompanyName.ashx",
		{
			minChars: 3,
			width: 287,
			matchContains: true,
			autoFill: false,
			max: 15,
			delay: 200,
			selectFirst: false
		})
}
//===================== AutoComplete =========================

function ddlRequiredValidatorNoControlToValidate(source, arguments)
{
	var jobExp = $(source).parent('li').find('select').val();

	if (Number(jobExp) > -1)
		arguments.IsValid = true;
	else
		arguments.IsValid = false;
}

function clearHiddenId(e, obj, hiddenInput)
{
	var key = 0;
	if(!e) 
		e=window.event;
	
	key = e.keycode ? e.keycode : e.which;
	//alert(key);	
	if(key < 48 || key > 122) 
		return;
		
	var ulParent = $(obj).parents('ul');
	ulParent.find(hiddenInput)[0].value = 0;
}

function setTooltipGif(objName, heset, objCount) {
    $("#" + objName + "GIF" + objCount).mouseover(function(e) {
        var help = $("#" + objName + "Help" + objCount);
        //debugger
        help[0].style.top = (e.pageY - heset) + 'px';
        help[0].style.left = (e.pageX) + 'px';

        help.show();

    })

    $("#" + objName + "GIF" + objCount).mouseout(function(e) {
        var help = $("#" + objName + "Help" + objCount);
        help.hide();
    })
}
	
