//facility js

$(document).on("click","input#editExistingButton",function(evt){
	if(!$("input[name='searchFacilityID']:checked").val()){
		evt.preventDefault();
		alert("Please select an option before proceeding");
	}
})

//copy/paste function
$(document).on("click","span#fac-rrid-citation i, span#fac-grantnumber-citation i, span.fac-instrument-rrid i",function(){
	var ele = $(this).parent().attr("id");
	var id = $(this).prev().attr("id");
	console.log(ele+":"+id);
	copyPaste(ele,id);
});	

function copyPaste(ele,id) {
	
  var copyText = $("input#"+id).val();

  setTimeout(function() {
	  $(".feedback-bubble").fadeOut().empty();
	}, 3000);


  navigator.clipboard.writeText(copyText)
   	.then(() => {
        //alert("successfully copied");
        $("span#"+ele+" i").append("<span class=feedback-bubble>Copied</span>");
      })
    .catch(() => {
        //alert("something went wrong");
        $("span#"+ele+" i").append("<span class=feedback-bubble>Error</span>");
      });

  //alert("Copied the text: " + copyText);
}

	
//for tracking website clicks on listings
$("a.websiteLink").click(function(event) {
	var FacilityID = $(this).attr('facilityid');
	
	$.ajax({
			url: "ajax/facility.ajax.php",
			type: "POST",
			data: {FacilityID:FacilityID,Link:'Clicked'},
			cache: false,
			success: function(data){
			},
			error: function(jqXHR, textStatus, errorThrown){
				//alert("Error Adding Service.");          
			}
		  //dataType: 'json'
	});	
	
});

//citing rrid ui on listings

	$("#rrid-facility-cite").click(function() {
		$(this).toggleClass('cite-clicked');
		$("#fac-rrid-citation").toggle();
	});
	
	$(document).on("click",".rrid-instrument-cite", function() {
		//var counter = $(this).prev().children("#instrument_rrid_index").val();
		$(this).toggleClass('cite-clicked');
		var counter = $(this).parent().children("p#instrument_rrid").children("input#instrument_rrid_index").val();
		var fieldID = "#fac-instrument-rrid-citation-"+counter;
		
		$(fieldID).toggle();
	});
	
	$("#grantnumber-cite").click(function() {
		$("#fac-grantnumber-citation").toggle();
	});
	

//facility contact form
$(document).on("click","#contact-form.contact-lister #close",function(){
//$("#contact-form.contact-lister #close").click(function() {
		//$("#title").replaceWith("<td id=title colspan=2>Contact<td>");
		$("div#errorMsg").empty();
		$("#contact-form.contact-lister").hide();
		$('input#SenderEmail').val('');
		$('input#SenderPhone').val('');
		$('textarea#SenderMessage').val('');
		$('input#submissionClicked').remove();
		//$("div.contact-admin").hide();
		//$("div.contact-lister").remove();
		$("div#background").remove();
		$("input#SenderEmail, textarea#SenderMessage").css("background-color","unset");
	});

$(document).on("click", "div.contact-lister #ContactSubmit", function(evt) {
	evt.preventDefault(evt);
	$(".contact-lister").append("<input type=hidden id=submissionClicked value='valid'>");
});
	
$(document).on("change",".contact-lister input#SenderEmail, .contact-lister textarea#SenderMessage",function(){
	$(this).css("background-color","unset");
	$(".contact-lister div#errorMsg").empty();
});	
	
$(document).on("click","div.contactInfo",function(){
		$("body").append("<div id=background></div>");
		var clickName = $(this).text();

		$("#contact-form.contact-lister").show();
		$("#title").append(" "+clickName);
		//$("#myannouncementID").val(announcementID);
		
});

$(document).on("click","div.contact-lister #ContactSubmit",function(evt) {
	evt.preventDefault(evt);
	var email = $('.contact-lister input#SenderEmail').val();
	var phone = $('.contact-lister input#SenderPhone').val();
	var message = $('.contact-lister textarea#SenderMessage').val();
	var submissionClicked = $('.contact-lister input#submissionClicked').val();
	// var fid = $('.contact-lister input#FacilityID').val();
	
	$("div#errorMsg").empty();
	
	$.ajax({
		url: "ajax/facility.ajax.php",
		type: "POST",
		cache: false,
		data: { SendEmail: 1,SenderEmail:email,SenderPhone:phone,SenderMessage:message,SubmissionClicked:submissionClicked },
		success: function(data){
			console.log(data);
			if(data.substring(0,5)=='ERROR'){
				//if data starts with ERROR
				$("div#errorMsg").append(data);
				
				if($('.contact-lister input#SenderEmail').val()==''){
					$('.contact-lister input#SenderEmail').css("background-color","red");
				}
				if($('.contact-lister textarea#SenderMessage').val()==''){
					$('.contact-lister textarea#SenderMessage').css("background-color","red");
				}
				
			} else if(data.substring(0,4)=='http'){
				 //else if data starts with uri remove form then refresh page
				
				$("body").append("<div id='dialog-message' title='Message Sent'>Your email to the Facility was sent.</p></div>");
		    	$( function() {
		    	    $( "#dialog-message" ).dialog({
		    	      modal: true,
		    	      classes: {"ui-dialog": "cm-header"},
		    	      buttons: {
		    	        Ok: function() {
		    	          $( this ).dialog( "close" );
							$('.contact-lister input#SenderEmail').val('');
							$('.contact-lister input#SenderPhone').val('');
							$('.contact-lister textarea#SenderMessage').val('');
							$('.contact-lister input#submissionClicked').remove();
							$("div.contact-lister").hide();
							
							$("#background").remove();
							//window.location.replace(data);
		    	        }
		    	      }
		    	    });
		    	  } );
			
				
			}	
			
		},
		error: function(jqXHR, textStatus, errorThrown){
			//alert("error handler!");
			//response('');                        
		},
	  //dataType: 'json'
	});	

});

//for institute field
	 $(document).ready(function() {
	 if($('#institute_name, #institute_name_add').length){
	 	$('#institute_name, #institute_name_add').autocomplete({
		  source: function( request, response ) {
				$.ajax({
					url: "ajax/facility.ajax.php",
					type: "POST",
					data: { InstituteAutoComplete: request.term},
					success: function(data){
						response(data);
					},
					error: function(jqXHR, textStatus, errorThrown, data){
						//alert("error handler!");
					},
				  dataType: 'json'
				});
		 },
		 
		 select: function(event, ui) {
			$("#institute_name_add").val(ui.item.label);
			$("#PrimaryContactInstitution_id").val(ui.item.label);
			return false;
			}, 
			focus: function(event, ui){
				$("#institute_name").val(ui.item.label);
				return false;
			}
		 
		})
		
		.each(function(idx,ele){
		$(ele).data("ui-autocomplete")._renderItem = function( ul, item ) {
				let txt = String(item.label).replace(new RegExp(this.term, "gi"),"<span class=autocomplete-highlight>$&</span>");
				return $("<li></li>")
					.data("ui-autocomplete-item", item)
					.append("<div>" + txt + "</div>")
					.appendTo(ul);
		}
		});
	
	}
});	


