function postJson(url, data, success, error) {
    $.ajax({
        type: "post",
        url: url,
        contentType: "application/json",
        data: JSON.stringify(data),
        dataType: "json",
        success: success,
        error: error
    });
}
function successMessage(ele, message) {
    ele.html(message);
    ele.css('color', 'green');
    ele.fadeIn();
    setTimeout(function () { ele.fadeOut(); }, 2500);
}
function failMessage(ele, message) {
    ele.html(message);
    ele.css('color', 'red');
    ele.fadeIn();
    setTimeout(function () { ele.fadeOut(); }, 2500);
}
String.prototype.trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
}
String.prototype.ltrim = function () {
    return this.replace(/(^\s*)/g, "");
}
String.prototype.rtrim = function () {
    return this.replace(/(\s*$)/g, "");
}
String.prototype.endWith = function (str) {
    if (str == null || str == "" || this.length == 0 || str.length > this.length)
        return false;
    if (this.substring(this.length - str.length) == str)
        return true;
    else
        return false;
    return true;
}
String.prototype.startWith = function (str) {
    if (str == null || str == "" || this.length == 0 || str.length > this.length)
        return false;
    if (this.substr(0, str.length) == str)
        return true;
    else
        return false;
    return true;
}

function search() {
    var searchWord = $('#searchWord').val().trim();
    if (searchWord != '') {
        document.location = '/Articles/Search?wd=' + encodeURIComponent(searchWord);
    } else {
        $('#searchWord').val('');
    }
}

function searchEnter() {
    if (event.keyCode == '13') {
        search();
    }
}
$(function () {
    if ($('#currSearchWord').length > 0) {
        $('#searchWord').val($('#currSearchWord').html());
    }
})


var curr = 0;
var fiLength = 0;
function run() {
    if (curr >= fiLength-1) {
        $('.flashimages-container a:eq(' + curr + ')').hide();
        $('.flashimages-container a:eq(0)').show();
        $('.flashimages-description span:eq(' + curr + ')').hide();
        $('.flashimages-description span:eq(0)').show();
    } else {
        $('.flashimages-container a:eq(' + curr + ')').hide();
        $('.flashimages-container a:eq(' + (curr + 1) + ')').show();
        $('.flashimages-description span:eq(' + curr + ')').hide();
        $('.flashimages-description span:eq(' + (curr + 1) + ')').show();
    }
    curr++;
    if (curr >= fiLength) curr = 0;
    setTimeout(run, 3000);
}
$(function () {
    fiLength = $('.flashimages .flashimages-container a').length;
    if (fiLength > 1) {
        setTimeout(run, 3000);
    }
});
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}

var autoLogin = false;
$('#auto-login').click(function () {
    autoLogin = true;
    $(this).hide();
    $('#auto-login-checked').show();
});
$('#auto-login-checked').click(function () {
    autoLogin = false;
    $(this).hide();
    $('#auto-login').show();
});

function login() {
    postJson("/Web/Login", { LoginId: $('#loginForm input[name="LoginId"]').val(), Password: $('#loginForm input[name="Password"]').val(), VerificationCode: $('#loginForm input[name="VerificationCode"]').val(), autoLogin: autoLogin }, function(response) {
        if (response.Success == true) {
            var from = GetQueryString('from');
            if (from != null) {
                document.location = from;
            } else {
                location.reload();
            }
        } else {
            refreshVerificationCode('loginForm');
            showAlert('loginForm', response.Message);
        }
    }, function() {
        showAlert('loginForm', '登陆失败');
        refreshVerificationCode('loginForm');
    });
}

$('#btnLogin').click(function () {
    login();
});
function toRegister() {
    $('#loginForm').hide();
    $('#loginForm .alert').hide();
    $('#loginForm .alert').html('');
    $('#loginForm input').val('');
    $('#registerForm').show();
    $('.login-text').html('注册');
}
function toLogin() {
    $('#loginForm').show();
    $('#registerForm').hide();
    $('#registerForm .alert').hide();
    $('#registerForm .alert').html('');
    $('#registerForm input').val('');
    $('.login-text').html('登录');
}
function register() {
    postJson("/Web/Login/Register", { LoginId: $('#registerForm input[name="LoginId"]').val(), Password: $('#registerForm input[name="Password"]').val(), RePassword: $('#registerForm input[name="RePassword"]').val(), VerificationCode: $('#registerForm input[name="VerificationCode"]').val() }, function (response) {
        if (response.Success == true) {
            location.reload();
        } else {
            refreshVerificationCode('registerForm');
            showAlert('registerForm', response.Message);
        }
    }, function () { showAlert('registerForm', '注册失败'); refreshVerificationCode('registerForm'); });
}

$('#btnRegister').click(function () {
    register();
});
function showAlert(id, msg) {
    var el = $('#' + id + ' .alert');
    el.html(msg);
    el.show();
}
function resetAlert(id) {
    var el = $('#' + id + ' .alert');
    el.html('');
    el.hide();
    $('#' + id + ' input').val('');
}

function refreshVerificationCode(id) {
    var el = $('#' + id + ' img');
    el.attr('src', '/Utility/VerificationCodeImage?v=' + Math.random());
}

function del(path, id, warn) {
    if (warn == undefined) {
        warn = '删除后无法恢复，是否继续？';
    }
    if (confirm(warn)) {
        postJson(path, { id: id }, function (response) {
            if (response.Success == true) {
                location.reload();
            } else {
                alert(response.Message);
            }
        }, function () {
            alert(response.Message);
        });
    }
}
$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

function showSuccess(msg) {
    $('.alert').addClass('hide');
    $('.alert').addClass('alert-success');
    $('.alert').html(msg);
    $('.alert').removeClass('hide');
}

function showDanger(msg) {
    $('.alert').addClass('hide');
    $('.alert').addClass('alert-danger');
    $('.alert').html(msg);
    $('.alert').removeClass('hide');
}
$('input[name="VerificationCode"]').keyup(function (event) {
    if (event.keyCode == 13) {
        var id = $(this).attr('id');
        if (id == 'loginVerificationCode') {
            login();
        } else {
            register();
        }
    }
});

$(window).scroll(function () {
    if ($(window).scrollTop() > 100) {
        $(".to-top").fadeIn();
    }
    else {
        $(".to-top").fadeOut();
    }
});

$(".to-top").click(function () {
    if ($('html').scrollTop()) {
        $('html').animate({ scrollTop: 0 }, 500);
        return false;
    }
    $('body').animate({ scrollTop: 0 }, 500);
    return false;
});
function signIn() {
    $('#signIn').removeAttr('onclick');
    postJson('/Web/Users/SignIn', null, function (response) {
        if (response.Success == true) {
            changeBar(response.Data);
            $('#signIn').attr('class', 'label label-default');
            $('#signIn').html('已签到');
        } else {
            alert(response.Message);
        }
    });
}
function changeBar(data) {
    $('.userinfo-lv span').html('Lv' + data.Lv);
    $('.userinfo-exp span').html(data.Exp + '/' + data.NeedExp);
    var bar = $('.progress-bar');
    bar.attr('aria-valuenow', data.Exp);
    bar.attr('aria-valuemax', data.NeedExp);
    var rst = Math.floor(data.Exp * 100 / data.NeedExp);
    bar.attr('style', 'width:' + rst + '%');
    bar.html(rst + '%');
    bar.addClass('progress-bar-striped active');
    setTimeout(function () {
        bar.removeClass('progress-bar-striped active');
    }, 800);
}

function favorite(referenceId, referenceType) {
    if (!$('#btn-favorite').hasClass('disabled')) {
        $('#btn-favorite').addClass('disabled')
        if ($('#btn-favorite').hasClass('favorited')) {
            postJson('/Utility/Favorites/Delete', { referenceId: referenceId, referenceType: referenceType }, function (res) {
                if (res.Success) {
                    deletereferenceSuccess('btn-favorite','取消收藏');
                } else {
                    deletereferenceFail('btn-favorite',res.Message);
                }
            }, function () {
                    deletereferenceFail('btn-favorite',res.Message);
            });
        } else {
            postJson('/Utility/Favorites', { referenceId: referenceId, referenceType: referenceType }, function (res) {
                if (res.Success) {
                    referenceSuccess('btn-favorite', '收藏成功');
                } else {
                    referenceFail('btn-favorite',res.Message);
                }
            }, function () {
                    referenceFail('btn-favorite',res.Message);
            });
        }
    }
}
function zan(referenceId, referenceType,type) {
    if (!$('#btn-zan').hasClass('disabled')) {
        $('#btn-zan').addClass('disabled')
        if ($('#btn-zan').hasClass('zaned')) {
            postJson('/Utility/Behaviors/Delete', { referenceId: referenceId, referenceType: referenceType,type:type }, function (res) {
                if (res.Success) {
                    deletereferenceSuccess('btn-zan','取消点赞');
                } else {
                    deletereferenceFail('btn-zan',res.Message);
                }
            }, function () {
                    deletereferenceFail('btn-zan',res.Message);
            });
        } else {
            postJson('/Utility/Behaviors', { referenceId: referenceId, referenceType: referenceType,type:type }, function (res) {
                if (res.Success) {
                    referenceSuccess('btn-zan','点赞成功');
                } else {
                    referenceFail('btn-zan',res.Message);
                }
            }, function () {
                    referenceFail('btn-zan',res.Message);
            });
        }
    }
}
function referenceSuccess(btnId,msg) {
    $('.tool-bar-msg').html(msg);
    $('.tool-bar-msg').removeClass('fail');
    $('.tool-bar-msg').addClass('success');
    $('.tool-bar-msg').removeClass('hide');
    if (btnId == 'btn-zan') {
        $('#' + btnId).addClass('zaned');
        $('#' + btnId).html('<span class="glyphicon glyphicon-heart" aria-hidden="true"></span>点赞');
    } else if (btnId == 'btn-favorite') {
        $('#' + btnId).addClass('favorited');
        $('#' + btnId).html('<span class="glyphicon glyphicon-star" aria-hidden="true"></span>收藏');
    }
    setTimeout(function () {
        $('.tool-bar-msg').addClass('hide');
        $('#' + btnId).removeClass('disabled');
    }, 1000);
}
function referenceFail(btnId,msg) {
    $('.tool-bar-msg').html(msg);
    $('.tool-bar-msg').addClass('fail');
    $('.tool-bar-msg').removeClass('success');
    $('.tool-bar-msg').removeClass('hide');
    setTimeout(function () {
        $('.tool-bar-msg').addClass('hide');
        $('#' + btnId).removeClass('disabled');
    }, 1000);
}
function deletereferenceSuccess(btnId,msg) {
    $('.tool-bar-msg').html(msg);
    $('.tool-bar-msg').removeClass('fail');
    $('.tool-bar-msg').addClass('success');
    $('.tool-bar-msg').removeClass('hide');
    if (btnId == 'btn-zan') {
        $('#' + btnId).removeClass('zaned');
        $('#' + btnId).html('<span class="glyphicon glyphicon-heart-empty" aria-hidden="true"></span>点赞');
    } else if (btnId == 'btn-favorite') {
        $('#' + btnId).removeClass('favorited');
        $('#' + btnId).html('<span class="glyphicon glyphicon-star-empty" aria-hidden="true"></span>收藏');
    }
    setTimeout(function () {
        $('.tool-bar-msg').addClass('hide');
        $('#' + btnId).removeClass('disabled');
    }, 1000);
}
function deletereferenceFail(btnId,msg) {
    $('.tool-bar-msg').html(msg);
    $('.tool-bar-msg').addClass('fail');
    $('.tool-bar-msg').removeClass('success');
    $('.tool-bar-msg').removeClass('hide');
    setTimeout(function () {
        $('.tool-bar-msg').addClass('hide');
        $('#' + btnId).removeClass('disabled');
    }, 1000);
}