{% extends "sprout-seo/_layouts/general" %}
{% import "_includes/forms" as forms %}
{% import "sprout-base-fields/_includes/forms" as sproutFields %}
{% import "sprout-seo/_includes/sproutseo" as sprout %}

{% set imageElement      = null %}
{% set elementType       = craft.sproutSeo.getAssetElementType %}
{% set organizationItems = craft.sproutSeo.getOrganizationOptions() %}
{% set websiteIdentity   = globals.identity %}
{% set maxDescriptionLength = craft.sproutSeo.getDescriptionLength() %}

{% set websiteIdentityTypes = [
    { label: "Organization", value: "Organization" },
    { label: "Person", value: "Person" }
] %}

{% set websiteIdentityOptions = {"":""} %}

{% for item in organizationItems %}
    {% set websiteIdentityOptions = websiteIdentityOptions|merge({
        (item.name) : craft.sproutSeo.getJsonName(item.name)
    }) %}
{% endfor %}

{% if websiteIdentity.image is defined and websiteIdentity.image %}
    {% for id in websiteIdentity.image %}
        {% set image = craft.sproutSeo.getElementById(id) %}
        {% set imageElement = image %}
    {% endfor %}
{% endif %}

{% block content %}
    <form method="post" accept-charset="UTF-8" data-saveshortcut>
        {{ csrfInput() }}
        <input type="hidden" name="action"
               value="sprout-seo/global-metadata/save-global-metadata">
        <input type="hidden" name="globalKeys" value="meta,identity">

        <input type="hidden" name="siteId" value="{{ globals.siteId }}">

        {{ forms.textField({
            label: "Name"|t('sprout-seo') ~ sprout.infoIcon({
                label: "Name"|t('sprout-seo'),
                search: true,
                structured: true,
                openGraph: true,
                twitterCard: true,
                priority: 'globals'
            }),
            instructions: "The preferred name of your website. <a href='#' class='fieldtoggle instructionstoggle' data-target='toggle-alternate'>Add alternate name</a>."|t('sprout-seo'),
            name: 'sproutseo[globals][identity][name]',
            value: websiteIdentity['name'] is defined ? websiteIdentity.name : null,
            errors: '',
            first: true,
            maxlength: 60,
            showCharsLeft: true,
            required: true,
            placeholder: siteName,
            class: 'nicetext'
        }) }}

        <div id="toggle-alternate"
             class="{{ (websiteIdentity['alternateName'] is defined and websiteIdentity.alternateName ?:
             'hidden' ) }}">
            {{ forms.textField({
                label: "Alternate Name"|t('sprout-seo') ~ sprout.infoIcon({
                    label: "Alternate Name"|t('sprout-seo'),
                    search: true,
                    structured: true,
                    priority: 'globals'
                }),
                instructions: "An alternate name you want search engines to consider (i.e. such as a legal name or nickname)."|t('sprout-seo'),
                name: 'sproutseo[globals][identity][alternateName]',
                value: websiteIdentity['alternateName'] is defined ? websiteIdentity.alternateName : null,
                errors: '',
                maxlength: 60,
                showCharsLeft: true,
                class: 'nicetext'
            }) }}
        </div>

        {{ forms.textareaField({
            label: "Description"|t('sprout-seo') ~ sprout.infoIcon({
                label: "Description"|t('sprout-seo'),
                search: true,
                structured: true,
                openGraph: true,
                twitterCard: true,
                priority: 'globals'
            }),
            instructions: "A description of your website."|t('sprout-seo'),
            name: 'sproutseo[globals][identity][description]',
            value: websiteIdentity['description'] is defined ? websiteIdentity.description : null,
            errors: '',
            required: true,
            maxlength: maxDescriptionLength,
            showCharsLeft: true,
            placeholder: "The official website of " ~ siteName
        }) }}

        {{ forms.field({
            label: 'Image'|t('sprout-seo') ~ sprout.infoIcon({
                label: "Image"|t('sprout-seo'),
                search: true,
                structured: true,
                openGraph: true,
                twitterCard: true,
                priority: 'globals'
            }),
            instructions: "The preferred image or profile picture for your website."|t('sprout-seo'),
            required: true
        }, forms.elementSelect({
            elements: [imageElement],
            sourceElementId: websiteIdentity['image'] is defined and imageElement ? websiteIdentity.image : null,
            elementType: elementType,
            id: 'image',
            name: 'sproutseo[globals][identity][image]',
            jsClass: 'Craft.AssetSelectInput',
            addButtonLabel: 'Select Image'|t('sprout-seo'),
            sources: '*',
            limit: 1,
            criteria: {kind: ['image'], siteId : null}
        })) }}

        {% set keywordsValue = websiteIdentity['keywords'] is defined ? websiteIdentity.keywords : null %}

        {{ forms.textField({
            label: "Keywords"|t('sprout-seo') ~ sprout.infoIcon({
                label: "Keywords"|t('sprout-seo'),
                search: true,
                priority: 'globals'
            }),
            instructions: "The primary keywords or phrases that describe your website."|t('sprout-seo'),
            id: 'keywords',
            name: 'sproutseo[globals][identity][keywords]',
            value: keywordsValue,
            errors: ''
        }) }}

        {{ sproutFields.emailField({
            label: "Email"|t('sprout-seo') ~ sprout.infoIcon({
                label: "Email"|t('sprout-seo'),
                search: true,
                structured: true,
                priority: 'globals'
            }),
            instructions: 'The preferred email address for your website.'|t('sprout-seo'),
            namespaceInputId: 'sproutseo-websiteidentity-email',
            id: 'sproutseo-websiteidentity-email',
            fieldContext: 'sproutseo',
            name: 'sproutseo[globals][identity][email]',
            value: websiteIdentity['email'] is defined ? websiteIdentity.email : null,
            errors: ''
        }) }}

        {{ sproutFields.phoneField({
            label: "Telephone"|t('sprout-seo') ~ sprout.infoIcon({
                label: "Telephone"|t('sprout-seo'),
                search: true,
                structured: true,
                priority: 'globals'
            }),
            instructions: 'The preferred telephone number for your website.'|t('sprout-seo'),
            namespaceInputId: 'sproutseo-websiteidentity-phone',
            id: 'sproutseo-websiteidentity-phone',
            fieldContext: 'sproutseo',
            name: 'sproutseo[globals][identity][telephone]',
            value: websiteIdentity['telephone']['phone'] is defined ? websiteIdentity.telephone.phone : null,
            errors: '',
            limitToSingleCountry: false,
            country: websiteIdentity['telephone']['country'] is defined ? websiteIdentity.telephone.country : 'US',
            countryId: 'phoneCountry',
            namespaceCountryId: 'phoneCountry'
        }) }}

        {% set addressInput %}
            <div class="sproutaddressinfo-box"
                    {% if websiteIdentity.addressId is defined %}
                        data-addressinfoid='{{ websiteIdentity.addressId }}'
                    {% endif %}
                    data-defaultcountrycode='US'
            >
                <div class='address-add-button hidden'>
                    <a class='btn add icon dashed sprout-address-edit'
                       href='#'>{{ "Add Address"|t('sprout-seo') }}</a>
                </div>
                <div class='address-edit-buttons hidden'>
                    <a class='small btn right icon sprout-address-edit clear-button'
                       href='#'>{{ "Clear"|t('sprout-seo') }}</a>
                    <a class='small btn right icon sprout-address-edit update-button'
                       href='#'>{{ "Edit"|t('sprout-seo') }}</a>
                </div>
                <div class='address-format hidden'>
                      {{ addressDisplayHtml }}
                </div>
                <div class='sproutfields-address-formfields hidden'>
                    <input type="hidden" name="address[delete]" />
                    {{ countryInputHtml }}
                    {{ addressFormHtml }}
                </div>
            </div>
        {% endset %}

        {{ forms.field({
            label: 'Address'|t('sprout-seo') ~ sprout.infoIcon({
                label: "Address Field"|t('sprout-seo'),
                search: true,
                structured: true,
                priority: 'globals'
            }),
            instructions: 'The preferred physical address for your website.'|t('sprout-seo'),
            fieldClass: 'sproutfields-addressfield',
            required: false
        }, addressInput) }}

        {{ forms.textField({
            label: "Latitude"|t('sprout-seo') ~ sprout.infoIcon({
                label: "Latitude"|t('sprout-seo'),
                search: true,
                structured: true,
                priority: 'globals'
            }),
            instructions: 'The latitude of your address.'|t('sprout-seo'),
            name: 'sproutseo[globals][identity][latitude]',
            value: websiteIdentity['latitude'] is defined ? websiteIdentity.latitude : null,
            errors: ''
        }) }}

        {{ forms.textField({
            label: "Longitude"|t('sprout-seo') ~ sprout.infoIcon({
                label: "Longitude"|t('sprout-seo'),
                search: true,
                structured: true,
                priority: 'globals'
            }),
            instructions: 'The longitude of your address.'|t('sprout-seo'),
            name: 'sproutseo[globals][identity][longitude]',
            value: websiteIdentity['longitude'] is defined ? websiteIdentity.longitude : null,
            errors: ''
        }) }}

        <hr>

        <div class="field identityType-field-wrapper">
            <div class="heading">
                <label for="siteOwnerType">{{ "Website Identity"|t('sprout-seo') }}  {{ sprout.infoIcon({
                        label: "Website Identity"|t('sprout-seo'),
                        search: true,
                        structured: true,
                        priority: 'globals'
                    }) }}
                </label>
                <div class="instructions">
                    <p>{{ "Select the primary concept that represents your brand identity." |t('sprout-seo') |raw }}</p>
                </div>
            </div>

            <div class="input">

                <div class="identitytype-dropdown">
                    {{ forms.selectField({
                        id: 'identityType',
                        name: 'sproutseo[globals][identity][@type]',
                        options: websiteIdentityTypes,
                        value: globals.getWebsiteIdentityType(),
                        errors: "",
                        required: false
                    }) }}
                </div>

                <div id="organization"
                     class="organization-info {% if globals.getWebsiteIdentityType() == 'Person' %}hidden{% endif %}">

                    <div class="identitytype-dropdown organizationinfo-dropdown">
                        {{ forms.selectField({
                            id: 'first',
                            role: 'listbox',
                            name: 'sproutseo[globals][identity][organizationSubTypes][0]',
                            options: websiteIdentityOptions,
                            value: '',
                            errors: "",
                            required: false,
                        }) }}
                    </div>

                    <div class="identitytype-dropdown organizationinfo-dropdown hidden">
                        {{ forms.selectField({
                            id: 'second',
                            role: 'listbox',
                            name: 'sproutseo[globals][identity][organizationSubTypes][1]',
                            options: {'':''},
                            value: '',
                            errors: '',
                            required: false,
                        }) }}
                    </div>

                    <div class="identitytype-dropdown organizationinfo-dropdown hidden">
                        {{ forms.selectField({
                            id: 'third',
                            role: 'listbox',
                            name: 'sproutseo[globals][identity][organizationSubTypes][2]',
                            options: {'':''},
                            value: '',
                            errors: '',
                            required: false,
                        }) }}
                    </div>
                </div>
            </div>
        </div>

        <hr>

        {# These fields should only display when 'Organization' is selected #}
        <div class="organization-info {% if globals.getWebsiteIdentityType() == 'Person' %}hidden{% endif %}">

            {{ forms.dateField({
                label: "Founding Date"|t('sprout-seo') ~ sprout.infoIcon({
                    label: "Founding Date"|t('sprout-seo'),
                    search: true,
                    structured: true,
                    priority: 'globals'
                }),
                id : "foundingDate",
                instructions: 'The date that this organization was founded.'|t('sprout-seo'),
                name: 'sproutseo[globals][identity][foundingDate]',
                value: websiteIdentity['foundingDate']['date'] is defined ? craft.sproutSeo.getDate(websiteIdentity.foundingDate) : null,
                errors: '',
                required: false
            }) }}

            <hr>

            {# These fields should only display when 'Organization => LocalBusiness' is selected #}
            <div id="localbusiness"
                 {% if not globals.isLocalBusiness() %}class="hidden"{% endif %}>

                {% set priceRangeOptions = craft.sproutSeo.getPriceRangeOptions(currentSite) %}

                <div class="field">
                    <div class="heading">
                        <label for="siteOwnerType">{{ "Opening Hours"|t('sprout-seo') }} {{ sprout.infoIcon({
                                label: "Opening Hours"|t('sprout-seo'),
                                search: true,
                                structured: true,
                                priority: 'globals'
                            }) }}</label>
                        <div class="instructions">
                            <p>{{ "The general opening hours for a business. Leave the hours blank to indicate the business is closed on a particular day."    |t('sprout-seo') |raw }}</p>
                        </div>
                    </div>
                    <div>
                        <table class="data">
                            <thead>
                            <tr>
                                <td></td>
                                <th>{{ "Opening Time"|t('sprout-seo') }}</th>
                                <th>{{ "Closing Time"|t('sprout-seo') }}</th>
                            </tr>
                            </thead>
                            <tbody>
                            {% for day in 0..6 %}
                                <tr>
                                    <th>
                                        {{ craft.app.locale.getWeekDayName(day) }}
                                    </th>
                                    <td>
                                        {{ forms.timeField({
                                            id: 'openingHours-'~day~'-open',
                                            name: 'sproutseo[globals][identity][openingHours]['~day~'][open]',
                                            value: websiteIdentity['openingHours'][day]['open'] is defined ? websiteIdentity['openingHours'][day]['open'].time : null,
                                        }) }}
                                    </td>
                                    <td>
                                        {{ forms.timeField({
                                            id: 'openingHours-'~day~'-close',
                                            name: 'sproutseo[globals][identity][openingHours]['~day~'][close]',
                                            value: websiteIdentity['openingHours'][day]['close'] is defined ? websiteIdentity['openingHours'][day]['close'].time : null,
                                        }) }}
                                    </td>
                                </tr>
                            {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>

                {{ forms.field({
                    label: "Price Range"|t('sprout-seo') ~ sprout.infoIcon({
                        label: "Price Range"|t('sprout-seo'),
                        search: true,
                        structured: true,
                        priority: 'globals'
                    }),
                    first: true,
                }, sproutFields.selectOther({
                    name: 'sproutseo[globals][identity][priceRange]',
                    options: priceRangeOptions ,
                    value: websiteIdentity['priceRange'] is defined ? websiteIdentity.priceRange : null,
                    otherPlaceholderText: 'Custom Price Range'|t('sprout-seo')
                })) }}


                <hr>

            </div>
        </div>

        {# These fields should only display when 'Person' is selected #}
        <div class="person-info {% if globals.getWebsiteIdentityType() == 'Organization' %}hidden{% endif %}">

            {% set genderOptions = craft.sproutSeo.getGenderOptions(currentSite) %}

            {{ forms.field({
                label: "Gender"|t('sprout-seo') ~ sprout.infoIcon({
                    label: "Gender"|t('sprout-seo'),
                    search: true,
                    structured: true,
                    priority: 'globals'
                }),
                first: true,
            }, sproutFields.selectOther({
                name: 'sproutseo[globals][identity][gender]',
                options: genderOptions ,
                value: websiteIdentity['gender'] is defined ? websiteIdentity.gender : null,
                otherPlaceholderText: 'Custom Gender'|t('sprout-seo')
            })) }}

            <hr>

        </div>

        <div class="buttons">
            <input type="submit" class="btn submit" value="Save"/>
        </div>

    </form>

{% endblock %}

{% do view.registerAssetBundle("barrelstrength\\sproutseo\\web\\assets\\globals\\GlobalsAsset") %}

{% js %}

    var items = {{ organizationItems|json_encode|raw }};
    var websiteIdentity = {{ websiteIdentity|json_encode|raw }};

    $(document).ready(function() {
    Craft.SproutFields.initFields($("#content"));

    $('#keywords-field input').tagEditor({
    animateDelete: 20
    });

    // check if we need load depending dropdowns
    if (websiteIdentity)
    {
    if (websiteIdentity.hasOwnProperty('organizationSubTypes') && websiteIdentity.organizationSubTypes[0])
    {
    $('#first').val(websiteIdentity.organizationSubTypes[0]).change();
    }
    if (websiteIdentity.hasOwnProperty('organizationSubTypes') && websiteIdentity.organizationSubTypes[1])
    {
    $('#second').val(websiteIdentity.organizationSubTypes[1]).change();
    }
    if (websiteIdentity.hasOwnProperty('organizationSubTypes') && websiteIdentity.organizationSubTypes[2])
    {
    $('#third').val(websiteIdentity.organizationSubTypes[2]).change();
    }
    }

    $( "#identityType" ).change(function() {
    if(this.value === 'Person')
    {
    $( ".person-info" ).removeClass('hidden');
    $( ".organization-info" ).addClass('hidden');
    }
    else
    {
    $( ".person-info" ).addClass('hidden');
    $( ".organization-info" ).removeClass('hidden');
    }

    if(this.value === 'Organization')
    {
    $( ".organization-info" ).removeClass('hidden');
    $( ".person-info" ).addClass('hidden');

    if ($( "#first" ).val() == 'LocalBusiness')
    {
    $( "#localbusiness" ).removeClass('hidden');
    }
    }
    else
    {
    $( ".organization-info" ).addClass('hidden');
    $( ".person-info" ).removeClass('hidden');
    }
    });

    $( "#first" ).change(function() {
    console.log(this.value);
    if(this.value === 'LocalBusiness')
    {
    $( "#localbusiness" ).removeClass('hidden');
    }
    else
    {
    $( "#localbusiness" ).addClass('hidden');
    }
    });

        new Craft.SproutBase.AddressBox($('.sproutaddressinfo-box'), {
            source: 'websiteIdentity',
            namespace: 'address'
        })
    });

{% endjs %}

