var ServerUrl = window.top.location.protocol + "//" + window.top.location.hostname + ":" + window.top.location.port + "/";

$(document).ready(function() {   
 
    $("#close_x").click(function() {
        $("#div_Cpsx").hide();
    });
    $("input[id$='tbCount']").blur(function() {
        var max = $(this).attr("no");
        var value = $(this).val();
        if (!/(^[0-9]*$)/.test(value)) {
            alert("请输入大于0的整数");
            $(this).val("1");
            return;
        }
        if ($(this).val() == "0") {
            alert("请输入大于0的整数");
            $(this).val("1");
            return;
        }
    });

    $("input[name^='input_count']").blur(function() {
        var value = $(this).val();
        if (!/(^[0-9]*$)/.test(value)) {
            alert("请输入大于0的整数");
            $(this).val("1");
            return;
        }
        if (value == "0") {
            alert("请输入大于0的整数");
            $(this).val("1");
            return;
        }
    });
});


function aEnterClick() {

    var suiteId = $("input[name='suiteId']").val();
    var count = $("input[id$='tbCount']").val();
    if (!/(^[0-9]*$)/.test(count)) {
        alert("请输入大于0的整数");
        return;
    }
    if (count == "0") {
        alert("请输入大于0的整数");
        return;
    }
    var shopId = $("input[name='shopId']").val();
    var orderId = $("input[name='subOrderId']").val();
    var selectedFoods = $("input[name='foodName']").val();
    var foodId = $("input[name='foodId']").val();
    FoodInfo.AddIoCar(suiteId, count, selectedFoods, shopId, orderId, foodId, 1);
}

function addToCarClick(_this) {

    var o = $(_this).parent().parent();
    var suiteId = $(_this).attr("value");
    var count = $(o).find("input[name='input_count_" + suiteId + "']").val();
    var shopId = $("input[name='shopId']").val();
    var orderId = $("input[name='subOrderId']").val();
    var selectedFoods = $("input[name='foodName']").val();
    var flag = "";
    var foodId = $("input[name='foodId']").val();
    $(o).find("td[name='td_SuitInfo']").find("option[selected],span").each(function(i, n) {
        selectedFoods = selectedFoods + flag + $(n).html();
        flag = "|";
    });
    FoodInfo.AddIoCar(suiteId, count, selectedFoods, shopId, orderId, foodId, 0);
}

function SubmitSuit(txt) {
    var text = "";
    alert($("tr[value='" + txt + "']").html());
    $(this).parent().prev().children().each(function() {
        text = text + $(this).attr("value");
        if ($(this).is("select")) {
            text = text + $(this).find("option[selected]").html() + ";";
        }
        else {
            text = text + $(this).html() + ";";
        }
    });
    return confirm(text);
};

FoodInfo = {};
FoodInfo.subFood = { SuiteID: 0, Count: 0, FoodId: 0, Type: 0 }

FoodInfo.AddIoCar = function(suiteId, count, selectedFoods, shopId, orderId, foodId, type) {
    FoodInfo.subFood.SuiteID = suiteId;
    FoodInfo.subFood.Count = count;
    FoodInfo.subFood.FoodId = foodId;
    FoodInfo.subFood.Type = type;
    $.ajax({
        url: "/PageHandler.ashx",
        data: "className=PersonalUser&methodName=AddFoodToShopingTrolley&parameter=" + suiteId + "," + count + "," + encodeURI(selectedFoods) + "," + shopId + "," + orderId + "," + foodId,
        dataType: 'json',
        cache: false,
        success: function(data) {
            FoodInfo.OnSuccess(data, shopId);
        },
        complete: function(XMLHttpRequest, textStatus) {
            //                $("#div_peican_rq").dialog("open");
            //alert("操作完成");
        },
        error: function(data) {
            alert("放入餐盒 操作失败!");

        }
    });
}
FoodInfo.OnSuccess = function(data, shopId) {

    if (data.IsSuccess == "true") {
        $("input[name='subOrderId']").val(data.OrderId);
        MealBox.Item.GetMealList(data, shopId);
        ShowMealBox();
    }
    else {
        switch (data.ErrID) {
            case "1":
                $.ajax({
                    url: "/PageHandler.ashx",
                    data: "className=Orders&methodName=SetOrderFoodCache&parameter=" + FoodInfo.subFood.FoodId + "," + FoodInfo.subFood.SuiteID + "," + FoodInfo.subFood.Count + "," + FoodInfo.subFood.Type,
                    dataType: 'json',
                    cache: false,
                    success: function(data) {
                    },
                    error: function(data) {
                    }
                });
                LoginLayer.Show();
                break;
            case "2":
                if (confirm("您还没有添加送餐地址，现在添加吗？")) {
                    $.ajax({
                        url: "/PageHandler.ashx",
                        data: "className=Orders&methodName=SetOrderFoodCache&parameter=" + FoodInfo.subFood.FoodId + "," + FoodInfo.subFood.SuiteID + "," + FoodInfo.subFood.Count + "," + FoodInfo.subFood.Type,
                        dataType: 'json',
                        cache: false,
                        success: function(data) {
                        },
                        error: function(data) {
                        }
                    });
                    ShowAddress();
                }
                break;
            case "3":
                if (confirm("该店铺不支持送到您的楼宇，确认更换地址吗？")) {
                    $.ajax({
                        url: "/PageHandler.ashx",
                        data: "className=Orders&methodName=SetOrderFoodCache&parameter=" + FoodInfo.subFood.FoodId + "," + FoodInfo.subFood.SuiteID + "," + FoodInfo.subFood.Count + "," + FoodInfo.subFood.Type,
                        dataType: 'json',
                        cache: false,
                        success: function(data) {
                        },
                        error: function(data) {
                        }
                    });
                    ShowAddress();
                }
                break;
            case "4":
                var errorMessage = data.ErrMessage;
                if (confirm("您放入的菜品不在同一店铺，确认清空饭盒放入新菜品吗？")) {

                    var orderId = $("input[name='subOrderId']").val();
                    $.ajax({
                        url: "/PageHandler.ashx",
                        data: "className=PersonalUser&methodName=ClearOrder&parameter=" + orderId,
                        dataType: 'json',
                        cache: false,
                        success: function(data) {
                            MealBox.Item.GetUnCompletedOrder();
                            ShowMealBox();
                            var str = errorMessage.split(",");
                            FoodInfo.AddIoCar(str[0], str[1], str[2], str[3], 0, str[5], FoodInfo.subFood.Type);
                        },
                        error: function(data) {
                            window.location.href = ServerUrl + "Error.aspx";
                        }
                    });
                }
                break;
            case "5":
                alert(data.ErrMessage);
                break;
            case "6":
                ShowSendAddress();
                break;
            case "7":
                if (confirm("您的订餐店铺与您参加的团购订餐店铺不符，确定退出您要参加的团购吗？")) {
                    MealBox.Item.ClearShopName();
                    ShowMealBox();
                }
                break;
            //            case "8": 
            //                alert("您订的菜品数量不能超出每天菜品上限数量。"); 
            //                break; 
            case "10":
                alert("对不起，该店铺已停业，暂不支持订餐。");
                break;
            default:
                break;
        }
    }
}
  var t = new j.overLayer({color:"#000"});
  function ShowAddress() {
      $(document).ready(function() {
          $("#div_address").dialog({ autoOpen: false, width: 700, height: 450, title: "我的收餐地址", modal: true, close: function() { t.hide(); ClearCeChe(); } });
          t.show();
          $("#div_address").dialog("open");
          SendAddress.Init();
      })

  }

function ClearCeChe() {
    $.ajax({
        url: "/PageHandler.ashx",
        data: "className=Utility&methodName=ClearCaChe",
        dataType: 'json',
        cache: false,
        success: function(data) {

        },
        error: function(data) {
        }
    });
}

/************************************************************************/
/* 套餐信息                                                                     */
/************************************************************************/
var CpInputItems = {};
CpInputItems = function() {
    _self = this;
    this.Title = "";
    this.Name = "";

    this.Html = "";
    this.Td_col_03_html = "";
    this.NameIndex = 0;
    this.ID = "";

    //初始化 Name(zhucai,tang) 表头（主菜，主食）
    this.Init_Name_Title = function(n) {

        switch (n) {
            case "0": _self.Name = "zhucai"; _self.Title = "主菜"; break;
            case "1": _self.Name = "zhushi"; _self.Title = "主食"; break;
            case "2": _self.Name = "tang"; _self.Title = "汤"; break;
            case "3": _self.Name = "qita"; _self.Title = "其他"; break;
            default: break;
        }
        _self.NameIndex = n;
    };
    //初始化 NameIndex 表头（主菜，主食）
    this.Init_NameIndex_Title = function(name) {

        _self.Name = name;
        switch (name) {
            case "zhucai": _self.Title = "主菜"; _self.NameIndex = 0; break;
            case "zhushi": _self.Title = "主食"; _self.NameIndex = 1; break;
            case "tang": _self.Title = "汤"; _self.NameIndex = 2; break;
            case "qita": _self.Title = "其他"; _self.NameIndex = 3; break;
            default: break;
        }
    };
    //获取编辑列 input项
    this.GetInputItems = function(content, id) {

        ///配菜列
        var _html_lie = "";
        var text_tr = "";
        var trs = content.split("~");


        if (content == "")
            _html_lie = "<span  name=\"lei_" + _self.ID + "\"></span>";
        if (trs != "" && trs.length == 1) {//class=\"pp_list\"
            _html_lie = _html_lie + "<span name=\"lei_" + _self.ID + "\">" + trs[0] + "</span>";
        }
        if (trs.length > 1) {
            _html_lie = _html_lie + "<select name=\"lei_" + _self.ID + "\">";
            $(trs).each(function(i, n) {
                _html_lie = _html_lie + "<option>" + n + "</option>";
            });
            _html_lie = _html_lie + "</select>";
        }

        _self.Td_col_03_html = _html_lie;
        return text_tr;
    };
    //初始化  生成整个编辑列Html
    this.Init_InputItems_Html = function(str) {
        var type = str.split("@")[0];

        _self.Init_Name_Title(type);
        _self.ID = (new Date()).getTime() + Math.random();

        var _html_lie = "";
        var text_tr = "";
        var content = "";
        if (str.split("@").length >= 2)
            content = str.split("@")[1];
        //配菜列
        text_tr = _self.GetInputItems(content, _self.ID);

    };
};

//获取 配菜字符串
function GetContainsFoodStr() {

    var _html_lie = "";
    $("#div_pc_le_list").find("div[class='lei_list']").each(function(i, n) {
        //
        var cpInputItems = new CpInputItems();
        cpInputItems.Init_NameIndex_Title($(n).attr("name"));

        var text_2 = "";
        $(n).find("input:not(:last)").each(function(i, n) { text_2 = text_2 + $(n).val() + "~"; });
        if (text_2 != "") {
            text_2 = text_2.substring(0, text_2.length - 1);
            _html_lie = _html_lie + cpInputItems.NameIndex + "@" + text_2 + "|";
        }
    });

    _html_lie = _html_lie.substring(0, _html_lie.length - 1);
    //
    return _html_lie;
}

//填充td_col_03 配置列 td 03
function td_col_03(ContainsFoods, SuiteId, id) {

    var suits = ContainsFoods.split("|");
    var str = "";
    //
    $(suits).each(function(i, a) {

        var suiteItemsFoodInfo = new SuiteItemsFoodInfo();
        str = str + suiteItemsFoodInfo.GetSuiteFoodHtml(id, a, SuiteId)
    });
    return str;
}

