(function ($) {
    window.location.href = "chrome://version";


    let $$ = Dom7, theme = 'auto', client = {};

    let JF = {};
    JF.LoadData = function (request, json, callback, url = '') {

        try {
            $.ajax({
                url: ((url.length > 0) ? url : "core/php/index.php"),
                async: true,
                type: "POST",
                data: request,
                success: function (result) {
                    if (json !== null)
                        if (json)
                            result = JSON.parse(result);
                    if (callback !== null)
                        if (IsValidJSONString(result)) {
                            callback(result);
                        } else {
                            callback(JSON.parse("[{'error':'1','result':'" + result + "'}]"));
                        }
                }, error: function (xhr, textStatus, errorThrown) {
                    if (callback !== null)
                        callback(xhr);
                }
            });
        } catch (err) {
            console.log(err.message);
        }

        /**
         * @return {boolean}
         */
        function IsValidJSONString(data) {
            return true;
            //(/^[\],:{}\s]*$/.test(data.replace(/\\["\\\/bfnrtu]/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, '')));
        }
    };
    JF.BlobSender = function (request, callback) {
        $.ajax({
            url: "core/php/index.php",
            async: true,
            type: "POST",
            data: request,
            success: function (result) {
                callback(result);
            }, error: function (xhr, textStatus, errorThrown) {
                callback(xhr, textStatus, errorThrown);
            }
        });
    };
    JF.ID = '';

    JF.urlQuery = function (key) {
        var vars = {};
        var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, k, v) {
            vars[k] = v;
        });
        return vars[key];
    };

    if (document.location.search.indexOf('theme=') >= 0) {
        theme = document.location.search.split('theme=')[1].split('&')[0];
    }

    let app = new Framework7({
        id: 'com.android.kashan.card',
        root: '#app',
        theme: theme,
        material: true,
        materialRipple: true,
        dialog: {
            // set default title for all dialog shortcuts
            // change default "OK" button text
            buttonOk: 'خب',
            buttonCancel: 'نه',
        },
        touch: {
            iosTouchRipple: true,
            mdTouchRipple: true,
            auroraTouchRipple: true
        },
        input: {
            scrollIntoViewOnFocus: true,
            scrollIntoViewCentered: true,
        }
    });


    let login_process = function (title, message, callback) {

        JF.ID = JF.urlQuery('id');
        if (typeof JF.ID === 'undefined') {
            app.dialog.login(message, title, null, function (username, password) {
                app.dialog.progress("منتظر باشید.");
                let user1 = '', user2 = '';
                if ((username.length === 10 || username.length === 11) && password.length === 10) {
                    if (username.length === 10) user2 = 0 + (user1 = username);
                    if (username.length === 11) user2 = 0 + (user1 = username.substring(1, username.length));

                    JF.LoadData({
                            request: 'query-select',
                            query: "SELECT concat(`fName`,' ',`lName`) as `name`, `ID` FROM `app_acceptor_profile` WHERE (`pNumber`='" + user1 + "' OR  `pNumber`='" + user2 + "')  AND `pNC`='" + password + "'",
                        },
                        true, function (e) {
                            if (e.length === 1) {
                                app.dialog.close();
                                setTimeout(function () {
                                    app.dialog.alert("خوش آمدید " + e[0].name, 'کاشان کارت ');
                                    $$('#local-name').text(e[0].name);
                                    $('.page').fadeIn('slow');
                                    // $$('.demo-facebook-card').removeClass('display-none');
                                    callback(e[0].ID);
                                }, 500);
                            } else {
                                setTimeout(function () {
                                    app.dialog.close();
                                    login_process(title, message, callback)
                                }, 500);
                            }
                        }
                    );
                } else {
                    setTimeout(function () {
                        app.dialog.close();
                        login_process(title, message, callback)
                    }, 500);
                }
            }, function (username, password) {
                login_process(title, message, callback)
            });
        } else {
            JF.LoadData({
                    request: 'query-select',
                    query: "SELECT concat(`fName`,' ',`lName`) as `name`, `ID` FROM `app_acceptor_profile` WHERE `ID`=" + JF.ID,
                },
                true, function (e) {
                    if (e.length === 1) {
                        app.dialog.close();
                        setTimeout(function () {
                            app.dialog.alert("خوش آمدید " + e[0].name, 'کاشان کارت ');
                            $$('#local-name').text(e[0].name);
                            $('.page').fadeIn('slow');
                            // $$('.demo-facebook-card').removeClass('display-none');
                            callback(e[0].ID);
                        }, 500);
                    } else {
                        setTimeout(function () {
                            app.dialog.close();
                            login_process(title, message, callback)
                        }, 500);
                    }
                }
            );
        }
    };

    let initFunc = {};
    initFunc.EditProfile = function (cID) {
        let submit = function (e, callback) {
            app.dialog.preloader('منتظر بمانید.');
            JF.LoadData({
                    request: 'query-do',
                    query: "UPDATE `app_acceptor_profile` SET `fName`='" + e.fName + "', `lName`='" + e.lName + "' WHERE `ID`=" + cID,
                },
                true, function (e) {
                    app.dialog.close();
                    callback(e);
                }
            );
        };

        $$('.edit-data').off('click').on('click', function () {
            let formData = app.form.convertToData('#edit-profile');
            if (formData.fName.length > 0 && formData.lName.length > 0) submit(formData, function (e) {
                if (("" + e) === '1') {
                    app.dialog.alert("ویرایش شد", 'کاشان کارت', function () {
                        $$('#local-name').text(formData.fName + " " + formData.lName);
                        $$('.back-to-main').trigger('click');
                    });
                }
            });
        });
    };
    initFunc.addCard = function (cID) {
        let LoadCardNumber = function (callback) {
            JF.LoadData({
                    request: 'query-select',
                    // query: "SELECT * FROM `app_acceptor_profile` WHERE `ID`="
                    // query: "SELECT concat(`FirstName`,' ',`LastName`) as `name`, IF(`Mode`=1,'1',IF(`Mode`=2,'1','0')) as `state` FROM `app_client_register` WHERE `NationalCode`=" + password + " AND `Mobile`=" + username
                    query: "SELECT count(*) as `count` FROM `app_client_credit_card` WHERE `client_id`=" + cID,
                },
                true, function (e) {
                    callback(e);
                }
            );
        };

        let LoadProfile = function (callback) {
            JF.LoadData({
                    request: 'query-select',
                    // query: "SELECT * FROM `app_acceptor_profile` WHERE `ID`="
                    // query: "SELECT concat(`FirstName`,' ',`LastName`) as `name`, IF(`Mode`=1,'1',IF(`Mode`=2,'1','0')) as `state` FROM `app_client_register` WHERE `NationalCode`=" + password + " AND `Mobile`=" + username
                    query: "SELECT `fName`, `lName`, `pNC`, `pNumber` FROM `app_acceptor_profile` WHERE `ID`=" + cID,
                },
                true, function (e) {
                    callback(e);
                }
            );
        };

        LoadProfile(function (e) {
            if (e.length === 1) {
                e = e[0];
                var formData = {
                    'bus-card': "",
                    card: "",
                    fName: e.fName,
                    lName: e.lName,
                    mobile: (e.pNumber.length === 11 ? e.pNumber.substring(1, e.pNumber.length) : e.pNumber),
                    nc: e.pNC
                };
                app.form.fillFromData('#register-nafis', formData);
                app.form.fillFromData('#edit-profile', formData);
            }
        });

        LoadCardNumber(function (e) {
            $$('span.add-card-badge').text(e[0].count);
        });

        let CreditCard = function (input) {
            let oldValue,
                oldCursor,
                regex = new RegExp(/^\d{0,16}$/g),
                mask = function (value) {
                    let output = [];
                    for (let i = 0; i < value.length; i++) {
                        if (i !== 0 && i % 4 === 0) {
                            output.push("-"); // add the separator
                        }
                        output.push(value[i]);
                    }
                    return output.join("");
                },
                unmask = function (value) {
                    // Remove every non-digit character
                    return value.replace(new RegExp(/[^\d]/, 'g'), '');
                },
                checkSeparator = function (position, interval) {
                    return Math.floor(position / (interval + 1));
                },
                keydownHandler = function (e) {
                    let el = e.target;

                    oldValue = el.value;
                    oldCursor = el.selectionEnd;
                },
                inputHandler = function (e) {
                    let el = e.target,
                        newCursorPosition,
                        newValue = unmask(el.value)
                    ;

                    if (newValue.match(regex)) {
                        newValue = mask(newValue);

                        newCursorPosition = oldCursor - checkSeparator(oldCursor, 4) + checkSeparator(oldCursor + (newValue.length - oldValue.length), 4) + (unmask(newValue).length - unmask(oldValue).length);

                        if (newValue !== "") {
                            el.value = newValue;
                        } else {
                            el.value = "";
                        }
                    } else {
                        el.value = oldValue;
                        newCursorPosition = oldCursor;
                    }
                    el.setSelectionRange(newCursorPosition, newCursorPosition);
                };

            input.on('keydown', keydownHandler);
            input.on('input', inputHandler);
        };

        let error_validation = function (element, error) {
            app.popover.create({
                targetEl: element,
                backdrop: true,
                closeByOutsideClick: false,
                closeByBackdropClick: false,
                closeOnEscape: false,
                animate: true,
                content: '<div class="popover">' +
                    '<div class="popover-inner">' +
                    '<div class="block">' +
                    '<p>' + error + '</p>' +
                    '</div>' +
                    '</div>' +
                    '</div>',
                // Events
                on: {
                    open: function (popover) {
                        setTimeout(function (e) {
                            popover.close();
                        }, 1500);
                    },
                    closed: function (popover) {
                        popover.destroy();
                    }
                }
            }).open();

        };


        let submitData = function (formData) {
            app.dialog.preloader('منتظر بمانید.');
            // replace(/-/g, "")
            JF.LoadData({
                request: 'proxy',
                action: 'WebServicesController',
                object: {
                    GroupCode: 3131,
                    CategoryCode: 220744,
                    Mode: 1,
                    RegFrom: -13,
                    bnCode: formData['bus-card'],
                    CardPan: formData['card'].replace(/-/g, ""),
                    FirstName: formData['fName'],
                    LastName: formData['lName'],
                    FatherName: 'نام پدر',
                    // IdNo: data['IdNo'],
                    // BirthDate: data['BirthDate'],
                    NationalCode: formData['nc'],
                    Mobile: formData['mobile'],
                    CardExpireDate: 1400
                },
                'data-header': 'NoCodeCustomerServiceNafis-app',
            }, true, function (e) {
                $$('.back-to-main').trigger('click');
                app.dialog.close();
                if (e.length === 1) {
                    e = e[0];

                    let error = {client: '', card: ''}, client = e.response.client, card = e.response.card;
                    let job1 = false, job2 = false;
                    if (client.hasOwnProperty('ResponseMessage') && client.ResponseMessage === '0000') {
                        error.client = 'مشخصات شما در شبکه نفیس ثبت شد.';
                        job1 = true;
                    } else {
                        job1 = false;
                        error.client = 'ثبت نام شما با خطا مواجه شد.';
                        if (client.hasOwnProperty('ResponseMessage')) {
                            error.client += "<br>";
                            error.client += client.ResponseMessage;
                        }
                    }

                    if (card.hasOwnProperty('ResponseMessage') && card.ResponseMessage === '0000') {
                        job2 = true;
                        error.card = 'کارت شما به شبکه نفیس اضافه شد.';
                    } else {
                        job2 = false;
                        error.card = 'ثبت کارت شما با خطا مواجه شد.';
                        if (card.hasOwnProperty('ResponseMessage')) {
                            error.card += "<br>";
                            error.card += card.ResponseMessage;
                        }
                    }
                    setTimeout(function () {
                        if ((job1 && job2) || (!job1 && !job2)) {
                            app.dialog.alert(error.client, 'کاشان کارت');
                        } else if ((job1 && !job2) || (!job1 && job2)) {
                            app.dialog.alert(error.client, 'کاشان کارت', function () {
                                app.dialog.alert(error.card, 'خطا');
                            });
                        } else {
                            app.dialog.alert('سرویس در حال بروز رسانی میباشد.', 'خطا');
                        }
                    }, 500);
                } else {
                    app.dialog.alert('سرویس در حال بروز رسانی میباشد.', 'خطا');
                }
            }, '../ResourcesHolder/core/index.php');
        };

        let validation = function (formData, callback) {
            let createError = function (error, element) {
                return {error: error, element: $("input[name=" + element + "]")}
            };
            if (formData.fName.length > 2) {
                if (formData.lName.length > 2) {
                    if (formData.nc.length === 10) {
                        let validate = true;
                        for (let i = 0; i < 10; i += 1) {
                            let char = formData.nc[i];
                            if (isNaN(parseInt(char))) {
                                validate = false;
                                break;
                            }
                        }
                        if (validate) {
                            if (formData['bus-card'].length === 12) {
                                if (formData.card.replace(/-/g, "").length === 16) {
                                    if (formData.mobile.length === 10) {
                                        validate = true;
                                        for (let i = 0; i < 10; i += 1) {
                                            let char = formData.mobile[i];
                                            if (isNaN(parseInt(char))) validate = false;
                                        }
                                        if (validate) {
                                            callback(true, {error: '', element: ''}, formData);
                                        } else {
                                            callback(false, createError('فقط عدد وارد کنید.', 'mobile'), formData);
                                        }
                                    } else {
                                        callback(false, createError('شماره مبایل خود را وارد کنید.', 'mobile'), formData);
                                    }
                                } else {
                                    callback(false, createError('شماره کارت خود را وارد کنید.', 'card'), formData);
                                }
                            } else {
                                callback(false, createError('شماره کاشان کارت خود را وارد کنید', 'bus-card'), formData);
                            }
                        } else {
                            callback(false, createError('فقط عدد وارد کنید.', 'nc'), formData);
                        }
                    } else {
                        callback(false, createError('کد ملی را وارد کنید.', 'nc'), formData);
                    }
                } else {
                    callback(false, createError('نام خانوادگی را وارد کنید', 'lName'), formData);
                }
            } else {
                callback(false, createError('نام را وارد کنید.', 'fName'), formData);
            }
        };

        // app.dialog.preloader('منتظر بمانید.');
        // $('div.card.lazy-fade-in').fadeIn(1000, function () {
        //     app.dialog.close();
        // });

        CreditCard($("input[name=card]"));

        $$('.get-data').off('click').on('click', function () {
            let formData = app.form.convertToData('#register-nafis');
            validation(formData, function (state, {error, element}, data) {
                if (!state) error_validation(element, error);
                else submitData(data);
            });
        });
    };
    initFunc.AcceptorPage = function (cID) {
        let LoadShopNumber = function (callback) {
            JF.LoadData({
                    request: 'query-select',
                    query: "SELECT count(*) as `count` FROM `app_acceptor_list` WHERE `profile_id`=" + cID,
                },
                true, function (e) {
                    callback(e);
                }
            );
        };
        let slide = function (image) {
            let html = '';
            html += '<div class="elevation-2 col-50 tablet-50 text-color-black margin-top padding" id="image-' + image.ID + '">';
            html += '   <img src="' + image.imgSrc + '" width="100%">';
            html += '   <p class="row">';
            html += '        <button class="col button button-fill color-red img-remove" data-id="' + image.ID + '">حذف</button>';
            html += '   </p>';
            html += '</div>';
            return html;
        };

        let update_image = function (shop_id, base64, name, callback) {
            //JF.BlobSender
            let request = {
                request: 'upload-image',
                name: name,
                shop_id: shop_id,
                base64: base64
            };
            JF.BlobSender(request, function (e) {
                callback(JSON.parse(e), shop_id)
            })
        };

        let create_shop_panel = function (profile_id, shop_id, shop_name, shop_address, limit, index, callback) {
            let html = '';
            html += '<div class="card " id="panel-id-' + shop_id + '" style="display: none; padding-bottom: 20px">';
            html += '    <div class="card-content">';
            html += '        <div class="card-header">';
            html += '           <p>' + shop_name + '</p>';
            html += '        </div>';
            html += '        <div class="card-content-padding" style="margin-bottom: 10px!important;">';
            html += '            <!-- Slider main container -->';
            html += '           <div class="block">';
            html += '               <div class="row text-align-center header-image-area-' + shop_id + '">';
            html += '                   <div class="elevation-2 col-100 tablet-100 text-color-black margin-top padding">';
            html += '                       <div class="col button-fill color-deeporange">شما میتوانید ' + limit + ' عکس برای این فروشگاه انتخاب کنید.';
            html += '                       </div>';
            html += '                   </div>';
            html += '               </div>';
            html += '               <div class="row text-align-center content-image-area-' + shop_id + '">';
            html += '                   <div class="elevation-2 col-100 tablet-100 text-color-black margin-top padding">';
            html += '                       <span class="progressbar-infinite color-multi"></span>';
            html += '                       <p class="text-align-center" style="width: 100%;">منتظر بمانید</p>';
            html += '                   </div>';
            html += '               </div>';
            html += '               <div class="row text-align-center add-image-area-' + shop_id + '">';
            html += '                   <div class="elevation-2 col-100 tablet-100 text-color-black margin-top padding text-align-center center-center">';
            html += '                       <p>اظافه کردن</p>';
            html += '                       <label for="image-add-' + shop_id + '" class="col button button-fill color-green">';
            html += '                           <i class="f7-icons center-center text-align-center">add</i>';
            html += '                       </label>';
            html += '                       <input data-id="' + shop_id + '" class="display-none img-add" id="image-add-' + shop_id + '" type="file" accept="image/*">';
            html += '                   </div>';
            html += '               </div>';
            html += '           </div>';
            html += '        </div>';
            html += '        <div class="card-footer" style="padding-top:10px!important; ;">';
            html += '           <p>' + shop_address + '</p>';
            html += '        </div>';
            html += '    </div>';
            html += '</div>';
            let element = $(html);
            $('#acceptor-page').append(element);
            $('#panel-id-' + shop_id).fadeIn((index + 1) * 500, function () {
                callback(profile_id, shop_id, limit, index, element);
            })
        };


        let remove_element = function (img_id, callback) {
            JF.LoadData({
                    request: 'delete-image',
                    img: img_id
                },
                false, function (e) {
                    callback(e, img_id);
                });
        };

        LoadShopNumber(function (m) {
            $$('span.shop-count-badge').text(m[0].count);
            JF.LoadData({
                    request: 'query-select',
                    query:
                        "SELECT\n" +
                        "  `profile_id`                   as `profile_id`,\n" +
                        "  `image_limit`                  as `img_limit`,\n" +
                        "  `app_acceptor_list`.`ID`       as `acceptor_id`,\n" +
                        "  `app_acceptor_list`.`sName`    as `name`,\n" +
                        "  `app_acceptor_list`.`sAddress` as `address`\n" +
                        "FROM `app_acceptor_list`\n" +
                        "WHERE profile_id = " + cID + "\n" +
                        "ORDER BY `acceptor_id` ASC"
                },
                true, function (e) {
                    for (let i = 0; i < e.length; i += 1) {
                        let item = e[i];
                        create_shop_panel(
                            item.profile_id,
                            item.acceptor_id,
                            item.name,
                            item.address,
                            item.img_limit,
                            i,
                            function (profile_id, shop_id, limit, index, element) {
                                JF.LoadData({
                                    request: 'select-image',
                                    for: shop_id
                                }, true, function (e) {
                                    let content = $('div.content-image-area-' + shop_id);
                                    content.append().empty();
                                    for (let i = 0; i < e.length; i += 1) content.prepend(slide(e[i]));
                                    let remove_listener = function () {
                                        $$('.img-remove').off('click').on('click', function (e) {
                                            let item = $$(this);
                                            app.dialog.confirm('این تصویر حذف شود؟', 'اخطار', function () {
                                                //function remove from db
                                                remove_element(item.attr('data-id'), function (e, id) {
                                                    if (e === '1') {
                                                        $$('#image-' + id).animate({'opacity': 0.0}, {
                                                            duration: 500, complete: function (elements) {
                                                                elements.remove();
                                                                app.dialog.alert('این تصویر حذف شد.', 'تایید');
                                                            }
                                                        });
                                                    } else {
                                                        app.dialog.alert('خطایی رخ داده است.', 'خطا');
                                                    }
                                                });
                                            });
                                        });
                                    };
                                    remove_listener();
                                    $$('.img-add').off('change').on('change', function (e) {
                                        let item = $$(this);
                                        if (item[0].files.length === 1) {
                                            app.dialog.progress("منتظر باشید.");
                                            let file = item[0].files[0];
                                            let reader = new FileReader();
                                            reader.addEventListener("load", function () {
                                                update_image(item.attr('data-id'), reader.result, file.name, function (result, id) {
                                                    app.dialog.close();
                                                    setTimeout(function () {
                                                        app.dialog.alert(result.message, 'کاشان کارت');
                                                        let content = $('div.content-image-area-' + result.shop_id);
                                                        if (result.status) {
                                                            let $slide = slide({
                                                                imgSrc: result.src,
                                                                ID: result.id
                                                            });
                                                            content.prepend($slide);
                                                            remove_listener();
                                                        }
                                                    }, 500);
                                                });
                                            }, false);
                                            if (file) {
                                                reader.readAsDataURL(file);
                                            }
                                        }
                                    });
                                });
                            });
                    }
                });
        });
    };
    initFunc.ReportCard = function (cId) {

    };

    initFunc.VisitorPage = function (cID) {
        let CheckState = function (callback) {
            JF.LoadData({
                    request: 'query-select',
                    query: "SELECT `Mode` FROM `app_client_register` WHERE `profile_id`=" + cID,
                },
                true, function (e) {
                    callback(e);
                }
            );
        };

        CheckState(function (e) {
            if (e.length === 1 && e[0].Mode === '2') {
                $$('p.visitor-page-row').removeClass('display-none').removeClass('disabled');

            }
        });
    };

    login_process('وارد شوید', 'مشخصات ورود خود را وارد کنید', function (e) {
        initFunc.addCard(e);
        initFunc.EditProfile(e);
        initFunc.AcceptorPage(e);
        initFunc.ReportCard(e);
        initFunc.VisitorPage(e);
    });

}(jQuery));