var ProductInfo = "";
var number = "";
$(document).ready(function () {
    init();

});

/*
* 页面初始化函数
* */
init = function () {
    var pid = getUrlParam("pid"),
        attr = getUrlParam("attr");
    // num = getUrlParam("num");
    if (pid === "" || attr === "") {
        go404Html();
    }
    else {
        $(".goback").attr("href", "goods.html?pid=" + pid);
        getProductInfo(pid);
        selectCity();
    }
}

getProductInfo = function (pid) {
    var parameter = urlEncode(["SelectProduct", pid]);
    $.ajax({
        type: "post",
        url: "/new/php/index.php",
        data: {mode: parameter},
        dataType: "json",
        success: function (data) {
            printProductInfo(data);
        }
    });
}

printProductInfo = function (data) {
    if (data == -1 || data[0].length === 0) {
        go404Html();
    }
    else {
        $("#PageLoading").css({"display": "none"});
        $("#PageWarp").css({"display": "block"});
        ProductInfo = data[0][0];
        // $("#goodName").html(data[0][0].ProductIntroduce);
        var attr = JSON.parse(unescape(getUrlParam("attr")));
        $(".m-orderItem").html("");
        for (var i in attr) {
            if (i == 0) {
                $("#payment_amount").html(parseInt(attr[0].Money) * parseInt(attr[0].Number));
                $("#total").html(parseInt(attr[0].Money) * parseInt(attr[0].Number));
                number = attr[0].Number;
		ProductInfo.ProductPrice = parseInt(attr[0].Money) * parseInt(attr[0].Number);
                $(".number").html(attr[0].Number);//数量
            }

            if (i != 0) {
                var a = '<div class="row-2 flexbox">' +
                    '<div class="goodImg">' +
                    '<img src="' + attr[i]['img'] + '" width="100%"/>' +
                    '</div>' +
                    '                    <div class="goodInfo flex">\n' +
                    '                        <div class="goodName">' + ProductInfo.ProductName + '</div>\n' +
                    '                        <div class="goodName ti">\n' +
                    '                        <div class="goodStatus f-fr"><span>การจำแนกสี: ' + attr[i]['color'] + '</span></div>' +
                    (attr[i]['size'] ? '<div class="goodStatus f-fr"><span>ขนาด:' + attr[i]["size"] + '</span></div>' : '') +
                    '<div class="goodStatus f-fr"><span>จำนวน: ' + attr[0].Number + '</span></div>' +
                    '                        </div>' +
                    '</div>' +
                    '</div>';
                $(".m-orderItem").append(a);
            }
        }
    }
}

submit = function () {
    var lid = "",
        ordernum = orderNum(),
        pid = getUrlParam("pid"),
        pcid = escape(getUrlParam("attr")),
        attr = "",
        ppr = ProductInfo.ProductPrice,
        pn = number,
        urn = $("#UserReallyName").val().trim(),
        upn = $("#thaphone").val().trim(),
        uem = $("#UserEMail").val().trim(),
        pc = $("#tha_postal").val().trim(),
        p = $("#Province").html(),
        c = "",
        a = $("#Area").val().trim(),
        address = $("#Address").val().trim(),
        rem = $("#Remarks").val().trim(),
        fr = 0,
        am = ProductInfo.ProductPrice,
        pay = ProductInfo.ProductPrice,
        state = 1;

    if (urn == "") {
        // alert("请输入姓名");
        alert("กรุณาป้อนชื่อ");
        return;
    }
    else if (upn == "") {
        // alert("请输入手机号码");
        alert("โปรดระบุหมายเลขโทรศัพท์มือถือ");
        return;
    }
/*
    else if (uem == "") {
        // alert("请输入电子邮件");
        alert("กรุณาใส่อีเมล์");
        return;
    }
*/
    else if (pc == "") {
        // alert("请输入邮编");
        alert("กรุณาใส่รหัสไปรษณีย์");
        return;
    }
    else if (p == "") {
        // alert("请输入省份");
        alert("โปรดระบุจังหวัด");
        return;
    }
    else if (a == "") {
        // alert("请输入直辖区");
        alert("โปรดระบุเขตอำเภอเมือง");
        return;
    }
    else if (address == "") {
        // alert("请输入详细地址");
        alert("โปรดระบุรายละเอียดที่อยู่");
        return;
    }
/*
    else if (rem == "") {
        // alert("请输入留言");
        alert("กรุณาป้อนข้อความ");
        return;
    }
*/

    $("#PageLoading").css({"display": "block"});
    $("#PageWarp").css({"display": "none"});

    var parameter = urlEncode(["InsertOrder", lid, ordernum, pid, pcid, attr, ppr, pn, urn, upn, uem, pc, p, c, a, address, rem, fr, am, pay, state]);
    $.ajax({
        type: "post",
        url: "/new/php/index.php",
        data: {mode: parameter},
        dataType: "json",
        success: function (data) {
            if (data != -1 && data[0].OrderId) {

/*
                    console.log(data);
                    $("#PageLoading").css({"display": "none"});
                    $("#PageWarp").css({"display": "none"});
                    $("#PageWarp").remove();
                    $("#ts_OrderNum").html(data[0].OrderNum);
                    $("#ts_UserReallyName").html(data[0].UserReallyName);
                    $("#ts_ProductName").html(ProductInfo.ProductName);
                    $("#ts_Payment").html(data[0].Payment);
                    $("#ts_UserPhoneNum").html(data[0].UserPhoneNum);
                    $("#ts_Address").html(data[0].Address);
                    $("#TS").css({"display": "block"});
                    $("#ts_back")[0].onclick = function () {
                        window.location.href = "goods.html?pid=" + getUrlParam("pid");
                    }
                    $("#ts_lx")[0].onclick = function () {
                        window.location.href = " https://www.facebook.com/pg/MinimatterTimes";
                    }

*/





                insertUserIpAddress(ordernum, function () {
                    console.log(data);
                    $("#PageLoading").css({"display": "none"});
                    $("#PageWarp").css({"display": "none"});
                    $("#PageWarp").remove();
                    $("#ts_OrderNum").html(data[0].OrderNum);
                    $("#ts_UserReallyName").html(data[0].UserReallyName);
                    $("#ts_ProductName").html(ProductInfo.ProductName);
                    $("#ts_Payment").html(data[0].Payment);
                    $("#ts_UserPhoneNum").html(data[0].UserPhoneNum);
                    $("#ts_Address").html(data[0].Address);
                    $("#TS").css({"display": "block"});
                    $("#ts_back")[0].onclick = function () {
                        window.location.href = "goods.html?pid=" + getUrlParam("pid");
                    }
                    $("#ts_lx")[0].onclick = function () {
                        window.location.href = " https://www.facebook.com/pg/MinimatterTimes";
                    }
                });

            }
            else {
                alert("ซื้อล้มเหลวกรุณาติดต่อฝ่ายบริการลูกค้า ต้องขอโทษด้วยครับไม่สะดวก!!!");
            }
        }
    });

    //facebook推广购物事件，请不要删除！！！！！
    fbq('track', 'Purchase', {
        value: ProductInfo.ProductPrice,
        currency: 'THB',
        content_ids: ProductInfo.ProductRemarks,
        content_type: 'product_group'
    });
}


/*
* 获取下单用户ip地址插入数据库
* */
insertUserIpAddress = function (num, cb) {
    var IPAddress = returnCitySN.cip,
        country = returnCitySN.cname,
        city = '',
        parameter = urlEncode(["InsertOrderIPAddress", num, IPAddress, country, city]);
    $.ajax({
        type: "post",
        url: "/new/php/index.php",
        data: {mode: parameter},
        dataType: "json",
        success: function (data) {
            if (data == 1) {
                cb && cb();
            }
        }
    });
}


/*
* 根据当前时间，生成订单号
* */
orderNum = function () {
    var vNow = new Date(), sNow = "";
    sNow += String(vNow.getFullYear());
    sNow += String(vNow.getMonth() + 1);
    sNow += String(vNow.getDate());
    sNow += String(vNow.getHours());
    sNow += String(vNow.getMinutes());
    sNow += String(vNow.getSeconds());
    sNow += String(vNow.getMilliseconds());
    return sNow;//返回订单号
}

/*
* 输入泰国指定的邮政编码，生成指定的泰国地址。
* */
selectCity = function () {
    $('#tha_postal').change(function () {
        var id = $(this).val();
        ajaxLocked = true;
        $.ajax({
            url: '/new/php/Forward.php',
            type: 'post',
            data: {'postName': id},
            dataType: 'json',
            success: function (ret) {
                if (ret) {
                    if (ret.length != 0) {
                        var option = "";
                        for (var i in ret) {
                            option += '<option value="' + ret[i].name + '" data-city="' + ret[i].parent_name + '">' + ret[i].name + '</option>';
                            $('.regions').html(ret[0].parent_name);
                            $('input[name="city"]').val(ret[0].parent_name);
                        }
                        $(".tha_district").html('').append(option);
                        ajaxLocked = false;
                    } else {
                        alert('รหัสไปรษณีย์ ผิด!');
                        $('#tha_postal').val('');
                        $('.tha_district').html('');
                        $('.regions').html('');
                        $('input[name="city"]').val('');
                        ajaxLocked = true;
                    }
                } else {
                    alert('รหัสไปรษณีย์ ผิด!');
                    $('#tha_postal').val('');
                    $('.tha_district').html('');
                    $('.regions').html('');
                    $('input[name="city"]').val('');
                    ajaxLocked = true;
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
            }
        });
    });
}

/*
* 获取url参数
* @param {string} 需要获取参数的名字
* */
getUrlParam = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]);
    return null; //返回参数值
}

/*
* 将字符串拼接成数组，并且修改成指定格式。用于ajax上传。
* @param {array}
* */
urlEncode = function (arr) {
    var i; //循环初始化
    for (i = 0; i < arr.length; i++) {//循环对数组各元素进行加密
        arr[i] = encodeURIComponent(encodeURIComponent(arr[i]));
    }
    return arr.join();//转换为字符串返回
}

/*
* 页面跳转指定的404页面
* */
go404Html = function () {
    window.location.href = "../404.html";
}

