var senparc = {};
var maxSubMenuCount = 5;
var menuState;
var hiddenMask = $('#hiddenMask');
function stopBubble(e) {
    if (e && e.stopPropagation) {
        e.stopPropagation();
    } else {
        window.event.cancelBubble = true;
    }
}
senparc.menu = {
    token: '',
    init: function () {
        menuState = $('#menuState');
        //重新配置微信开发者帐号信息
        $("#anewSetWeiXin").click(function () {
            hiddenMask.css('display', 'block');
            $("#menuLogin").css('display', 'block').stop().animate({ top: 0 }, 500).one('dblclick', function () {
                $(this).stop().animate({ top: -134 }, 500, function () {
                    hiddenMask.css('display', 'none');
                    $(this).css('display', 'none');
                    $('#masking').css('display', 'none');
                });
            });
            $('#masking').css('display', 'block');
        });
        $('#buttonDetails').click(function (e) {
            stopBubble(e);
        }).hide();

        $("#buttonDetails_type").change(senparc.menu.typeChanged);

        $(':input[id^=menu_button]').click(function (e) {
            stopBubble(e); //阻止冒泡
            var posiLeft = $(this).offset().left - 150;
            var posiTop = $(this).offset().top + 35;
            $('#buttonDetails').css({ left: posiLeft, top: posiTop }).stop().show();
            $(window).one('click', function () {
                $('#buttonDetails').stop().hide();
            });

            var idPrefix = $(this).attr('data-root')
                            ? ('menu_button' + $(this).attr('data-root'))
                            : ('menu_button' + $(this).attr('data-j') + '_sub_button' + $(this).attr('data-i'));

            var keyId = idPrefix + "_key";
            var nameId = idPrefix + "_name";
            var typeId = idPrefix + "_type";
            var urlId = idPrefix + "_url";

            var txtDetailsKey = $('#buttonDetails_key');
            var txtDetailsName = $('#buttonDetails_name');
            var ddlDetailsType = $('#buttonDetails_type');
            var txtDetailsUrl = $('#buttonDetails_url');
            var txtDetails_internet = $("#buttonDetails_internet");

            var hiddenButtonKey = $('#' + keyId);
            var hiddenButtonType = $('#' + typeId);
            var hiddenButtonUrl = $('#' + urlId);

            txtDetailsKey.val(hiddenButtonKey.val());
            txtDetailsName.val($('#' + nameId).val());
            ddlDetailsType.val(hiddenButtonType.val());
            txtDetailsUrl.val(hiddenButtonUrl.val());


            senparc.menu.typeChanged();

            txtDetailsKey.unbind('blur').blur(function () {
                hiddenButtonKey.val($(this).val());
            });
            ddlDetailsType.unbind('blur').blur(function () {
                hiddenButtonType.val($(this).val());
            });
            txtDetailsUrl.unbind('blur').blur(function () {
                hiddenButtonUrl.val($(this).val());
            });
            txtDetails_internet.unbind('change').change(function () {
                txtDetailsUrl.val($(this).val());
                hiddenButtonUrl.val($(this).val());
            });
        });
        $("#help").click(function (e) {//帮助
            stopBubble(e);
            hiddenMask.css('display', 'block');
            $("#helpBar").css('display', 'block').stop().animate({ top: 0 }, 400);
            $(window).one('click', function () {
                $("#helpBar").stop().animate({ top: -140 }, 400, function () {
                    hiddenMask.css('display', 'none');
                    $(this).css('display', 'none');
                });
            });
        });
        $('#menuLogin').click(function (e) {
            stopBubble(e);
        });
        $("#helpBar").click(function (e) {
            stopBubble(e);
        });
        $('#menuLogin_Submit').click(function () {
            //发送POST请求，数据也是json格式。但数值部分需要转换为字符串
            $.post("/WeiXin/SetMenu.ashx",
                { dotype: "GetToken", appId: $('#menuLogin_AppId').val(), appSecret: $('#menuLogin_AppSecret').val() },
                 function (result) {
                     if (result == -1) {
                         top.showTipsMsg('Save information failed, please check your AppId and AppSecret is correct', 3000, 5);
                         return;
                     }
                     $("#menuLogin").stop().animate({ top: -134 }, 500, function () {
                         hiddenMask.css('display', 'none');
                         $(this).css('display', 'none');
                         $('#masking').css('display', 'none');
                         top.showTipsMsg('Configuration saved successfully.', 1500, 4);
                     });
                     senparc.menu.setToken(result);
                 });
        });
        $('#btnGetMenu').click(function () {
            menuState.html('Get menu...');
            $.post('/WeiXin/SetMenu.ashx', { dotype: "GetMenu", token: senparc.menu.token }, function (json) {
                if (json.menu) {
                    $(':input[id^=menu_button]:not([id$=_type])').val('');
                    $('#buttonDetails:input').val('');

                    var buttons = json.menu.button;
                    //此处i与j和页面中反转
                    for (var i = 0; i < buttons.length; i++) {
                        var button = buttons[i];
                        $('#menu_button' + i + '_name').val(button.name);
                        $('#menu_button' + i + '_key').val(button.key);
                        $('#menu_button' + i + '_type').val(button.type || 'click');
                        $('#menu_button' + i + '_url').val(button.url);

                        if (button.sub_button && button.sub_button.length > 0) {
                            //二级菜单
                            for (var j = 0; j < button.sub_button.length; j++) {
                                var subButton = button.sub_button[j];
                                var idPrefix = '#menu_button' + i + '_sub_button' + j;
                                $(idPrefix + "_name").val(subButton.name);
                                $(idPrefix + "_type").val(subButton.type || 'click');
                                $(idPrefix + "_key").val(subButton.key);
                                $(idPrefix + "_url").val(subButton.url);
                            }
                        } else {
                            //底部菜单
                            //...
                        }
                    }
                    menuState.html('Has been completed');
                } else {
                    menuState.html(json.error || 'The implementation process there is an error, please check!');
                }
            });
        });

        $('#btnDeleteMenu').click(function () {
            if (!confirm('Are you sure you want to delete menu? This operation cannot be revoked!')) {
                return;
            }

            menuState.html('Delete menu...');
            $.post('/WeiXin/SetMenu.ashx', { dotype: "DeleteMenu", token: senparc.menu.token }, function (json) {
                alert(json + "---" + json.Success);
                if (json.Success) {
                    menuState.html('Successfully deleted, if accidentally deleted, and the new menu state interface, can immediately click the [update] button to the server.');
                } else {
                    menuState.html(json.Message);
                }
            });
        });

        $('#submitMenu').click(function () {
            if (!confirm('Sure you want to submit? This operation cannot be revoked!')) {
                return;
            }
            //alert(senparc.menu.token);
            menuState.html('Upload...');

            $('#form_Menu').ajaxSubmit({
                dataType: 'json',
                success: function (json) {
                    if (json.Successed) {
                        menuState.html('Uploaded successfully');
                    } else {
                        menuState.html(json.Message);
                    }
                }
            });
        });
    },
    typeChanged: function () {
        var val = $('#buttonDetails_type').val();
        switch (val.toUpperCase()) {
            case "CLICK":
                $('#buttonDetails_key_area').slideDown(100);
                $('#buttonDetails_url_area').slideUp(100);
                $('#buttonDetails_internet_area').slideUp(100);
                break;
            case "VIEW":
                $('#buttonDetails_key_area').slideUp(100);
                $('#buttonDetails_url_area').slideDown(100);
                $('#buttonDetails_internet_area').slideDown(100);
                break;
            default:
                //                $('#buttonDetails_internet_area').slideDown(100);
                //                $('#buttonDetails_key_area').slideUp(100);
                //                $('#buttonDetails_url_area').slideUp(100);
                break;
        }
    },
    setToken: function (token) {
        if (!token) {
            if (jQuery.trim($('#tokenStr').val()).length < 1) {//没有关于微信app配置信息
                hiddenMask.css('display', 'block');
                $("#menuLogin").css('display', 'block').stop().animate({ top: 0 }, 500);
                $('#masking').css('display', 'block');
            } else {
                senparc.menu.token = $('#tokenStr').val();
                $('#btnGetMenu').click();
            }
        } else {
            senparc.menu.token = token;
            $('#tokenStr').val(token);
            $('#btnGetMenu').click();
        }
    }
};