//查询按钮
function groupTreeOnSelect(row) {
    $("#dgHotel").datagrid("load", { query: $("#txtQueryContent").val(), groupId: $("#groupTree").treegrid('getSelected').ID });
}
//修改密码
function changePassword() {
    var oldPassword = $("#iptOldPassword").val();
    if (oldPassword == "") {
        $("#iptOldPassword").focus();
        $.tools.alert(lang.PETOP);
        return;
    }
    var password = $("#iptPassword").val();
    if (password == "") {
        $("#iptPassword").focus();
        $.tools.alert(lang.PRANP);
        return;
    }
    var newPassword = $("#iptNewPassword").val();
    if (newPassword == "") {
        $("#iptNewPassword").focus();
        $.tools.alert(lang.PETCP);
        return;
    }
    if (newPassword != password) {
        $("#iptNewPassword").focus();
        $.tools.alert(lang.TPINCPIA);
        return;
    }
    var parm = { password: password, oldPassword: oldPassword };
    $.tools.post(parm, "/Home/ChangedPassword/", function () {
        $("#iptOldPassword").val("");
        $("#iptPassword").val("");
        $("#iptNewPassword").val("");
        $('#changePasswordDlg').window('close');
    }, this);
}
//分组格式化
function groupFormatter(value, rows) {
    return value + "(" + rows.length + ")";
}
//清除服务
function clearMsg(hostID, roomTypeModalID) {
    var params = { hostId: hostID, modalId: roomTypeModalID, status: 2, brightness: 0, temperature: 0, fanSpeed: 0, mode: 0, valve: 0 };
    $.tools.confrimPost(lang.RTRTCSR, params, "/LightControl/SetLight/", function (r) {
        if (r.IsSuccess) {
            $('#dgAlarm').datagrid('reload');
        }
    }, this);
}
//清除服务操作
function operationFormatter(val, row) {
    if (row.Name != "SOS" && row.Name != lang.GuestsAtTheDoorOpen && row.Name != lang.NoOneDoorOpen && row.Name != lang.NonGuestAtTheDoor) {
        var btn = "<a href='javascript:void(0)' onclick=clearMsg(" + row.HostID + "," + row.RoomTypeModalID + ")>" + lang.Remove + "</a>";
        return btn;
    }
    return "";
}
//选择当前酒店
function ddlHotelChange(newVal, oldVal) {
    if (oldVal != null && oldVal != "") {
        $.tools.post({ hotelID: newVal }, "/Home/SetCurrentHotel/", function (r) {
            window.location.reload();
        }, this, true);
    }
}
//切换酒店操作
function toggleHotelFormatter(val, row) {
    var btn = "<a href='javascript:void(0)' onclick=ddlHotelChange(" + row.ID + "," + row.ID + ")>" + lang.Toggle + "</a>";
    return btn;
}
//主机授权
//function accreditOk() {
//    $('#dialog2')
//				.find('.dlg-content').css({ height: '500px' })
//				.panel({ border: false, fit: true, href: '/Host/HostAuthorization/', queryParams: { password: $('#txtAuthorizationPassword').val()} }).end()
//				.dialog({ title: lang.HostAuthorization, width: 600, height: 400 })
//				.dialog('open');
//    $('#aboutDlg').window('close').find('input[type=password]').val('');
//}
//显示关于界面
function showAbout() {
    $("#aboutDlg").css('display', 'block');
    $.tools.post(null, "/Home/ProductInfo/", function (r) {
        $("#aboutDlg .Version").html(r.Data.Version);
        $("#aboutDlg .SerialNumber").html(r.Data.SerialNumber);
        //$("#aboutDlg .Limit").html(r.Data.Limit);
        $("#aboutDlg .CurrentHotel").html(r.Data.CurrentHotel);
        $("#aboutDlg .Expires").html(r.Data.Expires);
        $('#aboutDlg').window('open');
    }, this, true);
}

var playing = false;
var playing1 = false;
var playing2 = false;
var playing3 = false;
var viewModel = null;
var timeoutID0 = null;
//定时刷新数据
function startTimeRefresh() {
    window.clearTimeout(timeoutID0);
    timeoutID0 = null;
    viewModel.refreshRoomStatistics(function () {
        timeoutID0 = setTimeout("startTimeRefresh()", 10000);
    });
}

$(function () {
    $.ajax({
        url: "/Home/LoadMenu/",
        type: "POST",
        dataType: "json",
        cache: true,
        success: function (r) {
            //装载有权限酒店
            if (null != r.HotelName) {
                $('#curHotel').html(r.HotelName);
                if (r.LogoPath != "" && window.location.host.indexOf("blv") == -1) {
                    $('#logo').html("<img alt='' src='" + r.LogoPath + "' />");
                }
                if (r.IsExpire) {
                    showAbout();
                }
                $('#home').attr('src', '/RoomStatus/Index/');
            }
            function activeMenuItem(jq, menuPanel) {
                jq.addClass("active").siblings(".active").removeClass(function () {
                    var m1 = $(this).data();
                    $(this).find(".icon").removeClass(m1.Icon).addClass(m1.Icon + "-inactive");
                    return "active";
                });
                menuPanel.find(".my-menu-item").hide().eq(jq.index()).show();
                var m = jq.data();
                if (m) {
                    jq.find(".icon").removeClass(m.Icon + "-inactive").addClass(m.Icon);
                }
            }

            var menuBar = $("#menu > ul").html("");
            var menuPanel = $("#menu .panel ul").html("");
            $.each(r.MenuData, function (i, n) {
                $("<li class='my-menu-item'><span class='icon " + n.Icon + "-inactive'>&nbsp;</span><span class='text'>" + n.Name + "</span></li>")
					.data(n)
					.bind("mouseover", function () { activeMenuItem($(this), menuPanel); })
					.appendTo(menuBar);
                var li = $("<li class='my-menu-item'></li>").appendTo(menuPanel);
                if (n.Items.length != 0) {
                    $.each(n.Items, function (ii, nn) {
                        if (ii != 0) { li.append(" | "); }
                        $("<a href='" + nn.Url + "' target='main'>" + nn.Name + "</a>").click({ name: nn.Name, parentName: n.Name }, function (e) {
                            menuPanel.find("a").removeClass("active");
                            $(this).addClass("active");
                        }).appendTo(li);
                    });
                }
            });
            activeMenuItem(menuBar.find("li:first"), menuPanel);
        }
    });

    $("#menu > ul li:first").addClass("active");
    $("#menu .panel ul  li").hide().first().show();

    $("#menu > ul li").bind("mouseover", function () {
        $(this).addClass("active").siblings(".active").removeClass("active");
        $("#menu .panel ul  li").hide().eq($(this).index()).show();
    });

    function ViewModel() {
        var self = this;
        //登录用户信息
        //self.User = ko.observable();
        //客房统计信息
        self.Statistics = ko.observable();
        //显示故障提醒
        self.showPeripheral = function () {
            $("#dgPeripheral").propertygrid({ url: "/RoomService/LoadCurrentHostFault/" });
            $("#peripheralDlg").window("open");
        };
        //显示服务提醒窗口
        self.showServiceMsg = function () {
            $("#dgAlarm").propertygrid({ url: "/RoomService/LoadCurrentRoomServices/" });
            $("#serviceAlertDlg").window("open");
        };
        //显示有权限的酒店列表
        self.showHotels = function () {
            $("#hotelDlg").window("open");
            $("#dgHotel").propertygrid({ url: "/Home/GetCurrentHotel?groupId=" + $("#groupTree").treegrid('getSelected').ID });
        };
        //显示修改密码窗口
        self.showChangePassword = function () {
            $('#changePasswordDlg').window('open');
        };
        //注销
        self.logout = function () {
            $.messager.confirm(lang.Prompt, lang.ConfirmLogOut, function (r) {
                if (r) window.location.href = '/Home/LogOut/';
            });
            //$.tools.alert("我的提示，我的提示，我的提示，我的提示，我的提示，我的提示，我的提示。");
            //$.messager.alert("操作提示", "请完善商品信息！", "warning");
        };
        //显示关于对话框
        self.showAbout = function () { showAbout() };
        //刷新客房统计信息
        self.refreshRoomStatistics = function (callback) {
            $.ajax({
                url: "/RoomStatus/LoadRoomStatistics/",
                type: "POST",
                dataType: "json",
                success: function (r) {
                    if (r.IsSuccess) {
                        self.Statistics(r.Data);
                        for (var i in r.Data.Services) {
                            switch (r.Data.Services[i].Code) {
                                case "004000008": //sos
                                    playing = false;
                                    $('#jplayer').jPlayer("pause");
                                    if (r.Data.Services[i].Beep && r.Data.Services[i].Value > 0) {
                                        if (!playing) {
                                            playing = true;
                                            $('#jplayer').jPlayer("play");
                                        }
                                    }
                                    break;
                                case "004000003": //清理
                                    playing1 = false;
                                    $('#jplayer1').jPlayer("pause");
                                    if (r.Data.Services[i].Beep && r.Data.Services[i].Value > 0) {
                                        if (!playing1) {
                                            playing1 = true;
                                            $('#jplayer1').jPlayer("play");
                                            break;
                                        }
                                    }
                                    break;
                                case "004000004": //呼叫
                                    playing2 = false;
                                    $('#jplayer2').jPlayer("pause");
                                    if (r.Data.Services[i].Beep && r.Data.Services[i].Value > 0) {
                                        if (!playing2) {
                                            playing2 = true;
                                            $('#jplayer2').jPlayer("play");
                                            break;
                                        }
                                    }
                                    break;
                                case "004000006": //退房
                                    playing3 = false;
                                    $('#jplayer3').jPlayer("pause");
                                    if (r.Data.Services[i].Beep && r.Data.Services[i].Value > 0) {
                                        if (!playing3) {
                                            playing3 = true;
                                            $('#jplayer3').jPlayer("play");
                                            break;
                                        }
                                    }
                                    break;
                            }
                        } //end for (var i in r.Data.Services)                        
                    } else {
                        window.location.href = '/Home/LogOut/';
                    }
                    r.Data = null;
                    callback && callback();
                },
                error: function (request, status, error) {
                    callback && callback();
                }
            });
        };
    }

    viewModel = new ViewModel();
    ko.applyBindings(viewModel);
    startTimeRefresh();

    //sos
    $('#jplayer').jPlayer({
        ready: function () {
            $(this).jPlayer('setMedia', { mp3: '/Sounds/sos.wav' }).jPlayer('repeat');
        },
        swfPath: '/Scripts/jplayer/',
        supplied: 'mp3'
    });
    //清理
    $('#jplayer1').jPlayer({
        ready: function () {
            $(this).jPlayer('setMedia', { mp3: '/Sounds/clear.wav' }).jPlayer('repeat');
        },
        swfPath: '/Scripts/jplayer/',
        supplied: 'mp3'
    });
    //呼叫
    $('#jplayer2').jPlayer({
        ready: function () {
            $(this).jPlayer('setMedia', { mp3: '/Sounds/call.wav' }).jPlayer('repeat');
        },
        swfPath: '/Scripts/jplayer/',
        supplied: 'mp3'
    });
    //退房
    $('#jplayer3').jPlayer({
        ready: function () {
            $(this).jPlayer('setMedia', { mp3: '/Sounds/checkout.wav' }).jPlayer('repeat');
        },
        swfPath: '/Scripts/jplayer/',
        supplied: 'mp3'
    });
});
