﻿/*
前台引用此脚本文件
*/

/*
设置页面按回车默认提交的按钮
*/
function SetDefaultButton(btnID) {
    $(document).keydown(function(event) {  //这里如果写成$(window)，在ie下面就不会起作用
        if (event.keyCode == 13) {
            event.returnValue = false; //不让表单自动提交。
            document.getElementById(btnID).click(); //激发按扭事件   
            return false;
        }
    });
}

//$(document).ready(function() {
//});
/*
登录跳转
*/
function SignIn(returnUrl, needAlert) {
    if(needAlert)
        alert('您不是會員，請先登錄！');
    location.href = "/UI/Login.aspx?returnUrl=" + encodeURIComponent(returnUrl);
}
/*普通列表页提交脚本*/
///group 你要针对哪个组进行验证
function JQuerySubmitForm(target, argument, openSelector) {
    var _searchBefore = true;
    if (typeof (SearchBefore) == "function")
        _searchBefore = SearchBefore(); //在查询数据前执行的函数(如果存在)
    if (!_searchBefore)
        return;

    var _target = "";
    switch (typeof (target)) {
        case "string":
            _target = target;
            break;
        case "object":
            _target = target.target.name; //设置提交方是谁
            break;
    }
    SetSubmitHiddenField(_target, argument);
    var paramSerial = $('form').serialize();
    $.ajax({
        url: window.location.href, //默认提交到本页
        data: paramSerial,
        async: true,
        type: 'POST', // 设置请求类型为 ‘POST’，默认为 ‘GET’
        dataType: 'html',
//        timeout: 30000, //超时时间设定
        success: function(data) {
            $('#ShowData')[0].innerHTML = GetFormData(data);
        },
        complete: function() {
            if (typeof (SearchCallBack) == "function")
                SearchCallBack(); //在返回查询数据后,执行的函数(如果存在)
        },
        error: function() {
            alert('程序異常，請重試！');
        }
    });

}
/*
设置提交的按钮
*/
function SetSubmitHiddenField(target, argument, formObj) {
    var _form = formObj == undefined ? document.forms[0] : formObj;
    if ($("#__EVENTTARGET").length == 0) {
        //        $(AspNetFormJQ).append("<input type=\"hidden\" name=\"__EVENTTARGET\" id=\"__EVENTTARGET\" value=\"\" />")
        $(_form).append("<input type=\"hidden\" name=\"__EVENTTARGET\" id=\"__EVENTTARGET\" />"); //value=\"\"
    }
    if ($("#__EVENTARGUMENT").length == 0) {
        //        $(AspNetFormJQ).append("<input type=\"hidden\" name=\"__EVENTARGUMENT\" id=\"__EVENTARGUMENT\" value=\"\" />")
        $(_form).append("<input type=\"hidden\" name=\"__EVENTARGUMENT\" id=\"__EVENTARGUMENT\"  />"); //value=\"\"
    }
    //    $(AspNetFormJQ)[0].__EVENTTARGET.value = target;
    //    $(AspNetFormJQ)[0].__EVENTARGUMENT.value = argument;
    _form.__EVENTTARGET.value = target;
    _form.__EVENTARGUMENT.value = argument;
}
function GetFormData(data) {
    var begin = data.indexOf("<form");
    var end = data.indexOf("</form>");
    return data.substring(begin, end + 7);
}

function SetBookImgNotFound(sender) {
    sender.src = "/images/NotFound.jpg";
}
function Setheight(iframe) {
    var height = $(window.frames[iframe.name].document.body).height();
    var scrollHeight = window.frames[iframe.name].document.body.scrollHeight;//兼容IE7
    height = scrollHeight > height ? scrollHeight : height;
    if (height < iframe.height) {
        iframe.height = height;
    }
    if (height > iframe.height) {
        iframe.height = height + 30;
    }
}
var cookieProductID = "ComicBookShop_ShoppingCar";
var cookieSet = { expires: 7, path: '/' }; //设置cookie路径的
var ComicBookShop_CheckCode = "ComicBookShop_CheckCode"; //校验码标识


/*isBuy是否购买
添加商品及数量到购物车的数据库中
needConfirm是否需要确认提示
*/
function Add2ShoppingCar(pageUrl, productInfoID, productName, num, memberID, isBuy, needConfirm) {
    $.ajax({
        type: "POST",
        url: pageUrl+"/AddToShoppingCar",
        data: "{'memberID':'" + memberID + "', 'productInfoID':'" + productInfoID + "', 'num':'" + num + "'}",
        contentType: "application/json; charset=utf-8", //调用PageMethod必须设置此项
        dataType: "json",
        success: function(data) {
            if (data == true) {
                if (!isBuy && needConfirm) {
                    if (confirm("添加【" + productName + "】成功，是否進行結算？"))
                        isBuy = true;
                }
                if (isBuy)
                    location.href = "/UI/ComicShoppingCar.aspx";
            }
            else {
                alert("添加【" + productName + "】失敗，請重試！");
            }
        },
        complete: function() {
        },
        error: function() {
            alert('服務器繁忙，請重試！');
        }
    });

}
function UpdateShoppingCar(pageUrl, productInfoID, productName, num, memberID) {
    $.ajax({
        type: "POST",
        url: pageUrl + "/UpdateShoppingCar",
        data: "{'memberID':'" + memberID + "', 'productInfoID':'" + productInfoID + "', 'num':'" + num + "'}",
        contentType: "application/json; charset=utf-8", //调用PageMethod必须设置此项
        dataType: "json",
        success: function(data) {
            if (data == true) {
                
            }
            else {
                alert("更新【" + productName + "】數量失敗，請重試！");
            }
        },
        complete: function() {
        },
        error: function() {
            alert('服務器繁忙，請重試！');
        }
    });
}
/*
添加商品及数量到购物车cookie中,返回当前商品在cookie中的总数
*/
//function AddToShoppingCar(id, num,creator) {
////    debugger;
//    var _num = 1;
//    if (num != undefined)
//        _num = num;

//    var totalNum = _num; //总数默认为传入参数
////    var cookieSet = { expires: 7, path: '/' }; //设置cookie路径的
////    $.cookie(cookieProductID, null, cookieSet);//清除Cookie
//    var jsonStr = "[{'ProductID':'" + id + "','Num':'" + _num + "','Selected':'false','Creator':'" + creator + "'}]"; //构造json字符串,id是商品id   num是这个商品的数量
//    if ($.cookie(cookieProductID) == null) {
//        $.cookie(cookieProductID, jsonStr, cookieSet); //如果没有这个cookie就设置他  
//    }
//    else {
//        var jsonObj = eval('(' + $.cookie(cookieProductID) + ')'); //如果有，把json字符串转换成对象
//        var findProduct = false;//是否找到产品ID,找到则为TRUE,否则为FALSH
//        for (var obj in jsonObj) {
//            if (jsonObj[obj].ProductID == id) {
//                jsonObj[obj].Num = Number(jsonObj[obj].Num) + _num;
//                totalNum = jsonObj[obj].Num;
//                findProduct = true;
//                break;
//            }
//        }
//        if (findProduct == false) { //没找到,则添加
//            jsonObj[jsonObj.length] = new Object();
//            jsonObj[jsonObj.length - 1].ProductID = id;
//            jsonObj[jsonObj.length - 1].Num = num;
//            jsonObj[jsonObj.length - 1].Selected = false;
//            jsonObj[jsonObj.length - 1].Creator = creator;
//        }
//        
//        $.cookie(cookieProductID, JSON.stringify(jsonObj), cookieSet);  //写入coockie   JSON需要json2.js支持
//    }
//    return totalNum;
//    //    alert($.cookie(cookieProductID));
//}
/*
在购物车中删除一商品
objID 执行此函数的当前对象id
totalPriceID 總價格控件的ID
*/
function DeleteProductInShoppingCar(pageUrl,objID,totalPriceID, memberID, productInfoID, productName) {
    if (confirm("是否確定刪除")) {
        $.ajax({
            type: "POST",
            url: pageUrl + "/DeleteShoppingCar",
            data: "{'memberID':'" + memberID + "', 'productInfoID':'" + productInfoID + "'}",
            contentType: "application/json; charset=utf-8", //调用PageMethod必须设置此项
            dataType: "json",
            success: function(data) {
                if (data == true) {
                    DeleteOneInShoppingCar(objID, totalPriceID);
                }
                else {
                    alert("删除【" + productName + "】失敗，請重試！");
                    return false;
                }
            },
            complete: function() {
            },
            error: function() {
                alert('服務器繁忙，請重試！');
            }
        });
    }
}
/*
objID 执行此函数的当前对象id
totalPriceID 總價格控件的ID
*/
function DeleteOneInShoppingCar(objID,totalPriceID) {
    var tr = $("#" + objID).parent().parent(); //获取该对象所在的行
    var tbl = $("#" + objID).parent().parent().parent(); //获取该对象所在的table
    tr.remove();
    RecalculateTotalPrice(totalPriceID);
    if (tbl.children(0).length == 2) { //已经删除所有行(除了表头和表尾)
        $("#OrderConfirm").hide();
    }
}

//function DeleteProductInShoppingCar(id) {
//    var returnValue = false;
//    if ($.cookie(cookieProductID) != null) {
//        var jsonObj = eval('(' + $.cookie(cookieProductID) + ')'); //如果有，把json字符串转换成对象
//        for (var obj in jsonObj) {
//            if (jsonObj[obj].ProductID == id) {
//                jsonObj.splice(obj, 1);
//                returnValue = true;
//                break;
//            }
//        }
//        $.cookie(cookieProductID, JSON.stringify(jsonObj), cookieSet);  //写入coockie   JSON需要json2.js支持
//    }
//    return returnValue;
//}
//function AddToShoppingCar(id, num) {
//    //debugger;
//    var _num = 1;
//    if (num != undefined)
//        _num = num;

//    var totalNum = _num;//总数默认为传入参数
//    var cookieSet = { expires: 7, path: '/' }; //设置cookie路径的
//    //$.cookie(cookieProductID, null, cookieSet);//清除Cookie
//    var jsonStr = "{'" + id + "':'" + _num + "'}"; //构造json字符串,id是商品id   num是这个商品的数量
//    if ($.cookie(cookieProductID) == null) {
//        $.cookie(cookieProductID, jsonStr, cookieSet);//如果没有这个cookie就设置他  
//    }
//    else {
//        var jsonObj = eval('(' + $.cookie(cookieProductID) + ')'); //如果有，把json字符串转换成对象
//        if (jsonObj[id] == undefined) {//看看有没有参数id的商品，如果没有则创建
//            jsonObj[id] = _num; 
//        }
//        else {
//            jsonObj[id] = Number(jsonObj[id]) + _num; //如果有则增加数量
//            totalNum = jsonObj[id];
//        }      
//        $.cookie(cookieProductID, JSON.stringify(jsonObj), cookieSet);  //写入coockie   JSON需要json2.js支持
//    }
//    return totalNum;
////    alert($.cookie(cookieProductID));
//}
/*
productInfoID:产品ID
operateCode:+表示增加 -表示减
num: 要增加/减少 的数量
unitPrice:单价
curRowNumID: 当前行的数量的控件ID
subTotalID:当前行总价格控件ID 
totalPriceID:购物车中所有商品的总价格控件ID
isUpdate:true表示更新，false表示追加
*/
function ShopCarCalculate(pageUrl, memberID, productInfoID, productName, num, unitPrice, curRowNumID, subTotalID, totalPriceID, isUpdate) {
    var _num = 0;
    var curNum = $("#" + curRowNumID).val(); //当前数量
    //    eval('_num = Number(curNum)' + operateCode + num); //计算
    _num = Number(curNum) + num;
    if (_num < 1) {
        alert('數量不能小於一，若不需要此商品請點【刪除】！');
    }
    else {
        var subTotal = 0.00; //声明为浮点类型
        subTotal = _num * unitPrice;
        $("#" + curRowNumID).val(_num);
        $("#" + subTotalID).html(subTotal.toFixed(2)); //保留2位小数
        RecalculateTotalPrice(totalPriceID);
        if(isUpdate)
            UpdateShoppingCar(pageUrl, productInfoID, productName, curNum, memberID);    
        else
            Add2ShoppingCar(pageUrl,productInfoID, productName, num, memberID, false, false);
    }
}

//function ShopCarCalculate(productInfoID, num, unitPrice, curRowNumID, subTotalID, totalPriceID) {

//    var _num = 0;
//    
//    var curNum = $("#" + curRowNumID).val();//当前数量
////    eval('_num = Number(curNum)' + operateCode + num); //计算
//    _num = Number(curNum) + num;
//    if (_num < 1) {
//        alert('数量不能小于1！若不需要此商品请点[删除]！');
//    }
//    else {
//        var subTotal = 0.00;//声明为浮点类型
//        subTotal = _num * unitPrice;
//        $("#" + curRowNumID).val(_num);
//        $("#" + subTotalID).html(subTotal.toFixed(2)); //保留2位小数
//        RecalculateTotalPrice(totalPriceID);
//        AddToShoppingCar(productInfoID, num);
////        var totalPrice = 0.00;
////        $("span[class='ShopCarSubTotal']").each(function(i, obj) {
////            totalPrice += parseFloat(obj.innerText);
////        });
////        $("#" + totalPriceID).html(totalPrice.toFixed(2).toString());
//    }
////    alert(_num);
//}
/*
重新计算购物车总金额
*/
function RecalculateTotalPrice(totalPriceID) {
    var totalPrice = 0.00;
    $("span[class='ShopCarSubTotal']").each(function(i, obj) {
        totalPrice += parseFloat(obj.innerText);
    });
    $("#" + totalPriceID).html(totalPrice.toFixed(2).toString());
}
/*
cityObjID City控件的ID
areaObjID Area控件的ID
provinceCode 省代码
cityCode 市代码
*/
function BindCityAreaToControl(cityObjID,areaObjID, provinceCode,cityCode) {
    var now = new Date().getTime(); //now表示每次点击都会发送新的请求
    $.getJSON(window.location.href + "?getJson=CityArea&ProvinceID=" + provinceCode + "&CityID=" + cityCode + "&now=" + now, function(data) {
        var emptyChild = document.createElement("option");
        emptyChild.value = "";
        emptyChild.innerText = "請選擇";

        $('#' + areaObjID + ">option").remove();
        //document.getElementById(areaObjID).options.length = 0;//每次都清空Area数据
        if (provinceCode != "") {
            document.getElementById(cityObjID).options.length = 0;
            document.getElementById(cityObjID).appendChild(emptyChild);
            for (var index in data) {
                var newChild = document.createElement("option");
                newChild.value = data[index].CityID;
                newChild.innerText = data[index].CityName;
                document.getElementById(cityObjID).appendChild(newChild);
            }
        }
        if (cityCode != "") {
            document.getElementById(areaObjID).appendChild(emptyChild);
            for (var index in data) {
                var newChild = document.createElement("option");
                newChild.value = data[index].AreaID;
                newChild.innerText = data[index].AreaName;
                document.getElementById(areaObjID).appendChild(newChild);
            }
        }
    });
}

/*
objGv：gridView对象
*/
function ConfirmOrder(objGv,objSelectedPrdID) {
    var selectedPrdID = new Array();//已选择商品ID
    var result = true;
    var selected = false; //是否有选择商品
    var selectedOne = false;//是否至少选择了一个
    var creator = "";
    //从1开始到objGv.rows.length-1：只遍历数据行而忽略列头列尾
    var rows = objGv.rows.length - 1;
    for (var i = 1; i < rows; i++) {
        selected = $(objGv.rows[i]).find("td:eq(0) :checkbox")[0].checked;
        if (selected) {
            selectedOne = true;
            if (creator == "")
                creator = $.trim($(objGv.rows[i]).find("td:eq(6)").text());
            else {
                if (creator != $.trim($(objGv.rows[i]).find("td:eq(6)").text())) {
                    result = false; //暂时目前只可以购买同一个发布人的书籍
                    break;
                }
            }
            selectedPrdID.push($(objGv.rows[i]).find("td:eq(1)").text());
        }
    }
    //            if ($.cookie(cookieProductID) != null) {
    //                var jsonObj = eval('(' + $.cookie(cookieProductID) + ')');
    //                for (var obj in jsonObj) {
    //                    if (jsonObj[obj].Selected==true) {
    //                        selected = true;
    //                        if (creator == -1) {
    //                            creator = jsonObj[obj].Creator;
    //                        }
    //                        else {
    //                            if (creator != jsonObj[obj].Creator) {
    //                                result = false; //暂时目前只可以购买同一个发布人的书籍
    //                                break;
    //                            }
    //                        }
    //                    }
    //                }
    //            }
    if (result && selectedOne) {
        objSelectedPrdID.value = selectedPrdID.join(',');
        //跨页提交，要在页面放一个Button，设置postbackurl，接收方才可以使用Page.PreviousPage
        window.document.forms[0].action = "/UI/Order/ComicOrderConfirm.aspx";
        window.document.forms[0].submit();
    }
    //window.location.href = "/UI/Order/ComicOrderConfirm.aspx";
    else if (!result && selectedOne)
        alert('一次只可以購買一個商家的書籍，若需要購買其他商家的書籍，請另外再下訂單！')
    else if (!selected)
        alert('請選擇書籍！');
}

/*扩张函数 开始*/

//从左边截取n个字符 ,如果包含汉字,则汉字按两个字符计算 
String.prototype.left=function(n){ 
    return this.slice(0,n-this.slice(0,n).replace(/[\x00-\xff]/g,"").length) 
}; 


//从右边截取n个字符 ,如果包含汉字,则汉字按两个字符计算 
String.prototype.right = function(n) {
    return this.slice(this.slice(-n).replace(/[\x00-\xff]/g, "").length - n)
}
/*扩张函数 结束*/
