﻿/*
* TCore
* @version: 1.0.0 (2021)
* @requires: jQuery v3.0 or later
* @author: TORANJDATA
* @event-namespace: .TCore
* @license: www.toranjnet.com
* Copyright 2021 TORANJDATA
*/
'use strict';

$.extend({
    tc: {
        init: function () {
            $(document).ready(function () {
                var handleAjaxTemplate = function () {
                    $.each($("[data-innerload]"), function () {
                        $.tc.remote($(this), $(this).attr("data-innerload"));
                    })
                };
                handleAjaxTemplate();
            });
        },

        btnLoading: function (status, $btn) {
            var loading = $btn.attr('data-loading-text') !== '' ? $btn.attr('data-loading-text') : 'loading...',
                $label = $btn.find('.btn--label'),
                label = $label.html(),
                data = $btn.data();

            if (status != null) {
                if (status == 'loading') {
                    $btn.addClass('disabled');
                    $label.addClass('loading');
                    $btn.attr('data-btn-label', label);
                    $label.html(loading);

                } else if ((status == 'reset')) {
                    $btn.removeClass('disabled');
                    $label.removeClass('loading');
                    $label.html($btn.attr('data-btn-label'));
                }
            }
        },

        remote: function ($pnl, url) {
            //$pnl.empty();
            $pnl.load(url);
        },

        timers: function (element, stop, callback) {

            callback = callback || function () { };
            return element.each(function () {
                var countdown = $('.countdown').text(),
                    interval = 1000;

                var timers = setInterval(function () {
                    var timer = countdown.split(':');
                    //by parsing integer, I avoid all extra string processing
                    var minutes = parseInt(timer[0], 10);
                    var seconds = parseInt(timer[1], 10);
                    --seconds;
                    minutes = (seconds < 0) ? --minutes : minutes;
                    seconds = (seconds < 0) ? 59 : seconds;
                    seconds = (seconds < 10) ? '0' + seconds : seconds;
                    //minutes = (minutes < 10) ?  minutes : minutes;
                    $('.countdown').html(minutes + ':' + seconds);
                    if (minutes < 0) {
                        clearInterval(timers);
                        callback();
                    }

                    //check if both minutes and seconds are 0
                    if ((seconds <= 0) && (minutes <= 0)) {
                        clearInterval(timers);
                        callback();
                    }
                    countdown = minutes + ':' + seconds;

                    if (stop == true) {
                        clearInterval(timers);
                        callback();
                    }

                }, interval);



            });
        },

        userValidtion: function (form) {
            function checkMelliCode(meli_code) {
                if (meli_code.length == 10) {
                    if (meli_code == '1111111111' || meli_code == '0000000000' || meli_code == '2222222222' || meli_code == '3333333333' || meli_code == '4444444444' || meli_code == '5555555555' || meli_code == '6666666666' || meli_code == '7777777777' || meli_code == '8888888888' || meli_code == '9999999999') {
                        return false;
                    }
                    var c = parseInt(meli_code.charAt(9));
                    var n = parseInt(meli_code.charAt(0)) * 10 +
                        parseInt(meli_code.charAt(1)) * 9 +
                        parseInt(meli_code.charAt(2)) * 8 +
                        parseInt(meli_code.charAt(3)) * 7 +
                        parseInt(meli_code.charAt(4)) * 6 +
                        parseInt(meli_code.charAt(5)) * 5 +
                        parseInt(meli_code.charAt(6)) * 4 +
                        parseInt(meli_code.charAt(7)) * 3 +
                        parseInt(meli_code.charAt(8)) * 2;
                    var r = n - parseInt(n / 11) * 11;
                    if ((r == 0 && r == c) || (r == 1 && c == 1) || (r > 1 && c == 11 - r)) {
                        return true;
                    }
                    else {
                        return false;
                    }
                }
                else {
                    return false;
                }
            };

            $.validator.addMethod("NationalCode", function (value, element) {
                if (value.length == 0) {
                    return true;
                } else {

                    return checkMelliCode(value);
                }

            }, "فرمت صحیح شماره ملی را وارد نمایید");

            $.validator.addMethod("CityName", function (value, element) {

                if ($(element).attr('aria-required') && (value == $(element).parents('.row').find('#StateName').val())) {
                    return false;
                } else {
                    return true;
                }
            }, " این فیلد الزامی می باشد");
            // check validation
            $(form).validate({
                errorClass: 'is-invalid text-danger',
                errorElement: 'span',
                errorPlacement: function (error, element) {
                    if (element.attr("name") == "Website") {
                        element.parent(".input-group").after(error);
                    } else if (element.attr("name") == "Location") {
                        element.parents(".form-group").find('.leaflet').after(error);
                    } else if (element.attr("name") == "PhotoUrl") {
                        element.parents("#Registration").find('.FileUploader').after(error);
                    } else if (element.parents('.input-group').length > 0) {
                        element.parents(".input-group").after(error);
                    } else {
                        element.after(error)
                    }
                },
                rules: {
                    Email: {
                        email: true,
                        remote: {
                            url: "/AjaxLibrary/Public.aspx?act=UserCheck",
                            type: "post",
                            data: {
                                key: "email",
                                value: function () {
                                    return $('#Email').val();
                                },
                                oldValue: function () {
                                    return $('#Email').attr("data-current-email");
                                }
                            },
                        },
                    },
                    CellPhone: {
                        pattern: "09[0-9]{9}", //--> 09(1[0-9]|3[1-9]|2[1-9])-?[0-9]{3}-?[0-9]{4}  
                        remote: {
                            url: "/AjaxLibrary/Public.aspx?act=UserCheck",
                            type: "post",
                            data: {
                                key: "cellphone",
                                value: function () {
                                    return $('#CellPhone').val();
                                },
                                oldValue: function () {
                                    return $('#CellPhone').attr("data-current-cellphone");
                                }
                            },
                        },
                    },
                    NationalCode: {
                        NationalCode: true,
                    },
                    CityName: {
                        CityName: true
                    }


                },
                // Specify validation error messages
                messages: {
                    Email: {
                        remote: "ایمیل قبلا ثبت گردیده است",
                    },
                    CellPhone: {
                        pattern: "فرمت شماره همراه صحیح نمی باشد. نمونه صحیح: 09121101212",
                        remote: "شماره همراه قبلا ثبت گردیده است",
                    },
                }
            });

            return form.valid();
        },

        initLocation: function () {
            var GetLocation = function (id) {

                $.ajax({
                    url: "/AjaxLibrary/public.aspx?act=LocationsByParent",
                    type: "POST",
                    data: { "LocationID": id },
                    success: function (result) {
                        if (result == "error") {
                            alert('خطا...!');
                        }
                        else {
                            //alert(result);
                            var obj = JSON.parse(result);
                            $("select[name='CityID'] option").remove();
                            var html = '<option data-id="' + id + '" value="' + id + '">همه </option>';
                            $.each(obj, function (index, value) {
                                html += '<option data-id="' + value.LocationID + '" value="' + value.LocationID + '">' + value.LocationName + '</option>';
                            });

                            $("select[name='CityID']").append(html);
                            if ($("select[name='CityID']").attr('data-id') !== "" && !(typeof $("select[name='CityID']").attr('data-id') === "undefined")) {
                                $("select[name='CityID'] option[data-id='" + $("select[name='CityID']").attr('data-id') + "']").attr("selected", "selected");
                            }
                        }
                    },
                    beforeSend: function () { },
                    error: function () { alert('خطا...!'); },
                    complete: function () { }
                });
            };

            var id = $("select[name='StateID']").find(":selected").attr('data-id');
            if (typeof id === "undefined") {
                id = 0;
            } else {
                GetLocation(id);
            }


            $("select[name='StateID']").change(function () {
                var id = $(this).find(':selected').val();
                GetLocation(id);
            });

        },

        Maplocation: function (id, lat, lng, loc, icon) {

            ajaxLocation();

            function ajaxLocation() {
                $.ajax({
                    url: "/AjaxLibrary/public.aspx?act=IranLocations",
                    type: "POST",
                    data: {
                        "LocationID": id
                    },
                    success: function (result) {
                        if (result == "error") {
                            alert('خطا..!');

                        }
                        else {
                            var obj = JSON.parse(result);
                            createMap(id, lat, lng, loc, icon, obj)

                        }
                    },
                    beforeSend: function () { },
                    error: function () { alert('خطا...!'); },
                    complete: function () { }
                });
            }


            function createMap(id, lat, lng, loc, icon, data) {


                var map = L.map(id).setView(loc, 13);

                L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw',
                    {
                        id: 'mapbox/light-v9',
                        tileSize: 512, zoomOffset: -1,
                        attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, ' +
                            'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>'
                    }).addTo(map);
                var LeafIcon = L.Icon.extend({
                    options: {
                        iconSize: [64, 64],
                        shadowSize: [0, 0],
                        iconAnchor: [30, 50],
                        shadowAnchor: [0, 0],
                        popupAnchor: [0, 0]
                    }
                });
                var mapIcon = new LeafIcon({ iconUrl: icon });
                var marker = L.marker([lat, lng], { icon: mapIcon }).addTo(map);
                map.on('click', function (e) {
                    $("#Location").val("lat: " + e.latlng.lat + ", lng: " + e.latlng.lng);
                    map.removeLayer(marker);
                    marker = L.marker([e.latlng.lat, e.latlng.lng], { icon: mapIcon }).addTo(map);
                });
                map.scrollWheelZoom.disable();
                var featuresLayer = new L.GeoJSON(data, {
                    style: function (feature) {
                        return { color: feature.properties.color };
                    },
                    onEachFeature: function (feature, marker) {
                        marker.bindPopup('<h4 style="color:' + feature.properties.color + '">' + feature.properties.name + '</h4>');
                    }
                });

                map.addLayer(featuresLayer);

                var searchControl = new L.Control.Search({
                    position: 'topleft',
                    layer: featuresLayer,
                    propertyName: 'name',
                    marker: false,
                    textErr: 'مکان مورد نظر پیدا نشد',	//error message
                    textCancel: 'انصراف',		    //title in cancel button
                    textPlaceholder: 'جستجو...',
                    container: 'input-search',
                    moveToLocation: function (latlng, title, map) {
                        //map.fitBounds( latlng.layer.getBounds() );
                        // var zoom = map.getBoundsZoom(latlng.layer.getBounds());
                        map.setView(latlng, 12); // access the zoom
                    }
                });

                searchControl.on('search:locationfound', function (e) {

                    //console.log('search:locationfound', );

                    //map.removeLayer(this._markerSearch)

                    e.layer.setStyle({ fillColor: '#3f0', color: '#0f0' });
                    if (e.layer._popup)
                        e.layer.openPopup();

                }).on('search:collapsed', function (e) {

                    featuresLayer.eachLayer(function (layer) {	//restore feature color
                        featuresLayer.resetStyle(layer);
                    });
                });

                map.addControl(searchControl);  //inizialize search control
            }
        },

        Newsletter: function () {

            var NewsletterReg = function ($this) {
                debugger;
                var form = $this.parents('form:first');
                var data = form.serializeJSON();

                if (form.valid() && (!$('#check_email').is(":checked"))) {
                    $.ajax({
                        url: "/AjaxLibrary/Public.aspx?act=NewsletterRegV2",
                        cache: false,
                        type: "POST",
                        data: {
                            "data": JSON.stringify(data)
                        },
                        success: function (result) {

                            if (result == "error") {
                                swal(obj.msg, {
                                    icon: obj.status,
                                });
                            }
                            else {
                                var obj = JSON.parse(result);
                                if (obj.status == "error") {
                                    swal(obj.msg, {
                                        icon: obj.status,
                                    });
                                }
                                else {
                                    swal(obj.msg, {
                                        icon: obj.status,
                                    });
                                }
                            }
                        },
                        complete: function () {
                        },
                        beforeSend: function () {
                            $(this).hide(); // تبدیل دکمه به لودینگ
                        },
                        error: function () {
                            swal(obj.msg, {
                                icon: obj.status,
                            });
                        }
                    });
                };
            }

            $(document).ready(function () {
                var handleNewsletter = function () {
                    $('body').on('click', '.submit-newsletter', function (e) {
                        e.preventDefault();
                        NewsletterReg($(this));
                    });

                    $('body').on('keypress', '.submit-newsletter', function (e) {
                        if (e.keyCode == 13) {
                            NewsletterReg($(this));
                            return false;
                        }
                    });
                };

                handleNewsletter();
            });
        },

        components: {}
    }
});

$.tc.init();
