
$(document).ready(function () {
	var visit_owner_search = new Bloodhound({
		datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
		queryTokenizer: Bloodhound.tokenizers.whitespace,
		prefetch: 'remote.php?op=owner/search/%QUERY&encode=json',
		remote: {
			url: 'remote.php?op=owner/search/%QUERY&encode=json',
			wildcard: '%QUERY'
		}
	});

	var visit_reason_search = new Bloodhound({
		datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
		queryTokenizer: Bloodhound.tokenizers.whitespace,
		prefetch: 'remote.php?op=visit/search/reason/%QUERY&encode=json',
		remote: {
			url: 'remote.php?op=visit/search/reason/%QUERY&encode=json',
			wildcard: '%QUERY'
		}
	});

	var visit_diagnosis_search = new Bloodhound({
		datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
		queryTokenizer: Bloodhound.tokenizers.whitespace,
		prefetch: 'remote.php?op=visit/search/diagnosis/%QUERY&encode=json',
		remote: {
			url: 'remote.php?op=visit/search/diagnosis/%QUERY&encode=json',
			wildcard: '%QUERY'
		}
	});

	var visit_drug_search = new Bloodhound({
		datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
		queryTokenizer: Bloodhound.tokenizers.whitespace,
		prefetch: 'remote.php?op=visit/search/drug/%QUERY&encode=json',
		remote: {
			url: 'remote.php?op=visit/search/drug/%QUERY&encode=json',
			wildcard: '%QUERY'
		}
	});

	var visit_diagnostic_search = new Bloodhound({
		datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
		queryTokenizer: Bloodhound.tokenizers.whitespace,
		prefetch: 'remote.php?op=visit/search/diagnostic/%QUERY&encode=json',
		remote: {
			url: 'remote.php?op=visit/search/diagnostic/%QUERY&encode=json',
			wildcard: '%QUERY'
		}
	});

	var visit_procedure_search = new Bloodhound({
		datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
		queryTokenizer: Bloodhound.tokenizers.whitespace,
		prefetch: 'remote.php?op=visit/search/procedure/%QUERY&encode=json',
		remote: {
			url: 'remote.php?op=visit/search/procedure/%QUERY&encode=json',
			wildcard: '%QUERY'
		}
	});

	// initialize popover elements
	$('[data-toggle="popover"]').popover({
		placement: 'auto bottom'
	});

	/**
	 * EVENTS
	 */
	// intercept CTRL + S to save visit content
	$(window).keypress(function (event) {
		if (!(event.which == 115 && event.ctrlKey) && !(event.which == 19))
			return true;
		visit_save();
		event.preventDefault();
		return false;
	});


	// save button action: call visit_save function
	$("#visit-action-save").click(function () {
		visit_save();
	});
	
	// delete button action: call visit_delete function
	$("#visit-action-delete").click(function () {
		visit_delete();
	});


	$("#owner-reload").click( function() {
		owner_load(pet.oid);
	});

	$("#owner-edit").click( function() {
		if (typeof owner.oid === 'undefined') {
			owner.oid = 'NULL';
		}
		owner_form_load(owner.oid);
	});
	
	
	$("#button-owner-save").click(function () {
		owner_save();
	});


	// detect a typeahead input for the owner and get values remotely
	$('#owner-search').typeahead(null, {
		name: 'owner',
		display: 'value',
		source: visit_owner_search
	}).bind("typeahead:selected", function (obj, datum, name) {
		oid = datum.oid;
		owner_load( oid );
	});


	// detect a typeahead input for the reason for visit and get values remotely
	$('#reason-search').typeahead(null, {
		name: 'reason',
		display: 'value',
		source: visit_reason_search
	}).bind("typeahead:selected", function (obj, datum, name) {
		$('#panel-reason-data').html('<div id="#panel-reason-data-result"><input type="hidden" value="' + datum.id + '" id="reason-for-visit" name="reason-for-visit">' + datum.value + ' <a href="#" class="glyphicon glyphicon-remove-sign" aria-hidden="true" onclick="$(this).parent().remove();"></a></div>');
		$("#reason-search").typeahead("val", "");
	});

	// detect a typeahead input for diagnosis and get values remotely
	$('#diagnosis-search').typeahead(null, {
		name: 'diagnosis',
		display: 'value',
		source: visit_diagnosis_search
	}).bind("typeahead:selected", function (obj, datum, name) {
		$('#panel-diagnosis-data').html('<div id="#panel-diagnosis-data-result"><input type="hidden" value="' + datum.id + '" id="diagnosis" name="diagnosis">' + datum.value + ' <a href="#" class="glyphicon glyphicon-remove-sign" aria-hidden="true" onclick="$(this).parent().remove();"></a></div>');
		$("#diagnosis-search").typeahead("val", "");
	});

	// detect a typeahead input for drugs and get values remotely
	$('#drug-search').typeahead(null, {
		name: 'drug',
		display: 'value',
		source: visit_drug_search
	}).bind("typeahead:selected", function (obj, datum, name) {
		$('#panel-drug-data').append('<div class="drug-row"><input type="hidden" value="' + datum.id + '" id="did" name="did"><input type="text" value="1" id="drug-qty" name="drug-qty" size="2">' + datum.value + ' <a href="#" class="glyphicon glyphicon-remove-sign" aria-hidden="true" onclick="$(this).parent().remove();"></a></div>');
		$("#drug-search").typeahead("val", "");
	});

	// detect a typeahead input for drugs and get values remotely
	$('#diagnostic-search').typeahead(null, {
		name: 'diagnostic',
		display: 'value',
		source: visit_diagnostic_search
	}).bind("typeahead:selected", function (obj, datum, name) {
		$('#panel-diagnostic-data').append('<div class="diagnostic-row"><input type="hidden" value="' + datum.id + '" id="diagnostic-test" name="diagnostic-test">' + datum.value + ' <a href="#" class="glyphicon glyphicon-remove-sign" aria-hidden="true" onclick="$(this).parent().remove();" ></a></div>');
		$("#diagnostic-search").typeahead("val", "");
	});

	// detect a typeahead input for procedures and get values remotely
	$('#procedure-search').typeahead(null, {
		name: 'procedure',
		display: 'value',
		source: visit_procedure_search
	}).bind("typeahead:selected", function (obj, datum, name) {
		$('#panel-procedure-data').append('<div class="procedure-row"><input type="hidden" value="' + datum.id + '" id="procedure" name="procedure">' + datum.value + '<a href="#" class="glyphicon glyphicon-remove-sign" aria-hidden="true" onclick="$(this).parent().remove();" ></a></div>');
		$("#procedure-search").typeahead("val", "");
	});


	/**
	 * GENERAL LOGIC
	 */

	$("#panel-pet-data").html(pet.name + ' (' + pet.gender + ')' + '<br>');
	$("#panel-pet-data").append(pet.description);

	$('#pet-popover').attr('data-content', pet.html);

	owner_load(pet.oid);
	

});

/*
 * Load Visit detail with remote data collected c/o Json call
 */
function visit_load(id) {
	$.ajax({
		url: "remote.php",
		type: "GET",
		data: "op=visit/get/" + id + '&encode=json',
		success: function (data) {
			visit = JSON.parse(data);
		}
	});
}

/**
 * Check and save a visit object
 */
function visit_save() {
	// FORM VALIDATION
	var valid_form_data = true;
	var required_fields = '<br>';

	// validate owner
	if (jQuery.isEmptyObject(owner) == true) {
		valid_form_data = false;
		required_fields += $("#owner-search").prop('placeholder') + '<br>';
	}


	// check note title if is required and not empty
	var note_title = $.trim($("#note-title").val());
	if ($("#note-title").prop('required') == true && note_title.length == 0) {
		valid_form_data = false;
		required_fields += $("#note-title").prop('placeholder') + '<br>';
	}


	// check note text if is required and not empty
	var note_text = $.trim($("#note-text").val());
	if ($("#note-text").prop('required') == true && note_text.length == 0) {
		valid_form_data = false;
		required_fields += $("#note-text").prop('placeholder') + '<br>';
	}


	// check if a reason for visit has been set
	var reason_id = $.trim($("#reason-for-visit").val());
	if ($("#reason-search").prop('required') == true && reason_id.length == 0) {
		valid_form_data = false;
		required_fields += $("#reason-search").prop('placeholder') + '<br>';
	}

	// check if a diagnosis for visit has been set
	var diagnosis_id = $.trim($("#diagnosis").val());
	if ($("#diagnosis-search").prop('required') === true && diagnosis_id.length === 0) {
		valid_form_data = false;
		required_fields += $("#diagnosis-search").prop('placeholder') + '<br>';
	}
	
	// check if a procedure for visit has been set
	var procedure_id = $.trim($("#procedure").val());
	if ($("#procedure-search").prop('required') === true && procedure_id.length === 0) {
		valid_form_data = false;
		required_fields += $("#procedure-search").prop('placeholder') + '<br>';
	}


	visit.pid = pet.pid;
	visit.oid = owner.oid;
	visit.reason_id = reason_id;
	visit.diagnosis_id = diagnosis_id;
	visit.teaser = $("#visit-teaser").val();

	visit.status_id = $("#status-id").prop('selected', true).val();
	visit.type_id = $("#type-id").prop('selected', true).val();
	
	visit.notes = {"title": $("#note-title").val(), "text": $("#note-text").val()};

	// create drugs array of JSON objects
	visit.drugs = [];
	$(".drug-row").each(function () {
		var did = $(this).children("input[name='did']").val();
		var drug_qty = $(this).children("input[name='drug-qty']").val();

		if (did) {
			// check id Drug quantity is a number (integer) and positive 
			if (Math.floor(drug_qty) != drug_qty && $.isNumeric(drug_qty) == false) {
				valid_form_data = false;
				required_fields += $("#drug-search").prop('placeholder') + ' (quantity) <br>';
			} else {
				visit.drugs.push({"did": did, "qty": drug_qty});
			}
		}

	});

	// create diagnostic_test array of JSON objects
	visit.diagnostic_tests = [];
	$(".diagnostic-row").each(function () {
		var diagnostic = $(this).children("input[name='diagnostic-test']").val();
		if (diagnostic) {
			visit.diagnostic_tests.push({"id": diagnostic});
		}

	});

	// create procedure array of JSON objects
	visit.procedures = [];
	$(".procedure-row").each(function () {
		var procedure = $(this).children("input[name='procedure']").val();
		if (procedure) {
			visit.procedures.push({"id": procedure});
		}
	});

	// check and save the visit remotely
	// create the Bootbox alert and stop the saving process
	if (valid_form_data === false) {
		bootbox.alert({
			title: translated_messages[0],
			message: translated_messages[1] + required_fields
		});
	} else {
		// validation ok; sending visit data to server for saving into database
		// show dialog message "Are you sure to save a new visit ?"
		bootbox.confirm( translated_messages[2], function(result){
			if(result){
				// show message "Visit save in progress..."
				waitingDialog.show( translated_messages[3], {dialogSize: 'sm', progressType: 'warning'});
				$.ajax({
					type: 'POST',
					url: 'remote.php?op=visit/save&encode=json',
					data: {json: JSON.stringify(visit)},
					success: function (datum) {
						waitingDialog.hide();
						visit = JSON.parse(datum);
						window.setTimeout( function() {
							window.location.href = 'visit.php?vid=' + visit.vid;
						} );
					}
				});
			}
		})
		
	}

}


function visit_delete(){
	// validation ok; sending visit data to server for saving into database
	// show dialog message "Are you sure to save a new visit ?"
	bootbox.confirm( translated_messages[5], function(result){
		if(result){
			// show message "Visit save in progress..."
			waitingDialog.show( translated_messages[3], {dialogSize: 'sm', progressType: 'warning'});
			$.ajax({
				type: 'POST',
				url: 'remote.php?op=visit/delete&encode=json',
				data: {json: JSON.stringify(visit)},
				success: function (datum) {
					waitingDialog.hide();
					visit = JSON.parse(datum);
					window.setTimeout( function() {
						window.location.href = 'visit.php?vid=' + visit.vid;
					} );
				}
			});
		}
	});
}

function owner_load( id ) {
	$.ajax({
		url: "remote.php",
		type: "GET",
		data: "op=owner/get/" + id + '&encode=json',
		success: function (data) {

			owner = JSON.parse( data );

			if (jQuery.isEmptyObject(owner) == false) {


				$("#panel-owner-data").html(owner.firstname + ', ' + owner.lastname + '<br/>');
				$("#panel-owner-data").append(owner.address + ' - ' + owner.zip + ', ' + owner.city + '<br/>');
				$("#panel-owner-data").append('ph' + owner.phone + '<br/>');
				$("#panel-owner-data").append('<a href="mailto:' + owner.email + '">' + owner.email + '</a>');


				$("#owner-search").typeahead("val", "");
			} else {
				// empty owner: put some code here
			}
		}
	});
}



function owner_form_load(oid) {
	// get oid from database and load owner details
	$.get('remote.php?op=owner/form/' + oid + '&encode=html', function (data) {
		oid = data;
		$("#modal-owner-body").html(data);
	});
}

/*
function owner_panel_load(id) {
	$.ajax({
		url: "remote.php",
		type: "GET",
		data: "op=owner/get/" + id,
		success: function (data) {
			$("#panel-owner-data").html(data);
			$("#owner-search").typeahead("val", "");
		}
	});
}
*/

/**
 * save a owner remotely
 * 
 * @returns void
 */
function owner_save() {
	var valid_form_data = $('#owner-form').parsley().isValid();
	var parsley_form_fields = $('#owner-form').parsley().fields;
	
	
	if( valid_form_data == false ){
		var required_fields = '<br>';
	
		$.each( parsley_form_fields, function(key, field){
			if ( field.validationResult != true ){
				required_fields += field.$element[0].name + '<br>';
			}
		});
		bootbox.alert({
			title: 'alert',
			message: translated_messages[1] + required_fields
		});
	}else{
		// validation ok; sending owner data to server for saving into database
		// show message "Visit save in progress..."
		waitingDialog.show( translated_messages[4], {dialogSize: 'sm', progressType: 'warning'});

		owner.oid			= $("#oid").val();
		owner.country_id	= $("#country-id").prop('selected', true).val();
		owner.firstname		= $("#firstname").val();
		owner.lastname		= $("#lastname").val();
		owner.address		= $("#address").val();
		owner.zip			= $("#zip").val();
		owner.city			= $("#city").val();
		owner.ssn			= $("#ssn").val();
		owner.phone			= $("#phone").val();
		owner.mobile		= $("#mobile").val();
		owner.email			= $("#email").val();

		
		// sending data to server for validation
		$.ajax({
			type: 'POST',
			url: 'remote.php?op=owner/save&encode=json',
			data: {json: JSON.stringify(owner)},
			success: function ( rv ) {
				waitingDialog.hide();
				if( rv != false ){
					owner.oid = rv;
					owner_load( owner.oid );
					$("#modal-owner").modal("hide");
				}
			}
		});
	}
}

