header.js 8.38 KB
/**
 * 公共头部
 * @author: yyq<yanqing.yang@yoho.cn>
 * @date: 2016/5/9
 */
var $ = require('yoho-jquery'),
    handlebars = require('yoho-handlebars');

var $tool = $('.tool-wrapper'),
    $yohoGroup = $tool.find('.yoho-group'),
    $loginBox = $('#loginBox');

var $head = $('.head-wrapper'),
    $searchForm = $('#search-form'),
    $searchSug = $head.find('.search-suggest'),
    $goCart = $head.find('.go-cart'),
    $goodsNum = $goCart.find('.goods-num-tip'),
    $miniCart = $head.find('.mini-cart-wrapper');

var $subNav = $('.sub-nav-list .contain-third');

var thirdLineNum = 9,
    delayer,
    centerFn,
    loginFn,
    cartFn;

// handlebars模板
// centerFn = handlebars.compile($('#simple-account-info-tpl').html());
// loginFn = handlebars.compile($('#header-login-info-tpl').html());
// cartFn = handlebars.compile($('#mini-cart-tpl').html());

// handlebars helper
handlebars.registerHelper('notzero', function(v1, options) {
    if (v1 !== '0') {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }
});

// 格式化三级菜单
function formatThirdMenu() {
    $subNav.each(function() {
        var $thirdList = $(this).find('.hide-list'),
            list = [],
            i = 0;

        if ($thirdList.length) {
            $thirdList.children().each(function() {
                if (i % thirdLineNum === 0) {
                    list.push('');
                }
                list[list.length - 1] += this.outerHTML + '';
                i++;
            });
            for (i = 0; i < 3; i++) {
                $thirdList.before('<dl class="category-list">' + list[i] + '</dl>');
            }
            $thirdList.remove();
        }
    });
}

// 更新头部登陆信息
function updateLoginInfo(data) {
    var info = {
        usercenter: 'http://www.yohobuy.com/home?t=' + new Date().getTime(),
        nickname: data.profile_name,
        signout: 'http://www.yohobuy.com/logout_' + data.token
    };

    if (data.vip.curVipInfo.curLevel * 1 === 3) {
        data.vip3 = true;
    }

    $tool.find('.simple-user-center').html(centerFn(data));
    $loginBox.html(loginFn(info));
}

// 同步sso登录状态
function syncLoginInfo() {
    var param = {
        return_type: 'jsonp',
        method: 'open.passport.get'
    };

    $.getJSON('http://www.yohobuy.com/common/passport/?callback=?', param, function(jsonData) {
        if (jsonData && jsonData.data && jsonData.data.result !== -1) {
            updateLoginInfo(jsonData.data.data);
        } else {
            window.setCookie('_UID', '', {
                domain: '.yohobuy.com',
                expires: -1
            });
        }
    });
}

// 关键词搜索联想
function searchSuggest(key) {
    var param = {
        return_type: 'jsonp',
        query: key
    };

    $.getJSON('http://search.yohobuy.com/api/suggest?callback=?', param, function(jsonData) {
        if (jsonData.code === 200) {
            if (jsonData.data && jsonData.data.length) {
                $searchSug.html(jsonData.data).show();
            } else {
                $searchSug.hide();
            }
        }
    });
}

// 同步mini购物车数据
function syncCratInfo(strG) {
    var info, total;

    if (strG) {
        window.setCookie('_g', strG, {
            path: '/',
            domain: '.yohobuy.com'
        });
    }
    if (window.cookie('_g')) {
        info = $.parseJSON(window.cookie('_g'));
        total = parseInt(info._nac, 10) + parseInt(info._ac, 10);
        total = total > 0 ? total : 0;
        $goCart.data({
            key: info._k,
            num: total
        });
        $goodsNum.text(total);
    }
}

function loadCartDetail(key) {
    var param = {
        return_type: 'jsonp',
        method: 'open.Shoppingcart.getCartData',
        shopping_key: key
    };

    $.getJSON('http://www.yohobuy.com/common/shoppingCart/?callback=?', param, function(jsonData) {
        var totalGoods, data;

        if (jsonData.code === 200) {
            data = jsonData.data;
            totalGoods = $.merge(data.main_goods, data.advance_goods);
            totalGoods = $.merge(totalGoods, data.outlet_goods);
            totalGoods = $.merge(totalGoods, data.gift_goods);
            totalGoods = $.merge(totalGoods, data.need_pay_gifts);
            if (totalGoods && totalGoods.length) {
                data.totalGoods = totalGoods;
                $miniCart.html(cartFn({
                    carData: data
                }));
            } else {
                $miniCart.html('<div class="empty-cart"><h3>您的购物车暂无商品</h3></div>');
            }
        }
    });
}

function delCartGoods(data, callback) {
    var param = {
        return_type: 'jsonp',
        method: 'open.Shoppingcart.delone',
        shopping_key: data.key,
        id: data.id,
        isreduce: data.isreduce
    };

    $.getJSON('http://www.yohobuy.com/common/shoppingCart/?callback=?', param, function(jsonData) {
        var strG = '';

        if (jsonData.code === 200) {
            strG = '{"_k":"' + data.key + '","_nac":' + jsonData.data.total_goods_num + ',"_ac":0,"_r":0}';
            syncCratInfo(strG);
            return callback();
        }
    });
}

syncLoginInfo();
formatThirdMenu();
setInterval(syncCratInfo, 2000);

$yohoGroup.hover(function() {
    var data = $(this).data();

    $(this).text(data.cn);
}, function() {
    var data = $(this).data();

    $(this).text(data.en);
});

$searchForm.on('keyup', '.search-key', function(e) {
    var val = $.trim($(this).val()),
        $child = $searchSug.find('li'),
        $act = $searchSug.find('.action'),
        $focus;

    if (e.which > 36 && e.which < 41) {

        if (e.which === 38) {
            $focus = $act.prev();
            if (!$act.length || !$focus.length) {
                $focus = $child.eq($child.length - 1);
            }
        } else if (e.which === 40) {
            $focus = $act.next();
            if (!$act.length || !$focus.length) {
                $focus = $child.eq(0);
            }
        } else {
            return;
        }

        $child.removeClass('action');
        $focus.addClass('action');
        $(this).val($focus.find('.searchvalue').text());
    } else if (e.which === 13) {
        if (val !== '') {
            $searchForm.submit();
        }
    } else {
        val = val.replace(new RegExp('\'', 'gm'), ''); // 去掉特殊字符

        $(this).val(val);
        searchSuggest(val);
    }
}).on('blur', '.search-key', function() {
    setTimeout(function() {
        $searchSug.hide();
    }, 200);
});

$goCart.hover(function() {
    var data, _html = '';

    if ($goCart.hasClass('on-hover')) {
        return;
    }

    data = $goCart.data();
    if (data && data.num * 1) {
        _html = '<div class="loading-cart"><h3>加载中,请稍后</h3></div>';
        loadCartDetail(data.key);
    } else {
        _html = '<div class="empty-cart"><h3>您的购物车暂无商品</h3></div>';
    }
    $miniCart.html(_html);
    $goCart.addClass('on-hover');
}, function() {
    $goCart.removeClass('on-hover');
});

$goCart.on('click', '.cart-goods-del', function() {
    var $dom = $(this),
        data = $dom.data(),
        callback;

    if (data) {
        callback = function() {
            $dom.closest('.goods-item').remove();
        };
        data.key = $goCart.data().key;
        delCartGoods(data, callback);
    }
});

$subNav.on({
    mouseenter: function() {
        var $thirdNav = $(this).children('.third-nav-wrapper'),
            $show = $thirdNav.find('.show-detail'),
            param = {};

        delayer = setTimeout(function() {
            $thirdNav.show();
        }, 200);

        if (!$show.length || $show.hasClass('show')) {
            return;
        }
        param.content_code = $show.data().code;
        param.client_type = 'web';
        param.width = 174;
        param.height = 155;
        param._ = new Date();
        $.getJSON('http://new.yohobuy.com/common/getbanner?callback=?', param, function(JsonData) {
            if (JsonData.code === 200) {
                $show.addClass('show');
                $show.find('img').attr('src', JsonData.data.src);
                $show.find('a').attr('href', JsonData.data.url);
                $show.find('.title').text(JsonData.data.title);
            }
        });
    },
    mouseleave: function() {
        var $thirdNav = $(this).children('.third-nav-wrapper');

        if (delayer) {
            clearTimeout(delayer);
        }
        $thirdNav.hide();
    }
});