﻿
var empty = "", otherTip = "网络故障，请刷新后再试...", success = "操作成功", error = "操作失败，稍刷新后再试..."; function checkContent() {
    if ($("#message").val() == "") {
        alert('留言内容不能为空');
        return false;
    }
    if ($("#username").val() == "") {
        alert('请先登陆再留言！');
        return false;
    }
}
function clearContent() {
    $("#message").val("");
}
function check() {
    if ($("#title").val() == "") {
        alert('标题不能为空');
        return false;
    }
    if ($("#Advantage").val() == "") {
        alert('优点内容不能为空');
        return false;
    }
    if ($("#Inadequate").val() == "") {
        alert('不足 内容不能为空');
        return false;
    }
    if ($("#Summary").val() == "") {
        alert('总结内容不能为空');
        return false;
    }
}
function clear() {
    $("#title").val("");
    $("#Advantage").val("");
    $("#Inadequate").val("");
    $("#Summary").val("");
}
function checkFeedback() {
    var item = $(":radio:checked");
    var len = item.length;
    if (len < 1) {
        alert("还没有选择操作类型！");
        return false;
    }
    if ($("#feedbackcontent").val() == "") {
        alert('内容不能为空');
        return false;
    }
    if ($("#MemberName").val() == "") {
        alert('请先登陆再留言');
        return false;
    }
}

function favorite(u, pid) {
    if (u == "") { alert('您还未登录'); return false; }
    $.ajax({ url: "/product/service.ashx?ac=favorite&u=" + escape(u) + "&pid=" + pid,
        type: "GET", dataType: "text", error: function(XMLHttpRequest) { },
        success: function(data) {
            if (data == 1) { alert("已添加到收藏夹"); }
            else if (data == 2) { alert("您已经收藏过此商品了，无需再次收藏"); }
        }
    });
}

function buy2(id, img, num, name, marketPrice, price, integral, integralPrice, storage, prosize, procolor) {

    if ($('#numcount').val() > parseInt($('#txtstorage').html(), 10)) {
        alert('库存不足');
        return;
    }
    var color = document.getElementById("color").value;
    var size = document.getElementById("size").value;

    if (prosize != "" && size == "") {
        alert("请选择商品尺寸");
        return;
    }
    if (procolor != "" && color == "") {
        alert("请选择商品颜色");
        return;
    }
    
    var procount = document.getElementById("numcount").value;
    buy(id, img, num, name, marketPrice, price, procount, integral, integralPrice, storage, color, size);

    location.href = '/shop/cart.aspx';

}

//common
var JSON = {
    ToString: function(items) {
        if (typeof items != "object")
            return "[]";
        var str = "[";
        for (var i in items) {
            str += "{";
            for (var n in items[i]) {
                if (typeof items[i][n] == "number") {
                    str += n + ':' + items[i][n] + ',';
                }
                else {
                    str += n + ':"' + items[i][n] + '",';
                }
            }
            str += "},";
        }
        str += "]";

        str = str.replace(/,}/g, "}").replace(",]", "]");

        return str;
    },
    ForString: function(str) {

        if (typeof str != "string") {

            return null;
        }

        return eval('(' + str + ')');

    }
};

function master_setInterval(callback, timeout, param) {
    var args = Array.prototype.slice.call(arguments, 2);
    var _cb = function() {
        callback.apply(null, args);
    }
    window.setInterval(_cb, timeout);
}

String.prototype.format = function() {

    var sz = this.toString();

    if (arguments.length < 1)
        return sz;

    for (var i = 0; i < arguments.length; i++) {

        var arg = arguments[i];

        if (typeof arg == 'string' || typeof arg == 'number') {

            var re = new RegExp("[\{]" + i + "[\}]", "ig");

            sz = sz.replace(re, arg);

        }
    }

    return sz;

}
//end

//star
function addGradeEvent() {
    $("#grade_list img").each(function(i) {

        $(this).bind("mouseover", function() {
            changeGradeColor(this);
        }).bind("click", function() {
            setGrade(i + 1);
        });

    });

    $("#grade_list").mouseout(function() {

        gradeInit();

    });
}
function changeGradeColor(obj) {

    $(obj).attr("src", "/css/images/star.gif");

    $(obj).prevAll().attr("src", "/css/images/star.gif");

    $(obj).nextAll().attr("src", "/css/images/star_bg.gif");

}
function setGrade(num) {

    $("#point").val(num);

}
function gradeInit() {

    var lastGrade = $("#point").val();

    if (lastGrade == 0) {
        $("#grade_list img").attr("src", "/css/images/star_bg.gif");
        return;
    }

    changeGradeColor($("#grade_list img").eq(lastGrade - 1));

}
//end

//product history
var historyCount = 8;
function GetHistory() {

    var array = [];

    var oldList = decodeURI(GetCookie("history"));

    if (oldList != "null") {
        array = JSON.ForString(oldList);
    }

    return array;

}
function AddHistory(id, img, name, link) {

    var existsObj = false;
    var obj = { id: id, img: img, name: name, link: link };

    var array = GetHistory();
    if (array.length >= historyCount)
        return;

    for (var n in array) {

        if (obj.id == array[n].id) {
            existsObj = true;
            break;
        }

    }
    if (existsObj)
        return;

    array.push(obj);
    SetCookie("history", encodeURI(JSON.ToString(array)), 365, "/");

}
function GetHistoryHtml() {

    if (document.getElementById("historyRecord")) {

        var historyHtml = "";
        var array = GetHistory();

        if (array.length == 0)
            return;

        if (array.length == historyCount) {
            document.getElementById("historyDel").style.display = "";
        }
        for (var n in array) {

            historyHtml += '<dl>';

            historyHtml += '<dt><img src="' + array[n].img + '" /></dt>';
            historyHtml += '<dd><a href="' + array[n].link + '">' + array[n].name + '</a></dd>';

            historyHtml += '</dl>';

        }

        document.getElementById("historyRecord").innerHTML = historyHtml;

    }

}
function DeleteHistory() {
    SetCookie("history", "[]", 1, "/");
    document.getElementById("historyRecord").innerHTML = "";
}
//--end

//shopping cart
var cartWrapID = "cartWrap";
function getCartObj() {

    var array = [];

    var oldList = GetCookie("shopcart");

    if (oldList && oldList != "null") {
        array = JSON.ForString(oldList);
    }

    return array;

}

function buy(id, img, num, name, marketPrice, price, count, integral, integralPrice,storage,color,size) {

    if (isNaN(parseInt(count)) || count < 1) count = 1;
    else count = parseInt(count, 10);

    integral = parseInt(integral,10);
    integralPrice = parseInt(integralPrice,10);

    var existsObj = false;
    var obj = { id: id, img: img, num: num, name: name,
        marketPrice: marketPrice, price: price, count: count,
        integral: integral, integralPrice: integralPrice, storage: storage,
        color: color, size: size
    };

    var array = getCartObj();
    for (var n in array) {

        if (obj.id == array[n].id && obj.price == array[n].price) {
            existsObj = true;
            array[n].count = array[n].count + count;

            break;
        }

    }
    if (!existsObj)
        array.push(obj);

    SetCookie("shopcart", JSON.ToString(array), 365, "/");

}
function showCart() {

    if (!document.getElementById(cartWrapID))
        return;

    var cartHtml = "";
    var array = getCartObj();

    for (var n in array) {
        var p = array[n];

        var proPrice = p.count * p.price;

        cartHtml += '<table class="cartList" id="cartList{0}">';
        cartHtml += '<colgroup>';
        cartHtml += '<col width="106" />';
        cartHtml += '<col width="115" />';
        cartHtml += '<col width="260" />';
        cartHtml += '<col width="80" />';
        cartHtml += '<col width="80" />';
        cartHtml += '<col width="80" />';
        cartHtml += '<col width="100" />';
        cartHtml += '<col width="96" />';
        cartHtml += '<col width="69" />';
        cartHtml += '</colgroup>';
        cartHtml += '<tr>';
        cartHtml += '<td>';
        cartHtml += '<img alt="{1}" src="{2}" />';
        cartHtml += '</td>';
        cartHtml += '<td>';
        cartHtml += '<a title="{1}" href="/product/view.aspx?pid={0}">{3}</a>';
        cartHtml += '</td>';
        cartHtml += '<td>{1}</td>';
        cartHtml += '<td>';
        cartHtml += '<span class="line-through">{4}</span>';
        cartHtml += '</td>';
        cartHtml += '<td>{5}</td>';
        cartHtml += '<td>{8}</td>';
        cartHtml += '<td>';
        cartHtml += '<input class="text" type="text" maxlength="7" onkeypress="return event.keyCode>=48&&event.keyCode<=57" id="txtcount_{0}_{9}" value="{6}" />';
        cartHtml += '<input class="button" type="button" onclick="catChangeCount({0},{5},{10})" value="确定" />';
        cartHtml += '</td>';
        //tip:proPrice_{0}_{1}:distinguish integral purchase and cash purchase the same goods。
        cartHtml += '<td><em id="proPrice_{0}_{9}">{7}</em></td>';
        cartHtml += '<td><a class="del" href="javascript:void(0)" onclick="deleteCart({0})"> </a></td>';
        cartHtml += '</tr>';
        cartHtml += '</table>';

        cartHtml = cartHtml.format(p.id, p.name, p.img, p.num, p.marketPrice, p.price, p.count, proPrice, p.integralPrice,parseInt(p.price,10),p.storage);
    }
    
    var totalCount = cartGetTotalCount();
    document.getElementById(cartWrapID).innerHTML = cartHtml;
    document.getElementById("totalCount").innerHTML = totalCount;
    document.getElementById("totalPrice").innerHTML = cartGetTotalPrice(); ;

    document.getElementById("cartCount").innerHTML = totalCount;

}

function showOrderCart() {

    if (!document.getElementById(cartWrapID))
        return;

    var cartHtml = "";
    var array = getCartObj();

    var discount = 0;
    var productList = "";

    for (var n in array) {
        var p = array[n];

        var proPrice = p.count * p.price;
        discount = p.marketPrice - p.price;

        cartHtml += '<tr>';
        cartHtml += '<td>{0}</td>';
        cartHtml += '<td>{1}</td>';
        cartHtml += '<td align="center">￥{2}</td>';
        cartHtml += '<td align="center">{7}</td>';
        cartHtml += '<td align="center">￥{3}</td>';
        cartHtml += '<td align="center">{4}</td>';
        cartHtml += '<td align="center">{5}</td>';
        cartHtml += '<td align="center">￥{6}</td>';
        cartHtml += '</tr>';

        productList += p.id + ","
                         + p.num + ","
                         + p.name + ","
                         + p.marketPrice + ","
                         + p.price + ","
                         + p.count + ","
                         + p.integral + ","
                         + p.integralPrice + ","
                         + p.size + ","
                         + p.color + "|";

        cartHtml = cartHtml.format(p.num, p.name, p.price, discount, p.integral, p.count, proPrice, p.integralPrice);

    }

    if (productList != "") productList = productList.substr(0, productList.length - 1);

    $(cartHtml).appendTo("#"+ cartWrapID);

    var totalPrice = cartGetTotalPrice();
    var totalIntegralPrice = cartGetTotalIntegralPrice();

    $(".txtTotalPrice").html(totalPrice);
    $("#txtTotalIntegralPrice").html(totalIntegralPrice);
    $("#productList").val(productList);
    $("#totalPrice").val(totalPrice);
    $("#totalCount").val(cartGetTotalCount());
    $("#totalGiveIntegral").val(cartGetTotalGiveIntegral());
    $("#totalIntegralPrice").val(totalIntegralPrice);

}

function deleteCart(pid) {

    var array = getCartObj();

    for (var n = 0; n < array.length; n++) {

        if (pid == array[n].id) {

            array = array.slice(0, n).concat(array.slice(n + 1));

        }
    }

    SetCookie("shopcart", JSON.ToString(array), 365, "/");

    showCart();
}

function clearCart() {

    SetCookie("shopcart", "[]", 1, "/");

    showCart();

}

function clearCart2() {

    SetCookie("shopcart", "[]", 1, "/");

}

function catChangeCount(pid, price,storage) {

    var count = document.getElementById("txtcount_" + pid + "_" + parseInt(price, 10)).value;

    if (!/^\d+$/.test(count) || count == 0) {
        count = 1;
        document.getElementById("txtcount_" + pid + "_" + parseInt(price, 10)).value = count;
    }

    document.getElementById("proPrice_" + pid + "_" + parseInt(price, 10)).innerHTML = count * price;

    var array = getCartObj();
    for (var n in array) {
        if (array[n].id == pid && array[n].price == price) {
            array[n].count = parseInt(count);
            break;
        }
    }
        
    SetCookie("shopcart", JSON.ToString(array), 365, "/");

    document.getElementById("totalCount").innerHTML = cartGetTotalCount();
    document.getElementById("totalPrice").innerHTML = cartGetTotalPrice();

    document.getElementById("cartCount").innerHTML = cartGetTotalCount();

    if (cartGetProductCount(pid) > storage) {
        alert("库存不足，此商品还有库存 " + storage + "，请重新输入!");
        document.getElementById("txtcount_" + pid + "_" + parseInt(price, 10)).value = 1;
        catChangeCount(pid, price, storage);
    }

    /*
    if (cartGetTotalIntegralPrice() > userIntegral) {
    alert("您的积分不够");
    }
    */
}
function cartGetProductCount(pid) {

    var totalCount = 0;
    var array = getCartObj();

    for (var n in array) {

        if (pid == array[n].id) {
            totalCount += array[n].count;
        }
    }

    return totalCount;

}
function cartGetTotalCount() {

    var totalCount = 0;
    var array = getCartObj();

    for (var n in array) {

        totalCount += array[n].count;

    }

    return totalCount;

}
function cartGetTotalPrice() {

    var totalPrice = 0;
    var array = getCartObj();

    for (var n in array) {

        var proPrice = array[n].count * array[n].price;
        totalPrice += proPrice;

    }

    return totalPrice;

}
function cartGetTotalIntegralPrice() {

    var totalIntegral = 0;
    var array = getCartObj();

    for (var n in array) {

        var integralPrice = array[n].count * array[n].integralPrice;
        totalIntegral += integralPrice;

    }

    return totalIntegral;

}
function cartGetTotalGiveIntegral() {

    var total = 0;
    var array = getCartObj();

    for (var n in array) {

        var giveIntegral = array[n].count * array[n].integral;
        total += giveIntegral;

    }

    return total;

}
//end

//product timerProMove
var showTimerIndex = 0;
function timerProMove() {

    var $array = $(".limitPro").eq(0).find("dl");

    var proCount = $array.size();

    if (proCount == 1) return;

    $array.eq(showTimerIndex).animate({ opacty: "toggle", left: "+200px" }, "slow", null, function() {

        showTimerIndex++;

        if (showTimerIndex >= proCount) {
            showTimerIndex = 0;
        }

        $array.eq(showTimerIndex).animate({ opacty: "show", left: "0" }, "slow");

    });
}

function show_date_time(showtimeid, target, pid) {

    today = new Date();
    timeold = (target.getTime() - today.getTime());

    sectimeold = timeold / 1000;
    secondsold = Math.floor(sectimeold);
    msPerDay = 24 * 60 * 60 * 1000;
    e_daysold = timeold / msPerDay;
    daysold = Math.floor(e_daysold);
    e_hrsold = (e_daysold - daysold) * 24;
    hrsold = Math.floor(e_hrsold);
    e_minsold = (e_hrsold - hrsold) * 60;
    minsold = Math.floor((e_hrsold - hrsold) * 60);
    seconds = Math.floor((e_minsold - minsold) * 60);

    if (daysold < 0) {
        $("#btn" + pid).val("已到期").attr("onclick", "");
    }
    else {
        if (daysold < 10) { daysold = "0" + daysold }
        if (daysold < 100) { daysold = daysold }
        if (hrsold < 10) { hrsold = "0" + hrsold }
        if (minsold < 10) { minsold = "0" + minsold }
        if (seconds < 10) { seconds = "0" + seconds }

        var timeHtml = "剩余<span>" + parseInt(daysold * 24, 10) + parseInt(hrsold, 10) + "</span>小时<span>" + minsold + "</span>分<span>" + seconds + "</span>秒";

        document.getElementById(showtimeid).innerHTML = timeHtml;

    }
}

function showQianggou() {

    $.ajax({ url: "/product/service.ashx?ac=timerpro",

        type: "GET", dataType: "text", error: function(XMLHttpRequest) { },

        success: function(data) {

            $("#limitPro").html(data);

            setInterval("timerProMove()", 10000);

        }
    });
}
//--end

function checkout() {

    var array = getCartObj();

    if (array.length == 0) {
        alert("您的购物车中没有商品");
    }
    else {
        location.href = "/shop/order.aspx";
    }

}
function loadCity(value, id) {
    $("#Community").html("");
    ajaxGet("/member/Execution.ashx?ac=GetCity&id=" + value.toString().split(",")[0], id);

}
function loadCommunity(value, id) {
    ajaxGet("/member/Execution.ashx?ac=Community&id=" + value.toString().split(",")[0], id);
}
function ajaxGet(goURL, id) {

    $.ajax({ url: goURL, type: "GET", dataType: "text",
        error: function() { alert(otherTip); },
        success: function(data) {
            if (data != "error") {
                $("#" + id).html(data)

            } else { alert(error); }
        }
    });
}
function updateArea() {
    $("#div_defaultArea").hide();
    $("#isChange").val("1");
    $("#div_area").show();
}
function addressDisplay() {
    if ($("#div_defaultArea").html() == "" || $("#div_defaultArea").html() == null) {
        $("#div_defaultArea").hide();
        $("#isChange").val("1");
        $("#div_area").show();
    }
}
function checkAddress() {
    var name = document.getElementById("Consignee").value;
    var address1 = document.getElementById("Address").value;
    if (name == "" || address1 == "") {
        alert("收件人、地址不能为空!");
        return false;

    }
    var area = $('select[name="area"]').val();
    if (area == "-1" && $("#div_defaultArea").html() == "") {
        alert("请选择所在区域！");
        return false;
    }
    var tel = document.getElementById("LinkPhone").value;
    var mobile = document.getElementById("Mobile").value;
    var patrn = /^(0?1[3,5,8](\d){9}(-(\d){1,6})?|0(\d){3}-(\d){6,8}(-(\d){1,6})?|0(\d){2}-(\d){8}(-(\d){1,6})?|00(\d){11,20})$/;
    if (tel != "") {
        if (!patrn.exec(tel)) {
            alert("请正确填写联系电话:如010-7874545,0085247454587,13545478789");
            return false;
        }
    }
    if (mobile != "") {
        if (!patrn.exec(mobile)) {
            alert("请正确填写联系电话:如010-7874545,0085247454587,13545478789");
            return false;
        }
    }
    if (tel == "" && mobile == "") {
        alert("请至少填写一种正确的联系方式!")
        return false;
    }
    var email = document.getElementById("Email").value.trim();
    var epartn = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
    if (!epartn.exec(email)) {
        alert("请正确填写Email格式,如:melinIfo@melin.com");
        return false;

    }
}
function displayFaPiao() {
    $("#faPiao").show();
}
function hedeFapiao() {
    $("#faPiao").hide();
}
function checkSubmit() {
    //  checkAddress();
    var selected = $('#isNeed').attr('checked');
    if (selected) {
        if ($("#InvoiceContent").val() == "") {
            alert("请填写发票内容！");
            return false;
        } 
    }

}

