/*******************************************************************************
 * Copyright 2014 Centre for Development of Advanced Computing(C-DAC), Pune
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 ******************************************************************************/



var displaySearch;
var dialogFormHTML;
var divDialogForm;

var stateParam;
var semantictagParam;
var acceptabilityParam;
var returnlimitParam;
var refsetidParam;
var parentidsParam;

var enumSERVICES = {
	SEARCH : {
		type : "search",
		suggest_url : "http://localhost:8080/csnoserv/api/search/suggest",
		search_url : "http://localhost:8080/csnoserv/api/search/search",
		hostname : "http://localhost:8080/", //change host name here
	},
};


var enumSTATE = {
	BOTH : "both",
	ACTIVE : "active",
	INACTIVE : "inactive"
};

var enumSEMANTICTAG = {

	ALL : "all",
	PROCEDURE : "procedure",
	DISORDER : "disorder",
	FINDING : "finding",
	OBSERVABLE_ENTITY : "observable entity",
	BODY_STRUCTURE : "body structure",
	ORGANISM : "organism",
	SUBSTANCE : "substance",
	SPECIMEN : "specimen",
	SPECIAL_CONCEPT : "special concept",
	LINKAGE_CONCEPT : "linkage concept",
	PHYSICAL_FORCE : "physical force",
	EVENT : "event",
	ENVIRONMENT : "environment",
	GEOGRAPHIC_LOCATION : "geographic location",
	SOCIAL_CONCEPT : "social concept",
	SITUATION_WITH_EXPLICIT_CONTEXT : "situation",
	STAGING_SCALE : "staging scale",
	PHYSICAL_OBJECT : "physical object",
	QUALIFIER_VALUE : "qualifier value",
	RECORD_ARTIFACT : "record artifact",
	PERSON : "person",
	LINK_ASSERTION : "link assertion",
	NAMESPACE_CONCEPT : "namespace concept",
	ATTRIBUTE : "attribute",
	ASSESSMENT_SCALE : "assessment scale",
	RACIAL_GROUP : "racial group",
	TUMOR_STAGING : "tumor staging",
	OCCUPATION : "occupation",
	MORPHOLOGIC_ABNORMALITY : "morphologic abnormality",
	CELL : "cell",
	CELL_STRUCTURE : "cell structure",
	ETHNIC_GROUP : "ethnic group",
	PRODUCT : "product",
	INACTIVE_CONCEPT : "inactive concept",
	NAVIGATIONAL_CONCEPT : "navigational concept",
	LIFE_STYLE : "life style",
	REGIME_THERAPY : "regime/therapy",
	RELIGION_PHILOSOPHY : "religion/philosophy",
	DISPOSITION : "disposition",
	MEDICINAL_PRODUCT : "medicinal product",
	MEDICINAL_PRODUCT_FORM : "medicinal product form",
	CLINICAL_DRUG : "clinical drug",
	UNIT_OF_PRESENTATION : "unit of presentation",
	NUMBER : "number",
	ADMINISTRATION_METHOD : "administration method",
	BASIC_DOSE_FORM : "basic dose form",
	DOSE_FORM : "dose form",
	INTENDED_SITE : "intended site",
	RELEASE_CHARACTERISTIC : "release characteristic",
	STATE_OF_MATTER : "state of matter",
	TRANSFORMATION : "transformation",
	BRAND_PRODUCT : "brand product",
	ROLE : "role",
	PRODUCT_NAME : "product name",
	PACKAGED_CLINICAL_DRUG : "packaged clinical drug",
	REAL_CLINICAL_DRUG : "real clinical drug",
	REAL_MEDICINAL_PRODUCT : "real medicinal product",
	REAL_PACKAGED_CLINICAL_DRUG : "real packaged clinical drug",
	SUPPLIER : "supplier"
};

/*
*Loading on document loading
*/
$(document).ready(function(){
	loadSemanticTagsSearch();
});


/*
*Ajax call used for load semantic tags from CSNOServ
*/
function loadSemanticTagsSearch(){
	var semanticURL=enumSERVICES.SEARCH.hostname+"csnoserv/api/search/semantic";
	$.ajax({url: semanticURL,
				method: 'GET',
				headers: {
						'Access-Control-Allow-Origin': '*'
					},
				success: function(result){			
			loadSemanticTagListSearch(result);
		 },error:function(result){	
			console.log("no response"+result);	
		}});
	
	}
	
	/*
	*loading semantic tags from result of Ajax call loadSemanticTags
	*/
	function loadSemanticTagListSearch(semanticTagList){	
		var dataStr='';
		enumSEMANTICTAG = {};
		semanticTagList.forEach(element => {
		dataStr=element;
		if(dataStr!="undefined"){
			dataStr=dataStr.toUpperCase().split(' ').join('_');
			enumSEMANTICTAG[dataStr]=element;	
		}	
	});
	enumSEMANTICTAG.ALL='all';	
}


var enumACCEPTABILITY = {
	ALL : "all",
	PREFERRED : "preferred",
	PREFERRED_EXCLUDING_FSN : "preferredexcludingfsn",
	SYNONYMS : "synonyms",
	ACCEPTABLE : "acceptable"
};


				function setSearchDialog() {

					
					dialogFormHTML = '<div id="snomed-ct-search"><input type="text" placeholder="Enter 3 characters to search..." id="txt-snomed-ct-search" class="searchText" name="txt-snomed-ct-search" style="width:95%;color:#000000;"></input><input type="image" name="submit" src="images/search.png" id="srcImg" alt="Search"  title="Search" style="height: 20px; width: 20px;float:right;cursor:pointer;position:relative;top:3px;padding-left:5px;display:block;"></div>';
					dialogFormHTML += '<span id="recordcount" vertical-align:top; ></span><label id="nosuggestion">No suggestions found</label><label id="norecord">No results found</label><label id="msg3chars">Please enter atleast 3 characters</label>';
					dialogFormHTML += '<div id="licenseBox" style=" max-height:290px;"></div>';
					divDialogForm = '<div id="dialog-form" style="width: 600px;">'
							+ dialogFormHTML + '</div>';

					$('body').append(divDialogForm);

					/*
					dialogData = '';
					dialogHTML = '<div id="dialog-message" title="CSNOCtrl Information"><p>'
							+ dialogData + '</p></div>';
					$('body').append(dialogHTML);
					*/

					var dialog = $("#dialog-form").dialog({

						autoOpen : false,
						height : 160,
						width : 600,
						modal : true,
						resizable : false,
						
						buttons : {

							"." : function(event) {

							}
						}

					}

					);

					dialog.data("uiDialog")._title = function(title) {
						title.html(this.options.title);

					};

					if (document.getElementById("conceptdiv"))
						$("#conceptdiv").remove();

					dialog
							.dialog(
									'option',
									'title',
									'<img style="width:63px;height:20%;vertical-align: text-bottom;padding-right:34em;" src="images/CSNOCtrl.png" style="position:relative;right:0px;top:0px;"/><img align="right" style="position:relative;vertical-align: text-bottom; height: 20%; width: 36px; top: 0px;" src="images/CDACLogo.png"/> ');

				}

/*
 * loadResultsList() function loads the matching records for the term searched
 * in SNOMEDCT repository. The records contains the Concept-id,Description and
 * Description-id The result will display the concept-id, description-id and
 * description of the selected concept from the result list.
 * 
 * Parameter Description: @param state(var)-Defines state of the concept. Refer
 * enumSTATE in searchtool.js to pass values for the state_IN parameter If state
 * is, ACTIVE- It will return all active Concepts with all active Descriptions.
 * INACTIVE- It will return all inactive Concepts with all active and inactive
 * Descriptions. BOTH- It will return all active and inactive Concepts with all
 * active and inactive Descriptions.
 * 
 * @param semantictag(var)-Defines semantic tag in which SNOMED CT term/text will be
 * searched. Refer enumSEMANTICTAG in searchtool.js to pass values for the semantictag_IN
 * parameter. If semantic tag is, ALL- It will search SNOMED CT term in all Semantic Tags
 * 
 * Other examples-'PROCEDURE','DISORDER','BODY_STRUCTURE'
 * 
 * @param acceptability(var)-Represents whether only FSN and Preferred Terms are to
 * be fetched or all matching terms.Refer enumACCEPTABILITY in searchtool.js to
 * pass values for the acceptability_IN parameter. If acceptability is,
 * PREFERRED- Only FSN and Preferred Terms for given term will be fetched 
 * PREFERRED_EXCLUDING_FSN- Only Preferred terms excluding FSN for given term will be fetched
 * ACCEPTABLE- Only acceptable terms shall be fetched
 * SYNONYMS- All terms excluding FSN shall be fetched 
 * ALL- It will fetch all SNOMED CT terms
 * 
 * @param returnlimit(var)-Maximum number of matching terms to be fetched. To get all
 * the hits available, pass '-1'. @param call (var)-It will contain the
 * definition of the callback function used to retrieve return value/result from
 * the selectSNOMEDCT function. The result includes Concept-id,Description-id
 * and Description of the selected concept from SNOMED CT repository. User will
 * have to define a callback function in your HTML page.
 */

/* variable declared to handle scroll events for search term result list */
var keyStatus = 1;
var scrollStatusDown = 1;
var scrollStatusUp = 0;
 
function loadResultsList(state, semantictag, acceptability, returnlimit, refsetid, parentids, call) {
	
	$('#recordcount').show();
	$('#norecord').hide();
	$('#msg3chars').hide();
	$('#nosuggestion').hide();

	if (document.getElementById("conceptdiv"))
		$("#conceptdiv").remove();

	if (displaySearch == false) {

		if (document.getElementById("conceptdiv"))
			$("#conceptdiv").remove();
		displaySearch = true;
	}

	if (displaySearch == true) {

		var dataValue = document.getElementById("txt-snomed-ct-search").value;

		if (dataValue.trim() == '') {
			$("#dialog-form").dialog("option", "height", 160);
			if (document.getElementById("conceptdiv"))
				$("#conceptdiv").remove();
			
			$('#recordcount').hide();
			$('#norecord').show();
			$('#msg3chars').hide();
			$('#nosuggestion').hide();
			var txtBox = document.getElementById("txt-snomed-ct-search");
			txtBox.focus();
			return;
		}

		var servURL = '';

		servURL = enumSERVICES.SEARCH.search_url;

		servURL += "?term=" + encodeURIComponent(dataValue) + "&state=" + state
				+ "&semantictag=" + semantictag + "&acceptability=" + acceptability
				+ "&returnlimit=" + returnlimit+"&refsetid="+refsetid+"&parentid="+parentids+"&fullconcept=false";

		$
				.ajax({
					type : "GET",
					url : servURL,
					//dataType : "json",
					crossDomain : true,
					success : function(data, textStatus, jqXHR) {

						var htmlData = '';						
						$('#recordcount').text("No. of records : "+data.length);
						if (data.length == 0) {
							$("#dialog-form").dialog("option", "height", 160);
							if (document.getElementById("conceptdiv"))
								$("#conceptdiv").remove();
							
							$('#recordcount').hide();
							$('#norecord').show();
							$('#msg3chars').hide();
							$('#nosuggestion').hide();
							var txtBox = document
									.getElementById("txt-snomed-ct-search");
							txtBox.focus();
							return;
						}

						displaySearch = false;

						htmlData = '';
						htmlData += '<div class="concept" id="conceptdiv">';
						htmlData += '<table class="bordered">';
						htmlData += '<thead><tr><th>Description&nbsp;&nbsp;</th></tr></thead>';
						htmlData += '<tbody id="conceptBody">';
						
						for (var i = 0; i < data.length; ++i) {
							var val = '\'' + data[i].conceptId + '###$$$'
									+ data[i].term + '###$$$' + data[i].id
									+ '\'';

							htmlData += '<tr '
							
							if(i==0) 
								htmlData += ' id="currentTerm" class="activerow" '
							
							htmlData += 'tabindex="0" title="' + data[i].conceptFsn
									+ '" onmouseover="mouseOverSearchList(this);" onmouseout="mouseOutSearchList();" onclick="selectValue(\'' + escape(val)
									+ '\',' + call + ');"  >'									
									+'<td>' + data[i].term + '</td></tr>';
						}
						htmlData += '</tbody>';
						
						$("#dialog-form").dialog("option", "height", "500");
						htmlData += '</table>';
						htmlData += '</div>';
						if (document.getElementById("conceptdiv"))
							$("#conceptdiv").remove();
						$("#dialog-form").append(htmlData);

						$(document).keydown(function(e){
							
							if (document.getElementById("conceptBody") && (e.keyCode == 13) && keyStatus==1){
								
								//'enter' key pressed
								if (e.keyCode == 13) {
									$('tr.activerow').trigger('click');
								}
								
								e.preventDefault();
								e.stopImmediatePropagation();
							}
							
							if (document.getElementById("conceptBody") && (e.keyCode == 40 || e.keyCode == 38) && keyStatus==1){
								
								e.preventDefault();
								e.stopImmediatePropagation();
								
								//'up' arrow key pressed
								if (e.keyCode == 38) {
									var activeTableRow = $('.bordered tbody tr.activerow').prev(".bordered tbody tr");
									if (activeTableRow.length) {
										$('.bordered tbody tr.activerow').removeAttr( "id" );
										$('.bordered tbody tr.activerow').removeClass("activerow");
										
										activeTableRow.addClass('activerow');
										activeTableRow.attr('id', 'currentTerm');
									} 
									else{
										scrollStatusUp = 0;
										document.getElementById("snomed-ct-search").scrollIntoView(false);
									}
								}	
								
								//'down' arrow key pressed
								if (e.keyCode == 40) {
									var activeTableRow = $('.bordered tbody tr.activerow').next(".bordered tbody tr");
									if (activeTableRow.length) {
										$('.bordered tbody tr.activerow').removeAttr( "id" );
										$('.bordered tbody tr.activerow').removeClass("activerow");
										
										activeTableRow.addClass('activerow');
										activeTableRow.attr('id', 'currentTerm');
									}
									else
										scrollStatusDown = 0;
								}									
								
								if($('#license').offset().top -  $('.bordered tbody tr.activerow').offset().top < 10)
									scrollStatusDown = 1;
								
								if($('.bordered tbody tr.activerow').offset().top -  $('#dialog-form').offset().top < 10)
									scrollStatusUp = 1;
								
								if(scrollStatusDown == 1){
									if(document.getElementById("currentTerm"))
										document.getElementById("currentTerm").scrollIntoView(false);	
								}
								
								if(scrollStatusUp == 1){
									if(document.getElementById("currentTerm"))
										document.getElementById("currentTerm").scrollIntoView();	
								}
															
							}
							
						});
						

					},
					error : function(jqXHR, textStatus, errorThrown) {
						console.log(textStatus);
					}
				});
	}

}


/* mouseOverSearchList function is to highlight the current search term among the list.
And removes the previous highlighted term.
It removed the id and class from the previous highlighted term and instead adds to current term.
Additionally, it block the table traversal using arrow keys until mouse is over an element or a search term.
*/

function mouseOverSearchList(element){
	$('.bordered tbody tr.activerow').removeAttr( "id" );
	$('.bordered tbody tr.activerow').removeClass("activerow");
	$(element).attr('id', 'currentTerm');
	$(element).addClass('activerow');
	
	keyStatus = 0;
}


/* mouseOutSearchList function is to remove the actions associated until mouse was hovered.
 * Additionally, it enables the table traversal using arrow keys as the mouse cursor is removed.
 * It sets the other variable sued for upwards or downwards scrolling after the check of presence of term
 * in the list from which the cursor was removed.
*/

function mouseOutSearchList(){
	keyStatus = 1;
	
	if($('#license').offset().top -  $('.bordered tbody tr.activerow').offset().top < 10)
		scrollStatusDown = 1;
	else
		scrollStatusDown = 0;
	
	if($('.bordered tbody tr.activerow').offset().top -  $('#dialog-form').offset().top < 10)
		scrollStatusUp = 1;
	else
		scrollStatusUp = 0;
}


/*
 * selectSNOMEDCT function provides the search and suggest results for the term
 * to be searched from SNOMEDCT repository with the help of input parameters (
 * state_IN, semantictag_IN, acceptability_IN, returnlimit_IN, callback). The most matching
 * terms from the SNOMEDCT repository are populated and displayed on the page
 * for the searched term. Parameter Description: @param state_IN(var)-Defines
 * state of the concept. Refer enumSTATE in searchtool.js to pass values for the
 * state_IN parameter If state is, ACTIVE- It will return all active Concepts
 * with all active Descriptions. INACTIVE- It will return all inactive Concepts
 * with all active and inactive Descriptions. BOTH- It will return all active and
 * inactive Concepts with all active and inactive Descriptions.
 * 
 * @param semantictag_IN(var)-Defines semantic tag in which SNOMED CT term/text will be
 * searched. Refer enumSEMANTICTAG in searchtool.js to pass values for the semantictag_IN
 * parameter. If semantic tag is, ALL- It will search SNOMED CT term in all semantic tags
 * 
 * Other examples-'PROCEDURE','DISORDER','BODY_STRUCTURE'
 * 
 * @param acceptability_IN(var)-Represents whether only FSN and Preferred Terms are
 * to be fetched or all matching terms.Refer enumACCEPTABILITY in searchtool.js
 * to pass values for the acceptability_IN parameter. If acceptability is,
 * PREFERRED- Only FSN and Preferred Terms for given term will be fetched
 * PREFERRED_EXCLUDING_FSN- Only Preferred terms excluding FSN for given term will be fetched
 * ACCEPTABLE- Only acceptable terms shall be fetched
 * SYNONYMS- All terms excluding FSN shall be fetched 
 * ALL- It will fetch all SNOMED CT terms
 * 
 * @param returnlimit_IN(var)-Maximum number of matching terms to be fetched. To get
 * all the hits available, pass '-1'. @param callback (var)-It will contain the
 * definition of the callback function used to retrieve return value/result from
 * the selectSNOMEDCT function. The result includes Concept-id,Description-id
 * and Description of the selected concept from SNOMED CT repository. User will
 * have to define a callback function in your HTML page like-
 * 
 * @param refsetid_IN(var)-Refset Identifier for search in particular Refset and null otherwise.
 * 
 * var callback =function(selectedSNOMEDTerm){setValue(selectedSNOMEDTerm);};
 * function setValue(selectedSNOMEDTerm) { //selectedSNOMEDTerm contains
 * Concept-id,Description-id and Description. User can manipulate the string or
 * edit the function definition as per his requirement
 * //document.getElementById(HTMLcontrolid).value=selectedSNOMEDTerm; }
 * 
 * The function shall contain only 1 parameter <selectedSNOMEDTerm> that refers
 * to the result including Concept-id,Description-id and Description. User will
 * have to define a function like setValue in the callback function to set the
 * return value <selectedSNOMEDTerm> in some HTML control of the web page. For
 * different HTML controls user will have to define different callback functions
 * and write corresponding <setValue> functions for them.
 * 
 */

function selectSNOMEDCT(state_IN, semantictag_IN, acceptability_IN, returnlimit_IN,refsetid_IN,parentids_IN,
		callback) {
		
	if(parentids_IN!=null && refsetid_IN!=null)
	{
		alert("Refset ID and Parent ID can't be provided simultaneously");
		return;
	}
			
			setSearchDialog();				
	if (returnlimit_IN <= -1 || returnlimit_IN == '' || returnlimit_IN == undefined
			|| returnlimit_IN == null) {
		returnlimit_IN = -1;

	}
	returnlimitParam = returnlimit_IN;


	if (refsetid_IN <= -1 || refsetid_IN == '' || refsetid_IN == undefined
			|| refsetid_IN == null) {
		refsetid_IN = null;
	}
	refsetidParam=refsetid_IN;
	
	if (parentids_IN <= 1 || parentids_IN == '' || parentids_IN == undefined
			|| parentids_IN == null) {
		parentids_IN = null;

	}
	parentidsParam = parentids_IN;
	if(parentidsParam!=null)
		{
		parentidsParam=parentidsParam.replace(new RegExp(",", 'g'), "++");
		}
		

	if (state_IN == null || state_IN == ''
			|| state_IN == undefined) {
		state_IN = enumSTATE.ACTIVE;
	} else
		state_IN = enumSTATE[state_IN];

	stateParam = state_IN;

	if (semantictag_IN == null || semantictag_IN == undefined
			|| semantictag_IN == '') {
		semantictag_IN = enumSEMANTICTAG.ALL;
	} else
		{
			var semanticTagList="";	
			for(var i=0;i<semantictag_IN.length;i++)
			{			
			 semanticTagList=semanticTagList+(enumSEMANTICTAG[semantictag_IN[i]])+"++";
			}
			semantictag_IN=semanticTagList.slice(0,semanticTagList.length-2);	
		}
	semantictagParam = semantictag_IN;
	
	if (acceptability_IN == null
			|| acceptability_IN == undefined || acceptability_IN == '') {
		acceptability_IN = enumACCEPTABILITY.SYNONYMS;
	} else
		acceptability_IN = enumACCEPTABILITY[acceptability_IN];

	acceptabilityParam = acceptability_IN;

	$('#dialog-form').dialog({
		position : 'center'
		//	position : 'top'
	});
	$("#dialog-form").click(
			function(e) {
				if (e.target.id == "srcImg") {
					var dataValue = document
							.getElementById("txt-snomed-ct-search").value;
					if (dataValue.length >= 3) {
						if (document.getElementById("conceptdiv"))
							$("#conceptdiv").remove();
						$('#msg3chars').hide();
						$('#nosuggestion').hide();						
						loadResultsList(stateParam, semantictagParam,
								acceptabilityParam, returnlimitParam, refsetidParam,parentidsParam,callback);
					} else {
						if (document.getElementById("conceptdiv"))
							$("#conceptdiv").remove();
						$('#msg3chars').show();
						
						$('#recordcount').hide();
						$('#norecord').hide();
						$('#nosuggestion').hide();
					}
				}
			});

	
	var footer = '';
	footer += '<div class="footer-nav">';
	footer += '<ul><li style="float: left;position: relative;margin-left: 0px; ">&copy; CSNOtk v7.0 </li><li style="float: right;position: absolute;right: 60px; padding: 0 10px;">CSNOCtrl&nbsp;&copy;Centre for Development of Advanced Computing</li>';
	footer += '<li style="float: right;position: absolute;right: 4px; padding: 0 10px;"><a href="#" id="license">License</a></li></ul>';
	footer += '</div>';
	displaySearch = false;

	$("#dialog-form").dialog("option", "height", 160);
	$("#dialog-form").html(dialogFormHTML);
	jQuery('.ui-dialog button:nth-child(1)').button('disable');
	$('.ui-dialog-buttonpane').find("button").show().filter(":contains('.')")
			.hide();
		$(".ui-dialog-buttonpane").html("");
		$(".ui-dialog-buttonpane").append(footer);
	
	$('#recordcount').hide();
	$('#norecord').hide();
	$('#msg3chars').hide();
	$('#nosuggestion').hide();

	var txtBox = document.getElementById("txt-snomed-ct-search");
	txtBox.focus();

	$("#dialog-form").dialog("open");

	$("#txt-snomed-ct-search")
			.keyup(
					function(e) {
						if (e.which == 13) {
							var dataValue = document
									.getElementById("txt-snomed-ct-search").value;

							if (dataValue == '') {
								$("#dialog-form").dialog("option", "height", 160);
								var txtBox = document
										.getElementById("txt-snomed-ct-search");
								txtBox.focus();
								return;
							}

							if (dataValue.length >= 3) {
								$("#dialog-form").dialog("option","height", 500);
								if (document.getElementById("conceptdiv"))
									$("#conceptdiv").remove();
								$("#msg3chars").hide();
								$('#nosuggestion').hide();
								var txtBox = document
										.getElementById("txt-snomed-ct-search");
								txtBox.blur();
								loadResultsList(stateParam, semantictagParam,
										acceptabilityParam, returnlimitParam, refsetidParam,parentidsParam,callback);
							} else {
								if (document.getElementById("conceptdiv"))
									$("#conceptdiv").remove();
								
								$('#recordcount').hide();
								$('#norecord').hide();
								$("#msg3chars").show();
								$('#nosuggestion').hide();
							}
						}
						else
							{
							
							$('#recordcount').hide();
							$('#nosuggestion').hide();
							}
					});


	var xhrRequest = null;
	$("#txt-snomed-ct-search")
			.autocomplete(
					{
						max : 20,
						minLength : 3,
						cacheLength : 1,
						scroll : false,
						width : 520,
						highlight : false,
						autoFocus : false,
						source : function(request, response) {

							var dataValue = document
									.getElementById("txt-snomed-ct-search").value;

							var servURL = "";
							if (dataValue == '') {
								$("#dialog-form").dialog("option", "height",
										160);
								if (document.getElementById("conceptdiv"))
									$("#conceptdiv").remove();
								var txtBox = document
										.getElementById("txt-snomed-ct-search");
								txtBox.focus();
								return;
							}

							if (dataValue.length >= 3) {
								if (document.getElementById("conceptdiv"))
									$("#conceptdiv").remove();
								$("#dialog-form").dialog("option", "height",
										160);
								$("#msg3chars").hide();
								$('#nosuggestion').hide();

							} else {
								if (document.getElementById("conceptdiv"))
									$("#conceptdiv").remove();
								$("#dialog-form").dialog("option", "height",
										160);
								
								$('#recordcount').hide();
								$('#norecord').hide();
								$("#msg3chars").show();
								$('#nosuggestion').hide();
							}

							servURL = enumSERVICES.SEARCH.suggest_url;
							
							servURL += "?term="
									+ encodeURIComponent(request.term)
									+ "&state=" + stateParam + "&semantictag="
									+ semantictagParam + "&acceptability="
									+ acceptabilityParam + "&returnlimit=5"+"&refsetid="+refsetidParam+"&parentid="+parentidsParam;
							console.log(servURL);

							if (xhrRequest && xhrRequest.readystate != 4)
								xhrRequest.abort();
							xhrRequest = $
									.ajax({
										type : "GET",
										url : servURL,
										dataType : "jsonp",
										crossDomain : true,
										success : function(data, textStatus,
												jqXHR) {
											console.log(data);
											var items = data;
											if(items.length<=0)
											{
												
												$('#recordcount').hide();
												$('#norecord').hide();
												$("#msg3chars").hide();
												$('#nosuggestion').show();
											}
											response(items);
										},
										error : function(jqXHR, textStatus,
												errorThrown) {
											console.log(textStatus);

										}
									});

						},
						select : function(event, ui) {
							var data = document
									.getElementById("txt-snomed-ct-search").value;
							if (data.length >= 3) {
								
								$("#msg3chars").hide();
								$('#nosuggestion').hide();
								document.getElementById("txt-snomed-ct-search").value = ui.item.value;
								if (document.getElementById("conceptdiv"))
									$("#conceptdiv").remove();

								var txtBox = document
										.getElementById("txt-snomed-ct-search");
								txtBox.blur();
								
								loadResultsList(stateParam, semantictagParam,
										acceptabilityParam, returnlimitParam,refsetidParam,parentidsParam,callback);
							} else {
								if (document.getElementById("conceptdiv"))
									$("#conceptdiv").remove();
								
								$('#recordcount').hide();
								$('#norecord').hide();
								$("#msg3chars").show();
								$('#nosuggestion').hide();
							}
						}

					});
	
	//action when dialog box is closed either by esc key/close button or other means
	$("#dialog-form").dialog({
			close: function( event, ui ) {
					$("#dialog-form").dialog("destroy").remove();
					$("#dialog-form").remove();
					dialogFormHTML = "";
					divDialogForm = "";
					$(".ui-dialog").remove();
			}
	});
	
	//action when license link/button in the dialog box is clicked 	
	$('#license').click(function() {
		$('#licenseBox').load("license.html", function(content) {
			$('#licenseBox').dialog({
				autoOpen : false,
				resizable : false,
				height : "auto",
				width : 800,
				dialogClass : 'noTitle',
				title : "LICENSE INFO",
				modal : true,
				show : {
					effect : "blind",
					duration : 1000
				},
				hide : {
					effect : "explode",
					duration : 1000
				}
			});
			$('#licenseBox').dialog('open');
		});

	});

	if(window.innerWidth<1368)
		{
	       document.getElementsByClassName("ui-dialog ui-widget ui-widget-content ui-corner-all ui-draggable ui-dialog-buttons")[0].style.marginTop='-7%'
		}


}


/*
*clearSearchDialog function is to close the dialog box and to reset the global variables.
*It clears/removes the appended elements from the body of the page.
*/
function clearSearchDialog(){
	
	$("#dialog-form").dialog("close");
	$("#dialog-form").dialog("destroy").remove();
	
	dialogFormHTML = "";
	divDialogForm = "";
	
	$(".ui-dialog").remove();
}

/*
 * selectValue() function selects the record from the list. The record returns
 * the details of the searched term from the SNOMEDCT repository. The details
 * include description id,description and concept id of the selected record. The
 * result shows concept-id,description-id and description of the term. @param
 * value (var) contains the result including concept-id, description-id and
 * description.
 * 
 * @param callback (var) - It will contain the definition of the callback
 * function used to retrieve return value/result from the selectSNOMEDCT().The
 * result includes Concept-id,Description-id and Description of the selected
 * concept.
 * 
 * returnterm_OUT (var) contains the detailed output with concept-id,
 * description-id and description.
 */

function selectValue(value, callback) {
	
	var data = unescape(value);

	var term = data.split('###$$$');
	
	//it is close/clear the dialog box as term is selected
	clearSearchDialog();
	
	//it is to set the content/value that need to be returned to call back function
	htmlData = '<table id="searchResultTable">';
	htmlData += '<tr class="conId1"><th class="conTh">Description </th><td class="conDtls">' + term[1] + '</td></tr>'
	htmlData += '<tr class="conId1"><th class="conTh">Concept ID </th><td class="conDtls">' + term[0].replace("'", "") + '</td></tr>'
	htmlData += '<tr class="conId1"><th class="conTh">Description ID </th><td class="conDtls">' + term[2].replace("'", "") + '</td></tr>'
	htmlData += '</table>';
	
	returnterm_OUT = htmlData;
			
	if (typeof callback === "function")
		callback(returnterm_OUT);
}
