<!DOCTYPE html>
<html lang="es" id="DXOInteractiveDocument">
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>T&amp;C_EN_v1 - Genera Documentos Online - DOCXPRESSO</title>
        <meta charset="utf-8">

        <meta name="description" content="Descripción de la plantilla.">
        <meta name="keywords" content="etiqueta">
        <link href="/css/plugins/summernote/summernote.css" rel="stylesheet">
        <link href="/css/plugins/summernote/summernote-bs3.css" rel="stylesheet">
        <link href="/css/plugins/toastr/toastr.min.css" rel="stylesheet"/>
        <link href="/css/plugins/docxpresso/docxpresso.css" rel="stylesheet">
        <link href="/css/plugins/docxpresso/tagging.css" rel="stylesheet">
        <link href="/css/plugins/jQueryUI/jquery-ui-1.10.4.custom.min.css" rel="stylesheet">
        <link href="/css/bootstrap.min.css" rel="stylesheet">
        <link href="/font-awesome/css/font-awesome.css" rel="stylesheet">
        <link href="/css/plugins/iCheck/custom.css" rel="stylesheet">
        <link href="/css/plugins/bootstrap-multiselect/bootstrap-multiselect.css" rel="stylesheet">
        <link href="/css/plugins/datapicker/datepicker3.css" rel="stylesheet">
        <link href="/css/plugins/webui-popover/jquery.webui-popover.css" rel="stylesheet">
        <link href="/css/style.css" rel="stylesheet"/>
                        <link href="/templates/skins/css/view.css" rel="stylesheet"/>  
                <!--JQuery-->
        <script src="/js/jquery-2.1.1.js"></script>
        <style>
            /*styles for wysiwigs*/
            #mainDXO .h5p_page p b span {font-weight: bold}
            #mainDXO .h5p_page h1 span {font-weight: inherit; font-family: inherit; font-size: inherit}
            #mainDXO .h5p_page h2 span {font-weight: inherit; font-family: inherit; font-size: inherit}
            #mainDXO .h5p_page h3 span {font-weight: inherit; font-family: inherit; font-size: inherit}
            #mainDXO .h5p_page h4 span {font-weight: inherit; font-family: inherit; font-size: inherit}
        </style>
        <style>
            /* no styles at this level but the ones that suppressed numbering in lists*/
/* This is a spacial class designed to remove unwanted bullets when a li has
ul as its first child*/
.removeBullet:before {
    content: none !important;
}
.DXOHiddenParagraph {
    display: none;
}
.DXOHiddenList:before {
    visibility: hidden;
}
#mainDXO .h5p_page div.Mpm1 {data-width: 59.53032rem;margin-top: 7.08408rem;margin-bottom: 7.08408rem;margin-left: 8.50392rem;margin-right: 8.50392rem;writing-mode: lr-tb;}
.h5p_page_Mpm1 {width: 59.53032rem;}
#mainDXO .h5p_page p.P1 {margin-top: 0rem !important;margin-bottom: 0.7992rem !important;line-height: 1.269 !important;text-align: left !important;orphans: 2 !important;widows: 2 !important;writing-mode: lr-tb;font-size: 1.1rem;}
#mainDXO .h5p_page p.P2 {margin-top: 0rem !important;margin-bottom: 0.7992rem !important;line-height: 1.269 !important;text-align: left !important;orphans: 2 !important;widows: 2 !important;writing-mode: lr-tb;font-size: 1.1rem;}
#mainDXO .h5p_page p.P3 {margin-top: 0rem !important;margin-bottom: 0.7992rem !important;line-height: 1.269 !important;text-align: left !important;orphans: 2 !important;widows: 2 !important;writing-mode: lr-tb;font-size: 1.1rem;}
#mainDXO .h5p_page span.T1 {language: en !important;country: NZ !important;font-size: 1.1rem;}
#mainDXO .h5p_page span.T2 {language: en !important;country: NZ !important;font-weight: bold !important;font-size: 1.1rem;}
#mainDXO .h5p_page p.Standard {margin-top: 0rem !important;margin-bottom: 0.7992rem !important;line-height: 1.269 !important;text-align: left !important;orphans: 2 !important;widows: 2 !important;writing-mode: lr-tb;font-size: 1.1rem;}
#mainDXO .h5p_page p.Heading {margin-top: 0rem !important;margin-bottom: 0.7992rem !important;line-height: 1.269 !important;text-align: left !important;orphans: 2 !important;widows: 2 !important;writing-mode: lr-tb;margin-top: 1.1988rem !important;margin-bottom: 0.6012rem !important;keep-with-next: always !important;font-size: 1.1rem;}
#mainDXO .h5p_page p.Heading span {font-family: Liberation Sans;font-family: 'Liberation Sans';font-size: 1.4rem;}
#mainDXO .h5p_page p.Text_20_body {margin-top: 0rem !important;margin-bottom: 0.7992rem !important;line-height: 1.269 !important;text-align: left !important;orphans: 2 !important;widows: 2 !important;writing-mode: lr-tb;margin-top: 0rem !important;margin-bottom: 0.69984rem !important;line-height: 1.35125 !important;font-size: 1.1rem;}
#mainDXO .h5p_page p.List {margin-top: 0rem !important;margin-bottom: 0.7992rem !important;line-height: 1.269 !important;text-align: left !important;orphans: 2 !important;widows: 2 !important;writing-mode: lr-tb;margin-top: 0rem !important;margin-bottom: 0.69984rem !important;line-height: 1.35125 !important;font-size: 1.1rem;}
#mainDXO .h5p_page p.List span {font-size: 1.1rem;}
#mainDXO .h5p_page p.Caption {margin-top: 0rem !important;margin-bottom: 0.7992rem !important;line-height: 1.269 !important;text-align: left !important;orphans: 2 !important;widows: 2 !important;writing-mode: lr-tb;margin-top: 0.6012rem !important;margin-bottom: 0.6012rem !important;font-size: 1.1rem;}
#mainDXO .h5p_page p.Caption span {font-size: 1.2rem;font-style: italic;}
#mainDXO .h5p_page p.Index {margin-top: 0rem !important;margin-bottom: 0.7992rem !important;line-height: 1.269 !important;text-align: left !important;orphans: 2 !important;widows: 2 !important;writing-mode: lr-tb;font-size: 1.1rem;}
#mainDXO .h5p_page p.Index span {font-size: 1.1rem;}
#mainDXO .h5p_page span.Default_20_Paragraph_20_Font {font-size: 1.1rem;}
#mainDXO .h5p_page span.Internet_20_link {color: #0563c1 !important;text-decoration: underline !important;text-decoration-style: solid !important;text-decoration-color: font-color !important;font-size: 1.1rem;}
#mainDXO .h5p_page span.Unresolved_20_Mention {color: #605e5c !important;background-color: #e1dfdd !important;font-size: 1.1rem;}
#mainDXO .h5p_page span.ListLabel_20_1 {font-size: 1rem !important;}
#mainDXO .h5p_page span.ListLabel_20_2 {font-size: 1rem !important;}
#mainDXO .h5p_page span.ListLabel_20_3 {font-size: 1rem !important;}
#mainDXO .h5p_page span.ListLabel_20_4 {font-size: 1rem !important;}
#mainDXO .h5p_page span.ListLabel_20_5 {font-size: 1rem !important;}
#mainDXO .h5p_page span.ListLabel_20_6 {font-size: 1rem !important;}
#mainDXO .h5p_page span.ListLabel_20_7 {font-size: 1rem !important;}
#mainDXO .h5p_page span.ListLabel_20_8 {font-size: 1rem !important;}
#mainDXO .h5p_page span.ListLabel_20_9 {font-size: 1rem !important;}
#mainDXO .h5p_page ul.No_20_List {counter-reset: ulNo_20_List_1;margin-left: 0;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.No_20_List ul {counter-reset: ulNo_20_List_2;margin-left: -0.5in;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.No_20_List li {margin-left: 0.5in;text-indent: -0.25in;font-size: 1.1rem;}
#mainDXO .h5p_page ul.No_20_List li:before {counter-increment: ulNo_20_List_1;content: counter(ulNo_20_List_1, decimal)  ". ";margin-left: -0.25in;display: table-cell;}
#mainDXO .h5p_page ul.No_20_List ul ul {counter-reset: ulNo_20_List_3;margin-left: -0.75in;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.No_20_List li ul li {margin-left: 0.75in;text-indent: -0.25in;font-size: 1.1rem;}
#mainDXO .h5p_page ul.No_20_List li ul li:before {counter-increment: ulNo_20_List_2;content: counter(ulNo_20_List_2, decimal)  ". ";margin-left: -0.25in;display: table-cell;}
#mainDXO .h5p_page ul.No_20_List ul ul ul {counter-reset: ulNo_20_List_4;margin-left: -1in;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.No_20_List li ul li ul li {margin-left: 1in;text-indent: -0.25in;font-size: 1.1rem;}
#mainDXO .h5p_page ul.No_20_List li ul li ul li:before {counter-increment: ulNo_20_List_3;content: counter(ulNo_20_List_3, decimal)  ". ";margin-left: -0.25in;display: table-cell;}
#mainDXO .h5p_page ul.No_20_List ul ul ul ul {counter-reset: ulNo_20_List_5;margin-left: -1.25in;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.No_20_List li ul li ul li ul li {margin-left: 1.25in;text-indent: -0.25in;font-size: 1.1rem;}
#mainDXO .h5p_page ul.No_20_List li ul li ul li ul li:before {counter-increment: ulNo_20_List_4;content: counter(ulNo_20_List_4, decimal)  ". ";margin-left: -0.25in;display: table-cell;}
#mainDXO .h5p_page ul.No_20_List ul ul ul ul ul {counter-reset: ulNo_20_List_6;margin-left: -1.5in;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.No_20_List li ul li ul li ul li ul li {margin-left: 1.5in;text-indent: -0.25in;font-size: 1.1rem;}
#mainDXO .h5p_page ul.No_20_List li ul li ul li ul li ul li:before {counter-increment: ulNo_20_List_5;content: counter(ulNo_20_List_5, decimal)  ". ";margin-left: -0.25in;display: table-cell;}
#mainDXO .h5p_page ul.No_20_List ul ul ul ul ul ul {counter-reset: ulNo_20_List_7;margin-left: -1.75in;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.No_20_List li ul li ul li ul li ul li ul li {margin-left: 1.75in;text-indent: -0.25in;font-size: 1.1rem;}
#mainDXO .h5p_page ul.No_20_List li ul li ul li ul li ul li ul li:before {counter-increment: ulNo_20_List_6;content: counter(ulNo_20_List_6, decimal)  ". ";margin-left: -0.25in;display: table-cell;}
#mainDXO .h5p_page ul.No_20_List ul ul ul ul ul ul ul {counter-reset: ulNo_20_List_8;margin-left: -2in;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.No_20_List li ul li ul li ul li ul li ul li ul li {margin-left: 2in;text-indent: -0.25in;font-size: 1.1rem;}
#mainDXO .h5p_page ul.No_20_List li ul li ul li ul li ul li ul li ul li:before {counter-increment: ulNo_20_List_7;content: counter(ulNo_20_List_7, decimal)  ". ";margin-left: -0.25in;display: table-cell;}
#mainDXO .h5p_page ul.No_20_List ul ul ul ul ul ul ul ul {counter-reset: ulNo_20_List_9;margin-left: -2.25in;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.No_20_List li ul li ul li ul li ul li ul li ul li ul li {margin-left: 2.25in;text-indent: -0.25in;font-size: 1.1rem;}
#mainDXO .h5p_page ul.No_20_List li ul li ul li ul li ul li ul li ul li ul li:before {counter-increment: ulNo_20_List_8;content: counter(ulNo_20_List_8, decimal)  ". ";margin-left: -0.25in;display: table-cell;}
#mainDXO .h5p_page ul.No_20_List ul ul ul ul ul ul ul ul ul {counter-reset: ulNo_20_List_10;margin-left: -2.5in;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.No_20_List li ul li ul li ul li ul li ul li ul li ul li ul li {margin-left: 2.5in;text-indent: -0.25in;font-size: 1.1rem;}
#mainDXO .h5p_page ul.No_20_List li ul li ul li ul li ul li ul li ul li ul li ul li:before {counter-increment: ulNo_20_List_9;content: counter(ulNo_20_List_9, decimal)  ". ";margin-left: -0.25in;display: table-cell;}
#mainDXO .h5p_page ul.No_20_List ul ul ul ul ul ul ul ul ul ul {counter-reset: ulNo_20_List_11;margin-left: -2.75in;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.No_20_List li ul li ul li ul li ul li ul li ul li ul li ul li ul li {margin-left: 2.75in;text-indent: -0.25in;font-size: 1.1rem;}
#mainDXO .h5p_page ul.No_20_List li ul li ul li ul li ul li ul li ul li ul li ul li ul li:before {counter-increment: ulNo_20_List_10;content: counter(ulNo_20_List_10, decimal)  ". ";margin-left: -0.25in;display: table-cell;}
#mainDXO .h5p_page ul.WWNum1 {margin-left: 0;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum1 ul {margin-left: -0.5in;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum1 li {margin-left: 0.5in;text-indent: -0.25in;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum1 li:before {font-size: 1rem !important;content: "\2022";font-family: Verdana;counter-increment: ulWWNum1_1;margin-left: -0.25in;display: table-cell;display: table-cell;}
#mainDXO .h5p_page ul.WWNum1 ul ul {margin-left: -1in;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum1 li ul li {margin-left: 1in;text-indent: -0.25in;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum1 li ul li:before {font-size: 1rem !important;content: "o";counter-increment: ulWWNum1_2;margin-left: -0.25in;display: table-cell;display: table-cell;}
#mainDXO .h5p_page ul.WWNum1 ul ul ul {margin-left: -1.5in;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum1 li ul li ul li {margin-left: 1.5in;text-indent: -0.25in;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum1 li ul li ul li:before {font-size: 1rem !important;content: "\25aa";counter-increment: ulWWNum1_3;margin-left: -0.25in;display: table-cell;display: table-cell;}
#mainDXO .h5p_page ul.WWNum1 ul ul ul ul {margin-left: -2in;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum1 li ul li ul li ul li {margin-left: 2in;text-indent: -0.25in;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum1 li ul li ul li ul li:before {font-size: 1rem !important;content: "\25aa";counter-increment: ulWWNum1_4;margin-left: -0.25in;display: table-cell;display: table-cell;}
#mainDXO .h5p_page ul.WWNum1 ul ul ul ul ul {margin-left: -2.5in;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum1 li ul li ul li ul li ul li {margin-left: 2.5in;text-indent: -0.25in;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum1 li ul li ul li ul li ul li:before {font-size: 1rem !important;content: "\25aa";counter-increment: ulWWNum1_5;margin-left: -0.25in;display: table-cell;display: table-cell;}
#mainDXO .h5p_page ul.WWNum1 ul ul ul ul ul ul {margin-left: -3in;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum1 li ul li ul li ul li ul li ul li {margin-left: 3in;text-indent: -0.25in;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum1 li ul li ul li ul li ul li ul li:before {font-size: 1rem !important;content: "\25aa";counter-increment: ulWWNum1_6;margin-left: -0.25in;display: table-cell;display: table-cell;}
#mainDXO .h5p_page ul.WWNum1 ul ul ul ul ul ul ul {margin-left: -3.5in;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum1 li ul li ul li ul li ul li ul li ul li {margin-left: 3.5in;text-indent: -0.25in;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum1 li ul li ul li ul li ul li ul li ul li:before {font-size: 1rem !important;content: "\25aa";counter-increment: ulWWNum1_7;margin-left: -0.25in;display: table-cell;display: table-cell;}
#mainDXO .h5p_page ul.WWNum1 ul ul ul ul ul ul ul ul {margin-left: -4in;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum1 li ul li ul li ul li ul li ul li ul li ul li {margin-left: 4in;text-indent: -0.25in;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum1 li ul li ul li ul li ul li ul li ul li ul li:before {font-size: 1rem !important;content: "\25aa";counter-increment: ulWWNum1_8;margin-left: -0.25in;display: table-cell;display: table-cell;}
#mainDXO .h5p_page ul.WWNum1 ul ul ul ul ul ul ul ul ul {margin-left: -4.5in;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum1 li ul li ul li ul li ul li ul li ul li ul li ul li {margin-left: 4.5in;text-indent: -0.25in;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum1 li ul li ul li ul li ul li ul li ul li ul li ul li:before {font-size: 1rem !important;content: "\25aa";counter-increment: ulWWNum1_9;margin-left: -0.25in;display: table-cell;display: table-cell;}
#mainDXO .h5p_page ul.WWNum1 ul ul ul ul ul ul ul ul ul ul {counter-reset: ulWWNum1_11;margin-left: -2.75in;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum1 li ul li ul li ul li ul li ul li ul li ul li ul li ul li {margin-left: 2.75in;text-indent: -0.25in;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum1 li ul li ul li ul li ul li ul li ul li ul li ul li ul li:before {counter-increment: ulWWNum1_10;content: counter(ulWWNum1_10, decimal)  ". ";margin-left: -0.25in;display: table-cell;}
#mainDXO .h5p_page ul.WWNum2 {counter-reset: ulWWNum2_1;margin-left: 0;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum2 ul {counter-reset: ulWWNum2_2;margin-left: 0;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum2 li {font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum2 li:before {counter-increment: ulWWNum2_1;content: counter(ulWWNum2_1, decimal)  ". ";display: table-cell;}
#mainDXO .h5p_page ul.WWNum2 ul ul {counter-reset: ulWWNum2_3;margin-left: 0;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum2 li ul li {font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum2 li ul li:before {counter-increment: ulWWNum2_2;content: counter(ulWWNum2_2, decimal)  ". ";display: table-cell;}
#mainDXO .h5p_page ul.WWNum2 ul ul ul {counter-reset: ulWWNum2_4;margin-left: 0;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum2 li ul li ul li {font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum2 li ul li ul li:before {counter-increment: ulWWNum2_3;content: counter(ulWWNum2_3, decimal)  ". ";display: table-cell;}
#mainDXO .h5p_page ul.WWNum2 ul ul ul ul {counter-reset: ulWWNum2_5;margin-left: 0;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum2 li ul li ul li ul li {font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum2 li ul li ul li ul li:before {counter-increment: ulWWNum2_4;content: counter(ulWWNum2_4, decimal)  ". ";display: table-cell;}
#mainDXO .h5p_page ul.WWNum2 ul ul ul ul ul {counter-reset: ulWWNum2_6;margin-left: 0;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum2 li ul li ul li ul li ul li {font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum2 li ul li ul li ul li ul li:before {counter-increment: ulWWNum2_5;content: counter(ulWWNum2_5, decimal)  ". ";display: table-cell;}
#mainDXO .h5p_page ul.WWNum2 ul ul ul ul ul ul {counter-reset: ulWWNum2_7;margin-left: 0;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum2 li ul li ul li ul li ul li ul li {font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum2 li ul li ul li ul li ul li ul li:before {counter-increment: ulWWNum2_6;content: counter(ulWWNum2_6, decimal)  ". ";display: table-cell;}
#mainDXO .h5p_page ul.WWNum2 ul ul ul ul ul ul ul {counter-reset: ulWWNum2_8;margin-left: 0;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum2 li ul li ul li ul li ul li ul li ul li {font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum2 li ul li ul li ul li ul li ul li ul li:before {counter-increment: ulWWNum2_7;content: counter(ulWWNum2_7, decimal)  ". ";display: table-cell;}
#mainDXO .h5p_page ul.WWNum2 ul ul ul ul ul ul ul ul {counter-reset: ulWWNum2_9;margin-left: 0;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum2 li ul li ul li ul li ul li ul li ul li ul li {font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum2 li ul li ul li ul li ul li ul li ul li ul li:before {counter-increment: ulWWNum2_8;content: counter(ulWWNum2_8, decimal)  ". ";display: table-cell;}
#mainDXO .h5p_page ul.WWNum2 ul ul ul ul ul ul ul ul ul {counter-reset: ulWWNum2_10;margin-left: 0;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum2 li ul li ul li ul li ul li ul li ul li ul li ul li {font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum2 li ul li ul li ul li ul li ul li ul li ul li ul li:before {counter-increment: ulWWNum2_9;content: counter(ulWWNum2_9, decimal)  ". ";display: table-cell;}
#mainDXO .h5p_page ul.WWNum2 ul ul ul ul ul ul ul ul ul ul {counter-reset: ulWWNum2_11;margin-left: -2.75in;padding: 0; list-style-type: none;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum2 li ul li ul li ul li ul li ul li ul li ul li ul li ul li {margin-left: 2.75in;text-indent: -0.25in;font-size: 1.1rem;}
#mainDXO .h5p_page ul.WWNum2 li ul li ul li ul li ul li ul li ul li ul li ul li ul li:before {counter-increment: ulWWNum2_10;content: counter(ulWWNum2_10, decimal)  ". ";margin-left: -0.25in;display: table-cell;}
#mainDXO .h5p_page div {font-size: 1.1rem;}
#mainDXO .h5p_page p {hyphenation-ladder-count: no-limit;writing-mode: page;font-size: 1.1rem;}
#mainDXO .h5p_page p span {font-family: Calibri;font-size: 1.1rem;language: es;country: ES;hyphenate: false;hyphenation-remain-char-count: 2;hyphenation-push-char-count: 2;}
#mainDXO .h5p_page span {font-family: Calibri;font-size: 1.1rem;language: es;country: ES;hyphenate: false;hyphenation-remain-char-count: 2;hyphenation-push-char-count: 2;}
#mainDXO .h5p_page table {border-collapse: collapse;font-size: 1.1rem;}
#mainDXO .h5p_page table tr {keep-together: auto;font-size: 1.1rem;}
   
        </style>

        <style>
            #saveLocalTools {display: none !important}
#validators {display: none !important}
#progress {display: none !important}
html body {overflow-x: auto !important}
#dxfooter {display: none !important}
            .h5p_page {padding-right: initial;}
            .h5p_page::after {border-right: none}
            body {background-color: #fff; padding-bottom: 30px}
            .note-editor {height: auto !important; box-sizing: border-box !important}
            .note-editor .note-toolbar {background-color: transparent !important; border-bottom: none !important}
            .note-editor .note-color-palette div .note-color-btn {box-sizing: border-box !important;}
            .note-editor .note-toolbar .note-para .dropdown-menu {box-sizing: border-box !important;}
            .form-control {height: auto !important}
            .form-group {margin-bottom: 0}
            .ibox-title {height: 18px}
            .ibox-title h5 {font-size: 13px}
            .modal-body {padding: 10px 40px 10px 10px; font-size: 13px}
            .modal-body input {font-size: 13px !important}
            .modal-body select {font-size: 13px !important}
            .hr-line-dashed {margin: 4px 0}
            .inmodal .modal-header {padding: 10px 15px 8px 15px; font-size: 16px}
            #shareModal .chosen-container *{box-sizing: border-box !important;}
            #shareModal .chosen-container-multi .chosen-choices li.search-choice {background: #f1f1f1;box-shadow: none;color: #333333;cursor: default;line-height: 13px;margin: 3px 0 3px 4px;padding: 3px 18px 3px 5px;position: relative;}
            /* datepicker override */
            th.datepicker-switch, th.next, th.prev, th.dow {font-size: inherit}
            .datepicker tfoot tr th {font-size: inherit; padding: 0}
            #history-frame {background-image: url(/css/preloader.gif)}
                        #mainDXO section.h5p_page span.spanWrapperIcon:before {content:"" !important}
            #mainDXO section.h5p_page span.spanWrapperBackground {padding: 0 0 1px 0 !important; border: none !important; background-color: #555 !important; color: #fff !important; border-radius: 0px !important}
            #mainDXO section.h5p_page span.spanWrapperBackground span {color: #fff !important;}
            #mainDXO section.h5p_page span.spanWrapperBackground span.h5p_varspan {background-color: inherit !important; color: #fff !important}
            #mainDXO select {background-color: #555 !important; color: #fff}
            #mainDXO section.h5p_page span.spanWrapperBackground a {color: #eee !important}
                        .docFrame::-webkit-scrollbar {
                width: 10px;
                height: 10px;
                background-color: #eee;
            }
            .docFrame::-webkit-scrollbar-thumb {
                background-color: #777;
            }
            .docFrame::-webkit-scrollbar-track {
                background-color: #eee;
            } 
            .docFrame {
                scrollbar-width: thin;
                scrollbar-color: #777 #eee;
            }
            /* mark */
            #mainDXO mark {background-color: rgba(154, 205, 50, 0.5) !important;}
        </style>
    </head>

    <body class="docFrame">
        
        <a href="#" class="btn btn-success" id="goTop" onclick="return false" aria-label="Ir al inicio de la página"><i class="fa fa-chevron-up" aria-hidden="true"> </i></a>
        <!-- custom message modal -->
        <div class="modal inmodal fade" id="messageModal" tabindex="-1" role="dialog"  aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                        <h3 id="acceptedDoc"><i class="fa fa-check green"> </i> Aceptado</h3>
                        <h3 id="rejectedDoc" style="display:none"><i class="fa fa-times-circle red"> </i> Rechazado</h3>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-sm-12">
                                    <div class="form-horizontal">
                                        <div class="ibox float-e-margins">
                                            <div class="ibox-title" style="border: none">
                                                <h5>Comentarios</h5>
                                            </div>
                                            <div class="ibox-content no-padding">
                                                <div class="summernoteValidation" id="saveComment"></div>
                                            </div>
                                        </div>
                                    </div>          
                            </div>              
                        </div>  
                                                                    </div>
                    <div class="modal-footer" style="border-top: none">
                        <button type="button" class="btn btn-white btn-sm" data-dismiss="modal">Cerrar</button>
                        <button type="button" class="btn btn-primary btn-sm" id="saveValidation">Enviar</button>
                    </div>
                </div>
            </div>
        </div>
                <!-- workflow modal -->
        <div class="modal inmodal fade" id="wfModal" tabindex="-1" role="dialog"  aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                        <h3 id="acceptedDoc"><i class="fa fa-sitemap"> </i> Workflow
                                                </h3>
                    </div>
                    <div class="modal-body">
                        <div>
                                                            <div class="col-lg-12">
                                    <p style="text-align: center"><i class="fa fa-exclamation-circle"> </i> No hay un workflow definido.</p>
                                </div>
                                                    </div>                        
                    </div>
                    <div class="modal-footer" style="border-top: none;">
                        <button type="button" class="btn btn-white btn-sm m-t-sm" data-dismiss="modal">Cerrar</button>
                    </div>
                </div>
            </div>
        </div>
                    
        <!-- attachment modal -->
        <div class="modal inmodal" id="attachmentModal" tabindex="-1" role="dialog" data-backdrop="static" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content animated fadeIn">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Cerrar</span></button>
                        <strong><i class="fa fa-paperclip" aria-hidden="true"></i> Archivos adjuntos</strong>
                    </div>
                    <div class="modal-body" style="max-height: 300px; overflow-y: auto; overflow-x: hidden">
                        <div class="row">
                            <div class="col-sm-12">
                                <div class="form-horizontal">
                                 
                                </div>
                            </div>              
                        </div>                        
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-white btn-sm" data-dismiss="modal">Cerrar</button>
                    </div>
                </div>
            </div>
        </div>
        
                    
        <div id="fixedbar" >
            <div id="topToolBar" class="note-editor">
                <div class="note-toolbar btn-toolbar">
                                        <form id="">
                        <div id="saveTools" class="btn-group"  style="display: none; margin-top: -6px; float: right; padding-top: 0; padding-left: 5px; padding-right: 20px">
                            <button id="cancelGo" style="display:none" class="btn btn-danger btn-sm btn-small" onclick="javascript:history.back();"> <i class="fa fa-times" aria-hidden="true"> </i> <span class="buttonTop"> </span></button>
                                                <input type="hidden" name="workflow" id="workflow" value="0" />
                        <input type="hidden" name="microsite" id="microsite" value="0" />
                        <input type="hidden" name="name" id="name" value="" />
                        <input type="hidden" name="email" id="email" value="" />
                        <input type="hidden" name="useremail" id="useremail" value="" />
                        <input type="hidden" name="comments" id="comments" value="" />
                        <input type="hidden" name="validationComments" id="validationComments" value="" />
                        <input type="hidden" name="forwardRejection" id="forwardRejection" value="" />
                        <input type="hidden" name="token" id="token" value="0" />
                        <input type="hidden" name="trackID" id="trackID" value="" />
                        <input type="hidden" name="usageId" id="usageId" value="" />
                        <input type="hidden" name="percentComp" id="percentComp" value="" />
                        <input type="hidden" name="preAttached" id="preAttached" value="{}" />
                        <input type="hidden" name="captcha" id="captcha" value="0" />
                        <input type="hidden" name="captchaStamp" id="captchaStamp" value="1679642029.7" />
                        <input type="hidden" name="captchaHash" id="captchaHash" value="9c45ab6dd0e586690124171dabc4ab91d25ce410" />
                        <input type="hidden" name="locale" id="locale" value="es" />
                        <input type="hidden" name="validate" id="validate" value="" />
                        <input type="hidden" name="timestamp" id="timestamp" value="1679642019" />
                        <input type="hidden" name="openTime" id="openTime" value="1679642029" />
                        <input type="hidden" name="uniqid" id="uniqid" value="641d4da3740a15172957" />
                        <input type="hidden" name="APIKEY" id="APIKEY" value="8f4a4161331f1deaa5fca137be716233aac8052e" />
                        <input type="hidden" name="responseDataURI" id="responseDataURI" value="" />
                        <input type="hidden" name="flattenResponse" id="flattenResponse" value="0" />
                        <input type="hidden" name="processingDataURI" id="processingDataURI" value="" />
                        <input type="hidden" name="responseURL" id="responseURL" value="" />
                                                </div>
                    </form>
                    
                    <div id="progress">
                        <div id="progressBarTool">
                            <div id="progressBar"> </div>
                        </div>
                        <div id="progressValue"> 0% </div>
                    </div>
                    

                </div>
            </div>
        </div> 
        
        <!--History info-->
                        
                
        
        
        <!--<div id="h5p-tooltip-wrapper"><div id="h5p-tooltip">tooltip</div><div id="h5p-tooltip-arrow"></div></div>-->
        
        <div id="mainDXO">
        <section id="section_0" class="h5p_layout h5p_page h5p_page_Mpm1"><div class="Mpm1" data-layout="Mpm1" data-w="59.53032rem" data-ml="8.50392rem" data-mr="8.50392rem"><p data-h5p="text:p=1" class="P3"><span data-h5p="text:span=1" class="T2">Terms &amp; Conditions</span></p><p data-h5p="text:p=2" class="Standard"><span data-h5p="text:span=2" class="T1">These Terms and Conditions (the "</span><span data-h5p="text:span=3" class="T2">Terms</span><span data-h5p="text:span=4" class="T1">") will apply to the provision by Teladoc Health (hereinafter "</span><span data-h5p="text:span=5" class="T2">Teladoc” </span><span data-h5p="text:span=6" class="T1">or “</span><span data-h5p="text:span=7" class="T2">us</span><span data-h5p="text:span=8" class="T1">") of Vero Connected Care (hereinafter the “</span><span data-h5p="text:span=9" class="T2">Portal</span><span data-h5p="text:span=10" class="T1">") to eligible members, defined as a member or a Policyholder that includes the Services as defined within a services agreement between Vero Insurance and Teladoc.</span></p><p data-h5p="text:p=3" class="Standard"><span data-h5p="text:span=11" class="T1">Please read these Terms carefully and make sure that you understand them.</span></p><p data-h5p="text:p=4" class="Standard"><span data-h5p="text:span=12" class="T1">You will be asked to agree to these Terms before registering on the portal. By clicking "I AGREE" you are entering into a legally binding agreement with Teladoc and expressly accepting these Terms and the Privacy Policy.</span></p><p data-h5p="text:p=5" class="Standard"><span data-h5p="text:span=13" class="T1">Acceptance of these Terms is a condition of use for the Service.</span></p><p data-h5p="text:p=6" class="Standard"><span data-h5p="text:span=14" class="T2">Vero Insurance</span></p><p data-h5p="text:p=7" class="Standard"><span data-h5p="text:span=15" class="T1">The purpose of the Portal is to make routine, non-emergency communication more convenient and to provide you with fast and secure access to our Services.</span></p><p data-h5p="text:p=8" class="Standard"><span data-h5p="text:span=16" class="T1">In case of a medical emergency, do not use the Portal to communicate with us.<br data-h5p="text:line-break=1"/>Please dial the relevant local emergency number for the country you are in, and then contact your treating doctor.</span></p><p data-h5p="text:p=9" class="Standard"><span data-h5p="text:span=17" class="T2">Service limitation/restrictions</span></p><p data-h5p="text:p=10" class="Standard"><span data-h5p="text:span=18" class="T1">The Portal has, by its own nature certain limitations/restrictions regarding the Service and does not replace face-to-face consultations with your treating doctor or primary healthcare practitioner, nor does it replace primary healthcare. Face-to face consultations are always essential in cases of medical emergencies and where physical examination/intervention is required.</span></p><p data-h5p="text:p=11" class="Standard"><span data-h5p="text:span=19" class="T1">You are responsible for providing the Healthcare Professionals with the information that they advise is required in order to provide you with the Service.</span></p><p data-h5p="text:p=12" class="Standard"><span data-h5p="text:span=20" class="T1">If following use of the Portal, you have doubts or concerns regarding the professional advice/service provided, or regarding your health and wellbeing, please seek further medical assistance in a regular face-to-face consultation.</span></p><p data-h5p="text:p=13" class="Standard"><span data-h5p="text:span=21" class="T1">As with any other healthcare service, no results can be guaranteed or assured.</span></p><p data-h5p="text:p=14" class="Standard"><span data-h5p="text:span=22" class="T2">Privacy</span></p><p data-h5p="text:p=15" class="Standard"><span data-h5p="text:span=23" class="T1">Teladoc provides its services in compliance with New Zealand Privacy laws. Please refer to the Privacy Statement for details.</span></p><p data-h5p="text:p=16" class="Standard"><span data-h5p="text:span=24" class="T2">Identity Checks and Authentication</span></p><p data-h5p="text:p=17" class="Standard"><span data-h5p="text:span=25" class="T1">1) Initial authentication: Performing a physical comparison by photo ID verification:</span></p><p data-h5p="text:p=18" class="Standard"><span data-h5p="text:span=26" class="T1">To access our Service, we may request an identity check. This only ever needs to be done once when we collect your initial written consent. Thereafter we will simply ask a combination of security questions along with your contact details. If the photographic ID does not have the address, then we will ask for a further non-photographic document to confirm the patient address. This process should ordinarily only take a few minutes.</span></p><p data-h5p="text:p=19" class="Standard"><span data-h5p="text:span=27" class="T1">New Patient Registrations through our APP: our agent will simultaneously assign the case to one of our doctors and send the patient an email explaining the identity check process.</span></p><p data-h5p="text:p=20" class="Standard"><span data-h5p="text:span=28" class="T1">1) We will ask the patient to verify identity by taking a picture of their passport, driver license, National Identity card, or residence permit and thereafter following a few short steps where they will take a "selfie" and the identity check will be complete.</span></p><p data-h5p="text:p=21" class="Standard"><span data-h5p="text:span=29" class="T1">If the photographic ID does not have the address, then we will ask for a further non-photographic document to confirm the patient address. This process should ordinarily only take a few minutes.</span></p><p data-h5p="text:p=22" class="Standard"><span data-h5p="text:span=30" class="T1">2) If the patient is consulting on behalf of their child, we will ask for proof of parental responsibility before creating a unique file for the child. This will usually be a birth certificate.</span></p><p data-h5p="text:p=23" class="Standard"><span data-h5p="text:span=31" class="T1">3) Ongoing authentication:</span></p><p data-h5p="text:p=24" class="Standard"><span data-h5p="text:span=32" class="T1">a: Check credentials against eligibility data provided by the client (Vero Insurance)</span></p><p data-h5p="text:p=25" class="Standard"><span data-h5p="text:span=33" class="T1">b: The first time a member uses the portal, they will provide identifying information – name, email address and date of birth.</span></p><p data-h5p="text:p=26" class="Standard"><span data-h5p="text:span=34" class="T1">c: We will confirm identity by asking security questions when speaking with the member. This way, we ensure we are talking to the correct person. Audits are performed to ensure that the above-mentioned process is followed by listening to phone recordings and ensuring that the protocol is accurately being used.</span></p><p data-h5p="text:p=27" class="Standard"><span data-h5p="text:span=35" class="T2">Prescriptions</span></p><p data-h5p="text:p=28" class="Standard"><span data-h5p="text:span=36" class="T1">Our Health Professionals do not issue prescription for medicines or referrals to specialists. If you would like a prescription or referral, please contact your treating doctor. You agree that: (i) you will not request prescriptions or referrals from the Health Professional; (ii) to contact your treating doctor for prescriptions and referrals.</span></p><p data-h5p="text:p=29" class="Standard"><span data-h5p="text:span=37" class="T2">User Account and Eligibility</span></p><p data-h5p="text:p=30" class="Standard"><span data-h5p="text:span=38" class="T1">When registering on the Portal you will be required to create an account by providing us with your preferred email address. You will then receive an email with login credentials to the Portal. To create an account, you confirm that you are older than 18 years of age. If you are under 18 years of age, you may not register to use the Service. You may not transfer or share your login credentials with anyone or create more than one account (with the exception provided below). Under no circumstances may you use someone else's account.</span></p><p data-h5p="text:p=31" class="Standard"><span data-h5p="text:span=39" class="T2">Use of Service by minors</span></p><p data-h5p="text:p=32" class="Standard"><span data-h5p="text:span=40" class="T1">The Service is not available for persons under 18 years of age. However, the Account holder for any User under the age of 18 must be the User's parents or legal guardian. If you register as the parent or legal guardian, you will be fully responsible for complying with these Terms.</span></p><p data-h5p="text:p=33" class="Standard"><span data-h5p="text:span=41" class="T2">Acceptable Use Policies</span></p><p data-h5p="text:p=34" class="Standard"><span data-h5p="text:span=42" class="T1">You agree not to use the Portal for any purpose other than to request a case or communicate with us about your case.</span></p><p data-h5p="text:p=35" class="Standard"><span data-h5p="text:span=43" class="T1">In particular, you agree that you will not attempt to:</span></p><ul data-h5p="text:list=1" class="WWNum1" id="list4275310638" style="counter-reset: ulWWNum1_1 0;"><li style="color: initial; font-family: initial;margin-top: 0rem !important;margin-bottom: 0.7992rem !important;line-height: 1.269 !important;text-align: left !important;orphans: 2 !important;widows: 2 !important;writing-mode: lr-tb;" data-h5p="text:list-item=1"><p style="display: table-cell;margin-left:0 !important;text-indent: 0 !important;" data-h5p="text:p=36" class="P1"><span data-h5p="text:span=44" class="T1">impersonate any person or entity, or misrepresent your affiliation with a person or entity;</span></p></li><li style="color: initial; font-family: initial;margin-top: 0rem !important;margin-bottom: 0.7992rem !important;line-height: 1.269 !important;text-align: left !important;orphans: 2 !important;widows: 2 !important;writing-mode: lr-tb;" data-h5p="text:list-item=2"><p style="display: table-cell;margin-left:0 !important;text-indent: 0 !important;" data-h5p="text:p=37" class="P1"><span data-h5p="text:span=45" class="T1">use the Portal or the Service to violate any laws or regulations;</span></p></li><li style="color: initial; font-family: initial;margin-top: 0rem !important;margin-bottom: 0.7992rem !important;line-height: 1.269 !important;text-align: left !important;orphans: 2 !important;widows: 2 !important;writing-mode: lr-tb;" data-h5p="text:list-item=3"><p style="display: table-cell;margin-left:0 !important;text-indent: 0 !important;" data-h5p="text:p=38" class="P1"><span data-h5p="text:span=46" class="T1">decompile, reverse-engineer, disassemble or translate any software or other components that the Portal or the Service utilizes;</span></p></li><li style="color: initial; font-family: initial;margin-top: 0rem !important;margin-bottom: 0.7992rem !important;line-height: 1.269 !important;text-align: left !important;orphans: 2 !important;widows: 2 !important;writing-mode: lr-tb;" data-h5p="text:list-item=4"><p style="display: table-cell;margin-left:0 !important;text-indent: 0 !important;" data-h5p="text:p=39" class="P1"><span data-h5p="text:span=47" class="T1">distribute viruses or other harmful computer code through the Portal;</span></p></li><li style="color: initial; font-family: initial;margin-top: 0rem !important;margin-bottom: 0.7992rem !important;line-height: 1.269 !important;text-align: left !important;orphans: 2 !important;widows: 2 !important;writing-mode: lr-tb;" data-h5p="text:list-item=5"><p style="display: table-cell;margin-left:0 !important;text-indent: 0 !important;" data-h5p="text:p=40" class="P1"><span data-h5p="text:span=48" class="T1">circumvent any security safeguard that we use to protect the security of our information systems; or otherwise use the Portal or the Service in any manner that exceeds its scope of use.</span></p></li></ul><p data-h5p="text:p=41" class="Standard"><span data-h5p="text:span=49" class="T2">Intellectual Property</span></p><p data-h5p="text:p=42" class="Standard"><span data-h5p="text:span=50" class="T1">All copyright material contained within this Portal is the property of Teladoc, or Teladoc has the adequate licenses to use it. Any access to this material by you does not entitle you to any license or right for the reproduction and/or distribution and you must not do so without explicit, prior written consent from Teladoc, which may constitute a serious offence of Intellectual and industrial property.</span></p><p data-h5p="text:p=43" class="Standard"><span data-h5p="text:span=51" class="T2">Communications</span></p><p data-h5p="text:p=44" class="Standard"><span data-h5p="text:span=52" class="T1">The Portal has safeguards that are intended to prevent unauthorized parties from being able to access or read messages while they are in transmission. However, keeping messages secure depends on two important factors. First, we need you to make sure we have your correct email and contact data and you must inform us if it ever changes. Second, you should keep your Portal username and password confidential and not share with others. If you think someone knows your password, you should notify us at </span><a data-h5p="text:a=1" href="mailto:privacyanz@teladochealth.com" target="" title=""><span data-h5p="text:span=53" class="T1">privacyanz@teladochealth.com</span></a><span data-h5p="text:span=54" class="T1"> and promptly log into the Portal and change it.</span></p><p data-h5p="text:p=45" class="Standard"><span data-h5p="text:span=55" class="T1">Depending on your preferred method of communication, you will receive an email or phone call whenever you have scheduled an appointment through the Portal.</span></p><p data-h5p="text:p=46" class="Standard"><span data-h5p="text:span=56" class="T1">Messages and files sent and received through the Portal may be included in our records and may be deleted in accordance with our records retention policy.</span></p><p data-h5p="text:p=47" class="Standard"><span data-h5p="text:span=57" class="T1">The operation of the Portal may be interrupted by problems with computer hardware or software, interruptions in internet services, computer viruses or other problems beyond our control. If you need to reach us in the event of a service outage, you can contact us through the phone number in the contact us at 0800 425 005.</span></p><p data-h5p="text:p=48" class="Standard"><span data-h5p="text:span=58" class="T2">Termination</span></p><p data-h5p="text:p=49" class="Standard"><span data-h5p="text:span=59" class="T1">Teladoc reserves the right to suspend or terminate your use of the Portal and/or your account for any reason at any time.</span></p><p data-h5p="text:p=50" class="Standard"><span data-h5p="text:span=60" class="T1">You may deactivate your account for any reason at any time by sending an email to </span><a data-h5p="text:a=2" href="mailto:medicalanz@teladochealth.com" target="" title=""><span data-h5p="text:span=61" class="T1">medicalanz@teladochealth.com</span></a></p><p data-h5p="text:p=51" class="Standard"><span data-h5p="text:span=62" class="T1">After termination, we will have no further obligation to provide you the Service.</span></p><p data-h5p="text:p=52" class="Standard"><span data-h5p="text:span=63" class="T2">Modification, discontinuation or suspension of the Portal</span></p><p data-h5p="text:p=53" class="Standard"><span data-h5p="text:span=64" class="T1">We may modify, discontinue, or suspend the Portal service for any reason at any time. We will inform of it as soon as reasonably practicable.</span></p><p data-h5p="text:p=54" class="Standard"><span data-h5p="text:span=65" class="T2">Modification of these Terms</span></p><p data-h5p="text:p=55" class="Standard"><span data-h5p="text:span=66" class="T1">We may, at any time, and at our sole discretion, modify, add or delete sections of these Terms, as well as correct errors or omissions contained herein. By using the Service following any such modification of the Terms, you are expressly accepting the updated Terms. Therefore, please review the Terms regularly.</span></p><p data-h5p="text:p=56" class="Standard"><span data-h5p="text:span=67" class="T1">Any modification of these Terms will be displayed within the Portal as soon as reasonably practicable.</span></p><p data-h5p="text:p=57" class="Standard"><span data-h5p="text:span=68" class="T2">Disclaimers and limitation of liability</span></p><p data-h5p="text:p=58" class="Standard"><span data-h5p="text:span=69" class="T1">YOU ACKNOWLEDGE THAT YOUR USE OR MISUSE OF THE PORTAL AND/OR THE SERVICE IS AT YOUR SOLE RISK, AND THAT YOU ASSUME FULL RESPONSIBILITY FOR ALL RISK ASSOCIATED THEREWITH. TELADOC MAKES NO REPRESENTATION, WARRANTY, OR GUARANTEE REGARDING THE RELIABILITY, TIMELINESS, QUALITY, SUITABILITY OR AVAILABILITY OF THE PORTAL AND/OR THE SERVICE, OR THAT THE PORTAL AND/OR THE SERVICE WILL BE UNINTERRUMPTED OR ERROR-FREE.</span></p><p data-h5p="text:p=59" class="Standard"><span data-h5p="text:span=70" class="T1">YOU UNDERSTAND THAT TO THE EXTENT PERMITTED UNDER THE APPLICABLE LAW, IN NO EVENT WILL TELADOC OR ITS OFFICERS, DIRECTORS, EMPLOYEES, PARENT, SUBSIDIARIES OR AFFILIATES BE LIABLE FOR ANY DAMAGES, LIABILITY OR LOSSES RELATED TO, IN CONNECTION WITH, OR OTHERWISE RESULTING FROM (i) ANY USE OF THE PORTAL AND/OR THE SERVICE PROVIDED BY HEALTHCARE PROFESSIONALS; OR (ii) FROM YOUR INABILITY TO ACCESS OR USE THE PORTAL AND/OR THE SERVICE.</span></p><p data-h5p="text:p=60" class="Standard"><span data-h5p="text:span=71" class="T1">TELADOC SHALL NOT BE LIABLE FOR DELAY OR FAILURE IN PERFORMANCE RESULTING FROM CAUSES BEYOND TELADOC'S REASONABLE CONTROL.</span></p><p data-h5p="text:p=61" class="Standard"><span data-h5p="text:span=72" class="T2">Indemnification</span></p><p data-h5p="text:p=62" class="Standard"><span data-h5p="text:span=73" class="T1">You agree to indemnify, defend and hold harmless Teladoc, its officers, directors, employees, agents, subsidiaries, affiliates, licensors and suppliers, from and against any claim, actions, demands, liabilities and settlements resulting from, or alleged to result from, your violation of these Terms.</span></p><p data-h5p="text:p=63" class="Standard"><span data-h5p="text:span=74" class="T2">General Provisions</span></p><p data-h5p="text:p=64" class="Standard"><span data-h5p="text:span=75" class="T1">Binding agreement. These Terms constitute a binding agreement between you and Teladoc and constitute a complete and exclusive statement of the Terms of the agreement between you and Teladoc regarding the Service.</span></p><p data-h5p="text:p=65" class="Standard"><span data-h5p="text:span=76" class="T1">Assignment. Teladoc may assign this agreement to any of its affiliates and/or in connection with any merger, sale of all or substantially all assets, sale or equity interests or other change of control transaction involving Teladoc. Users shall not assign or otherwise transfer this agreement, in whole or in part, without Teladoc's prior written consent.</span></p><p data-h5p="text:p=66" class="Standard"><span data-h5p="text:span=77" class="T1">Headings. The headings contained herein are for convenience of reference and shall not affect in any way the meaning and interpretation of these Terms.</span></p><p data-h5p="text:p=67" class="Standard"><span data-h5p="text:span=78" class="T1">Severability. The provisions of these Terms are severable and, should any provision herein be deemed unenforceable or invalid, such unenforceability or invalidity shall not affect the remainder of these Terms, which will continue in full force and effect.</span></p><p data-h5p="text:p=68" class="Standard"><span data-h5p="text:span=79" class="T1">Governing law. The interpretation and enforcement of this Agreement shall be subject to the laws of New Zealand. The parties submit to the exclusive jurisdiction of New Zealand courts and courts of appeal from them. The parties will not object to the exercise of jurisdiction by those courts on any basis.</span></p><div class="h5p_container_div"><div class="h5p_wrappingdiv" data-type="block" data-id="672a5a6bfb15f79dd15ca834e1d72132" data-h5p="vars"><ul data-h5p="text:list=2" class="WWNum2" id="list3922205860" style="counter-reset: ulWWNum2_1 1;"><li style="color: initial; font-family: initial;" data-h5p="text:list-item=6" class="removeBullet h5p_listitem" data-type="list" data-id="672a5a6bfb15f79dd15ca834e1d72132-1"><ul data-h5p="text:list=3" id="list_5ebb3bc0a_63eb504e2446f" style="counter-reset: ulWWNum2_2 0;"><li style="color: initial; font-family: initial;margin-top: 0rem !important;margin-bottom: 0.7992rem !important;line-height: 1.269 !important;text-align: left !important;orphans: 2 !important;widows: 2 !important;writing-mode: lr-tb;" data-h5p="text:list-item=7" data-type="list" data-id="672a5a6bfb15f79dd15ca834e1d72132-2" class=" h5p_listitem"><p style="display: table-cell;margin-left:0 !important;text-indent: 0 !important;" data-h5p="text:p=69" class="P2"><span><span class="spanWrapper"><span class="h5p_varspan" data-name="user_hash" contentEditable ="true">user_hash</span></span><span class="spanWrapper"><span class="h5p_varspan" data-name="docid" contentEditable ="true">docid</span></span> </span><span id="vars" data-bookmarkstart="vars" data-h5p="text:bookmark=1"/></p></li><li style="color: initial; font-family: initial;margin-top: 0rem !important;margin-bottom: 0.7992rem !important;line-height: 1.269 !important;text-align: left !important;orphans: 2 !important;widows: 2 !important;writing-mode: lr-tb;" data-h5p="text:list-item=8"><p style="display: table-cell;margin-left:0 !important;text-indent: 0 !important;" data-h5p="text:p=70" class="P2">&nbsp;</p></li></ul></li></ul></div></div><p data-h5p="text:p=71" class="Standard">&nbsp;</p></div></section><script>
var numFormat = ",.";
$(document).ready(function(){
    //do some cleaning on load
    sortCells = $('td[data-sorting], th[data-sorting]');
    sortCells.each(function(){
        var first = $(this).text().trim().charAt(0);
        if (first == '@'){
            var oldHTML = $(this).html();
            var newHTML = oldHTML.replace('@', '');
            $(this).html(newHTML);
        } 
    });
    function sortingTable(node, pos, ordBy){
        var rows = node.children('tbody').children('tr').get();

        rows.sort(function(a, b) {

        var X = $(a).children('td').eq(pos).text().toUpperCase();
        var Y = $(b).children('td').eq(pos).text().toUpperCase();
        
        if (numFormat != '.,'){
            //we are dealing with a different locale and we need to do some 
            //transformation in numbers
            X = convert2number(X);
            Y = convert2number(Y);
        } else {
            X = X.replace(/,/g, '').replace(/ /g, '');
            Y = Y.replace(/,/g, '').replace(/ /g, '');
        }
        var currencies = ['$', '¥', '£', '€'];
        var arrayLength = currencies.length;
        var XX = X;
        var YY = Y;
        for (var i = 0; i < arrayLength; i++) {
            XX = XX.replace(currencies[i], '');
            YY = YY.replace(currencies[i], '');
        }
        if (!isNaN(XX) && !isNaN(YY)){
            var floatXX = parseFloat(XX);
            var floatYY = parseFloat(YY);
            return -(floatYY-floatXX) * ordBy;
        } else if (!isNaN(XX) && isNaN(YY)){
            return -1 * ordBy;
        } else if (isNaN(XX) && !isNaN(YY)){
            return ordBy;
        } else {
            if(X < Y) {
                return -1 * ordBy;
            }
            if(X > Y) {
                return 1 * ordBy;
            }
            return 0;
        }
      });

      $.each(rows, function(index, row) {
        node.children('tbody').append(row);
      });
    }
    
    function removeTableCellDecoration() {
        $("td[data-sorting], th[data-sorting]").removeClass('sortDecorator');    
    }

    $("td[data-sorting], th[data-sorting]").click(function(){
        removeTableCellDecoration();
        $(this).addClass('sortDecorator');
        //get desired ordering
        var ordering = $(this).attr('data-sortOrdering');
        if (ordering == 'ASC'){
            var ordBy = -1;
            $(this).attr('data-sortOrdering', 'DESC');
        } else {
            var ordBy = 1;
            $(this).attr('data-sortOrdering', 'ASC');
        }
        var cellPosition = $(this).prevAll().length;
        var table = $(this).parents('table:first');
        sortingTable(table, cellPosition, ordBy);
    });  
    
    function convert2number(str) {
        str = str.trim();
        if (str.match(/^\d+/)) {
            //we have to take special care when the thousand separators are '.'
            result_0 = str.replace(/\./g, '_@_');
            result_1 = result_0.replace(numFormat[0], '.');
            result = result_1.replace(/_@_/g, '');
            result .replace(/ /g, '');
            return result;
        } else {
            return str;
        }
        
    }
    
});


</script>
        </div>
        
        <div id="annexDXO">
        </div>
        <!-- textarea modal -->
        <div class="modal inmodal" id="textareaModal" tabindex="-1" role="dialog"  data-backdrop="static" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content animated fadeIn">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Cerrar</span></button>
                        <strong><i class="fa fa-cog" aria-hidden="true"></i> Editar el texto  <span id="textareaVar" style="display:none"></span></strong>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-sm-12">
                                <div class="form-horizontal">
                                    <div class="ibox float-e-margins">
                                        <div class="ibox-content no-padding">
                                            <div class="summernoteTextarea" id="textArea"></div>
                                        </div>
                                    </div>
                                </div>          
                            </div>              
                        </div>                        
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-white btn-sm" data-dismiss="modal">Cerrar</button>
                        <button type="button" class="btn btn-primary btn-sm" id="saveTextarea">Guardar</button>
                    </div>
                </div>
            </div>
        </div>
                    
                    <div id="dxfooter" style="text-align: center; font-size: 13px; font-family: Verdana; margin-top: 20px">
    Powered by <a href="https://docxpresso.com" target="_blank">docxpresso</a>
</div>
                
        <!-- Bootstrap -->
        <script src="/js/bootstrap.min.js"></script>
        <!-- UI -->
        <script src="/js/plugins/jquery-ui/jquery-ui.min.js"></script>
        <!-- toastr -->
        <script src="/js/plugins/toastr/toastr.min.js"></script>
        <!-- awesome cursor -->
        <script src="/js/plugins/awesome-cursor/jquery.awesome-cursor.min.js"></script>
        <!-- Date picker -->
        <script src="/js/plugins/datapicker/bootstrap-datepicker.js"></script>
                <script src="/js/plugins/datapicker/locales/bootstrap-datepicker.es.js"></script>    
                <!-- Signature pad -->
        <script src="/js/plugins/signature-pad/signature-pad.min.js"></script>
        <!-- ScrollTo -->
        <script src="/js/plugins/scrollTo/jquery.scrollTo.min.js"></script>
        <!-- Parse query -->
        <script src="/js/plugins/parseQuery/jquery.parsequery.js"></script>
        <!-- SUMMERNOTE -->
        <script src="/js/plugins/summernote/summernote.min.js"></script>
                <script src="/js/plugins/summernote/lang/summernote-es.js"></script>    
                <!-- iCheck -->
        <script src="/js/plugins/iCheck/icheck.min.js"></script>
        <!-- Docxpresso -->
        <script src="/js/plugins/docxpresso/docxpresso.js"></script>
        <!-- Bootstrap Multiselect -->
        <script src="/js/plugins/bootstrap-multiselect/bootstrap-multiselect.js"></script>
        <!-- Webui-popover -->
        <script src="/js/plugins/webui-popover/jquery.webui-popover.js"></script>
        <!-- Docxpresso Helper functions -->
        <script src="/js/plugins/docxpresso/helpers.js"></script>
        <!-- Docxpresso number to words -->
        <script src="/js/plugins/docxpresso/number2letters.js"></script>
        <!-- iframe Resizer -->
        <script src="/js/plugins/iframeResizer/iframeResizer.contentWindow.min.js"></script>
        <!-- mark -->
        <script src="/js/plugins/mark/jquery.mark.min.js"></script>
                                
        <script>
                
        //disable all clicks
        /*document.getElementById('mainDXO').addEventListener("click", handlerClickEvents,true);
        
        function handlerClickEvents(e){
            e.stopPropagation();
            e.preventDefault();
        }*/

        //hide top bar if iframe id is equal to
        var defValuesForm = {};
        if (window.frameElement != null && window.frameElement.id == 'viewDocFrame'){
            //hide topbar
            document.getElementById('fixedbar').style.display = 'none';
            document.body.style.paddingTop = '1px';
            document.body.classList.add('thinSB');
            //if it is the viewer of a web form we have to make sure that form
            //default values are taken into account
            var strutFormData = JSON.parse('{"settings":{"timestamp":1637066810.538828,"showTabs":true,"progressBar":true,"previewDoc":true},"strut":[{"element":"section","name":"section_0","label":"section_0","description":"","active":true,"childs":[{"id":"672a5a6bfb15f79dd15ca834e1d72132","element":"block","name":"var","active":true,"childs":[{"element":"var","name":"user_hash","active":true},{"element":"var","name":"docid","active":true}]}]}]}');
            var strutTabs = strutFormData.strut;
            var strutLen = strutTabs.length;
            for(var k = 0; k < strutLen; k++){
                parseChilds(strutTabs[k]);
            }
            function parseChilds(formGroup){
                if (typeof formGroup.element != 'undefined'
                    && formGroup.element == 'var'
                    && formGroup.active
                    && typeof formGroup.defaultValue != 'undefined' 
                    && formGroup.defaultValue != ''){
                    defValuesForm[formGroup.name] = formGroup.defaultValue;
                } else if (typeof formGroup.childs != 'undefined' && formGroup.childs.length > 0) {
                    var lenGroup = formGroup.childs.length;
                    for (var j = 0; j < lenGroup; j++){
                        parseChilds(formGroup.childs[j]);
                    }
                }
            }
        }
        //set the interface type for interaction with "external" JS
        dxoInterface = 'document';
        //this dxo object will hold all the parsed JSON info
        dxo = {};
        //initialize the global variables
        //customData holds additional info not tied to a particular template
        window.customData = '';
        
        //in case there are prefixes we need to store the inactiva attachments
        window.inactiveAttachments = [];
        //other variables that should be explained
        window.group = 0;
        window.dependencies = {};
        window.partials = {};
        window.annexes = {};
        window.originalImages = {};
        window.attachments = {};
        window.rpcs = [];
        window.rpcData = {};
        window.multiselects = {};
        parsedClonableBlocks = [];
        window.localDataLoaded = false;
        //create a global array to hold the variables that are potential emails
        window.emails = [];
        
        //let us create a Mutation Observer object to detect changes on special variables

        var targets = document.getElementsByClassName('h5p_varspecial');
        var observer = [];
        for (var i = 0; i < targets.length; ++i) {
            //console.log(targets[i]);
            observer[i] = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                  //console.info("EVENT TRIGGERED" + mutation.target.getAttributeNode("data-name").value);
                });    
            });
            observer[i].observe(targets[i], {childList: true});
        }
        
        function decodeDXO (str) {
            try {
                str = decodeURIComponent(str);
            } catch (e) {
                console.log(e);
            }
            str = str.replace(/&apos;/g, "'");
            return str;
        }
        
        function encodeDXO (str) {
            //str = $('<div />').html(str).text();
            str = encodeURIComponent(str);
            str = str.replace(/\'/g, "&apos;");
            return str;
        }
        
        
        function gcaptcha() {
            if(grecaptcha.getResponse() == ""){
                toastr.error('Posible ataque de SPAM. Por favor, inténtelo de nuevo.', 'Aviso');
                grecaptcha.reset();
            } else {
                $('#gcap').val(grecaptcha.getResponse());
                $( "#docxpresso_form" ).submit();
            }
        }
        
        function clickTab(selector){
            section = selector.parents('section:first');
            num = section.attr('data-order');
            //trigger a click on the corresponding tab
            $('a[data-order="' + num + '"]').click();
        }
        
        function highlight(selector){
            $.scrollTo(selector, 500, {offset: -80});
            //flash the variable that should be edited again
            originalBColor = selector.css('background-color');
            originalColor = selector.css('color');
            selector.css('background-color', '#ffff99')
                    .css('color', '#b70000')
                    .fadeOut('slow').fadeIn('slow')
                    .fadeOut('fast').fadeIn('fast')
                    .fadeOut('fast').fadeIn('fast')
                    .fadeOut('fast').fadeIn('fast', function(){
                        selector.css('background-color', originalBColor);
                        selector.css('color', originalColor);
                    });
        }
        
        function parseSingleVar(j, vars) {
            if (docxpressoData.data[j].type == 'options' && (docxpressoData.data[j].choice == 'radio' || docxpressoData.data[j].choice == 'checkbox')) {
                vars[docxpressoData.data[j].name] = [];
                choice = $('input[data-list="' + docxpressoData.data[j].name + '"]');
                choice.each(function(){
                    if ($(this).is(':checked')) {
                        vars[docxpressoData.data[j].name].push(encodeDXO($(this).val()));
                    } else {
                        vars[docxpressoData.data[j].name].push('');
                    }
                });
            } else if (docxpressoData.data[j].type == 'options' && docxpressoData.data[j].choice == 'multipleSelect') {
                vars[docxpressoData.data[j].name] = [];
                span = $('span.h5p_varspan[data-name="' + docxpressoData.data[j].name + '"]');
                span.each(function(){
                    var tmp = [];
                    var nodes = $(this)[0].childNodes;
                    $(nodes).each(function(){
                        tmp.push(encodeDXO($(this).text()));
                    });

                    vars[docxpressoData.data[j].name].push(tmp);
                });
            } else if (docxpressoData.data[j].type != 'bookmark' && docxpressoData.data[j].type != 'image') {
                vars[docxpressoData.data[j].name] = [];
                span = $('span.h5p_varspan[data-name="' + docxpressoData.data[j].name + '"]');
                span.each(function(){
                    //we need to clean additional <br>s inserted by IE
                    spanval = cleanBRs($(this).html(), docxpressoData.data[j].type);
                    if (docxpressoData.data[j].validation == 'email' || docxpressoData.data[j].validation == 'URL') {
                        var newLink = linkDressUp (spanval, docxpressoData.data[j].validation);
                        vars[docxpressoData.data[j].name].push(encodeDXO(newLink));
                    } else {
                        vars[docxpressoData.data[j].name].push(encodeDXO(spanval));
                    }
                });
            } else if (docxpressoData.data[j].type == 'image' && docxpressoData.data[j].source != 'QR') {
                vars[docxpressoData.data[j].name] = [];
                img = $('img[data-image="' + docxpressoData.data[j].name + '"]');
                dxo[docxpressoData.data[j].name]['width'] = new Array();
                dxo[docxpressoData.data[j].name]['height'] = new Array();
                img.each(function(){
                    vars[docxpressoData.data[j].name].push($(this).attr('src'));
                    if ($(this).attr('data-width') != 'undefined') {
                        dxo[docxpressoData.data[j].name]['width'].push($(this).attr('data-width'));
                    }
                    if ($(this).attr('data-height') != 'undefined') {
                        dxo[docxpressoData.data[j].name]['height'].push($(this).attr('data-height'));
                    }
                })
            }
            return vars;
        }
        
        //updating of special vars depending on others
        function string2number(str, format) {
            if (typeof str !== 'string') {
                return str;
            }
            if (format.length > 2){
                format[0] = '.';
                format[1] = ',';
            }
            if (format[0] == '.') {
                resultArray = str.split(format[1]);
		result = resultArray.join('');
            } else {
                //we have to take special care when the thousand separators are '.'
                result_0 = str.replace(/\./g, '_@_');
                result_1 = result_0.replace(format[0], '.');
                result = result_1.replace(/_@_/g, '');
            }

            return Number(result);
        }
        
        function number2string (number, format) {
            var numarray = (number + "").split(".");
            var ipart = numarray[0];
            if (numarray.length > 1) {
                var decpart = numarray[1];
            }
            //tokenize the integer part
            iarray = ipart.split('');
            var len = iarray.length;
            var counter = 0;
            var integer = '';
            for (var j=0; j < len; j++) {
                integer += iarray[j];
                if ((len- j - 1)%3 == 0 && j != len -1) {
                    integer += format[1];
                }
            }
            //we have to avid cases like "-," or "-."
            integer = integer.replace("-,", "-");
            integer = integer.replace("-.", "-");
            if (typeof decpart != 'undefined') {
                return integer + format[0] + decpart;
            } else {
                return integer
            }
        }
        window.updateVars = {};
        window.updater = setInterval(function() {updateSpecialVars();}, 2000);
        var frameName = window.name;
        function updateSpecialVars() {
            if (frameName == 'history-frame'){
                //in this case we just get the values from the history
            } else {
                for (var j = 0; j < docxpressoData.special.length; j++) {
                    updateSingleSpecialVars(docxpressoData.special[j]);
                }
            }   
        }
        
        function updateSingleSpecialVars(sVar){
            if (typeof sVar['mode'] != 'undefined'){
                var mode = sVar['mode'];
            } else {
                var mode = 'math';
            }
            if (mode == 'math'){
                try {
                    var formula = sVar['formula'];
                    var type = sVar['type'];
                    var dependsOn = sVar['dependsOn'];
                    var precision = sVar['precision'];
                    $('[data-name="'+ sVar['name'] + '"]').each(function(){
                        $(this).text(number2string(specialValue($(this), formula, type, dependsOn, precision), window.numformat));
                    });
                } catch(error) {
                    console.log(error);
                }
            } else if (mode == 'incremental') {
                var snodes= $('span.h5p_varspecial[data-name="' + sVar['name'] + '"]:visible');
                //get the numberig configuration
                var varOffset = parseInt(sVar['offset']);
                var varPrefix = decodeDXO(sVar['prefix']);
                var varSuffix = decodeDXO(sVar['suffix']);
                
                snodes.each(function(loop){
                    var numbering = loop + varOffset + 1;
                    if (sVar['numbering'] == 'romanLowercase'){
                        numbering = int2Roman(numbering).toLowerCase()
                    } else if (sVar['numbering'] == 'romanUppercase'){
                        numbering = int2Roman(numbering).toUpperCase()
                    } else if (sVar['numbering'] == 'letterLowercase'){
                        numbering = int2Letter(numbering - 1).toLowerCase()
                    } else if (sVar['numbering'] == 'letterUppercase'){
                        numbering = int2Letter(numbering - 1).toUpperCase()
                    }
                    $(this).text(varPrefix + numbering + varSuffix);
                });
            } else if (mode == 'number2word') {
                 $('[data-name="'+ sVar['name'] + '"]').each(function(){
                    var dependsOnValue = $('[data-name="'+ dependsOn + '"]:first').text();
                    $(this).text(convertToWord($(this), sVar));
                });
            }else {
                $('[data-name="'+ sVar['name'] + '"]').each(function(){
                    var dependsOnValue = $('[data-name="'+ dependsOn + '"]:first').text();
                    $(this).text(dependencyOnValue($(this), sVar));
                });
            }
        }
        
        
        function dependencyOnValue (node, sVar){
            var result = decodeDXO(sVar['default']);
            var dependsOn = sVar['dependsOn'][0];
            dependsOn = dependsOn.replace('[[','').replace(']]', '');
            var type = sVar['type']
            
            //now we should take into account the special case of 
            //radios and checkboxes
            var choice = null;
            if (typeof dxo[dependsOn] != 'undefined' && dxo[dependsOn].choice != 'undefined'){
                var choice = dxo[dependsOn].choice;
            }
            var selectedOptions = [];
            if (choice == 'radio' || choice == 'checkbox'){
                var choices;
                if (type === 'General') {
                    choices = $('input[data-name="' + dependsOn + '"]:checked');
                } else if (type === 'Bookmark') {
                    choices = $(node).parents('div[data-type="block"]:first').find('input[name="' + dependsOn + '"]:checked');
                } else if (type === 'Column') {
                    choices = $(node).parents('table:first').find('input[name="' + dependsOn + '"]:checked');
                } else if (type === 'Row') {
                    choices = $(node).parents('tr:first').find('input[name="' + dependsOn + '"]:checked');
                } else if (type === 'listItem') {
                    choices = $(node).parents('li:first').find('input[name="' + dependsOn + '"]:checked');
                }
                if (choices.length > 0) {
                    choices.each(function(){
                        selectedOptions.push($(this).val());
                    });
                }
            } else {
                var baseNode;
                if (type === 'General') {
                    baseNode = $('[data-name="'+ dependsOn + '"]:first');
                } else if (type === 'Bookmark') {
                    baseNode = $(node).parents('div[data-type="block"]:first').find('[data-name="'+ dependsOn + '"]:first');
                } else if (type === 'Column') {
                    baseNode = $(node).parents('table:first').find('[data-name="'+ dependsOn + '"]:first');
                } else if (type === 'Row') {
                    baseNode = $(node).parents('tr:first').find('[data-name="'+ dependsOn + '"]:first');
                } else if (type === 'listItem') {
                    baseNode = $(node).parents('li:first').find('[data-name="'+ dependsOn + '"]:first');
                }
                var selValue = baseNode.text();
                selectedOptions = new Array(selValue);
            }
            if (typeof sVar['bindings'] == 'object'){
                var bindings = sVar['bindings'];
                for (prop in bindings){
                    if (selectedOptions.indexOf(decodeDXO(prop)) > -1){
                        result = decodeDXO(bindings[prop]);
                    }
                }
            }
            return result;
        }
        
        function convertToWord (node, sVar){
            var result = decodeDXO(sVar['default']);
            var dependsOn = sVar['dependsOn'][0];
            dependsOn = dependsOn.replace('[[','').replace(']]', '');
            var type = sVar['type']
            
            var baseNode;
            if (type === 'General') {
                baseNode = $('[data-name="'+ dependsOn + '"]:first');
            } else if (type === 'Bookmark') {
                baseNode = $(node).parents('div[data-type="block"]:first').find('[data-name="'+ dependsOn + '"]:first');
            } else if (type === 'Column') {
                baseNode = $(node).parents('table:first').find('[data-name="'+ dependsOn + '"]:first');
            } else if (type === 'Row') {
                baseNode = $(node).parents('tr:first').find('[data-name="'+ dependsOn + '"]:first');
            } else if (type === 'listItem') {
                baseNode = $(node).parents('li:first').find('[data-name="'+ dependsOn + '"]:first');
            }
            var selValue = baseNode.text();
            //parametrize the conversor
            var lang = 'es';
            if (sVar['currency']){
                var currency = {};
                currency.singular = decodeDXO(sVar['currencySingular']);
                currency.plural = decodeDXO(sVar['currencyPlural']);
                currency.decSingular = decodeDXO(sVar['fractionSingular']);
                currency.decPlural = decodeDXO(sVar['fractionPlural']);
            } else {
                var currency = null;
            }
            var numberFormat = {};
            if (typeof docxpressoData['settings']['numberFormat'] != 'undefined'){
                numberFormat.thousands = docxpressoData['settings']['numberFormat'][1];
                numberFormat.decimal = docxpressoData['settings']['numberFormat'][0];
            } else {
                numberFormat.thousands = ',';
                numberFormat.decimal = '.';
            }
            numberFormat.numDecimals = sVar['precisionWord'];
            if(lang == 'es'){
                numberFormat.connector = 'con';
            } else {
                numberFormat.connector = 'and';
            }   
            if (sVar['uppercase']){
                var letterFormat = 'uppercase';
            } else {
                var letterFormat = 'lowercase';
            }
            var result = number2letters(selValue, lang, currency, numberFormat, letterFormat);
            return result;
        }
        
        function specialValue (node, formula, type, dependsOn, precision) {
            var varValues = {};
            var len = dependsOn.length;
            var method = formula;
            for (var j = 0; j < len; j++){
                if (type !== 'General') {
                    varValues[dependsOn[j]] = computeValue(node, type, dependsOn[j]);
                    method = method.replace(/\s/gi, '');
                    method = method.replace('SUM{' + dependsOn[j] + '}', '(' + varValues[dependsOn[j]] + ')');
                    method = method.replace(dependsOn[j], '(' + varValues[dependsOn[j]] + ')');
                } else {
                    //in the general case dependencies may be more cumbersome so
                    //we may need to parse subformulas
                    var reg = /SUM{\s*(.*?)\s*}/g;
                    var subformulas = method.match(reg);
                    if (subformulas){
                        sf = subformulas.length;
                        for (var k = 0; k < sf; k++) {
                            formula = subformulas.slice(0);
                            formulaVal = computeSUM(formula[k]);
                            method = method.replace(subformulas[k], formulaVal);
                        }
                    }
                    //we should also replace general variables that are not within a SUM
                    varValues[dependsOn[j]] = computeValue(node, type, dependsOn[j]);
                    method = method.replace(dependsOn[j], '(' + varValues[dependsOn[j]] + ')');
                }
            }
            try {
                //console.log('devuelve:');
                //console.log(eval(method));
                if (precision > -1){
                    return eval(method).toFixed(precision);
                } else {
                    return eval(method);
                }
            } catch (error){
                //console.log(error);
                return ' ';
            }
        }
        function computeValue (node, type, name) {
            name = name.replace('[[', '');
            name = name.replace(']]', '');
            var res = 0;
            var nodeList;
            if (type === 'General') {
                nodeList = $('span[data-name="' + name + '"]');
            } else if (type === 'Bookmark') {
                nodeList = $(node).parents('div[data-type="block"]:first').find('[data-name="'+ name + '"]');
            } else if (type === 'Column') {
                nodeList = $(node).parents('table:first').find('[data-name="'+ name + '"]');
            } else if (type === 'Row') {
                nodeList = $(node).parents('tr:first').find('[data-name="'+ name + '"]');
            } else if (type === 'listItem') {
                nodeList = $(node).parents('li:first').find('[data-name="'+ name + '"]');
            }
            $(nodeList).each(function(){
                   valnum = string2number($(this).text(), window.numformat);
                   //console.log(valnum);
                   if (!isNaN(valnum)) {res += (valnum);}
            });
            return res;
        }
        function computeSUM(formula){
            formula = formula.trim();
            var expression = formula.substr(4, formula.length - 5);
            //extract variable names and properties
            var reg = /\[\[(.*?)\]\]/g;
            var sumVars = formula.match(reg);
            var len = sumVars.length;
            var rowVars = {};
            var maxRows = 0;
            //remove square brackets and detect row values
            for (var k = 0; k < len; k++) {
                sumVars[k] = sumVars[k].replace('[[', '');
                sumVars[k] = sumVars[k].replace(']]', '');
                sumVars[k] = sumVars[k].trim();
                rows = $('tr').find('[data-name="'+ sumVars[k] + '"]');
                if (rows.length > 0) {
                    if (rows.length > maxRows) {
                        maxRows = rows.length;
                    }
                    rowVars[sumVars[k]] = [];
                    $('span[data-name="' + sumVars[k] + '"]').each(function(){
                        valnum = string2number($(this).text(), window.numformat);
                        if (!isNaN(valnum)) {
                            rowVars[sumVars[k]].push((valnum));
                        }else {
                            rowVars[sumVars[k]].push(0);
                        }
                    });
                } else {
                    valnum = string2number($('span[data-name="' + sumVars[k] + '"]').eq(0).text(), window.numformat);
                    if (!isNaN(valnum)) {
                        rowVars[sumVars[k]] = (valnum);
                    }else {
                        rowVars[sumVars[k]] = 0;
                    }
                }                           
            }
            //start to replace values
            var result = 0;
            for (var j = 0; j < maxRows; j++) {
                var exp = expression;
                for (var n = 0; n < len; n++) {
                    if ( typeof rowVars[sumVars[n]] === 'string' ) {
                        exp = exp.replace('[[' + sumVars[n] + ']]', '(' + rowVars[sumVars[n]] + ')');    
                    } else {
                        exp = exp.replace('[[' + sumVars[n] + ']]', '(' +rowVars[sumVars[n]][j] + ')');
                    }
                }
                result = result + ' + ' + exp;
            }
            var res = eval(result);
            return res;
        }
        
        $(document).ready(function(){
            if(document.referrer != '' && window.self == window.top){
                $('#cancelGo').show();
            }
            $(window).bind("load", function() {
                //this is to make sure that the page is fully loaded
                //$('#mainDXO').awesomeCursor('file-text');
            });
            $("#mainDXO").on('click','*', function(e){
                var tn = $(this).prop("tagName");
                var ptn = $(this).parent().prop("tagName");
                if (tn == 'A' || ptn == 'A'){
                    e.stopPropagation();
                    return true;
                } else {
                    e.stopPropagation();
                    e.preventDefault();
                }
            });
            //Hide cancel button if there is no history
            var myHistory = window.history.length;
            var respRedir = $('#responseURL').val();
            if (myHistory < 2 && (respRedir == '' || typeof respRedir == 'undefined')){
                $('#cancelGo').hide();
            }
            
            $('*').removeAttr('contenteditable');
            //$('#mainDXO input').prop('disabled', true);
            //$('#mainDXO select').prop('disabled', true);
            $('select').on('mousedown', function(e) {
                e.preventDefault();
                this.blur();
                window.focus();
            });
            window.scrolled = 0;
            $(window).scroll(function() {
                window.scrolled = $(window).scrollTop();
                if ( window.scrolled > 240 ) {
                    $('#goTop').fadeIn('slow');
                } else {
                    $('#goTop').fadeOut('slow');
                }
            });
            
            $('#goTop').click(function() {
                $('body, html').animate({scrollTop: 0}, 500);
                return false;
            });
            
            $('.summernoteValidation').summernote({
                lang: 'es',
                height: 56,
                toolbar: [
                    ['style', ['bold', 'italic', 'underline', 'clear']],
                    ['color', ['color']],
                    ['para', ['ul', 'ol']],
                  ],
                onblur: function(e) {   
                }
            });
            
            $('#wfPane').click(function(){
                $('#wfModal').modal('show');
            });
            
            //parse GET query
            var query = $.parseQuery();
            //check for toolbar
            if (query['toolbar'] == '0'){
                $('#fixedbar').hide();
            }
            //check for query
            if (typeof query['q'] != 'undefined'){
                var searchQuery = decodeDXO(query['q']);
                //remove *
                searchQuery = searchQuery.replace('*', '');
                var searchQueryArray = searchQuery.split(' ');
                console.log('search terms');
                console.log(searchQueryArray);
                //higlight thos search terms
                var lSearch = searchQueryArray.length
                for (var k = 0; k < lSearch ; ++k){
                    $('#mainDXO').mark(searchQueryArray[k]);
                }
            }
            //check for tabnum
            window.clickTabNum = query['tabnum'];
            
            
            var progressTimer = 2000;
            serverData = 0;
            local = localStorage.getItem("preview_162");
            localTime = localStorage.getItem("previewTime_162");
            if (local !== null && !serverData && !window.thumb) {
                $('#loadLocalData').click(function(){
                    retrieveLocalData();
                });
                $('#localModal').modal('show');
            }
            if (serverData) {
                $('#serverModal').modal('show');                
            }
            
            var loadedData = '{}';
            var preparsedServerData = $('<div />').html(loadedData).text();
            var dataToLoadFromServer = JSON.parse(preparsedServerData);
                        if (typeof dataToLoadFromServer.validations != 'undefined'
                && typeof dataToLoadFromServer.validations.percentage != 'undefined'){
                $('#progressValue').html(' ' + dataToLoadFromServer.validations.percentage + '% ');
                if (dataToLoadFromServer.validations.percentage == 0){
                    dataToLoadFromServer.validations.percentage = 1;
                }
                $('#progressBar').css('width', dataToLoadFromServer.validations.percentage + '%');
            }
            toastr.options = {
                "closeButton": true,
                "debug": false,
                "progressBar": true,
                "positionClass": "toast-top-center",
                "onclick": null,
                "showDuration": "400",
                "hideDuration": "1000",
                "timeOut": "7000",
                "extendedTimeOut": "1000",
                "showEasing": "swing",
                "hideEasing": "linear",
                "showMethod": "fadeIn",
                "hideMethod": "fadeOut"
            }
            
            $('.summernoteComments').summernote({
                height: 70,
                toolbar: [
                  ['font', ['bold', 'italic', 'underline', 'clear']],
                  ['para', ['ul', 'ol']],
                ],
                                 'lang': 'es'
                            });
            
            //parse RPC data
                            
            //check for onLoad RPCs
            for (remote in window.rpcData) {
                if(window.rpcData[remote]['event'] == 'onLoad' && !serverData){
                    //we do not load external data on load if we got data directly from the server
                    var rpcurl = createRPCURL(rpcData[remote], query) ;
                    $.ajax({
                        url: rpcurl,
                        crossDomain: true,
                        dataType: "jsonp",
                        cache: false,
                        // parse response
                        success: function( data ) {
                            //load the data
                            //clone the blocks
                            cloneBlocks(data.blocks);
                            //replace variables
                            replaceVars(data.varValues, false, false);
                            //replace spacial variables
                            replaceVars(data.specialVarValues, true, false);
                        },
                        error: function( xhr, status, errorThrown ) {
                            //alert( "Sorry, there was a problem!" );
                            //console.log( "Error: " + errorThrown );
                            //console.log( "Status: " + status );
                            //console.dir( xhr );
                        }
                    });
                }
            }
                
            //jsonp callbacks
            function rpc_callback(){
                //do nothing
            }
            function remoteProcedureCallsDropdowns () {
                var l = window.rpcs.length;
                for (var j = 0; j < l; j++) {
                    var val = window.rpcs[j].slice();
                    populateDropdown(val[0], val[1], val[2], val[3]);
                };
            }
            function populateDropdown (name, rpcurl, type, trigger) {
                $.ajax({
                    url: rpcurl,
                    crossDomain: true,
                    dataType: "jsonp",
                    cache: false,
                    // parse response
                    success: function( options ) {
                        for (var k=0; k < options.length; k++) {
                            var key = options[k][0];
                            if (options[k][1] != '') {
                                var value = options[k][1];
                            } else {
                                var value = options[k][0];
                            }
                            $('select[data-list="' + name + '"]').each(function(){
                                if (typeof dxo[name]['default'] != 'undefined' && dxo[name]['default'] != '') {
                                    var defaultStr = decodeDXO(dxo[name]['default']);
                                } else {
                                    var defaultStr = ''
                                }
                                var defOptions = defaultStr.split(';');
                                //$(this).removeAttr('disabled');
                                $(this).css('opacity', 1);
                                //$(this).children('option').attr('disabled');
                                if (defOptions.indexOf(value) > -1){
                                    optionData += '<option value="' + value.replace(/"/g, '&quot;')  + '" selected>' + key + '</option>';
                                } else if (value.charAt(0) == '@') {
                                    var tmpvalue = value.substring(1);
                                    optionData = '<option value="' + tmpvalue.replace(/"/g, '&quot;') + '" selected>' + key + '</option>';
                                    $(this).parent().find('span.h5p_varspan').html(tmpvalue);
                                } else {
                                    optionData = '<option value="' + value.replace(/"/g, '&quot;') + '">' + key + '</option>';
                                }
                                $(this).append($(optionData));
                            });
                        }
                                                
                        if (type == 'rpc' && trigger != 0) {
                            //let us activate the associated rpc trigger
                            $('select[data-list="' + name + '"]').each(
                                    function(){
                                $(this).change(function(){
                                    RemoteCallFromDropdown($(this), trigger);
                                });
                            });
                        }
                        if (serverData && typeof dataToLoadFromServer.varValues[name] !== 'undefined') {
                            //make sure that the server data is reloaded
                            var serverValues = {};
                            serverValues[name] = dataToLoadFromServer.varValues[name];
                            console.log(serverValues);
                            replaceVars(serverValues, false, false);
                        }
                        //call to a custom function if defined
                        if (typeof customOnListLoaded === "function") {
                            customOnListLoaded(name);
                        }
                    },
                    error: function( xhr, status, errorThrown ) {
                        //alert( "Sorry, there was a problem!" );
                        //console.log( "Error: " + errorThrown );
                        //console.log( "Status: " + status );
                        //console.dir( xhr );
                    }
                });
            }
            
            function RemoteCallFromDropdown(node, trigger) {
                rpcurl = rpcData[trigger]['url'];
                rpcurl += '?callback=?&method=' + rpcData[trigger]['method'];
                rpcurl += '&timestamp=' + rpcData[trigger]['timestamp'];
                rpcurl += '&uniqid=' + rpcData[trigger]['uniqid']; 
                rpcurl += '&APIKEY=' + rpcData[trigger]['APIKEY'];
                rpcurl += '&data=' + node.val();
                $.ajax({
                    url: rpcurl,
                    crossDomain: true,
                    dataType: "jsonp",
                    cache: false,
                    // parse response
                    success: function( data ) {
                        if (typeof data.replaceMode != 'undefined' && data.replaceMode == 'row') {
                            var varValues = data["varValues"];
                            //find the enclosing tbody element 
                            var tbody = node.parents('tbody:first');
                            for (name in varValues) {
                                if (varValues.hasOwnProperty(name)){
                                    if (typeof dxo[name] != 'undefined') {
                                        var type = dxo[name]['type'];
                                        if (type == 'image') {
                                            var selector = tbody.find('img[data-image="' + name + '"]');
                                            selector.attr('src', varValues[name]);
                                        } else {
                                            var selector = tbody.find('span.h5p_varspan[data-name="' + name + '"]');
                                            selector.html(varValues[name]);
                                            //set the focus so special variables are updated
                                            selector.focus();
                                        }
                                    }
                                }   
                            }
                        } else {
                            //clone the blocks
                            cloneBlocks(data.blocks);
                            //replace variables
                            replaceVars(data.varValues, false);
                            //replace spacial variables
                            replaceVars(data.specialVarValues, true);    
                        }
                    },
                    error: function( xhr, status, errorThrown ) {
                        //alert( "Sorry, there was a problem!" );
                        //console.log( "Error: " + errorThrown );
                        //console.log( "Status: " + status );
                        //console.dir( xhr );
                    }
                });
            }
            
            //parse general data
            json = '{"data":[{"name":"user_hash","label":"user_hash","tip":"user_hash","comment":"%20","type":"hidden","options":"","list":"null","rpc":"","global":true,"choice":"dropdown","editable":false,"instanceVar":false,"default":"","confirm":false,"richText":false,"compulsory":false,"validation":"none","service":"","minNumber":"","maxNumber":"","stepNumber":"","serviceName":"","blockManualEdition":false,"attachment":"","exp":"","regex":"","trigger":0,"addTo":[],"timestamp":1676365902.299416},{"name":"docid","label":"docid","tip":"docid","comment":"%20","type":"docid","options":"","list":"null","rpc":"","global":true,"choice":"dropdown","editable":false,"instanceVar":false,"default":"","confirm":false,"richText":false,"compulsory":false,"validation":"none","service":"","minNumber":"","maxNumber":"","stepNumber":"","serviceName":"","blockManualEdition":false,"attachment":"","exp":"","regex":"","trigger":0,"addTo":[],"timestamp":1676365902.299416}],"charts":[],"groups":[{"type":"block","bookmark":"vars","active":true,"groupId":"672a5a6bfb15f79dd15ca834e1d72132","variables":["user_hash","docid"],"print":"never","name":"BLOCK [ var ]","display":"hide","toggleWith":null,"toggleValues":null,"responsive":false,"private":false,"removeWhitespace":true,"timestamp":1637066845.4891},{"type":"list","bookmark":"","active":true,"groupId":"672a5a6bfb15f79dd15ca834e1d72132-1","variables":["user_hash","docid"],"print":"print","name":"","display":"show","toggleWith":null,"toggleValues":null,"responsive":false,"private":false,"removeWhitespace":false,"timestamp":1676365902.210454},{"type":"list","bookmark":"","active":true,"groupId":"672a5a6bfb15f79dd15ca834e1d72132-2","variables":["user_hash","docid"],"print":"print","name":"","display":"show","toggleWith":null,"toggleValues":null,"responsive":false,"private":false,"removeWhitespace":false,"timestamp":1676365902.210455}],"signatures":{"signers":[],"notifications":"","notificationEvents":"","subject":"","message":"","webhook":"","provider":"","embeddedSignature":""},"special":[],"partials":[],"rpcs":{"onRequest":[],"onLoad":"","onUpload":""},"settings":{"numberFormat":".,","outputFormat":["pdf"],"outputComments":0,"timestamp":1637066845.4891,"externalCSS":"","tabs":0,"toolbarPosition":"absoluteBottom","interfaceMode":"basic","captcha":0,"enforceValidation":0,"responsive":0,"blockDocument":0,"advancedUI":0,"tabNames":"","showDeck":0,"identifier":"user_hash","prefixDoc":true,"externalJS":""},"attachments":[]}';
            json = json.replace(/%3B/gi, ";");
            json = json.replace(/%2C/gi, ",");
            docxpressoData = JSON.parse(json);
                        numData = docxpressoData.data.length;
            numGroups = docxpressoData.groups.length;
            numSpecial = docxpressoData.special.length;
            if (typeof docxpressoData.partials != 'undefined'){
                numPartials = docxpressoData.partials.length;
            } else {
                numPartials = 0;
            }
            //get the number format as an array
            preformat = docxpressoData.settings.numberFormat;
            window.numformat = preformat.split('');

            //Create the array that will hold the variables that need to be
            //confirmed by the enduser
            window.confirmation = [];

            var dxoGroups = {};
            var dxoPartials = {};
            window.dxoSpecial = {};
                        
            //check for annexes
            if (typeof docxpressoData.settings.annexes != 'undefined'
                && docxpressoData.settings.annexes.length > 0){
                $.each(docxpressoData.settings.annexes, function(index){
                    var loader = '<div id="loadAnnex_' + index + '">' + index + '</div>';
                    var receptacle = $(loader).appendTo($('#annexDXO'));
                    if (docxpressoData.settings.annexes[index]['default'] != ''){
                        //we should load the default annex
                        receptacle.attr('data-token', docxpressoData.settings.annexes[index]['default']);
                        receptacle.load('/documents/load_annexes' + '?token=' + docxpressoData.settings.annexes[index]['default']);
                    }
                    if (docxpressoData.settings.annexes[index]['dependsOn'] != ''){
                        window.annexes[docxpressoData.settings.annexes[index]['dependsOn']] = {};
                        window.annexes[docxpressoData.settings.annexes[index]['dependsOn']]['default'] = docxpressoData.settings.annexes[index]['default'];
                        window.annexes[docxpressoData.settings.annexes[index]['dependsOn']]['index'] = index;      
                        window.annexes[docxpressoData.settings.annexes[index]['dependsOn']]['documents'] =docxpressoData.settings.annexes[index]['documents'];
                    }
                })
            } 
            
            window.names2Index = {};
            //preparse certain global variables data
            $.each(docxpressoData.data, function(index) {
                dxo[docxpressoData.data[index].name] = docxpressoData.data[index];
                names2Index[docxpressoData.data[index].name] = index;
                if (docxpressoData.data[index].type == 'image'){
                    //populate the original images object with the original value on pre-load
                    img = $('img[data-image="' + docxpressoData.data[index].name + '"]');
                    //var imageValue = docxpressoData.data[index].src;
                    var imageValue = $(img).attr('src');
                    img.each(function(){
                        if (window.originalImages.hasOwnProperty(docxpressoData.data[index].name)) {
                            window.originalImages[docxpressoData.data[index].name].push(imageValue);
                        } else {
                            window.originalImages[docxpressoData.data[index].name] = [];
                            window.originalImages[docxpressoData.data[index].name][0] = imageValue;
                        }
                    });
                }
            });

            //we first need to parse block dependencies            
            for (j = 0; j < numGroups; j++) {
                dataGroup = docxpressoData.groups[j];
                if (dataGroup.toggleWith !== null) {
                    if (typeof window.dependencies[dataGroup.toggleWith] == 'undefined') {
                        window.dependencies[dataGroup.toggleWith] = {};
                        window.dependencies[dataGroup.toggleWith][dataGroup.groupId] = dataGroup.toggleValues;
                    } else {
                        window.dependencies[dataGroup.toggleWith][dataGroup.groupId] = dataGroup.toggleValues;
                    }
                }
            }
            delete dataGroup;
            
            //generate dxoGroups for the data parsing
            for (j = 0; j < numGroups; j++) {
                dxoGroups[docxpressoData.groups[j].groupId] = docxpressoData.groups[j];
            }
            
            //generate dxoGroups for the data parsing
            for (j = 0; j < numGroups; j++) {
                dxoGroups[docxpressoData.groups[j].groupId] = docxpressoData.groups[j];
            }

            //now parse partials dependencies
            var dataPartials;
            for (var j = 0; j < numPartials; j++) {
                dataPartials = docxpressoData.partials[j];
                if (dataPartials.toggleWith !== null) {
                    if (typeof window.partials[dataPartials.toggleWith] == 'undefined') {
                        window.partials[dataPartials.toggleWith] = {};
                        window.partials[dataPartials.toggleWith][dataPartials.name] = dataPartials.toggleValues;
                    } else {
                        window.partials[dataPartials.toggleWith][dataPartials.name] = dataPartials.toggleValues;
                    }
                }
            }
            delete dataPartials;
            //generate dxoPartials for the data parsing
            for (j = 0; j < numPartials; j++) {
                dxoPartials[docxpressoData.partials[j].name] = docxpressoData.partials[j];
            }
            
            //responsive tables
            if (typeof docxpressoData.settings.responsive != 'undefined' &&
                docxpressoData.settings.responsive) {
                $('table').each(function(){
                    if(typeof $(this).data('id') != 'undefined') {
                        if (typeof dxoGroups[$(this).data('id')] != 'undefined'){
                            if(typeof dxoGroups[$(this).data('id')]['responsive'] != 'undefined'
                                && dxoGroups[$(this).data('id')]['responsive']){
                                $(this).wrap( "<div class='dxoResponsiveTable'></div>" );
                         }
                        }
                    } else {
                        $(this).wrap( "<div class='dxoResponsiveTable'></div>" );
                    }
                });
            }
            
            //check if we have to hide a block element: table, bookmark or list
            //IMPORTANT: teh visibility properties of the blocks should be the same than when printing
            for (j = 0; j < numGroups; j++) { 
                if (docxpressoData.groups[j].display == 'hide') {
                    var element = $('*[data-id="' + docxpressoData.groups[j].groupId + '"]');
                    element.hide();
                } else if (docxpressoData.groups[j].print == 'unprint' || docxpressoData.groups[j].print == 'unprintable'|| docxpressoData.groups[j].print == 'never'){
                    //we are also hiding the blocks that should not be printed
                    var element = $('*[data-id="' + docxpressoData.groups[j].groupId + '"]');
                    element.removeAttr('data-type');
                    element.removeAttr('data-id');
                    element.attr('data-unprint', 1);
                    element.hide();
                }
            }
            for (j = 0; j < numPartials; j++) { 
                if (docxpressoData.partials[j].print == 'unprint'){
                    //we are also hiding the blocks that should not be printed
                    var element = $('div[class="partial_' + docxpressoData.partials[j].name + '"]');
                    element.removeAttr('data-type');
                    element.removeAttr('data-id');
                    element.attr('data-unprint', 1);
                    element.hide();
                }
            }
            
            window.templateVariables = {};
            window.templateSignatures = [];
            templateVars = [];
            //parse now the general data
            $.each(docxpressoData.data, function(index) { 
                templateVars.push(docxpressoData.data[index].name);
                var decorate = true;
                //decorate the variables
                if (docxpressoData.data[index].type == 'text') {
                    decorateTextVar(docxpressoData.data[index], 'text', decorate);
                } else if (docxpressoData.data[index].type == 'multilineText') {
                    decorateTextVar(docxpressoData.data[index], 'multilineText', decorate);
                } else if (docxpressoData.data[index].type == 'textarea') {
                    decorateTextVar(docxpressoData.data[index], 'textarea', decorate);
                } else if (docxpressoData.data[index].type == 'date') {
                    decorateDateVar(docxpressoData.data[index], decorate);
                } else if (docxpressoData.data[index].type == 'phone') {
                    //just decorate it as plain text
                    decorateTextVar(docxpressoData.data[index], 'text', decorate);
                } else if (docxpressoData.data[index].type == 'options') {
                    decorateOptionsVar(docxpressoData.data[index], decorate);
                } else if (docxpressoData.data[index].type == 'list') {
                    decorateListVar(docxpressoData.data[index], 'list', decorate);
                } else if (docxpressoData.data[index].type == 'rpc') {
                    decorateListVar(docxpressoData.data[index], 'rpc', decorate);
                } else if (docxpressoData.data[index].type == 'image') {
                    decorateImageVar(docxpressoData.data[index], decorate);
                } else if (docxpressoData.data[index].type == 'hidden') {
                    decorateHiddenVar(docxpressoData.data[index], decorate);
                } else if (docxpressoData.data[index].type == 'file') {
                    decorateFileVar(docxpressoData.data[index], decorate);
                }
                
                //decorate variable with external links
                if (typeof docxpressoData.data[index].link != 'undefined' 
                    && docxpressoData.data[index].link != ''
                    && decorate){
                    var span = $('span.h5p_varspan[data-name="' + docxpressoData.data[index].name + '"]');
                    counter = 0;
                    span.each(function(){
                        var button = '<button class="btn btn-warning btn-xs" ';
                        button += 'data-title="' + docxpressoData.data[index].label + '" ';
                        button += 'data-externalLink="' + docxpressoData.data[index].link + '" ';
                        button += '><i class="fa fa-link" aria-hidden="true"> </i></button>';
                        if (docxpressoData.data[index].type == 'textarea'){
                            $('<div style="float:left; margin-right: 4px"> ' + button + ' </div>').insertBefore( $(this).parent() );
                        } else if (docxpressoData.data[index].type == 'options' && (docxpressoData.data[index].choice == 'radio' || docxpressoData.data[index].choice == 'checkbox')){
                            if (counter == 0) {
                                $('<span> ' + button + ' </span>').insertBefore( $(this).parent() );
                            }
                        } else {
                            $('<span> ' + button + ' </span>').insertBefore( $(this).parent() );
                        }
                        counter++;
                    });
                    
                }

            });
                

            //parse Groups
            for (j = 0; j < numGroups; j++) {
                if (docxpressoData.groups[j].type == 'table') {
                    decorateTable(docxpressoData.groups[j].groupId, docxpressoData.groups[j].active);
                } else if (docxpressoData.groups[j].type == 'list') {
                    decorateList(docxpressoData.groups[j].groupId, docxpressoData.groups[j].active);
                } else if (docxpressoData.groups[j].type == 'block') {
                    decorateBlock(docxpressoData.groups[j]);
                }
            }

            window.templateVariables['162'] = templateVars;
            
            for (j = 0; j < numSpecial; j++) {
                if (typeof dxoSpecial[docxpressoData.special[j].name] == 'undefined') {
                    decorateSpecial(docxpressoData.special[j]);
                    dxoSpecial[docxpressoData.special[j].name] = docxpressoData.special[j];
                }
            } 
            
            //populate "remote dropdowns"
            remoteProcedureCallsDropdowns();
            
            //Text variables
            function decorateTextVar (data, type, decorate) {
                span = $('span.h5p_varspan[data-name="' + data.name + '"]');
                span.each(function(){
                    if (data.validation == 'email'){
                        if (window.emails.indexOf(data.name) < 0){
                            window.emails.push(data.name);
                        }
                    }
                    if (data.editable && decorate) {
                        $(this).addClass('decorated');
                        if (data.global) {
                            $(this).attr('data-global', '1');
                        }
                        if (typeof data.value !== 'undefined') {
                            $(this).html(decodeDXO(data.value));
                        } else {
                            if (typeof defValuesForm[data.name] !== 'undefined' && defValuesForm[data.name] !== ''){
                                //loaded from a form default 
                                var insertval = defValuesForm[data.name];
                            } else if (typeof data.default != 'undefined' && data.default != '') {
                                var insertval = data.default;
                            } else if (data.label.charAt(0) == '@') {
                                var insertval = data.label.substring(1);
                            } else {
                                var insertval = data.label;
                            }
                            $(this).html(decodeDXO(insertval));
                        }
                        spanParent = $(this).parents('span.spanWrapper:first');
                        //enforce original span CSS props
                        parentTag = $(spanParent).parent();
                        parentTagName = $(parentTag).prop('tagName');
                        if (parentTagName.toLowerCase() == 'span') {
                            var classes = $(parentTag).attr('class');
                            if (typeof classes == 'string' && classes != '') {
                                $(this).attr('class', classes + ' h5p_varspan decorated');
                            }
                        }
                        if (type == 'textarea') {
                            $('<div style="float: left; width: 15px;"><i class="fa fa-edit red"> </i></div>').prependTo(spanParent);
                        } else {
                            spanParent.addClass('spanWrapperBackground');
                            spanParent.addClass('spanWrapperIcon');
                        }
                        spanParent.data('label', data.label);
                        spanParent.data('name', data.name);
                        spanParent.data('type', type);
                        if (type == 'textarea') {
                            $(this).removeAttr('contenteditable');
                            span.attr('style', 'display: inline-block');
                        }
                    } else {
                        $(this).html(decodeDXO(data.label));
                        $(this).removeAttr('contenteditable');
                    }
                });   
            }
            //Hidden variables
            function decorateHiddenVar (data, decorate) {
                span = $('span.h5p_varspan[data-name="' + data.name + '"]');
                span.each(function(){
                    $(this).css('display', 'none');
                    $(this).removeAttr('contenteditable');
                    if (typeof defValuesForm[data.name] !== 'undefined' && defValuesForm[data.name] !== ''){
                        //loaded from a form default 
                        $(this).html(defValuesForm[data.name]);
                    } else if (typeof data.default != 'undefined' && data.default != '') {
                        $(this).html(data.default);
                    }
                });   
            }
            //Date variables
            function decorateDateVar (data, decorate) {
                span = $('span.h5p_varspan[data-name="' + data.name + '"]');
                span.each(function(){
                    if (data.editable && decorate) {
                        $(this).addClass('decorated');
                        if (data.global) {
                            $(this).attr('data-global', '1');
                        }
                        
                        spanParent = $(this).parents('span.spanWrapper:first');
                        spanParent.addClass('spanWrapperBackground');
                        parentTag = $(spanParent).parent();
                        parentTagName = $(parentTag).prop('tagName');
                        if (parentTagName.toLowerCase() == 'span') {
                            var classes = $(parentTag).attr('class');
                            if (typeof classes == 'string' && classes != '') {
                                $(span).attr('class', classes + ' h5p_varspan decorated');
                            }
                        }
                        //$('<i class="fa fa-calendar"> </i>').prependTo(spanParent);
                        spanParent.data('label', data.label);
                        spanParent.data('name', data.name);
                        if (typeof data.exp === 'undefined' || data.exp == '') {
                            data.exp = 'dd/mm/yyyy';
                        }
                        //$(spanParent).datepicker({format: data.exp, todayHighlight: true, autoclose: true, language: 'es', clearBtn: true});
                        var defaultDate = '';
                        if (typeof defValuesForm[data.name] !== 'undefined' && defValuesForm[data.name] !== ''){
                            //loaded from a form default 
                            defaultDate = defValuesForm[data.name];
                        } else if (typeof data.default != 'undefined' && data.default != '') {
                            defaultDate = data.default;
                        }
                        if (defaultDate != '') {
                            if (defaultDate == 'today' || defaultDate == 'hoy'){
                                $(spanParent).datepicker('update', new Date());
                                $(this).html($(spanParent).datepicker('getFormattedDate'));
                            } else if (defaultDate.charAt(0) == '+'){
                                var delay = defaultDate.replace('+', '');
                                var myDate = new Date();
                                myDate.setDate(myDate.getDate() + parseInt(delay));
                                $(spanParent).datepicker('update', myDate);
                                $(this).html($(spanParent).datepicker('getFormattedDate'));
                            } else {
                                //var curdate = data.default.replace(' de ', ' &#100;e ');
                                $(spanParent).datepicker('update', decodeDXO(defaultDate));
                                $(this).html($(spanParent).datepicker('getFormattedDate'));
                            }
                        } else {
                            $(this).html(decodeDXO(data.label));
                        }
                        $(spanParent).on("changeDate", function(event) {
                            var newdate = $(this).datepicker('getFormattedDate');
                            $(this).children('span:first').html(newdate);
                            $(this).datepicker('hide');
                            if (data.global){
                                setTimeout(function(){updateGlobalVariables(data.name, newdate);}, 100);
                            }
                        });
                    } else {
                        $(this).html(decodeDXO(data.label));
                        $(this).removeAttr('contenteditable');
                    }
                });
            }
            //a helper to update global variables after a "programmatic change like for example dates
            function updateGlobalVariables (name, value){
                $('span.h5p_varspan[data-name="' + name + '"]').html(value);
            }
            //Select variables
            function decorateListVar (data, type, decorate) {
                span = $('span.h5p_varspan[data-name="' + data.name + '"]');
                var counter = 0;
                $.each(span, function(){
                    if (data.global) {
                        $(this).attr('data-global', '1');
                        var globalVar = true;
                    } else {
                        var globalVar = false;
                    }
                    if (typeof data.value !== 'undefined') {
                        $(this).html(decodeDXO(data.value));
                    } else {
                        $(this).html(decodeDXO(data.label));
                    }
                    spanParent = $(this).parents('span.spanWrapper:first');
                    $('<i class="fa fa-edit"> </i>').prependTo(spanParent);
                    spanParent.data('label', data.label);
                    spanParent.data('name', data.name);
                    spanParent.css('display', 'none');
                    var selectData = '<select ';
                    if (!data.edit || !decorate){
                        selectData += 'disabledNo style="background-color: #f0f0f0" ';
                    } else {
                        selectData += 'class="decorated" ';
                    }
                    selectData += 'data-label="' + data.label + '" data-reference="' + data.name + '" aria-label="' + data.label + '" data-list="' + data.name + '" >';
                    selectData += '<option value="" style="color: #ccc;" selected>' + decodeDXO(data.label) + '</option>';
                    selectData += '</select>';
                    var selInserted = $(selectData).insertBefore(spanParent);
                    spanParent.prev().bind('click keyup', function(){
                        if($(this).val() != ''){
                            $(this).next().find('span:first').html($(this).val());
                        }
                        if(data.global){
                            $('select[data-reference="' + data.name+ '"]').val($(this).val());
                            $('select[data-reference="' + data.name+ '"]').next().find('span:first').html($(this).val());
                        }
                        refreshValidation(data.name);
                    });
                    if (typeof window.dependencies[data.name] != 'undefined'
                        || typeof window.partials[data.name] != 'undefined'
                        || typeof window.annexes[data.name] != 'undefined' ) {
                        $('body').on('change', 'select[data-reference="' + data.name+ '"]', function(){
                            if (typeof window.dependencies[data.name] != 'undefined'
                                || typeof window.partials[data.name] != 'undefined'){
                                modifyBlockVisibility(data.name, $(this).val(), $(this), globalVar);
                            }
                            if (typeof window.annexes[data.name] != 'undefined'){
                                annexesVisibility(data.name, $(this).val(), $(this));
                            }
                        });
                    }
                    //get the options from the resource
                    if (counter == 0){
                        //this condition is to avoid loading the same resource more than once
                        trigger = 0;
                        if (type == 'list') {
                            var rpcurl = "https://consents.globalcareondemand.com/auxdata/resourcedata?callback=?&id=" + data.list;
                        } else {
                            rpc = window.rpcData[data.rpc];
                            var rpcurl = createRPCURL(rpc, query);
                            if (typeof rpc.trigger != 'undefined') {
                                trigger = rpc.trigger;
                            }
                        }
                        window.rpcs.push([data.name, rpcurl, type, trigger]);
                    }
                    counter++;
                    //change visibility on load
                    modifyBlockVisibility(data.name, $(this).val(), $(this), globalVar);
                    annexesVisibility(data.name, $(this).val());
                });
            }           
            
            function decorateOptionsVar (data, decorate) {
                var span = $('span.h5p_varspan[data-name="' + data.name + '"]');
                var optionStr = decodeDXO(data.options);
                if (typeof defValuesForm[data.name] !== 'undefined' && defValuesForm[data.name] !== ''){
                    //loaded from a form default 
                    var defaultStr = decodeDXO(defValuesForm[data.name]);
                } else if (typeof data.default != 'undefined' && data.default != '') {
                    var defaultStr = decodeDXO(data.default);
                } else {
                    var defaultStr = ''
                }
                var options = optionStr.split(';');
                var defOptions = defaultStr.split(';');
                if (typeof data.choice === 'undefined' || data.choice === 'dropdown' || data.choice === 'multipleSelect'){
                    span.each(function(){
                        if (data.global) {
                            $(this).attr('data-global', '1');
                            var globalVar = true;
                        } else {
                            var globalVar = false;
                        }
                        if (typeof data.value !== 'undefined') {
                            $(this).html(decodeDXO(data.value));
                        } else {
                            $(this).html(decodeDXO(data.label));
                        }
                        spanParent = $(this).parents('span.spanWrapper:first');
                        $('<i class="fa fa-edit"> </i>').prependTo(spanParent);
                        spanParent.data('label', data.label);
                        spanParent.data('name', data.name);
                        spanParent.css('display', 'none');
                        var selectData = '<select ';
                        if (data.choice === 'multipleSelect' || ((data.choice === 'checkbox' || data.choice === 'radio') && options.length > 1) ){
                            //we dispaly multiple checkboxes and radios as multiple selects within interactive documents
                            selectData += 'multiple ';
                            window.multiselects[data.name] = [];
                        }
                        if (!data.edit || !decorate){
                            selectData += 'disabledNo style="background-color: #f0f0f0" ';
                        } else {
                            selectData += 'class="decorated" ';
                        }
                        selectData += 'data-label="' + data.label + '" aria-label="' + data.label + '" data-reference="' + data.name + '" data-list="' + data.name + '">';
                        if (decodeDXO(data.label).trim() != ''){
                            selectData += '<option value="' + decodeDXO(data.label).replace(/"/g, '&quot;') + '" class="disabledOption" selected>' + decodeDXO(data.label) + '</option>';
                        }
                        for (var k=0; k < options.length; k++) {
                            if (defOptions.indexOf(options[k]) > -1){
                                var defval = options[k].replace(/"/g, '&quot;');
                                selectData += '<option value="' + options[k].replace(/"/g, '&quot;')  + '" selected>' + options[k] + '</option>';
                            } else if (options[k].charAt(0) == '@') {
                                opt = options[k].substring(1);
                                var defval = opt.replace(/"/g, '&quot;');
                                selectData += '<option value="' + opt.replace(/"/g, '&quot;')  + '" selected>' + opt + '</option>';
                                $(this).html(opt);
                            } else if (options[k].charAt(0) == '#') {
                                opt = options[k].substring(1);
                                selectData += '<option value="' + opt.replace(/"/g, '&quot;')  + '" data-select="' + data.name + '">' + opt + '</option>';
                            } else {
                                selectData += '<option value="' + options[k].replace(/"/g, '&quot;') 
                                           + '">' + options[k] + '</option>';
                            }
                        }
                        selectData += '</select>';
                        var selInserted = $(selectData).insertBefore(spanParent);
                        selInserted.attr('data-default', defval);
                        spanParent.prev().bind('click keyup', function(){
                            if($(this).val() != ''){
                                $(this).next().find('span:first').html($(this).val());
                            }
                            if(data.global){
                                $('select[data-reference="' + data.name+ '"]').val($(this).val());
                                $('select[data-reference="' + data.name+ '"]').next().find('span:first').html($(this).val());
                            }
                            refreshValidation(data.name);
                        });
                        if (typeof window.dependencies[data.name] != 'undefined'
                            || typeof window.partials[data.name] != 'undefined'
                            || typeof window.annexes[data.name] != 'undefined' ) {
                            $('body').on('change', 'select[data-reference="' + data.name+ '"]', function(){
                                if (typeof window.dependencies[data.name] != 'undefined'
                                    || typeof window.partials[data.name] != 'undefined'){
                                    modifyBlockVisibility(data.name, $(this).val(), $(this), globalVar);
                                }
                                if (typeof window.annexes[data.name] != 'undefined'){
                                    annexesVisibility(data.name, $(this).val(), $(this));
                                }
                            });
                        } 
                        //change visibility on load
                        modifyBlockVisibility(data.name, spanParent.prev().val(), spanParent.prev(), globalVar);
                        annexesVisibility(data.name, spanParent.prev().val());
                    });
                } else if (data.choice === 'radio' || data.choice === 'checkbox') {
                    if (data.global) {
                        var globalVar = true;
                    } else {
                        var globalVar = false;
                    }
                    olength = options.length;
                    span.each(function(index){
                        spanParent = $(this).parents('span.spanWrapper:first');
                        spanParent.data('label', data.label);
                        spanParent.data('name', data.name);
                        if (data.edit && decorate){
                            $(this).addClass('decorated');
                        }
                        $(this).addClass('choice');
                        $(this).attr('contenteditable', false);
                        $(this).html('');
                        opt = options[index % olength];
                        if (defOptions.indexOf(opt) > -1){
                                var element = '<label class="container-' + data.choice + '"><span class="hidden">' + decodeURIComponent(opt.replace(/"/g, '&quot;')) + '</span><input type="' + data.choice + '" aria-label ="' + data.label + '" name ="' + data.name + '" value="' + opt.replace(/"/g, '&quot;')  + '" data-list="' + data.name + '"  data-family="' + data.name + '" data-name="' + data.name + '"';
                                if (!data.edit || !decorate){
                                    element += ' disabledNo ';
                                }
                                element += ' checked /><span class="' + data.choice + '-mark"></span></label>';
                        } else if (opt.charAt(0) == '@') {
                            opt = opt.substring(1);
                            var element = '<label  class="container-' + data.choice + '"><span class="hidden">' + decodeURIComponent(opt.replace(/"/g, '&quot;')) + '</span><input type="' + data.choice + '" aria-label ="' + data.label + '" name ="' + data.name + '" value="' + opt.replace(/"/g, '&quot;')  + '" data-list="' + data.name + '"  data-family="' + data.name + '" data-name="' + data.name + '"';
                            if (!data.edit || !decorate){
                                element += ' disabledNO ';
                            }
                            element += ' checked /><span class="' + data.choice + '-mark"></span></label>';
                        } else {
                            var element = '<label  class="container-' + data.choice + '"><span class="hidden">' + decodeURIComponent(opt.replace(/"/g, '&quot;')) + '</span><input type="' + data.choice + '" aria-label ="' + data.label + '" name ="' + data.name + '" value="' + opt.replace(/"/g, '&quot;')  + '" data-list="' + data.name + '"  data-family="' + data.name + '" data-name="' + data.name + '"';
                            if (!data.edit || !decorate){
                                element += ' disabledNo ';
                            }
                            element += ' /><span class="' + data.choice + '-mark"></span></label>';
                        }
                        var choice = $(element).appendTo($(this));
                        if (typeof window.dependencies[data.name] !== 'undefined'
                            || typeof window.partials[data.name] != 'undefined'
                            || typeof window.annexes[data.name] !== 'undefined') {
                            $('body').on('change', 'input[name="' + data. name + '"]', function(){
                                //we should only get de values associated with a single
                                //"data-family" group if blocks are cloned
                                var family = $(this).attr('data-family');
                                choices = $('input[name="' + data. name + '"][data-family="' + family + '"]:checked');
                                if(typeof window.dependencies[data.name] !== 'undefined'
                                   || typeof window.partials[data.name] != 'undefined'){
                                    if (choices.length > 0) {
                                        var selectedOptions = [];
                                        choices.each(function(){
                                            selectedOptions.push($(this).val());
                                        });
                                        modifyBlockVisibility(data.name, selectedOptions.join(';'), $(this), globalVar);
                                    } else {
                                        modifyBlockVisibility(data.name, '--toggle--it', $(this), globalVar);
                                    }
                                }
                                if(typeof window.annexes[data.name] !== 'undefined'){
                                    if (choices.length > 0) {
                                        choices.each(function(){
                                            annexesVisibility(data.name, $(this).val());
                                        });
                                    } else {
                                        annexesVisibility(data.name, '--toggle--it');
                                    }
                                }
                            });
                        }
                    });
                    //change visibility on load 
                    //TODO: double check that we do not need to test for data-family at this stage
                    choices = $('input[name="' + data. name + '"]:checked');
                    if (choices.length > 0) {
                        if (data.choice === 'radio' || data.choice === 'checkbox'){
                            var selectedOptions = [];
                            choices.each(function(){
                                selectedOptions.push($(this).val());
                            });
                            modifyBlockVisibility(data.name, selectedOptions.join(';'), $(this), globalVar);
                        } else {
                            choices.each(function(){
                                modifyBlockVisibility(data.name, $(this).val(), $(this), globalVar);
                                annexesVisibility(data.name, $(this).val());
                            }); 
                        }
                    } else {
                        modifyBlockVisibility(data.name, '--toggle--it', $(this), globalVar);
                        annexesVisibility(data.name, '--toggle--it');
                    }
                } 
            }
            
            //decorate multiselects
            function decorateMultiSelects(){
                $('#mainDXO select[multiple]').multiselect({
                    onChange: function(option, checked, select) {
                        reference = $(this)[0]['$select'].data('reference');
                        window.multiselects[reference] = $('select[data-reference="' + reference + '"]').val();
                    },
                    onInitialized: function(select, container) {
                        var spanChild = container.find('span.multiselect-selected-text');
                        var spanParent = container.parents('span[data-h5p]:first');
                        var ff = spanParent.css('font-family');
                        var fs = spanParent.css('font-size');
                        spanChild.css('font-family', ff);
                        spanChild.css('font-size', fs);
                    }
                });

                //remove the first selected value in multiselects
                $('#mainDXO select[multiple]').each(function(){
                    var label = decodeURI($(this).data('label'));
                    $(this).multiselect('deselect', label);
                    //$(this).next().find('input[value="' + label + '"]').prop('disabled', true);
                });
            }
            
            decorateMultiSelects();
            
            function updateSelects(){
                $('select[data-reference]:not([multiple])').each(function(){
                    selData = $(this).next().find('.h5p_varspan').text();
                    //if (selData != decodeURIComponent($(this).attr('data-reference'))) {
                        //the first condition is to avoid trying to update the select to its placeholder value
                        $(this).val(selData);
                    //}
                });
                $('select[data-reference][multiple]').each(function(){
                    span = $(this).next().find('.h5p_varspan');
                    var tmp = [];
                    var nodes = $(span)[0].childNodes;
                    $(nodes).each(function(){
                        tmp.push($(this).text());
                    });
                    //let us make sure that teh multiselect does not lie with no label
                    if (tmp.length == 0){
                        tmp[0] = $(this).attr('data-label');
                    }
                    $(this).val(tmp);
                });
            }
            

            //image variables
            function decorateImageVar (data, decorate) {
                if (data.source == 'QR'){
                    //the QR es generated by Docxpresso so we just exits silently
                    return;
                }
                img = $('img[data-image="' + data.name + '"]');
                img.css('cursor', 'default');
                /*img.each(function(){
                    var imageDecorated = $(this);
                    if (data.editable && decorate) {
                        $(this).addClass('decorated');
                        $(this).removeAttr('title');
                        if (data.global) {
                            $(this).attr('data-global', '1');
                        }
                        if (typeof data.value !== 'undefined') {
                            $(this).attr('src', data.value);
                        } 
                        preImageNode = '<i class="fa fa-picture-o preImage"> </i>';
                        $(preImageNode).insertBefore(this);
                    } else {
                        if (typeof data.value !== 'undefined') {
                            $(this).attr('src', data.value);
                        }
                        $(this).removeAttr('contenteditable');
                    }
                }); */           
            }
            //File type variables
            function decorateFileVar (data, decorate) {
                span = $('span.h5p_varspan[data-name="' + data.name + '"]');
                span.each(function(){
                    $(this).removeAttr('contenteditable');
                    if (data.editable && decorate) {
                        if (data.global) {
                            $(this).attr('data-global', '1');
                        }
                        spanParent = $(this).parents('span.spanWrapper:first');
                        $(this).addClass('decorated');
                        spanParent.data('label', data.label);
                        spanParent.data('name', data.name);
                        spanParent.data('type', data.type);
                        for (var k in docxpressoData['attachments']['files']){
                            if (docxpressoData['attachments']['files'][k]['linkedTo'] == data.name) {
                                var file = encodeDXO(docxpressoData['attachments']['files'][k]['name']); 
                                content = '<big><small class="fileName" data-file="'+ file + '"> </small></big>';
                                $(this).html(decodeDXO(content));
                                break;
                            }
                        }
                    } else {
                        if (data.global) {
                            $(this).attr('data-global', '1');
                        }
                        for (var k in docxpressoData['attachments']['files']){
                            if (docxpressoData['attachments']['files'][k]['linkedTo'] == data.name) {
                                var file = encodeDXO(docxpressoData['attachments']['files'][k]['name']);
                                content = '<small class="fileName" data-file="'+ file + '"> </small>';
                                $(this).html(decodeDXO(content));
                                break;
                            }
                        }
                    }
                });
            }
            
            //Preload preattched files
            var preAttached = $('#preAttached').val();
            var parsedPreAttched = $('<div />').html(preAttached).text();
            if (parsedPreAttched == ''){
                parsedPreAttched = '{}';
            }
            var preAttachments = JSON.parse(parsedPreAttched);
            $.each(preAttachments, function(index) {
                var link = '<a href="' + preAttachments[index]['url'] + '" target="_blank">' + preAttachments[index]['originalName'] + '</a>';
                $('small[data-file="' + index +'"]').html(link);
                $('button[data-removefile="' + index + '"]').css('display', 'inline');
            });
            
                      
            
            //because images we have to get its dimensions
            $('img[data-image]').load(function(){
                var h = $(this).css('height');
                var w = $(this).css('width');
                $(this).attr('data-height', h);
                $(this).attr('data-width', w);
            });
            //activate the image icon so the click event is bubble up
            $('.preImage').click(function(){
                $(this).parent().children('img[data-image]').click();
            });
            
            //special variable
            function decorateSpecial (data) {
                span = $('span.h5p_varspecial[data-name="' + data.name + '"]');
                span.each(function(){
                    spanParent = $(this).parents('span.spanWrapperSpecial:first');
                    parentTag = $(spanParent).parent();
                    parentTagName = $(parentTag).prop('tagName');
                    if (parentTagName.toLowerCase() == 'span') {
                        var classes = $(parentTag).attr('class');
                        if (typeof classes == 'string' && classes != '') {
                            $(span).attr('class', classes + ' h5p_varspecial');
                        }
                    }
                    if (typeof data.value !== 'undefined') {
                        $(this).html(decodeDXO(data.value));
                    } else {
                        $(this).html(decodeDXO(data.label));
                    }
                    //$('<i class="fa fa-refresh"> </i>').prependTo(spanParent);
                    spanParent.data('label', data.label);
                    spanParent.data('name', data.name);
                });                
            }
            //block visibility
            function modifyBlockVisibility(name, value, node, global){
                for (blocks in window.dependencies[name]) {
                    groupId = blocks;
                    values = window.dependencies[name][groupId];
                    if (typeof values == 'string'){
                        var tmp = values.split(';');
                        display = dxoGroups[groupId]['display'];
                        //the selector may depende if it is a global variable
                        //and or if there is a single ocurrence of that node
                        divo = getAffectedNodes(groupId, name, node, global)
                        var state = 'show';
                        if ( checkMatch(tmp, value) ){
                            //toggle visibility
                            if (display === 'show') {
                                $(divo).hide();
                                modifyVisibilityTrailingWhitespace(divo, dxoGroups[groupId], 'hide')
                                state = 'hide';
                            } else {
                                $(divo).show();
                                modifyVisibilityTrailingWhitespace(divo, dxoGroups[groupId], 'show')
                            }
                        } else {
                            //recover original state
                            if (display === 'show') {
                                $(divo).show();
                                modifyVisibilityTrailingWhitespace(divo, dxoGroups[groupId], 'show')
                            } else {
                                $(divo).hide();
                                modifyVisibilityTrailingWhitespace(divo, dxoGroups[groupId], 'hide')
                                state = 'hide';
                            }
                        }
                    }
                }
                //now run over the partials
                for (partial in window.partials[name]) {
                    var values = window.partials[name][partial];
                    if (typeof values == 'string'){
                        var tmp = values.split(';');
                        var display = dxoPartials[partial]['display'];
                        //the selector may depende if it is a global variable
                        //and or if there is a single ocurrence of that node
                        var divo = $('div.partial_' + partial);
                        var state = 'show';
                        if ( checkMatch(tmp, value) ){
                            //toggle visibility
                            if (display === 'show') {
                                $(divo).hide();
                                //modifyVisibilityTrailingWhitespace(divo, dxoPartials[partial], 'hide')
                                state = 'hide';
                            } else {
                                $(divo).show();
                                //modifyVisibilityTrailingWhitespace(divo, dxoPartials[partial], 'show')
                            }
                        } else {
                            //recover original state
                            if (display === 'show') {
                                $(divo).show();
                                //modifyVisibilityTrailingWhitespace(divo, dxoPartials[partial], 'show')
                            } else {
                                $(divo).hide();
                                //modifyVisibilityTrailingWhitespace(divo, dxoPartials[partial], 'hide')
                                state = 'hide';
                            }
                        }
                    }
                }
                window.modifiedVisibility = true;
            }
            //WARNING: Modified from preview to get values from spans in lists
            function getAffectedNodes (groupId, varname, node, global){
                if (global){
                    return $('*[data-id="' + groupId + '"]');
                } else {
                    var type = dxo[varname].type;
                    var choice = dxo[varname].choice;
                    if (type == 'list'){
                        var num = $('select[data-list="' + varname + '"]').length;
                        if (num == 1){
                            return $('*[data-id="' + groupId + '"]');
                        } else {
                            //get the index of that precise ocurrence
                            var index = $('select[data-list="' + varname + '"]').index( node );
                            //get the index of that precise ocurrence
                            var index = $('select[data-list="' + varname + '"]').index( node );
                            //check if it is cloned
                            var clonedparents = $(node).parents('[data-id]:first').length;
                            if (clonedparents > 0){
                                //we have to distinguish between tables and bookmarks
                                if($(node).parents('[data-id]:first').prop('tagName') == 'TABLE'){
                                    $block = $(node).parents('tbody:first').find('*[data-id="' + groupId + '"]');
                                    if ($block.length == 0){
                                        //go one level higher
                                        $parentBlock = $(node).parents('[data-id]:first').parents('[data-id]:first').prop('tagName');
                                        if ($parentBlock == 'TABLE'){
                                            $block = $(node).parents('tbody:first').parents('tbody:first').find('*[data-id="' + groupId + '"]');
                                        } else {
                                            $block = $(node).parents('tbody:first').parents('[data-id]:first').find('*[data-id="' + groupId + '"]');
                                        }
                                    }
                                    return $block;
                                } else {
                                    $block = $(node).parents('[data-id]:first').find('*[data-id="' + groupId + '"]');
                                    if ($block.length == 0){
                                        //go one level higher
                                        $parentBlock = $(node).parents('[data-id]:first').parents('[data-id]:first').prop('tagName');
                                        if ($parentBlock == 'TABLE'){
                                            $block = $(node).parents('[data-id]:first').parents('tbody:first').find('*[data-id="' + groupId + '"]');
                                        } else {
                                            $block = $(node).parents('[data-id]:first').parents('[data-id]:first').find('*[data-id="' + groupId + '"]');
                                        }
                                    }
                                    return $block;
                                    //return $(node).parents('[data-id]:first').find('*[data-id="' + groupId + '"]');
                                }
                            } else {
                                return $('*[data-id="' + groupId + '"]').eq(index);
                            }
                        }      
                    } else if (type == 'options'){
                        //we have several subcases
                        if (typeof choice === 'undefined' || choice === 'dropdown' || choice === 'multipleSelect'){
                            var num = $('select[data-list="' + varname + '"]').length;
                            if (num == 1){
                                return $('*[data-id="' + groupId + '"]');
                            } else {
                                //get the index of that precise ocurrence
                                var index = $('select[data-list="' + varname + '"]').index( node );
                                //check if it is cloned
                                var clonedparents = $(node).parents('[data-id]:first').length;
                                if (clonedparents > 0){
                                    //we have to distinguish between tables and bookmarks
                                    if($(node).parents('[data-id]:first').prop('tagName') == 'TABLE'){
                                        $block = $(node).parents('tbody:first').find('*[data-id="' + groupId + '"]');
                                        if ($block.length == 0){
                                            //go one level higher
                                            $parentBlock = $(node).parents('[data-id]:first').parents('[data-id]:first').prop('tagName');
                                            if ($parentBlock == 'TABLE'){
                                                $block = $(node).parents('tbody:first').parents('tbody:first').find('*[data-id="' + groupId + '"]');
                                            } else {
                                                $block = $(node).parents('tbody:first').parents('[data-id]:first').find('*[data-id="' + groupId + '"]');
                                            }
                                        }
                                        return $block;
                                    } else {
                                        $block = $(node).parents('[data-id]:first').find('*[data-id="' + groupId + '"]');
                                        if ($block.length == 0){
                                            //go one level higher
                                            $parentBlock = $(node).parents('[data-id]:first').parents('[data-id]:first').prop('tagName');
                                            if ($parentBlock == 'TABLE'){
                                                $block = $(node).parents('[data-id]:first').parents('tbody:first').find('*[data-id="' + groupId + '"]');
                                            } else {
                                                $block = $(node).parents('[data-id]:first').parents('[data-id]:first').find('*[data-id="' + groupId + '"]');
                                            }
                                        }
                                        return $block;
                                        //return $(node).parents('[data-id]:first').find('*[data-id="' + groupId + '"]');
                                    }
                                } else {
                                    return $('*[data-id="' + groupId + '"]').eq(index);
                                }
                            } 
                        } else if (choice == 'radio' || choice == 'checkbox'){
                            //this case is much more complicated because we may have multiple input 
                            //elements within a group
                            var families = [];
                            $('input[data-name="' + varname + '"][data-family]').each(function(){
                                var family = $(this).attr('data-family');
                                if (families.indexOf(family) < 0){
                                    families.push(family);
                                }                                 
                            });
                            if (families.length == 1){
                                return $('*[data-id="' + groupId + '"]');
                            } else {
                                //get the position in the array
                                var myFamily = node.attr('data-family');
                                var myIndex = families.indexOf(myFamily);
                                if (myIndex >= 0){
                                    return $('*[data-id="' + groupId + '"]').eq(myIndex);
                                } else {
                                    return $('*[data-id="' + groupId + '"]');
                                }
                            }
                        }
                    }
                }
            }
            //general function to update visibility after data loading
            //WARNING: Modified from preview to get values from spans in lists
            function modifyGeneralBlockVisibility (){
                dependencyVisibility(window.dependencies);
                dependencyVisibility(window.partials);
            }
            
            function dependencyVisibility(origin){
                var families = [];
                //run over all dependencies
                for (propname in origin){
                    //use try catch for potential errors when importing data from another template
                    try{
                        //first get some required properties
                        var global = dxo[propname].global;
                        //relevant types are options, lists and rpcs
                        var type = dxo[propname].type;
                        var choice = dxo[propname].choice;
                        //let us now run over the relevant cases
                        if (type == 'list'){
                            $('span[data-name="' + propname + '"]').each(function(){
                                modifyBlockVisibility(propname, $(this).text(), $(this), global);
                            });
                        } else if (type == 'options'){
                            //we have several subcases
                            if (typeof choice === 'undefined' || choice === 'dropdown' || choice === 'multipleSelect'){
                                $('select[data-list="' + propname + '"]').each(function(){
                                    modifyBlockVisibility(propname, $(this).val(), $(this), global);
                                });
                            } else if (choice == 'radio' || choice == 'checkbox'){
                                $('input[data-name="' + propname + '"]').each(function(){
                                    var family = $(this).attr('data-family');
                                    if (families.indexOf(family) < 0){
                                        families.push(family);
                                        choices = $('input[data-name="' + propname + '"][data-family="' + family + '"]:checked');
                                        selectedOptions = [];
                                        if (choices.length > 0) {
                                            var selectedOptions = [];
                                            choices.each(function(){
                                                selectedOptions.push($(this).val());
                                            });
                                            modifyBlockVisibility(propname, selectedOptions.join(';'), $(this), global);
                                        } else {
                                            modifyBlockVisibility(propname, '--toggle-it', $(this), global);
                                        }
                                    }
                                });
                            }
                        }
                    } catch(error){
                        console.log(error);
                    }
                }
            }
            
            function modifyVisibilityTrailingWhitespace(divo, grouprops, mode){
                //check if we have to handle trailing whitespace
                if (typeof grouprops['removeWhitespace'] != 'undefrined'
                    && grouprops['removeWhitespace']){
                    if (divo.prop('tagName') == 'TABLE' 
                        && divo.parent().prop('tagName') == 'DIV'){
                        //tables are wrapped in a div
                        var nextNode = divo.parent().next();
                    } else {
                        var nextNode = divo.next();
                    }
                    if(nextNode.prop('tagName') == 'P'){
                        var ptext = nextNode.text().trim();
                        //remove all whitespace chars
                        const pregex = /&nbsp;/gi;
                        ptext.replace(pregex, '').trim();
                        if (ptext == '' && mode == 'show'){
                            nextNode.show();
                        } else if (ptext == '' && mode == 'hide'){
                            nextNode.hide();
                        }
                    }
                }
            }
            
            //annex visibility
            function annexesVisibility(name, value){
                if (typeof window.annexes[name] == 'undefined'){
                    return;
                }
                var len = window.annexes[name]['documents'].length;
                var found = false;
                var token = '';
                var index = window.annexes[name]['index'];
                var old_token = $('#loadAnnex_' + index).attr('data-token');
                for(var k = 0; k < len; k++){
                    var varValues = decodeURIComponent(window.annexes[name]['documents'][k].varValues).split(';');
                    var annex = window.annexes[name]['documents'][k].annexId;
                    if ( checkMatch(varValues, value) ){
                        found = true;
                        token = annex;
                    }
                }
                if (found){
                    if (token != '0' && token != old_token){
                        $('#loadAnnex_' + index).html('');
                        $('#loadAnnex_' + index).removeAttr('data-token');
                        $('#loadAnnex_' + index).attr('data-token', token);
                        $('#loadAnnex_' + index).load('/documents/load_annexes' + '?token=' + token);
                    } else if (token == '0') {
                        $('#loadAnnex_' + index).html('');
                        $('#loadAnnex_' + index).removeAttr('data-token');
                    }
                } else {
                    if (window.annexes[name]['default'] != '' && window.annexes[name]['default'] != old_token){
                        $('#loadAnnex_' + index).html('');
                        $('#loadAnnex_' + index).removeAttr('data-token');
                        $('#loadAnnex_' + index).attr('data-token', window.annexes[name]['default']);
                        $('#loadAnnex_' + index).load('/documents/load_annexes' + '?token=' + window.annexes[name]['default']);
                    } else if (window.annexes[name]['default'] != old_token) {
                        $('#loadAnnex_' + index).html('');
                        $('#loadAnnex_' + index).removeAttr('data-token');
                    }
                }
            }
            
            function checkMatch(origin, target){
                var found = false;
                if (typeof target == 'string'){
                    var arrTarget = target.split(';');   
                } else {
                    var arrTarget = target;
                }
                if (arrTarget != null){
                    var len = arrTarget.length;
                    for (var k = 0; k < len; k++){
                        if (origin.indexOf(encodeURI(arrTarget[k].trim())) > -1 || origin.indexOf(arrTarget[k].trim()) > -1){
                            found = true;
                        }
                    }
                }
                return found;
            }
            
            //TABLES
            function decorateTable (groupId, active){
                //we should also check that there is at least an editable variable within
                var editable = false;
                var innerVars = dxoGroups[groupId].variables;
                var n = innerVars.length;
                for (var j = 0; j < n; j++){
                    if (typeof dxo[innerVars[j]] != 'undefined' && dxo[innerVars[j]].editable){
                        editable = true;
                    }
                }
            }
            
            
                
            
                
            //LISTS
            function decorateList (groupId, active){
                //we should also check that there is at least an editable variable within
                var editable = false;
                var innerVars = dxoGroups[groupId].variables;
                var n = innerVars.length;
                for (var j = 0; j < n; j++){
                    if (dxo[innerVars[j]].editable){
                        editable = true;
                    }
                }
                if (active == false || editable == false) {
                    $( "li[data-id='" + groupId + "']" ).removeClass('h5p_listitem');
                    return false;
                }
                
                
            }

            //BLOCKS
            function decorateBlock (data){
                //first check if this block is "unbrowsable" so it is ignored in the
                //browser interface
                if (data.print == 'unbrowsable' || data.print == 'never'){
                    return;
                }
                //we should also check that there is at least an editable variable within
                var editable = false;
                var innerVars = dxoGroups[data.groupId].variables;
                var n = innerVars.length;
                for (var j = 0; j < n; j++){
                    if (dxo[innerVars[j]].editable){
                        editable = true;
                    }
                }
                //remove decoration
                $( "div[data-id='" + data.groupId + "']" ).removeClass('h5p_wrappingdiv');

                DIV = $( "div[data-id='" + data.groupId + "']" );
                //check for visibility and dependencies
                if (data.display == 'show') {
                    $(DIV).css('display', 'block');
                } else {
                    $(DIV).css('display', 'none');
                }
            }
            
            
            //tooltips and helpers
            //standard variables
            $('[contenteditable]').not(".note-editable").focus
            (function(){
                var node = $(this);
                //select text on variables that have not been yet edited
                var name = $(this).attr('data-name');
                var def = decodeDXO(dxo[name]['label'])
                if ($(this).text().trim() == def) {
                    //select the text
                    var selText = document.createRange();
                    selText.selectNodeContents(this);
                    window.getSelection().removeAllRanges(); // remove all selected content
                    window.getSelection().addRange(selText); // add range object to selection;
                }
                
                $(this).parent().addClass('activeWrapper');
                if ($(this).data('global') == "1") {
                    var varname = $(this).data('name');
                    //clearInterval(window.keylogger);
                    /*setTimeout(function(){ window.keylogger = setInterval(function() {
                            var valvar = $(node).html();
                            $('[data-name = "' + varname + '"]').not($(node)).html(valvar);
                          }, 10);
                      }, 30);*/
                    $(this).keyup(function(){
                        var valvar = $(this).html();
                        $('[data-name = "' + varname + '"]').not($(this)).html(valvar);
                    });
                }
                //let us now take care of the linked special vars if any
                //first get the variable name
                var name = $(this).attr('data-name');
                window.focused = name;
                if (name != 'undefined') {
                    //check for any special variable depending on it
                    var addTo = dxo[name]['addTo'];
                    len = addTo.length;
                    for (k = 0; k < len; k++) {
                        addTmp = decodeDXO(addTo[k]);
                        add = addTmp.split('|||');
                        addName = add[0];
                        addType = add[1];
                        //let us find the corresponding special vars nodes for a given name and type
                        var formula = dxoSpecial[addName]['formula'];
                        window.updateVars[addName] = {};
                        if (addType === 'Row'){
                            window.updateVars[addName]['nodeList'] = $(node).parents('tr:first').eq(0).find('[data-name="'+ addName + '"]');                        
                        } else if (addType === 'Column'){
                            window.updateVars[addName]['nodeList'] = $(node).parents('table:first').find('[data-name="'+ addName + '"]');
                        } else if (addType === 'listItem'){
                            window.updateVars[addName]['nodeList'] = $(node).parents('li:first').eq(0).find('[data-name="'+ addName + '"]');                        
                        } else {
                            window.updateVars[addName]['nodeList'] = $('[data-name="'+ addName + '"]');
                        }
                        window.updateVars[addName]['type'] = addType;
                        window.updateVars[addName]['dependsOn'] = dxoSpecial[addName]['dependsOn'];
                        window.updateVars[addName]['precision'] = dxoSpecial[addName]['precision'];
                        window.updateVars[addName]['formula'] = formula;
                    }
                }
            });
            $('[contenteditable]').not(".note-editable").click(function(){
                var name = $(this).attr('data-name');
                var def = decodeDXO(dxo[name]['label'])
                if ($(this).text().trim() == def) {
                    //select the text
                    var selText = document.createRange();
                    selText.selectNodeContents(this);
                    window.getSelection().removeAllRanges(); // remove all selected content
                    window.getSelection().addRange(selText); // add range object to selection;
                }
            });
            
            $('[contenteditable]').not(".note-editable").blur(function(){
                $('body').removeClass('no-balloons');
                $('#h5p-infoballoon').remove();
                $('#h5p-tooltip-wrapper').hide();
                $('#h5p-commentLine').remove();
                $('.h5p-help').remove();
                $(this).parent().removeClass('activeWrapper');
                var name = $(this).attr('data-name');
                if ($(this).text().trim() == '') {
                    //recover the label because the variable can not be left empty
                    if (dxo[name]['label'].charAt(0) == '@') {
                        var insertval = dxo[name]['label'].substring(1);
                    } else {
                        var insertval = dxo[name]['label'];
                    }
                    $(this).html(decodeDXO(insertval));
                }
                updateSpecialVars();
                window.updateVars = {};
                window.focused = '';
                //check if it is a variable that has to be confirmed and add it
                //to the window.confirmation array if it is not there
                if (dxo[name]['confirm']){
                    var add = window.confirmation.indexOf(name);
                    if (add < 0){
                        window.confirmation.push(name);
                    }
                } 
                if ($(this).data('global') == "1") {
                    var varname = $(this).data('name');
                    var valvar = $(this).html();
                    $('[data-name = "' + varname + '"]').not($(this)).html(valvar);
                }
            });
            $('*[data-list]').focus(function(){
                $('body').addClass('no-balloons');
                drawHelp(this);
            });
            $('span.spanWrapper, button.btn-docxpresso').mouseover(function(){
                //$('body').addClass('no-balloons');
                //drawHelp(this);
            });
            function drawHelp(obj){
                /*$('#h5p-infoballoon').remove();
                $('#h5p-commentLine').remove();
                $('#h5p-tooltip-wrapper').hide();
                $('.h5p-help').remove();
                h5pChild = $(obj).find('.h5p_varspan:first');
                var x = $(obj).offset().left;
                if (h5pChild.length > 0) {
                    var y = h5pChild.offset().top;
                } else {
                    var y = $(obj).offset().top;
                }
                tagover = $(obj).prop("tagName");
                if (tagover.toLowerCase() == 'span') {
                    var tagname = $(obj).data('name');
                } else if (tagover.toLowerCase() == 'button') {
                    var tagname = $(obj).parents('span:first').children('select').data('list');
                } else {
                    var tagname = $(obj).data('list');
                }
                if (typeof dxo[tagname] !== 'undefined') {
                tip = decodeDXO(dxo[tagname]['tip']);
                    if (typeof tip !== 'undefined' && tip.length > 1){
                        $('#h5p-tooltip').text(tip);
                        $('#h5p-tooltip-wrapper').css('left', x).css('top', y - 24).show();
                    }
                }
                if (typeof dxo[tagname] != 'undefined'){
                    var helper = '<div class="h5p-help"><div class="h5p-help-header"><i class="fa fa-question-circle"> </i> ';
                    helper += decodeDXO(dxo[tagname]['label']);
                    helper += '</div><div class="h5p-help-body">';
                    helper += decodeDXO(dxo[tagname]['comment']);
                    helper += '</div></div>';
                    page = $(obj).parents('.h5p_page:first');
                    var z = page.offset().top;
                    if ($('<div>' + decodeDXO(dxo[tagname]['comment']) + '</div>').text().trim() != ''){
                        $('body').addClass('no-balloons');
                        $(helper).prependTo(page).css('top', y - z - 3).css('z-index', '900').show();
                        var commentLine = '<div id="h5p-commentLine"> </div>';
                        var linetop = y -2;
                        var linewidth = $('.h5p-help').offset().left - x + 1;
                        $(commentLine).prependTo($('body')).css('top', linetop).css('left', x).css('width', linewidth);
                    } else {
                        $('body').addClass('no-balloons');
                    }
                }*/
            }
            $('*[data-list]').mouseover(function(){
                /*h5pChild = $(this).find('.h5p_varspan:first');
                var x = $(this).offset().left;
                if (h5pChild.length > 0) {
                    var y = h5pChild.offset().top;
                } else {
                    var y = $(this).offset().top;
                }
                tagover = $(this).prop("tagName");
                if (tagover.toLowerCase() == 'span') {
                    var tagname = $(this).data('name');
                } else if (tagover.toLowerCase() == 'button') {
                    var tagname = $(this).parents('span:first').children('select').data('list');
                } else {
                    var tagname = $(this).data('list');
                }
                if (typeof dxo[tagname] !== 'undefined') {
                    tip = decodeDXO(dxo[tagname]['tip']);
                    if (typeof tip !== 'undefined' && tip.length > 1){
                        $('#h5p-tooltip').text(tip);
                        $('#h5p-tooltip-wrapper').css('left', x).css('top', y - 24).show();
                    }
                }*/
            });
            $('*[data-list]').mouseleave(function(){
                /*$('#h5p-infoballoon').remove();
                $('#h5p-tooltip-wrapper').hide();*/
            });
            $('*[data-list]').blur(function(){
                /*$('body').removeClass('no-balloons');
                $('#h5p-infoballoon').remove();
                $('#h5p-tooltip-wrapper').hide();
                $('#h5p-commentLine').remove();
                $('.h5p-help').remove();*/
            });
            $('span.spanWrapper, button.btn-docxpresso').mouseleave(function(){
                /*$('body').removeClass('no-balloons');
                $('#h5p-infoballoon').remove();
                $('#h5p-tooltip-wrapper').hide();
                $('#h5p-commentLine').remove();
                $('.h5p-help').remove();*/
            });
            
            $('span.spanWrapper, *[data-list], button.btn-docxpresso').keypress(function(){
                $('body').removeClass('no-balloons');
                $('#h5p-infoballoon').remove();
                $('#h5p-tooltip-wrapper').hide();
                $('#h5p-commentLine').remove();
                $('.h5p-help').remove();
            });
            $('span.spanWrapper, *[data-list]').click(function(){
                /*$('#h5p-tooltip-wrapper').hide();
                if ($(this).data('type') == 'textarea') {
                    currentTextArea = $(this);
                    varspan = $(this).children('.h5p_varspan');
                    $('#textareaVar').html(varspan.attr('data-name'));
                    $(".summernoteTextarea").code(varspan.html());
                    $('#textareaModal').modal('show');
                } else {
                    $(this).find('span[contenteditable]').focus();
                }*/
            });
            //prevent carriage returns in variables that are not multiline text
            $('span.spanWrapper').on('keydown', function(e){
                if (e.which===13 && $(this).data('type') != 'multilineText') {
                    e.preventDefault();
                } else if (e.which===13 && $(this).data('type') == 'multilineText') {
                    e.preventDefault(); 
                    if (window.getSelection) {
                        var selection = window.getSelection();
                        var range = selection.getRangeAt(0);
                        var lineBreak = document.createElement("br");
                        range.insertNode(lineBreak);
                        range.collapse(false);
                        selection.removeAllRanges();
                        selection.addRange(range);
                        return false;
                    }
                }
            });
            //images
            $('img[data-image]').mouseover(function(){
                /*$('body').removeClass('no-balloons');
                $('#h5p-infoballoon').remove();
                $('#h5p-commentLine').remove();
                $('#h5p-tooltip-wrapper').hide();
                $('.h5p-help').remove();
                var x = $(this).offset().left;
                var y = $(this).offset().top;
                tip = decodeDXO(dxo[$(this).data('image')]['tip']);
                $('#h5p-tooltip').text(tip);
                $('#h5p-tooltip-wrapper').css('left', x).css('top', y - 24).show();
                source = decodeDXO(dxo[$(this).data('image')]['source']); 
                helper = '<div class="h5p-help"><div class="h5p-help-header"><i class="fa fa-question-circle"> </i> ';
                helper += decodeDXO(dxo[$(this).data('image')]['label']);
                helper += '</div><div class="h5p-help-body">';
                helper += decodeDXO(dxo[$(this).data('image')]['comment']);
                helper += '</div></div>';
                page = $(this).parents('.h5p_page:first');
                var z = page.offset().top;
                if ($('<div>' + decodeDXO(dxo[$(this).data('image')]['comment']) + '</div>').text().trim() != ''){
                    $('body').addClass('no-balloons');
                    $(helper).prependTo(page).css('top', y - z - 3).css('z-index', '900').show();
                    var commentLine = '<div id="h5p-commentLine"> </div>';
                    var linetop = y -2;
                    var linewidth = $('.h5p-help').offset().left - x + 1;
                    $(commentLine).prependTo($('body')).css('top', linetop).css('left', x).css('width', linewidth);
                } */
            });
            $('img[data-image]').mouseleave(function(){
                $('body').removeClass('no-balloons');
                $('#h5p-infoballoon').remove();
                $('#h5p-tooltip-wrapper').hide();
                $('#h5p-commentLine').remove();
                $('.h5p-help').remove();
            });
            $('img[data-image]').click(function(){
                $('body').removeClass('no-balloons');
                $('#h5p-infoballoon').remove();
                $('#h5p-tooltip-wrapper').hide();
                $('#h5p-commentLine').remove();
                $('.h5p-help').remove();
                //get variable name
                imageName = $(this).data('image');

                source = dxo[$(this).data('image')]['source'];
                var global = dxo[$(this).data('image')]['global'];
                var editable = dxo[$(this).data('image')]['editable'];
                var myinput = $(this).parent().children('input[type="file"][data-image]');
                if (source == 'signature' && editable) {
                    canvas = document.querySelector("#signatureModal canvas");
                    //Retina screens
                    /*var ratio =  Math.max(window.devicePixelRatio || 1, 1);
                    canvas.width = canvas.width * ratio;
                    canvas.height = canvas.height * ratio;
                    canvas.getContext("2d").scale(ratio, ratio);*/
                    var signaturePad = new SignaturePad(canvas);
                    $("#signatureModal").modal('show');
                    // reference
                    var img = this;
                    $('#saveSignature').off('click');
                    $('#saveSignature').click(function(){
                        //take care of  resizing
                        var format = dxo[imageName]['format'];
                        //default scaling signature factor
                        var scaling = 1;
                        //we use a scaling factor to get more pixels when printed
                        var canvas_scaling = 2;
                        //if we are using 'redimension' we can not scale the canvas if
                        //we want to preserve the design
                        if (format == 'redimension') {
                            canvas_scaling = 1;
                        }
                        var w = img.width * canvas_scaling;
                        var h = img.height * canvas_scaling;
                        var signatureWidth = 300;
                        var signatureHeight = 150;
                        
                        //set the correct CSS styles depending on the format
                        if (format == 'preserveWidth') {
                            $('img[data-image="' + imageName + '"]').css('height', 'auto');
                            $('img[data-image="' + imageName + '"]').parent().css('height', 'auto');
                            if ( w < (signatureWidth * scaling)) {
                                //redefine scaling variable
                                scaling = w/signatureWidth ;
                            }
                        } else if (format == 'preserveHeight') {
                            $('img[data-image="' + imageName + '"]').css('width', 'auto');
                            $('img[data-image="' + imageName + '"]').parent().css('width', 'auto');
                            if (  h < (signatureHeight * scaling)) {
                                //redefine scaling variable
                                scaling = h/signatureHeight ;
                            }
                        } else if (format == 'redimension') {
                            $('img[data-image="' + imageName + '"]').css('width', 'auto');
                            $('img[data-image="' + imageName + '"]').css('height', 'auto');
                            $('img[data-image="' + imageName + '"]').parents('div:first').css('width', 'auto');
                            $('img[data-image="' + imageName + '"]').parents('div:first').css('height', 'auto');
                            
                            if ( w < (signatureWidth * scaling)) {
                                //redefine scaling variable
                                preScaleX = w/signatureWidth ;
                            } else {
                                preScaleX = scaling;
                            }
                            if (  h < (signatureHeight * scaling)) {
                                //redefine scaling variable
                                preScaleY = h/signatureHeight ;
                            } else {
                                preScaleY = scaling;
                            }
                            var preScale = Math.min(preScaleX, preScaleY);
                            scaling = Math.min(preScale, scaling);
                        }
                        
                        //signature = signaturePad.toDataURL();
                        var canvas2 = document.createElement("canvas");
                        
                        canvas2.width = w;
                        canvas2.height = h;
                        var ctx = canvas2.getContext("2d");
                        //ctx.fillStyle = "yellow";
                        //ctx.fillRect(0, 0, w, h);
                        var wdef = (signatureWidth * scaling);
                        var hdef = (signatureHeight * scaling);
                        var offX = (w - wdef)/2;
                        var offY = (h - hdef)/2;
                        var imgsign = new Image();   // Create new img element
                        imgsign.src = signaturePad.toDataURL();
                        var signature;
                        imgsign.onload = function() {
                            ctx.drawImage(imgsign, 0, 0, signatureWidth, signatureHeight, offX, offY, wdef, hdef);
                            signature = canvas2.toDataURL();
                            if (global) {
                                $('img[data-image="' + imageName + '"]').attr('src', signature);
                            } else {
                                $(img).attr('src', signature);
                            }
                        };
                        $("#signatureModal").modal('hide');
                        
                    });
                    $('#loadSignature').off('click');
                    $('#loadSignature').click(function(){
                        
                        $("#signatureModal").modal('hide');
                        $('#saveSignature').off('click');
                        myinput.click();
                    });
                    
                } else if (editable) {
                    //activate the associated input file type field
                    var el = $(this).parent().children("input");
                    if (el) {
                      el.click();
                    }
                }
            });
            //special variables
            $('span.spanWrapperSpecial').mouseover(function(){
                $('body').removeClass('no-balloons');
                $('#h5p-infoballoon').remove();
                $('#h5p-commentLine').remove();
                $('#h5p-tooltip-wrapper').hide();
                $('.h5p-help').remove();
                var x = $(this).offset().left;
                var y = $(this).offset().top;
                tip = decodeDXO(dxoSpecial[$(this).data('name')]['tip']);
                $('#h5p-tooltip').text(tip);
                $('#h5p-tooltip-wrapper').css('left', x).css('top', y - 24).show();
                helper = '<div class="h5p-help"><div class="h5p-help-header"><i class="fa fa-question-circle"> </i> ';
                helper += decodeDXO($(this).data('label'));
                helper += '</div><div class="h5p-help-body">';
                helper += decodeDXO(dxoSpecial[$(this).data('name')]['comment']);
                helper += '</div></div>'
                page = $(this).parents('.h5p_page:first');
                var z = page.offset().top;
                if ($('<div>' + decodeDXO(dxoSpecial[$(this).data('name')]['comment']) + '</div>').text().trim() != ''){
                    $('body').addClass('no-balloons');
                    $(helper).prependTo(page).css('top', y - z - 3).css('z-index', '900').show();
                    var commentLine = '<div id="h5p-commentLine"> </div>';
                    var linetop = y -2;
                    var linewidth = $('.h5p-help').offset().left - x + 1;
                    $(commentLine).prependTo($('body')).css('top', linetop).css('left', x).css('width', linewidth);
                }
            });
            $('span.spanWrapperSpecial').mouseleave(function(){
                $('body').removeClass('no-balloons');
                $('#h5p-infoballoon').remove();
                $('#h5p-tooltip-wrapper').hide();
                $('#h5p-commentLine').remove();
                $('.h5p-help').remove();
            });
            $('span.spanWrapperSpecial').click(function(){
                $('body').removeClass('no-balloons');
                $('#h5p-infoballoon').remove();
                $('#h5p-tooltip-wrapper').hide();
                $('#h5p-commentLine').remove();
                $('.h5p-help').remove();
            });
            
            //RICH TEXT EDITOR
            $('*[data-proc]').click(function(){
                //get the variable selected
                var selection;
                if(window.getSelection){
                    selection = window.getSelection();
                }else if(typeof document.selection!="undefined"){
                    selection = document.selection;
                }
                var parent = $(selection.anchorNode).closest("span[data-name]");
                if (parent != 'undefined') {
                    var varname = parent.data('name');
                } else {
                    var varname = false;
                }
                
                if (varname && dxo[varname]['richText']){
                    var rich = true;
                } else if (varname){
                    var rich = false;
                    toastr.error('Esta variable no acepta texto enriquecido.', 'Aviso');
                } else {
                    rich = false
                }
                if (rich) {
                    cmd = $(this).data('proc');
                    if (typeof $(this).data('value') !== 'undefined') {
                        value = $(this).data('value');
                    } else {
                        value = null;
                    }   
                    document.execCommand(cmd, false, value);
                }
            });
            //ATTACHMENTS
            //we have to delegate the event when data is loaded
            $('body').on('click', '.loadFile', function(){
                $('input[name="' + $(this).attr('data-file') + '"]').click();
            });
            $('input.fileAttached').change(function(){
                var name = $(this).attr('name');
                var maxSize = $(this).attr('data-max-size');
                if (typeof $(this)[0].files[0] == 'undefined' ){
                    $('small[data-file="' + name + '"]').html('');
                    window.globalValidations.attachs[name] = false;
                    window.attachments[name]['file'] = '';
                    window.attachments[name]['size'] = 0;
                    $('button[data-removefile="' + name + '"]').css('display', 'none');
                } else if (maxSize > 0 && (maxSize * 1024) < $(this)[0].files[0].size){
                    toastr.error('El tamaño de este fichero es mayor del permitido. Por favor, escoja un fichero de menor tamaño.', 'Aviso');
                    $(this).val('');
                    $('small[data-file="' + name + '"]').html('');
                    window.globalValidations.attachs[name] = false;
                    window.attachments[name]['file'] = '';
                    window.attachments[name]['size'] = 0;
                    $('button[data-removefile="' + name + '"]').css('display', 'none');
                } else {
                    $('small[data-file="' + name + '"]').html($(this)[0].files[0].name);
                    checkAttachments();
                    window.attachments[name]['file'] = $(this)[0].files[0].name;
                    window.attachments[name]['size'] = Math.ceil($(this)[0].files[0].size / 1024);
                    $('button[data-removefile="' + name + '"]').css('display', 'inline');
                }
                
            });
            
            $('.removeFile').click(function(){
                var name = $(this).attr('data-removefile');
                var control = $('input[name="' + name + '"]');
                control.replaceWith( control.val('').clone( true ) );
                $('small[data-file="' + name + '"]').html('');
                window.globalValidations.attachs[name] = false;
                window.attachments[name]['file'] = '';
                window.attachments[name]['size'] = 0;
                $('button[data-removefile="' + name + '"]').css('display', 'none');
                //save this id in the deleted attachments
                var deleted = $('#deletedAttachments').val();
                if (deleted == ''){
                    deleted = name;
                } else {
                    deleted += ';' + name;
                }
                $('#deletedAttachments').val(deleted);
            });
            
            $('#saveContinue').click(function(){
                $("#attachmentModal").modal('hide'); 
                //if there is a custom submit method run it first
                var submit = true;
                if (typeof customOnSubmit === "function") { 
                    submit = customOnSubmit();
                } 
                if (submit){
                    //let us check at this stage that the size of the POST
                    //variables is not too big
                    if (skipOutputModal == true){
                        $('#saveAndDownload').click(); 
                    } else {
                        $("#saveModal").modal('show'); 
                    }
                }
            });
            //FORM
            $('.i-checks').iCheck({
                    checkboxClass: 'icheckbox_square-green',
                    radioClass: 'iradio_square-green'
                });
            $('#cancel').click(function(){
                $("#cancelModal").modal('show');
            });
            $('#cancelGo').click(function(){
                window.warning = false;
                var source = $(this).attr('data-source');
                var response = $('#responseURL').val();
                if (source == 'backoffice' && (response == '' || typeof response == 'undefined')){
                    window.location.href = 'https://consents.globalcareondemand.com/documents/show/162';
                } else if (history.length === 0 && typeof response != 'undefined') {
                    window.location.href = response;
                } else {
                        window.history.back();     
                }
            });
            
            
            $('#process').click(function(){
                window.location.href = 'https://consents.globalcareondemand.com/documents/process/162';
            });
            $('#attachPane').click(function(){
                openAttachmentPad();
            });
            
           
            
            

            
            function parseBlocks(node) {
                var blocks = {};
                var step = function(node, blocks) {
                    var counter = 0;
                    var currentBlock = '';
                    do {
                        if (node.nodeType == 1){
                            if (node.getAttribute('data-type')){
                                if (node.getAttribute('data-h5p') != currentBlock) {
                                    currentBlock = node.getAttribute('data-h5p');
                                    counter= 0;
                                }       
                                blocks[node.getAttribute('data-h5p') + '::' + counter] = {};
                                if(node.hasChildNodes()){
                                    step(node.firstChild, blocks[node.getAttribute('data-h5p') + '::' + counter]);
                                }
                                counter++;
                            } else if (node.hasChildNodes()){
                                step(node.firstChild, blocks);
                            }
                        }
                    }
                    while (node = node.nextSibling);
                }
                step(node, blocks);
                return blocks;
            }
            
            function parseVars() {
                var vars = {};
                for (var j = 0; j < numData; j++) {
                    vars = parseSingleVar(j, vars);
                }
                return vars;
            }
            
            function parseSpecialVars() {
                var svars = {};
                for (j = 0; j < numSpecial; j++) {
                    svars[docxpressoData.special[j].name] = [];
                    span = $('span.h5p_varspecial[data-name="' + docxpressoData.special[j].name + '"]');
                    span.each(function(){
                        svars[docxpressoData.special[j].name].push(encodeDXO($(this).html()));
                    });
                }
                return svars;
            }
            
            function checkAttachments() {
                counter = 0;
                if (typeof docxpressoData.attachments !== 'undefined' 
                    && typeof docxpressoData.attachments.files !== 'undefined' ) {
                    numAttachments = docxpressoData.attachments.files.length;
                    for (j = 0; j < numAttachments; j++) {
                        var name = docxpressoData.attachments['files'][j]['name'];
                        if ($.inArray(docxpressoData.attachments['files'][j]['name'], window.inactiveAttachments) == -1){
                            counter += verifyAttachment(name, j);
                        }
                    }
                }
                return counter;
            }
            
            function verifyAttachment(name, j){
                count = 0;
                if (typeof window.attachments[name] == 'undefined' ){
                    window.attachments[name] = {};
                }
                
                if(docxpressoData.attachments['files'][j]['dependsOn'] == '' 
                   && $.inArray(docxpressoData.attachments['files'][j]['name'], window.inactiveAttachments) == -1){
                    count++;
                    window.attachments[name]['active'] = true;
                    $('div.attachedFile[data-file="' + name + '"]').show();
                    $('div.attachedFile[data-file="' + name + '"]').next('div.hr-line-dashed').show();
                    $('input[name="' + name + '"]').prop('disabled', false);
                } else if (docxpressoData.attachments['files'][j]['dependsOn'] != '' ) {
                    //get the variable value
                    dependsOn = docxpressoData.attachments['files'][j]['dependsOn'];
                    value = docxpressoData.attachments['files'][j]['value'];
                    var tmp = value.split(';');
                    var vars= [];
       
                    if (dxo[dependsOn].type == 'options' && (dxo[dependsOn].choice == 'radio' || dxo[dependsOn].choice == 'checkbox')) {
                        choice = $('input[data-list="' + dependsOn + '"]');
                        choice.each(function(){
                            if ($(this).is(':checked')) {
                                vars.push($(this).val());
                            }
                        });
                    } else {
                        span = $('span.h5p_varspan[data-name="' + dependsOn + '"]');
                        span.each(function(){
                            vars.push(encodeDXO($(this).html()));
                        });
                    }
                    varLen = vars.length;
                    var found = false;
                    for (var n = 0; n < varLen; n++) {
                        if (tmp.indexOf(vars[n].trim()) > -1 || tmp.indexOf(encodeURI(vars[n].trim())) > -1){
                            found = true;
                        }
                    }
                    if (found){
                        count++;
                        window.attachments[name]['active'] = true;
                        $('div.attachedFile[data-file="' + name + '"]').show();
                        $('div.attachedFile[data-file="' + name + '"]').next('div.hr-line-dashed').show();
                        $('input[name="' + name + '"]').prop('disabled', false);
                    } else {
                        window.attachments[name]['active'] = false;
                        //hide and disable this attachment
                        $('div.attachedFile[data-file="' + name + '"]').hide();
                        $('div.attachedFile[data-file="' + name + '"]').next('div.hr-line-dashed').hide();
                        $('input[name="' + name + '"]').prop('disabled', true);
                    }
                }
                //check if it is an optional attachment
                window.attachments[name]['optional'] = docxpressoData.attachments['files'][j]['optional'];
                return count;
            }
            
            function openAttachmentPad () {
                attachmentsNumber = checkAttachments();
                if (attachmentsNumber > 0){
                    $('#saveContinue').hide();
                    $("#attachmentModal").modal('show');
                } else {
                    toastr.error('No hay archivos adjuntos asociados a este documento.', 'Aviso');
                }   
            }
            
            $('#download').click(function(){
                $('#confirmSubmit').attr("data-type", "standard");
                if (typeof confirmOnSubmit === 'function') {
                    confirmOnSubmit();
                } else {   
                    launchSubmit();
                }
            });
            
            $('#continueLater').click(function(){
                $('#confirmSubmit').attr("data-type", "continueLater");
                if (typeof confirmOnSubmit === 'function') {
                    confirmOnSubmit();
                } else {   
                    submitContinueLater();
                }
            });
            
            $('#emailLinkValue').keyup(function(){
                if ($(this).val() != '') {
                    $('#emailLink').iCheck('check');
                }
            });

            $('#accept').click(function(){
                $('#validate').val(1);
                $('.forwardButton').parent().hide();
                openComments(1);
            });
            
            $('#reject').click(function(){
                $('#validate').val(0);
                $('.forwardButton').parent().show();
                openComments(0);
            });
            
            $('.forwardButton').parent().click(function(){
                $(this).find('input').prop('checked', true);
            });
            
            function openComments(validated){
                if (validated == 1){
                    $('#acceptedDoc').show();
                    $('#rejectedDoc').hide();
                } else {
                    $('#rejectedDoc').show();
                    $('#acceptedDoc').hide();
                }
                $('#messageModal').modal('show');   
            }
            
            $('#saveValidation').click(function(){
                var comments = $('.summernoteValidation').code();
                var validate = $('#validate').val();
                comments = comments.replace(/<\/?[^>]+>/gi, '').trim();
                var forwardSteps = $('.forwardButton').length;
                var forwardValue = $('input[name="forwardRejection"]:checked').val();
                if (validate == 0 && comments == '') {
                    toastr.error('Por favor, incluya las razones del rechazo.', 'Aviso');
                    return false;
                } else if (validate == 0 && forwardSteps > 0 && typeof forwardValue == 'undefined') {
                    toastr.error('Porfavor, debe escoger un paso del workflow para notificar al usuario correspondiente y solicitar las acciones pertinentes.', 'Aviso');
                    return false;
                }else {
                    $('#messageModal').modal('hide'); 
                    saveAndDownload();
                }
            });

            function saveAndDownload() {
                                    $( "#docxpresso_form" ).submit();
                            }
            
            $( "#docxpresso_form" ).submit(function( event ) {
                var comments = encodeURIComponent($('.summernoteValidation').code());
                $('#validationComments').val(comments);
                var validate = $('#validate').val();
                var forwardSteps = $('.forwardButton').length;
                var forwardValue = $('input[name="forwardRejection"]:checked').val();
                if (validate == 0 && forwardSteps > 0 && typeof forwardValue != 'undefined'){
                    $('#forwardRejection').val(forwardValue);
                }
                warning = false;
                return;
            });
            
            
            //this function removes Word and other formatting in summernote WYSIWYG
            function CleanPastedHTML(input) {
                //Remove line breaks and strip Mso classes inserted by Word
                //also detect if it has benn pasted from Word
                var stringStripper = /(\n|\r| class=(")?Mso[a-zA-Z]+(")?)/g;
                var output = input.replace(stringStripper, ' ');
                //Strip comments
                var commentSripper = new RegExp('<!--(.*?)-->','g');
                var output = output.replace(commentSripper, '');
                //Remove tags that may contain styles or are nonprintable
                var tagStripper = new RegExp('<(/)*(meta|link|span|\\?xml:|st1:|o:|font)(.*?)>','gi');
                output = output.replace(tagStripper, '');
                //Remove irrelevant content within the following tags (tags included)
                var badTags = ['style', 'script','applet','embed','noframes','noscript'];
                for (var i=0; i< badTags.length; i++) {
                    tagStripper = new RegExp('<'+badTags[i]+'.*?'+badTags[i]+'(.*?)>', 'gi');
                    output = output.replace(tagStripper, '');
                }
                //Remove style attributes
                var badAttributes = ['style', 'start'];
                for (var i=0; i< badAttributes.length; i++) {
                    var attributeStripper = new RegExp(' ' + badAttributes[i] + '="(.*?)"','gi');
                    output = output.replace(attributeStripper, '');
                }
                return output;
            }
            
            $( window ).resize(function() {
                var iframeHeight = $(window).height() - 97;
                if(window.top != window.self){
                    //do not resize
                } else {
                    $('#external-frame').css('height', iframeHeight + 'px');
                }
                $('#history-frame').css('height', iframeHeight + 40 + 'px');
                $('#historyList').css('min-height', iframeHeight + 42 + 'px');
                backdropSize();
            });
            $('.modal').not('#externalModal, #importDataModal').on('shown.bs.modal', function (e) {
                backdropSize();
                //relocation of modals within iframes
                if(window.top != window.self){
                    if ('parentIFrame' in window) {
                        parentIFrame.getPageInfo(relocate);
                        function relocate(pageInfo){
                            var modal_top_px_origin = pageInfo.scrollTop - pageInfo.offsetTop + 20;
                            if(modal_top_px_origin <= 0){
                                modal_top_px_origin = 10;
                            }
                            $('.modal').css("top",modal_top_px_origin+"px");
                        }
                    }
                }
            });
            
            function backdropSize(){
                var w = document.body.clientWidth;
                var h = $(window).height();
                var modalHeight = $('.modal-dialog:visible').innerHeight();
                var nw = w - 17;
                if (modalHeight > h && w > 500 && !window.mobileDevice){
                    $('.modal-backdrop').css('width', nw + 'px');
                }
                //we force scroll bars
                //$('.modal').not('#externalModal, #workflowModal').css('overflow-y', 'scroll');
            }
                        
            function cloneBlocks(blocks, node){
                if (typeof node === 'undefined') {
                    node = $('body');
                }
                if (typeof blocks !== 'undefined') {
                    var childBlocks = [];
                    //run over the childs
                    for (block in blocks) {
                        if (blocks.hasOwnProperty(block)){
                            var temp = block.split('::');
                            var blockName = temp[0];
                            if (typeof childBlocks[blockName] === 'undefined') {
                                childBlocks[blockName] = 1;
                            } else {
                                childBlocks[blockName]++;
                            }
                        }
                    }
                    for (child in childBlocks) {
                        toClone = node.find('*[data-h5p ="{{' + child + '}}"] , *[data-h5p="' + child + '"]');
                        //remove precloned objects
                        toClone.each(function(index){
                            if (index > 0) {
                                //console.log('nodo a eliminar');
                                //console.log($(this));
                                $(this).remove();
                                //console.log(blocks);
                            }
                        });
                        //start the cloning
                        for (var n = 0; n < childBlocks[child]-1; n++) {
                            toClone.eq(0).clone(true, true).insertBefore(toClone.eq(0));
                            //reset all data-family values with a new random value
                            var unid = new Date().getTime() + "_" + getRandomArbitrary(9999999, 99);
                            toClone.find('input[type="radio"], input[type="checkbox"]').each(function(){
                                var family = $(this).attr('data-family');
                                $(this).attr('data-family', family + unid);
                            });
                        }
                            
                    }

                    //run over the childs
                    for (block in blocks) {
                        if (blocks.hasOwnProperty(block)){
                            var subBlocks = blocks[block];
                            var subBlockCount = Object.keys(subBlocks).length;
                            if (subBlockCount > 0) {
                                var nTemp = block.split('::');
                                var bName = nTemp[0];
                                var order = nTemp[1]
                                var newNode = node.find('*[data-h5p ="{{' + bName + '}}"] , *[data-h5p="' + bName + '"]').eq(order);
                                cloneBlocks(subBlocks, newNode);
                            }
                        }
                    } 
                }
            }
            
            function resetVariables(node){
                //first get all stantard text vars an reset to default values
                var textspans = node.find('span.h5p_varspan[data-name]');
                textspans.each(function(){
                    var name = $(this).attr('data-name');
                    if (typeof dxo[name] != 'undefined' && !dxo[name]['global']){
                        if (dxo[name]['choice'] != 'checkbox' && dxo[name]['choice'] != 'radio'){
                            $(this).text(decodeURIComponent(dxo[name]['label']));
                        }
                    }
                });
                var choices = node.find('select[data-list]');
                choices.each(function(){
                    var multiple = $(this).attr('multiple');
                    if (typeof multiple == 'undefined'){
                        var name = $(this).attr('data-name');
                        var defval = $(this).attr('data-default');
                        if (typeof defval != 'undefined'){
                            $(this).val(defval);
                        } else {
                            $(this).val(''); 
                        }
                    } 
                });
                
                var checks = node.find('input[data-list]');
                checks.each(function(){
                    $(this).prop('checked', false);
                });
                
            }
            
            function getRandomArbitrary(min, max) {
                return Math.floor(Math.random() * (max - min) + min);
            }
            
            window.replaceVars = function(data, special, form) {
                if (form === undefined){
                    form = true
                }
                for (name in data) {
                    replaceSingleVar(name, data, special, '', form);        
                }
                modifyGeneralBlockVisibility();
                if (form){
                    updateSpecialVars();
                }
                decorateMultiSelects();
                window.localDataLoaded = true;
            }
            
            window.replaceSingleVar = function(name, data, special, preselector, form){
                if (special && data.hasOwnProperty(name)){
                    var selector = $('span.h5p_varspecial[data-name="' + name + '"]');
                    var len = data[name].length;
                    selector.each(function(index){
                        $(this).html(decodeDXO(data[name][index%len]));
                    });
                } else if (data.hasOwnProperty(name) && typeof dxo[name] !== 'undefined'){
                    var len = data[name].length;
                    var global = dxo[name]['global'];
                    if (global || preselector == ''){
                        var preselection = '';
                    } else {
                        var preselection = preselector + ' ';
                    }  
                    //let us protect the case where only var values are
                    //sent assuming they are standard text variables
                    //by default
                    if (typeof dxo[name] !== 'undefined' 
                        && typeof dxo[name]['type'] !== 'undefined') {   
                        var type = dxo[name]['type'];
                        if (type == 'options' 
                            && typeof dxo[name]['choice'] !== 'undefined' ) {
                            var choice = dxo[name]['choice'];
                        } else {
                            var choice = 'dropdown';
                        }
                    } else {
                        var type = 'unknown';
                    }
                    if (type == 'image') {
                       var selector = $(preselection + 'img[data-image="' + name + '"]');
                        for (var k = 0; k < len; k++) {
                            if (typeof data[name][k] == 'string'){
                                var imgsrc = decodeURIComponent(data[name][k]);
                            } else {
                                var imgsrc = decodeURIComponent(data[name][k]['src']);
                            }
                            selector.eq(k).attr('src', imgsrc);
                            //console.log(selector.eq(k).attr('src'));
                            var format = dxo[name]['format'];
                            if (format == 'preserveWidth') {
                                selector.eq(k).css('height', 'auto');
                                selector.eq(k).parent().css('height', 'auto');
                            } else if (format == 'preserveHeight') {
                                selector.eq(k).css('width', 'auto');
                                selector.eq(k).parent().css('width', 'auto');
                            } else if (format == 'redimension') {
                                selector.eq(k).css('width', 'auto');
                                selector.eq(k).css('height', 'auto');
                                selector.eq(k).parent().css('width', 'auto');
                                selector.eq(k).parent().css('height', 'auto');
                            }
                        }
                    } else if (type == 'file' || type == 'docid' || type == 'ip') {
                        //file and doc ID variables are not considered
                    } else if (type == 'list' || (type == 'options' && choice == 'dropdown') || type == 'rpc') {
                        var selector = $(preselection + 'select[data-list="' + name + '"]');
                        if (global && len > 0){
                            if (decodeDXO(data[name][0]) != '') {
                                    //we have to take special care whenever we have included additional values with
                                    //an #Other option
                                    //check that the option exist
                                var opt = selector.children('option[value="' + decodeDXO(data[name][0]).replace(/"/g, "&quot;") + '"]');
                                if (opt.length == 0) {
                                    //the option does not exist...let us create it
                                    $('<option value="' + decodeDXO(data[name][0]).replace(/"/g, "&quot;") + '" selected>' + decodeDXO(data[name][0]) + '</option>').appendTo(selector.eq(k));
                                }
                                selector.val(decodeDXO(data[name][0]));
                            }
                        } else {
                            for (var k = 0; k < len; k++) {
                                if (decodeDXO(data[name][k]) != '') {
                                    //we have to take special care whenever we have included additional values with
                                    //an #Other option
                                    //check that the option exist
                                    var opt = selector.eq(k).children('option[value="' + decodeDXO(data[name][k]).replace(/"/g, "&quot;") + '"]');
                                    if (opt.length == 0) {
                                        //the option does not exist...let us create it
                                        $('<option value="' + decodeDXO(data[name][k]).replace(/"/g, "&quot;") + '" selected>' + decodeDXO(data[name][k]) + '</option>').appendTo(selector.eq(k));
                                    }
                                    selector.eq(k).val(decodeDXO(data[name][k]));
                                }
                            }
                        }
                        //we also have to update the associated span
                        var selector = $(preselection + 'span.h5p_varspan[data-name="' + name + '"]');
                        if (global && len > 0){
                            selector.html(decodeDXO(data[name][0]));
                            //update block visibility
                            if (typeof window.dependencies[name] !== 'undefined'
                                || typeof window.partials[name] !== 'undefined') {
                                //modifyBlockVisibility(name, decodeDXO(data[name][0]), null, true);
                            }
                            if (typeof window.annexes[name] !== 'undefined') {
                                annexesVisibility(name, decodeDXO(data[name][0]));
                            }
                        } else {
                            for (var k = 0; k < len; k++) {
                                selector.eq(k).html(decodeDXO(data[name][k]));
                                //update block visibility
                                if (typeof window.dependencies[name] !== 'undefined'
                                    || typeof window.partials[name] !== 'undefined') {
                                    //modifyBlockVisibility(name, decodeDXO(data[name][k]), selector.eq(k), false);
                                }
                                if (typeof window.annexes[name] !== 'undefined') {
                                    annexesVisibility(name, decodeDXO(data[name][k]));
                                }
                            }
                        }
                    } else if(type == 'options' && choice == 'multipleSelect') {
                        var selector = $(preselection + 'select[data-list="' + name + '"]');
                        if (global && len > 0){
                            var tmp = data[name][0];
                            //we have to take care of the case where the data is given as a coma separated string
                            if (typeof tmp == 'string'){
                                tmp = tmp.split(',');
                            }
                            var ll = tmp.length;
                            for(var k = 0; k < ll; k++){
                                tmp[k] = decodeDXO(tmp[k]);
                            }
                            if(tmp.length == 0){
                                tmp[0] = decodeDXO(selector.attr('data-label'));
                            }
                            selector.val(tmp);
                            //modifyBlockVisibility(name, tmp, null, true);
                            //selector.multiselect('refresh');
                            //window.multiselects[name] = tmp;
                        } else {
                            for (var k = 0; k < len; k++) {
                                var tmp = data[name][k];
                                //we have to take care of the case where the data is given as a coma separated string
                                if (typeof tmp == 'string'){
                                    tmp = tmp.split(',');
                                }
                                var ll = tmp.length;
                                for(var j = 0; j < ll; j++){
                                    tmp[j] = decodeDXO(tmp[j]);
                                }
                                if(tmp.length == 0){
                                    tmp[0] = decodeDXO(selector.attr('data-label'));
                                }
                                selector.eq(k).val(tmp);
                                //check for the last appearance
                                //modifyBlockVisibility(name, tmp, selector.eq(k));
                                //selector.multiselect('refresh');
                                //window.multiselects[name] = tmp;
                            }
                        }
                        var checkedVals = [];
                        for (var k = 0; k < len; k++) {
                            if (decodeDXO(data[name][0][k]) != '') {
                                selector.eq(k).prop("checked", true);
                                checkedVals.push(decodeDXO(data[name][0][k]));
                            } else {
                                selector.eq(k).prop("checked", false);
                            }
                           
                        }
                        
                    } else if(type == 'options' && ((choice === 'checkbox' || choice === 'radio') && typeof data[name][0] === 'object') ) {
                        var merged = [].concat.apply([], data[name]);
                        //we only use the data[name][0] array of values
                        var selector = $(preselection + 'input[data-list="' + name + '"]');
                        //we have to redefine the length
                        len = merged.length;
                        var checkedVals = [];
                        for (var k = 0; k < len; k++) {
                            if (decodeDXO(merged[k]) != '') {
                                selector.eq(k).prop("checked", true);
                                checkedVals.push(decodeDXO(merged[k]));
                            } else {
                                selector.eq(k).prop("checked", false);
                            }
                           
                        }
                        if (typeof window.dependencies[name] !== 'undefined'
                            || typeof window.partials[name] !== 'undefined') {
                            //modifyBlockVisibility(name, checkedVals.join(';'), null);
                        }
                        if (typeof window.annexes[name] !== 'undefined') {
                            annexesVisibility(name, checkedVals.join(';'));
                        }

                    } else if(type == 'options' && choice != 'dropdown') {
                        var selector = $(preselection + 'input[data-list="' + name + '"]');
                        var checkedVals = [];
                        for (var k = 0; k < len; k++) {
                            if (decodeDXO(data[name][k]) != '') {
                                selector.eq(k).prop("checked", true);
                                checkedVals.push(decodeDXO(data[name][k]));
                            } else {
                                selector.eq(k).prop("checked", false);
                            }
                        }
                        if (typeof window.dependencies[name] !== 'undefined'
                            || typeof window.partials[name] !== 'undefined') {
                            //modifyBlockVisibility(name, checkedVals.join(';'), null);
                        }
                        if (typeof window.annexes[name] !== 'undefined') {
                            annexesVisibility(name, checkedVals.join(';'));
                        }
                    } else {
                        var selector = $(preselection + 'span.h5p_varspan[data-name="' + name + '"]');
                        if (global && len > 0){
                            selector.html(decodeDXO(data[name][0]));
                        } else {
                            for (var k = 0; k < len; k++) {
                                //if the value has been left empty load the label
                                if (data[name][k] != '') {
                                    selector.eq(k).html(decodeDXO(data[name][k]));
                                } else {
                                    selector.eq(k).html(decodeDXO(dxo[name]['label']));
                                }
                            }   
                        }
                    }
                }
                if(typeof selector != 'undefined' && typeof selector.eq(0) != 'undefined' && form){
                    scrollAsNeeded(selector.eq(0));
                }
            }
            
            function scrollAsNeeded(node){
                var topel = node.offset().top;
                var botel = node.offset().top + node.outerHeight();
                var bosc = $(window).scrollTop() + $(window).innerHeight();
                var tosc = $(window).scrollTop();

                if ((bosc > topel) && (tosc < botel)){
                    // do nothing
                } else {
                    //let us scroll to show the element on window
                    if (node.is(':visible')){
                        $.scrollTo(node, 500, {offset: -80});
                    } else {
                        //this may be a select
                        try {
                            $.scrollTo(node.parent().prev(), 500, {offset: -80});
                        } catch(e){
                            //do noting
                        }
                    }
                }
            }
            
            window.cloneFrameBlock = function(name, order, scroll){
                if (scroll === undefined){
                    scroll = true
                }
                toClone = $('*[data-h5p="' + name + '"]').eq(order);
                cloned = toClone.clone(true, true).insertAfter(toClone);
                if(scroll){
                    scrollAsNeeded(cloned);
                }
                //resetVariables(toClone);
                //TODO: checkBlockVisibility
                modifyGeneralBlockVisibility();
                //TODO: special vars
                updateSpecialVars();
            }
            
            window.removeFrameBlock = function(name, order){
                toRemove = $('*[data-h5p="' + name + '"]').eq(order);
                scrollAsNeeded(toRemove);
                toRemove.remove();
                //resetVariables(toClone);
                //TODO: checkBlockVisibility
                modifyGeneralBlockVisibility();
                //TODO: special vars
                updateSpecialVars();
            }
            
            window.FrameFull = function(data, form){
                if (form === undefined){
                    form = true
                }
                //clone the blocks
                //console.log(data);
                if (typeof data.blocks != 'undefined' ) {
                    //console.log(data.blocks);
                    cloneBlocks(data.blocks);
                }
                //replace variables
                if (typeof data.varValues != 'undefined' ) {
                    replaceVars(data.varValues, false, form);
                }
                //replace special variables
                if (typeof data.specialVarValues != 'undefined' ) {
                    replaceVars(data.specialVarValues, true, form);
                }
            }
            

            //load server data if any
            if (serverData) {
                //fake motion progress bar
                var bar = 38;
                progressBar = setInterval(function() {
                    if (bar > 98) {
                        clearInterval(progressBar);
                    } else {
                        bar++;
                        $('#loadVar').css('width', bar + '%');
                    }
                }, progressTimer/80);
                //first check if we need to clone groups by ID in order to
                //manage clonable data that has not been directly generated by the Docxpresso interface
                if (typeof dataToLoadFromServer.cloneGroupsByID != 'undefined' ) {
                    var cloneGroup = dataToLoadFromServer.cloneGroupsByID;
                    var groupLength = cloneGroup.length;
                    for (var k = 0; k < groupLength; k++){
                        //each array entry must be an object with the properties: id, ntimes, type and match
                        //that must be passed to the cloneGroupIdElement function defined in the docxpresso>helpers.js
                        cloneGroupIdElement(cloneGroup[k]['id'], cloneGroup[k]['ntimes'], cloneGroup[k]['type'], cloneGroup[k]['match']);
                    }
                }                
                //clone the blocks
                if (typeof dataToLoadFromServer.blocks != 'undefined' ) {
                    cloneBlocks(dataToLoadFromServer.blocks);
                }
                //replace variables
                if (typeof dataToLoadFromServer.varValues != 'undefined' ) {
                    replaceVars(dataToLoadFromServer.varValues, false, false);
                }
                //replace special variables
                if (typeof dataToLoadFromServer.specialVarValues != 'undefined' ) {
                    replaceVars(dataToLoadFromServer.specialVarValues, true, false);
                }
                
                
            }
            
            //relocation of Bootstrap modals for embeddings within a iframe
            $('.modal').on('shown.bs.modal', function() {
                if(window.top != window.self){
                    if ('parentIFrame' in window) {
                        parentIFrame.getPageInfo(relocate);
                        function relocate(pageInfo){
                            var modal_top_px_origin = pageInfo.scrollTop - pageInfo.offsetTop + 20;
                            if(modal_top_px_origin <= 0){
                                modal_top_px_origin = 10;
                            }
                            $('.modal').css("top",modal_top_px_origin+"px");
                        }
                    }
                }
            });
            
            //Confirmation of variables
            $('#confirmValues').click(function(){
                $('#confirmationModal').modal('hide');
                confirmValues();
            });

            function populateConfirmationPad(){
                $('#confirmation-pad').html('');
                var l = window.confirmation.length;
                var html = '<div class="form-horizontal">'
                for (var k = 0; k < l; k++) {
                    html += '<h4>Variable: ' + dxo[window.confirmation[k]]['label'] + '<br/>';
                    html += '<small>' + decodeURIComponent(dxo[window.confirmation[k]]['tip']) + '</small></h4>';
                    if (dxo[window.confirmation[k]]['global']) {
                        html += '<div class="form-group">';
                        html += '<label class="col-sm-2 control-label">';
                        html += '<button type="button" class="btn btn-primary btn-xs" data-valtype="' + dxo[window.confirmation[k]]['type'] + '" data-valname="' + window.confirmation[k] + '" data-num="0"><i class="fa fa-edit"></i>'
                        html += '</button> Valor:</label> ';
                        html += '<div class="col-sm-8"><p style="padding-top: 7px">"' + $('span[data-name="' + window.confirmation[k] + '"]').eq(0).text() + '"</p></div>';
                        html += '<label class="col-sm-2 control-label" style="clear: left">Confirmar: </label>';
                        html += '<div class="col-sm-8"><div class="input-group"><span class="input-group-addon"><i class="fa fa-check"></i></span>';
                        html += '<input type="text" class="form-control input_' + window.confirmation[k] + '" value="" placeholder="Confirmar valor" /></div></div>';
                        html += '</div>';
                    } else {
                        $('span[data-name="' + window.confirmation[k] + '"]').each(function(index){
                            html += '<div class="form-group" style="margin-bottom: 12px">';
                            html += '<label class="col-sm-2 control-label">';
                            html += '<button type="button" class="btn btn-primary btn-xs" data-valtype="' + dxo[window.confirmation[k]]['type'] + '" data-valname="' + window.confirmation[k] + '" data-num="' + index + '"><i class="fa fa-edit"></i>'
                            html += '</button> Valor:</label> ';
                            html += '<div class="col-sm-8"><p style="padding-top: 7px">"' + $('span[data-name="' + window.confirmation[k] + '"]').eq(index).text() + '"</p></div>';
                            html += '<label class="col-sm-2 control-label" style="clear: left">Confirmar: </label>';
                            html += '<div class="col-sm-8"><div class="input-group"><span class="input-group-addon"><i class="fa fa-check"></i></span>';
                            html += '<input type="text" class="form-control input_' + window.confirmation[k] + '_' + index + '" value="" placeholder="Confirmar valor" /></div></div>';
                            html += '</div>';
                        });
                    }
                    html += '<div class="hr-line-dashed"></div>';
                }
                html += '</div>';
                $('#confirmation-pad').html(html);
                $('#confirmation-pad button').off('click');
                $('#confirmation-pad button').click(function(){
                    selector = $('.h5p_varspan[data-name="' + $(this).attr('data-valname') + '"]:eq(' + $(this).attr('data-num') + ')');
                    //when there are tabs things get a little more complex because
                    //we need to "show" the correct tab first
                    if (typeof docxpressoData['settings']['tabs'] !== 'undefined'
                        && docxpressoData['settings']['tabs'] == 1) {
                        clickTab(selector);    
                    }
                    $("#confirmationModal").modal('hide');
                    highlight(selector);  
                });
            }

            function confirmValues(){
                var l = window.confirmation.length;
                var remove = [];
                for (var k = 0; k < l; k++) {
                    if (dxo[window.confirmation[k]]['global']) {
                        if ($('span[data-name="' + window.confirmation[k] + '"]').eq(0).text() == $('.input_' + window.confirmation[k]).val()) {
                            remove.push(k);
                        }
                    } else {
                        var rem = true;
                        $('span[data-name="' + window.confirmation[k] + '"]').each(function(index){
                            if ($('span[data-name="' + window.confirmation[k] + '"]').eq(index).text() != $('.input_' + window.confirmation[k] + '_' + index).val()) {
                                rem = false;
                            }
                        });
                        if (rem) {
                            remove.push(k);
                        }
                    }
                }
                var ll = remove.length;
                for(var j = ll -1; j >= 0; j--){
                    window.confirmation.splice(remove[j], 1);
                } 
                if (window.confirmation.length > 0){
                    toastr.error('Hubo errores en la confirmación.', 'Aviso');
                }
                //back to where we started
                attachmentPreSave();
            }
            
            //custom function on loaded completed
            if (typeof customOnFullyLoaded === "function") {
                customOnFullyLoaded();
            }
            //disable inputs
            //$('#mainDXO input').prop('disabled', true);
            //$('#mainDXO select').prop('disabled', true);
            $('select').on('mousedown', function(e) {
                e.preventDefault();
                this.blur();
                window.focus();
            });
            
        });//end of document ready
        
        //Custom JS functions
                document.getElementById('download').innerHTML = '<i class="fa fa-check-square" aria-hidden="true"> </i> <span class="buttonTop">Accept</span>';
                
        function preparseWYSIWYG (varspan, HTMLdata) {
            //get the font styles
            var color = varspan.css('color');
            var family = varspan.css('font-family');
            var size =  varspan.css('font-size');
            varspan.html(HTMLdata);
            varspan.find('p, li').each(function(){
                var styleArray = $(this).attr('style');
                if (typeof styleArray === 'undefined') {
                    styleArray = [];
                }
                var styles = {};
                var prop = '';
                var numStyles = styleArray.length;
                for (var j = 0; j < numStyles; j++) {
                  prop = styleArray[j].split(':');
                  styles[$.trim(prop[0].replace('-',''))] = $.trim(prop[1]);
                }
                if( typeof styles.color === 'undefined') {
                    $(this).css('color', color);
                }
                if( typeof styles.fontsize === 'undefined') {
                    $(this).css('font-size', size);
                }
                if( typeof styles.fontfamily === 'undefined') {
                    $(this).css('font-family', family);
                }
            });
        }
        
        function linkDressUp(linkable, type) {
            var linkedData = linkable;
            str = $('<div />').html(linkable).text();
            if (str == linkable){
                if (type == 'email') {
                    linkedData = '<a href="mailto:' + linkable + '">';
                    linkedData += linkable;
                    linkedData += '</a>';
                } else if (type == 'URL') {
                    //we need a further check because if the URL does not start
                    //with http:// or https:// MS Word fails to open the
                    //document
                    var http = linkable.substring(0,7);
                    var https = linkable.substring(0,8);
                    if (http == 'http://' || https == 'https://') {
                        linkedData = '<a href="' + linkable + '">';
                        linkedData += linkable;
                        linkedData += '</a>';
                    }
                }
            } 
            return linkedData;
        }
        
        function createRPCURL(rpc, query){
            var rpcurl = rpc.url;
            params = [];
            defaultParamValues = [];
            if (typeof rpc.params !== 'undefined') {
                params = rpc.params.split(';');
            }
            if (typeof rpc.defaultParamValues !== 'undefined') {
                defaultParamValues = rpc.defaultParamValues.split(';');
            }
            getParams = '?callback=?&method=' + rpc.method;
            getParams += '&timestamp=' + rpc.timestamp;
            getParams += '&uniqid=' + rpc.uniqid; 
            getParams += '&APIKEY=' + rpc.apikey;
            getParams += '&';
            len = params.length;
            for (var n = 0; n < len; n++) {
                getParams +=  params[n] + "="; 
                if(typeof query[params[n]] == 'undefined'){
                    if (typeof defaultParamValues[n] !== 'undefined' && defaultParamValues[n] !== '') {
                        message = rpc.prompt.replace('%param%', params[n]);
                        answer = prompt(message, defaultParamValues[n]);
                    } else {
                        answer = prompt('Por favor, inserte el valor requerido', params[n]);
                    }
                    if (answer !== null){
                        getParams += answer;
                    } else if (typeof defaultParamValues[n] !== 'undefined' ){
                        getParams += defaultParamValues[n];
                    } else {
                        getParams += 'undefined';
                    }
                } else {
                    getParams += query[params[n]];
                }
                getParams += '&';
            }
            rpcurl += getParams;
            return rpcurl;
        }
        
        $('#selectemail').change(function(){
            if ($(this).val() == 0){
                $('#signatureSel').hide();
                $('#signatureInput').show();
            } else {
                $('#inputemail').val($(this).val());
            }
        });
        
        //Aux functions for incremental variables
        function int2Roman(num) {
            if (typeof num !== 'number') 
            return false; 

            var digits = String(+num).split(""),
            key = ["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM",
            "","X","XX","XXX","XL","L","LX","LXX","LXXX","XC",
            "","I","II","III","IV","V","VI","VII","VIII","IX"],
            roman_num = "",
            i = 3;
            while (i--)
            roman_num = (key[+digits.pop() + (i * 10)] || "") + roman_num;
            return Array(+digits.join("") + 1).join("M") + roman_num;
        }

        function int2Letter(i) {   
            return (i >= 26 ? int2Letter(Math.floor(i / 26) -1 ) : '') + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[i % 26];  
        }
        
            
        </script>
    </body>
</html>