var cards = {
    "^3[47]\\d{1,2}(| |-)\\d{6}\\1\\d{6}$":"amex","^5[1-5]\\d{2}(| |-)(?:\\d{4}\\1){2}\\d{4}$":"mastercard",
    "^4\\d{3}(| |-)(?:\\d{4}\\1){2}\\d{4}$":"visa","^6(?:011|5\\d\\d)(| |-)(?:\\d{4}\\1){2}\\d{4}$":"discover"}

var payment = {}
payment.setup = function(context,pricing,product_name){
    sessionStorage.store_context = context
    if (pricing != null){
        sessionStorage.pricing = pricing.constructor == String ? pricing: JSON.stringify(pricing)
    }else{
        sessionStorage.pricing = "[]"
    }
    sessionStorage.product_name = product_name
    sessionStorage.customer = JSON.stringify({info:{}})
    
    $('.payment-amount > input').on('focusin',function(){            
        $('.payment-amount > .payment-list').slideDown('fast')
    })
    $('.payment-amount > input').on('focusout',function(){
        $('.payment-amount > .payment-list').slideUp('slow')
    })
    
    payment.init(0)
        //  jx.dom.set.focus('amount')
    var d = new Date()
    $('.copyright').text(d.getFullYear())
    if( $('.jxmodal').length == 0){
        $('.close-dialog').hide()
        
    }

}
payment.init = function(index){
    var p = JSON.parse(sessionStorage.pricing)
    console.log(p)
    if(p.length == 0){
        return ;
    }
    var _item = p[index]
    var amount = (_item.unit_amount/100).toFixed(2)
    $('.amount').val( amount)
    //$('.amount-value').text(amount)
    $('.currency').text(_item.currency.toUpperCase())
    $('.amount').change()
    sessionStorage.product = JSON.parse(sessionStorage.customer)

}
payment.validate = function(e){
    var id = e.target
    console.log([id,e])
    customer = JSON.parse(sessionStorage.customer)
    if($(id).attr('class').match(/number|cvc|exp/) && sessionStorage.has_card){
        return 1 ;
    }
    $(id).removeClass('error')
    var pattern = $(id).attr('data-pattern')
    var field = $(id).attr('class')
    var value = $(id).val().trim()
    
    $(id).val(value)
    if (customer.info[field] != null){
        delete customer.info[field]
    }
    if (pattern == 'card'){
        var r = jx.utils.patterns.visitor(jx.utils.keys(cards),function(key){
            
            if(value.match(key)){
                return cards[key]
            }
        })
        if(r.length > 0){
            //
            // @TODO: Generalize this to a function call (poor programming)
            customer.info[field] = value
            sessionStorage.customer = JSON.stringify(customer)
            var link = ([sessionStorage.store_context,'/static/img/cards/',r[0]+'.svg']).join('')
            jx.dom.set.attribute('pay-icon','src',link)
            return 1
        }else{

            jx.dom.set.attribute('pay-icon','src','')
            $(id).addClass('error')
            return 0
        }
        
    }else{
        if(value.match(pattern)){
            customer.info[field] = value
            sessionStorage.customer = JSON.stringify(customer)
            return 1
        }else{
            // id.className = id.className + ' error'
            $(id).addClass('error')
            return 0
        } 

    }
}
payment.dialog = function(title,message,type){
    ICONS = {'WARN':'fas fa-exclamation-triangle','CHECK':'fas fa-check fa-3x','PROGRESS':'fas fa-cog fa-spin'}
    var uri = ([sessionStorage.store_context,'/html/dialog']).join('')
    
    var info = {title:title,message:message,icon:ICONS[type],type:type}
    var httpclient = HttpClient.instance()
    httpclient.setData( JSON.stringify(info)) 
    httpclient.setHeader('content-type','application/json') 
    httpclient.post(uri,function(x){
        jx.modal.show({html:x.responseText,id:'payment-dialog'}) 
    })
}
payment.proceed = function(pointer){
    
    var values = jx.utils.patterns.visitor($('input'),function(_input){
        //
        // re-running validation
        return payment.validate({target:_input})
        //     if ($(_input).attr('class') != 'amount'){
        //         $(_input).keyup()
        //     }else {

        //         $(_input).change()
        //     }
        })

    var N = $('input').length
    info = JSON.parse(sessionStorage.customer).info
    var n = jx.utils.keys(info).length
    if (n != jx.math.sum(values) && ! sessionStorage.has_card){
       //
       // Nothing to be done here because the user interface would have lit-up
       //
       ;    
    }else{
        //
        // Submit the charge to be processed
        //
        payment.dialog('Preparing payment','Please wait ...','PROGRESS') 
        info.amount = info.amount * 100
        $('.dialog > .message').text('Processing card, please wait ...')
        var uri = ([sessionStorage.store_context,sessionStorage.product_name,'pay']).join('/')
        var http = HttpClient.instance()
        if(sessionStorage.has_card == "1"){
            info.has_card = true
        }
        console.log(info)
        http.setData(info,"application/json")        
        http.post(uri,function(x){
            
            if(x.status == 200){
                TYPE='CHECK'    
                TITLE = ''
                jx.utils.patterns.visitor($('input'),function(_input){
                    $(_input).val('')
                    $(_input).attr('disabled',true)
                    
                })
                sessionStorage.customer = JSON.stringify({info:{}})

            }else{
                TITLE='.::'
                TYPE='WARN'
            }
            $('.jxmodal')[$('.jxmodal').length -1 ].remove()
            payment.dialog(TITLE,x.responseText,TYPE)
            if (payment.do_post !=null){
                payment.do_post()
            }
            
        })
    }
}

payment.card_onfile = function(){
    
    var name = $('.card_onfile > i').attr('class')
    if (name.match(/square/i)){
        $('.card_onfile > i').attr('class','fas fa-check')
        $('.number').slideUp( function(){
            $('.expire').slideUp()
        })
        var pointer = function(){}
        sessionStorage.has_card = 1
    }else{
        delete sessionStorage.has_card
        $('.card_onfile > i').attr('class','far fa-square')
        $('.number').slideDown( function(){            
            $('.expire').slideDown()
        })
        pointer = function(){
            payment.validate(event)
        }

    }
    jx.utils.patterns.visitor(['.number','.exp','.cvc'],function(id){
        $(id).click = pointer
    })
}