//給jQuery新增一個方法
jQuery.fn.serializeObject = function () {
    var formData = {};
    var formArray = this.serializeArray();
    for (var i = 0, n = formArray.length; i < n; ++i) {
        formData[formArray[i].name] = formArray[i].value;
    }
    return formData;
};

$(function () {});

//訊息JS
function alertMsg(msg) {
    /*
	$('#alertMsg .modal-body').html(msg);
	$('#alertMsg').modal({ keyboard: false ,backdrop: 'static'});
	$('#alertMsg').modal('show');
	*/
    $.alert({
        title: "系統訊息",
        icon: "fa fa-warning",
        theme: "material",
        content: msg,
        closeIcon: false,
        animation: "scale",
        closeAnimation: "scale",
        opacity: 0.5,
        draggable: false,
        type: "blue",
        buttons: {
            okay: {
                text: "確定",
                btnClass: "btn-orange",
            },
        },
    });
}

//JS訊息 跳轉指定網址
function scriptMsg(msg, url) {
    $.alert({
        title: "系統訊息",
        icon: "fa fa-warning",
        theme: "material",
        content: msg,
        closeIcon: false,
        animation: "scale",
        closeAnimation: "scale",
        opacity: 0.5,
        draggable: false,
        type: "blue",
        buttons: {
            okay: {
                text: "確定",
                btnClass: "btn-orange",
                action: function () {
                    location.href = url;
                },
            },
        },
    });
}

//複寫javascript alert視窗
function alert(data, func) {
    alertMsg(data);
}

//另開視窗
function openwindow(url) {
    var url; //網頁位置;
    var name; //網頁名稱;
    var iWidth = window.screen.availWidth / 2; //視窗的寬度;
    var iHeight = window.screen.availHeight / 2; //視窗的高度;
    var iTop = (window.screen.availHeight - 30 - iHeight) / 2; //視窗的垂直位置;
    var iLeft = (window.screen.availWidth - 10 - iWidth) / 2; //視窗的水平位置;
    window.open(
        url,
        com_name,
        "height=" +
            iHeight +
            ",,innerHeight=" +
            iHeight +
            ",width=" +
            iWidth +
            ",innerWidth=" +
            iWidth +
            ",top=" +
            iTop +
            ",left=" +
            iLeft +
            ",status=no,location=no,status=no,menubar=no,toolbar=no,resizable=no,scrollbars=no"
    );
}

function gameOpen(data) {
    var url; //網頁位置;
    var name; //網頁名稱;
    var iWidth = window.screen.availWidth / 2; //視窗的寬度;
    var iHeight = window.screen.availHeight / 2; //視窗的高度;
    var iTop = (window.screen.availHeight - 30 - iHeight) / 2; //視窗的垂直位置;
    var iLeft = (window.screen.availWidth - 10 - iWidth) / 2; //視窗的水平位置;
    var win = window.open(
        "",
        com_name,
        "height=" +
            iHeight +
            ",,innerHeight=" +
            iHeight +
            ",width=" +
            iWidth +
            ",innerWidth=" +
            iWidth +
            ",top=" +
            iTop +
            ",left=" +
            iLeft +
            ",status=no,location=no,status=no,menubar=no,toolbar=no,resizable=no,scrollbars=no"
    );
    win.document.write(data);
}

function openservice(url) {
    var url; //網頁位置;
    var name; //網頁名稱;
    var iWidth = 700; //視窗的寬度;
    var iHeight = window.screen.availHeight / 2; //視窗的高度;
    var iTop = (window.screen.availHeight - 30 - iHeight) / 2; //視窗的垂直位置;
    var iLeft = (window.screen.availWidth - 10 - iWidth) / 2; //視窗的水平位置;
    window.open(
        url,
        com_name,
        "height=" +
            iHeight +
            ",,innerHeight=" +
            iHeight +
            ",width=" +
            iWidth +
            ",innerWidth=" +
            iWidth +
            ",top=" +
            iTop +
            ",left=" +
            iLeft +
            ",status=no,location=no,status=no,menubar=no,toolbar=no,resizable=no,scrollbars=no"
    );
}

Number.prototype.numberFormat = function (c, d, t) {
    var n = this,
        c = isNaN((c = Math.abs(c))) ? 2 : c,
        d = d == undefined ? "." : d,
        t = t == undefined ? "," : t,
        s = n < 0 ? "-" : "",
        i = String(parseInt((n = Math.abs(Number(n) || 0).toFixed(c)))),
        j = (j = i.length) > 3 ? j % 3 : 0;
    return (
        s +
        (j ? i.substr(0, j) + t : "") +
        i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) +
        (c
            ? d +
              Math.abs(n - i)
                  .toFixed(c)
                  .slice(2)
            : "")
    );
};

//一健轉回主錢包
function transfer_all() {
    $.blockUI({
        message: '<img src="' + ASSETS_PATH + '/www/img/009.gif" >',
        baseZ: 99999999,
    });
    $.ajax({
        type: "POST",
        url: CI_URL + "Manger/transfer_all",
        cache: !1,
        dataType: "json",
    }).done(function (msg) {
        $.unblockUI();
        if (msg.RntCode == "Y") {
            //window.location.reload();
            scriptMsg(msg.Msg, location.href);
        } else if (msg.RntCode == "W") {
            location.href = location.href;
        } else {
            alert(msg.Msg);
        }
    });
}

function menu_main_ajax_balance() {
    $("#menu_main_balance").html(
        '<img src="' + ASSETS_PATH + '/admin/images/loadingbar/042.gif" >'
    );
    $.ajax({
        type: "POST",
        url: CI_URL + "Manger/ajax_balance",
        cache: !1,
        //async:false,
        dataType: "json",
        data: {
            makersnum: 0,
        },
    }).done(function (msg) {
        var balance = msg.balance;
        if (balance != "--") balance = Number(balance).numberFormat(0);
        $("#menu_main_balance").html(balance);
    });
}

//啟動遊戲 & 餘額
function transfer_ajax_balance(obj, makersnum) {
    $("#" + obj).html(
        '<img src="' + ASSETS_PATH + '/admin/images/loadingbar/001.gif" >'
    );
    $.ajax({
        type: "POST",
        url: CI_URL + "Manger/ajax_balance",
        cache: !1,
        //async:false,
        dataType: "json",
        data: {
            makersnum: makersnum,
        },
    }).done(function (msg) {
        var balance = msg.balance;
        if (balance != "--") balance = Number(balance).numberFormat();
        $("#" + obj).html(balance);
    });
}
//啟動遊戲 & 轉點
function transfer_open(makers_num, new_window, GameCode, lobbyMode) {
    new_window = new_window || false;
    GameCode = GameCode || "";
    lobbyMode = lobbyMode || false;
    if (!isLogin) {
        $("#loginModal").modal("show");
        $("#rtn").val(location.href);
        return;
    }
    if (!makers_num) {
        alert("即將開放，敬請期待");
        return;
    }
    var Transfer_amount_reg = /^[0-9]*[1-9][0-9]*$/;
    //$('#transferModal').modal({ keyboard: false ,backdrop: 'static'});
    //$('#transferModal').modal('show');
    $.confirm({
        title: "啟動遊戲",
        draggable: false,
        theme: "material",
        type: "blue",
        closeIcon: true,
        content: "url:" + CI_URL + "Transfer?gm=" + makers_num,
        buttons: {
            transfer: {
                text: "轉入遊戲",
                btnClass: "btn-info",
                action: function () {
                    var input = this.$content.find("input#transfer_amount");
                    var errorTextDiv = this.$content.find("#errorTextDiv");
                    var errorTextMsg = this.$content.find("#errorTextMsg");
                    var successTextDiv = this.$content.find("#successTextDiv");
                    var successTextMsg = this.$content.find("#successTextMsg");
                    if (!input.val().trim()) {
                        /*
						$.alert({
							title: '錯誤提示',
							content: "轉入點數欄位不得為空",
							type: 'red',
							buttons: {
								okay: {
									text: '確定',
									btnClass: 'btn-orange',
								}
							}
						});
						*/
                        $(input).focus();
                        $(successTextDiv).hide();
                        $(errorTextDiv).show();
                        $(errorTextMsg).html("轉入點數欄位不得為空");

                        return false;
                    }
                    if (!Transfer_amount_reg.test(input.val().trim())) {
                        /*
						$.alert({
							title: '錯誤提示',
							content: "轉入點數需為正整數",
							type: 'red',
							buttons: {
								okay: {
									text: '確定',
									btnClass: 'btn-orange',
								}
							}
						});*/
                        $(input).focus();
                        $(successTextDiv).hide();
                        $(errorTextDiv).show();
                        $(errorTextMsg).html("轉入點數需為正整數");
                        return false;
                    }
                    //開始轉點程序

                    $.blockUI({
                        message:
                            '<img src="' + ASSETS_PATH + '/www/img/009.gif" >',
                        baseZ: 99999999,
                    });
                    $.ajax({
                        type: "POST",
                        url: CI_URL + "Manger/transfer_do",
                        cache: !1,
                        dataType: "json",
                        data: {
                            amount: input.val().trim(),
                            makers_num_A: 0,
                            makers_num_B: makers_num,
                        },
                    }).done(function (msg) {
                        $.unblockUI();
                        menu_main_ajax_balance();
                        transfer_ajax_balance("transfer_main_amount", 0);
                        transfer_ajax_balance(
                            "transfer_makers_amount",
                            makers_num
                        );
                        if (msg.RntCode == "Y") {
                            //window.location.reload();
                            //scriptMsg(msg.Msg,location.href);
                            $(errorTextDiv).hide();
                            $(successTextDiv).show();
                            $(successTextMsg).html(msg.Msg);
                            input.val("");
                            $(input).focus();
                        } else if (msg.RntCode == "W") {
                            location.href = location.href;
                        } else {
                            $(successTextDiv).hide();
                            $(errorTextDiv).show();
                            $(errorTextMsg).html(msg.Msg);
                        }
                    });
                    return false;
                },
            },
            open_game: {
                text: "進入遊戲",
                btnClass: "btn-red",
                action: function () {
                    if (new_window) {
                        window.open(
                            CI_URL +
                                "/Opengame?gm=" +
                                makers_num +
                                "&GameCode=" +
                                GameCode +
                                (lobbyMode ? "&lobbyMode=" + lobbyMode : "")
                        );
                    } else {
                        location.href =
                            CI_URL +
                            "/Opengame?gm=" +
                            makers_num +
                            "&GameCode=" +
                            GameCode +
                            (lobbyMode ? "&lobbyMode=" + lobbyMode : "");
                    }
                },
            },
        },
    });
}

//刷新驗證碼
function changeChkImg(s_name, obj) {
    s_name = s_name || "";
    obj = obj || "chkImg";
    $.ajax({
        type: "POST",
        url: BASE_URI + "Manger/refresh_token",
        cache: false,
        async: false,
        dataType: "json",
    }).done(function (msg) {
        var now = new Date();
        $("#" + obj).attr(
            "src",
            BASE_URI +
                "Vcode?token=" +
                msg.token +
                "&now=" +
                now.getTime() +
                "&s_name=" +
                s_name
        );
    });
}

//驗證登入
function CheckLogin() {
    $.ajax({
        type: "POST",
        url: CI_URL + "Index/check_login",
        cache: false,
        dataType: "json",
    }).done(function (data) {
        if (data.RntCode == "N") {
            //alert(data.Msg);
            location.href = CI_URL;
        }
    });
}

function img_fixed(evt) {
    var file = evt.target.files[0];
    var orientation;
    EXIF.getData(file, function () {
        orientation = EXIF.getTag(this, "Orientation");
    });
    var reader = new FileReader();
    reader.onload = function (e) {
        getImgData(this.result, orientation, function (data) {
            //这里可以使用校正后的图片data了
            //console.log(data);
            $(".kv-file-content")
                .find(".file-preview-image")
                .attr("id", "newIMG");
            var img = document.getElementById("newIMG");
            img.src = data;
        });
    };
    reader.readAsDataURL(file);
}

function img_fixed2(evt) {
    var file = evt.target.files;
    $(file).each(function (index) {
        var orientation;
        EXIF.getData(file[index], function () {
            orientation = EXIF.getTag(this, "Orientation");
        });
    });
}

// @param {string} img 图片的base64
// @param {int} dir exif获取的方向信息
// @param {function} next 回调方法，返回校正方向后的base64
function getImgData(img, dir, next) {
    var image = new Image();
    image.onload = function () {
        var degree = 0,
            drawWidth,
            drawHeight,
            width,
            height;
        drawWidth = this.naturalWidth;
        drawHeight = this.naturalHeight;
        //以下改变一下图片大小
        var maxSide = Math.max(drawWidth, drawHeight);
        if (maxSide > 1024) {
            var minSide = Math.min(drawWidth, drawHeight);
            minSide = (minSide / maxSide) * 1024;
            maxSide = 1024;
            if (drawWidth > drawHeight) {
                drawWidth = maxSide;
                drawHeight = minSide;
            } else {
                drawWidth = minSide;
                drawHeight = maxSide;
            }
        }
        var canvas = document.createElement("canvas");
        canvas.width = width = drawWidth;
        canvas.height = height = drawHeight;
        var context = canvas.getContext("2d");
        //判断图片方向，重置canvas大小，确定旋转角度，iphone默认的是home键在右方的横屏拍摄方式
        switch (dir) {
            //iphone横屏拍摄，此时home键在左侧
            case 3:
                degree = 180;
                drawWidth = -width;
                drawHeight = -height;
                break;
            //iphone竖屏拍摄，此时home键在下方(正常拿手机的方向)
            case 6:
                canvas.width = height;
                canvas.height = width;
                degree = 90;
                drawWidth = width;
                drawHeight = -height;
                break;
            //iphone竖屏拍摄，此时home键在上方
            case 8:
                canvas.width = height;
                canvas.height = width;
                degree = 270;
                drawWidth = -width;
                drawHeight = height;
                break;
        }
        //使用canvas旋转校正
        context.rotate((degree * Math.PI) / 180);
        context.drawImage(this, 0, 0, drawWidth, drawHeight);
        //返回校正图片
        next(canvas.toDataURL("image/jpeg", 0.8));
    };
    image.src = img;
}
