{% extends "templates/web.html" %}

{% block title %}{{ title }}{% endblock %}

{% block header %}
<h1>{{ title }}</h1>
{% endblock %}

{% block breadcrumbs %}
{% include "templates/includes/breadcrumbs.html" %}
{% endblock %}

{% block header_actions %}
  {% if frappe.form_dict.name or frappe.form_dict.new %}
    <a href="{{ cancel_url or pathname }}" class="btn btn-default btn-sm">
    		{{ _("Cancel") }}</a>
    <button type="submit" class="btn btn-primary btn-sm btn-form-submit">
    		{{ _("Submit") if frappe.form_dict.new else _("Update") }}</button>
  {% elif is_list %}
  	<div style="padding-bottom: 15px;">
	    <a href="/{{ pathname + args }}{{ delimeter }}new=1" class="btn btn-primary btn-new btn-sm">
	    {{ _("New {0}").format(_(doc_type)) }}
	    </a>
	</div>
  {% endif %}
{% endblock %}

{% block page_content %}
<div class="introduction">
	{% if introduction_text %}
	<p class="lead">{{ introduction_text }}</p>
	<hr>
	{% endif %}
</div>
{% if login_required and frappe.user=="Guest" %}
<div class="login-required">
	<div class="text-muted">
		{{ _("Please login to create a new {0}").format(_(doc_type)) }}
	</div>
	<p>
		<a href="/login?redirect-to=/{{ pathname }}" class="btn btn-primary">
			{{ _("Login") }}
		</a>
	</p>
</div>
{% elif is_list %}
	{% include "templates/includes/list/list.html" %}
	<script>{% include "templates/includes/list/list.js" %}</script>
{% else %}
<br>

{%- macro properties(field) %}
		name="{{ field.fieldname }}" id="{{ field.fieldname }}"
		{% if field.placeholder -%} placeholder="{{ _(field.placeholder) }}" {%- endif %}
		data-label="{{ _(field.label) }}" data-fieldtype="{{ field.fieldtype }}"
		{{ (field.reqd and field.fieldtype!="Attach") and "required" or "" }}
		{{ field.read_only and "disabled" or "" }}
{% endmacro -%}

{%- macro value(field) -%}{% if doc %}{{
	doc.get(field.fieldname) or
	field.default or
	frappe.form_dict.get(field.fieldname) or "" }}{% else %}{{ getCookie(field.options) or field.default or "" }}{% endif %}{%- endmacro -%}

{%- macro help(field) -%}
		{% if field.description -%}
		<span class="help-block small">{{ _(field.description) }}</span>
		{%- endif -%}
{%- endmacro %}

{% macro label(field) %}
		<label for="{{ field.fieldname }}" class="control-label text-muted small">
				{{ _(field.label) }}</label>
{% endmacro %}

{% macro render_field(field) %}
	{% if field.hidden %}
	<input type="hidden"
		name="{{ field.fieldname }}" {% if field.default -%} value="{{ field.default }}" {%- endif %}>
	{% elif field.fieldtype == "HTML" and field.options %}
	<div class="form-group">
		{{ field.options }}
	</div>
	{% elif field.fieldtype in ("Data", "Date", "Datetime") %}
	<div class="form-group">
		{{ label(field) }}
		<input type="text" class="form-control" {{ properties(field) }}
			value="{{ value(field) }}">
		{{ help(field) }}
	</div>
	{% elif field.fieldtype=="Select" %}
	<div class="form-group">
		{{ label(field) }}
		<select class="form-control" {{ properties(field) }}>
			{% for option in field.options.split("\n") -%}
			<option value="{{ option }}"
				{{ 'selected="selected"' if value(field)==option else '' }}>
				{{ option }}</option>
			{%- endfor %}
		</select>
		{{ help(field) }}
	</div>
	{% elif field.fieldtype=="Text" %}
	<div class="form-group">
		{{ label(field) }}
		<textarea class="form-control" style="height: 200px;"
		{{ properties(field) }}>{{ value(field) }}</textarea>
		{{ help(field) }}
	</div>
	{% elif field.fieldtype=="Attach" %}
	<div class="form-group">
		{{ label(field) }}
		{% if value(field) -%}
		<p class="small">
			<a href="{{ doc.get(field.fieldname) }}" target="blank">
				{{ doc.get(field.fieldname) }}
			</a>
			<br><button class="btn btn-small btn-default btn-xs
				change-attach" style="margin-top: 5px;">Change</button>
		</p>
		{%- endif %}
		<p class="{{ value(field) and 'hide' or '' }} attach-input-wrap">
			<input type="file" style="margin-top: 7px;"
				{{ properties(field) }}>
		</p>
		{{ help(field) }}
	</div>
	{% elif field.fieldtype=="Check" %}
	<div class="form-group">
		<div class="checkbox">
			<label>
				<input type="checkbox" id="{{ field.fieldname }}"
					name="{{ field.fieldname }}"
					{{ doc and doc.get(field.fieldname) and 'checked' or '' }}>
					{{ _(field.label) }}
			</label>
			{{ help(field) }}
		</div>
	</div>
	{% endif %}
{% endmacro %}

<div class="form-message text-muted hide"></div>
<form role="form"
	data-web-form="{{ name }}" data-owner="{{ doc.owner }}">
	{% if frappe.form_dict.name and web_page_link_text %}
	<div class="row">
		<div class="col-sm-9">
			<p class="text-muted">
				<a class="btn btn-default btn-sm" href="{{ doc.route }}" target="_blank">
					{{ web_page_link_text }}</a>
			</p>
		</div>
	</div>
	{% endif %}
	<input type="hidden" name="web_form" value="{{ name }}">
	<input type="hidden" name="doctype" value="{{ doc_type }}">
	{% if frappe.form_dict.name -%}
	<input type="hidden" name="name" value="{{ frappe.form_dict.name }}">
	{%- endif %}

		{% for section in layout %}
		<div class="row">
				{% for column in section %}
				<div class="col-sm-{{ (12 / (section|len))|int }}" style="max-width: 500px;">
						{% for field in column %}
								{{ render_field(field) }}
						{% endfor %}
				</div>
				{% endfor %}
		</div>
		{% endfor %}
</form>
{% if allow_comments and not frappe.form_dict.new -%}
<div class="comments">
	<br><br>
	<h3>{{ _("Comments") }}</h3>
	{% include 'templates/includes/comments/comments.html' %}
</div>
{%- endif %}
{% endif %}
<div class="padding"></div>
{% endblock %}

{% block script %}
<script>
frappe.ready(function() {
	window.file_reading = false;
		window.success_message = "{{ success_message or "" }}";
	frappe.datepicker_format = "{{ frappe.date_format.replace('yyyy', 'yy') }}";
	var $form = $("form[data-web-form='{{ name }}']");

	// read file attachment
	$form.on("change", "[type='file']", function() {
		var $input = $(this);
		if($input.attr("type")==="file") {
			var input = $input.get(0);
			var reader = new FileReader();

			input.filedata = null;
			if(input.files.length) {
				file = input.files[0];
				window.file_reading = true;
				reader.onload = function(e) {
					input.filedata = {
						"__file_attachment": 1,
						"filename": file.name,
						"dataurl": reader.result
					};
					window.file_reading = false;
				}

				reader.readAsDataURL(file);
			}
		}
	});

	// change attach
	$form.on("click", ".change-attach", function() {
		$(this).parent().addClass("hide")
			.parent().find(".attach-input-wrap").removeClass("hide");

		return false;
	});

	// submit
	$(".btn-form-submit").on("click", function() {
		var args = {};
		if(window.saving)
			return;
		window.saving = true;

		if(window.file_reading) {
			window.saving = false;
			frappe.msgprint("Reading file, please retry.");
			return;
		}

		$form.find("[name]").each(function() {
			var $input = $(this);
			var input_type = $input.attr("type");
			if(input_type==="file") {
				var val = $input.get(0).filedata;
			} else if(input_type==="checkbox") {
				var val = $input.is(":checked") ? 1 : 0;
			} else if($input.attr("data-fieldtype")==="Date") {
				var val = $.datepicker.formatDate("yy-mm-dd",
					$input.datepicker('getDate'));
			} else {
				var val = $input.val();
			}

			if($input.prop("required") && val===undefined) {
				frappe.msgprint(__("{0} is required",
					$input.attr("data-label")));
				window.saving = false;
				throw "mandatory missing";
			}

			args[$input.attr("name")] = val;
		});

		frappe.call({
			type: "POST",
			method: "frappe.website.doctype.web_form.web_form.accept",
			args: args,
			freeze: true,
			btn: $form.find("[type='submit']"),
			callback: function(data) {
				if(!data.exc) {
					if(window.success_message) {
						$form.addClass("hide");
						$(".comments, .introduction").addClass("hide");
						scroll(0, 0);
						$(".form-message")
							.html('{{ success_message }}<p><a href="{{ success_url }}">{{ _("Continue") }}</a></p>')
							.removeClass("hide");
                    } else {
						frappe.msgprint(__('Successfully Updated. Redirecting...'));
						setTimeout(function() {
							window.location.href = "{{ success_url }}";
						}, 3000);
				    }
			    }
		    },
            always: function() {
                window.saving = false;
            }
		});

		return false;
	});

	// close button
	$(".close").on("click", function() {
		var name = $(this).attr("data-name");
		if(name) {
			frappe.call({
				type:"POST",
				method: "frappe.website.doctype.web_form.web_form.delete",
				args: {
					"web_form": "{{ name }}",
					"name": name
				},
				callback: function(r) {
					if(!r.exc) {
						location.reload();
					}
				}
			});
		}
	})

	// import date picker / timepicker if required
	{% if "Date" in types %}
	frappe.require("assets/frappe/js/lib/jquery/jquery-ui.min.js");
	frappe.require("assets/frappe/js/lib/jquery/bootstrap_theme/jquery-ui.selected.css");
	$form.find("[data-fieldtype='Date']").datepicker({
		altFormat:'yy-mm-dd',
		changeYear: true,
		yearRange: "-70Y:+10Y",
		dateFormat: frappe.datepicker_format,
	});

	// convert dates to user format
	$form.find("[data-fieldtype='Date']").each(function() {
		var val = $(this).val();
		if(val) {
			$(this).val($.datepicker.formatDate(frappe.datepicker_format,
				$.datepicker.parseDate("yy-mm-dd", val)));
		}
	})

	{% endif %}

	{% if "Datetime" in types %}
	frappe.require("assets/frappe/js/lib/jquery/jquery.ui.slider.min.js");
	frappe.require("assets/frappe/js/lib/jquery/jquery.ui.sliderAccess.js");
	frappe.require("assets/frappe/js/lib/jquery/jquery.ui.timepicker-addon.css");
	frappe.require("assets/frappe/js/lib/jquery/jquery.ui.timepicker-addon.js");
	$form.find("[data-fieldtype='Datetime']").datetimepicker({
		altFormat:'yy-mm-dd',
		changeYear: true,
		yearRange: "-70Y:+10Y",
		dateFormat: frappe.datepicker_format,
	})
	{% endif %}
});

{% if script is defined %}
{{ script }}
{% endif %}

</script>
{% endblock %}

{% block style %}
{% if style is defined %}<style>{{ style }}</style>{% endif %}
{% endblock %}