var ProductId = "",
    ProductIdCountDown = "",
    ProductAttrId = [],
    ProductAttrInfo = 0;

$(document).ready(function () {
    init();
    $(window).scroll(WindowScroll);

});


init = function () {
    getProductInfo();
}

var getProductInfo = function () {
    var pid =   getUrlParam("pid") || window.location.pathname.substr(1);
    var parameter = urlEncode(["SelectProduct", pid]);
    $.ajax({
        type: "post",
        url: "/taiwan/php/index.php",
        data: {mode: parameter},
        dataType: "json",
        success: function (data) {
            $("#PageLoading").css({"display": "none"});
            $("#PageWarp").css({"display": "block"});
            printProductInfo(data[0][0]);
            PrintProductAttribute(data[0][0].ProductAttr);
        }
    });
}

var printProductInfo = function (data) {
    ProductAttrId = data;
    ProductId = data.ProductId;
    ProductIdCountDown = data.CountDown;
    $("#ProductName").html(data.ProductName);
    $("#ProductPrice").html(Math.ceil(data.ProductPrice));
    $("#ColorPrice").html("฿" + Math.ceil(data.ProductPrice));
    $("#ProductPrimeCost").html(Math.ceil(data.ProductPrimeCost));
    $("#ProductInfo").html(data.ProductInfo);
    $("#Discount").html(data.Discount);
    $("#Sold").html(data.Sold);
    $("#Promotion").html(data.Promotion);
$("#ProductInfo img").css({"width":"100%","height":"auto"});
    // countTime(ProductIdCountDown);
    // countDown(ProductIdCountDown);
    setInterval(function () {
        freshTime();
    }, 1000);
    var banner = JSON.parse(data.ProductAttr)["7b824b9c-738b-11e8-a479-0610c52349b6"],
        color = JSON.parse(data.ProductAttr)["69d4e108-738a-11e8-a479-0610c52349b6"],
        size = JSON.parse(data.ProductAttr)["d6d6361b-acea-11e8-bbc6-0a4b7569e232"],
        classs = JSON.parse(data.ProductAttr)["cfb738c4-bff6-11e8-bbc6-0a4b7569e232"],
        comment = JSON.parse(data.ProductAttr)["d5cca263-c224-11e8-bbc6-0a4b7569e232"];
    $("#Color").html("");
    for (var i in color) {
        for (var j in color[i]) {
            var a = '<a  _src=' + color[i][j] + ' onclick = itemClick(this)>' + j + '</a>';
            $("#Color").append($(a));
        }
    }
    $("#Color a").eq(0).addClass("checked");
    $("#ColorBanner").attr("src", $("#Color a").eq(0).attr("_src"));
    // ProductAttrId.push(escape($("#Color a").eq(0).html()), escape($("#Color a").eq(0).attr("_src")));


    if (size && !$.isEmptyObject(size)) {
        for (var i in size) {
            for (var j in size[i]) {
                var a = '<a onclick = itemClick(this)>' + size[i][j] + '</a>';
                $("#Size").append($(a));
            }
        }
        $("#Size a").eq(0).addClass("checked");
    }
    else {
        $("#Size").parent().hide();
    }

    var num = 0;
    for (var j in banner) {
        num++;
    }

    for (var i in banner) {
        for (var j in banner[i]) {
            var li = '<li class="item slide"><img src="' + banner[i][j] + '"/></li>';
            $(".scroller").append(li);
            var i = '<i><span class="pagination">' + (parseInt(j) + 1) + '/' + num + '</span></i>';
            $(".nav").append(i);
            $(".nav i").eq(0).addClass("current");
        }
    }
    bannerMove();

    var mp4 = $("#ProductInfo img.edui-upload-video"), el;
    for (var i = 0; i < mp4.length; i++) {
        var url = mp4.eq(i).attr("_url");
        el = '<video src=' + url + ' controls="controls" preload="auto" width = "100%"></video>';
        mp4.eq(i).after(el);
        mp4.eq(i).remove();
    }
    mp4.remove();
    //就是这一块
    if (comment && !$.isEmptyObject(comment)) {
        $("#comment").eq(0).html("");
        for (var i in comment) {
            //for (var j = 0;j<=i;j++) {
            $("#comment").eq(0).append(
                $('<li>' +
                    '<div style="margin-bottom:8px;  color: #999;font-size:12px">' +
                    '<span>' + comment[i].name + '</span>' +
                    '<span style="float: right;">' +
                    '<span lass="reviewStar size1 star5">' + comment[i].time + '</span>' +
                    '</span>' +
                    '</div>' +
                    '<div>' +
                    '<p style="margin-bottom: 8px;font-size: 14px;word-break: break-all;">' + comment[i].text + '</p>' +
                    '<div class="imgg" style="margin-bottom:10px;overflow: hidden">' + '</div>' +
                    // '<p style="position: relative;min-height: 10px;">' +
                    //     '<span style="position: absolute;bottom: 0;right: 15px;color:#8f8f94">' + comment[i].time + '</span>' +
                    // '</p>' +
                    '</div>' +
                    '</li>'
                ));
            if (comment[i].imgurl != "") {
                var CreateCommentImg = function (el, img, flag) {
                    img = flag ? '/taiwan/' + img : img;
                    var div = '<img style="z-index:0;" src="' + img + '">';
                    $(".imgg").eq(i).append(div);
                }
                var img = comment[i]['imgurl'].split(",");
                img.forEach(function (val) {
                    CreateCommentImg(el, val, false);
                });
            }
            //}
        }
        // $(".u-format .items").eq(0).eq(0).addClass("tab-sel");
    }
    else {
        $(".ProductEvaluate")[0].style.display = "none";
//        $(".header-nav")[0].children[2].style.display = "none";
  //      Roll();
    }

}

var bannerMove = function () {
    var glide = new Glide('.module-preview ', {
        autoplay: 3000
    });
    glide.on(['mount', 'run.after'], function () {
        $(".nav i").removeClass("current");
        $(".nav i").eq(glide._i).addClass("current");
    })
    glide.mount();
}


var ToTop = function () {
    $("html,body").scrollTop(0);
}

var ToProductInfo = function () {
    $("html,body").scrollTop($(".ProductInfo").offset().top - 50);
    // $("html,body").animate({scrollTop: $(".ProductInfo").offset().top - 50});
}

var ToProductEvaluate = function () {
    $("html,body").scrollTop($(".ProductEvaluate").offset().top);

    // $("html,body").animate({scrollTop: $(".ProductEvaluate").offset().top});
}


function freshTime() {
    var arr = ProductIdCountDown.split(/[- : \/]/);
    var endtime = new Date(arr[0], arr[1] - 1, arr[2], arr[3], arr[4], arr[5]);
    var nowtime = new Date();
    var lefttime = parseInt(endtime.getTime() - nowtime.getTime());//这是毫秒，如果再/1000就是秒
    if (lefttime <= 0) {
        var toyear = new Date().getFullYear();
        var tomonth = new Date().getMonth() + 1;
        var today = new Date().getDate() + 2;
        arr[0] = toyear;
        arr[1] = tomonth;
        arr[2] = today;
        endtime = new Date(arr[0], arr[1] - 1, arr[2], arr[3], arr[4], arr[5]);
        lefttime = parseInt(endtime.getTime() - nowtime.getTime());//这是毫秒，如果再/1000就是秒
    }
    var hm = 60 * 60 * 1000;
    var h = parseInt((lefttime / hm));
    var mm = 60 * 1000;
    var m = parseInt((lefttime / mm) % 60);
    var s = parseInt((lefttime / 1000) % 60);
    m = checktime(m);
    s = checktime(s);
    $("#J_TimeHour").html(h);
    $("#J_TimeMin").html(m);
    $("#J_TimeSec").html(s);
    if (lefttime < 0) {
        $("#J_TimeHour").html(0);
        $("#J_TimeMin").html(0);
        $("#J_TimeSec").html(0);
    }
}

//倒计时效果js代码
function checktime(i) {
    if (i < 10) {
        i = "0" + i;
    }
    else {
        i = i;
    }
    return i;
}


var WindowScroll = function () {
    var top = $(document).scrollTop();
    if (top > $(".group-warp").eq(0).height() * 0.2) {
        $("#head").addClass("transparent");
    }

    if (top >= $(".ProductInfo").offset().top - 100) {
        $("#head").addClass("transparent");
        $("#head li").removeClass("active");
        $("#head li").eq(1).addClass("active");
    }

    if (top >= $(".ProductEvaluate").offset().top - 500) {
        $("#head").addClass("transparent");
        $("#head li").removeClass("active");
        $("#head li").eq(2).addClass("active");
    }

    if (top < $(".ProductEvaluate").offset().top - 500) {
        $("#head").addClass("transparent");
        $("#head li").removeClass("active");
        $("#head li").eq(1).addClass("active");
    }


    if (top <= $(".ProductInfo").offset().top - 100) {
        $("#head").addClass("transparent");
        $("#head li").removeClass("active");
        $("#head li").eq(0).addClass("active");
    }

    if (top <= $(".group-warp").eq(0).height() * 0.2) {
        $("#head").removeClass("transparent");
    }
}


var showPage = function () {
    // if ($(".widgets-cover").hasClass("show")) {
    //     $(".widgets-cover").removeClass("show");
    //     $("body").css({"position": "static", "top": "0px", "scroll-behavior": "unset"});
    // }
    // else {
    //     $("body").css({"position": "fixed", "top": "0px", "scroll-behavior": "unset"});
    //     $(".widgets-cover").addClass("show");
    // }

    if ($("#page-order").css("display") == "block") {
        $("#PageWarp").css({display: "block"});
        $("#page-order").animate({left: '100%'}, "", function () {
            $("#page-order").css({display: "none"});
        });
    }
    else {
        $("#page-order").css({display: "block"});
        $("#page-order").animate({left: '0'}, "", function () {
            $("#PageWarp").css({display: "none"});
        });
    }
}


/*********************************************下单页面事件区域*************************************************/

var PrintProductAttribute = function (obj) {
    obj = JSON.parse(obj);
    var classs = obj['cfb738c4-bff6-11e8-bbc6-0a4b7569e232'],
        color = obj['69d4e108-738a-11e8-a479-0610c52349b6'],
        size = obj['d6d6361b-acea-11e8-bbc6-0a4b7569e232'];
    var
        colorel = $(".count_atrr .con"),
        sizeel = $(".count_size .con");
    // var isclasss = true;

    //打印图片颜色分类
    colorel.html("");
    for (var i in color) {
        for (var j in color[i]) {
            var div = '<div class="tab" onclick="ColorClick(this,\'' + j + '\')"><img src="' + color[i][j] + '"></div>';
            colorel.append($(div));
            if (i == 0) {
                // ColorClick(colorel.find(".tab").eq(0), j);
                colorel.find(".tab").eq(0).addClass("tab-sel");
                colorel.eq(0).parent().find("span").html(j);
            }
        }
    }

    //打印尺寸分类
    if (size && !$.isEmptyObject(size)) {
        sizeel.html("");
        for (var i in size) {
            for (var j in size[i]) {
                var div = '<label class="tab" onclick="SizeClick(this)"><span>' + size[i][j] + '</span></label>';
                sizeel.append($(div));
                if (i == 0) {
                    sizeel.find(".tab").eq(0).addClass("tab-sel");
                }
            }
        }
    }
    else {
        sizeel.parent().remove();
    }

    var classsel = $(".count_classs .con"), classs_obj, classs_a;
    //打印套餐
    if ($.isEmptyObject(classs)) {
        $(".count_classs .con").parent().remove();
        ProductAttrId.OrderNum = 1;
    }
    else {
        classsel.html("");
        $.each(classs, function (i, val) {
            ProductAttrInfo++;
            classs_obj = val;
            $.each(val, function (j, val1) {
                if (j == "type") {
                    if ($(".dt-paramselect .meal").length != parseInt(val1)) {

                        while (parseInt(val1) > $(".dt-paramselect .meal").length) {
                            classs_a = $(".meal").eq(0).clone();
                            classs_a.hide();
                            $(".dt-paramselect").append(classs_a);
                        }
                        // for (var k = 0; k < parseInt(val1) - $(".dt-paramselect .meal").length; k++) {
                        //     classs_a = $(".meal").eq(0).clone();
                        //     classs_a.hide();
                        //     $(".dt-paramselect").append(classs_a);
                        // }
                    }
                }
                else if (j != "type") {
                    var div = '<label class="tab" onclick="ClasssClick(this,\'' + j + '\',\'' + val.type + '\')"><span>' + val1 + '</span></label>';
                    classsel.append($(div));
                    // div.onclick = function () {
                    //     alert();
                    // }
                    // $(div).bind('click', function () {
                    //     alert();
                    // });

                }
            });
        });
        $(".dt-paramselect").append($(".u-fornum"));
        $(".count_classs label").eq(0).click();

        /*
                if (ProductAttrInfo == 1) {
                    ClasssClick($(".count_classs label").eq(0), ProductAttrId.ProductPrice, classs[0].type);
                }
                else {
                    ClasssClick($(".count_classs label").eq(0), ProductAttrId.ProductPrice, ProductAttrInfo);
                }
        */

        // for (var i in classs) {
        //     for (var j in classs[i]) {
        //         if (j == "type") {
        //             // $(".u-fornum").before(colorel.parent().clone().hide());
        //             // $(".u-fornum").before(sizeel.parent().clone().hide());
        //             $(".secondsetmeal").append(colorel.parent().clone());
        //             $(".secondsetmeal").append(sizeel.parent().clone());
        //         }
        //         else if (j != "type") {
        //             var div = '<label class="tab" onclick="ClasssClick(this,\'' + j + '\')"><span>' + classs[i][j] + '</span></label>';
        //             classsel.append($(div));
        //         }
        //     }
        // }
        // ClasssClick($(".count_classs label").eq(0));
    }


    console.log(obj);
}

/**/
var ClasssClick = function (el, val, type) {
    $(el.parentNode).find(".tab").removeClass("tab-sel");
    $(el).addClass("tab-sel");
    $(".meal").hide();
    $(".meal").eq(0).show();
    for (var i = 0; i < parseInt(type); i++) {
        $(".meal").eq(i).show();
    }
    type ? ProductAttrId.OrderNum = type : "";
    val ? ProductAttrId.ProductPrice = val : "";
}

/*选择颜色点击事件*/
var ColorClick = function (el, val) {
    $(el.parentNode).find(".tab").removeClass("tab-sel");
    $(el).addClass("tab-sel");
    $(el.parentNode.parentNode).find("span").html(val);

    // $(el.parentNode).children().removeClass("checked");
    // // $("#Color a").removeClass("checked");
    // $(el).addClass("checked");
    // if ($(el.parentNode).attr("id") === "Color") {
    //     $("#ColorBanner").attr("src", $(el).attr("_src"));
    // }
    // var banner = escape($("#ColorBanner").attr("src")),
    //     color = escape($("#Color a.checked").html()),
    //     size = escape($("#Size a.checked").html());
    // ProductAttrInfo = [];
    // ProductAttrInfo.push(banner, color, size);
}

/*选择尺寸点击事件*/
var SizeClick = function (el) {
    $(el.parentNode).find(".tab").removeClass("tab-sel");
    $(el).addClass("tab-sel");
}

/*购买数量添加*/
var addnumber = function () {
    $('.textWrap .num').html(parseInt($('.textWrap .num').html()) + 1);
}

/*购买数量减少*/
var minnumber = function () {
    if (parseInt($('.textWrap .num').html()) > 1) {
        $('.textWrap .num').html(parseInt($('.textWrap .num').html()) - 1);
    }
}


/*点击购买函数*/
var goShop = function () {
    // var num = parseInt($("#number").val()),
    //     attr = ProductAttrInfo.join(),
    //     str = "shop.html?pid=" + ProductId + "&attr=" + attr + "&num=" + num;
    var num = parseInt($("#number").text()),
        obj = [],
        attr = {},
        numobj = {},
        url = "shop.html?pid=" + ProductId + "&attr=",
        str = "";

    numobj["Number"] = num;
    numobj["Money"] = ProductAttrId.ProductPrice;
    obj.push(numobj);

    for (var i = 0; i < ProductAttrId.OrderNum; i++) {
        attr = {};
        attr["color"] = $(".meal").eq(i).find(".tt span").eq(0).text();
        attr["img"] = $(".meal").eq(i).find("div.tab-sel img").attr("src");
        attr["size"] = $(".meal").eq(i).find("label.tab-sel span").text();
        obj.push(attr);
    }
    OrderPrice = parseInt(obj[0].Number) * parseInt(obj[0].Money);
//facebook购物车推广事件，请勿删除！
  fbq('track', 'AddToCart', {
    value: OrderPrice,
    currency: 'TWD',
    content_ids: 'ProductAttrId.ProductRemarks',
    content_type: 'product_group',
  });
    str = escape(JsonToString(obj));
    url += str;
    console.log(url);
    window.location.href = url;


}


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; //返回参数值
}

urlEncode = function (arr) {
    var i; //循环初始化
    for (i = 0; i < arr.length; i++) {
        arr[i] = encodeURIComponent(encodeURIComponent(arr[i]));
    }
    return arr.join();
}


Roll = function () {
    //$(".marquee ul").css('position', 'absolute');
    animate();
};

animate = function () {
    var boxHeight = $('.marquee').height();
    var ulHeight = $(".marquee ul").height();
    $(".marquee").css('top', 0);
    $(".marquee").animate({scrollTop: $(".marquee")[0].scrollTop == 0 ? (ulHeight - boxHeight) : 0}, 10000, animate);
}


//json转换为string
var JsonToString = function (obj) {
    var i,
        _type = false,
        _str = "",
        _type = typeof (obj); //获取类型
    //开始序列化
    if (obj == null) {
    }
    else {
        obj = obj.valueOf(); //获取值 同时类型也为对应
        if ("boolean,number".indexOf(_type) > -1) {//bool和number类型转化
            _str = obj.toString();
        }
        else if (_type == "string") {//json处理字符串时需要加上 "\""符号
            _str = "\"" + obj + "\"";
        }
        else if (typeof obj == "array") { //数组处理
            _str = "[";
            for (i = 0; i < obj.length; i++) {
                _str += JsonToString(obj[i]) + ((i < obj.length - 1) ? "," : "")
            }
            ;_str += "]";
            return _str
        }
        else {//object处理
            _str = "{";
            for (i in obj) {
                if (obj.hasOwnProperty(i)) {
                    if (_str.length > 1) {
                        _str += ","
                    }
                    ;_str += "\"" + i + "\":" + JsonToString(obj[i]);
                }
            }
            _str += "}";
        }
        return _str;
    }
}
