﻿

function addfavorite()
{
   if (document.all)
   {
      window.external.addFavorite('http://www.exian.cn/','曲一线官网');
   }
   else if (window.sidebar)
   {
      window.sidebar.addPanel('曲一线官网', 'http://www.exian.cn/', "");
   }
} 


function validBuy(frm){

    
    if (isNaN(frm.num.value)) { 
        alert('请输入正确的购买数. '); 
        return false; 
    }

    cart.set(parseInt(frm.bid.value),parseInt(frm.num.value));

}

function setHeadButton(place)
{
    document.getElementById('hb_' + place).className = 'act';
}

function vInput(input,string,isout)
{
    if (isout)
    {
        if (input.value == '')
        {
            input.value=string;
        }
    }
    else
    {
        if (input.value == string)
        {
            input.value = '';
        }
    }
}

function checkSearchForm(input,string)
{
    if (input.value == string)
    {
        //alert('请输入要搜索的关键字.');
        input.value = '';
        return false;
    }
}

//cart begin
//使用时通过 cookiename 获取，注意： 在服务器获取时可能会存在需要进行urldecode 方法处理

var cartClass = function(cookiename,path,cookiehours){

var list = {};

this.changed = null;

this.added = null;

this.deled = null;

this.initialize = function(){

    var v = getCookie(cookiename);
    var c = getCookie(cookiename+"_c");
    if (v && c){
        v = v.split(",");
        c = c.split(",");
        //容错，如果数据不完整则全无效
        if (v.length == c.length)
        {
            var len = v.length;
            for(var i=0;i<len;i++)
            {
                if (!isNaN(v[i]) && !isNaN(c[i]))
                {
                    list[v[i]] = parseInt(c[i]);
                }
            }
        }
    }
}

//设置数量，如果减去则将数量填写为负
this.set = function(id,count){
    var v;
    if (list[id])
    {
        v = parseInt(list[id]) + parseInt(count);
        if (v < 1) v = 1;
        list[id] = v;
    }else{
        v = parseInt(count);
        if (v < 1) v = 1;
        list[id] = v;
        if (this.added){
            this.added(id);
        }
    }
    
    if (this.changed)
        this.changed(id,list[id]);
}

//删除一个数
this.del = function(id){
    delete list[id];
    if (this.deled){
        this.deled(id);
    }
}

//清除
this.clear = function(){
    for(var id in list)
    {
        this.del(id);
    }
}

//数量
this.count = function(){
    var i = 0;
    for(var id in list)
    {
        if (!isNaN(id))
        {
            i ++;
        }
    }
    return i;
}

//将存储的数据量填入html元素中
this.fill = function(idprefix){
    for(var id in list)
    {
        if (isNaN(id)) continue;
        if (!document.getElementById(idprefix + id))
        {
            alert('not find fill item ' + idprefix+id);
            continue;
        }
        document.getElementById(idprefix + id).value = list[id];
    }
    
}

this.getPrice = function(idprefix,numprefix){
    var value = 0;
    for(var id in list){
        if (isNaN(id)) continue;
        if (!document.getElementById(idprefix + id)) continue;
        if (!document.getElementById(numprefix + id)) continue;
        value += parseFloat(document.getElementById(idprefix + id).value) * parseInt(document.getElementById(numprefix + id).value);
    }
    return value;
}

this.save = function(){
    var v = "";
    var c = "";
    
    for(var id in list){
        if (!isNaN(id)){
            v = v.concat(id,",");
            c = c.concat(list[id],",");
        }
    }
    if (v != "" && c != "")
    {
        v = v.substr(0,v.length-1);
        c = c.substr(0,c.length-1);
    }
    if (!cookiehours) cookiehours = 0;
    setCookie(cookiename,v,cookiehours,path);
    setCookie(cookiename+"_c",c,cookiehours,path);    
}


function setCookie(objName,objValue,objHours,objPath){
   var str = objName + "=" + encodeURIComponent (objValue);
   if(objHours > 0){
    var date = new Date();
    var ms = objHours*3600*1000;
    date.setTime(date.getTime() + ms);
    str += "; expires=" + date.toGMTString();
   }
   if (objPath){
    str += "; path=" + objPath;
   }
   document.cookie = str;
  }
  
  function getCookie(objName){
   var arrStr = document.cookie.split("; ");
   for(var i = 0;i < arrStr.length;i ++){
    var temp = arrStr[i].split("=");
    if(temp[0] == objName) return decodeURIComponent(temp[1]);
   } 
  }
  
  function delCookie(name){
   var date = new Date();
   date.setTime(date.getTime() - 10000);
   document.cookie = name + "=; expires=" + date.toGMTString();
  }

this.initialize();
}

//cart end

var cart = new cartClass("cart","/");
cart.deled = cart.added = function(){
    document.getElementById('cart_count').innerHTML = "&nbsp;"+ cart.count() +"&nbsp;";
    changePrice();
    cart.save();
}

cart.changed = function(id,count){
    //当具有价格变化时
    if (document.getElementById('cart_' + id))
    {
        document.getElementById('cart_' + id).value = count;
        changePrice(); 
    }
    cart.save();
}

function changePrice() {

    var pp = cart.getPrice('cart_price_', 'cart_');
    /*if (document.getElementById('cart_price')) {*/
        var d = document.getElementsByName("delivermethod");
        var v = "";
        for (var i = 0; i < d.length; i++) {
            if (d[i].checked) {
                v = d[i].value;
                break;
            }
        }

        var p = 0;
        switch (v) {
            case "1":
                p = 5;//暂时禁用
                break;
            case "2":
                p = delivermethod_price_express;
                break;
            case "3":
                p = delivermethod_price_ems;
                break;
        }
        p = getRound(p);
        pp = getRound(pp);
        var pxp = getRound(parseFloat(p) + parseFloat(pp));

        if (document.getElementById('cart_price')) document.getElementById('cart_price').innerHTML = pp;
        if (document.getElementById('cart_price_2')) document.getElementById('cart_price_2').innerHTML = pp;
        if (document.getElementById('cart_freight')) document.getElementById('cart_freight').innerHTML = p;
        if (document.getElementById('cart_pricetotal')) document.getElementById('cart_pricetotal').innerHTML = pxp;



        if (document.getElementById('p_freightprice')) document.getElementById('p_freightprice').value = p;
        if (document.getElementById('p_wareprice')) document.getElementById('p_wareprice').value = pp;
        if (document.getElementById('p_price')) document.getElementById('p_price').value = pxp;
    /*}*/


    }

    function setcod() {
        var _is = IsCod();
        if (_is)
            changePrice();
        else
            alert('城市“' + document.getElementById('city').value + '”不支持货到付款。');
        return _is;
    }

    function IsCod(vv) {

        var isok = false;
        var v = vv || document.getElementById('city').value;
        for (var i = 0; i < cod_arr.length; i++) {
            if (cod_arr[i] == v) return true;
        }
        return false;
    }
    
function getRound( v )
{
    if (v == 0) return 0;
    return (Math.round((v * 100))/100).toFixed(2);
}


function postPay(frm){


    if ($.trim(frm.tel.value) == '') {
        alert('请填写你的手机.');
        frm.tel.focus();
        return false;
    }
    if (!/^[\d]{11}$/.test($.trim(frm.tel.value))) {
        alert('请填写正确的手机.');
        frm.tel.focus();
        return false;
    }
    if ($.trim(frm.consignee.value) == '')
    {
        alert('请填写收货人姓名.');
        frm.consignee.focus();
        return false;
    }
    if ($.trim(frm.province.value) == '' || $.trim(frm.province.value) == '省份' )
    {
        alert('请选择收货地点所在省份.');
        frm.province.focus();
        return false;
    }
    if ($.trim(frm.city.value) == '' || $.trim(frm.city.value) == '城市')
    {
        alert('请选择收货地点所在城市.');
        frm.city.focus();
        return false;
    }
    if ($.trim(frm.county.value) == '' || $.trim(frm.county.value) == '区县')
    {
        alert('请选择收货地点所在区县.');
        frm.county.focus();
        return false;
    }
    if ($.trim(frm.address.value) == '')
    {
        alert('请填写收货地址.');
        frm.address.focus();
        return false;
    }
    if ($.trim(frm.post.value) == '')
    {
        alert('请填收货地址的邮政编码.');
        frm.post.focus();
        return false;
    }
    if (isNaN(frm.post.value))
    {
        alert('请填写正确的邮政编码.');
        frm.post.focus();
        return false;
    }

    var pm = $('input[name=payment]:checked').val();
    if (!pm) {
        alert('请选择付款方式.');
        return false;
    }

    if (!window.confirm("确认要提交吗？")) return false;

//    $.ajax('../ajax.aspx?action=IsLogin', '', function (result) {
//        if (result == '1') {
//            mysubmit(); //已登录，直接提交
//        } else {
//            OpenMobileJBox(frm.tel.value); //未登录，验证提交
//        }
//    });

   // OpenMobileJBox(frm.tel.value); //未登录，验证提交

    postPaySubmit(frm);

    return false;
}

function postPaySubmit(frm) {
    var data = $(frm).serialize();
//    alert(data);
    $.post('OrderSave.aspx', data, function (result) {
        if (result == "success") {
            location.href = "Success.aspx?oid=" + $('#oid').val();
        } else if (result == 'mobilecode error') {
            $('#tcload').hide();
            $('#btnsub').attr('disabled', false);
            alert('验证码错误，请检查.');
        } else {
            alert(result);
        }
    });
}

function OpenMobileJBox(mobile) {

    if ($('#div-jBoxID').length > 0) { $('#div-jBoxID').disposejBox(); }
    jBox.open('div-jBoxID', 'load', { url: '../dialog.aspx?action=TelphoneCode&mobile=' + mobile + '&a=' + Math.random(), callback: function () {

        codesendtimer(30);

    }
    }, '手机验证', 'width=450,height=150,center=true,draggable=true,model=true,close=true');
}

function codesendtimer(time) {
    $('#btn_rsend').val('('+ time +'秒后)重新发送');
    if (time < 1) {
        $('#btn_rsend').val('重新发送');
        $('#btn_rsend').attr('disabled',false);
        return;
    }
    $('#btn_rsend').attr('disabled',true);
    setTimeout("codesendtimer(" + (time-1) + ")", 1000);
}

function setCode(frm) {
    var code = $.trim(frm.code.value);
    if (code == "" || isNaN(code)) {
        alert('请输入正确的验证码.');
        return;
    }
    $('#mobilecode').val(frm.code.value);
    $(frm.btnsub).attr('disabled', true);
    $('#tcload').css('display', 'block');
    mysubmit();
}

//account login
function SendValid() {

    var mobile = document.getElementById('mobile').value;
    if (!/^[\d]{11}$/.test(mobile)) {
        alert('请输入正确的手机号.');
        return;
    }


    $('#sv_btn').attr('disabled', true);
    $.get('../Ajax.aspx?action=IsAccount&mobile=' + mobile, '', function (result) {

        $('#sv_btn').attr('disabled', false);
        if (result == "1") {
            OpenMobileJBox(document.getElementById('mobile').value);
        } else {

            alert('您输入的手机号不正确或您还未购买图书.');
            //location.href = '../book/';
        }

    });

}

//提交验证
function SendValidSubmit() {
    $.post('Index.aspx', {
        action: 'login',
        mobile: document.getElementById('mobile').value,
        mobilecode: document.getElementById('mobilecode').value
    }, function (result) {

        if (result == 'success') {
            location.href = 'Order.aspx';
        } else if (result == 'mobilecode error') {
            $('#tcload').hide();
            $('#btnsub').attr('disabled', false);
            alert('验证码错误，请检查.');
        } else if (result == 'nouser') {

            alert('您输入的手机号不正确或您还未购买图书.');
            //location.href = '../book/';

        } else {
            alert(result);
        }

    });
}


function OpenPayMark() {
    if ($('#div-mark').length > 0) { $('#div-mark').disposejBox(); }
    //jBox.open('div-mark', 'inline', '<div style="text-algin:center; marign:50px; width:auto; color:blue;">如您已完成付款，请点击：<br><input type="button" value="付款成功" onclick="location.href=\'../account/\'"><br /><br />在支付中遇到问题，点此刷新后重试支付:<br/><input type="button" value="付款失败" onclick="$(\'#div-mark\').hidejBox();location.reload(true);"></div>', '支付面板', 'width=300,height=150,center=true,draggable=true,model=true');
    jBox.open('div-mark', 'div', 'pay_mark', '支付面板', 'width=400,height=200,center=true,draggable=true,model=true');
}


