Ext.ns('Ext.app');
Ext.apply(Ext.form.VTypes,{
    numeric:function(val, field){
        return /[0-9]/.test(val);
    },
    numericText:'数字で入力してください。',
    numericMask:/[0-9]/i
});


Ext.app.ConfirmPanel = Ext.extend(Ext.form.FormPanel,{
    initComponent:function()
    {
        var tpl = new Ext.XTemplate(
        );    

        Ext.app.ConfirmPanel.superclass.initComponent.call(this);
    }
});

/**
 * 支払いパネルクラス 
 */
Ext.app.PaymentEditor = Ext.extend(Ext.form.FormPanel,{
    initComponent:function(){

        Ext.applyIf(this,{
            border:false,
            monitorValid:true,
            cls:'payment-form-wrap',
            labelWidth:180,
            labelHeight:'100%',
            layoutConfig:{
                labelSeparator:'&nbsp;'
            },
            defaults:{
                anchor:'95%',
                msgTarget:'under',
                labelStyle:'padding:5px 0 10px 5px;;white-space:nowrap;font-weight:bold; background-color:#FFC600;color:#555;text-align:right;'
            },
            items:[
                {
                    xtype:'radio',
                    cls:'payment-radio',
                    allowBlank:false,
                    inputValue:'creditcard',
                    name:'od_paymenttype',
                    fieldLabel:'<span style="padding-right:10px">クレジットカード決済</span>',
                    boxLabel:'<div class="desc"> クレジット決済はテレコムクレジットを利用します。カード情報等は本サイトには記録されません。JCB、VISA、MasterCard、American Express、Diners Club、Discoverの全てのクレジットカードがご利用可能です。 <img src="images/creditcards.gif" /> </div>'
                },
                {
                    xtype:'radio',
                    cls:'payment-radio',
                    allowBlank:false,
                    name:'od_paymenttype',
                    inputValue:'deliverypay',
                    fieldLabel:'<span style="padding-right:10px">代金引換</span>',
                    boxLabel:'<div class="desc"> 商品をお受け取りの際に、配達員にお支払いください。商品代金、送料の他に代引き手数料が必要です。手数料につきましては、下記をご確認ください。また、代金引換ができるのは30万円までになります。 <p>■代引き手数料</p> ※商品+送料+代引き手数料=合計金額（税込み）で計算してください。 <table class="shipping-cost"> <tr><th>1万円未満</th><td>315円</td></tr> <tr><th>1万円以上～3万円未満</th><td>420円</td></tr> <tr><th>3万円以上～10万円未満</th><td>630円</td></tr> <tr><th>10万円以上～30万円まで</th><td>1050円</td></tr> </table> </div>'
                }
            ],
            buttons:[
                {
                    formBind:true,
                    text:'VALID CHECKING'
                }
            ]
        });
        
        Ext.app.PaymentEditor.superclass.initComponent.call(this);
    },
    initEvents:function(){
        Ext.app.PaymentEditor.superclass.initEvents.call(this);
    },
    getValues:function(){
    
    },
    addCardForm:function(type){
        var extraItems;
        
        if(type == "card") {
            extraItems = [
                    {
                        xtype:'displayfield',
                        hideLabel:true,
                        value:'<b>クレジットカード支払い</b>'
                    },
                    {
                        xtype:'displayfield',
                        hideLabel:true,
                        value:'クレジット決済はテレコムクレジットを利用します。カード情報等は本サイトには記録されません。'
                    }
                ];
        }else if(type == 'daibiki'){
            extraItems = [
                {
                    xtype:'displayfield',
                    hideLabel:true,
                    value:'<b>銀行振込支払い</b>'
                },
                {
                    xtype:'displayfield',
                    hideLabel:true,
                    value:'入金が確認後に発送となります。'
                }
            ]; 
        }

        
        
        var extraField = {
            xtype:'fieldset',
            itemId:'extrafield',
            defaults:{
                border:false,
                anchor:'95%'
            },
            items:extraItems
        };

        this.add(extraField);
        this.doLayout();
    }
});
Ext.reg('app-payment',Ext.app.PaymentEditor);


/**
 * ショッピングカートプロトタイプ 
 */
Ext.app.ShopCart = Ext.extend(Ext.Panel,{
    initComponent:function()
    {
        
        //注文情報の初期化
        this.orderInfo = {};

        var cancelBtn = new Ext.Action({
            text:'キャンセル',
            iconCls:'cancel',
            scope:this,
            handler:function(){
                this.cancelOrder();
            }
        });

        var productCard = {
            title:'商品を選択',
            xtype:'form',
            itemId:'product',
            ref:'product',
            layout:'column',
            
            defaults:{
                xtype:'fieldset',
                columnWidth:0.5,
                border:false,
                defaults:{
                    xtype:'textfield',
                    anchor:'90%'
                }
            },
            items:[
                {
                    xtype:'panel',
                    el:'shopcart-step1-el'
                },      
                    
                {
                    layout:'form',
                    labelWidth:200,
                    defaults:{
                        anchor:'90%'
                    },
                    items:[
                        {
                            xtype:'displayfield',
                            hideLabel:true,
                            cls:'address-header',
                            value:'<div class="wrap"><h3 class="order-header">生ローヤルゼリー「Forabee」</h3></div>'
                        },
                        {
                            xtype:'compositefield',
                            fieldLabel:'<span class="prod-label">100g <span class="price">7,500円</span></span>',
                            items:[
                               new Ext.ux.form.SpinnerField({
                                    name:'od_item1',
                                    width:50,
                                    height:40,
                                    value:0,
                                    minValue:0,
                                    maxValue:100
                               }),
                               {
                                    xtype:'displayfield',
                                    value:'個'
                               }
                            ]
                        },
                        {
                            xtype:'compositefield',
                            fieldLabel:'<span class="prod-label">250g <span class="price">15,000円</span></span>',
                            items:[
                               new Ext.ux.form.SpinnerField({
                                    name:'od_item2',
                                    width:50,
                                    height:40,
                                    value:0,
                                    minValue:0,
                                    maxValue:100
                               }),
                               {
                                    xtype:'displayfield',
                                    value:'個'
                               }
                            ]
                        },
                        {
                            xtype:'compositefield',
                            fieldLabel:'<span class="prod-label">500g <span class="price">25,000円</span></span>',
                            items:[
                               new Ext.ux.form.SpinnerField({
                                    name:'od_item3',
                                    width:50,
                                    height:40,
                                    value:0,
                                    minValue:0,
                                    maxValue:100
                               }),
                               {
                                    xtype:'displayfield',
                                    value:'個'
                               }
                            ]
                        },
                        {
                            xtype:'panel',
                            border:false,
                            height:250,
                            bodyStyle:{
                                'text-align':'center',
                                'padding':'15px'
                            },
                            el:"shopcart-step1-shipping-el"
                        }
                    ]
                }
            ],
            buttons:[
                cancelBtn,
                '->',
                {
                    text:'次へ',
                    iconCls:'next',
                    scope:this,
                    handler:function(){
                        var panel = this.getComponent('mainpanel');
                        var form = panel.getComponent('product').getForm();
                        if (!form.isValid()) {
                            Ext.Msg.alert(
                            '確認',
                            '入力に不備があります。数量は半角数字で入力してください。'
                            ).setIcon(Ext.Msg.WARNING);
                            return;
                        }
                        var values = panel.getComponent('product').getForm().getValues();
                        //数量チェック 
                        if ( (parseInt(values.od_item1) + 
                            parseInt(values.od_item2) + 
                            parseInt(values.od_item3)) < 1) {
                            Ext.Msg.alert(
                                Ext.app.APPNAME, '商品の数量が入力されていません。'
                            ).setIcon(Ext.Msg.ERROR);
                            return;
                        }
                        panel.layout.setActiveItem(1);
                        this.orderInfo.product = values;
                        this.changecard(1);
                    }
                }
            ]
        };

        var addressCard = {
            title:'住所・送り先を入力',
            xtype:'app-address-form',
            itemId:'address',
            ref:'addresscard',
            listeners:{
                scope:this,
                activate:function(panel) {
                    panel.setData();
                }
            },
            buttons:[
                cancelBtn,
                '->',
                {
                    text:'戻る',
                    iconCls:'back',
                    scope:this,
                    handler:function(){
                        this.getComponent('mainpanel').layout.setActiveItem(0);
                        this.changecard(0);
                    }
                },
                {
                    text:'次へ',
                    iconCls:'next',
                    formBind:true,
                    scope:this,
                    handler:function(){
                        var panel = this.getComponent('mainpanel');
                        if (!panel.getComponent('address').getForm().isValid()){return};
                        var values = panel.getComponent('address').getForm().getValues();
                         
                        panel.layout.setActiveItem(2);
                        this.orderInfo.address = values;
                        this.changecard(2);
                    }
                }
            ]
        };
        
        var paymentCard = {
            title:'支払い方法の選択',
            xtype:'app-payment',
            itemId:'payment',
            ref:'payment',
            monitorValid:true,
            html:'',
            buttons:[
                cancelBtn,
                '->',
                {
                    text:'戻る',
                    iconCls:'back',
                    scope:this,
                    handler:function(){
                        this.getComponent('mainpanel').layout.setActiveItem(1);
                        this.changecard(1);
                    }
                },
                {
                    text:'次へ',
                    formBind:true,
                    iconCls:'next',
                    scope:this,
                    handler:function(){
                        var panel = this.getComponent('mainpanel');
                        var values = panel.getComponent('payment').getForm().getValues();
                        if (!values.od_paymenttype) {
                            Ext.Msg.alert(
                                '支払い方法選択',
                                '支払い方法が選択されていません。'
                                ).setIcon(Ext.Msg.WARNING);
                            return;
                        }
                        this.orderInfo.od_payment = values.od_paymenttype;
                        panel.layout.setActiveItem(3);
                        this.changecard(3);
                    }
                }
            ]
        };

        var confirmCard = {
            title:'注文情報の確認',
            xtype:'form',
            ref:'confirm',
            itemId:'confirm',
            labelWidth:1,
            labelPad:0,
            defaults:{
                hideLabel:true,
                bodyStyle:{
                    padding:'8px'
                }
            },
            items:[
                {
                    xtype:'panel',
                    ref:'orderdetail',
                    html:'注文情報がありません。'
                },
                {
                    xtype:'fieldset',
                    border:false,
                    items:[
                        {
                            xtype:'displayfield',
                            hideLabel:false,
                            anchor:false,
                            width:450,
                            ctCls:'checkbox-centered',
                            value:'<p>利用規約をご確認の上、「利用規約に同意する」にチェックを入れてください。</p>'
                        },
                        {
                            xtype:'panel',
                            border:false,
                            hideLabel:false,
                            anchor:false,
                            width:450,
                            autoScroll:true,
                            bodyStyle:{
                                'text-align':'center',
                                'padding':'7px'
                            },
                            el:"shopcart-term"
                        },
                        {
                            xtype:'checkbox',
                            hideLabel:false,
                            ctCls:'checkbox-centered',
                            anchor:false,
                            width:450,
                            allowBlank:false,
                            name:'acceptterms',
                            boxLabel:'利用規約に同意する。'
                        }
                    ]
                }
            ],
            buttons:[
                cancelBtn,
                '->',
                {
                    text:'戻る',
                    iconCls:'back',
                    scope:this,
                    handler:function(){
                        this.getComponent('mainpanel').layout.setActiveItem(2);
                        this.changecard(2);
                    }
                },
                {
                    text:'注文を確定',
                    iconCls:'submit',
                    scope:this,
                    handler:function(){
                        
                        var accept = this.mainpanel.confirm.getForm().getValues().acceptterms;
                        if (!accept || accept != 'on') {
                            Ext.Msg.alert(
                                '確認',
                                '「利用規約に同意する」にチェックがありません。'
                            ).setIcon(Ext.Msg.WARNING);
                            return;
                        };
                        this.submitOrder();
                    }
                }
            ],
            listeners:{
                scope:this,
                'show':function(panel) {
                    panel.el.mask('注文情報を計算中....');
                    var orderStr = Ext.util.JSON.encode(this.orderInfo);
                    //var tpl = Ext.XTemplate.from('shopcart-confirm-tpl');
                    var tpl = new Ext.XTemplate(
                            '<div class="confirm-order">',
                            '<h1>お客様情報(請求先)</h1>',
                            '<table class="customer-info">',
                            '<tr><th>お名前</th><td>{values.address.od_name}</td></tr>',
                            '<tr><th>郵便番号</th><td>{values.address.od_postal}</td></tr>',

                            '<tr>',
                            '<th>住所</th>',
                            '<td>{values.address.od_address}</td>',
                            '</tr>',
                            '<tr><th>電話番号</th><td>{values.address.od_phone}</td></tr>',
                            '<tr><th>メールアドレス</th><td>{values.address.od_email}</td></tr>',
                            '<tr><th>年齢</th><td>{values.address.od_age}</td></tr>',
                            '<tr><th>備考</th><td>{values.address.od_message}</td></tr>',
                            '<tr>',
                            '<th>forabeeからのお得な情報</th>',
                            '<td>',
                            '<tpl if="values.ml">',
                                '希望する',
                            '</tpl>',

                            '<tpl if="!values.ml">',
                                '希望しない',
                            '</tpl>',
                            '</td>',
                            '</tr>',
                            '</table>',

                            '<h1>お届け先情報</h1>',
                            '<tpl if="!values.st_address">',
                            '<table class="customer-info">',
                            '<tr><th>お届け先</th><td style="text-align:right">請求先と同じ</td></tr>',
                            '</table>',
                            '</tpl>',
                            '<tpl if="values.st_address">',
                            '<table class="customer-info">',
                            '<tr><th>お名前</th><td>{values.st_address.od_st_name}</td></tr>',
                            '<tr><th>郵便番号</th><td>{values.st_address.od_st_postal}</td></tr>',

                            '<tr>',
                            '<th>住所</th>',
                            '<td>{values.st_address.od_st_address} </td>',
                            '</tr>',

                            '<tr><th>電話番号</th><td>{values.st_address.od_st_phone}</td></tr>',
                            '</table>',
                            '</tpl>',

                            '<h1>注文商品</h1>',

                            '<table>',
                            '<tr><th>商品名</th><th>個数</th><th>合計</th><tr>',
                            '<tpl for="values.product">',
                            '<tr>',
                            '<td>',
                            '{name}</td><td>{value}</td><td class="price">￥{price}',
                            '</td>',
                            '</tr>',
                            '</tpl>',
                            '</table>',
                            
                            '<h1>送料</h1>',
                            '<table class="confirm-table">',
                            '<tr>',
                            '<th>送料合計</th>',
                            '<td >商品数 {count}点</td>',
                            '<td class="price">￥{shipcost}</td>',
                            '</tr>',
                            '</table>',

                            '<h1>支払い方法</h1>',
                            '<table class="confirm-table">',
                            '<tr>',
                            '<th>種類</th>',
                            '<td style="text-align:right">{od_payment}</td>',
                            '</tr>',
                            '<tpl if="values.od_payment==\'銀行振り込み\'">',
                                '<tr>',
                                '<th>手数料</th>',
                                '<td class="price">振り込み手数料はお客様負担でお願いいたします。</td>',
                                '</tr>',
                            '</tpl>',
                            '<tpl if="values.shipping_charge!=0">',
                                '<tr>',
                                '<th>手数料</th>',
                                '<td class="price">￥{shipping_charge}</td>',
                            '</tr>',
                            '</tpl>',
                            '</table>',
                            
                            '<h1>合計</h1>',
                            '<table class="confirm-table">',
                            '<tr>',
                            '<th>支払い代金(消費税含)</th>',
                            '<td class="price">￥{total}</td>',
                            '</tr>',
                            '</table>',
                            '</div>'
                    );
                    
                    
                    
                    Ext.Ajax.request({
                        url:Ext.app.conf.CALC_ORDER_API,
                        params:{
                            order:orderStr
                        },
                        scope:this,
                        success:function(result,opt){
                            var res = Ext.util.JSON.decode(result.responseText);
                            if (res.success){
                                panel.el.unmask();
                                res.shipping_charge = parseInt(res.shipping_charge);
                                tpl.overwrite(panel.orderdetail.body, res.order);
                            }else{
                                Ext.Msg.alert(
                                    'エラー：' + Ext.app.APPNAME,
                                    res.errmsg).setIcon(Ext.Msg.WARNING);
                            }
                        }
                    });
                }
            }
        };


        Ext.apply(this,{
            layout:'border',
            defaults:{
                border:false
            },
            items:[
                {
                    region:'north',
                    html:'<div id="register-step"></div>',
                    height:100
                },
                {
                    layout:'card',
                    itemId:'mainpanel',
                    ref:'mainpanel',
                    activeItem:0,
                    region:'center',
                    defaults:{
                        bodyStyle:{
                            padding:'15px'
                        },
                        border:false,
                        autoScroll:true,
                        buttonAlign:'left',
                        footerStyle:{
                            'background-color':'#EFEFEF'
                        }
                    },
                    items:[productCard, addressCard, paymentCard, confirmCard]
                }
            ]
        });

        Ext.app.ShopCart.superclass.initComponent.call(this);
    },
    initEvents:function()
    {
        this.addEvents({
            cancel:true
        });
        Ext.app.ShopCart.superclass.initEvents.call(this);
    },
    cancelOrder:function()
    {
        this.orderInfo = {};
        this.fireEvent('cancel');
    },
    changecard:function(index){
        var pos = 100 *index;
        Ext.get('register-step').applyStyles({
            'background-position':'0px -' + pos +'px'
        });
    },
    
    submitOrder:function()
    {
        var orderStr = Ext.util.JSON.encode(this.orderInfo);
        //Ajax Request
        var redirect;
        if (this.orderInfo.od_payment == 'credit') {
            redirect = 'PAYMENT PAGE';
        }

        var callback = function(url){
            location.href = url ? url : baseUrl;
        };
        
        Ext.Ajax.request({
            url:Ext.app.conf.SUBMIT_ORDER_API,
            scope:this,
            params:{
                order:Ext.encode(this.orderInfo)
            },
            success:function(result,opt){
                var res = Ext.decode(result.responseText);
                if (res.success){
                    //注文確定後にリダイレクト
                    callback(res.url);
                }else{
                    Ext.Msg.alert(
                        'エラー：' + Ext.app.APPNAME,
                        '注文送信に失敗しました。' + res.errmsg).setIcon(Ext.Msg.WARNING);
                }
            }
        });
    },

    getUserData:function()
    {
        Ext.Ajax.request({
            url:Ext.app.conf.USERINFO_API,
            scope:this,
            success:function(result,opt){
                var res = Ext.decode(result.responseText);
                if (res.success) {
                    this.mainpanel.addresscard.initData(res.rows[0]);
                }
            },
            failure:function(result,opt){
                 
            }
        });
    }

});

