/*******************************************************************************
 * 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 index = 0;
var jsonData;
var currentCountDisplayed;
var displaySearch;
var h = 80;

var txtId;
var currentHierachy, currentSERVICE;
var selectedConceptId;
var conceptIdOfSearch, conceptIdOfHierarchySearch, conceptIdOfFiniteSearch;

var enumLANGREFSET={
	//UK: "uk",
	//US: "us",
	//HI: "hi"
};
var ar=[];
 $.ajaxSetup({
		async : false
	});  
//change host name here
	 $.ajax({url: "http://localhost:8080/csnoserv/api/search/langrefset", 
			method: 'GET',
         headers: {
                 'Access-Control-Allow-Origin': '*'
             },
         success: function(result){	
		  
        	 var i;
     		for (i = 0; i < result.length-1; i++) {
     			 ar.push(result[i][1].toUpperCase());
				 var tempData=result[i][1].toUpperCase();
     			 enumLANGREFSET[tempData]=result[i][1];
				 
     		}
			 
  },error:function(result){
 	console.log("no response"+result);

 }});
		  $.ajaxSetup({
		async : true
	});


var enumRELATIONSHIP={
	IS_A: "is a",
	FINDING_SITE:"finding site",
	CAUSATIVE_AGENT:"causative agent",
	HAS_INTENT:"has intent",
	PROCEDURE_SITE:"procedure site",
	SPECIMEN_SUBSTANCE:"specimen substance",
	ASSOCIATED_FINDING:"associated finding",
	ASSOCIATED_WITH:"associated with",
	ASSOCIATED_MORPHOLOGY:"associated morphology",
	HAS_ACTIVE_INGREDIENT:"has active ingredient",
	PROCEDURE_SITE_DIRECT:"procedure site direct",
	SPECIMEN_SOURCE_TOPOGRAPHY:"specimen source topography",
	HAS_FOCUS:"has focus",
	HAS_MEASURED_COMPONENT:"has measured component",
	COMPONENT:"component",
	PROCEDURE_SITE_INDIRECT:"procedure site indirect",
	USING:"using",
	DIRECT_DEVICE:"direct device",
	USING_DEVICE:"using device",
	SPECIMEN_SOURCE_MORPHOLOGY:"specimen source morphology",
	DIRECT_MORPHOLOGY:"direct morphology ",
	INDIRECT_MORPHOLOGY:"indirect morphology ",
	PART_OF:"part of ",
	DUE_TO:"due to ",
	RECIPIENT_CATEGORY:"recipient category ",
	SUBJECT_RELATIONSHIP_CONTEXT:"subject relationship context ",
	DIRECT_SUBSTANCE:"direct substance ",
	USING_SUBSTANCE:"using substance ",
	INTERPRETS:"interprets ",
	SPECIMEN_PROCEDURE:"specimen procedure ",
	HAS_DEFINITIONAL_MANIFESTATION:"has definitional manifestation ",
	ASSOCIATED_ETIOLOGIC_FINDING:"associated etiologic finding ",
	HAS_INTERPRETATION:"has interpretation ",
	AFTER:"after ",
	METHOD:"method ",
	TEMPORALLY_FOLLOWS:"temporally follows ",
	ASSOCIATED_PROCEDURE:"associated procedure ",
	ASSOCIATED_FUNCTION:"associated function ",
	PROCEDURE_DEVICE:"procedure device ",
	REVISION_STATUS:"revision status ",
	MEASUREMENT_METHOD:"measurement method ",
	OCCURRENCE:"occurrence ",
	MEASURES:"measures ",
	PROCEDURE_MORPHOLOGY:"procedure morphology ",
	FINDING_METHOD:"finding method ",
	INDIRECT_DEVICE:"indirect device ",
	ROUTE_OF_ADMINISTRATION:"route of administration ",
	USING_ACCESS_DEVICE:"using access device ",
	TEMPORAL_CONTEXT:"temporal context ",
	APPROACH:"approach ",
	SURGICAL_APPROACH:"surgical approach ",
	SEVERITY:"severity ",
	COURSE:"course ",
	CLINICAL_COURSE:"clinical course ",
	LATERALITY:"laterality ",
	SPECIMEN_SOURCE_IDENTITY:"specimen source identity ",
	ACCESS_INSTRUMENT:"access instrument ",
	STAGE:"stage ",
	USING_ENERGY:"using energy ",
	ONSET:"onset ",
	INSTRUMENTATION:"instrumentation ",
	PRIORITY:"priority  ",
	EXTENT:"extent ",
	SCALE_TYPE:"scale type ",
	SUBJECT_OF_INFORMATION:"subject of information ",
	FINDING_CONTEXT:"finding context ",
	HAS_SPECIMEN:"has specimen ",
	ACCESS:"access ",
	PROPERTY:"property ",
	TIME_ASPECT:"time aspect ",
	EPISODICITY:"episodicity ",
	LOCATION:"location ",
	PATHOLOGICAL_PROCESS:"pathological process ",
	COMMUNICATION_WITH_WOUND:"communication with wound ",
	PROCEDURE_CONTEXT:"procedure context ",
	FINDING_INFORMER:"finding informer",
	HAS_DISPOSITION:"has disposition",
	HAS_MANUFACTURED_DOSE_FORM:"has manufactured dose form",
	HAS_BASIS_OF_STRENGTH_SUBSTANCE:"has basis of strength substance",
	HAS_PRESENTATION_STRENGTH_NUMERATOR_VALUE:"has presentation strength numerator value",
	HAS_PRESENTATION_STRENGTH_NUMERATOR_UNIT:"has presentation strength numerator unit",
	HAS_PRESENTATION_STRENGTH_DENOMINATOR_VALUE:"has presentation strength denominator value",
	HAS_PRESENTATION_STRENGTH_DENOMINATOR_UNIT:"has presentation strength denominator unit",
	HAS_BASIC_DOSE_FORM:"has basic dose form",
	HAS_CONCENTRATION_STRENGTH_DENOMINATOR_UNIT:"has concentration strength denominator unit",
	HAS_CONCENTRATION_STRENGTH_DENOMINATOR_VALUE:"has concentration strength denominator value",
	HAS_CONCENTRATION_STRENGTH_NUMERATOR_UNIT:"has concentration strength numerator unit",
	HAS_CONCENTRATION_STRENGTH_NUMERATOR_VALUE:"has concentration strength numerator value",
	HAS_DOSE_FORM_ADMINISTRATION_METHOD:"has dose form administration method",
	HAS_DOSE_FORM_INTENDED_SITE:"has dose form intended site",
	HAS_DOSE_FORM_RELEASE_CHARACTERISTIC:"has dose form release characteristic",
	HAS_DOSE_FORM_TRANSFORMATION:"has dose form transformation",
	HAS_STATE_OF_MATTER:"has state of matter",
	HAS_INGREDIENT:"has ingredient",
	HAS_PRECISE_ACTIVE_INGREDIENT:"has precise active ingredient",
	IS_MODIFICATION_OF:"is modification of"
};


$(document).ready(function() {
	resetControls();
});

function resetControls() {

	document.getElementById("forState").value = "ACTIVE";
	document.getElementById("forSemanticTag").value = "ALL";
	document.getElementById("forAcceptability").value = "SYNONYMS";
	document.getElementById("txtreturnlimit").value = "-1";
	document.getElementById("conceptId").value = "";
	document.getElementById("langRefset").value="US";
	document.getElementById("cptId").value = "";
	document.getElementById('conResult').value = "";
	document.getElementById("relation").value = "IS_A";
	document.getElementById("srcTgt").value = "source";

	$("#blankConceptIdLookup").hide();
	$("#wrongConceptIdLookup").hide();
	$("#blankConceptIdRelation").hide();
	$("#wrongConceptIdRelation").hide();	
}

function lookupByConcept(conceptId,langRefset,targetSpanId) {
	var dataValue = document.getElementById(conceptId).value;
	var langrefset= enumLANGREFSET[document.getElementById(langRefset).value];
	
		$("#conceptdetails").remove();
		
		$("#blankConceptIdLookup").hide();
		$("#wrongConceptIdLookup").hide();

	if (dataValue.trim() == '') {
		$("#conceptdetails").remove();
		$("#blankConceptIdLookup").show();
		$("#wrongConceptIdLookup").hide();
		var txtBox = document.getElementById(conceptId);
		txtBox.focus();
		return;
	}

	if (!(dataValue.match(/^[0-9]+$/))) {
		$("#conceptdetails").remove();
		$("#blankConceptIdLookup").hide();
		$("#wrongConceptIdLookup").show();		
		var txtBox = document.getElementById(conceptId);
		txtBox.focus();
		return;
	}

	// Call ur webservice here
	$
			.ajax({
				type : "GET",
				url : "http://localhost:8080/csnoserv/api/lookup/concept", // replace
				// with
				// ur
				// service
				// call
				//dataType : "text/jsonp",
				crossDomain : true,
				data : {
					"id" : dataValue,
					"langrefset" : langrefset
				},
				success : function(data, textStatus, jqXHR) {
					var htmlData = '';
					var jsonData = data;
					if (jsonData != null) {
						if (data.conceptId == 0) {
							message('Invalid Concept ID');
							return;
						}
						if (jsonData.conceptId == 'null') {
							$("#conceptdetails").remove();
							message('Please enter a valid Concept ID');
						} else {
							htmlData = '<table id="conceptdetails">';
							var status = '';
							if (jsonData.active == true)
								status = "ACTIVE";
							else
								status = "INACTIVE";

							htmlData += '<tr class="conId1"><th class="conTh">Concept ID</th><td class="conDtls">'
									+ jsonData.conceptId + '</td></tr>';
							htmlData += '<tr class="conId1"><th  class="conTh">Fully Specified Name</th><td class="conDtls">'
									+ jsonData.fsn + '</td></tr>';
							htmlData += '<tr class="conId1"><th class="conTh">Status</th><td class="conDtls">'
									+ status + '</td></tr>';
							htmlData += '<tr class="conId1"><th  class="conTh" style="vertical-align:top;">Synonyms</th><td  class="conDtls" rowspan="'
									+ jsonData.descriptions + '"><table>';
									if(jsonData.descriptions.length>0)
									{
							for (var index = 0; index < jsonData.descriptions.length; index++) {
								htmlData += '<tr><td>'
										+ jsonData.descriptions[index].term
										+ '</td></tr>';
									}}
									else{
										htmlData += '<tr><td style="color:red;">'
										+ "Description not found for specified Language"
										+ '</td></tr>';
									}
							htmlData += '</table></td></tr></table>';
							targetSpanId = '#' + targetSpanId;
							$(targetSpanId).html(htmlData);
						}

					} else {
						$("#wrongConceptIdLookup").show();
					}
				},
				error : function(jqXHR, textStatus, errorThrown) {
					$("#wrongConceptIdLookup").show();
					console.log(textStatus);
				}
			});
}

function lookupByConceptRelation(cptId, relation, srcTgt, targetSpanId) {

	$("#blankConceptIdRelation").hide();
	$("#wrongConceptIdRelation").hide();
	
	$("#relconcept").remove();

	var id = document.getElementById(cptId).value;
	if (id.trim() == '') {
		$("#relconcept").remove();	
		$("#blankConceptIdRelation").show();
		$("#wrongConceptIdRelation").hide();	
		var txtBox = document.getElementById(cptId);
		txtBox.focus();
		return;
	}
	var relationV = document.getElementById(relation).value;
	var direction = document.getElementById(srcTgt).value;	
	if (!(id.match(/^[0-9]+$/))) {
		$("#relconcept").remove();
		$("#blankConceptIdRelation").hide();
		$("#wrongConceptIdRelation").show();
		var txtBox = document.getElementById(conceptId);
		txtBox.focus();
		return;
	}
	
	$
			.ajax({
				type : "GET",
				url : "http://localhost:8080/csnoserv/api/lookup/relationship",
				// replace with your service call
				// url:"http://localhost:8080/csnoserv/api/lookup/relationship",
				//dataType : "text/jsonp",
				crossDomain : true,
				data : {
					"id" : id,
					"relation" : enumRELATIONSHIP[relationV],
					"direction" : direction,
					
				},				
				success : function(data, textStatus, jqXHR) {					
					var htmlData = '';

					var jsonData = data;
					if (jsonData != null) {
						if (jsonData.length > 0) {
							htmlData = '<br/><table id="relconcept">';
							htmlData += '<tr><th>' + 'Related Concepts'
									+ '</th></tr>';

							for (var index = 0; index < jsonData.length; index++) {
								htmlData += '<tr><td>' + jsonData[index].id+'</td>'+'<td>'+jsonData[index].fullySpecifiedName
										+ '</td></tr>';
							}
							htmlData += '</table>';
							targetspanId = '#' + targetSpanId;
							$(targetspanId).html(htmlData);
						} else {
							$("#relconcept").remove();
							$("#wrongConceptIdRelation").show();
						}
					} else {
						$("#relconcept").remove();
						$("#wrongConceptIdRelation").show();
					}
				},
				error : function(jqXHR, textStatus, errorThrown) {
					$("#wrongConceptIdRelation").show();
					console.log(textStatus);													
				}

			});

}

function infoDialog(dialogCode) {
	var infoDialogHTML = '';
	if (dialogCode == 'searchCtrl') {		
		infoDialogHTML = infoDialogHTML
				+ '<ol><li style="margin-left: 20px">Add following javascripts in your web page : <ul><li style="margin-left: 40px">jquery.js</li><li style="margin-left: 40px">jquery-ui.custom.min.js</li><li style="margin-left: 40px">jquery.autocomplete.js</li></ul></li>'
				+ '<li style="margin-left: 20px">Add following CSNOCtrl scripts in your web page : <ul><li style="margin-left: 40px">searchtool.js</li><li style="margin-left: 40px">searchtool.css</li></ul></li>'
				+ '<li style="margin-left: 20px;">Call <i>selectSNOMEDCT(state_IN,semantictag_IN,acceptability_IN,returnlimit_IN,refsetid_IN,parentid_IN,callback)</i> function to view CSNOCtrl dialog box.'
				+ '<ul><li  style="margin-left: 20px;">Parameter Description</li></ul>'
				+ '<ol><li  style="margin-left: 40px;"><b>state_IN</b>-	Defines the state of concept. Refer enumSTATE in searchtool.js to pass values for the state_IN parameter. Possible values for state_IN parameter are as follows-<ul><b>ACTIVE</b> - It will return only active components.</ul><ul><b>INACTIVE</b> - It will return only inactive components.</ul><ul><b>BOTH</b> -It will return active and inactive components.</ul></li>'
				+ '<li style="margin-left: 40px;"><b>semantictag_IN</b>-	Defines semantic tag of the concept. Refer enumSEMANTICTAG in searchtool.js to pass values for the semantictag_IN parameter.Possible values for semantictag_IN parameter are as follows-<ul><b>ALL</b> - It will search for SNOMED CT terms in all semantic tags</ul><ul>Other possible values are- PROCEDURE,DISORDER,BODY_STRUCTURE,etc.</ul></li>'
				+ '<li style="margin-left: 40px;"><b>acceptability_IN</b>-	Refer enumACCEPTABILITY in searchtool.js to pass values for the acceptability_IN parameter. Possible values for acceptability_IN parameter are as follows-<ul><b>PREFERRED</b> - If acceptability_IN is PREFERRED, only FSN and Preferred Terms for a given term shall be fetched.</ul><ul><b>PREFERRED_EXCLUDING_FSN</b> - Only Preferred Terms excluding FSN for given term shall be fetched.</ul><ul><b>SYNONYMS</b> - Only synonyms for the given term shall be fetched.</ul><ul><b>ACCEPTABLE</b> - Only Acceptable Terms for given term shall be fetched. </ul><ul><b>ALL</b> - It will fetch for all SNOMED CT terms related to the search term, irrespective of their acceptability value.</ul></li>'
				+ '<li style="margin-left: 40px;"><b>refsetid_IN</b>-	Defines Refset Identifier. For Search through whole SNOMED CT terminology refsetid is null. For Search through specific Refset refsetid should be a numeric value.</li>'
				+ '<li style="margin-left: 40px;"><b>parentid_IN</b>-	Defines Concept Identifier. For Search through whole SNOMED CT terminology parentid is null. For Search through all descendants of a Specific Concept, parentid should be a numeric value.Coma seprated mutiple values can also be provide.</li>'
				+ '<li style="margin-left: 40px;"><b>returnlimit_IN</b>-	Defines the maximum number of matching terms to be fetched from the SNOMED CT repository.For displaying all results, returnlimit should be -1.</li>'
				+ '<li style="margin-left: 40px;"><b>fullconcept</b>-	Defines whether you want full details regarding concept.For displaying full results, fullconcept value should be true.</li>'
				+ '<li style="margin-left: 40px;"><b>callback</b>-	It will contain the definition of the callback function'
				+ ' used to retrieve return value/result from the <i>selectSNOMEDCT</i> function.<br>The result includes Concept ID,Description ID'
				+ ' and Description of the selected concept from SNOMED CT repository.<br>Callback function has to be defined for '
				+ ' user defined HTML page.<br/><div class="code">var callback =function(selectedSNOMEDTerm){setValue'
				+ ' (selectedSNOMEDTerm);};<br/>function setValue(selectedSNOMEDTerm)<br>{<p style="color:green;text-align:justify;">'
				+ '&nbsp;/* Parameter selectedSNOMEDTerm contains Concept ID,Description ID and Description.User can manipulate the string or edit the '
				+ 'function definition as per his requirement*/</p>&nbsp;document.getElementById(HTMLcontrolid).html=selectedSNOMEDTerm;<br>}'
				+ '<br></div>The function shall contain only 1 parameter <i>selectedSNOMEDTerm</i> that refers to the result including'
				+ ' Concept ID,Description ID and Description.<br>User will have to define a function like <i>setValue</i> in the callback function' 
				+ ' to set the return value <i>selectedSNOMEDTerm</i> in some HTML control of the web page.<br>For different HTML controls' 
				+ ', user will have to define different callback functions.</li>'
				+ '</ol>';
	}
	if (dialogCode == 'conceptLookup') {
		infoDialogHTML = infoDialogHTML
				
		+ '<ol><li style="margin-left: 20px">Add following javascripts in your web page : <ul><li style="margin-left: 40px">jquery.js</li><li style="margin-left: 40px">jquery-ui.custom.min.js</li></ul></li>'
		+ '<li style="margin-left: 20px">Add following CSNOCtrl scripts in your web page : <ul><li style="margin-left: 40px">demo.js</li></ul></li>'
		+ '<li style="margin-left: 20px;">Call <i>lookupByConcept(conceptId,langRefset,targetSpanId)</i> function to get concept details.'
		+ '<ul><li  style="margin-left: 20px;">Parameter Description</li></ul>'
		+ '<ol><li  style="margin-left: 40px;"><b>conceptId</b>-	Defines the SNOMED CT Concept Identifier.</ul></li>'
		+ '<li style="margin-left: 40px;"><b>langRefset</b>-	Defines language refset. Refer enumLANGREFSET in demo.js to pass values for the langRefset parameter. Possible values for langRefset parameter are as follows-<ul><b>US</b> - It will provide concept details in us english</ul><ul><b>UK</b> - It will provide concept details in uk english.</ul></li>'
		+ '<li style="margin-left: 40px;"><b>targetSpanId</b>-	Defines the span id where to display concept details.'		
		+ ' used to retrieve return value/result from the <i>lookupByConcept</i> function.<br>The result includes Concept ID,Fully Specified Name,'
		+ ' Status and Synonyms of the concept from SNOMED CT repository.'
		+ '</li>'
		+ '</ol>';
		}

	if (dialogCode == 'conceptRelationLookup') {
		infoDialogHTML = infoDialogHTML
		+ '<ol><li style="margin-left: 20px">Add following javascripts in your web page : <ul><li style="margin-left: 40px">jquery.js</li><li style="margin-left: 40px">jquery-ui.custom.min.js</li></ul></li>'
		+ '<li style="margin-left: 20px">Add following CSNOCtrl scripts in your web page : <ul><li style="margin-left: 40px">demo.js</li></ul></li>'
		+ '<li style="margin-left: 20px;">Call <i>lookupByConceptRelation(conceptControlID,relationControlID,directionControlID,targetSpanConrolID)</i>  function for displaying the Ids of the related SNOMED CT concepts.'
		+ '<ul><li  style="margin-left: 20px;">Parameter Description</li></ul>'
		+ '<ol><li  style="margin-left: 40px;"><b>conceptControlID</b>-	Defines the SNOMED CT Concept Identifier.</ul></li>'
		+ '<li style="margin-left: 40px;"><b>relationControlID</b>-	Defines type of relation.</ul></li>'
		+ '<li style="margin-left: 40px;"><b>directionControlID</b>-	Defines direction of relation.'
		+ '<li style="margin-left: 40px;"><b>targetSpanConrolID</b>-	Defines the span id where to display concept details.'
		+ ' used to retrieve return value/result from the <i>lookupByConceptRelation</i> function.<br>The result includes Concept ID,Fully Specified Name,'
		+ ' of the concept from SNOMED CT repository.'
		+ '</li>'
		+ '</ol>';
	}

	infoDialogHTML = infoDialogHTML
			+ '<span width style="font-size:x-small;margin-left: 10px">Note:- CSNOCtrl js and css are available with CSNOCtrl downloadable package</span>';
	$("#dialog-howto").html(infoDialogHTML);
	$("#dialog-howto").dialog({
		modal : true,
		width : 550,
		height : 330,
		close: function( event, ui ) {
			$(".ui-dialog").remove();
		}
	});
	// Adding this if else again because any option cannot be added before above
	// dialog call which initializes the dialog.
	if (dialogCode == 'searchCtrl') {
		$("#dialog-howto").dialog("option", "width", 550);
		$("#dialog-howto").dialog("option", "height", 600);
		$('#dialog-howto').dialog('option', 'title',
				'How To Use CSNOCtrl: Search');

	} else if (dialogCode == 'conceptLookup') {
		$("#dialog-howto").dialog("option", "width", 550);
		$("#dialog-howto").dialog("option", "height", 300);
		$('#dialog-howto').dialog('option', 'title',
				'How To Use CSNOCtrl: LookUp');
	} else if (dialogCode == 'conceptRelationLookup') {
		$("#dialog-howto").dialog("option", "width", 550);
		$("#dialog-howto").dialog("option", "height", 300);
		$('#dialog-howto').dialog('option', 'title',
				'How To Use CSNOCtrl: Getting Concept Relationships');
	}

	$("#dialog-howto").dialog('option', 'position', 'center');
}

