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);
        initialize();
    }
}

getProductInfo = function (pid) {
    var parameter = urlEncode(["SelectProduct", pid]);
    $.ajax({
        type: "post",
        url: "/malai/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>ColorClassification: ' + attr[i]['color'] + '</span></div>' +
                    (attr[i]['size'] ? '<div class="goodStatus f-fr"><span>Size:' + attr[i]["size"] + '</span></div>' : '') +
                    '<div class="goodStatus f-fr"><span>Quantity: ' + 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("Please type in your name");
        return;
    }
    else if (upn == "") {
        // alert("请输入手机号码");
        alert("Please enter the phone number");
        return;
    }
/*
    else if (uem == "") {
        // alert("请输入电子邮件");
        alert("Please enter an email");
        return;
    }
*/
    else if (pc == "") {
        // alert("请输入邮编");
        alert("Please enter a zip code");
        return;
    }
    else if (p == "") {
        // alert("请输入省份");
        alert("Please enter the province");
        return;
    }
    else if (a == "") {
        // alert("请输入直辖区");
        alert("Please enter the territorial jurisdiction");
        return;
    }
    else if (address == "") {
        // alert("请输入详细地址");
        alert("Please enter the full address");
        return;
    }
    else if (rem == "") {
        // alert("请输入留言");
        alert("Please enter a message");
        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: "/malai/php/index.php",
        data: {mode: parameter},
        dataType: "json",
        success: function (data) {
/*
            if (data != -1 && data[0].OrderId) {
                $("#PageLoading").css({"display": "none"});
                $("#PageWarp").css({"display": "block"});
                alert("Purchase Success!");
                window.location.href = "goods.html?pid=" + getUrlParam("pid");
                // insertUserIpAddress(ordernum, function () {
                //
                // });

            }
*/
            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 () {

                });*/
            }
            else {
                alert("Sorry, your purchase failed, please contact customer service!!!");
            }
        }
    });

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


/*
* 获取下单用户ip地址插入数据库
* */
insertUserIpAddress = function (num, cb) {
    var IPAddress = ipaddress.traits.ip_address,
        country = ipaddress.country.names["zh-CN"],
        city = ipaddress.city.names["zh-CN"],
        parameter = urlEncode(["InsertOrderIPAddress", num, IPAddress, country, city]);
    $.ajax({
        type: "post",
        url: "/malai/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: '/malai/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) {
//             }
//         });
//     });
// }

/*
*   選擇马来西亚的州
*/
//province(州類类)
function provinceList()
{
    this.length=24;
    this[0] = new Option("Pilih negeri anda...","0");
    this[1] = new Option("Johor","1");
    this[2] = new Option("Kedah","2");
    this[3] = new Option("Kelantan","3");
    this[4] = new Option("Melaka","4");
    this[5] = new Option("Negeri Sembilan","5");
    this[6] = new Option("Pahang","6");
    this[7] = new Option("Perak","7");
    this[8] = new Option("Perlis","8");
    this[9] = new Option("Pulau Pinang","9");
    this[10] = new Option("Selangor","10");
    this[11] = new Option("Terengganu","11");
    this[12] = new Option("Kuala Lumpur","12");
    this[13] = new Option("Putra Jaya","13");
    this[14] = new Option("Sarawak","14");
    this[15] = new Option("Sabah","15");
    this[16] = new Option("Labuan","16");

    return this;
}
//创建provincelist实例
var provinceOb=new provinceList();
//定义province、city变量，用于select元素
var province;
//初始化地区下拉菜单
function initialize(privinceId){
    //获取select元素
    province=document.getElementById("Area");
    //循环添加省份到province
    for(var i=0;i<provinceOb.length;i++){
        try{
            province.add(provinceOb[i]);
        }catch(e){
            province.add(provinceOb[i],null);
        }
     }
    //初始化privinceId
    if(privinceId==undefined){
        privinceId=0;
    }
    //设置province默认选项
    province.options[privinceId].selected=true;  
}

/*
* 获取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";
}

