common.js 14.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
/**
 * 页面公共逻辑
 * @author: xuqi<qi.xu@yoho.cn>
 * @date: 2015/10/21
 */
let $ = require('yoho-jquery');
let yohoCookie = require('yoho-cookie');

let $footer = $('#yoho-footer'),
    $yohoPage = $('.yoho-page'),
    $header = $('.yoho-header');

let cleanHtml = require('../../utils/cleanHtml');

// 为您优选-40位随机数指纹请求id
let RECID = (new Date().getTime() + '_H5_YOHOBUY_' + Math.floor(Math.random() * 1000000 + 1000000) +
    '_' + Math.floor(Math.random() * 1000000 + 1000000));

let _ChannelVary = {
    boys: 1,
    girls: 2,
    kids: 3,
    lifestyle: 4
};

require('./common/share');

function cookie(name) {

    // var re = new RegExp(name + '=([^;$]*)', 'i'),
    //     matchPattern = '$1';

    // if (name === '_UID') {
    //     return decodeURIComponent(re.test(document.cookie) ? RegExp[matchPattern] : '');
    // }

    // try {
    //     return re.test(decodeURIComponent(document.cookie)) ? RegExp[matchPattern] : '';
    // } catch (e) {
    //     return decodeURIComponent(re.test(document.cookie) ? RegExp[matchPattern] : '');
    // }

    return yohoCookie.get(name);
}

function setCookie(name, value, options) {
    let expires = '',
        path,
        domain,
        secure,
        date;

    if (typeof value !== 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }

        if (options.expires &&
            (typeof options.expires === 'number' || options.expires.toUTCString)) {
            if (typeof options.expires === 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        path = options.path ? '; path=' + options.path : '';
        domain = options.domain ? '; domain=' + options.domain : '';
        secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    }
}

function isCookiesEnabled() {
    let cookieEnabled = (navigator.cookieEnabled) ? true : false;

    if (typeof navigator.cookieEnabled === 'undefined' && !cookieEnabled) {
        document.cookie = 'testcookie';
        cookieEnabled = (document.cookie.indexOf('testcookie') !== -1) ? true : false;
    }

    return (cookieEnabled);
}

function getUser() {
    let c = cookie('_UID'),
        user;

    if (typeof c === 'undefined') {
        return 0;
    }

    user = c.split('::');

    if (typeof user === 'undefined' || user.length < 4) {
        return 0;
    }

    return user;
}

function getUid() {
    let user = getUser();

    if (user === 0) {
        return 0;
    }

    return user[1];
}

function getShoppingKey() {
    let c = cookie('_g');

    if (typeof c === 'undefined') {
        return '';
    }

    return JSON.parse(c).k;
}

// 根据页面内容重新设置通用底部的显示
function rePosFooter() {
    let winH;

    if ($footer.length === 0) {
        return;
    }

    $footer.addClass('bottom');

    if ($footer.css('position') === 'static') {
        $footer.css('position', '');
    }

    winH = Math.min($(window).height(), window.screen.availHeight);

    if ($('body').height() >= winH - parseInt($footer.css('height'), 0)) {
        $footer.removeClass('bottom');
    }
    $footer.show();
}

/**
 *
 * add extra margin-bottom for footer to show yoho copyright when there is fixed bottom element on page
 * @param {String} The jquery selecor of the fixed bottom element
 * @return undefined
 */
function reMarginFooter(fixedElement) {
    let fixedElH = $(fixedElement).outerHeight();

    if (fixedElement) {
        $footer.css('margin-bottom', fixedElH + 'px');
    }
}

function queryString() {
    let vars = [],
        hash,
        i;
    let hashes = window.location.search.slice(1).split('&');

    for (i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

/**
 * 对象字段排序
 */
function mapSort(obj) {
    if (!obj) {
        return {};
    }
    let data = {};

    Object.keys(obj).sort().forEach(k => {
        data[k] = obj[k];
    });

    return data;
}

// 给jQuery 扩展 queryString函数
$.extend({
    queryString: queryString
});

// 页面通用底部位置及status设置
(function() {
    let $op = $footer.children('.op-row'),
        $backToTop = $('.back-to-top'),
        $floatTop = $('.float-top');

    let user = getUser();

    setTimeout(function() {
        rePosFooter(); // 计算底部位置
    }, 500);

    if (user === 0) {

        // 未登录
        $op.prepend(
            '<a href="/signin.html?refer=' + location.href + '" rel="nofollow">登录</a>' +
            '<span class="sep-line">|</span>' +
            '<a href="/reg.html" rel="nofollow">注册</a>'
        );
    } else {

        // 已登录
        $op.prepend(
            '<span>Hi,</span>' +
            '<a class="user-name" href="/home?tmp=' + Math.random() + '">' + cleanHtml.htmlEncode(user[0]) + '</a>' +
            '<span class="sep-line">|</span>' +
            '<a href="/passport/signout/index">退出</a>'
        );
    }

    if ($backToTop.length > 0) {
        $backToTop.on('touchend touchcancel', function(e) {
            $(window).scrollTop(0);
            e.preventDefault();
            return false;
        });
    }
    if ($floatTop.length > 0) {
        $floatTop.on('click', function(e) {
            $(window).scrollTop(0);
            e.preventDefault();
            return false;
        });
    }

    $footer.removeClass('hide');

    // 单击下载按钮 - 接受微信商城或者第三方来源的数据埋点信息
    let unionType = queryString().union_type || '';

    if (unionType && cookie('unionTypeYas') !== unionType) {
        setCookie('unionTypeYas', unionType, {
            path: '/'
        });
    }

    /*
    关于yas种cookies的逻辑澄清:

    1. yas的关于渠道号的cookies的key 是 mkt_code
    2. mkt_code 失效时间为7天
    3. 如果url后面加union_type,mkt_code 在微信下是覆盖的,其他端不覆盖
    4. 如果mkt_code=100000000000349,则直接覆盖成对应的渠道号
    5. yas的cookies 种在 .yohobuy.com 根域下

    周奇琪

    mkt_code 控制移动到 YAS 2017.07.13
    */

    // let isWechat = /micromessenger/i.test(navigator.userAgent || '');
    // let mktc = queryString().mkt_code || queryString().union_type || '';

    // function saveMktCode() {
    //     if (mktc) {
    //         setCookie('mkt_code', mktc, {
    //             path: '/',
    //             domain: 'yohobuy.com',
    //             expires: 7 // 7天
    //         });
    //     }
    // }

    // if (isWechat) {
    //     saveMktCode();
    // } else {
    //     if (!cookie('mkt_code') || mktc === '100000000000349') {
    //         saveMktCode();
    //     }
    // }

    // 尝试打开 APP
    // require('./common/open-app');

    // 尝试打开 MINIAPP
    require('./common/open-miniapp');
}());

$header.on('touchstart', 'a', function() {
    $header.find('a').removeClass('highlight');
    $(this).addClass('highlight');
}).on('touchend touchcancel', 'a', function() {
    $(this).removeClass('highlight');
});

$yohoPage.on('touchstart', '.tap-hightlight', function() {
    $(this).siblings('.tap-hightlight').removeClass('highlight');
    $(this).addClass('highlight');
}).on('touchend touchcancel', '.tap-hightlight', function() {
    $(this).removeClass('highlight');
});

$('.new-nav-home').on('touchstart', function(e) {
    $('.homebuttom').toggleClass('hide');
    e.preventDefault();
    e.stopPropagation();
});

// 点击关闭头部菜单
$('.main-wrap').on('click', '*', (e) => {
    let $this = $(e.currentTarget);

    if (!$this.hasClass('new-nav-home')) {
        $('.homebuttom').addClass('hide');
    } else {
        return false;
    }
});

// 商品列表找相似按钮
$('body').on('touchstart', '.similar-btn', function() {
    let $thisP = $(this).parents('.good-info');

    $thisP.find('.similar-c').toggle();
    $thisP.siblings('.good-info').find('.similar-c').hide();
    return false;
});

// 更新union_type
+(() => {
    $('a[href*="activity.yoho.cn"]').each(function() {
        const $el = $(this);
        const href = $el.attr('href');

        if (href.indexOf('union_type') < 0 && cookie('unionTypeYas')) {
            const sps = href.split('?');

            $el.attr('href', `${sps[0]}?union_type=${cookie('unionTypeYas')}&${sps[1]}`);
        }
    });
})();

(function() {
    let lastTime = 0,
        prefixes = 'webkit moz ms o'.split(' '),
        requestAnimationFrame = window.requestAnimationFrame,
        cancelAnimationFrame = window.cancelAnimationFrame,
        prefix,
        i;

    // 通过遍历各浏览器前缀,来得到requestAnimationFrame和cancelAnimationFrame在当前浏览器的实现形式
    for (i = 0; i < prefixes.length; i++) {
        if (requestAnimationFrame && cancelAnimationFrame) {
            break;
        }
        prefix = prefixes[i];
        requestAnimationFrame = requestAnimationFrame || window[prefix + 'RequestAnimationFrame'];
        cancelAnimationFrame = cancelAnimationFrame || window[prefix + 'CancelAnimationFrame'] ||
            window[prefix + 'CancelRequestAnimationFrame'];
    }

    // 如果当前浏览器不支持requestAnimationFrame和cancelAnimationFrame,则会退到setTimeout
    if (!requestAnimationFrame || !cancelAnimationFrame) {
        requestAnimationFrame = function(callback) {
            let currTime = new Date().getTime();

            // 为了使setTimteout的尽可能的接近每秒60帧的效果
            let timeToCall = Math.max(0, 16 - (currTime - lastTime));
            let id = window.setTimeout(function() {
                callback(currTime + timeToCall);
            }, timeToCall);

            lastTime = currTime + timeToCall;
            return id;
        };

        cancelAnimationFrame = function(id) {
            window.clearTimeout(id);
        };
    }

    window.requestAnimationFrame = requestAnimationFrame;
    window.cancelAnimationFrame = cancelAnimationFrame;
}());


// 临时修改  footer
function phoneHidden(phone) {
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
}

if ($footer.find('.user-name').text().length === 11) {
    $footer.find('.user-name').html(phoneHidden($footer.find('.user-name').text()));
}

// 浮层下载APP
function downLoadApp(unionType) {
    let appUrl = 'http://union.yoho.cn/union/downapp.html';
    let clickedAt = new Date();

    setTimeout(function() {
        let mkt = unionType || queryString().union_type || cookie('unionTypeYas') || false;

        if ((new Date()) - clickedAt < 2000) {
            if (mkt) {
                appUrl += '?union_type=' + mkt;
            }

            if (window._yas && window._yas.sendCustomInfo) {
                window._yas.sendCustomInfo({
                    op: 'YB_DOWNLOAD_C',
                    param: JSON.stringify({
                        C_ID: _ChannelVary[cookie('_Channel')] || 1,
                        TO_URL: appUrl
                    })
                }, true);
            }

            window.location = appUrl;
        }
    }, 500);
}

// 为您优选埋点 http://redmine.yoho.cn/issues/10117
function givePoint(parameter) {
    if (!window._yas || !window._yas.sendCustomInfo) {
        return false;
    }

    if (!parameter.REC_POSE || !parameter.PRD_ID) {
        return true;
    }

    // 男:1,女:2,潮童:3,创意生活:4
    let CID = _ChannelVary[cookie('_Channel')] || 1;
    let isAppOp = parameter.isAppOp;

    parameter = $.extend({
        REC_ID: RECID,
        PRD_NUM: 0,
        C_ID: CID,
        ACTION_ID: 0,
        PAGE_NUM: 1
    }, parameter);
    delete parameter.isAppOp;

    window._yas.sendCustomInfo({
        op: 'YB_CHOOSE_FOR_YOU_Y',
        appop: isAppOp ? 'YB_CHOOSE_FOR_YOU' : '', // app内打开wap的埋点场合
        param: JSON.stringify(parameter)
    }, true);
}

/**
 * 页面头颜色修正
 */
(function() {
    let channel = cookie('_Channel');
    let header = $('#yoho-header, .homebuttom');
    let footer = $('.footer-tab .tab-item.current');

    if (!header.hasClass('set-channel')) {
        if (!/^\/home/.test(location.pathname)) {
            switch (channel) {
                case 'boys':
                    if (!header.hasClass('boys')) {
                        header.addClass('boys');
                    }
                    break;
                case 'girls':
                    if (!header.hasClass('girls')) {
                        header.addClass('girls');
                    }
                    break;
                case 'lifestyle':
                    if (!header.hasClass('life-style')) {
                        header.addClass('life-style');
                    }
                    break;
                case 'kids':
                    if (!header.hasClass('kids')) {
                        header.addClass('kids');
                    }
                    break;
                default:
                    if (!header.hasClass('boys')) {
                        header.addClass('boys');
                    }
                    break;
            }
        } else {
            header.removeClass('kids');
            header.removeClass('girls');
            header.removeClass('life-style');
            header.addClass('boys');
        }
    }

    switch (channel) {
        case 'boys':
            if (footer) {
                footer.addClass('boys');
            }
            break;
        case 'girls':
            if (footer) {
                footer.addClass('girls');
            }
            break;
        case 'lifestyle':
            if (footer) {
                footer.addClass('life-style');
            }
            break;
        case 'kids':
            if (footer) {
                footer.addClass('kids');
            }
            break;
        default:
            if (footer) {
                footer.addClass('boys');
            }
            break;
    }
}());

// 暴露公共接口
window.cookie = cookie;

window.setCookie = setCookie;

window.isCookiesEnabled = isCookiesEnabled;

window.getUser = getUser;

window.getUid = getUid;

window.getShoppingKey = getShoppingKey;

window.rePosFooter = rePosFooter;

window.reMarginFooter = reMarginFooter;

window.queryString = queryString();

window.givePoint = givePoint;

window._ChannelVary = _ChannelVary;

window.downLoadApp = downLoadApp;

window.mapSort = mapSort;

require('js/common/weixin-report');