var constants = {
    group: {
        3: {
            kinds: [
                {
                    id: 1,
                    name: 'Simplu'
                },
            ]
        },
        1: {
            kinds: [
                {
                    id: 1,
                    name: 'Simplu'
                },
            ]
        },
        4: {
            kinds: [
                {
                    id: 1,
                    name: 'Simplu'
                },
                {
                    id: 3,
                    name: 'UNEJ'
                }
            ]
        },
        2: {
            kinds: [
                {
                    id: 1,
                    name: 'Simplu'
                },
                {
                    id: 2,
                    name: 'LTD'
                }
            ]
        },

        5: {
            kinds: [
                {
                    id: 1,
                    name: 'Simplu'
                },
                {
                    id: 2,
                    name: 'LTD'
                }
            ]
        }
    },
    kindNames: {
        1: 'Simplu',
        2: 'LTD',
        3: 'UNEJ'
    }
};

var kalOpt = {
    months: 4,
    mode: 'multiple',
    weekStart: 1,
    direction: 'future',
    directionScrolling: true,
    useYearNav: false,
    blackout: function (date) {
        var dateFmt = 'YYYY-MM-DD';
        var date = Kalendae.moment(date).startOf('day');
        var shortDate = date.format(dateFmt);
        var day = date.day();

        var publicationID = this.settings.publicationID;
        var publication = ko.utils.arrayFirst(app.publications(), function (e) {
            return e.id() === publicationID;
        });

        if (!publication) {
            return [1, 0, 0, 0, 0, 0, 0][day];
        }

        var disabledWeekDays = publication.disabledWeekDays();
        for (var i = 0; i < disabledWeekDays.length; i++) {
            if (disabledWeekDays[i] == day) {
                return true;
            }
        }

        var disabledDates = publication.disabledDates();
        for (var i = 0; i < disabledDates.length; i++) {
            if (disabledDates[i].split('T')[0] == shortDate) {
                return true;
            }
        }

        return false;
    }
};

var PublicationModel = function (data) {
    ko.mapping.fromJS(data, {}, this);
    var self = this;

    self.selected = ko.observable(false);
    self.columns = ko.observableArray([]);
    self.columnID = ko.observable(0);
    self.optionIDs = ko.observableArray([]);
    self.dates = ko.observableArray([]);
    self.pubName = data.name;
    self.distribution = ko.pureComputed(function () {
        return self.type() == 1 ? 'National' : 'Local';
    });
    self.price = ko.observable({'total': '0', 'vat': '0', 'base': '0'});

    self.isPristine = function () {
        return (self.dates().length && self.columnID());
    };

    self.options = ko.pureComputed(function () {
        var selectedColumn = ko.utils.arrayFilter(self.columns(), function (column) {
            return column.id == self.columnID();
        });

        return selectedColumn.length ? selectedColumn[0].options : [];
    }, self).extend({notify: 'always'});

    self.columnName = ko.pureComputed(function () {
        var selectedColumn = ko.utils.arrayFilter(self.columns(), function (column) {
            return column.id == self.columnID();
        });

        return selectedColumn[0].name;

    }, self).extend({notify: 'always'});

    self.columnID.subscribe(app.getSummary);
    self.optionIDs.subscribe(app.getSummary);
    self.dates.subscribe(function () {
        if (self.dates().length == 0) {
            self.price({'vat': '0', 'base': '0', 'total': '0'});
        }

        app.getSummary();
    });

    self.columnID.subscribe(function () {
        self.optionIDs([]);
    });

    self.optionStr = ko.pureComputed(function () {
        var optionNames = [];
        ko.utils.arrayForEach(self.optionIDs(), function (sopt) {
            ko.utils.arrayForEach(self.options(), function (opt) {
                if (sopt == opt.id) {
                    optionNames.push(opt.name);
                }
            });
        });
        return optionNames.join(', ');
    });

    self.columnStr = function () {
        ret = '';
        ko.utils.arrayForEach(self.columns(), function (col) {
            if (col.id == self.columnID()) {
                ret = col.name;
            }
        });

        return ret ? ret : '';
    };

    self.datesStr = ko.pureComputed(function () {
        var sDates = '';
        ko.utils.arrayForEach(self.dates(), function (date) {
            sDates = sDates + moment(date).format('D-M-Y, ');
        });

        sDates = sDates.trim();
        if (sDates.length > 0 && sDates.charAt(sDates.length - 1) == ',') {
            sDates = sDates.substr(0, sDates.length - 1);
        }

        return sDates;
    });

    self.selected.subscribe(function (isSelected) {
        app.getSummary();
        if (isSelected && self.columns().length == 0) {
            $.get('/columns/' + self.id()).done(function (data) {
                self.columns(data);
                if (self.columns().length == 0) {
                    return;
                }

                $('select').material_select('destroy');
                $('select').material_select();

                kalOpt.publicationID = self.id();
                var k = new Kalendae('cal' + self.id(), kalOpt);
                k.subscribe('change', function (date) {
                    app.text.pauseNotifications = true;
                    $('#textarea1').blur();
                    app.text.pauseNotifications = false;

                    self.dates(this.getSelectedAsDates());
                });
            });
        }
    });
}

var Application = function () {
    var self = this;

    // my vars
    self.isLoggedIn = ko.observable(false);
    self.adType = ko.observable(2);
    self.kinds = ko.observableArray([]);
    self.selectedKind = ko.observable();
    self.invoicePerAd = ko.observable(true);
    self.groupId = ko.observable(0);
    self.kindNames = constants.kindNames;
    self.quoteFile = ko.observable({});
    // end of  my vars

    self.text = ko.observable('');
    self.words = ko.observable(0);
    self.publications = ko.observableArray([]);
    self.price = ko.observable({});
    self.finalStep = ko.observable(false);

    self.firstName = ko.observable('');
    self.lastName = ko.observable('');
    self.address = ko.observable('');
    self.company = ko.observable('');
    self.vat = ko.observable('');
    self.crn = ko.observable('');
    self.phone = ko.observable('');
    self.email = ko.observable('');
    self.nin = ko.observable('');
    self.bank = ko.observable('');
    self.iban = ko.observable('');
    self.contactValid = ko.observable(false);

    // my functions
    self.isPristineQuote = function () {
        return self.adType() && self.contactValid() && Object.keys(self.quoteFile()).length != 0;
    };

    self.selectedKind.subscribe(function () {
        if (self.selectedKind() == 3) {
            ko.utils.arrayForEach(self.publications(), function (publication) {
                if (publication.id() == jenuPublication) {
                    publication.selected(true);
                } else {
                    publication.selected(false);
                }
            });
        } else {
            ko.utils.arrayForEach(self.publications(), function (publication) {
                publication.selected(false);
            });

            $(".collapsible > li:first-child .collapsible-header").trigger("click");
        }
    });

    self.doFinalQuote = function () {
        if (self.isPristineQuote() && self.selected().length) {
            $(".quote-btn-create").addClass("disabled").text("Asteptati...");
            var adObj = {
                columns: [],
                selectedKind: self.selectedKind(),
                invoicePerAd: self.invoicePerAd(),
                groupId: self.groupId()
            };


            ko.utils.arrayForEach(self.selected(), function (pub) {
                var days = [];
                var options = [];

                ko.utils.arrayForEach(pub.optionIDs(), function (id) {
                    options.push({'OptionID': id});
                });

                ko.utils.arrayForEach(pub.dates(), function (date) {
                    days.push({'Date': moment(date).format('YYYY-MM-DDT00:00:00[Z]')});
                });

                if (pub.isPristine()) {
                    adObj.columns.push({
                        'PublicationID': pub.id(),
                        'publicationName': pub.name(),
                        'ColumnID': pub.columnID(),
                        'columnName': pub.columnName(),
                        'Options': options,
                        'Days': days,
                    });
                }
            });

            var name = (self.company() != '') ? self.company() :
                self.firstName() + ' ' + self.lastName();

            adObj['contact'] = {
                name: name,
                type: self.company() != '' ? 2 : 1,
                firstName: self.firstName(),
                lastName: self.lastName(),
                address: self.address(),
                phone: self.phone(),
                email: self.email(),
                vat: self.vat(),
                nin: self.nin(),
                crn: self.crn(),
                bank: self.bank(),
                iban: self.iban()
            };

            if (!Object.keys(self.quoteFile()).length) {
                return;
            }

            adObj["file"] = self.quoteFile();


            var formData = new FormData();
            formData.append("columns", JSON.stringify(adObj.columns));
            formData.append("selectedKind", adObj.selectedKind);
            formData.append("contact", JSON.stringify(adObj.contact));
            formData.append("quoteFile", adObj.file);
            formData.append("invoicePerAd", adObj.invoicePerAd);
            formData.append("groupID", adObj.groupId);

            $.ajax({
                type: "POST",
                url: "/quotation",
                processData: false,
                contentType: false,
                data: formData,
                success: function (resp) {
                    if (resp.success) {
                        //redirect here to the user account
                        window.location = '/contul-meu';
                    }
                },
            });
        }
    };
    // end of my functions

    self.buildSummary = function () {
        var obj = {
            text: self.text(), columns: [],
        };

        ko.utils.arrayForEach(self.selected(), function (pub) {
            var days = [];
            var options = [];

            ko.utils.arrayForEach(pub.optionIDs(), function (id) {
                options.push({'OptionID': id});
            });

            ko.utils.arrayForEach(pub.dates(), function (date) {
                days.push({'Date': moment(date).format('YYYY-MM-DDT00:00:00[Z]')});
            });

            if (pub.isPristine()) {
                obj.columns.push({
                    'PublicationID': pub.id(),
                    'ColumnID': pub.columnID(),
                    'Options': options,
                    'Days': days
                });
            }
        });

        return obj;
    };

    self.createDraft = function () {
        var obj = self.buildSummary();
        var name = (self.company() != '') ? self.company() :
            self.firstName() + ' ' + self.lastName();

        obj['contact'] = {
            name: name,
            type: self.company() != '' ? 2 : 1,
            firstName: self.firstName(),
            lastName: self.lastName(),
            address: self.address(),
            phone: self.phone(),
            email: self.email(),
            vat: self.vat(),
            nin: self.nin(),
            crn: self.crn(),
            bank: self.bank(),
            iban: self.iban()
        };

        var payButton = $('.pay-ad');
        var doPayment = function (data) {
            $.each(data, function (k, v) {
                $('#payForm input[name=' + k + ']').attr('value', v);
            });

            payButton.removeAttr('disabled');
            $('#payForm').submit();
        };

        payButton.attr('disabled', 'disabled');
        $.ajax({
            type: 'POST',
            url: '/createDraft',
            dataType: 'json',
            contentType: 'application/json;charset=utf-8',
            data: JSON.stringify(obj),
            success: function (data) {
                var id = data.ad_id;
                if (!id) {
                    payButton.removeAttr('disabled');
                    return;
                }

                var uploader = $('#image-upload').prop('jFiler');

                if (!uploader.files || uploader.files.length == 0) {
                    doPayment(data);
                    return;
                }

                formData = new FormData();
                formData.append('id', id);
                formData.append('file', uploader.files[0]);

                $.ajax({
                    url: '/uploadImage',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function () {
                        doPayment(data);
                    },
                    error: function (data) {
                        payButton.removeAttr('disabled');
                    }
                });
            },
            error: function (data) {
                payButton.removeAttr('disabled');
            }
        });
    };

    self.isPristine = ko.computed(function () {
        return self.price().total !== '0' && self.contactValid();
    });

    self.doFinal = function () {
        if (self.isPristine() && self.selected().length) {
            self.finalStep(true);
        }
    };

    self.selected = function () {
        return ko.utils.arrayFilter(self.publications(), function (publication) {
            return publication.selected();
        });
    };

    self.addTooltip = function (els) {
        $('label[for="' + els[1].id + '"]').tooltip();
    };

    self.resetPrice = function () {
        ko.utils.arrayForEach(self.selected(), function (pub) {
            pub.price({'vat': '0', 'base': '0', 'total': '0'});
        });

        self.price({'vat': '0', 'base': '0', 'total': '0'});
        self.finalStep(false);
    };

    self.getSummary = function () {
        if (!self.text().length) {
            self.words('0');
            self.resetPrice();
            return;
        }

        if (!self.selected().length) {
            self.resetPrice();
            return;
        }

        var obj = self.buildSummary();
        if (!obj.columns.length) {
            self.resetPrice();
            return;
        }

        $.ajax({
            type: 'POST',
            url: '/summary',
            dataType: 'json',
            contentType: 'application/json;charset=utf-8',
            data: JSON.stringify(obj),
            success: function (data) {
                self.price(data.price);
                self.words(data.words);

                ko.utils.arrayForEach(data.columns, function (column) {
                    ko.utils.arrayForEach(self.selected(), function (pub) {
                        if (column.id === pub.id()) {
                            pub.price(column.price);
                            return;
                        }
                    });
                });
            },
        });
    };

    self.text.subscribe(self.getSummary);
};

Application.prototype = function () {
    return {
        getPublications: function () {
            var self = this;
            $.get('/listing', function (data) {
                ko.mapping.fromJS(data, {
                    create: function (options) {
                        return new PublicationModel(options.data);
                    }
                }, self.publications);

                // just testing for viata libera
                // var pub = self.publications()[3];
                // self.publications.removeAll();
                // self.publications.push(pub);

                if (self.publications().length == 1) {
                    self.publications()[0].selected(true);
                }
            });
        },
        getUserProfile: function () {
            var self = this;
            $.get('/users/profile', function (resp) {
                var profile = resp.data;

                // date personale
                self.firstName(profile.contact.firstName);
                self.lastName(profile.contact.lastName);
                self.address(profile.contact.address);
                self.email(profile.contact.email);
                self.nin(profile.contact.nin);
                self.phone(profile.contact.phone);

                // date companie
                self.company(profile.group.contact.name);
                self.groupId(profile.group.id);
                self.vat(profile.group.contact.vat);
                self.iban(profile.group.contact.iban);
                self.bank(profile.group.contact.bank);
                self.crn(profile.group.contact.crn);

                self.invoicePerAd(profile.group.invoiceInterval);

                if (self.invoicePerAd() != 0) {
                    $("#date_persoana input").prop("disabled", "disabled");
                    self.contactValid(true);
                }

                if (constants.group[profile.group.type]) {
                    self.kinds(constants.group[profile.group.type].kinds);
                    $('select').material_select();
                }
            });
        }
    };
}();

function gotostep(step) {
    $('#' + step).click();
}

var app = new Application();
app.getPublications();

ko.bindingHandlers.visible = {
    init: function (element, valueAccessor) {
        var value = valueAccessor();
        $(element).toggle(ko.unwrap(value));
    },
    update: function (element, valueAccessor) {
        var value = valueAccessor();
        ko.unwrap(value) ? $(element).slideDown('fast') :
            $(element).slideUp('fast');
    }
};

ko.applyBindings(app);

$(document).ready(function () {
    var isLoggedIn = !!$("#loggedInUser").val();

    if (isLoggedIn) {
        app.isLoggedIn(isLoggedIn);
        app.getUserProfile();
    }


    $('.tabs').tabs();

    $('.button-collapse').sideNav();

    $('.slider').slider({
        full_width: true,
        indicators: true,
        height: 170
    });

    $('.modal').modal();

    $('#do-payment').on('click', function (e) {
        $('#date_persoana').submit();
    });


    $('#image-upload-quote').filer({
        limit: 1,
        maxSize: 10,
        fileMaxSize: 10,
        // extensions: ['jpg', 'png'],
        changeInput: false,
        // showThumbs: true,
        // appendTo: '.image-preview-summary',
        // templates: {
        //     box: '<div class="thumb-preview jFiler-items-grid"></div>',
        //     item: '<div class="thumb-preview-item jFiler-item">\
        //         <div class="jFiler-item-container">\
        //         <div class="jFiler-item-thumb">\
        //         {{fi-image}}\
        //     </div>\
        //         </div>\
        //         </div>',
        //     itemAppendToEnd: false,
        //     canvasImage: false,
        //     removeConfirmation: true,
        //     _selectors: {
        //         list: '.thumb-preview',
        //         item: '.thumb-preview-item',
        //     }
        // },
        captions: {
            button: 'Choose Files',
            feedback: 'Choose files To Upload',
            feedback2: 'files were chosen',
            drop: 'Drop file here to Upload',
            removeConfirmation: 'Are you sure you want to remove this file?',
            errors: {
                filesLimit: 'Nu puteti incarca mai mult de o imagine.',
                // filesType: 'Numai fisiere JPG si PNG sunt permise.',
                filesSize: '{{fi-name}} este prea mare! Puteti incarca imagini de maxim {{fi-fileMaxSize}} MB.',
                filesSizeAll: 'Fisierele alese sunt prea mari! Puteti incarca imagini de maxim {{fi-maxSize}} MB.',
                folderUpload: 'Nu puteti incarca directoare.'
            }
        },
        onSelect: function (f) {
            app.quoteFile(f);
        },
        onRemove: function () {
            app.quoteFile({});
        }
    });

    $('#image-upload').filer({
        limit: 1,
        maxSize: 10,
        fileMaxSize: 10,
        extensions: ['jpg', 'png'],
        changeInput: false,
        showThumbs: true,
        appendTo: '.image-preview-summary',
        templates: {
            box: '<div class="thumb-preview jFiler-items-grid"></div>',
            item: '<div class="thumb-preview-item jFiler-item">\
                <div class="jFiler-item-container">\
                <div class="jFiler-item-thumb">\
                {{fi-image}}\
            </div>\
                </div>\
                </div>',
            itemAppendToEnd: false,
            canvasImage: false,
            removeConfirmation: true,
            _selectors: {
                list: '.thumb-preview',
                item: '.thumb-preview-item',
            }
        },
        captions: {
            button: 'Choose Files',
            feedback: 'Choose files To Upload',
            feedback2: 'files were chosen',
            drop: 'Drop file here to Upload',
            removeConfirmation: 'Are you sure you want to remove this file?',
            errors: {
                filesLimit: 'Nu puteti incarca mai mult de o imagine.',
                filesType: 'Numai fisiere JPG si PNG sunt permise.',
                filesSize: '{{fi-name}} este prea mare! Puteti incarca imagini de maxim {{fi-fileMaxSize}} MB.',
                filesSizeAll: 'Fisierele alese sunt prea mari! Puteti incarca imagini de maxim {{fi-maxSize}} MB.',
                folderUpload: 'Nu puteti incarca directoare.'
            }
        }
    });

    $('.image-preview-summary').on('DOMNodeInserted', 'img', function () {
        var img = $('.image-preview-summary img').clone();
        $('.image-preview-finalize').empty().append(img);
    });

    $('.btn-delete-image').click(function () {
        var el = $('#image-upload');
        el.prop('jFiler').reset();
        $('#file-path-name').val('');
        $('.image-preview-finalize img').remove();
    });

    $.validate({
        lang: 'ro',
        form: '#date_persoana',
        scrollToTopOnError: true,
        modules: 'html5',
        modules: 'sanitize',
        modules: 'security',
        modules: 'sepa',
        onError: function ($form) {
            return false;
        },
        onSuccess: function ($form) {
            return false;
        },
        onElementValidate: function (valid, $el, $form, errorMess) {
            if (!app.invoicePerAd()) {
                app.contactValid(true);
            } else {
                app.contactValid(valid);
            }
        }
    });

});
