/* ================================================================================
 * sg.js v1.0
 * http://git.shemic.com/sg/script
 * ================================================================================
 * Copyright 2018-2020 Dever(dever.cc)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ================================================================================
 */

var host = 'http://sg.5dev.cn/';
document.write('<link rel="stylesheet" href="'+host+'assets/layui/css/layui.css">');
document.write('<script src="'+host+'assets/layui/layui.js"></script>');

var SG = 
{
    id : '#pay',
    layui : '',
    product_name : '#product_name',
    amount : '#amount',
    prefix : 'Pay with ',
    submit : 'pay',
    url : host + 'payment/?l=api.get&json=1&callback=?',
    method : 
    {
        'credit' : 
        {
            'id' : 21
            ,'name' : 'credit cards'
            ,'type' : 'page2'
        }
        ,'sadad' : 
        {
            'id' : 4
            ,'name' : 'sadad'
            ,'type' : 'redirection'
        }
        ,'naps' : 
        {
            'id' : 3
            ,'name' : 'naps'
            ,'type' : 'redirection'
        }
        /*
        ,'installments_page' : 
        {
            'id' : 12
            ,'name' : 'installments page'
            ,'type' : 'page'
        }
        */
        ,'installments' : 
        {
            'id' : 2
            ,'name' : 'installments'
            ,'type' : 'redirection'
        }
    },
    Html : function()
    {
        var self = this;
        var html = '<select id="sg-method" name="sg-method" lay-verify="required">';
        for (var i in self.method) {
            html += '<option value="'+i+'">'+self.prefix+self.method[i]['name']+'</option>';
        }

        html += '</select>';

        html = self.CreateFormItem(html, 'Pay Method');

        html += self.CreateFormItem('<a class="layui-btn" id="sg-submit">'+self.submit+'</a>');

        if (self.layui.$(self.id).length) {
            self.layui.$(self.id).html(html);
            self.Init('#sg-submit', '#sg-method');
            self.layui.form.render('select');
        }
    }
    ,Notify : function(res)
    {
        alert(222);
    }
    ,Init : function(submit, value)
    {
        var self = this;
        self.layui.$(submit).bind('click', function() {
            var key = self.layui.$(value).val();
            var method = self.method[key];
            if (method.type == 'page2') {
                self.ShowPage(key, method);
            } else {
                self.Submit(key, method);
            }
        });
    }
    ,ShowPage : function(key, method)
    {
        var self = this;
        var html = self.CreatePage();
        self.layui.layer.alert(html, {
            area: ['auto', '600px'],
            title : 'notice'
            //,skin: 'layui-layer-lan' //样式类名
            ,closeBtn: 0
            ,btn: [self.submit, 'close']
            ,success: function(layero, index){
                self.layui.form.render('select');
            }
        }, function() {
            var state = self.CheckPageParam(key, method).validateCcForm();
            if (state) {
                self.Submit(key, method);
            }
        });
    }
    ,CreatePage : function()
    {
        var self = this;
        var html = '<form class="layui-form" action="">';
        html += self.CreateFormItemInput('card_holder_name', 'Card Holder\'s Name', 'Card Name');
        html += self.CreateFormItemInput('card_number', 'Debit/Credit Card Number', 'Card Number');

        var option = 
        {
            'Jan (01)' : '01',
            'Feb (02)' : '02',
            'Mar (03)' : '03',
            'Apr (04)' : '04',
            'May (05)' : '05',
            'June (06)' : '06',
            'July (07)' : '07',
            'Aug (08)' : '08',
            'Sep (09)' : '09',
            'Oct (10)' : '10',
            'Nov (11)' : '11',
            'Dec (12)' : '12',
        };
        html += self.CreateFormItemSelect('expiry_month', 'Expiration Month', 'Expiration Month', option);

        var date = new Date;
        var year = date.getFullYear();
        var total = 10;
        var option = {};
        for (var i = 0; i < total; i++) {
            option[year + i] = year + i - 2000;
        }
        html += self.CreateFormItemSelect('expiry_year', 'Expiration Year', 'Expiration Year', option);

        html += self.CreateFormItemInput('cvv', 'Security Code', 'Card CVV');

        html += '</form>';
        return html;
    }
    ,Submit : function(key, method)
    {
        if (location.href.indexOf('?status=') != -1) {
            var refer = location.href.split('?status=');
            var refer = refer[0];
        } else if (location.href.indexOf('&status=') != -1) {
            var refer = location.href.split('&status=');
            var refer = refer[0];
        } else {
            var refer = location.href;
        }
        
        var self = this;
        var param = {};
        param.type = method.id;
        param.refer = refer;
        param.product_name = self.layui.$(self.product_name).val();
        param.amount = parseInt(self.layui.$(self.amount).val());
        
        self.layui.$.ajax({
           url: self.url, 
           type: 'post',
           dataType: 'jsonp',
           data: param,
           success: function (response) {
                if (response.status == 1 && response.data && response.data.form) {
                    self.layui.$(self.id).append(response.data.form);

                    if (method.type == 'page2') {
                        var expDate = self.layui.$('#expiry_year').val()+''+self.layui.$('#expiry_month').val();
                        var params = {};
                        params.card_holder_name = self.layui.$('#card_holder_name').val();
                        params.card_number = self.layui.$('#card_number').val();
                        params.expiry_date = expDate;
                        params.card_security_code = self.layui.$('#cvv').val();
                        self.layui.$.each(params, function(k, v){
                            self.layui.$('<input>').attr({
                                type: 'hidden',
                                id: k,
                                name: k,
                                value: v
                            }).appendTo('#sg-form'); 
                        });
                        self.Click();
                    } else if (method.type == 'page') {

                    } else {
                        self.Click();
                    }

                    /*
                    if(response.paymentMethod == 'cc_merchantpage' || response.paymentMethod == 'installments_merchantpage') {
                        showMerchantPage(response.url);
                    }
                    */
                }
           }
        });
    }

    ,Click : function()
    {
        var self = this;
        self.layui.$('#sg-form input[type=submit]').click();
    }

    ,CheckPageParam : function(key, method)
    {
        var self = this;
        var payfortFort = self.CheckPayFort();
        return {
            validateCcForm: function () {
                this.hideError();
                var isValid = payfortFort.validateCardHolderName(self.layui.$('#card_holder_name'));
                if(!isValid) {
                    this.showError('Invalid Card Holder Name', '#card_holder_name');
                    return false;
                }
                isValid = payfortFort.validateCreditCard(self.layui.$('#card_number'));
                if(!isValid) {
                    this.showError('Invalid Credit Card Number', '#card_number');
                    return false;
                }
                isValid = payfortFort.validateCvc(self.layui.$('#cvv'));
                if(!isValid) {
                    this.showError('Invalid Card CVV', '#cvv');
                    return false;
                }
                return true;
            },
            showError: function(msg, id) {
                self.layui.layer.tips(msg, id, {
                    tips: [2, '#3595CC'],
                    time: 3000
                });
            },
            hideError: function() {
                return;
            }
        };
    }

    ,CheckPayFort : function()
    {
        var self = this;
        return {
            validateCreditCard: function(element) {
                var isValid = false;
                var eleVal = self.layui.$(element).val();
                eleVal = this.trimString(element.val());
                eleVal = eleVal.replace(/\s+/g, '');
                self.layui.$(element).val(eleVal);
                isValid = self.ValidateCreditCard(eleVal);
                return isValid;
            },
            validateCardHolderName: function(element) {
                self.layui.$(element).val(this.trimString(element.val()));
                var cardHolderName = self.layui.$(element).val();
                if(!cardHolderName || cardHolderName.length > 50) {
                    return false;
                }
                return true;
            },
            validateCvc: function(element) {
                self.layui.$(element).val(this.trimString(element.val()));
                var cvc = self.layui.$(element).val();
                if(!cvc || cvc.length > 4 || cvc.length == 0) {
                    return false;
                }
                if(!this.isPosInteger(cvc)) {
                    return false;
                }
                return true;
            },
            isDefined: function(variable) {
                if (typeof (variable) === 'undefined' || typeof (variable) === null) {
                    return false;
                }
                return true;
            },
            trimString: function(str){
                return str.trim();
            },
            isPosInteger: function(data) {
                var objRegExp  = /(^\d*$)/;
                return objRegExp.test( data );
            }
       };
    }

    ,CreateFormItemSelect : function(id, info, title, option)
    {
        var html = '<select id="'+id+'" name="'+id+'" lay-verify="required">';
        for (var i in option) {
            html += '<option value="'+option[i]+'">'+i+'</option>';
        }

        html += '</select>';

        var style = 'float: left;padding-left: 0px;padding-top: 5px;';

        return this.CreateFormItem(html, title, style);
    }

    ,CreateFormItemInput : function(id, info, title)
    {
        var html = '<input type="text" name="'+id+'" id="'+id+'" required="" lay-verify="required" placeholder="'+info+'" autocomplete="off" class="layui-input">';

        var style = 'float: left;padding-left: 0px;padding-top: 5px;';

        return this.CreateFormItem(html, title, style);
    }
    ,CreateFormItem : function(content, title, style)
    {
        if (style) {
            var attr = 'style="'+style+'"';
        } else {
            var attr = 'class="layui-form-label"';
        }
        if (title) {
            title = '<label '+attr+'>'+title+'</label>';
        } else {
            title = '';
        }
        var html = '<div class="layui-form-item">'+title+'<div class="layui-input-block">' + content + '</div></div>';

        return html;
    }
    ,getUrlParameter : function(sParam)
    {
        var sPageURL = decodeURIComponent(window.location.search.substring(1)),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

        for (i = 0; i < sURLVariables.length; i++) {
            sParameterName = sURLVariables[i].split('=');

            if (sParameterName[0] === sParam) {
                return sParameterName[1] === undefined ? true : sParameterName[1];
            }
        }
    }

    ,ValidateCreditCard : function(card)
    {
        var self = this;
        var card_types = [
          {
            name: 'amex',
            pattern: /^3[47]/,
            valid_length: [15]
          }, {
            name: 'diners_club_carte_blanche',
            pattern: /^30[0-5]/,
            valid_length: [14]
          }, {
            name: 'diners_club_international',
            pattern: /^36/,
            valid_length: [14]
          }, {
            name: 'jcb',
            pattern: /^35(2[89]|[3-8][0-9])/,
            valid_length: [16]
          }, {
            name: 'laser',
            pattern: /^(6304|670[69]|6771)/,
            valid_length: [16, 17, 18, 19]
          }, {
            name: 'visa_electron',
            pattern: /^(4026|417500|4508|4844|491(3|7))/,
            valid_length: [16]
          }, {
            name: 'visa',
            pattern: /^4/,
            valid_length: [16]
          }, {
            name: 'mastercard',
            pattern: /^5[1-5]/,
            valid_length: [16]
          }, {
            name: 'maestro',
            pattern: /^(5018|5020|5038|6304|6759|676[1-3])/,
            valid_length: [12, 13, 14, 15, 16, 17, 18, 19]
          }, {
            name: 'discover',
            pattern: /^(6011|622(12[6-9]|1[3-9][0-9]|[2-8][0-9]{2}|9[0-1][0-9]|92[0-5]|64[4-9])|65)/,
            valid_length: [16]
          }
        ];

        for (var i in card_types) {
            state = self.CheckCardMatch(card, card_types[i]);
            if (state) {
                state = self.CheckCardLength(card, card_types[i]);
                if (state) {
                    return true;
                }
            }
        }

        return false;
    }

    ,CheckCardMatch : function(card, item)
    {
        if (card.match(item.pattern)) {
            return true;
        } else {
            return false;
        }
    }
    ,CheckCardLength : function(card, item)
    {
        var length = card.length;
        for (var i in item.valid_length) {
            if (item.valid_length[i] == length) {
                return true; 
            }
        }
        return false; 
    }
}