/* Minification failed. Returning unminified contents.
(10,63-64): run-time error JS1009: Expected '}': [
(10,80-81): run-time error JS1006: Expected ')': :
(10,80): run-time error JS1004: Expected ';'
(10,100-101): run-time error JS1195: Expected expression: )
(19,5-6): run-time error JS1006: Expected ')': }
(18,10): run-time error JS1004: Expected ';'
(19,6-7): run-time error JS1195: Expected expression: )
 */
jQuery(function ($) {
    $.ajaxSetup({
        beforeSend: function (jqXHR, settings) {
            if (/post/i.test(settings.type)) {
                let csrf_token_name = "__RequestVerificationToken",
                    csrf_token_value = $(`input[name=${csrf_token_name}]`).val();

                // data doesn't contain csrf token
                if ($.isPlainObject(settings.data) && !settings.data[csrf_token_name]) {
                    settings.data = $.extend(settings.data, { [csrf_token_name]: csrf_token_value });
                } else if (!new RegExp(`${csrf_token_name}=`).test(settings.data)) {
                    if(settings.data)
                        settings.data += `&${csrf_token_name}=${csrf_token_value}`;
                    else
                        settings.data = `${csrf_token_name}=${csrf_token_value}`;
                }
            }
        }
    });

    // canvas widget view
    $("body").on("submit", ".canvas-widget form", function (e) {
        console.debug("submit .canvas-widget form triggered");
        var $form = $(this);
        
        $.ajax({
            url: $form.attr("action"),
            method: $form.attr("method"),
            data: $form.serialize(),
            success: function (data) {
                var widget = $form.closest(".canvas-widget");

                widget.find("[widget-refresh]").each(function() {
                    var container = $(this)
                        , url = container.attr("widget-refresh");

                    console.debug("widget refresh", this, url);
                    container.load(url);
                });
            }
        });

        // STOP the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.
        e.stopImmediatePropagation();
        return false;
    });

    /*need this in order for the mode-x.js to work*/
    ace.config.set("basePath", "/App_Asset/Public/ace");
    
    tinymce.init({
        selector: '.tinymce'
        , theme: 'silver'
        , allow_html_in_named_anchor: true
        , cleanup_on_startup: false
        , rim_span_elements: false
        , verify_html: false
        , cleanup: false
        , convert_urls: false
        , plugins: "autoresize"
        , min_height: 150
        , max_height: 750
        , autoresize_bottom_margin: 0
        , external_plugins: {
            "searchreplace": "plugins/searchreplace/plugin.min.js",            
            "paste": "plugins/paste/plugin.min.js",
            "noneditable": "plugins/noneditable/plugin.min.js",
            "visualchars": "plugins/visualchars/plugin.min.js",
            "link": "plugins/link/plugin.min.js",
            "code": "plugins/code/plugin.min.js",
            "image": "plugins/image/plugin.min.js"
        }
        , paste_data_images: true
        , toolbar: ["undo redo | fontselect | fontsizeselect | forecolor backcolor | bold italic underline",
           "alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent | link image | code"
        ]
        , contextmenu: "cut copy paste | link image"
        , valid_elements: "*[*]"
        , skin_url: '/App_Asset/Public/tinymce/skins/silver'
    });

    $(".ace-editor").each(function () {        
        var html = $(this).hide();
        var placeholder = html.data('placeholder');

        if (!placeholder) {
            placeholder = $("<div>").insertBefore(html);
            html.data('placeholder', placeholder);
        }

        var editor = ace.edit(placeholder.get()[0]);
        var extension = $(this).data('extension');
        
        if (typeof extension !== typeof undefined && extension === '.js') {
            editor.session.setMode("ace/mode/javascript");
        }
        else if (typeof extension !== typeof undefined && extension === '.css') {
            editor.session.setMode("ace/mode/css");
        }
        else {
            editor.session.setMode("ace/mode/razor");
        }
        editor.session.setValue(html.val());

        editor.setAutoScrollEditorIntoView(true);
        editor.setOption("maxLines", html.attr('rows'));
        editor.setOption("minLines", 10);

        editor.getSession().on("change", function () {
            html.val(editor.getSession().getValue());
        });
    });

    $('body').on('click', 'button.btn-confirm', function () {

       var $buttonName= $(this).attr('name');
       var $buttonVal= $(this).val();

        var $form = $(this).closest('form');

        var placeholder = $('.modal-placeholder');
        if (!placeholder.length)
            placeholder = $('<div class="modal fade" tabindex="-1" role="dialog"><div class="modal-dialog modal-lg"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button><h4 class="modal-title"></h4></div><div class="modal-body"></div><div class="modal-footer"></div></div></div></div>').addClass('modal-placeholder').appendTo('body');

        var self = $(this);

        (self.data('btn-confirm.init') || $.noop)(placeholder);

        var attrDialogTitle = $(this).data('dialogtitle');
        if (typeof attrDialogTitle !== typeof undefined && attrDialogTitle !== false) {
            placeholder.find(".modal-title").html(attrDialogTitle);
        } else {
            placeholder.find(".modal-title").html(self.html());
        }

        placeholder.find(".modal-body").html(self.data('confirmation'));

        var btnStr = '<button id="confirm" class="btn btn-primary" data-ajax="false">Yes</button><button class="btn btn-default" data-dismiss="modal">Cancel</button>';
        if (self.data('buttons')) {
            var buttons = self.data('buttons').split("|");
            for (i = 0; i < buttons.length; i++) {
                if (i == 0) {
                    btnStr = '<button id="confirm" class="btn btn-primary" data-ajax="false">' + buttons[i] + '</button>';
                }
                else {
                    btnStr += '<button class="btn btn-default" data-dismiss="modal">' + buttons[i] + '</button>';
                }
            }
        }
        placeholder.find(".modal-footer").html(btnStr);

        placeholder.modal("show").one('click', '#confirm', function () {
            var input = $("<input name='" + $buttonName + "'>").attr("type", "hidden").val($buttonVal);
            placeholder.modal('hide');
            $form.append(input);
            $form.trigger('submit'); // submit the form
        });

        return false;
    });

    $('body').on('click', 'a.btn-confirm', function () {

        var placeholder = $('.modal-placeholder');
        if (!placeholder.length)
            placeholder = $('<div class="modal fade" tabindex="-1" role="dialog"><div class="modal-dialog modal-lg"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button><h4 class="modal-title"></h4></div><div class="modal-body"></div><div class="modal-footer"></div></div></div></div>').addClass('modal-placeholder').appendTo('body');

        var self = $(this);

        (self.data('btn-confirm.init') || $.noop)(placeholder);

        var attrDialogTitle = $(this).data('dialogtitle');
        if (typeof attrDialogTitle !== typeof undefined && attrDialogTitle !== false) {
            placeholder.find(".modal-title").html(attrDialogTitle);
        } else {
            placeholder.find(".modal-title").html(self.html());
        }

        placeholder.find(".modal-body").html(self.data('confirmation'));

        var btnStr = '<a href="' + self.attr("href") + '" class="btn btn-primary" data-ajax="false">Yes</a><button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>';

        if (self.data('buttons')) {
            var buttons = self.data('buttons').split("|");
            for (i = 0; i < buttons.length; i++) {
                if (i == 0) {
                    btnStr = '<a href="' + self.attr("href") + '" class="btn btn-primary" data-ajax="false">' + buttons[i] + '</a>';
                }
                else {
                    btnStr += '<button type="button" class="btn btn-default" data-dismiss="modal">' + buttons[i] + '</button>';
                }
            }
        }
        placeholder.find(".modal-footer").html(btnStr);

        placeholder.modal("show");

        return false;
    });

    $('body').on('click', '.modal-footer .buttons button, .modal-footer .buttons input', function () {
        var self = $(this)
        , modal = self.closest(".modal");

        modal.modal('hide');
        modal.find('form').submit();
    });

    $("body").on('click', 'a.btn-modal, .modal a', function () {
        var self = $(this);

        if (self.data("ajax") != undefined && !self.data("ajax")) {
            window.location = self.attr('href');
            return false;
        }

        var placeholder = $('.modal-placeholder');

        if (!placeholder.length)
            placeholder = $('<div class="modal fade" tabindex="-1" role="dialog"><div class="modal-dialog modal-lg"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button><h4 class="modal-title"></h4></div><div class="modal-body"></div><div class="modal-footer"><div style="display:none;" class="returnurl"></div><button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <span class="buttons"></span></div></div></div></div>').addClass('modal-placeholder')
                .appendTo(self.closest(".canvas-widget, body"));

        var self = $(this);

        (self.data('btn-modal.init') || $.noop)(placeholder);

        var attrDialogTitle = $(this).data('dialogtitle');
        if (typeof attrDialogTitle !== typeof undefined && attrDialogTitle !== false) {
            placeholder.find(".modal-title").html(attrDialogTitle);
        } else {
            placeholder.find(".modal-title").html(self.html());
        }

        placeholder.find(".returnurl").html(self.data('returnurl'));

        console.debug("Retrieve data from URL [" + self.attr('href') + "]");

        $.ajax({
            url: self.attr('href'),
            method: 'get',
            error: function (xhr, ajaxOptions, thrownError) {
                console.debug("Error while get from: " + this.url + " status[" + xhr.status + "]" + " error[" + thrownError + "]" + " content[" + xhr.responseText + "]");
                alert("Error while get from: " + this.url + " status[" + xhr.status + "]" + " error[" + thrownError + "]" + " content[" + xhr.responseText + "]");

            },
            success: function (data) {
                console.debug("Information before modal shows");
                placeholder.modal("show");
                console.debug("Information after modal shows");
                placeholder.find(".modal-body").empty().append(data);

                $(".modal-footer .buttons").empty();
                placeholder.find(".modal-body form [type='submit']").appendTo(".modal-footer .buttons");

                console.debug("Information after modal data");
                if(data.indexOf("ace-editor") >0)
                {
                    placeholder.find(".modal-body .ace-editor").each(function () {
                        var html = $(this).hide();
                        var placeholder = html.data('placeholder');

                        if (!placeholder) {
                            placeholder = $("<div>").insertBefore(html);
                            html.data('placeholder', placeholder);
                        }

                        var editor = ace.edit(placeholder.get()[0]);
                        editor.session.setMode("ace/mode/razor");
                        editor.session.setValue(html.val());

                        editor.setAutoScrollEditorIntoView(true);
                        editor.setOption("maxLines", html.attr('rows'));
                        editor.setOption("minLines", 10);

                        editor.getSession().on("change", function () {
                            html.val(editor.getSession().getValue());
                        });
                    });
                }
            }
        });

        return false;
    });

    $("body").on('submit', '.modal form', function (e) {
        console.debug("site.js.body.submit is called");

        var attrNoAjaxSubmit = $(this).attr('data-noajaxsubmit');
        if (typeof attrNoAjaxSubmit !== typeof undefined && attrNoAjaxSubmit !== false) {
            console.debug("no ajax submit is called in site.js.body.submit");
            $(this).closest('.ui-dialog-content').dialog('close');           
            return;
        }

        $.ajax({
            type: "POST",
            url: $(this).attr('action'),
            data: $(this).serialize(), // serializes the form's elements.
            success: function (data) {

                $(this).closest('.ui-dialog-content').dialog('close');

                if (data == "") {
                    if ($('.modal-footer .returnurl').html())
                    {
                        var url=decodeURI($('.modal-footer .returnurl').html());
                        
                        url= url.replace(/\&amp;/g,'&');
                        window.location = url;
                    }
                    else
                    location.reload();
                }
                else {
                    $('.modal-placeholder .modal-body').empty().append(data);
                }
            }
        });

        e.preventDefault(); // avoid to execute the actual submit of the form.
    });


    $(".choose-media").each(function () {
        var self = $(this);

        self.data('btn-modal.init', function (placeholder) {
            var target = self.data('choose-media');

            var previewImg = self.parent().next().find(target);

            placeholder.one('click', '.media-preview', function () {
                var clickedImg = $(this), id = clickedImg.data('id'), src = clickedImg.data('filepath');
                console.log('clicked', clickedImg);
                if (previewImg.is("img"))
                    previewImg.attr('src', src);
                if(!self.next().is(":file"))
                    self.next().val(id);


                var targetUrl = self.data('target-url');
                console.log("Updateing .. ", targetUrl);
                $(targetUrl).each(function (idx, elm) {
                    var selfElm = $(elm);
                    console.log('selfElm', selfElm);
                    if (selfElm.is("input")) {
                        selfElm.val(src).trigger('change');
                    } else if (selfElm.is("img")) {
                        selfElm.attr("src", src);
                    } else if (selfElm.is("a")) {
                        console.log("a", src);
                        selfElm.attr("href", src);
                        selfElm.text(clickedImg.data("filename"));
                    }

                })
                
                





                placeholder.modal('hide');
            });

        });
    });

    $(".field-choose-media").each(function () {
        var self = $(this);

        self.data('btn-modal.init', function (placeholder) {
            var target = self.data('preview-div');
            var mediaidinput = self.data('media-id-input');

            var previewImg = self.parent().find(target);

            placeholder.one('click', '.media-preview', function () {

                var clickedImg = $(this), id = clickedImg.data('id');

                self.parent().find(mediaidinput).val(id);

                var downloadlink = self.parent().find(self.data('downloadlink'));

                if (clickedImg.data('isimage')) {
                    previewImg.attr('src', clickedImg.attr('src')).show();
                    $(downloadlink).parent().hide();
                }
                else {
                    previewImg.hide();
                    $(downloadlink).text(clickedImg.data('filename'));
                    $(downloadlink).parent().show();
                    $(downloadlink).attr('href', clickedImg.data('filepath'));
                }

                //clear the file input
                self.parent().find('input:file').wrap('<form>').closest('form').get(0).reset();
                self.parent().find('input:file').unwrap();

                placeholder.modal('hide');
            });

        });
    });

    $(document).on("click", '.cboxGlobalCheckAll', function () {
        var checked = $(this).prop('checked');
        var t = $(this).parents('table').find('tbody');
        if(t == null || t.length == null || t.length <1){
            t = $(this).parents('div').find('.itemList');
        }        

        console.debug(t.find('input:checkbox').length);
        t.find('input:checkbox').each(function () {
            var attr = $(this).attr('disabled');
            if (typeof attr !== typeof undefined && attr !== false) return;
            if ($(this).is(":visible"))
                $(this).prop('checked', checked);
        });
    });

    $('#showDisabled').on('click', function () {

        $('table :checkbox').prop('checked', false);
        $('.itemList :checkbox').prop('checked', false);
        $('.cboxGlobalCheckAll').prop('checked', false);

        $('.ShowInactive').toggle($(this).is(':checked'));
        $('.ShowActive').toggle(!$(this).is(':checked'));
            
        $('tfoot').remove();
        $('.norow').remove();

        if ($('tr:visible').length == 1) {
            $('table tr:last').after('<tr class="norow"><td colspan="10">No records found</td></tr>');
        }
    });

    $('.selectAll').click(function () {
        var checkboxdivclass = $(this).attr('checkboxdivclass');

        $('.' + checkboxdivclass + ' input:checkbox:enabled').prop('checked', true);
    });

    $('.selectNone').click(function () {
        var checkboxdivclass = $(this).attr('checkboxdivclass');
        $('.' + checkboxdivclass + ' input:checkbox:enabled').prop('checked', false);
    });

    $('.checkbox-tree input:checkbox').click(function () {
        if ($(this).prop('checked')) { //if checked, all parent li is checked
            $(this).parents('li').children('input:checkbox').prop('checked', true);
        }
        else { //if unchecked, all child li is unchecked
            $(this).closest('li').find('input:checkbox').prop('checked', false);
        }
    });

    $('.rich-text').click(function () {
        if ($(this).prop('checked')) {
            tinyMCE.execCommand('mceAddEditor', false, 'Value');
        }
        else {
            tinyMCE.execCommand('mceFocus', false, 'Value');
            tinyMCE.execCommand('mceRemoveEditor', false, 'Value');
        }
    });

    $("body").tooltip({
        selector: '[data-toggle="tooltip"]'
    });
 
    $('body').on('click', '.copyrazor', function () {
        var $temp = $("<input>");
        $("body").append($temp);

        if ($(this).data('copyrazorfrom'))
        {
            $temp.val($($(this).data('copyrazorfrom')).text()).select();
        }
        else
        {
            $temp.val($(this).parent().prev().text()).select();
        }
        document.execCommand("copy");
        $temp.remove();

        return false;
    });

    $(".select2").select2();

    $(".select2-bootstrap").select2({
        theme: "bootstrap"
    });
});

function toggleNavigation() {
    jQuery("body").toggleClass("mini-navbar");
    smoothlyMenu();
}

function smoothlyMenu() {
    if (!jQuery('body').hasClass('mini-navbar') || jQuery('body').hasClass('body-small')) {
        // Hide menu in order to smoothly turn on when maximize menu
        jQuery('#side-menu').hide();
        // For smoothly turn on menu
        setTimeout(
            function () {
                jQuery('#side-menu').fadeIn(400);
            }, 200);
    } else if (jQuery('body').hasClass('fixed-sidebar')) {
        jQuery('#side-menu').hide();
        setTimeout(
            function () {
                jQuery('#side-menu').fadeIn(400);
            }, 100);
    } else {
        // Remove all inline style from jquery fadeIn function to reset menu state
        jQuery('#side-menu').removeAttr('style');
    }
}

function detectBody() {
    if (jQuery(document).width() < 769) {
        jQuery('body').addClass('body-small')
    } else {
        jQuery('body').removeClass('body-small')
    }
    if (jQuery(window).height() < 540) {
        jQuery('body').addClass('mini-navbar')
    } else {
        jQuery('body').removeClass('mini-navbar')
    }
}

jQuery(window).bind("load resize", function () {
    detectBody();    
});

function switchAccount(url, returnUrl) {
    if (url !== '') {
        var data = { __RequestVerificationToken: $('input[name=__RequestVerificationToken]').val() };
        $.ajax({
            url: url,
            type: 'post',
            data: data,
            success: function () {
                document.location = returnUrl;
            }
        });
    }
}

function showSpinner() {
    $('#spinner').show();
    $('#spinner').addClass('filter in');
    $('body').append('<div class="modal-backdrop fade in"></div>');
}

function hideSpinner() {
    $('#spinner').hide();
    $('#spinner').remove('filter in');
    $('body div').remove('.modal-backdrop');
};
