common.js 7.42 KB
/**
 * 页面公共逻辑
 * @author: xuqi<qi.xu@yoho.cn>
 * @date: 2015/10/21
 */
var $ = require('jquery'),
    Hammer = require('yoho.hammer');

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

function cookie(name) {
    var cookies = document.cookie,
        cookieVal,
        offset;

    if (document.cookie && document.cookie !== '') {
        offset = cookies.indexOf(name + '=');
        if (offset > -1) {
            offset += name.length + 1;

            cookieVal = decodeURIComponent($.trim(cookies.substring(offset, cookies.indexOf(';', offset))));
        }
    }

    return cookieVal;
}

function setCookie(name, value, options) {
    var 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 getUser() {
    var 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() {
    var user = getUser();

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

    return user[1];
}

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

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

    return JSON.parse(c).k;
}

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

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

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

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

/**
 *
 * 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) {
    var fixedElH = $(fixedElement).outerHeight();

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

//页面通用底部位置及status设置
(function() {
    var $op = $footer.children('.op-row');

    var user = getUser();

    var backToTopHammer;

    rePosFooter(); //计算底部位置

    if (user === 0) {

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

        //已登录
        $op.prepend(
            '<span>Hi,</span>' +
            '<a class="user-name" href="http://m.yohobuy.com/home?tmp=' + Math.random() + '">' + user[0] + '</a>' +
            '<a href="http://m.yohobuy.com/passport/signout/index?token=' + user[3] + '">退出</a>'
        );
    }

    if ($op.find('.back-to-top').length > 0) {
        backToTopHammer = new Hammer($op.find('.back-to-top')[0]);
        backToTopHammer.on('tap', function(e) {
            $(window).scrollTop(0);
            e.srcEvent.preventDefault();
            return false;
        });
    }

    $footer.removeClass('hide');
}());

(function(w, d, s, j, f) {
    var a = d.createElement(s);
    var m = d.getElementsByTagName(s)[0];

    w.YohoAcquisitionObject = f;

    w[f] = function() {
        w[f].p = arguments;
    };

    a.async = 1;
    a.src = j;
    m.parentNode.insertBefore(a, m);
})(window, document, 'script', 'http://cdn.yoho.cn/yas-jssdk/1.0.13.6.3/yas.js', '_yas');

(function() {
    var uid = getUid();

    uid = uid === 0 ? '' : uid;

    window._ozuid = uid;//暴露ozuid

    if (window._yas) {
        window._yas(1 * new Date(), '1.0.13.6.3', 'yohobuy_m', uid, '', '');
    }
}());

$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');
});

// $('.nav-home').on('touchstart', function() {
//     $('.homebuttom').toggleClass('none');
// });

(function() {
    var 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, element) {
            var currTime = new Date().getTime();

            //为了使setTimteout的尽可能的接近每秒60帧的效果
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var 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;
}());

// 给jQuery 扩展 queryString函数
$.extend({
    queryString: function() {
        var vars = [],
            hash,
            i;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

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

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

window.setCookie = setCookie;

window.getUser = getUser;

window.getUid = getUid;

window.getShoppingKey = getShoppingKey;

window.rePosFooter = rePosFooter;

window.reMarginFooter = reMarginFooter;