/* Minification failed. Returning unminified contents.
(104,40-41): run-time error JS1014: Invalid character: `
(104,47-54): run-time error JS1004: Expected ';': Contact
(104,90-91): run-time error JS1004: Expected ';': {
(104,110-111): run-time error JS1014: Invalid character: `
(136,47-48): run-time error JS1014: Invalid character: `
(136,48-49): run-time error JS1195: Expected expression: <
(136,103-104): run-time error JS1195: Expected expression: <
(136,148-149): run-time error JS1010: Expected identifier: <
(136,152-153): run-time error JS1014: Invalid character: `
(167,25-26): run-time error JS1193: Expected ',' or ')': }
(168,62-63): run-time error JS1004: Expected ';': {
(188,43-44): run-time error JS1014: Invalid character: `
(188,44-45): run-time error JS1195: Expected expression: <
(188,82-83): run-time error JS1197: Too many errors. The file might not be a JavaScript file: {
 */
//--------------------------------------------------------------------
//  Home 
//--------------------------------------------------------------------

// IIFE - Immediately Invoked Function Expression
(function (library) {
    library(window.jQuery, window, document);
}(function ($, window, document) {

    var initProjects = function () {

        var $section = $('#Projects');
        if (!$section.length)
            return;


        $section.find('.nav a[data-toggle="tab"]').on('shown.bs.tab', function (e)
        {
            var $self = $(e.target); // activated tab/link
            var target = $self.attr('href');
            var $target = $(target);

            window.initGalleria($(document));
        });

    };

    //-- gallery
    var initGallery = function ()
    {
        var $section = $('#Gallery');
        if (!$section.length)
            return;

        if ($.iLightBox) {
            /* IMPORTANT NOTE */
            //Read the iLightBox API documentation carefully. Cannot use $galleryLinks.iLightBox(options)! This can only be done on a SINGLE element not a group.
            //Grouping must be done manually as below.

            var $galleryLinks = $section.find('.gallery-container a');
            if ($galleryLinks.length) {
                var elements = [];
                $galleryLinks.each(function (i, item) {
                    var thumbnail = '';
                    var options = $(item).data('options') /*&& eval('({' + $(item).data('options') + '})')*/ || {};
                    if (options.length) {
                        thumbnail = options.thumbnail;
                    };

                    var element = { url: $(item).attr('href'), thumbnail: thumbnail };
                    elements.push(element);
                });

                $(document).off('click.gallery').on('click.gallery',
                    '#Gallery .gallery-container a, a[data-lightbox-gallery]',
                    function (e) {
                        var $self = $(e.currentTarget);
                        var startIndex = $self.parent().index();

                        $.iLightBox(elements,
                            {
                                startFrom: startIndex,
                                skin: 'dark',
                                path: 'horizontal',
                                overlay: {
                                    opacity: .8,
                                    blur: true
                                },
                                keyboard: {
                                    esc: false
                                },
                                styles: {
                                    nextOpacity: .55,
                                    prevOpacity: .55
                                }
                            });

                        return false;
                    });
            }
        }
    };

    //-- contact form
    var initContactForm = function () {

        var $form = $('form[action="/api/send/email"]');

        $form.on('submit',
            function (e) {
                var form = $form[0];
                if ($form.valid()) {
                    //form
                    var formModel = $form.serializeForm();

                    //antiforgery token
                    var token = $form.find('[name="__RequestVerificationToken"]').val();
                    var headers = { '__RequestVerificationToken': token };
                    //var headers = {};

                    //json
                    var model = {};
                    model['Destination'] = 'info@sblsolutions.com.au';
                    model['Subject'] = `[sbl] Contact Request from ${formModel['Name']} ${formModel['Phone']}`;
                    model['Body'] = formModel['Message'];

                    //make payment
                    $.ajax({
                        type: form.method,
                        url: form.action,
                        contentType: 'application/json;charset=utf-8',
                        dataType: 'json',
                        data: JSON.stringify(model),
                        headers: headers,
                        beforeSend: function (xhr) {
                            AjaxGlobalHandler.onBeginHandler(xhr, form);
                        },
                        complete: function (xhr, status) {
                            //ignore
                        },
                        success: function (data, status, xhr) {
                            if (xhr.readyState === 4) {
                                if (xhr.status === 200) {
                                    //200=OK, 201=Created, 202=Accepted

                                    //var model = $.parseJSON(data.json);
                                    var responseMessage = data;

                                    var $message = $form.find('.alert');
                                    $message.fadeIn()
                                        .removeClass('fade')
                                        .removeClass('alert-danger')
                                        .removeClass('alert-success')
                                        .addClass('alert-success')
                                        .find('div')
                                        .html(`<h4><i class="fa fa-fw fa-check"></i>${responseMessage}</h4><p>We will get back to you very shortly.</p>`);

                                    var $submitButton = $form.find(':submit');
                                    if ($submitButton.length)
                                    {
                                        //$submitButton
                                        var $formRow = $form.find('.row');
                                        $formRow.fadeOut().delay(15000).queue(function (next) {
                                            $message.fadeOut()
                                                .addClass('fade')
                                                .removeClass('alert-danger')
                                                .removeClass('alert-success')
                                                .find('div')
                                                .html('');

                                            $form[0].reset();
                                            $submitButton.fadeIn();
                                            $formRow.fadeIn();
                                            $(this).dequeue(); //next();
                                        });
                                    }

                                    //google analytics goal
                                    //ga('send', 'event', { eventCategory: 'enquiry', eventAction: 'contactus', eventLabel: 'submit', eventValue: 1});
                                }

                                //reset submit button
                                AjaxGlobalHandler.resetSubmitButton($form[0]);

                                return;
                            }
                        },
                        error: function (xhr, status, error) {
                            if (xhr.readyState === 4) {
                                var responseMessage = 'Failed to send message!';
                                //if(!String.prototype.isNullOrWhitespace(error))
                                //    responseMessage = error;

                                if (xhr.responseJSON !== undefined &&
                                    xhr.responseJSON !== null &&
                                    xhr.responseJSON.length) {
                                    //TODO: handle error.
                                    //var errorModel = $.parseJSON(xhr.responseJSON);
                                }

                                var $message = $form.find('.alert');
                                $message.fadeIn()
                                    .removeClass('fade')
                                    .removeClass('alert-danger')
                                    .removeClass('alert-success')
                                    .addClass('alert-danger')
                                    .find('div')
                                    .html(`<h4><i class="fa fa-fw fa-times"></i>${responseMessage}</h4><p>Please <a href="mailto:info@sblsolutions.com.au">email us</a> directly if problems persists.</p>`);

                                //reset submit button
                                AjaxGlobalHandler.resetSubmitButton($form[0]);
                            }
                        }
                    });
                }

                //do not allow form to post.
                e.preventDefault();
                return false;
            });
    };

    //-- init
    var init = function () {

        initProjects();
        initGallery();
        initContactForm();
    };

    window.initHomeView = init;

    //-- dom ready
    $(function () {

        var viewInit = function () {
            init();
        }();

    });
}));;
