// For questionnaires page
//Don't let them unload
jQuery(window).bind('beforeunload', function(e) {
    if ($('.draggable').length > 0){
		var message = "Are you sure you want to exit this page? You appear to have an unsaved questionnaire open.";
		e.returnValue = message;
		return message;
	}
});

//This will get overridden in some circumstances.... that's fine
function append_another( selector ){
	var $new_node = $( selector ).first().clone();
	
	var random_number = (new Date).getTime();
	$new_node.find('input[type="radio"]').each(function(){
		var current_name = $(this).attr('name');
		$(this).attr('name', current_name.replace('[]','['+random_number+']'));	
	});
	
	$new_node.find('input,textarea').val('');
	$new_node.insertAfter( $( selector ).last() );
	$new_node.show(); //in case the template is hidden

	//now create a removal button
	$remover = $('<a>').addClass('remover').attr('href','#remove').html('<img src="/images/icons/remove.png" alt="[x]" title="Remove" />');
	$remover.click(function(){
		$(this).parent().remove();
	});
	$remover.appendTo($new_node);
}

function get_questionnaire_html() {

    //we need to actually modify the dom before getting .html();
    $("form.questionnaire_form input[type='radio']").each(function () {
        if (this.checked) {
            $(this).prop("defaultChecked", true);
        } else {
            $(this).prop("defaultChecked", false);
        }
    });
    $("form.questionnaire_form input[type='checkbox']").each(function () {
        if (this.checked) {
            $(this).prop("defaultChecked", true);
        } else {
            $(this).prop("defaultChecked", false);
        }
    });
    $("form.questionnaire_form input:not([type='checkbox']):not([type='radio'])").each(function () {
        $(this).prop("defaultValue", $(this).val());
    });


	//Select menus... reset defaults all at once remember for save and continue later
	$("form.questionnaire_form select option").each(function () {
        if($(this).is(':selected')){
			$(this).prop('defaultSelected',true);
		} else {
			$(this).prop('defaultSelected',false);
		}
    });

    $("form.questionnaire_form textarea").each(function () {
        $(this).prop("defaultValue", $(this).val());
    });

    return  $('.questionnaire_form').html();

}

function save_questionnaire(form_id) {

    var form = $('#' + form_id);
    $.ajax({
        type: 'POST',
        url: '/ajax/save_questionnaire.php',
        data: {
            questionnaire: $('input[name=questionnaire]').val(),
            form_data: get_questionnaire_html()
        }
    }).done(function(results) {
        results = jQuery.parseJSON(results);
        alert(results.message);
        parent.$('.load_frame').remove();
        parent.location.href=location.pathname;
    });
}

function create_save_questionnaire_button(form_id) {

    $('#' + form_id + ' .save_questionnaire').remove();
    $('.wrapper')
        .before(
        $('<a>')
            .addClass('button save_questionnaire')
            .text('Save And Continue')
            .click(function(e) {
                var form = $('#' + form_id);
                $.ajax({
                    type: 'POST',
                    url: '/ajax/save_questionnaire.php',
                    data: {
                        questionnaire: $('input[name=questionnaire]').val(),
                        form_data: get_questionnaire_html()
                    }
                }).done(function(results) {
                    results = jQuery.parseJSON(results);
                    alert(results.message);
                });
            })
    );

    create_delete_questionnaire_button(form_id);
}

function create_delete_questionnaire_button(form_id) {

    // if the input does not exist, return
    if ($('#' + form_id + ' input[name=is_existing_questionnaire]').length == 0) {
        return null;
    }

    // is_existing_questionnaire

    var button = $('<button>')
        .addClass('delete_questionnaire_draft')
        .click(function() {
            if (confirm('Are you sure you want to delete this draft? This cannot be undone')) {
                $.ajax({
                    url: '/ajax/delete_questionnaire_draft.php',
                    type: 'POST',
                    data: {
                        questionnaire: $('input[name="questionnaire"]').attr('value'),
                        rand: random_string(10)
                    }
                }).done(function(data) {

                    data = $.parseJSON(data);
                    alert(data.message);

                    if (data.result == 'success') {

                        var button_id = form_id.replace('_f_form', '');

                        $('.load_frame').remove();
                        $('.screen_cover').remove();

                        $('#'+ button_id).prev('button').show().trigger('click');
                        $('#' + button_id).remove();
                    }
                });
            }
        })
        .text('Delete Draft');

    var paragraph = $('<p>')
        .addClass('delete_questionnaire_text')
        .text('It looks like you are using a saved copy. You can continue using this draft, or delete it and start fresh.')
        .append(button);

    $('#' + form_id)
        .before(paragraph);

}

function has_required_fields(form_selector,focus_on_first) {
    var is_valid = true;
    $(form_selector).find('input[required],textarea[required],select[required]').each(function() {
      $(this).parent().parent().css({'outline':'0px solid #c00'});
      if ( $(this).is("input[type='checkbox']")){
          if( !$(this).is(":checked")){
              is_valid = false;
              $(this).parent().parent().css({'outline':'1px solid #c00'});
              if (focus_on_first===true){
                  $(this).focus();
                  return false;	
              }
          }
      }
      if ( $(this).is("input[type='radio']")){
        var name = $(this).attr("name");
          if($('input:radio[name="'+name+'"]:checked').length == 0){
              is_valid = false;
              $(this).parent().parent().css({'outline':'1px solid #c00'});
              if (focus_on_first===true){
                  $(this).focus();
                  return false;	
              }
          }
      }
      if ( $(this).val() === '' ){
          is_valid = false;
          $(this).parent().parent().css({'outline':'1px solid #c00'});
          if (focus_on_first===true){
              $(this).focus();
              return false;	
          }
      }
    });
    return is_valid;
  }


$(function() {

    // get all the buttons with "target_form" attribute, and put them into an array
    var target_forms = $('.text button[target_form]');
    var target_forms_list = [];
    $(target_forms).each(function(e) {
        target_forms_list.push($(this).attr('target_form'));
    });

    // ajax it and get the results
    $.ajax({
        type: 'POST',
        url: '/ajax/load_questionnaire.php',
        data: {
            target_forms: target_forms_list,
            rand: random_string(10)
        }
    }).done(function(results) {

        results = jQuery.parseJSON(results);
        $.each(results, function(key,value) {

            if (value.id != '') {

                var complete_button = $('<button>')
                    .addClass('button add short launcher continue_questionnaire')
                    .text('Continue Previous Form From ' + value.date)
                    .click(function(e) {
                        $(this).launch(e, $(this).attr('target_form'));
                        window.scrollTo(0,0); 
                    }).attr('target_form', value.target_form);

                //complete_button;

                $('button[target_form="' + value.target_form + '"]').after(complete_button).hide();
            }
        })
    });

});

$(document).ready(function(e) {
	//if ginger extension is added lets alert the patient to disable, it interferes with the questionnaires
	var observer = new MutationObserver(function(mutations) {
		mutations.forEach(function(mutation) {
			alertMe = 0;
			if(mutation.addedNodes[0] && mutation.addedNodes[0].classList.contains('ginger-extension-writer')) {
				if(alertMe < 1) {
					alert("Please go to your extensions and disable your Grammar and Spelling checker by Ginger before attempting to fill out questionnaires. This extension can render questionnaires unreadable." );
				}
				alert++;
			}


		});
	});

	// Notify childlist only!
	var observerConfig = {
		childList: true
	};

	var targetNode = document.body;
	observer.observe(targetNode, observerConfig);
});
