﻿/**
 * 購物車類別
 */
var ShoppingCart = {

    payfrom: null,
    form: null,
    UsingVal: null,

    /**
    * 新增商品
    * @param {number} pid -商品流水號
    */
    AddItem: function (pid) {
        if (pid == undefined || pid == null) return;

        Ext.Ajax.request({
            url: "Handler.aspx?fn=AddItem",
            params: { pid: pid },
            mode: "post",
            scope: this,
            success: function (response, options) {
                var o = Ext.decode(response.responseText), d;
                try {
                    if (o.success) {
                        d = Ext.decode(o.data);
                        Util.MsgBox(false, o.msg);
                        Ext.getDom("CartAmount").innerHTML = d.amount;
                        Ext.getDom("CartTotal").innerHTML = d.price;
                    }
                    else {
                        Util.InfoBox(o.msg);
                    }
                }
                catch (e) {
                    Util.MsgBox(true, e.message);
                }
                finally {
                    o = null;
                }
            },
            failure: function () {
                Util.MsgBox(true, "加入購物車失敗，系統網路忙線中，<br/>請重新整理頁面或請稍候再試。");
            }
        })
    },

    /**
    * 更新商品資料
    * @param {number} pid	-商品流水號
    */
    UpdateCommodity: function (pid, field) {
        var orgValue = field.value;

        if (pid == undefined || pid == null) return;
        Ext.Ajax.request({
            url: "Handler.aspx?fn=UpdateItem",
            params: { pid: pid, num: orgValue },
            mode: "post",
            scope: this,
            success: function (response, options) {
                var o = Ext.decode(response.responseText);
                var id;
                try {
                    if (o.success) {
                        id = pid.toString();

                        //取得計算資料
                        o = Ext.decode(o.data);

                        //團購Icon
                        if (o.isGroupOrder) {
                            if (!Ext.get("Group" + id).isDisplayed())
                                Ext.get("Group" + id).fadeIn({ endOpacity: 1, duration: .5, useDisplay: true, remove: false, concurrent: true });
                        }
                        else {
                            if (Ext.get("Group" + id).isDisplayed())
                                Ext.get("Group" + id).fadeOut({ endOpacity: 0, duration: .5, useDisplay: true, remove: false, concurrent: true });
                        }

                        //變更金額
                        Ext.getDom("Price" + id).innerHTML = o.price.toString();
                        //變更紅利
                        Ext.getDom("Bonus" + id).innerHTML = o.bonus.toString();
                        //變更小計
                        Ext.getDom("Sum" + id).innerHTML = o.sum.toString();
                        //變更合計
                        Ext.getDom("SumPrice").innerHTML = o.allsum.toString();
                        Ext.getDom("CartTotal").innerHTML = (o.allsum - o.fee1 - o.fee2 - o.fee3).toString();
                        //變更合計紅利
                        Ext.getDom("SumBonus").innerHTML = o.allbonus.toString();
                        //變更消費總金額
                        Ext.getDom("TotalPrice").innerHTML = o.finalPrice.toString();
                        //設定運費
                        this.SetFeesBox([o.fee1, o.fee2, o.fee3]);
                    }
                    else {
                        Util.InfoBox(o.msg);
                    }
                }
                catch (e) { return; }
                finally { o = null; }
            },
            failure: function (response, options) {
                Util.MsgBox(true, "商品資料更新失敗，系統網路忙線中，<br/>請重新整理頁面或請稍候再試。");
            }
        });
    },

    /**
    * 刪除商品資料
    * @param {number} pid	-商品流水號
    */
    DeleteCommodity: function (pid) {
        if (pid == undefined || pid == null) return;

        Util.ConfirmBox("您確定要刪除此商品嗎？", function (ans) {
            if (ans == "no") return;
            Ext.Ajax.request({
                url: "Handler.aspx?fn=DeleteItem",
                params: { pid: pid },
                mode: "post",
                scope: this,
                success: function (response, options) {
                    var o = Ext.decode(response.responseText);
                    var id;
                    try {
                        if (o.success) {
                            id = pid.toString();

                            //取得計算資料
                            o = Ext.decode(o.data);

                            //變更合計
                            Ext.getDom("SumPrice").innerHTML = o.allsum.toString();
                            Ext.getDom("CartTotal").innerHTML = (o.allsum - o.fee1 - o.fee2 - o.fee3).toString();
                            //變更合計紅利
                            Ext.getDom("SumBonus").innerHTML = o.allbonus.toString();
                            //變更項目數量
                            Ext.getDom("AllTotal").innerHTML = o.amount.toString();
                            Ext.getDom("CartAmount").innerHTML = o.amount.toString();
                            //變更消費總金額
                            Ext.getDom("TotalPrice").innerHTML = o.finalPrice.toString();
                            //設定運費
                            ShoppingCart.SetFeesBox([o.fee1, o.fee2, o.fee3]);

                            if (o.amount.toString() == "0") {
                                if (Ext.isIE) {
                                    location.reload();
                                }
                                else {
                                    Ext.get("Commodity" + pid.toString()).update("<td colspan=\"7\">您的購物車目前沒有任何商品。</td>");
                                    Ext.get("AllSum").fadeOut({ endOpacity: 0, duration: .5, useDisplay: true, remove: true, concurrent: true });
                                    Ext.get("Payment").fadeOut({ endOpacity: 0, duration: .5, useDisplay: true, remove: true, concurrent: true });
                                }
                            }
                            else {
                                Ext.get("Commodity" + pid.toString()).fadeOut({ endOpacity: 0, duration: .5, useDisplay: true, remove: true, concurrent: true });
                            }
                        }
                        else {
                            Util.MsgBox(true, o.msg);
                        }
                    }
                    catch (e) {
                        Util.MsgBox(true, e.message);
                    }
                    finally { o = null; }
                },
                failure: function () {
                    Util.MsgBox(true, "商品資料更新失敗，系統網路忙線中，<br/>請重新整理頁面或請稍候再試。");
                }
            });
        });
    },

    /**
    * 設定運費區段
    * @param {Array} feeArray -運費陣列
    */
    SetFeesBox: function (feeArray) {
        var fee1 = document.getElementById("FeeNormal").getElementsByTagName("td")[2];
        var fee2 = document.getElementById("FeeCold").getElementsByTagName("td")[2];
        var fee3 = document.getElementById("FeeFreeze").getElementsByTagName("td")[2];

        try {
            fee1.innerHTML = feeArray[0] || "0";
            fee2.innerHTML = feeArray[1] || "0";
            fee3.innerHTML = feeArray[2] || "0";

            if (feeArray[0] > 0) {
                if (!Ext.get("FeeNormal").isDisplayed())
                    Ext.get("FeeNormal").fadeIn({ endOpacity: 1, duration: .5, useDisplay: true, remove: false, concurrent: true });
            }
            else {
                if (Ext.get("FeeNormal").isDisplayed())
                    Ext.get("FeeNormal").fadeOut({ endOpacity: 0, duration: .5, useDisplay: true, remove: false, concurrent: true });
            }

            if (feeArray[1] > 0) {
                if (!Ext.get("FeeCold").isDisplayed())
                    Ext.get("FeeCold").fadeIn({ endOpacity: 1, duration: .5, useDisplay: true, remove: false, concurrent: true });
            }
            else {
                if (Ext.get("FeeCold").isDisplayed())
                    Ext.get("FeeCold").fadeOut({ endOpacity: 0, duration: .5, useDisplay: true, remove: false, concurrent: true });
            }

            if (feeArray[2] > 0) {
                if (!Ext.get("FeeFreeze").isDisplayed())
                    Ext.get("FeeFreeze").fadeIn({ endOpacity: 1, duration: .5, useDisplay: true, remove: false, concurrent: true });
            }
            else {
                if (Ext.get("FeeFreeze").isDisplayed())
                    Ext.get("FeeFreeze").fadeOut({ endOpacity: 0, duration: .5, useDisplay: true, remove: false, concurrent: true });
            }
        }
        catch (e) {
            return;
        }
        finally {
            fee1 = null;
            fee2 = null;
            fee3 = null;
        }
    },

    /**
    * 使用紅利點數
    * @param {bool} isUse -是否使用紅利點數
    */
    UsingBonus: function (isUse) {
        var bonus;

        if (ShoppingCart.UsingVal == isUse) return;

        try {
            ShoppingCart.UsingVal = isUse;
            bonus = parseInt(Ext.getDom("MyBonus").innerHTML);

            if (isUse && bonus <= 0) throw Error("您沒有足夠的紅利點數！");

            //讀取紅利資料
            Ext.Ajax.request({
                url: "Handler.aspx?fn=UsingBonus",
                mode: "post",
                params: { isUsing: (isUse ? 1 : 0) },
                scope: this,
                success: function (response, options) {
                    var o = Ext.decode(response.responseText);
                    if (o.success) {
                        o = Ext.decode(o.data);
                        Ext.getDom("OffSettingBonus").innerHTML = o.offsetting.toString();
                        Ext.getDom("TotalPrice").innerHTML = o.finalPrice.toString();
                        if (isUse) {
                            //顯示折抵項
                            Ext.get("Offsetting").fadeIn({ endOpacity: 1, duration: .5, useDisplay: true, remove: false, concurrent: true });
                        }
                        else {
                            Ext.get("Offsetting").fadeOut({ endOpacity: 0, duration: .5, useDisplay: true, remove: false, concurrent: true });
                        }
                    }
                    else {
                        Util.MsgBox(true, o.msg);
                    }
                },
                failure: function () {
                    Util.MsgBox(true, "紅利點數讀取失敗，系統網路忙線中，<br/>請重新整理頁面或請稍候再試。");
                }
            });
        }
        catch (e) {
            ShoppingCart.UsingVal = false;
            ShoppingCart.SetRadio('0');
            Util.MsgBox(true, e.message);
            Ext.get("Offsetting").fadeOut({ endOpacity: 0, duration: .5, useDisplay: true, remove: false, concurrent: true });
        }
    },

    /**
    * 設定RadioBox
    * @param {string} val -選擇的radio value
    */
    SetRadio: function (val) {
        var radio, i;
        try {
            radio = Ext.DomQuery.select("input[name=Using]");
            for (i = 0; i < radio.length; i++) {
                radio[i].checked = (radio[i].value == val ? true : false);
            }
        }
        catch (e) {
            return;
        }
        finally {
            radio = null;
            i = null;
        }
    },

    /**
    * 初始化確認表單
    */
    InitConfirmForm: function () {
        Ext.onReady(function () {

            //讀取交易資料
            Ext.Ajax.request({
                url: "Handler.aspx?fn=GetTransaction",
                mode: "get",
                scope: this,
                success: function (response, options) {
                    var o = Ext.decode(response.responseText);
                    if (o.data != undefined) o = Ext.decode(o.data);

                    //建立縣市資料集
                    storeCounty = new Ext.data.JsonStore({
                        url: "Handler.aspx?fn=GetCounty",
                        totalProperty: "total",
                        root: "data",
                        fields: ["value", "text"]
                    });

                    storeCountySend = new Ext.data.JsonStore({
                        url: "Handler.aspx?fn=GetCounty",
                        totalProperty: "total",
                        root: "data",
                        fields: ["value", "text"]
                    });

                    //建立地區資料集
                    storeArea = new Ext.data.JsonStore({
                        url: "Handler.aspx?fn=GetArea",
                        totalProperty: "total",
                        root: "data",
                        fields: ["value", "text"]
                    });

                    //建立地區資料集
                    storeAreaSend = new Ext.data.JsonStore({
                        url: "Handler.aspx?fn=GetArea",
                        totalProperty: "total",
                        root: "data",
                        fields: ["value", "text"]
                    });

                    Ext.QuickTips.init();
                    Ext.BLANK_IMAGE_URL = "../include/ext/resources/images/default/s.gif";
                    ShoppingCart.form = new Ext.BasicForm("ConfirmForm");
                    ShoppingCart.form.add(
				        new Ext.form.TextField({
				            id: "recName",
				            renderTo: "_recName",
				            hideLabel: true,
				            emptyText: "請輸入姓名",
				            maxLength: 20,
				            minLength: 2,
				            allowBlank: false,
				            anchor: "100%",
				            value: o.recName
				        }),
				        new Ext.form.TextField({
				            id: "recMail",
				            applyTo: "recMail",
				            hideLabel: true,
				            emptyText: "輸入電子信箱",
				            maxLength: 64,
				            vtype: "email",
				            allowBlank: false,
				            width: 300,
				            value: o.recEmail
				        }),
				        new Ext.form.TextField({
				            id: "recTel1",
				            applyTo: "recTel1",
				            hideLabel: true,
				            maxLength: 20,
				            minLength: 6,
				            allowBlank: false,
				            anchor: "100%",
				            value: o.recTel1
				        }),
				        new Ext.form.TextField({
				            id: "recTel2",
				            applyTo: "recTel2",
				            hideLabel: true,
				            maxLength: 20,
				            minLength: 6,
				            allowBlank: true,
				            anchor: "100%",
				            value: o.recTel2
				        }),
				        new Ext.form.RadioGroup({
				            id: "recConcat",
				            renderTo: "recConcatBox",
				            hideLabel: true,
				            allowBlank: false,
				            anchor: "100%",
				            columns: 4,
				            items: [{
				                name: "recConcat",
				                inputValue: '0',
				                autoWidth: true,
				                boxLabel: "不限時",
				                listeners: {
				                    "render": function () {
				                        if (o.recConcat == '0') this.setValue(true);
				                    }
				                }
				            }, {
				                name: "recConcat",
				                inputValue: '1',
				                boxLabel: "9:00-12:00",
				                autoWidth: true,
				                listeners: {
				                    "render": function () {
				                        if (o.recConcat == '1') this.setValue(true);
				                    }
				                }
				            }, {
				                name: "recConcat",
				                inputValue: '2',
				                boxLabel: "12:00-17:00",
				                autoWidth: true,
				                listeners: {
				                    "render": function () {
				                        if (o.recConcat == '2') this.setValue(true);
				                    }
				                }
				            }, {
				                name: "recConcat",
				                inputValue: '3',
				                boxLabel: "17:00-20:00",
				                autoWidth: true,
				                listeners: {
				                    "render": function () {
				                        if (o.recConcat == '3') this.setValue(true);
				                    }
				                }
				            }]
				        }),
				        new Ext.form.ComboBox({
				            id: "_recCounty",
				            applyTo: "_recCounty",
				            hiddenName: "recCounty",
				            hideLabel: true,
				            triggerAction: "all",
				            emptyText: "選擇縣市..",
				            mode: "remote",
				            displayField: "text",
				            valueField: "value",
				            readOnly: true,
				            allowBlank: false,
				            style: "margin-top:0px;",
				            width: 90,
				            store: storeCounty,
				            listeners: {
				                "select": function (combo) {
				                    var cmp = Ext.ComponentMgr.get("_recArea");
				                    var dom = Ext.getDom("recZip");

				                    storeArea.load({
				                        params: { cid: combo.getValue() },
				                        callback: function (r, options, success) {
				                            if (success == true) {
				                                if (storeArea.getCount() > 0) {
				                                    cmp.setValue(r[0].get('value'));
				                                    dom.value = r[0].get('value').split(':')[1];
				                                    cmp.setDisabled(false);
				                                }
				                            }
				                            else {
				                                Util.MsgBox(true, "鄉鎮區域資料載入失敗，系統忙碌請稍候再試！");
				                            }
				                        }
				                    });
				                },
				                'render': function (combo) {
				                    if (Ext.isEmpty(o.recCounty)) return;
				                    combo.getStore().load({
				                        callback: function (r, options, success) {
				                            if (success == true) {
				                                combo.setValue(o.recCounty);
				                            }
				                        }
				                    });
				                }
				            }
				        }),
				        new Ext.form.ComboBox({
				            id: "_recArea",
				            applyTo: "_recArea",
				            hiddenName: "recArea",
				            hideLabel: true,
				            triggerAction: "all",
				            emptyText: "鄉鎮區域..",
				            mode: "local",
				            displayField: "text",
				            valueField: "value",
				            readOnly: true,
				            disabled: true,
				            allowBlank: false,
				            width: 90,
				            store: storeArea,
				            listeners: {
				                "select": function (combo) {
				                    var dom = Ext.getDom("recZip");
				                    if (dom != undefined) {
				                        dom.value = combo.getValue().split(':')[1];
				                    }
				                },
				                'render': function (cmp) {
				                    if (Ext.isEmpty(o.recCounty) || Ext.isEmpty(o.recArea)) return;
				                    storeArea.load({
				                        params: { cid: o.recCounty },
				                        callback: function (r, options, success) {
				                            if (success == true) {
				                                if (storeArea.getCount() > 0) {
				                                    cmp.setValue(o.recZip);
				                                    cmp.setDisabled(false);
				                                }
				                            }
				                        }
				                    });
				                }
				            }
				        }),
				        new Ext.form.TextField({
				            id: "recZip",
				            applyTo: "recZip",
				            allowBlank: false,
				            readOnly: true,
				            width: 50,
				            fieldClass: "field_null",
				            value: o.recZip || undefined
				        }),
				        new Ext.form.TextField({
				            id: "recAddress",
				            applyTo: "recAddress",
				            hideLabel: true,
				            emptyText: "輸入您的通訊地址",
				            maxLength: 128,
				            allowBlank: false,
				            style: 'margin:5px 0 0 0',
				            width: 450,
				            value: o.recAddr
				        }),
				        new Ext.form.RadioGroup({
				            id: "recTime",
				            renderTo: "recTimeBox",
				            hideLabel: true,
				            allowBlank: false,
				            columns: 3,
				            items: [{
				                name: "recTime",
				                inputValue: '1',
				                boxLabel: "早上",
				                autoWidth: true,
				                listeners: {
				                    "render": function () {
				                        if (o.recTime == '1') this.setValue(true);
				                    }
				                }
				            }, {
				                name: "recTime",
				                inputValue: '2',
				                boxLabel: "中午",
				                autoWidth: true,
				                listeners: {
				                    "render": function () {
				                        if (o.recTime == '2') this.setValue(true);
				                    }
				                }
				            }, {
				                name: "recTime",
				                inputValue: '3',
				                boxLabel: "晚上",
				                autoWidth: true,
				                listeners: {
				                    "render": function () {
				                        if (o.recTime == '3') this.setValue(true);
				                    }
				                }
				            }]
				        }),
                        new Ext.form.TextArea({
                            id: "note",
                            applyTo: "note",
                            hideLabel: true,
                            maxLength: 256,
                            width: 490,
                            height: 120,
                            value: o.note || ''
                        }),
				        new Ext.form.RadioGroup({
				            id: "VanSelect",
				            renderTo: "VanSelectBox",
				            hideLabel: true,
				            allowBlank: false,
				            width: "100%",
				            columns: 2,
				            items: [{
				                name: "VanSelect",
				                inputValue: '0',
				                boxLabel: "無",
				                autoWidth: true,
				                checked: true
				            }, {
				                name: "VanSelect",
				                inputValue: '1',
				                boxLabel: "與收貨人相同",
				                autoWidth: true
				            }],
				            listeners: {
				                "change": function (r, chk) {
				                    var sendName = Ext.getCmp('sendName');
				                    var sendCounty = Ext.getCmp('_sendCounty');
				                    var sendArea = Ext.getCmp('_sendArea');
				                    var sendZip = Ext.getCmp('sendZip');
				                    var sendTel1 = Ext.getCmp('sendTel1');
				                    var sendTel2 = Ext.getCmp('sendTel2');
				                    var sendAddr = Ext.getCmp('sendAddress');

				                    var recName = Ext.getCmp('recName');
				                    var recCounty = Ext.getCmp('_recCounty');
				                    var recArea = Ext.getCmp('_recArea');
				                    var recZip = Ext.getCmp('recZip');
				                    var recTel1 = Ext.getCmp('recTel1');
				                    var recTel2 = Ext.getCmp('recTel2');
				                    var recAddr = Ext.getCmp('recAddress');

				                    if (chk.inputValue == '1') {
				                        sendName.setValue(recName.getValue());
				                        sendZip.setValue(recZip.getValue());
				                        sendAddr.setValue(recAddr.getValue());
				                        sendTel1.setValue(recTel1.getValue());
				                        sendTel2.setValue(recTel2.getValue());

				                        //鄉鎮
				                        if (sendCounty.getStore().getCount() == 0) {
				                            sendCounty.getStore().load({
				                                callback: function (r, options, success) {
				                                    if (success == false) return;
				                                    sendCounty.setValue(recCounty.getValue());
				                                }
				                            });
				                        }
				                        else {
				                            sendCounty.setValue(recCounty.getValue());
				                        }

				                        //區域
				                        if (sendArea.getStore().getCount() == 0 &&
                                            !Ext.isEmpty(recCounty.getValue())) {
				                            sendArea.getStore().load({
				                                params: {
				                                    cid: recCounty.getValue()
				                                },
				                                callback: function (r, options, success) {
				                                    if (success == false) return;
				                                    sendArea.setValue(recArea.getValue());
				                                }
				                            });
				                        }
				                        else {
				                            if (!Ext.isEmpty(recArea.getValue()))
				                                sendArea.setValue(recArea.getValue());
				                        }

				                        if (!Ext.isEmpty(recArea.getValue()) && sendArea.disabled) {
				                            sendArea.setDisabled(false);
				                        }
				                    }
				                }
				            }
				        }),
                        new Ext.form.TextField({
                            id: "invNum",
                            applyTo: "invNum",
                            hideLabel: true,
                            maxLength: 60,
                            width: 300,
                            disabled: true,
                            value: o.invNum || "免填",
                            listeners: {
                                "blur": function () {
                                    if (Ext.ComponentMgr.get("_invType3").checked && this.getValue() == '') {
                                        this.markInvalid("選擇三聯發票必須填寫發票統一編號。");
                                    }
                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "invTitle",
                            applyTo: "invTitle",
                            hideLabel: true,
                            maxLength: 60,
                            width: 300,
                            disabled: true,
                            value: o.invTitle || "免填",
                            listeners: {
                                "blur": function () {
                                    if (Ext.ComponentMgr.get("_invType3").checked && this.getValue() == '') {
                                        this.markInvalid("選擇三聯發票必須填寫發票抬頭。");
                                    }
                                }
                            }
                        }),
                        new Ext.form.Radio({
                            id: "_invType1",
                            name: "invType",
                            renderTo: "invTypeBox",
                            inputValue: '0',
                            boxLabel: "一般發票",
                            listeners: {
                                "check": function (radio, chk) {
                                    if (!chk) return;
                                    Ext.ComponentMgr.get("invNum").setValue("免填");
                                    Ext.ComponentMgr.get("invTitle").setValue("免填");
                                    Ext.ComponentMgr.get("invNum").setDisabled(true);
                                    Ext.ComponentMgr.get("invTitle").setDisabled(true);
                                }
                            }
                        }),
                        new Ext.form.Radio({
                            id: "_invType2",
                            name: "invType",
                            renderTo: "invTypeBox",
                            inputValue: '1',
                            boxLabel: "二聯式發票",
                            listeners: {
                                "check": function (radio, chk) {
                                    if (!chk) return;
                                    Ext.ComponentMgr.get("invNum").setValue('');
                                    Ext.ComponentMgr.get("invTitle").setValue('');
                                    Ext.ComponentMgr.get("invNum").setDisabled(false);
                                    Ext.ComponentMgr.get("invTitle").setDisabled(false);
                                },
                                "render": function () {
                                    if (o.invType == '1') {
                                        this.setValue(true);
                                        Ext.ComponentMgr.get("invNum").setDisabled(false);
                                        Ext.ComponentMgr.get("invTitle").setDisabled(false);
                                        if (o.invNum != '') Ext.ComponentMgr.get("invNum").setValue(o.invNum);
                                        if (o.invTitle != '') Ext.ComponentMgr.get("invTitle").setValue(o.invTitle);
                                    }
                                }
                            }
                        }),
                        new Ext.form.Radio({
                            id: "_invType3",
                            renderTo: "invTypeBox",
                            name: "invType",
                            inputValue: '2',
                            boxLabel: "三聯式發票",
                            listeners: {
                                "check": function (radio, chk) {
                                    if (!chk) return;
                                    Ext.ComponentMgr.get("invNum").setValue('');
                                    Ext.ComponentMgr.get("invTitle").setValue('');
                                    Ext.ComponentMgr.get("invNum").setDisabled(false);
                                    Ext.ComponentMgr.get("invTitle").setDisabled(false);
                                },
                                "render": function () {
                                    if (o.invType == '2') {
                                        this.setValue(true);
                                        Ext.ComponentMgr.get("invNum").setDisabled(false);
                                        Ext.ComponentMgr.get("invTitle").setDisabled(false);
                                        if (o.invNum != '') Ext.ComponentMgr.get("invNum").setValue(o.invNum);
                                        if (o.invTitle != '') Ext.ComponentMgr.get("invTitle").setValue(o.invTitle);
                                    }
                                }
                            }
                        }),
				        new Ext.form.TextField({
				            id: "sendName",
				            applyTo: "sendName",
				            hideLabel: true,
				            emptyText: "請輸入姓名",
				            maxLength: 20,
				            minLength: 2,
				            allowBlank: false,
				            anchor: "100%",
				            value: o.sendName
				        }),
				        new Ext.form.ComboBox({
				            id: "_sendCounty",
				            applyTo: "_sendCounty",
				            hiddenName: "sendCounty",
				            hideLabel: true,
				            triggerAction: "all",
				            emptyText: "選擇縣市..",
				            mode: "remote",
				            displayField: "text",
				            valueField: "value",
				            readOnly: true,
				            allowBlank: false,
				            style: "margin-top:0px;",
				            width: 90,
				            store: storeCountySend,
				            listeners: {
				                "select": function (combo) {
				                    var cmp = Ext.ComponentMgr.get("_sendArea");
				                    var dom = Ext.getDom("sendZip");

				                    storeAreaSend.load({
				                        params: { cid: combo.getValue() },
				                        callback: function (r, options, success) {
				                            if (success == true) {
				                                if (storeAreaSend.getCount() > 0) {
				                                    cmp.setValue(r[0].get('value'));
				                                    dom.value = r[0].get('value').split(':')[1];
				                                    cmp.setDisabled(false);
				                                }
				                            }
				                            else {
				                                Util.MsgBox(true, "鄉鎮區域資料載入失敗，系統忙碌請稍候再試！");
				                            }
				                        }
				                    });
				                },
				                'render': function (combo) {
				                    if (Ext.isEmpty(o.sendCounty)) return;
				                    combo.getStore().load({
				                        callback: function (r, options, success) {
				                            if (success == true) {
				                                combo.setValue(o.sendCounty);
				                            }
				                        }
				                    });
				                }
				            }
				        }),
				        new Ext.form.ComboBox({
				            id: "_sendArea",
				            applyTo: "_sendArea",
				            hiddenName: "sendArea",
				            hideLabel: true,
				            triggerAction: "all",
				            emptyText: "鄉鎮區域..",
				            mode: "local",
				            displayField: "text",
				            valueField: "value",
				            readOnly: true,
				            disabled: true,
				            allowBlank: false,
				            width: 90,
				            store: storeAreaSend,
				            listeners: {
				                "select": function (combo) {
				                    var dom = Ext.getDom("sendZip");
				                    if (dom != undefined) {
				                        dom.value = combo.getValue().split(':')[1];
				                    }
				                },
				                'render': function (cmp) {
				                    if (Ext.isEmpty(o.sendCounty) || Ext.isEmpty(o.sendArea)) return;
				                    cmp.getStore().load({
				                        params: { cid: o.sendCounty },
				                        callback: function (r, options, success) {
				                            if (success == true) {
				                                if (cmp.getStore().getCount() > 0) {
				                                    cmp.setValue(o.sendZip);
				                                    cmp.setDisabled(false);
				                                }
				                            }
				                        }
				                    });
				                }
				            }
				        }),
				        new Ext.form.TextField({
				            id: "sendZip",
				            applyTo: "sendZip",
				            allowBlank: false,
				            readOnly: true,
				            width: 50,
				            fieldClass: "field_null",
				            value: o.sendZip
				        }),
				        new Ext.form.TextField({
				            id: "sendAddress",
				            applyTo: "sendAddress",
				            hideLabel: true,
				            emptyText: "輸入您的通訊地址",
				            maxLength: 128,
				            allowBlank: false,
				            style: 'margin:5px 0 0 0',
				            width: 450,
				            value: o.sendAddr
				        }),
				        new Ext.form.TextField({
				            id: "sendTel1",
				            applyTo: "sendTel1",
				            hideLabel: true,
				            maxLength: 20,
				            minLength: 6,
				            allowBlank: false,
				            anchor: "100%",
				            value: o.sendTel1
				        }),
				        new Ext.form.TextField({
				            id: "sendTel2",
				            applyTo: "sendTel2",
				            hideLabel: true,
				            maxLength: 20,
				            minLength: 6,
				            allowBlank: true,
				            anchor: "100%",
				            value: o.sendTel2
				        })
			        );
                },
                failure: function () {
                    Util.MsgBox(true, "資料讀取失敗，系統網路忙線中，<br/>請重新整理頁面或請稍候再試。");
                }
            });
        });
    },

    /**
    * 送出確認表單
    **/
    DoSubmit: function () {
        try {
            if (!Ext.ComponentMgr.get("recConcat").validate()) throw Error("您尚未選擇『聯絡時間』！");
            if (!Ext.ComponentMgr.get("recTime").validate()) throw Error("您尚未選擇『收貨時段』！");
            if (!Ext.ComponentMgr.get("_invType1").checked && !Ext.ComponentMgr.get("_invType2").checked && !Ext.ComponentMgr.get("_invType3").checked)
                throw Error("您尚未選擇『發票類型』！");

            if (ShoppingCart.form == null || !ShoppingCart.form.isValid()) throw Error("表單資料未填寫完整！");

            if (Ext.ComponentMgr.get("_invType3").checked && (Ext.ComponentMgr.get("invNum").getValue() == '' || Ext.ComponentMgr.get("invTitle").getValue() == '')) {

                if (Ext.ComponentMgr.get("invNum").getValue() == '') throw Error(true, "選擇三聯發票必須填寫發票統一編號。");
                if (Ext.ComponentMgr.get("invTitle").getValue() == '') throw Error(true, "選擇三聯發票必須填寫發票抬頭。");
            }

            ShoppingCart.form.submit({
                method: "POST",
                url: "Handler.aspx?fn=ConfirmForm",
                waitTitle: "系統訊息",
                waitMsg: "資料處理中，請稍候...",
                reset: false,
                success: function (form, action) {
                    var o, myMask;
                    try {
                        o = Ext.util.JSON.decode(action.response.responseText);
                        if (!o.success) throw Error();
                        myMask = new Ext.LoadMask(Ext.getBody(), { msg: "資料處理中，請稍候..." });
                        myMask.show();
                        location.href = "Member.aspx?u=Payment";
                    }
                    catch (e) {
                        Util.MsgBox(true, e.message);
                    }
                },
                failure: function (form, action) {
                    var o;
                    try {
                        o = Ext.util.JSON.decode(action.response.responseText);
                        throw Error(o.msg);
                    } catch (e) {
                        Util.MsgBox(true, e.message);
                    }
                }
            });
        }
        catch (e) {
            Util.MsgBox(true, e.message);
        }
    },

    /**
    * 移至單元
    **/
    GoTo: function (unit) {
        switch (unit) {
            default:
                location.href = "Default.aspx";
                break;

            case 0:
                location.href = "Member.aspx?u=ShoppingCart";
                break;

            case 1:
                location.href = "Member.aspx?u=Confirm";
                break;

            case 2:
                location.href = "Member.aspx?u=Payment";
                break;
        }
    },

    /**
    *　初始化付款表單
    **/
    InitPaymentForm: function () {
        new Ext.form.Radio({
            id: "_payBox0",
            name: "payment",
            inputValue: '0',
            boxLabel: "貨到付款"
        }).render("_payBox0");

        new Ext.form.Radio({
            id: "_payBox1",
            name: "payment",
            inputValue: '1',
            boxLabel: "銀行或郵局匯款"
        }).render("_payBox1");

        new Ext.form.Radio({
            id: "_payBox2",
            name: "payment",
            inputValue: '2',
            boxLabel: "ATM/金融卡轉帳"
        }).render("_payBox2");

        new Ext.form.Radio({
            id: "_payBox3",
            name: "payment",
            inputValue: '3',
            boxLabel: "線上刷卡"
        }).render("_payBox3");
    },

    /**
    * 付款
    */
    DoPay: function () {
        var pay = null;

        if (!Ext.ComponentMgr.get("_payBox0").checked && !Ext.ComponentMgr.get("_payBox1").checked &&
    		!Ext.ComponentMgr.get("_payBox2").checked && !Ext.ComponentMgr.get("_payBox3").checked) {
            Util.MsgBox(true, "您尚未選擇付款方式！");
            return;
        }

        for (var i = 0; i < 4; i++) {
            if (Ext.ComponentMgr.get(("_payBox" + i)).checked) {
                pay = i;
                break;
            }
        }

        Ext.Ajax.request({
            method: "POST",
            url: "Handler.aspx?fn=DoPay",
            params: { payment: pay },
            waitTitle: "系統訊息",
            waitMsg: "資料處理中，請稍候...",
            reset: false,
            success: function (response, options) {
                var o, myMask, d;
                try {
                    o = Ext.util.JSON.decode(response.responseText);
                    if (!o.success) throw Error(o.msg);
                    myMask = new Ext.LoadMask(Ext.getBody(), { msg: "資料處理中，請稍候..." });
                    myMask.show();

                    if (pay == 3) {
                        if (o.data == undefined || o.data == null || o.data == '') throw Error("商品金額資料錯誤，請重新整理頁面。");

                        d = Ext.decode(o.data);
                        if (d.orderTotal == '' || d.orderNum == '') throw Error("商品金額資料錯誤，請重新整理頁面。");

                        Ext.getDom("OrderTotal").value = d.orderTotal;
                        Ext.getDom("OrderNum").value = d.orderNum;
                        document.getElementById("PaymentForm").submit();
                    }
                    else {
                        location.href = "Member.aspx?u=OrderDetail";
                    }
                }
                catch (e) {
                    Util.MsgBox(true, e.message);
                }
            },
            failure: function (response, action) {
                var o;
                try {
                    o = Ext.util.JSON.decode(response.responseText);
                    throw Error(o.msg);
                }
                catch (e) {
                    Util.MsgBox(true, e.message);
                }
            }
        });
    },

    /**
    * 取消訂單
    */
    Cancel: function () {
        Util.ConfirmBox("您確定要取消該次的交易資料？", function (ans) {
            if (ans == "no") return;
            //讀取交易資料
            Ext.Ajax.request({
                url: "Handler.aspx?fn=Cancel",
                mode: "get",
                scope: this,
                success: function (response, options) {
                    var o = null;
                    try {
                        o = Ext.decode(response.responseText);
                        if (!o.success) throw new Error(o.msg);
                        Util.MsgBox(false, o.msg, function () {
                            location.href = "Default.aspx";
                        });
                    }
                    catch (e) {
                        Util.MsgBox(true, e.message);
                    }
                },
                failure: function () {
                    Util.MsgBox(true, "資料讀取失敗，系統網路忙線中，<br/>請重新整理頁面或請稍候再試。");
                }
            });
        });
    }
};

