/* Minification failed. Returning unminified contents.
(28,20-21): run-time error JS1195: Expected expression: )
(28,23-24): run-time error JS1195: Expected expression: >
(32,2-3): run-time error JS1002: Syntax error: }
 */
/*! jQuery Validation Plugin - v1.13.0 - 7/1/2014
 * http://jqueryvalidation.org/
 * Copyright (c) 2014 Jörn Zaefferer; Licensed MIT */
!function (a) { "function" == typeof define && define.amd ? define(["jquery"], a) : a(jQuery) }(function (a) { a.extend(a.fn, { validate: function (b) { if (!this.length) return void (b && b.debug && window.console && console.warn("Nothing selected, can't validate, returning nothing.")); var c = a.data(this[0], "validator"); return c ? c : (this.attr("novalidate", "novalidate"), c = new a.validator(b, this[0]), a.data(this[0], "validator", c), c.settings.onsubmit && (this.validateDelegate(":submit", "click", function (b) { c.settings.submitHandler && (c.submitButton = b.target), a(b.target).hasClass("cancel") && (c.cancelSubmit = !0), void 0 !== a(b.target).attr("formnovalidate") && (c.cancelSubmit = !0) }), this.submit(function (b) { function d() { var d; return c.settings.submitHandler ? (c.submitButton && (d = a("<input type='hidden'/>").attr("name", c.submitButton.name).val(a(c.submitButton).val()).appendTo(c.currentForm)), c.settings.submitHandler.call(c, c.currentForm, b), c.submitButton && d.remove(), !1) : !0 } return c.settings.debug && b.preventDefault(), c.cancelSubmit ? (c.cancelSubmit = !1, d()) : c.form() ? c.pendingRequest ? (c.formSubmitted = !0, !1) : d() : (c.focusInvalid(), !1) })), c) }, valid: function () { var b, c; return a(this[0]).is("form") ? b = this.validate().form() : (b = !0, c = a(this[0].form).validate(), this.each(function () { b = c.element(this) && b })), b }, removeAttrs: function (b) { var c = {}, d = this; return a.each(b.split(/\s/), function (a, b) { c[b] = d.attr(b), d.removeAttr(b) }), c }, rules: function (b, c) { var d, e, f, g, h, i, j = this[0]; if (b) switch (d = a.data(j.form, "validator").settings, e = d.rules, f = a.validator.staticRules(j), b) { case "add": a.extend(f, a.validator.normalizeRule(c)), delete f.messages, e[j.name] = f, c.messages && (d.messages[j.name] = a.extend(d.messages[j.name], c.messages)); break; case "remove": return c ? (i = {}, a.each(c.split(/\s/), function (b, c) { i[c] = f[c], delete f[c], "required" === c && a(j).removeAttr("aria-required") }), i) : (delete e[j.name], f) } return g = a.validator.normalizeRules(a.extend({}, a.validator.classRules(j), a.validator.attributeRules(j), a.validator.dataRules(j), a.validator.staticRules(j)), j), g.required && (h = g.required, delete g.required, g = a.extend({ required: h }, g), a(j).attr("aria-required", "true")), g.remote && (h = g.remote, delete g.remote, g = a.extend(g, { remote: h })), g } }), a.extend(a.expr[":"], { blank: function (b) { return !a.trim("" + a(b).val()) }, filled: function (b) { return !!a.trim("" + a(b).val()) }, unchecked: function (b) { return !a(b).prop("checked") } }), a.validator = function (b, c) { this.settings = a.extend(!0, {}, a.validator.defaults, b), this.currentForm = c, this.init() }, a.validator.format = function (b, c) { return 1 === arguments.length ? function () { var c = a.makeArray(arguments); return c.unshift(b), a.validator.format.apply(this, c) } : (arguments.length > 2 && c.constructor !== Array && (c = a.makeArray(arguments).slice(1)), c.constructor !== Array && (c = [c]), a.each(c, function (a, c) { b = b.replace(new RegExp("\\{" + a + "\\}", "g"), function () { return c }) }), b) }, a.extend(a.validator, { defaults: { messages: {}, groups: {}, rules: {}, errorClass: "error", validClass: "valid", errorElement: "label", focusInvalid: !0, errorContainer: a([]), errorLabelContainer: a([]), onsubmit: !0, ignore: ":hidden", ignoreTitle: !1, onfocusin: function (a) { this.lastActive = a, this.settings.focusCleanup && !this.blockFocusCleanup && (this.settings.unhighlight && this.settings.unhighlight.call(this, a, this.settings.errorClass, this.settings.validClass), this.hideThese(this.errorsFor(a))) }, onfocusout: function (a) { this.checkable(a) || !(a.name in this.submitted) && this.optional(a) || this.element(a) }, onkeyup: function (a, b) { (9 !== b.which || "" !== this.elementValue(a)) && (a.name in this.submitted || a === this.lastElement) && this.element(a) }, onclick: function (a) { a.name in this.submitted ? this.element(a) : a.parentNode.name in this.submitted && this.element(a.parentNode) }, highlight: function (b, c, d) { "radio" === b.type ? this.findByName(b.name).addClass(c).removeClass(d) : a(b).addClass(c).removeClass(d) }, unhighlight: function (b, c, d) { "radio" === b.type ? this.findByName(b.name).removeClass(c).addClass(d) : a(b).removeClass(c).addClass(d) } }, setDefaults: function (b) { a.extend(a.validator.defaults, b) }, messages: { required: "This field is required.", remote: "Please fix this field.", email: "Please enter a valid email address.", url: "Please enter a valid URL.", date: "Please enter a valid date.", dateISO: "Please enter a valid date ( ISO ).", number: "Please enter a valid number.", digits: "Please enter only digits.", creditcard: "Please enter a valid credit card number.", equalTo: "Please enter the same value again.", maxlength: a.validator.format("Please enter no more than {0} characters."), minlength: a.validator.format("Please enter at least {0} characters."), rangelength: a.validator.format("Please enter a value between {0} and {1} characters long."), range: a.validator.format("Please enter a value between {0} and {1}."), max: a.validator.format("Please enter a value less than or equal to {0}."), min: a.validator.format("Please enter a value greater than or equal to {0}.") }, autoCreateRanges: !1, prototype: { init: function () { function b(b) { var c = a.data(this[0].form, "validator"), d = "on" + b.type.replace(/^validate/, ""), e = c.settings; e[d] && !this.is(e.ignore) && e[d].call(c, this[0], b) } this.labelContainer = a(this.settings.errorLabelContainer), this.errorContext = this.labelContainer.length && this.labelContainer || a(this.currentForm), this.containers = a(this.settings.errorContainer).add(this.settings.errorLabelContainer), this.submitted = {}, this.valueCache = {}, this.pendingRequest = 0, this.pending = {}, this.invalid = {}, this.reset(); var c, d = this.groups = {}; a.each(this.settings.groups, function (b, c) { "string" == typeof c && (c = c.split(/\s/)), a.each(c, function (a, c) { d[c] = b }) }), c = this.settings.rules, a.each(c, function (b, d) { c[b] = a.validator.normalizeRule(d) }), a(this.currentForm).validateDelegate(":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'] ,[type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], [type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'], [type='radio'], [type='checkbox']", "focusin focusout keyup", b).validateDelegate("select, option, [type='radio'], [type='checkbox']", "click", b), this.settings.invalidHandler && a(this.currentForm).bind("invalid-form.validate", this.settings.invalidHandler), a(this.currentForm).find("[required], [data-rule-required], .required").attr("aria-required", "true") }, form: function () { return this.checkForm(), a.extend(this.submitted, this.errorMap), this.invalid = a.extend({}, this.errorMap), this.valid() || a(this.currentForm).triggerHandler("invalid-form", [this]), this.showErrors(), this.valid() }, checkForm: function () { this.prepareForm(); for (var a = 0, b = this.currentElements = this.elements() ; b[a]; a++) this.check(b[a]); return this.valid() }, element: function (b) { var c = this.clean(b), d = this.validationTargetFor(c), e = !0; return this.lastElement = d, void 0 === d ? delete this.invalid[c.name] : (this.prepareElement(d), this.currentElements = a(d), e = this.check(d) !== !1, e ? delete this.invalid[d.name] : this.invalid[d.name] = !0), a(b).attr("aria-invalid", !e), this.numberOfInvalids() || (this.toHide = this.toHide.add(this.containers)), this.showErrors(), e }, showErrors: function (b) { if (b) { a.extend(this.errorMap, b), this.errorList = []; for (var c in b) this.errorList.push({ message: b[c], element: this.findByName(c)[0] }); this.successList = a.grep(this.successList, function (a) { return !(a.name in b) }) } this.settings.showErrors ? this.settings.showErrors.call(this, this.errorMap, this.errorList) : this.defaultShowErrors() }, resetForm: function () { a.fn.resetForm && a(this.currentForm).resetForm(), this.submitted = {}, this.lastElement = null, this.prepareForm(), this.hideErrors(), this.elements().removeClass(this.settings.errorClass).removeData("previousValue").removeAttr("aria-invalid") }, numberOfInvalids: function () { return this.objectLength(this.invalid) }, objectLength: function (a) { var b, c = 0; for (b in a) c++; return c }, hideErrors: function () { this.hideThese(this.toHide) }, hideThese: function (a) { a.not(this.containers).text(""), this.addWrapper(a).hide() }, valid: function () { return 0 === this.size() }, size: function () { return this.errorList.length }, focusInvalid: function () { if (this.settings.focusInvalid) try { a(this.findLastActive() || this.errorList.length && this.errorList[0].element || []).filter(":visible").focus().trigger("focusin") } catch (b) { } }, findLastActive: function () { var b = this.lastActive; return b && 1 === a.grep(this.errorList, function (a) { return a.element.name === b.name }).length && b }, elements: function () { var b = this, c = {}; return a(this.currentForm).find("input, select, textarea").not(":submit, :reset, :image, [disabled]").not(this.settings.ignore).filter(function () { return !this.name && b.settings.debug && window.console && console.error("%o has no name assigned", this), this.name in c || !b.objectLength(a(this).rules()) ? !1 : (c[this.name] = !0, !0) }) }, clean: function (b) { return a(b)[0] }, errors: function () { var b = this.settings.errorClass.split(" ").join("."); return a(this.settings.errorElement + "." + b, this.errorContext) }, reset: function () { this.successList = [], this.errorList = [], this.errorMap = {}, this.toShow = a([]), this.toHide = a([]), this.currentElements = a([]) }, prepareForm: function () { this.reset(), this.toHide = this.errors().add(this.containers) }, prepareElement: function (a) { this.reset(), this.toHide = this.errorsFor(a) }, elementValue: function (b) { var c, d = a(b), e = b.type; return "radio" === e || "checkbox" === e ? a("input[name='" + b.name + "']:checked").val() : "number" === e && "undefined" != typeof b.validity ? b.validity.badInput ? !1 : d.val() : (c = d.val(), "string" == typeof c ? c.replace(/\r/g, "") : c) }, check: function (b) { b = this.validationTargetFor(this.clean(b)); var c, d, e, f = a(b).rules(), g = a.map(f, function (a, b) { return b }).length, h = !1, i = this.elementValue(b); for (d in f) { e = { method: d, parameters: f[d] }; try { if (c = a.validator.methods[d].call(this, i, b, e.parameters), "dependency-mismatch" === c && 1 === g) { h = !0; continue } if (h = !1, "pending" === c) return void (this.toHide = this.toHide.not(this.errorsFor(b))); if (!c) return this.formatAndAdd(b, e), !1 } catch (j) { throw this.settings.debug && window.console && console.log("Exception occurred when checking element " + b.id + ", check the '" + e.method + "' method.", j), j } } if (!h) return this.objectLength(f) && this.successList.push(b), !0 }, customDataMessage: function (b, c) { return a(b).data("msg" + c.charAt(0).toUpperCase() + c.substring(1).toLowerCase()) || a(b).data("msg") }, customMessage: function (a, b) { var c = this.settings.messages[a]; return c && (c.constructor === String ? c : c[b]) }, findDefined: function () { for (var a = 0; a < arguments.length; a++) if (void 0 !== arguments[a]) return arguments[a]; return void 0 }, defaultMessage: function (b, c) { return this.findDefined(this.customMessage(b.name, c), this.customDataMessage(b, c), !this.settings.ignoreTitle && b.title || void 0, a.validator.messages[c], "<strong>Warning: No message defined for " + b.name + "</strong>") }, formatAndAdd: function (b, c) { var d = this.defaultMessage(b, c.method), e = /\$?\{(\d+)\}/g; "function" == typeof d ? d = d.call(this, c.parameters, b) : e.test(d) && (d = a.validator.format(d.replace(e, "{$1}"), c.parameters)), this.errorList.push({ message: d, element: b, method: c.method }), this.errorMap[b.name] = d, this.submitted[b.name] = d }, addWrapper: function (a) { return this.settings.wrapper && (a = a.add(a.parent(this.settings.wrapper))), a }, defaultShowErrors: function () { var a, b, c; for (a = 0; this.errorList[a]; a++) c = this.errorList[a], this.settings.highlight && this.settings.highlight.call(this, c.element, this.settings.errorClass, this.settings.validClass), this.showLabel(c.element, c.message); if (this.errorList.length && (this.toShow = this.toShow.add(this.containers)), this.settings.success) for (a = 0; this.successList[a]; a++) this.showLabel(this.successList[a]); if (this.settings.unhighlight) for (a = 0, b = this.validElements() ; b[a]; a++) this.settings.unhighlight.call(this, b[a], this.settings.errorClass, this.settings.validClass); this.toHide = this.toHide.not(this.toShow), this.hideErrors(), this.addWrapper(this.toShow).show() }, validElements: function () { return this.currentElements.not(this.invalidElements()) }, invalidElements: function () { return a(this.errorList).map(function () { return this.element }) }, showLabel: function (b, c) { var d, e, f, g = this.errorsFor(b), h = this.idOrName(b), i = a(b).attr("aria-describedby"); g.length ? (g.removeClass(this.settings.validClass).addClass(this.settings.errorClass), g.html(c)) : (g = a("<" + this.settings.errorElement + ">").attr("id", h + "-error").addClass(this.settings.errorClass).html(c || ""), d = g, this.settings.wrapper && (d = g.hide().show().wrap("<" + this.settings.wrapper + "/>").parent()), this.labelContainer.length ? this.labelContainer.append(d) : this.settings.errorPlacement ? this.settings.errorPlacement(d, a(b)) : d.insertAfter(b), g.is("label") ? g.attr("for", h) : 0 === g.parents("label[for='" + h + "']").length && (f = g.attr("id"), i ? i.match(new RegExp("\b" + f + "\b")) || (i += " " + f) : i = f, a(b).attr("aria-describedby", i), e = this.groups[b.name], e && a.each(this.groups, function (b, c) { c === e && a("[name='" + b + "']", this.currentForm).attr("aria-describedby", g.attr("id")) }))), !c && this.settings.success && (g.text(""), "string" == typeof this.settings.success ? g.addClass(this.settings.success) : this.settings.success(g, b)), this.toShow = this.toShow.add(g) }, errorsFor: function (b) { var c = this.idOrName(b), d = a(b).attr("aria-describedby"), e = "label[for='" + c + "'], label[for='" + c + "'] *"; return d && (e = e + ", #" + d.replace(/\s+/g, ", #")), this.errors().filter(e) }, idOrName: function (a) { return this.groups[a.name] || (this.checkable(a) ? a.name : a.id || a.name) }, validationTargetFor: function (a) { return this.checkable(a) && (a = this.findByName(a.name).not(this.settings.ignore)[0]), a }, checkable: function (a) { return /radio|checkbox/i.test(a.type) }, findByName: function (b) { return a(this.currentForm).find("[name='" + b + "']") }, getLength: function (b, c) { switch (c.nodeName.toLowerCase()) { case "select": return a("option:selected", c).length; case "input": if (this.checkable(c)) return this.findByName(c.name).filter(":checked").length } return b.length }, depend: function (a, b) { return this.dependTypes[typeof a] ? this.dependTypes[typeof a](a, b) : !0 }, dependTypes: { "boolean": function (a) { return a }, string: function (b, c) { return !!a(b, c.form).length }, "function": function (a, b) { return a(b) } }, optional: function (b) { var c = this.elementValue(b); return !a.validator.methods.required.call(this, c, b) && "dependency-mismatch" }, startRequest: function (a) { this.pending[a.name] || (this.pendingRequest++, this.pending[a.name] = !0) }, stopRequest: function (b, c) { this.pendingRequest--, this.pendingRequest < 0 && (this.pendingRequest = 0), delete this.pending[b.name], c && 0 === this.pendingRequest && this.formSubmitted && this.form() ? (a(this.currentForm).submit(), this.formSubmitted = !1) : !c && 0 === this.pendingRequest && this.formSubmitted && (a(this.currentForm).triggerHandler("invalid-form", [this]), this.formSubmitted = !1) }, previousValue: function (b) { return a.data(b, "previousValue") || a.data(b, "previousValue", { old: null, valid: !0, message: this.defaultMessage(b, "remote") }) } }, classRuleSettings: { required: { required: !0 }, email: { email: !0 }, url: { url: !0 }, date: { date: !0 }, dateISO: { dateISO: !0 }, number: { number: !0 }, digits: { digits: !0 }, creditcard: { creditcard: !0 } }, addClassRules: function (b, c) { b.constructor === String ? this.classRuleSettings[b] = c : a.extend(this.classRuleSettings, b) }, classRules: function (b) { var c = {}, d = a(b).attr("class"); return d && a.each(d.split(" "), function () { this in a.validator.classRuleSettings && a.extend(c, a.validator.classRuleSettings[this]) }), c }, attributeRules: function (b) { var c, d, e = {}, f = a(b), g = b.getAttribute("type"); for (c in a.validator.methods) "required" === c ? (d = b.getAttribute(c), "" === d && (d = !0), d = !!d) : d = f.attr(c), /min|max/.test(c) && (null === g || /number|range|text/.test(g)) && (d = Number(d)), d || 0 === d ? e[c] = d : g === c && "range" !== g && (e[c] = !0); return e.maxlength && /-1|2147483647|524288/.test(e.maxlength) && delete e.maxlength, e }, dataRules: function (b) { var c, d, e = {}, f = a(b); for (c in a.validator.methods) d = f.data("rule" + c.charAt(0).toUpperCase() + c.substring(1).toLowerCase()), void 0 !== d && (e[c] = d); return e }, staticRules: function (b) { var c = {}, d = a.data(b.form, "validator"); return d.settings.rules && (c = a.validator.normalizeRule(d.settings.rules[b.name]) || {}), c }, normalizeRules: function (b, c) { return a.each(b, function (d, e) { if (e === !1) return void delete b[d]; if (e.param || e.depends) { var f = !0; switch (typeof e.depends) { case "string": f = !!a(e.depends, c.form).length; break; case "function": f = e.depends.call(c, c) } f ? b[d] = void 0 !== e.param ? e.param : !0 : delete b[d] } }), a.each(b, function (d, e) { b[d] = a.isFunction(e) ? e(c) : e }), a.each(["minlength", "maxlength"], function () { b[this] && (b[this] = Number(b[this])) }), a.each(["rangelength", "range"], function () { var c; b[this] && (a.isArray(b[this]) ? b[this] = [Number(b[this][0]), Number(b[this][1])] : "string" == typeof b[this] && (c = b[this].replace(/[\[\]]/g, "").split(/[\s,]+/), b[this] = [Number(c[0]), Number(c[1])])) }), a.validator.autoCreateRanges && (b.min && b.max && (b.range = [b.min, b.max], delete b.min, delete b.max), b.minlength && b.maxlength && (b.rangelength = [b.minlength, b.maxlength], delete b.minlength, delete b.maxlength)), b }, normalizeRule: function (b) { if ("string" == typeof b) { var c = {}; a.each(b.split(/\s/), function () { c[this] = !0 }), b = c } return b }, addMethod: function (b, c, d) { a.validator.methods[b] = c, a.validator.messages[b] = void 0 !== d ? d : a.validator.messages[b], c.length < 3 && a.validator.addClassRules(b, a.validator.normalizeRule(b)) }, methods: { required: function (b, c, d) { if (!this.depend(d, c)) return "dependency-mismatch"; if ("select" === c.nodeName.toLowerCase()) { var e = a(c).val(); return e && e.length > 0 } return this.checkable(c) ? this.getLength(b, c) > 0 : a.trim(b).length > 0 }, email: function (a, b) { return this.optional(b) || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(a) }, url: function (a, b) { return this.optional(b) || /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(a) }, date: function (a, b) { return this.optional(b) || !/Invalid|NaN/.test(new Date(a).toString()) }, dateISO: function (a, b) { return this.optional(b) || /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test(a) }, number: function (a, b) { return this.optional(b) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a) }, digits: function (a, b) { return this.optional(b) || /^\d+$/.test(a) }, creditcard: function (a, b) { if (this.optional(b)) return "dependency-mismatch"; if (/[^0-9 \-]+/.test(a)) return !1; var c, d, e = 0, f = 0, g = !1; if (a = a.replace(/\D/g, ""), a.length < 13 || a.length > 19) return !1; for (c = a.length - 1; c >= 0; c--) d = a.charAt(c), f = parseInt(d, 10), g && (f *= 2) > 9 && (f -= 9), e += f, g = !g; return e % 10 === 0 }, minlength: function (b, c, d) { var e = a.isArray(b) ? b.length : this.getLength(a.trim(b), c); return this.optional(c) || e >= d }, maxlength: function (b, c, d) { var e = a.isArray(b) ? b.length : this.getLength(a.trim(b), c); return this.optional(c) || d >= e }, rangelength: function (b, c, d) { var e = a.isArray(b) ? b.length : this.getLength(a.trim(b), c); return this.optional(c) || e >= d[0] && e <= d[1] }, min: function (a, b, c) { return this.optional(b) || a >= c }, max: function (a, b, c) { return this.optional(b) || c >= a }, range: function (a, b, c) { return this.optional(b) || a >= c[0] && a <= c[1] }, equalTo: function (b, c, d) { var e = a(d); return this.settings.onfocusout && e.unbind(".validate-equalTo").bind("blur.validate-equalTo", function () { a(c).valid() }), b === e.val() }, remote: function (b, c, d) { if (this.optional(c)) return "dependency-mismatch"; var e, f, g = this.previousValue(c); return this.settings.messages[c.name] || (this.settings.messages[c.name] = {}), g.originalMessage = this.settings.messages[c.name].remote, this.settings.messages[c.name].remote = g.message, d = "string" == typeof d && { url: d } || d, g.old === b ? g.valid : (g.old = b, e = this, this.startRequest(c), f = {}, f[c.name] = b, a.ajax(a.extend(!0, { url: d, mode: "abort", port: "validate" + c.name, dataType: "json", data: f, context: e.currentForm, success: function (d) { var f, h, i, j = d === !0 || "true" === d; e.settings.messages[c.name].remote = g.originalMessage, j ? (i = e.formSubmitted, e.prepareElement(c), e.formSubmitted = i, e.successList.push(c), delete e.invalid[c.name], e.showErrors()) : (f = {}, h = d || e.defaultMessage(c, "remote"), f[c.name] = g.message = a.isFunction(h) ? h(b) : h, e.invalid[c.name] = !0, e.showErrors(f)), g.valid = j, e.stopRequest(c, j) } }, d)), "pending") } } }), a.format = function () { throw "$.format has been deprecated. Please use $.validator.format instead." }; var b, c = {}; a.ajaxPrefilter ? a.ajaxPrefilter(function (a, b, d) { var e = a.port; "abort" === a.mode && (c[e] && c[e].abort(), c[e] = d) }) : (b = a.ajax, a.ajax = function (d) { var e = ("mode" in d ? d : a.ajaxSettings).mode, f = ("port" in d ? d : a.ajaxSettings).port; return "abort" === e ? (c[f] && c[f].abort(), c[f] = b.apply(this, arguments), c[f]) : b.apply(this, arguments) }), a.extend(a.fn, { validateDelegate: function (b, c, d) { return this.bind(c, function (c) { var e = a(c.target); return e.is(b) ? d.apply(e, arguments) : void 0 }) } }) });;
/* NUGET: BEGIN LICENSE TEXT
 *
 * Microsoft grants you the right to use these script files for the sole
 * purpose of either: (i) interacting through your browser with the Microsoft
 * website or online service, subject to the applicable licensing or use
 * terms; or (ii) using the files as included with a Microsoft product subject
 * to that product's license terms. Microsoft reserves all other rights to the
 * files not expressly granted by Microsoft, whether by implication, estoppel
 * or otherwise. Insofar as a script file is dual licensed under GPL,
 * Microsoft neither took the code under GPL nor distributes it thereunder but
 * under the terms set out in this paragraph. All notices and licenses
 * below are for informational purposes only.
 *
 * NUGET: END LICENSE TEXT */
/*
** Unobtrusive validation support library for jQuery and jQuery Validate
** Copyright (C) Microsoft Corporation. All rights reserved.
*/
(function(a){var d=a.validator,b,e="unobtrusiveValidation";function c(a,b,c){a.rules[b]=c;if(a.message)a.messages[b]=a.message}function j(a){return a.replace(/^\s+|\s+$/g,"").split(/\s*,\s*/g)}function f(a){return a.replace(/([!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~])/g,"\\$1")}function h(a){return a.substr(0,a.lastIndexOf(".")+1)}function g(a,b){if(a.indexOf("*.")===0)a=a.replace("*.",b);return a}function m(c,e){var b=a(this).find("[data-valmsg-for='"+f(e[0].name)+"']"),d=b.attr("data-valmsg-replace"),g=d?a.parseJSON(d)!==false:null;b.removeClass("field-validation-valid").addClass("field-validation-error");c.data("unobtrusiveContainer",b);if(g){b.empty();c.removeClass("input-validation-error").appendTo(b)}else c.hide()}function l(e,d){var c=a(this).find("[data-valmsg-summary=true]"),b=c.find("ul");if(b&&b.length&&d.errorList.length){b.empty();c.addClass("validation-summary-errors").removeClass("validation-summary-valid");a.each(d.errorList,function(){a("<li />").html(this.message).appendTo(b)})}}function k(d){var b=d.data("unobtrusiveContainer"),c=b.attr("data-valmsg-replace"),e=c?a.parseJSON(c):null;if(b){b.addClass("field-validation-valid").removeClass("field-validation-error");d.removeData("unobtrusiveContainer");e&&b.empty()}}function n(){var b=a(this);b.data("validator").resetForm();b.find(".validation-summary-errors").addClass("validation-summary-valid").removeClass("validation-summary-errors");b.find(".field-validation-error").addClass("field-validation-valid").removeClass("field-validation-error").removeData("unobtrusiveContainer").find(">*").removeData("unobtrusiveContainer")}function i(c){var b=a(c),d=b.data(e),f=a.proxy(n,c);if(!d){d={options:{errorClass:"input-validation-error",errorElement:"span",errorPlacement:a.proxy(m,c),invalidHandler:a.proxy(l,c),messages:{},rules:{},success:a.proxy(k,c)},attachValidation:function(){b.unbind("reset."+e,f).bind("reset."+e,f).validate(this.options)},validate:function(){b.validate();return b.valid()}};b.data(e,d)}return d}d.unobtrusive={adapters:[],parseElement:function(b,h){var d=a(b),f=d.parents("form")[0],c,e,g;if(!f)return;c=i(f);c.options.rules[b.name]=e={};c.options.messages[b.name]=g={};a.each(this.adapters,function(){var c="data-val-"+this.name,i=d.attr(c),h={};if(i!==undefined){c+="-";a.each(this.params,function(){h[this]=d.attr(c+this)});this.adapt({element:b,form:f,message:i,params:h,rules:e,messages:g})}});a.extend(e,{__dummy__:true});!h&&c.attachValidation()},parse:function(b){var c=a(b).parents("form").andSelf().add(a(b).find("form")).filter("form");a(b).find(":input").filter("[data-val=true]").each(function(){d.unobtrusive.parseElement(this,true)});c.each(function(){var a=i(this);a&&a.attachValidation()})}};b=d.unobtrusive.adapters;b.add=function(c,a,b){if(!b){b=a;a=[]}this.push({name:c,params:a,adapt:b});return this};b.addBool=function(a,b){return this.add(a,function(d){c(d,b||a,true)})};b.addMinMax=function(e,g,f,a,d,b){return this.add(e,[d||"min",b||"max"],function(b){var e=b.params.min,d=b.params.max;if(e&&d)c(b,a,[e,d]);else if(e)c(b,g,e);else d&&c(b,f,d)})};b.addSingleVal=function(a,b,d){return this.add(a,[b||"val"],function(e){c(e,d||a,e.params[b])})};d.addMethod("__dummy__",function(){return true});d.addMethod("regex",function(b,c,d){var a;if(this.optional(c))return true;a=(new RegExp(d)).exec(b);return a&&a.index===0&&a[0].length===b.length});d.addMethod("nonalphamin",function(c,d,b){var a;if(b){a=c.match(/\W/g);a=a&&a.length>=b}return a});if(d.methods.extension){b.addSingleVal("accept","mimtype");b.addSingleVal("extension","extension")}else b.addSingleVal("extension","extension","accept");b.addSingleVal("regex","pattern");b.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url");b.addMinMax("length","minlength","maxlength","rangelength").addMinMax("range","min","max","range");b.addMinMax("minlength","minlength").addMinMax("maxlength","minlength","maxlength");b.add("equalto",["other"],function(b){var i=h(b.element.name),j=b.params.other,d=g(j,i),e=a(b.form).find(":input").filter("[name='"+f(d)+"']")[0];c(b,"equalTo",e)});b.add("required",function(a){(a.element.tagName.toUpperCase()!=="INPUT"||a.element.type.toUpperCase()!=="CHECKBOX")&&c(a,"required",true)});b.add("remote",["url","type","additionalfields"],function(b){var d={url:b.params.url,type:b.params.type||"GET",data:{}},e=h(b.element.name);a.each(j(b.params.additionalfields||b.element.name),function(i,h){var c=g(h,e);d.data[c]=function(){return a(b.form).find(":input").filter("[name='"+f(c)+"']").val()}});c(b,"remote",d)});b.add("password",["min","nonalphamin","regex"],function(a){a.params.min&&c(a,"minlength",a.params.min);a.params.nonalphamin&&c(a,"nonalphamin",a.params.nonalphamin);a.params.regex&&c(a,"regex",a.params.regex)});a(function(){d.unobtrusive.parse(document)})})(jQuery);;
/*
global $
*/
$(document).foundation()
$(document).ready(() => {
    $(document).foundation()
    $('a.reveal-link').trigger('click');
    $('a.close-reveal-modal').trigger('click');
 });

// ---------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------
// Interactive options
// ---------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------

//function toggleClass(elementId, classToToggle) {
//    const element = $(`#${elementId}`)

//    if (element.hasClass(classToToggle)) {
//        element.removeClass(classToToggle)
//    } else {
//        element.addClass(classToToggle)
//    }
//}

//// ---------------------------------------------------------------------------------------
//// ---------------------------------------------------------------------------------------
//// Navigation options
//// ---------------------------------------------------------------------------------------
//// ---------------------------------------------------------------------------------------

//const startPage = 'home'

//function validateLogin() {
//    // const loginContainer = $('.login-form')
//    // const usernameTxt = loginContainer.find('input[name="username"]')
//    // const username = usernameTxt.val()
//    activate()
//}

//function activate() {
//    const body = $('body')
//    body.addClass('logged-in')
//    navigateTo(startPage)
//}

//function signOut() {
//    const body = $('body')
//    body.removeClass('logged-in')
//    closeModalAndNavigate(startPage)
//}

//// ---------------------------------------------------------------------------------------
//// ---------------------------------------------------------------------------------------
//// Modal options
//// ---------------------------------------------------------------------------------------
//// ---------------------------------------------------------------------------------------



//function closeModal(modalName) {
//    $(`#${modalName}`).foundation('close')
//}

//function closeModalAndNavigate(pageName) {
//    if (pageName) {
//        navigateTo(pageName)
//    }

//    $('.reveal').foundation('close')
//}

//// ---------------------------------------------------------------------------------------
//// ---------------------------------------------------------------------------------------
//// Navigation options
//// ---------------------------------------------------------------------------------------
//// ---------------------------------------------------------------------------------------

//function loadPage(page) {
//    $.ajax({
//        url: '/pages/' + page + '.html',
//        dataType: 'html',
//    }).done(data => {
//        const container = $('#main-content')
//        container.removeClass()
//        container.addClass(page)
//        container.html(data)
//        container.foundation()
//    })
//}

//function navigateTo(page, replace = false) {
//    const url = '/?page=' + page
//    if (replace) {
//        window.history.replaceState(null, '', url)
//    } else {
//        window.history.pushState(null, '', url)
//    }
//    loadPage(page)
//}

//function getParam(name) {
//    if (
//        (name = new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)').exec(
//            location.search
//        ))
//    )
//        return decodeURIComponent(name[1])
//}

//window.addEventListener('popstate', e => {
//    const page = getParam('page') || startPage
//    loadPage(page)
//})
//function getLocation() {
//    if (navigator.geolocation) {
//        navigator.geolocation.getCurrentPosition(setLocation);
//    }
//}

//function setLocation(position) {
//    var pos = position;
//    var latlgn = pos.coords.latitude + ', ' + pos.coords.longitude;

//    $.ajax({
//        type: 'GET',
//        dataType: 'html',
//        url: path + '/home/GuardarUbicacion/',
//        data: { coordinates: latlgn }
//    }).done(function (data) {
//        if (data) {

//        }
//    });
//}

;
var isMobil = (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()));
var version = '1.1.9';

jQuery.validator.unobtrusive.adapters.add("mustbetrue", function (options) {
    if (options.element.tagName.toUpperCase() == "INPUT" && options.element.type.toUpperCase() == "CHECKBOX") {
        options.rules["required"] = true;
        if (options.message) {
            options.messages["required"] = options.message;
        }
    }
});

jQuery(function ($) {
    $.validator.addMethod('date',
        function (value, element) {
            if (this.optional(element)) {
                return true;
            }

            var ok = true;
            try {
                var comp = value.split('/');

                var d = parseInt(comp[0], 10);
                var m = parseInt(comp[1], 10);
                var y = parseInt(comp[2], 10);

                var date = new Date(y, m - 1, d);
                if (date.getFullYear() == y && date.getMonth() + 1 == m && date.getDate() == d) {
                    ok = true;
                }
                else {
                    ok = false;
                }
            }
            catch (err) {
                ok = false;
            }

            return ok;
        });
});

function isValidDate(date) {
    if (Object.prototype.toString.call(date) !== "[object Date]") {
        return false;
    }

    return !isNaN(date.getTime());
}

$(document).on('click', function (e) {
    cerrarCombos();
});

let startDate = new Date();
let elapsedTime = 0;
var question1;
var question2;

const beforeunload = function () {
    var stop = GetCookie("stopPoll");
    if (stop == null) {

        const endDate = new Date();
        const spentTime = endDate.getTime() - startDate.getTime();
        elapsedTime = spentTime / 1000;
        console.log("---> " + elapsedTime);

        if (elapsedTime > 180) {  //180
            clearInterval(counter);
            createCookie('stopPoll', "1", 1);
            $('.modalEncuesta').show();
            $(".btn-si-encuesta1").unbind("click").on("click", function () {
                $(this).removeClass("btn-gray").addClass("btn");
                $(".btn-no-encuesta1").removeClass("btn").addClass("btn-gray");
                question1 = true;
                $(".textoPregunta1").hide();
            });

            $(".btn-no-encuesta1").unbind("click").on("click", function () {
                $(this).removeClass("btn-gray").addClass("btn");
                $(".btn-si-encuesta1").removeClass("btn").addClass("btn-gray");
                question1 = false;
                $(".textoPregunta1").hide();
            });

            $(".btn-si-encuesta2").unbind("click").on("click", function () {
                $(this).removeClass("btn-gray").addClass("btn");
                $(".btn-no-encuesta2").removeClass("btn").addClass("btn-gray");
                question2 = true;
                $(".textoPregunta2").hide();
            });

            $(".btn-no-encuesta2").unbind("click").on("click", function () {
                $(this).removeClass("btn-gray").addClass("btn");
                $(".btn-si-encuesta2").removeClass("btn").addClass("btn-gray");
                question2 = false;
                $(".textoPregunta2").hide();
            });

            $(".close").unbind("click").on("click", function () {
                $('.modalEncuesta').hide();
            });

            $(".btn-envio-encuesta").unbind("click").on("click", function () {
                EnvioEncuesta();
            });
        }
        else {
            var datos = GetCookie("startDate");
            if (datos == null) {
                createCookie('startDate', startDate, 1);
            }
        }
    }
};

window.addEventListener('beforeunload', beforeunload);

var pos = 0;
var counter;
$(document).ready(function () {
    poolCountdown();
    startDate = new Date();
    var datos = GetCookie("startDate");
    if (datos == null) {
        createCookie('startDate', startDate, 1);
    }
    else {
        startDate = new Date(datos);
    }

    counter = setInterval(beforeunload, 10000);

    $.ajaxSetup({ cache: false });

    $(document).ajaxSuccess(function (event, xhr, settings) {
        if (xhr.getResponseHeader("version") != null && xhr.getResponseHeader("version") != window.version) {
            systemAlert('Actualización del sistema', 'Se ha realizado una actualización al sistema. Se descargarán los archivos de la nueva versión.', function () {
                window.location.reload(true);
            }, "1");
        }
    });

    tagevent = function (word) {};

    CreateSelect($("#day"), $(".day"), $(".Selectday"), $(".Arrowday"), 40, 20, 0);
    CreateSelect($("#month"), $(".month"), $(".Selectmonth"), $(".Arrowmonth"), 40, 20, 0);
    CreateSelect($("#year"), $(".year"), $(".Selectyear"), $(".Arrowyear"), 40, 20, 0);

    CreateSelect($("#day2"), $(".day2"), $(".Selectday2"), $(".Arrowday2"), 40, 20, 0);
    CreateSelect($("#month2"), $(".month2"), $(".Selectmonth2"), $(".Arrowmonth2"), 40, 20, 0);
    CreateSelect($("#year2"), $(".year2"), $(".Selectyear2"), $(".Arrowyear2"), 40, 20, 0);

    CreateSelect($("#Genre"), $(".Genre"), $(".SelectGenre"), $(".ArrowGenre"), 40, 20, 0);

    // ============== menu btn =========== //
    $('.header__btn').click(function (event) {
        $('.latMenu').addClass('menu-open');
    });

    $('.latMenu__btnClose').click(function (event) {
        $('.latMenu').removeClass('menu-open');
    });

    $(".navbar-toggler").unbind("click");
    $(".navbar-toggler").on("click", function () {
        if ($(".navbar-collapse").hasClass("open-menu")) {
            $(".navbar-collapse").removeClass("open-menu");
        }
        else {
            $(".navbar-collapse").addClass("open-menu");
        }
    });

    $('.slide-row').click(function (event) {
        $('.full-modal').css('display', 'block');
        $('body').css('overflow', 'hidden');
    });

    $(".citaPendiente").show();
    $(".aceptarCitaPendiente").unbind("click");
    $(".aceptarCitaPendiente").on("click", function () {
        redirect(path + "/pacientes/citas");
    });

    $(".flecha1").unbind("click");
    $(".flecha1").on("click", function () {
        pos = pos - 1;

        if (pos <= 0) {
            $(".flecha1").hide();
            pos = 0;
        }
        else {
            $(".flecha1").show();
        }

        CargarHoras(1);
    });

    $(".flecha2").unbind("click");
    $(".flecha2").on("click", function () {

        pos = pos + 1;

        if (pos <= 0) {
            $(".flecha1").hide();
            pos = 0;
        }
        else {
            $(".flecha1").show();
        }

        CargarHoras(2);
    });

    $(".menuEntidadesPrincipal").unbind("click");
    $(".menuEntidadesPrincipal").on("click", function () {
        if ($(".menuEntidades").is(":visible")) {
            $(".menuEntidades").fadeOut();
        }
        else {
            $(".menuEntidades").fadeIn();
        }
    });

    $('.menuEntidades').unbind('hover');
    $('.menuEntidades').hover(function (e) {
        e.preventDefault();
        e.stopPropagation();

        $(this).css("background-color", "#F6F6F6");
    }, function (e) {

        e.preventDefault();
        e.stopPropagation();

        $(this).css("background-color", "#FFFFFF");
    });

    $('.menuEntidades').unbind('click');
    $('.menuEntidades').on('click', function () {
        var id = $(this).attr("data-id");
        $("#entityID").val(id);
        $(".menuEntidades").fadeOut();

        var nombre = $(this).attr("data-name");
        var direccion = $(this).attr("data-address");
        var ciudad = $(this).attr("data-city");

        $(".nombre").text(nombre);
        $(".direccion").text(direccion);
        $(".ciudad").text(ciudad);

        CargarHoras(0);
    });

    $("#disponibilidad1").unbind("change");
    $("#disponibilidad1").on("change", function () {
        CargarHoras(0);
    });

    $('.btn-modal-pregunta').click(function (event) {
        $('.modalPregunta').show();
        $('body').addClass('body-noscroll');
        //$('.modalPregunta').toggle();
        //$("html, body").animate({ scrollTop: 0 }, 0);
        //$('body').css('overflow', 'hidden');        
    });

    $('.close-modal-pregunta').click(function (event) {
        //$('.wrap-modal').css('display', 'block');
        //$('.wrap-modal').css('padding-top', '205px');
        //$('.wrap-modal-map').css('display', 'none');
        //$('.place-map').empty();

        $('.modalPregunta').hide();
        $('body').removeClass('body-noscroll');
        //$('body').css('overflow', 'scroll');
        //$('body').css('overflow-x', 'hidden');
    });

    $('.close-modal-sugerencia').click(function (event) {
        $('.modalContactenos').hide();
        $('body').removeClass('body-noscroll');
        //$('body').css('overflow', 'scroll');
        //$('body').css('overflow-x', 'hidden');
    });

    $('.btn-modal-descubre').click(function (event) {
        $('.modalDescubre').toggle();
        $("html, body").animate({ scrollTop: 0 }, 0);
        //$('body').css('overflow', 'hidden');
    });

    $('.close-modal-descubre').click(function (event) {
        $('.wrap-modal').css('display', 'block');
        $('.wrap-modal').css('padding-top', '205px');
        $('.wrap-modal-map').css('display', 'none');
        $('.place-map').empty();

        $('.modalDescubre').toggle();
        //$('body').css('overflow', 'scroll');
        //$('body').css('overflow-x', 'hidden');
    });

    $('.btn-modal-cita').click(function (event) {
        $('.modalCita').show();
        $('body').addClass('body-noscroll');
    });

    $('.close-modal-cita').click(function (event) {
        $('.modalCita').hide();
        $('.place-map').empty().hide();
        $('body').removeClass('body-noscroll');
    });

    $('.btn-modal-barrera').click(function (event) {
        $('.modalBarrera').show();
        $('body').addClass('body-noscroll');
    });

    $('.close-modal-barrera').click(function (event) {
        $('.modalBarrera').hide();
        $('.place-map').empty().hide();
        $('body').removeClass('body-noscroll');
    });

    $('.send-modal').click(function (event) {
        $(".doc1").hide();
        $(".doc2").hide();
        $(".doc3").hide();
        $('.place-map').empty().hide();

        var document = $("#documento").val();

        tagevent('Botón Asistir a Cita');

        var day = $("#day2").val();
        var month = $("#month2").val();
        var year = $("#year2").val();

        if (document.length > 0 && day.length > 0 && month.length > 0 && year.length > 0) {
            $(".buscando").show();
            $(".btn-buscando").hide();

            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: path + '/home/verificardocumento',
                data: { document: document, day: day, month: month, year: year }
            }).done(function (json) {
                if (json.result) {
                    //$(".buscando").hide();

                    createCookie('documento', document, 15);

                    //redirect(path + "/home/agendarcita");

                    if (json.data.codigo == "EPS5001" || json.data.codigo == "EPS5000") {
                        if ((json.edad >= 10 && json.edad <= 29) && json.data.codigo == "EPS5000") {
                            redirect(path + "/home/agendarcita");
                        }
                        else {
                            $(".buscando").hide();
                            $(".btn-buscando").show();

                            if (json.data.codigo == "EPS5000")    // CAPITAL SALUD
                            {
                                $('.place-map').append('Para una cita de anticoncepción llama al call center al teléfono: <br /><span class="font-weight-bold">3389760</span>').show();
                                //$('.wrap-modal').hide();
                                //$('.wrap-modal-map').show();

                                //$(".close-modal").unbind("click");
                                //$(".close-modal").on("click", function () {

                                //    $('.wrap-modal').show();
                                //    $('.wrap-modal-map').hide();

                                //    $('.place-map').empty();

                                //    $('.modalCita').hide();
                                //    //$('.modalDescubre').hide();
                                //});
                            }
                            else // UNICAJAS
                            {
                                $('.place-map').append('Para una cita de anticoncepción llama al call center al teléfono: <br /><span class="font-weight-bold">3481248</span>').show();
                                //$('.wrap-modal').hide();
                                //$('.wrap-modal-map').show();

                                //$(".close-modal").unbind("click");
                                //$(".close-modal").on("click", function () {

                                //    $('.wrap-modal').show();
                                //    $('.wrap-modal-map').hide();

                                //    $('.place-map').empty();

                                //    $('.modalCita').hide();
                                //    //$('.modalDescubre').hide();
                                //});
                            }
                        }
                    }
                    else {
                        $(".buscando").hide();
                        $(".btn-buscando").show();
                        $('.place-map').append('Tu aseguradora es ' + json.data.sede + ', para pedir una cita de anticoncepción llama al: <br /><span class="font-weight-bold">' + json.data.telefono + '</span>').show();
                        //$('.wrap-modal').hide();
                        //$('.wrap-modal-map').show();

                        //$(".close-modal").unbind("click");
                        //$(".close-modal").on("click", function () {

                        //    $('.wrap-modal').show();
                        //    $('.wrap-modal-map').hide();

                        //    $('.place-map').empty();

                        //    $('.modalCita').hide();
                        //    //$('.modalDescubre').hide();
                        //});
                    }
                }
                else {
                    $(".buscando").hide();
                    $(".btn-buscando").show();
                    $('.place-map').empty().hide();

                    $(".doc1").hide();
                    $(".doc3").hide();
                    $(".doc2").show();
                }
            });
        }
        else {
            if (document.length == 0) {
                $(".doc1").show();
                $(".doc2").hide();
            }

            if (day.length == 0 || month.length == 0 || year.length == 0) {
                $(".doc3").show();
            }
        }
    });

    $('.no-found2').click(function (event) {
        $('.modalPregunta').show();
        $('body').addClass('body-noscroll');
        //$("html, body").animate({ scrollTop: 0 }, 0);
        //$('body').css('overflow', 'hidden');
    });

    $('.suggestions').click(function (event) {
        $('.modalContactenos').show();
        $('body').addClass('body-noscroll');
        //$("html, body").animate({ scrollTop: 0 }, 0);
        //$('body').css('overflow', 'hidden');
    });

    EventosBuscador();

    $(".btn-close2").unbind("click");
    $(".btn-close2").on("click", function () {
        history.back();
    });

    $(".send-question").unbind("click");
    $(".send-question").on("click", function () {
        validateNewQuestion();
    });

    $(".send-suggestion").unbind("click");
    $(".send-suggestion").on("click", function () {
        validateNewSuggestion();
    });

    $(".send-barrier").unbind("click");
    $(".send-barrier").on("click", function () {
        validateNewBarrier();
    });

    $(".send-register").unbind("click");
    $(".send-register").on("click", function () {
        validateRegister();
    });

    $(".vermas").unbind("click");
    $(".vermas").on("click", function () {
        $(".masinfo").toggle();
        $(".vermas").toggle();
    });

    $(".vermaspreguntas").unbind("click");
    $(".vermaspreguntas").on("click", function () {
        var page = $("#page").val();
        var categoryID = $("#categoryID").val();
        $.ajax({
            type: 'POST',
            dataType: 'html',
            url: path + '/preguntas/listado',
            data: {
                page: page,
                categoryID: categoryID
            }
        }).done(function (html) {
            $("#listado-preguntas").empty().html(html);
            $(".vermaspreguntas").hide();
        });
        
    });

    $(".terminos").unbind("click");
    $(".terminos").on("click", function (e) {
        e.preventDefault();
        tagevent('Términos y Condiciones');

        VerTerminos();
    });

    $(".politicas").unbind("click");
    $(".politicas").on("click", function (e) {        
        e.preventDefault();
        tagevent('Políticas de Privacidad');

        VerPolitica();
    });

    $("#day").unbind("change");
    $("#day").on("change", function () {
        validarFechas();
    });

    $("#month").unbind("change");
    $("#month").on("change", function () {
        validarFechas();
    });

    $("#year").unbind("change");
    $("#year").on("change", function () {
        validarFechas();
    });

    $("#Email").keyup(function (e) {
        e.preventDefault();
        e.stopPropagation();

        if (e.keyCode == 13) {
            $(".send-register").click();
        }
    });

    $(".volverhome").unbind("click");
    $(".volverhome").on("click", function () {
        redirect(path + "/home");
    });

    //$("form").data("validator").settings.ignore = "";
    $.validator.setDefaults({ ignore: [] });
    $.validator.unobtrusive.parse('#form-register');

    EventosHoras();
    //validarFechas();
    $('body').css('overflow-x', 'hidden');

    EventosDetallePregunta();
});

var pools = [];
var pool = null;
function poolCountdown() {
    var countdown = readCookie('countdown');
    if (countdown == null) {
        createCookie('countdown', 60, 15);
        setTimeout(poolCountdown, 1000);
    }
    else if (countdown > 0) {
        createCookie('countdown', --countdown, 15);
        setTimeout(poolCountdown, 1000);
    }
    else if (countdown == 0) {
        createCookie('countdown', --countdown, 15);
        $.ajax({
            type: 'GET',
            dataType: 'json',
            url: path + '/pool/getpools'
        }).done(function (json) {
            if (json.data) {
                pools = json.data;
                if (pools.length > 0) {
                    poolEvent(true);
                    nextPool(true);
                }
            }
        });
    }
}

function poolEvent(first) {
    $('#pool-modal .close-modal').off('click').on('click', function () {
        $('body').removeClass('body-noscroll');
        $('#pool-modal').hide();
    });

    $('#pool-modal .pool-value').off('click').on('click', function () {
        var value = $(this).attr('data-value');
        submitPool(value, first);
    });

    $('#pool-modal #pool-select').off('change').on('change', function () {
        var value = $(this).val();
        submitPool(value, first);
        $('#pool-modal #pool-select').val('');
    });
}

function submitPool(value, first) {
    if (first) {
        $('#detail-message').hide();
        $('#pool-answers').hide();
        $('#question-detail').show();

        var title = '';
        if (value < 7) {
            $('#detail-items').show();
            title = '¿En qué podemos mejorar?';
        }
        else if (value < 9) {
            $('#detail-items').hide();
            title = '¿Qué más te gustaría encontrar en nuestra página?';
            $('#detail-message').show();
        }
        else {
            $('#detail-items').show();
            title = '¿Qué es lo que más te gusta de nuestra página?';
        }

        $('#detail-title').html(title);

        $('#other-message').off('change').on('change', function () {
            $('#detail-message').toggle();
        });

        $('#pool-modal #send-detail').off('click').on('click', function () {
            submitPool(value, false);
            $('#pool-modal #pool-select').val('');
        });
    }
    else {
        var items = [];
        $.each($(".message-item:checked"), function () {
            items.push($(this).val());
        });

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: path + '/pool/answerpool',
            traditional: true,
            data: {
                poolID: pool.PoolID,
                value: value,
                items: items,
                message: $('#detail-message').val()
            }
        }).done(function (json) {
            $('#pool-answers').show();
            $('#question-detail').hide();
            $('detail-message').val('');

            $.each($(".message-item:checked"), function () {
                $(this).prop('checked', false);
            });

            poolEvent(false);
            nextPool(false);
        });
    }
}

function nextPool(first) {
    pool = pools.shift();

    if (pool == null && first) {
        $('body').removeClass('body-noscroll');
        $('#pool-modal').hide();
    }
    else if (pool == null && !first) {
        $('#pool-answers').hide();
        $('#pool-end').show();
    }
    else {
        $('#pool-value').html(pool.Value);
        $('body').addClass('body-noscroll');
        $('#pool-modal').show();

        if (first) {
            $('#question-values').show();
            $('#question-emoticons').hide();
        }
        else {
            $('#question-values').hide();
            $('#question-emoticons').show();
        }
    }
}

function EnvioEncuesta() {
    var valid = true;
    $(".textoPregunta1").hide();
    $(".textoPregunta2").hide();

    if (question1 == undefined) {
        $(".textoPregunta1").show();
        valid = false;
    }

    if (question2 == undefined) {
        $(".textoPregunta2").show();
        valid = false;
    }

    if (valid) {
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: path + '/home/savenewpoll',
            data: { question1: question1, question2: question2 }
        }).done(function (json) {
            if (json.result) {
                $(".modalEncuesta").hide();

                $(".respuestaModalEncuesta").show();
                $(".close").on("click", function () {
                    $(".respuestaModalEncuesta").hide();
                });

                $(".btn-cerrar-encuesta").on("click", function () {
                    $(".respuestaModalEncuesta").hide();
                });
            }
        });
    }
}

function EventosDetallePregunta() {
    $(".showtooltip").mouseover(function (e) {
        e.preventDefault();
        e.stopPropagation();

        var offsetBtn = $(this).offset();

        var msn = palabras[$(this).attr("data-id")];
        $(".fuenteAlerta").html(msn);

        $(".ArrowAlert").fadeIn(200);
        $("#divAlerta").fadeIn(200);
        $('.ArrowAlert').offset({ left: offsetBtn.left + 28, top: offsetBtn.top + 40 });

        if (offsetBtn.left > 720) {
            $('#divAlerta').offset({ left: offsetBtn.left - 150, top: offsetBtn.top + 62 });
        }
        else {
            $('#divAlerta').offset({ left: offsetBtn.left, top: offsetBtn.top + 62 });
        }
    }).mouseout(function () {
        $("#divAlerta").fadeOut(200);
        $(".ArrowAlert").fadeOut(200);
    });
}

function CargarHoras(flecha) {
    var fecha = $("#fecha").val();
    var entityID = $("#entityID").val();
    var disponibilidad1 = $("#disponibilidad1").val();

    $.ajax({
        type: 'GET',
        dataType: 'html',
        url: path + '/home/agendarcitaitem/',
        data: { fecha: fecha, entityID: entityID, dia: 1, flecha: flecha }
    }).done(function (data) {
        if (data) {
            var $target = $('.dia1');
            $target.empty();
            $target.append(data);

            EventosHoras();

            $("#fecha").val($("#fechaActual_1").val());
        }
    });

    $.ajax({
        type: 'GET',
        dataType: 'html',
        url: path + '/home/agendarcitaitem/',
        data: { fecha: fecha, entityID: entityID, dia: 2, flecha: flecha }
    }).done(function (data) {
        if (data) {
            var $target = $('.dia2');
            $target.empty();
            $target.append(data);
            EventosHoras();
        }
    });

    $.ajax({
        type: 'GET',
        dataType: 'html',
        url: path + '/home/agendarcitaitem/',
        data: { fecha: fecha, entityID: entityID, dia: 3, flecha: flecha }
    }).done(function (data) {
        if (data) {
            var $target = $('.dia3');
            $target.empty();
            $target.append(data);
            EventosHoras();
        }
    });

    $.ajax({
        type: 'GET',
        dataType: 'html',
        url: path + '/home/agendarcitaitem/',
        data: { fecha: fecha, entityID: entityID, dia: 4, flecha: flecha }
    }).done(function (data) {
        if (data) {
            var $target = $('.dia4');
            $target.empty();
            $target.append(data);
            EventosHoras();
        }
    });

    $.ajax({
        type: 'GET',
        dataType: 'html',
        url: path + '/home/agendarcitaitem/',
        data: { fecha: fecha, entityID: entityID, dia: 5, flecha: flecha }
    }).done(function (data) {
        if (data) {
            var $target = $('.dia5');
            $target.empty();
            $target.append(data);
            EventosHoras();
        }
    });
}

function EventosHoras() {
    $(".itemHora").unbind("click");
    $(".itemHora").on("click", function () {

        var dia = $(this).attr("data-dia");
        var hora = $(this).attr("data-hora");
        var mensaje = $(this).attr("data-message");

        $(".confirmarCita").show();

        var body = $("html, body");
        body.stop().animate({ scrollTop: 0 }, 500, 'swing', function () {

        });

        $(".fechaConfirmacion").text(mensaje);

        $(".nombreConfirmacion").text($(".nombre").text());
        $(".especialidadConfirmacion").text($(".especialidad").text());
        $(".direccionConfirmacion").text($(".direccion").text());
        $(".ciudadConfirmacion").text($(".ciudad").text());

        $("#Documento").val($("#document").val());
        $("#Nombres").val($("#name").val());

        $("#date").val(dia);
        $("#time").val(hora);

        $(".cerrarConfirmacion").unbind("click");
        $(".cerrarConfirmacion").on("click", function (e) {
            e.preventDefault();
            e.stopPropagation();

            $(".confirmarCita").hide();
        });

        $(".confirmAppointment").unbind("click");
        $(".confirmAppointment").on("click", function () {
            $.validator.setDefaults({ ignore: [] });
            $.validator.unobtrusive.parse('#form-appointment-confirm');

            ConfirmAppointment();
        });
    });
}

function ConfirmAppointment() {
    if ($('#form-appointment-confirm').valid()) {
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: path + '/home/confirmarcita',
            data: $('#form-appointment-confirm').serialize()
        }).done(function (json) {
            if (json.result) {
                $(".confirmarCita").hide();

                $(".listoCita").show();

                $(".listoAgendamiento").unbind("click");
                $(".listoAgendamiento").on("click", function () {
                    redirect(path + "/pacientes/detallecita");
                });
            }
        });
    }
}

function validarFechas() {
    if ($("#day").val().length > 0 && $("#month").val().length > 0 && $("#year").val().length > 0) {
        $('#BirthDate2').val($('#day').val() + '/' + $('#month').val() + '/' + $('#year').val());
    }
}

function validateRegister() {
    $('#form-register').unbind('submit');
    $('#form-register').submit(function () {
        $("#BirthDate2").val($("#fecha").val());

        var valid = $('#form-register').valid();

        if (valid) {
            tagevent('Formulario Registro');

            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: path + '/home/newregister',
                data: $('#form-register').serialize()
            }).done(function (json) {
                if (json.result) {
                    $("#Name").val("");
                    $("#LastName").val("");
                    $("#Email").val("");
                    $("#Genre").val("");
                    $("#BirthDate2").val("");
                    $("#fecha").val("");

                    systemAlert("Suscripción", "Datos enviados exitosamente.");
                }
            });
        }

        return false;
    });

    $('#form-register').submit();
}

function CreateSelect(objectID, object, objectSelect, objectArrow, topSelect, topArrow, left) {
    object.unbind("click");
    object.on("click", function (e) {
        e.preventDefault();
        e.stopPropagation();

        cerrarCombos();

        if (!objectSelect.is(":visible")) {
            var offsetBtn = object.offset();
            objectSelect.fadeIn(200);
            objectArrow.fadeIn(200);
            objectSelect.offset({ left: offsetBtn.left + left, top: offsetBtn.top + topSelect });
            objectArrow.offset({ left: offsetBtn.left + 35, top: offsetBtn.top + topArrow });

            $(".itemSelect").unbind("click");
            $(".itemSelect").on("click", function () {
                var document = $(this).attr('data-document');
                var image = $(this).attr('data-image');
                var text = $(this).attr('data-text');

                if (image != undefined) {
                    $(this).parent().parent().find('.imagenPrincipal').attr('src', image);
                    $(this).parent().parent().find('.nombrePrincipal').text(text);
                    $(this).parent().parent().find('.documentoPrincipal').text(document);
                }
                else if (text != undefined) {
                    $(this).parent().parent().find('.botonSelect').text(text);
                }
                else {
                    $(this).parent().parent().find('.botonSelect').text($(this).text());
                }

                objectSelect.fadeOut(200);
                objectArrow.fadeOut(200);

                $(this).parent().find('div').removeClass('itemSelected');
                $(this).addClass('itemSelected');

                objectID.val($(this).attr('data-id'));

                objectID.change();
            });
        }
        else {
            objectSelect.fadeOut(200);
            objectArrow.fadeOut(200);
        }
    });
}

function cerrarCombos() {
    $(".Selectday, .Arrowday").fadeOut(200);
    $(".Selectmonth, .Arrowmonth").fadeOut(200);
    $(".Selectyear, .Arrowyear").fadeOut(200);

    $(".SelectGenre, .ArrowGenre").fadeOut(200);
}

function VerTerminos() {
    $.ajax({
        type: 'GET',
        dataType: 'html',
        url: path + '/home/terminosycondiciones',
        cache: false,
        data: {}
    }).done(function (html) {
        html = html.trim();

        var $content = $(html);

        clearLayer();
        openLayer($content);
    });
}

function VerPolitica() {
    $.ajax({
        type: 'GET',
        dataType: 'html',
        url: path + '/home/politicasdeprivacidad',
        cache: false,
        data: {}
    }).done(function (html) {
        html = html.trim();

        var $content = $(html);

        clearLayer();
        openLayer($content);
    });
}

var status = "1";
function validateNewQuestion() {
    if ($("#texto").val().length == 0) {
        $(".textoPregunta").show();
    }
    else {
        $(".textoPregunta").hide();
    }

    var valid = $('#form-newquestion').valid();
    var correo = $("#Email").val();
 
    if (valid && status == "1") {
        status = "0";
        tagevent('Formulario Nueva Pregunta');
        console.log(status);

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: path + '/home/savenewquestion',
            data: {
                email: correo,
                question: $("#texto").val(),
                token: $('#form-newquestion').find("#g-recaptcha-response").val()
            }
        }).done(function (json) {
            if (json.result) {

                $("#texto").val("");
                $('#nueva-pregunta').foundation('close');
                systemAlert('Que no cunda el panico', 'Tu pregunta ha sido enviada correctamente.', function () {
                    window.location.reload(true);
                }, "2");


            } else {
                systemAlert('Que no cunda el panico', 'Tuvimos problemas para enviar tu pregunta. Intenta más tarde.', function () {
                    window.location.reload(true);
                }, "3");
            }
        });
    }
}

function validateNewSuggestion() {
    $(".textoPregunta").hide();
    if ($(".wrap-modal-ask-contactenos").find("#texto").val().length == 0) {
        $(".textoPregunta").show();
    }
    else {
        $(".textoPregunta").hide();
    }

    $('#form-new-suggestion').unbind('submit');
    $('#form-new-suggestion').submit(function () {
        var valid = $('#form-new-suggestion').valid();
        var nombre = $(".wrap-modal-ask-contactenos").find("#Name").val();
        var correo = $(".wrap-modal-ask-contactenos").find("#Email").val();
        var texto = $(".wrap-modal-ask-contactenos").find("#texto").val();

        if (valid) {
            tagevent('Formulario Nuevo contacto');

            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: path + '/home/savenewsuggestion',
                data: {
                    name: nombre,
                    email: correo,
                    suggestion: texto
                }
            }).done(function (json) {
                if (json.result) {
                    $('.modalContactenos').hide();

                    systemAlert('Sexperto', 'Tu sugerencia ha sido enviada correctamente.', function () {
                        window.location.reload(true);
                    }, "2");
                }
            });
        }

        return false;
    });

    $('#form-new-suggestion').submit();
}

function validateNewBarrier() {
    var error = false;
    $(".textoPregunta").hide();
    $(".textoBarrera").hide();
    if ($(".modalBarreras").find("#texto").val().length == 0) {
        $(".textoPregunta").show();
        error = true;
    }
    else {
        $(".textoPregunta").hide();
    }

    if ($("#barriers").val().length == 0) {
        $(".textoBarrera").show();
        error = true;
    }
    else {
        $(".textoBarrera").hide();
    }

    if ($("#documentTypeID").val().length == 0) {
        $(".textoDocumento").show();
        error = true;
    }
    else {
        $(".textoDocumento").hide();
    }

    $('#form-new-barriers').unbind('submit');
    $('#form-new-barriers').submit(function () {
        var valid = $('#form-new-barriers').valid();
        var documentTypeID = $("#documentTypeID").val();
        var documentNumber = $("#DocumentNumber").val();
        var barreraID = $("#barriers").val();
        var nombre = $(".modalBarreras").find("#Name").val();
        var correo = $(".modalBarreras").find("#Email").val();
        var texto = $(".modalBarreras").find("#texto").val();

        if (valid && !error) {
            tagevent('Formulario Nueva Barrera');

            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: path + '/home/savenewbarrier',
                data: {
                    barrierID: barreraID,
                    documentTypeID: documentTypeID,
                    documentNumber: documentNumber,
                    name: nombre,
                    email: correo,
                    message: texto
                }
            }).done(function (json) {
                if (json.result) {
                    $('.modalBarrera').hide();

                    systemAlert('Sexperto', 'Tu barrera ha sido enviada correctamente.', function () {
                        window.location.reload(true);
                    }, "2");
                }
            });
        }

        return false;
    });

    $('#form-new-barriers').submit();
}

function scrollToAnchor(aid) {
    var aTag = $(aid);
    $('html,body').animate({ scrollTop: aTag.offset().top }, 'slow');
}
$.extend(
    {
        redirectPost: function (location, args) {
            var form = $('<form>', { action: location, method: 'post' });
            $.each(args,
                function (key, value) {
                    $(form).append(
                        $('<input>', { type: 'hidden', name: key, value: value })
                    );
                });
            $(form).appendTo('body').submit();
        }
    });
function EventosBuscador() {
    $('.resultado').hide();

    $('#busqueda').unbind("keyup");
        $('#busqueda').on('keypress', function (e) {
        if (e.which == 13) {
            search();
        }
    });
    $('#busqueda').on("keyup", buscar);

    $('#boton-busqueda').unbind("keyup");
    $('#boton-busqueda').on("click", search);

    //$(window).off('resize').on('resize', function () {
    //    clearTimeout(searchtime);
    //    searchtime = setTimeout(function () {
    //        var offsetBtn = $("#busqueda").offset();
    //        $('.resultado').offset({ left: offsetBtn.left });
    //    }, 10);
    //});
}
function search() {
    debugger;
    var question = $('#busqueda').val();

    if (question && question.length >= 3) {
        $.redirectPost("/busqueda ", { busqueda: question })
    }
    // window.location.replace("home/search/" + encodeURI(question));

    // window.location.href = "home/search/" + encodeURI(question);

}
var duplicate = "";
function guardarBusqueda() {
    var question = $('#busqueda').val();
    if (duplicate != question && question.length > 2) {
        duplicate = question;

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: path + '/home/savequestionhome/',
            data: { question: question }
        }).done(function (json) {

        });
    }
}

var interval = undefined;
function buscar(e) {
    e.preventDefault();
    e.stopPropagation();

    clearInterval(interval);

    if (e.keyCode == 13) {
        busqueda();
    }

    if ($('#busqueda').val().length == 0) {
        if ($('.resultado').is(":visible")) {
            $('.resultado').toggle(200);
        }
    }

    if ($('#busqueda').val().length >= 2) {
        interval = setInterval(busqueda, 500);
    }
    else {
        $('.resultado').empty();
        //$('.resultado').append('<div class="fuente itemSelect itemSelected" data-id="">Ingresa un nombre más largo</div>');
        //$('.resultado').toggle(200);
    }
}

function busqueda() {
    clearInterval(interval);
    guardarBusqueda();

    if (!$('.resultado').is(":visible")) {
        $('.resultado').show();
        var offsetBtn = $("#busqueda").offset();
        $('.resultado').offset({ left: offsetBtn.left });
    }

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: path + '/home/busquedapregunta/',
        data: { busqueda: $('#busqueda').val() }
    }).done(function (json) {
        if (json.result == 1) {
            $('.resultado').empty();

            tagevent('Búsqueda Pregunta');

            $(json.data).each(function (index) {
                $('.resultado').append('<div class="fuente itemSelectBuscador itemSelectPaciente" data-id="' + this.QuestionID + '" data-url="' + this.FriendlyName + '">' + this.Name + '</div>');
            });

            $('.itemSelectPaciente').unbind("click");
            $('.itemSelectPaciente').on("click", function () {
                var id = $(this).attr("data-id");
                var url = $(this).attr("data-url");

                $("#busqueda").val("");
                $('.resultado').toggle(200);

                $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: path + '/home/setquestionvalue/',
                    data: { questionID: id }
                }).done(function (json) {
                    if (json.result) {
                        redirect(path + "/pregunta/" + url);
                    }
                });
            });
        }
        else {
            $('.resultado').empty();
            //$('.resultado').append('<div class="fuente itemSelect itemSelected" data-id="">No hay resultados para la búsqueda</div>');
        }
    });
}

function redirect(url) {
    document.location.href = url;
}

function systemAlert(title, text, callback, tipo) {
    var $alert = $('#system-alert').clone();

    if (tipo == "1") {
        $alert.css('background-image', 'url(' + path + '/Resources/Images/imgUpdate.jpg)');
    }
    else if (tipo == "2") {
        $alert.css('background-image', 'url(' + path + '/Resources/Images/imgOk.jpg)');
    }
    else {
        $alert.css('background-image', 'url(' + path + '/Resources/Images/imgAlert.jpg)');
    }

    $alert.find('#alert-title').html(title);
    $alert.find('#alert-text').html(text);

    $alert.find('#alert-close').click(function () { closeLayer(); callback(); });
    $alert.find('#alert-button').click(function () { closeLayer(); if (callback) { callback(); } });

    openLayer($alert);
}
function systemAlert2(title, text, callback, tipo) {
    var $alert = $('#systemModal').clone();

    if (tipo == "1") {
        $alert.css('background-image', 'url(' + path + '/Resources/Images/imgUpdate.jpg)');
    }
    else if (tipo == "2") {
        $alert.css('background-image', 'url(' + path + '/Resources/Images/imgOk.jpg)');
    }
    else {
        $alert.css('background-image', 'url(' + path + '/Resources/Images/imgAlert.jpg)');
    }

    $alert.find('#alert-title').html(title);
    $alert.find('#alert-text').html(text);

    $alert.find('#alert-close').click(function () { closeLayer(); callback(); });
    $alert.find('#alert-button').click(function () { closeLayer(); if (callback) { callback(); } });

    var popup = new Foundation.Reveal($('#systemModal'));
    popup.open();
}

//  Funcionalidad ventana de Layer

function prepareLayer() {
    var $layer = $('#div-layer');
    $layer.empty();

    $('body').css('overflow', 'hidden');

    $layer.prepend('<img class="theImg" style="margin:11% auto;" src="' + path + '/Resources/Images/loading_c.png" widht="150" height="300" />');

    $layer.css('text-align', 'center');


    $layer.show();
}

function openLayer($content) {
    var $layer = $('#div-layer');
    $layer.empty();
    $content.css({
        bottom: ''
    });

    $content.css({
        bottom: '0px',
        height: $content.height(),
        "z-index": 1
    });

    $('body').css('overflow', 'hidden');
    $layer.append($content).show();

    $layer.css({ 'text-align': 'left', "z-index": 1 });

    setTimeout(resizeLayer, 0);
}

function resizeLayer() {
    var $layer = $('#div-layer');
    var $content = $layer.find('.layer-content');
    $content.css({
        bottom: '',
        height: ''
    });
    $content.css({
        bottom: '0px',
        height: $content.height()
    });
}

function closeLayer() {
    $('#div-layer').empty().hide();
    $('body').css('overflow-y', 'scroll');
}

function clearLayer() {
    $('#div-layer').empty();
    $('body').css('overflow-y', 'scroll');
}

//  Fin Funcionalidad ventana de Layer

function placeholder() {
    var isOperaMini = Object.prototype.toString.call(window.operamini) == '[object OperaMini]';
    var isInputSupported = 'placeholder' in document.createElement('input') && !isOperaMini;
    var isTextareaSupported = 'placeholder' in document.createElement('textarea') && !isOperaMini;
    if (!isInputSupported || !isTextareaSupported) {
        $(document).unbind('ajaxComplete').ajaxComplete(function () {
            if ($('input, textarea').length > 0) {
                if ($('input, textarea').placeholder) {
                    $('input, textarea').placeholder();
                }
                else {
                    setTimeout(placeholder, 10);
                }
            }
        });
        if ($('input, textarea').length > 0) {
            if ($('input, textarea').placeholder) {
                $('input, textarea').placeholder();
            }
            else {
                setTimeout(placeholder, 10);
            }
        }
    }
}

function googleEvents(action, category, label) {
    if (typeof gtag == 'undefined') {
        gtag('config', googleUA, { 'page_path': window.location.href });
    }
    else {
        gtag('config', googleUA, { 'page_path': window.location.href });
        gtag('event', action, {
            'event_category': category,
            'event_label': label
        });
    }
}

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(setLocation);
    }
}

function setLocation(position) {
    var pos = position;
    var latlgn = pos.coords.latitude + ', ' + pos.coords.longitude;

    $.ajax({
        type: 'GET',
        dataType: 'html',
        url: path + '/home/GuardarUbicacion/',
        data: { coordinates: latlgn }
    }).done(function (data) {
        if (data) {

        }
    });
}

// COOKIES

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else {
        var expires = "";
    }

    document.cookie = name + "=" + value + expires + "; path=/";
}

function GetCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }

    return null;
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }

    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

// END COOKIES;
$(document).ready(function () {

    $('.close-modal-gracias').click(function (event) {
        $('.modalGracias').hide();
        $('body').removeClass('body-noscroll');

    });

    $('#submitRate').click(function () {

        var rateContent = new Object();
        rateContent.Rate = $("#rateForm input[type='radio']:checked").val();
        rateContent.Message = $('#rateMessage').val();
        rateContent.url = $('#url').val();
        rateContent.contentId = $('#contentId').val();
        rateContent.token = $("#g-recaptcha-response").val();

        $.ajax({
            url: '/contenido/save/rate',
            type: 'post',
            data: JSON.stringify(rateContent),
            contentType: "application/json; charset=utf-8",
            dataType: "text",
            accepts: "text/plain; charset=utf-8",
            error: function (err) {
                console.error(JSON.stringify(err, null, 2));
            }
        }).done(function (data) {
            data = JSON.parse(data)
            if (data.result != undefined && data.result == false) {
                $("#rateForm input[type='radio']:checked").attr("checked", false);

                $('#rateMessage').val('');
                $('.modalGracias').show();
                $('body').addClass('body-noscroll');
                systemAlert('Que no cunda el panico', 'Tuvimos problemas la enviar tus comentarios. Intenta más tarde.', function () {
                    window.location.reload(true);
                }, "3");
            } else {
                $("#rateForm input[type='radio']:checked").attr("checked", false);

                $('#rateMessage').val('');
                $('.modalGracias').show();
                $('body').addClass('body-noscroll');
            }
        });
    })

})

;
